-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdated-html-editor.html
More file actions
1670 lines (1421 loc) · 54 KB
/
updated-html-editor.html
File metadata and controls
1670 lines (1421 loc) · 54 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offline HTML5 Editor</title>
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 1.6;
color: #333;
background-color: #f5f5f5;
height: 100vh;
display: flex;
flex-direction: column;
}
/* Header styles */
header {
background-color: #3b82f6;
color: white;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header-content {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 1400px;
margin: 0 auto;
width: 100%;
}
h1 {
font-size: 1.5rem;
font-weight: bold;
}
/* Button styles */
button {
background-color: #2563eb;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 0.25rem;
cursor: pointer;
font-size: 0.875rem;
transition: background-color 0.2s;
}
button:hover {
background-color: #1d4ed8;
}
.button-group {
display: flex;
gap: 0.5rem;
}
/* Toolbar styles */
.toolbar {
background-color: #e5e7eb;
padding: 0.5rem 1rem;
border-bottom: 1px solid #d1d5db;
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.file-info {
display: flex;
align-items: center;
gap: 0.5rem;
}
.unsaved {
color: #ef4444;
}
.font-size-control {
display: flex;
align-items: center;
gap: 0.25rem;
}
.font-button {
padding: 0.25rem 0.5rem;
background-color: #d1d5db;
}
.font-button:hover {
background-color: #9ca3af;
}
/* Main editor area */
.editor-container {
display: flex;
flex: 1;
overflow: hidden;
}
.source-container {
height: 100%;
padding: 0.5rem;
transition: width 0.3s;
}
.preview-container {
height: 100%;
padding: 0.5rem;
border-left: 1px solid #d1d5db;
transition: width 0.3s;
}
textarea {
width: 100%;
height: 100%;
padding: 0.5rem;
font-family: monospace;
border: 1px solid #d1d5db;
border-radius: 0.25rem;
resize: none;
outline: none;
}
textarea:focus {
border-color: #3b82f6;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.25rem 0.5rem;
background-color: #f3f4f6;
border: 1px solid #d1d5db;
border-bottom: none;
border-top-left-radius: 0.25rem;
border-top-right-radius: 0.25rem;
}
.preview-frame {
width: 100%;
height: calc(100% - 30px);
background-color: white;
border: 1px solid #d1d5db;
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
}
.small-button {
font-size: 0.75rem;
padding: 0.25rem 0.5rem;
}
/* Status bar */
.status-bar {
background-color: #e5e7eb;
padding: 0.5rem 1rem;
border-top: 1px solid #d1d5db;
font-size: 0.75rem;
color: #6b7280;
}
.status-content {
display: flex;
justify-content: space-between;
max-width: 1400px;
margin: 0 auto;
width: 100%;
}
/* File input styling */
.file-input {
display: none;
}
/* Utility */
.hidden {
display: none;
}
/* Find and Replace Modal */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal.active {
display: flex;
}
.modal-content {
background-color: white;
padding: 1.5rem;
border-radius: 0.5rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
min-width: 400px;
max-width: 500px;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid #e5e7eb;
}
.modal-header h2 {
font-size: 1.25rem;
margin: 0;
}
.close-btn {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #6b7280;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
.close-btn:hover {
background-color: #f3f4f6;
border-radius: 0.25rem;
}
.modal-body {
display: flex;
flex-direction: column;
gap: 1rem;
}
.input-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.input-group label {
font-size: 0.875rem;
font-weight: 500;
color: #374151;
}
.input-group input {
padding: 0.5rem;
border: 1px solid #d1d5db;
border-radius: 0.25rem;
font-size: 0.875rem;
}
.input-group input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}
.checkbox-group {
display: flex;
align-items: center;
gap: 0.5rem;
}
.checkbox-group input[type="checkbox"] {
cursor: pointer;
}
.checkbox-group label {
cursor: pointer;
font-size: 0.875rem;
}
.modal-footer {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid #e5e7eb;
}
.modal-footer button {
flex: 1;
}
.replace-stats {
font-size: 0.875rem;
color: #6b7280;
margin-top: 0.5rem;
}
</style>
</head>
<body>
<!-- Header -->
<header>
<div class="header-content">
<h1>Offline HTML5 Editor</h1>
<div class="button-group">
<button id="newBtn">New</button>
<label for="openFile" class="button" id="openBtn">
Open
<input type="file" id="openFile" class="file-input" accept=".html,.htm">
</label>
<button id="saveBtn">Save</button>
</div>
</div>
</header>
<!-- Toolbar -->
<div class="toolbar">
<div class="file-info">
<span id="fileName">untitled.html</span>
<span id="saveStatus" class="unsaved hidden">(unsaved)</span>
</div>
<button id="cleanBtn">Clean HTML</button>
<button id="formatBtn">Format HTML</button>
<button id="convertEntitiesBtn">Convert Entities</button>
<button id="formatBreaksBtn">Format Line Breaks</button>
<button id="capitalizeAcronymsBtn">CAPITALIZE Acronyms</button>
<button id="undoCapsBtn" title="Undo last acronym capitalization">Undo Caps</button>
<button id="wrapQuotesBtn">❝ Wrap Quotes ❞</button>
<button id="copyTextBtn">Copy All Text</button>
<button id="findReplaceBtn">Find & Replace</button>
<div class="button-group" style="border-left: 2px solid #9ca3af; padding-left: 1rem;">
<button id="sentenceCaseBtn" title="Convert selection to Sentence case">Sentence case</button>
<button id="lowerCaseBtn" title="Convert selection to lowercase">lowercase</button>
<button id="upperCaseBtn" title="Convert selection to UPPERCASE">UPPERCASE</button>
<button id="titleCaseBtn" title="Convert selection to Title Case">Title Case</button>
</div>
<div class="font-size-control">
<button class="font-button" id="fontDecrease">-</button>
<span>Font</span>
<button class="font-button" id="fontIncrease">+</button>
</div>
<button id="togglePreviewBtn">Hide Preview</button>
<div style="margin-left: auto; display: flex; align-items: center; gap: 0.5rem;">
<input type="url" id="shareUrl" placeholder="Paste article URL here" style="padding: 0.4rem; border: 1px solid #d1d5db; border-radius: 0.25rem;">
<button id="shareBtn" title="Share the URL on Facebook">Share on FB</button>
<button id="archiveBtn" title="Open a clean, archived version of the URL">Open Archive</button>
<button id="summaryBtn" title="Open summary link">Summary</button>
</div>
</div>
<!-- Main editor -->
<div class="editor-container">
<div class="source-container" id="sourceContainer" style="width: 50%;">
<textarea id="htmlSource" spellcheck="false"></textarea>
</div>
<div class="preview-container" id="previewContainer" style="width: 50%;">
<div class="preview-header">
<span>Preview (Always Editable)</span>
</div>
<iframe id="previewFrame" class="preview-frame" sandbox="allow-same-origin"></iframe>
</div>
</div>
<!-- Status bar -->
<div class="status-bar">
<div class="status-content">
<div id="charCount">Characters: 0</div>
<div id="wordCount">Words: 0</div>
<div id="lineCount">Lines: 0</div>
<div>Keyboard shortcuts: Ctrl+S (Save), Ctrl+N (New), Ctrl+F (Find & Replace)</div>
</div>
</div>
<!-- Find and Replace Modal -->
<div id="findReplaceModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2>Find and Replace</h2>
<button class="close-btn" id="closeFindReplace">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<label for="findInput">Find:</label>
<input type="text" id="findInput" placeholder="Enter text to find">
</div>
<div class="input-group">
<label for="replaceInput">Replace with:</label>
<input type="text" id="replaceInput" placeholder="Enter replacement text">
</div>
<div class="checkbox-group">
<input type="checkbox" id="caseSensitive">
<label for="caseSensitive">Case sensitive</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="useRegex">
<label for="useRegex">Use regular expression</label>
</div>
<div class="replace-stats" id="replaceStats"></div>
</div>
<div class="modal-footer">
<button id="findNextBtn">Find Next</button>
<button id="replaceBtn">Replace</button>
<button id="replaceAllBtn">Replace All</button>
</div>
</div>
</div>
<!-- JavaScript - ALL JS CODE MUST BE WITHIN THESE SCRIPT TAGS -->
<script>
// DOM Elements
const htmlSource = document.getElementById('htmlSource');
const previewFrame = document.getElementById('previewFrame');
const sourceContainer = document.getElementById('sourceContainer');
const previewContainer = document.getElementById('previewContainer');
const togglePreviewBtn = document.getElementById('togglePreviewBtn');
const newBtn = document.getElementById('newBtn');
const openFile = document.getElementById('openFile');
const saveBtn = document.getElementById('saveBtn');
const summaryBtn = document.getElementById('summaryBtn');
const cleanBtn = document.getElementById('cleanBtn');
const formatBtn = document.getElementById('formatBtn');
const convertEntitiesBtn = document.getElementById('convertEntitiesBtn');
const formatBreaksBtn = document.getElementById('formatBreaksBtn');
const wrapQuotesBtn = document.getElementById('wrapQuotesBtn');
const copyTextBtn = document.getElementById('copyTextBtn');
const capitalizeAcronymsBtn = document.getElementById('capitalizeAcronymsBtn');
const fontIncrease = document.getElementById('fontIncrease');
const fontDecrease = document.getElementById('fontDecrease');
const fileName = document.getElementById('fileName');
const saveStatus = document.getElementById('saveStatus');
const charCount = document.getElementById('charCount');
const wordCount = document.getElementById('wordCount');
const lineCount = document.getElementById('lineCount');
const shareUrl = document.getElementById('shareUrl');
const shareBtn = document.getElementById('shareBtn');
const archiveBtn = document.getElementById('archiveBtn');
const sentenceCaseBtn = document.getElementById('sentenceCaseBtn');
const lowerCaseBtn = document.getElementById('lowerCaseBtn');
const upperCaseBtn = document.getElementById('upperCaseBtn');
const titleCaseBtn = document.getElementById('titleCaseBtn');
const undoCapsBtn = document.getElementById('undoCapsBtn');
const findReplaceBtn = document.getElementById('findReplaceBtn');
const findReplaceModal = document.getElementById('findReplaceModal');
const closeFindReplace = document.getElementById('closeFindReplace');
const findInput = document.getElementById('findInput');
const replaceInput = document.getElementById('replaceInput');
const caseSensitive = document.getElementById('caseSensitive');
const useRegex = document.getElementById('useRegex');
const findNextBtn = document.getElementById('findNextBtn');
const replaceBtn = document.getElementById('replaceBtn');
const replaceAllBtn = document.getElementById('replaceAllBtn');
const replaceStats = document.getElementById('replaceStats');
// Inline elements that should preserve spacing when normalized
const inlineElements = new Set([
'a', 'abbr', 'acronym', 'b', 'bdo', 'cite', 'code', 'dfn', 'em', 'i', 'kbd',
'mark', 'q', 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time',
'u', 'var', 'button', 'label', 'input', 'textarea', 'select', 'img', 'svg',
'path', 'use'
]);
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
const noiseLinePatterns = [
/^\s*sign up here\.?\s*$/i,
/^\s*sign up (?:for|to)\s+(?:our\s+)?(?:free\s+)?(?:daily\s+)?[a-z\s]*newsletter[s]?(?:\s+alerts?)?\.?\s*$/i,
/^\s*subscribe (?:here|now)\.?$/i
];
const shortCtaLeadPattern = /^(sign up|subscribe|register|sign in)\b/i;
const shortCtaContextPattern = /(newsletter|updates|alerts|here|now)/i;
const dividerLinePattern = /^\s*[_\-–=•*]{3,}\s*$/;
const externalLinkIconsRegex = /[\u2197\u2196\u2198\u2199\u{1F517}]/gu;
const reutersTickerRegex = /\s*\(\s*[A-Za-z0-9][A-Za-z0-9._-]{1,12}\.[A-Za-z]{1,5}[A-Za-z0-9._-]*\s*\)(?=[\s,.;:!?)]|$)/g;
// State variables
let currentFileName = 'untitled.html';
let isSaved = true;
let fontSize = 14;
let showPreview = true;
let isUpdatingSource = false; // Flag to prevent circular updates
let lastCapitalizedContent = null;
let currentSearchIndex = -1;
let searchMatches = [];
// Initialize editor
function initEditor() {
// Set initial content
htmlSource.value = '';
updatePreview();
updateStatusBar();
htmlSource.style.fontSize = `${fontSize}px`;
// Add event listeners
htmlSource.addEventListener('input', () => {
lastCapitalizedContent = null;
updatePreview();
updateStatusBar();
setUnsaved();
});
togglePreviewBtn.addEventListener('click', togglePreview);
newBtn.addEventListener('click', newDocument);
openFile.addEventListener('change', loadHTML);
saveBtn.addEventListener('click', saveHTML);
summaryBtn.addEventListener('click', openSummary);
cleanBtn.addEventListener('click', cleanHTML);
formatBtn.addEventListener('click', formatHTML);
convertEntitiesBtn.addEventListener('click', convertEntities);
formatBreaksBtn.addEventListener('click', formatTextBreaks);
wrapQuotesBtn.addEventListener('click', wrapSelectedTextWithQuotes);
copyTextBtn.addEventListener('click', copyAllText);
capitalizeAcronymsBtn.addEventListener('click', capitalizeAcronyms);
undoCapsBtn.addEventListener('click', undoCapitalizeAcronyms);
fontIncrease.addEventListener('click', () => changeFontSize(1));
fontDecrease.addEventListener('click', () => changeFontSize(-1));
shareBtn.addEventListener('click', shareOnFacebook);
archiveBtn.addEventListener('click', openArchiveUrl);
sentenceCaseBtn.addEventListener('click', () => changeCase('sentence'));
lowerCaseBtn.addEventListener('click', () => changeCase('lower'));
upperCaseBtn.addEventListener('click', () => changeCase('upper'));
titleCaseBtn.addEventListener('click', () => changeCase('title'));
findReplaceBtn.addEventListener('click', openFindReplace);
closeFindReplace.addEventListener('click', closeFindReplaceModal);
findNextBtn.addEventListener('click', findNext);
replaceBtn.addEventListener('click', replaceOne);
replaceAllBtn.addEventListener('click', replaceAll);
document.addEventListener('paste', handleGlobalUrlPaste);
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Save: Ctrl+S
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
saveHTML();
}
// New: Ctrl+N
if (e.ctrlKey && e.key === 'n') {
e.preventDefault();
newDocument();
}
// Find & Replace: Ctrl+F
if (e.ctrlKey && e.key === 'f') {
e.preventDefault();
openFindReplace();
}
// Close modal: Escape
if (e.key === 'Escape' && findReplaceModal.classList.contains('active')) {
closeFindReplaceModal();
}
// Clean HTML: Ctrl+Shift+C
if (e.ctrlKey && e.shiftKey && (e.key === 'C' || e.key === 'c')) {
e.preventDefault();
cleanHTML();
showNotification('HTML Cleaned');
}
// Wrap Quotes: Ctrl+Shift+Q
if (e.ctrlKey && e.shiftKey && (e.key === 'Q' || e.key === 'q')) {
e.preventDefault();
wrapSelectedTextWithQuotes();
}
});
// Automatically focus the preview pane so the user can start typing/pasting
previewFrame.contentWindow.focus();
}
// Function to capitalize common acronyms
function capitalizeAcronyms() {
// Common acronyms to capitalize
const acronyms = [
'nato', 'nasa', 'fbi', 'cia', 'nsa', 'dod', 'doj', 'epa', 'fda', 'cdc',
'who', 'un', 'eu', 'uk', 'usa', 'ussr', 'unicef', 'unesco', 'opec',
'asean', 'nafta', 'apec', 'osha', 'irs', 'atf', 'dea', 'fema', 'tsa',
'cnn', 'bbc', 'npr', 'pbs', 'abc', 'nbc', 'cbs', 'hbo', 'espn',
'html', 'css', 'php', 'xml', 'json', 'ajax', 'api', 'sql', 'http', 'https',
'ftp', 'smtp', 'url', 'uri', 'cdn', 'dns', 'ip', 'tcp', 'udp', 'ssl', 'tls',
'vpn', 'lan', 'wan', 'wifi', 'ids', 'ips', 'dos', 'ddos', 'xss', 'csrf',
'ssd', 'hdd', 'ram', 'rom', 'cpu', 'gpu', 'usb', 'hdmi', 'lcd', 'led',
'ai', 'ml', 'ar', 'vr', 'iot', 'saas', 'paas', 'iaas', 'devops',
'ceo', 'cfo', 'cio', 'cto', 'coo', 'hr', 'pr', 'roi', 'kpi', 'seo',
'ppc', 'cpa', 'cpc', 'ctr', 'rpm', 'cpm', 'gdpr', 'hipaa',
'lgbtq', 'adhd', 'ptsd', 'aids', 'hiv', 'mrsa', 'msds', 'copd',
'evali' // From the example
];
// Create a pattern to match whole words that are acronyms
// This will match whole words only (with word boundaries)
const pattern = new RegExp('\\b(' + acronyms.join('|') + ')\\b', 'gi');
// Get content from the source or preview (whichever is active)
const isSourceActive = document.activeElement === htmlSource;
let content;
if (isSourceActive) {
content = htmlSource.value;
} else {
// If preview is active, sync changes to source first
syncToSource();
content = htmlSource.value;
}
// Replace lowercase acronyms with uppercase versions
const updatedContent = content.replace(pattern, match => match.toUpperCase());
if (updatedContent === content) {
showNotification('No acronyms to capitalize');
return;
}
lastCapitalizedContent = content;
// Update the editor content
htmlSource.value = updatedContent;
updatePreview();
updateStatusBar();
setUnsaved();
showNotification('Acronyms capitalized');
}
function undoCapitalizeAcronyms() {
if (lastCapitalizedContent === null) {
showNotification('No caps changes to undo');
return;
}
htmlSource.value = lastCapitalizedContent;
updatePreview();
updateStatusBar();
setUnsaved();
lastCapitalizedContent = null;
showNotification('Acronym capitalization undone');
}
// Function to wrap selected text with special quotation marks
function wrapSelectedTextWithQuotes() {
const isSourceActive = document.activeElement === htmlSource;
// If in preview, sync to source first
if (!isSourceActive) {
syncToSource();
}
// Check for selection in source
const hasSelection = htmlSource.selectionStart !== htmlSource.selectionEnd;
if (hasSelection) {
// There is a selection in source
const start = htmlSource.selectionStart;
const end = htmlSource.selectionEnd;
const selectedText = htmlSource.value.substring(start, end);
const wrappedText = `❝ ${selectedText} ❞`;
htmlSource.value =
htmlSource.value.substring(0, start) +
wrappedText +
htmlSource.value.substring(end);
htmlSource.selectionStart = start;
htmlSource.selectionEnd = start + wrappedText.length;
showNotification('Selection wrapped with quotes');
} else {
// No selection, find non-empty paragraphs and wrap only those with content
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlSource.value;
// Find all paragraphs with actual content
const contentParagraphs = Array.from(tempDiv.querySelectorAll('p'))
.filter(p => p.textContent.trim() !== '');
if (contentParagraphs.length > 0) {
// Check if content is already wrapped with quotes
const firstP = contentParagraphs[0];
const lastP = contentParagraphs[contentParagraphs.length - 1];
const contentStartsWithQuote = firstP.textContent.trim().startsWith('❝');
const contentEndsWithQuote = lastP.textContent.trim().endsWith('❞');
if (!contentStartsWithQuote && !contentEndsWithQuote) {
// Add opening quote to first non-empty paragraph
const trimmedContent = firstP.textContent.trim();
firstP.textContent = firstP.textContent.replace(trimmedContent, `❝ ${trimmedContent}`);
// Add closing quote to last non-empty paragraph
const lastTrimmedContent = lastP.textContent.trim();
lastP.textContent = lastP.textContent.replace(lastTrimmedContent, `${lastTrimmedContent} ❞`);
// Update source
htmlSource.value = tempDiv.innerHTML;
showNotification('Content wrapped with quotes');
} else {
showNotification('Content already has quotes');
}
} else {
// No paragraphs with content, look for any text content
const textContent = tempDiv.textContent.trim();
if (textContent && !textContent.includes('❝') && !textContent.includes('❞')) {
// Wrap entire content if there are no quotes already
htmlSource.value = `<p>❝ ${textContent} ❞</p>`;
showNotification('Content wrapped with quotes');
} else if (!textContent) {
showNotification('No content to wrap');
} else {
showNotification('Content already has quotes');
}
}
}
// Update preview
lastCapitalizedContent = null;
updatePreview();
updateStatusBar();
setUnsaved();
}
// Function to copy all text from the preview pane
function copyAllText() {
try {
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
// Get just the text content from the preview
const textContent = previewDocument.body.innerText;
// Create a temporary textarea element to copy from
const tempTextArea = document.createElement('textarea');
tempTextArea.value = textContent;
tempTextArea.setAttribute('readonly', '');
tempTextArea.style.position = 'absolute';
tempTextArea.style.left = '-9999px';
document.body.appendChild(tempTextArea);
// Select and copy the text
tempTextArea.select();
document.execCommand('copy');
// Remove the temporary element
document.body.removeChild(tempTextArea);
showNotification('All text copied to clipboard');
} catch (e) {
console.error('Error copying text:', e);
showNotification('Failed to copy text');
}
}
// Format text breaks - convert single line breaks to double line breaks
function formatTextBreaks() {
// Work with the current content
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
// Check if there is any content in the editor
if (!htmlSource.value.trim()) {
showNotification('No content to format');
return;
}
// First get the plain text content to preserve structure
const bodyContent = previewDocument.body.innerText;
// Process the text breaks - convert single line breaks to double
let formattedText = bodyContent;
// First normalize line endings
formattedText = formattedText.replace(/\r\n/g, '\n');
formattedText = formattedText.replace(/\r/g, '\n');
// Then add an extra newline between single line breaks
formattedText = formattedText.replace(/([^\n])\n([^\n])/g, '$1\n\n$2');
// Now convert to paragraphs
const paragraphs = formattedText.split(/\n\n+/);
const formattedHtml = paragraphs
.filter(p => p.trim()) // Remove empty paragraphs
.map(p => `<p>${p.trim()}</p>`)
.join('\n');
// Update the editor
htmlSource.value = formattedHtml;
lastCapitalizedContent = null;
updatePreview();
updateStatusBar();
setUnsaved();
showNotification('Line breaks formatted to paragraphs');
}
// Update preview
function updatePreview() {
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
// If the iframe's body doesn't exist yet, write the full structure
if (!previewDocument.body) {
previewDocument.open();
previewDocument.write('<!DOCTYPE html><html><head><style>body{font-family:sans-serif;padding:10px;}</style></head><body></body></html>');
previewDocument.close();
}
// Efficiently update only the body content
// This prevents flickering and preserves scroll position
if (previewDocument.body.innerHTML !== htmlSource.value) {
previewDocument.body.innerHTML = htmlSource.value;
}
// Ensure design mode is on and event listeners are attached
if (previewDocument.designMode !== 'on') {
previewDocument.designMode = 'on';
previewDocument.addEventListener('input', debounce(syncToSource, 300));
previewDocument.addEventListener('paste', handlePaste);
}
}
function buildLinkHtml(url) {
const tempWrapper = document.createElement('div');
const paragraph = document.createElement('p');
const link = document.createElement('a');
link.href = url;
link.textContent = url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
paragraph.appendChild(link);
tempWrapper.appendChild(paragraph);
return tempWrapper.innerHTML;
}
function insertLinkFromUrl(url, { useSelection = true, skipSync = false } = {}) {
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
if (!previewDocument || !previewDocument.body) {
return;
}
const linkHtml = buildLinkHtml(url);
try {
if (useSelection) {
execCommand(previewDocument, 'insertHTML', false, linkHtml);
} else {
previewDocument.body.insertAdjacentHTML('beforeend', linkHtml);
}
} catch (err) {
console.error('Error inserting link HTML:', err);
previewDocument.body.insertAdjacentHTML('beforeend', linkHtml);
}
if (!skipSync) {
syncToSource();
}
}
// Handle paste events in the preview
function handlePaste(e) {
// Prevent the browser's default paste behavior immediately
e.preventDefault();
try {
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
// Get the pasted content as plain text
const pastedText = (e.clipboardData || window.clipboardData).getData('text/plain').trim();
// --- SMART PASTE LOGIC ---
// If the pasted text is a URL, send it to the share input field and also insert a link
if (urlRegex.test(pastedText)) {
shareUrl.value = pastedText;
showNotification('URL detected and added to share field!');
insertLinkFromUrl(pastedText, { useSelection: true, skipSync: true });
} else {
// If it's not a URL, treat it as normal text and format it into paragraphs
const formattedText = pastedText
.split(/\r?\n/)
.filter(p => p.trim())
.map(p => `<p>${p}</p>`)
.join('');
if (formattedText) {
// Insert the clean HTML using our helper command
execCommand(previewDocument, 'insertHTML', false, formattedText);
}
}
} catch (err) {
console.error('Error handling paste:', err);
}
}// Helper to safely execute commands in the preview document
function execCommand(doc, command, showUI, value) {
try {
doc.execCommand(command, showUI, value);
} catch (e) {
console.error(`Error executing "${command}":`, e);
}
}
function handleGlobalUrlPaste(e) {
const target = e.target;
const tagName = target && target.tagName ? target.tagName.toLowerCase() : '';
const isEditableTarget =
target === htmlSource ||
target === shareUrl ||
tagName === 'input' ||
tagName === 'textarea' ||
(target && target.isContentEditable);
if (isEditableTarget) {
return;
}
const pastedText = (e.clipboardData || window.clipboardData).getData('text/plain').trim();
if (!pastedText || !urlRegex.test(pastedText)) {
return;
}
e.preventDefault();
shareUrl.value = pastedText;
showNotification('URL detected and added to share field!');
shareUrl.focus();
shareUrl.select();
insertLinkFromUrl(pastedText, { useSelection: false, skipSync: false });
}
// Sync changes from preview to source
// Start of syncToSource function
function syncToSource() {
// Prevent circular updates
if (isUpdatingSource) return;
isUpdatingSource = true;
try {
const previewDocument = previewFrame.contentDocument || previewFrame.contentWindow.document;
// Get only the content between body tags, not the full HTML
let bodyContent = previewDocument.body.innerHTML;
// Format the content properly - clean up paragraphs
bodyContent = formatParagraphs(bodyContent);
// Update the source textarea ONLY if the content has changed.
// We DO NOT update the preview frame back again, as that is what causes the cursor jump.
if (bodyContent !== htmlSource.value) {
htmlSource.value = bodyContent;
lastCapitalizedContent = null;
updateStatusBar();
setUnsaved();
}
} finally {
isUpdatingSource = false;
}
}
// End of syncToSource function
// Collapse whitespace between tags while keeping inline spacing intact
function collapseWhitespaceBetweenTags(html) {
return html.replace(
/(<\/?([a-zA-Z0-9:-]+)[^>]*>)(\s+)(<\/?([a-zA-Z0-9:-]+)[^>]*>)/g,
(match, leftTag, leftName, whitespace, rightTag, rightName) => {
const leftInline = inlineElements.has(leftName.toLowerCase());
const rightInline = inlineElements.has(rightName.toLowerCase());
if (leftInline || rightInline) {
return `${leftTag} ${rightTag}`;
}
return `${leftTag}\n${rightTag}`;
}
);
}
// Remove short call-to-action blurbs or divider-only paragraphs
function removeNoiseParagraphs(html) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
tempDiv.querySelectorAll('p, li').forEach(node => {
const text = node.textContent.trim();
if (!text) {