This repository was archived by the owner on May 19, 2026. It is now read-only.
forked from layoutit/polycss
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolyDOM.test.ts
More file actions
1535 lines (1410 loc) · 52.3 KB
/
Copy pathpolyDOM.test.ts
File metadata and controls
1535 lines (1410 loc) · 52.3 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 { describe, it, expect, vi, afterEach } from "vitest";
import { renderPoly } from "./polyDOM";
import { renderPolygonsWithTextureAtlas, renderPolygonsWithTextureAtlasAsync } from "./textureAtlas";
import type { Polygon } from "@layoutit/polycss-core";
const FLAT_TRIANGLE: Polygon = {
vertices: [
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
],
color: "#ff0000",
};
const SECOND_FLAT_TRIANGLE: Polygon = {
vertices: [
[1, 0, 0],
[2, 0, 0],
[1, 1, 0],
],
color: "#ff0000",
};
const VERTICAL_QUAD: Polygon = {
vertices: [
[0, 0, 0],
[1, 0, 0],
[1, 0, 1],
[0, 0, 1],
],
color: "#00ff00",
};
const NON_RECT_QUAD: Polygon = {
vertices: [
[0, 0, 0],
[2, 0, 0],
[2, 1, 0],
[0, 2, 0],
],
color: "#00ffff",
};
const MODERATE_PROJECTIVE_QUAD: Polygon = {
vertices: [
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 6, 0],
],
color: "#00ffcc",
};
const UNSTABLE_PROJECTIVE_QUAD: Polygon = {
vertices: [
[0, 0, 0],
[0, 0.02, 0],
[0.2, 2, 0],
[0.2, 0, 0],
],
color: "#ff00ff",
};
const QUAD_CANONICAL_SIZE = 64;
const OFFAXIS_TRIANGLE: Polygon = {
vertices: [
[0, 0, 0],
[1, 1, 0],
[0, 1, 1],
],
color: "#0000ff",
};
function extractMatrix(el: HTMLElement): number[] {
const match = el.style.transform.match(/matrix3d\(([^)]+)\)/);
if (!match) return [];
return match[1].split(",").map(Number);
}
function transformMatrixPoint(matrix: number[], x: number, y: number, z = 0): [number, number, number] {
const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
return [
(matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w,
(matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w,
(matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]) / w,
];
}
function expectPointClose(actual: [number, number, number], expected: [number, number, number]): void {
expect(actual[0]).toBeCloseTo(expected[0], 2);
expect(actual[1]).toBeCloseTo(expected[1], 2);
expect(actual[2]).toBeCloseTo(expected[2], 2);
}
function roundedMatrix(values: number[], decimals = 3): number[] {
return values.map((value) => Number(value.toFixed(decimals)));
}
function computeExpectedPlan(
vertices: [number, number, number][],
tileSize = 50,
elev = tileSize,
): { matrix: number[]; canvasW: number; canvasH: number } {
const toCss = (v: [number, number, number]): [number, number, number] => [
v[1] * tileSize,
v[0] * tileSize,
v[2] * elev,
];
const pts = vertices.map(toCss);
const p0 = pts[0], p1 = pts[1], p2 = pts[2];
const e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
const e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
const L01 = Math.hypot(e1[0], e1[1], e1[2]);
const xAxis = [e1[0] / L01, e1[1] / L01, e1[2] / L01];
let nx = -(e1[1] * e2[2] - e1[2] * e2[1]);
let ny = -(e1[2] * e2[0] - e1[0] * e2[2]);
let nz = -(e1[0] * e2[1] - e1[1] * e2[0]);
const nLen = Math.hypot(nx, ny, nz);
nx /= nLen; ny /= nLen; nz /= nLen;
const yAxis = [
ny * xAxis[2] - nz * xAxis[1],
nz * xAxis[0] - nx * xAxis[2],
nx * xAxis[1] - ny * xAxis[0],
];
const local2D = pts.map((p): [number, number] => {
const dx = p[0] - p0[0], dy = p[1] - p0[1], dz = p[2] - p0[2];
return [
dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2],
dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2],
];
});
let xMin = Infinity, yMin = Infinity, xMax = -Infinity, yMax = -Infinity;
for (const [x, y] of local2D) {
if (x < xMin) xMin = x;
if (y < yMin) yMin = y;
if (x > xMax) xMax = x;
if (y > yMax) yMax = y;
}
const shiftX = -xMin;
const shiftY = -yMin;
const tx = p0[0] - shiftX * xAxis[0] - shiftY * yAxis[0];
const ty = p0[1] - shiftX * xAxis[1] - shiftY * yAxis[1];
const tz = p0[2] - shiftX * xAxis[2] - shiftY * yAxis[2];
return {
matrix: [
xAxis[0], xAxis[1], xAxis[2], 0,
yAxis[0], yAxis[1], yAxis[2], 0,
nx, ny, nz, 0,
tx, ty, tz, 1,
],
canvasW: Math.max(1, Math.ceil(xMax - xMin)),
canvasH: Math.max(1, Math.ceil(yMax - yMin)),
};
}
function computeExpectedMatrix(
vertices: [number, number, number][],
tileSize = 50,
elev = tileSize,
): number[] {
return computeExpectedPlan(vertices, tileSize, elev).matrix;
}
function computeExpectedQuadMatrix(
vertices: [number, number, number][],
tileSize = 50,
elev = tileSize,
): number[] {
const { matrix, canvasW, canvasH } = computeExpectedPlan(vertices, tileSize, elev);
return [
matrix[0] * canvasW / QUAD_CANONICAL_SIZE,
matrix[1] * canvasW / QUAD_CANONICAL_SIZE,
matrix[2] * canvasW / QUAD_CANONICAL_SIZE,
0,
matrix[4] * canvasH / QUAD_CANONICAL_SIZE,
matrix[5] * canvasH / QUAD_CANONICAL_SIZE,
matrix[6] * canvasH / QUAD_CANONICAL_SIZE,
0,
matrix[8], matrix[9], matrix[10], 0,
matrix[12], matrix[13], matrix[14], 1,
];
}
function expectColumnDirection(actual: number[], expected: number[], start: 0 | 4): void {
const actualLen = Math.hypot(actual[start], actual[start + 1], actual[start + 2]);
const expectedLen = Math.hypot(expected[start], expected[start + 1], expected[start + 2]);
expect(actualLen).toBeGreaterThan(0);
expect(expectedLen).toBeGreaterThan(0);
expect(actual[start] / actualLen).toBeCloseTo(expected[start] / expectedLen, 3);
expect(actual[start + 1] / actualLen).toBeCloseTo(expected[start + 1] / expectedLen, 3);
expect(actual[start + 2] / actualLen).toBeCloseTo(expected[start + 2] / expectedLen, 3);
}
function expectMatrixClose(actual: number[], expected: number[]): void {
expect(actual.length).toBe(expected.length);
for (let i = 0; i < expected.length; i++) expect(actual[i]).toBeCloseTo(expected[i], 6);
}
describe("renderPoly — solid polygons", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("returns a triangle u element for a solid color triangle", () => {
const result = renderPoly(FLAT_TRIANGLE)!;
expect(result).not.toBeNull();
expect(result.element.tagName.toLowerCase()).toBe("u");
expect(result.element.classList.contains("polycss-poly")).toBe(false);
expect(result.element.classList.contains("polycss-poly-atlas")).toBe(false);
expect(result.element.classList.contains("polycss-poly-solid")).toBe(false);
expect(result.element.classList.contains("polycss-poly-textured")).toBe(false);
result.dispose();
});
it("keeps class-owned constants out of inline styles", () => {
const result = renderPoly(FLAT_TRIANGLE)!;
expect(result.element.style.transform).toContain("matrix3d(");
expect(extractMatrix(result.element).length).toBe(16);
expect(result.element.style.position).toBe("");
expect(result.element.style.left).toBe("");
expect(result.element.style.top).toBe("");
expect(result.element.style.transformOrigin).toBe("");
expect(result.element.style.backfaceVisibility).toBe("");
expect(result.element.style.backgroundRepeat).toBe("");
result.dispose();
});
it("returns rect b elements and triangle u elements", () => {
const vertical = renderPoly(VERTICAL_QUAD)!;
const offAxis = renderPoly(OFFAXIS_TRIANGLE)!;
expect(vertical.element.tagName.toLowerCase()).toBe("b");
expect(vertical.element.className).toBe("");
expect(offAxis.element.tagName.toLowerCase()).toBe("u");
vertical.dispose();
offAxis.dispose();
});
it("dispose() is idempotent and does not throw", () => {
const result = renderPoly(FLAT_TRIANGLE)!;
expect(() => {
result.dispose();
result.dispose();
}).not.toThrow();
});
});
describe("renderPoly — degenerate inputs", () => {
it("returns null for zero-length first edge", () => {
const result = renderPoly({
vertices: [
[0, 0, 0],
[0, 0, 0],
[1, 0, 0],
],
});
expect(result).toBeNull();
});
it("returns null for collinear vertices", () => {
const result = renderPoly({
vertices: [
[0, 0, 0],
[1, 0, 0],
[2, 0, 0],
],
});
expect(result).toBeNull();
});
it("returns null for fewer than 3 vertices", () => {
const result = renderPoly({
vertices: [[0, 0, 0], [1, 0, 0]],
});
expect(result).toBeNull();
});
});
describe("renderPoly — matrix math parity", () => {
it("flat triangles use a finite border-triangle matrix", () => {
const result = renderPoly(FLAT_TRIANGLE)!;
const actual = extractMatrix(result.element);
expect(actual.length).toBe(16);
expect(actual.every(Number.isFinite)).toBe(true);
expect(result.element.style.width).toBe("");
expect(result.element.style.height).toBe("");
expect(result.element.style.borderBottomWidth).toBe("");
result.dispose();
});
it("vertical quad matrix3d values match expected", () => {
const result = renderPoly(VERTICAL_QUAD)!;
const actual = extractMatrix(result.element);
const expected = roundedMatrix(computeExpectedQuadMatrix(VERTICAL_QUAD.vertices as [number, number, number][]));
expect(actual.length).toBe(16);
for (let i = 0; i < 16; i++) expect(actual[i]).toBeCloseTo(expected[i], 6);
result.dispose();
});
it("off-axis triangles use a finite border-triangle matrix", () => {
const result = renderPoly(OFFAXIS_TRIANGLE)!;
const actual = extractMatrix(result.element);
expect(actual.length).toBe(16);
expect(actual.every(Number.isFinite)).toBe(true);
expect(result.element.style.borderBottomWidth).toBe("");
result.dispose();
});
it("custom tileSize and layerElevation scale translation", () => {
const poly: Polygon = {
vertices: [
[0, 0, 1],
[1, 0, 1],
[1, 0, 2],
[0, 0, 2],
],
};
const result = renderPoly(poly, { tileSize: 50, layerElevation: 25 })!;
const actual = extractMatrix(result.element);
const expected = roundedMatrix(computeExpectedQuadMatrix(poly.vertices as [number, number, number][], 50, 25));
for (let i = 0; i < 16; i++) expect(actual[i]).toBeCloseTo(expected[i], 6);
result.dispose();
});
});
describe("renderPolygonsWithTextureAtlas", () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it("uses canonical u geometry by default", () => {
const result = renderPolygonsWithTextureAtlas([FLAT_TRIANGLE]);
const element = result.rendered[0].element;
const styleText = element.getAttribute("style") ?? "";
expect(element.tagName.toLowerCase()).toBe("u");
expect(styleText).toMatch(/^transform:[^;]+;color:/);
expect(styleText).not.toContain("border-width:");
expect(styleText).not.toContain("background:linear-gradient");
expect(styleText).not.toMatch(/(^|;)width:/);
expect(styleText).not.toMatch(/(^|;)height:/);
result.dispose();
});
it("async renderer returns the same solid triangle element shape", async () => {
const result = await renderPolygonsWithTextureAtlasAsync([FLAT_TRIANGLE, SECOND_FLAT_TRIANGLE]);
const element = result.rendered[0].element;
expect(result.rendered).toHaveLength(2);
expect(element.tagName.toLowerCase()).toBe("u");
expect(element.style.transform).toContain("matrix3d(");
expect(result.solidPaintDefaults.paintColor).toMatch(/^#[0-9a-f]{6}$/);
result.dispose();
});
it("async renderer returns empty output when cancelled before planning", async () => {
const result = await renderPolygonsWithTextureAtlasAsync([FLAT_TRIANGLE], {}, () => true);
expect(result.rendered).toEqual([]);
result.dispose();
});
it("uses the whole polygon normal when the first three vertices are nearly collinear", () => {
const skinnyLeadingNgon: Polygon = {
vertices: [
[39.426, 9.805, 14.918],
[31.127, 10.135, 18.149],
[25.602, 10.356, 20.3],
[31.007, 10.318, 20.785],
[38.519, 10.266, 21.458],
],
color: "#db8729",
};
const result = renderPolygonsWithTextureAtlas([skinnyLeadingNgon]);
const element = result.rendered[0].element;
const matrix = extractMatrix(element);
expect(matrix.length).toBe(16);
expect(matrix[8]).toBeGreaterThan(0.99);
expect(Math.abs(matrix[9])).toBeLessThan(0.02);
expect(matrix[10]).toBeCloseTo(-0.069, 3);
result.dispose();
});
it("uses color/currentColor, not an atlas canvas, for full rectangular solid polygons", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas([VERTICAL_QUAD], { doc });
const element = result.rendered[0].element;
expect(canvases).toHaveLength(0);
const styleText = element.getAttribute("style") ?? "";
expect(styleText.trim().startsWith("transform:")).toBe(true);
expect(styleText).toMatch(/^transform:[^;]+;color:/);
expect(styleText).not.toContain("width:");
expect(styleText).not.toContain("height:");
expect(styleText).not.toMatch(/:\s|;\s/);
expect(styleText).toMatch(/color:\s*#[0-9a-f]{6}/);
expect(styleText).not.toMatch(/color:rgb/i);
expect(element.style.color).not.toBe("");
expect(element.style.backgroundColor).toBe("");
result.dispose();
});
it("can render solid non-rect polygons with border-shape when projective quads are disabled", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
defaultView: {
CSS: {
supports: (property: string) => property === "border-shape",
},
},
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas([NON_RECT_QUAD], {
doc,
strategies: { disable: ["b"] },
});
const element = result.rendered[0].element;
expect(canvases).toHaveLength(0);
expect(element.tagName.toLowerCase()).toBe("i");
expect(element.className).toBe("");
expect(element.style.getPropertyValue("border-shape")).toContain("polygon(");
expect(element.style.boxSizing).toBe("");
expect(element.style.borderStyle).toBe("");
expect(element.style.borderWidth).toBe("");
expect(element.style.width).toBe("");
expect(element.style.height).toBe("");
const styleText = element.getAttribute("style") ?? "";
const borderShape = styleText.match(/border-shape:([^;]+)/)?.[1] ?? "";
expect(styleText).toMatch(/^transform:[^;]+;border-shape:[^;]+;color:/);
expect(styleText).not.toMatch(/:\s|;\s/);
expect(borderShape).not.toContain(", ");
expect(borderShape).not.toMatch(/\b0%/);
expect(borderShape.match(/polygon\(/g) ?? []).toHaveLength(1);
expect(borderShape).toMatch(/\)\s*circle\(0\)$/);
expect(styleText).toMatch(/color:\s*#[0-9a-f]{6}/);
expect(styleText).not.toMatch(/color:rgb/i);
expect(element.style.color).not.toBe("");
expect(element.style.backgroundImage).toBe("");
result.dispose();
});
it("border-shape default bleed expands the generated paint box", () => {
const doc = {
defaultView: {
CSS: {
supports: (property: string) => property === "border-shape",
},
},
createElement: (tagName: string) => document.createElement(tagName),
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas([NON_RECT_QUAD], {
doc,
tileSize: 1,
strategies: { disable: ["b"] },
});
const element = result.rendered[0].element;
const matrix = extractMatrix(element);
const xScale = Math.hypot(matrix[0], matrix[1], matrix[2]);
const yScale = Math.hypot(matrix[4], matrix[5], matrix[6]);
expect(element.tagName.toLowerCase()).toBe("i");
expect(xScale).toBeGreaterThan(2 / 16);
expect(yScale).toBeGreaterThan(2 / 16);
expect(element.style.getPropertyValue("border-shape")).toContain("polygon(");
result.dispose();
});
it("uses the atlas fallback for solid non-rect polygons on non-desktop pointers when projective quads are disabled", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
defaultView: {
CSS: {
supports: (property: string) => property === "border-shape",
},
matchMedia: (query: string) => ({
matches: query.includes("pointer: coarse") || query.includes("hover: none"),
}),
},
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas([NON_RECT_QUAD], {
doc,
strategies: { disable: ["b"] },
});
const element = result.rendered[0].element;
expect(canvases).toHaveLength(1);
expect(element.style.getPropertyValue("border-shape")).toBe("");
result.dispose();
});
it("keeps textured polygons on atlas even when border-shape is supported", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
defaultView: {
CSS: {
supports: (property: string) => property === "border-shape",
},
},
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas(
[{ ...FLAT_TRIANGLE, texture: "https://example.com/tex.png" }],
{ doc },
);
const element = result.rendered[0].element;
expect(canvases).toHaveLength(1);
expect(element.style.getPropertyValue("border-shape")).toBe("");
expect(element.style.backgroundClip).toBe("");
result.dispose();
});
it("falls back to atlas for solid non-rect polygons when border-shape and projective quads are unavailable", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
defaultView: {
CSS: {
supports: () => false,
},
},
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const result = renderPolygonsWithTextureAtlas([NON_RECT_QUAD], {
doc,
strategies: { disable: ["b"] },
});
const element = result.rendered[0].element;
expect(canvases).toHaveLength(1);
expect(element.style.getPropertyValue("border-shape")).toBe("");
result.dispose();
});
it("returns a polygon s element for texture without UVs", () => {
const texturedPoly: Polygon = {
vertices: FLAT_TRIANGLE.vertices,
texture: "https://example.com/tex.png",
};
const result = renderPolygonsWithTextureAtlas([texturedPoly]);
const element = result.rendered[0].element;
expect(element.tagName.toLowerCase()).toBe("s");
expect(element.classList.contains("polycss-poly")).toBe(false);
expect(element.classList.contains("polycss-poly-textured")).toBe(false);
expect(element.style.transform).toContain("matrix3d(");
expect(element.getAttribute("style")).not.toMatch(/:\s|;\s/);
expect(element.style.filter).toBe("");
result.dispose();
});
it("uses matrix scale for the fixed border-shape paint box", () => {
const obliqueQuad: Polygon = {
vertices: [
[0, 0, 0],
[1, 9, 0],
[1, 10, 0],
[0, 10, 0],
],
color: "#ffffff",
};
const result = renderPolygonsWithTextureAtlas([obliqueQuad], {
tileSize: 1,
strategies: { disable: ["b"] },
});
const element = result.rendered[0].element;
const matrix = extractMatrix(element);
expect(element.tagName.toLowerCase()).toBe("i");
expect(element.style.width).toBe("");
expect(element.style.height).toBe("");
expect(element.style.getPropertyValue("--polycss-local-w")).toBe("");
expect(element.style.getPropertyValue("--polycss-local-h")).toBe("");
expect(matrix[0]).toBeGreaterThan(10 / 16);
expect(matrix[1]).toBeCloseTo(0, 6);
expect(matrix[4]).toBeCloseTo(0, 6);
expect(matrix[5]).toBeGreaterThan(1 / 16);
result.dispose();
});
it("keeps the first-edge transform basis for UV-mapped textured polygons", () => {
const obliqueTriangle: Polygon = {
vertices: [
[0, 0, 0],
[1, 9, 0],
[0, 10, 0],
],
color: "#ffffff",
texture: "https://example.com/tex.png",
uvs: [[0, 0], [1, 0], [0, 1]],
};
const result = renderPolygonsWithTextureAtlas([obliqueTriangle], { tileSize: 1 });
const element = result.rendered[0].element;
const matrix = extractMatrix(element);
const expected = roundedMatrix(computeExpectedMatrix(obliqueTriangle.vertices as [number, number, number][], 1, 1));
expect(element.style.width).toBe("");
expect(element.style.height).toBe("");
expectColumnDirection(matrix, expected, 0);
expectColumnDirection(matrix, expected, 4);
expect(matrix[12]).toBeCloseTo(expected[12], 6);
expect(matrix[13]).toBeCloseTo(expected[13], 6);
expect(matrix[14]).toBeCloseTo(expected[14], 6);
result.dispose();
});
it("uses one basis for an untextured coplanar island when it keeps the DOM box tight", () => {
const left: Polygon = {
vertices: [
[0, 0, 0],
[0, 10, 0],
[1, 10, 0],
[1, 1, 0],
],
color: "#ff0000",
};
const right: Polygon = {
vertices: [
[0, 10, 0],
[0, 20, 0],
[1, 19, 0],
[1, 10, 0],
],
color: "#ff0000",
};
const result = renderPolygonsWithTextureAtlas([left, right], {
tileSize: 1,
strategies: { disable: ["b"] },
});
const leftMatrix = extractMatrix(result.rendered[0].element);
const rightMatrix = extractMatrix(result.rendered[1].element);
expectColumnDirection(leftMatrix, rightMatrix, 0);
expectColumnDirection(leftMatrix, rightMatrix, 4);
result.dispose();
});
it("keeps the first-edge transform basis for shared textured seams", () => {
const bladeFace: Polygon = {
vertices: [
[0, 0, 0],
[1, 9, 0],
[0, 10, 0],
],
texture: "https://example.com/tex.png",
uvs: [[0, 0], [1, 0], [0, 1]],
};
const bevelFace: Polygon = {
vertices: [
[1, 9, 0],
[0, 0, 0],
[0, 0, 1],
],
texture: "https://example.com/tex.png",
uvs: [[1, 0], [0, 0], [0, 1]],
};
const isolated = renderPolygonsWithTextureAtlas([bladeFace], { tileSize: 1 });
const shared = renderPolygonsWithTextureAtlas([bladeFace, bevelFace], { tileSize: 1 });
const sharedMatrix = extractMatrix(shared.rendered[0].element);
const sharedEdgeMatrix = roundedMatrix(computeExpectedMatrix(bladeFace.vertices as [number, number, number][], 1, 1));
const isolatedMatrix = extractMatrix(isolated.rendered[0].element);
expectColumnDirection(isolatedMatrix, sharedEdgeMatrix, 0);
expectColumnDirection(isolatedMatrix, sharedEdgeMatrix, 4);
expectColumnDirection(sharedMatrix, sharedEdgeMatrix, 0);
expectColumnDirection(sharedMatrix, sharedEdgeMatrix, 4);
isolated.dispose();
shared.dispose();
});
it("keeps textured geometry stable with default edge repair", () => {
const left: Polygon = {
vertices: [
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
],
texture: "https://example.com/tex.png",
uvs: [[0, 0], [1, 0], [0, 1]],
};
const right: Polygon = {
vertices: [
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
],
texture: "https://example.com/tex.png",
uvs: [[1, 0], [1, 1], [0, 1]],
};
const repaired = renderPolygonsWithTextureAtlas([left, right], {
tileSize: 1,
textureQuality: 1,
});
expect(repaired.rendered[0].element.style.width).toBe("");
expect(repaired.rendered[0].element.style.height).toBe("");
expectMatrixClose(
extractMatrix(repaired.rendered[0].element),
roundedMatrix(computeExpectedMatrix(left.vertices as [number, number, number][], 1, 1)),
);
expect(repaired.rendered[0].plan?.textureEdgeRepair).toBe(true);
repaired.dispose();
});
it("keeps hard textured edge geometry stable with default edge repair", () => {
const floor: Polygon = {
vertices: [
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
],
texture: "https://example.com/tex.png",
uvs: [[0, 0], [1, 0], [0, 1]],
};
const wall: Polygon = {
vertices: [
[1, 0, 0],
[0, 0, 0],
[0, 0, 1],
],
texture: "https://example.com/tex.png",
uvs: [[1, 0], [0, 0], [0, 1]],
};
const repaired = renderPolygonsWithTextureAtlas([floor, wall], {
tileSize: 1,
textureQuality: 1,
});
expect(repaired.rendered[0].element.style.width).toBe("");
expect(repaired.rendered[0].element.style.height).toBe("");
expect(repaired.rendered[1].element.style.width).toBe("");
expect(repaired.rendered[1].element.style.height).toBe("");
expectMatrixClose(
extractMatrix(repaired.rendered[0].element),
roundedMatrix(computeExpectedMatrix(floor.vertices as [number, number, number][], 1, 1)),
);
expectMatrixClose(
extractMatrix(repaired.rendered[1].element),
roundedMatrix(computeExpectedMatrix(wall.vertices as [number, number, number][], 1, 1)),
);
expect(repaired.rendered[0].plan?.textureEdgeRepair).toBe(true);
repaired.dispose();
});
it("repairs low-alpha atlas pixels at textured polygon edges", async () => {
const getImageData = vi.fn((_x: number, _y: number, width: number, height: number) => {
const data = new Uint8ClampedArray(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
const edgeRow = y === 0 || y === height - 1;
data[i] = edgeRow ? 255 : 20;
data[i + 1] = edgeRow ? 255 : 30;
data[i + 2] = edgeRow ? 255 : 40;
data[i + 3] = edgeRow ? 1 : 255;
}
}
return { data, width, height } as ImageData;
});
const putImageData = vi.fn();
const ctx = {
canvas: undefined as HTMLCanvasElement | undefined,
save: vi.fn(),
restore: vi.fn(),
setTransform: vi.fn(),
beginPath: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
closePath: vi.fn(),
clip: vi.fn(),
fillRect: vi.fn(),
drawImage: vi.fn(),
getImageData,
putImageData,
} as unknown as CanvasRenderingContext2D;
const getContext = vi.fn(() => ctx);
const doc = {
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = {
width: 0,
height: 0,
getContext,
toBlob: (callback: (blob: Blob | null) => void) => callback(null),
} as unknown as HTMLCanvasElement;
(ctx as { canvas?: HTMLCanvasElement }).canvas = canvas;
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
vi.stubGlobal("Image", class MockImage {
decoding = "";
naturalWidth = 512;
naturalHeight = 512;
width = 512;
height = 512;
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
set src(_value: string) {
queueMicrotask(() => this.onload?.());
}
});
const left: Polygon = {
vertices: [
[0, 0, 0],
[4, 0, 0],
[4, 4, 0],
[0, 4, 0],
],
texture: "https://example.com/edge-alpha.png",
};
const right: Polygon = {
vertices: [
[4, 0, 0],
[8, 0, 0],
[8, 4, 0],
[4, 4, 0],
],
texture: "https://example.com/edge-alpha.png",
};
const result = renderPolygonsWithTextureAtlas([left, right], {
doc,
tileSize: 1,
textureQuality: 1,
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(getContext).toHaveBeenCalledWith("2d", { willReadFrequently: true });
expect(getImageData).toHaveBeenCalled();
expect(putImageData).toHaveBeenCalled();
const repaired = putImageData.mock.calls[0][0] as ImageData;
const firstRow = Array.from({ length: repaired.width }, (_, x) =>
Array.from(repaired.data.slice(x * 4, x * 4 + 4)),
);
const lastRowStart = (repaired.height - 1) * repaired.width * 4;
const lastRow = Array.from({ length: repaired.width }, (_, x) =>
Array.from(repaired.data.slice(lastRowStart + x * 4, lastRowStart + x * 4 + 4)),
);
expect([...firstRow, ...lastRow]).toContainEqual([20, 30, 40, 255]);
result.dispose();
});
it("returns a polygon s element for UV-mapped texture", () => {
const uvPoly: Polygon = {
vertices: FLAT_TRIANGLE.vertices,
texture: "https://example.com/tex.png",
uvs: [[0, 0], [1, 0], [0, 1]],
};
const result = renderPolygonsWithTextureAtlas([uvPoly]);
const element = result.rendered[0].element;
expect(element.tagName.toLowerCase()).toBe("s");
expect(element.classList.contains("polycss-poly")).toBe(false);
expect(element.style.transform).toContain("matrix3d(");
result.dispose();
});
it("samples degenerate UV texture regions instead of covering with the full texture", async () => {
const drawImage = vi.fn();
const ctx = {
save: vi.fn(),
restore: vi.fn(),
setTransform: vi.fn(),
beginPath: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
closePath: vi.fn(),
clip: vi.fn(),
fillRect: vi.fn(),
drawImage,
} as unknown as CanvasRenderingContext2D;
const doc = {
createElement(tagName: string) {
if (tagName === "canvas") {
return {
width: 0,
height: 0,
getContext: () => ctx,
toBlob: (callback: (blob: Blob | null) => void) => callback(null),
};
}
return document.createElement(tagName);
},
} as unknown as Document;
vi.stubGlobal("Image", class MockImage {
decoding = "";
naturalWidth = 512;
naturalHeight = 512;
width = 512;
height = 512;
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
set src(_value: string) {
queueMicrotask(() => this.onload?.());
}
});
const uvPoly: Polygon = {
vertices: FLAT_TRIANGLE.vertices,
texture: "https://example.com/degen-uv.png",
uvs: [[0.25, 0.25], [0.25, 0.25], [0.25, 0.25]],
};
const result = renderPolygonsWithTextureAtlas([uvPoly], { doc });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(drawImage).toHaveBeenCalled();
const sourceRectCalls = drawImage.mock.calls.filter((call) => call.length === 9);
expect(sourceRectCalls).toHaveLength(1);
expect(sourceRectCalls[0][3]).toBe(1);
expect(sourceRectCalls[0][4]).toBe(1);
expect(drawImage.mock.calls.some((call) => call.length === 5)).toBe(false);
result.dispose();
});
it("emits per-polygon normal vars in dynamic mode", () => {
const result = renderPolygonsWithTextureAtlas([FLAT_TRIANGLE], { textureLighting: "dynamic" });
const element = result.rendered[0].element;
// The calc-driven background-color + background-blend-mode now live
// in the global stylesheet (scoped to data-polycss-lighting="dynamic"
// on the scene). Per-polygon style only carries the surface normal
// — much smaller payload per element on big meshes.
expect(element.style.getPropertyValue("--pnx")).not.toBe("");
expect(element.style.getPropertyValue("--pny")).not.toBe("");
expect(element.style.getPropertyValue("--pnz")).not.toBe("");
result.dispose();
});
it("does not emit dynamic style hooks in baked mode", () => {
const result = renderPolygonsWithTextureAtlas([FLAT_TRIANGLE], { textureLighting: "baked" });
const element = result.rendered[0].element;
expect(element.style.backgroundColor).toBe("");
expect(element.style.backgroundBlendMode).toBe("");
expect(element.style.getPropertyValue("--pnx")).toBe("");
result.dispose();
});
it("scales generated atlas canvas dimensions when textureQuality is set", () => {
const canvases: Array<{ width: number; height: number; getContext: () => null }> = [];
const doc = {
createElement(tagName: string) {
if (tagName === "canvas") {
const canvas = { width: 0, height: 0, getContext: () => null };
canvases.push(canvas);
return canvas;
}
return document.createElement(tagName);
},
} as unknown as Document;
const texturedTriangle = { ...FLAT_TRIANGLE, texture: "https://example.com/tex.png" };
const full = renderPolygonsWithTextureAtlas([texturedTriangle], { doc, textureQuality: 1 });