Skip to content

Commit

Permalink
Merge pull request #343 from MovieReviewComment/feature/issue-302/his…
Browse files Browse the repository at this point in the history
…tory-actions

[#302] Implement useHistoryActions
  • Loading branch information
2wheeh authored Apr 24, 2024
2 parents c8d0cfb + 2d10447 commit a987de3
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions ui/src/hooks/editor/use-history-actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use client';

import { mergeRegister } from '@lexical/utils';
import {
CAN_REDO_COMMAND,
CAN_UNDO_COMMAND,
COMMAND_PRIORITY_CRITICAL,
REDO_COMMAND,
UNDO_COMMAND,
} from 'lexical';
import type { LexicalEditor } from 'lexical';
import { useEffect, useState } from 'react';

export function useHistoryActions(editor: LexicalEditor | undefined | null): {
canUndo: boolean;
canRedo: boolean;
undo: () => void;
redo: () => void;
} {
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);

useEffect(() => {
if (!editor) {
return;
}

return mergeRegister(
editor.registerCommand(
CAN_UNDO_COMMAND,
(payload) => {
setCanUndo(payload);
return false;
},
COMMAND_PRIORITY_CRITICAL
),
editor.registerCommand(
CAN_REDO_COMMAND,
(payload) => {
setCanRedo(payload);
return false;
},
COMMAND_PRIORITY_CRITICAL
)
);
}, [editor]);

return {
canUndo,
canRedo,
undo: () => editor?.dispatchCommand(UNDO_COMMAND, undefined),
redo: () => editor?.dispatchCommand(REDO_COMMAND, undefined),
};
}

0 comments on commit a987de3

Please sign in to comment.