Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update useDynamicFontSizing.ts #7785

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions packages/ui/src/hooks/useDynamicFontSizing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,22 @@ export function useDynamicFontSizing(
onSetFontSize: (amount: string) => void
} {
const [fontSize, setFontSize] = useState(maxFontSize)
const textInputElementWidthRef = useRef(0)
const textInputElementWidthRef = useRef<number | null>(null)

const onLayout = useCallback((event: LayoutChangeEvent) => {
if (textInputElementWidthRef.current) {
return
}

const width = event.nativeEvent.layout.width
textInputElementWidthRef.current = width
if (textInputElementWidthRef.current !== width) {
textInputElementWidthRef.current = width
}
}, [])

const onSetFontSize = useCallback(
(amount: string) => {
if (!textInputElementWidthRef.current) return

const stringWidth = getStringWidth(amount, maxCharWidthAtMaxFontSize, fontSize, maxFontSize)
const scaledSize = fontSize * (textInputElementWidthRef.current / stringWidth)
// If scaledSize = 0 then onLayout hasn't triggered yet and we should default to the largest size
const scaledSizeWithMin = scaledSize ? Math.max(scaledSize, minFontSize) : maxFontSize
const newFontSize = Math.round(Math.min(maxFontSize, scaledSizeWithMin))
const newFontSize = Math.max(minFontSize, Math.min(maxFontSize, Math.round(scaledSize)))
setFontSize(newFontSize)
},
[fontSize, maxFontSize, minFontSize, maxCharWidthAtMaxFontSize],
Expand All @@ -43,6 +41,5 @@ const getStringWidth = (
currentFontSize: number,
maxFontSize: number,
): number => {
const widthAtMaxFontSize = value.length * maxCharWidthAtMaxFontSize
return widthAtMaxFontSize * (currentFontSize / maxFontSize)
return (value.length * maxCharWidthAtMaxFontSize * currentFontSize) / maxFontSize
}