-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.jsx
More file actions
1574 lines (1505 loc) · 89.2 KB
/
app.jsx
File metadata and controls
1574 lines (1505 loc) · 89.2 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
const {useState,useEffect,useRef,useCallback,useMemo}=React;
/* ═══════════════════════════════════════════════════════════════
CONSTANTS
═══════════════════════════════════════════════════════════════ */
const SCHEMA_VERSION=1; // bump if notebook/section/page shape changes; used for safe migrations
const NB_COLORS=["#7c6ef0","#e05a9f","#e89020","#1cb888","#3b82f6","#9061e0","#e54545","#14b8a6","#d96830","#64748b"];
const FONT_SIZES=[{l:"10",v:"1"},{l:"12",v:"2"},{l:"14",v:"3"},{l:"16",v:"4"},{l:"18",v:"5"},{l:"24",v:"6"},{l:"32",v:"7"}];
const HEADINGS=[{l:"Normal",v:"div"},{l:"H1",v:"h1"},{l:"H2",v:"h2"},{l:"H3",v:"h3"},{l:"H4",v:"h4"}];
const TXT_COLORS=["#000000","#374151","#dc2626","#ea580c","#ca8a04","#16a34a","#2563eb","#7c3aed","#db2777","#ffffff"];
const HL_COLORS=["transparent","#fef08a","#bbf7d0","#bfdbfe","#e9d5ff","#fecdd3","#fed7aa","#ccfbf1","#e2e8f0"];
const IMG_MAX_INLINE_BYTES=5*1024*1024; // 5 MB hard cap on pasted images before downscale attempt
const IMG_DOWNSCALE_TARGET_WIDTH=1600;
const IMG_DOWNSCALE_QUALITY=0.85;
const uid=()=>"id-"+Date.now().toString(36)+Math.random().toString(36).substr(2,6);
const THEMES={
dark:{
"--bg":"#0e0e16","--surface":"#161622","--surface-alt":"#1c1c2c",
"--border":"#282840","--border-light":"#32324a",
"--text":"#e4e4f0","--text-secondary":"#8585a0","--text-muted":"#52526a",
"--accent":"#7c6ef0","--accent-bg":"rgba(124,110,240,.12)","--accent-hover":"#6359d0",
"--hover":"rgba(255,255,255,.04)","--shadow":"rgba(0,0,0,.5)",
"--editor-bg":"#111119","--code-bg":"#1a1a28",
"--scrollbar":"#32324a","--scrollbar-hover":"#444468",
"--danger":"#f87171","--success":"#34d399","--warning":"#fbbf24",
"--nav-bg":"#111118",
},
light:{
"--bg":"#f6f5f0","--surface":"#ffffff","--surface-alt":"#f0efe8",
"--border":"#ddd8ce","--border-light":"#eae6dc",
"--text":"#1a1a1a","--text-secondary":"#606058","--text-muted":"#9a9a88",
"--accent":"#6359d0","--accent-bg":"rgba(99,89,208,.09)","--accent-hover":"#4f42b5",
"--hover":"rgba(0,0,0,.035)","--shadow":"rgba(0,0,0,.06)",
"--editor-bg":"#fcfcfa","--code-bg":"#f0efe8",
"--scrollbar":"#c8c4b8","--scrollbar-hover":"#a8a498",
"--danger":"#e54545","--success":"#1cb888","--warning":"#e89020",
"--nav-bg":"#eceade",
}
};
const DEFAULT_DATA={notebooks:[{
id:"nb-1",name:"My Notebook",color:"#7c6ef0",sections:[{
id:"sec-1",name:"General",color:"#7c6ef0",pages:[{
id:"page-1",title:"Welcome to NoteForge",
content:`<h2>Welcome to NoteForge</h2>
<p>Your encrypted, offline note-taking app.</p>
<h3>Features</h3>
<ul>
<li><strong>AES-256 encryption</strong> — protect all notes with a master password</li>
<li><strong>Notebook locks</strong> — individual password per notebook</li>
<li>Rich text: <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strike</s></li>
<li>Headings, lists, tables, code blocks, links</li>
<li>Paste images, checklists, find & replace</li>
</ul>
<h3>Shortcuts</h3>
<ul>
<li><code>Ctrl+B/I/U</code> — Bold/Italic/Underline</li>
<li><code>Ctrl+F</code> — Find & Replace</li>
<li><code>Ctrl+D</code> — Duplicate page</li>
<li><code>Ctrl+P</code> — Print</li>
<li><code>Ctrl+Shift+E</code> — Export HTML</li>
</ul>
<p>Go to <strong>File → Encryption Settings</strong> to enable master encryption.</p>`,
created:Date.now(),modified:Date.now(),pinned:false,deleted:false
}]
}]
}]};
/* ═══════════════════════════════════════════════════════════════
STORAGE
═══════════════════════════════════════════════════════════════ */
const store={
async get(){
try{
if(window.electronAPI)return await window.electronAPI.storageGet();
const v=localStorage.getItem("noteforge-data");
return v?{value:v}:null;
}catch{return null}
},
async set(val){
try{
if(window.electronAPI)return await window.electronAPI.storageSet(val);
localStorage.setItem("noteforge-data",val);return true;
}catch{return false}
}
};
const prefsStore={
load(){try{return JSON.parse(localStorage.getItem("noteforge-prefs")||"{}")}catch{return{}}},
save(p){try{localStorage.setItem("noteforge-prefs",JSON.stringify(p))}catch{}}
};
/* ═══════════════════════════════════════════════════════════════
UTILITIES
═══════════════════════════════════════════════════════════════ */
const snippet=(html)=>html?decodeEntities(html.replace(/<[^>]*>/g," ")).replace(/\s+/g," ").trim().slice(0,80):"";
const escHtml=(s)=>s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");
const hasElectronCrypto=()=>!!(window.electronAPI?.checkEncryption);
// Decode HTML entities using the browser's built-in parser — safe because we read textContent only
let _entityDecoder=null;
function decodeEntities(s){
if(!s)return s;
if(!_entityDecoder)_entityDecoder=document.createElement("textarea");
_entityDecoder.innerHTML=s;
return _entityDecoder.value;
}
/* ── HTML Sanitization (DOMPurify) ─────────────────────────────
Strips script tags, event handlers, javascript: URLs, etc.
Applied before any HTML is set as innerHTML.
Additional hook: restrict <input type=...> to checkbox only, so a malicious
paste can't inject <input type="password"> for in-note phishing. */
let _dompurifyHookInstalled=false;
function installDOMPurifyHook(){
if(_dompurifyHookInstalled||!window.DOMPurify)return;
window.DOMPurify.addHook("uponSanitizeAttribute",(node,data)=>{
if(node.nodeName==="INPUT"&&data.attrName==="type"){
if(String(data.attrValue).toLowerCase()!=="checkbox")data.keepAttr=false;
}
});
_dompurifyHookInstalled=true;
}
const sanitizeHTML=(html)=>{
if(!html)return html;
if(window.DOMPurify){
installDOMPurifyHook();
return window.DOMPurify.sanitize(html,{
ALLOWED_TAGS:["h1","h2","h3","h4","p","br","strong","b","em","i","u","s","del",
"ul","ol","li","blockquote","pre","code","table","thead","tbody","tr","td","th",
"a","img","hr","div","span","label","input","sub","sup","font"],
ALLOWED_ATTR:["href","src","title","alt","style","class","id","type","checked",
"for","color","size","face","target","width","height","colspan","rowspan"],
FORBID_TAGS:["script","iframe","object","embed","form","textarea","select","button","meta","link","base"],
FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur","onchange",
"onsubmit","onkeydown","onkeyup","onkeypress","onmousedown","onmouseup",
"onauxclick","onpointerdown","onpointerup","onwheel","onbeforeinput","oninput","onpaste"],
ALLOW_DATA_ATTR:false,
});
}
// Fallback if DOMPurify not loaded — strip obvious dangerous patterns
return html
.replace(/<script[\s\S]*?<\/script>/gi,"")
.replace(/<iframe[\s\S]*?<\/iframe>/gi,"")
.replace(/<object[\s\S]*?<\/object>/gi,"")
.replace(/<embed[\s\S]*?>/gi,"")
.replace(/\bon\w+\s*=/gi,"data-removed=")
.replace(/javascript\s*:/gi,"removed:");
};
/* ── CRITICAL: Sanitize data before ANY write to disk ──────────
Strips plaintext sections from ALL locked notebooks.
This is the mandatory safety net — no conditions, no exceptions.
Called by persist() and the beforeunload emergency flush. */
function sanitizeForDiskSync(data){
if(!data?.notebooks)return data;
return{...data,notebooks:data.notebooks.map(nb=>{
if(!nb.locked)return nb;
// Locked notebook: NEVER write plaintext sections to disk
return{...nb,sections:[]};
})};
}
/* ── Image downscale helper ────────────────────────────────────
Large pasted photos are resized to IMG_DOWNSCALE_TARGET_WIDTH and
re-encoded as JPEG. Keeps the encrypted data file lean. */
function downscaleImage(file, maxBytes){
return new Promise((resolve,reject)=>{
if(file.size>IMG_MAX_INLINE_BYTES){
return reject(new Error(`Image is ${(file.size/1048576).toFixed(1)} MB — over the 5 MB inline limit.`));
}
const reader=new FileReader();
reader.onerror=()=>reject(new Error("Could not read image"));
reader.onload=(ev)=>{
const img=new Image();
img.onerror=()=>reject(new Error("Could not decode image"));
img.onload=()=>{
// If already small enough, use original
if(file.size<=(maxBytes||512000)){return resolve(ev.target.result)}
// Downscale to target width, preserving aspect ratio
const scale=Math.min(1,IMG_DOWNSCALE_TARGET_WIDTH/img.width);
const w=Math.round(img.width*scale),h=Math.round(img.height*scale);
const canvas=document.createElement("canvas");
canvas.width=w;canvas.height=h;
const ctx=canvas.getContext("2d");
ctx.drawImage(img,0,0,w,h);
const mime=file.type==="image/png"?"image/png":"image/jpeg";
try{
const dataUrl=canvas.toDataURL(mime,IMG_DOWNSCALE_QUALITY);
resolve(dataUrl);
}catch(e){reject(new Error("Could not compress image"))}
};
img.src=ev.target.result;
};
reader.readAsDataURL(file);
});
}
/* ═══════════════════════════════════════════════════════════════
MODAL DIALOGS — replace native alert/confirm/prompt for consistent UX
═══════════════════════════════════════════════════════════════ */
function ConfirmDialog({title,message,confirmLabel,confirmStyle,onConfirm,onCancel,dark}){
const ref=useRef(null);
useEffect(()=>{ref.current?.focus()},[]);
return <div className="nf-modal-overlay" onMouseDown={e=>{if(e.target===e.currentTarget)onCancel()}}>
<div className="nf-modal" style={dark?THEMES.dark:THEMES.light} onMouseDown={e=>e.stopPropagation()}>
<h3>{title}</h3>
<p>{message}</p>
<div className="nf-modal-actions">
<button className="nf-modal-btn secondary" onClick={onCancel}>Cancel</button>
<button ref={ref} className={`nf-modal-btn ${confirmStyle||"primary"}`} onClick={onConfirm}
onKeyDown={e=>{if(e.key==="Enter")onConfirm();if(e.key==="Escape")onCancel()}}>{confirmLabel||"OK"}</button>
</div>
</div>
</div>;
}
function PromptDialog({title,message,placeholder,defaultValue,confirmLabel,onConfirm,onCancel,dark}){
const [val,setVal]=useState(defaultValue||"");
const ref=useRef(null);
useEffect(()=>{ref.current?.focus();ref.current?.select()},[]);
return <div className="nf-modal-overlay" onMouseDown={e=>{if(e.target===e.currentTarget)onCancel()}}>
<div className="nf-modal" style={dark?THEMES.dark:THEMES.light} onMouseDown={e=>e.stopPropagation()}>
<h3>{title}</h3>
{message&&<p>{message}</p>}
<input ref={ref} className="nf-modal-input" placeholder={placeholder||""} value={val}
onChange={e=>setVal(e.target.value)}
onKeyDown={e=>{if(e.key==="Enter")onConfirm(val);if(e.key==="Escape")onCancel()}}/>
<div className="nf-modal-actions">
<button className="nf-modal-btn secondary" onClick={onCancel}>Cancel</button>
<button className="nf-modal-btn primary" onClick={()=>onConfirm(val)}>{confirmLabel||"OK"}</button>
</div>
</div>
</div>;
}
function AlertDialog({title,message,dark,onClose}){
const ref=useRef(null);
useEffect(()=>{ref.current?.focus()},[]);
return <div className="nf-modal-overlay" onMouseDown={e=>{if(e.target===e.currentTarget)onClose()}}>
<div className="nf-modal" style={dark?THEMES.dark:THEMES.light} onMouseDown={e=>e.stopPropagation()}>
<h3>{title}</h3>
<p>{message}</p>
<div className="nf-modal-actions">
<button ref={ref} className="nf-modal-btn primary" onClick={onClose}
onKeyDown={e=>{if(e.key==="Enter"||e.key==="Escape")onClose()}}>OK</button>
</div>
</div>
</div>;
}
function ShortcutsDialog({onClose,dark}){
const ref=useRef(null);
useEffect(()=>{ref.current?.focus()},[]);
const rows=[
["Ctrl+N","New Page"],["Ctrl+Shift+N","New Notebook"],
["Ctrl+B / I / U","Bold / Italic / Underline"],["Ctrl+D","Duplicate Page"],
["Ctrl+F","Find & Replace"],["Ctrl+L","Lock App"],
["Ctrl+Z / Ctrl+Y","Undo / Redo"],["Ctrl+= / Ctrl+-","Zoom In / Out"],
["Ctrl+\\","Toggle Sidebar"],["Ctrl+Shift+D","Toggle Theme"],
["Ctrl+P","Print"],["Ctrl+Shift+E","Export HTML"],["F1","This dialog"],
];
return <div className="nf-modal-overlay" onMouseDown={e=>{if(e.target===e.currentTarget)onClose()}}>
<div className="nf-modal" style={{...(dark?THEMES.dark:THEMES.light),width:440}}
onMouseDown={e=>e.stopPropagation()}>
<h3>Keyboard Shortcuts</h3>
<div ref={ref} tabIndex={-1} style={{outline:"none",marginTop:10,maxHeight:"60vh",overflowY:"auto"}}
onKeyDown={e=>{if(e.key==="Escape"||e.key==="Enter")onClose()}}>
<table style={{width:"100%",borderCollapse:"collapse",fontSize:12.5}}>
<tbody>
{rows.map(([k,v])=><tr key={k}>
<td style={{padding:"4px 8px 4px 0",whiteSpace:"nowrap"}}>
<kbd style={{fontFamily:"'JetBrains Mono',monospace",fontSize:11,padding:"2px 6px",
background:"var(--code-bg)",border:"1px solid var(--border)",borderRadius:4}}>{k}</kbd>
</td>
<td style={{padding:"4px 0",color:"var(--text-secondary)"}}>{v}</td>
</tr>)}
</tbody>
</table>
</div>
<div className="nf-modal-actions"><button className="nf-modal-btn primary" onClick={onClose}>Close</button></div>
</div>
</div>;
}
/* ═══════════════════════════════════════════════════════════════
SVG ICONS
═══════════════════════════════════════════════════════════════ */
function I({n,s=16}){
const p={
book:<><path d="M4 19.5A2.5 2.5 0 016.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z"/></>,
folder:<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/>,
file:<><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14,2 14,8 20,8"/></>,
plus:<><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
search:<><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></>,
trash:<><polyline points="3,6 5,6 21,6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></>,
pin:<><line x1="12" y1="17" x2="12" y2="22"/><path d="M5 17h14v-1.76a2 2 0 00-1.11-1.79l-1.78-.9A2 2 0 0115 10.76V6h1a2 2 0 000-4H8a2 2 0 000 4h1v4.76a2 2 0 01-1.11 1.79l-1.78.9A2 2 0 005 15.24z"/></>,
bold:<><path d="M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6z"/><path d="M6 12h9a4 4 0 014 4 4 4 0 01-4 4H6z"/></>,
italic:<><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></>,
underline:<><path d="M6 3v7a6 6 0 006 6 6 6 0 006-6V3"/><line x1="4" y1="21" x2="20" y2="21"/></>,
strike:<><path d="M16 4H9a3 3 0 00-3 3v0a3 3 0 003 3h0"/><path d="M8 20h7a3 3 0 003-3v0a3 3 0 00-3-3h0"/><line x1="4" y1="12" x2="20" y2="12"/></>,
ul:<><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="3" cy="6" r="1" fill="currentColor"/><circle cx="3" cy="12" r="1" fill="currentColor"/><circle cx="3" cy="18" r="1" fill="currentColor"/></>,
ol:<><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/><text x="3" y="8" fontSize="8" fill="currentColor" stroke="none">1</text><text x="3" y="14" fontSize="8" fill="currentColor" stroke="none">2</text><text x="3" y="20" fontSize="8" fill="currentColor" stroke="none">3</text></>,
check:<><polyline points="9,11 12,14 22,4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></>,
undo:<><polyline points="1,4 1,10 7,10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></>,
redo:<><polyline points="23,4 23,10 17,10"/><path d="M20.49 15a9 9 0 11-2.13-9.36L23 10"/></>,
moon:<path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/>,
sun:<><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></>,
chev:<polyline points="9,18 15,12 9,6"/>,
edit:<><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></>,
x:<><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
code:<><polyline points="16,18 22,12 16,6"/><polyline points="8,6 2,12 8,18"/></>,
hr:<line x1="2" y1="12" x2="22" y2="12"/>,
indent:<><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/><polyline points="3,8 7,12 3,16"/></>,
outdent:<><line x1="21" y1="6" x2="11" y2="6"/><line x1="21" y1="12" x2="11" y2="12"/><line x1="21" y1="18" x2="11" y2="18"/><polyline points="7,8 3,12 7,16"/></>,
sidebar:<><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="9" y1="3" x2="9" y2="21"/></>,
table:<><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></>,
wrap:<><path d="M3 6h18"/><path d="M3 12h15a3 3 0 110 6h-4"/><polyline points="13,15 11,18 13,21"/><path d="M3 18h4"/></>,
zin:<><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></>,
zout:<><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></>,
palette:<><circle cx="13.5" cy="6.5" r="2"/><circle cx="17.5" cy="10.5" r="2"/><circle cx="8.5" cy="7.5" r="2"/><circle cx="6.5" cy="12" r="2"/><path d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10c1.38 0 2.5-1.12 2.5-2.5 0-.61-.23-1.2-.64-1.67-.08-.1-.13-.21-.13-.33 0-.28.22-.5.5-.5H16c3.31 0 6-2.69 6-6 0-5.51-4.49-10-10-10z"/></>,
hl:<><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4L16.5 3.5z"/></>,
dl:<><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7,10 12,15 17,10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
link:<><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></>,
quote:<><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.76-2.017-2-2H5c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V21z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.76-2.017-2-2h-3c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3z"/></>,
print:<><polyline points="6,9 6,2 18,2 18,9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></>,
copy:<><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></>,
eraser:<><path d="M7 21h10"/><path d="M5.5 13.5L12 7l5 5-6.5 6.5a2.12 2.12 0 01-3 0L5.5 16.5a2.12 2.12 0 010-3z"/><path d="M18 13l-1.5-1.5"/></>,
scissors:<><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></>,
clipboard:<><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/></>,
lock:<><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></>,
unlock:<><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 019.9-1"/></>,
shield:<><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></>,
};
return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">{p[n]}</svg>;
}
/* ═══════════════════════════════════════════════════════════════
SMALL COMPONENTS
═══════════════════════════════════════════════════════════════ */
function Btn({icon,label,onClick,active,disabled,s=14}){
return <button title={label} onClick={onClick} disabled={disabled}
className={`tb${active?" active":""}`}><I n={icon} s={s}/></button>;
}
function Sel({value,opts,onChange,w=80}){
return <select className="nf-select" value={value} onChange={e=>onChange(e.target.value)} style={{width:w}}>
{opts.map(o=><option key={o.v} value={o.v}>{o.l}</option>)}
</select>;
}
function CPick({colors,onChange,label}){
const [open,setOpen]=useState(false);
const ref=useRef(null);
useEffect(()=>{
if(!open)return;
const h=e=>{if(ref.current&&!ref.current.contains(e.target))setOpen(false)};
document.addEventListener("mousedown",h);return()=>document.removeEventListener("mousedown",h);
},[open]);
return <div ref={ref} style={{position:"relative"}}>
<button title={label} onClick={()=>setOpen(!open)} className="tb"><I n={label==="Text Color"?"palette":"hl"} s={13}/></button>
{open&&<div className="nf-cpick-popup fade-in">
{colors.map(c=><button key={c} className="nf-cpick-swatch" onClick={()=>{onChange(c);setOpen(false)}}
style={{border:c==="transparent"?"1px dashed var(--border)":"1px solid var(--border-light)",background:c}}/>)}
</div>}
</div>;
}
function RenameInput({id,initialValue,onRename,onCancel}){
const [val,setVal]=useState(initialValue||"");
const ref=useRef(null);
useEffect(()=>{
if(ref.current){ref.current.focus();ref.current.select()}
},[]);
const commit=()=>onRename(id,val);
return <input ref={ref} className="nf-rename" value={val}
onChange={e=>setVal(e.target.value)}
onBlur={commit}
onKeyDown={e=>{if(e.key==="Enter"){e.preventDefault();commit()}if(e.key==="Escape")onCancel()}}
onClick={e=>e.stopPropagation()}
onMouseDown={e=>e.stopPropagation()}/>;
}
/* ═══════════════════════════════════════════════════════════════
PASSWORD DIALOG (reusable overlay)
═══════════════════════════════════════════════════════════════ */
function PasswordDialog({title,subtitle,onSubmit,onCancel,confirmLabel,error,showConfirm,showHint,children,dark}){
const [pw,setPw]=useState("");
const [pw2,setPw2]=useState("");
const [hint,setHint]=useState("");
const [localErr,setLocalErr]=useState("");
const ref=useRef(null);
useEffect(()=>{ref.current?.focus()},[]);
const submit=()=>{
if(showConfirm&&pw!==pw2){setLocalErr("Passwords don't match");return}
if(!pw.trim()){setLocalErr("Enter a password");return}
setLocalErr("");onSubmit(pw,hint);
};
const stop=e=>e.stopPropagation();
// Live password requirements (only shown when setting new password)
const hasLen=pw.length>=10;
const hasUpper=/[A-Z]/.test(pw);
const hasLower=/[a-z]/.test(pw);
const hasDigit=/[0-9]/.test(pw);
const hasSymbol=/[^A-Za-z0-9]/.test(pw);
const classes=[hasUpper,hasLower,hasDigit,hasSymbol].filter(Boolean).length;
const allMet=hasLen&&classes>=3;
const Req=({met,text})=><div style={{display:"flex",alignItems:"center",gap:6,fontSize:12,
color:met?"var(--success)":"var(--text-muted)",transition:"color .15s"}}>
<span style={{fontSize:14}}>{met?"✓":"○"}</span>{text}
</div>;
return <div className="nf-overlay" style={dark?THEMES.dark:THEMES.light} onClick={stop} onMouseDown={stop} onKeyDown={stop} onKeyUp={stop} onKeyPress={stop}>
<div className="nf-overlay-card">
<div style={{marginBottom:16}}><I n="shield" s={32}/></div>
<div className="nf-overlay-title">{title}</div>
<div className="nf-overlay-sub">{subtitle}</div>
{(error||localErr)&&<div className="nf-overlay-error">{error||localErr}</div>}
<input ref={ref} className="nf-overlay-input" type="password" placeholder="Password"
value={pw} onChange={e=>setPw(e.target.value)}
onKeyDown={e=>{if(e.key==="Enter"&&(!showConfirm||pw2))submit()}}/>
{showConfirm&&<>
<input className="nf-overlay-input" type="password" placeholder="Confirm password"
value={pw2} onChange={e=>setPw2(e.target.value)}
onKeyDown={e=>{if(e.key==="Enter")submit()}}/>
{/* Password requirements */}
{pw.length>0&&<div style={{textAlign:"left",padding:"8px 12px",background:"var(--surface-alt)",
borderRadius:8,marginBottom:12}}>
<div style={{fontSize:11,fontWeight:600,color:"var(--text-muted)",marginBottom:6,textTransform:"uppercase",letterSpacing:".5px"}}>Password Requirements</div>
<Req met={hasLen} text="At least 10 characters"/>
<Req met={classes>=3} text="3 of 4: uppercase, lowercase, number, symbol"/>
<div style={{marginTop:6,display:"flex",gap:3}}>
{[hasUpper,hasLower,hasDigit,hasSymbol].map((m,i)=>
<div key={i} style={{flex:1,height:3,borderRadius:2,background:m?"var(--success)":"var(--border)",transition:"background .15s"}}/>
)}
</div>
{pw2.length>0&&pw!==pw2&&<div style={{color:"var(--danger)",fontSize:11,marginTop:6}}>Passwords don't match</div>}
{allMet&&pw===pw2&&pw2.length>0&&<div style={{color:"var(--success)",fontSize:11,marginTop:6}}>Ready to encrypt</div>}
</div>}
{showHint&&<input className="nf-overlay-input" type="text" placeholder="Password hint (optional, stored unencrypted)"
value={hint} onChange={e=>setHint(e.target.value)}
style={{marginBottom:12,fontSize:12,opacity:.8}}/>}
</>}
{children}
<button className="nf-overlay-btn primary" onClick={submit}
style={showConfirm&&(!allMet||pw!==pw2)?{opacity:.5,cursor:"not-allowed"}:{}}
disabled={showConfirm&&(!allMet||pw!==pw2)}>
{confirmLabel||"Unlock"}
</button>
{onCancel&&<button className="nf-overlay-btn secondary" onClick={onCancel}>Cancel</button>}
</div>
</div>;
}
/* ═══════════════════════════════════════════════════════════════
MAIN APP
═══════════════════════════════════════════════════════════════ */
function NoteForge(){
const savedPrefs=useRef(prefsStore.load());
const [data,setData]=useState(null);
const [dark,setDark]=useState(savedPrefs.current.dark!==undefined?savedPrefs.current.dark:true);
const [navOpen,setNavOpen]=useState(savedPrefs.current.navOpen!==undefined?savedPrefs.current.navOpen:true);
const [wrap,setWrap]=useState(savedPrefs.current.wrap!==undefined?savedPrefs.current.wrap:true);
const [zoom,setZoom]=useState(savedPrefs.current.zoom||100);
const [aNb,setANb]=useState(null);
const [aSec,setASec]=useState(null);
const [aPg,setAPg]=useState(null);
const [expNb,setExpNb]=useState({});
const [showFR,setShowFR]=useState(false);
const [findT,setFindT]=useState("");
const [replT,setReplT]=useState("");
const [gSearch,setGSearch]=useState("");
const [gResults,setGResults]=useState([]);
const [gFocused,setGFocused]=useState(false);
const [pgFilter,setPgFilter]=useState("");
const [showTrash,setShowTrash]=useState(false);
const [editId,setEditId]=useState(null);
const [editVal,setEditVal]=useState("");
const [ctx,setCtx]=useState(null);
const [edCtx,setEdCtx]=useState(null);
const [stats,setStats]=useState({w:0,c:0,l:0});
const [saved,setSaved]=useState(true);
// Encryption state
const [appPhase,setAppPhase]=useState("loading"); // loading|needsPassword|ready
const [encEnabled,setEncEnabled]=useState(false);
const [masterHint,setMasterHint]=useState(null);
const [pwDialog,setPwDialog]=useState(null); // null | {type,nbId,...}
const [pwError,setPwError]=useState("");
const [unlockedNbs,setUnlockedNbs]=useState(new Set());
const [autoUpdate,setAutoUpdate]=useState(true); // loaded from config
const [sandboxEnabled,setSandboxEnabled]=useState(true); // loaded from config (main-process setting)
// Modal dialogs (custom replacements for native alert/confirm/prompt)
const [confirmDialog,setConfirmDialog]=useState(null); // {title,message,confirmLabel,confirmStyle,resolve}
const [promptDialog,setPromptDialog]=useState(null); // {title,message,placeholder,defaultValue,resolve}
const [alertDialog,setAlertDialog]=useState(null); // {title,message}
const [showShortcuts,setShowShortcuts]=useState(false);
const [restoreFlow,setRestoreFlow]=useState(null); // {backupPath,hasHint}
// Toolbar reflection — tracks current format under cursor
const [toolbarFmt,setToolbarFmt]=useState({block:"div",size:"3"});
const edRef=useRef(null);
const saveTimer=useRef(null);
const statsTimer=useRef(null);
const dataRef=useRef(null);
dataRef.current=data;
const aNbRef=useRef(null);aNbRef.current=aNb;
const aSecRef=useRef(null);aSecRef.current=aSec;
const nbKeys=useRef(new Map()); // nbId -> opaque nbKeyId (main-process session key handle)
const [autoLockMin,setAutoLockMin]=useState(savedPrefs.current.autoLockMin||15);
// Promise-based confirm/prompt/alert helpers — wrap the modal state so call
// sites read naturally: `if(await confirm("Delete?")) { ... }`
const confirm=useCallback((opts)=>new Promise(resolve=>{
const o=typeof opts==="string"?{message:opts}:opts;
setConfirmDialog({
title:o.title||"Confirm",
message:o.message||"",
confirmLabel:o.confirmLabel||"OK",
confirmStyle:o.confirmStyle||"primary",
resolve,
});
}),[]);
const promptUser=useCallback((opts)=>new Promise(resolve=>{
const o=typeof opts==="string"?{message:opts}:opts;
setPromptDialog({
title:o.title||"Input",
message:o.message||"",
placeholder:o.placeholder||"",
defaultValue:o.defaultValue||"",
confirmLabel:o.confirmLabel||"OK",
resolve,
});
}),[]);
const alertUser=useCallback((opts)=>new Promise(resolve=>{
const o=typeof opts==="string"?{message:opts}:opts;
setAlertDialog({
title:o.title||"Notice",
message:o.message||"",
resolve,
});
}),[]);
useEffect(()=>{prefsStore.save({dark,navOpen,wrap,zoom,autoLockMin})},[dark,navOpen,wrap,zoom,autoLockMin]);
/* ── Lock / Auto-lock ────────────────────────────────────── */
const idleTimer=useRef(null);
const lockApp=useCallback(async()=>{
if(saveTimer.current&&dataRef.current){
clearTimeout(saveTimer.current);saveTimer.current=null;
const sanitized={...sanitizeForDiskSync(dataRef.current),version:SCHEMA_VERSION};
await store.set(JSON.stringify(sanitized));
}
if(window.electronAPI?.lockApp)await window.electronAPI.lockApp();
nbKeys.current.clear();
dataRef.current=null;setData(null);setANb(null);setASec(null);setAPg(null);
setUnlockedNbs(new Set());
prevPgRef.current=null; // Force editor to repaint content after unlock even if we land on the same page id
if(encEnabled)setAppPhase("needsPassword");
},[encEnabled]);
// Reset idle timer on any user interaction (throttled to ~1 Hz so mousemove
// doesn't flood the call — we still lock after `autoLockMin` minutes)
useEffect(()=>{
if(!encEnabled||appPhase!=="ready")return;
const ms=autoLockMin*60*1000;
let lastReset=0;
const reset=()=>{
const now=Date.now();
if(now-lastReset<1000)return;
lastReset=now;
if(idleTimer.current)clearTimeout(idleTimer.current);
idleTimer.current=setTimeout(()=>lockApp(),ms);
};
reset();
const events=["mousedown","mousemove","keydown","scroll","wheel","touchstart"];
events.forEach(e=>window.addEventListener(e,reset,{passive:true}));
return()=>{
if(idleTimer.current)clearTimeout(idleTimer.current);
events.forEach(e=>window.removeEventListener(e,reset));
};
},[encEnabled,appPhase,lockApp,autoLockMin]);
// Force-flush on window close (sync so it completes before shutdown)
useEffect(()=>{
const flush=()=>{
if(saveTimer.current&&dataRef.current){
clearTimeout(saveTimer.current);saveTimer.current=null;
// CRITICAL: strip plaintext from locked notebooks before ANY write
const sanitized={...sanitizeForDiskSync(dataRef.current),version:SCHEMA_VERSION};
const json=JSON.stringify(sanitized);
if(window.electronAPI?.storageSetSync)window.electronAPI.storageSetSync(json);
else try{localStorage.setItem("noteforge-data",json)}catch{}
}
};
window.addEventListener("beforeunload",flush);
return()=>window.removeEventListener("beforeunload",flush);
},[]);
/* ── Navigate ────────────────────────────────────────────── */
const navigateTo=useCallback((nbId,secId,pgId)=>{
setANb(nbId);setASec(secId);setAPg(pgId);
if(nbId)setExpNb(p=>({...p,[nbId]:true}));
setShowTrash(false);
},[]);
const loadIntoState=useCallback((d)=>{
dataRef.current=d;
setData(d);
const nb=d.notebooks[0];
if(nb){
const isLocked=nb.locked&&!nb.sections?.length;
if(!isLocked){
const sec=nb.sections[0];
if(sec){const pg=sec.pages.find(p=>!p.deleted);navigateTo(nb.id,sec.id,pg?.id||null)}
else{setANb(nb.id);setExpNb({[nb.id]:true})}
} else {setANb(nb.id);setExpNb({[nb.id]:true})}
}
setAppPhase("ready");
},[navigateTo]);
/* ── Load (encryption-aware) ─────────────────────────────── */
useEffect(()=>{
(async()=>{
// Load config
if(window.electronAPI?.getConfig){
const cfg=await window.electronAPI.getConfig();
if(cfg.autoUpdate!==undefined)setAutoUpdate(cfg.autoUpdate);
if(cfg.sandbox!==undefined)setSandboxEnabled(cfg.sandbox!==false);
}
if(hasElectronCrypto()){
const status=await window.electronAPI.checkEncryption();
setEncEnabled(status.encrypted);
if(status.hint)setMasterHint(status.hint);
if(status.encrypted){setAppPhase("needsPassword");return}
}
// Not encrypted — load normally
let d=null;
try{const r=await store.get();if(r?.value)d=JSON.parse(r.value)}catch{}
if(!d||!d.notebooks)d=structuredClone(DEFAULT_DATA);
loadIntoState(d);
})();
},[]);
/* ── Persist ─────────────────────────────────────────────── */
const persist=useCallback(async(nd)=>{
dataRef.current=nd; // Update ref IMMEDIATELY — don't wait for React re-render
setData(nd);setSaved(false);
if(saveTimer.current)clearTimeout(saveTimer.current);
saveTimer.current=setTimeout(async()=>{
let toSave=nd;
// Step 1: Re-encrypt sections for any locked+unlocked-in-session notebooks
// so edits are captured in the encrypted blob before we strip plaintext.
// Uses cached main-process session key — no scrypt on the hot path.
if(hasElectronCrypto()){
const nbs=await Promise.all(nd.notebooks.map(async nb=>{
if(nb.locked&&nb.sections?.length>0&&nbKeys.current.has(nb.id)){
const nbKeyId=nbKeys.current.get(nb.id);
const r=await window.electronAPI.reencryptNotebookSections(JSON.stringify(nb.sections),nbKeyId);
if(r.success)return{...nb,encSections:r.blob};
}
return nb;
}));
toSave={...nd,notebooks:nbs};
}
// Step 2: MANDATORY — strip ALL plaintext from locked notebooks before writing
// This is the safety net. Even if step 1 failed or was skipped, plaintext never hits disk.
toSave=sanitizeForDiskSync(toSave);
// Stamp schema version so future releases can migrate safely
toSave={...toSave,version:SCHEMA_VERSION};
await store.set(JSON.stringify(toSave));setSaved(true);
},500);
},[]);
useEffect(()=>()=>{if(saveTimer.current)clearTimeout(saveTimer.current)},[]);
/* ── Derived ─────────────────────────────────────────────── */
const curPage=useMemo(()=>{
if(!data||!aPg)return null;
for(const nb of data.notebooks)for(const sec of nb.sections){
const pg=sec.pages.find(p=>p.id===aPg&&!p.deleted);if(pg)return pg;
}
return null;
},[data,aPg]);
const curSection=useMemo(()=>{
if(!data||!aSec)return null;
for(const nb of data.notebooks){const sec=(nb.sections||[]).find(s=>s.id===aSec);if(sec)return sec}
return null;
},[data,aSec]);
const curNotebook=useMemo(()=>data?.notebooks?.find(n=>n.id===aNb)||null,[data,aNb]);
const sectionPages=useMemo(()=>{
if(!curSection)return[];
let pages=curSection.pages.filter(p=>!p.deleted);
if(pgFilter.trim()){const q=pgFilter.toLowerCase();pages=pages.filter(p=>p.title.toLowerCase().includes(q))}
return pages.sort((a,b)=>(b.pinned?1:0)-(a.pinned?1:0)||b.modified-a.modified);
},[curSection,pgFilter]);
const breadcrumb=useMemo(()=>{
if(!data||!aPg)return null;
for(const nb of data.notebooks)for(const sec of nb.sections)
if(sec.pages.find(p=>p.id===aPg))return{nb:nb.name,sec:sec.name,color:nb.color};
return null;
},[data,aPg]);
const trashPages=useMemo(()=>{
if(!data)return[];const r=[];
for(const nb of data.notebooks)for(const sec of nb.sections||[])for(const pg of sec.pages)
if(pg.deleted)r.push({...pg,nbName:nb.name,secName:sec.name});
return r;
},[data]);
/* ── Editor content ──────────────────────────────────────── */
const prevPgRef=useRef(null);
useEffect(()=>{
if(!edRef.current)return;
if(curPage&&aPg!==prevPgRef.current){
edRef.current.innerHTML=sanitizeHTML(curPage.content)||"<p><br></p>";
prevPgRef.current=aPg;updStats();
} else if(!curPage&&prevPgRef.current){
edRef.current.innerHTML="";
prevPgRef.current=null;
}
},[aPg,curPage]);
const updStats=useCallback(()=>{
if(statsTimer.current)clearTimeout(statsTimer.current);
statsTimer.current=setTimeout(()=>{
if(!edRef.current)return;const t=edRef.current.innerText||"";
setStats({w:t.trim()?t.trim().split(/\s+/).length:0,c:t.length,l:t.split("\n").length});
},120);
},[]);
const updatePage=useCallback((pageId,updater)=>{
const d=dataRef.current;if(!d)return;
const nd={...d,notebooks:d.notebooks.map(nb=>({...nb,sections:(nb.sections||[]).map(sec=>{
const idx=sec.pages.findIndex(p=>p.id===pageId);
if(idx===-1)return sec;
const np=[...sec.pages];np[idx]={...np[idx],...updater(np[idx])};
return{...sec,pages:np};
})}))};
persist(nd);
},[persist]);
const onInput=useCallback(()=>{
if(!edRef.current||!dataRef.current||!aPg)return;
updatePage(aPg,()=>({content:edRef.current.innerHTML,modified:Date.now()}));updStats();
},[aPg,updatePage,updStats]);
const exec=useCallback((cmd,val=null)=>{
edRef.current?.focus();document.execCommand(cmd,false,val);setTimeout(()=>onInput(),10);
},[onInput]);
/* ── Paste ───────────────────────────────────────────────── */
const onPaste=useCallback(e=>{
const cd=e.clipboardData;if(!cd)return;
// Check for images first
for(const item of cd.items){
if(item.type.startsWith("image/")){
e.preventDefault();const file=item.getAsFile();
if(!file)return;
// Auto-downscale large images so the encrypted data file stays lean.
// 5 MB hard cap to avoid canvas/memory pathologies.
downscaleImage(file,512000).then(dataUrl=>{
exec("insertHTML",`<img src="${dataUrl}" alt="">`);
}).catch(err=>{
alertUser({title:"Image too large",message:err.message||"Could not process image."});
});
return;
}
}
// Always prevent default — never let the browser insert raw clipboard HTML
e.preventDefault();
// Prefer plain text (strips all formatting — clean paste like OneNote)
const text=cd.getData("text/plain");
if(text){document.execCommand("insertText",false,text);return}
// Fallback: if only HTML is available (rare), sanitize it
const html=cd.getData("text/html");
if(html){const clean=sanitizeHTML(html);if(clean)document.execCommand("insertHTML",false,clean)}
},[exec,alertUser]);
const onKeyDown=useCallback(e=>{
if(e.key==="Tab"){
const sel=window.getSelection();if(sel.anchorNode){
let node=sel.anchorNode;
while(node&&node!==edRef.current){
if(node.nodeName==="PRE"){e.preventDefault();document.execCommand("insertText",false," ");return}
node=node.parentNode;
}
}
}
},[]);
/* ── Shortcuts ───────────────────────────────────────────── */
useEffect(()=>{
const h=e=>{
const mod=e.ctrlKey||e.metaKey;
if(mod&&e.key==="f"){e.preventDefault();setShowFR(p=>!p)}
if(mod&&e.key==="h"){e.preventDefault();setShowFR(true)}
if(mod&&e.key==="d"&&!e.shiftKey){e.preventDefault();if(aPg)duplicatePage(aPg)}
if(mod&&e.key==="l"){e.preventDefault();if(encEnabled)lockApp()}
if(e.key==="F1"){e.preventDefault();setShowShortcuts(true)}
};
window.addEventListener("keydown",h);return()=>window.removeEventListener("keydown",h);
},[aPg,encEnabled,lockApp]);
/* ── Electron menu ───────────────────────────────────────── */
useEffect(()=>{
if(!window.electronAPI)return;
const cleanup=window.electronAPI.onMenuAction(a=>{
if(a==="toggle-sidebar")setNavOpen(p=>!p);
if(a==="toggle-theme")setDark(p=>!p);
if(a==="find-replace")setShowFR(p=>!p);
if(a==="zoom-in")setZoom(z=>Math.min(200,z+10));
if(a==="zoom-out")setZoom(z=>Math.max(50,z-10));
if(a==="zoom-reset")setZoom(100);
if(a==="toggle-wrap")setWrap(p=>!p);
if(a==="export-html")doExportHTML();
if(a==="export-text")doExportText();
if(a==="print"){
const nb=dataRef.current?.notebooks?.find(n=>n.id===aNbRef.current);
const isLocked=nb?.locked||false;
window.electronAPI.printWithWarning(isLocked);
}
if(a==="open-data-folder")window.electronAPI.openDataFolder();
if(a==="encryption-settings")setPwDialog({type:"enc-settings"});
if(a==="export-backup")window.electronAPI.exportBackup();
if(a==="restore-backup")(async()=>{
const r=await window.electronAPI.restoreBackup();
if(r?.error){alertUser({title:"Restore failed",message:r.error});return}
if(r?.readyForPassword){setRestoreFlow({backupPath:r.backupPath,hasHint:r.hasHint})}
})();
if(a==="lock-app"){if(encEnabled)lockApp()}
if(a==="empty-trash")emptyTrash();
if(a==="show-shortcuts")setShowShortcuts(true);
if(a==="new-notebook")addNotebook();
if(a==="new-page"){
const d=dataRef.current;if(!d)return;
const nb=d.notebooks.find(n=>n.id===aNbRef.current);
if(nb&&nb.sections?.length){
const sid=aSecRef.current&&(nb.sections||[]).find(s=>s.id===aSecRef.current)?aSecRef.current:nb.sections[0].id;
addPage(nb.id,sid);
}
}
});
return cleanup;
},[encEnabled,lockApp]);
// Track cursor format for heading/font-size select reflection
useEffect(()=>{
if(!edRef.current)return;
const sync=()=>{
try{
// Only update when caret is actually inside the editor
const sel=document.getSelection();
if(!sel?.anchorNode||!edRef.current.contains(sel.anchorNode))return;
const block=(document.queryCommandValue("formatBlock")||"div").toLowerCase();
const size=document.queryCommandValue("fontSize")||"3";
setToolbarFmt(p=>(p.block===block&&p.size===size)?p:{block,size});
}catch{}
};
document.addEventListener("selectionchange",sync);
return()=>document.removeEventListener("selectionchange",sync);
},[curPage]);
useEffect(()=>{const h=()=>{setCtx(null);setEdCtx(null)};window.addEventListener("click",h);return()=>window.removeEventListener("click",h)},[]);
/* ═══════════════════════════════════════════════════════════
CRUD
═══════════════════════════════════════════════════════════ */
const addNotebook=()=>{
const id=uid();const d=dataRef.current;
persist({...d,notebooks:[...d.notebooks,{id,name:"New Notebook",color:NB_COLORS[d.notebooks.length%NB_COLORS.length],locked:false,encSections:null,sections:[]}]});
setANb(id);setASec(null);setAPg(null);setExpNb(p=>({...p,[id]:true}));setEditId(id);setEditVal("New Notebook");
};
const addSection=(nbId)=>{
const id=uid();const d=dataRef.current;
persist({...d,notebooks:d.notebooks.map(n=>n.id!==nbId?n:{...n,sections:[...(n.sections||[]),{id,name:"New Section",color:n.color,pages:[]}]})});
setANb(nbId);setASec(id);setAPg(null);setExpNb(p=>({...p,[nbId]:true}));setEditId(id);setEditVal("New Section");
};
const addPage=(nbId,secId)=>{
const id=uid();const d=dataRef.current;
persist({...d,notebooks:d.notebooks.map(nb=>nb.id!==nbId?nb:{...nb,sections:(nb.sections||[]).map(sec=>sec.id!==secId?sec:{
...sec,pages:[...sec.pages,{id,title:"New Page",content:"<p><br></p>",created:Date.now(),modified:Date.now(),pinned:false,deleted:false}]
})})});
navigateTo(nbId,secId,id);setEditId(id);setEditVal("New Page");
};
const duplicatePage=(pgId)=>{
const d=dataRef.current;if(!d)return;
for(const nb of d.notebooks)for(const sec of nb.sections||[]){
const pg=sec.pages.find(p=>p.id===pgId);
if(pg){
const id=uid();
persist({...d,notebooks:d.notebooks.map(n=>n.id!==nb.id?n:{...n,sections:(n.sections||[]).map(s=>s.id!==sec.id?s:{
...s,pages:[...s.pages,{...pg,id,title:pg.title+" (copy)",created:Date.now(),modified:Date.now(),pinned:false}]
})})});
navigateTo(nb.id,sec.id,id);return;
}
}
};
const rename=(itemId,name)=>{
if(!name.trim())name="Untitled";const d=dataRef.current;
persist({...d,notebooks:d.notebooks.map(nb=>{
if(nb.id===itemId)return{...nb,name};
return{...nb,sections:(nb.sections||[]).map(sec=>{
if(sec.id===itemId)return{...sec,name};
return{...sec,pages:sec.pages.map(pg=>pg.id===itemId?{...pg,title:name}:pg)};
})};
})});
setEditId(null);
};
const autoSelectNextPage=(excludeId)=>{
const d=dataRef.current;if(!d||!aSec)return;
for(const nb of d.notebooks)for(const sec of nb.sections||[])
if(sec.id===aSec){const pg=sec.pages.find(p=>!p.deleted&&p.id!==excludeId);setAPg(pg?.id||null);return}
setAPg(null);
};
const softDelete=(pid)=>{updatePage(pid,()=>({deleted:true,modified:Date.now()}));if(aPg===pid)autoSelectNextPage(pid)};
const restorePage=(pid)=>updatePage(pid,()=>({deleted:false}));
const permDelete=async(pid)=>{
if(!await confirm({title:"Delete Forever",message:"Permanently delete this page? This cannot be undone.",confirmLabel:"Delete Forever",confirmStyle:"danger"}))return;
const d=dataRef.current;
persist({...d,notebooks:d.notebooks.map(nb=>({...nb,sections:(nb.sections||[]).map(sec=>({...sec,pages:sec.pages.filter(p=>p.id!==pid)}))}))});
if(aPg===pid)autoSelectNextPage(pid);
};
const togglePin=(pid)=>{
for(const nb of dataRef.current.notebooks)for(const sec of nb.sections||[])
if(sec.pages.find(p=>p.id===pid)){updatePage(pid,p=>({pinned:!p.pinned}));return}
};
const delSection=async(sid)=>{
const d=dataRef.current;let count=0;let parentNb=null;
for(const nb of d.notebooks)for(const sec of nb.sections||[])if(sec.id===sid){count=sec.pages.length;parentNb=nb}
const ok=await confirm({
title:"Delete Section",
message:count>0?`Delete section and ${count} page${count>1?"s":""}? This cannot be undone.`:"Delete empty section?",
confirmLabel:"Delete",confirmStyle:"danger",
});
if(!ok)return;
persist({...d,notebooks:d.notebooks.map(nb=>({...nb,sections:(nb.sections||[]).filter(s=>s.id!==sid)}))});
if(aSec===sid){
// Auto-select next section in same notebook
const remaining=(parentNb?.sections||[]).filter(s=>s.id!==sid);
if(remaining[0]){setASec(remaining[0].id);const pg=remaining[0].pages.find(p=>!p.deleted);setAPg(pg?.id||null)}
else{setASec(null);setAPg(null)}
}
};
const delNotebook=async(nid)=>{
const d=dataRef.current;const nb=d.notebooks.find(n=>n.id===nid);
const pc=nb?(nb.sections||[]).reduce((a,s)=>a+s.pages.length,0):0;
const ok=await confirm({
title:"Delete Notebook",
message:pc>0?`Delete "${nb.name}" and all ${pc} pages? This cannot be undone.`:`Delete "${nb?.name}"?`,
confirmLabel:"Delete",confirmStyle:"danger",
});
if(!ok)return;
persist({...d,notebooks:d.notebooks.filter(n=>n.id!==nid)});
const keyId=nbKeys.current.get(nid);
if(keyId&&window.electronAPI?.forgetNotebookKey)window.electronAPI.forgetNotebookKey(keyId);
nbKeys.current.delete(nid);
if(aNb===nid){setANb(null);setASec(null);setAPg(null)}
};
// Empty trash — removes all soft-deleted pages
const emptyTrash=async()=>{
const d=dataRef.current;if(!d)return;
let n=0;
for(const nb of d.notebooks)for(const sec of nb.sections||[])for(const pg of sec.pages)if(pg.deleted)n++;
if(n===0){alertUser({title:"Trash is empty",message:"Nothing to clean up."});return}
const ok=await confirm({
title:"Empty Trash",
message:`Permanently delete ${n} page${n>1?"s":""} from trash? This cannot be undone.`,
confirmLabel:"Empty Trash",confirmStyle:"danger",
});
if(!ok)return;
persist({...d,notebooks:d.notebooks.map(nb=>({...nb,sections:(nb.sections||[]).map(sec=>({...sec,pages:sec.pages.filter(p=>!p.deleted)}))}))});
};
// Re-lock a notebook in-session — discards in-memory plaintext and the cached session key
const relockNotebook=async(nbId)=>{
const d=dataRef.current;const nb=d.notebooks.find(n=>n.id===nbId);
if(!nb||!nb.locked||!nb.encSections)return;
const ok=await confirm({
title:`Re-lock "${nb.name}"?`,
message:"You'll need to re-enter the notebook password to view these pages again.",
confirmLabel:"Re-lock",
});
if(!ok)return;
const keyId=nbKeys.current.get(nbId);
if(keyId&&window.electronAPI?.forgetNotebookKey)await window.electronAPI.forgetNotebookKey(keyId);
nbKeys.current.delete(nbId);
// Strip plaintext sections from in-memory state (encSections is already on disk-authoritative)
const nd={...d,notebooks:d.notebooks.map(n=>n.id!==nbId?n:{...n,sections:[]})};
persist(nd);
setUnlockedNbs(p=>{const s=new Set(p);s.delete(nbId);return s});
if(aNb===nbId&&!nb.sections?.length){setASec(null);setAPg(null)}
};
/* ═══ Notebook Lock/Unlock ═════════════════════════════════ */
const lockNotebook=async(nbId,password)=>{
if(!hasElectronCrypto())return{error:"Encryption not available"};
const d=dataRef.current;const nb=d.notebooks.find(n=>n.id===nbId);
if(!nb||!nb.sections?.length)return{error:"Nothing to lock"};
const r=await window.electronAPI.encryptNotebookSections(JSON.stringify(nb.sections),password);
if(!r.success)return{error:r.error};
// Store only the opaque handle to the main-process session key. Password is discarded here.
if(r.nbKeyId)nbKeys.current.set(nbId,r.nbKeyId);
// Keep sections in memory (user still has access this session).
// sanitizeForDiskSync() strips them before every write — plaintext never reaches disk.
const nd={...d,notebooks:d.notebooks.map(n=>n.id!==nbId?n:{...n,locked:true,encSections:r.blob})};
persist(nd);
setUnlockedNbs(p=>{const s=new Set(p);s.add(nbId);return s});
return{};
};