]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/defaults/button-definitions.ts
Lexical: Updated lexical, added undo state tracking, format styles
[bookstack] / resources / js / wysiwyg / ui / defaults / button-definitions.ts
1 import {EditorBasicButtonDefinition, EditorButton, EditorButtonDefinition} from "../framework/buttons";
2 import {
3     $createNodeSelection,
4     $createParagraphNode, $getRoot, $getSelection,
5     $isParagraphNode, $isTextNode, $setSelection,
6     BaseSelection, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, COMMAND_PRIORITY_LOW, ElementNode, FORMAT_TEXT_COMMAND,
7     LexicalNode,
8     REDO_COMMAND, TextFormatType,
9     UNDO_COMMAND
10 } from "lexical";
11 import {
12     getNodeFromSelection,
13     selectionContainsNodeType,
14     selectionContainsTextFormat,
15     toggleSelectionBlockNodeType
16 } from "../../helpers";
17 import {$createCalloutNode, $isCalloutNodeOfCategory, CalloutCategory} from "../../nodes/callout";
18 import {
19     $createHeadingNode,
20     $createQuoteNode,
21     $isHeadingNode,
22     $isQuoteNode,
23     HeadingNode,
24     HeadingTagType
25 } from "@lexical/rich-text";
26 import {$isLinkNode, LinkNode} from "@lexical/link";
27 import {EditorUiContext} from "../framework/core";
28 import {$isImageNode, ImageNode} from "../../nodes/image";
29 import {$createDetailsNode, $isDetailsNode} from "../../nodes/details";
30 import {getEditorContentAsHtml} from "../../actions";
31 import {$isListNode, insertList, ListNode, ListType, removeList} from "@lexical/list";
32 import undoIcon from "@icons/editor/undo.svg"
33 import redoIcon from "@icons/editor/redo.svg"
34 import boldIcon from "@icons/editor/bold.svg"
35 import italicIcon from "@icons/editor/italic.svg"
36 import underlinedIcon from "@icons/editor/underlined.svg"
37 import strikethroughIcon from "@icons/editor/strikethrough.svg"
38 import superscriptIcon from "@icons/editor/superscript.svg"
39 import subscriptIcon from "@icons/editor/subscript.svg"
40 import codeIcon from "@icons/editor/code.svg"
41 import formatClearIcon from "@icons/editor/format-clear.svg"
42 import listBulletIcon from "@icons/editor/list-bullet.svg"
43 import listNumberedIcon from "@icons/editor/list-numbered.svg"
44 import listCheckIcon from "@icons/editor/list-check.svg"
45 import linkIcon from "@icons/editor/link.svg"
46 import imageIcon from "@icons/editor/image.svg"
47 import detailsIcon from "@icons/editor/details.svg"
48 import sourceIcon from "@icons/editor/source-view.svg"
49
50 export const undo: EditorButtonDefinition = {
51     label: 'Undo',
52     icon: undoIcon,
53     action(context: EditorUiContext) {
54         context.editor.dispatchCommand(UNDO_COMMAND, undefined);
55     },
56     isActive(selection: BaseSelection|null): boolean {
57         return false;
58     },
59     setup(context: EditorUiContext, button: EditorButton) {
60         button.toggleDisabled(true);
61
62         context.editor.registerCommand(CAN_UNDO_COMMAND, (payload: boolean): boolean => {
63             button.toggleDisabled(!payload)
64             return false;
65         }, COMMAND_PRIORITY_LOW);
66     }
67 }
68
69 export const redo: EditorButtonDefinition = {
70     label: 'Redo',
71     icon: redoIcon,
72     action(context: EditorUiContext) {
73         context.editor.dispatchCommand(REDO_COMMAND, undefined);
74     },
75     isActive(selection: BaseSelection|null): boolean {
76         return false;
77     },
78     setup(context: EditorUiContext, button: EditorButton) {
79         button.toggleDisabled(true);
80
81         context.editor.registerCommand(CAN_REDO_COMMAND, (payload: boolean): boolean => {
82             button.toggleDisabled(!payload)
83             return false;
84         }, COMMAND_PRIORITY_LOW);
85     }
86 }
87
88 function buildCalloutButton(category: CalloutCategory, name: string): EditorButtonDefinition {
89     return {
90         label: `${name} Callout`,
91         action(context: EditorUiContext) {
92             toggleSelectionBlockNodeType(
93                 context.editor,
94                 (node) => $isCalloutNodeOfCategory(node, category),
95                 () => $createCalloutNode(category),
96             )
97         },
98         isActive(selection: BaseSelection|null): boolean {
99             return selectionContainsNodeType(selection, (node) => $isCalloutNodeOfCategory(node, category));
100         }
101     };
102 }
103
104 export const infoCallout: EditorButtonDefinition = buildCalloutButton('info', 'Info');
105 export const dangerCallout: EditorButtonDefinition = buildCalloutButton('danger', 'Danger');
106 export const warningCallout: EditorButtonDefinition = buildCalloutButton('warning', 'Warning');
107 export const successCallout: EditorButtonDefinition = buildCalloutButton('success', 'Success');
108
109 const isHeaderNodeOfTag = (node: LexicalNode | null | undefined, tag: HeadingTagType) => {
110       return $isHeadingNode(node) && (node as HeadingNode).getTag() === tag;
111 };
112
113 function buildHeaderButton(tag: HeadingTagType, name: string): EditorButtonDefinition {
114     return {
115         label: name,
116         action(context: EditorUiContext) {
117             toggleSelectionBlockNodeType(
118                 context.editor,
119                 (node) => isHeaderNodeOfTag(node, tag),
120                 () => $createHeadingNode(tag),
121             )
122         },
123         isActive(selection: BaseSelection|null): boolean {
124             return selectionContainsNodeType(selection, (node) => isHeaderNodeOfTag(node, tag));
125         }
126     };
127 }
128
129 export const h2: EditorButtonDefinition = buildHeaderButton('h2', 'Large Header');
130 export const h3: EditorButtonDefinition = buildHeaderButton('h3', 'Medium Header');
131 export const h4: EditorButtonDefinition = buildHeaderButton('h4', 'Small Header');
132 export const h5: EditorButtonDefinition = buildHeaderButton('h5', 'Tiny Header');
133
134 export const blockquote: EditorButtonDefinition = {
135     label: 'Blockquote',
136     action(context: EditorUiContext) {
137         toggleSelectionBlockNodeType(context.editor, $isQuoteNode, $createQuoteNode);
138     },
139     isActive(selection: BaseSelection|null): boolean {
140         return selectionContainsNodeType(selection, $isQuoteNode);
141     }
142 };
143
144 export const paragraph: EditorButtonDefinition = {
145     label: 'Paragraph',
146     action(context: EditorUiContext) {
147         toggleSelectionBlockNodeType(context.editor, $isParagraphNode, $createParagraphNode);
148     },
149     isActive(selection: BaseSelection|null): boolean {
150         return selectionContainsNodeType(selection, $isParagraphNode);
151     }
152 }
153
154 function buildFormatButton(label: string, format: TextFormatType, icon: string): EditorButtonDefinition {
155     return {
156         label: label,
157         icon,
158         action(context: EditorUiContext) {
159             context.editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
160         },
161         isActive(selection: BaseSelection|null): boolean {
162             return selectionContainsTextFormat(selection, format);
163         }
164     };
165 }
166
167 export const bold: EditorButtonDefinition = buildFormatButton('Bold', 'bold', boldIcon);
168 export const italic: EditorButtonDefinition = buildFormatButton('Italic', 'italic', italicIcon);
169 export const underline: EditorButtonDefinition = buildFormatButton('Underline', 'underline', underlinedIcon);
170 export const textColor: EditorBasicButtonDefinition = {label: 'Text color'};
171 export const highlightColor: EditorBasicButtonDefinition = {label: 'Highlight color'};
172
173 export const strikethrough: EditorButtonDefinition = buildFormatButton('Strikethrough', 'strikethrough', strikethroughIcon);
174 export const superscript: EditorButtonDefinition = buildFormatButton('Superscript', 'superscript', superscriptIcon);
175 export const subscript: EditorButtonDefinition = buildFormatButton('Subscript', 'subscript', subscriptIcon);
176 export const code: EditorButtonDefinition = buildFormatButton('Inline Code', 'code', codeIcon);
177 export const clearFormating: EditorButtonDefinition = {
178     label: 'Clear formatting',
179     icon: formatClearIcon,
180     action(context: EditorUiContext) {
181         context.editor.update(() => {
182             const selection = $getSelection();
183             for (const node of selection?.getNodes() || []) {
184                 if ($isTextNode(node)) {
185                     node.setFormat(0);
186                 }
187             }
188         });
189     },
190     isActive() {
191         return false;
192     }
193 };
194
195 function buildListButton(label: string, type: ListType, icon: string): EditorButtonDefinition {
196     return {
197         label,
198         icon,
199         action(context: EditorUiContext) {
200             context.editor.getEditorState().read(() => {
201                 const selection = $getSelection();
202                 if (this.isActive(selection)) {
203                     removeList(context.editor);
204                 } else {
205                     insertList(context.editor, type);
206                 }
207             });
208         },
209         isActive(selection: BaseSelection|null): boolean {
210             return selectionContainsNodeType(selection, (node: LexicalNode | null | undefined): boolean => {
211                 return $isListNode(node) && (node as ListNode).getListType() === type;
212             });
213         }
214     };
215 }
216
217 export const bulletList: EditorButtonDefinition = buildListButton('Bullet list', 'bullet', listBulletIcon);
218 export const numberList: EditorButtonDefinition = buildListButton('Numbered list', 'number', listNumberedIcon);
219 export const taskList: EditorButtonDefinition = buildListButton('Task list', 'check', listCheckIcon);
220
221
222 export const link: EditorButtonDefinition = {
223     label: 'Insert/edit link',
224     icon: linkIcon,
225     action(context: EditorUiContext) {
226         const linkModal = context.manager.createModal('link');
227         context.editor.getEditorState().read(() => {
228             const selection = $getSelection();
229             const selectedLink = getNodeFromSelection(selection, $isLinkNode) as LinkNode|null;
230
231             let formDefaults = {};
232             if (selectedLink) {
233                 formDefaults = {
234                     url: selectedLink.getURL(),
235                     text: selectedLink.getTextContent(),
236                     title: selectedLink.getTitle(),
237                     target: selectedLink.getTarget(),
238                 }
239
240                 context.editor.update(() => {
241                     const selection = $createNodeSelection();
242                     selection.add(selectedLink.getKey());
243                     $setSelection(selection);
244                 });
245             }
246
247             linkModal.show(formDefaults);
248         });
249     },
250     isActive(selection: BaseSelection|null): boolean {
251         return selectionContainsNodeType(selection, $isLinkNode);
252     }
253 };
254
255 export const table: EditorBasicButtonDefinition = {
256     label: 'Table',
257 };
258
259 export const image: EditorButtonDefinition = {
260     label: 'Insert/Edit Image',
261     icon: imageIcon,
262     action(context: EditorUiContext) {
263         const imageModal = context.manager.createModal('image');
264         const selection = context.lastSelection;
265         const selectedImage = getNodeFromSelection(selection, $isImageNode) as ImageNode|null;
266
267         context.editor.getEditorState().read(() => {
268             let formDefaults = {};
269             if (selectedImage) {
270                 formDefaults = {
271                     src: selectedImage.getSrc(),
272                     alt: selectedImage.getAltText(),
273                     height: selectedImage.getHeight(),
274                     width: selectedImage.getWidth(),
275                 }
276
277                 context.editor.update(() => {
278                     const selection = $createNodeSelection();
279                     selection.add(selectedImage.getKey());
280                     $setSelection(selection);
281                 });
282             }
283
284             imageModal.show(formDefaults);
285         });
286     },
287     isActive(selection: BaseSelection|null): boolean {
288         return selectionContainsNodeType(selection, $isImageNode);
289     }
290 };
291
292 export const details: EditorButtonDefinition = {
293     label: 'Insert collapsible block',
294     icon: detailsIcon,
295     action(context: EditorUiContext) {
296         context.editor.update(() => {
297             const selection = $getSelection();
298             const detailsNode = $createDetailsNode();
299             const selectionNodes = selection?.getNodes() || [];
300             const topLevels = selectionNodes.map(n => n.getTopLevelElement())
301                 .filter(n => n !== null) as ElementNode[];
302             const uniqueTopLevels = [...new Set(topLevels)];
303
304             if (uniqueTopLevels.length > 0) {
305                 uniqueTopLevels[0].insertAfter(detailsNode);
306             } else {
307                 $getRoot().append(detailsNode);
308             }
309
310             for (const node of uniqueTopLevels) {
311                 detailsNode.append(node);
312             }
313         });
314     },
315     isActive(selection: BaseSelection|null): boolean {
316         return selectionContainsNodeType(selection, $isDetailsNode);
317     }
318 }
319
320 export const source: EditorButtonDefinition = {
321     label: 'Source code',
322     icon: sourceIcon,
323     async action(context: EditorUiContext) {
324         const modal = context.manager.createModal('source');
325         const source = await getEditorContentAsHtml(context.editor);
326         modal.show({source});
327     },
328     isActive() {
329         return false;
330     }
331 };