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