Skip to content

Commit

Permalink
fix: address feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
sashuk committed Jun 27, 2023
1 parent f91c86d commit 81c83a9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@ import { useCallback, useMemo, useState } from 'react'

import { useFormConfig } from '../../FormConfig'

const TRACKED_EVENTS_LIMIT = 3
/**
* This hook keeps the highlighted state for Rich Text Editor form fields after
* first `onChange` callback which is triggered by editor itself when initial value is
* provided. Starting from second `onChange` or first `onFocus` invocation (which are
* triggered by user) the field is no longer highlighted.
*
* Editor triggers the very first onChange callback by itself only when initial value
* is provided in order to propagate the value to wrapping form.
*/

/**
* After first two editor changes are tracked (the initial one and the one originated
* from user), hook stops responding due to performance reasons.
*/
const TRACKED_EVENTS_LIMIT = 2

export const useEnforceHighlightAutofill = () => {
const { highlightAutofill } = useFormConfig()
Expand All @@ -22,10 +36,12 @@ export const useEnforceHighlightAutofill = () => {
return
}

if (timesChangeOrFocusTriggered < TRACKED_EVENTS_LIMIT) {
setTimesChangeOrFocusTriggered(timesChangeOrFocusTriggered + 1)
if (timesChangeOrFocusTriggered <= TRACKED_EVENTS_LIMIT) {
setTimesChangeOrFocusTriggered(
timesChangeOrFocusTriggered => timesChangeOrFocusTriggered + 1
)
}
}, [timesChangeOrFocusTriggered])
}, [highlightAutofill, timesChangeOrFocusTriggered])

return {
enforceHighlightAutofill,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { useIsomorphicLayoutEffect } from '@toptal/picasso-shared'
import type { EditorState, LexicalEditor } from 'lexical'

const TriggerInitialOnChangePlugin = ({
Expand All @@ -13,17 +12,11 @@ const TriggerInitialOnChangePlugin = ({
}) => {
const [editor] = useLexicalComposerContext()

useIsomorphicLayoutEffect(() => {
if (onChange) {
return editor.registerUpdateListener(
({ editorState, prevEditorState, tags }) => {
if (prevEditorState.isEmpty()) {
onChange(editorState, editor, tags)
}
}
)
editor.registerUpdateListener(({ editorState, prevEditorState, tags }) => {
if (prevEditorState.isEmpty()) {
onChange(editorState, editor, tags)
}
}, [editor, onChange])
})

return null
}
Expand Down

0 comments on commit 81c83a9

Please sign in to comment.