-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1154 lines (1045 loc) · 52.3 KB
/
Copy pathapp.js
File metadata and controls
1154 lines (1045 loc) · 52.3 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
// LinkedIn Post Formatter — single-file React app loaded from CDN.
// React + ReactDOM + htm + emoji-mart all come in via <script> tags in index.html.
(function () {
"use strict";
const { useState, useEffect, useRef, useMemo, useCallback, forwardRef } = React;
const html = htm.bind(React.createElement);
// ────────────────────────────────────────────────────────────────────────────
// Unicode formatting engine
// ────────────────────────────────────────────────────────────────────────────
// Block bases for uppercase A, lowercase a, digit 0 in each variant.
// upperEx/lowerEx hold per-letter overrides (Unicode reserves several script,
// fraktur, and double-struck math codepoints — the canonical glyph lives in
// the Letterlike Symbols block instead). digitFn handles non-contiguous digit
// sets (circled: 0 at U+24EA, 1–9 at U+2460+).
const BASES = {
// Modern set produced by the toolbar.
bs: { upper: 0x1d5d4, lower: 0x1d5ee, digit: 0x1d7ec },
is: { upper: 0x1d608, lower: 0x1d622, digit: null },
bis: { upper: 0x1d63c, lower: 0x1d656, digit: null },
c: { // Script (regular)
upper: 0x1d49c, lower: 0x1d4b6, digit: null,
upperEx: { B: "ℬ", E: "ℰ", F: "ℱ", H: "ℋ", I: "ℐ", L: "ℒ", M: "ℳ", R: "ℛ" },
lowerEx: { e: "ℯ", g: "ℊ", o: "ℴ" },
},
bc: { upper: 0x1d4d0, lower: 0x1d4ea, digit: null }, // Bold Script
f: { // Fraktur
upper: 0x1d504, lower: 0x1d51e, digit: null,
upperEx: { C: "ℭ", H: "ℌ", I: "ℑ", R: "ℜ", Z: "ℨ" },
},
d: { // Double-struck (Blackboard bold)
upper: 0x1d538, lower: 0x1d552, digit: 0x1d7d8,
upperEx: { C: "ℂ", H: "ℍ", N: "ℕ", P: "ℙ", Q: "ℚ", R: "ℝ", Z: "ℤ" },
},
fw: { upper: 0xff21, lower: 0xff41, digit: 0xff10 }, // Fullwidth
ci: { // Circled
upper: 0x24b6, lower: 0x24d0, digit: null,
digitFn: (d) => d === 0 ? "⓪" : String.fromCodePoint(0x2460 + d - 1),
},
m: { upper: 0x1d670, lower: 0x1d68a, digit: 0x1d7f6 },
// Legacy serif blocks — only for detecting pasted text; not produced.
b: { upper: 0x1d400, lower: 0x1d41a, digit: 0x1d7ce },
i: { upper: 0x1d434, lower: 0x1d44e, digit: null },
bi: { upper: 0x1d468, lower: 0x1d482, digit: null },
s: { upper: 0x1d5a0, lower: 0x1d5ba, digit: 0x1d7e2 },
};
// italic h has no math italic codepoint — uses ℎ (U+210E)
const ITALIC_EXCEPTIONS = { h: "ℎ" };
const CP_A_UP = "A".codePointAt(0);
const CP_A_LO = "a".codePointAt(0);
const CP_ZERO = "0".codePointAt(0);
const COMB_UNDERLINE = "̲";
const COMB_STRIKE = "̶";
// Reverse lookup: styled codepoint -> { plain, variant }
const STYLED_TO_PLAIN = new Map();
for (const v of Object.keys(BASES)) {
const b = BASES[v];
for (let i = 0; i < 26; i++) {
const upPlain = String.fromCodePoint(CP_A_UP + i);
const loPlain = String.fromCodePoint(CP_A_LO + i);
const upStyled = (b.upperEx && b.upperEx[upPlain]) || String.fromCodePoint(b.upper + i);
const loStyled = (b.lowerEx && b.lowerEx[loPlain]) || String.fromCodePoint(b.lower + i);
STYLED_TO_PLAIN.set(upStyled.codePointAt(0), { plain: upPlain, variant: v });
STYLED_TO_PLAIN.set(loStyled.codePointAt(0), { plain: loPlain, variant: v });
}
for (let i = 0; i < 10; i++) {
let styled = null;
if (b.digitFn) styled = b.digitFn(i);
else if (b.digit !== null) styled = String.fromCodePoint(b.digit + i);
if (styled) STYLED_TO_PLAIN.set(styled.codePointAt(0), { plain: String.fromCodePoint(CP_ZERO + i), variant: v });
}
}
STYLED_TO_PLAIN.set(0x210e, { plain: "h", variant: "i" });
function variantChar(ch, variant) {
const cp = ch.codePointAt(0);
if (cp === undefined) return ch;
const base = BASES[variant];
if (!base) return ch;
if (variant === "i" && ITALIC_EXCEPTIONS[ch]) return ITALIC_EXCEPTIONS[ch];
if (cp >= CP_A_UP && cp <= CP_A_UP + 25) {
if (base.upperEx && base.upperEx[ch]) return base.upperEx[ch];
return String.fromCodePoint(base.upper + (cp - CP_A_UP));
}
if (cp >= CP_A_LO && cp <= CP_A_LO + 25) {
if (base.lowerEx && base.lowerEx[ch]) return base.lowerEx[ch];
return String.fromCodePoint(base.lower + (cp - CP_A_LO));
}
if (cp >= CP_ZERO && cp <= CP_ZERO + 9) {
if (base.digitFn) return base.digitFn(cp - CP_ZERO);
if (base.digit !== null) return String.fromCodePoint(base.digit + (cp - CP_ZERO));
}
return ch;
}
function stripVariant(text) {
let out = "";
for (const ch of text) {
const cp = ch.codePointAt(0);
const found = STYLED_TO_PLAIN.get(cp);
out += found ? found.plain : ch;
}
return out;
}
function stripDecorations(text) {
return text.replace(/[̶̲]/g, "");
}
function stripAllFormatting(text) {
// Also normalise EN QUAD (U+2000) back to regular space — we use it as a
// wider space when applying underline/strike to plain text so the combining
// mark has something to render on.
return stripDecorations(stripVariant(text)).replace(/ /g, " ");
}
function applyVariant(text, variant) {
const plain = stripVariant(text);
let out = "";
for (const ch of plain) out += variantChar(ch, variant);
return out;
}
function applyDecoration(text, decoration) {
const mark = decoration === "underline" ? COMB_UNDERLINE : COMB_STRIKE;
let out = "";
for (const ch of text) {
out += ch;
const cp = ch.codePointAt(0);
if (cp >= 0x0300 && cp <= 0x036f) continue; // skip combining marks
if (ch === "\n" || ch === "\r") continue;
out += mark;
}
return out;
}
// Map BASES variants to user-facing type-style names. The toolbar produces
// only the modern set (bs/is/bis/bc/m); legacy serif blocks (b/i/bi) fold in
// for detection of pasted text. 's' (sans-regular) is visually plain — null.
const VARIANT_TO_TYPESTYLE = {
bs: "bold", b: "bold",
is: "italic", i: "italic",
bis: "boldItalic", bi: "boldItalic",
c: "script",
bc: "boldScript",
f: "fraktur",
d: "doubleStruck",
fw: "fullwidth",
ci: "circled",
m: "monospace",
};
const TYPESTYLE_TO_VARIANT = {
bold: "bs",
italic: "is",
boldItalic: "bis",
script: "c",
boldScript: "bc",
fraktur: "f",
doubleStruck: "d",
fullwidth: "fw",
circled: "ci",
monospace: "m",
};
function detectStyle(text) {
let total = 0, underline = 0, strike = 0;
const typeCounts = {};
let prevFormattable = false;
for (const ch of text) {
const cp = ch.codePointAt(0);
if (cp === 0x0332) { if (prevFormattable) underline++; continue; }
if (cp === 0x0336) { if (prevFormattable) strike++; continue; }
const styled = STYLED_TO_PLAIN.get(cp);
const isPlain = /[A-Za-z0-9]/.test(ch);
if (isPlain || styled) {
total++;
prevFormattable = true;
const ts = styled ? VARIANT_TO_TYPESTYLE[styled.variant] : null;
if (ts) typeCounts[ts] = (typeCounts[ts] || 0) + 1;
} else {
prevFormattable = false;
}
}
if (total === 0) {
return { typeStyle: null, underline: false, strike: false };
}
let typeStyle = null;
for (const ts of Object.keys(typeCounts)) {
if (typeCounts[ts] === total) { typeStyle = ts; break; }
}
return {
typeStyle,
underline: underline > 0 && underline >= Math.floor(total * 0.5),
strike: strike > 0 && strike >= Math.floor(total * 0.5),
};
}
function applyFormatting(text, opts) {
let result = stripAllFormatting(text);
let variant = opts.typeStyle ? TYPESTYLE_TO_VARIANT[opts.typeStyle] : null;
// Combining underline/strike anchors poorly on plain ASCII — when only a
// decoration is requested, fall back to Monospace as a carrier. Pure
// rendering detail; toggleStyle/detectStyle never expose it.
if (!variant && (opts.underline || opts.strike)) variant = "m";
if (variant) result = applyVariant(result, variant);
// Monospace + underline/strike: regular spaces don't carry the combining
// mark visibly. Swap to EN QUAD (U+2000) so the line/strike continues
// across word breaks. Other math-block variants anchor the mark fine on
// regular spaces.
if ((opts.underline || opts.strike) && variant === "m") {
result = result.replace(/ /g, " ");
}
if (opts.underline) result = applyDecoration(result, "underline");
if (opts.strike) result = applyDecoration(result, "strike");
return result;
}
// Type styles (bold, italic, boldItalic, script, monospace) are mutually
// exclusive within their group; same for decorations (underline, strike).
// Type style + decoration freely combine (e.g. bold + underline).
// In each group: clicking the active button clears, clicking a different
// one replaces.
function toggleStyle(text, style) {
const current = detectStyle(text);
const next = { ...current };
if (style === "underline" || style === "strike") {
if (current[style]) {
next[style] = false;
} else {
next.underline = style === "underline";
next.strike = style === "strike";
}
} else {
next.typeStyle = current.typeStyle === style ? null : style;
}
return applyFormatting(text, next);
}
// ────────────────────────────────────────────────────────────────────────────
// List formatting
// ────────────────────────────────────────────────────────────────────────────
const NBSP2 = " ";
const RX_BULLET = /^( )?•\s/;
const RX_NUMBERED = /^( )?\d+\.\s/;
function detectListType(text) {
for (const line of text.split("\n")) {
if (line.trim() === "") continue;
if (RX_BULLET.test(line)) return "BULLETED";
if (RX_NUMBERED.test(line)) return "NUMBERED";
return null;
}
return null;
}
function stripListMarkers(text) {
return text.split("\n").map((line) =>
RX_BULLET.test(line) ? line.replace(RX_BULLET, "") :
RX_NUMBERED.test(line) ? line.replace(RX_NUMBERED, "") :
line
).join("\n");
}
function toggleList(text, type) {
if (detectListType(text) === type) return stripListMarkers(text);
const lines = stripListMarkers(text).split("\n");
if (type === "NUMBERED") {
let n = 1;
return lines.map((line) => line.trim() ? `${NBSP2}${n++}. ${line}` : line).join("\n");
}
return lines.map((line) => line.trim() ? `${NBSP2}• ${line}` : line).join("\n");
}
// ────────────────────────────────────────────────────────────────────────────
// Lucide icons (inline SVG paths)
// ────────────────────────────────────────────────────────────────────────────
const ICON_PATHS = {
bold: html`<path d="M14 12a4 4 0 0 0 0-8H6v8" /><path d="M15 20a4 4 0 0 0 0-8H6v8Z" />`,
italic: html`<line x1="19" x2="10" y1="4" y2="4" /><line x1="14" x2="5" y1="20" y2="20" /><line x1="15" x2="9" y1="4" y2="20" />`,
underline: html`<path d="M6 4v6a6 6 0 0 0 12 0V4" /><line x1="4" x2="20" y1="20" y2="20" />`,
strikethrough: html`<path d="M16 4H9a3 3 0 0 0-2.83 4" /><path d="M14 12a4 4 0 0 1 0 8H6" /><line x1="4" x2="20" y1="12" y2="12" />`,
smilePlus: html`<path d="M22 11v1a10 10 0 1 1-9-10" /><path d="M8 14s1.5 2 4 2 4-2 4-2" /><line x1="9" x2="9.01" y1="9" y2="9" /><line x1="15" x2="15.01" y1="9" y2="9" /><path d="M16 5h6" /><path d="M19 2v6" />`,
undo: html`<path d="M9 14 4 9l5-5" /><path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5 5.5 5.5 0 0 1-5.5 5.5H11" />`,
redo: html`<path d="m15 14 5-5-5-5" /><path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13" />`,
eraser: html`<path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21" /><path d="M22 21H7" /><path d="m5 11 9 9" />`,
list: html`<line x1="8" x2="21" y1="6" y2="6" /><line x1="8" x2="21" y1="12" y2="12" /><line x1="8" x2="21" y1="18" y2="18" /><line x1="3" x2="3.01" y1="6" y2="6" /><line x1="3" x2="3.01" y1="12" y2="12" /><line x1="3" x2="3.01" y1="18" y2="18" />`,
listOrdered: html`<line x1="10" x2="21" y1="6" y2="6" /><line x1="10" x2="21" y1="12" y2="12" /><line x1="10" x2="21" y1="18" y2="18" /><path d="M4 6h1v4" /><path d="M4 10h2" /><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1" />`,
check: html`<polyline points="20 6 9 17 4 12" />`,
copy: html`<rect width="14" height="14" x="8" y="8" rx="2" ry="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />`,
save: html`<path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" /><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7" /><path d="M7 3v4a1 1 0 0 0 1 1h7" />`,
trash: html`<path d="M3 6h18" /><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" /><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><line x1="10" x2="10" y1="11" y2="17" /><line x1="14" x2="14" y1="11" y2="17" />`,
bookmark: html`<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />`,
};
function Icon({ name, className = "h-4 w-4" }) {
return html`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
className=${className} aria-hidden="true">
${ICON_PATHS[name]}
</svg>
`;
}
// ────────────────────────────────────────────────────────────────────────────
// Emoji picker (emoji-mart wrapper)
// ────────────────────────────────────────────────────────────────────────────
let emojiDataPromise = null;
function getEmojiData() {
if (!emojiDataPromise) {
emojiDataPromise = fetch("https://cdn.jsdelivr.net/npm/@emoji-mart/data")
.then((r) => r.json())
.catch(() => ({}));
}
return emojiDataPromise;
}
function EmojiPicker({ onSelect }) {
const containerRef = useRef(null);
useEffect(() => {
let cancelled = false;
let pickerEl = null;
getEmojiData().then((data) => {
if (cancelled || !containerRef.current) return;
if (typeof EmojiMart === "undefined" || !EmojiMart.Picker) {
containerRef.current.textContent = "Emoji picker failed to load.";
return;
}
// We deliberately don't pass emoji-mart's onClickOutside — its handler
// is registered on document and persists past removeChild on unmount,
// which fires onClose on the next click and prevents reopening. Outside-
// click is handled by the parent Editor instead.
pickerEl = new EmojiMart.Picker({
data,
onEmojiSelect: (emoji) => onSelect(emoji.native),
previewPosition: "none",
navPosition: "bottom",
maxFrequentRows: 1,
autoFocus: true,
theme: "light",
dynamicWidth: true,
});
containerRef.current.appendChild(pickerEl);
});
return () => {
cancelled = true;
if (pickerEl && pickerEl.parentNode) pickerEl.parentNode.removeChild(pickerEl);
};
}, [onSelect]);
// On mobile the picker fills the bottom sheet (flex-1, w-full); on desktop
// it sizes to emoji-mart's intrinsic 360px and rounds itself. flex+flex-col
// is required on mobile so the picker (a flex child via CSS) sizes correctly.
return html`<div ref=${containerRef} className="overflow-hidden flex flex-col flex-1 w-full md:block md:flex-initial md:w-[360px] md:h-[360px] md:rounded-lg" />`;
}
// ────────────────────────────────────────────────────────────────────────────
// Symbol picker (Unicode blocks)
// ────────────────────────────────────────────────────────────────────────────
// Iterate a Unicode block range, dropping reserved/unassigned codepoints.
// \p{Assigned} matches "any code point assigned to an abstract character" —
// exactly the gaps we want to skip so the grid doesn't show tofu.
function blockChars(start, end) {
const out = [];
for (let cp = start; cp <= end; cp++) {
const ch = String.fromCodePoint(cp);
if (/\p{Assigned}/u.test(ch)) out.push(ch);
}
return out;
}
const SYMBOL_BLOCKS = [
{ name: "Icons", chars: blockChars(0x2700, 0x27bf) },
{ name: "Arrows", chars: blockChars(0x2190, 0x21ff) },
{ name: "Shapes", chars: blockChars(0x25a0, 0x25ff) },
{ name: "Currency", chars: ["$", ...blockChars(0x20a0, 0x20cf)] },
{ name: "Misc Tech", chars: blockChars(0x2300, 0x23ff) },
{ name: "Math", chars: blockChars(0x2200, 0x22ff) },
{ name: "Math+", chars: blockChars(0x2a00, 0x2aff) },
{ name: "Misc Math", chars: [...blockChars(0x27c0, 0x27ef), ...blockChars(0x2980, 0x29ff)] },
];
function SymbolPicker({ onSelect }) {
const [activeTab, setActiveTab] = useState(0);
const block = SYMBOL_BLOCKS[activeTab];
return html`
<div className="symbol-picker bg-white flex flex-col overflow-hidden flex-1 w-full md:flex-initial md:w-[420px] md:h-[360px] md:rounded-lg md:shadow-xl md:border md:border-zinc-200">
<div className="flex border-b border-zinc-200 overflow-x-auto flex-shrink-0">
${SYMBOL_BLOCKS.map((b, i) => html`
<button
key=${b.name}
type="button"
onClick=${() => setActiveTab(i)}
className=${`px-3 py-2 text-xs font-medium whitespace-nowrap flex-shrink-0 -mb-px border-b-2 transition-colors ${
i === activeTab
? "text-blue-600 border-blue-600"
: "text-zinc-600 hover:text-zinc-900 border-transparent"
}`}
>${b.name}</button>
`)}
</div>
<div className="flex-1 overflow-y-auto p-1">
<div className="grid grid-cols-9 md:grid-cols-12 gap-0.5">
${block.chars.map((ch) => html`
<button
key=${ch.codePointAt(0)}
type="button"
onClick=${() => onSelect(ch)}
title=${`U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`}
className="aspect-square flex items-center justify-center text-lg hover:bg-zinc-100 active:bg-zinc-200 rounded transition-colors"
>${ch}</button>
`)}
</div>
</div>
</div>
`;
}
// ────────────────────────────────────────────────────────────────────────────
// Responsive helpers
// ────────────────────────────────────────────────────────────────────────────
// True when viewport is below Tailwind's `md` breakpoint (768px). Drives the
// mobile/desktop layout split: bottom-sheet popovers, fixed bottom toolbar,
// larger touch targets, no char count.
function useIsMobile() {
const query = "(max-width: 767px)";
const [matches, setMatches] = useState(() =>
typeof window !== "undefined" && window.matchMedia(query).matches
);
useEffect(() => {
const mq = window.matchMedia(query);
const handler = (e) => setMatches(e.matches);
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, []);
return matches;
}
// Wraps a popover. On mobile: portals a slide-up sheet (with backdrop) above
// the fixed bottom toolbar. On desktop: renders an absolutely-positioned
// anchored popover (the original behavior). The forwarded ref lands on the
// element the parent's outside-click handler tests against.
const BottomSheet = forwardRef(function BottomSheet({ open, onClose, children, className = "" }, ref) {
const isMobile = useIsMobile();
if (!open) return null;
if (isMobile) {
return ReactDOM.createPortal(html`
<div>
<div className="fixed inset-x-0 top-0 bottom-14 z-40 bg-black/40" onMouseDown=${onClose} />
<div
ref=${ref}
className=${`fixed left-0 right-0 bottom-14 z-50 bg-white rounded-t-2xl shadow-2xl flex flex-col overflow-hidden animate-slide-up ${className}`}
style=${{ maxHeight: "65dvh" }}
>
<div className="h-1 w-12 bg-zinc-300 rounded-full mx-auto my-2 flex-shrink-0" />
${children}
</div>
</div>
`, document.body);
}
return html`
<div ref=${ref} className=${`absolute z-50 left-0 mt-2 ${className}`}>
${children}
</div>
`;
});
// ────────────────────────────────────────────────────────────────────────────
// Toolbar primitives
// ────────────────────────────────────────────────────────────────────────────
const ToolButton = forwardRef(function ToolButton(
{ onClick, title, icon, disabled, active },
ref
) {
const cls = disabled
? "text-zinc-300 cursor-not-allowed"
: active
? "bg-zinc-200 text-zinc-900"
: "bg-zinc-50 text-zinc-700 hover:bg-zinc-100 active:bg-zinc-200";
return html`
<button
ref=${ref}
type="button"
onClick=${onClick}
disabled=${disabled}
title=${title}
aria-label=${title}
className=${`inline-flex items-center justify-center h-11 w-11 md:h-9 md:w-9 rounded-md transition-colors flex-shrink-0 ${cls}`}
>
${icon}
</button>
`;
});
function ToolGroup({ children }) {
return html`<div className="flex items-center gap-0.5">${children}</div>`;
}
function Divider() {
return html`<div className="self-stretch w-px bg-zinc-200 mx-1" />`;
}
// ────────────────────────────────────────────────────────────────────────────
// Drafts (localStorage)
// ────────────────────────────────────────────────────────────────────────────
const DRAFTS_KEY = "linkedin-formatter:drafts";
const DRAFT_PREVIEW_LIMIT = 100;
function loadDrafts() {
try {
const raw = localStorage.getItem(DRAFTS_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed.filter((d) => d && typeof d.content === "string") : [];
} catch {
return [];
}
}
function persistDrafts(drafts) {
try { localStorage.setItem(DRAFTS_KEY, JSON.stringify(drafts)); } catch {}
}
function draftPreview(content) {
const flat = content.replace(/\s+/g, " ").trim();
if (!flat) return "(empty)";
return flat.length > DRAFT_PREVIEW_LIMIT ? flat.slice(0, DRAFT_PREVIEW_LIMIT) + "…" : flat;
}
function formatRelativeTime(ts) {
const diff = Date.now() - ts;
const sec = Math.floor(diff / 1000);
if (sec < 60) return "just now";
const min = Math.floor(sec / 60);
if (min < 60) return `${min} min${min === 1 ? "" : "s"} ago`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr} hour${hr === 1 ? "" : "s"} ago`;
const day = Math.floor(hr / 24);
if (day < 7) return `${day} day${day === 1 ? "" : "s"} ago`;
return new Date(ts).toLocaleDateString();
}
function DraftsPanel({ currentValue, onRestore, onClose }) {
const [drafts, setDrafts] = useState(() => loadDrafts());
const canSave = currentValue.trim().length > 0;
const update = (next) => { setDrafts(next); persistDrafts(next); };
const saveCurrent = () => {
if (!canSave) return;
const draft = {
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
content: currentValue,
savedAt: Date.now(),
};
update([draft, ...drafts]);
};
const deleteOne = (id) => update(drafts.filter((d) => d.id !== id));
const deleteAll = () => {
if (drafts.length === 0) return;
const ok = window.confirm(`Delete all ${drafts.length} draft${drafts.length === 1 ? "" : "s"}?`);
if (!ok) return;
update([]);
};
const handleRestore = (draft) => {
onRestore(draft.content);
onClose();
};
return html`
<div className="bg-white flex flex-col overflow-hidden flex-1 w-full md:flex-initial md:w-[380px] md:h-[420px] md:rounded-lg md:shadow-xl md:border md:border-zinc-200">
<div className="flex items-center justify-between px-3 py-2 border-b border-zinc-200 flex-shrink-0">
<h3 className="text-sm font-semibold text-zinc-800">Drafts</h3>
${drafts.length > 0 ? html`
<button
type="button"
onClick=${deleteAll}
className="text-xs font-medium text-zinc-500 hover:text-red-600 transition-colors"
>Delete all</button>
` : null}
</div>
<button
type="button"
onClick=${saveCurrent}
disabled=${!canSave}
className=${`flex items-center gap-2 px-3 py-2.5 border-b border-zinc-100 text-sm font-medium transition-colors flex-shrink-0 ${
canSave ? "text-blue-600 hover:bg-blue-50 active:bg-blue-100" : "text-zinc-300 cursor-not-allowed"
}`}
>
<${Icon} name="save" />
${canSave ? "Save current as draft" : "Type something to save a draft"}
</button>
<div className="flex-1 overflow-y-auto">
${drafts.length === 0 ? html`
<div className="text-sm text-zinc-400 px-3 py-8 text-center">No saved drafts yet</div>
` : drafts.map((d) => html`
<div key=${d.id} className="group flex items-stretch border-b border-zinc-100 last:border-b-0 hover:bg-zinc-50">
<button
type="button"
onClick=${() => handleRestore(d)}
title="Restore this draft"
className="flex-1 min-w-0 text-left px-3 py-2"
>
<div className="text-sm text-zinc-800 break-words line-clamp-2">${draftPreview(d.content)}</div>
<div className="text-[11px] text-zinc-400 mt-0.5">${formatRelativeTime(d.savedAt)}</div>
</button>
<button
type="button"
onClick=${() => deleteOne(d.id)}
title="Delete draft"
aria-label="Delete draft"
className="flex-shrink-0 inline-flex items-center justify-center w-10 text-zinc-400 hover:text-red-600 hover:bg-red-50 transition-colors"
>
<${Icon} name="trash" />
</button>
</div>
`)}
</div>
</div>
`;
}
// ────────────────────────────────────────────────────────────────────────────
// Editor
// ────────────────────────────────────────────────────────────────────────────
const HISTORY_LIMIT = 200;
const HISTORY_DEBOUNCE_MS = 400;
const PLACEHOLDER = "Write here...";
function Editor() {
const isMobile = useIsMobile();
const [value, setValue] = useState("");
const [emojiOpen, setEmojiOpen] = useState(false);
const [symbolsOpen, setSymbolsOpen] = useState(false);
const [draftsOpen, setDraftsOpen] = useState(false);
const [copied, setCopied] = useState(false);
const textareaRef = useRef(null);
const emojiButtonRef = useRef(null);
const emojiPopoverRef = useRef(null);
const symbolsButtonRef = useRef(null);
const symbolsPopoverRef = useRef(null);
const draftsButtonRef = useRef(null);
const draftsPopoverRef = useRef(null);
const [history, setHistory] = useState([{ value: "", selection: { start: 0, end: 0 } }]);
const [historyIndex, setHistoryIndex] = useState(0);
const debouncedTimer = useRef(null);
const pushHistory = useCallback((entry) => {
setHistory((prev) => {
const trimmed = prev.slice(0, historyIndex + 1);
const next = [...trimmed, entry];
if (next.length > HISTORY_LIMIT) next.shift();
return next;
});
setHistoryIndex((prev) => Math.min(prev + 1, HISTORY_LIMIT - 1));
}, [historyIndex]);
const getSelection = () => {
const ta = textareaRef.current;
if (!ta) return { start: 0, end: 0 };
return { start: ta.selectionStart || 0, end: ta.selectionEnd || 0 };
};
const setSelectionAfterRender = (sel) => {
requestAnimationFrame(() => {
const ta = textareaRef.current;
if (!ta) return;
ta.focus();
ta.setSelectionRange(sel.start, sel.end);
});
};
const commitChange = (newValue, newSelection, immediate) => {
setValue(newValue);
setSelectionAfterRender(newSelection);
if (debouncedTimer.current !== null) {
window.clearTimeout(debouncedTimer.current);
debouncedTimer.current = null;
}
if (immediate) {
pushHistory({ value: newValue, selection: newSelection });
} else {
debouncedTimer.current = window.setTimeout(() => {
pushHistory({ value: newValue, selection: newSelection });
debouncedTimer.current = null;
}, HISTORY_DEBOUNCE_MS);
}
};
const handleChange = (e) => {
const ta = e.target;
commitChange(ta.value, { start: ta.selectionStart, end: ta.selectionEnd }, false);
};
const transformSelection = (transform) => {
const ta = textareaRef.current;
if (!ta) return;
const { start, end } = getSelection();
const isEmpty = start === end;
const selected = isEmpty ? value : value.slice(start, end);
const replaced = transform(selected);
if (isEmpty) {
commitChange(replaced, { start: 0, end: replaced.length }, true);
} else {
const newValue = value.slice(0, start) + replaced + value.slice(end);
commitChange(newValue, { start, end: start + replaced.length }, true);
}
};
const transformLineRange = (transform) => {
const ta = textareaRef.current;
if (!ta) return;
const { start, end } = getSelection();
const lineStart = value.lastIndexOf("\n", start - 1) + 1;
let lineEnd = value.indexOf("\n", end);
if (lineEnd === -1) lineEnd = value.length;
const before = value.slice(0, lineStart);
const middle = value.slice(lineStart, lineEnd);
const after = value.slice(lineEnd);
const transformed = transform(middle);
commitChange(before + transformed + after, { start: lineStart, end: lineStart + transformed.length }, true);
};
const onBold = () => transformSelection((t) => toggleStyle(t, "bold"));
const onItalic = () => transformSelection((t) => toggleStyle(t, "italic"));
const onBoldItalic = () => transformSelection((t) => toggleStyle(t, "boldItalic"));
const onScript = () => transformSelection((t) => toggleStyle(t, "script"));
const onBoldScript = () => transformSelection((t) => toggleStyle(t, "boldScript"));
const onFraktur = () => transformSelection((t) => toggleStyle(t, "fraktur"));
const onDoubleStruck = () => transformSelection((t) => toggleStyle(t, "doubleStruck"));
const onFullwidth = () => transformSelection((t) => toggleStyle(t, "fullwidth"));
const onCircled = () => transformSelection((t) => toggleStyle(t, "circled"));
const onMono = () => transformSelection((t) => toggleStyle(t, "monospace"));
const onUnderline = () => transformSelection((t) => toggleStyle(t, "underline"));
const onStrike = () => transformSelection((t) => toggleStyle(t, "strike"));
const onErase = () => transformSelection(stripAllFormatting);
const onBullet = () => transformLineRange((t) => toggleList(t, "BULLETED"));
const onNumber = () => transformLineRange((t) => toggleList(t, "NUMBERED"));
const flushPending = () => {
if (debouncedTimer.current !== null) {
window.clearTimeout(debouncedTimer.current);
debouncedTimer.current = null;
pushHistory({ value, selection: getSelection() });
return true;
}
return false;
};
const onUndo = () => {
const pushed = flushPending();
const targetIndex = pushed ? historyIndex : historyIndex - 1;
if (targetIndex < 0) return;
setHistoryIndex(targetIndex);
const entry = history[targetIndex];
setValue(entry.value);
setSelectionAfterRender(entry.selection);
};
const onRedo = () => {
const newIndex = historyIndex + 1;
if (newIndex >= history.length) return;
setHistoryIndex(newIndex);
const entry = history[newIndex];
setValue(entry.value);
setSelectionAfterRender(entry.selection);
};
const insertChar = useCallback((ch) => {
const ta = textareaRef.current;
const start = ta ? (ta.selectionStart || 0) : value.length;
const end = ta ? (ta.selectionEnd || 0) : value.length;
const newValue = value.slice(0, start) + ch + value.slice(end);
const cursor = start + ch.length;
commitChange(newValue, { start: cursor, end: cursor }, true);
}, [value]);
const insertEmoji = useCallback((emoji) => { insertChar(emoji); setEmojiOpen(false); }, [insertChar]);
const insertSymbol = useCallback((ch) => { insertChar(ch); setSymbolsOpen(false); }, [insertChar]);
const closeEmoji = useCallback(() => setEmojiOpen(false), []);
const closeSymbols = useCallback(() => setSymbolsOpen(false), []);
const closeDrafts = useCallback(() => setDraftsOpen(false), []);
const restoreDraft = (content) => {
flushPending();
const cursor = content.length;
commitChange(content, { start: cursor, end: cursor }, true);
};
const onCopy = async () => {
try {
await navigator.clipboard.writeText(value);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
const ta = textareaRef.current;
if (ta) {
ta.select();
try { document.execCommand("copy"); setCopied(true); setTimeout(() => setCopied(false), 1500); }
catch (e) { /* ignore */ }
}
}
};
// Close emoji popover on outside click
useEffect(() => {
if (!emojiOpen) return;
const handler = (e) => {
const target = e.target;
if (
emojiPopoverRef.current && !emojiPopoverRef.current.contains(target) &&
emojiButtonRef.current && !emojiButtonRef.current.contains(target)
) {
setEmojiOpen(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [emojiOpen]);
// Close symbols popover on outside click
useEffect(() => {
if (!symbolsOpen) return;
const handler = (e) => {
const target = e.target;
if (
symbolsPopoverRef.current && !symbolsPopoverRef.current.contains(target) &&
symbolsButtonRef.current && !symbolsButtonRef.current.contains(target)
) {
setSymbolsOpen(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [symbolsOpen]);
// Close drafts popover on outside click
useEffect(() => {
if (!draftsOpen) return;
const handler = (e) => {
const target = e.target;
if (
draftsPopoverRef.current && !draftsPopoverRef.current.contains(target) &&
draftsButtonRef.current && !draftsButtonRef.current.contains(target)
) {
setDraftsOpen(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [draftsOpen]);
// Escape to close any open popover
useEffect(() => {
if (!emojiOpen && !symbolsOpen && !draftsOpen) return;
const handler = (e) => {
if (e.key !== "Escape") return;
setEmojiOpen(false);
setSymbolsOpen(false);
setDraftsOpen(false);
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
}, [emojiOpen, symbolsOpen, draftsOpen]);
const onKeyDown = (e) => {
const mod = e.ctrlKey || e.metaKey;
if (!mod) return;
const k = e.key.toLowerCase();
if (k === "z" && !e.shiftKey) { e.preventDefault(); onUndo(); return; }
if ((k === "z" && e.shiftKey) || k === "y") { e.preventDefault(); onRedo(); return; }
if (k === "b") { e.preventDefault(); onBold(); return; }
if (k === "i") { e.preventDefault(); onItalic(); return; }
if (k === "u") { e.preventDefault(); onUnderline(); return; }
};
const charCount = useMemo(() => Array.from(value).length, [value]);
const wordCount = useMemo(() => {
// Drop list markers (" • " / " N. ") so they don't inflate the count,
// then keep only tokens that contain a letter or digit (skips lone bullets,
// dashes, etc.). \p{L} matches the styled Unicode math alphabetics too.
const cleaned = stripListMarkers(value);
if (!cleaned.trim()) return 0;
return cleaned.split(/\s+/).filter((t) => /[\p{L}\p{N}]/u.test(t)).length;
}, [value]);
const canUndo = historyIndex > 0;
const canRedo = historyIndex < history.length - 1;
const copyClass = copied
? "bg-emerald-50 border-emerald-200 text-emerald-700"
: "bg-blue-600 border-blue-600 text-white hover:bg-blue-700";
// Picker buttons defined once so refs are unambiguous; only one of the two
// toolbar branches below renders at a time, so each is mounted exactly once.
const emojiButton = html`
<div className="relative">
<${ToolButton}
ref=${emojiButtonRef}
onClick=${() => { setEmojiOpen((o) => !o); setSymbolsOpen(false); }}
title="Insert emoji"
icon=${html`<${Icon} name="smilePlus" />`}
active=${emojiOpen}
/>
<${BottomSheet} ref=${emojiPopoverRef} open=${emojiOpen} onClose=${closeEmoji}>
<${EmojiPicker} onSelect=${insertEmoji} />
<//>
</div>
`;
const symbolsButton = html`
<div className="relative">
<${ToolButton}
ref=${symbolsButtonRef}
onClick=${() => { setSymbolsOpen((o) => !o); setEmojiOpen(false); setDraftsOpen(false); }}
title="Insert symbol"
icon=${html`<span className="text-base leading-none">Ω</span>`}
active=${symbolsOpen}
/>
<${BottomSheet} ref=${symbolsPopoverRef} open=${symbolsOpen} onClose=${closeSymbols}>
<${SymbolPicker} onSelect=${insertSymbol} />
<//>
</div>
`;
const draftsButton = html`
<div className="relative">
<${ToolButton}
ref=${draftsButtonRef}
onClick=${() => { setDraftsOpen((o) => !o); setEmojiOpen(false); setSymbolsOpen(false); }}
title="Drafts"
icon=${html`<${Icon} name="bookmark" />`}
active=${draftsOpen}
/>
<${BottomSheet} ref=${draftsPopoverRef} open=${draftsOpen} onClose=${closeDrafts}>
<${DraftsPanel} currentValue=${value} onRestore=${restoreDraft} onClose=${closeDrafts} />
<//>
</div>
`;
return html`
<${React.Fragment}>
<div className="rounded-xl border border-zinc-200 bg-white shadow-sm overflow-visible flex-1 flex flex-col min-h-0">
${!isMobile ? html`
<div className="border-b border-zinc-100">
<div className="flex items-center gap-1 px-3 pt-2 pb-1 flex-wrap">
<${ToolGroup}>
<${ToolButton} onClick=${onBold} title="Bold (Ctrl+B)" icon=${html`<${Icon} name="bold" />`} />
<${ToolButton} onClick=${onItalic} title="Italic (Ctrl+I)" icon=${html`<${Icon} name="italic" />`} />
<${ToolButton} onClick=${onBoldItalic} title="Bold Italic" icon=${html`<span className="font-semibold italic text-base leading-none">𝘽</span>`} />
<//>
<${Divider} />
<${ToolGroup}>
<${ToolButton} onClick=${onScript} title="Script" icon=${html`<span className="text-base leading-none -mt-0.5">𝒮</span>`} />
<${ToolButton} onClick=${onBoldScript} title="Bold Script" icon=${html`<span className="font-semibold text-base leading-none -mt-0.5">𝓢</span>`} />
<${ToolButton} onClick=${onFraktur} title="Fraktur" icon=${html`<span className="text-base leading-none">𝔉</span>`} />
<${ToolButton} onClick=${onDoubleStruck} title="Double-struck" icon=${html`<span className="text-base leading-none">𝔻</span>`} />
<${ToolButton} onClick=${onFullwidth} title="Fullwidth" icon=${html`<span className="text-sm leading-none">A</span>`} />
<${ToolButton} onClick=${onCircled} title="Circled" icon=${html`<span className="text-base leading-none">Ⓒ</span>`} />
<${ToolButton} onClick=${onMono} title="Monospace" icon=${html`<span className="font-mono text-base leading-none">𝙼</span>`} />
<//>
<${Divider} />
<${ToolGroup}>
<${ToolButton} onClick=${onUnderline} title="Underline (Ctrl+U)" icon=${html`<${Icon} name="underline" />`} />
<${ToolButton} onClick=${onStrike} title="Strikethrough" icon=${html`<${Icon} name="strikethrough" />`} />
<//>
<div className="ml-auto relative">
<button