Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
7322 lines (7124 loc) · 409 KB
/
Copy pathapp.js
File metadata and controls
7322 lines (7124 loc) · 409 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
(function() {
// SECTION: Constants
if (typeof pdfjsLib !== 'undefined') pdfjsLib.GlobalWorkerOptions.workerSrc = '/vendor/pdf.worker.min-3.11.174.js';
// All pdf.js getDocument calls go through here. pdf.js needs its bundled
// substitute fonts (standard_fonts/) for PDFs that reference fonts without
// embedding them (common in CAD-exported plan sets) and cmaps/ for
// predefined CID text encodings — without these, every glyph in such a PDF
// renders as the .notdef box. Accepts an ArrayBuffer/TypedArray, a Blob, a
// URL string, or a DocumentInitParameters object; returns an object with a
// .promise resolving to the PDFDocumentProxy (the only loading-task surface
// the app uses).
const PDF_OPEN_OPTIONS = {
standardFontDataUrl: '/vendor/standard_fonts/',
cMapUrl: '/vendor/cmaps/',
cMapPacked: true,
};
function getPdfDocument(src) {
if (typeof Blob !== 'undefined' && src instanceof Blob) {
// pdf.js 3.x does not accept a Blob directly — read it first.
return { promise: src.arrayBuffer().then((buf) => pdfjsLib.getDocument({ ...PDF_OPEN_OPTIONS, data: buf }).promise) };
}
let params;
if (typeof src === 'string' || (typeof URL !== 'undefined' && src instanceof URL)) {
params = { ...PDF_OPEN_OPTIONS, url: src };
} else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) {
params = { ...PDF_OPEN_OPTIONS, data: src };
} else {
params = { ...PDF_OPEN_OPTIONS, ...src };
}
return pdfjsLib.getDocument(params);
}
// B9 (J15): coarse-pointer detection for the touch copy swaps — "Tap" status
// hints, no "(right-click …)" tooltip suffixes, no ⇧Q chips. Read live (not
// captured) so a convertible that gains a mouse gets desktop wording on the
// next repaint.
function isCoarsePointer() { return window.matchMedia('(pointer: coarse)').matches; }
// Desktop tool tooltips advertise the right-click context menu; touch opens
// it by long-press, so the suffix is dropped there. Used by the dynamic
// title writers (updateUI); static titles are scrubbed once at boot.
function withRightClickHint(base) { return isCoarsePointer() ? base : base + ' (right-click for settings)'; }
const SUPABASE_URL = (typeof window !== 'undefined' && window.SUPABASE_URL) || '';
const SUPABASE_ANON_KEY = (typeof window !== 'undefined' && window.SUPABASE_ANON_KEY) || '';
const SUPABASE_ENABLED = !!(SUPABASE_URL && SUPABASE_ANON_KEY && SUPABASE_URL.includes('supabase'));
let supabase = null;
if (SUPABASE_ENABLED && typeof window.supabase !== 'undefined') {
const { createClient } = window.supabase;
supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
}
// Pure constants (TOOL, SCALE_MODES, PLUMBING_DEFAULTS, LINE_DEFAULTS, COLORS, SCALE_PRESETS) live in constants.js
// (classic <script src> loaded before this IIFE); referenced here by bare name via the shared global lexical scope.
const uid = () => Math.random().toString(36).slice(2, 10);
function getLineModifiers() {
try {
const raw = localStorage.getItem('lineModifiers');
const saved = raw ? JSON.parse(raw) : {};
return {
sizes: (saved.sizes && saved.sizes.length) ? saved.sizes : LINE_DEFAULTS.sizes,
materials: (saved.materials && saved.materials.length) ? saved.materials : LINE_DEFAULTS.materials,
defaultColor: saved.defaultColor || COLORS[2]
};
} catch (_) {
return { sizes: [...LINE_DEFAULTS.sizes], materials: [...LINE_DEFAULTS.materials], defaultColor: COLORS[2] };
}
}
function saveLineModifiers(mods) {
try { localStorage.setItem('lineModifiers', JSON.stringify(mods)); } catch (_) {}
}
function getPlumbingModifiers() {
try {
const raw = localStorage.getItem('plumbingModifiers');
const saved = raw ? JSON.parse(raw) : {};
return {
sizes: (saved.sizes && saved.sizes.length) ? saved.sizes : PLUMBING_DEFAULTS.sizes,
types: (saved.types && saved.types.length) ? saved.types : PLUMBING_DEFAULTS.types,
materials: (saved.materials && saved.materials.length) ? saved.materials : PLUMBING_DEFAULTS.materials,
iconByType: (saved.iconByType && typeof saved.iconByType === 'object') ? saved.iconByType : {},
defaultColor: saved.defaultColor || COLORS[2],
// S1: the other trades' Quick profiles + the device's default trade
// ride this same blob (→ user_airboard.plumbing_modifiers, no migration).
profiles: (saved.profiles && typeof saved.profiles === 'object') ? saved.profiles : {},
defaultTrade: TRADES.includes(saved.defaultTrade) ? saved.defaultTrade : null
};
} catch (_) {
return { sizes: [...PLUMBING_DEFAULTS.sizes], types: [...PLUMBING_DEFAULTS.types], materials: [...PLUMBING_DEFAULTS.materials], iconByType: {}, defaultColor: COLORS[2], profiles: {}, defaultTrade: null };
}
}
function savePlumbingModifiers(mods) {
try { localStorage.setItem('plumbingModifiers', JSON.stringify(mods)); } catch (_) {}
}
// Trade profiles (Electrical, First-Class S1). One store shape per trade —
// sizes / types / materials / iconByType / defaultColor (+ mountByType for
// trades that carry a mount height). 'plumbing' IS the legacy blob; the
// others live under plumbingModifiers.profiles[trade], seeded from the
// constants.js defaults the first time they are read.
const TRADE_DEFAULTS = { electrical: ELECTRICAL_DEFAULTS, hvac: HVAC_DEFAULTS };
function getTradeModifiers(trade) {
const t = TRADES.includes(trade) ? trade : 'plumbing';
const base = getPlumbingModifiers();
if (t === 'plumbing') return base;
const def = TRADE_DEFAULTS[t];
const saved = (base.profiles && base.profiles[t] && typeof base.profiles[t] === 'object') ? base.profiles[t] : {};
return {
sizes: (saved.sizes && saved.sizes.length) ? saved.sizes : [...def.sizes],
types: (saved.types && saved.types.length) ? saved.types : [...def.types],
materials: (saved.materials && saved.materials.length) ? saved.materials : [...def.materials],
iconByType: (saved.iconByType && typeof saved.iconByType === 'object') ? saved.iconByType : {},
mountByType: { ...(def.mountByType || {}), ...((saved.mountByType && typeof saved.mountByType === 'object') ? saved.mountByType : {}) },
defaultColor: saved.defaultColor || COLORS[0]
};
}
function saveTradeModifiers(trade, mods) {
const t = TRADES.includes(trade) ? trade : 'plumbing';
if (t === 'plumbing') { savePlumbingModifiers(mods); return; }
const base = getPlumbingModifiers();
base.profiles = base.profiles || {};
base.profiles[t] = { sizes: mods.sizes, types: mods.types, materials: mods.materials, iconByType: mods.iconByType || {}, mountByType: mods.mountByType || {}, defaultColor: mods.defaultColor };
savePlumbingModifiers(base);
}
// The trade the Quick creator speaks right now: the project's, else the
// device's remembered default, else plumbing (today's behavior).
function getQuickTrade() {
if (TRADES.includes(state.trade)) return state.trade;
const d = getPlumbingModifiers().defaultTrade;
return TRADES.includes(d) ? d : 'plumbing';
}
// Stamp the project's trade (explicit, per project — decision ⚑2). `remember`
// also makes it the device default for the next new project. Telemetry:
// trade_set answers "how much of the base is electrical".
function setProjectTrade(trade, opts) {
const t = TRADES.includes(trade) ? trade : null;
const changed = state.trade !== t;
state.trade = t;
if (opts && opts.remember && t) {
const mods = getPlumbingModifiers();
if (mods.defaultTrade !== t) { mods.defaultTrade = t; savePlumbingModifiers(mods); }
}
if (changed) {
markProjectDirty();
logUserEvent('trade_set', state.currentProjectId || null, { trade: t, route: (opts && opts.route) || 'settings' });
// D21 (J5-D): a trade change is one of the TWO events allowed to move a
// tool between the strip and the ⋯ (the other is a pin). Re-resolve now
// so the strip settles at the change, never mid-use.
if (App.updateHeaderMore) App.updateHeaderMore();
}
updateUI();
}
// Codes & jurisdiction (rulebook slice 4): which editions the rulebook resolves
// against for this project, and whose amendments apply. `state.codes` holds
// only what the project chose; the device default (the last bid's choices,
// like the trade) and CODE_DEFAULTS sit under it. Telemetry: codes_set.
const CODES_DEFAULT_KEY = 'codesDefault';
function getDeviceDefaultCodes() {
try { return normalizeProjectCodes(JSON.parse(localStorage.getItem(CODES_DEFAULT_KEY) || 'null')); } catch (_) { return null; }
}
function getProjectCodes() {
return { ...CODE_DEFAULTS, jurisdiction: '', occupancy: 'public', ...(getDeviceDefaultCodes() || {}), ...(state.codes || {}) };
}
function setProjectCodes(patch, opts) {
const merged = { ...(state.codes || {}), ...(patch || {}) };
Object.keys(merged).forEach((k) => { if (merged[k] == null || String(merged[k]).trim() === '') delete merged[k]; });
const next = normalizeProjectCodes(merged);
const changed = JSON.stringify(next) !== JSON.stringify(state.codes || null);
state.codes = next;
// Remembered as the device default unless told not to (the tour never remembers).
if (!opts || opts.remember !== false) { try { localStorage.setItem(CODES_DEFAULT_KEY, JSON.stringify(next)); } catch (_) {} }
if (changed) {
markProjectDirty();
logUserEvent('codes_set', state.currentProjectId || null, { ...(next || {}), route: (opts && opts.route) || 'settings' });
}
updateUI();
}
// The default mount height (inches AFF) a trade profile assigns a device:
// the variant's entry, then the category's. null = at the ceiling / none.
function tradeMountHeightFor(trade, typeValue, sizeValue) {
const mods = getTradeModifiers(trade);
const m = mods.mountByType || {};
if (typeValue && typeof m[typeValue] === 'number') return m[typeValue];
if (sizeValue && typeof m[sizeValue] === 'number') return m[sizeValue];
return null;
}
// The bundled symbol a trade variant starts with (constants.js
// iconNameByType → the CUSTOM_ICONS entry of that name), unless the user has
// pinned one in the profile's iconByType.
function tradeIconForType(trade, typeValue) {
const mods = getTradeModifiers(trade);
if (mods.iconByType && mods.iconByType[typeValue]) return mods.iconByType[typeValue];
const def = TRADE_DEFAULTS[trade];
const name = def && def.iconNameByType && def.iconNameByType[typeValue];
if (!name) return null;
const ic = getEffectiveCustomIcons().find(i => i.name === name);
return ic ? ic.value : null;
}
// COLORS and SCALE_PRESETS live in constants.js (see note above).
// SECTION: Icon data (icon *_PATH consts, VB_384_512_PATHS, CUSTOM_ICONS) lives in icons.js,
// a classic <script src> loaded before this IIFE; referenced here via the shared global lexical scope.
// CUSTOM_ICON_META + the pure icon-render rules live in icon-render.js (loaded
// before app.js) and resolve here by bare name. The helpers below stay because
// they read the runtime user-icon cache; they inject getEffectiveCustomIcons()
// into the pure *FromList/*Rule primitives.
let customIconsCache = [];
function getUserCustomIcons() {
return customIconsCache;
}
function saveUserCustomIcons(arr) {
customIconsCache = Array.isArray(arr) ? arr : [];
customIconsPutToIndexedDB(customIconsCache);
}
function getEffectiveCustomIcons() {
return [...CUSTOM_ICONS, ...getUserCustomIcons()];
}
function getCustomIconViewBox(path) {
return iconViewBoxFromList(path, getEffectiveCustomIcons());
}
function getCustomIconMeta(path) {
return iconMetaFromList(path, getEffectiveCustomIcons());
}
function iconRenderVb(path) {
return iconRenderVbRule(getCustomIconMeta(path), path);
}
function iconRenderCenter(path) {
return iconRenderCenterRule(getCustomIconMeta(path), path);
}
function iconViewBoxString(path) {
return iconViewBoxStringRule(getCustomIconViewBox(path), path);
}
const COUNTER_BTN_DEFAULT_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" width="28" height="28"><path fill="currentColor" d="M320 320C178.6 320 64 277 64 224C64 171 178.6 128 320 128C461.4 128 576 171 576 224C576 277 461.4 320 320 320zM64 416L64 306.7C80.9 319 101 328.9 122.1 336.8C175.1 356.7 245.1 368 320 368C394.9 368 464.9 356.7 517.9 336.8C539.1 328.9 559.1 319 576 306.7L576 416C576 469 461.4 512 320 512C178.6 512 64 469 64 416z"/></svg>';
const USER_ACTIVITY_ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M320 171.9L305 151.1C280 116.5 239.9 96 197.1 96C123.6 96 64 155.6 64 229.1L64 231.7C64 255.3 70.2 279.7 80.6 304L186.6 304C189.8 304 192.7 302.1 194 299.1L225.8 222.8C229.5 214 238.1 208.2 247.6 208C257.1 207.8 265.9 213.4 269.8 222.1L321.1 336L362.5 253.2C366.6 245.1 374.9 239.9 384 239.9C393.1 239.9 401.4 245 405.5 253.2L428.7 299.5C430.1 302.2 432.8 303.9 435.9 303.9L559.5 303.9C570 279.6 576.1 255.2 576.1 231.6L576.1 229C576 155.6 516.4 96 442.9 96C400.2 96 360 116.5 335 151.1L320 171.8zM533.6 352L435.8 352C414.6 352 395.2 340 385.7 321L384 317.6L341.5 402.7C337.4 411 328.8 416.2 319.5 416C310.2 415.8 301.9 410.3 298.1 401.9L248.8 292.4L238.3 317.6C229.6 338.5 209.2 352.1 186.6 352.1L106.4 352.1C153.6 425.9 229.4 493.8 276.8 530C289.2 539.4 304.4 544.1 319.9 544.1C335.4 544.1 350.7 539.5 363 530C410.6 493.7 486.4 425.8 533.6 352z"/></svg>';
const DROP_ICON_STYLES = [
{ id: 'circle', name: 'Circle', svg: '<svg viewBox="0 0 24 24" width="24" height="24"><circle cx="12" cy="12" r="8" stroke="currentColor" stroke-width="2" fill="none"/></svg>' },
{ id: 'x', name: 'X', svg: '<svg viewBox="0 0 24 24" width="24" height="24"><path stroke="currentColor" stroke-width="2" fill="none" d="M6 6 L18 18 M18 6 L6 18"/></svg>' },
{ id: 'plus', name: 'Plus', svg: '<svg viewBox="0 0 24 24" width="24" height="24"><path stroke="currentColor" stroke-width="2" fill="none" d="M12 4 L12 20 M4 12 L20 12"/></svg>' },
{ id: 'diamond', name: 'Diamond', svg: '<svg viewBox="0 0 24 24" width="24" height="24"><path stroke="currentColor" stroke-width="2" fill="none" d="M12 4 L20 12 L12 20 L4 12 Z"/></svg>' },
{ id: 'triangle', name: 'Triangle', svg: '<svg viewBox="0 0 24 24" width="24" height="24"><path stroke="currentColor" stroke-width="2" fill="none" d="M12 4 L20 20 L4 20 Z"/></svg>' },
];
// SECTION: ICONS array lives in icons.js (see icon-data note above).
// The annotation model (canvas/annotation shape accessors, merge/migrate,
// backup<->proj format conversion, bake-frame verify, backup/data appliers,
// orphan reconcile) lives in annotation-model.js (createAnnotationModel(ctx),
// loaded before this file). Same-named wrappers keep the ~150 call sites,
// the App registry, and the feature-file contracts frozen.
const annotationModel = createAnnotationModel({
getState: () => state,
uid: () => uid(),
showToast: (msg, ms) => showToast(msg, ms),
ensureGroupColors: (groups) => ensureGroupColors(groups),
saveUserCustomIcons: (arr) => saveUserCustomIcons(arr),
getLineRealWorldLengthFeet: (line, pageIdx, isPoly, ann) => getLineRealWorldLengthFeet(line, pageIdx, isPoly, ann),
});
// mergeAnnotations / migratePageToCanvases / verifyPageBakeFrame have no
// app-side callers (their callers moved into the model) — annotationModel.*.
function makeAnnotations() { return annotationModel.makeAnnotations(); }
function getPageCanvases(page) { return annotationModel.getPageCanvases(page); }
function getActiveCanvas(page, pageIdxHint) { return annotationModel.getActiveCanvas(page, pageIdxHint); }
function getActiveAnnotations(page, pageIdxHint) { return annotationModel.getActiveAnnotations(page, pageIdxHint); }
function getMergedAnnotationsForPage(page, onlyIds) { return annotationModel.getMergedAnnotationsForPage(page, onlyIds); }
function ensureActiveCanvas(page) { return annotationModel.ensureActiveCanvas(page); }
function pageHasAnyAnnotations(p, opts) { return annotationModel.pageHasAnyAnnotations(p, opts); }
function projectHasAnyCanvasMarkup(opts) { return annotationModel.projectHasAnyCanvasMarkup(opts); }
// One count for "how many marks are on this layer": the confirms name it (S08: the model's table).
function countCanvasMarks(ann, opts) { return annotationModel.countCanvasMarks(ann, opts); }
function backupDataToProjFormat(data) { return annotationModel.backupDataToProjFormat(data); }
function computePageBakeFrame(p) { return annotationModel.computePageBakeFrame(p); }
function applyTakeoffBackupToState(backup) { return annotationModel.applyTakeoffBackupToState(backup); }
function applyPageAnnotationsFromData(page, p, scaleFallback) { return annotationModel.applyPageAnnotationsFromData(page, p, scaleFallback); }
function hydrateStateFromProjectData(d, opts) { return annotationModel.hydrateStateFromProjectData(d, opts); }
function reconcileOrphanedCountersAndLineTypes() { return annotationModel.reconcileOrphanedCountersAndLineTypes(); }
function planPaletteRelink(incomingCounters, incomingLineTypes) { return annotationModel.planPaletteRelink(incomingCounters, incomingLineTypes); }
function applyPaletteRelink(plan) { return annotationModel.applyPaletteRelink(plan); }
function getIconName(path) {
if (state.iconNames && state.iconNames[path]) return state.iconNames[path];
const custom = getEffectiveCustomIcons().find(i => i.value === path);
if (custom) return custom.name;
const ic = ICONS.find(i => i.value === path);
return ic ? ic.name : 'Icon';
}
function getOrderedIcons() {
const order = state.iconOrder;
if (!order || !Array.isArray(order) || order.length === 0) return ICONS;
const byPath = new Map(ICONS.map(i => [i.value, i]));
const ordered = order.map(p => byPath.get(p)).filter(Boolean);
const rest = ICONS.filter(i => !order.includes(i.value));
return [...ordered, ...rest];
}
// SECTION: State
const state = {
pages: [], currentPage: 0, zoom: 1.0, tool: TOOL.NONE, scaleMode: SCALE_MODES.NONE,
scalePointA: null, scalePointB: null, gridOriginPickMode: false, activeCounterType: null, activePolylineId: null, drawingPolyline: null,
quickLineStart: null, highlightStart: null, multiplyZoneStart: null, scaleZoneStart: null, deleteZoneStart: null, roomBoxStart: null, scheduleBoxStart: null, chainStart: null, ghostRectStart: null, placingGhost: null, placingGhostLast: null, placingGhostFromStamp: false, activeGhostId: null, draggingGhostIdx: null, draggingGhostLast: null, ghostDragMoved: false, justFinishedDragGhost: false, pendingRoomBox: null, pendingRoomBoxEdit: null, pendingMultiplyZone: null, pendingMultiplyZoneValue: null, pendingMultiplyZoneEdit: null, pendingScaleZone: null, pendingScaleZoneEdit: null, scaleModalApplyTarget: null, scaleCheckMode: false, pendingNote: null, editingNote: null, mousePos: { x: 0, y: 0 }, pan: { x: 0, y: 0 }, isPanning: false, panStart: null,
counters: [], lineTypes: [], activeLineTypeId: null, groupsEnabled: false, trade: null, stripPins: {}, ceilingHeightFt: null, makeUpFt: null, codes: null, bidCheck: { manual: {} }, bidCheckCollapsed: true, ctxTarget: null, selectedLineId: null, selectedLineIsPoly: false, selectedLinePageIdx: null, selectedDuctRunId: null, selectedDuctRunPageIdx: null, ductListCollapsed: false,
counterSettings: { ...COUNTER_SETTINGS_DEFAULTS }, // per device: merged from localStorage below (MAP-SETTINGS)
iconNames: {},
iconOrder: null,
pagesListCollapsed: false,
pagesTitlesTruncated: true,
countersListCollapsed: false,
sidebarReorderModeActive: false,
lineTypesListCollapsed: false,
linesListCollapsed: true,
counterSearch: '',
lineTypeSearch: '',
linesSearch: '',
linesTypeExpanded: {},
groupsListCollapsed: true,
summaryListCollapsed: false,
lineTypeSettings: { ...LINE_TYPE_SETTINGS_DEFAULTS }, // per device, like counterSettings
legendSettings: { bgOpacity: 1, textOpacity: 1, bgColor: '#ffffff', showBorder: true, legendScale: 1, showResizeHighlight: false },
// Duct Schedule knobs (DUCT unit D5) — per project, riding save/load +
// export/import like legendSettings: the schedule's editable seam-&-waste
// and fitting-factor % lines plus the Counted|Factor mode pick. D6 adds
// the design-build ductulator knobs: equal-friction rate (in/100ft) and
// the velocity cap (fpm) behind the size-chip/S-popover suggestions.
ductSettings: { ...DUCT_SETTINGS_DEFAULTS },
waterSettings: normalizeWaterSettings(null), // WATER-PLAN rung 5: the velocity caps per side
multiplyZoneSettings: { showLabelOnZone: true, defaultMultiplier: 2, labelSize: 14, labelPosition: 'center' },
scaleZoneSettings: { showLabelOnZone: true, labelSize: 14, labelPosition: 'top-left' },
exportSettings: { markerScale: 0.75, lineScale: 0.75, bundleHighlightsToPdf: true, bundleNotesToPdf: true },
recentLineColors: [],
recentBids: [],
recentDrops: [],
editingPolyline: null, editingPolyIndex: null, draggingVertexIdx: null, movingLabel: null, resizingNoteIdx: null, resizingNotePageIdx: null, resizingNoteFontSizeIdx: null, resizingNoteFontSizePageIdx: null, resizingNoteFontSizeStartY: null, resizingNoteFontSizeStartLocalY: null, resizingNoteFontSizeStartVal: null, justFinishedResize: false, draggingNoteIdx: null, draggingNotePageIdx: null, draggingNoteOffset: null, dragNoteStartPos: null, justFinishedDragNote: false, draggingLegend: false, resizingLegend: false, legendDragOffset: null, legendResizeStart: null, draggingZone: null, justFinishedZoneDrag: false, longPressTimer: null, longPressFired: false,
pinchStartDistance: null, pinchStartZoom: null,
touchPanStart: null, touchPanning: false,
aiming: false, aimPressTimer: null, aimPoint: null, aimClient: null, aimRafPending: false,
aimOffsetPx: 0, aimMouseDownClient: null, justFinishedLoupe: false,
rectPress: null, rectDragging: false, justFinishedRectDrag: false,
vertexDragStart: null, vertexDragMoved: false,
lastScaleTapTime: 0,
lastScaleTapPt: null,
currentProjectId: null,
currentProjectName: null,
currentProjectExternalRef: null,
// The cloud row's updated_at as loaded (view links only today) — the bid
// basis manifest carries it so PipeTooling can tell "takeoff changed since".
currentProjectUpdatedAt: null,
isAdmin: false,
isOverseer: false,
isLead: false, // LEAD-ROLE (2026-10-02): profiles.is_lead, see App.canTakeOver
isDigitalTwin: false,
pendingDeletePage: null,
supabaseSession: null,
pdfBuffer: null,
pdfBufferSize: 0,
pdfStoragePath: null,
pdfHash: null,
// In-memory only: hash of a locally-uploaded (never-saved) PDF, stamped by
// features/pdf-intake.js. NOT state.pdfHash, which carries cloud-PDF
// semantics through the save/upload ladder. Rides signed-out IndexedDB
// backups so the same-PDF re-upload re-apply can hash-verify the match.
localPdfHash: null,
lastSavedAt: null,
pendingCanvasLoad: null,
checkedOutBy: null,
checkedOutAt: null,
checkedOutEmail: null,
isViewer: false,
loadedViaViewLink: false,
viewToken: null,
hideMarks: false,
showAllCanvases: false, // in-memory peek: render every canvas layer of the page at once
emphasizedCounterId: null, // in-memory "find this counter" halo: counter-type id whose markers get the ring emphasis (features/drop-peek.js); survives page flips, cleared by Escape / background click
peekCanvasIdsByPage: {}, // in-memory peek subset: pageIdx -> [canvasId,...] to show besides the active one (absent = all); chosen via right-click on #showAllCanvasesBtn
canCheckOut: false,
projectOwnerId: null,
maxZoom: null,
groups: [],
rooms: [],
roomsListCollapsed: false,
parkedScaleDraft: null, // D20 (J5-A): a live polyline / quick-line draft held across the Set Scale modal and resumed when it closes. In-memory, one modal round-trip long.
counterAirMoreOpen: null, // D19: in-memory per project — the Counter modal's "More ▸ air & mounting" disclosure. null = follow the trade (open on hvac/electrical); true/false = the estimator's override for this project. A view preference like showAllCanvases, deliberately NOT in save/load.
recentRoomHeights: [],
activeGroupId: null,
activeCanvasIdByPage: {},
// Quick Keys: slot ('1'..'9','0') -> { kind: 'counter'|'lineType', id }.
// Per-project (ids are uid()-scoped to the project); rides save/load,
// export/import, and the IDB takeoff backup. See features/quick-keys.js.
numberKeyBindings: {},
showLegendOverlay: true,
showGridOverlay: false,
showScaleRefLine: true,
gridSettings: null,
userActivityAllRowsCache: null,
userActivityViewMode: 'events'
};
state.showGroupColors = localStorage.getItem('groupColorDisplay') === '1';
// Counter and Line Type display settings persist per device (MAP-SETTINGS, decided
// 2026-09-25): a visual preference like Hide marks, never the project. The stored blob
// merges over the defaults field by field (displaySettingsFields in constants.js), so
// a key added later keeps its default and a corrupt entry costs only itself.
// saveDisplaySettings is every writer's one door: the two settings modals, the header
// Snap button, the J hotkey and the Lines this-sheet toggle.
const DISPLAY_SETTINGS_STORE = [['counterSettings', COUNTER_SETTINGS_DEFAULTS], ['lineTypeSettings', LINE_TYPE_SETTINGS_DEFAULTS]];
function saveDisplaySettings() {
DISPLAY_SETTINGS_STORE.forEach(([key, defaults]) => {
try { localStorage.setItem(key, JSON.stringify(displaySettingsFields(defaults, state[key]))); } catch (_) { /* private window: this session keeps them */ }
});
}
DISPLAY_SETTINGS_STORE.forEach(([key, defaults]) => {
try { Object.assign(state[key], displaySettingsFields(defaults, JSON.parse(localStorage.getItem(key) || 'null'))); } catch (_) { /* corrupt entry -> the defaults */ }
});
// Sidebar usage-filter scope persists per device (idea recovered from the
// unlanded claude/app-review-docs-bb19fa attempt): a big-palette user who
// sets "this project" keeps it across sessions. The setters write these
// keys; 'off' is stored too so an explicit reset also sticks.
try {
const cScope = localStorage.getItem('counterSidebarFilterScope');
if (cScope === 'page' || cScope === 'project') setCounterListFilterScope(cScope);
const ltScope = localStorage.getItem('lineTypeSidebarFilterScope');
if (ltScope === 'page' || ltScope === 'project') setLineTypeListFilterScope(ltScope);
} catch (_) {}
// D21 (J5-D): the device's last strip pins seed a new project, so an
// estimator who pinned Duct keeps it across a plain reload and into the next
// bid. A project that carries its own pins overwrites this on hydrate.
function readDeviceStripPins() {
try {
const sp = JSON.parse(localStorage.getItem('stripPins') || '{}');
if (sp && typeof sp === 'object' && !Array.isArray(sp)) {
return Object.fromEntries(Object.entries(sp).filter(([, v]) => typeof v === 'boolean'));
}
} catch (_) { /* corrupted entry -> trade defaults */ }
return {};
}
state.stripPins = readDeviceStripPins();
try {
const rrh = JSON.parse(localStorage.getItem('recentRoomHeights') || '[]');
if (Array.isArray(rrh)) state.recentRoomHeights = rrh.filter(h => typeof h === 'number' && h > 0).slice(0, 5);
} catch (_) { /* corrupted entry -> empty recents */ }
state.pagesTitlesTruncated = localStorage.getItem('pagesTitlesTruncated') !== '0';
state.hideUnmarkedPagesFromSidebar = localStorage.getItem('hideUnmarkedPagesFromSidebar') === '1';
try {
state.counterSearch = localStorage.getItem('counterSearch') || '';
state.lineTypeSearch = localStorage.getItem('lineTypeSearch') || '';
state.linesSearch = localStorage.getItem('linesSearch') || '';
const le = localStorage.getItem('linesTypeExpanded');
state.linesTypeExpanded = le ? JSON.parse(le) : {};
} catch (_) {}
try {
const rc = localStorage.getItem('recentLineColors');
const parsed = rc ? JSON.parse(rc) : null;
if (Array.isArray(parsed) && parsed.every(x => typeof x === 'string')) {
state.recentLineColors = parsed.slice(0, RECENT_COLORS_MAX);
}
} catch (_) {}
try {
// Recent drop sizes ({ value, unit }), per device like recentRoomHeights.
const rd = JSON.parse(localStorage.getItem('recentDrops') || '[]');
if (Array.isArray(rd)) {
state.recentDrops = rd.filter(d => d && typeof d.value === 'number' && d.value > 0 && typeof d.unit === 'string').slice(0, RECENT_DROPS_MAX);
}
} catch (_) {}
try {
// Recent bids ({ id, name, at }), per device. The header switcher's menu
// reads this instead of the cloud: list_accessible_projects carries every
// project's whole `data` payload, which a menu that opens on click cannot
// afford. nextRecentBids re-filters, so a corrupted store is harmless.
const rb = JSON.parse(localStorage.getItem(RECENT_BIDS_KEY) || '[]');
if (Array.isArray(rb)) state.recentBids = nextRecentBids(rb, null).slice(0, RECENT_BIDS_MAX);
} catch (_) {}
function getGroupColor(groupId) {
const g = (state.groups || []).find(x => x.id === groupId);
return (g && g.color) || COLORS[0];
}
function ensureGroupColors(groups) {
if (!Array.isArray(groups)) return groups;
groups.forEach((g, i) => { if (!g.color) g.color = COLORS[i % COLORS.length]; });
return groups;
}
// #7b: When true, the next pdfInput.onchange treats the upload as "add
// additional pages to the current project" and routes through Prepare PDF
// in append mode. Set by the Project Settings "Add additional PDF pages"
// button. Always cleared at the top of pdfInput.onchange so it can't leak
// across calls.
let lastAuthUserId = null;
let lastModifiedAt = 0;
let lastSaveIncludedPdf = false;
// turnInInProgress + inFlightRecoverySavePromise live in save-engine.js
// (Stage 5): saveEngine.isTurnInInProgress() / resetTurnInState().
// dirtyStartedAt lives in save-engine.js (Stage 2): saveEngine.getDirtyStartedAt().
// Autosave/checkout timing & threshold constants live in constants.js (see note in the Constants section).
// The auto-recheckout rate-limit state (per-project count/cap Maps + min-gap
// stamp) lives in save-engine.js (Stage 5); resetAutoRecheckoutCounter below.
// Background-expiry entry point: implementation lives in save-engine.js
// (Stage 5), including the old supabase-disabled no-op fallback. Its last
// app-side callers (the visibility probe and the autosave tick) moved into
// the engine in Stage 7; App.handleBackgroundCheckoutExpired delegates.
function resetAutoRecheckoutCounter(projectId) { return saveEngine.resetAutoRecheckoutCounter(projectId); }
let lastCheckoutRefreshAt = 0;
let suspendAutoSaveUntilCheckout = false;
// lastHiddenAt lives in save-engine.js (Stage 7, the visibility handler).
let serverClockOffsetMs = 0;
function serverNowMs() { return Date.now() + serverClockOffsetMs; }
function updateServerClockFromRpc(rpcData) {
const off = computeClockOffsetMs(rpcData, Date.now());
if (off != null) serverClockOffsetMs = off;
}
const withTimeout = (promiseOrFactory, ms, label) => {
const controller = (typeof promiseOrFactory === 'function') ? new AbortController() : null;
const inner = controller ? promiseOrFactory(controller.signal) : promiseOrFactory;
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => {
if (controller) { try { controller.abort(); } catch (_) {} }
reject(new Error((label || 'Request') + ' timed out after ' + (ms / 1000) + 's'));
}, ms);
});
const result = Promise.race([inner, timeout]).finally(() => clearTimeout(timer));
result.controller = controller;
return result;
};
// noteAutoSaveOutcome + recordAutosaveLatency (the failure/backoff/latency
// bookkeeping) live in save-engine.js (Stage 6), internal to the save paths.
// noteSupabaseJsFailure has no app-side callers anymore (its callers all
// moved in by Stage 6) — saveEngine.noteSupabaseJsFailure.
// Save/sync engine: this and the other `[sync]`-prefixed sections form the
// scattered save/sync subsystem. See ARCHITECTURE.md "Save/sync engine map"
// for the logical reading order. (rg "SECTION: \[sync\]" app.js)
// SECTION: [sync] Sync recovery & client recycle
// The recovery/recycle orchestrators, probes, client recycle, and raw-fetch
// fallbacks live in save-engine.js (Stage 4); same-named wrappers below.
// runRecoveryProbeAndMaybeRecycle: engine-internal since Stage 6;
// recycleClientIfWedgedOnIdleReturn since Stage 7 (its one caller, the
// long-idle return, moved in with the visibility handler).
// updateSyncPausedBanner + retrySyncNow + captureNetworkInfoDetail/Obj live
// in save-engine.js (Stage 6); the sync-paused banner Retry button below
// reaches the abort-and-retry through this wrapper.
function retrySyncNow() { return saveEngine.retrySyncNow(); }
// Canvas/display environment for the export envelope -- catches "my counts vanish at
// high zoom" by revealing the device pixel ratio, the probed canvas caps, the current
// render-area-safety knob (lowered if a blank was caught), and the last render's buffer
// dims. Read at export time only; all identifiers are module-scope and initialised by
// the time logs are exported.
// --- Interaction-latency telemetry (rings of recent samples, ms) ---
// placeMs: counter click -> mark painted (incl. undo snapshot + overlay).
// zoomCrispMs: last gesture input -> first crisp base paint after commit.
// undoSnapshotMs / renderAnnotationsMs / updateUIMs: the per-piece costs of
// the placement hot path, so "feels slow" decomposes into numbers. p50/p95
// ride the Save Status envelope via captureDisplayInfoObj below.
const PERF_SAMPLE_CAP = 200;
const perfSamples = { placeMs: [], zoomCrispMs: [], undoSnapshotMs: [], renderAnnotationsMs: [], updateUIMs: [] };
let pendingZoomCrispT0 = null;
function notePerfSample(kind, ms) {
const arr = perfSamples[kind];
if (!arr) return;
arr.push(Math.round(ms * 100) / 100);
if (arr.length > PERF_SAMPLE_CAP) arr.splice(0, arr.length - PERF_SAMPLE_CAP);
}
function perfSummary() {
const out = {};
for (const k of Object.keys(perfSamples)) {
const arr = perfSamples[k];
out[k] = { n: arr.length, p50: percentile(arr, 0.5), p95: percentile(arr, 0.95) };
}
return out;
}
function noteZoomCrispPaint() {
if (pendingZoomCrispT0 == null) return;
notePerfSample('zoomCrispMs', performance.now() - pendingZoomCrispT0);
pendingZoomCrispT0 = null;
}
function captureDisplayInfoObj() {
try {
return {
devicePixelRatio: (typeof window !== 'undefined' && window.devicePixelRatio) || null,
canvasCaps: getCanvasCaps(),
fallback: { maxDim: FALLBACK_MAX_DIM, maxArea: FALLBACK_MAX_AREA },
renderAreaSafety,
lastRender: {
pdfW: pdfCanvas ? pdfCanvas.width : null,
pdfH: pdfCanvas ? pdfCanvas.height : null,
annW: annCanvas ? annCanvas.width : null,
annH: annCanvas ? annCanvas.height : null,
effDpr: currentEffDpr
},
interactionLatency: perfSummary()
};
} catch (_) { return null; }
}
// autosaveEventDetail (the enriched event-detail builder) lives in
// save-engine.js (Stage 6), internal to the engine's event writers.
// serializeSaveErrorForEvent + saveDebugSerializeError moved (deduped) to
// save-utils.js as the single pure serializeSaveError; formatSaveStatusErrDetail
// moved there too. All three are referenced here by bare name (save-utils
// globals).
// runRecoveryProbe (Stage 7: its callers, the long-idle return and the
// online event, moved into the engine), runSupabaseClientProbe and
// recreateSupabaseClient have no app-side callers
// anymore (their orchestrators moved with them) — reach them via saveEngine.*.
// rawProjectsUpdate / rawProjectsInsert: engine-internal since Stage 6
// (the save paths moved in with them).
// rawCheckInProject / rawListAccessibleProjects have no app-side callers
// anymore (Turn In + permission refresh moved in Stage 5) — saveEngine.*.
// SECTION: Feature flags (per device, dormant-by-default ships)
// A change that must reach main before a tester has walked it on the real
// site ships behind a flag: OFF for everyone until `?ff=<name>` is opened
// once on a device (remembered in localStorage `clickcount-ff-<name>`;
// `?ff=-<name>` forgets it; several: `?ff=a,b`). The flag is a device
// preference like the hide-marks toggle, so it survives sign-out on
// purpose (not in the sign-out key list) and never rides a project. When
// the tester signs off, the follow-up PR flips the default and deletes the
// reads — the flag is a staging area, not a settings surface. Live flags:
// self-release the save-engine self-release stamp (2026-09-15, _TODO R1)
const FEATURE_FLAG_KEY_PREFIX = 'clickcount-ff-';
function featureFlagEnabled(name) {
try { return localStorage.getItem(FEATURE_FLAG_KEY_PREFIX + name) === '1'; } catch (_) { return false; }
}
(function applyFeatureFlagsFromUrl() {
try {
const raw = new URLSearchParams(location.search || '').get('ff');
if (!raw) return;
raw.split(',').forEach((tok) => {
tok = tok.trim();
if (!tok) return;
if (tok[0] === '-') localStorage.removeItem(FEATURE_FLAG_KEY_PREFIX + tok.slice(1));
else localStorage.setItem(FEATURE_FLAG_KEY_PREFIX + tok, '1');
});
} catch (_) { /* no storage: flags stay off */ }
})();
// SECTION: [sync] Global force reload
// The force-reload + keep-alive implementations moved to save-engine.js
// (createSaveEngine, a classic script loaded before this IIFE). The engine
// receives everything state/closure-coupled through this ctx of accessors —
// arrows resolve the live values at call time, so client recycles and `let`
// reassignments are always seen. The same-named wrappers below keep every
// call site, the App registry, and the window.* contracts frozen.
const saveEngine = createSaveEngine({
getState: () => state,
getSupabase: () => supabase,
isSupabaseEnabled: () => SUPABASE_ENABLED,
withTimeout: (p, ms, label) => withTimeout(p, ms, label),
isAutoSaveSuspended: () => suspendAutoSaveUntilCheckout,
getLastCheckoutRefreshAt: () => lastCheckoutRefreshAt,
// Stage 2 (dirty core): app-side state whose primary writers migrate later.
setLastModifiedAt: (ms) => { lastModifiedAt = ms; },
invalidateFooterTotals: () => invalidateFooterTotals(),
isCheckoutExpiredAttention: () => checkoutExpiredNeedsAttention,
setLastCheckoutRefreshAt: (ms) => { lastCheckoutRefreshAt = ms; },
updateServerClockFromRpc: (data) => updateServerClockFromRpc(data),
// Stage 3 (storage ring).
serverNowMs: () => serverNowMs(),
perfLog: (label, ms, extra) => perfLog(label, ms, extra),
getUserCustomIcons: () => getUserCustomIcons(),
computePageBakeFrame: (p) => computePageBakeFrame(p),
getLastModifiedAt: () => lastModifiedAt,
// Stage 4 (client resilience).
setSupabase: (client) => { supabase = client; },
getSupabaseUrl: () => SUPABASE_URL,
getSupabaseAnonKey: () => SUPABASE_ANON_KEY,
// Stage 5 (checkout UX): stage-6 save-path state via get/set until those
// paths migrate; UI hooks resolve at call time (definitions come later in
// this IIFE, but the engine only calls them from event/async contexts).
setTurnInProgress: (label) => setTurnInProgress(label),
showToast: (msg, ms) => showToast(msg, ms),
updateUI: () => updateUI(),
updateStatus: () => updateStatus(),
updateSaveStatusIndicator: () => updateSaveStatusIndicator(),
updateSettingsCheckoutSection: () => updateSettingsCheckoutSection(),
clearCheckoutExpiredAttention: () => clearCheckoutExpiredAttention(),
setCheckoutExpiredAttention: () => { checkoutExpiredNeedsAttention = true; suspendAutoSaveUntilCheckout = true; },
// Force turn-in notice modal (features/turn-in.js) — deferred App.* lookup
// per the registry load-order rule; truthy return = handled (engine skips
// its toast fallback).
notifyForceTurnedIn: (info) => !!(window.App && window.App.openForceTurnInNoticeModal && window.App.openForceTurnInNoticeModal(info)),
suspendAutoSave: () => { suspendAutoSaveUntilCheckout = true; },
isAuthError: (e) => isAuthError(e),
// T1-01 clobber guard: deferred App.* lookup (features/restore-last-session.js
// registers after app.js, per the registry load-order rule).
isRestorePromptPending: () => !!(window.App && window.App.isRestorePromptPending && window.App.isRestorePromptPending()),
// Dormant until flipped (_TODO.md R1-FLIP): the self-release stamp only
// classifies when the tester's device has opened ?ff=self-release.
isSelfReleaseStampEnabled: () => featureFlagEnabled('self-release'),
// Stage 6 (save paths): render-core / feature hooks the engine's save
// blobs and export envelope need; lastSaveIncludedPdf stays app-side
// (the load paths write it).
getServerClockOffsetMs: () => serverClockOffsetMs,
captureDisplayInfoObj: () => captureDisplayInfoObj(),
getMaxZoom: () => getProjectMaxZoom(), // DEEP-ZOOM: the project's own ceiling rides the save blob, never the device's
assertPdfWithinLimit: (bytes, context) => assertPdfWithinLimit(bytes, context),
maybeLogProjectSaveEvent: (projectId) => maybeLogProjectSaveEvent(projectId),
setLastSaveIncludedPdf: (v) => { lastSaveIncludedPdf = v; },
});
function checkGlobalForceReload() { return saveEngine.checkGlobalForceReload(); }
function doGlobalReloadNow(trigger) { return saveEngine.doGlobalReloadNow(trigger); }
function showGlobalReloadBanner() { return saveEngine.showGlobalReloadBanner(); }
saveEngine.installGlobalReloadStampCommit();
// isTransientSaveError(e) lives in save-utils.js (loaded before this IIFE).
// The [SaveDebug] helpers (isSaveDebugEnabled/setSaveDebugEnabled/
// saveDebugRunId/saveDebugLog/saveDebugLogError) live in save-engine.js
// (Stage 2); same-named wrappers below (saveDebugRunId has none since its
// one app-side caller, the autosave tick, moved in with Stage 7).
function isSaveDebugEnabled() { return saveEngine.isSaveDebugEnabled(); }
function setSaveDebugEnabled(on) { return saveEngine.setSaveDebugEnabled(on); }
function saveDebugLog(phase, payload) { return saveEngine.saveDebugLog(phase, payload); }
function getSaveStatusLogWindowMs() { return saveEngine.getSaveStatusLogWindowMs(); }
// The saveStatusLog array + prune/push live in save-engine.js (Stage 2);
// read it via saveEngine.getSaveStatusLog() (App.getSaveStatusLog delegates).
// saveStatusModalTickTimer moved to features/save-status.js (private to the modal).
let checkoutExpiredNeedsAttention = false;
// checkoutExpiredToastShown (the one-shot expired toast) lives in
// save-engine.js (Stage 5); re-armed via the engine call below.
function clearCheckoutExpiredAttention() {
checkoutExpiredNeedsAttention = false;
saveEngine.clearCheckoutExpiredToastShown();
suspendAutoSaveUntilCheckout = false;
updateSaveStatusIndicator();
}
function pruneSaveStatusLog() { return saveEngine.pruneSaveStatusLog(); }
// SECTION: [sync] Save Status log & envelope
function pushSaveEvent(kind, message, detail) { return saveEngine.pushSaveEvent(kind, message, detail); }
// SECTION: [sync] Field-error telemetry
// Save/sync failures arrive richly instrumented via the Save Status
// envelope, but a plain JS exception in the field (a handler throwing on an
// odd project) used to vanish silently — "it just stopped working" reports
// came with nothing. These hooks ride the SAME rails: client_error /
// client_unhandled_rejection events land in the saveStatusLog and export
// with the envelope. Deduped by kind+message and capped per session so a
// throw-in-a-loop can't flood the log (the log window prunes anyway; the cap
// keeps the envelope's tail useful). pushSaveEvent already drops everything
// when Supabase is disabled — cloud users are who export envelopes, so
// that's the right gate to inherit. Never rethrows, never preventDefaults:
// the console still shows the original error.
const CLIENT_ERROR_CAP = 10;
const clientErrorSeen = new Set();
let clientErrorCount = 0;
function reportClientError(kind, message, stack, source) {
try {
const msg = String(message || 'unknown').slice(0, 300);
const dedupeKey = kind + '|' + msg;
if (clientErrorSeen.has(dedupeKey) || clientErrorCount >= CLIENT_ERROR_CAP) return;
clientErrorSeen.add(dedupeKey);
clientErrorCount++;
pushSaveEvent(kind, msg, JSON.stringify({
source: String(source || '').slice(0, 200),
stack: String(stack || '').slice(0, 1500),
capped: clientErrorCount >= CLIENT_ERROR_CAP ? 'last reported this session' : undefined,
}));
// Mirror to the server-side activity feed (signed-in only — logUserEvent
// gates itself) so field crashes show up PROACTIVELY in the admin User
// Activity view instead of waiting for a user to export their envelope.
// Message + source only; the stack stays client-side in the envelope.
// The dedupe + session cap above already bound the volume.
logUserEvent(kind, state.currentProjectId || null, {
message: msg,
source: String(source || '').slice(0, 200),
});
} catch (_) { /* telemetry must never become its own error source */ }
}
window.addEventListener('error', (e) => {
// Resource-load errors (img/script) surface here with no .error — skip
// them; the SW/network layer owns those stories.
if (!e || (!e.error && !e.message)) return;
reportClientError('client_error', e.message, e.error && e.error.stack, (e.filename || '') + ':' + (e.lineno || 0));
});
window.addEventListener('unhandledrejection', (e) => {
const r = e && e.reason;
reportClientError('client_unhandled_rejection', (r && r.message) || String(r), r && r.stack, 'promise');
});
// getProjectSummaryForLogs + buildSaveLogsEnvelope(+WithSnapshots) + the
// per-tab session id live in save-engine.js (Stage 6). The wrapper keeps
// the App registry + features/save-status.js contract frozen.
function buildSaveLogsEnvelopeWithSnapshots() { return saveEngine.buildSaveLogsEnvelopeWithSnapshots(); }
function perfLog(label, durationMs, extra) {
const msg = '[Perf] ' + label + ': ' + durationMs + 'ms';
if (extra && Object.keys(extra).length) console.log(msg, extra);
else console.log(msg);
}
// SECTION: [sync] Dirty tracking & local session reset
// markProjectDirty + dirtyGeneration/dirtyStartedAt live in save-engine.js
// (Stage 2). The wrapper keeps the ~90 call sites + the App publish frozen;
// the debounced local-backup kick stays here (the writer moves in Stage 3).
function markProjectDirty() { return saveEngine.markProjectDirty(); }
// SECTION: Undo/redo stacks
// The undo/redo stack lives in annotation-model.js (createUndoStack(ctx),
// same seam as createAnnotationModel). Same-named wrappers keep the call
// sites + App publishes frozen; updateUI reads the depths via canUndo/canRedo.
const undoStackModel = createUndoStack({
getState: () => state,
uid: () => uid(),
ensureGroupColors: (g) => ensureGroupColors(g),
markProjectDirty: () => markProjectDirty(),
renderPdf: () => renderPdf(),
updateUI: () => updateUI(),
remapSessionPageIndices: (to) => annotationModel.remapSessionPageIndices(to),
});
// A run being edited (TOOL.EDIT_POLY) is spliced OUT of its page's polylines
// into state.editingPolyline, so a snapshot taken mid-edit (a vertex delete,
// a BEND-OVERRIDE choice) would capture the page WITHOUT it and an undo
// would drop the run outright while the tool sat in edit mode with nothing
// to edit (found by the BEND-OVERRIDE test round, 2026-09-18). Both wrappers
// put the run back for the length of the copy; undo then restores the page
// with the run as it was before the change, and leaves edit mode (below).
// `run` substitutes the copy that goes home (Done Editing homes the run as it
// was when editing began, so one undo reverts the whole edit session, drags
// included — drags take no snapshot of their own).
function withEditingPolylineHome(fn, run) {
const poly = state.editingPolyline ? (run || state.editingPolyline) : null;
const page = poly ? state.pages[state.editingPolyIndex] : null;
const canvas = page ? getActiveCanvas(page) : null;
if (!canvas) return fn();
if (!canvas.annotations.polylines) canvas.annotations.polylines = [];
canvas.annotations.polylines.push(poly);
try { return fn(); } finally { const i = canvas.annotations.polylines.indexOf(poly); if (i >= 0) canvas.annotations.polylines.splice(i, 1); }
}
function pushUndoSnapshot(homeRun) {
const t0 = performance.now();
const r = withEditingPolylineHome(() => undoStackModel.pushUndoSnapshot(), homeRun);
notePerfSample('undoSnapshotMs', performance.now() - t0);
return r;
}
// The step for a change to the page list itself (a page delete): undo puts
// the list back, not just what is on the pages (MAP-PAGE-UNDO, undo-stack.js).
function pushUndoSnapshotPageList() {
const t0 = performance.now();
const r = withEditingPolylineHome(() => undoStackModel.pushUndoSnapshotPageList());
notePerfSample('undoSnapshotMs', performance.now() - t0);
return r;
}
// Page-scoped snapshot for high-frequency page-local mutations (placements,
// drops, notes): O(current page) instead of O(project). Cascade operations
// (group/room deletes, imports, canvas repair) must keep pushUndoSnapshot.
function pushUndoSnapshotCurrentPage() {
const t0 = performance.now();
const r = withEditingPolylineHome(() => undoStackModel.pushUndoSnapshotPage(state.currentPage));
notePerfSample('undoSnapshotMs', performance.now() - t0);
return r;
}
// An undo/redo applied mid-edit nulls state.editingPolyline (the run is back
// on its page from the snapshot); the tool must follow it out of edit mode.
function leaveEditModeIfOrphaned() {
if (state.tool === TOOL.EDIT_POLY && !state.editingPolyline) {
state.editingPolylineOrig = null;
state.editingPolyIndex = null;
state.activePolylineId = null;
state.tool = TOOL.NONE;
state.draggingVertexIdx = null;
annCanvas.classList.remove('interactive');
if (App.hideBendVertexMenu) App.hideBendVertexMenu();
updateUI();
renderAnnotations();
}
}
// The one undo choke point (Ctrl+Z + the bottom-bar button): a successful
// undo toasts how many are left so the 50-step ceiling is never a surprise.
// STAMP-PICKUP (features/ghost.js): a ghost that Stamp handed to the cursor is dropped by
// an undo or redo, since the undo of the stamp puts that ghost back on the sheet (the
// snapshot holds it) and a second copy in hand would double it. A ghost in hand from a
// capture is untouched: no step holds it, so nothing comes back for it to double.
function dropGhostPickedUpByStamp() {
if (!state.placingGhostFromStamp) return;
state.placingGhost = null;
state.placingGhostLast = null;
state.placingGhostFromStamp = false;
}
function undo() {
// Undo/redo take the snapshot for the opposite stack at apply time, so the
// run being edited must be home for those too (else redo drops it).
const applied = withEditingPolylineHome(() => undoStackModel.undo());
if (applied) {
leaveEditModeIfOrphaned();
dropGhostPickedUpByStamp();
const left = undoStackModel.undoDepth();
showToast(left + (left === 1 ? ' undo left' : ' undos left'), 1000);
}
return applied;
}
function redo() { const applied = withEditingPolylineHome(() => undoStackModel.redo()); if (applied) { leaveEditModeIfOrphaned(); dropGhostPickedUpByStamp(); } return applied; }
function clearUndoStacks() { return undoStackModel.clearUndoStacks(); }
function resetAutosaveDegradedState() { return saveEngine.resetAutosaveDegradedState(); }
// Projects this signed-in session has held for editing (checked out, or
// opened as the editor). The header [Close] beside the edit-status banner
// shows only while VIEWING one of these — an estimator who turned a project
// in gets a one-click way out; a project only ever viewed does not grow a
// button. In-memory, cleared with the sign-out wipe (not by Close project
// itself — the same user reopening the project is still that session).
const editedProjectIds = new Set();
function resetLocalSessionState(opts) {
opts = opts || {};
const keepArtboard = !!opts.keepArtboard;
if (!keepArtboard) editedProjectIds.clear();
saveEngine.abortInFlightAutoSave('session_reset', true);
try { subscribeToProjectCheckoutChanges(null); } catch (_) {}
clearPdfBitmapCache();
state.pages = [];
state.currentPage = 0;
state.currentProjectId = null;
state.currentProjectName = null;
state.currentProjectExternalRef = null;
state.currentProjectUpdatedAt = null;
state.pdfBuffer = null;
state.pdfBufferSize = 0;
state.pdfStoragePath = null;
state.pdfHash = null;
state.localPdfHash = null;
state.projectOwnerId = null;
state.lastSavedAt = null;
saveEngine.resetLocalBackupState();
lastSaveIncludedPdf = false;
state.pendingCanvasLoad = null;
// R12: every project field from the one list (annotation-model.js
// freshProjectFields): groups, trade, codes, ceiling and make-up, Bid Check
// ticks, rooms, the layer map, the duct and water knobs, and the Quick Keys.
// The header pins start from the device's last arrangement (D21). The view
// settings (legend, zones, grid) ride the project but carry into the next.
// Quick Keys are unconditional: this reset doubles as the SIGN-OUT wipe, so
// bindings (and their artboard-seed lineage flag) never leak to the next user
// on a shared machine. The seed survives the normal new-bid flow (sign in ->
// upload PDF), which never passes through here.
Object.assign(state, freshProjectFields({ stripPins: readDeviceStripPins() }));
state.numberKeyBindingsSeededFromArtboard = false;
state.counterAirMoreOpen = null; // D19: the next project follows its own trade, not this one's override
state.parkedScaleDraft = null;
state.maxZoom = null;
state.checkedOutBy = null;
state.checkedOutAt = null;
state.checkedOutEmail = null;
state.isViewer = false;
state.loadedViaViewLink = false;
state.canCheckOut = false;
saveEngine.setAutoSaveDirty(false);
saveEngine.resetDirtyTracking();
saveEngine.resetSaveFlags();
saveEngine.resetTurnInState();
lastModifiedAt = 0;
if (App.resetCopyProjectState) App.resetCopyProjectState();
if (App.resetPdfIntakeFlags) App.resetPdfIntakeFlags();
if (App.onLastSessionRestoreReset) App.onLastSessionRestoreReset();
clearUndoStacks();
resetAutosaveDegradedState();
saveEngine.clearSaveStatusLog();
state.userActivityAllRowsCache = null;
state.userActivityViewMode = 'events';
try { saveEngine.resetAutoRecheckoutCounter(); } catch (_) {}
lastCheckoutRefreshAt = 0;
try { clearCheckoutExpiredAttention(); } catch (_) {}
try { localStorage.removeItem('clickcount-last-project'); } catch (_) {}
if (!keepArtboard) {
state.counters = [];
state.lineTypes = [];
try { customIconsCache = []; } catch (_) {}
}
try { updateSaveStatusIndicator(); } catch (_) {}
}
let signOutBroadcastChannel = null;
function broadcastSignOut() {
try {
if (typeof BroadcastChannel !== 'undefined') {
if (!signOutBroadcastChannel) signOutBroadcastChannel = new BroadcastChannel('clickcount-auth');
signOutBroadcastChannel.postMessage({ kind: 'signed_out', ts: Date.now() });
}
} catch (_) {}
try { localStorage.setItem('clickcount-signout-broadcast', String(Date.now())); } catch (_) {}
}
function handleCrossTabSignOut(source) {
try { pushSaveEvent('cross_tab_signout', 'Sign-out received from another tab', source || ''); } catch (_) {}
try { resetLocalSessionState(); } catch (_) {}
try { state.supabaseSession = null; state.isAdmin = false; state.isOverseer = false; state.isLead = false; state.isDigitalTwin = false; } catch (_) {}
// Clear lastAuthUserId so the local SIGNED_OUT event that follows (once
// supabase-js syncs the auth storage change) skips a redundant broadcast.
lastAuthUserId = null;
try { stopPresenceHeartbeat && stopPresenceHeartbeat(); } catch (_) {}
try { updateUI(); renderPdf(); updateSaveStatusIndicator(); } catch (_) {}
}
if (typeof window !== 'undefined') {
try {
if (typeof BroadcastChannel !== 'undefined') {
signOutBroadcastChannel = new BroadcastChannel('clickcount-auth');
signOutBroadcastChannel.addEventListener('message', (ev) => {