forked from yeole-rohan/ray-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathray-editor.js
More file actions
1749 lines (1558 loc) · 66.6 KB
/
Copy pathray-editor.js
File metadata and controls
1749 lines (1558 loc) · 66.6 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
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
class RayEditor {
constructor(containerId, options = {}, contentId = null) {
this.contentId = contentId;
this.container = document.getElementById(containerId);
this.options = options;
this.toolbar = null;
this.editorArea = null;
this.imageUploadUrl = null
this.maxImageSize = null
this.init();
this.toolbarIndex = 0;
if(this.options.mentions.mentionTag == ""){
this.options.mentions.mentionTag = '@';
}
this.options.mentions.mentionTag = this.options.mentions.mentionTag || '@';
this.options.mentions.mentionTagUnescaped = this.options.mentions.mentionTag;
this.options.mentions.mentionTag = this.options.mentions.mentionTag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
this.overflowMode = false;
this.isSourceMode = false;
this.sourceTextarea = null;
}
init() {
this.#createToolbar();
this.#createEditorArea();
this.#bindEvents();
this.#addWatermark();
this.#includeCSS();
this.#setToolbarType();
this.#setDarkMode();
if (this.options.overflowMenu) {
const debouncedCheck = () => {
if (this.resizeTimeout) clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(() => {
const width = this.toolbar.offsetWidth;
if (width !== this.lastToolbarWidth) {
this.lastToolbarWidth = width;
this.#checkToolbarWidth();
}
}, 60);
};
this.resizeObserver = new ResizeObserver(debouncedCheck);
this.resizeObserver.observe(this.toolbar);
window.addEventListener('resize', debouncedCheck);
requestAnimationFrame(() => this.#checkToolbarWidth());
}
}
#createToolbar() {
if(this.contentId){
const contentElement = document.getElementById(this.contentId);
if (!contentElement) {
console.error(`Content element with ID "${this.contentId}" not found.`);
return;
}
this.container = contentElement.parentNode;
this.toolbar = document.createElement('div');
this.toolbar.className = 'ray-editor-toolbar';
this.container.insertBefore(this.toolbar, contentElement);
}else{
this.toolbar = document.createElement('div');
this.toolbar.className = 'ray-editor-toolbar';
this.container.appendChild(this.toolbar);
}
this.#generateToolbarButtons(buttonConfigs);
}
addEventListener(event, callback) {
if (!this.editorArea) {
console.error('Editor element not found');
return;
}
this.editorArea.addEventListener(event, callback);
}
destroy() {
return new Promise((resolve, reject) => {
try {
console.log('Destroying RayEditor instance');
if (this.editorArea) {
this.editorArea.setAttribute('contenteditable', 'false');
this.editorArea.removeEventListener('keyup', this.#updateToolbar);
this.editorArea.classList.remove('ray-editor-content');
}
if (this.toolbar) {
this.toolbar.remove();
this.toolbar = null;
}
resolve();
} catch (err) {
reject(err);
}
});
}
then(callback) {
return Promise.resolve(this).then(callback);
}
// Method to get the content from the editor
getRayEditorContent() {
if (!this.editorArea) {
console.error('Editor element not found');
return null;
}
const tempDiv = document.createElement('div');
tempDiv.innerHTML = this.editorArea.innerHTML;
const tagsToClean = ['p', 'a', 'span', 'b', 'i', 'u', 'strong', 'em'];
// Helper to check if an element is inside a code block
const isInsideCodeBlock = el => {
return el.closest('pre, code, .ray-code-block') !== null;
};
// Helper function to remove <p> inside <ul>, <ol>, or <li> and keep the text content
const removePInsideList = () => {
const listItems = tempDiv.querySelectorAll('ul li, ol li');
listItems.forEach(li => {
if (isInsideCodeBlock(li)) return;
const p = li.querySelector('p');
if (p) {
// Move text content of <p> to the <li> and remove the <p>
li.innerHTML = li.innerHTML.replace(p.outerHTML, p.textContent);
}
});
};
// Call the function to handle <p> inside <ul>, <ol>, <li>
removePInsideList();
// Recursive cleaner: removes <br> and empty inline children, then checks text
const isEffectivelyEmpty = el => {
if (isInsideCodeBlock(el)) return;
// Remove empty inline children
tagsToClean.forEach(tag => {
el.querySelectorAll(tag).forEach(child => {
if (isInsideCodeBlock(child)) return;
if (!child.textContent.trim() && child.children.length === 0) {
child.remove();
}
});
});
// Finally, check if this element is still empty
return !el.textContent.trim() && el.children.length === 0;
};
// Walk backwards so we can safely remove elements without disrupting traversal
const allTargets = Array.from(tempDiv.querySelectorAll(tagsToClean.join(','))).reverse();
allTargets.forEach(el => {
if (isInsideCodeBlock(el)) return;
if (isEffectivelyEmpty(el)) {
el.remove();
}
});
// Select all div elements without a class and replace them with <p> tags
const divsWithoutClass = tempDiv.querySelectorAll('div:not([class])');
divsWithoutClass.forEach(div => {
if (isInsideCodeBlock(div)) return;
const p = document.createElement('p');
p.innerHTML = div.innerHTML; // Copy content to <p>
div.parentNode.replaceChild(p, div); // Replace <div> with <p>
});
tempDiv.querySelectorAll('.ray-code-content').forEach(pre => {
pre.setAttribute('contenteditable', 'false');
});
return tempDiv.innerHTML;
}
setRayEditorContent(html) {
if (!this.editorArea) {
console.error('Editor element not found');
return null;
}
// Parse string HTML into a temporary DOM
const temp = document.createElement('div');
temp.innerHTML = html;
// Modify code blocks
temp.querySelectorAll('.ray-code-content').forEach(pre => {
pre.setAttribute('contenteditable', 'true');
pre.setAttribute('spellcheck', 'false');
});
// Set the updated HTML content into the editor
this.editorArea.innerHTML = temp.innerHTML;
temp.remove()
}
#createEditorArea() {
if(this.contentId){
const contentElement = document.getElementById(this.contentId);
if (!contentElement) {
console.error(`Content element with ID "${this.contentId}" not found.`);
return;
}
this.editorArea = document.createElement('div');
this.editorArea.className = 'ray-editor-content';
for (let attr of contentElement.attributes) {
if (attr.name === 'class') {
this.editorArea.className += ' ' + attr.value;
} else if (attr.name !== 'id') {
this.editorArea.setAttribute(attr.name, attr.value);
}
}
if (contentElement.id) {
this.editorArea.id = contentElement.id;
}
this.editorArea.contentEditable = true;
this.editorArea.spellcheck = true;
if (contentElement.tagName === 'TEXTAREA') {
this.editorArea.innerHTML = contentElement.value || '<p><br></p>';
} else {
this.editorArea.innerHTML = contentElement.innerHTML || '<p><br></p>';
}
contentElement.parentNode.replaceChild(this.editorArea, contentElement);
} else {
this.editorArea = document.createElement('div');
this.editorArea.className = 'ray-editor-content';
this.editorArea.contentEditable = true;
this.editorArea.spellcheck = true;
this.editorArea.innerHTML = '<p><br></p>';
this.container.appendChild(this.editorArea);
}
}
#addWatermark() {
if (!this.editorArea || this.options.hideWatermark) return;
const watermark = document.createElement('div');
watermark.id = 'ray-editor-watermark';
watermark.innerHTML = `Made with ❤️ by <a href="https://rohanyeole.com" target="_blank" rel="noopener">Rohan Yeole</a>`;
// Insert after the editor
this.editorArea.parentNode.insertBefore(watermark, this.editorArea.nextSibling);
}
#generateToolbarButtons(buttonConfigs) {
// for (const key in this.options) {
Object.keys(buttonConfigs).forEach((key) => {
// Check if this key is enabled in userOptions
if (!this.options[key]) return;
if (this.options[key].imageUploadUrl && this.options[key].imageMaxSize) {
this.imageUploadUrl = this.options[key].imageUploadUrl
this.maxImageSize = this.options[key].imageMaxSize
}
if (this.options[key].fileUploadUrl && this.options[key].fileMaxSize) {
this.fileUploadUrl = this.options[key].fileUploadUrl
this.fileMaxSize = this.options[key].fileMaxSize
}
const config = buttonConfigs[key];
if (config.dropdown && config.options) {
this.#createDropdown(config);
} else {
this.#createButton(config);
}
});
}
#createDropdown(config) {
const select = document.createElement('select');
select.className = `ray-dropdown ray-dropdown-${config.keyname}`;
select.title = config.keyname.charAt(0).toUpperCase() + config.keyname.slice(1);
Object.entries(config.options).forEach(([key, opt]) => {
const option = document.createElement('option');
option.value = opt.value;
option.textContent = opt.label;
select.appendChild(option);
});
select.addEventListener('change', () => {
const selected = config.options[select.selectedOptions[0].textContent.toLowerCase().replace(/\s/g, '')];
if (selected?.cmd) {
this.#execCommand(selected.cmd, selected.value);
}
});
this.toolbar.appendChild(select);
}
#createButton(config) {
const btn = document.createElement('button');
btn.type = 'button';
btn.id = `ray-btn-${config.keyname}`;
const formattedTitle = config.keyname.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
btn.title = formattedTitle;
btn.setAttribute('data-tooltip', formattedTitle);
btn.innerHTML = config.label;
btn.className = `ray-btn ray-btn-${config.keyname}`;
btn.addEventListener('click', () => {
if (config.cmd) {
this.#execCommand(config.cmd, config.value || null);
} else if (config.keyname === 'uppercase') {
this.#transformSelectedText('upper');
} else if (config.keyname === 'lowercase') {
this.#transformSelectedText('lower');
} else if (config.keyname === 'toggleCase') {
this.#toggleTextCase();
} else if (config.keyname === 'codeBlock') {
this.#insertCodeBlock()
} else if (config.keyname === 'codeInline') {
this.#insertInlineCode()
} else if (config.keyname === 'backgroundColor') {
this.#applyBackgroundColor()
} else if (config.keyname === 'textColor') {
this.#applyTextColor()
} else if (config.keyname === 'imageUpload') {
this.#triggerImageUpload()
} else if (config.keyname === 'fileUpload') {
this.#triggerFileUpload()
} else if (config.keyname === 'link') {
this.#openLinkModal()
} else if (config.keyname === 'removeFormat') {
this.#execCommand('removeFormat')
} else if (config.keyname === 'table') {
this.#openTableModal();
} else if (config.keyname === 'showSource') {
this.#toggleSourceMode();
}
});
this.toolbar.appendChild(btn);
}
#execCommand(command, value = null) {
document.execCommand(command, false, value);
this.editorArea.focus();
this.#updateToolbar();
}
#bindEvents() {
const events = ['keyup', 'mouseup', 'keydown', 'paste', 'click'];
events.forEach(evt => {
this.editorArea.addEventListener(evt, (e) => {
const sel = window.getSelection();
if (!sel.rangeCount) return;
const node = sel.anchorNode;
const elementNode = node.nodeType === 3 ? node.parentElement : node;
this.#updateToolbar()
if (evt === 'keydown') {
this.#handleCodeBlockExit(e, elementNode);
this.#handleInlineCodeExit(e, sel, elementNode);
}
if (evt === 'keyup'){
const mentionRegex = new RegExp('(?:^|\\s)(' + this.options.mentions.mentionTag + '\\w+)', 'g');
const text = elementNode.textContent;
const match = mentionRegex.exec(text);
if (match) {
const mention = match[1];
if (e.key == ' ' || e.key == 'Enter') {
this.#handleMention(mention);
}
}
}
if (evt === 'paste') {
this.#handleYoutubeEmbed(e);
}
if (evt === 'click') {
const anchor = e.target.closest('a');
if (anchor && this.editorArea.contains(anchor)) {
e.preventDefault();
this.#showLinkPopup(anchor);
}
}
// Check if the clicked element is not a table or not inside a table
const table = e.target.closest('table');
// If the click is outside any table, remove highlight from all tables
if (!table) {
// Remove highlight from all tables
document.querySelectorAll('table').forEach(t => {
t.classList.remove('ray-editor-table-highlighted');
});
}
});
});
}
#showLinkPopup(anchor) {
// Remove existing popup if any
const existingPopup = document.querySelector('.ray-editor-link-edit-remove');
if (existingPopup) existingPopup.remove();
// Create popup element
const popup = document.createElement('div');
popup.className = 'ray-editor-link-edit-remove';
popup.innerHTML = `
<button class="edit-link">Edit</button>
<button class="remove-link">Remove</button>
`;
document.body.appendChild(popup);
// Position the popup near the anchor
const rect = anchor.getBoundingClientRect();
popup.style.top = `${rect.bottom + window.scrollY}px`;
popup.style.left = `${rect.left + window.scrollX}px`;
// Handle edit and remove actions
popup.querySelector('.edit-link').addEventListener('click', () => {
this.#openLinkModal(anchor);
popup.remove();
});
popup.querySelector('.remove-link').addEventListener('click', () => {
this.#removeLink(anchor);
popup.remove();
});
// Remove popup when clicking outside
document.addEventListener('click', function onDocClick(e) {
if (!popup.contains(e.target) && e.target !== anchor) {
popup.remove();
document.removeEventListener('click', onDocClick);
}
});
}
#handleCodeBlockExit(e, elementNode) {
if (e.key !== 'Enter' || e.shiftKey) return;
const codeContent = elementNode.closest('.ray-code-content');
if (!codeContent) return;
const text = codeContent.innerText.trim();
if (text === '') {
e.preventDefault();
codeContent.innerHTML = '';
const newPara = document.createElement('p');
newPara.innerHTML = '<br>';
const codeBlock = codeContent.closest('.ray-code-block');
if (codeBlock) {
codeBlock.parentNode.insertBefore(newPara, codeBlock.nextSibling);
const range = document.createRange();
range.selectNodeContents(newPara);
range.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else {
codeContent.dataset.lastEmptyEnter = 'true';
setTimeout(() => delete codeContent.dataset.lastEmptyEnter, 500);
}
}
#handleInlineCodeExit(e, sel, elementNode) {
if (e.key !== 'ArrowRight') return;
const inlineCode = elementNode.closest('code');
if (!inlineCode || !sel.isCollapsed) return;
const range = sel.getRangeAt(0);
const atEnd = range.endOffset === inlineCode.textContent.length;
if (atEnd) {
e.preventDefault();
const spacer = document.createTextNode('\u00A0');
inlineCode.parentNode.insertBefore(spacer, inlineCode.nextSibling);
const newRange = document.createRange();
newRange.setStartAfter(spacer);
newRange.collapse(true);
sel.removeAllRanges();
sel.addRange(newRange);
}
}
#handleYoutubeEmbed(e) {
const clipboard = e.clipboardData || window.clipboardData;
const pastedText = clipboard.getData('text');
const ytRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w-]{11})/;
const match = pastedText.match(ytRegex);
if (!match) return;
e.preventDefault();
const videoId = match[1];
const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube.com/embed/${videoId}`;
iframe.width = '560';
iframe.height = '315';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
iframe.className = 'ray-youtube-embed';
const range = window.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(iframe);
}
#applyTextTransformation(transformFn) {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
const selectedText = range.toString();
if (!selectedText.trim()) return;
const transformed = transformFn(selectedText);
range.deleteContents();
range.insertNode(document.createTextNode(transformed));
// Reset selection to after inserted text
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
#transformSelectedText(mode) {
this.#applyTextTransformation((text) =>
mode === 'upper' ? text.toUpperCase() : text.toLowerCase()
);
}
#toggleTextCase() {
this.#applyTextTransformation((text) =>
[...text].map(char =>
char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()
).join('')
);
}
#insertCodeBlock() {
const selection = window.getSelection();
if (!selection.rangeCount) return;
if (!this.editorArea.contains(selection.anchorNode)) return;
const range = selection.getRangeAt(0);
// Create wrapper div
const wrapper = document.createElement('div');
wrapper.className = 'ray-code-block';
// Create <pre><code> structure
const pre = document.createElement('pre');
pre.className = 'ray-code-content';
pre.setAttribute('contenteditable', 'true');
pre.setAttribute('spellcheck', 'false')
const code = document.createElement('code');
code.innerHTML = '<br>';
// Assemble
pre.appendChild(code);
wrapper.appendChild(pre);
// Insert into DOM
range.deleteContents();
range.insertNode(wrapper);
// Place cursor inside <code>
setTimeout(() => {
const newRange = document.createRange();
newRange.selectNodeContents(code);
newRange.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(newRange);
}, 0);
}
#insertInlineCode() {
const selection = window.getSelection();
if (!selection.rangeCount || selection.isCollapsed) return;
const range = selection.getRangeAt(0);
const selectedText = range.toString();
const parentCode = this.#getSelectedElementInTag('code');
if (parentCode) {
// Already in code → unwrap it
const parent = parentCode.parentNode;
while (parentCode.firstChild) {
parent.insertBefore(parentCode.firstChild, parentCode);
}
parent.removeChild(parentCode);
} else {
// Wrap selection in <code>
const code = document.createElement('code');
code.textContent = selectedText;
range.deleteContents();
range.insertNode(code);
// Reselect inserted content
const newRange = document.createRange();
newRange.selectNodeContents(code);
selection.removeAllRanges();
selection.addRange(newRange);
}
}
#getSelectedElementInTag(tagName) {
const sel = window.getSelection();
if (!sel.rangeCount) return null;
let node = sel.anchorNode;
while (node && node !== document) {
if (node.nodeType === 1 && node.tagName.toLowerCase() === tagName.toLowerCase()) {
return node;
}
node = node.parentNode;
}
return null;
}
#applyTextColor() {
const input = document.createElement("input");
input.type = "color";
input.value = "#000000";
input.style.position = "absolute";
input.style.left = "-9999px"; // keep it hidden from view
document.body.appendChild(input);
input.oninput = () => {
const color = input.value;
this.#execCommand("foreColor", color)
input.remove(); // Clean up
};
input.click();
}
#applyBackgroundColor() {
const input = document.createElement("input");
input.type = "color";
input.value = "#ffffff";
input.style.position = "absolute";
input.style.left = "-9999px";
document.body.appendChild(input);
input.oninput = () => {
const color = input.value;
this.#execCommand("backColor", color)
input.remove();
};
input.click();
}
#triggerImageUpload() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
input.addEventListener('change', () => {
const image = input.files[0];
if (!image) return;
if (!image.type.startsWith('image/')) {
alert('Only images are allowed.');
return;
}
if (!this.maxImageSize || typeof this.maxImageSize !== 'number') {
alert('❌ Configuration error: maxImageSize must be provided in bytes as a number.');
return;
}
if (image.size > this.maxImageSize) {
alert(`Image size must be under ${this.maxImageSize / (1024 * 1024)}MB.`);
return;
}
this.#handleImageUpload(image);
});
document.body.appendChild(input);
input.click();
document.body.removeChild(input);
}
#handleImageUpload(image) {
if (!this.imageUploadUrl) {
console.error('Upload URL is not configured.');
return;
}
const formData = new FormData();
formData.append('file', image);
const placeholder = this.#insertUploadPlaceholder(image.name);
fetch(this.imageUploadUrl, {
method: 'POST',
body: formData
})
.then(res => {
if (!res.ok) throw new Error(`Upload failed with status ${res.status}`);
return res.json();
})
.then(data => {
const imageUrl = data.url;
if (!imageUrl) throw new Error('No image URL returned from server.');
this.#replacePlaceholderWithImage(placeholder, imageUrl, image.name);
})
.catch(err => {
console.error('Image upload failed:', err);
this.#showUploadErrorWithRemove(placeholder, image.name);
});
}
#insertUploadPlaceholder(filename) {
const placeholder = document.createElement('div');
placeholder.className = 'upload-placeholder';
placeholder.textContent = `Uploading ${filename}...`;
this.editorArea.appendChild(placeholder);
return placeholder;
}
#replacePlaceholderWithImage(placeholder, imageUrl, imageName) {
const img = document.createElement('img');
img.src = imageUrl;
img.alt = imageName;
img.title = imageName;
// Set width and height once the image is fully loaded
img.onload = () => {
// Create resizable image and get both wrapper and editable line
const { wrapper } = this.#makeImageResizable(img);
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
// Replace range with the resizable image wrapper
placeholder.remove()
range.insertNode(wrapper);
// Move the cursor *after* the inserted wrapper
range.setStartAfter(wrapper);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
#showUploadErrorWithRemove(placeholder, imagename) {
placeholder.innerHTML = `❌ Failed to upload "${imagename}"`;
const removeBtn = document.createElement('button');
removeBtn.textContent = 'Remove';
removeBtn.style.marginLeft = '10px';
removeBtn.style.background = 'transparent';
removeBtn.style.border = 'none';
removeBtn.style.color = '#d00';
removeBtn.style.cursor = 'pointer';
removeBtn.onclick = () => placeholder.remove();
placeholder.appendChild(removeBtn);
}
#makeImageResizable(img) {
const wrapper = document.createElement('div');
wrapper.style.position = 'relative';
wrapper.style.display = 'inline-block';
wrapper.contentEditable = false;
// Style image for better UX
img.style.maxWidth = '100%';
img.style.display = 'block';
img.style.cursor = 'move';
img.style.borderRadius = '4px';
img.style.transition = 'box-shadow 0.2s ease';
wrapper.appendChild(img);
// Resize handle (visual indicator for dragging)
const handle = document.createElement('div');
handle.style.position = 'absolute';
handle.style.width = '10px';
handle.style.height = '10px';
handle.style.right = '0';
handle.style.bottom = '0';
handle.style.cursor = 'se-resize';
handle.style.background = 'hsl(220, 100%, 60%)';
handle.style.border = '1px solid white';
handle.style.borderRadius = '2px';
handle.style.opacity = '0'; // Start hidden
handle.style.transition = 'opacity 0.2s ease';
wrapper.appendChild(handle);
// Close Button (Top-Right)
const closeBtn = document.createElement('div');
closeBtn.innerHTML = '×';
closeBtn.style.position = 'absolute';
closeBtn.style.top = '0';
closeBtn.style.right = '0';
closeBtn.style.cursor = 'pointer';
closeBtn.style.background = 'hsla(0, 0%, 0%, 0.7)';
closeBtn.style.color = 'white';
closeBtn.style.width = '20px';
closeBtn.style.height = '20px';
closeBtn.style.borderRadius = '0 0 0 4px';
closeBtn.style.display = 'flex';
closeBtn.style.justifyContent = 'center';
closeBtn.style.alignItems = 'center';
closeBtn.style.opacity = '0';
closeBtn.style.transition = 'opacity 0.2s ease';
// Show/hide close button on hover/focus
wrapper.addEventListener('mouseenter', () => closeBtn.style.opacity = '1');
wrapper.addEventListener('mouseleave', () => closeBtn.style.opacity = '0');
// Delete on click
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
wrapper.remove(); // Remove entire resizable wrapper + image
});
wrapper.appendChild(closeBtn);
// Add subtle border when image is active
wrapper.addEventListener('click', (e) => {
e.stopPropagation();
img.style.boxShadow = '0 0 0 2px hsl(220, 100%, 60%)'; // Blue focus ring
handle.style.opacity = '1'; // Show handle
// Hide handle when clicking elsewhere
setTimeout(() => {
const clickOutsideHandler = () => {
handle.style.opacity = '0';
img.style.boxShadow = 'none';
document.removeEventListener('click', clickOutsideHandler);
};
document.addEventListener('click', clickOutsideHandler);
}, 0);
});
// Resize logic (with aspect ratio lock)
let startX, startY, startWidth, startHeight;
// **Modified resizing logic (constrains aspect ratio)**
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
startX = e.clientX;
startY = e.clientY;
startWidth = img.clientWidth;
startHeight = img.clientHeight;
img.style.boxShadow = '0 0 0 2px hsl(120, 100%, 25%)'; // Green during resize
const doDrag = (e) => {
const newWidth = startWidth + (e.clientX - startX);
const newHeight = startHeight + (e.clientY - startY);
img.style.width = `${Math.max(50, newWidth)}px`; // Min 50px
img.style.height = `${Math.max(50, newHeight)}px`;
};
function stopDrag() {
img.style.boxShadow = '0 0 0 2px hsl(220, 100%, 60%)'; // Revert to blue
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', stopDrag);
}
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', stopDrag);
});
// **Return BOTH the wrapper AND the new line for proper insertion**
return {
wrapper,
};
}
#triggerFileUpload() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '*/*';
input.style.display = 'none';
input.addEventListener('change', () => {
const file = input.files[0];
if (!file) return;
// Reject images here — we already handle those elsewhere
if (file.type.startsWith('image/')) {
alert('Use the image button for image uploads.');
return;
}
if (!this.fileMaxSize || typeof this.fileMaxSize !== 'number') {
alert('❌ Configuration error: fileMaxSize must be provided in bytes as a number.');
return;
}
if (file.size > this.fileMaxSize) {
alert(`File size must be under ${this.fileMaxSize / (1024 * 1024)}MB.`);
return;
}
this.#handleFileUpload(file);
});
document.body.appendChild(input);
input.click();
document.body.removeChild(input);
}
#handleFileUpload(file) {
if (!this.fileUploadUrl) {
console.error('No file upload URL configured.');
return;
}
const formData = new FormData();
formData.append('file', file);
const placeholder = this.#insertUploadPlaceholder(file.name);
fetch(this.fileUploadUrl, {
method: 'POST',
body: formData
})
.then(res => {
if (!res.ok) throw new Error(`Status ${res.status}`);
return res.json();
})
.then(data => {
const fileUrl = data.url;
if (!fileUrl) throw new Error('No file URL returned.');
this.#replacePlaceholderWithFileLink(placeholder, file.name, fileUrl);
})
.catch(err => {
console.error('File upload failed:', err);
this.#showUploadErrorWithRemove(placeholder, file.name);
});
}
#replacePlaceholderWithFileLink(placeholder, filename, url) {
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.download = filename;
link.textContent = `📄 ${filename}`;
link.style.textDecoration = 'underline';
link.style.color = '#0366d6';
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
range.deleteContents(); // Optional: clear selected content
// Insert the link
range.insertNode(link);
// Move the cursor after the inserted link
range.setStartAfter(link);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
// insert a space or newline after the link
const spacer = document.createTextNode(' ');
link.after(spacer);
placeholder.remove()
}
// save the current selection
#saveSelection() {
if (window.getSelection) {
const sel = window.getSelection();
if (sel.rangeCount > 0) {
return sel.getRangeAt(0);
}
}
return null;
}
// to restore a saved selection
#restoreSelection(range) {
if (range && window.getSelection) {
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
// to open the link insertion modal
#openLinkModal(anchor = null) {
const savedRange = this.#saveSelection();
// Create modal elements
const modal = document.createElement('div');
modal.className = 'ray-editor-link-modal';
modal.innerHTML = `
<div class="modal-content">
<label>URL: <input type="text" id="link-url" /></label>
<label>Target:
<select id="link-target">
<option value="_self">Same Tab</option>
<option value="_blank">New Tab</option>
</select>
</label>
<label>Rel:
<select id="link-rel">
<option value="">Follow</option>
<option value="nofollow">No Follow</option>
</select>
</label>
<div class="modal-actions">
<button id="insert-link">Insert Link</button>
<button id="cancel-link">Cancel</button>
</div>
</div>
`;