Repository navigation
Expand file tree
/
Copy pathslate.html
More file actions
2050 lines (1986 loc) · 107 KB
/
Copy pathslate.html
File metadata and controls
2050 lines (1986 loc) · 107 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, maximum-scale=1, user-scalable=no"/>
<title>Slate — personal math whiteboard</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' rx='22' fill='%23141414'/><text x='50' y='68' font-size='52' text-anchor='middle' fill='white' font-family='Georgia'>∑</text></svg>"/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Caveat:wght@500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"/>
<script>
window.MathJax = {
startup: { typeset: false },
svg: { fontCache: 'none' },
tex: { inlineMath: [], displayMath: [] },
};
</script>
<script defer src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<style>
:root{
--bg:#141414; --grid:rgba(255,255,255,.052); --grid2:rgba(255,255,255,.085);
--ink:#f2f2f0; --panel:#1e1e1e; --panel-br:#2c2c2c;
--chrome:#1c1c1cf2; --chrome-br:#303030; --mut:#9c9c9c; --faint:#6d6d6d;
--acc:#2dd4bf; --danger:#f87171;
--sh:0 10px 32px -8px rgba(0,0,0,.55);
--r:14px;
}
[data-theme="light"]{
--bg:#f7f7f5; --grid:rgba(20,20,20,.055); --grid2:rgba(20,20,20,.09);
--ink:#1c1c1c; --panel:#ffffff; --panel-br:#e4e4e0;
--chrome:#fffffff2; --chrome-br:#e2e2de; --mut:#71716d; --faint:#a3a39e;
--sh:0 10px 32px -12px rgba(30,30,30,.25);
}
*{box-sizing:border-box;margin:0;-webkit-tap-highlight-color:transparent}
html,body{height:100%;overflow:hidden;overscroll-behavior:none}
body{font-family:Inter,system-ui,sans-serif;background:var(--bg);color:var(--ink)}
#board{position:fixed;inset:0;touch-action:none;display:block}
button{font-family:inherit;cursor:pointer;border:none;background:none;color:inherit}
.hide-ui .chrome{opacity:0;pointer-events:none;transform:translateY(6px)}
.chrome{transition:opacity .2s, transform .2s}
/* ---------- top bar ---------- */
#topbar{position:fixed;top:14px;left:14px;right:14px;display:flex;align-items:center;gap:8px;z-index:20;pointer-events:none}
#topbar>*{pointer-events:auto}
.bar{display:flex;align-items:center;gap:2px;background:var(--chrome);backdrop-filter:blur(12px);
border:1px solid var(--chrome-br);border-radius:12px;padding:4px;box-shadow:var(--sh)}
.tb{display:inline-flex;align-items:center;gap:7px;padding:7px 11px;border-radius:9px;font-size:12.5px;font-weight:600;color:var(--mut)}
.tb:hover{background:rgba(128,128,128,.13);color:var(--ink)}
.tb.on{color:var(--acc)}
.tb svg{width:15px;height:15px}
#bname{font-size:13px;font-weight:600;color:var(--ink);background:none;border:1px solid transparent;border-radius:8px;padding:6px 9px;width:170px;outline:none}
#bname:hover{border-color:var(--chrome-br)} #bname:focus{border-color:var(--acc)}
#saved{font-size:10.5px;color:var(--faint);padding:0 8px;display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
#saved i{width:6px;height:6px;border-radius:50%;background:var(--acc);display:inline-block}
.spacer{flex:1;pointer-events:none}
/* ---------- toolbar ---------- */
#toolbar{position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:20;display:flex;gap:10px;align-items:stretch;max-width:calc(100vw - 20px)}
.tool{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 11px 5px;border-radius:10px;color:var(--mut);position:relative}
.tool svg{width:19px;height:19px}
.tool small{font-size:9px;font-weight:600;letter-spacing:.04em;color:var(--faint)}
.tool:hover{background:rgba(128,128,128,.13);color:var(--ink)}
.tool.on{background:var(--acc);color:#04211d}
.tool.on small{color:#04211dcc}
.vsep{width:1px;background:var(--chrome-br);margin:6px 2px}
.dot{width:21px;height:21px;border-radius:50%;border:2px solid transparent;padding:0;flex:0 0 auto}
.dot.on{border-color:var(--ink);box-shadow:0 0 0 2px var(--bg)}
#dots{display:flex;align-items:center;gap:7px;padding:0 8px}
#sizer{display:flex;align-items:center;gap:8px;padding:0 10px 0 4px}
#sizer input{width:86px;accent-color:var(--acc)}
#sizer b{font-size:10px;color:var(--faint);font-weight:600}
.act{padding:8px 12px;border-radius:9px;font-size:12.5px;font-weight:600;color:var(--mut)}
.act:hover{background:rgba(128,128,128,.13);color:var(--ink)}
.act:disabled{opacity:.35;pointer-events:none}
/* ---------- zoom ---------- */
#zoombar{position:fixed;right:14px;top:50%;z-index:20}
#zoombar .bar{flex-direction:column;gap:3px;transform:translateY(-50%)}
#zoombar .act{padding:7px 10px;font-size:12px}
#zpct{min-width:46px;text-align:center;font-size:11.5px;color:var(--mut);font-weight:600}
/* ---------- menus / popovers ---------- */
.pop{position:fixed;z-index:40;background:var(--chrome);backdrop-filter:blur(14px);border:1px solid var(--chrome-br);
border-radius:14px;box-shadow:var(--sh);padding:8px;min-width:230px;display:none}
.pop.open{display:block}
.pop .mi{display:flex;align-items:center;gap:10px;width:100%;text-align:left;padding:9px 11px;border-radius:9px;font-size:13px;font-weight:500;color:var(--ink)}
.pop .mi:hover{background:rgba(128,128,128,.13)}
.pop .mi small{margin-left:auto;color:var(--faint);font-size:10.5px}
.pop hr{border:none;border-top:1px solid var(--chrome-br);margin:6px 4px}
.brow{display:flex;align-items:center;gap:4px;border-radius:9px;padding:2px 2px 2px 0}
.brow:hover{background:rgba(128,128,128,.10)}
.brow .mi{flex:1}
.brow .ic{padding:7px;border-radius:8px;color:var(--faint);font-size:11px}
.brow .ic:hover{background:rgba(128,128,128,.18);color:var(--ink)}
/* ---------- text edit overlay ---------- */
#tedit{position:fixed;z-index:30;display:none;background:transparent;border:1.5px dashed color-mix(in srgb, var(--acc) 60%, transparent);
border-radius:6px;outline:none;resize:none;overflow:hidden;white-space:pre;color:var(--ink);padding:2px 6px;line-height:1.3}
/* ---------- math editor ---------- */
#msheet{position:fixed;left:50%;bottom:86px;transform:translateX(-50%);z-index:35;width:min(680px,calc(100vw - 24px));
background:var(--chrome);backdrop-filter:blur(14px);border:1px solid var(--chrome-br);border-radius:16px;box-shadow:var(--sh);
padding:14px;display:none;flex-direction:column;gap:10px}
#msheet.open{display:flex}
#mprev{min-height:64px;display:flex;align-items:center;justify-content:center;background:var(--panel);
border:1px solid var(--panel-br);border-radius:10px;padding:12px;overflow-x:auto}
#mprev svg{max-width:100%}
#mprev .err{color:var(--danger);font-size:12.5px;font-family:'JetBrains Mono',monospace}
#minput{font-family:'JetBrains Mono',monospace;font-size:14px;background:var(--panel);color:var(--ink);
border:1px solid var(--panel-br);border-radius:10px;padding:11px 13px;outline:none;width:100%}
#minput:focus{border-color:var(--acc)}
#mchips{display:flex;gap:6px;flex-wrap:wrap}
.chip{font-family:'JetBrains Mono',monospace;font-size:11.5px;padding:5px 9px;border-radius:7px;background:var(--panel);
border:1px solid var(--panel-br);color:var(--mut)}
.chip:hover{color:var(--ink);border-color:var(--acc)}
#mrow{display:flex;gap:8px;justify-content:flex-end;align-items:center}
#mrow .hint{margin-right:auto;font-size:11px;color:var(--faint)}
.btn{padding:8px 16px;border-radius:9px;font-size:13px;font-weight:600;color:var(--mut);border:1px solid var(--chrome-br)}
.btn:hover{color:var(--ink)}
.btn.pri{background:var(--acc);border-color:var(--acc);color:#04211d}
/* ---------- help ---------- */
#help{position:fixed;inset:0;z-index:50;background:rgba(0,0,0,.45);display:none;align-items:center;justify-content:center;padding:20px}
#help.open{display:flex}
#help .card{background:var(--chrome);border:1px solid var(--chrome-br);border-radius:18px;box-shadow:var(--sh);
padding:26px 30px;max-width:560px;width:100%;max-height:86vh;overflow-y:auto}
#help h2{font-size:16px;margin-bottom:14px}
#help table{width:100%;border-collapse:collapse;font-size:13px}
#help td{padding:5.5px 6px;color:var(--mut)}
#help td:first-child{color:var(--ink);font-weight:600;width:46%}
#help kbd{font-family:'JetBrains Mono',monospace;font-size:11px;background:var(--panel);border:1px solid var(--panel-br);
border-radius:5px;padding:2px 6px;color:var(--ink)}
.toast{position:fixed;top:66px;left:50%;transform:translateX(-50%);z-index:90;background:var(--chrome);border:1px solid var(--chrome-br);
color:var(--ink);border-radius:999px;padding:9px 18px;font-size:12.5px;font-weight:600;box-shadow:var(--sh);opacity:0;transition:opacity .25s;pointer-events:none}
.toast.show{opacity:1}
#printarea{display:none}
@media print{
body>*{display:none!important}
#printarea{display:block!important;position:static}
#printarea img{max-width:100%;page-break-after:always;break-after:page}
#printarea img:last-child{page-break-after:auto;break-after:auto}
}
@media(max-width:900px){ .tool small{display:none} .tool{padding:9px 10px} #sizer input{width:60px} #bname{width:110px} }
</style>
</head>
<body data-theme="dark">
<canvas id="board"></canvas>
<div id="topbar" class="chrome">
<div class="bar">
<button class="tb" id="bmenu-btn" title="Boards">☰</button>
<input id="bname" value="My board" spellcheck="false"/>
<span id="saved"><i></i>saved</span>
</div>
<div class="spacer"></div>
<div class="bar">
<button class="tb" id="grid-btn" title="Toggle grid (G)">Grid</button>
<button class="tb" id="snap-btn" title="Snap to grid (S)">Snap</button>
<button class="tb" id="theme-btn" title="Theme (D)">◐</button>
<button class="tb" id="export-btn" title="Export">⤓ Export</button>
<button class="tb" id="help-btn" title="Shortcuts (?)">?</button>
<button class="tb" id="ui-btn" title="Hide UI (U)">Hide UI</button>
<button class="tb" id="fullapp-btn" title="Open in a full browser tab (downloads + saved boards work there)" style="display:none;color:var(--acc)">⤢ Full app</button>
</div>
</div>
<div id="toolbar" class="chrome">
<div class="bar" id="tools"></div>
<div class="bar">
<button class="act" id="undo-btn" title="Undo (Ctrl+Z)">Undo</button>
<button class="act" id="redo-btn" title="Redo (Ctrl+Y)">Redo</button>
</div>
<div class="bar">
<div id="dots"></div>
<div class="vsep"></div>
<div id="sizer"><b>SIZE</b><input type="range" id="size" min="1" max="14" step="0.5" value="3"/></div>
</div>
</div>
<div id="zoombar" class="chrome"><div class="bar">
<button class="act" id="zin" title="Zoom in (+)">+</button>
<span id="zpct">100%</span>
<button class="act" id="zout" title="Zoom out (-)">−</button>
<button class="act" id="zfit" title="Zoom to fit (F)">Fit</button>
</div></div>
<div class="pop" id="bmenu" style="top:64px;left:14px"></div>
<div class="pop" id="emenu" style="top:64px;right:14px">
<button class="mi" id="ex-pdf">Export as PDF <small>A4 · per page</small></button>
<button class="mi" id="ex-png">Export as PNG <small>your canvas</small></button>
<hr/>
<button class="mi" id="ex-pdfimport">Import PDF (.pdf) <small>exact design · image</small></button>
<button class="mi" id="ex-pdfimport-text">Import PDF + editable text <small>adds text layer</small></button>
<button class="mi" id="ex-json">Backup board (.json)</button>
<button class="mi" id="ex-import">Import board (.json)</button>
</div>
<textarea id="tedit" spellcheck="false"></textarea>
<div id="msheet">
<div id="mprev"><span class="err">Type LaTeX below — live preview appears here</span></div>
<input id="minput" placeholder="e.g. f(x) = 3x^2 + 5x - 7 or \frac{d}{dx}\left(x^2\right) = 2x" spellcheck="false"/>
<div id="mchips"></div>
<div id="mrow">
<span class="hint">Enter to place · Esc to cancel</span>
<button class="btn" id="mcancel">Cancel</button>
<button class="btn pri" id="mok">Place equation</button>
</div>
</div>
<div id="psheet" style="position:fixed;left:50%;bottom:86px;transform:translateX(-50%);z-index:35;width:min(560px,calc(100vw - 24px));background:var(--chrome);backdrop-filter:blur(14px);border:1px solid var(--chrome-br);border-radius:16px;box-shadow:var(--sh);padding:14px;display:none;flex-direction:column;gap:10px">
<input id="pexpr" placeholder="y = e.g. x^2 - 3 · sin(x)*x · 1/x" spellcheck="false"
style="font-family:'JetBrains Mono',monospace;font-size:14px;background:var(--panel);color:var(--ink);border:1px solid var(--panel-br);border-radius:10px;padding:11px 13px;outline:none;width:100%"/>
<div style="display:flex;gap:8px;align-items:center">
<b style="font-size:10px;color:var(--faint);letter-spacing:.06em">X RANGE</b>
<input id="pxmin" value="-10" style="width:82px;font-family:'JetBrains Mono',monospace;font-size:13px;background:var(--panel);color:var(--ink);border:1px solid var(--panel-br);border-radius:8px;padding:7px 9px;outline:none"/>
<span style="color:var(--faint)">→</span>
<input id="pxmax" value="10" style="width:82px;font-family:'JetBrains Mono',monospace;font-size:13px;background:var(--panel);color:var(--ink);border:1px solid var(--panel-br);border-radius:8px;padding:7px 9px;outline:none"/>
<span id="perr" style="font-size:11.5px;color:var(--danger);margin-left:6px"></span>
<span style="flex:1"></span>
<button class="btn" id="pcancel">Cancel</button>
<button class="btn pri" id="pok">Plot it</button>
</div>
<div style="font-size:11px;color:var(--faint)">sin cos tan sqrt abs ln log exp · pi e · powers with ^ · Enter to place</div>
</div>
<div id="help"><div class="card">
<h2>Slate — shortcuts</h2>
<table>
<tr><td>Select / Hand / Pen / Eraser</td><td><kbd>V</kbd> <kbd>H</kbd> <kbd>P</kbd> <kbd>E</kbd></td></tr>
<tr><td>Rectangle / Ellipse / Arrow</td><td><kbd>R</kbd> <kbd>O</kbd> <kbd>A</kbd></td></tr>
<tr><td>Text / Note / Code / Math</td><td><kbd>T</kbd> <kbd>N</kbd> <kbd>C</kbd> <kbd>M</kbd></td></tr>
<tr><td>Highlighter / Image / Plot</td><td><kbd>L</kbd> <kbd>I</kbd> <kbd>X</kbd></td></tr>
<tr><td>Insert image</td><td>paste (<kbd>Ctrl</kbd>+<kbd>V</kbd>) or drag & drop a file</td></tr>
<tr><td>Smart shape snap</td><td>draw a circle/rect/line, then <b>hold still</b> before release</td></tr>
<tr><td>Import PDF</td><td>Export menu → <b>Import PDF (.pdf)</b> keeps the design exactly · <b>+ editable text</b> adds a text layer · or drag & drop</td></tr>
<tr><td>Undo / Redo</td><td><kbd>Ctrl</kbd>+<kbd>Z</kbd> / <kbd>Ctrl</kbd>+<kbd>Y</kbd></td></tr>
<tr><td>Duplicate / Copy / Paste</td><td><kbd>Ctrl</kbd>+<kbd>D</kbd> / <kbd>C</kbd> / <kbd>V</kbd></td></tr>
<tr><td>Delete selection</td><td><kbd>Del</kbd> or <kbd>Backspace</kbd></td></tr>
<tr><td>Nudge selection</td><td>Arrow keys (<kbd>Shift</kbd> = ×10)</td></tr>
<tr><td>Pan</td><td><kbd>Space</kbd>+drag · middle mouse · wheel</td></tr>
<tr><td>Zoom</td><td><kbd>Ctrl</kbd>+wheel · pinch · <kbd>+</kbd>/<kbd>−</kbd> · <kbd>F</kbd> fit</td></tr>
<tr><td>Grid / Snap / Theme / Hide UI</td><td><kbd>G</kbd> <kbd>S</kbd> <kbd>D</kbd> <kbd>U</kbd></td></tr>
<tr><td>Edit any text / equation</td><td>Double-click it</td></tr>
<tr><td>Constrain shapes / straight arrows</td><td>Hold <kbd>Shift</kbd></td></tr>
</table>
<p style="margin-top:14px;font-size:11.5px;color:var(--faint)">Everything is saved automatically in this browser. No account, no cloud, no watermark. Yours.</p>
</div></div>
<div class="toast" id="toast"></div>
<button id="showui" style="position:fixed;top:14px;right:14px;z-index:25;display:none;background:var(--chrome);border:1px solid var(--chrome-br);border-radius:999px;padding:8px 16px;font-size:12px;font-weight:600;color:var(--mut);box-shadow:var(--sh)">Show UI</button>
<!-- export overlay: works even in hard-sandboxed embeds (right-click/long-press to save, or Print → Save as PDF) -->
<div id="expov" style="position:fixed;inset:0;z-index:80;display:none;background:rgba(0,0,0,.72);backdrop-filter:blur(4px);align-items:center;justify-content:center;padding:20px">
<div style="background:var(--chrome);border:1px solid var(--chrome-br);border-radius:16px;box-shadow:var(--sh);max-width:min(960px,95vw);max-height:92vh;display:flex;flex-direction:column;overflow:hidden">
<div style="display:flex;align-items:center;gap:10px;padding:14px 18px;border-bottom:1px solid var(--chrome-br)">
<b id="exhead" style="font-size:14px;color:var(--ink)">Your board</b>
<span id="exhint" style="font-size:12px;color:var(--mut)">Right-click the image → “Save image as…” · on mobile, long-press → Save</span>
<span style="flex:1"></span>
<button class="btn pri" id="exprint" style="padding:7px 14px">🖨 Print / Save as PDF</button>
<button class="btn" id="exdl" style="padding:7px 14px">Download</button>
<button class="btn" id="exclose" style="padding:7px 12px">Close</button>
</div>
<div style="overflow:auto;padding:16px;background:#0a0a0a;display:flex;justify-content:center">
<div id="eximgs" style="display:flex;flex-direction:column;align-items:center;gap:4px;max-width:100%"></div>
</div>
</div>
</div>
<div id="printarea"></div>
<script>
'use strict';
/* =====================================================================
SLATE — a personal, from-scratch infinite whiteboard.
Canvas engine, tools, math blocks, exports. No accounts. No watermark.
===================================================================== */
/* ---------- tiny utils ---------- */
const $=s=>document.querySelector(s);
const uid=()=> 'o'+Math.random().toString(36).slice(2,10);
const clamp=(v,a,b)=>Math.min(b,Math.max(a,v));
const dist=(x1,y1,x2,y2)=>Math.hypot(x2-x1,y2-y1);
const now=()=>Date.now();
let TOAST_T=null;
function toast(msg){const t=$('#toast');t.textContent=msg;t.classList.add('show');clearTimeout(TOAST_T);TOAST_T=setTimeout(()=>t.classList.remove('show'),2200);}
/* ---------- safe storage (works even in sandboxed iframes) ----------
Some embeds block localStorage entirely (SecurityError on ANY access).
Everything goes through this shim: real localStorage when available,
an in-memory session store otherwise — the app always works. */
const store=(()=>{
const mem=Object.create(null);
let ok=false;
try{ localStorage.setItem('__slate_probe','1'); localStorage.removeItem('__slate_probe'); ok=true; }catch{ ok=false; }
return {
ok,
get(k){ if(ok){ try{ const v=localStorage.getItem(k); if(v!=null) return v; }catch{} } return (k in mem)?mem[k]:null; },
set(k,v){ mem[k]=v; if(ok){ try{ localStorage.setItem(k,v); return true; }catch{ return false; } } return true; },
rm(k){ delete mem[k]; if(ok){ try{ localStorage.removeItem(k); }catch{} } },
};
})();
/* ---------- palette / themes ---------- */
const PAL={ ink:null, teal:'#2dd4bf', blue:'#60a5fa', red:'#f87171', amber:'#fbbf24', purple:'#a78bfa', orange:'#fb923c' };
const NOTE_BG={ ink:'#fbbf24', teal:'#99f6e4', blue:'#bfdbfe', red:'#fecaca', amber:'#fde68a', purple:'#ddd6fe', orange:'#fed7aa' };
function themeVals(){
const dark=document.body.dataset.theme!=='light';
return dark
? {bg:'#141414', ink:'#f2f2f0', panel:'#1e1e1e', panelBr:'#2c2c2c', grid:'rgba(255,255,255,.052)', grid2:'rgba(255,255,255,.085)', noteInk:'#292929'}
: {bg:'#f7f7f5', ink:'#1c1c1c', panel:'#ffffff', panelBr:'#e4e4e0', grid:'rgba(20,20,20,.055)', grid2:'rgba(20,20,20,.09)', noteInk:'#2a2a20'};
}
function col(key){ return key==='ink' ? themeVals().ink : (PAL[key]||key); }
/* ---------- state ---------- */
const S={
objects:[], cam:{x:0,y:0,z:1},
pdfs:null, // compressed original PDFs for imported pages (keeps boards tiny)
tool:'pen', color:'ink', size:3,
sel:new Set(), grid:true, snap:false,
boardId:null, boardName:'My board',
undo:[], redo:[], clip:null,
dirty:true,
};
const GRID=24;
/* ---------- canvas setup ---------- */
const cv=$('#board'); let ctx=cv.getContext('2d');
let DPR=1, W=0, H=0;
function resize(){ DPR=window.devicePixelRatio||1; W=innerWidth; H=innerHeight; cv.width=W*DPR; cv.height=H*DPR; cv.style.width=W+'px'; cv.style.height=H+'px'; S.dirty=true; }
addEventListener('resize',resize);
/* ---------- camera ---------- */
const w2sX=x=>(x+S.cam.x)*S.cam.z, w2sY=y=>(y+S.cam.y)*S.cam.z;
const s2wX=x=>x/S.cam.z-S.cam.x, s2wY=y=>y/S.cam.z-S.cam.y;
function zoomAt(sx,sy,f){ const wx=s2wX(sx),wy=s2wY(sy); S.cam.z=clamp(S.cam.z*f,.08,8); S.cam.x=sx/S.cam.z-wx; S.cam.y=sy/S.cam.z-wy; S.dirty=true; zlabel(); }
function zlabel(){ $('#zpct').textContent=Math.round(S.cam.z*100)+'%'; }
/* ---------- object bounds ---------- */
function strokeBounds(o){let x1=1e9,y1=1e9,x2=-1e9,y2=-1e9;for(const p of o.pts){if(p[0]<x1)x1=p[0];if(p[1]<y1)y1=p[1];if(p[0]>x2)x2=p[0];if(p[1]>y2)y2=p[1];}const m=o.w*2;return{x:x1-m,y:y1-m,w:x2-x1+m*2,h:y2-y1+m*2};}
function textMetrics(o){ ctx.save(); ctx.font=fontFor(o); const lines=o.txt.split('\n'); let w=10; for(const l of lines) w=Math.max(w,ctx.measureText(l||' ').width); ctx.restore(); return {w:w+8, h:lines.length*o.fs*1.3+6}; }
/* tick helpers for plot blocks */
function niceStep(range){ const raw=range/5, mag=Math.pow(10,Math.floor(Math.log10(raw)));
const n=raw/mag; return (n<1.5?1:n<3.5?2:n<7.5?5:10)*mag; }
function fmtTick(v){ const a=Math.abs(v); if(a>=1000||a<0.001&&a>0)return v.toExponential(0);
return String(Math.round(v*1000)/1000); }
function bounds(o){
switch(o.t){
case 's': return strokeBounds(o);
case 'r': case 'o': case 'n': case 'c': case 'i': case 'p': return {x:o.x,y:o.y,w:o.w,h:o.h};
case 'a': return {x:Math.min(o.x1,o.x2)-8,y:Math.min(o.y1,o.y2)-8,w:Math.abs(o.x2-o.x1)+16,h:Math.abs(o.y2-o.y1)+16};
case 't': { const m=textMetrics(o); return {x:o.x,y:o.y,w:m.w,h:m.h}; }
case 'm': { const d=mathDim(o); return {x:o.x-MPAD,y:o.y-MPAD,w:d.w+MPAD*2,h:d.h+MPAD*2}; }
}
}
function selBounds(){ let b=null; for(const id of S.sel){ const o=objById(id); if(!o)continue; const ob=bounds(o); if(!b)b={...ob}; else { const x2=Math.max(b.x+b.w,ob.x+ob.w),y2=Math.max(b.y+b.h,ob.y+ob.h); b.x=Math.min(b.x,ob.x); b.y=Math.min(b.y,ob.y); b.w=x2-b.x; b.h=y2-b.y; } } return b; }
const objById=id=>S.objects.find(o=>o.id===id);
/* ---------- math blocks (MathJax → SVG → Image) ---------- */
const MPAD=18; const mcache=new Map();
function mathKey(o){ return o.latex+'|'+col(o.c); }
function mathDim(o){ const c=mcache.get(mathKey(o)); const bw=c?c.w:220, bh=c?c.h:56; return {w:bw*o.s, h:bh*o.s}; }
function renderMath(o){
const key=mathKey(o);
if(mcache.has(key)) return mcache.get(key);
if(!window.MathJax || !MathJax.tex2svg){ return null; }
try{
const node=MathJax.tex2svg(o.latex,{display:true});
const svg=node.querySelector('svg');
const exW=parseFloat(svg.getAttribute('width'))||10, exH=parseFloat(svg.getAttribute('height'))||3;
const w=exW*9, h=exH*9; // 1ex ≈ 9px at our base size
svg.setAttribute('width',w+'px'); svg.setAttribute('height',h+'px');
svg.style.color=col(o.c);
const xml=new XMLSerializer().serializeToString(svg);
const img=new Image();
const entry={img,w,h,ready:false,error:false};
img.onload=()=>{entry.ready=true;S.dirty=true;};
img.onerror=()=>{entry.error=true;S.dirty=true;};
img.src='data:image/svg+xml;charset=utf-8,'+encodeURIComponent(xml);
mcache.set(key,entry);
return entry;
}catch(e){ const entry={error:true,w:220,h:56}; mcache.set(key,entry); return entry; }
}
/* ---------- fonts ---------- */
function fontFor(o){
if(o.t==='c') return `500 ${o.fs||14}px 'JetBrains Mono',monospace`;
if(o.f==='plain') return `500 ${o.fs}px Inter,sans-serif`;
return `600 ${o.fs}px Caveat,cursive`;
}
/* ---------- drawing ---------- */
function drawGrid(){
if(!S.grid) return;
const t=themeVals(); const step=GRID*S.cam.z;
if(step<5) return;
const x0=(S.cam.x*S.cam.z)%step, y0=(S.cam.y*S.cam.z)%step;
ctx.lineWidth=1;
for(let gx=x0-step;gx<W+step;gx+=step){
const wxi=Math.round(s2wX(gx)/GRID);
ctx.strokeStyle=(wxi%5===0)?t.grid2:t.grid;
ctx.beginPath();ctx.moveTo(gx,0);ctx.lineTo(gx,H);ctx.stroke();
}
for(let gy=y0-step;gy<H+step;gy+=step){
const wyi=Math.round(s2wY(gy)/GRID);
ctx.strokeStyle=(wyi%5===0)?t.grid2:t.grid;
ctx.beginPath();ctx.moveTo(0,gy);ctx.lineTo(W,gy);ctx.stroke();
}
}
/* ---------- Miro-quality ink: variable-width filled outline ----------
Instead of stroking segments (visible joints, uniform width), each stroke
becomes ONE filled polygon whose half-width follows pressure/velocity,
with soft tapered caps — the perfect-freehand technique, hand-rolled. */
function strokeHalfWidth(w,p){ return Math.max(w*(0.45+0.75*(p??0.5))/2, 0.34); }
function strokeOutline(pts,w,uniform){
const n=pts.length; if(n<3)return null;
// per-point direction (central difference) + tapered radius
const taperN=uniform?1:Math.min(5,Math.max(2,Math.floor(n/2)));
const left=[],right=[];
let d0x=1,d0y=0,dNx=1,dNy=0,r0=1,rN=1;
for(let i=0;i<n;i++){
const a=pts[Math.max(0,i-1)],b=pts[Math.min(n-1,i+1)],p=pts[i];
let dx=b[0]-a[0],dy=b[1]-a[1];
const len=Math.hypot(dx,dy)||1; dx/=len; dy/=len;
let r=uniform?Math.max(w*1.35,1):strokeHalfWidth(w,p[2]);
if(i<taperN) r*=Math.pow((i+1)/(taperN+1),0.55); // tip taper in
if(i>=n-taperN) r*=Math.pow((n-i)/(taperN+1),0.55); // tail taper out
r=Math.max(r,0.22);
left.push([p[0]-dy*r,p[1]+dx*r]);
right.push([p[0]+dy*r,p[1]-dx*r]);
if(i===0){d0x=dx;d0y=dy;r0=r;}
if(i===n-1){dNx=dx;dNy=dy;rN=r;}
}
const capStart=[pts[0][0]-d0x*r0*1.2, pts[0][1]-d0y*r0*1.2];
const capEnd=[pts[n-1][0]+dNx*rN*1.2, pts[n-1][1]+dNy*rN*1.2];
return [...left,capEnd,...right.reverse(),capStart];
}
function fillLoopSmooth(loop){
const n=loop.length; if(n<3)return;
ctx.beginPath();
const mx=(loop[0][0]+loop[1][0])/2,my=(loop[0][1]+loop[1][1])/2;
ctx.moveTo(w2sX(mx),w2sY(my));
for(let i=1;i<=n;i++){
const p=loop[i%n],q=loop[(i+1)%n];
ctx.quadraticCurveTo(w2sX(p[0]),w2sY(p[1]),w2sX((p[0]+q[0])/2),w2sY((p[1]+q[1])/2));
}
ctx.closePath(); ctx.fill();
}
function pathStroke(o,zoom){
const pts=o.pts; if(pts.length===0)return;
const hl=!!o.hl;
ctx.fillStyle=col(o.c);
if(hl){ const dark=document.body.dataset.theme!=='light';
ctx.globalCompositeOperation=dark?'lighter':'multiply';
ctx.globalAlpha=dark?0.5:0.42; }
if(pts.length===1){
ctx.beginPath();
ctx.arc(w2sX(pts[0][0]),w2sY(pts[0][1]),(hl?o.w*1.35:strokeHalfWidth(o.w,pts[0][2]))*zoom,0,7);
ctx.fill(); if(hl){ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';} return;
}
if(pts.length===2){
const r=(hl?o.w*1.35:strokeHalfWidth(o.w,pts[0][2]))*zoom;
ctx.strokeStyle=col(o.c); ctx.lineCap='round'; ctx.lineWidth=r*2;
ctx.beginPath(); ctx.moveTo(w2sX(pts[0][0]),w2sY(pts[0][1]));
ctx.lineTo(w2sX(pts[1][0]),w2sY(pts[1][1])); ctx.stroke(); if(hl){ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';} return;
}
const loop=strokeOutline(pts,o.w,hl);
if(loop) fillLoopSmooth(loop);
if(hl){ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';}
}
/* ---------- safe function-expression compiler (for plot blocks) ----------
Supports: + - * / ^ ( ), numbers, x, pi, e, sin cos tan asin acos atan,
sqrt abs ln log exp floor ceil sinh cosh tanh. Implicit multiplication
(2x, 3sin(x), x(x+1)) is inserted automatically. No eval — real parser. */
const PLOT_FUN={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,
sqrt:Math.sqrt,abs:Math.abs,ln:Math.log,log:Math.log10,exp:Math.exp,floor:Math.floor,ceil:Math.ceil,
sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh};
function compileExpr(src){
let s=String(src).toLowerCase().replace(/\s+/g,'').replace(/^y=/,'').replace(/^f\(x\)=/,'');
if(!s)throw new Error('empty expression');
// implicit multiplication: 2x → 2*x, )( → )*(, x( → x*(, 2sin( → 2*sin(
s=s.replace(/(\d|\)|x(?![a-z])|pi|\be)(?=(\d|\(|x(?![a-z])|[a-z]))/g,'$1*');
const tokens=s.match(/\d+\.?\d*|[a-z]+|[+\-*/^()]/g)||[];
if(tokens.join('')!==s)throw new Error('invalid characters');
const out=[],ops=[];
const prec={'+':1,'-':1,'*':2,'/':2,'^':3,'neg':4};
const rightAssoc={'^':1,'neg':1};
let prev=null;
for(const t of tokens){
if(/^\d/.test(t)) out.push(parseFloat(t));
else if(t==='x') out.push('x');
else if(t==='pi') out.push(Math.PI);
else if(t==='e') out.push(Math.E);
else if(PLOT_FUN[t]) ops.push(t);
else if(t==='('){ ops.push(t); }
else if(t===')'){
while(ops.length&&ops[ops.length-1]!=='(') out.push(ops.pop());
if(!ops.length)throw new Error('unbalanced )');
ops.pop();
if(ops.length&&PLOT_FUN[ops[ops.length-1]]) out.push(ops.pop());
}
else{ // operator
let op=t;
if(t==='-'&&(prev===null||prev==='('||/[+\-*/^]/.test(prev))) op='neg';
while(ops.length){
const top=ops[ops.length-1];
if(top==='(')break;
const tp=prec[top]??(PLOT_FUN[top]?5:0);
if(tp>prec[op]||(tp===prec[op]&&!rightAssoc[op])) out.push(ops.pop()); else break;
}
ops.push(op);
}
prev=t;
}
while(ops.length){ const op=ops.pop(); if(op==='(')throw new Error('unbalanced ('); out.push(op); }
if(!out.length)throw new Error('empty expression');
return x=>{
const st=[];
for(const t of out){
if(typeof t==='number')st.push(t);
else if(t==='x')st.push(x);
else if(t==='neg')st.push(-st.pop());
else if(PLOT_FUN[t])st.push(PLOT_FUN[t](st.pop()));
else{ const b=st.pop(),a=st.pop();
st.push(t==='+'?a+b:t==='-'?a-b:t==='*'?a*b:t==='/'?a/b:Math.pow(a,b)); }
}
return st[0];
};
}
const plotFnCache=new Map();
function plotFn(o){
if(!plotFnCache.has(o.expr)){
try{ plotFnCache.set(o.expr,compileExpr(o.expr)); }
catch(e){ plotFnCache.set(o.expr,null); }
}
return plotFnCache.get(o.expr);
}
/* Ramer–Douglas–Peucker simplification (keeps pressure of surviving points) */
function simplifyStroke(pts,eps){
if(pts.length<4)return pts;
const keep=new Uint8Array(pts.length); keep[0]=1; keep[pts.length-1]=1;
const stack=[[0,pts.length-1]];
while(stack.length){
const [a,b]=stack.pop();
let maxD=0,idx=-1;
for(let i=a+1;i<b;i++){
const d=distToSeg(pts[i][0],pts[i][1],pts[a][0],pts[a][1],pts[b][0],pts[b][1]);
if(d>maxD){maxD=d;idx=i;}
}
if(maxD>eps&&idx>0){ keep[idx]=1; stack.push([a,idx],[idx,b]); }
}
const out=[]; for(let i=0;i<pts.length;i++) if(keep[i])out.push(pts[i]);
return out;
}
function rr(x,y,w,h,r){ctx.beginPath();ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();}
function wrapText(text,maxW,font){ ctx.save(); ctx.font=font; const out=[];
for(const raw of text.split('\n')){ let line='';
for(const word of raw.split(' ')){ const t=line?line+' '+word:word;
if(ctx.measureText(t).width>maxW && line){ out.push(line); line=word; } else line=t; }
out.push(line); }
ctx.restore(); return out; }
function drawObj(o){
const z=S.cam.z, t=themeVals();
switch(o.t){
case 's': pathStroke(o,z); break;
case 'r': { ctx.strokeStyle=col(o.c); ctx.lineWidth=o.sw*z;
rr(w2sX(o.x),w2sY(o.y),o.w*z,o.h*z,Math.min(10*z,o.w*z/4,o.h*z/4)); ctx.stroke(); break; }
case 'o': { ctx.strokeStyle=col(o.c); ctx.lineWidth=o.sw*z; ctx.beginPath();
ctx.ellipse(w2sX(o.x+o.w/2),w2sY(o.y+o.h/2),Math.abs(o.w/2)*z,Math.abs(o.h/2)*z,0,0,7); ctx.stroke(); break; }
case 'a': { const x1=w2sX(o.x1),y1=w2sY(o.y1),x2=w2sX(o.x2),y2=w2sY(o.y2);
ctx.strokeStyle=col(o.c); ctx.lineWidth=o.sw*z; ctx.lineCap='round';
ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2); ctx.stroke();
if(o.head!==false){
const ang=Math.atan2(y2-y1,x2-x1), hlen=Math.max(10*z,o.sw*z*3.4);
ctx.beginPath(); ctx.moveTo(x2,y2);
ctx.lineTo(x2-hlen*Math.cos(ang-0.46),y2-hlen*Math.sin(ang-0.46));
ctx.moveTo(x2,y2);
ctx.lineTo(x2-hlen*Math.cos(ang+0.46),y2-hlen*Math.sin(ang+0.46));
ctx.stroke();
} break; }
case 'i': { const x=w2sX(o.x),y=w2sY(o.y);
let im=o._img;
if(!im){ im=o._img=new Image(); im.onload=()=>{S.dirty=true;}; im.src=o.src; }
if(im.complete&&im.naturalWidth){ ctx.imageSmoothingQuality='high'; ctx.drawImage(im,x,y,o.w*z,o.h*z); }
else { ctx.fillStyle=t.panel; rr(x,y,o.w*z,o.h*z,8*z); ctx.fill();
ctx.fillStyle=col('ink'); ctx.globalAlpha=.4; ctx.font=`600 ${13*z}px Inter`; ctx.textBaseline='middle';
ctx.fillText('🖼 loading…',x+12*z,y+o.h*z/2); ctx.globalAlpha=1; }
break; }
case 'p': { const x=w2sX(o.x),y=w2sY(o.y),pw=o.w*z,ph=o.h*z;
ctx.fillStyle=t.panel; ctx.strokeStyle=t.panelBr; ctx.lineWidth=1.2*z;
rr(x,y,pw,ph,10*z); ctx.fill(); ctx.stroke();
const fn=plotFn(o);
const pad={l:34*z,r:12*z,tp:26*z,b:22*z};
const gx0=x+pad.l,gy0=y+pad.tp,gw=pw-pad.l-pad.r,gh=ph-pad.tp-pad.b;
// expression label
ctx.fillStyle=col(o.c); ctx.font=`600 ${12.5*z}px 'JetBrains Mono',monospace`; ctx.textBaseline='top';
ctx.fillText(('y = '+o.expr).slice(0,42),x+12*z,y+8*z);
if(!fn){ ctx.fillStyle=col('red'); ctx.font=`600 ${12*z}px Inter`;
ctx.fillText('⚠ invalid expression — double-click to fix',gx0,gy0+gh/2); break; }
// sample
const N=Math.max(140,Math.floor(gw/ (1.5*z) ));
const xs=[],ys=[]; let ymin=Infinity,ymax=-Infinity;
for(let i=0;i<=N;i++){
const xv=o.xmin+(o.xmax-o.xmin)*i/N;
let yv; try{ yv=fn(xv); }catch{ yv=NaN; }
xs.push(xv); ys.push(yv);
if(isFinite(yv)){ if(yv<ymin)ymin=yv; if(yv>ymax)ymax=yv; }
}
if(!isFinite(ymin)){ ymin=-1; ymax=1; }
if(ymin===ymax){ ymin-=1; ymax+=1; }
const yr=ymax-ymin; ymin-=yr*0.08; ymax+=yr*0.08;
const mx=v=>gx0+(v-o.xmin)/(o.xmax-o.xmin)*gw;
const my=v=>gy0+gh-(v-ymin)/(ymax-ymin)*gh;
// clip graph area
ctx.save(); ctx.beginPath(); ctx.rect(gx0,gy0,gw,gh); ctx.clip();
// grid + axes
ctx.lineWidth=1; ctx.strokeStyle=t.grid2;
const stepX=niceStep(o.xmax-o.xmin), stepY=niceStep(ymax-ymin);
ctx.font=`500 ${9.5*z}px Inter`; ctx.fillStyle=col('ink'); ctx.globalAlpha=.5;
for(let vx=Math.ceil(o.xmin/stepX)*stepX; vx<=o.xmax; vx+=stepX){
ctx.beginPath(); ctx.moveTo(mx(vx),gy0); ctx.lineTo(mx(vx),gy0+gh); ctx.stroke();
ctx.fillText(fmtTick(vx),mx(vx)+2*z,gy0+gh-11*z);
}
for(let vy=Math.ceil(ymin/stepY)*stepY; vy<=ymax; vy+=stepY){
ctx.beginPath(); ctx.moveTo(gx0,my(vy)); ctx.lineTo(gx0+gw,my(vy)); ctx.stroke();
ctx.fillText(fmtTick(vy),gx0+4*z,my(vy)-11*z);
}
ctx.globalAlpha=1;
// zero axes (stronger)
ctx.strokeStyle=col('ink'); ctx.globalAlpha=.55; ctx.lineWidth=1.4;
if(0>=o.xmin&&0<=o.xmax){ ctx.beginPath(); ctx.moveTo(mx(0),gy0); ctx.lineTo(mx(0),gy0+gh); ctx.stroke(); }
if(0>=ymin&&0<=ymax){ ctx.beginPath(); ctx.moveTo(gx0,my(0)); ctx.lineTo(gx0+gw,my(0)); ctx.stroke(); }
ctx.globalAlpha=1;
// curve
ctx.strokeStyle=col(o.c); ctx.lineWidth=Math.max(2*z,1.4); ctx.lineJoin='round'; ctx.lineCap='round';
ctx.beginPath(); let pen=false;
const jumpLim=(ymax-ymin)*0.5;
for(let i=0;i<=N;i++){
const yv=ys[i];
if(!isFinite(yv)||(i>0&&isFinite(ys[i-1])&&Math.abs(yv-ys[i-1])>jumpLim)){ pen=false; continue; }
const px=mx(xs[i]),py=my(yv);
if(!pen){ ctx.moveTo(px,py); pen=true; } else ctx.lineTo(px,py);
}
ctx.stroke(); ctx.restore();
break; }
case 't': { ctx.fillStyle=col(o.c); ctx.font=fontFor(o); ctx.textBaseline='top';
ctx.save(); ctx.translate(w2sX(o.x),w2sY(o.y)); ctx.scale(z,z);
o.txt.split('\n').forEach((l,i)=>ctx.fillText(l,4,3+i*o.fs*1.3)); ctx.restore(); break; }
case 'n': { const x=w2sX(o.x),y=w2sY(o.y);
ctx.save(); ctx.shadowColor='rgba(0,0,0,.28)'; ctx.shadowBlur=14*z; ctx.shadowOffsetY=4*z;
ctx.fillStyle=NOTE_BG[o.bg]||o.bg; rr(x,y,o.w*z,o.h*z,8*z); ctx.fill(); ctx.restore();
ctx.fillStyle=t.noteInk; const fs=o.fs||20; const font=`600 ${fs}px Caveat,cursive`; ctx.font=font; ctx.textBaseline='top';
const lines=wrapText(o.txt||'',o.w-24,font);
ctx.save(); ctx.translate(x,y); ctx.scale(z,z);
lines.slice(0,Math.floor((o.h-20)/(fs*1.25))).forEach((l,i)=>ctx.fillText(l,13,12+i*fs*1.25));
ctx.restore(); break; }
case 'c': { const x=w2sX(o.x),y=w2sY(o.y);
ctx.fillStyle=t.panel; ctx.strokeStyle=t.panelBr; ctx.lineWidth=1.2*z;
rr(x,y,o.w*z,o.h*z,10*z); ctx.fill(); ctx.stroke();
ctx.fillStyle='#4ade80'; ctx.beginPath(); ctx.arc(x+16*z,y+15*z,3.4*z,0,7); ctx.fill();
ctx.fillStyle=col('ink'); const fs=o.fs||13.5; ctx.font=`500 ${fs}px 'JetBrains Mono',monospace`; ctx.textBaseline='top';
ctx.save(); ctx.translate(x,y); ctx.scale(z,z);
ctx.beginPath(); ctx.rect(0,0,o.w,o.h); ctx.clip();
(o.txt||'').split('\n').slice(0,Math.floor((o.h-24)/(fs*1.55))).forEach((l,i)=>ctx.fillText(l,14,30+i*fs*1.55));
ctx.restore(); break; }
case 'm': { const entry=renderMath(o); const d=mathDim(o);
const x=w2sX(o.x),y=w2sY(o.y);
// panel behind, like the reference
ctx.fillStyle=t.panel; rr(x-MPAD*S.cam.z,y-MPAD*S.cam.z,(d.w+MPAD*2)*S.cam.z/1,(d.h+MPAD*2)*S.cam.z/1,10*S.cam.z);
ctx.fill();
if(entry&&entry.ready){ ctx.imageSmoothingQuality='high'; ctx.drawImage(entry.img,x,y,d.w*S.cam.z,d.h*S.cam.z); }
else { ctx.fillStyle=col('ink'); ctx.globalAlpha=.45; ctx.font=`600 ${15*S.cam.z}px Inter`; ctx.textBaseline='middle';
ctx.fillText(entry&&entry.error?'⚠ LaTeX error — double-click to fix':'∑ rendering…',x+8*S.cam.z,y+d.h*S.cam.z/2); ctx.globalAlpha=1; }
break; }
}
}
function drawSelection(){
if(S.sel.size===0)return;
const b=selBounds(); if(!b)return;
const x=w2sX(b.x),y=w2sY(b.y),w=b.w*S.cam.z,h=b.h*S.cam.z;
ctx.strokeStyle='#2dd4bf'; ctx.lineWidth=1.4; ctx.setLineDash([5,4]);
ctx.strokeRect(x-4,y-4,w+8,h+8); ctx.setLineDash([]);
for(const [hx,hy] of handles(b)){
ctx.fillStyle='#2dd4bf'; ctx.strokeStyle=themeVals().bg; ctx.lineWidth=2;
ctx.beginPath(); ctx.arc(w2sX(hx),w2sY(hy),5.5,0,7); ctx.fill(); ctx.stroke();
}
}
const handles=b=>[[b.x,b.y],[b.x+b.w,b.y],[b.x,b.y+b.h],[b.x+b.w,b.y+b.h]];
let marquee=null, tempObj=null, eraserPt=null, penPt=null;
function drawPenDot(){
if(!penPt||(S.tool!=='pen'&&S.tool!=='hl'))return;
const hl=S.tool==='hl';
const r=Math.max((hl?S.size*1.35:strokeHalfWidth(S.size,0.62))*S.cam.z,1.5);
ctx.beginPath(); ctx.arc(penPt.x,penPt.y,r,0,7);
ctx.fillStyle=col(S.color); ctx.globalAlpha=hl?.4:.85; ctx.fill();
ctx.globalAlpha=1;
}
function frame(){
const t=themeVals();
ctx.setTransform(DPR,0,0,DPR,0,0);
ctx.fillStyle=t.bg; ctx.fillRect(0,0,W,H);
drawGrid();
// highlighters render ON TOP with blend modes (multiply on light, additive
// on dark) — content stays readable underneath, just like a real marker
for(const o of S.objects) if(!(o.t==='s'&&o.hl)) drawObj(o);
for(const o of S.objects) if(o.t==='s'&&o.hl) drawObj(o);
if(tempObj) drawObj(tempObj);
drawSelection();
if(marquee){ ctx.fillStyle='rgba(45,212,191,.08)'; ctx.strokeStyle='rgba(45,212,191,.7)'; ctx.lineWidth=1;
const x=Math.min(marquee.x1,marquee.x2),y=Math.min(marquee.y1,marquee.y2),w=Math.abs(marquee.x2-marquee.x1),h=Math.abs(marquee.y2-marquee.y1);
ctx.fillRect(x,y,w,h); ctx.strokeRect(x,y,w,h); }
if(eraserPt){ ctx.strokeStyle=col('ink'); ctx.globalAlpha=.5; ctx.lineWidth=1.3;
ctx.beginPath(); ctx.arc(eraserPt.x,eraserPt.y,12,0,7); ctx.stroke(); ctx.globalAlpha=1; }
drawPenDot();
}
function render(){
requestAnimationFrame(render);
if(!S.dirty) return; S.dirty=false;
if(liveSnap&&tempObj&&drag&&drag.k==='draw'){
// fast path while inking: blit the cached scene, draw ONLY the live stroke —
// constant-time per frame no matter how full the board is (Miro-level latency)
ctx.setTransform(1,0,0,1,0,0);
ctx.drawImage(liveSnap,0,0);
ctx.setTransform(DPR,0,0,DPR,0,0);
drawObj(tempObj);
drawPenDot();
return;
}
frame();
}
/* ---------- hit testing ---------- */
function hitStroke(o,wx,wy,tol){ const p=o.pts; const ww=o.hl?o.w*1.6:o.w;
for(let i=0;i<p.length-1;i++){ if(distToSeg(wx,wy,p[i][0],p[i][1],p[i+1][0],p[i+1][1])<tol+ww)return true; }
return p.length===1 && dist(wx,wy,p[0][0],p[0][1])<tol+ww; }
function distToSeg(px,py,x1,y1,x2,y2){ const dx=x2-x1,dy=y2-y1; const l2=dx*dx+dy*dy;
if(l2===0)return dist(px,py,x1,y1); let t=((px-x1)*dx+(py-y1)*dy)/l2; t=clamp(t,0,1);
return dist(px,py,x1+t*dx,y1+t*dy); }
function hitObj(o,wx,wy){
const tol=8/S.cam.z;
if(o.t==='s') return hitStroke(o,wx,wy,tol);
if(o.t==='a') return distToSeg(wx,wy,o.x1,o.y1,o.x2,o.y2)<tol+o.sw;
const b=bounds(o);
if(o.t==='r'){ const inside=wx>b.x-tol&&wx<b.x+b.w+tol&&wy>b.y-tol&&wy<b.y+b.h+tol;
const inner=wx>b.x+tol&&wx<b.x+b.w-tol&&wy>b.y+tol&&wy<b.y+b.h-tol; return inside&&!inner; }
if(o.t==='o'){ const cx=b.x+b.w/2,cy=b.y+b.h/2,rx=b.w/2,ry=b.h/2;
const v=((wx-cx)/rx)**2+((wy-cy)/ry)**2; return v>0.72&&v<1.32; }
return wx>=b.x&&wx<=b.x+b.w&&wy>=b.y&&wy<=b.y+b.h;
}
function topHit(wx,wy){ for(let i=S.objects.length-1;i>=0;i--){ if(hitObj(S.objects[i],wx,wy)) return S.objects[i]; } return null; }
/* ---------- undo (baseline = last committed state) ---------- */
const CLEAN=(k,v)=>String(k).startsWith('_')?undefined:v;
let baseline='[]';
function commit(){
S.undo.push(baseline);
baseline=JSON.stringify(S.objects,CLEAN);
if(S.undo.length>80)S.undo.shift();
S.redo.length=0; saveSoon(); refreshUR();
}
function undo(){ if(!S.undo.length)return; S.redo.push(baseline); baseline=S.undo.pop();
S.objects=JSON.parse(baseline); S.sel.clear(); S.dirty=true; saveSoon(); refreshUR(); }
function redo(){ if(!S.redo.length)return; S.undo.push(baseline); baseline=S.redo.pop();
S.objects=JSON.parse(baseline); S.sel.clear(); S.dirty=true; saveSoon(); refreshUR(); }
function refreshUR(){ $('#undo-btn').disabled=!S.undo.length; $('#redo-btn').disabled=!S.redo.length; }
/* ---------- persistence ---------- */
const LS_REG='slate.boards.v1', LS_B='slate.b.';
function loadRegistry(){ try{return JSON.parse(store.get(LS_REG))||[];}catch{return[];} }
function saveRegistry(r){ store.set(LS_REG,JSON.stringify(r)); }
let saveT=null;
function saveSoon(){ $('#saved').style.opacity=.4; clearTimeout(saveT); saveT=setTimeout(saveNow,450); }
// never lose the last edit: flush pending saves when the tab hides/closes
addEventListener('pagehide',()=>{ clearTimeout(saveT); saveNow(); });
addEventListener('visibilitychange',()=>{ if(document.visibilityState==='hidden'){ clearTimeout(saveT); saveNow(); } });
function saveNow(){
if(!S.boardId)return;
const wrote=store.set(LS_B+S.boardId,JSON.stringify(serializableBoard(),CLEAN));
const reg=loadRegistry(); const e=reg.find(b=>b.id===S.boardId);
if(e){ e.name=S.boardName; e.up=now();
reg.splice(reg.indexOf(e),1); reg.unshift(e); } // last-used board boots first next time
saveRegistry(reg);
$('#saved').style.opacity=1;
if(!wrote) toast('⚠ Storage full — export a backup');
}
/* accept v3 {objects,cam}, legacy v2 {pages:[{objects,cam}]}, or v1 {objects,cam}.
v2 notebooks flatten onto one canvas: pages are stacked with a small gap so
nothing overlaps (the notebook page system was removed from the engine). */
function normBoard(d){
const cam=d.cam||{x:0,y:0,z:1};
if(Array.isArray(d.pages)&&d.pages.length){
const GAP=48; let objs=[], prevBottom=null;
for(const p of d.pages){
const o2=Array.isArray(p.objects)?JSON.parse(JSON.stringify(p.objects,CLEAN)):[];
if(o2.length){
const b=contentBoundsOf(o2,0);
let dy=0;
if(prevBottom!=null) dy=prevBottom-b.y+GAP;
for(const o of o2) offsetObjY(o,dy);
prevBottom=b.y+b.h+dy;
}
objs=objs.concat(o2);
}
return {objects:objs,cam:{x:0,y:0,z:1}};
}
return {objects:Array.isArray(d.objects)?d.objects:[],cam};
}
function offsetObjY(o,dy){
if(!dy)return;
if(o.t==='s') o.pts=o.pts.map(p=>[p[0],p[1]+dy,p[2]]);
else if(o.t==='a'){ o.y1+=dy; o.y2+=dy; }
else o.y+=dy;
}
function openBoard(id){
saveNow();
const raw=store.get(LS_B+id); if(!raw)return;
const d=JSON.parse(raw);
const bd=normBoard(d);
S.boardId=id; S.boardName=d.name;
S.objects=bd.objects; S.cam=bd.cam;
S.pdfs=Array.isArray(d.pdfs)?d.pdfs:null;
pdfRehydrateP=null;
S.sel.clear(); S.undo=[]; S.redo=[]; baseline=JSON.stringify(S.objects,CLEAN); S.dirty=true;
$('#bname').value=S.boardName; zlabel(); refreshUR(); closePops();
rehydratePdfImages();
}
function newBoard(name,objects,pdfs){
const id='b'+Math.random().toString(36).slice(2,9);
const reg=loadRegistry(); reg.unshift({id,name,up:now()}); saveRegistry(reg);
S.pdfs=Array.isArray(pdfs)?pdfs:null;
store.set(LS_B+id,JSON.stringify({v:3,name,objects:objects||[],cam:{x:0,y:0,z:1},pdfs:S.pdfs},CLEAN));
return id;
}
function deleteBoard(id){
const reg=loadRegistry().filter(b=>b.id!==id); saveRegistry(reg); store.rm(LS_B+id);
if(id===S.boardId){ if(reg.length)openBoard(reg[0].id); else { const nid=newBoard('My board',[]); openBoard(nid);} }
renderBoardsMenu();
}
/* ---------- welcome content ---------- */
function welcomeObjects(){
return [
{t:'t',id:uid(),x:60,y:40,txt:'Welcome to Slate ✎',c:'ink',fs:44,f:'hand'},
{t:'t',id:uid(),x:64,y:110,txt:'Your personal math whiteboard — boards save in this browser automatically.',c:'ink',fs:24,f:'hand'},
{t:'m',id:uid(),x:100,y:210,latex:'\\frac{d}{dx}\\left(3x^2+5x-7\\right)=6x+5',s:1,c:'ink'},
{t:'t',id:uid(),x:104,y:320,txt:'M math · X plot · P pen · L highlighter · I image · draw a circle and HOLD to snap ✨',c:'teal',fs:22,f:'hand'},
{t:'t',id:uid(),x:104,y:360,txt:'⤓ Import a PDF from the Export menu — pages land on your canvas, design intact',c:'purple',fs:22,f:'hand'},
{t:'n',id:uid(),x:660,y:56,w:210,h:150,txt:'Sticky notes for ideas — N to add one',bg:'amber',fs:20},
{t:'p',id:uid(),x:640,y:250,w:330,h:250,expr:'sin(x)*x',xmin:-10,xmax:10,c:'teal'},
];
}
/* ---------- tools & toolbar ---------- */
const ICON={
select:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M5 3l6 16 2.4-6.4L20 10 5 3z" stroke-linejoin="round"/></svg>',
hand:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M7 11V5.5a1.5 1.5 0 013 0V10m0-5.5v-1a1.5 1.5 0 013 0V10m0-4.5a1.5 1.5 0 013 0V12m0-3a1.5 1.5 0 013 0v5c0 4-3 7-7 7-3.5 0-5-1.5-7.5-6l-1.2-2.3c-.5-1 .8-2.2 1.9-1.4L7 13" stroke-linecap="round" stroke-linejoin="round"/></svg>',
pen:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 20l1-4L16.5 4.5a2.1 2.1 0 013 3L8 19l-4 1z" stroke-linejoin="round"/><path d="M13.5 7.5l3 3"/></svg>',
eraser:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M8 20l-4.5-4.5a1.7 1.7 0 010-2.4L12 4.6a1.7 1.7 0 012.4 0l5 5a1.7 1.7 0 010 2.4L12 19.5" stroke-linejoin="round"/><path d="M8 20h12"/></svg>',
hl:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M9.5 13.5l-4 4L4 21l3.5-1.5 4-4M8 12l7.5-7.5a2 2 0 013 2.6L11 15z" stroke-linejoin="round"/><path d="M3 21h8" opacity=".5"/></svg>',
image:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><circle cx="9" cy="10" r="1.8"/><path d="M4 18l5-5 3.5 3.5L16 13l4 4" stroke-linejoin="round"/></svg>',
plot:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 4v16h16"/><path d="M6 15c3-8 5 4 7-3s3-4 5-7" stroke-linecap="round"/></svg>',
rect:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="4" y="6" width="16" height="12" rx="2"/></svg>',
ellipse:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><ellipse cx="12" cy="12" rx="8.5" ry="6.5"/></svg>',
arrow:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M5 19L19 5M19 5h-7M19 5v7" stroke-linecap="round" stroke-linejoin="round"/></svg>',
text:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M5 6V4h14v2M12 4v16m-3 0h6" stroke-linecap="round"/></svg>',
note:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 5.5A1.5 1.5 0 015.5 4h13A1.5 1.5 0 0120 5.5V14l-6 6H5.5A1.5 1.5 0 014 18.5v-13z"/><path d="M14 20v-6h6"/></svg>',
code:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M9 6l-6 6 6 6M15 6l6 6-6 6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
math:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M18 5H8l6 7-6 7h10M4 19h.01" stroke-linecap="round" stroke-linejoin="round"/></svg>',
};
const TOOLS=[
['select','Select','V'],['hand','Hand','H'],['pen','Pen','P'],['hl','Mark','L'],['eraser','Eraser','E'],
['rect','Rect','R'],['ellipse','Ellipse','O'],['arrow','Arrow','A'],
['text','Text','T'],['note','Note','N'],['code','Code','C'],['math','Math','M'],
['image','Image','I'],['plot','Plot','X'],
];
function buildToolbar(){
const holder=$('#tools');
for(const [id,label,key] of TOOLS){
const b=document.createElement('button');
b.className='tool'; b.id='tool-'+id; b.title=`${label} (${key})`;
b.innerHTML=`${ICON[id]}<small>${key}</small>`;
b.onclick=()=>setTool(id);
holder.appendChild(b);
}
const dots=$('#dots');
for(const key of Object.keys(PAL)){
const d=document.createElement('button');
d.className='dot'; d.dataset.k=key;
d.style.background = key==='ink' ? 'linear-gradient(135deg,#f2f2f0 50%,#1c1c1c 50%)' : PAL[key];
d.title=key; d.onclick=()=>{ S.color=key; refreshDots(); applyColorToSelection(); };
dots.appendChild(d);
}
refreshDots();
}
function refreshDots(){ document.querySelectorAll('.dot').forEach(d=>d.classList.toggle('on',d.dataset.k===S.color)); }
function setTool(id){ S.tool=id; document.querySelectorAll('.tool').forEach(b=>b.classList.toggle('on',b.id==='tool-'+id));
cv.style.cursor = id==='hand'?'grab' : id==='select'?'default' : id==='text'?'text' : id==='eraser'?'none':'crosshair';
if(id!=='eraser'){eraserPt=null;}
if(id!=='pen'&&id!=='hl'){penPt=null;}
S.dirty=true;
if(id==='math') openMathSheet(null);
if(id==='plot') openPlotSheet(null);
if(id==='image') pickImage(null);
}
function applyColorToSelection(){ if(!S.sel.size)return; let ch=false;
for(const id of S.sel){ const o=objById(id); if(!o)continue;
if(o.t==='n'){o.bg=S.color;} else o.c=S.color; ch=true; }
if(ch){commit();S.dirty=true;} }
/* ---------- pointer input ---------- */
let drag=null; const pointers=new Map(); let pinch=null; let spaceDown=false;
let penState=null; // live ink smoothing state
let activePen=null; // pointerId of an active stylus (palm rejection)
let liveSnap=null; // cached scene bitmap for O(1) live drawing
cv.addEventListener('pointerdown',onDown); cv.addEventListener('pointermove',onMove);
addEventListener('pointerup',onUp); addEventListener('pointercancel',onUp);
function snap(v){ return S.snap?Math.round(v/GRID)*GRID:v; }
/* Simulated pressure from speed (mouse/finger): fast = lighter, like a marker. */
function velocityPressure(e){
if(!penState)return 0.55;
const dt=Math.max(e.timeStamp-penState.lastT,1);
const d=dist(e.clientX,e.clientY,penState.lastX,penState.lastY);
const v=d/dt; // px per ms
penState.lastT=e.timeStamp; penState.lastX=e.clientX; penState.lastY=e.clientY;
return clamp(0.92-v*0.16,0.28,0.92);
}
function snapScene(){
const c=document.createElement('canvas'); c.width=cv.width; c.height=cv.height;
c.getContext('2d').drawImage(cv,0,0); return c;
}
function onDown(e){
// palm rejection: while a stylus is down, ignore stray touches
if(e.pointerType==='touch'&&activePen!=null)return;
if(e.pointerType==='pen')activePen=e.pointerId;
cv.setPointerCapture(e.pointerId);
pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(pointers.size===2){ // pinch start
const [a,b]=[...pointers.values()];
pinch={d:dist(a.x,a.y,b.x,b.y),cx:(a.x+b.x)/2,cy:(a.y+b.y)/2};
drag=null; tempObj=null; liveSnap=null; return;
}
const sx=e.clientX,sy=e.clientY, wx=s2wX(sx),wy=s2wY(sy);
closePops();
if(spaceDown||e.button===1||S.tool==='hand'){ drag={k:'pan',sx,sy,cx:S.cam.x,cy:S.cam.y}; cv.style.cursor='grabbing'; return; }
if(e.button===2)return;
switch(S.tool){
case 'pen': case 'hl': {
if(S.sel.size){S.sel.clear();}
frame(); // ensure the canvas shows the exact current scene…
liveSnap=snapScene(); // …then cache it: live drawing becomes O(1) per frame
const p0=e.pointerType==='pen'?(e.pressure||0.5):0.7;
penState={sx:wx,sy:wy,sp:p0,lastT:e.timeStamp,lastX:sx,lastY:sy,type:e.pointerType,
lastProgressT:e.timeStamp,lpX:sx,lpY:sy,downT:e.timeStamp};
tempObj={t:'s',id:uid(),pts:[[wx,wy,p0]],c:S.color,w:S.size};
if(S.tool==='hl')tempObj.hl=true;
drag={k:'draw'}; break; }
case 'image': pickImage({x:wx,y:wy}); break;
case 'plot': openPlotSheet(null,{x:wx,y:wy}); break;
case 'eraser': drag={k:'erase',removed:false}; eraseAt(wx,wy); break;
case 'rect': case 'ellipse':
tempObj={t:S.tool==='rect'?'r':'o',id:uid(),x:snap(wx),y:snap(wy),w:1,h:1,c:S.color,sw:Math.max(2,S.size)};
drag={k:'size',ox:snap(wx),oy:snap(wy)}; break;
case 'arrow':
tempObj={t:'a',id:uid(),x1:snap(wx),y1:snap(wy),x2:wx,y2:wy,c:S.color,sw:Math.max(2,S.size)};
drag={k:'arrow'}; break;
case 'text': createText(wx,wy); break;
case 'note': {
const o={t:'n',id:uid(),x:snap(wx),y:snap(wy),w:210,h:150,txt:'',bg:S.color==='ink'?'amber':S.color,fs:20};
S.objects.push(o); commit(); S.sel=new Set([o.id]); S.dirty=true; setTool('select'); editTextObj(o); break; }
case 'code': {
const o={t:'c',id:uid(),x:snap(wx),y:snap(wy),w:320,h:150,txt:'',fs:13.5};
S.objects.push(o); commit(); S.sel=new Set([o.id]); S.dirty=true; setTool('select'); editTextObj(o); break; }
case 'math': openMathSheet(null,{x:wx,y:wy}); break;
case 'select': selectDown(e,sx,sy,wx,wy); break;
}
S.dirty=true;
}
function selectDown(e,sx,sy,wx,wy){
// resize handle?
if(S.sel.size){ const b=selBounds();
for(let i=0;i<4;i++){ const [hx,hy]=handles(b)[i];
if(dist(sx,sy,w2sX(hx),w2sY(hy))<10){ drag={k:'resize',h:i,b:{...b},orig:snapshotSel()}; return; } } }
const hit=topHit(wx,wy);
if(hit){
if(!S.sel.has(hit.id)){ S.sel=e.shiftKey?new Set([...S.sel,hit.id]):new Set([hit.id]); }
else if(e.shiftKey){ S.sel.delete(hit.id); }
drag={k:'move',wx,wy,orig:snapshotSel(),moved:false};
} else {
if(!e.shiftKey) S.sel.clear();
marquee={x1:sx,y1:sy,x2:sx,y2:sy};
drag={k:'marquee'};
}
}