Repository navigation
Expand file tree
/
Copy pathoverlay.test.ts
More file actions
1207 lines (1148 loc) · 40.3 KB
/
Copy pathoverlay.test.ts
File metadata and controls
1207 lines (1148 loc) · 40.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, expect, it, vi } from 'vitest';
import {
buildOverlayScript,
isElementRectsMessage,
isOverlayMessage,
OVERLAY_SCRIPT,
} from './overlay';
interface FakeWindow {
addEventListener: (type: string, fn: unknown, capture?: boolean) => void;
parent: { postMessage: (msg: unknown, target: string) => void };
__cs_err?: boolean;
__cs_rej?: boolean;
__cs_msg?: boolean;
}
function runOverlay(opts: { removeThrows?: boolean; addThrows?: boolean }): {
warn: ReturnType<typeof vi.fn>;
tick: () => void;
} {
const warn = vi.fn();
const fakeConsole = { warn };
const fakeDocument = {
body: {},
addEventListener: () => {
if (opts.addThrows) throw new Error('add failed');
},
removeEventListener: () => {
if (opts.removeThrows) throw new Error('remove failed');
},
};
const fakeWindow: FakeWindow = {
addEventListener: () => {},
parent: { postMessage: () => {} },
};
let intervalFn: (() => void) | null = null;
const fakeSetInterval = (fn: () => void) => {
intervalFn = fn;
return 1;
};
const sandbox = new Function(
'window',
'document',
'console',
'setInterval',
`with (window) { ${OVERLAY_SCRIPT} }`,
);
sandbox(fakeWindow, fakeDocument, fakeConsole, fakeSetInterval);
return {
warn,
tick: () => {
if (intervalFn) intervalFn();
},
};
}
describe('OVERLAY_SCRIPT reattach loop warning throttle', () => {
it('dedupes repeated reattach failures across many ticks', () => {
const { warn, tick } = runOverlay({ removeThrows: true, addThrows: true });
// Initial reattach already ran inside script; simulate 25 more interval fires (~5s @ 200ms).
for (let i = 0; i < 25; i++) tick();
// 4 install specs (mouseover/mouseout/click/submit) * 2 ops (remove+add)
// = 8 distinct keys at most. The point: it must not scale with tick count.
expect(warn.mock.calls.length).toBeLessThanOrEqual(8);
});
it('emits at most one warn per unique error key over the whole loop', () => {
const { warn, tick } = runOverlay({ removeThrows: true });
for (let i = 0; i < 25; i++) tick();
const keys = new Set(warn.mock.calls.map((c) => String(c[0])));
// each warn call should be a unique key
expect(warn.mock.calls.length).toBe(keys.size);
// should be ≤ 4 (one per install-spec event type), well under the 25-tick spam ceiling
expect(warn.mock.calls.length).toBeLessThanOrEqual(4);
});
});
// ---------------------------------------------------------------------------
// SET_MODE trust boundary: control messages must come from window.parent.
// Untrusted in-iframe scripts could synthesise MessageEvent-shaped objects or
// bounce events off the iframe itself (window.postMessage(self, ...)), which
// would arrive with ev.source === window. Both paths must be rejected.
// ---------------------------------------------------------------------------
interface ListenerHarness {
body: object;
documentElement: { getAttribute: (name: string) => string | null };
selectorMatches: Map<string, unknown[]>;
elementIds: Map<string, unknown>;
documentListeners: Map<string, (e: unknown) => void>;
windowListeners: Map<string, (e: unknown) => void>;
parent: object;
postedToParent: unknown[];
setHitTarget: (target: unknown) => void;
runTick: () => void;
queueMutations: (records: object[]) => void;
hitLayer: { isConnected: boolean; style: Record<string, string>; textContent?: string };
}
function runOverlayWithHarness(script = OVERLAY_SCRIPT): ListenerHarness {
const body = {};
const selectorMatches = new Map<string, unknown[]>();
const elementIds = new Map<string, unknown>();
const documentListeners = new Map<string, (e: unknown) => void>();
const windowListeners = new Map<string, (e: unknown) => void>();
const postedToParent: unknown[] = [];
const parent = { postMessage: (msg: unknown) => postedToParent.push(msg) };
let hitTarget: unknown = null;
let tick = () => {};
const hitLayer = {
isConnected: false,
style: {} as Record<string, string>,
setAttribute: () => {},
addEventListener: () => {},
remove: () => {
hitLayer.isConnected = false;
},
};
const fakeDocument = {
body,
querySelectorAll: (selector: string) => selectorMatches.get(selector) ?? [],
querySelector: (selector: string) => selectorMatches.get(selector)?.[0] ?? null,
createElement: () => hitLayer,
documentElement: {
attrs: {} as Record<string, string>,
getAttribute(name: string) {
return this.attrs[name] ?? null;
},
setAttribute(name: string, value: string) {
this.attrs[name] = value;
},
appendChild: () => {
hitLayer.isConnected = true;
},
},
elementFromPoint: () => hitTarget,
getElementById: (id: string) => elementIds.get(id) ?? null,
addEventListener: (type: string, fn: (e: unknown) => void) => {
documentListeners.set(type, fn);
},
removeEventListener: () => {},
};
let mutations: object[] = [];
class MutationObserver {
observe() {}
takeRecords() {
const records = mutations;
mutations = [];
return records;
}
}
const fakeWindow = {
MutationObserver,
CSS: { escape: (value: string) => value.replaceAll(':', '\\:') },
addEventListener: (type: string, fn: (e: unknown) => void) => {
windowListeners.set(type, fn);
},
parent,
};
const fakeSetInterval = (fn: () => void) => {
tick = fn;
return 1;
};
const sandbox = new Function(
'window',
'document',
'console',
'setInterval',
`with (window) { ${script} }`,
);
sandbox(fakeWindow, fakeDocument, { warn: () => {} }, fakeSetInterval);
return {
body,
documentElement: fakeDocument.documentElement,
selectorMatches,
elementIds,
documentListeners,
windowListeners,
parent,
postedToParent,
setHitTarget: (target) => {
hitTarget = target;
},
runTick: () => tick(),
queueMutations: (records) => {
mutations.push(...records);
},
hitLayer,
};
}
describe('OVERLAY_SCRIPT fragment navigation', () => {
it.each([
['#courses', 'courses'],
['#%E8%AF%BE%E7%A8%8B', '课程'],
['#invalid%encoding', 'invalid%encoding'],
])('scrolls %s locally without following the workspace base URL', (href, id) => {
const h = runOverlayWithHarness();
const scrollIntoView = vi.fn();
h.elementIds.set(id, { scrollIntoView });
const preventDefault = vi.fn();
const stopPropagation = vi.fn();
h.documentListeners.get('click')?.({
target: {
tagName: 'SPAN',
parentElement: {
tagName: 'A',
href: `workspace://design/${href}`,
getAttribute: () => href,
},
},
preventDefault,
stopPropagation,
});
expect(preventDefault).toHaveBeenCalledOnce();
expect(scrollIntoView).toHaveBeenCalledOnce();
expect(stopPropagation).not.toHaveBeenCalled();
});
it.each([
'#missing',
'/missing-page',
'https://example.com',
])('retains the navigation boundary for %s', (href) => {
const h = runOverlayWithHarness();
const preventDefault = vi.fn();
const stopPropagation = vi.fn();
h.documentListeners.get('click')?.({
target: { tagName: 'A', href, getAttribute: () => href },
preventDefault,
stopPropagation,
});
expect(preventDefault).toHaveBeenCalledOnce();
expect(stopPropagation).toHaveBeenCalledOnce();
});
function screenDouble(id: string) {
const attrs: Record<string, string> = { 'data-oc-screen': id };
return {
id,
scrollIntoView: vi.fn(),
getAttribute: (name: string) => attrs[name] ?? null,
setAttribute: (name: string, value: string) => {
attrs[name] = value;
},
removeAttribute: (name: string) => {
delete attrs[name];
},
};
}
it('shows the targeted data-oc-screen without scrolling or leaving the document', () => {
const h = runOverlayWithHarness();
const home = screenDouble('home');
const pricing = screenDouble('pricing');
h.elementIds.set('pricing', pricing);
h.selectorMatches.set('[data-oc-screen]', [h.documentElement, home, pricing]);
const preventDefault = vi.fn();
h.documentListeners.get('click')?.({
target: { tagName: 'A', href: '#pricing', getAttribute: () => '#pricing' },
preventDefault,
stopPropagation: vi.fn(),
});
expect(h.documentElement.getAttribute('data-oc-active-screen')).toBe('pricing');
expect(h.documentElement.getAttribute('data-oc-screen')).toBeNull();
expect(pricing.getAttribute('hidden')).toBeNull();
expect(home.getAttribute('hidden')).toBe('');
expect(h.documentElement.getAttribute('hidden')).toBeNull();
expect(preventDefault).toHaveBeenCalledOnce();
expect(pricing.scrollIntoView).not.toHaveBeenCalled();
});
it('selects the first screen when the document renders one later', () => {
const h = runOverlayWithHarness();
const home = screenDouble('home');
const pricing = screenDouble('pricing');
h.selectorMatches.set('[data-oc-screen]', [home, pricing]);
h.runTick();
expect(h.documentElement.getAttribute('data-oc-active-screen')).toBe('home');
expect(home.getAttribute('hidden')).toBeNull();
expect(pricing.getAttribute('hidden')).toBe('');
});
});
describe('OVERLAY_SCRIPT fullscreen Escape forwarding', () => {
it('waits for artifact handlers before forwarding an unconsumed Escape', async () => {
const harness = runOverlayWithHarness();
harness.windowListeners.get('keydown')?.({ key: 'Escape' });
expect(harness.postedToParent).toEqual([]);
await Promise.resolve();
expect(harness.postedToParent).toContainEqual({ __codesign: true, type: 'PREVIEW_ESCAPE' });
});
it('respects artifact dialogs, IME composition and non-Escape keys', async () => {
const harness = runOverlayWithHarness();
const onKey = harness.windowListeners.get('keydown');
const consumed = { key: 'Escape', defaultPrevented: false };
onKey?.(consumed);
consumed.defaultPrevented = true;
onKey?.({ key: 'Escape', isComposing: true });
onKey?.({ key: 'Escape', keyCode: 229 });
onKey?.({ key: 'Enter' });
await Promise.resolve();
expect(harness.postedToParent).toEqual([]);
});
});
describe('OVERLAY_SCRIPT stable clicked targets', () => {
function select(h: ListenerHarness, target: object) {
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
h.documentListeners.get('click')?.({
preventDefault: () => {},
stopPropagation: () => {},
target,
});
return h.postedToParent.find(
(message) => (message as { type: string }).type === 'ELEMENT_SELECTED',
);
}
const element = (parent: object) => ({
nodeType: 1,
tagName: 'BUTTON',
id: 'repeat',
parentElement: parent,
previousElementSibling: null as object | null,
style: { outline: '3px dashed green' },
outerHTML: '<button id="repeat">Second</button>',
getBoundingClientRect: () => ({ top: 10, left: 20, width: 100, height: 40 }),
});
it('falls back to the exact body path when two elements share an ID', () => {
const h = runOverlayWithHarness();
const first = element(h.body);
const second = { ...element(h.body), previousElementSibling: first };
h.selectorMatches.set('#repeat', [first, second]);
expect(select(h, second)).toMatchObject({ selector: '/button[2]' });
});
it('uses an escaped ID only when it uniquely identifies the clicked element', () => {
const h = runOverlayWithHarness();
const target = { ...element(h.body), id: 'colon:id' };
h.selectorMatches.set('#colon\\:id', [target]);
expect(select(h, target)).toMatchObject({ selector: '#colon\\:id' });
});
it('restores a pre-existing outline after hover and pin without scrolling a clicked target', () => {
const h = runOverlayWithHarness();
const scrollIntoView = vi.fn();
const target = { ...element(h.body), scrollIntoView };
select(h, target);
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'CLEAR_PIN' },
});
expect(target.style.outline).toBe('3px dashed green');
expect(scrollIntoView).not.toHaveBeenCalled();
});
});
describe('OVERLAY_SCRIPT SET_MODE source validation', () => {
it('drops SET_MODE messages whose source is not window.parent (forged)', () => {
const h = runOverlayWithHarness();
const onMessage = h.windowListeners.get('message');
const onClick = h.documentListeners.get('click');
expect(onMessage).toBeDefined();
expect(onClick).toBeDefined();
// Forged: source is the iframe itself (e.g. window.postMessage(self,...)),
// not the embedding parent. Even though the envelope looks valid, the
// mode must NOT switch to 'comment'.
const forgedSource = {};
onMessage?.({
source: forgedSource,
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
// currentMode is internal to the IIFE, so we observe via the click gate:
// in default mode, clicks must not be intercepted (no postMessage to parent).
onClick?.({
preventDefault: () => {},
stopPropagation: () => {},
target: { tagName: 'DIV', getBoundingClientRect: () => ({}), outerHTML: '<div/>' },
});
expect(h.postedToParent).toHaveLength(0);
});
it('accepts SET_MODE only when ev.source === window.parent', () => {
const h = runOverlayWithHarness();
const onMessage = h.windowListeners.get('message');
const onClick = h.documentListeners.get('click');
onMessage?.({
source: h.parent,
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
// Now in comment mode → click should be intercepted and posted to parent.
onClick?.({
preventDefault: () => {},
stopPropagation: () => {},
target: {
tagName: 'BUTTON',
getBoundingClientRect: () => ({ top: 1, left: 2, width: 3, height: 4 }),
outerHTML: '<button/>',
},
});
expect(h.postedToParent).toHaveLength(1);
expect((h.postedToParent[0] as { type: string }).type).toBe('ELEMENT_SELECTED');
});
it('drops messages with no source (null) even when envelope matches', () => {
const h = runOverlayWithHarness();
const onMessage = h.windowListeners.get('message');
const onClick = h.documentListeners.get('click');
onMessage?.({
source: null,
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
onClick?.({
preventDefault: () => {},
stopPropagation: () => {},
target: { tagName: 'DIV', getBoundingClientRect: () => ({}), outerHTML: '<div/>' },
});
expect(h.postedToParent).toHaveLength(0);
});
});
// ---------------------------------------------------------------------------
// WATCH_SELECTORS + scroll/resize → ELEMENT_RECTS broadcast.
// The iframe owns the source of truth for each pinned element's rect; the
// parent can't observe iframe-internal scroll, so pins drift without this.
// ---------------------------------------------------------------------------
interface RectHarness {
documentListeners: Map<string, (e: unknown) => void>;
windowListeners: Map<string, (e: unknown) => void>;
parent: object;
postedToParent: Array<Record<string, unknown>>;
runRaf: () => void;
registerElement: (selector: string, rect: DOMRect, visible?: boolean) => void;
registerBodyPath: (selector: string, rect: DOMRect) => void;
}
interface FakeElement {
tagName: string;
children: FakeElement[];
getBoundingClientRect: () => DOMRect;
scrollIntoView: () => void;
style: { outline?: string };
getClientRects?: () => DOMRect[];
}
function runOverlayForRects(): RectHarness {
const documentListeners = new Map<string, (e: unknown) => void>();
const windowListeners = new Map<string, (e: unknown) => void>();
const posted: Array<Record<string, unknown>> = [];
const parent = { postMessage: (msg: unknown) => posted.push(msg as Record<string, unknown>) };
const elements = new Map<
string,
{
getBoundingClientRect: () => DOMRect;
getClientRects?: () => DOMRect[];
scrollIntoView: () => void;
style: { outline?: string };
}
>();
const makeElement = (tagName: string, rect = makeRect(0, 0, 0, 0)): FakeElement => ({
tagName,
children: [],
getBoundingClientRect: () => rect,
scrollIntoView: () => {},
style: {},
});
const body = makeElement('BODY');
const fakeDocument = {
body,
addEventListener: (type: string, fn: (e: unknown) => void) => {
documentListeners.set(type, fn);
},
removeEventListener: () => {},
querySelector: (sel: string) => elements.get(sel) ?? null,
evaluate: (sel: string) => ({ singleNodeValue: elements.get(sel) ?? null }),
};
let pendingRaf: (() => void) | null = null;
const fakeWindow = {
addEventListener: (type: string, fn: (e: unknown) => void) => {
windowListeners.set(type, fn);
},
parent,
requestAnimationFrame: (fn: () => void) => {
pendingRaf = fn;
return 42;
},
};
const fakeSetInterval = () => 1;
const sandbox = new Function(
'window',
'document',
'console',
'setInterval',
`with (window) { ${OVERLAY_SCRIPT} }`,
);
sandbox(fakeWindow, fakeDocument, { warn: () => {} }, fakeSetInterval);
return {
documentListeners,
windowListeners,
parent,
postedToParent: posted,
runRaf: () => {
const fn = pendingRaf;
pendingRaf = null;
if (fn) fn();
},
registerElement: (selector, rect, visible = true) => {
elements.set(selector, {
getBoundingClientRect: () => rect,
scrollIntoView: () => {},
style: {},
getClientRects: () => (visible ? [rect] : []),
});
},
registerBodyPath: (selector, rect) => {
const parts = selector.slice(1).split('/');
let current = body;
for (const part of parts) {
const match = /^([a-zA-Z][a-zA-Z0-9-]*)\[(\d+)\]$/.exec(part);
if (!match) throw new Error(`Invalid test selector: ${selector}`);
const tag = String(match[1]).toUpperCase();
const index = Number(match[2]);
let seen = 0;
let next: FakeElement | undefined;
for (const child of current.children) {
if (child.tagName.toUpperCase() === tag) {
seen += 1;
if (seen === index) {
next = child;
break;
}
}
}
while (!next) {
const created = makeElement(tag);
if (tag === 'SVG' || tag === 'PATH') created.tagName = tag.toLowerCase();
current.children.push(created);
seen += 1;
if (seen === index) next = created;
}
current = next;
}
current.getBoundingClientRect = () => rect;
},
};
}
function makeRect(top: number, left: number, width: number, height: number): DOMRect {
return {
top,
left,
width,
height,
bottom: top + height,
right: left + width,
x: left,
y: top,
toJSON: () => ({}),
} as DOMRect;
}
describe('selection payload validation', () => {
const message = {
__codesign: true,
type: 'ELEMENT_SELECTED',
selector: '#target',
tag: 'button',
outerHTML: '<button/>',
rect: { top: 1, left: 2, width: 3, height: 4 },
};
it('requires actual element metadata, not just an envelope', () => {
expect(isOverlayMessage({ __codesign: true, type: 'ELEMENT_SELECTED' })).toBe(false);
expect(isOverlayMessage(message)).toBe(true);
});
it.each([Number.NaN, Number.POSITIVE_INFINITY, -1])('rejects invalid sizes %s', (width) => {
const rect = { ...message.rect, width };
expect(isOverlayMessage({ ...message, rect })).toBe(false);
expect(
isElementRectsMessage({
__codesign: true,
type: 'ELEMENT_RECTS',
entries: [{ selector: '#target', rect }],
}),
).toBe(false);
});
});
describe('OVERLAY_SCRIPT rect broadcast', () => {
it('resolves nested SVG paths using the same case normalization as HTML ancestors', () => {
const h = runOverlayForRects();
h.registerBodyPath('/button[2]/svg[1]/path[1]', makeRect(30, 40, 20, 20));
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'WATCH_SELECTORS', selectors: ['/button[2]/svg[1]/path[1]'] },
});
h.runRaf();
expect(h.postedToParent.at(-1)?.['entries']).toEqual([
{
selector: '/button[2]/svg[1]/path[1]',
rect: { top: 30, left: 40, width: 20, height: 20 },
},
]);
});
it('reports an empty measured set instead of retaining a hidden layer rectangle', () => {
const h = runOverlayForRects();
h.registerElement('#hidden', makeRect(0, 0, 0, 0), false);
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'WATCH_SELECTORS', selectors: ['#hidden'] },
});
h.runRaf();
expect(h.postedToParent.at(-1)).toMatchObject({ type: 'ELEMENT_RECTS', entries: [] });
});
it('broadcasts ELEMENT_RECTS after WATCH_SELECTORS message', () => {
const h = runOverlayForRects();
h.registerElement('#a', makeRect(10, 20, 30, 40));
const onMessage = h.windowListeners.get('message');
onMessage?.({
source: h.parent,
data: { __codesign: true, type: 'WATCH_SELECTORS', selectors: ['#a'] },
});
h.runRaf();
const rectMsg = h.postedToParent.find((m) => m['type'] === 'ELEMENT_RECTS');
expect(rectMsg).toBeDefined();
const entries = rectMsg?.['entries'] as Array<{
selector: string;
rect: Record<string, number>;
}>;
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
selector: '#a',
rect: { top: 10, left: 20, width: 30, height: 40 },
});
});
it('re-broadcasts on scroll so pins track the element', () => {
const h = runOverlayForRects();
h.registerElement('#a', makeRect(100, 0, 50, 50));
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'WATCH_SELECTORS', selectors: ['#a'] },
});
h.runRaf();
const firstCount = h.postedToParent.filter((m) => m['type'] === 'ELEMENT_RECTS').length;
expect(firstCount).toBe(1);
// Simulate the user scrolling the iframe content: the element's top moved.
h.registerElement('#a', makeRect(30, 0, 50, 50));
const onScroll = h.windowListeners.get('scroll');
expect(onScroll).toBeDefined();
onScroll?.({});
h.runRaf();
const all = h.postedToParent.filter((m) => m['type'] === 'ELEMENT_RECTS');
expect(all).toHaveLength(2);
const lastEntries = all[1]?.['entries'] as Array<{ rect: Record<string, number> }>;
expect(lastEntries[0]?.rect['top']).toBe(30);
});
it('coalesces burst of scroll events into one rAF-scheduled broadcast', () => {
const h = runOverlayForRects();
h.registerElement('#a', makeRect(0, 0, 1, 1));
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'WATCH_SELECTORS', selectors: ['#a'] },
});
h.runRaf(); // initial broadcast from WATCH_SELECTORS
const onScroll = h.windowListeners.get('scroll');
onScroll?.({});
onScroll?.({});
onScroll?.({});
h.runRaf();
const all = h.postedToParent.filter((m) => m['type'] === 'ELEMENT_RECTS');
// Initial + exactly one from the burst — not three.
expect(all).toHaveLength(2);
});
it('silently skips selectors that do not resolve to elements', () => {
const h = runOverlayForRects();
h.registerElement('#live', makeRect(5, 5, 5, 5));
h.windowListeners.get('message')?.({
source: h.parent,
data: {
__codesign: true,
type: 'WATCH_SELECTORS',
selectors: ['#live', '#ghost'],
},
});
h.runRaf();
const rectMsg = h.postedToParent.find((m) => m['type'] === 'ELEMENT_RECTS');
const entries = rectMsg?.['entries'] as Array<{ selector: string }>;
expect(entries).toHaveLength(1);
expect(entries[0]?.selector).toBe('#live');
});
it('pins and watches a selector sent from the parent', () => {
const h = runOverlayForRects();
h.registerElement('#saved-comment-target', makeRect(12, 24, 48, 96));
h.windowListeners.get('message')?.({
source: h.parent,
data: {
__codesign: true,
type: 'PIN_SELECTOR',
selector: '#saved-comment-target',
},
});
h.runRaf();
const rectMsg = h.postedToParent.find((m) => m['type'] === 'ELEMENT_RECTS');
expect(rectMsg).toBeDefined();
const entries = rectMsg?.['entries'] as Array<{
selector: string;
rect: Record<string, number>;
}>;
expect(entries[0]).toMatchObject({
selector: '#saved-comment-target',
rect: { top: 12, left: 24, width: 48, height: 96 },
});
});
it('resolves body-relative XPath selectors saved by click selection', () => {
const h = runOverlayForRects();
h.registerBodyPath('/div[1]/span[1]', makeRect(20, 30, 40, 50));
h.windowListeners.get('message')?.({
source: h.parent,
data: {
__codesign: true,
type: 'PIN_SELECTOR',
selector: '/div[1]/span[1]',
},
});
h.runRaf();
const rectMsg = h.postedToParent.find((m) => m['type'] === 'ELEMENT_RECTS');
const entries = rectMsg?.['entries'] as Array<{
selector: string;
rect: Record<string, number>;
}>;
expect(entries[0]).toMatchObject({
selector: '/div[1]/span[1]',
rect: { top: 20, left: 30, width: 40, height: 50 },
});
});
});
describe('source provenance selection hints', () => {
const context = {
sourceHash: 'a'.repeat(64),
previewRevision: 'preview-1',
targets: { '10:50': 'button' },
};
function click(
h: ListenerHarness,
marker: string | null,
tagName = 'BUTTON',
parent?: object,
childNodes: { nodeType: number; textContent: string }[] = [],
) {
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
h.documentListeners.get('click')?.({
preventDefault: () => {},
stopPropagation: () => {},
target: {
nodeType: 1,
tagName,
parentElement: parent ?? h.body,
style: {},
outerHTML: '<button>Save</button>',
childNodes,
getAttribute: (name: string) => (name === 'data-codesign-source-id' ? marker : null),
getBoundingClientRect: () => ({ top: 0, left: 0, width: 10, height: 10 }),
},
});
return h.postedToParent.at(-1);
}
it('emits only the clicked host own known marker and bound revisions', () => {
const h = runOverlayWithHarness(buildOverlayScript(context));
const selection = click(h, 'preview-1:10:50');
expect(selection).toMatchObject({
sourceEdit: {
targetId: '10:50',
sourceHash: context.sourceHash,
previewRevision: 'preview-1',
},
});
expect(isOverlayMessage(selection)).toBe(true);
});
it('validates direct text without consuming icon or emphasized sibling content', () => {
const h = runOverlayWithHarness(
buildOverlayScript({ ...context, directTexts: { '10:50': ' Save now' } }),
);
expect(
click(h, 'preview-1:10:50', 'BUTTON', undefined, [
{ nodeType: 1, textContent: 'icon' },
{ nodeType: 3, textContent: ' Save' },
{ nodeType: 8, textContent: 'React separator' },
{ nodeType: 3, textContent: ' now' },
]),
).toHaveProperty('sourceEdit');
});
it.each([
'Changed by an effect',
'Save now',
' Save now!',
])('refuses DOM text changed from the inspected definition: %s', (textContent) => {
const h = runOverlayWithHarness(
buildOverlayScript({ ...context, directTexts: { '10:50': ' Save now' } }),
);
expect(
click(h, 'preview-1:10:50', 'BUTTON', undefined, [{ nodeType: 3, textContent }]),
).not.toHaveProperty('sourceEdit');
});
it('never guesses an ancestor origin or trusts unknown marker/tag pairs', () => {
for (const [marker, tagName] of [
[null, 'SPAN'],
['preview-1:99:100', 'BUTTON'],
['preview-1:10:50', 'DIV'],
] as const) {
const h = runOverlayWithHarness(buildOverlayScript(context));
const parent = {
nodeType: 1,
tagName: 'BUTTON',
parentElement: h.body,
getAttribute: () => 'preview-1:10:50',
};
expect(click(h, marker, tagName, parent)).not.toHaveProperty('sourceEdit');
}
});
it.each([
'10:50',
'author-value',
'preview-old:10:50',
'preview-1:99:100',
])('ignores authored, stale or unmapped attribute values: %s', (marker) => {
const h = runOverlayWithHarness(buildOverlayScript(context));
const selection = click(h, marker);
expect(isOverlayMessage(selection)).toBe(true);
expect(selection).not.toHaveProperty('sourceEdit');
});
it('does not treat a current-looking marker as provenance without an injected target', () => {
const h = runOverlayWithHarness(buildOverlayScript({ ...context, targets: {} }));
expect(click(h, 'preview-1:10:50')).not.toHaveProperty('sourceEdit');
});
it('keeps old comments compatible and ignores authored markers without an inspect plan', () => {
const h = runOverlayWithHarness();
const selection = click(h, 'preview-1:10:50');
expect(isOverlayMessage(selection)).toBe(true);
expect(selection).not.toHaveProperty('sourceEdit');
});
it('does not accept a forged parent control message even with a source-edit plan', () => {
const h = runOverlayWithHarness(buildOverlayScript(context));
h.windowListeners.get('message')?.({
source: {},
data: { __codesign: true, type: 'SET_MODE', mode: 'comment' },
});
h.documentListeners.get('click')?.({ target: { tagName: 'BUTTON' } });
expect(h.postedToParent).toEqual([]);
});
it('bounds metadata and existing selection strings', () => {
const h = runOverlayWithHarness(buildOverlayScript(context));
const message = click(h, 'preview-1:10:50');
if (!isOverlayMessage(message)) throw new Error('Missing fixture selection');
for (const invalid of [
{ ...message, sourceEdit: { ...message.sourceEdit, path: '../outside.jsx' } },
{ ...message, sourceEdit: { ...message.sourceEdit, sourceHash: 'old' } },
{ ...message, selector: 'x'.repeat(8193) },
{ ...message, outerHTML: 'x'.repeat(801) },
{ ...message, parentOuterHTML: 'x'.repeat(601) },
{ ...message, tag: 'x'.repeat(129) },
])
expect(isOverlayMessage(invalid)).toBe(false);
});
});
describe('unified preview edit selection and validation', () => {
const sourceHash = 'b'.repeat(64);
const previewRevision = 'preview-edit';
function fixture() {
const h = runOverlayWithHarness(
buildOverlayScript({
sourceHash,
previewRevision,
targets: { '10:50': 'button' },
fieldPlans: {
'10:50': {
textLayout: [
{ kind: 'text', textId: '11:20', value: 'Cart (' },
{ kind: 'dynamic' },
{ kind: 'text', textId: '30:40', value: ')' },
],
editableFields: [
{ kind: 'set-text', textId: '11:20', value: 'Cart (' },
{ kind: 'set-text', textId: '30:40', value: ')' },
],
},
},
}),
);
const button = {
nodeType: 1,
tagName: 'BUTTON',
id: 'cart',
parentElement: h.body,
style: {},
isConnected: true,
outerHTML: '<button disabled>Cart (2)</button>',
childNodes: [
{ nodeType: 3, textContent: 'Cart (' },
{ nodeType: 3, textContent: '2' },
{ nodeType: 3, textContent: ')' },
],
getAttribute: (name: string) =>
name === 'data-codesign-source-id' ? 'preview-edit:10:50' : null,
getBoundingClientRect: () => ({ top: 0, left: 0, width: 100, height: 30 }),
};
h.selectorMatches.set('#cart', [button]);
h.setHitTarget(button);
function control(type: string, extra: Record<string, unknown> = {}) {
h.windowListeners.get('message')?.({
source: h.parent,
data: { __codesign: true, type, sourceHash, previewRevision, ...extra },
});
}
control('SET_MODE', { mode: 'source-edit' });
function pointer() {
const preventDefault = vi.fn();
const stopImmediatePropagation = vi.fn();
h.documentListeners.get('pointerdown')?.({
type: 'pointerdown',
clientX: 10,
clientY: 10,
preventDefault,
stopImmediatePropagation,
target: h.hitLayer,
});
return { preventDefault, stopImmediatePropagation };
}
return { h, button, control, pointer };
}
it('selects disabled hosts via a removable hit layer without dispatching artifact clicks', () => {
const { h, control, pointer } = fixture();
expect(h.hitLayer.isConnected).toBe(true);
const event = pointer();
expect(event.preventDefault).toHaveBeenCalledOnce();
expect(event.stopImmediatePropagation).toHaveBeenCalledOnce();
const selected = h.postedToParent.at(-1);
expect(isOverlayMessage(selected)).toBe(true);
expect(selected).toMatchObject({
sourceEditRevision: { sourceHash, previewRevision },
sourceEdit: {
targetId: '10:50',
fieldStates: [
{ key: 'text:11:20', status: 'ready' },
{ key: 'text:30:40', status: 'ready' },
],
},
});
control('SET_MODE', { mode: 'default' });
expect(h.hitLayer.isConnected).toBe(false);
});
it('revalidates the pinned instance immediately before saving and reports DOM changes', () => {
const { h, button, control, pointer } = fixture();
pointer();
const prefixNode = button.childNodes[0];
if (!prefixNode) throw new Error('Missing text node');
prefixNode.textContent = 'Changed (';
control('SOURCE_EDIT_VALIDATE', {
requestId: 'save-1',
targetId: '10:50',
fieldKey: 'text:11:20',
});