feat: add client component demonstrating Pretext text measurement

This commit is contained in:
2026-06-27 21:24:11 +00:00
parent fa3d3e93d6
commit 5cc7a6b7b5
+39
View File
@@ -0,0 +1,39 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { measureText } from '@chenglou/pretext';
interface MeasuredTextProps {
text: string;
}
export default function MeasuredText({ text }: MeasuredTextProps) {
const ref = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number | null>(null);
useEffect(() => {
if (!ref.current) return;
const style = window.getComputedStyle(ref.current);
const measured = measureText(text, {
font: {
family: style.fontFamily.split(',')[0].replace(/['"]/g, ''),
size: parseFloat(style.fontSize),
weight: style.fontWeight,
},
});
setWidth(measured.width);
}, [text]);
return (
<div>
<span ref={ref} style={{ fontSize: '2rem', fontWeight: 700 }}>
{text}
</span>
{width !== null && (
<p style={{ color: 'dimgray' }}>Measured width: {width.toFixed(2)}px</p>
)}
</div>
);
}