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