@flighthq/menu 0.5.0-next.1944.cd6b6e7 → 0.5.1-edge.638.d4dbd4e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/menu.test.ts CHANGED
@@ -1,32 +1,139 @@
1
- import type { MenuBackend, MenuItemTemplate } from '@flighthq/types/contract';
1
+ import { connectSignal } from '@flighthq/signals/contract';
2
+ import type {
3
+ HasMenuApplication,
4
+ HasMenuHighlight,
5
+ HasMenuPopup,
6
+ HasMenuSelect,
7
+ MenuItemTemplate,
8
+ } from '@flighthq/types/contract';
2
9
 
3
10
  import {
11
+ attachMenuHighlight,
12
+ attachMenuSelect,
4
13
  cloneMenuTemplate,
14
+ createMenuHighlight,
5
15
  createMenuItemTemplate,
16
+ createMenuSelect,
17
+ destroyMenuApplication,
18
+ detachMenuHighlight,
19
+ detachMenuSelect,
20
+ disposeMenuHighlight,
21
+ disposeMenuSelect,
6
22
  enableMenuSignals,
7
- explainMenuBackend,
8
- getMenuBackend,
9
23
  getMenuSignals,
10
- installMenuHostBackend,
11
- observeMenuHostResult,
12
- onMenuSelect,
13
- resetMenuBackendForTest,
14
24
  setApplicationMenu,
15
- setMenuBackend,
16
25
  showContextMenu,
17
- showWebContextMenu,
18
26
  validateMenuItemTemplate,
19
27
  } from './menu';
20
28
 
