import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import { createRequire } from 'node:module'; const { readSource } = createRequire(import.meta.url)('./test-fixtures/sources.js'); const read = file => readFileSync(new URL(file, import.meta.url), 'utf8'); const qml = read('SurfaceManager.qml'); const dismissed = []; let cancellations = 0; // Entry lifecycle signals in emission order, as `:`. const lifecycle = []; const entry = name => ({ name, // A registry entry hears `dismissed` whenever its popup closes or is replaced. dismissed() { if (name === 'power') cancellations++; lifecycle.push(`dismissed:${name}`); }, // ...and `opening` whenever the host opens it, switches to it, or reopens it. opening() { lifecycle.push(`opening:${name}:${s.popupName}`); }, }); const entries = Object.fromEntries(['audio', 'clipboard', 'power', 'vault'].map(name => [name, entry(name)])); const s = vm.createContext({ popupOpen: false, popupName: '', operationId: 0, niriService: { focusedWindow: 42 }, returnWindowId: null, registry: { popups: [], popup: name => entries[name] || null }, dismissing: name => dismissed.push(name), openTimer: { stop() {}, restart() {} }, DiagnosticData: { nextOperationId: id => id + 1, transition: () => ({}) }, console: { info() {} }, Qt: { rect: (x, y, width, height) => ({ x, y, width, height }) }, }); s.root = s; vm.runInContext(qml.slice(qml.indexOf(' function dismissTask('), qml.indexOf(' Timer {')).replaceAll('anchor: rect', 'anchor'), s); const anchor = { x: 0, y: 0, width: 34, height: 34 }; s.popupState = () => s.popupName; s.openPopup('clipboard', anchor, ''); assert.equal(s.returnWindowId, 42); s.niriService.focusedWindow = null; s.openPopup('power', anchor, ''); assert.equal(s.returnWindowId, 42); assert.deepEqual(dismissed, ['clipboard']); s.openPopup('audio', anchor, ''); assert.equal(cancellations, 1); for (const reason of ['outside', 'escape-key', 'bar-toggle', 'popup-closed']) { s.openPopup('power', anchor, ''); s.closePopup(reason); } assert.equal(cancellations, 5); s.closePopup('outside'); assert.equal(cancellations, 5, 'idempotent close does not cancel twice'); // `opening` fires before the popup becomes active, on a fresh open, a switch // (after the previous popup's `dismissed`) and a repeated open; never on close. lifecycle.length = 0; s.openPopup('clipboard', anchor, ''); s.openPopup('vault', anchor, ''); assert.deepEqual(lifecycle, ['opening:clipboard:', 'dismissed:clipboard', 'opening:vault:clipboard'], 'switching dismisses the previous popup before opening the next'); s.closePopup('bar-toggle'); assert.deepEqual(lifecycle, ['opening:clipboard:', 'dismissed:clipboard', 'opening:vault:clipboard', 'dismissed:vault'], 'close never emits opening'); // Only registry popups open: any other name leaves the state untouched. s.openPopup('unregistered', anchor, ''); assert.equal(s.popupOpen, false, 'an unregistered name never opens'); assert.equal(s.popupName, ''); lifecycle.length = 0; s.openPopup('vault', anchor, ''); s.openPopup('vault', anchor, ''); s.openPopup('power', anchor, ''); s.openPopup('vault', anchor, ''); assert.deepEqual(lifecycle, ['opening:vault:', 'opening:vault:vault', 'dismissed:vault', 'opening:power:vault', 'dismissed:power', 'opening:vault:power']); s.closePopup('escape-key'); assert.equal(lifecycle.at(-1), 'dismissed:vault'); assert.equal(lifecycle.filter(event => event.startsWith('opening:')).length, 4); // A registry panel declaring `sessionState` gets the host's live session object // and is never copied by name; other panels keep copy-by-name retention. const hostSource = read('PopupHost.qml'); const hostFunction = name => { const begin = hostSource.indexOf(` function ${name}(`); const finish = hostSource.indexOf('\n }\n', begin) + 7; assert(begin >= 0 && finish > begin, `PopupHost.${name} exists`); return hostSource.slice(begin, finish).replace(/(\w+): (?:string|var)\b/g, '$1').replace(/\): void \{/, ') {'); }; const sessionEntry = { name: 'search', retainedState: { query: '', scrollY: 0 } }; const h = vm.createContext({ registry: { popup: name => (name === sessionEntry.name ? sessionEntry : null) }, surfaces: { panelStates: { search: { query: 'kept', scrollY: 4 }, legacy: { query: 'legacy' } } }, }); h.root = h; vm.runInContext(hostFunction('copyRetained') + hostFunction('bindSession'), h); const sessionPanel = { sessionState: { query: '', scrollY: 0 }, query: '' }; h.bindSession('search', sessionPanel); assert.equal(sessionPanel.sessionState, h.surfaces.panelStates.search, 'the panel holds the host object itself'); h.copyRetained('search', { query: 'other' }, sessionPanel); h.copyRetained('search', sessionPanel, h.surfaces.panelStates.search); assert.equal(h.surfaces.panelStates.search.query, 'kept', 'no copy-by-name for a session panel'); const legacyPanel = { sessionState: {} }; h.bindSession('legacy', legacyPanel); assert.deepEqual(legacyPanel.sessionState, {}, 'only registry panels are bound'); const plainPanel = { query: 'typed' }; h.bindSession('search', plainPanel); assert.equal(plainPanel.sessionState, undefined, 'panels without sessionState are untouched'); const saved = { query: '' }; h.copyRetained('search', plainPanel, saved); assert.equal(saved.query, 'typed', 'plain panels keep copy-by-name retention'); // A registry panel declaring `closeRequested(reason)` closes its own popup through // the host, only while it is the open one; other panels are never connected. const closes = []; h.surfaces.popupOpen = true; h.surfaces.popupName = 'search'; h.surfaces.closePopup = reason => { closes.push(reason); h.surfaces.popupOpen = false; }; vm.runInContext(hostFunction('bindClose'), h); const signal = () => { const handlers = []; return Object.assign(reason => handlers.forEach(handler => handler(reason)), { connect: handler => handlers.push(handler) }); }; const closingPanel = { closeRequested: signal() }; h.bindClose('search', closingPanel); closingPanel.closeRequested('launched'); assert.deepEqual(closes, ['launched'], 'the host closes with the panel reason'); closingPanel.closeRequested('again'); assert.deepEqual(closes, ['launched'], 'a closed popup is not closed again'); h.surfaces.popupOpen = true; h.surfaces.popupName = 'other'; closingPanel.closeRequested('stale'); assert.deepEqual(closes, ['launched'], 'a panel never closes another open popup'); const legacyClosing = { closeRequested: signal() }; h.bindClose('legacy', legacyClosing); h.surfaces.popupName = 'legacy'; legacyClosing.closeRequested('legacy'); assert.deepEqual(closes, ['launched'], 'only registry panels are connected'); h.bindClose('search', plainPanel); assert.equal(plainPanel.closeRequested, undefined, 'panels without closeRequested are untouched'); const service = readSource('Clipboard.qml'); assert.match(service, /target: root\.niriService\s*function onFocusedWindowChanged\(\)\s*\{\s*root\.checkPasteFocus\(\);/, 'focus stream triggers paste checks'); const typed = []; let timerStarts = 0; let closed = 0; const c = vm.createContext({ pendingPasteId: '', pasteWindowId: null, pasteAttempts: 0, focusReply: '', lastAction: {}, surfaces: { popupOpen: true, returnWindowId: 42, closePopup() { this.popupOpen = false; closed++; } }, niriService: { focusedWindow: 42, windowById: id => id === 42 ? { id: 42, app_id: 'fixture.editor', title: 'private title' } : null }, rawRowById: id => id === 'item' ? { body: 'synthetic text' } : null, stateJson: () => '{}', textProcess: { createObject: (_, props) => typed.push(props) }, pasteFocusTimer: { start() { timerStarts++; }, restart() { timerStarts++; }, stop() {} }, }); c.root = c; vm.runInContext(service.slice(service.indexOf(' function paste('), service.indexOf(' function deleteRow(')), c); c.paste('missing'); assert.equal(c.lastAction.accepted, false); assert.equal(timerStarts, 0); c.niriService.focusedWindow = null; c.paste('item'); assert.equal(closed, 1); assert.equal(c.lastAction.pending, true); assert.equal(c.lastAction.target, 'fixture.editor', 'a pending paste names its destination app, never its title'); assert.equal(typed.length, 0, 'never type before compositor focus proof'); c.paste('item'); assert.equal(closed, 1, 'one pending paste'); c.checkPasteFocus(); assert.equal(typed.length, 0); c.niriService.focusedWindow = 42; c.checkPasteFocus(); assert.deepEqual(typed.map(x => [Array.from(x.command), x.payload]), [[['/usr/bin/wtype', '-'], 'synthetic text']]); assert.equal(c.pendingPasteId, ''); assert.equal(c.lastAction.pending, false); c.checkPasteFocus(0); assert.equal(typed.length, 1, 'completion is idempotent'); c.niriService.focusedWindow = null; c.surfaces.popupOpen = true; c.paste('item'); c.niriService.focusedWindow = 99; c.checkPasteFocus(); assert.equal(c.lastAction.error, 'paste destination lost focus'); assert.equal(typed.length, 1); c.niriService.focusedWindow = null; c.surfaces.popupOpen = true; c.paste('item'); c.surfaces.popupOpen = true; c.checkPasteFocus(); assert.equal(c.pendingPasteId, ''); assert.equal(typed.length, 1, 'new popup cancels pending typing'); c.surfaces.popupOpen = true; c.paste('item'); c.finishPaste('paste destination lost focus'); assert.equal(c.pendingPasteId, '', 'focus deadline clears pending paste'); assert.equal(typed.length, 1); const util = vm.createContext({}); vm.runInContext(read('Util.js').replace(/^\.pragma library\s*/, ''), util); const viewport = { contentItem: {}, contentY: 100, contentHeight: 500, height: 120 }; const item = { height: 30, mapToItem: () => ({ y: 300 }) }; util.revealIn(item, viewport); assert.equal(viewport.contentY, 210); item.mapToItem = () => ({ y: 50 }); util.revealIn(item, viewport); assert.equal(viewport.contentY, 50); item.mapToItem = () => ({ y: 70 }); util.revealIn(item, viewport); assert.equal(viewport.contentY, 50, 'visible focus does not move the viewport'); console.log('popup-lifecycle.test.mjs: ALL PASS');