Skip to content

Fix useDynamicTextareaHeight not taking into account padding #2848

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

Merged
merged 3 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions .changeset/ten-peaches-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@primer/react": patch
---

Fix `useDynamicTextareaHeight` not taking into account top padding of `textarea`

Also makes the hook accept a `RefObject` instead of an element instance
2 changes: 1 addition & 1 deletion src/drafts/MarkdownEditor/_MarkdownInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const MarkdownInput = forwardRef<HTMLTextAreaElement, MarkdownInputProps>
return subscription?.unsubscribe
}, [pasteUrlsAsPlainText])

const dynamicHeightStyles = useDynamicTextareaHeight({maxHeightLines, minHeightLines, element: ref.current, value})
const dynamicHeightStyles = useDynamicTextareaHeight({maxHeightLines, minHeightLines, elementRef: ref, value})
const heightStyles = fullHeight ? {} : dynamicHeightStyles

return (
Expand Down
24 changes: 14 additions & 10 deletions src/drafts/hooks/useDynamicTextareaHeight.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {useLayoutEffect, useState} from 'react'
import {RefObject, useLayoutEffect, useState} from 'react'

import {SxProp} from '../../sx'
import {getCharacterCoordinates} from '../utils/character-coordinates'

type UseDynamicTextareaHeightSettings = {
minHeightLines: number
maxHeightLines: number
element: HTMLTextAreaElement | null
minHeightLines?: number
maxHeightLines?: number
elementRef: RefObject<HTMLTextAreaElement | null>
/** The current value of the input. */
value: string
}
Expand All @@ -16,43 +16,47 @@ type UseDynamicTextareaHeightSettings = {
* resizing it as the user types. If the user manually resizes the textarea, their setting
* will be respected.
*
* Returns an object to spread to the component's `sx` prop.
* Returns an object to spread to the component's `sx` prop. If you are using `Textarea`,
* apply this to the child `textarea` element: `<Textarea sx={{'& textarea': resultOfThisHook}} />`.
*
* NOTE: for the most accurate results, be sure that the `lineHeight` of the element is
* explicitly set in CSS.
*/
export const useDynamicTextareaHeight = ({
minHeightLines,
maxHeightLines,
element,
elementRef,
value,
}: UseDynamicTextareaHeightSettings): SxProp['sx'] => {
const [height, setHeight] = useState<string | undefined>(undefined)
const [minHeight, setMinHeight] = useState<string | undefined>(undefined)
const [maxHeight, setMaxHeight] = useState<string | undefined>(undefined)

useLayoutEffect(() => {
const element = elementRef.current
if (!element) return

const computedStyles = getComputedStyle(element)
const pt = computedStyles.paddingTop
const lastCharacterCoords = getCharacterCoordinates(element, element.value.length)

// The calculator gives us the distance from the top border to the bottom of the caret, including
// any top padding, so we need to delete the top padding to accurately get the height
// We could also parse and subtract the top padding, but this is more reliable (no chance of NaN)
element.style.paddingTop = '0'

const lastCharacterCoords = getCharacterCoordinates(element, element.value.length)

// Somehow we come up 1 pixel too short and the scrollbar appears, so just add one
setHeight(`${lastCharacterCoords.top + lastCharacterCoords.height + 1}px`)
element.style.paddingTop = pt

const lineHeight =
computedStyles.lineHeight === 'normal' ? `1.2 * ${computedStyles.fontSize}` : computedStyles.lineHeight
// Using CSS calculations is fast and prevents us from having to parse anything
setMinHeight(`calc(${minHeightLines} * ${lineHeight})`)
setMaxHeight(`calc(${maxHeightLines} * ${lineHeight})`)
if (minHeightLines !== undefined) setMinHeight(`calc(${minHeightLines} * ${lineHeight})`)
if (maxHeightLines !== undefined) setMaxHeight(`calc(${maxHeightLines} * ${lineHeight})`)
// `value` is an unnecessary dependency but it enables us to recalculate as the user types
}, [minHeightLines, maxHeightLines, element, value])
}, [minHeightLines, maxHeightLines, value, elementRef])

return {height, minHeight, maxHeight, boxSizing: 'content-box'}
}