|
1 |
| -import React from 'react'; |
| 1 | +import React, { useCallback, useEffect, useState } from 'react'; |
2 | 2 | import classNames from 'classnames';
|
3 | 3 |
|
4 | 4 | import './style.scss';
|
5 | 5 |
|
| 6 | +type UseSvgRef = (element: SVGTextElement) => void; |
| 7 | +type UseSvgWidthResult = [UseSvgRef, number, number]; |
| 8 | + |
6 | 9 | interface ITinyTag extends React.HTMLAttributes<HTMLSpanElement> {
|
7 |
| - value?: string; |
8 |
| - color?: string; |
| 10 | + value: string; |
9 | 11 | }
|
10 | 12 |
|
11 |
| -export default function TinyTag({ color, value, className, ...restProps }: ITinyTag) { |
| 13 | +const useSvgWidth = (): UseSvgWidthResult => { |
| 14 | + const [element, ref] = useState<SVGTextElement | null>(null); |
| 15 | + const [svgWidth, setSvgWidth] = useState(0); |
| 16 | + const [rectWidth, setRectWidth] = useState(0); |
| 17 | + |
| 18 | + const getWidth = useCallback(() => { |
| 19 | + if (!element) return; |
| 20 | + const paddingWidth = 8; |
| 21 | + const textWidth = Math.round(element.getBoundingClientRect()?.width); |
| 22 | + const svgWidth = textWidth + paddingWidth; |
| 23 | + setSvgWidth(svgWidth); |
| 24 | + setRectWidth(Math.max(svgWidth - 1, 0)); |
| 25 | + }, [element]); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + getWidth(); |
| 29 | + }, [element]); |
| 30 | + |
| 31 | + return [ref, svgWidth, rectWidth]; |
| 32 | +}; |
| 33 | + |
| 34 | +export default function TinyTag({ value, className, ...restProps }: ITinyTag) { |
| 35 | + const [ref, svgWidth, rectWidth] = useSvgWidth(); |
12 | 36 | return (
|
13 |
| - <span |
14 |
| - className={classNames('dtc-tinyTag', className)} |
15 |
| - style={{ borderColor: color, color }} |
16 |
| - {...restProps} |
17 |
| - > |
18 |
| - {value} |
| 37 | + <span className={classNames('dtc-tinyTag', className)} {...restProps}> |
| 38 | + <svg |
| 39 | + width={svgWidth} |
| 40 | + height="15" |
| 41 | + viewBox={`0 0 ${svgWidth} 15`} |
| 42 | + fill="none" |
| 43 | + xmlns="http://www.w3.org/2000/svg" |
| 44 | + > |
| 45 | + <rect |
| 46 | + x="0.5" |
| 47 | + y="0.5" |
| 48 | + width={rectWidth} |
| 49 | + height="14" |
| 50 | + rx="1.5" |
| 51 | + stroke="currentColor" |
| 52 | + strokeLinejoin="bevel" |
| 53 | + /> |
| 54 | + <text |
| 55 | + ref={ref} |
| 56 | + fill="currentColor" |
| 57 | + xmlSpace="preserve" |
| 58 | + fontSize="10" |
| 59 | + letterSpacing="0px" |
| 60 | + > |
| 61 | + <tspan x="4" y="11.1"> |
| 62 | + {value} |
| 63 | + </tspan> |
| 64 | + </text> |
| 65 | + </svg> |
19 | 66 | </span>
|
20 | 67 | );
|
21 | 68 | }
|
0 commit comments