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