]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/fixes.js
Audit Log: Fixed bad reference to linked entity item
[bookstack] / resources / js / wysiwyg / fixes.js
1 /**
2  * Handle alignment for embed (iframe/video) content.
3  * TinyMCE built-in handling doesn't work well for these when classes are used for
4  * alignment, since the editor wraps these elements in a non-editable preview span
5  * which looses tracking and setting of alignment options.
6  * Here we manually manage these properties and formatting events, by effectively
7  * syncing the alignment classes to the parent preview span.
8  * @param {Editor} editor
9  */
10 export function handleEmbedAlignmentChanges(editor) {
11     function updateClassesForPreview(previewElem) {
12         const mediaTarget = previewElem.querySelector('iframe, video');
13         if (!mediaTarget) {
14             return;
15         }
16
17         const alignmentClasses = [...mediaTarget.classList.values()].filter(c => c.startsWith('align-'));
18         const previewAlignClasses = [...previewElem.classList.values()].filter(c => c.startsWith('align-'));
19         previewElem.classList.remove(...previewAlignClasses);
20         previewElem.classList.add(...alignmentClasses);
21     }
22
23     editor.on('SetContent', () => {
24         const previewElems = editor.dom.select('span.mce-preview-object');
25         for (const previewElem of previewElems) {
26             updateClassesForPreview(previewElem);
27         }
28     });
29
30     editor.on('FormatApply', event => {
31         const isAlignment = event.format.startsWith('align');
32         const isElement = event.node instanceof editor.dom.doc.defaultView.HTMLElement;
33         if (!isElement || !isAlignment || !event.node.matches('.mce-preview-object')) {
34             return;
35         }
36
37         const realTarget = event.node.querySelector('iframe, video');
38         if (realTarget) {
39             const className = (editor.formatter.get(event.format)[0]?.classes || [])[0];
40             const toAdd = !realTarget.classList.contains(className);
41
42             const wrapperClasses = (event.node.getAttribute('data-mce-p-class') || '').split(' ');
43             const wrapperClassesFiltered = wrapperClasses.filter(c => !c.startsWith('align-'));
44             if (toAdd) {
45                 wrapperClassesFiltered.push(className);
46             }
47
48             const classesToApply = wrapperClassesFiltered.join(' ');
49             event.node.setAttribute('data-mce-p-class', classesToApply);
50
51             realTarget.setAttribute('class', classesToApply);
52             editor.formatter.apply(event.format, {}, realTarget);
53             updateClassesForPreview(event.node);
54         }
55     });
56 }
57
58 /**
59  * Cleans up the direction property for an element.
60  * Removes all inline direction control from child elements.
61  * Removes non "dir" attribute direction control from provided element.
62  * @param {HTMLElement} element
63  */
64 function cleanElementDirection(element) {
65     const directionChildren = element.querySelectorAll('[dir],[style*="direction"],[style*="text-align"]');
66     for (const child of directionChildren) {
67         child.removeAttribute('dir');
68         child.style.direction = null;
69         child.style.textAlign = null;
70     }
71     element.style.direction = null;
72     element.style.textAlign = null;
73 }
74
75 /**
76  * This tracks table cell range selection, so we can apply custom handling where
77  * required to actions applied to such selections.
78  * The events used don't seem to be advertised by TinyMCE.
79  * Found at https://github.com/tinymce/tinymce/blob/6.8.3/modules/tinymce/src/models/dom/main/ts/table/api/Events.ts
80  * @param {Editor} editor
81  */
82 export function handleTableCellRangeEvents(editor) {
83     /** @var {HTMLTableCellElement[]} * */
84     let selectedCells = [];
85
86     editor.on('TableSelectionChange', event => {
87         selectedCells = (event.cells || []).map(cell => cell.dom);
88     });
89     editor.on('TableSelectionClear', () => {
90         selectedCells = [];
91     });
92
93     // TinyMCE does not seem to do a great job on clearing styles in complex
94     // scenarios (like copied word content) when a range of table cells
95     // are selected. Here we watch for clear formatting events, so some manual
96     // cleanup can be performed.
97     const attrsToRemove = ['class', 'style', 'width', 'height'];
98     editor.on('ExecCommand', event => {
99         if (event.command === 'RemoveFormat') {
100             for (const cell of selectedCells) {
101                 for (const attr of attrsToRemove) {
102                     cell.removeAttribute(attr);
103                 }
104             }
105         }
106     });
107
108     // TinyMCE does not apply direction events to table cell range selections
109     // so here we hastily patch in that ability by setting the direction ourselves
110     // when a direction event is fired.
111     editor.on('ExecCommand', event => {
112         const command = event.command;
113         if (command !== 'mceDirectionLTR' && command !== 'mceDirectionRTL') {
114             return;
115         }
116
117         const dir = command === 'mceDirectionLTR' ? 'ltr' : 'rtl';
118         for (const cell of selectedCells) {
119             cell.setAttribute('dir', dir);
120             cleanElementDirection(cell);
121         }
122     });
123 }
124
125 /**
126  * Direction control might not work if there are other unexpected direction-handling styles
127  * or attributes involved nearby. This watches for direction change events to clean
128  * up direction controls, removing non-dir-attr direction controls, while removing
129  * directions from child elements that may be involved.
130  * @param {Editor} editor
131  */
132 export function handleTextDirectionCleaning(editor) {
133     editor.on('ExecCommand', event => {
134         const command = event.command;
135         if (command !== 'mceDirectionLTR' && command !== 'mceDirectionRTL') {
136             return;
137         }
138
139         const blocks = editor.selection.getSelectedBlocks();
140         for (const block of blocks) {
141             cleanElementDirection(block);
142         }
143     });
144 }