-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplugin.js
More file actions
701 lines (625 loc) · 26.4 KB
/
plugin.js
File metadata and controls
701 lines (625 loc) · 26.4 KB
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
/*
* Supercode TinyMCE Plugin
* Supercode is an enhanced source code editor plugin for TinyMCE, the popular web-based WYSIWYG editor. This plugin provides users with a seamless experience for editing and displaying source code within the TinyMCE editor environment.
*
* Repository: https://github.com/prathamVaidya/supercode-tinymce-plugin
* Author: Pratham Vaidya
* License: GPL-3.0
* Version: 1.2.0
*
* Released under the GPL-3.0 License.
*/
! function() {
"use strict";
/**
modal ->
{
element : Modal Container Ref
editor : Ace Editor
}
*/
const MODAL_HTML = `
<div id="supercode-backdrop"></div>
<div id="supercode-modal">
<div id="supercode-header">
<h1>Source Code Editor</h1>
<button id="supercode-close-btn">
Close
</button>
</div>
<div id="supercode-editor"></div>
<div id="supercode-footer">
<div id="supercode-theme-container">
<label for="supercode-theme-dropdown">Select Theme:</label>
<select id="supercode-theme-dropdown">
<optgroup label="LIGHT">
<option value="chrome">Chrome</option>
<option value="clouds">Clouds</option>
<option value="crimson_editor">Crimson Editor</option>
<option value="dawn">Dawn</option>
<option value="dreamweaver">Dreamweaver</option>
<option value="eclipse">Eclipse</option>
<option value="github">GitHub</option>
<option value="iplastic">IPlastic</option>
<option value="katzenmilch">KatzenMilch</option>
<option value="kuroir">Kuroir</option>
<option value="solarized_light">Solarized Light</option>
<option value="sqlserver">SQL Server</option>
<option value="textmate">TextMate</option>
<option value="tomorrow">Tomorrow</option>
<option value="xcode">XCode</option>
</optgroup>
<optgroup label="DARK">
<option value="ambiance">Ambiance</option>
<option value="chaos">Chaos</option>
<option value="clouds_midnight">Clouds Midnight</option>
<option value="cobalt">Cobalt</option>
<option value="dracula">Dracula</option>
<option value="gob">Green on Black</option>
<option value="gruvbox">Gruvbox</option>
<option value="idle_fingers">idle Fingers</option>
<option value="kr_theme">krTheme</option>
<option value="merbivore">Merbivore</option>
<option value="merbivore_soft">Merbivore Soft</option>
<option value="mono_industrial">Mono Industrial</option>
<option value="monokai">Monokai</option>
<option value="pastel_on_dark">Pastel on Dark</option>
<option value="solarized_dark">Solarized Dark</option>
<option value="terminal">Terminal</option>
<option value="tomorrow_night">Tomorrow Night</option>
<option value="tomorrow_night_blue">Tomorrow Night Blue</option>
<option value="tomorrow_night_bright">Tomorrow Night Bright</option>
<option value="tomorrow_night_eighties">Tomorrow Night 80s</option>
<option value="twilight">Twilight</option>
<option value="vibrant_ink">Vibrant Ink</option>
</optgroup>
</select>
</div>
<div id="supercode-button-container">
<button id="supercode-cancel-btn">Cancel</button>
<button id="supercode-save-btn">Save</button>
</div>
</div>
</div>
`
const MODAL_CSS = `
:root{
--supercode-modal-primary: #ffffff;
--supercode-modal-secondary: #222f3e;
--supercode-modal-border: rgba(0, 0, 0, 0.1);
}
/* Media query for mobile devices */
@media only screen and (max-width: 767px) {
#supercode-modal {
width: 100% !important;
height: 100% !important;
border-radius: 0 !important;
}
}
.disable-scroll {
overflow: hidden;
}
#supercode-modal-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 990;
display: none;
opacity: 0;
transition: opacity 0.1s linear;
}
#supercode-backdrop {
position: absolute;
top: 0;
left: 0;
background: black;
opacity: 0.7;
width: 100%;
height: 100%;
z-index: 1;
}
#supercode-modal {
width: 90%;
height: 80%;
max-width: 1200px;
z-index: 2;
overflow: hidden;
border-radius: 10px;
display: flex;
flex-direction: column;
background: var(--supercode-modal-primary);
}
#supercode-header {
display: flex;
padding: 0.5rem 1rem;
border-bottom: 1px solid var(--supercode-modal-border);
color: var(--supercode-modal-secondary);
}
#supercode-modal h1 {
flex-grow: 1;
margin: auto;
font-size: 14px;
}
#supercode-close-btn {
background: none;
border: none;
padding: 0;
height: 100%;
cursor: pointer;
fill: var(--supercode-modal-secondary);
}
#supercode-editor {
width: 100%;
height: 100%;
position: relative;
}
#supercode-footer {
padding: 0.5rem 1rem;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
gap: 1rem;
border-top: 1px solid var(--supercode-modal-border);
}
#supercode-theme-container {
display: flex;
align-items: center;
}
#supercode-theme-container label {
margin-right: 1.0rem; /* Adjust as needed */
color: var(--supercode-modal-secondary);
padding:5px 0px 0px 0px;
}
#supercode-theme-container select {
/* Add styles for select dropdown */
padding:6px 3px;
min-width:200px !important;
border-radius: 4px;
}
#supercode-button-container {
display: flex;
gap: 1rem;
}
#supercode-footer #supercode-button-container button {
padding: 0.5rem 1rem;
border-radius: 5px;
font-weight: bold;
border: none;
cursor: pointer;
min-width: 5rem;
transition: opacity 0.1s linear;
}
#supercode-footer #supercode-button-container button:hover {
opacity: 0.8;
}
#supercode-cancel-btn {
background: transparent;
color: var(--supercode-modal-secondary);
}
#supercode-save-btn {
background: var(--supercode-modal-secondary);
color: var(--supercode-modal-primary);
}
/* Media query for responsiveness */
@media (min-width: 768px) {
#supercode-footer {
flex-direction: row; /* Switch to horizontal layout */
align-items: center;
}
#supercode-theme-container {
width: auto; /* Allow select container to adjust width */
margin-bottom: 0; /* Remove margin for desktop view */
}
#supercode-button-container {
display: flex; /* Show button container */
gap: 1rem; /* Add spacing between buttons */
}
}
`;
const CLOSE_ICON_FALLBACK = `<svg width="24" height="24"><path d="M17.3 8.2 13.4 12l3.9 3.8a1 1 0 0 1-1.5 1.5L12 13.4l-3.8 3.9a1 1 0 0 1-1.5-1.5l3.9-3.8-3.9-3.8a1 1 0 0 1 1.5-1.5l3.8 3.9 3.8-3.9a1 1 0 0 1 1.5 1.5Z" fill-rule="evenodd"></path></svg>`
const CODE_ICON_FALLBACK = `<svg width="24" height="24" focusable="false"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 0 1 0-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7ZM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 0 0-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7Z"></path></g></svg>`
let modal = null;
const initDependencies = (config) => {
const scripts = {
"ace-default" : {
url: 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.9.6/ace.js',
loaded: false,
required: true,
},
"beautify-html" : {
url: 'https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify-html.min.js',
loaded: false,
required: true,
},
"ace-autocomplete" : {
url: 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.9.6/ext-language_tools.min.js',
loaded: false,
required: false,
},
}
if(config.autocomplete){
scripts['ace-autocomplete'].required = true;
}
Object.values(scripts).forEach((script) => {
if (script.loaded) return;
let element = document.createElement('script');
element.src = script.url;
element.type = "text/javascript";
document.body.appendChild(element);
})
}
const injectCSS = (css) => {
const style = document.createElement('style');
style.innerHTML = css;
document.head.append(style);
}
// on plugin load
const mainPlugin = function(editor) {
let editorWidth = 0, originalHeader, isScreenSizeChanged = false, session, aceEditor;
const Config = {
theme: 'chrome',
fontSize: 14, // in px
wrap: true,
icon: undefined, // auto set during config
iconName: 'sourcecode',
autocomplete: false,
language: 'html',
renderer: null,
parser: null,
shortcut: true,
aceCss: null,
fontFamily: null,
fallbackModal: false, // enabled in cases like inline, or versions where `CustomView` is not supported.
modalPrimaryColor: '#ffffff',
modalSecondaryColor: '#222f3e',
dark: false,
debug: true
}
const debug = (msg) => {
if(Config.debug){
console.warn(`${msg} \n\nUse debug:false option to disable this warning`);
}
}
// Get Configurations
const setConfig = (editor) => {
const supercodeOptions = editor.getParam('supercode');
if (supercodeOptions && typeof supercodeOptions === "object") {
for (const key in supercodeOptions) {
if (supercodeOptions.hasOwnProperty(key)) {
const value = supercodeOptions[key];
switch (key) {
case 'theme':
case 'language':
case 'iconName':
case 'aceCss':
case 'fontFamily':
case 'modalPrimaryColor':
case 'modalSecondaryColor':
if (typeof value === "string") {
Config[key] = value;
}
break;
case 'fontSize':
if (typeof value === "number" && value > 0) {
Config.fontSize = parseInt(value);
}
break;
case 'wrap':
case 'autocomplete':
case 'shortcut':
case 'fallbackModal':
case 'dark':
case 'debug':
if (typeof value === "boolean") {
Config[key] = value;
}
break;
case 'parser':
case 'renderer':
if (typeof value === "function") {
Config[key] = value;
}
break;
default:
// Ignore unrecognized options
break;
}
}
}
}
// Set plugin icon
Config.icon = editor.ui.registry.getAll?.().icons?.[Config.iconName];
if (!Config.icon) {
Config.icon = CODE_ICON_FALLBACK;
debug("Supercode Icon name is invalid or you are using older versions of tinyMCE. The icon is set to default fallback code icon.");
}
// Detect and set fallback model if its required
if(!Config.fallbackModal){
// case: inline mode, < v5
if(editor.getParam('inline') === true || tinymce.majorVersion <= 5){
Config.fallbackModal = true
}
}
}
const setAceOptions = () => {
const options = {};
if(Config.autocomplete){
options.enableLiveAutocompletion = true;
}
if(Config.fontFamily){
options.fontFamily = Config.fontFamily;
}
aceEditor.setOptions(options);
// Check if the theme cookie exists
const themeCookieExists = document.cookie.split(';').some((item) => item.trim().startsWith('supercodeTheme='));
let selectedTheme = `${Config.theme}`;
// If the cookie exists, load the theme from the cookie
if (themeCookieExists) {
selectedTheme = document.cookie
.split('; ')
.find(row => row.startsWith('supercodeTheme='))
.split('=')[1];
aceEditor.setTheme(`ace/theme/${selectedTheme}`);
} else {
aceEditor.setTheme(`ace/theme/${Config.theme}`);
}
const themeSelect = document.getElementById("supercode-theme-dropdown");
Array.from(themeSelect.options).forEach(option => {
if (option.value === selectedTheme) {
option.selected = true;
}
});
aceEditor.setFontSize(Config.fontSize);
aceEditor.setShowPrintMargin(false);
}
// Builds ace editor only on the first run
const buildAceEditor = (view) => {
// Attach Ace Editor to shadow dom to prevent tinymce css affecting it
view.attachShadow({ mode: 'open' });
if(Config.aceCss){
const sheet = new CSSStyleSheet()
sheet.replaceSync(Config.aceCss);
view.shadowRoot.adoptedStyleSheets.push(sheet);
}
view.shadowRoot.innerHTML = `<div class="supercode-editor" style="width: 100%; height: 100%; position: absolute; left:0; top:0"></div>`;
const editorElement = view.shadowRoot.querySelector('.supercode-editor');
editorElement.style.width = '100%';
editorElement.style.height = '100%';
aceEditor = ace.edit(editorElement);
// https://github.com/josdejong/jsoneditor/issues/742#issuecomment-698449020
aceEditor.renderer.attachToShadowRoot();
setAceOptions();
}
const setHeader = (view, originalHeader) => {
// add a copy of original header to give original header look
const newHeader = originalHeader.cloneNode(true);
newHeader.style.position = 'relative';
// If menu-bar exists utilize the space to show Title "Source Code Editor"
const menubar = newHeader.querySelector('.tox-menubar');
if(menubar){
menubar.innerHTML = `<b style='font-size: 14px; font-weight: bold; padding: 11px 9px;'>Source Code Editor</b>`
}
// disable all the buttons except supercode button, attach event listener
let overflowButton = null, isPluginButton = false;
newHeader.querySelectorAll('.tox-tbtn, .tox-split-button').forEach((btn) => {
if(btn.getAttribute('data-mce-name') != 'supercode'){
// remove overflow button to make space for code button
if(btn.getAttribute('data-mce-name') === 'overflow-button'){
overflowButton = btn;
}
btn.classList.remove('tox-tbtn--enabled');
btn.classList.add('tox-tbtn--disabled');
btn.removeAttribute('data-mce-name');
}
else{
isPluginButton = true;
btn.setAttribute('data-mce-name', 'supercode-toggle')
btn.classList.add('tox-tbtn--enabled');
btn.onclick = onSaveHandler;
}
});
// in case of overflow, replace the overflow button with code button
if(!isPluginButton && overflowButton){
overflowButton.classList = 'tox-tbtn tox-tbtn--enabled';
overflowButton.innerHTML = `<span class="tox-icon tox-tbtn__icon-wrap">${Config.icon}</span>`;
overflowButton.onclick = onSaveHandler;
}
view.innerHTML = ''; // delete any existing header
view.append(newHeader);
}
const setMainView = (view, width) => {
// configure body of view to look similar to tinymce body, adds ace editor
view.style.width = width+'px';
view.style.height = '100%';
view.style.position = 'relative';
buildAceEditor(view);
}
setConfig(editor);
initDependencies(Config);
const modalKeydownListener = (e) => {
if(e.key === 'Escape') {
hideModal();
}
};
const showModal = () => {
if(!modal){
// Build Modal
const modalContainer = document.createElement('div');
modalContainer.id = 'supercode-modal-container';
modalContainer.innerHTML = MODAL_HTML
injectCSS(MODAL_CSS);
document.body.append(modalContainer);
modal = {
element: modalContainer,
editor: ace.edit(modalContainer.querySelector('#supercode-editor'))
}
}
// transfer global editor in active scope (All methods work on local scope and need aceEditor)
aceEditor = modal.editor;
setAceOptions(); // update ace options according to current editor configs
/* Update Event Listeners */
modal.element.querySelector('#supercode-backdrop').onclick = hideModal;
modal.element.querySelector('#supercode-close-btn').onclick = hideModal;
modal.element.querySelector('#supercode-cancel-btn').onclick = hideModal;
modal.element.querySelector('#supercode-save-btn').onclick = () => {
onSaveHandler();
hideModal();
};
if(Config.shortcut){
modal.element.querySelector('#supercode-editor').addEventListener('keydown', modalKeydownListener);
}
modal.element.querySelector('#supercode-theme-dropdown').addEventListener('change', onThemeHandler);
/* Update Modal based on editor's theme */
document.querySelector('body').classList.add('disable-scroll');
document.body.style.setProperty('--supercode-modal-primary', Config.modalPrimaryColor);
document.body.style.setProperty('--supercode-modal-secondary', Config.modalSecondaryColor);
if(Config.dark){
document.body.style.setProperty('--supercode-modal-border', 'rgba(255, 255, 255, 0.1)');
}
modal.element.querySelector('#supercode-close-btn').innerHTML = editor.ui.registry.getAll?.().icons?.['close'] ?? CLOSE_ICON_FALLBACK;
modal.element.style.display = 'flex';
setTimeout(() => {
modal.element.style.opacity = 1;
}, 10)
/* Load current editor's ace session into aceEditor */
loadAceSession();
}
const hideModal = () => {
if(Config.shortcut){
removeEventListener('keydown', modalKeydownListener);
}
document.querySelector('body').classList.remove('disable-scroll');
modal.element.style.opacity = 0;
editor.focus();
setTimeout(() => {
modal.element.style.display = 'none';
}, 10)
};
const onSaveHandler = () => {
editor.focus();
editor.undoManager.transact(function() {
let value = aceEditor.getValue();
if(Config.renderer){
value = Config.renderer(value);
}
editor.setContent(value);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
editor.execCommand('ToggleView', false, 'supercode');
}
const onKeyDownHandler = (e) => {
if((e.key === ' ' && e.ctrlKey) || e.key === 'Escape'){
onSaveHandler();
}
};
const onThemeHandler = (e) => {
const selectedTheme = e.target.value;
aceEditor.setTheme(`ace/theme/${selectedTheme}`);
document.cookie = `supercodeTheme=${selectedTheme}; expires=Fri, 31 Dec 9999 23:59:59 GMT`;
};
const getSourceCode = (value) => {
if(Config.parser){
return Config.parser(value);
}
return html_beautify(value);
}
const loadAceSession = () => {
// Load or build new ace session from editor
let content = getSourceCode(editor.getContent());
if(!session){
session = ace.createEditSession(content, `ace/mode/${Config.language}`);
session.setUseWrapMode(Config.wrap);
}
aceEditor.setSession(session);
session.setValue(content);
aceEditor.gotoLine(Infinity);
aceEditor.focus();
}
const startPlugin = function() {
if(Config.fallbackModal){
showModal();
} else {
const container = editor.getContainer();
if(editorWidth){
isScreenSizeChanged = editorWidth != container.clientWidth;
}
editorWidth = container.clientWidth;
if(isScreenSizeChanged || !originalHeader){
originalHeader = container.querySelector('.tox-editor-header');
}
editor.execCommand('ToggleView', false, 'supercode');
}
}
if(!Config.fallbackModal){
const CodeView = {
onShow: (api) => {
const codeView = api.getContainer();
// On tinymce size change => resize code view
if(isScreenSizeChanged){
setHeader(codeView.querySelector('.supercode-header'), originalHeader);
codeView.querySelector('.supercode-body ').style.width = editorWidth+'px';
aceEditor.resize();
}
// Only on First time plugin opened => mount view
if(codeView.childElementCount === 0){
codeView.style.padding = 0;
codeView.style.display = 'flex';
codeView.style.flexDirection = 'column';
codeView.innerHTML = `<div class="supercode-header"></div><div class="supercode-body"></div>`
// Ctrl + Space Toggle Shortcut, Escape to Exit Source Code Mode
if(Config.shortcut){
codeView.addEventListener('keydown', onKeyDownHandler)
}
// configure header
setHeader(codeView.querySelector('.supercode-header'), originalHeader);
// configure main code view to look same
setMainView(codeView.querySelector('.supercode-body '), editorWidth);
}
loadAceSession();
},
onHide: () => {
if(Config.shortcut){
removeEventListener('keydown', onKeyDownHandler)
}
}
};
editor.ui.registry.addView('supercode', CodeView);
}
editor.ui.registry.addButton('supercode', {
icon: Config.iconName,
tooltip: 'Source Code Editor (Ctrl + space)',
onAction: startPlugin
});
editor.ui.registry.addMenuItem('supercode', {
icon: Config.iconName,
text: 'Source Code',
onAction: startPlugin
});
editor.ui.registry.addContextMenu('supercode', {
update: element => {
return 'supercode';
}
});
// Ctrl + Space Toggle Shortcut
if(Config.shortcut){
editor.shortcuts.add('ctrl+32', 'Toggles Source Code Editing Mode', startPlugin);
}
return {
getMetadata: function () {
return {
name: "Supercode",
url: "https://github.com/prathamVaidya/supercode-tinymce-plugin"
};
}
}
};
// On Script Load, the plugin will be loaded
tinymce.PluginManager.add('supercode', mainPlugin);
}();