UNPKG

@wordpress/compose

Version:
94 lines (91 loc) 2.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useStateWithHistory; var _undoManager = require("@wordpress/undo-manager"); var _element = require("@wordpress/element"); /** * WordPress dependencies */ function undoRedoReducer(state, action) { 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(value) { return { manager: (0, _undoManager.createUndoManager)(), value }; } /** * useState with undo/redo history. * * @param initialValue Initial value. * @return Value, setValue, hasUndo, hasRedo, undo, redo. */ function useStateWithHistory(initialValue) { const [state, dispatch] = (0, _element.useReducer)(undoRedoReducer, initialValue, initReducer); return { value: state.value, setValue: (0, _element.useCallback)((newValue, isStaged) => { dispatch({ type: 'RECORD', value: newValue, isStaged }); }, []), hasUndo: state.manager.hasUndo(), hasRedo: state.manager.hasRedo(), undo: (0, _element.useCallback)(() => { dispatch({ type: 'UNDO' }); }, []), redo: (0, _element.useCallback)(() => { dispatch({ type: 'REDO' }); }, []) }; } //# sourceMappingURL=index.js.map