diff --git a/packages/picasso-forms/src/RichTextEditor/hooks/use-enforce-highlight-autofill.ts b/packages/picasso-forms/src/RichTextEditor/hooks/use-enforce-highlight-autofill.ts index a188e245a3b..3ba563cea34 100644 --- a/packages/picasso-forms/src/RichTextEditor/hooks/use-enforce-highlight-autofill.ts +++ b/packages/picasso-forms/src/RichTextEditor/hooks/use-enforce-highlight-autofill.ts @@ -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() @@ -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, diff --git a/packages/picasso/src/LexicalEditor/plugins/TriggerInitialOnChangePlugin.ts b/packages/picasso/src/LexicalEditor/plugins/TriggerInitialOnChangePlugin.ts index 68b75edb5c1..00d2118a19e 100644 --- a/packages/picasso/src/LexicalEditor/plugins/TriggerInitialOnChangePlugin.ts +++ b/packages/picasso/src/LexicalEditor/plugins/TriggerInitialOnChangePlugin.ts @@ -1,5 +1,4 @@ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext' -import { useIsomorphicLayoutEffect } from '@toptal/picasso-shared' import type { EditorState, LexicalEditor } from 'lexical' const TriggerInitialOnChangePlugin = ({ @@ -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 }