-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-safety-kit.html
More file actions
1003 lines (936 loc) · 58.2 KB
/
Copy pathdata-safety-kit.html
File metadata and controls
1003 lines (936 loc) · 58.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Safety Kit — portable backup/undo/sync module</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* ── Theme: cloned verbatim from Flowboard's "pearl" (light) theme variables. ──
This kit is fixed to light — no theme switcher — per request. If the host
app has its own theme system, these variables are the seam to re-point. */
:root{
--bg:#f5f5f7;--topbar:rgba(255,255,255,.88);
--bd:rgba(0,0,0,.09);--bd-s:rgba(0,0,0,.07);--bd-i:rgba(0,0,0,.15);
--txt:#1d1d1f;--txt-b:#000;--txt-m:#6e6e73;--txt-d:#86868b;--txt-dd:#aeaeb2;
--surf:#fff;--surf2:rgba(0,0,0,.04);--surf3:rgba(0,0,0,.07);
--modal:#fff;--card:rgba(255,255,255,.82);--card-h:#fff;
--inp:rgba(0,0,0,.05);--inp2:rgba(0,0,0,.06);--inp-d:rgba(0,0,0,.07);
--scroll:rgba(0,0,0,.12);--ghost-bg:rgba(0,0,0,.06);
--ghost-c:#6e6e73;--ghost-bd:rgba(0,0,0,.14);--dnd:rgba(0,100,200,.08);
}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--txt);font-family:'Segoe UI',system-ui,sans-serif;padding:28px 24px 60px}
.wrap{max-width:640px;margin:0 auto}
h1{font-size:19px;margin:0 0 4px;color:var(--txt-b)}
.sub{color:var(--txt-d);font-size:12px;margin-bottom:18px}
.banner{background:rgba(245,158,11,.1);border:1px solid rgba(245,158,11,.35);border-radius:10px;padding:14px 16px;margin-bottom:20px;font-size:12.5px;color:var(--txt-m);line-height:1.6}
.banner b{color:#b45309}
.topbar-row{display:flex;align-items:center;gap:10px;margin-bottom:16px}
.sync-badge{font-size:11px;font-weight:700;padding:5px 11px;border-radius:20px;border:1px solid var(--bd-i)}
.sync-badge.local{color:var(--txt-d);background:var(--surf2)}
.sync-badge.syncing{color:#b45309;background:rgba(245,158,11,.1);border-color:rgba(245,158,11,.3)}
.sync-badge.synced{color:#10b981;background:rgba(16,185,129,.1);border-color:rgba(16,185,129,.3)}
.sync-badge.error{color:#e11d48;background:rgba(225,29,72,.1);border-color:rgba(225,29,72,.3)}
.panel{background:var(--surf);border:1px solid var(--bd);border-radius:14px;padding:16px;margin-bottom:16px;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.panel h2{font-size:12px;margin:0 0 10px;color:var(--txt-d);text-transform:uppercase;letter-spacing:.05em;font-weight:700}
ul.item-list{list-style:none}
ul.item-list li{display:flex;align-items:center;gap:8px;padding:8px 4px;border-bottom:1px solid var(--bd)}
ul.item-list li:last-child{border-bottom:none}
ul.item-list li .txt{flex:1;font-size:13px}
ul.item-list li.done .txt{color:var(--txt-d);text-decoration:line-through}
input[type=text]{background:var(--inp);border:1px solid var(--bd-i);border-radius:9px;color:var(--txt);padding:8px 12px;font:inherit;flex:1;min-width:120px;outline:none}
/* ── Everything below this line is cloned as-is from Flowboard's own CSS ──
(button system, modal/overlay, snapshot list items, diff viewer) so the
backup UI itself is not a reinterpretation — it's the same interface. */
.btn{border:none;border-radius:9px;padding:7px 15px;cursor:pointer;font-size:13px;font-weight:700;transition:opacity .15s,transform .12s,box-shadow .15s;white-space:nowrap;font-family:inherit}
.btn:active{transform:scale(.96)}
.btn-primary{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff;box-shadow:0 2px 12px rgba(99,102,241,.3)}
.btn-ghost{background:var(--ghost-bg);color:var(--ghost-c);border:1px solid var(--ghost-bd)}
.btn-danger{background:rgba(251,113,133,.12);color:#f43f5e;border:1px solid rgba(251,113,133,.25)}
.btn-green{background:rgba(16,185,129,.12);color:#10b981;border:1px solid rgba(16,185,129,.25)}
.lbl{display:block;font-size:10px;color:var(--txt-d);font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:7px}
.finput{background:var(--inp);border:1px solid var(--bd-i);border-radius:9px;color:var(--txt);padding:8px 12px;font-size:13px;outline:none;width:100%;font-family:inherit}
.overlay{position:fixed;inset:0;background:rgba(0,0,0,.35);display:flex;align-items:center;justify-content:center;z-index:200;padding:16px}
.modal{background:var(--modal);border:1px solid var(--bd);border-radius:18px;padding:26px;width:510px;max-width:100%;max-height:92vh;overflow-y:auto;position:relative}
.bak-item{background:var(--surf2);border:1px solid var(--bd);border-radius:10px;padding:11px 13px;display:flex;align-items:center;gap:9px;margin-bottom:7px;transition:background .15s}
.bak-item:hover{background:var(--surf3)}
.bak-name{font-weight:700;font-size:13px;color:var(--txt-b);margin-bottom:2px;cursor:text}
.bak-date{font-size:11px;color:var(--txt-d)}
.bak-actions{display:flex;gap:5px;flex-shrink:0}
.bak-actions button{border:none;border-radius:6px;padding:4px 9px;cursor:pointer;font-size:11px;font-weight:700;transition:opacity .12s,transform .12s}
.bak-actions button:hover{opacity:.82}
.bak-actions button:active{transform:scale(.93)}
.auto-bak-item{background:var(--surf2);border:1px solid var(--bd);border-radius:10px;padding:10px 13px;display:flex;align-items:center;gap:9px;margin-bottom:7px;transition:background .15s}
.auto-bak-item:hover{background:var(--surf3)}
.auto-trigger-badge{font-size:10px;font-weight:700;padding:2px 7px;border-radius:20px;white-space:nowrap}
.diff-sheet-header{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--txt-d);padding:10px 0 5px;border-bottom:1px solid var(--bd);margin-bottom:4px}
.diff-sheet-header:not(:first-child){margin-top:12px}
.diff-row{display:flex;align-items:flex-start;gap:8px;padding:7px 9px;border-radius:7px;margin-bottom:3px;font-size:12px;line-height:1.45}
.diff-add{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.2)}
.diff-mod{background:rgba(245,158,11,.09);border:1px solid rgba(245,158,11,.22)}
.diff-del{background:rgba(225,29,72,.09);border:1px solid rgba(225,29,72,.2)}
.diff-type-badge{font-size:11px;font-weight:800;width:18px;text-align:center;flex-shrink:0;padding-top:1px}
.diff-badge-add{color:#10b981}
.diff-badge-mod{color:#b45309}
.diff-badge-del{color:#e11d48}
.diff-rownum{font-size:10px;color:var(--txt-dd);flex-shrink:0;padding-top:2px;min-width:24px}
.diff-expand-btn{background:none;border:none;cursor:pointer;color:var(--txt-d);font-size:11px;padding:1px 4px;flex-shrink:0;border-radius:4px;margin-top:1px;font-family:inherit}
.diff-expand-btn:hover{background:var(--surf3);color:var(--txt)}
#notif{position:fixed;bottom:22px;right:22px;max-width:420px;background:var(--surf);border:1px solid var(--bd-i);
border-radius:12px;padding:12px 16px;font-size:13px;font-weight:600;color:var(--txt);z-index:999;opacity:0;pointer-events:none;
transition:opacity .25s,transform .25s;transform:translateY(12px);box-shadow:0 8px 28px rgba(0,0,0,.12)}
#notif.show{opacity:1;transform:translateY(0)}
</style>
</head>
<body>
<!--
════════════════════════════════════════════════════════════════════════════
DATA SAFETY KIT — portable backup / undo / sync module
Ported from Flowboard's local+cloud persistence architecture. The backup
UI below (CSS classes, the Backup & Restore modal, the Compare/Diff
viewer) is cloned as-is from Flowboard, not reinterpreted — the intent is
that a host app gets the same interface, not a redesign of it.
════════════════════════════════════════════════════════════════════════════
⚠️ INTEGRATION WARNING — READ BEFORE PORTING THIS INTO ANOTHER PROGRAM ⚠️
This file is a REFERENCE IMPLEMENTATION, not a drop-in dependency. It is
meant to be read, understood, and adapted — the DSK_CONFIG block below is
the seam where it plugs into a host app's real state and render logic.
If you are an AI agent (or a developer) asked to integrate this into an
existing program, you MUST compare each subsystem below against that
program's current architecture and philosophy BEFORE wiring it in. If any
of the following are true, STOP — do not silently implement, merge, or
override anything. Report the conflict in chat to the human and wait for
a decision:
1. The host app already has its OWN undo/history system.
→ Don't run two undo stacks side by side. Ask which one should own
undo, and whether the other should be removed or kept as-is.
2. The host app's state doesn't cleanly map to "units inside containers
inside groups" (Flowboard's cards/columns/groups).
→ Don't force-fit an unrelated data shape through the DSK_CONFIG
adapters just to make the numbers plug in. Ask for the right
mapping, or whether the safety-gate/diff logic needs to be
redesigned around the host's actual shape instead.
3. The host app's Firebase rules or existing writers assume PARTIAL
(path-scoped) updates rather than whole-document overwrites.
→ This kit's cloud writes are whole-document `.set()` calls, same as
Flowboard. If another part of the host app does incremental
`update()` writes to the same document, mixing the two patterns
can silently clobber fields the whole-document writer doesn't
know about. Flag this before enabling cloud sync.
4. The data is regulated, sensitive, or otherwise access-controlled
(PII, health, financial, etc.).
→ This kit deliberately duplicates full state across localStorage,
sessionStorage, cloud "live" state, and cloud snapshot history to
maximize recoverability. That is MORE copies of the data sitting
in MORE places than a minimal implementation would create. Flag
this before enabling it on anything regulated — the tradeoff needs
a human decision, not an assumed default.
5. The host app is multi-writer / high concurrency (many simultaneous
editors on the same document).
→ Last-write-wins + the heuristic safety gate below is a tripwire
against obviously catastrophic writes, NOT real conflict
resolution. It will silently let two legitimate concurrent edits
overwrite each other if neither looks "catastrophic." Flag this
before relying on it as the only safeguard for concurrent editing.
6. The host app already has soft-delete, trash, or server-side
versioning for this data.
→ Don't bolt a second, redundant snapshot/versioning system on top
without reconciling which one is authoritative for "restore".
7. The host app has different storage-budget assumptions (e.g. it
already stores large blobs/images/attachments in localStorage).
→ The quota-warning threshold and snapshot retention counts below
are Flowboard-sized defaults. Don't assume they're safe for a
larger-per-record app; flag and recalculate instead.
8. The host app's mutations don't go through clearly identifiable,
individually-callable functions (e.g. they're generated, or routed
through a single reducer/dispatch instead of one function per
action).
→ The "call pushUndo() as the first line of every mutating function"
convention assumes that shape. If it doesn't fit, flag it — the
undo hook point needs to move to wherever mutations actually funnel
through (e.g. a single dispatch wrapper), not be sprinkled by hand.
None of the above are reasons to refuse the task — they're reasons to
surface the tradeoff to the human FIRST, since reconciling it after the
fact (once both systems are live and depended on) is much more expensive
than a five-minute conversation now.
════════════════════════════════════════════════════════════════════════════
-->
<div class="wrap">
<h1>🗄 Data Safety Kit</h1>
<div class="sub">Standalone demo of the portable backup / undo / sync module. Open this file directly in a browser — nothing to install.</div>
<div class="banner">
<b>This is a reference module, not a finished feature.</b> See the long HTML comment at the top of this
file's source for the full integration warning — it lists 8 specific conditions under which an AI or
developer porting this into another program should stop and ask a human before implementing, rather than
silently merging it in. <code>view-source:</code> this file or open it in an editor to read it.
</div>
<div class="topbar-row">
<button class="btn btn-primary" onclick="DSK.showBackupModal()">💾 Backup & Restore</button>
<button class="btn btn-ghost" onclick="DSK.undo()">↩ Undo</button>
<button class="btn btn-ghost" onclick="DSK.redo()">↪ Redo</button>
<span id="sync-badge" class="sync-badge local" style="margin-left:auto">💾 Local</span>
</div>
<div class="panel">
<h2>Demo list</h2>
<div style="display:flex;gap:8px;margin-bottom:4px">
<input type="text" id="new-item" placeholder="Add an item and press Enter…">
<button class="btn btn-green" onclick="demoAddItem()">Add</button>
</div>
<ul class="item-list" id="item-list"></ul>
</div>
<div class="panel">
<h2>Cloud sync (optional)</h2>
<div class="sub" style="margin:0">
Firebase is <b>not configured</b> in this demo. Fill in <code>DSK_CONFIG.firebaseConfig</code> and set
<code>DSK_CONFIG.firebaseEnabled = true</code> in the source to enable it — every subsystem (undo,
snapshots, export/import, the modal below) already runs fully local-only with no cloud dependency.
</div>
</div>
</div>
<div id="modal-root"></div>
<div id="notif"></div>
<script>
/* ════════════════════════════════════════════════════════════════════════
DSK_CONFIG — the ONLY section a host app should need to edit to adopt
this module. Everything below this block is generic and reads/writes
the host app's state exclusively through these adapters — it never
assumes a global variable name, a specific state shape, or that
Firebase is present.
════════════════════════════════════════════════════════════════════════ */
var DSK_CONFIG = {
// Namespaces every localStorage/sessionStorage key this kit creates, so
// it can't collide with the host app's own keys.
storagePrefix: 'dsk_demo',
// ── STATE ADAPTER ──────────────────────────────────────────────────────
// Point these at the host app's real root state variable and render
// function. The kit calls these instead of touching a global directly.
getState: function(){ return AppState; },
setState: function(next){ AppState = next; },
onStateApplied: function(){ renderDemo(); }, // call the host app's own render()
// ── SHAPE ADAPTER ──────────────────────────────────────────────────────
// Generalizes Flowboard's cards-inside-columns-inside-groups into three
// counting/enumeration hooks. If the host app has no natural equivalent
// for "containers" or "groups", return [] / 0 to disable that half of
// the safety gate rather than forcing a fake mapping.
countUnits: function(state){ return (state.items||[]).length; },
getContainerIds: function(state){ return []; }, // no "columns" in this demo
getGroupCount: function(state){ return 0; }, // no "groups" in this demo
// Must return [{id, label, data, container?}, ...] — used by the diff
// viewer. `container` is optional; when present, the diff groups rows
// under a "Sheet: <container>" header, same as Flowboard grouping by
// column. Omit it (as this demo does) for a flat list.
diffItems: function(state){
return (state.items||[]).map(function(it){ return {id: it.id, label: it.text, data: it}; });
},
// ── UI ADAPTER ──────────────────────────────────────────────────────────
notify: function(msg, ms){
var el = document.getElementById('notif');
if(!el) return;
el.textContent = msg; el.classList.add('show');
clearTimeout(DSK_CONFIG.notify._t);
DSK_CONFIG.notify._t = setTimeout(function(){ el.classList.remove('show'); }, ms || 7800);
},
updateSyncBadge: function(status){
var el = document.getElementById('sync-badge'); if(!el) return;
var map = {
local: {t:'💾 Local', cls:'local'},
syncing: {t:'🔄 Syncing', cls:'syncing'},
synced: {t:'☁ Synced', cls:'synced'},
error: {t:'⚠ No Sync', cls:'error'}
};
var s = map[status] || map.local;
el.textContent = s.t; el.className = 'sync-badge ' + s.cls;
},
// ── CLOUD (optional) ────────────────────────────────────────────────────
// Leave firebaseEnabled:false to run this kit fully local-only — every
// subsystem (undo, snapshots, export/import, the Backup modal) works
// with zero cloud dependency. Only flip this on after resolving warning
// #3 and #4 above with the host app's actual Firebase setup.
firebaseEnabled: false,
firebaseConfig: null, // { apiKey, databaseURL, ... }
boardKey: null, // cloud document key/path segment, e.g. a share code
// ── RETENTION / THRESHOLDS ──────────────────────────────────────────────
// Flowboard-sized defaults — see warning #7 before trusting these as-is
// for an app with larger per-record sizes.
maxUndoSteps: 50,
maxUndoSessionMirror: 10,
maxManualSnapshots: 25,
maxAutoSnapshots: 15,
idleSnapshotMs: 20 * 60 * 1000,
quotaWarnBytes: 4 * 1024 * 1024,
cloudWriteDebounceMs: 600,
autoSnapCloudDebounceMs: 2000
};
/* ════════════════════════════════════════════════════════════════════════
DSK — the module itself. Generic below this line; do not hardcode
anything demo-specific here. All host-app specifics live in DSK_CONFIG.
════════════════════════════════════════════════════════════════════════ */
var DSK = (function(){
var C = DSK_CONFIG;
function k(name){ return C.storagePrefix + '_' + name; }
function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g, function(c){ return {'&':'&','<':'<','>':'>','"':'"'}[c]; }); }
var _undoStack = [], _redoStack = [], _undoInProgress = false;
var _idleTimer = null, _savesSinceIdle = 0;
var _cloudEnabled = false, _db = null, _stateRef = null, _autoSnapRef = null;
var _pendingWrites = 0, _syncTimer = null, _remoteBaseline = null, _skipCloudWrite = false;
var _diffRows = null;
function uid(){ return '_' + Math.random().toString(36).slice(2, 9); }
function nowIso(){ return new Date().toLocaleString(); }
// ── LOCAL PERSISTENCE (always on, no cloud dependency) ──────────────────
function save(){
var state = C.getState();
if(!_skipCloudWrite) state.lastModified = Date.now();
var data;
try{
data = JSON.stringify(state);
localStorage.setItem(k('live'), data);
var used = new Blob([data]).size
+ new Blob([localStorage.getItem(k('manual_snaps')) || '']).size
+ new Blob([localStorage.getItem(k('auto_snaps')) || '']).size;
if(used > C.quotaWarnBytes && !save._warned){
save._warned = true;
C.notify('⚠️ Storage nearly full (' + Math.round(used/1024/1024*10)/10 + 'MB used) — export a backup soon!');
} else if(used <= C.quotaWarnBytes){
save._warned = false;
}
}catch(e){
// Distinguish WHY the local write failed instead of guessing — mirrors
// the fix made in Flowboard's own save() after a false-positive report
// where the sync badge showed "synced" while the local write had
// actually failed (the two paths are fully decoupled; see below).
console.error('[DSK] Local write failed:', e);
var boardKB = data ? Math.round(new Blob([data]).size/1024) : '?';
var isQuota = e && (e.name === 'QuotaExceededError' || e.code === 22 || e.code === 1014 || e.name === 'NS_ERROR_DOM_QUOTA_REACHED');
var isSecurity = e && e.name === 'SecurityError';
var msg;
if(isQuota){
msg = '❌ Local save FAILED — storage quota exceeded (state ~' + boardKB + 'KB). Delete old snapshots or export a backup now — this change is NOT saved on this device.';
}else if(isSecurity){
msg = '❌ Local save FAILED — this browser is blocking local storage (private/incognito mode, or site data disabled). This change is NOT saved on this device.';
}else{
msg = '❌ Local save FAILED — ' + (e && e.name ? e.name : 'unknown error') + '. This change may NOT be saved — see console.';
}
C.notify(msg);
}
// Idle auto-snapshot: fires C.idleSnapshotMs after the last real change.
if(!_skipCloudWrite && !_undoInProgress){
_savesSinceIdle++;
clearTimeout(_idleTimer);
_idleTimer = setTimeout(function(){
if(_savesSinceIdle > 0) createAutoSnapshot('Idle checkpoint – ' + nowIso(), 'idle');
}, C.idleSnapshotMs);
}
if(!_skipCloudWrite && _cloudEnabled) scheduleCloudPush();
}
// ── UNDO / REDO ───────────────────────────────────────────────────────
// Convention: call DSK.pushUndo() as the FIRST line of every mutating
// function in the host app, after any guard/early-return checks but
// before the mutation itself. See integration warning #8 if the host
// app's mutations don't funnel through individually-callable functions.
function pushUndo(){
if(_skipCloudWrite || _undoInProgress) return;
_undoStack.push(JSON.stringify(C.getState()));
if(_undoStack.length > C.maxUndoSteps) _undoStack.shift();
_redoStack = [];
persistUndoSession();
}
function undo(){
if(_undoStack.length === 0) return;
_redoStack.push(JSON.stringify(C.getState()));
if(_redoStack.length > C.maxUndoSteps) _redoStack.shift();
_undoInProgress = true;
C.setState(JSON.parse(_undoStack.pop()));
save(); C.onStateApplied();
_undoInProgress = false;
persistUndoSession();
C.notify('↩ Undone' + (_undoStack.length > 0 ? ' (' + _undoStack.length + ' more)' : ''));
}
function redo(){
if(_redoStack.length === 0) return;
_undoStack.push(JSON.stringify(C.getState()));
if(_undoStack.length > C.maxUndoSteps) _undoStack.shift();
_undoInProgress = true;
C.setState(JSON.parse(_redoStack.pop()));
save(); C.onStateApplied();
_undoInProgress = false;
persistUndoSession();
C.notify('↪ Redone' + (_redoStack.length > 0 ? ' (' + _redoStack.length + ' more)' : ''));
}
function persistUndoSession(){
try{ sessionStorage.setItem(k('undo'), JSON.stringify(_undoStack.slice(-C.maxUndoSessionMirror))); }catch(e){}
}
function restoreUndoSession(){
try{
var stored = sessionStorage.getItem(k('undo'));
if(!stored) return;
var arr = JSON.parse(stored);
if(Array.isArray(arr) && arr.length){
_undoStack = arr;
C.notify('↩ Undo history restored from last session (' + arr.length + ' step' + (arr.length !== 1 ? 's' : '') + ')');
}
}catch(e){}
}
// ── MANUAL SNAPSHOTS (local-only by design — see integration note) ─────
function getManualSnapshots(){ try{ return JSON.parse(localStorage.getItem(k('manual_snaps')) || '[]'); }catch(e){ return []; } }
function setManualSnapshots(a){ localStorage.setItem(k('manual_snaps'), JSON.stringify(a)); }
function createManualSnapshot(name){
if(name === null) return; // user cancelled the prompt
var a = getManualSnapshots();
a.unshift({ id: uid(), name: name || ('Snapshot ' + nowIso()), ts: Date.now(), units: C.countUnits(C.getState()), data: JSON.stringify(C.getState()) });
if(a.length > C.maxManualSnapshots) a.splice(C.maxManualSnapshots);
setManualSnapshots(a);
C.notify('📌 Snapshot saved!');
if(document.getElementById('modal-root').querySelector('.overlay')) showBackupModal();
}
function renameManualSnapshot(id){
var baks = getManualSnapshots();
var b = baks.find(function(x){ return x.id === id; });
if(!b) return;
var el = document.getElementById('bakname_' + id);
if(!el) return;
var orig = b.name;
var inp = document.createElement('input');
inp.value = orig;
inp.style.cssText = 'background:transparent;border:none;border-bottom:1px solid #3b82f6;color:var(--txt-b);font-size:13px;font-weight:700;outline:none;width:100%;font-family:inherit;padding:1px 0';
inp.onblur = function(){
var v = inp.value.trim() || orig;
baks.forEach(function(x){ if(x.id === id) x.name = v; });
setManualSnapshots(baks); showBackupModal();
};
inp.onkeydown = function(e){
if(e.key === 'Enter'){ inp.blur(); }
else if(e.key === 'Escape'){ inp.value = orig; inp.blur(); }
};
el.replaceWith(inp); inp.focus(); inp.select();
}
function restoreManualSnapshot(id){
var b = getManualSnapshots().find(function(x){ return x.id === id; });
if(!b || !confirm('Restore this snapshot? Current state will be replaced.')) return;
autoSnapBefore('Before: Restore snapshot – ' + nowIso());
_undoStack = []; _redoStack = []; persistUndoSession();
C.setState(JSON.parse(b.data)); save(); C.onStateApplied();
C.notify('✅ Restored from snapshot!');
closeModal();
}
function deleteManualSnapshot(id){
setManualSnapshots(getManualSnapshots().filter(function(x){ return x.id !== id; }));
showBackupModal();
}
// ── AUTO SNAPSHOTS ────────────────────────────────────────────────────
// Triggers: session-start (if state changed since last auto-snap),
// idle timer (see save()), and pre-destructive-action via autoSnapBefore().
function getAutoSnapshots(){ try{ return JSON.parse(localStorage.getItem(k('auto_snaps')) || '[]'); }catch(e){ return []; } }
function setAutoSnapshots(a){
try{ localStorage.setItem(k('auto_snaps'), JSON.stringify(a)); }
catch(e){ console.warn('[DSK] Storage full — auto-snapshot skipped locally (still attempting cloud push).'); }
}
function createAutoSnapshot(name, trigger){
var a = getAutoSnapshots();
var snap = { id: uid(), name: name, ts: Date.now(), trigger: trigger || 'auto', units: C.countUnits(C.getState()), data: JSON.stringify(C.getState()) };
a.unshift(snap);
var dropped = a.length > C.maxAutoSnapshots ? a.splice(C.maxAutoSnapshots) : [];
setAutoSnapshots(a);
_savesSinceIdle = 0;
if(_cloudEnabled) pushAutoSnapToCloud(snap, dropped);
if(document.getElementById('modal-root').querySelector('.overlay')) showBackupModal();
}
function sessionStartSnapshot(){
var ts = C.getState().lastModified || 0;
if(ts === 0) return; // nothing saved yet — skip
var autos = getAutoSnapshots();
var lastTs = autos.length ? autos[0].ts : 0;
if(ts <= lastTs) return; // no changes since last auto-snap
createAutoSnapshot('Opened – ' + nowIso(), 'session');
}
function autoSnapBefore(label){ createAutoSnapshot(label, 'destructive'); }
function restoreAutoSnapshot(id){
var b = getAutoSnapshots().find(function(x){ return x.id === id; });
if(!b || !confirm('Restore this auto-snapshot? Current state will be replaced.')) return;
autoSnapBefore('Before: Restore auto-snapshot – ' + nowIso());
_undoStack = []; _redoStack = []; persistUndoSession();
C.setState(JSON.parse(b.data)); save(); C.onStateApplied();
C.notify('✅ Restored from auto-snapshot!');
closeModal();
}
function deleteAutoSnapshot(id){
var remaining = getAutoSnapshots().filter(function(x){ return x.id !== id; });
setAutoSnapshots(remaining);
if(_cloudEnabled && _autoSnapRef) _autoSnapRef.child(id).remove().catch(function(){});
showBackupModal();
}
// ── EXPORT / IMPORT ──────────────────────────────────────────────────
function exportState(snapshotId){
var data, name;
if(snapshotId){
var b = getManualSnapshots().concat(getAutoSnapshots()).find(function(x){ return x.id === snapshotId; });
if(!b) return;
data = b.data; name = b.name;
}else{
data = JSON.stringify(C.getState()); name = C.storagePrefix + '_export';
}
var a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([data], { type: 'application/json' }));
a.download = name.replace(/[^\w\s-]/g, '').trim().replace(/\s+/g, '_') + '_' + Date.now() + '.json';
a.click();
}
function importState(){
var inp = document.createElement('input'); inp.type = 'file'; inp.accept = '.json';
inp.onchange = function(e){
var file = e.target.files[0]; if(!file) return;
var r = new FileReader();
r.onload = function(ev){
try{
var d = JSON.parse(ev.target.result);
if(!confirm('Import this file? Current state will be replaced.')) return;
autoSnapBefore('Before: Import – ' + nowIso());
_undoStack = []; _redoStack = []; persistUndoSession();
C.setState(d); save(); C.onStateApplied();
C.notify('✅ Imported!'); closeModal();
}catch(e2){ alert('Invalid file — could not parse JSON.'); }
};
r.readAsText(file);
};
inp.click();
}
// ── FORCE PULL / PUSH (cloud override — only relevant if cloud enabled) ──
function forcePushToCloud(){
if(!_cloudEnabled || !_stateRef){ C.notify('⚠️ Not connected to a cloud document.'); return; }
if(!confirm('Push your local state to the cloud?\n\nThis will overwrite the cloud version with your current local state.')) return;
autoSnapBefore('Before: Manual force-push to cloud – ' + nowIso());
C.updateSyncBadge('syncing');
_pendingWrites++;
var state = C.getState(); state.lastModified = Date.now(); save();
_stateRef.set(state).then(function(){
_pendingWrites = Math.max(0, _pendingWrites - 1);
setRemoteBaseline(state);
C.updateSyncBadge('synced');
C.notify('☁ State pushed to cloud.');
if(document.getElementById('modal-root').querySelector('.overlay')) showBackupModal();
}).catch(function(err){
_pendingWrites = Math.max(0, _pendingWrites - 1);
C.updateSyncBadge('error');
C.notify('❌ Push failed: ' + err.message);
});
}
function forcePullFromCloud(){
if(!_cloudEnabled || !_stateRef){ C.notify('⚠️ Not connected to a cloud document.'); return; }
if(!confirm('Pull the cloud state to this device?\n\nThis will replace your current local state with the cloud version.')) return;
autoSnapBefore('Before: Manual force-pull from cloud – ' + nowIso());
C.updateSyncBadge('syncing');
_stateRef.once('value').then(function(snap){
var remote = snap.val();
if(!remote){ C.notify('⚠️ No cloud data found.'); C.updateSyncBadge('synced'); return; }
setRemoteBaseline(remote);
C.setState(remote); C.onStateApplied();
_skipCloudWrite = true; save(); _skipCloudWrite = false;
C.updateSyncBadge('synced');
C.notify('⬇ Pulled from cloud.');
if(document.getElementById('modal-root').querySelector('.overlay')) showBackupModal();
}).catch(function(err){
C.updateSyncBadge('error');
C.notify('❌ Pull failed: ' + err.message);
});
}
// ── DIFF VIEWER ───────────────────────────────────────────────────────
// Generic: relies entirely on C.diffItems(state) -> [{id,label,data,container?}, ...]
function computeDiff(stateA, stateB){
var itemsA = C.diffItems(stateA), itemsB = C.diffItems(stateB);
var mapA = {}, mapB = {};
itemsA.forEach(function(i){ mapA[i.id] = i; });
itemsB.forEach(function(i){ mapB[i.id] = i; });
var added = [], deleted = [], modified = [];
Object.keys(mapB).forEach(function(id){
if(!mapA[id]) added.push(mapB[id]);
else if(JSON.stringify(mapA[id].data) !== JSON.stringify(mapB[id].data)) modified.push({ before: mapA[id], after: mapB[id] });
});
Object.keys(mapA).forEach(function(id){ if(!mapB[id]) deleted.push(mapA[id]); });
return { added: added, deleted: deleted, modified: modified };
}
// ── SAFETY GATE ───────────────────────────────────────────────────────
// A heuristic tripwire against obviously catastrophic writes, NOT real
// conflict resolution. See integration warning #5.
function isSafeWrite(state){
if(!_remoteBaseline) return true;
var units = C.countUnits(state);
var containerIds = C.getContainerIds(state);
var groups = C.getGroupCount(state);
if(_remoteBaseline.groups > 0 && groups === 0) return false;
if(_remoteBaseline.containerIds.length > 0 && containerIds.length === 0) return false;
if(_remoteBaseline.units > 3 && units === 0) return false;
var dropped = _remoteBaseline.units - units;
if(_remoteBaseline.units > 0 && dropped / _remoteBaseline.units > 0.75 && dropped > 5) return false;
if(_remoteBaseline.containerIds.length > 2 && containerIds.length > 0){
var matches = containerIds.filter(function(id){ return _remoteBaseline.containerIds.indexOf(id) !== -1; }).length;
if(matches / _remoteBaseline.containerIds.length < 0.2) return false;
}
return true;
}
function setRemoteBaseline(state){
_remoteBaseline = { units: C.countUnits(state), containerIds: C.getContainerIds(state), groups: C.getGroupCount(state) };
}
// ── CLOUD SYNC (optional — no-ops entirely if firebaseEnabled is false) ──
// NOTE: per-edit writes below are whole-document `.set()` calls, same
// tradeoff as Flowboard. Auto-snapshots, however, are stored as
// INDIVIDUALLY KEYED children (autoSnapRef.child(id).set(...) /
// .child(id).remove()) rather than one big array overwrite — this fixes
// a known inefficiency in the original Flowboard implementation, where
// a single new snapshot rewrote the entire snapshot history (up to 15x
// the document size) in one write. Do not regress to the array-overwrite
// pattern when porting this.
function connectCloud(){
if(!C.firebaseEnabled || !C.firebaseConfig || !C.boardKey) return;
if(!window.firebase){ console.warn('[DSK] firebase SDK not loaded — cloud sync disabled.'); return; }
if(!firebase.apps.length) firebase.initializeApp(C.firebaseConfig);
_db = firebase.database();
_stateRef = _db.ref('dsk/' + C.boardKey + '/state');
_autoSnapRef = _db.ref('dsk/' + C.boardKey + '/autoSnaps');
_cloudEnabled = true;
C.updateSyncBadge('syncing');
_stateRef.once('value').then(function(snap){
var remote = snap.val();
if(remote === null){
_pendingWrites++;
_stateRef.set(C.getState()).then(function(){ _pendingWrites--; setRemoteBaseline(C.getState()); C.updateSyncBadge('synced'); });
return;
}
setRemoteBaseline(remote);
var localTs = C.getState().lastModified || 0, remoteTs = remote.lastModified || 0;
if(localTs >= remoteTs){
C.setState(remote); // trust remote on connect unless local is strictly newer — mirrors Flowboard's "never push on first fire" fix
}
C.onStateApplied();
C.updateSyncBadge('synced');
_stateRef.on('value', function(s2){
if(_pendingWrites > 0) return; // ignore echo of our own write
var r2 = s2.val(); if(!r2) return;
setRemoteBaseline(r2);
if((r2.lastModified || 0) > (C.getState().lastModified || 0)){
C.setState(r2); C.onStateApplied();
}
});
});
}
function scheduleCloudPush(){
clearTimeout(_syncTimer);
_syncTimer = setTimeout(function(){
var state = C.getState();
if(!isSafeWrite(state)){
C.updateSyncBadge('error');
C.notify('🛑 Sync blocked — this write would delete most of your data. Reload to resync before continuing.');
console.error('[DSK] Cloud write blocked by safety gate. Baseline:', _remoteBaseline, 'Attempted units:', C.countUnits(state));
return;
}
_pendingWrites++;
C.updateSyncBadge('syncing');
_stateRef.set(state).then(function(){
_pendingWrites = Math.max(0, _pendingWrites - 1);
setRemoteBaseline(state);
if(_pendingWrites === 0) C.updateSyncBadge('synced');
}).catch(function(err){
_pendingWrites = Math.max(0, _pendingWrites - 1);
C.updateSyncBadge('error');
console.error('[DSK] Cloud write failed:', err);
var code = err && err.code, msg;
if(code === 'PERMISSION_DENIED') msg = '⚠ Cloud sync FAILED — permission denied. Local copy is safe.';
else if(typeof navigator !== 'undefined' && navigator.onLine === false) msg = '⚠ Cloud sync FAILED — offline. Local copy is safe; will retry on reconnect.';
else msg = '⚠ Cloud sync FAILED — ' + (code || (err && err.message) || 'unknown error') + '. Local copy is safe.';
C.notify(msg);
});
}, C.cloudWriteDebounceMs);
}
function pushAutoSnapToCloud(snap, droppedSnaps){
if(!_cloudEnabled) return;
clearTimeout(pushAutoSnapToCloud._t);
pushAutoSnapToCloud._t = setTimeout(function(){
_autoSnapRef.child(snap.id).set(snap).catch(function(err){ console.warn('[DSK] Auto-snap cloud push failed:', err); });
(droppedSnaps || []).forEach(function(old){ _autoSnapRef.child(old.id).remove().catch(function(){}); });
}, C.autoSnapCloudDebounceMs);
}
/* ══════════════════════════════════════════════════════════════════════
BACKUP UI — cloned from Flowboard's showBackupModal()/showDiffPicker()/
showSnapshotDiff(). The markup, class names, and layout are the same;
only the data source (DSK's generic getters instead of Flowboard's
getBaks()/getAutoBaks()/S) and the omission of Flowboard's USB-drive
section (a hardware-file-access feature this generic kit doesn't
implement) differ from the original.
══════════════════════════════════════════════════════════════════════ */
function setModal(html, w, cb){
var root = document.getElementById('modal-root'); root.innerHTML = '';
var ov = document.createElement('div'); ov.className = 'overlay'; ov.onclick = closeModal;
var m = document.createElement('div'); m.className = 'modal';
if(w) m.style.width = w;
m.onclick = function(e){ e.stopPropagation(); };
m.innerHTML = html;
ov.appendChild(m); root.appendChild(ov);
if(cb) setTimeout(cb, 10);
}
function closeModal(){ document.getElementById('modal-root').innerHTML = ''; }
function triggerBadge(trigger){
var map = {
session: { label:'Session start', bg:'rgba(96,165,250,.15)', color:'#3b82f6' },
idle: { label:'Idle checkpoint', bg:'rgba(168,85,247,.15)', color:'#a855f7' },
destructive: { label:'Before delete', bg:'rgba(244,63,94,.12)', color:'#f43f5e' },
auto: { label:'Auto', bg:'rgba(148,163,184,.15)', color:'#6b7280' }
};
var t = map[trigger] || map.auto;
return '<span class="auto-trigger-badge" style="background:' + t.bg + ';color:' + t.color + '">' + t.label + '</span>';
}
function showBackupModal(){
var baks = getManualSnapshots();
var autos = getAutoSnapshots();
var autoHtml = autos.length === 0
? '<div style="color:var(--txt-dd);font-size:13px;padding:12px 0 4px">No auto-snapshots yet — they appear after your first session.</div>'
: autos.map(function(b){
return '<div class="auto-bak-item">' +
'<div style="flex:1">' +
'<div class="bak-name" style="cursor:default">' + esc(b.name) + '</div>' +
'<div class="bak-date">' + new Date(b.ts).toLocaleString() + ' · ' + b.units + ' item' + (b.units !== 1 ? 's' : '') + ' · ' + triggerBadge(b.trigger) + '</div>' +
'</div>' +
'<div class="bak-actions">' +
'<button onclick="DSK.restoreAutoSnapshot(\'' + b.id + '\')" style="background:rgba(96,165,250,.15);color:#3b82f6">Restore</button>' +
'<button onclick="DSK.deleteAutoSnapshot(\'' + b.id + '\')" style="background:rgba(225,29,72,.1);color:#e11d48">Delete</button>' +
'</div></div>';
}).join('');
var bakHtml = baks.length === 0
? '<div style="color:var(--txt-dd);font-size:13px;padding:16px 0 8px">No snapshots yet.</div>'
: baks.map(function(b){
return '<div class="bak-item">' +
'<div style="flex:1"><div id="bakname_' + b.id + '" class="bak-name" ondblclick="DSK.renameManualSnapshot(\'' + b.id + '\')" title="Double-click to rename">' + esc(b.name) + '</div>' +
'<div class="bak-date">' + new Date(b.ts).toLocaleString() + ' · ' + b.units + ' item' + (b.units !== 1 ? 's' : '') + '</div></div>' +
'<div class="bak-actions">' +
'<button onclick="DSK.restoreManualSnapshot(\'' + b.id + '\')" style="background:rgba(96,165,250,.15);color:#3b82f6">Restore</button>' +
'<button onclick="DSK.exportState(\'' + b.id + '\')" style="background:var(--surf3);color:var(--txt-m)">Export</button>' +
'<button onclick="DSK.deleteManualSnapshot(\'' + b.id + '\')" style="background:rgba(225,29,72,.1);color:#e11d48">Delete</button>' +
'</div></div>';
}).join('');
var ul = _undoStack.length, rl = _redoStack.length;
var undoBar = '<div style="display:flex;gap:8px;align-items:center;padding:9px 13px;background:var(--surf2);border:1px solid var(--bd);border-radius:10px;margin-bottom:18px;font-size:12px;color:var(--txt-m)">' +
'<span style="flex:1">↩ <strong style="color:var(--txt)">' + ul + '</strong> undo step' + (ul !== 1 ? 's' : '') + ' in memory' +
(rl > 0 ? ' · ↪ <strong style="color:var(--txt)">' + rl + '</strong> redo step' + (rl !== 1 ? 's' : '') : '') + '</span>' +
(ul > 0 ? '<button class="btn btn-ghost" style="padding:3px 9px;font-size:11px" onclick="DSK.undo();DSK.showBackupModal()">↩ Undo</button>' : '') + '</div>';
var _totalSnaps = baks.length + autos.length;
setModal(
'<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px">' +
'<div style="font-size:17px;font-weight:800;color:var(--txt-b)">💾 Backup & Restore</div>' +
'<div style="display:flex;gap:6px">' +
(_totalSnaps >= 2 ? '<button class="btn btn-ghost" style="padding:4px 10px;font-size:12px" onclick="DSK.showDiffPicker()">⇄ Compare</button>' : '') +
'<button class="btn btn-ghost" style="padding:4px 10px;font-size:12px" onclick="DSK.closeModal()">✕</button>' +
'</div>' +
'</div>' +
undoBar +
'<div style="background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.2);border-radius:10px;padding:11px 14px;margin-bottom:18px;font-size:13px;color:#10b981">' +
'✅ <strong>Auto-save is ON</strong> — every change saves instantly to local storage' + (_cloudEnabled ? ' and cloud' : '.') +
'</div>' +
(_cloudEnabled ?
'<label class="lbl">Cloud Sync Override</label>' +
'<div style="display:flex;gap:9px;margin-bottom:20px">' +
'<button class="btn btn-ghost" style="flex:1;font-size:12px" onclick="DSK.forcePullFromCloud()">⬇ Pull from Cloud</button>' +
'<button class="btn btn-ghost" style="flex:1;font-size:12px" onclick="DSK.forcePushToCloud()">⬆ Push to Cloud</button>' +
'</div>'
: '') +
'<label class="lbl">Auto Snapshots (' + autos.length + '/' + C.maxAutoSnapshots + ')</label>' +
'<div style="max-height:180px;overflow-y:auto;padding-right:2px;margin-bottom:20px">' + autoHtml + '</div>' +
'<label class="lbl">Save Manual Snapshot</label>' +
'<div style="display:flex;gap:9px;margin-bottom:18px">' +
'<input id="bak-n" class="finput" placeholder="Snapshot name…" style="flex:1" onkeydown="if(event.key===\'Enter\')DSK.createManualSnapshot(document.getElementById(\'bak-n\').value)">' +
'<button class="btn btn-green" onclick="DSK.createManualSnapshot(document.getElementById(\'bak-n\').value)">📌 Save</button>' +
'</div>' +
'<label class="lbl">Transfer Data</label>' +
'<div style="display:flex;gap:9px;margin-bottom:22px">' +
'<button class="btn btn-ghost" style="flex:1;font-size:12px" onclick="DSK.exportState()">⬇ Export .json</button>' +
'<button class="btn btn-ghost" style="flex:1;font-size:12px" onclick="DSK.importState()">⬆ Import .json</button>' +
'</div>' +
'<label class="lbl">Manual Snapshots (' + baks.length + '/' + C.maxManualSnapshots + ')</label>' +
'<div style="max-height:240px;overflow-y:auto;padding-right:2px">' + bakHtml + '</div>' +
'<div style="margin-top:14px;padding:11px 13px;background:var(--surf2);border-radius:10px;font-size:12px;color:var(--txt-d);line-height:1.8">' +
'<strong style="color:var(--txt-m)">💡 Transfer your data:</strong><br>' +
'1. Export as .json → save to USB or email<br>' +
'2. On another device: open this app → Import .json' +
'</div>',
'580px', function(){ var i = document.getElementById('bak-n'); if(i) i.focus(); });
}
function showDiffPicker(){
var allSnaps = [];
getManualSnapshots().forEach(function(b){ allSnaps.push({ id: b.id, label: b.name, ts: b.ts, src: 'm' }); });
getAutoSnapshots().forEach(function(b){ allSnaps.push({ id: b.id, label: b.name, ts: b.ts, src: 'a' }); });
allSnaps.sort(function(a, b){ return b.ts - a.ts; });
if(allSnaps.length < 2){ C.notify('⚠️ Need at least 2 snapshots to compare.'); return; }
var opts = allSnaps.map(function(s){ return '<option value="' + s.id + '|' + s.src + '">' + esc(s.label) + ' — ' + new Date(s.ts).toLocaleString() + '</option>'; }).join('');
var opts2 = allSnaps.map(function(s, i){ return '<option value="' + s.id + '|' + s.src + '"' + (i === 1 ? ' selected' : '') + '>' + esc(s.label) + ' — ' + new Date(s.ts).toLocaleString() + '</option>'; }).join('');
setModal(
'<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px">' +
'<div style="font-size:17px;font-weight:800;color:var(--txt-b)">⇄ Compare Snapshots</div>' +
'<button class="btn btn-ghost" style="padding:4px 10px;font-size:12px" onclick="DSK.showBackupModal()">← Back</button>' +
'</div>' +
'<label class="lbl">Snapshot A <span style="font-weight:400;color:var(--txt-dd)">(older / before)</span></label>' +
'<select id="diff-sel-a" class="finput" style="width:100%;margin-bottom:14px">' + opts + '</select>' +
'<label class="lbl">Snapshot B <span style="font-weight:400;color:var(--txt-dd)">(newer / after)</span></label>' +
'<select id="diff-sel-b" class="finput" style="width:100%;margin-bottom:22px">' + opts2 + '</select>' +
'<button class="btn btn-green" style="width:100%;font-size:13px" onclick="DSK.runSnapshotDiff()">⚡ Show Diff</button>',
'540px');
}
function runSnapshotDiff(){
var selA = document.getElementById('diff-sel-a'), selB = document.getElementById('diff-sel-b');
if(!selA || !selB) return;
var partsA = selA.value.split('|'), partsB = selB.value.split('|');
var idA = partsA[0], idB = partsB[0];
if(idA === idB){ C.notify('⚠️ Please select two different snapshots.'); return; }
showSnapshotDiff(idA, idB);
}
function showSnapshotDiff(idA, idB){
var all = getManualSnapshots().concat(getAutoSnapshots());
var snapA = all.find(function(x){ return x.id === idA; });
var snapB = all.find(function(x){ return x.id === idB; });
if(!snapA || !snapB){ C.notify('⚠️ Snapshot not found.'); return; }
var stateA = JSON.parse(snapA.data), stateB = JSON.parse(snapB.data);
var diff = computeDiff(stateA, stateB);
var total = diff.added.length + diff.modified.length + diff.deleted.length;
var fmtTs = function(ts){ var d = new Date(ts); return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); };
var trunc = function(s, n){ s = String(s || ''); return s.length > n ? s.slice(0, n) + '…' : s; };
var header =
'<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">' +
'<div style="font-size:17px;font-weight:800;color:var(--txt-b)">⇄ Snapshot Diff</div>' +
'<button class="btn btn-ghost" style="padding:4px 10px;font-size:12px" onclick="DSK.showDiffPicker()">← Back</button>' +
'</div>' +
'<div style="font-size:12px;padding:8px 10px;background:var(--surf2);border:1px solid var(--bd);border-radius:8px;margin-bottom:12px;line-height:1.7">' +
'<span style="color:var(--txt-d)">A:</span> <strong>' + esc(snapA.name) + '</strong> <span style="color:var(--txt-dd)">' + fmtTs(snapA.ts) + '</span><br>' +
'<span style="color:var(--txt-d)">B:</span> <strong>' + esc(snapB.name) + '</strong> <span style="color:var(--txt-dd)">' + fmtTs(snapB.ts) + '</span>' +
'</div>';
var statsBar =
'<div style="display:flex;gap:7px;margin-bottom:14px;flex-wrap:wrap">' +
'<span style="background:rgba(16,185,129,.15);color:#10b981;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700">+' + diff.added.length + ' added</span>' +
'<span style="background:rgba(245,158,11,.15);color:#b45309;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700">~' + diff.modified.length + ' modified</span>' +
'<span style="background:rgba(225,29,72,.12);color:#e11d48;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700">–' + diff.deleted.length + ' deleted</span>' +
'</div>';
if(total === 0){
setModal(header + statsBar + '<div style="text-align:center;padding:28px;color:var(--txt-d);font-size:13px">✓ Snapshots are identical — no differences found.</div>', '580px');
return;
}
// Group by container when the diffItems adapter supplies one (mirrors
// Flowboard grouping by column); otherwise render one flat "Items" sheet.
var sheets = {}, order = [];
function addToSheet(name, entry){ name = name || 'Items'; if(!sheets[name]){ sheets[name] = []; order.push(name); } sheets[name].push(entry); }
diff.modified.forEach(function(item){ addToSheet((item.after && item.after.container) || (item.before && item.before.container), { type: 'mod', item: item }); });
diff.added.forEach(function(item){ addToSheet(item.container, { type: 'add', item: item }); });
diff.deleted.forEach(function(item){ addToSheet(item.container, { type: 'del', item: item }); });
_diffRows = {};
var rn = 0, rows = '';
order.forEach(function(sheet){
rows += '<div class="diff-sheet-header">Sheet: ' + esc(sheet) + '</div>';
sheets[sheet].forEach(function(entry){
rn++;
var n = rn, type = entry.type, item = entry.item;
if(type === 'add'){
var t = item.label || '(empty)';
_diffRows[n] = { type: 'add', textA: '', textB: t };
rows += '<div class="diff-row diff-add"><span class="diff-type-badge diff-badge-add">+</span><span class="diff-rownum">#' + n + '</span>' +
'<span class="diff-content" id="dc-' + n + '" style="flex:1">' + esc(trunc(t, 80)) + '</span>' +
'<button class="diff-expand-btn" onclick="DSK.diffExpand(' + n + ')" title="Toggle full text">▼</button></div>';
}else if(type === 'del'){
var t2 = item.label || '(empty)';
_diffRows[n] = { type: 'del', textA: t2, textB: '' };
rows += '<div class="diff-row diff-del"><span class="diff-type-badge diff-badge-del">–</span><span class="diff-rownum">#' + n + '</span>' +
'<span class="diff-content" id="dc-' + n + '" style="flex:1">' + esc(trunc(t2, 80)) + '</span>' +
'<button class="diff-expand-btn" onclick="DSK.diffExpand(' + n + ')" title="Toggle full text">▼</button></div>';
}else{
var tA = (item.before && item.before.label) || '(empty)', tB = (item.after && item.after.label) || '(empty)';
_diffRows[n] = { type: 'mod', textA: tA, textB: tB };
rows += '<div class="diff-row diff-mod"><span class="diff-type-badge diff-badge-mod">~</span><span class="diff-rownum">#' + n + '</span>' +
'<span class="diff-content" id="dc-' + n + '" style="flex:1"><span style="opacity:.55">was: </span>' + esc(trunc(tA, 40)) + '<br><span style="opacity:.55">now: </span>' + esc(trunc(tB, 40)) + '</span>' +
'<button class="diff-expand-btn" onclick="DSK.diffExpand(' + n + ')" title="Toggle full text">▼</button></div>';
}
});
});
setModal(header + statsBar + '<div style="max-height:380px;overflow-y:auto;padding-right:2px">' + rows + '</div>', '640px');
}
function diffExpand(n){
if(!_diffRows || !_diffRows[n]) return;
var d = _diffRows[n];
var el = document.getElementById('dc-' + n);
if(!el) return;
var expanded = el.dataset.expanded === '1';
if(d.type === 'mod'){
el.innerHTML = expanded
? '<span style="opacity:.55">was: </span>' + esc(d.textA.slice(0, 40)) + (d.textA.length > 40 ? '…' : '') + '<br><span style="opacity:.55">now: </span>' + esc(d.textB.slice(0, 40)) + (d.textB.length > 40 ? '…' : '')
: '<span style="opacity:.55">was: </span>' + esc(d.textA) + '<br><span style="opacity:.55">now: </span>' + esc(d.textB);
}else{
var full = d.type === 'add' ? d.textB : d.textA;
el.textContent = expanded ? (full.length > 80 ? full.slice(0, 80) + '…' : full) : full;
}
el.dataset.expanded = expanded ? '0' : '1';
}
// ── INIT ──────────────────────────────────────────────────────────────
function load(){
try{
var raw = localStorage.getItem(k('live'));
if(raw) C.setState(JSON.parse(raw));
}catch(e){ console.error('[DSK] Failed to load local state:', e); }
}
function init(){
load();
C.onStateApplied();
restoreUndoSession();
sessionStartSnapshot();
if(C.firebaseEnabled) connectCloud();
C.updateSyncBadge(C.firebaseEnabled ? 'syncing' : 'local');
}
return {
init: init, save: save,
pushUndo: pushUndo, undo: undo, redo: redo,
createManualSnapshot: createManualSnapshot, renameManualSnapshot: renameManualSnapshot, restoreManualSnapshot: restoreManualSnapshot, deleteManualSnapshot: deleteManualSnapshot, getManualSnapshots: getManualSnapshots,
createAutoSnapshot: createAutoSnapshot, autoSnapBefore: autoSnapBefore, restoreAutoSnapshot: restoreAutoSnapshot, deleteAutoSnapshot: deleteAutoSnapshot, getAutoSnapshots: getAutoSnapshots,
exportState: exportState, importState: importState,
forcePushToCloud: forcePushToCloud, forcePullFromCloud: forcePullFromCloud,
diffSnapshots: computeDiff,
showBackupModal: showBackupModal, showDiffPicker: showDiffPicker, runSnapshotDiff: runSnapshotDiff, showSnapshotDiff: showSnapshotDiff, diffExpand: diffExpand,
closeModal: closeModal,
get undoStack(){ return _undoStack; }, get redoStack(){ return _redoStack; }
};
})();
/* ════════════════════════════════════════════════════════════════════════
DEMO APP — a minimal task list wired to DSK, purely to prove the module
works end to end. This whole section is throwaway in a real integration;
only DSK_CONFIG, the DSK module, and its Backup-UI markup above are
meant to survive porting.
════════════════════════════════════════════════════════════════════════ */
var AppState = { items: [], lastModified: 0 };
function renderDemo(){
var ul = document.getElementById('item-list');
ul.innerHTML = '';
AppState.items.forEach(function(it){
var li = document.createElement('li');
if(it.done) li.className = 'done';
var cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = it.done;
cb.onchange = function(){ demoToggleItem(it.id); };
var span = document.createElement('span'); span.className = 'txt'; span.textContent = it.text;
var del = document.createElement('button'); del.className = 'btn btn-danger'; del.style.cssText = 'padding:3px 8px;font-size:11px'; del.textContent = '✕';
del.onclick = function(){ demoDeleteItem(it.id); };
li.appendChild(cb); li.appendChild(span); li.appendChild(del);
ul.appendChild(li);
});
}
function demoAddItem(){
var inp = document.getElementById('new-item');
var text = inp.value.trim();
if(!text) return;
DSK.pushUndo(); // ← the convention: undo snapshot BEFORE the mutation
AppState.items.push({ id: '_' + Math.random().toString(36).slice(2,9), text: text, done: false });
inp.value = '';
DSK.save(); renderDemo();
}
function demoToggleItem(id){
DSK.pushUndo();
var it = AppState.items.find(function(x){ return x.id === id; });
if(it) it.done = !it.done;
DSK.save(); renderDemo();
}
function demoDeleteItem(id){
DSK.pushUndo();
AppState.items = AppState.items.filter(function(x){ return x.id !== id; });
DSK.save(); renderDemo();
}
document.getElementById('new-item').addEventListener('keydown', function(e){ if(e.key === 'Enter') demoAddItem(); });
DSK.init();