Skip to content

perf: actually debounce rich text editor field value updates to only process latest state #12086

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

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
18 changes: 16 additions & 2 deletions packages/richtext-lexical/src/field/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
useField,
} from '@payloadcms/ui'
import { mergeFieldStyles } from '@payloadcms/ui/shared'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ErrorBoundary } from 'react-error-boundary'

import type { SanitizedClientEditorConfig } from '../lexical/config/types.js'
Expand Down Expand Up @@ -117,6 +117,8 @@ const RichTextComponent: React.FC<

const pathWithEditDepth = `${path}.${editDepth}`

const dispatchFieldUpdateTask = useRef<number>(undefined)

const updateFieldValue = (editorState: EditorState) => {
const newState = editorState.toJSON()
prevValueRef.current = newState
Expand All @@ -126,7 +128,19 @@ const RichTextComponent: React.FC<
const handleChange = useCallback(
(editorState: EditorState) => {
if (typeof window.requestIdleCallback === 'function') {
requestIdleCallback(() => updateFieldValue(editorState))
// Cancel earlier scheduled value updates,
// so that a CPU-limited event loop isn't flooded with n callbacks for n keystrokes into the rich text field,
// but that there's only ever the latest one state update
// dispatch task, to be executed with the next idle time,
// or the deadline of 500ms.
if (typeof window.cancelIdleCallback === 'function' && dispatchFieldUpdateTask.current) {
cancelIdleCallback(dispatchFieldUpdateTask.current)
}
// Schedule the state update to happen the next time the browser has sufficient resources,
// or the latest after 500ms.
dispatchFieldUpdateTask.current = requestIdleCallback(() => updateFieldValue(editorState), {
timeout: 500,
})
} else {
updateFieldValue(editorState)
}
Expand Down
Loading