diff --git a/packages/block-editor/src/components/rich-text/index.tsx b/packages/block-editor/src/components/rich-text/index.tsx index e42687f893641c..fafe6636d163dc 100644 --- a/packages/block-editor/src/components/rich-text/index.tsx +++ b/packages/block-editor/src/components/rich-text/index.tsx @@ -34,7 +34,6 @@ import { } from '../block-edit/context'; import FormatToolbarContainer from './format-toolbar-container'; import { store as blockEditorStore } from '../../store'; -import { useMarkPersistent } from './use-mark-persistent'; import { useEventListeners } from './event-listeners'; import FormatEdit from './format-edit'; import { @@ -436,6 +435,9 @@ function RichTextWrapper( ] ); + // When the field last changed, or 0 after a format change. + const lastChangeRef = useRef( 0 ); + const { value, getValue, @@ -445,7 +447,20 @@ function RichTextWrapper( [ getDomPositionKey ]: getDomPosition, } = useRichText( { value: adjustedValue, - onChange: adjustedOnChange, + onChange( newValue: unknown, meta: { __unstableText: string } ) { + // Typing goes into one undo level until a second without typing or + // a format change, after which the next change starts a new one. + if ( Date.now() - lastChangeRef.current >= 1000 ) { + __unstableMarkLastChangeAsPersistent(); + } + // The hook is untyped, and calls it with the field's kind of value. + ( adjustedOnChange as ( ...args: unknown[] ) => void )( + newValue, + meta + ); + lastChangeRef.current = + meta.__unstableText === value.text ? 0 : Date.now(); + }, selectionStart, selectionEnd, onSelectionChange, @@ -614,12 +629,6 @@ function RichTextWrapper( ariaActiveDescendant, ] ); - useMarkPersistent( { - html: adjustedValue, - value, - onMarkPersistent: __unstableMarkLastChangeAsPersistent, - } ); - const [ keyboardShortcuts ] = useState( () => new Set< ( event: KeyboardEvent ) => void >() ); diff --git a/packages/block-editor/src/components/rich-text/multi-block-format-edit.tsx b/packages/block-editor/src/components/rich-text/multi-block-format-edit.tsx index c1048eadf93d40..88f838b53eba3d 100644 --- a/packages/block-editor/src/components/rich-text/multi-block-format-edit.tsx +++ b/packages/block-editor/src/components/rich-text/multi-block-format-edit.tsx @@ -227,8 +227,12 @@ function Fields( { contentRef, }: FieldsProps ) { const registry = useRegistry(); - const { updateBlockAttributes, replaceBlocks, selectionChange } = - useDispatch( blockEditorStore ); + const { + updateBlockAttributes, + replaceBlocks, + selectionChange, + __unstableMarkLastChangeAsPersistent, + } = useDispatch( blockEditorStore ); const keys: string[] = useSelect( ( select ) => { const { getBlockName } = select( blockEditorStore ); @@ -334,6 +338,8 @@ function Fields( { ), { uniqueByBlock: true } ); + // The next change to these blocks starts a new undo level. + __unstableMarkLastChangeAsPersistent(); return; } // The selected text was replaced, by an inline image or a diff --git a/packages/block-editor/src/components/rich-text/test/use-mark-persistent.jsdom.test.ts b/packages/block-editor/src/components/rich-text/test/use-mark-persistent.jsdom.test.ts deleted file mode 100644 index d503ca4df0856d..00000000000000 --- a/packages/block-editor/src/components/rich-text/test/use-mark-persistent.jsdom.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { renderHook } from '@testing-library/react'; -import { StrictMode } from '@wordpress/element'; -import type { RichTextFormatList } from '@wordpress/rich-text'; -import { useMarkPersistent } from '../use-mark-persistent'; - -const markPersistent = vi.fn(); - -function props( - html: string, - text = html, - activeFormats: RichTextFormatList = [] -) { - return { - html, - value: { text, activeFormats }, - onMarkPersistent: markPersistent, - }; -} - -describe( 'useMarkPersistent', () => { - beforeEach( () => { - vi.useFakeTimers(); - markPersistent.mockClear(); - } ); - - afterEach( () => { - vi.useRealTimers(); - } ); - - it( 'does not mark on mount', () => { - renderHook( useMarkPersistent, { initialProps: props( 'a' ) } ); - vi.runAllTimers(); - - expect( markPersistent ).not.toHaveBeenCalled(); - } ); - - it( 'does not mark on mount in strict mode', () => { - renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - wrapper: StrictMode, - } ); - vi.runAllTimers(); - - expect( markPersistent ).not.toHaveBeenCalled(); - } ); - - it( 'marks once after a second without typing', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - rerender( props( 'ab' ) ); - vi.advanceTimersByTime( 500 ); - rerender( props( 'abc' ) ); - vi.advanceTimersByTime( 999 ); - - expect( markPersistent ).not.toHaveBeenCalled(); - - vi.advanceTimersByTime( 1 ); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'starts the timer for the first character in an empty field', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( '' ), - } ); - - rerender( props( 'a' ) ); - vi.advanceTimersByTime( 1000 ); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'treats html that lags behind the text as typing', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - // The text updates first, e.g. when the block debounces - // `setAttributes`. - rerender( props( 'a', 'ab' ) ); - rerender( props( 'ab' ) ); - - expect( markPersistent ).not.toHaveBeenCalled(); - - vi.advanceTimersByTime( 1000 ); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'marks immediately when formatting changes', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'ab' ), - } ); - - rerender( props( 'ab', 'ab' ) ); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'marks immediately when active formats toggle', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - rerender( props( 'a', 'a', [ { type: 'core/bold' } ] ) ); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'replaces a pending typing mark with an immediate one', () => { - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - rerender( props( 'ab' ) ); - rerender( props( 'ab', 'ab' ) ); - vi.runAllTimers(); - - expect( markPersistent ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'calls the latest callback without resetting the timer', () => { - const next = vi.fn(); - const { rerender } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - rerender( props( 'ab' ) ); - vi.advanceTimersByTime( 500 ); - rerender( { ...props( 'ab' ), onMarkPersistent: next } ); - vi.advanceTimersByTime( 500 ); - - expect( markPersistent ).not.toHaveBeenCalled(); - expect( next ).toHaveBeenCalledTimes( 1 ); - } ); - - it( 'cancels a pending mark on unmount', () => { - const { rerender, unmount } = renderHook( useMarkPersistent, { - initialProps: props( 'a' ), - } ); - - rerender( props( 'ab' ) ); - unmount(); - vi.runAllTimers(); - - expect( markPersistent ).not.toHaveBeenCalled(); - } ); -} ); diff --git a/packages/block-editor/src/components/rich-text/types.ts b/packages/block-editor/src/components/rich-text/types.ts index 2e24711c9b955d..c227489de7b101 100644 --- a/packages/block-editor/src/components/rich-text/types.ts +++ b/packages/block-editor/src/components/rich-text/types.ts @@ -62,21 +62,6 @@ export type FieldFormatSettings = { disabled?: boolean; }; -/** - * A snapshot of the value, to classify the change since the last one. - */ -export type MarkPersistentSnapshot = { - html: unknown; - text: string; - hasActiveFormats: boolean; -}; - -export type UseMarkPersistentOptions = { - html: unknown; - value: Pick< RichTextValue, 'text' | 'activeFormats' >; - onMarkPersistent: () => void; -}; - /** * Props of `RichText.Content`. Other props go to the element. */ diff --git a/packages/block-editor/src/components/rich-text/use-mark-persistent.ts b/packages/block-editor/src/components/rich-text/use-mark-persistent.ts deleted file mode 100644 index 1157c1709e4fc9..00000000000000 --- a/packages/block-editor/src/components/rich-text/use-mark-persistent.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { useLayoutEffect, useRef } from '@wordpress/element'; -import { useDebounce, useEvent } from '@wordpress/compose'; -import type { MarkPersistentSnapshot, UseMarkPersistentOptions } from './types'; - -const TYPING_TIMEOUT = 1000; - -/** - * Classifies the change between two snapshots of the value. - * - * @param previous Previous snapshot. - * @param next Next snapshot. - * - * @return The change type. - */ -function getChangeType( - previous: MarkPersistentSnapshot, - next: MarkPersistentSnapshot -): 'none' | 'typing' | 'discrete' { - if ( - previous.html === next.html && - previous.hasActiveFormats === next.hasActiveFormats - ) { - return 'none'; - } - - return previous.text === next.text ? 'discrete' : 'typing'; -} - -export function useMarkPersistent( { - html, - value, - onMarkPersistent, -}: UseMarkPersistentOptions ) { - const { text } = value; - const hasActiveFormats = !! value.activeFormats?.length; - const previousRef = useRef< MarkPersistentSnapshot >( undefined ); - // Stable, so a new callback doesn't reset the debounce. - const markPersistent = useEvent( onMarkPersistent ); - // Don't create an undo level for every character. Create one after a - // second of no input. - const markPersistentDebounced = useDebounce( - markPersistent, - TYPING_TIMEOUT - ); - - // Must be set synchronously to make sure it applies to the last change. - useLayoutEffect( () => { - const previous = previousRef.current; - const next = { html, text, hasActiveFormats }; - - // Ignore mount. - if ( ! previous ) { - previousRef.current = next; - return; - } - - // Effects can re-run without a change, e.g. in strict mode. Keep the - // last handled snapshot, so html lagging behind the text (e.g. a - // debounced `setAttributes`) still counts as typing. - const changeType = getChangeType( previous, next ); - if ( changeType === 'none' ) { - return; - } - - previousRef.current = next; - - if ( changeType === 'typing' ) { - markPersistentDebounced(); - return; - } - - markPersistentDebounced.cancel(); - markPersistent(); - }, [ - html, - text, - hasActiveFormats, - markPersistent, - markPersistentDebounced, - ] ); -} diff --git a/test/e2e/specs/editor/various/undo.spec.js b/test/e2e/specs/editor/various/undo.spec.js index 62aea6988e89a2..5b9a39d8b7a70d 100644 --- a/test/e2e/specs/editor/various/undo.spec.js +++ b/test/e2e/specs/editor/various/undo.spec.js @@ -164,6 +164,158 @@ test.describe( 'undo', () => { } ); } ); + test( 'should undo formatting separately from typing', async ( { + editor, + page, + pageUtils, + } ) => { + await editor.canvas + .locator( 'role=document[name="Add default block"i]' ) + .click(); + await page.keyboard.type( 'one two' ); + await editor.page.waitForTimeout( 1000 ); + await pageUtils.pressKeys( 'shift+ArrowLeft', { times: 3 } ); + await pageUtils.pressKeys( 'primary+b' ); + await page.keyboard.press( 'ArrowRight' ); + await page.keyboard.type( ' three' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +
one two three
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +one two
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +one two
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( '' ); + + // Undo inserting the paragraph. + await pageUtils.pressKeys( 'primary+z' ); + + await expect( + page.getByRole( 'button', { name: 'Undo', exact: true } ) + ).toBeDisabled(); + } ); + + test( 'should not end the undo level when leaving a format with the arrow key', async ( { + editor, + page, + pageUtils, + } ) => { + await editor.insertBlock( { + name: 'core/paragraph', + attributes: { content: 'ab' }, + } ); + await page.keyboard.press( 'End' ); + // At the end of a format, the arrow keys enter and leave it without + // moving the caret. + await page.keyboard.press( 'ArrowLeft' ); + await page.keyboard.type( 'x' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +abx
+` + ); + + await page.keyboard.press( 'ArrowRight' ); + await page.keyboard.type( 'y' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +abxy
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +ab
+` + ); + } ); + + test( 'should undo each format change across blocks separately', async ( { + editor, + page, + pageUtils, + } ) => { + await editor.canvas + .locator( 'role=document[name="Add default block"i]' ) + .click(); + await page.keyboard.type( 'ab' ); + await page.keyboard.press( 'Enter' ); + await page.keyboard.type( 'ab' ); + await page.keyboard.press( 'ArrowLeft' ); + // The same text on both lines, so the caret lands between the same + // letters one line up. + await pageUtils.pressKeys( 'shift+ArrowUp' ); + + await expect + .poll( () => + page.evaluate( () => + window.wp.data + .select( 'core/block-editor' ) + .getSelectedBlockClientIds() + ) + ) + .toHaveLength( 2 ); + + await pageUtils.pressKeys( 'primary+b' ); + await pageUtils.pressKeys( 'primary+i' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +ab
+ + + +ab
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +ab
+ + + +ab
+` + ); + + await pageUtils.pressKeys( 'primary+z' ); + + await expect.poll( editor.getEditedPostContent ).toBe( + ` +ab
+ + + +ab
+` + ); + } ); + test( 'should undo bold', async ( { page, pageUtils, editor } ) => { await editor.canvas .locator( 'role=document[name="Add default block"i]' )