Skip to content

Commit

Permalink
Avoid calling getCharacterCoordinates when fullHeight is set in t…
Browse files Browse the repository at this point in the history
…he MarkdownEditor (#3423)

* avoid calling getCharacterCoordinates when fullHeight is set

* changeset + rename
  • Loading branch information
japf authored Jun 19, 2023
1 parent 3fd3c89 commit af32ec7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/honest-fishes-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

improve performance of the MarkdownEditor component when fullHeight is enabled
10 changes: 8 additions & 2 deletions src/drafts/MarkdownEditor/_MarkdownInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,14 @@ export const MarkdownInput = forwardRef<HTMLTextAreaElement, MarkdownInputProps>
return subscription?.unsubscribe
}, [pasteUrlsAsPlainText])

const dynamicHeightStyles = useDynamicTextareaHeight({maxHeightLines, minHeightLines, elementRef: ref, value})
const heightStyles = fullHeight ? {} : dynamicHeightStyles
const heightStyles = useDynamicTextareaHeight({
// if fullHeight is enabled, there is no need to compute a dynamic height (for perfs reasons)
disabled: fullHeight,
maxHeightLines,
minHeightLines,
elementRef: ref,
value,
})

return (
<InlineAutocomplete
Expand Down
8 changes: 7 additions & 1 deletion src/drafts/hooks/useDynamicTextareaHeight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {SxProp} from '../../sx'
import {getCharacterCoordinates} from '../utils/character-coordinates'

type UseDynamicTextareaHeightSettings = {
disabled?: boolean
minHeightLines?: number
maxHeightLines?: number
elementRef: RefObject<HTMLTextAreaElement | null>
Expand All @@ -23,6 +24,7 @@ type UseDynamicTextareaHeightSettings = {
* explicitly set in CSS.
*/
export const useDynamicTextareaHeight = ({
disabled,
minHeightLines,
maxHeightLines,
elementRef,
Expand All @@ -33,6 +35,8 @@ export const useDynamicTextareaHeight = ({
const [maxHeight, setMaxHeight] = useState<string | undefined>(undefined)

useLayoutEffect(() => {
if (disabled) return

const element = elementRef.current
if (!element) return

Expand All @@ -56,7 +60,9 @@ export const useDynamicTextareaHeight = ({
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, value, elementRef])
}, [minHeightLines, maxHeightLines, value, elementRef, disabled])

if (disabled) return {}

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

0 comments on commit af32ec7

Please sign in to comment.