-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
TinyMCE.tsx
1466 lines (1238 loc) · 51.7 KB
/
TinyMCE.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from 'react';
import { useState, useEffect, useCallback, useRef, forwardRef, useImperativeHandle, useMemo } from 'react';
import { ScrollOptions, ScrollOptionTypes, EditorCommand, NoteBodyEditorProps, ResourceInfos, HtmlToMarkdownHandler, ScrollToTextValue } from '../../utils/types';
import { resourcesStatus, commandAttachFileToBody, getResourcesFromPasteEvent, processPastedHtml } from '../../utils/resourceHandling';
import attachedResources from '@joplin/lib/utils/attachedResources';
import useScroll from './utils/useScroll';
import styles_ from './styles';
import CommandService from '@joplin/lib/services/CommandService';
import { ToolbarButtonInfo } from '@joplin/lib/services/commands/ToolbarButtonUtils';
import ToggleEditorsButton, { Value as ToggleEditorsButtonValue } from '../../../ToggleEditorsButton/ToggleEditorsButton';
import ToolbarButton from '../../../../gui/ToolbarButton/ToolbarButton';
import usePluginServiceRegistration from '../../utils/usePluginServiceRegistration';
import { utils as pluginUtils } from '@joplin/lib/services/plugins/reducer';
import { _, closestSupportedLocale } from '@joplin/lib/locale';
import useContextMenu from './utils/useContextMenu';
import { copyHtmlToClipboard } from '../../utils/clipboardUtils';
import shim from '@joplin/lib/shim';
import { MarkupLanguage, MarkupToHtml } from '@joplin/renderer';
import BaseItem from '@joplin/lib/models/BaseItem';
import setupToolbarButtons from './utils/setupToolbarButtons';
import { plainTextToHtml } from '@joplin/lib/htmlUtils';
import openEditDialog from './utils/openEditDialog';
import { themeStyle } from '@joplin/lib/theme';
import { loadScript } from '../../../utils/loadScript';
import bridge from '../../../../services/bridge';
import { TinyMceEditorEvents } from './utils/types';
import type { Editor } from 'tinymce';
import { joplinCommandToTinyMceCommands, TinyMceCommand } from './utils/joplinCommandToTinyMceCommands';
import shouldPasteResources from './utils/shouldPasteResources';
import lightTheme from '@joplin/lib/themes/light';
import { Options as NoteStyleOptions } from '@joplin/renderer/noteStyle';
import markupRenderOptions from '../../utils/markupRenderOptions';
import { DropHandler } from '../../utils/useDropHandler';
import Logger from '@joplin/utils/Logger';
import useWebViewApi from './utils/useWebViewApi';
import useLinkTooltips from './utils/useLinkTooltips';
import { focus } from '@joplin/lib/utils/focusHandler';
const md5 = require('md5');
const { clipboard } = require('electron');
const supportedLocales = require('./supportedLocales');
import { hasProtocol } from '@joplin/utils/url';
import useTabIndenter from './utils/useTabIndenter';
import useKeyboardRefocusHandler from './utils/useKeyboardRefocusHandler';
import useDocument from '../../../hooks/useDocument';
const logger = Logger.create('TinyMCE');
// In TinyMCE 5.2, when setting the body to '<div id="rendered-md"></div>',
// it would end up as '<div id="rendered-md"><br/></div>' once rendered
// (an additional <br/> was inserted).
//
// This behaviour was "fixed" later on, possibly in 5.6, which has this change:
//
// - Fixed getContent with text format returning a new line when the editor is empty #TINY-6281
//
// The problem is that the list plugin was, unknown to me, relying on this <br/>
// being present. Without it, trying to add a bullet point or checkbox on an
// empty document, does nothing. The exact reason for this is unclear
// so as a workaround we manually add this <br> for empty documents,
// which fixes the issue.
//
// However,
// <div id="rendered-md"><br/></div>
// breaks newline behaviour in new notes (see https://github.com/laurent22/joplin/issues/9786).
// Thus, we instead use
// <div id="rendered-md"><p></p></div>
// which also seems to work around the list issue.
//
// Perhaps upgrading the list plugin (which is a fork of TinyMCE own list plugin)
// would help?
function awfulInitHack(html: string): string {
return html === '<div id="rendered-md"></div>' ? '<div id="rendered-md"><p></p></div>' : html;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
function findEditableContainer(node: any): any {
while (node) {
if (node.classList && node.classList.contains('joplin-editable')) return node;
node = node.parentNode;
}
return null;
}
let markupToHtml_ = new MarkupToHtml();
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
function stripMarkup(markupLanguage: number, markup: string, options: any = null) {
if (!markupToHtml_) markupToHtml_ = new MarkupToHtml();
return markupToHtml_.stripMarkup(markupLanguage, markup, options);
}
interface LastOnChangeEventInfo {
content: string;
resourceInfos: ResourceInfos;
contentKey: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
let dispatchDidUpdateIID_: any = null;
let changeId_ = 1;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const TinyMCE = (props: NoteBodyEditorProps, ref: any) => {
const [editorContainer, setEditorContainer] = useState<HTMLDivElement|null>(null);
const editorContainerDom = useDocument(editorContainer);
const [editor, setEditor] = useState<Editor|null>(null);
const [scriptLoaded, setScriptLoaded] = useState(false);
const [editorReady, setEditorReady] = useState(false);
const [draggingStarted, setDraggingStarted] = useState(false);
const props_onMessage = useRef(null);
props_onMessage.current = props.onMessage;
const props_onDrop = useRef<DropHandler|null>(null);
props_onDrop.current = props.onDrop;
const markupToHtml = useRef(null);
markupToHtml.current = props.markupToHtml;
const lastOnChangeEventInfo = useRef<LastOnChangeEventInfo>({
content: null,
resourceInfos: null,
contentKey: null,
});
const editorRef = useRef<Editor>(null);
editorRef.current = editor;
const styles = styles_(props);
// const theme = themeStyle(props.themeId);
const { scrollToPercent } = useScroll({ editor, onScroll: props.onScroll });
usePluginServiceRegistration(ref);
useContextMenu(editor, props.plugins, props.dispatch, props.htmlToMarkdown, props.markupToHtml);
useTabIndenter(editor);
useKeyboardRefocusHandler(editor);
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const dispatchDidUpdate = (editor: any) => {
if (dispatchDidUpdateIID_) shim.clearTimeout(dispatchDidUpdateIID_);
dispatchDidUpdateIID_ = shim.setTimeout(() => {
dispatchDidUpdateIID_ = null;
if (editor && editor.getDoc()) editor.getDoc().dispatchEvent(new Event('joplin-noteDidUpdate'));
}, 10);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const insertResourcesIntoContent = useCallback(async (filePaths: string[] = null, options: any = null) => {
const resourceMd = await commandAttachFileToBody('', filePaths, options);
if (!resourceMd) return;
const result = await props.markupToHtml(MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN, resourceMd, markupRenderOptions({ bodyOnly: true }));
editor.insertContent(result.html);
}, [props.markupToHtml, editor]);
const insertResourcesIntoContentRef = useRef(null);
insertResourcesIntoContentRef.current = insertResourcesIntoContent;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const onEditorContentClick = useCallback((event: any) => {
const nodeName = event.target ? event.target.nodeName : '';
if (nodeName === 'INPUT' && event.target.getAttribute('type') === 'checkbox') {
editor.fire(TinyMceEditorEvents.JoplinChange);
dispatchDidUpdate(editor);
}
if (nodeName === 'A' && (event.ctrlKey || event.metaKey)) {
const href = event.target.getAttribute('href');
if (href.indexOf('#') === 0) {
const anchorName = href.substr(1);
const anchor = editor.getDoc().getElementById(anchorName);
if (anchor) {
anchor.scrollIntoView();
} else {
logger.warn('could not find anchor with ID ', anchorName);
}
} else {
props.onMessage({ channel: href });
}
}
}, [editor, props.onMessage]);
useImperativeHandle(ref, () => {
return {
content: async () => {
if (!editorRef.current) return '';
return prop_htmlToMarkdownRef.current(props.contentMarkupLanguage, editorRef.current.getContent(), props.contentOriginalCss);
},
resetScroll: () => {
if (editor) editor.getWin().scrollTo(0, 0);
},
scrollTo: (options: ScrollOptions) => {
if (!editor) return;
if (options.type === ScrollOptionTypes.Hash) {
const anchor = editor.getDoc().getElementById(options.value);
if (!anchor) {
console.warn('Cannot find hash', options);
return;
}
anchor.scrollIntoView();
} else if (options.type === ScrollOptionTypes.Percent) {
scrollToPercent(options.value);
} else {
throw new Error(`Unsupported scroll options: ${options.type}`);
}
},
supportsCommand: (name: string) => {
// TODO: should also handle commands that are not in this map (insertText, focus, etc);
return !!joplinCommandToTinyMceCommands[name];
},
execCommand: async (cmd: EditorCommand) => {
if (!editor) return false;
logger.debug('execCommand', cmd);
let commandProcessed = true;
if (cmd.name === 'insertText') {
const result = await markupToHtml.current(MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN, cmd.value, markupRenderOptions({ bodyOnly: true }));
editor.insertContent(result.html);
} else if (cmd.name === 'editor.focus') {
focus('TinyMCE::editor.focus', editor);
if (cmd.value?.moveCursorToStart) {
editor.selection.placeCaretAt(0, 0);
editor.selection.setCursorLocation(
editor.dom.root,
0,
);
}
} else if (cmd.name === 'editor.execCommand') {
if (!('ui' in cmd.value)) cmd.value.ui = false;
if (!('value' in cmd.value)) cmd.value.value = null;
if (!('args' in cmd.value)) cmd.value.args = {};
editor.execCommand(cmd.value.name, cmd.value.ui, cmd.value.value, cmd.value.args);
} else if (cmd.name === 'dropItems') {
if (cmd.value.type === 'notes') {
const result = await markupToHtml.current(MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN, cmd.value.markdownTags.join('\n'), markupRenderOptions({ bodyOnly: true }));
editor.insertContent(result.html);
} else if (cmd.value.type === 'files') {
insertResourcesIntoContentRef.current(cmd.value.paths, { createFileURL: !!cmd.value.createFileURL });
} else {
logger.warn('unsupported drop item: ', cmd);
}
} else if (cmd.name === 'editor.scrollToText') {
const cmdValue = cmd.value as ScrollToTextValue;
const findElementByText = (doc: Document, text: string, element: string) => {
const headers = doc.querySelectorAll(element);
for (const header of headers) {
if (header.textContent?.trim() === text) {
return header;
}
}
return null;
};
const contentDocument = editor.getDoc();
const targetElement = findElementByText(contentDocument, cmdValue.text, cmdValue.element);
if (targetElement) {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
} else {
logger.warn('editor.scrollToText: Could not find text to scroll to :', cmdValue);
}
} else {
commandProcessed = false;
}
if (commandProcessed) return true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const additionalCommands: any = {
selectedText: () => {
return stripMarkup(MarkupToHtml.MARKUP_LANGUAGE_HTML, editor.selection.getContent());
},
selectedHtml: () => {
return editor.selection.getContent();
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
replaceSelection: (value: any) => {
editor.selection.setContent(value);
editor.fire(TinyMceEditorEvents.JoplinChange);
dispatchDidUpdate(editor);
// It doesn't make sense but it seems calling setContent
// doesn't create an undo step so we need to call it
// manually.
// https://github.com/tinymce/tinymce/issues/3745
window.requestAnimationFrame(() => editor.undoManager.add());
},
pasteAsText: () => editor.fire(TinyMceEditorEvents.PasteAsText),
};
if (additionalCommands[cmd.name]) {
return additionalCommands[cmd.name](cmd.value);
}
if (!joplinCommandToTinyMceCommands[cmd.name]) {
logger.warn('unsupported Joplin command: ', cmd);
return false;
}
if (joplinCommandToTinyMceCommands[cmd.name] === true) {
// Already handled in useWindowCommandHandlers.ts
} else if (joplinCommandToTinyMceCommands[cmd.name] === false) {
// explicitly not supported
} else {
const tinyMceCmd: TinyMceCommand = { ...(joplinCommandToTinyMceCommands[cmd.name] as TinyMceCommand) };
if (!('ui' in tinyMceCmd)) tinyMceCmd.ui = false;
if (!('value' in tinyMceCmd)) tinyMceCmd.value = null;
editor.execCommand(tinyMceCmd.name, tinyMceCmd.ui, tinyMceCmd.value);
}
return true;
},
};
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
}, [editor, props.contentMarkupLanguage, props.contentOriginalCss]);
// -----------------------------------------------------------------------------------------
// Load the TinyMCE library. The lib loads additional JS and CSS files on startup
// (for themes), and so it needs to be loaded via <script> tag. Requiring it from the
// module would not load these extra files.
// -----------------------------------------------------------------------------------------
// const loadScript = async (script: any) => {
// return new Promise((resolve) => {
// let element: any = document.createElement('script');
// if (script.src.indexOf('.css') >= 0) {
// element = document.createElement('link');
// element.rel = 'stylesheet';
// element.href = script.src;
// } else {
// element.src = script.src;
// if (script.attrs) {
// for (const attr in script.attrs) {
// element[attr] = script.attrs[attr];
// }
// }
// }
// element.id = script.id;
// element.onload = () => {
// resolve(null);
// };
// document.getElementsByTagName('head')[0].appendChild(element);
// });
// };
useEffect(() => {
if (!editorContainerDom) return () => {};
let cancelled = false;
async function loadScripts() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const scriptsToLoad: any[] = [
{
src: `${bridge().vendorDir()}/lib/tinymce/tinymce.min.js`,
id: 'tinyMceScript',
loaded: false,
},
{
src: 'gui/NoteEditor/NoteBody/TinyMCE/plugins/lists.js',
id: 'tinyMceListsPluginScript',
loaded: false,
},
];
for (const s of scriptsToLoad) {
if (editorContainerDom.getElementById(s.id)) {
s.loaded = true;
continue;
}
// eslint-disable-next-line no-console
console.info('Loading script', s.src);
await loadScript(s, editorContainerDom);
if (cancelled) return;
s.loaded = true;
}
setScriptLoaded(true);
}
void loadScripts();
return () => {
cancelled = true;
};
}, [editorContainerDom]);
useWebViewApi(editor, editorContainerDom?.defaultView);
const { resetModifiedTitles: resetLinkTooltips } = useLinkTooltips(editor);
useEffect(() => {
if (!editorContainerDom) return () => {};
const theme = themeStyle(props.themeId);
const backgroundColor = props.whiteBackgroundNoteRendering ? lightTheme.backgroundColor : theme.backgroundColor;
const element = editorContainerDom.createElement('style');
element.setAttribute('id', 'tinyMceStyle');
editorContainerDom.head.appendChild(element);
element.appendChild(editorContainerDom.createTextNode(`
.joplin-tinymce .tox-editor-header {
padding-left: ${styles.leftExtraToolbarContainer.width + styles.leftExtraToolbarContainer.padding * 2}px;
padding-right: ${styles.rightExtraToolbarContainer.width + styles.rightExtraToolbarContainer.padding * 2}px;
}
.tox .tox-toolbar,
.tox .tox-toolbar__overflow,
.tox .tox-toolbar__primary,
.tox-editor-header .tox-toolbar__primary,
.tox .tox-toolbar-overlord,
.tox.tox-tinymce-aux .tox-toolbar__overflow,
.tox .tox-statusbar,
.tox .tox-dialog__header,
.tox .tox-dialog,
.tox textarea,
.tox input,
.tox .tox-menu,
.tox .tox-dialog__footer {
background-color: ${theme.backgroundColor} !important;
}
.tox .tox-dialog__body-content,
.tox .tox-collection__item {
color: ${theme.color};
}
.tox .tox-dialog__body-nav-item {
color: ${theme.color};
}
.tox .tox-dialog__body-nav-item[aria-selected=true] {
color: ${theme.color3};
border-color: ${theme.color3};
background-color: ${theme.backgroundColor3};
}
.tox .tox-checkbox__icons .tox-checkbox-icon__unchecked svg {
fill: ${theme.color};
}
.tox .tox-collection--list .tox-collection__item--active {
color: ${theme.backgroundColor};
}
.tox .tox-collection__item--state-disabled {
opacity: 0.7;
}
.tox .tox-menu {
/* Ensures that popover menus (the color swatch menu) has a visible border
even in dark mode. */
border: 1px solid rgba(140, 140, 140, 0.3);
}
/*
When creating dialogs, TinyMCE doesn't seem to offer a way to style the components or to assign classes to them.
We want the code dialog box text area to be monospace, and since we can't target this precisely, we apply the style
to all textareas of all dialogs. As I think only the code dialog displays a textarea that should be fine.
*/
.tox .tox-dialog textarea {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
.tox .tox-dialog-wrap__backdrop {
background-color: ${theme.backgroundColor} !important;
opacity:0.7
}
.tox .tox-editor-header {
border: none;
}
.tox .tox-tbtn,
.tox .tox-tbtn svg,
.tox .tox-menu button > svg,
.tox .tox-split-button,
.tox .tox-dialog__header,
.tox .tox-button--icon .tox-icon svg,
.tox .tox-button.tox-button--icon .tox-icon svg,
.tox textarea,
.tox input,
.tox .tox-label,
.tox .tox-toolbar-label {
color: ${theme.color3} !important;
fill: ${theme.color3} !important;
}
.tox .tox-statusbar a,
.tox .tox-statusbar__path-item,
.tox .tox-statusbar__wordcount,
.tox .tox-statusbar__path-divider {
color: ${theme.color};
fill: ${theme.color};
opacity: 0.7;
}
.tox .tox-tbtn--enabled,
.tox .tox-tbtn--enabled:hover,
.tox .tox-menu button:hover,
.tox .tox-split-button {
background-color: ${theme.selectedColor};
}
.tox .tox-button--naked:hover:not(:disabled) {
background-color: ${theme.backgroundColor} !important;
}
.tox .tox-tbtn:focus,
.tox .tox-split-button:focus {
background-color: ${theme.backgroundColor3}
}
.tox .tox-tbtn:hover,
.tox .tox-menu button:hover > svg {
color: ${theme.colorHover3} !important;
fill: ${theme.colorHover3} !important;
background-color: ${theme.backgroundColorHover3}
}
.tox .tox-tbtn {
height: ${theme.toolbarHeight}px;
min-height: ${theme.toolbarHeight}px;
margin: 0;
}
.tox .tox-tbtn[aria-haspopup=true] {
width: ${theme.toolbarHeight + 15}px;
min-width: ${theme.toolbarHeight + 15}px;
}
.tox .tox-tbtn > span,
.tox .tox-tbtn:active > span,
.tox .tox-tbtn:hover > span {
transform: scale(0.8);
}
.tox .tox-toolbar__primary,
.tox .tox-toolbar__overflow {
background: none;
background-color: ${theme.backgroundColor3} !important;
}
.tox .tox-split-button:hover {
box-shadow: none;
}
.tox-tinymce,
.tox .tox-toolbar__group,
.tox.tox-tinymce-aux .tox-toolbar__overflow,
.tox .tox-dialog__footer {
border: none !important;
}
.tox-tinymce {
border-top: none !important;
}
/* Override the TinyMCE font styles with more specific CSS selectors.
Without this, the built-in FontAwesome styles are not applied because
they are overridden by TinyMCE. */
.plugin-icon.fa, .plugin-icon.far, .plugin-icon.fas {
font-family: "Font Awesome 5 Free";
font-size: ${theme.toolbarHeight - theme.toolbarPadding}px;
}
.plugin-icon.fa, .plugin-icon.fas {
font-weight: 900;
}
.plugin-icon.fab, .plugin-icon.far {
font-weight: 400;
}
.joplin-tinymce .tox-toolbar__group {
background-color: ${theme.backgroundColor3};
padding-top: ${theme.toolbarPadding}px;
padding-bottom: ${theme.toolbarPadding}px;
}
.joplin-tinymce .tox .tox-edit-area__iframe {
background-color: ${backgroundColor} !important;
}
.joplin-tinymce .tox .tox-toolbar__primary {
/* This component sets an empty svg with a white background as the background
* which needs to be cleared to prevent it from flashing white in dark themes */
background: none;
background-color: ${theme.backgroundColor3} !important;
}
`));
return () => {
editorContainerDom.head.removeChild(element);
};
// editorReady is here because TinyMCE starts by initializing a blank iframe, which needs to be
// styled by us, otherwise users in dark mode get a bright white flash. During initialization
// our styling is overwritten which causes some elements to have the wrong styling. Removing the
// style and re-applying it on editorReady gives our styles precedence and prevents any flashing
//
// watchedNoteFiles is here , as it triggers a re-render of styles whenever it changes,
// this keeps the toolbar header styles in sync with toggle external editing button
//
// tl;dr: editorReady is used here because the css needs to be re-applied after TinyMCE init
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
}, [editorReady, editorContainerDom, props.themeId, lightTheme, props.whiteBackgroundNoteRendering, props.watchedNoteFiles]);
// -----------------------------------------------------------------------------------------
// Enable or disable the editor
// -----------------------------------------------------------------------------------------
useEffect(() => {
if (!editor) return;
editor.setMode(props.disabled ? 'readonly' : 'design');
}, [editor, props.disabled]);
// -----------------------------------------------------------------------------------------
// Create and setup the editor
// -----------------------------------------------------------------------------------------
useEffect(() => {
if (!scriptLoaded) return;
if (!editorContainer) return;
const loadEditor = async () => {
const language = closestSupportedLocale(props.locale, true, supportedLocales);
const pluginCommandNames: string[] = [];
const infos = pluginUtils.viewInfosByType(props.plugins, 'toolbarButton');
for (const info of infos) {
const view = info.view;
if (view.location !== 'editorToolbar') continue;
pluginCommandNames.push(view.commandName);
}
const toolbarPluginButtons = pluginCommandNames.length ? ` | ${pluginCommandNames.join(' ')}` : '';
// The toolbar is going to wrap based on groups of buttons
// (delimited by |). It means that if we leave large groups of
// buttons towards the end of the toolbar it's going to needlessly
// hide many buttons even when there is space. So this is why below,
// we create small groups of just one button towards the end.
const toolbar = [
'bold', 'italic', 'joplinHighlight', 'joplinStrikethrough', 'formattingExtras', '|',
'link', 'joplinInlineCode', 'joplinCodeBlock', 'joplinAttach', '|',
'bullist', 'numlist', 'joplinChecklist', '|',
'h1', 'h2', 'h3', '|',
'hr', '|',
'blockquote', '|',
'tableWithHeader', '|',
`joplinInsertDateTime${toolbarPluginButtons}`,
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const containerWindow = editorContainerDom.defaultView as any;
const editors = await containerWindow.tinymce.init({
selector: `#${editorContainer.id}`,
width: '100%',
body_class: 'jop-tinymce',
height: '100%',
resize: false,
icons: 'Joplin',
icons_url: 'gui/NoteEditor/NoteBody/TinyMCE/icons.js',
plugins: 'noneditable link joplinLists hr searchreplace codesample table',
noneditable_noneditable_class: 'joplin-editable', // Can be a regex too
iframe_aria_text: _('Rich Text editor. Press Escape then Tab to escape focus.'),
// #p: Pad empty paragraphs with to prevent them from being removed.
// *[*]: Allow all elements and attributes -- we already filter in sanitize_html
// See https://www.tiny.cloud/docs/configure/content-filtering/#controlcharacters
valid_elements: '#p,*[*]',
menubar: false,
relative_urls: false,
branding: false,
statusbar: false,
target_list: false,
// Handle the first table row as table header.
// https://www.tiny.cloud/docs/plugins/table/#table_header_type
table_header_type: 'sectionCells',
language_url: ['en_US', 'en_GB'].includes(language) ? undefined : `${bridge().vendorDir()}/lib/tinymce/langs/${language}`,
toolbar: toolbar.join(' '),
localization_function: _,
contextmenu: false,
browser_spellcheck: true,
// Work around an issue where images with a base64 SVG data URL would be broken.
//
// See https://github.com/tinymce/tinymce/issues/3864
//
// This was fixed in TinyMCE 6.1, so remove it when we upgrade.
images_dataimg_filter: (img: HTMLImageElement) => !img.src.startsWith('data:'),
formats: {
joplinHighlight: { inline: 'mark', remove: 'all' },
joplinStrikethrough: { inline: 's', remove: 'all' },
joplinInsert: { inline: 'ins', remove: 'all' },
joplinSub: { inline: 'sub', remove: 'all' },
joplinSup: { inline: 'sup', remove: 'all' },
code: { inline: 'code', remove: 'all', attributes: { spellcheck: 'false' } },
forecolor: { inline: 'span', styles: { color: '%value' } },
},
setup: (editor: Editor) => {
editor.addCommand('joplinAttach', () => {
insertResourcesIntoContentRef.current();
});
editor.ui.registry.addButton('joplinAttach', {
tooltip: _('Attach file'),
icon: 'paperclip',
onAction: async function() {
editor.execCommand('joplinAttach');
},
});
setupToolbarButtons(editor);
editor.ui.registry.addButton('joplinCodeBlock', {
tooltip: _('Code Block'),
icon: 'code-sample',
onAction: async function() {
openEditDialog(editor, markupToHtml, dispatchDidUpdate, null);
},
});
editor.ui.registry.addToggleButton('joplinInlineCode', {
tooltip: _('Inline Code'),
icon: 'sourcecode',
onAction: function() {
editor.execCommand('mceToggleFormat', false, 'code', { class: 'inline-code' });
},
onSetup: function(api) {
api.setActive(editor.formatter.match('code'));
const unbind = editor.formatter.formatChanged('code', api.setActive).unbind;
return function() {
if (unbind) unbind();
};
},
});
editor.ui.registry.addMenuButton('tableWithHeader', {
icon: 'table',
tooltip: 'Table',
fetch: (callback) => {
callback([
{
type: 'fancymenuitem',
fancytype: 'inserttable',
onAction: (data) => {
editor.execCommand('mceInsertTable', false, { rows: data.numRows, columns: data.numColumns, options: { headerRows: 1 } });
},
},
]);
},
});
editor.ui.registry.addButton('joplinInsertDateTime', {
tooltip: _('Insert time'),
icon: 'insert-time',
onAction: function() {
void CommandService.instance().execute('insertDateTime');
},
});
for (const pluginCommandName of pluginCommandNames) {
const iconClassName = CommandService.instance().iconName(pluginCommandName);
// Only allow characters that appear in Font Awesome class names: letters, spaces, and dashes.
const safeIconClassName = iconClassName.replace(/[^a-z0-9 -]/g, '');
editor.ui.registry.addIcon(pluginCommandName, `<i class="plugin-icon ${safeIconClassName}"></i>`);
editor.ui.registry.addButton(pluginCommandName, {
tooltip: CommandService.instance().label(pluginCommandName),
icon: pluginCommandName,
onAction: function() {
void CommandService.instance().execute(pluginCommandName);
},
});
}
editor.addShortcut('Meta+Shift+7', '', () => editor.execCommand('InsertOrderedList'));
editor.addShortcut('Meta+Shift+8', '', () => editor.execCommand('InsertUnorderedList'));
editor.addShortcut('Meta+Shift+9', '', () => editor.execCommand('InsertJoplinChecklist'));
// TODO: remove event on unmount?
editor.on('DblClick', (event) => {
const editable = findEditableContainer(event.target);
if (editable) openEditDialog(editor, markupToHtml, dispatchDidUpdate, editable);
});
editor.on('drop', (event) => {
// Prevent the message "Dropped file type is not supported" from showing up.
// It was added in TinyMCE 5.4 and doesn't apply since we do support
// the file type.
//
// See https://stackoverflow.com/questions/64782955/tinymce-inline-drag-and-drop-image-upload-not-working
//
// The other suggested solution, setting block_unsupported_drop to false,
// causes all dropped files to be placed at the top of the document.
//
// Because .preventDefault cancels TinyMCE's own drop handler, we only
// call .preventDefault if Joplin handled the event:
if (props_onDrop.current(event)) {
event.preventDefault();
}
});
editor.on('ObjectResized', (event) => {
if (event.target.nodeName === 'IMG') {
editor.fire(TinyMceEditorEvents.JoplinChange);
dispatchDidUpdate(editor);
}
});
editor.on('init', () => {
setEditorReady(true);
});
const preprocessContent = () => {
// Disable spellcheck for all inline code blocks.
const codeElements = editor.dom.doc.querySelectorAll('code.inline-code');
for (const code of codeElements) {
code.setAttribute('spellcheck', 'false');
}
};
editor.on('SetContent', () => {
preprocessContent();
props_onMessage.current({ channel: 'noteRenderComplete' });
});
},
});
setEditor(editors[0]);
};
void loadEditor();
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
}, [scriptLoaded, editorContainer]);
// -----------------------------------------------------------------------------------------
// Set the initial content and load the plugin CSS and JS files
// -----------------------------------------------------------------------------------------
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const loadDocumentAssets = (themeId: number, editor: any, pluginAssets: any[]) => {
const theme = themeStyle(themeId);
let docHead_: HTMLHeadElement = null;
function docHead() {
if (docHead_) return docHead_;
docHead_ = editor.getDoc().getElementsByTagName('head')[0];
return docHead_;
}
const allCssFiles = [
`${bridge().vendorDir()}/lib/@fortawesome/fontawesome-free/css/all.min.css`,
`gui/note-viewer/pluginAssets/highlight.js/${theme.codeThemeCss}`,
].concat(
pluginAssets
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
.filter((a: any) => a.mime === 'text/css')
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
.map((a: any) => a.path),
);
const allJsFiles = [].concat(
pluginAssets
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
.filter((a: any) => a.mime === 'application/javascript')
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
.map((a: any) => a.path),
);
const filePathToElementId = (path: string) => {
return `jop-tiny-mce-${md5(escape(path))}`;
};
const existingElements = Array.from(docHead().getElementsByClassName('jop-tinymce-css')).concat(Array.from(docHead().getElementsByClassName('jop-tinymce-js')));
const existingIds: string[] = [];
for (const e of existingElements) existingIds.push(e.getAttribute('id'));
const processedIds: string[] = [];
for (const cssFile of allCssFiles) {
const elementId = filePathToElementId(cssFile);
processedIds.push(elementId);
if (existingIds.includes(elementId)) continue;
const style = editor.dom.create('link', {
id: elementId,
rel: 'stylesheet',
type: 'text/css',
href: cssFile,
class: 'jop-tinymce-css',
});
docHead().appendChild(style);
}
for (const jsFile of allJsFiles) {
const elementId = filePathToElementId(jsFile);
processedIds.push(elementId);
if (existingIds.includes(elementId)) continue;
const script = editor.dom.create('script', {
id: filePathToElementId(jsFile),
type: 'text/javascript',
class: 'jop-tinymce-js',
src: jsFile,
});
docHead().appendChild(script);
}
// Remove all previously loaded files that aren't in the assets this time.
// Note: This is important to ensure that we properly change themes.
// See https://github.com/laurent22/joplin/issues/8520
for (const existingId of existingIds) {
if (!processedIds.includes(existingId)) {
const element = existingElements.find(e => e.getAttribute('id') === existingId);
if (element) docHead().removeChild(element);
}
}
};
function resourceInfosEqual(ri1: ResourceInfos, ri2: ResourceInfos): boolean {
if (ri1 && !ri2 || !ri1 && ri2) return false;
if (!ri1 && !ri2) return true;
const keys1 = Object.keys(ri1);
const keys2 = Object.keys(ri2);
if (keys1.length !== keys2.length) return false;
// The attachedResources() call that generates the ResourceInfos object
// uses cache for the resource objects, so we can use strict equality
// for comparison.
for (const k of keys1) {
if (ri1[k] !== ri2[k]) return false;
}
return true;
}
useEffect(() => {
if (!editor) return () => {};
if (resourcesStatus(props.resourceInfos) !== 'ready') {
editor.setContent('');
return () => {};
}
let cancelled = false;
const loadContent = async () => {
const resourcesEqual = resourceInfosEqual(lastOnChangeEventInfo.current.resourceInfos, props.resourceInfos);
if (lastOnChangeEventInfo.current.content !== props.content || !resourcesEqual) {
const result = await props.markupToHtml(
props.contentMarkupLanguage,
props.content,
markupRenderOptions({
resourceInfos: props.resourceInfos,
// Allow file:// URLs that point to the resource directory.
// This prevents HTML-style resource URLs (e.g. <a href="file://path/to/resource/.../"></a>)
// from being discarded.
allowedFilePrefixes: [props.resourceDirectory],
}),
);
if (cancelled) return;
// Use an offset bookmark -- the default bookmark type is not preserved after unloading
// and reloading the editor.