21
- function fakeBackend(overrides?: Partial<MenuBackend>): MenuBackend {
29
+ // A host exposing exactly the slots a test needs. Nothing is installed anywhere: two of these can be
30
+ // live at once, which is the property the ambient model could not express.
31
+ function popupHost(result: string | null, calls: string[] = []): HasMenuPopup & { calls: string[] } {
22
32
  return {
23
- setApplicationMenu: () => true,
24
- popupContextMenu: () => Promise.resolve(null),
25
- subscribeSelect: () => () => {},
26
- ...overrides,
33
+ calls,
34
+ menu: {
35
+ popup: {
36
+ popup(_items: readonly MenuItemTemplate[], x: number, y: number): Promise<string | null> {
37
+ calls.push(`popup@${x},${y}`);
38
+ return Promise.resolve(result);
39
+ },
40
+ },
41
+ },
42
+ };
43
+ }
44
+
45
+ function applicationHost(accepted: boolean, seen: MenuItemTemplate[][] = []): HasMenuApplication {
46
+ return {
47
+ menu: {
48
+ application: {
49
+ setApplicationMenu(items: readonly MenuItemTemplate[]): boolean {
50
+ seen.push([...items]);
51
+ return accepted;
52
+ },
53
+ },
54
+ },
55
+ };
56
+ }
57
+
58
+ function selectHost(): HasMenuSelect & { emit(id: string): void; subscriberCount(): number } {
59
+ const listeners = new Set<(id: string) => void>();
60
+ return {
61
+ emit(id: string): void {
62
+ for (const listener of listeners) listener(id);
63
+ },
64
+ menu: {
65
+ select: {
66
+ subscribe(listener: (id: string) => void): () => void {
67
+ listeners.add(listener);
68
+ return () => {
69
+ listeners.delete(listener);
70
+ };
71
+ },
72
+ },
73
+ },
74
+ subscriberCount(): number {
75
+ return listeners.size;
76
+ },
77
+ };
78
+ }
79
+
80
+ function highlightHost(): HasMenuHighlight & { emit(id: string): void } {
81
+ const listeners = new Set<(id: string) => void>();
82
+ return {
83
+ emit(id: string): void {
84
+ for (const listener of listeners) listener(id);
85
+ },
86
+ menu: {
87
+ highlight: {
88
+ subscribe(listener: (id: string) => void): () => void {
89
+ listeners.add(listener);
90
+ return () => {
91
+ listeners.delete(listener);
92
+ };
93
+ },
94
+ },
95
+ },
27
96
  };
28
97
  }
29
98
 
99
+ describe('attachMenuHighlight', () => {
100
+ it('delivers highlight ids into the entity signal', () => {
101
+ const host = highlightHost();
102
+ const highlight = createMenuHighlight();
103
+ const seen: string[] = [];
104
+ connectSignal(highlight.onMenuItemHighlight, (id) => seen.push(id));
105
+ attachMenuHighlight(host, highlight);
106
+ host.emit('open');
107
+ expect(seen).toEqual(['open']);
108
+ });
109
+ });
110
+
111
+ describe('attachMenuSelect', () => {
112
+ // ★ FALSIFIER 3, first half — the select event fires while attached.
113
+ it('delivers selections into the entity signal', () => {
114
+ const host = selectHost();
115
+ const select = createMenuSelect();
116
+ const seen: string[] = [];
117
+ connectSignal(select.onMenuItemSelect, (id) => seen.push(id));
118
+ attachMenuSelect(host, select);
119
+ host.emit('save');
120
+ expect(seen).toEqual(['save']);
121
+ });
122
+
123
+ // Re-attaching must not leave the first subscription live, or one emit would arrive twice.
124
+ it('replaces its own subscription rather than stacking them', () => {
125
+ const host = selectHost();
126
+ const select = createMenuSelect();
127
+ const seen: string[] = [];
128
+ connectSignal(select.onMenuItemSelect, (id) => seen.push(id));
129
+ attachMenuSelect(host, select);
130
+ attachMenuSelect(host, select);
131
+ expect(host.subscriberCount()).toBe(1);
132
+ host.emit('save');
133
+ expect(seen).toEqual(['save']);
134
+ });
135
+ });
136
+
30
137
  describe('cloneMenuTemplate', () => {
31
138
  it('produces an equal but distinct tree', () => {
32
139
  const original = createMenuItemTemplate({
@@ -42,6 +149,16 @@ describe('cloneMenuTemplate', () => {
42
149
  });
43
150
  });
44
151
 
152
+ describe('createMenuHighlight', () => {
153
+ it('allocates an inert entity that delivers nothing until attached', () => {
154
+ const highlight = createMenuHighlight();
155
+ const seen: string[] = [];
156
+ connectSignal(highlight.onMenuItemHighlight, (id) => seen.push(id));
157
+ highlightHost().emit('never');
158
+ expect(seen).toEqual([]);
159
+ });
160
+ });
161
+
45
162
  describe('createMenuItemTemplate', () => {
46
163
  it('fills type and enabled defaults', () => {
47
164
  const item = createMenuItemTemplate({ id: 'copy', label: 'Copy' });
@@ -56,469 +173,191 @@ describe('createMenuItemTemplate', () => {
56
173
  });
57
174
  });
58
175
 
59
- describe('enableMenuSignals', () => {
60
- it('returns a stable instance across calls', () => {
61
- expect(enableMenuSignals()).toBe(enableMenuSignals());
176
+ describe('createMenuSelect', () => {
177
+ it('allocates an inert entity that delivers nothing until attached', () => {
178
+ const select = createMenuSelect();
179
+ const seen: string[] = [];
180
+ connectSignal(select.onMenuItemSelect, (id) => seen.push(id));
181
+ selectHost().emit('never');
182
+ expect(seen).toEqual([]);
62
183
  });
63
184
  });
64
185
 
65
- describe('explainMenuBackend', () => {
66
- afterEach(() => resetMenuBackendForTest());
67
-
68
- it('reports host-not-enabled when no backend is installed', () => {
69
- resetMenuBackendForTest();
70
- const explanation = explainMenuBackend();
71
- expect(explanation.layer).toBe('host-not-enabled');
72
- expect(explanation.conflict).toBe(false);
73
- expect(explanation.viability).toBe('unobserved');
74
- });
75
-
76
- it('reports custom layer when a custom backend is set', () => {
77
- setMenuBackend(fakeBackend());
78
- expect(explainMenuBackend().layer).toBe('custom');
79
- });
80
-
81
- it('reports host layer when a host backend is installed', () => {
82
- installMenuHostBackend(fakeBackend());
83
- expect(explainMenuBackend().layer).toBe('host');
84
- });
85
-
86
- it('reports conflict when two different host backends are installed', () => {
87
- installMenuHostBackend(fakeBackend());
88
- installMenuHostBackend(fakeBackend());
89
- expect(explainMenuBackend().conflict).toBe(true);
90
- });
186
+ describe('destroyMenuApplication', () => {
187
+ function applicationHostWith(provider: { destroy?: () => void; setApplicationMenu: () => boolean }) {
188
+ return { menu: { application: provider } };
189
+ }
91
190
 
92
- it('reports observed viability after observeMenuHostResult', () => {
93
- installMenuHostBackend(fakeBackend());
94
- observeMenuHostResult('popupContextMenu', true);
95
- const explanation = explainMenuBackend();
96
- expect(explanation.operation).toBe('popupContextMenu');
97
- expect(explanation.viability).toBe('available');
191
+ it('destroys each distinct provider exactly once, even when hosts alias one', () => {
192
+ let destroyed = 0;
193
+ const shared = { destroy: () => destroyed++, setApplicationMenu: () => true };
194
+ // ★ ALIAS SAFETY: two hosts, ONE provider object. Destroying it twice would clear a successor's menu.
195
+ destroyMenuApplication(applicationHostWith(shared), applicationHostWith(shared));
196
+ expect(destroyed).toBe(1);
197
+ });
198
+
199
+ it('never destroys an already-released provider a second time', () => {
200
+ let destroyed = 0;
201
+ const provider = { destroy: () => destroyed++, setApplicationMenu: () => true };
202
+ destroyMenuApplication(applicationHostWith(provider));
203
+ destroyMenuApplication(applicationHostWith(provider));
204
+ expect(destroyed).toBe(1);
205
+ });
206
+
207
+ // ★ ATTEMPT-ALL then rethrow: a throwing obligation must not strand its siblings.
208
+ it('attempts every provider and rethrows the first error after the siblings run', () => {
209
+ let secondDestroyed = false;
210
+ const failing = {
211
+ destroy: () => {
212
+ throw new Error('first failed');
213
+ },
214
+ setApplicationMenu: () => true,
215
+ };
216
+ const healthy = { destroy: () => (secondDestroyed = true), setApplicationMenu: () => true };
217
+ expect(() => destroyMenuApplication(applicationHostWith(failing), applicationHostWith(healthy))).toThrow(
218
+ 'first failed',
219
+ );
220
+ expect(secondDestroyed).toBe(true);
221
+ });
222
+
223
+ // ★ RETRY ONLY THE FAILURES: the thrower stays retained, the successes do not.
224
+ it('retries a failed obligation and leaves the succeeded one released', () => {
225
+ let attempts = 0;
226
+ let healthyDestroyed = 0;
227
+ const flaky = {
228
+ destroy: () => {
229
+ attempts++;
230
+ if (attempts === 1) throw new Error('transient');
231
+ },
232
+ setApplicationMenu: () => true,
233
+ };
234
+ const healthy = { destroy: () => healthyDestroyed++, setApplicationMenu: () => true };
235
+ expect(() => destroyMenuApplication(applicationHostWith(flaky), applicationHostWith(healthy))).toThrow();
236
+ expect(() => destroyMenuApplication(applicationHostWith(flaky), applicationHostWith(healthy))).not.toThrow();
237
+ expect(attempts).toBe(2);
238
+ expect(healthyDestroyed).toBe(1);
239
+ });
240
+
241
+ it('tolerates a provider that declares no destroy', () => {
242
+ expect(() => destroyMenuApplication(applicationHostWith({ setApplicationMenu: () => true }))).not.toThrow();
98
243
  });
99
244
  });
100
245
 
101
- describe('getMenuBackend', () => {
102
- afterEach(() => resetMenuBackendForTest());
103
-
104
- it('returns the sentinel when no backend is installed', () => {
105
- resetMenuBackendForTest();
106
- expect(getMenuBackend()).not.toBeNull();
246
+ describe('detachMenuHighlight', () => {
247
+ it('is safe on an entity that was never attached', () => {
248
+ expect(() => detachMenuHighlight(createMenuHighlight())).not.toThrow();
107
249
  });
108
250
  });
109
251
 
110
- describe('getMenuBackend sentinel', () => {
111
- afterEach(() => resetMenuBackendForTest());
112
-
113
- it('reports no native application menu', () => {
114
- resetMenuBackendForTest();
115
- const backend = getMenuBackend();
116
- expect(backend.setApplicationMenu([])).toBe(false);
117
- });
118
-
119
- it('returns an unsubscribe function from subscribeSelect', () => {
120
- resetMenuBackendForTest();
121
- const backend = getMenuBackend();
122
- expect(typeof backend.subscribeSelect(() => {})).toBe('function');
123
- });
124
-
125
- it('returns null from popupContextMenu', async () => {
126
- resetMenuBackendForTest();
127
- const backend = getMenuBackend();
128
- await expect(backend.popupContextMenu([], 0, 0)).resolves.toBeNull();
252
+ describe('detachMenuSelect', () => {
253
+ // ★ FALSIFIER 3, second half — after unsubscribe the event must NOT fire.
254
+ it('stops delivery and releases the provider subscription', () => {
255
+ const host = selectHost();
256
+ const select = createMenuSelect();
257
+ const seen: string[] = [];
258
+ connectSignal(select.onMenuItemSelect, (id) => seen.push(id));
259
+ attachMenuSelect(host, select);
260
+ host.emit('first');
261
+ detachMenuSelect(select);
262
+ host.emit('second');
263
+ expect(seen).toEqual(['first']);
264
+ expect(host.subscriberCount()).toBe(0);
265
+ });
266
+
267
+ // ★ ORIGIN-PINNED: detaching one entity must not end another entity's subscription, even on one host.
268
+ it('ends only its own subscription', () => {
269
+ const host = selectHost();
270
+ const kept = createMenuSelect();
271
+ const dropped = createMenuSelect();
272
+ const keptSeen: string[] = [];
273
+ connectSignal(kept.onMenuItemSelect, (id) => keptSeen.push(id));
274
+ attachMenuSelect(host, kept);
275
+ attachMenuSelect(host, dropped);
276
+ detachMenuSelect(dropped);
277
+ host.emit('still-here');
278
+ expect(keptSeen).toEqual(['still-here']);
129
279
  });
130
280
  });
131
281
 
132
- describe('getMenuSignals', () => {
133
- it('returns the active signal group once enabled', () => {
134
- const signals = enableMenuSignals();
135
- expect(getMenuSignals()).toBe(signals);
136
- });
137
- });
138
-
139
- describe('installMenuHostBackend', () => {
140
- afterEach(() => resetMenuBackendForTest());
141
-
142
- it('installs a host backend that getMenuBackend returns', () => {
143
- const backend = fakeBackend();
144
- installMenuHostBackend(backend);
145
- expect(getMenuBackend()).toBe(backend);
146
- });
147
-
148
- it('is first-host-wins: a second different backend sets conflict', () => {
149
- const first = fakeBackend();
150
- const second = fakeBackend();
151
- installMenuHostBackend(first);
152
- installMenuHostBackend(second);
153
- expect(getMenuBackend()).toBe(first);
154
- expect(explainMenuBackend().conflict).toBe(true);
155
- });
156
-
157
- it('does not set conflict when the same backend is installed twice', () => {
158
- const backend = fakeBackend();
159
- installMenuHostBackend(backend);
160
- installMenuHostBackend(backend);
161
- expect(explainMenuBackend().conflict).toBe(false);
282
+ describe('disposeMenuHighlight', () => {
283
+ // Same contract as disposeMenuSelect: detach the provider subscription AND clear the entity's own
284
+ // listeners, so a leak in either path is visible here.
285
+ it('detaches and clears listeners', () => {
286
+ const host = highlightHost();
287
+ const highlight = createMenuHighlight();
288
+ const seen: string[] = [];
289
+ connectSignal(highlight.onMenuItemHighlight, (id) => seen.push(id));
290
+ attachMenuHighlight(host, highlight);
291
+ disposeMenuHighlight(highlight);
292
+ host.emit('after-dispose');
293
+ expect(seen).toEqual([]);
162
294
  });
163
295
  });
164
296
 
165
- describe('observeMenuHostResult', () => {
166
- afterEach(() => resetMenuBackendForTest());
167
-
168
- it('records a successful observation', () => {
169
- installMenuHostBackend(fakeBackend());
170
- observeMenuHostResult('popupContextMenu', true);
171
- const explanation = explainMenuBackend();
172
- expect(explanation.operation).toBe('popupContextMenu');
173
- expect(explanation.viability).toBe('available');
174
- });
175
-
176
- it('records a failed observation', () => {
177
- installMenuHostBackend(fakeBackend());
178
- observeMenuHostResult('popupContextMenu', false);
179
- expect(explainMenuBackend().viability).toBe('runtime-api-unavailable');
297
+ describe('disposeMenuSelect', () => {
298
+ // The signal path is proven INDEPENDENTLY of the subscription path: after dispose, both the provider
299
+ // subscription and the entity's listeners are gone, so a leak in either one is visible here.
300
+ it('detaches and clears listeners', () => {
301
+ const host = selectHost();
302
+ const select = createMenuSelect();
303
+ const seen: string[] = [];
304
+ connectSignal(select.onMenuItemSelect, (id) => seen.push(id));
305
+ attachMenuSelect(host, select);
306
+ disposeMenuSelect(select);
307
+ host.emit('after-dispose');
308
+ expect(seen).toEqual([]);
309
+ expect(host.subscriberCount()).toBe(0);
180
310
  });
181
311
  });
182
312
 
183
- describe('onMenuSelect', () => {
184
- afterEach(() => resetMenuBackendForTest());
185
-
186
- it('delivers the selected id from the backend', () => {
187
- let captured: ((id: string) => void) | null = null;
188
- setMenuBackend(
189
- fakeBackend({
190
- subscribeSelect: (l) => {
191
- captured = l;
192
- return () => {};
193
- },
194
- }),
195
- );
196
- const received: string[] = [];
197
- onMenuSelect((id) => received.push(id));
198
- captured!('save');
199
- expect(received).toEqual(['save']);
313
+ describe('enableMenuSignals', () => {
314
+ it('returns the same group on repeated calls', () => {
315
+ expect(enableMenuSignals()).toBe(enableMenuSignals());
200
316
  });
201
317
  });
202
318
 
203
- describe('resetMenuBackendForTest', () => {
204
- it('clears all backend slots', () => {
205
- const backend = fakeBackend();
206
- setMenuBackend(backend);
207
- installMenuHostBackend(fakeBackend());
208
- observeMenuHostResult('popupContextMenu', true);
209
- resetMenuBackendForTest();
210
- expect(getMenuBackend()).not.toBe(backend);
211
- expect(explainMenuBackend().layer).toBe('host-not-enabled');
212
- expect(explainMenuBackend().conflict).toBe(false);
213
- expect(explainMenuBackend().viability).toBe('unobserved');
319
+ describe('getMenuSignals', () => {
320
+ it('returns the enabled group', () => {
321
+ const signals = enableMenuSignals();
322
+ expect(getMenuSignals()).toBe(signals);
214
323
  });
215
324
  });
216
325
 
217
326
  describe('setApplicationMenu', () => {
218
- afterEach(() => resetMenuBackendForTest());
219
-
220
- it('delegates to the active backend', () => {
221
- let installed = 0;
222
- setMenuBackend(
223
- fakeBackend({
224
- setApplicationMenu: (i) => {
225
- installed = i.length;
226
- return true;
227
- },
228
- }),
229
- );
230
- expect(setApplicationMenu([{ id: 'a' }])).toBe(true);
231
- expect(installed).toBe(1);
327
+ // ★ FALSIFIER 2 — assert the RETURN VALUE and the DELIVERED ITEMS, never mere operation presence.
328
+ // A structural "does it have setApplicationMenu" probe passed on the old web stub, which answered
329
+ // false unconditionally; only the delivered items distinguish a real install.
330
+ it('reports the provider result and delivers the items', () => {
331
+ const seen: MenuItemTemplate[][] = [];
332
+ const items = [{ id: 'quit', label: 'Quit' }];
333
+ expect(setApplicationMenu(applicationHost(true, seen), items)).toBe(true);
334
+ expect(seen).toEqual([items]);
232
335
  });
233
- });
234
-
235
- describe('setMenuBackend', () => {
236
- afterEach(() => resetMenuBackendForTest());
237
336
 
238
- it('installs a custom backend and reverts to the sentinel on null', () => {
239
- const backend = fakeBackend();
240
- setMenuBackend(backend);
241
- expect(getMenuBackend()).toBe(backend);
242
- setMenuBackend(null);
243
- expect(getMenuBackend()).not.toBe(backend);
337
+ it('reports a refused install as false', () => {
338
+ expect(setApplicationMenu(applicationHost(false), [{ id: 'quit', label: 'Quit' }])).toBe(false);
244
339
  });
245
340
  });
246
341
 
247
342
  describe('showContextMenu', () => {
248
- afterEach(() => resetMenuBackendForTest());
249
-
250
- it('resolves the id returned by the backend popup', async () => {
251
- setMenuBackend(fakeBackend({ popupContextMenu: () => Promise.resolve('copy') }));
252
- await expect(showContextMenu([], 0, 0)).resolves.toBe('copy');
253
- });
254
-
255
- // The rest of this block exercises the real web renderer through the default backend, in jsdom.
256
- describe('web renderer', () => {
257
- const menuItems: MenuItemTemplate[] = [
258
- { id: 'open', label: 'Open' },
259
- { id: 'disabled', label: 'Disabled', enabled: false },
260
- { type: 'separator' },
261
- { id: 'recent', label: 'Recent', submenu: [{ id: 'file1', label: 'File 1' }], type: 'submenu' },
262
- { id: 'quit', label: 'Quit' },
263
- ];
264
-
265
- beforeEach(() => {
266
- resetMenuBackendForTest();
267
- setMenuBackend(fakeBackend({ popupContextMenu: showWebContextMenu }));
268
- document.body.innerHTML = '';
269
- });
270
-
271
- function press(key: string): void {
272
- document.dispatchEvent(new KeyboardEvent('keydown', { key }));
273
- }
274
-
275
- function renderedMenu(): HTMLUListElement {
276
- return document.body.querySelector('ul') as HTMLUListElement;
277
- }
278
-
279
- it('resolves with the clicked item id', async () => {
280
- const promise = showContextMenu(menuItems, 10, 10);
281
- renderedMenu().querySelector<HTMLElement>('li[data-item-id="quit"]')!.click();
282
- await expect(promise).resolves.toBe('quit');
283
- });
284
-
285
- it('resolves null when dismissed with Escape', async () => {
286
- const promise = showContextMenu(menuItems, 10, 10);
287
- press('Escape');
288
- await expect(promise).resolves.toBeNull();
289
- });
290
-
291
- it('removes its DOM once dismissed', async () => {
292
- const promise = showContextMenu(menuItems, 10, 10);
293
- expect(renderedMenu()).not.toBeNull();
294
- press('Escape');
295
- await promise;
296
- expect(renderedMenu()).toBeNull();
297
- });
298
-
299
- it('marks a disabled item unfocusable and gives it no click handler', async () => {
300
- const promise = showContextMenu(menuItems, 10, 10);
301
- const disabled = renderedMenu().querySelector<HTMLElement>('li[data-item-id="disabled"]')!;
302
- expect(disabled.getAttribute('data-enabled')).toBe('false');
303
-
304
- disabled.click();
305
- let settled = false;
306
- void promise.then(() => (settled = true));
307
- await Promise.resolve();
308
- expect(settled).toBe(false);
309
-
310
- press('Escape');
311
- await promise;
312
- });
313
-
314
- // Arrow travel must visit only the rows of this menu level. A submenu is a nested <ul> inside its
315
- // parent <li>, so a descendant query also matched every collapsed submenu row — display:none
316
- // entries that stole a keypress and could be selected unseen. Third ArrowDown lands on 'quit'
317
- // (open → recent → quit); before the fix it landed on the hidden 'file1'.
318
- it('skips the rows of a collapsed submenu when arrowing through the menu', async () => {
319
- const promise = showContextMenu(menuItems, 10, 10);
320
- press('ArrowDown');
321
- press('ArrowDown');
322
- press('ArrowDown');
323
- press('Enter');
324
- await expect(promise).resolves.toBe('quit');
325
- });
326
-
327
- // With nothing focused, ArrowUp enters at the bottom of the menu. -1 is a sentinel rather than a
328
- // position, so running it through the wrap arithmetic used to land one row short of the end.
329
- it('enters at the last item when the first key is ArrowUp', async () => {
330
- const promise = showContextMenu(menuItems, 10, 10);
331
- press('ArrowUp');
332
- press('Enter');
333
- await expect(promise).resolves.toBe('quit');
334
- });
335
-
336
- it('omits an item marked visible: false', async () => {
337
- const promise = showContextMenu(
338
- [
339
- { id: 'shown', label: 'Shown' },
340
- { id: 'hidden', label: 'Hidden', visible: false },
341
- ],
342
- 0,
343
- 0,
344
- );
345
- const menu = renderedMenu();
346
- expect(menu.querySelector('li[data-item-id="hidden"]')).toBeNull();
347
- expect(menu.querySelector('li[data-item-id="shown"]')).not.toBeNull();
348
- press('Escape');
349
- await promise;
350
- });
351
-
352
- // A hidden item must not merely be styled away: if it were still in the DOM it would keep its
353
- // place in arrow travel, which is the bug `visible` exists to avoid.
354
- it('does not give a hidden item a place in arrow travel', async () => {
355
- const promise = showContextMenu(
356
- [
357
- { id: 'first', label: 'First' },
358
- { id: 'hidden', label: 'Hidden', visible: false },
359
- { id: 'last', label: 'Last' },
360
- ],
361
- 0,
362
- 0,
363
- );
364
- press('ArrowDown');
365
- press('ArrowDown');
366
- press('Enter');
367
- await expect(promise).resolves.toBe('last');
368
- });
369
-
370
- it('renders a tooltip and a sublabel when supplied', async () => {
371
- const promise = showContextMenu(
372
- [{ id: 'save', label: 'Save', sublabel: 'All files', toolTip: 'Save now' }],
373
- 0,
374
- 0,
375
- );
376
- const li = renderedMenu().querySelector<HTMLElement>('li[data-item-id="save"]')!;
377
- expect(li.title).toBe('Save now');
378
- expect(li.textContent).toContain('All files');
379
- press('Escape');
380
- await promise;
381
- });
382
-
383
- it('draws a radio dot and a checkbox tick from the item type', async () => {
384
- const promise = showContextMenu(
385
- [
386
- { id: 'r', label: 'Radio', type: 'radio', checked: true },
387
- { id: 'c', label: 'Check', type: 'checkbox', checked: true },
388
- ],
389
- 0,
390
- 0,
391
- );
392
- const menu = renderedMenu();
393
- expect(menu.querySelector<HTMLElement>('li[data-item-id="r"]')!.textContent).toContain('●');
394
- expect(menu.querySelector<HTMLElement>('li[data-item-id="c"]')!.textContent).toContain('✓');
395
- press('Escape');
396
- await promise;
397
- });
398
-
399
- it('resolves null when the backdrop is clicked', async () => {
400
- const promise = showContextMenu(menuItems, 10, 10);
401
- const overlay = document.body.querySelector<HTMLElement>('div')!;
402
- overlay.click();
403
- await expect(promise).resolves.toBeNull();
404
- });
405
- });
406
- });
407
-
408
- describe('showWebContextMenu', () => {
409
- afterEach(() => {
410
- document.body.replaceChildren();
411
- vi.restoreAllMocks();
412
- });
413
-
414
- function getRootMenu(): HTMLUListElement {
415
- const menu = document.body.querySelector('ul');
416
- expect(menu).not.toBeNull();
417
- return menu as HTMLUListElement;
418
- }
419
-
420
- function getOverlay(): HTMLDivElement {
421
- const overlay = document.body.querySelector('div');
422
- expect(overlay).not.toBeNull();
423
- return overlay as HTMLDivElement;
424
- }
425
-
426
- function press(key: string): void {
427
- document.dispatchEvent(new KeyboardEvent('keydown', { key }));
428
- }
429
-
430
- it('renders separators, checked kinds, accelerators, and disabled items', async () => {
431
- const promise = showWebContextMenu(
432
- [
433
- { id: 'checked', label: 'Checked', type: 'checkbox', checked: true },
434
- { id: 'chosen', label: 'Chosen', type: 'radio', checked: true },
435
- { type: 'separator' },
436
- { id: 'save', label: 'Save', accelerator: 'Ctrl+S' },
437
- { id: 'disabled', label: 'Disabled', enabled: false },
438
- ],
439
- 10,
440
- 20,
441
- );
442
- const items = getRootMenu().querySelectorAll(':scope > li');
443
- expect(items).toHaveLength(5);
444
- expect(items[0].textContent).toBe('✓Checked');
445
- expect(items[1].textContent).toBe('●Chosen');
446
- expect(items[2].getAttribute('data-enabled')).toBeNull();
447
- expect(items[3].textContent).toBe('SaveCtrl+S');
448
- expect(items[4].getAttribute('data-enabled')).toBe('false');
449
-
450
- let settled = false;
451
- void promise.then(() => {
452
- settled = true;
453
- });
454
- items[4].dispatchEvent(new MouseEvent('click', { bubbles: true }));
455
- await Promise.resolve();
456
- expect(settled).toBe(false);
457
- getOverlay().click();
458
- await expect(promise).resolves.toBeNull();
459
- });
460
-
461
- it('selects enabled items by click and dismisses on outside click', async () => {
462
- const selected = showWebContextMenu([{ id: 'copy', label: 'Copy' }], 0, 0);
463
- getRootMenu().querySelector<HTMLElement>('li')!.click();
464
- await expect(selected).resolves.toBe('copy');
465
- expect(document.body.querySelector('ul')).toBeNull();
466
-
467
- const dismissed = showWebContextMenu([{ id: 'paste', label: 'Paste' }], 0, 0);
468
- getOverlay().click();
469
- await expect(dismissed).resolves.toBeNull();
470
- });
471
-
472
- it('wraps keyboard focus and selects with Enter or Space', async () => {
473
- const items = [
474
- { id: 'first', label: 'First' },
475
- { id: 'disabled', label: 'Disabled', enabled: false },
476
- { id: 'last', label: 'Last' },
477
- ];
478
-
479
- const enterSelection = showWebContextMenu(items, 0, 0);
480
- press('ArrowUp');
481
- expect(getRootMenu().querySelector('[data-focused="true"]')?.getAttribute('data-item-id')).toBe('last');
482
- press('Enter');
483
- await expect(enterSelection).resolves.toBe('last');
484
-
485
- const spaceSelection = showWebContextMenu(items, 0, 0);
486
- press('ArrowDown');
487
- press('ArrowDown');
488
- press('ArrowDown');
489
- expect(getRootMenu().querySelector('[data-focused="true"]')?.getAttribute('data-item-id')).toBe('first');
490
- press(' ');
491
- await expect(spaceSelection).resolves.toBe('first');
492
- });
493
-
494
- it('dismisses on Escape', async () => {
495
- const promise = showWebContextMenu([{ id: 'copy', label: 'Copy' }], 0, 0);
496
- press('Escape');
497
- await expect(promise).resolves.toBeNull();
498
- });
499
-
500
- it('opens a submenu on hover and resolves a child selection', async () => {
501
- const promise = showWebContextMenu(
502
- [{ id: 'file', label: 'File', type: 'submenu', submenu: [{ id: 'open', label: 'Open' }] }],
503
- 0,
504
- 0,
505
- );
506
- const parent = getRootMenu().querySelector<HTMLElement>(':scope > li')!;
507
- const submenu = parent.querySelector<HTMLElement>('ul')!;
508
- expect(submenu.style.display).toBe('none');
509
- parent.dispatchEvent(new MouseEvent('mouseenter'));
510
- expect(submenu.style.display).toBe('block');
511
- submenu.querySelector<HTMLElement>('li')!.click();
512
- await expect(promise).resolves.toBe('open');
513
- });
514
-
515
- it('clamps a menu that overflows the viewport', async () => {
516
- vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(new DOMRect(1900, 1900, 100, 100));
517
- const promise = showWebContextMenu([{ id: 'copy', label: 'Copy' }], 40, 30);
518
- expect(getRootMenu().style.left).toBe('0px');
519
- expect(getRootMenu().style.top).toBe('0px');
520
- getOverlay().click();
521
- await promise;
343
+ // ★ FALSIFIER 1 — two hosts live at once, each serving its own popup. Under the ambient model there
344
+ // was exactly one answer per process, so this assertion could not be written at all.
345
+ it('routes each call to the host it was given', async () => {
346
+ const first = popupHost('from-first');
347
+ const second = popupHost('from-second');
348
+ await expect(showContextMenu(first, [], 1, 2)).resolves.toBe('from-first');
349
+ await expect(showContextMenu(second, [], 3, 4)).resolves.toBe('from-second');
350
+ expect(first.calls).toEqual(['popup@1,2']);
351
+ expect(second.calls).toEqual(['popup@3,4']);
352
+ });
353
+
354
+ it('emits the core open/close dispatcher signals around the call', async () => {
355
+ const signals = enableMenuSignals();
356
+ const order: string[] = [];
357
+ connectSignal(signals.onContextMenuOpen, () => order.push('open'));
358
+ connectSignal(signals.onContextMenuClose, () => order.push('close'));
359
+ await showContextMenu(popupHost('x'), [], 0, 0);
360
+ expect(order).toEqual(['open', 'close']);
522
361
  });
523
362
  });
524
363