Skip to content

Commit 5d481c5

Browse files
committed
chore: use more accurate font measurement
1 parent cf1a099 commit 5d481c5

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

webview-ui/src/components/chat/ChatTextArea.tsx

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -510,16 +510,27 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
510510
setIsMouseDownOnMenu(true)
511511
}, [])
512512

513-
// Utility function to estimate text width
513+
// Utility function to accurately measure text width
514514
const estimateTextWidth = useCallback((text: string, fontSize: number = 11): number => {
515-
// Approximate character width based on font size (in pixels)
516-
const avgCharWidth = fontSize * 0.6
515+
// Create a hidden canvas for text measurement
516+
const canvas = document.createElement("canvas")
517+
const context = canvas.getContext("2d")
517518

518-
// Add extra space for the caret icon and padding
519+
if (!context) {
520+
// Fallback if canvas context is not available
521+
return text.length * 6 + 30
522+
}
523+
524+
// Set the font to match our select element
525+
context.font = `${fontSize}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif`
526+
527+
// Measure the text width
528+
const metrics = context.measureText(text)
529+
530+
// Add padding for the caret icon and select element padding
519531
const paddingWidth = 30
520532

521-
// Calculate estimated width
522-
return text.length * avgCharWidth + paddingWidth
533+
return Math.ceil(metrics.width) + paddingWidth
523534
}, [])
524535

525536
// Update mode select width when mode changes

0 commit comments

Comments
 (0)