Skip to content
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

Add useStateWithHistory hook and use to show a block editor with undo/redo #54377

Merged
merged 7 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions packages/compose/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Features

- `useStateWithHistory`: Add a new hook to manage state with undo/redo support.

## 6.18.0 (2023-08-31)

## 6.17.0 (2023-08-16)
Expand Down
12 changes: 12 additions & 0 deletions packages/compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,18 @@ const App = () => {
};
```

### useStateWithHistory

useState with undo/redo history.

_Parameters_

- _initialValue_ `T`: Initial value.

_Returns_

- Value, setValue, hasUndo, hasRedo, undo, redo.

### useThrottle

Throttles a function similar to Lodash's `throttle`. A new throttled function will be returned and any scheduled calls cancelled if any of the arguments change, including the function to throttle, so please wrap functions created on render in components in `useCallback`.
Expand Down
1 change: 1 addition & 0 deletions packages/compose/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@wordpress/is-shallow-equal": "file:../is-shallow-equal",
"@wordpress/keycodes": "file:../keycodes",
"@wordpress/priority-queue": "file:../priority-queue",
"@wordpress/undo-manager": "file:../undo-manager",
"change-case": "^4.1.2",
"clipboard": "^2.0.8",
"mousetrap": "^1.6.5",
Expand Down
101 changes: 101 additions & 0 deletions packages/compose/src/hooks/use-state-with-history/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* WordPress dependencies
*/
import { createUndoManager } from '@wordpress/undo-manager';
import { useCallback, useReducer } from '@wordpress/element';
import type { UndoManager } from '@wordpress/undo-manager';

type UndoRedoState< T > = {
manager: UndoManager;
value: T;
};

function undoRedoReducer< T >(
state: UndoRedoState< T >,
action:
| { type: 'UNDO' }
| { type: 'REDO' }
| { type: 'RECORD'; value: T; isStaged: boolean }
): UndoRedoState< T > {
switch ( action.type ) {
case 'UNDO': {
const undoRecord = state.manager.undo();
if ( undoRecord ) {
return {
...state,
value: undoRecord[ 0 ].changes.prop.from,
};
}
return state;
}
case 'REDO': {
const redoRecord = state.manager.redo();
if ( redoRecord ) {
return {
...state,
value: redoRecord[ 0 ].changes.prop.to,
};
}
return state;
}
case 'RECORD': {
state.manager.addRecord(
[
{
id: 'object',
changes: {
prop: { from: state.value, to: action.value },
},
},
],
action.isStaged
);
return {
...state,
value: action.value,
};
}
}

return state;
}

function initReducer< T >( value: T ) {
return {
manager: createUndoManager(),
value,
};
}

/**
* useState with undo/redo history.
*
* @param initialValue Initial value.
* @return Value, setValue, hasUndo, hasRedo, undo, redo.
*/
export default function useStateWithHistory< T >( initialValue: T ) {
const [ state, dispatch ] = useReducer(
undoRedoReducer,
initialValue,
initReducer
);

return {
value: state.value,
setValue: useCallback( ( newValue: T, isStaged: boolean ) => {
dispatch( {
type: 'RECORD',
value: newValue,
isStaged,
} );
}, [] ),
youknowriad marked this conversation as resolved.
Show resolved Hide resolved
hasUndo: state.manager.hasUndo(),
hasRedo: state.manager.hasRedo(),
undo: useCallback( () => {
dispatch( { type: 'UNDO' } );
}, [] ),
redo: useCallback( () => {
dispatch( { type: 'REDO' } );
}, [] ),
youknowriad marked this conversation as resolved.
Show resolved Hide resolved
};
}
59 changes: 59 additions & 0 deletions packages/compose/src/hooks/use-state-with-history/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* External dependencies
*/
import { screen, render, fireEvent } from '@testing-library/react';

/**
* Internal dependencies
*/
import useStateWithHistory from '../';

const TestComponent = () => {
const { value, setValue, hasUndo, hasRedo, undo, redo } =
useStateWithHistory( 'foo' );

return (
<div>
<input
value={ value }
onChange={ ( event ) => setValue( event.target.value ) }
/>
<button className="undo" onClick={ undo } disabled={ ! hasUndo }>
Undo
</button>
<button className="redo" onClick={ redo } disabled={ ! hasRedo }>
Redo
</button>
</div>
);
};

describe( 'useStateWithHistory', () => {
it( 'should allow undo/redo', async () => {
render( <TestComponent /> );
const input = screen.getByRole( 'textbox' );
expect( input ).toHaveValue( 'foo' );
const buttonUndo = screen.getByRole( 'button', { name: 'Undo' } );
const buttonRedo = screen.getByRole( 'button', { name: 'Redo' } );
expect( buttonUndo ).toBeDisabled();
expect( buttonRedo ).toBeDisabled();

// Make a change
fireEvent.change( input, { target: { value: 'bar' } } );
expect( input ).toHaveValue( 'bar' );
expect( buttonUndo ).toBeEnabled();
expect( buttonRedo ).toBeDisabled();

// Undo the change
fireEvent.click( buttonUndo );
expect( input ).toHaveValue( 'foo' );
expect( buttonUndo ).toBeDisabled();
expect( buttonRedo ).toBeEnabled();

// Redo the change
fireEvent.click( buttonRedo );
expect( input ).toHaveValue( 'bar' );
expect( buttonUndo ).toBeEnabled();
expect( buttonRedo ).toBeDisabled();
} );
} );
1 change: 1 addition & 0 deletions packages/compose/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export { default as useKeyboardShortcut } from './hooks/use-keyboard-shortcut';
export { default as useMediaQuery } from './hooks/use-media-query';
export { default as usePrevious } from './hooks/use-previous';
export { default as useReducedMotion } from './hooks/use-reduced-motion';
export { default as useStateWithHistory } from './hooks/use-state-with-history';
export { default as useViewportMatch } from './hooks/use-viewport-match';
export { default as useResizeObserver } from './hooks/use-resize-observer';
export { default as useAsyncList } from './hooks/use-async-list';
Expand Down
3 changes: 2 additions & 1 deletion packages/compose/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
{ "path": "../element" },
{ "path": "../is-shallow-equal" },
{ "path": "../keycodes" },
{ "path": "../priority-queue" }
{ "path": "../priority-queue" },
{ "path": "../undo-manager" }
],
"include": [ "src/**/*" ]
}
14 changes: 6 additions & 8 deletions packages/core-data/src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -425,14 +425,13 @@ export const editEntityRecord =
export const undo =
() =>
( { select, dispatch } ) => {
const undoEdit = select.getUndoManager().getUndoRecord();
if ( ! undoEdit ) {
const undoRecord = select.getUndoManager().undo();
if ( ! undoRecord ) {
return;
}
select.getUndoManager().undo();
dispatch( {
type: 'UNDO',
record: undoEdit,
record: undoRecord,
} );
};

Expand All @@ -443,14 +442,13 @@ export const undo =
export const redo =
() =>
( { select, dispatch } ) => {
const redoEdit = select.getUndoManager().getRedoRecord();
if ( ! redoEdit ) {
const redoRecord = select.getUndoManager().redo();
if ( ! redoRecord ) {
return;
}
select.getUndoManager().redo();
dispatch( {
type: 'REDO',
record: redoEdit,
record: redoRecord,
} );
};

Expand Down
4 changes: 2 additions & 2 deletions packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ export function getRedoEdit( state: State ): Optional< any > {
* @return Whether there is a previous edit or not.
*/
export function hasUndo( state: State ): boolean {
return Boolean( state.undoManager.getUndoRecord() );
return state.undoManager.hasUndo();
}

/**
Expand All @@ -916,7 +916,7 @@ export function hasUndo( state: State ): boolean {
* @return Whether there is a next edit or not.
*/
export function hasRedo( state: State ): boolean {
return Boolean( state.undoManager.getRedoRecord() );
return state.undoManager.hasRedo();
}

/**
Expand Down
18 changes: 14 additions & 4 deletions packages/undo-manager/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,19 +153,29 @@ export function createUndoManager() {
dropPendingRedos();
appendStagedRecordToLatestHistoryRecord();
}
const undoRecord = history[ history.length - 1 + offset ];
if ( ! undoRecord ) {
return;
}
offset -= 1;
return undoRecord;
},

redo() {
const redoRecord = history[ history.length + offset ];
if ( ! redoRecord ) {
return;
}
offset += 1;
return redoRecord;
},

getUndoRecord() {
return history[ history.length - 1 + offset ];
hasUndo() {
return !! history[ history.length - 1 + offset ];
},

getRedoRecord() {
return history[ history.length + offset ];
hasRedo() {
return !! history[ history.length + offset ];
},
};
}
Loading
Loading