@lyra/form-builder
Version:
Lyra form builder
80 lines (67 loc) • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = UndoRedoPlugin;
var _slateHotkeys = require('slate-hotkeys');
var _slateHotkeys2 = _interopRequireDefault(_slateHotkeys);
var _patchesToChange = require('../utils/patchesToChange');
var _patchesToChange2 = _interopRequireDefault(_patchesToChange);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*:: import type {Type} from '../typeDefs'*/
// This plugin handles our own undo redo (disables Slate built in handling)
/*:: type Options = {
stack: {
items: [],
index: number
},
onChange: void => void,
blockContentType: Type
}*/
function UndoRedoPlugin(options /*: Options*/ = {}) {
const stack = options.stack,
blockContentType = options.blockContentType,
onChange = options.onChange;
return {
// eslint-disable-next-line complexity
onKeyDown(event /*: SyntheticKeyboardEvent<*>*/, change /*: Change*/) {
if (_slateHotkeys2.default.isUndo(event) || _slateHotkeys2.default.isRedo(event)) {
let item;
// Undo
if (_slateHotkeys2.default.isUndo(event) && (item = stack.undo.pop())) {
var _item = item;
const patches = _item.patches,
editorValue = _item.editorValue;
// Create Slate change for these patches
const patchChange = (0, _patchesToChange2.default)(patches, editorValue, null, blockContentType);
// Keep track of the original operations, and create a reversed change
const originalOperationIndex = patchChange.operations.size;
patchChange.undo();
// Remove the original non-undo operations
patchChange.operations = patchChange.operations.splice(0, originalOperationIndex);
// Restore the selection
patchChange.select(editorValue.selection).focus();
// Tag the change, so that changeToPatches know's it's a undoRedo change.
patchChange.__isUndoRedo = 'undo';
stack.redo.push(item);
onChange(patchChange);
}
// Redo (pretty much as undo, just that we don't need to reverse any operations)
if (_slateHotkeys2.default.isRedo(event) && (item = stack.redo.pop())) {
var _item2 = item;
const patches = _item2.patches,
editorValue = _item2.editorValue,
select = _item2.select;
const patchChange = (0, _patchesToChange2.default)(patches, editorValue, null, blockContentType);
// Restore the selection
patchChange.applyOperations([select]).focus();
patchChange.__isUndoRedo = 'redo';
stack.undo.push(item);
onChange(patchChange);
}
return change;
}
return undefined;
}
};
}