-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.js
More file actions
1743 lines (1555 loc) · 51.5 KB
/
Copy pathreport.js
File metadata and controls
1743 lines (1555 loc) · 51.5 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
import {
anyRecordHasVibrationAlert,
buildEventSlug,
buildReportFilename,
formatCharge,
formatDateBr,
formatDecimal,
formatDistance,
formatFrequency,
formatMicrophoneFrequency,
formatMmS,
formatPspl,
getDateRange,
getPrimaryClient,
recordOverallCompliant,
CHANNEL_ORDER,
} from "./utils.js";
import "./vendor/jspdf/jspdf.umd.min.js";
const PAGE_W_MM = 210;
const PAGE_H_MM = 297;
const CONTENT_X_MM = 10;
const CONTENT_W_MM = 190;
const COVER_TITLE_TOP_MM = 29;
const COVER_SUMMARY_HEADING_TOP_MM = 62;
const COVER_SCOPE_TOP_MM = 70;
const COVER_CONCLUSION_TOP_MM = 97;
const COVER_CHARTS_TOP_MM = 123;
const COVER_RECORDS_HEADING_TOP_MM = 194;
const COVER_ROW_BASE_TOP_MM = 204.7;
const APPENDIX_TITLE_TOP_MM = 25;
const APPENDIX_META_ONE_TOP_MM = 30;
const APPENDIX_META_TWO_TOP_MM = 34;
const APPENDIX_HEADER_X_MM = 43;
const APPENDIX_ROW_BASE_TOP_MM = 45;
const ROW_HEIGHT_MM = 19.8;
const ROW_GAP_MM = 3.9;
const ROW_STEP_MM = ROW_HEIGHT_MM + ROW_GAP_MM;
const APPENDIX_ROWS_PER_PAGE = Math.max(1, Math.floor((((PAGE_H_MM - 47) - 12) + ROW_GAP_MM) / ROW_STEP_MM));
const CHART_SVG_W = 360;
const CHART_SVG_H = 210;
const COLORS = {
red: "#E5231B",
redSoft: "#F5D0CD",
dark: "#434C5B",
green: "#7BC51C",
greenSoft: "#DCF3C4",
light: "#F1F1F1",
navy: "#1C2240",
text: "#18202A",
muted: "#667487",
line: "#C9D1DA",
softPaper: "#F8FAFC",
chartGrid: "#D7D7D7",
chartAxis: "#2E2E2E",
chartWhite: "#FFFFFF",
chartBlue: "#2E86AB",
chartBrown: "#434C5B",
chartGuide: "#E5231B",
};
const REPORT_STYLES = `
.report-render-root {
position: fixed;
left: -12000px;
top: 0;
width: ${PAGE_W_MM}mm;
pointer-events: none;
user-select: none;
}
.report-page,
.report-page * {
box-sizing: border-box;
}
.report-page {
position: relative;
width: ${PAGE_W_MM}mm;
height: ${PAGE_H_MM}mm;
overflow: hidden;
background: ${COLORS.light};
color: ${COLORS.text};
font-family: Helvetica, Arial, sans-serif;
font-size: 2.42mm;
line-height: 1.16;
text-rendering: geometricPrecision;
letter-spacing: 0.001em;
word-spacing: 0.001em;
}
.report-topline {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 1.8mm;
background: ${COLORS.red};
}
.report-logo {
position: absolute;
left: 8mm;
top: 18mm;
width: 30mm;
height: 9.7mm;
object-fit: contain;
z-index: 2;
}
.report-corner {
position: absolute;
width: 16mm;
height: 16mm;
opacity: 0.95;
}
.report-corner--topright {
right: 7mm;
top: 8mm;
}
.report-corner--bottomleft {
left: 6mm;
bottom: 6mm;
}
.report-dna-badge {
position: absolute;
right: 10mm;
bottom: 10.8mm;
width: 40mm;
height: 8.5mm;
border-radius: 2.5mm;
background: ${COLORS.navy};
border: 0.3mm solid #667487;
display: flex;
align-items: center;
justify-content: center;
gap: 2.8mm;
color: #fff;
font-size: 2.9mm;
font-weight: 700;
letter-spacing: 0.03em;
}
.report-dna-badge__dna {
color: #FDB515;
}
.report-dna-badge__dot {
color: ${COLORS.green};
}
.report-title-card {
position: absolute;
left: ${CONTENT_X_MM}mm;
top: ${COVER_TITLE_TOP_MM}mm;
width: ${CONTENT_W_MM}mm;
height: 30.5mm;
background: #fff;
border-radius: 4px;
box-shadow: 1.3mm 1mm 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
z-index: 1;
}
.report-title-strip {
height: 4mm;
background: #C8C8C8;
}
.report-title-body {
padding: 6.4mm 7mm 2.7mm;
}
.report-title-text {
margin: 0;
color: ${COLORS.red};
font-size: 4.35mm;
font-weight: 700;
line-height: 1;
}
.report-title-client {
margin-top: 2.8mm;
color: #667487;
font-size: 3.25mm;
font-weight: 700;
line-height: 1.03;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.report-title-footer {
margin-top: 2.1mm;
color: #000;
font-size: 2.3mm;
font-weight: 700;
line-height: 1;
}
.report-heading {
position: absolute;
left: ${CONTENT_X_MM}mm;
margin: 0;
color: #000;
font-size: 5.15mm;
font-weight: 400;
line-height: 1;
}
.report-heading--summary {
top: ${COVER_SUMMARY_HEADING_TOP_MM}mm;
}
.report-heading--records {
top: ${COVER_RECORDS_HEADING_TOP_MM}mm;
}
.report-box {
position: absolute;
left: ${CONTENT_X_MM}mm;
width: ${CONTENT_W_MM}mm;
background: #fff;
border-radius: 4.5px;
box-shadow: 1.3mm 1mm 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
}
.report-box-strip {
height: 6.9mm;
}
.report-box-title {
position: absolute;
left: 4mm;
top: 1.55mm;
color: #fff;
font-size: 3.3mm;
font-weight: 700;
}
.report-box-body {
position: absolute;
left: 0;
right: 0;
top: 6.9mm;
bottom: 0;
padding: 3mm 4mm 2.6mm;
color: ${COLORS.text};
font-size: 2.56mm;
line-height: 1.12;
overflow: hidden;
}
.report-box-line {
margin: 0 0 1.5mm 0;
}
.report-box-line--success {
color: ${COLORS.green};
}
.report-box-line--warning {
color: ${COLORS.red};
}
.report-conclusion-table {
width: 100%;
border-collapse: collapse;
font-size: 1.96mm;
line-height: 1.1;
}
.report-conclusion-table td {
border: 0.12mm solid ${COLORS.line};
padding: 0.82mm 0.95mm;
vertical-align: middle;
}
.report-conclusion-table td:first-child {
width: 30mm;
background: #EAF5D7;
font-weight: 700;
}
.report-chart-row {
position: absolute;
left: ${CONTENT_X_MM}mm;
top: ${COVER_CHARTS_TOP_MM}mm;
width: ${CONTENT_W_MM}mm;
height: 62mm;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5.5mm;
}
.report-chart-panel {
position: relative;
background: #fff;
border-radius: 4.5px;
box-shadow: 1.3mm 1mm 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
}
.report-chart-strip {
height: 6.9mm;
background: ${COLORS.green};
}
.report-chart-title {
position: absolute;
left: 4mm;
top: 1.55mm;
color: #fff;
font-size: 3.15mm;
font-weight: 700;
}
.report-chart-body {
position: absolute;
left: 0;
right: 0;
top: 6.9mm;
bottom: 0;
padding: 1.35mm 1.45mm 1.35mm;
}
.report-chart-svg {
display: block;
width: 100%;
height: 100%;
}
.report-record-list {
position: absolute;
left: ${CONTENT_X_MM}mm;
top: 0;
width: ${CONTENT_W_MM}mm;
height: ${PAGE_H_MM}mm;
}
.report-record-card {
position: absolute;
left: 0;
width: ${CONTENT_W_MM}mm;
height: ${ROW_HEIGHT_MM}mm;
background: #fff;
border-radius: 4.5px;
box-shadow: 1.3mm 1mm 0 rgba(0, 0, 0, 0.08);
overflow: hidden;
}
.report-record-header {
height: 5.55mm;
background: ${COLORS.dark};
color: #fff;
padding: 0 4mm;
display: flex;
align-items: center;
font-size: 2.85mm;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.report-record-body {
position: relative;
height: 13.95mm;
padding: 1.35mm 4mm 0;
}
.report-record-table {
width: calc(100% - 47mm);
border-collapse: collapse;
table-layout: fixed;
font-size: 1.76mm;
color: ${COLORS.text};
}
.report-record-table td {
border: 0.12mm solid ${COLORS.line};
padding: 0.58mm 0.85mm;
vertical-align: middle;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.report-record-table td:nth-child(odd) {
background: #EAF5D7;
font-weight: 700;
}
.report-record-badge {
position: absolute;
right: 4mm;
top: 50%;
transform: translateY(-50%);
width: 33.5mm;
height: 6mm;
border-radius: 3mm;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 2.2mm;
font-weight: 700;
letter-spacing: 0.02em;
}
.report-footer-note {
position: absolute;
left: ${CONTENT_X_MM}mm;
top: 285mm;
color: ${COLORS.dark};
font-size: 2.24mm;
}
.report-appendix-title {
position: absolute;
left: ${APPENDIX_HEADER_X_MM}mm;
top: ${APPENDIX_TITLE_TOP_MM}mm;
margin: 0;
color: ${COLORS.red};
font-size: 4.18mm;
font-weight: 700;
}
.report-appendix-meta {
position: absolute;
left: ${APPENDIX_HEADER_X_MM}mm;
margin: 0;
color: ${COLORS.muted};
font-size: 2.58mm;
}
.report-appendix-meta--one {
top: ${APPENDIX_META_ONE_TOP_MM}mm;
}
.report-appendix-meta--two {
top: ${APPENDIX_META_TWO_TOP_MM}mm;
}
`;
function jsPdf() {
return globalThis.jspdf?.jsPDF ?? globalThis.jsPDF;
}
function ensureHtml2Canvas() {
const fn = globalThis.html2canvas;
if (typeof fn !== "function") {
throw new Error("O html2canvas nao foi carregado.");
}
return fn;
}
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\"/g, """)
.replace(/'/g, "'");
}
function svgAttr(value) {
return escapeHtml(value).replace(/\"/g, """);
}
function svgAttrs(attrs = {}) {
return Object.entries(attrs)
.filter(([, value]) => value != null && value !== false)
.map(([name, value]) => `${name}="${svgAttr(value)}"`)
.join(" ");
}
function svgTag(name, attrs = {}, content = "") {
const attrText = svgAttrs(attrs);
if (!content) {
return `<${name}${attrText ? ` ${attrText}` : ""} />`;
}
return `<${name}${attrText ? ` ${attrText}` : ""}>${content}</${name}>`;
}
function waitForFrame() {
return new Promise((resolve) => {
const raf = globalThis.requestAnimationFrame ?? ((callback) => globalThis.setTimeout(callback, 16));
raf(() => resolve());
});
}
async function waitForImages(root) {
const images = Array.from(root.querySelectorAll("img"));
if (!images.length) {
return;
}
await Promise.all(images.map(async (img) => {
if (img.complete) {
return;
}
if (typeof img.decode === "function") {
try {
await img.decode();
return;
} catch {
return;
}
}
await new Promise((resolve) => {
img.addEventListener("load", resolve, { once: true });
img.addEventListener("error", resolve, { once: true });
});
}));
}
function getCaptureScale(config) {
const scale = Number(config?.report?.png_scale);
if (Number.isFinite(scale) && scale > 0) {
return scale;
}
const fallback = Number(globalThis.devicePixelRatio ?? 1);
return Number.isFinite(fallback) && fallback > 0 ? fallback : 1;
}
function formatGeneratedAt(date) {
const day = String(date.getDate()).padStart(2, "0");
const month = String(date.getMonth() + 1).padStart(2, "0");
const year = String(date.getFullYear());
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
return `${day}/${month}/${year} ${hours}:${minutes}`;
}
function chunkRecords(records, chunkSize) {
const output = [];
for (let index = 0; index < records.length; index += chunkSize) {
output.push(records.slice(index, index + chunkSize));
}
return output;
}
function overallBatchCompliant(records) {
const states = records.map((record) => recordOverallCompliant(record)).filter((state) => state != null);
return Boolean(states.length && states.every(Boolean));
}
function pickMaxRecord(records, selector) {
let bestRecord = null;
let bestValue = Number.NEGATIVE_INFINITY;
for (const record of records) {
const value = selector(record);
if (value == null) {
continue;
}
if (bestRecord == null || value > bestValue) {
bestRecord = record;
bestValue = value;
}
}
return bestRecord;
}
function getMaxChannel(record) {
let bestChannel = null;
let bestValue = Number.NEGATIVE_INFINITY;
for (const axis of CHANNEL_ORDER) {
const channel = record?.channels?.[axis];
const value = channel?.ppv_mm_s;
if (value == null) {
continue;
}
if (bestChannel == null || value > bestValue) {
bestChannel = channel;
bestValue = value;
}
}
return bestChannel;
}
function ellipsis(text, maxChars) {
if (text.length <= maxChars) {
return text;
}
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
function titleCase(text) {
return text
.toLocaleLowerCase("pt-BR")
.replace(/(^|[\s-])(\p{L})/gu, (_, prefix, letter) => `${prefix}${letter.toLocaleUpperCase("pt-BR")}`);
}
function chartLabel(text) {
const source = String(text ?? "").trim();
if (!source) {
return "N/D";
}
const label = titleCase(source)
.replace(/Comunidade De /g, "Com. ")
.replace(/Barragem De /g, "Barr. ");
return ellipsis(label, 18);
}
function chartLabelForRecord(record) {
if (record?.sismogram_model === "geosonics" && record.serial_number) {
return ellipsis(`Serial No: ${record.serial_number}`, 24);
}
return chartLabel(record?.location);
}
function frequencyValue(value) {
if (value == null) {
return 1;
}
if (typeof value === "string") {
const text = value.trim();
if (!text) {
return 1;
}
if (text.startsWith(">")) {
return 100;
}
const parsed = Number(text.replace(",", "."));
return Number.isFinite(parsed) ? parsed : 1;
}
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 1;
}
function ppvForward(values) {
const scalarInput = Number.isFinite(Number(values));
const array = Array.isArray(values) ? values.map(Number) : [Number(values)];
const floor = 0.05;
const breakPoint = 0.1;
const lowBand = 0.5;
const offset = lowBand - breakPoint;
const transformed = array.map((value) => {
const safe = Math.max(value, floor);
if (value <= breakPoint) {
return lowBand * (Math.log(safe / floor) / Math.log(breakPoint / floor));
}
return value + offset;
});
return scalarInput ? transformed[0] : transformed;
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function measureLabelBox(lines) {
const widestLine = lines.reduce((max, line) => Math.max(max, line.length), 0);
return {
boxWidth: Math.max(18, Math.min(44, (widestLine * 2.35) + 5.2)),
boxHeight: lines.length > 1 ? 11.2 : 8.5,
};
}
function rectFromCenter(centerX, centerY, boxWidth, boxHeight) {
return {
left: centerX - (boxWidth / 2),
top: centerY - (boxHeight / 2),
right: centerX + (boxWidth / 2),
bottom: centerY + (boxHeight / 2),
};
}
function rectsOverlap(left, right, padding = 0.008) {
return !(
(left.right + padding) <= right.left
|| (left.left - padding) >= right.right
|| (left.bottom + padding) <= right.top
|| (left.top - padding) >= right.bottom
);
}
function rectIntersectionArea(left, right) {
if (!rectsOverlap(left, right, 0)) {
return 0;
}
const width = Math.max(0, Math.min(left.right, right.right) - Math.max(left.left, right.left));
const height = Math.max(0, Math.min(left.bottom, right.bottom) - Math.max(left.top, right.top));
return width * height;
}
function rectDistance(left, right) {
const horizontalGap = Math.max(left.left - right.right, right.left - left.right, 0);
const verticalGap = Math.max(left.top - right.bottom, right.top - left.bottom, 0);
return Math.hypot(horizontalGap, verticalGap);
}
function distancePointToRect(pointX, pointY, rect) {
const dx = Math.max(rect.left - pointX, 0, pointX - rect.right);
const dy = Math.max(rect.top - pointY, 0, pointY - rect.bottom);
return Math.hypot(dx, dy);
}
function connectorPointToRect(pointX, pointY, rect) {
const centerX = (rect.left + rect.right) / 2;
const centerY = (rect.top + rect.bottom) / 2;
const vx = pointX - centerX;
const vy = pointY - centerY;
const halfWidth = Math.max((rect.right - rect.left) / 2, 0.0001);
const halfHeight = Math.max((rect.bottom - rect.top) / 2, 0.0001);
const scale = 1 / Math.max(Math.abs(vx) / halfWidth, Math.abs(vy) / halfHeight, 0.0001);
return {
x: centerX + (vx * scale),
y: centerY + (vy * scale),
};
}
function buildLabelCandidates(pointX, pointY, boxWidthFrac, boxHeightFrac, index) {
const horizontalBias = pointX <= 0.5 ? 1 : -1;
const verticalBias = pointY <= 0.5 ? 1 : -1;
const directions = [
{ dx: horizontalBias, dy: verticalBias },
{ dx: horizontalBias, dy: 0 },
{ dx: 0, dy: verticalBias },
{ dx: horizontalBias, dy: -verticalBias },
{ dx: -horizontalBias, dy: verticalBias },
{ dx: -horizontalBias, dy: 0 },
{ dx: 0, dy: -verticalBias },
{ dx: -horizontalBias, dy: -verticalBias },
];
const tiers = [1, 1.4, 2.0];
const offsetXStep = Math.max(0.007, boxWidthFrac * 0.05);
const offsetYStep = Math.max(0.007, boxHeightFrac * 0.05);
const candidates = [];
tiers.forEach((tier) => {
const gapX = Math.max(0.022, boxWidthFrac * 0.24) * tier;
const gapY = Math.max(0.022, boxHeightFrac * 0.36) * tier;
directions.forEach((direction) => {
const offsetX = direction.dx === 0
? (((index % 2) === 0 ? -1 : 1) * offsetXStep * tier)
: direction.dx * ((boxWidthFrac / 2) + gapX);
const offsetY = direction.dy === 0
? ((((index % 3) - 1) * offsetYStep) * tier)
: direction.dy * ((boxHeightFrac / 2) + gapY);
candidates.push({
x: pointX + offsetX,
y: pointY + offsetY,
});
});
});
return candidates;
}
function placeChartLabels(labelSpecs) {
const ordered = [...labelSpecs].sort((left, right) => (
(right.boxWidthFrac * right.boxHeightFrac) - (left.boxWidthFrac * left.boxHeightFrac)
|| left.index - right.index
));
const placed = [];
ordered.forEach((spec) => {
const candidates = buildLabelCandidates(spec.pointXFrac, spec.pointYFrac, spec.boxWidthFrac, spec.boxHeightFrac, spec.index);
const minCenterX = (spec.boxWidthFrac / 2) + 0.015;
const maxCenterX = 1 - minCenterX;
const minCenterY = (spec.boxHeightFrac / 2) + 0.015;
const maxCenterY = 1 - minCenterY;
let best = null;
let bestScore = Number.POSITIVE_INFINITY;
candidates.forEach((candidate) => {
const centerX = clamp(candidate.x, minCenterX, maxCenterX);
const centerY = clamp(candidate.y, minCenterY, maxCenterY);
const rect = rectFromCenter(centerX, centerY, spec.boxWidthFrac, spec.boxHeightFrac);
const pointDistance = distancePointToRect(spec.pointXFrac, spec.pointYFrac, rect);
if (pointDistance < spec.minPointGap) {
return;
}
const overlapArea = placed.reduce((sum, item) => sum + rectIntersectionArea(rect, item.rect), 0);
const overlapCount = placed.reduce((count, item) => count + (rectsOverlap(rect, item.rect) ? 1 : 0), 0);
const desiredGap = Math.max(0.034, spec.boxHeightFrac * 0.78);
const proximityPenalty = placed.reduce((sum, item) => {
const gap = rectDistance(rect, item.rect);
return sum + (Math.max(0, desiredGap - gap) * 7600);
}, 0);
const distance = Math.hypot(centerX - spec.pointXFrac, centerY - spec.pointYFrac);
const edgeDistance = Math.min(centerX - minCenterX, maxCenterX - centerX, centerY - minCenterY, maxCenterY - centerY);
const edgePenalty = Math.max(0, 0.045 - edgeDistance) * 12000;
const axisPenalty = (centerX < 0.08 || centerX > 0.92 ? 250 : 0) + (centerY < 0.08 || centerY > 0.92 ? 250 : 0);
const score = (overlapCount * 2600) + (overlapArea * 11000) + proximityPenalty + (distance * 140) + edgePenalty + axisPenalty;
if (score < bestScore) {
best = { centerX, centerY, rect };
bestScore = score;
}
});
if (!best) {
const fallbackX = clamp(spec.pointXFrac + (spec.pointXFrac < 0.5 ? 0.11 : -0.11), minCenterX, maxCenterX);
const fallbackY = clamp(spec.pointYFrac + (spec.pointYFrac < 0.5 ? 0.1 : -0.1), minCenterY, maxCenterY);
best = {
centerX: fallbackX,
centerY: fallbackY,
rect: rectFromCenter(fallbackX, fallbackY, spec.boxWidthFrac, spec.boxHeightFrac),
};
}
const targetGap = Math.max(0.015, spec.boxHeightFrac * 0.26);
let resolvedRect = best.rect;
let resolvedCenterX = best.centerX;
let resolvedCenterY = best.centerY;
for (let iteration = 0; iteration < 8; iteration += 1) {
const conflicts = placed.filter((item) => rectDistance(resolvedRect, item.rect) < targetGap);
if (!conflicts.length) {
break;
}
const conflictCenterX = conflicts.reduce((sum, item) => sum + ((item.rect.left + item.rect.right) / 2), 0) / conflicts.length;
const conflictCenterY = conflicts.reduce((sum, item) => sum + ((item.rect.top + item.rect.bottom) / 2), 0) / conflicts.length;
const moveX = resolvedCenterX >= conflictCenterX ? 0.012 : -0.012;
const moveY = resolvedCenterY >= conflictCenterY ? 0.012 : -0.012;
resolvedCenterX = clamp(resolvedCenterX + moveX, minCenterX, maxCenterX);
resolvedCenterY = clamp(resolvedCenterY + moveY, minCenterY, maxCenterY);
resolvedRect = rectFromCenter(resolvedCenterX, resolvedCenterY, spec.boxWidthFrac, spec.boxHeightFrac);
}
const connector = connectorPointToRect(spec.pointXFrac, spec.pointYFrac, resolvedRect);
placed.push({
...spec,
xFrac: resolvedCenterX,
yFrac: resolvedCenterY,
connectorXFrac: connector.x,
connectorYFrac: connector.y,
rect: resolvedRect,
});
});
return placed.sort((left, right) => left.index - right.index);
}
function psplLabelPositions(points, axisMax, layout = {}) {
if (!points.length) {
return [];
}
const plotWidth = layout.plotWidth ?? 320;
const plotHeight = layout.plotHeight ?? 168;
const sortedPoints = [...points].sort((left, right) => left.distance - right.distance);
const safeAxisMax = Math.max(axisMax, 1);
const labelSpecs = sortedPoints.map((point, index) => {
const lines = [point.label, `${formatPspl(point.pspl)} dB`];
const { boxWidth, boxHeight } = measureLabelBox(lines);
return {
index,
pointXFrac: clamp(point.distance / safeAxisMax, 0.06, 0.94),
pointYFrac: clamp(1 - (point.pspl / 160), 0.08, 0.92),
boxWidth,
boxHeight,
boxWidthFrac: boxWidth / Math.max(plotWidth, 1),
boxHeightFrac: boxHeight / Math.max(plotHeight, 1),
lines,
color: point.color,
label: point.label,
pspl: point.pspl,
distance: point.distance,
minPointGap: Math.max(0.012, 4.2 / Math.max(Math.min(plotWidth, plotHeight), 1)),
};
});
return placeChartLabels(labelSpecs);
}
function ppvLabelPositions(points, layout = {}) {
if (!points.length) {
return [];
}
const plotWidth = layout.plotWidth ?? 320;
const plotHeight = layout.plotHeight ?? 168;
const sortedPoints = [...points].sort((left, right) => left.freq - right.freq);
const logMin = Math.log10(1);
const logMax = Math.log10(1000);
const yMax = ppvForward(60);
const labelSpecs = sortedPoints.map((point, index) => {
const lines = [point.label];
const { boxWidth, boxHeight } = measureLabelBox(lines);
return {
index,
pointXFrac: clamp((Math.log10(Math.max(point.freq, 1)) - logMin) / (logMax - logMin), 0.06, 0.94),
pointYFrac: clamp(1 - (ppvForward(point.ppv) / yMax), 0.08, 0.92),
boxWidth,
boxHeight,
boxWidthFrac: boxWidth / Math.max(plotWidth, 1),
boxHeightFrac: boxHeight / Math.max(plotHeight, 1),
lines,
color: point.color,
label: point.label,
freq: point.freq,
ppv: point.ppv,
minPointGap: Math.max(0.012, 4.2 / Math.max(Math.min(plotWidth, plotHeight), 1)),
};
});
return placeChartLabels(labelSpecs);
}
function hexagonPoints(centerX, centerY, radius) {
const points = [];
for (let index = 0; index < 6; index += 1) {
const angle = (Math.PI / 180) * (60 * index - 30);
const x = centerX + (radius * Math.cos(angle));
const y = centerY + (radius * Math.sin(angle));
points.push(`${x.toFixed(2)},${y.toFixed(2)}`);
}
return points.join(" ");
}
function buildCornerMotifSvg() {
return `
<svg class="report-corner" viewBox="0 0 20 20" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
<g fill="none" stroke="#2A2F46" stroke-width="0.65" opacity="0.95">
<polygon points="${hexagonPoints(10, 10, 5.4)}"></polygon>
<polygon points="${hexagonPoints(10, 10, 6.35)}" stroke-width="0.5"></polygon>
</g>
</svg>
`;
}
function svgText(x, y, text, attrs = {}) {
return svgTag("text", {
x,
y,
"text-rendering": "geometricPrecision",
"letter-spacing": "0.001em",
"word-spacing": "0.001em",
...attrs
}, escapeHtml(text));
}
function svgLine(x1, y1, x2, y2, attrs = {}) {
return svgTag("line", { x1, y1, x2, y2, ...attrs });
}
function svgPath(d, attrs = {}) {
return svgTag("path", { d, ...attrs });
}
function svgRect(x, y, width, height, attrs = {}) {
return svgTag("rect", { x, y, width, height, ...attrs });
}
function svgCircle(cx, cy, radius, attrs = {}) {
return svgTag("circle", { cx, cy, r: radius, ...attrs });
}
function svgPolygon(points, attrs = {}) {
return svgTag("polygon", { points, ...attrs });
}
function buildLabelBoxSvg(x, y, text, color, metrics = null) {
const lines = Array.isArray(text) ? text.map((line) => String(line)) : String(text).split(/\n/);
const { boxWidth, boxHeight } = metrics ?? measureLabelBox(lines);
const left = x - (boxWidth / 2);
const top = y - (boxHeight / 2);
const textLines = lines.map((line, index) => {
const lineOffset = lines.length === 1 ? 0 : (index === 0 ? -1.7 : 2.2);
return svgText(x, y + lineOffset, line, {
"text-anchor": "middle",
"dominant-baseline": "middle",
"font-size": lines.length > 1 ? 4.15 : 4.35,
fill: color,
"font-family": "Helvetica, Arial, sans-serif",
});
}).join("");
return `
${svgRect(left, top, boxWidth, boxHeight, {
rx: 2.4,
ry: 2.4,
fill: "rgba(255,255,255,0.98)",
stroke: color,
"stroke-width": 0.7,
})}
${textLines}
`;
}
function buildLabelConnectorSvg(pointX, pointY, connectorX, connectorY, color) {
const dx = connectorX - pointX;