Repository navigation
Expand file tree
/
Copy pathtaskflow.html
More file actions
5273 lines (4918 loc) · 287 KB
/
Copy pathtaskflow.html
File metadata and controls
5273 lines (4918 loc) · 287 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TaskFlow</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='t' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0%25' stop-color='%23e0e4ea'/%3E%3Cstop offset='100%25' stop-color='%23b0b8c8'/%3E%3C/linearGradient%3E%3ClinearGradient id='f' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0%25' stop-color='%234a9eff'/%3E%3Cstop offset='100%25' stop-color='%23b080e0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='7' fill='%23161616'/%3E%3Ctext x='16' y='16' text-anchor='middle' dominant-baseline='central' font-family='JetBrains Mono,monospace' font-weight='700' font-size='28' letter-spacing='-2'%3E%3Ctspan fill='url(%23t)'%3ET%3C/tspan%3E%3Ctspan fill='url(%23f)'%3EF%3C/tspan%3E%3C/text%3E%3C/svg%3E">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&family=Lora:ital,wght@0,400;0,500;0,600;0,700;1,400;1,600&family=Dancing+Script:wght@500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.9/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<style>
/* ════════════════════════════════════════════════
Theme tokens — dark is default. Light values live
under html[data-theme="light"]. Add new themes by
adding another selector with the same token names.
════════════════════════════════════════════════ */
:root, html[data-theme="dark"] {
/* Backgrounds */
--c-bg: #1a1a1a;
--c-bg-deep: #161616;
--c-bg-dropdown: #1a1a1e;
--c-bg-cool: #1a1f30;
--c-surface: #1e1e1e;
--c-surface-2: #222;
--c-surface-3: #242424;
--c-surface-3b: #242428;
--c-surface-raised: #2a2a2a;
--c-surface-cool: #2a2f3a;
--c-surface-cool-2: #2a3a4a;
--c-surface-modal: #2c2c2c;
--c-surface-elev: #2e2e2e;
--c-surface-hover: #353535;
--c-surface-hi: #3a3a3a;
--c-surface-hi-2: #3f3f3f;
/* Borders */
--c-border: #333333;
--c-border-weak: #444;
--c-border-strong: #4a4a4a;
/* Text */
--c-text: #d0d4e0;
--c-text-pale: #e0e0e0;
--c-text-pale-2: #ccc;
--c-text-secondary: #a0a0a0;
--c-text-secondary-2:#a8a8a8;
--c-text-secondary-3:#b0b0b0;
--c-text-secondary-4:#9a9a9a;
--c-text-secondary-5:#9aa4bd;
--c-text-secondary-6:#9aa;
--c-text-cool: #8a9bb8;
--c-text-cool-2: #6a7090;
--c-text-cool-3: #5a6080;
--c-text-faint-cool: #505060;
--c-text-muted: #606060;
--c-text-muted-2: #6a6a6a;
--c-text-muted-3: #666;
--c-text-muted-4: #707070;
--c-text-muted-5: #757575;
--c-text-muted-6: #777;
--c-text-muted-7: #808080;
--c-text-muted-8: #858585;
--c-text-muted-9: #888;
--c-text-muted-10: #8a8a8a;
--c-text-dim: #555;
--c-text-dim-2: #555555;
/* Accent */
--c-accent: #4a9eff;
--c-accent-08: rgba(74,158,255,0.08);
--c-accent-12: rgba(74,158,255,0.12);
--c-accent-25: rgba(74,158,255,0.25);
--c-accent-30: rgba(74,158,255,0.3);
--c-accent-06: rgba(74,158,255,0.06);
--c-accent-10: rgba(74,158,255,0.10);
--c-accent-16: rgba(74,158,255,0.16);
--c-accent-03: rgba(74,158,255,0.03);
--c-accent-cool-50: rgba(30,36,56,0.5);
--c-accent-cool-30: rgba(30,36,56,0.3);
/* Overlays / shadows */
--c-shadow-60: rgba(0,0,0,0.6);
--c-shadow-50: rgba(0,0,0,0.5);
--c-shadow-40: rgba(0,0,0,0.4);
--c-white-12: rgba(255,255,255,0.12);
--c-white-08: rgba(255,255,255,0.08);
--c-white-03: rgba(255,255,255,0.03);
--c-white-02: rgba(255,255,255,0.02);
/* Status badge backgrounds (match dark aesthetic) */
--c-status-done-bg: #2a4a2a;
--c-status-tmrw-bg: #3a3520;
--c-status-weekly-bg: #1a2a3e;
--c-status-monthly-bg: #3a2a1a;
--c-status-long-bg: #2a1a3e;
--c-status-urgent-bg: #4a1a1a;
/* Typography. --font-sans is overridden by html[data-font="..."]; --font-mono
stays JetBrains Mono so badges/keyboard hints don't get unreadable. */
--font-sans: 'IBM Plex Sans', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
}
/* Font cycle: sans (default) → serif → cursive.
Cursive is bumped up a notch in size because Dancing Script reads visually
smaller than the equivalent sans/serif at the same pixel size. */
html[data-font="serif"] { --font-sans: 'Lora', Georgia, 'Times New Roman', serif; }
html[data-font="cursive"] { --font-sans: 'Dancing Script', 'Brush Script MT', cursive; }
html[data-font="cursive"] body { font-size: 17px; }
html[data-theme="light"] {
/* Backgrounds — pure whites kept where the original used #ffffff, every other
surface is nudged a hair darker and de-blued (was a cool grey trending blue;
now a neutral warm grey). */
--c-bg: #e8e8e8;
--c-bg-deep: #dcdcdc;
--c-bg-dropdown: #ffffff;
--c-bg-cool: #dfdfe0;
--c-surface: #ffffff;
--c-surface-2: #efefef;
--c-surface-3: #e7e7e7;
--c-surface-3b: #e3e3e3;
/* --c-surface-raised is used both as elevated chip background and as the
1px panel divider color throughout the layout. Darker than the
surrounding surfaces so panel borders read clearly on light backgrounds. */
--c-surface-raised: #b6b6b6;
--c-surface-cool: #d2d2d3;
--c-surface-cool-2: #cacacb;
--c-surface-modal: #ffffff;
--c-surface-elev: #efefef;
--c-surface-hover: #c4c4c5;
--c-surface-hi: #b8b8b9;
--c-surface-hi-2: #acacad;
--c-border: #a4a4a4;
--c-border-weak: #989898;
--c-border-strong: #7a7a7a;
--c-text: #1a1f2e;
--c-text-pale: #2a2f3e;
--c-text-pale-2: #3a3f4e;
--c-text-secondary: #4a5060;
--c-text-secondary-2:#525868;
--c-text-secondary-3:#5a6070;
--c-text-secondary-4:#585e6e;
--c-text-secondary-5:#556080;
--c-text-secondary-6:#606878;
--c-text-cool: #4a5878;
--c-text-cool-2: #5c6890;
--c-text-cool-3: #6c7898;
--c-text-faint-cool: #7a82a0;
--c-text-muted: #6a7080;
--c-text-muted-2: #707685;
--c-text-muted-3: #747a88;
--c-text-muted-4: #787e8c;
--c-text-muted-5: #7c8290;
--c-text-muted-6: #808690;
--c-text-muted-7: #848a94;
--c-text-muted-8: #888e98;
--c-text-muted-9: #8c929c;
--c-text-muted-10: #8f959e;
--c-text-dim: #9aa0ac;
--c-text-dim-2: #9ea4b0;
--c-accent: #2e7de0;
--c-accent-08: rgba(46,125,224,0.1);
--c-accent-12: rgba(46,125,224,0.15);
--c-accent-25: rgba(46,125,224,0.25);
--c-accent-30: rgba(46,125,224,0.32);
--c-accent-06: rgba(46,125,224,0.08);
--c-accent-10: rgba(46,125,224,0.12);
--c-accent-16: rgba(46,125,224,0.2);
--c-accent-03: rgba(46,125,224,0.05);
--c-accent-cool-50: rgba(180,200,230,0.5);
--c-accent-cool-30: rgba(180,200,230,0.3);
--c-shadow-60: rgba(30,40,60,0.25);
--c-shadow-50: rgba(30,40,60,0.18);
--c-shadow-40: rgba(30,40,60,0.12);
--c-white-12: rgba(30,40,60,0.08);
--c-white-08: rgba(30,40,60,0.05);
--c-white-03: rgba(30,40,60,0.03);
--c-white-02: rgba(30,40,60,0.02);
--c-status-done-bg: #d4f0d4;
--c-status-tmrw-bg: #fbeec0;
--c-status-weekly-bg: #d4e0f4;
--c-status-monthly-bg: #f8dcc4;
--c-status-long-bg: #e4d4f4;
--c-status-urgent-bg: #f8d4d4;
}
/* ════════════════════════════════════════════════
Sepia — warm parchment / scholarly. Sits between
light and dark in luminosity; brown ink on aged
paper, amber accent in place of cool blue.
════════════════════════════════════════════════ */
html[data-theme="sepia"] {
--c-bg: #ece1c8;
--c-bg-deep: #e0d3b4;
--c-bg-dropdown: #f6ecd4;
--c-bg-cool: #e6dabe;
--c-surface: #f4ead2;
--c-surface-2: #ede2c6;
--c-surface-3: #e6dabb;
--c-surface-3b: #e2d6b6;
/* Darker than light's because the parchment bg is warmer/lighter; pushes
the major panel dividers visible against the cream. */
--c-surface-raised: #b8a778;
--c-surface-cool: #d4c7a0;
--c-surface-cool-2: #ccbf94;
--c-surface-modal: #f4ead2;
--c-surface-elev: #ede2c6;
--c-surface-hover: #c8bb90;
--c-surface-hi: #bcaf84;
--c-surface-hi-2: #b0a378;
--c-border: #9c8a60;
--c-border-weak: #877548;
--c-border-strong: #6c5b34;
--c-text: #3a2c1c;
--c-text-pale: #463624;
--c-text-pale-2: #54422e;
--c-text-secondary: #62503a;
--c-text-secondary-2:#695540;
--c-text-secondary-3:#705c46;
--c-text-secondary-4:#6c5842;
--c-text-secondary-5:#6e5a3c;
--c-text-secondary-6:#736044;
--c-text-cool: #6a583a;
--c-text-cool-2: #786642;
--c-text-cool-3: #88744a;
--c-text-faint-cool: #9a8456;
--c-text-muted: #80715a;
--c-text-muted-2: #84755e;
--c-text-muted-3: #887962;
--c-text-muted-4: #8a7c64;
--c-text-muted-5: #8c7e66;
--c-text-muted-6: #8e8068;
--c-text-muted-7: #90826a;
--c-text-muted-8: #92846c;
--c-text-muted-9: #94866e;
--c-text-muted-10: #968870;
--c-text-dim: #a09080;
--c-text-dim-2: #a49484;
--c-accent: #9c5a1e;
--c-accent-08: rgba(156,90,30,0.10);
--c-accent-12: rgba(156,90,30,0.15);
--c-accent-25: rgba(156,90,30,0.25);
--c-accent-30: rgba(156,90,30,0.32);
--c-accent-06: rgba(156,90,30,0.08);
--c-accent-10: rgba(156,90,30,0.12);
--c-accent-16: rgba(156,90,30,0.20);
--c-accent-03: rgba(156,90,30,0.05);
--c-accent-cool-50: rgba(180,160,120,0.5);
--c-accent-cool-30: rgba(180,160,120,0.3);
--c-shadow-60: rgba(60,40,20,0.28);
--c-shadow-50: rgba(60,40,20,0.20);
--c-shadow-40: rgba(60,40,20,0.13);
--c-white-12: rgba(60,40,20,0.09);
--c-white-08: rgba(60,40,20,0.06);
--c-white-03: rgba(60,40,20,0.03);
--c-white-02: rgba(60,40,20,0.02);
--c-status-done-bg: #cdd6b0;
--c-status-tmrw-bg: #ecd9a8;
--c-status-weekly-bg: #c8cfd0;
--c-status-monthly-bg: #e8c8a0;
--c-status-long-bg: #d4c4d0;
--c-status-urgent-bg: #e0bdae;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body,#root{height:100%;width:100%;overflow:hidden}
body{background:var(--c-bg);color:var(--c-text);font-family:var(--font-sans);transition:background 0.2s ease,color 0.2s ease}
::-webkit-scrollbar{width:6px}
::-webkit-scrollbar-track{background:transparent}
::-webkit-scrollbar-thumb{background:var(--c-border);border-radius:3px}
input::placeholder{color:var(--c-text-dim-2)!important}
input[type="color"]{-webkit-appearance:none;border:none;cursor:pointer}
input[type="color"]::-webkit-color-swatch-wrapper{padding:0}
input[type="color"]::-webkit-color-swatch{border:none;border-radius:5px}
@keyframes fadeInUp{from{opacity:0;transform:translateX(-50%) translateY(10px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
</style>
</head>
<body>
<script>
/* Set theme attribute before React mounts to avoid a flash on light-theme users */
try { var t = JSON.parse(localStorage.getItem('taskflow-theme')); if (t === 'light' || t === 'dark' || t === 'sepia') document.documentElement.dataset.theme = t; else document.documentElement.dataset.theme = 'dark'; } catch(e) { document.documentElement.dataset.theme = 'dark'; }
try { var f = JSON.parse(localStorage.getItem('taskflow-font')); if (f === 'sans' || f === 'serif' || f === 'cursive') document.documentElement.dataset.font = f; else document.documentElement.dataset.font = 'sans'; } catch(e) { document.documentElement.dataset.font = 'sans'; }
</script>
<div id="root"></div>
<script type="text/babel">
const{useState,useEffect,useCallback,useRef,useMemo}=React;
/* ══════════════════════════════════════════
── Supabase Configuration ──
══════════════════════════════════════════ */
const SUPABASE_URL = 'https://ixwpmtxssbdqqevejima.supabase.co';
const SUPABASE_ANON_KEY = 'sb_publishable_VFsG64zwQqH8JOy9ZnOpDQ_WBjiGs3G';
const _sbConfigured = SUPABASE_URL !== 'YOUR_SUPABASE_URL' && SUPABASE_ANON_KEY !== 'YOUR_SUPABASE_ANON_KEY';
const supabase = _sbConfigured ? window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY) : null;
/* ── Cloud persistence helpers ──
loadSB THROWS on real errors (network, paused project, auth failure) so callers
can distinguish "Supabase unreachable" from "row not in table". Returning a
silent null for both was how the v0.1.9.4 data-loss bug happened: a paused
project produced empty snapshots that pruned out real backups. Only return
null when the row genuinely does not exist (or supabase isn't configured /
user not signed in). */
async function loadSB(key) {
if (!supabase) return null;
const { data: userData, error: authErr } = await supabase.auth.getUser();
if (authErr) { const e = new Error('auth.getUser failed: ' + authErr.message); e.sbError = true; throw e; }
const user = userData && userData.user;
if (!user) return null;
const { data, error } = await supabase.from('user_store').select('value').eq('user_id', user.id).eq('key', key).maybeSingle();
if (error) { const e = new Error('loadSB(' + key + ') failed: ' + error.message); e.sbError = true; throw e; }
return data ? data.value : null;
}
/* ── Write-failure tracking. saveSB swallows errors and returns false, but
silent failures on the write side are the mirror of the read-side bug:
the user thinks the cloud is up-to-date when it isn't. We dispatch window
events on threshold-crossing so TaskFlow can flip cloudStatus accordingly.
Single transient failures don't trip — only a streak of SB_WRITE_FAIL_LIMIT
consecutive failures, to avoid red-flashing on every flaky save. */
const SB_WRITE_FAIL_LIMIT = 2;
let _sbWriteFailures = 0;
function _onSBWriteOK() {
if (_sbWriteFailures > 0) {
_sbWriteFailures = 0;
window.dispatchEvent(new CustomEvent('sb-write-recovered'));
}
}
function _onSBWriteFail(err) {
_sbWriteFailures++;
if (_sbWriteFailures >= SB_WRITE_FAIL_LIMIT) {
window.dispatchEvent(new CustomEvent('sb-write-failed', { detail: { message: err && err.message } }));
}
}
function resetSBWriteFailures() { _sbWriteFailures = 0; }
async function saveSB(key, value) {
if (!supabase) return false;
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return false;
const { error } = await supabase.from('user_store').upsert(
{ user_id: user.id, key, value, updated_at: new Date().toISOString() },
{ onConflict: 'user_id,key' }
);
if (error) throw error;
_onSBWriteOK();
return true;
} catch (e) { console.warn('[SB] saveSB error:', e.message); _onSBWriteFail(e); return false; }
}
async function deleteSB(key) {
if (!supabase) return false;
try {
const { data: { user } } = await supabase.auth.getUser();
if (!user) return false;
const { error } = await supabase.from('user_store').delete().eq('user_id', user.id).eq('key', key);
if (error) throw error;
return true;
} catch (e) { console.warn('[SB] deleteSB error:', e.message); return false; }
}
/* ── Debounced save queue — batches rapid saves so Supabase isn't hammered.
Writes are gated by _cloudWritesEnabled, which only flips true after the
initial sync has confirmed the cloud is reachable AND we have loaded the
real state. Without this gate, a paused/unreachable Supabase combined with
an empty localStorage (Firefox clear-on-close, fresh device, etc.) would
silently overwrite real cloud data with empty arrays. localStorage saves
continue regardless so the user can keep working offline. */
let _cloudWritesEnabled = false;
function enableCloudWrites() { _cloudWritesEnabled = true; }
function disableCloudWrites() { _cloudWritesEnabled = false; }
const _saveTimers = {};
function debouncedSaveSB(key, value, delay = 800) {
if (!_cloudWritesEnabled) return; // Sync hasn't confirmed yet — refuse to write
clearTimeout(_saveTimers[key]);
_saveTimers[key] = setTimeout(() => saveSB(key, value), delay);
}
/* ── Backup helpers — snapshot all data on login, keep last 10 ── */
const BACKUP_INDEX_KEY = 'taskflow-backup-index';
const BACKUP_DATA_PREFIX = 'taskflow-backup-';
const MAX_BACKUPS = 10;
async function createLoginBackup() {
if (!supabase) return false;
try {
const { data: { user }, error: authErr } = await supabase.auth.getUser();
if (authErr || !user) return false;
// Gather current cloud state. ANY read failure aborts — we will not write a
// partial/empty snapshot that could prune real backups out of the index.
const tasks = await loadSB(TASK_KEY);
const cats = await loadSB(CAT_KEY);
const mainTab = await loadSB('taskflow-mainTab');
const mmProjects = await loadSB(MM_PROJECTS_KEY);
const mmNodes = {};
if (mmProjects && Array.isArray(mmProjects)) {
for (const p of mmProjects) {
const nodes = await loadSB(MM_DATA_PREFIX + p.id);
if (nodes) mmNodes[p.id] = nodes;
}
}
// Refuse to snapshot an entirely empty state. This is a second line of
// defense behind the load-failure throws: if every key happens to be
// genuinely missing we still don't want to bury real backups under a
// stack of "empty" entries.
const hasAnyData =
(Array.isArray(tasks) && tasks.length > 0) ||
(cats && typeof cats === 'object' && Object.keys(cats).length > 0) ||
(Array.isArray(mmProjects) && mmProjects.length > 0);
if (!hasAnyData) {
console.log('[Backup] Skipping snapshot — cloud state is empty');
return false;
}
const snapshot = { tasks, cats, mainTab, mmProjects, mmNodes, ts: new Date().toISOString() };
// Skip if this snapshot is byte-identical to the latest existing backup.
// Otherwise no-op logins (e.g. signing in daily without editing) rotate
// the index, pruning real recovery points out the back. JSON.stringify
// is fine here: both inputs come from the same Supabase round-trip flow,
// so key ordering stays consistent. A false negative (creating an
// unnecessary backup) is harmless; a false positive is impossible.
let index = (await loadSB(BACKUP_INDEX_KEY)) || [];
if (index.length > 0) {
const latest = await loadSB(index[0].key);
if (latest) {
const sig = s => JSON.stringify({ tasks: s.tasks, cats: s.cats, mainTab: s.mainTab, mmProjects: s.mmProjects, mmNodes: s.mmNodes });
if (sig(latest) === sig(snapshot)) {
console.log('[Backup] Skipping snapshot — identical to latest at', index[0].ts);
return false;
}
}
}
const backupKey = BACKUP_DATA_PREFIX + snapshot.ts;
// Save snapshot
await saveSB(backupKey, snapshot);
// Update index — keep last MAX_BACKUPS
index.unshift({ ts: snapshot.ts, key: backupKey, taskCount: (tasks || []).length, projectCount: (mmProjects || []).length });
// Prune old backups
while (index.length > MAX_BACKUPS) {
const old = index.pop();
await deleteSB(old.key);
}
await saveSB(BACKUP_INDEX_KEY, index);
console.log('[Backup] Login snapshot created:', snapshot.ts);
return true;
} catch (e) { console.warn('[Backup] Failed to create backup:', e.message); return false; }
}
async function loadBackupIndex() {
try { return (await loadSB(BACKUP_INDEX_KEY)) || []; }
catch (e) { console.warn('[Backup] loadBackupIndex failed:', e.message); return []; }
}
async function restoreFromBackup(backupKey) {
if (!supabase) return false;
try {
const snapshot = await loadSB(backupKey);
if (!snapshot) return false;
// Restore tasks
if (snapshot.tasks) await saveSB(TASK_KEY, snapshot.tasks);
if (snapshot.cats) await saveSB(CAT_KEY, snapshot.cats);
if (snapshot.mainTab) await saveSB('taskflow-mainTab', snapshot.mainTab);
// Restore mindmap projects + nodes
if (snapshot.mmProjects) {
await saveSB(MM_PROJECTS_KEY, snapshot.mmProjects);
if (snapshot.mmNodes) {
for (const [pid, nodes] of Object.entries(snapshot.mmNodes)) {
await saveSB(MM_DATA_PREFIX + pid, nodes);
}
}
}
return snapshot;
} catch (e) { console.warn('[Backup] Restore failed:', e.message); return false; }
}
const uuid=()=>crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2)+Date.now().toString(36);
const now=()=>new Date().toISOString();
const msNow=()=>Date.now();
const DEFAULT_CATEGORIES={
'Work':{bg:'#A0F4C8',text:'#1a3a28'},
'Home':{bg:'#8EAADB',text:'#1a2a4e'},
'Personal':{bg:'#9AEBFE',text:'#1a3a4e'},
'Exercise':{bg:'#FFCCFF',text:'#4a1a4a'},
'Reef':{bg:'#CAAFFF',text:'#2a1a4e'},
'Band':{bg:'#F4C7C3',text:'#4a1a1a'},
'Other':{bg:'#D8D8D8',text:'#333'},
};
const STATUS_CONFIG={
'':{label:'Active',color:'#8a9bb8',bg:'transparent',rowBg:'transparent',sidebarColor:true},
'x':{label:'Done',color:'#6ecf6e',bg:'var(--c-status-done-bg)',rowBg:'rgba(110,207,110,0.08)',sidebarColor:true},
's':{label:'Skipped',color:'#777',bg:'var(--c-border)',rowBg:'rgba(120,120,120,0.06)',sidebarColor:true},
't':{label:'Tomorrow',color:'#f0c040',bg:'var(--c-status-tmrw-bg)',rowBg:'rgba(240,192,64,0.07)',sidebarColor:false},
'w':{label:'Weekly',color:'#50a0e0',bg:'var(--c-status-weekly-bg)',rowBg:'rgba(80,160,224,0.07)',sidebarColor:false},
'm':{label:'Monthly',color:'#e08050',bg:'var(--c-status-monthly-bg)',rowBg:'rgba(224,128,80,0.07)',sidebarColor:false},
'l':{label:'Long-term',color:'#b080e0',bg:'var(--c-status-long-bg)',rowBg:'rgba(176,128,224,0.07)',sidebarColor:false},
'u':{label:'Urgent',color:'#ff6b6b',bg:'var(--c-status-urgent-bg)',rowBg:'rgba(255,107,107,0.1)',sidebarColor:true},
};
const VIEWS=[
{key:'active',label:'Active',icon:'·'},
{key:'t',label:'Tomorrow',icon:'t'},
{key:'w',label:'Weekly',icon:'w'},
{key:'m',label:'Monthly',icon:'m'},
{key:'l',label:'Long-term',icon:'l'},
{key:'x',label:'Done',icon:'x'},
{key:'s',label:'Skipped',icon:'s'},
{key:'all',label:'All',icon:'≡'},
];
const RECURRENCE_PRESETS=[
{key:'daily',label:'Daily',icon:'☀'},
{key:'weekly',label:'Weekly',icon:'📅'},
{key:'biweekly',label:'Biweekly',icon:'📆'},
{key:'monthly',label:'Monthly',icon:'🗓'},
{key:'custom',label:'Custom...',icon:'⚙'},
];
const DAY_NAMES=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const DAY_NAMES_FULL=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const MONTH_NAMES=['January','February','March','April','May','June','July','August','September','October','November','December'];
const STATUS_KEYS=new Set(['x','s','t','w','m','l','u']);
const AUTO_RETURN_MS={t:86400000,w:604800000,m:2592000000};
const DUE_SOON_MS=604800000;
const TASK_KEY='taskflow-tasks';
const CAT_KEY='taskflow-cats';
function loadLS(k,fb){try{const v=localStorage.getItem(k);return v?JSON.parse(v):fb;}catch{return fb;}}
/* saveLS — returns true on success, false on failure (e.g. QuotaExceededError) */
let _lsWarningTimer=null;
function saveLS(k,v){try{localStorage.setItem(k,JSON.stringify(v));return true;}catch(e){console.error('[saveLS] FAILED for key:',k,e);if(!_lsWarningTimer){_lsWarningTimer=setTimeout(()=>{_lsWarningTimer=null;},10000);window.__lsSaveError={key:k,error:e.name,message:e.message,ts:Date.now()};window.dispatchEvent(new CustomEvent('ls-save-error',{detail:{key:k,error:e.name}}));}return false;}}
function fmt(iso){
if(!iso)return'';
return new Date(iso).toLocaleString('en-US',{month:'short',day:'numeric',hour:'numeric',minute:'2-digit',second:'2-digit',hour12:true});
}
function fmtDay(iso){return new Date(iso).toLocaleDateString('en-US',{weekday:'long',month:'long',day:'numeric',year:'numeric'});}
function dateKey(iso){return new Date(iso).toLocaleDateString('en-CA');}
/* ── Recurrence helpers ── */
function getNextOccurrence(task){
if(!task.recurrence||!task.dueDate)return null;
const rec=task.recurrence;
const curDate=new Date(task.dueDate);
let nextDate=new Date(curDate);
if(rec.type==='daily'){
nextDate.setDate(nextDate.getDate()+1);
}else if(rec.type==='weekly'){
nextDate.setDate(nextDate.getDate()+7);
}else if(rec.type==='biweekly'){
nextDate.setDate(nextDate.getDate()+14);
}else if(rec.type==='monthly'){
nextDate.setMonth(nextDate.getMonth()+1);
}else if(rec.type==='custom'&&rec.interval&&rec.unit){
if(rec.unit==='days')nextDate.setDate(nextDate.getDate()+rec.interval);
else if(rec.unit==='weeks')nextDate.setDate(nextDate.getDate()+rec.interval*7);
else if(rec.unit==='months')nextDate.setMonth(nextDate.getMonth()+rec.interval);
}
if(rec.endDate&&nextDate.toLocaleDateString('en-CA')>rec.endDate)return null;
return nextDate.toLocaleDateString('en-CA');
}
function cloneRecurringTask(task){
const nextDue=getNextOccurrence(task);
if(!nextDue)return null;
return{
...task,
id:uuid(),
status:'',
dueDate:nextDue,
statusChanged:null,
dateCompleted:null,
dateAdded:now(),
};
}
function describeRecurrence(rec){
if(!rec)return'';
if(rec.type==='daily')return'Every day';
if(rec.type==='weekly')return'Every week';
if(rec.type==='biweekly')return'Every 2 weeks';
if(rec.type==='monthly')return'Every month';
if(rec.type==='custom'&&rec.interval&&rec.unit){
const u=rec.unit==='days'?'day':(rec.unit==='weeks'?'week':'month');
return'Every '+rec.interval+' '+u+(rec.interval>1?'s':'');
}
return'';
}
/* Snooze timer — runs ONLY on cleared tasks (hidden from Active). When a
cleared Tomorrow/Weekly/Monthly task matures (24h/7d/30d after clearing),
it RETURNS to the Active view keeping its label; since it's now
activeVisible it also leaves its status tab (those show cleared tasks
only). A labeled task sitting in Active is inert — the timer re-arms only
when the user clears it again. Returns cascade to the task's cleared
subtree so children don't stay stranded invisible. */
function processAutoReturns(tasks){
const n=msNow();
const matured=tasks.filter(t=>t.autoReturn&&!t.activeVisible&&t.statusChanged&&AUTO_RETURN_MS[t.status]
&&n-new Date(t.statusChanged).getTime()>=AUTO_RETURN_MS[t.status]).map(t=>t.id);
if(!matured.length)return{tasks,changed:false};
const ids=expandToSubtreeIds(matured,tasks);
return{tasks:tasks.map(t=>ids.has(t.id)?{...t,activeVisible:true}:t),changed:true};
}
/* Due-soon: a CLEARED labeled task whose due date is near returns to Active
early (label kept), same as a matured snooze. Only fires on hidden tasks —
that guard is what prevents re-triggering every tick. */
function processDueDates(tasks){
const n=msNow();
const due=tasks.filter(t=>{
if(!t.dueDate||t.activeVisible||t.status===''||t.status==='x'||t.status==='s'||t.status==='u')return false;
const diff=new Date(t.dueDate).getTime()-n;
return diff<=DUE_SOON_MS&&diff>-86400000*30;
}).map(t=>t.id);
if(!due.length)return{tasks,changed:false};
const ids=expandToSubtreeIds(due,tasks);
return{tasks:tasks.map(t=>ids.has(t.id)?{...t,activeVisible:true}:t),changed:true};
}
/* Expand a set of task IDs to include every descendant in the given list.
Pure (no React closures) so it can be called inside setTasks(prev => ...)
with the latest state. Used wherever a subtree must move/hide/delete as a
unit — drag, "hide from active", clearChecked, Delete — so children never
get orphaned with stale activeVisible:true or a vanished parent. */
function expandToSubtreeIds(rootIds, taskList){
const out = new Set(rootIds);
let changed = true;
while(changed){
changed = false;
for(const t of taskList){
if(t.parentId && out.has(t.parentId) && !out.has(t.id)){ out.add(t.id); changed = true; }
}
}
return out;
}
/* ── Import/Export Utilities ── */
function parseXlsxDate(val){
if(!val)return null;
if(val instanceof Date||typeof val==='number'){
if(typeof val==='number'){const d=XLSX.SSF.parse_date_code(val);return new Date(d.y,d.m-1,d.d,d.H||0,d.M||0,d.S||0).toISOString();}
return new Date(val).toISOString();
}
const s=String(val).trim();if(!s)return null;
const d=new Date(s);
if(!isNaN(d.getTime()))return d.toISOString();
const cleaned=s.replace(/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\s*/i,'');
const d2=new Date(cleaned);
if(!isNaN(d2.getTime()))return d2.toISOString();
return null;
}
function importFromXlsx(file){
return new Promise((resolve,reject)=>{
const reader=new FileReader();
reader.onload=e=>{
try{
const data=new Uint8Array(e.target.result);
const wb=XLSX.read(data,{type:'array',cellDates:true});
const ws=wb.Sheets[wb.SheetNames[0]];
const rows=XLSX.utils.sheet_to_json(ws,{defval:null});
const STATUS_MAP={'x':'x','s':'s','t':'t','w':'w','m':'m','l':'l','u':'u'};
const tasks=[];
for(const row of rows){
const title=row['Todo 2026']||row['Todo']||row['Title']||row['title']||row['Task'];
if(!title||String(title).trim()==='')continue;
const rawStatus=row['x']||row['Status']||row['status']||'';
const status=STATUS_MAP[String(rawStatus).trim().toLowerCase()]||'';
const dateAdded=parseXlsxDate(row['Date Added'])||now();
const dateCompleted=parseXlsxDate(row['Date Completed'])||null;
const dueDate=parseXlsxDate(row['Due Date']);
const dueDateStr=dueDate?dueDate.split('T')[0]:null;
tasks.push({
id:uuid(),
title:String(title).trim(),
status,
order:row['Order']!=null?Number(row['Order']):tasks.length,
category:row['Category']&&String(row['Category']).trim()?String(row['Category']).trim():null,
importance:row['Importance']!=null?row['Importance']:null,
dateAdded,
dateCompleted:status==='x'?dateCompleted||dateAdded:null,
statusChanged:status?dateCompleted||dateAdded:null,
dueDate:dueDateStr,
notes:row['Notes']?String(row['Notes']):'',
autoReturn:status==='t'||status==='w'||status==='m',
recurrence:null,
startTime:null,
endTime:null,
});
}
resolve(tasks);
}catch(err){reject(err);}
};
reader.onerror=()=>reject(new Error('Failed to read file'));
reader.readAsArrayBuffer(file);
});
}
function importFromJson(file){
return new Promise((resolve,reject)=>{
const reader=new FileReader();
reader.onload=e=>{
try{
const data=JSON.parse(e.target.result);
if(data.tasks&&Array.isArray(data.tasks)){
resolve({tasks:data.tasks,categories:data.categories||null});
}else if(Array.isArray(data)){
resolve({tasks:data,categories:null});
}else{reject(new Error('Unrecognized JSON format'));}
}catch(err){reject(err);}
};
reader.onerror=()=>reject(new Error('Failed to read file'));
reader.readAsText(file);
});
}
function exportToJson(tasks,categories){
const data=JSON.stringify({version:1,exportedAt:now(),tasks,categories},null,2);
const blob=new Blob([data],{type:'application/json'});
const url=URL.createObjectURL(blob);
const a=document.createElement('a');
a.href=url;a.download='taskflow-export-'+new Date().toISOString().split('T')[0]+'.json';
document.body.appendChild(a);a.click();document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function exportToXlsx(tasks){
const rows=tasks.map(t=>({
'x':t.status||'',
'Todo 2026':t.title,
'Order':t.order??'',
'Category':t.category||'',
'Importance':t.importance||'',
'Date Added':t.dateAdded?new Date(t.dateAdded).toLocaleString('en-US',{weekday:'long',month:'long',day:'numeric',year:'numeric',hour:'numeric',minute:'2-digit',second:'2-digit',hour12:true}):'',
'Date Completed':t.dateCompleted?new Date(t.dateCompleted).toLocaleString('en-US',{weekday:'long',month:'long',day:'numeric',year:'numeric',hour:'numeric',minute:'2-digit',second:'2-digit',hour12:true}):'',
'Due Date':t.dueDate||'',
'Recurrence':describeRecurrence(t.recurrence)||'',
'Notes':t.notes||'',
}));
const ws=XLSX.utils.json_to_sheet(rows);
const colWidths=[{wch:4},{wch:45},{wch:6},{wch:14},{wch:12},{wch:42},{wch:42},{wch:12},{wch:20},{wch:30}];
ws['!cols']=colWidths;
const wb=XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb,ws,'Daily');
XLSX.writeFile(wb,'taskflow-export-'+new Date().toISOString().split('T')[0]+'.xlsx');
}
/* ── Import/Export Modal ── */
function ImportExportModal({onClose,onImport,onExportJson,onExportXlsx,taskCount}){
const ref=useRef(null);
const fileRef=useRef(null);
const[dragOver,setDragOver]=useState(false);
const[status,setStatus]=useState(null);
const[importMode,setImportMode]=useState('merge');
useEffect(()=>{
const h=e=>{if(ref.current&&!ref.current.contains(e.target))onClose();};
document.addEventListener('mousedown',h);return()=>document.removeEventListener('mousedown',h);
},[onClose]);
const handleFile=async(file)=>{
if(!file)return;
setStatus({type:'loading',msg:'Importing...'});
try{
let result;
if(file.name.endsWith('.json')){
result=await importFromJson(file);
}else if(file.name.endsWith('.xlsx')||file.name.endsWith('.xls')){
const tasks=await importFromXlsx(file);
result={tasks,categories:null};
}else{
setStatus({type:'error',msg:'Unsupported file type. Use .xlsx or .json'});return;
}
onImport(result.tasks,result.categories,importMode);
setStatus({type:'success',msg:'Imported '+result.tasks.length+' tasks!'});
setTimeout(onClose,1200);
}catch(err){
setStatus({type:'error',msg:'Import failed: '+err.message});
}
};
const handleDrop=e=>{e.preventDefault();setDragOver(false);const f=e.dataTransfer.files[0];if(f)handleFile(f);};
return(
<div style={{position:'fixed',inset:0,zIndex:1000,background:'var(--c-shadow-60)',display:'flex',alignItems:'center',justifyContent:'center',backdropFilter:'blur(4px)'}}>
<div ref={ref} style={{background:'var(--c-surface-3)',border:'1px solid var(--c-border)',borderRadius:14,padding:28,width:460,maxWidth:'90vw',boxShadow:'0 20px 60px var(--c-shadow-50)'}}>
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
<h2 style={{fontSize:20,fontWeight:600,color:'var(--c-text)',margin:0}}>Import / Export</h2>
<button onClick={onClose} style={{border:'none',background:'transparent',color:'var(--c-text-dim)',fontSize:22,cursor:'pointer',padding:'0 4px'}}
onMouseEnter={e=>e.currentTarget.style.color='var(--c-text)'} onMouseLeave={e=>e.currentTarget.style.color='var(--c-text-dim)'}>×</button>
</div>
{/* Import section */}
<div style={{marginBottom:24}}>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text-cool)',marginBottom:10,display:'flex',alignItems:'center',gap:8}}>
<span style={{fontSize:16}}>📥</span> Import Tasks
</div>
<div
onDragOver={e=>{e.preventDefault();setDragOver(true);}} onDragLeave={()=>setDragOver(false)} onDrop={handleDrop}
onClick={()=>fileRef.current?.click()}
style={{
border:dragOver?'2px solid var(--c-accent)':'2px dashed var(--c-surface-hi)',
borderRadius:10,padding:'24px 16px',textAlign:'center',cursor:'pointer',
background:dragOver?'var(--c-accent-06)':'var(--c-bg)',
transition:'all 0.15s',
}}>
<div style={{fontSize:28,marginBottom:8}}>{dragOver?'📂':'📄'}</div>
<div style={{fontSize:14,color:'var(--c-text-cool-2)',marginBottom:4}}>Drop a file here or click to browse</div>
<div style={{fontSize:12,color:'var(--c-text-muted)',fontFamily:"'JetBrains Mono',monospace"}}>.xlsx or .json</div>
<input ref={fileRef} type="file" accept=".xlsx,.xls,.json" style={{display:'none'}} onChange={e=>handleFile(e.target.files[0])}/>
</div>
{/* Import mode */}
<div style={{display:'flex',gap:8,marginTop:10}}>
{[{key:'merge',label:'Merge',desc:'Add to existing tasks'},{key:'replace',label:'Replace',desc:'Clear & replace all tasks'}].map(m=>(
<button key={m.key} onClick={()=>setImportMode(m.key)}
style={{
flex:1,border:importMode===m.key?'1.5px solid var(--c-accent)':'1.5px solid var(--c-border)',
borderRadius:8,padding:'8px 12px',cursor:'pointer',
background:importMode===m.key?'var(--c-accent-08)':'var(--c-bg)',
textAlign:'left',transition:'all 0.15s',
}}>
<div style={{fontSize:13,fontWeight:600,color:importMode===m.key?'var(--c-accent)':'var(--c-text-cool-2)'}}>{m.label}</div>
<div style={{fontSize:11,color:'var(--c-text-muted)',marginTop:2}}>{m.desc}</div>
</button>
))}
</div>
</div>
{/* Export section */}
<div>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text-cool)',marginBottom:10,display:'flex',alignItems:'center',gap:8}}>
<span style={{fontSize:16}}>📤</span> Export Tasks
<span style={{fontSize:12,color:'var(--c-text-muted)',fontWeight:400,fontFamily:"'JetBrains Mono',monospace"}}>{taskCount} tasks</span>
</div>
<div style={{display:'flex',gap:8}}>
<button onClick={onExportJson}
style={{flex:1,border:'1.5px solid var(--c-border)',borderRadius:8,padding:'12px 14px',cursor:'pointer',background:'var(--c-bg)',textAlign:'left',transition:'all 0.15s'}}
onMouseEnter={e=>e.currentTarget.style.borderColor='var(--c-accent)'} onMouseLeave={e=>e.currentTarget.style.borderColor='var(--c-border)'}>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text)'}}>TaskFlow JSON</div>
<div style={{fontSize:11,color:'var(--c-text-muted)',marginTop:3}}>Full data, re-importable into TaskFlow</div>
</button>
<button onClick={onExportXlsx}
style={{flex:1,border:'1.5px solid var(--c-border)',borderRadius:8,padding:'12px 14px',cursor:'pointer',background:'var(--c-bg)',textAlign:'left',transition:'all 0.15s'}}
onMouseEnter={e=>e.currentTarget.style.borderColor='var(--c-accent)'} onMouseLeave={e=>e.currentTarget.style.borderColor='var(--c-border)'}>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text)'}}>Excel (.xlsx)</div>
<div style={{fontSize:11,color:'var(--c-text-muted)',marginTop:3}}>Spreadsheet format, re-importable</div>
</button>
</div>
</div>
{/* Status message */}
{status&&(
<div style={{marginTop:14,padding:'8px 12px',borderRadius:6,fontSize:13,fontFamily:"'JetBrains Mono',monospace",
background:status.type==='success'?'rgba(110,207,110,0.1)':(status.type==='error'?'rgba(255,107,107,0.1)':'rgba(74,158,255,0.1)'),
color:status.type==='success'?'#6ecf6e':(status.type==='error'?'#ff6b6b':'var(--c-accent)'),
}}>{status.msg}</div>
)}
</div>
</div>
);
}
/* ── Mindmap Import/Export ── */
function exportMindmapJson(projects){
const data={version:1,type:'taskflow-mindmap',exportedAt:new Date().toISOString(),projects:projects.map(p=>{
const nodes=loadLS('taskflow-mm-'+p.id,[]); return{...p,nodes};
})};
const blob=new Blob([JSON.stringify(data,null,2)],{type:'application/json'});
const url=URL.createObjectURL(blob);
const a=document.createElement('a');
a.href=url;a.download='mindmap-export-'+new Date().toISOString().split('T')[0]+'.json';
document.body.appendChild(a);a.click();document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function importMindmapJson(file){
return new Promise((resolve,reject)=>{
const reader=new FileReader();
reader.onload=e=>{
try{
const data=JSON.parse(e.target.result);
if(data.type!=='taskflow-mindmap'||!Array.isArray(data.projects)){reject(new Error('Not a valid TaskFlow mindmap export'));return;}
resolve(data.projects);
}catch(err){reject(err);}
};
reader.onerror=()=>reject(new Error('Failed to read file'));
reader.readAsText(file);
});
}
function MindmapImportExportModal({onClose,projects,onImport,nodeCount,projectCount}){
const ref=useRef(null);
const fileRef=useRef(null);
const[dragOver,setDragOver]=useState(false);
const[status,setStatus]=useState(null);
const[importMode,setImportMode]=useState('merge');
useEffect(()=>{
const h=e=>{if(ref.current&&!ref.current.contains(e.target))onClose();};
document.addEventListener('mousedown',h);return()=>document.removeEventListener('mousedown',h);
},[onClose]);
const handleFile=async(file)=>{
if(!file)return;
if(!file.name.endsWith('.json')){setStatus({type:'error',msg:'Only .json files are supported'});return;}
setStatus({type:'loading',msg:'Importing...'});
try{
const importedProjects=await importMindmapJson(file);
onImport(importedProjects,importMode);
const totalNodes=importedProjects.reduce((s,p)=>s+(p.nodes?p.nodes.length:0),0);
setStatus({type:'success',msg:'Imported '+importedProjects.length+' project'+(importedProjects.length===1?'':'s')+' ('+totalNodes+' nodes)'});
setTimeout(onClose,1200);
}catch(err){setStatus({type:'error',msg:'Import failed: '+err.message});}
};
const handleDrop=e=>{e.preventDefault();setDragOver(false);const f=e.dataTransfer.files[0];if(f)handleFile(f);};
return(
<div style={{position:'fixed',inset:0,zIndex:1000,background:'var(--c-shadow-60)',display:'flex',alignItems:'center',justifyContent:'center',backdropFilter:'blur(4px)'}}>
<div ref={ref} style={{background:'var(--c-surface-3)',border:'1px solid var(--c-border)',borderRadius:14,padding:28,width:460,maxWidth:'90vw',boxShadow:'0 20px 60px var(--c-shadow-50)'}}>
<div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
<h2 style={{fontSize:20,fontWeight:600,color:'var(--c-text)',margin:0}}>Mindmap Import / Export</h2>
<button onClick={onClose} style={{border:'none',background:'transparent',color:'var(--c-text-dim)',fontSize:22,cursor:'pointer',padding:'0 4px'}}
onMouseEnter={e=>e.currentTarget.style.color='var(--c-text)'} onMouseLeave={e=>e.currentTarget.style.color='var(--c-text-dim)'}>×</button>
</div>
{/* Import section */}
<div style={{marginBottom:24}}>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text-cool)',marginBottom:10,display:'flex',alignItems:'center',gap:8}}>
<span style={{fontSize:16}}>📥</span> Import Mindmap
</div>
<div
onDragOver={e=>{e.preventDefault();setDragOver(true);}} onDragLeave={()=>setDragOver(false)} onDrop={handleDrop}
onClick={()=>fileRef.current?.click()}
style={{
border:dragOver?'2px solid var(--c-accent)':'2px dashed var(--c-surface-hi)',
borderRadius:10,padding:'24px 16px',textAlign:'center',cursor:'pointer',
background:dragOver?'var(--c-accent-06)':'var(--c-bg)',
transition:'all 0.15s',
}}>
<div style={{fontSize:28,marginBottom:8}}>{dragOver?'📂':'🗺️'}</div>
<div style={{fontSize:14,color:'var(--c-text-cool-2)',marginBottom:4}}>Drop a mindmap export here or click to browse</div>
<div style={{fontSize:12,color:'var(--c-text-muted)',fontFamily:"'JetBrains Mono',monospace"}}>.json (TaskFlow mindmap format)</div>
<input ref={fileRef} type="file" accept=".json" style={{display:'none'}} onChange={e=>handleFile(e.target.files[0])}/>
</div>
{/* Import mode */}
<div style={{display:'flex',gap:8,marginTop:10}}>
{[{key:'merge',label:'Merge',desc:'Add projects alongside existing'},{key:'replace',label:'Replace',desc:'Clear all & replace mindmap'}].map(m=>(
<button key={m.key} onClick={()=>setImportMode(m.key)}
style={{
flex:1,border:importMode===m.key?'1.5px solid var(--c-accent)':'1.5px solid var(--c-border)',
borderRadius:8,padding:'8px 12px',cursor:'pointer',
background:importMode===m.key?'var(--c-accent-08)':'var(--c-bg)',
textAlign:'left',transition:'all 0.15s',
}}>
<div style={{fontSize:13,fontWeight:600,color:importMode===m.key?'var(--c-accent)':'var(--c-text-cool-2)'}}>{m.label}</div>
<div style={{fontSize:11,color:'var(--c-text-muted)',marginTop:2}}>{m.desc}</div>
</button>
))}
</div>
</div>
{/* Export section */}
<div>
<div style={{fontSize:14,fontWeight:600,color:'var(--c-text-cool)',marginBottom:10,display:'flex',alignItems:'center',gap:8}}>
<span style={{fontSize:16}}>📤</span> Export Mindmap
<span style={{fontSize:12,color:'var(--c-text-muted)',fontWeight:400,fontFamily:"'JetBrains Mono',monospace"}}>{projectCount} project{projectCount===1?'':'s'}, {nodeCount} nodes</span>
</div>
<button onClick={()=>exportMindmapJson(projects)}