Repository navigation
Expand file tree
/
Copy pathannotation-model.js
More file actions
1225 lines (1203 loc) · 63 KB
/
Copy pathannotation-model.js
File metadata and controls
1225 lines (1203 loc) · 63 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
/*
* annotation-model.js — the canvas/annotation data model, extracted from
* app.js (Tier-2 item 7 of the post-engine map). Classic <script src> loaded
* AFTER geometry.js + icons.js (it reads bakeFramesMatch / CIRCLE_PATH by
* bare name) and BEFORE app.js, in the save-engine.js slot.
*
* Shape: createAnnotationModel(ctx) — the same seam recipe as
* createSaveEngine. ctx carries the state accessor and the app hooks the
* model's appliers need:
* getState() -> the live state object
* uid() -> id generator
* showToast(msg, ms) -> bake-mismatch warning UI
* ensureGroupColors(g) -> group color normalizer (app-side)
* saveUserCustomIcons(a)-> custom icon persister (app-side)
* getLineRealWorldLengthFeet(line, pageIdx, isPoly, ann)
* -> per-line real length in feet (app-side scale glue),
* used by the rect count/collect helpers
* app.js keeps same-named wrappers so every call site, the App registry, and
* the feature-file contracts stay frozen.
*
* The guarded CommonJS footer (inert in the browser) lets
* annotation-model.test.js require() this under node --test and
* eslint.config.js derive the app.js lint globals.
*/
// Collapse same-id palette entries (counters or line types) into one. Marks
// are stored under counterMarkers[id] / line.lineTypeId, so N palette entries
// sharing one id all claim the same placed marks and every total counts them
// N times (the Wendi FD bug, 2026-08-13: Palette Insights' name-keyed merge
// re-appended each RENAME of a counter with its original id). Keeps the FIRST
// occurrence's position and the LAST occurrence's fields (newest rename wins).
// Pure; safe on any array — entries without an id pass through untouched.
function dedupePaletteById(list) {
if (!Array.isArray(list)) return [];
const byId = new Map();
const out = [];
list.forEach(item => {
const id = item && item.id;
if (id == null) { out.push(item); return; }
if (byId.has(id)) Object.assign(byId.get(id), item);
else { const copy = { ...item }; byId.set(id, copy); out.push(copy); }
});
return out;
}
// --- Drop nodes (the Drop tool's model) -------------------------------------
//
// A drop is stored on a LINE END (line.startDrop / line.endDrop), but on the
// plan it belongs to a POINT: chain runs, and any two runs traced end-to-end,
// leave two line ends stacked on the same spot. The Drop tool clicks points,
// so it needs the point view — and the collapse is load-bearing, not cosmetic:
// writing a drop to both of a shared point's ends would add the vertical
// footage to the takeoff TWICE, which is the failure that loses trust in the
// number. So coincident ends become ONE node, and every write goes to exactly
// one of its refs while the rest are zeroed.
//
// Returns [{ x, y, refs: [{ kind: 'quick'|'poly', index, end: 'start'|'end' }],
// value, unit }] in PDF-space. `value`/`unit` report the node's
// current drop — the first ref carrying a positive one. Pure.
function collectDropNodes(ann, tol) {
const t = typeof tol === 'number' && tol > 0 ? tol : 1;
const nodes = [];
const add = (x, y, ref, drop, unit) => {
if (typeof x !== 'number' || typeof y !== 'number') return;
let node = null;
for (let i = 0; i < nodes.length; i++) {
const dx = nodes[i].x - x, dy = nodes[i].y - y;
if (dx * dx + dy * dy <= t * t) { node = nodes[i]; break; }
}
if (!node) { node = { x, y, refs: [], value: 0, unit: null }; nodes.push(node); }
node.refs.push(ref);
if (!(node.value > 0) && drop > 0) { node.value = drop; node.unit = unit || null; }
};
(ann?.quickLines || []).forEach((q, index) => {
add(q.x1, q.y1, { kind: 'quick', index, end: 'start' }, q.startDrop || 0, q.startDropUnit);
add(q.x2, q.y2, { kind: 'quick', index, end: 'end' }, q.endDrop || 0, q.endDropUnit);
});
(ann?.polylines || []).forEach((poly, index) => {
const pts = poly.points || [];
if (pts.length < 2) return;
add(pts[0].x, pts[0].y, { kind: 'poly', index, end: 'start' }, poly.startDrop || 0, poly.startDropUnit);
const last = pts[pts.length - 1];
add(last.x, last.y, { kind: 'poly', index, end: 'end' }, poly.endDrop || 0, poly.endDropUnit);
});
return nodes;
}
// Resolve one ref back to its line object.
function dropRefLine(ann, ref) {
if (!ann || !ref) return null;
return ref.kind === 'poly' ? (ann.polylines || [])[ref.index] : (ann.quickLines || [])[ref.index];
}
// Write `value` (in `unit`) to a node: the FIRST ref carries it, every other
// ref at the same point is zeroed, so a shared point contributes its vertical
// footage exactly once. `value` <= 0 clears the node. With `dryRun` true,
// nothing is written — the return value answers "would this change anything?",
// which callers check BEFORE pushing an undo snapshot (the stack has no
// discard API, so a snapshot must only be pushed for a real change). Returns
// true when something changed / would change.
function applyDropToNode(ann, node, value, unit, dryRun) {
if (!ann || !node || !Array.isArray(node.refs) || !node.refs.length) return false;
const v = typeof value === 'number' && value > 0 ? value : 0;
const u = String(unit || 'ft');
let changed = false;
node.refs.forEach((ref, i) => {
const line = dropRefLine(ann, ref);
if (!line) return;
const valKey = ref.end === 'start' ? 'startDrop' : 'endDrop';
const unitKey = valKey + 'Unit';
const want = i === 0 ? v : 0;
if ((line[valKey] || 0) !== want) { if (!dryRun) line[valKey] = want; changed = true; }
if (want > 0 && line[unitKey] !== u) { if (!dryRun) line[unitKey] = u; changed = true; }
});
if (changed && !dryRun) { node.value = v; node.unit = v > 0 ? u : null; }
return changed;
}
// --- Purging a deleted type or group from ghosts (Typicals) -----------------
//
// A ghost's src is annotation-shaped ({ counterMarkers, quickLines, polylines })
// but sits OUTSIDE the live marks, so the delete cascades (features/item-details.js
// performDeleteCounterLineType, features/groups.js deleteGroup) have to reach in
// here as well. Otherwise the Typical keeps the deleted counter's markers (drawn
// as a default circle), the deleted line type's runs, or the deleted group's id,
// and Stamp puts them back as marks no tally counts (MAP-GHOST-DELETE, D32).
//
// kind: 'counter' (drop counterMarkers[id]), 'lineType' (drop runs whose
// lineTypeId is id), 'group' (null every mark's and run's group id). A ghost
// left holding nothing is removed from ann.ghosts: capture never makes an empty
// one, and an empty one has no bounds to click. Mutates ann in place. Returns
// { changed, removedGhostIds }: changed counts the marks removed or ungrouped.
// No state, no DOM; the caller owns the undo snapshot, dirty and re-render.
function purgeFromGhosts(ann, kind, id) {
const out = { changed: 0, removedGhostIds: [] };
if (!ann || !Array.isArray(ann.ghosts) || id == null) return out;
const touched = [];
ann.ghosts.forEach(g => {
const src = g && g.src;
if (!src) return;
let n = 0;
if (kind === 'counter') {
const arr = src.counterMarkers && src.counterMarkers[id];
if (arr) { n += arr.length; delete src.counterMarkers[id]; }
} else if (kind === 'lineType') {
['quickLines', 'polylines'].forEach(key => {
if (!Array.isArray(src[key])) return;
const kept = src[key].filter(l => l.lineTypeId !== id);
n += src[key].length - kept.length;
src[key] = kept;
});
} else if (kind === 'group') {
const clear = (m) => { if (m && (m.group || null) === id) { m.group = null; n++; } };
Object.values(src.counterMarkers || {}).forEach(arr => (arr || []).forEach(clear));
(src.quickLines || []).forEach(clear);
(src.polylines || []).forEach(clear);
}
if (n) { out.changed += n; touched.push(g); }
});
const isEmpty = (g) => {
let marks = 0;
Object.values(g.src.counterMarkers || {}).forEach(arr => { marks += (arr || []).length; });
return !marks && !(g.src.quickLines || []).length && !(g.src.polylines || []).length;
};
touched.filter(isEmpty).forEach(g => {
out.removedGhostIds.push(g.id);
ann.ghosts.splice(ann.ghosts.indexOf(g), 1);
});
return out;
}
// --- What counts as a mark (S08, one table) ----------------------------------
//
// Every key makeAnnotations() returns, classified ONCE. Three hand lists of "is
// there anything on this layer" used to drift apart (the pages badge, the layer
// count, the signed-out re-apply, which forgot duct runs: REAPPLY-DUCT). Each
// key's role is one of:
// 'mark' the estimator put it there and it counts;
// 'placement' where something sits, or a reference laid over the sheet, that
// is not takeoff (the legend box; a ghost Typical until Stamp);
// 'derived' rebuilt from other marks, so counting it would count twice
// (duct fittings are inferred from their runs and die with them).
// `option` names the switch a caller may flip for the kinds whose answer depends
// on the question (a zone is a mark by default; a ghost or a fitting is not).
// `shape`: 'list' (an array), 'byId' ({ id: [marks] }), 'one' (an object or null).
// annotation-model.test.js walks makeAnnotations()'s keys and fails by name on a
// key missing here, so a new annotation kind is classified the day it is added.
const ANNOTATION_KINDS = Object.freeze({
counterMarkers: { role: 'mark', shape: 'byId' },
quickLines: { role: 'mark', shape: 'list' },
polylines: { role: 'mark', shape: 'list' },
ductRuns: { role: 'mark', shape: 'list' },
roomBoxes: { role: 'mark', shape: 'list' },
highlights: { role: 'mark', shape: 'list' },
notes: { role: 'mark', shape: 'list' },
multiplyZones: { role: 'mark', shape: 'list', option: 'zones' },
scaleZones: { role: 'mark', shape: 'list', option: 'zones' },
ghosts: { role: 'placement', shape: 'list', option: 'ghosts' },
legend: { role: 'placement', shape: 'one' },
ductFittings: { role: 'derived', shape: 'list', option: 'fittings' },
});
// Does this key count under these options? A kind with an option follows the
// caller's boolean when one is given, else its role; a kind without one is
// its role alone. An unclassified key never counts (the node test catches it).
function annotationKindCounts(key, opts) {
const kind = ANNOTATION_KINDS[key];
if (!kind) return false;
if (kind.option && opts && typeof opts[kind.option] === 'boolean') return opts[kind.option];
return kind.role === 'mark';
}
// How many marks one layer's annotations hold. opts: { zones, ghosts, fittings },
// each a boolean overriding the default (zones true, ghosts false, fittings false).
// `atMost` stops counting once reached, so the presence test is cheap.
function countAnnotationMarks(ann, opts, atMost) {
if (!ann || typeof ann !== 'object') return 0;
const cap = typeof atMost === 'number' && atMost > 0 ? atMost : Infinity;
let n = 0;
for (const key of Object.keys(ANNOTATION_KINDS)) {
if (!annotationKindCounts(key, opts)) continue;
const v = ann[key];
const shape = ANNOTATION_KINDS[key].shape;
if (shape === 'byId') {
if (v && typeof v === 'object') Object.keys(v).forEach((id) => { if (Array.isArray(v[id])) n += v[id].length; });
} else if (shape === 'one') {
if (v && typeof v === 'object') n += 1;
} else if (Array.isArray(v)) {
n += v.length;
}
if (n >= cap) return n;
}
return n;
}
function annotationHasMarks(ann, opts) { return countAnnotationMarks(ann, opts, 1) > 0; }
// --- The project's own fields (R12, one list) --------------------------------
//
// What a takeoff carries besides its sheets: the palette, and the fields that
// belong to the PROJECT. One list, read by everything that must treat them as a
// set: the boot pre-apply's Discard (app.js undoBootPreApply puts these back),
// the session reset (resetLocalSessionState starts a project from
// freshProjectFields), and annotation-model.test.js, which applies a backup with
// every field set and checks that exactly these change. A new per-project field
// goes here, in save-utils.js projectPayloadFields, and in both hydrators below;
// the round-trip tests fail by name on a missed one.
const PALETTE_FIELDS = ['counters', 'lineTypes', 'iconNames', 'iconOrder'];
const TAKEOFF_BACKUP_PROJECT_FIELDS = [
'groups', 'groupsEnabled', 'stripPins', 'trade', 'ceilingHeightFt', 'makeUpFt', 'codes', 'bidCheck', 'rooms',
'activeCanvasIdByPage', 'numberKeyBindings', 'ductSettings', 'waterSettings',
'legendSettings', 'multiplyZoneSettings', 'scaleZoneSettings', 'showGridOverlay', 'gridSettings',
];
// The view settings among them that the session carries into the next project:
// a project saved with them restores them, but closing one does not reset them.
const CARRIED_VIEW_FIELDS = ['legendSettings', 'multiplyZoneSettings', 'scaleZoneSettings', 'showGridOverlay', 'gridSettings'];
// Duct and water knobs through their models' normalizers (duct-model.js and
// water-model.js load before this file; node tests that skip them get a copy).
function normDuctSettings(raw) {
if (typeof normalizeDuctSettings === 'function') return normalizeDuctSettings(raw);
return raw && typeof raw === 'object' ? { ...raw } : {};
}
// The value each reset field starts from in a project that never set it (every
// project field but the carried view settings). Fresh objects on every call.
// stripPins is {} here ("follow the trade"); the session reset passes the device's
// last arrangement instead.
function freshProjectFields(overrides) {
const fresh = {
groups: [], groupsEnabled: false, stripPins: {}, trade: null, ceilingHeightFt: null, makeUpFt: null,
codes: null, bidCheck: { manual: {} }, rooms: [], activeCanvasIdByPage: {}, numberKeyBindings: {},
ductSettings: normDuctSettings(null),
waterSettings: typeof normalizeWaterSettings === 'function' ? normalizeWaterSettings(null) : null,
};
return Object.assign(fresh, overrides || {});
}
function createAnnotationModel(ctx) {
function makeAnnotations() { return { counterMarkers: {}, polylines: [], quickLines: [], highlights: [], notes: [], multiplyZones: [], scaleZones: [], roomBoxes: [], ghosts: [], ductRuns: [], ductFittings: [], legend: null }; }
function getPageCanvases(page) { return page?.canvases ?? []; }
// pageIdxHint (optional): the page's index when the caller already knows it —
// skips the O(pages) indexOf, which otherwise makes every all-pages loop over
// these accessors O(pages²) on large projects. Callers without the index are
// unchanged (indexOf fallback).
function getActiveCanvas(page, pageIdxHint) {
if (!page) return null;
const canvases = getPageCanvases(page);
if (!canvases.length) return null;
const pageIdx = (pageIdxHint != null && ctx.getState().pages?.[pageIdxHint] === page) ? pageIdxHint : ctx.getState().pages?.indexOf(page);
const activeId = pageIdx >= 0 ? ctx.getState().activeCanvasIdByPage?.[pageIdx] : null;
const found = activeId ? canvases.find(c => c.id === activeId) : null;
return found || canvases[0];
}
function getActiveAnnotations(page, pageIdxHint) {
const canvas = getActiveCanvas(page, pageIdxHint);
return canvas?.annotations ?? makeAnnotations();
}
function mergeAnnotations(...anns) {
const out = makeAnnotations();
anns.forEach(ann => {
if (!ann) return;
Object.entries(ann.counterMarkers || {}).forEach(([id, arr]) => {
if (!out.counterMarkers) out.counterMarkers = {};
if (!out.counterMarkers[id]) out.counterMarkers[id] = [];
out.counterMarkers[id].push(...arr);
});
(ann.quickLines || []).forEach(q => { (out.quickLines = out.quickLines || []).push(q); });
(ann.polylines || []).forEach(p => { (out.polylines = out.polylines || []).push(p); });
(ann.notes || []).forEach(n => { (out.notes = out.notes || []).push(n); });
(ann.highlights || []).forEach(h => { (out.highlights = out.highlights || []).push(h); });
(ann.multiplyZones || []).forEach(z => { (out.multiplyZones = out.multiplyZones || []).push(z); });
(ann.scaleZones || []).forEach(z => { (out.scaleZones = out.scaleZones || []).push(z); });
(ann.roomBoxes || []).forEach(b => { (out.roomBoxes = out.roomBoxes || []).push(b); });
(ann.ghosts || []).forEach(g => { (out.ghosts = out.ghosts || []).push(g); });
(ann.ductRuns || []).forEach(r => { (out.ductRuns = out.ductRuns || []).push(r); });
(ann.ductFittings || []).forEach(f => { (out.ductFittings = out.ductFittings || []).push(f); });
});
return out;
}
// onlyIds (optional): an ARRAY of canvas ids to include — the selective
// show-canvases peek. The active canvas is always included regardless of the
// list; omitted/null means every canvas (the classic show-all merge).
// Array-gated on purpose: report.js and the export paths pass this function
// around as a generic (page, pageIdx) annotations getter, so a non-array
// second argument (the page index) must keep meaning "merge everything".
function getMergedAnnotationsForPage(page, onlyIds) {
const canvases = getPageCanvases(page);
const filter = Array.isArray(onlyIds) ? onlyIds : null;
const active = filter ? getActiveCanvas(page) : null;
const use = filter ? canvases.filter(c => c === active || filter.includes(c.id)) : canvases;
const anns = use.map(c => c.annotations || makeAnnotations());
return mergeAnnotations(...anns);
}
function ensureActiveCanvas(page) {
migratePageToCanvases(page);
let canvas = getActiveCanvas(page);
if (!canvas) {
const id = ctx.uid();
page.canvases = [{ id, name: 'Main', annotations: makeAnnotations() }];
const pi = ctx.getState().pages?.indexOf(page);
if (pi >= 0) ctx.getState().activeCanvasIdByPage[pi] = id;
canvas = page.canvases[0];
}
return canvas;
}
function migratePageToCanvases(page) {
if (!page) return;
if (page.canvases && page.canvases.length) return;
const ann = page.annotations || makeAnnotations();
page.canvases = [{ id: ctx.uid(), name: 'Main', annotations: ann }];
delete page.annotations;
}
// S08: all three read the ANNOTATION_KINDS table above (opts as there).
function pageHasAnyAnnotations(p, opts) {
return getPageCanvases(p).some(c => annotationHasMarks(c && c.annotations, opts));
}
function projectHasAnyCanvasMarkup(opts) {
const pages = ctx.getState().pages;
return Array.isArray(pages) && pages.some(p => pageHasAnyAnnotations(p, opts));
}
// "How many marks are on this layer": the Clear Page confirm and the layer
// details name it. Moved here from app.js (S08); App.countCanvasMarks as before.
function countCanvasMarks(ann, opts) { return countAnnotationMarks(ann, opts); }
function backupDataToProjFormat(data) {
if (!data || (data.pages && Array.isArray(data.pages))) return data;
if (data.pageCanvases && Array.isArray(data.pageCanvases)) {
return {
...data,
pages: data.pageCanvases.map((canvases, i) => ({
index: i,
label: data.pageLabels?.[i],
canvases,
scale: data.pageScales?.[i],
rotation: (data.pageRotations?.[i] ?? 0),
bakeFrame: data.pageBakeFrames?.[i] ?? null
}))
};
}
return data;
}
// The frame a page's annotations are baked into: viewport dims at the page's rotation
// plus the PDF's intrinsic /Rotate. Stamped into saved data so a later load can detect
// when the loaded PDF would render the page in a different orientation than the marks
// were placed against ("rotated under the canvas"). See verifyPageBakeFrame.
function computePageBakeFrame(p) {
if (!p?.pdfPage) return null;
try {
const vp = p.pdfPage.getViewport({ scale: 1, rotation: p.rotation ?? 0 });
return { w: Math.round(vp.width), h: Math.round(vp.height), intrinsic: p.pdfPage.rotate ?? 0 };
} catch (_) { return null; }
}
let lastBakeMismatchToastAt = 0;
// Detect-and-warn (never auto-correct): if the loaded PDF produces a different frame than
// the marks were baked against, the overlay will be misaligned. Surface it instead of
// rendering silently wrong. `page.bakeMismatch` feeds the Save Status telemetry.
function verifyPageBakeFrame(page, savedBakeFrame) {
if (!savedBakeFrame || !page?.pdfPage) return;
const cur = computePageBakeFrame(page);
if (bakeFramesMatch(savedBakeFrame, cur, 1)) { page.bakeMismatch = false; return; }
page.bakeMismatch = true;
try { console.warn('[bakeFrame] page orientation mismatch', { saved: savedBakeFrame, current: cur, rotation: page.rotation ?? 0 }); } catch (_) { /* noop */ }
const now = Date.now();
if (now - lastBakeMismatchToastAt > 4000) {
lastBakeMismatchToastAt = now;
try { ctx.showToast('This view may be misaligned. The PDF differs from when the marks were placed.', 6000); } catch (_) { /* showToast may not be ready */ }
}
}
// WATER-PLAN rung 5: the water caps, through water-model's normalizer when it is loaded (the node tests load this file alone).
function normWater(raw) {
const wm = typeof window !== 'undefined' ? window.WaterModel : null;
if (wm && typeof wm.normalizeWaterSettings === 'function') return wm.normalizeWaterSettings(raw);
return raw && raw.capFps ? { capFps: { ...raw.capFps } } : raw;
}
// Codes & jurisdiction (rulebook slice 4): keep only the strings a project chose.
// constants.js normalizeProjectCodes (loaded before this file) is the one rule.
function normCodes(raw) { return normalizeProjectCodes(raw); }
// Header pins (D21), per project: a copy of the saved map, or {} (follow the trade).
function normStripPins(raw) {
return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? { ...raw } : {};
}
// Quick Keys go through features/quick-keys.js's one lifecycle rule (the project's
// bindings replace; none keeps an Artboard seed and drops a previous project's).
// Read at CALL time: the feature loads after app.js, which builds this model. Node
// (the tests load this file alone) and a shell without the feature copy them plain.
function applyQuickKeys(raw) {
const App = typeof window !== 'undefined' ? window.App : null;
if (App && typeof App.applyProjectQuickKeys === 'function') { App.applyProjectQuickKeys(raw); return; }
ctx.getState().numberKeyBindings = (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw : {};
}
function applyTakeoffBackupToState(backup) {
if (!backup) return;
if (Array.isArray(backup.counters)) ctx.getState().counters = backup.counters;
if (Array.isArray(backup.lineTypes)) ctx.getState().lineTypes = backup.lineTypes;
if (Array.isArray(backup.groups)) ctx.getState().groups = ctx.ensureGroupColors(backup.groups);
if (backup.groupsEnabled != null) ctx.getState().groupsEnabled = !!backup.groupsEnabled;
if (backup.stripPins && typeof backup.stripPins === 'object') ctx.getState().stripPins = normStripPins(backup.stripPins); // D21; absent = keep, like the rest of this merge
ctx.getState().trade = typeof backup.trade === 'string' && backup.trade ? backup.trade : null;
ctx.getState().ceilingHeightFt = typeof backup.ceilingHeightFt === 'number' && backup.ceilingHeightFt > 0 ? backup.ceilingHeightFt : null;
ctx.getState().makeUpFt = typeof backup.makeUpFt === 'number' && backup.makeUpFt >= 0 ? backup.makeUpFt : null;
ctx.getState().codes = normCodes(backup.codes);
ctx.getState().bidCheck = (backup.bidCheck && typeof backup.bidCheck === 'object') ? { ...backup.bidCheck, manual: { ...(backup.bidCheck.manual || {}) } } : { manual: {} }; // S5 Bid Check ticks + defaults
if (Array.isArray(backup.rooms)) ctx.getState().rooms = backup.rooms;
if (backup.iconNames && typeof backup.iconNames === 'object') ctx.getState().iconNames = backup.iconNames;
if (Array.isArray(backup.iconOrder)) ctx.getState().iconOrder = backup.iconOrder;
if (Array.isArray(backup.customIconPaths)) ctx.saveUserCustomIcons(backup.customIconPaths);
if (backup.activeCanvasIdByPage && typeof backup.activeCanvasIdByPage === 'object') ctx.getState().activeCanvasIdByPage = backup.activeCanvasIdByPage;
if (backup.numberKeyBindings && typeof backup.numberKeyBindings === 'object') ctx.getState().numberKeyBindings = backup.numberKeyBindings;
if (backup.pageCanvases && Array.isArray(backup.pageCanvases)) {
backup.pageCanvases.forEach((canvases, i) => {
if (ctx.getState().pages[i] && Array.isArray(canvases) && canvases.length) ctx.getState().pages[i].canvases = canvases;
});
} else if (backup.pageAnnotations && Array.isArray(backup.pageAnnotations)) {
backup.pageAnnotations.forEach((ann, i) => {
if (ctx.getState().pages[i]) {
ctx.getState().pages[i].canvases = [{ id: ctx.uid(), name: 'Main', annotations: ann }];
delete ctx.getState().pages[i].annotations;
}
});
}
if (backup.pageScales) backup.pageScales.forEach((s, i) => { if (ctx.getState().pages[i]) ctx.getState().pages[i].scale = s; });
if (backup.pageRotations) backup.pageRotations.forEach((r, i) => { if (ctx.getState().pages[i]) ctx.getState().pages[i].rotation = r ?? 0; });
if (backup.pageLabels) backup.pageLabels.forEach((l, i) => { if (typeof l === 'string' && l && ctx.getState().pages[i]) ctx.getState().pages[i].label = l; });
if (backup.pageBakeFrames) backup.pageBakeFrames.forEach((bf, i) => { if (ctx.getState().pages[i]) verifyPageBakeFrame(ctx.getState().pages[i], bf); });
if (backup.legendSettings) ctx.getState().legendSettings = { ...ctx.getState().legendSettings, ...backup.legendSettings };
if (backup.ductSettings) ctx.getState().ductSettings = normDuctSettings(backup.ductSettings); // R12: over the defaults, not the session's
if (backup.waterSettings) ctx.getState().waterSettings = normWater(backup.waterSettings); // WATER-PLAN rung 5
if (backup.multiplyZoneSettings) ctx.getState().multiplyZoneSettings = { ...ctx.getState().multiplyZoneSettings, ...backup.multiplyZoneSettings };
if (backup.scaleZoneSettings) ctx.getState().scaleZoneSettings = { ...ctx.getState().scaleZoneSettings, ...backup.scaleZoneSettings };
if (backup.showGridOverlay != null) ctx.getState().showGridOverlay = !!backup.showGridOverlay;
if (backup.gridSettings) ctx.getState().gridSettings = backup.gridSettings;
}
// The shared project hydration block: palettes, icon prefs, per-page
// annotations, and the per-project view settings. ONE home for the contract.
// The view-link boot (features/view-only.js) and the last-session restore
// (features/restore-last-session.js) shared it from 2026-07-30; since R12
// (2026-09-26) every project intake does: cloud load's two canvas-only branches
// (features/load-project.js), the sheets built from a cloud PDF
// (features/copy-project.js), both PDF-first intakes (features/pdf-intake.js)
// and Import Canvas (features/import-clear.js), each of which carried its own
// copy and had drifted. Callers construct state.pages first (or leave it empty,
// canvas-only); this fills in everything the project data payload carries.
//
// opts (each off by default, for the intakes that need it):
// scaleFallback: a sheet saved without a scale takes this one (Import Canvas's
// legacy top-level `scale`), passed to applyPageAnnotationsFromData;
// legacyScales: the old page-array scales (`pageScales`), or failing those one
// `scale` for every sheet, laid over the pages (the cloud-PDF and
// PDF-first intakes, which may read pre-pages or backup-shaped data);
// trimLayers: keep the chosen-layer map to the sheets this plan has (the
// intakes where the PDF in hand may not be the one saved).
// Returns { pageEntries, appliedPages }: how many saved sheets there were, and how
// many landed on a sheet of this plan (Import Canvas says so when it is fewer).
function hydrateStateFromProjectData(d, opts) {
const o = opts || {};
const state = ctx.getState();
state.counters = Array.isArray(d.counters) ? d.counters : [];
state.lineTypes = Array.isArray(d.lineTypes) ? d.lineTypes : [];
state.groups = ctx.ensureGroupColors(Array.isArray(d.groups) ? d.groups : []);
state.groupsEnabled = !!d.groupsEnabled;
state.stripPins = normStripPins(d.stripPins); // D21 header pins
state.trade = typeof d.trade === 'string' && d.trade ? d.trade : null; // 'plumbing' | 'electrical' | 'hvac' | null
state.ceilingHeightFt = typeof d.ceilingHeightFt === 'number' && d.ceilingHeightFt > 0 ? d.ceilingHeightFt : null; // S2 vertical-by-default
state.makeUpFt = typeof d.makeUpFt === 'number' && d.makeUpFt >= 0 ? d.makeUpFt : null;
state.codes = normCodes(d.codes); // rulebook slice 4: the editions + jurisdiction the project chose
state.bidCheck = (d.bidCheck && typeof d.bidCheck === 'object') ? { ...d.bidCheck, manual: { ...(d.bidCheck.manual || {}) } } : { manual: {} }; // S5 Bid Check ticks + defaults
state.rooms = Array.isArray(d.rooms) ? d.rooms : [];
if (d.iconNames && typeof d.iconNames === 'object') state.iconNames = d.iconNames;
if (Array.isArray(d.iconOrder)) state.iconOrder = d.iconOrder;
if (Array.isArray(d.customIconPaths)) ctx.saveUserCustomIcons(d.customIconPaths);
const pageEntries = Array.isArray(d.pages) ? d.pages : [];
let appliedPages = 0;
pageEntries.forEach(p => {
if (!p) return;
if (state.pages[p.index]) appliedPages++;
applyPageAnnotationsFromData(state.pages[p.index], p, o.scaleFallback);
});
if (o.legacyScales) {
if (Array.isArray(d.pageScales)) d.pageScales.forEach((scale, i) => { if (state.pages[i]) state.pages[i].scale = scale; });
else if (d.scale) state.pages.forEach(pg => { pg.scale = d.scale; });
}
if (d.activeCanvasIdByPage && typeof d.activeCanvasIdByPage === 'object') {
if (o.trimLayers) {
const kept = {};
Object.entries(d.activeCanvasIdByPage).forEach(([k, v]) => {
const idx = Number(k);
if (Number.isFinite(idx) && state.pages[idx]) kept[idx] = v;
});
state.activeCanvasIdByPage = kept;
} else {
state.activeCanvasIdByPage = d.activeCanvasIdByPage;
}
}
applyQuickKeys(d.numberKeyBindings); // MAP-QUICKKEYS: a restored cloud bid kept the last session's keys
state.maxZoom = d.maxZoom != null ? d.maxZoom : null;
if (d.legendSettings) state.legendSettings = { ...state.legendSettings, ...d.legendSettings };
state.ductSettings = normDuctSettings(d.ductSettings); // R12: the project's knobs over the defaults, never the last project's
if (d.waterSettings) state.waterSettings = normWater(d.waterSettings); // WATER-PLAN rung 5: the velocity caps
if (d.multiplyZoneSettings) state.multiplyZoneSettings = { ...state.multiplyZoneSettings, ...d.multiplyZoneSettings };
if (d.scaleZoneSettings) state.scaleZoneSettings = { ...state.scaleZoneSettings, ...d.scaleZoneSettings };
if (d.showGridOverlay != null) state.showGridOverlay = !!d.showGridOverlay;
if (d.gridSettings) state.gridSettings = d.gridSettings;
return { pageEntries: pageEntries.length, appliedPages };
}
function applyPageAnnotationsFromData(page, p, scaleFallback) {
if (!page) return;
if (p.canvases && Array.isArray(p.canvases) && p.canvases.length) {
page.canvases = p.canvases.map(c => ({
id: c.id || ctx.uid(),
name: c.name || 'Main',
annotations: c.annotations ? {
counterMarkers: c.annotations.counterMarkers && typeof c.annotations.counterMarkers === 'object' ? c.annotations.counterMarkers : {},
polylines: Array.isArray(c.annotations.polylines) ? c.annotations.polylines : [],
quickLines: Array.isArray(c.annotations.quickLines) ? c.annotations.quickLines : [],
highlights: Array.isArray(c.annotations.highlights) ? c.annotations.highlights : [],
notes: Array.isArray(c.annotations.notes) ? c.annotations.notes : [],
multiplyZones: Array.isArray(c.annotations.multiplyZones) ? c.annotations.multiplyZones : [],
scaleZones: Array.isArray(c.annotations.scaleZones) ? c.annotations.scaleZones : [],
roomBoxes: Array.isArray(c.annotations.roomBoxes) ? c.annotations.roomBoxes : [],
ghosts: Array.isArray(c.annotations.ghosts) ? c.annotations.ghosts : [],
ductRuns: Array.isArray(c.annotations.ductRuns) ? c.annotations.ductRuns : [],
ductFittings: Array.isArray(c.annotations.ductFittings) ? c.annotations.ductFittings : [],
legend: c.annotations.legend && typeof c.annotations.legend === 'object' ? c.annotations.legend : null
} : makeAnnotations()
}));
delete page.annotations;
} else if (p.annotations) {
const a = p.annotations;
const ann = {
counterMarkers: a.counterMarkers && typeof a.counterMarkers === 'object' ? a.counterMarkers : {},
polylines: Array.isArray(a.polylines) ? a.polylines : [],
quickLines: Array.isArray(a.quickLines) ? a.quickLines : [],
highlights: Array.isArray(a.highlights) ? a.highlights : [],
notes: Array.isArray(a.notes) ? a.notes : [],
multiplyZones: Array.isArray(a.multiplyZones) ? a.multiplyZones : [],
scaleZones: Array.isArray(a.scaleZones) ? a.scaleZones : [],
roomBoxes: Array.isArray(a.roomBoxes) ? a.roomBoxes : [],
ghosts: Array.isArray(a.ghosts) ? a.ghosts : [],
ductRuns: Array.isArray(a.ductRuns) ? a.ductRuns : [],
ductFittings: Array.isArray(a.ductFittings) ? a.ductFittings : [],
legend: a.legend && typeof a.legend === 'object' ? a.legend : null
};
page.canvases = [{ id: ctx.uid(), name: 'Main', annotations: ann }];
delete page.annotations;
}
// The saved sheet name (pages-list / Prepare PDF rename) must win over the
// default label callers pre-seed at page construction — like scale/rotation.
if (typeof p.label === 'string' && p.label) page.label = p.label;
page.scale = p.scale !== undefined ? p.scale : (scaleFallback ?? null);
page.rotation = p.rotation ?? 0;
verifyPageBakeFrame(page, p.bakeFrame);
}
function reconcileOrphanedCountersAndLineTypes() {
if (!ctx.getState().pages || !ctx.getState().pages.length) return;
// Self-heal duplicate-id palettes first (see dedupePaletteById): this
// reconcile runs at every palette intake (cloud load, import, copy,
// artboard apply, pdf-intake, canvas repair), so corrupted payloads are
// collapsed on open and written back clean by the next save.
ctx.getState().counters = dedupePaletteById(ctx.getState().counters);
ctx.getState().lineTypes = dedupePaletteById(ctx.getState().lineTypes);
ctx.getState().pages.forEach(migratePageToCanvases);
const counterIds = new Set((ctx.getState().counters || []).map(c => c.id));
const lineTypeIds = new Set((ctx.getState().lineTypes || []).map(lt => lt.id));
const roomIds = new Set((ctx.getState().rooms || []).map(r => r.id));
const orphanCounterIds = new Set();
const orphanLineTypeIds = new Set();
const orphanRoomIds = new Set();
ctx.getState().pages.forEach(p => {
getPageCanvases(p).forEach(c => {
const ann = c.annotations || makeAnnotations();
Object.keys(ann.counterMarkers || {}).forEach(id => { if (!counterIds.has(id)) orphanCounterIds.add(id); });
(ann.quickLines || []).forEach(q => { if (q.lineTypeId && !lineTypeIds.has(q.lineTypeId)) orphanLineTypeIds.add(q.lineTypeId); });
(ann.polylines || []).forEach(poly => { if (poly.lineTypeId && !lineTypeIds.has(poly.lineTypeId)) orphanLineTypeIds.add(poly.lineTypeId); });
(ann.roomBoxes || []).forEach(b => { if (b.roomId && !roomIds.has(b.roomId)) orphanRoomIds.add(b.roomId); });
});
});
if (orphanCounterIds.size > 0) {
ctx.getState().counters = ctx.getState().counters || [];
orphanCounterIds.forEach(id => {
if (!ctx.getState().counters.some(c => c.id === id)) {
ctx.getState().counters.push({ id, name: 'Unknown', icon: CIRCLE_PATH, color: '#e8c547' });
}
});
}
if (orphanLineTypeIds.size > 0) {
ctx.getState().lineTypes = ctx.getState().lineTypes || [];
orphanLineTypeIds.forEach(id => {
if (!ctx.getState().lineTypes.some(lt => lt.id === id)) {
ctx.getState().lineTypes.push({ id, name: 'Unknown', color: '#4a9eff', curveStyle: 'straight' });
}
});
}
if (orphanRoomIds.size > 0) {
ctx.getState().rooms = ctx.getState().rooms || [];
orphanRoomIds.forEach(id => {
if (!ctx.getState().rooms.some(r => r.id === id)) {
ctx.getState().rooms.push({ id, name: 'Unknown room', color: '#47c88e' });
}
});
}
}
// --- Palette relink (Load-from-Cloud, T1-09) ------------------------------
// Marks are keyed by palette id, so a wholesale palette replace (Load from
// Cloud) orphans every placed mark whose trade name survives under a new id.
// planPaletteRelink maps CURRENT palette ids to INCOMING ids by trimmed
// case-insensitive name (the exact nameKey convention Palette Insights uses
// for its "On Artboard" badge) and counts the placed marks each way;
// applyPaletteRelink rewrites the annotations through those maps. Name
// matching lives ONLY here — reconcileOrphanedCountersAndLineTypes stays
// byte-identical for its six other intake paths and remains the backstop
// that turns any still-unmatched mark into a visible "Unknown" row.
function paletteNameKey(s) { return String(s || '').trim().toLowerCase(); }
function planPaletteRelink(incomingCounters, incomingLineTypes) {
const state = ctx.getState();
// First incoming match wins on duplicate names (deterministic); identity
// mappings (oldId === newId) are dropped from the maps but still count as
// matched — those marks keep counting without a rewrite.
const buildMap = (current, incoming) => {
const incomingByName = new Map();
(incoming || []).forEach(it => {
const key = paletteNameKey(it.name);
if (key && !incomingByName.has(key)) incomingByName.set(key, it.id);
});
const map = {};
const matched = new Set();
(current || []).forEach(it => {
const key = paletteNameKey(it.name);
if (!key || !incomingByName.has(key)) return;
matched.add(it.id);
const newId = incomingByName.get(key);
if (newId !== it.id) map[it.id] = newId;
});
return { map, matched };
};
const c = buildMap(state.counters, incomingCounters);
const lt = buildMap(state.lineTypes, incomingLineTypes);
const currentCounterIds = new Set((state.counters || []).map(x => x.id));
const currentLineTypeIds = new Set((state.lineTypes || []).map(x => x.id));
let relinkedMarks = 0;
let orphanedMarks = 0;
// Marks already orphaned before the load (id not in the current palette)
// count toward neither bucket — reconcile's Unknown backfill covers them.
const tallyCounter = (id, n) => {
if (!n) return;
if (c.matched.has(id)) relinkedMarks += n;
else if (currentCounterIds.has(id)) orphanedMarks += n;
};
const tallyLine = (id) => {
if (!id) return;
if (lt.matched.has(id)) relinkedMarks++;
else if (currentLineTypeIds.has(id)) orphanedMarks++;
};
(state.pages || []).forEach(p => {
getPageCanvases(p).forEach(cv => {
const ann = cv.annotations || makeAnnotations();
Object.entries(ann.counterMarkers || {}).forEach(([id, arr]) => tallyCounter(id, (arr || []).length));
(ann.quickLines || []).forEach(q => tallyLine(q.lineTypeId));
(ann.polylines || []).forEach(poly => tallyLine(poly.lineTypeId));
});
});
return { counterIdMap: c.map, lineTypeIdMap: lt.map, relinkedMarks, orphanedMarks };
}
// Rewrites annotations in place through the plan's id maps, across every
// page/canvas. counterMarkers is rebuilt in ONE pass so key renames can
// never chain (oldA→x while x→y must not double-move oldA's markers);
// colliding targets MERGE (two same-named old counters relink to one
// incoming counter — markers concatenate, none are lost). No UI calls —
// the caller renders.
function applyPaletteRelink(plan) {
const counterIdMap = plan?.counterIdMap || {};
const lineTypeIdMap = plan?.lineTypeIdMap || {};
const hasCounterMap = Object.keys(counterIdMap).length > 0;
const hasLineMap = Object.keys(lineTypeIdMap).length > 0;
if (!hasCounterMap && !hasLineMap) return;
(ctx.getState().pages || []).forEach(p => {
getPageCanvases(p).forEach(cv => {
const ann = cv.annotations;
if (!ann) return;
if (hasCounterMap && ann.counterMarkers) {
const next = {};
Object.entries(ann.counterMarkers).forEach(([id, arr]) => {
const target = counterIdMap[id] || id;
if (next[target]) next[target].push(...(arr || []));
else next[target] = arr || [];
});
ann.counterMarkers = next;
}
if (hasLineMap) {
(ann.quickLines || []).forEach(q => { if (q.lineTypeId && lineTypeIdMap[q.lineTypeId]) q.lineTypeId = lineTypeIdMap[q.lineTypeId]; });
(ann.polylines || []).forEach(poly => { if (poly.lineTypeId && lineTypeIdMap[poly.lineTypeId]) poly.lineTypeId = lineTypeIdMap[poly.lineTypeId]; });
}
});
});
}
// --- Rect-select operations (Multiply Zone preview + Delete Area) ---------
// Hit semantics: lines count only when BOTH endpoints are inside the rect;
// zones/highlights/room boxes hit on their center point; notes on their
// anchor. pointInRect is a geometry.js global.
function countItemsInRect(ann, pageIdx, x1, y1, x2, y2) {
let counterCount = 0, lineRunCount = 0, lengthRealSum = 0, ductRunCount = 0;
const inRect = (p) => pointInRect(p, x1, y1, x2, y2);
(ctx.getState().counters || []).forEach(c => {
(ann?.counterMarkers?.[c.id] || []).forEach(m => { if (inRect(m)) counterCount++; });
});
(ann?.quickLines || []).forEach(q => {
const start = { x: q.x1, y: q.y1 }, end = { x: q.x2, y: q.y2 };
if (inRect(start) && inRect(end)) { lineRunCount++; lengthRealSum += ctx.getLineRealWorldLengthFeet(q, pageIdx, false, ann); }
});
(ann?.polylines || []).forEach(poly => {
const pts = poly.points || [];
const start = pts[0], end = pts[pts.length - 1];
if (start && end && inRect(start) && inRect(end)) { lineRunCount++; lengthRealSum += ctx.getLineRealWorldLengthFeet(poly, pageIdx, true, ann); }
});
// D17 (J6-G): duct runs follow the line rule — both end vertices inside —
// so the Multiply Zone dialog can say "… 1 duct run" before Apply.
(ann?.ductRuns || []).forEach(run => {
const verts = run?.vertices || [];
const start = verts[0], end = verts[verts.length - 1];
if (verts.length >= 2 && inRect(start) && inRect(end)) ductRunCount++;
});
return { counterCount, lineRunCount, lengthRealSum, ductRunCount };
}
function collectItemsToDeleteInRect(ann, pageIdx, x1, y1, x2, y2) {
const inRect = (p) => pointInRect(p, x1, y1, x2, y2);
const result = {
counterCount: 0, lineRunCount: 0, lengthRealSum: 0,
highlightCount: 0, noteCount: 0, multiplyZoneCount: 0, scaleZoneCount: 0, roomBoxCount: 0,
ductRunCount: 0, ductFittingCount: 0,
counters: [], quickLines: [], polylines: [],
highlights: [], notes: [], multiplyZones: [], scaleZones: [], roomBoxes: [],
ductRuns: [], ductFittings: []
};
(ctx.getState().counters || []).forEach(c => {
(ann?.counterMarkers?.[c.id] || []).forEach(m => {
if (inRect(m)) {
result.counterCount++;
result.counters.push({ counterId: c.id, marker: m });
}
});
});
(ann?.quickLines || []).forEach((q, i) => {
const start = { x: q.x1, y: q.y1 }, end = { x: q.x2, y: q.y2 };
if (inRect(start) && inRect(end)) {
result.lineRunCount++;
result.lengthRealSum += ctx.getLineRealWorldLengthFeet(q, pageIdx, false, ann);
result.quickLines.push({ index: i, line: q });
}
});
(ann?.polylines || []).forEach((poly, i) => {
const pts = poly.points || [];
const start = pts[0], end = pts[pts.length - 1];
if (start && end && inRect(start) && inRect(end)) {
result.lineRunCount++;
result.lengthRealSum += ctx.getLineRealWorldLengthFeet(poly, pageIdx, true, ann);
result.polylines.push({ index: i, poly });
}
});
(ann?.highlights || []).forEach((h, i) => {
const cx = (h.x1 + h.x2) / 2, cy = (h.y1 + h.y2) / 2;
if (inRect({ x: cx, y: cy })) {
result.highlightCount++;
result.highlights.push({ index: i });
}
});
(ann?.notes || []).forEach((n, i) => {
if (inRect({ x: n.x, y: n.y })) {
result.noteCount++;
result.notes.push({ index: i });
}
});
(ann?.multiplyZones || []).forEach((z, i) => {
const cx = (z.x1 + z.x2) / 2, cy = (z.y1 + z.y2) / 2;
if (inRect({ x: cx, y: cy })) {
result.multiplyZoneCount++;
result.multiplyZones.push({ index: i });
}
});
(ann?.scaleZones || []).forEach((z, i) => {
const cx = (z.x1 + z.x2) / 2, cy = (z.y1 + z.y2) / 2;
if (inRect({ x: cx, y: cy })) {
result.scaleZoneCount++;
result.scaleZones.push({ index: i });
}
});
(ann?.roomBoxes || []).forEach((b, i) => {
const cx = (b.x1 + b.x2) / 2, cy = (b.y1 + b.y2) / 2;
if (inRect({ x: cx, y: cy })) {
result.roomBoxCount++;
result.roomBoxes.push({ index: i });
}
});
// D19 (J6-H): duct runs follow the LINE rule — both end vertices inside —
// the same test D17 gave the Multiply Zone preview, so the two area tools
// agree about what a rectangle "holds". A run's fittings go with it
// wherever they sit: a fitting cannot outlive the run it is anchored to,
// and leaving one behind would strand it in the schedule.
const doomedRunIds = new Set();
(ann?.ductRuns || []).forEach((run, i) => {
const verts = run?.vertices || [];
const start = verts[0], end = verts[verts.length - 1];
if (verts.length >= 2 && inRect(start) && inRect(end)) {
result.ductRunCount++;
result.ductRuns.push({ index: i, run });
if (run.id != null) doomedRunIds.add(run.id);
}
});
if (doomedRunIds.size) {
(ann?.ductFittings || []).forEach((f, i) => {
if (f && doomedRunIds.has(f.runId)) {
result.ductFittingCount++;
result.ductFittings.push({ index: i });
}
});
}
return result;
}
// The splice core of Delete Area. Descending-index order is load-bearing:
// ascending splices would shift the later indices and delete wrong items.
// The UI choreography (undo snapshot, dirty, re-render) stays app-side in
// the performDeleteZone wrapper.
function deleteCollectedItems(ann, collected) {
(collected.counters || []).forEach(({ counterId, marker }) => {
const arr = ann?.counterMarkers?.[counterId];
if (arr) {
const idx = arr.indexOf(marker);
if (idx >= 0) arr.splice(idx, 1);
}
});
(collected.multiplyZones || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.multiplyZones || []).splice(index, 1);
});
(collected.scaleZones || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.scaleZones || []).splice(index, 1);
});
(collected.roomBoxes || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.roomBoxes || []).splice(index, 1);
});
(collected.polylines || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.polylines || []).splice(index, 1);
});
(collected.quickLines || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.quickLines || []).splice(index, 1);
});
(collected.highlights || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.highlights || []).splice(index, 1);
});
(collected.notes || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.notes || []).splice(index, 1);
});
// D19 (J6-H): fittings first, then the runs they hang off — each list is
// spliced descending within itself, so the order between them is cosmetic,
// but it reads the way the deletion actually cascades.
(collected.ductFittings || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.ductFittings || []).splice(index, 1);
});
(collected.ductRuns || []).slice().sort((a, b) => b.index - a.index).forEach(({ index }) => {
(ann?.ductRuns || []).splice(index, 1);
});
}
// --- Page-rotation math (rotatePoint90CW is a geometry.js global) ---------
function rotateAnnotations(page, w, h) {
const r = (pt) => rotatePoint90CW(pt, w, h);
const rotateAnn = (ann) => {
if (ann.counterMarkers) {
const next = {};
for (const [cid, arr] of Object.entries(ann.counterMarkers)) {
next[cid] = (arr || []).map(m => ({ ...m, ...r({ x: m.x, y: m.y }) }));
}
ann.counterMarkers = next;
}
(ann.quickLines || []).forEach(q => {
const a = r({ x: q.x1, y: q.y1 }), b = r({ x: q.x2, y: q.y2 });
q.x1 = a.x; q.y1 = a.y; q.x2 = b.x; q.y2 = b.y;
});
(ann.polylines || []).forEach(poly => {
if (poly.points) poly.points = poly.points.map(pt => r(pt));
});
(ann.highlights || []).forEach(h => {
const a = r({ x: h.x1, y: h.y1 }), b = r({ x: h.x2, y: h.y2 });
h.x1 = a.x; h.y1 = a.y; h.x2 = b.x; h.y2 = b.y;
});
(ann.multiplyZones || []).forEach(z => {
const a = r({ x: z.x1, y: z.y1 }), b = r({ x: z.x2, y: z.y2 });
z.x1 = a.x; z.y1 = a.y; z.x2 = b.x; z.y2 = b.y;
});
(ann.scaleZones || []).forEach(z => {
const a = r({ x: z.x1, y: z.y1 }), b = r({ x: z.x2, y: z.y2 });
z.x1 = a.x; z.y1 = a.y; z.x2 = b.x; z.y2 = b.y;
});
(ann.roomBoxes || []).forEach(bx => {
const a = r({ x: bx.x1, y: bx.y1 }), b = r({ x: bx.x2, y: bx.y2 });
bx.x1 = a.x; bx.y1 = a.y; bx.x2 = b.x; bx.y2 = b.y;
});
(ann.notes || []).forEach(n => {
const p = r({ x: n.x, y: n.y });
n.x = p.x; n.y = p.y;
});
// Duct runs: vertices are plain PDF-space points; segments/sizeSteps ride
// vertex INDICES, so rotation never touches them. Fittings anchored by
// vertexIdx rotate implicitly with their run; free-placed ones by position.
(ann.ductRuns || []).forEach(run => {
if (run.vertices) run.vertices = run.vertices.map(pt => r(pt));
});
(ann.ductFittings || []).forEach(f => {
if (f.position) f.position = r(f.position);
});
// A ghost's src is annotation-shaped (counterMarkers / quickLines /
// polylines in absolute PDF-space), so it rotates through this same
// walker — that shape choice is why ghosts need no rotation code of
// their own. Nested ghosts can't exist, so the recursion is one deep.
(ann.ghosts || []).forEach(g => { if (g && g.src) rotateAnn(g.src); });
if (ann.legend && typeof ann.legend === 'object') {
const p = r({ x: ann.legend.x, y: ann.legend.y });
ann.legend.x = p.x; ann.legend.y = p.y;
}
};
const canvases = getPageCanvases(page);
if (canvases.length) canvases.forEach(c => { if (c.annotations) rotateAnn(c.annotations); });
else rotateAnn(getActiveAnnotations(page));
}
function applyRotationDeltaToAnnotations(page, deltaDegrees) {
if (!page?.pdfPage || deltaDegrees % 90 !== 0) return;
const steps = Math.round((((deltaDegrees % 360) + 360) % 360) / 90);
if (steps === 0) return;
let rot = page.rotation ?? 0;
for (let i = 0; i < steps; i++) {
const vp = page.pdfPage.getViewport({ scale: 1, rotation: rot });
rotateAnnotations(page, vp.width, vp.height);
rot = (rot + 90) % 360;
}
}
// --- Ghosts (reference copies) --------------------------------------------
// A ghost is a translucent COPY of a batch of marks, kept as scaffolding for
// repeating a "typical" layout: it is drawn on the plan, dragged around, and
// never tallied. It is a DISTINCT annotation kind, not real marks carrying an
// isGhost flag — that way no totals surface (footer, sidebar, Summary, legend,
// report, Copy to /Tooling, Copy Summary, the PDF legend) can accidentally
// count one. Nothing reads ann.ghosts except the ghost code and the renderer.
//
// Shape: { id, label, showCounters, showLines, src }, where src is
// annotation-shaped ({ counterMarkers, quickLines, polylines }) and holds
// ABSOLUTE PDF-space coordinates — no offset vector. Moving a ghost rewrites
// its points; that keeps page rotation (rotateAnnotations) and bounds honest
// without a second coordinate convention to reason about.
function captureGhostFromRect(ann, pageIdx, x1, y1, x2, y2, label) {
// Same hit semantics as Delete Area / Multiply Zone: counters on their
// point, lines only when BOTH endpoints are inside the box.
const collected = collectItemsToDeleteInRect(ann, pageIdx, x1, y1, x2, y2);
if (!collected.counterCount && !collected.lineRunCount) return null;
const src = { counterMarkers: {}, quickLines: [], polylines: [] };
(collected.counters || []).forEach(({ counterId, marker }) => {
if (!src.counterMarkers[counterId]) src.counterMarkers[counterId] = [];
src.counterMarkers[counterId].push({ ...marker, id: ctx.uid() });
});
(collected.quickLines || []).forEach(({ line }) => {
src.quickLines.push({ ...JSON.parse(JSON.stringify(line)), id: ctx.uid() });