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