fix "x"
This commit is contained in:
240
test/modal-close.test.js
Normal file
240
test/modal-close.test.js
Normal file
@@ -0,0 +1,240 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const appSource = fs.readFileSync(path.join(__dirname, '../public/js/app.js'), 'utf8');
|
||||
|
||||
// A small DOM fixture lets the actual event handler and cleanup methods run
|
||||
// without starting authentication, network requests, or the application itself.
|
||||
function createFixture() {
|
||||
const elements = [];
|
||||
const listeners = new Map();
|
||||
class Element {
|
||||
constructor({ id = '', classes = [], dataset = {}, parent = null } = {}) {
|
||||
this.id = id;
|
||||
this.dataset = dataset;
|
||||
this.parentElement = parent;
|
||||
this.children = [];
|
||||
this.value = '';
|
||||
this.isConnected = true;
|
||||
const names = new Set(classes);
|
||||
this.classList = {
|
||||
contains: name => names.has(name),
|
||||
add: (...added) => added.forEach(name => names.add(name)),
|
||||
remove: (...removed) => removed.forEach(name => names.delete(name))
|
||||
};
|
||||
if (parent) parent.children.push(this);
|
||||
elements.push(this);
|
||||
}
|
||||
matches(selector) {
|
||||
if (selector === '[data-close-modal]') return 'closeModal' in this.dataset;
|
||||
if (selector.startsWith('.')) {
|
||||
return selector.slice(1).split('.').every(name => this.classList.contains(name));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
closest(selector) {
|
||||
return this.matches(selector) ? this : this.parentElement?.closest(selector) || null;
|
||||
}
|
||||
getAttribute(name) {
|
||||
return name === 'data-close-modal' ? this.dataset.closeModal ?? null : null;
|
||||
}
|
||||
remove() {
|
||||
this.isConnected = false;
|
||||
this.children.forEach(child => child.remove());
|
||||
}
|
||||
set innerHTML(value) {
|
||||
assert.equal(value, '', 'The fixture only supports clearing an existing container');
|
||||
this.children.forEach(child => child.remove());
|
||||
this.children = [];
|
||||
}
|
||||
get innerHTML() {
|
||||
return this.children.length ? '<dialog />' : '';
|
||||
}
|
||||
}
|
||||
const document = {
|
||||
addEventListener(type, handler) {
|
||||
if (!listeners.has(type)) listeners.set(type, []);
|
||||
listeners.get(type).push(handler);
|
||||
},
|
||||
getElementById: id => elements.find(node => node.id === id && node.isConnected) || null,
|
||||
querySelectorAll: selector => elements.filter(node => node.isConnected && node.matches(selector)),
|
||||
contains: node => node.isConnected
|
||||
};
|
||||
const context = vm.createContext({
|
||||
document,
|
||||
Element,
|
||||
HTMLElement: Element,
|
||||
window: { fetch: async () => { throw new Error('Unexpected network request'); } },
|
||||
console
|
||||
});
|
||||
vm.runInContext(`${appSource}\napp = Object.create(AccountManager.prototype); globalThis.manager = app;`, context);
|
||||
const add = options => new Element(options);
|
||||
const modal = (id, parent) => add({ id, parent, classes: ['modal-backdrop', 'open'] });
|
||||
function dispatch(type, target, properties = {}) {
|
||||
const event = {
|
||||
target,
|
||||
defaultPrevented: false,
|
||||
preventDefault() { this.defaultPrevented = true; },
|
||||
stopPropagation() {},
|
||||
...properties
|
||||
};
|
||||
(listeners.get(type) || []).forEach(handler => handler(event));
|
||||
return event;
|
||||
}
|
||||
return { manager: context.manager, document, listeners, add, modal, dispatch };
|
||||
}
|
||||
|
||||
test('close buttons work after asynchronous modal insertion, including clicks on the icon', async () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
await Promise.resolve(); // modals.html is fetched after listeners are installed.
|
||||
const parent = fixture.modal('accountModal');
|
||||
const other = fixture.modal('assetModal');
|
||||
const button = fixture.add({ parent, dataset: { closeModal: 'accountModal' } });
|
||||
const icon = fixture.add({ parent: button });
|
||||
|
||||
const event = fixture.dispatch('click', icon);
|
||||
|
||||
assert.equal(parent.classList.contains('open'), false);
|
||||
assert.equal(other.classList.contains('open'), true);
|
||||
assert.equal(event.defaultPrevented, true);
|
||||
|
||||
parent.classList.add('open');
|
||||
fixture.dispatch('click', button);
|
||||
assert.equal(parent.classList.contains('open'), false);
|
||||
});
|
||||
|
||||
test('repeated setup installs one modal close handler', () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const target = fixture.add({ dataset: { closeModal: 'accountModal' } });
|
||||
const closed = [];
|
||||
fixture.manager.closeModal = id => closed.push(id);
|
||||
|
||||
fixture.dispatch('click', target);
|
||||
|
||||
assert.deepEqual(closed, ['accountModal']);
|
||||
assert.equal(fixture.listeners.get('click').length, 1);
|
||||
});
|
||||
|
||||
test('backdrop clicks close their dialog, while clicks inside the form leave it open', () => {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const modal = fixture.modal('assetModal');
|
||||
const other = fixture.modal('accountModal');
|
||||
const content = fixture.add({ parent: modal });
|
||||
const input = fixture.add({ parent: content });
|
||||
|
||||
fixture.dispatch('click', input);
|
||||
assert.equal(modal.classList.contains('open'), true);
|
||||
fixture.dispatch('click', modal);
|
||||
assert.equal(modal.classList.contains('open'), false);
|
||||
assert.equal(other.classList.contains('open'), true);
|
||||
});
|
||||
|
||||
test('canceling destructive confirmations resolves false exactly once', async () => {
|
||||
for (const [modalId, resolverField] of [
|
||||
['assetRequestDeleteConfirmModal', 'pendingAssetRequestDeleteConfirmResolver'],
|
||||
['bulkDeleteAssetsConfirmModal', 'pendingBulkAssetDeleteConfirmResolver']
|
||||
]) {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const modal = fixture.modal(modalId);
|
||||
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
|
||||
const resolutions = [];
|
||||
const pending = new Promise(resolve => {
|
||||
fixture.manager[resolverField] = value => {
|
||||
resolutions.push(value);
|
||||
resolve(value);
|
||||
};
|
||||
});
|
||||
|
||||
fixture.dispatch('click', button);
|
||||
fixture.dispatch('click', button);
|
||||
|
||||
assert.equal(await pending, false);
|
||||
assert.deepEqual(resolutions, [false]);
|
||||
assert.equal(fixture.manager[resolverField], undefined);
|
||||
assert.equal(modal.classList.contains('open'), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('closing consumable rejection and return dialogs clears pending input state', () => {
|
||||
const fixture = createFixture();
|
||||
const rejectModal = fixture.modal('consumableRequestRejectModal');
|
||||
const idInput = fixture.add({ id: 'consumableRequestRejectIdInput', parent: rejectModal });
|
||||
const reasonInput = fixture.add({ id: 'consumableRequestRejectReasonInput', parent: rejectModal });
|
||||
idInput.value = '42';
|
||||
reasonInput.value = 'Previous reason';
|
||||
fixture.manager.pendingConsumableRequestRejectId = 42;
|
||||
fixture.manager.closeModal(rejectModal.id);
|
||||
assert.equal(rejectModal.classList.contains('open'), false);
|
||||
assert.equal(idInput.value, '');
|
||||
assert.equal(reasonInput.value, '');
|
||||
assert.equal(fixture.manager.pendingConsumableRequestRejectId, undefined);
|
||||
|
||||
const returnModal = fixture.modal('consumableReturnModal');
|
||||
fixture.manager.pendingConsumableReturnHistoryId = 99;
|
||||
fixture.manager.closeModal(returnModal.id);
|
||||
assert.equal(returnModal.classList.contains('open'), false);
|
||||
assert.equal(fixture.manager.pendingConsumableReturnHistoryId, undefined);
|
||||
});
|
||||
|
||||
test('closing dynamic user, role, profile and detail dialogs clears their containers', () => {
|
||||
for (const modalId of ['userModal', 'roleModal', 'profileModal', 'userDetailsModal']) {
|
||||
const fixture = createFixture();
|
||||
fixture.manager.setupModalCloseListeners();
|
||||
const container = fixture.add({ id: `${modalId}Container` });
|
||||
const modal = fixture.modal(modalId, container);
|
||||
const button = fixture.add({ parent: modal, dataset: { closeModal: modalId } });
|
||||
|
||||
fixture.dispatch('click', button);
|
||||
|
||||
assert.equal(container.innerHTML, '', modalId);
|
||||
assert.equal(fixture.document.getElementById(modalId), null, modalId);
|
||||
}
|
||||
});
|
||||
|
||||
test('Escape closes dialogs through their cleanup handlers', () => {
|
||||
const fixture = createFixture();
|
||||
for (const method of [
|
||||
'updateAccountDisplay', 'setupAccountRowListeners', 'setupFilters',
|
||||
'setupResponsiveShell', 'closeMobileNav', 'closeNotificationPopover'
|
||||
]) fixture.manager[method] = () => {};
|
||||
fixture.manager.setupEventListeners();
|
||||
const confirmation = fixture.modal('bulkDeleteAssetsConfirmModal');
|
||||
let resolution;
|
||||
fixture.manager.pendingBulkAssetDeleteConfirmResolver = value => { resolution = value; };
|
||||
const container = fixture.add({ id: 'profileModalContainer' });
|
||||
fixture.modal('profileModal', container);
|
||||
const notification = fixture.modal('notificationComposerModal');
|
||||
|
||||
fixture.dispatch('keydown', null, { key: 'Escape' });
|
||||
|
||||
assert.equal(confirmation.classList.contains('open'), false);
|
||||
assert.equal(resolution, false);
|
||||
assert.equal(container.innerHTML, '');
|
||||
assert.equal(notification.isConnected, false);
|
||||
});
|
||||
|
||||
test('closing a missing modal is harmless', () => {
|
||||
const fixture = createFixture();
|
||||
assert.doesNotThrow(() => fixture.manager.closeModal('alreadyRemovedModal'));
|
||||
});
|
||||
|
||||
test('static and dynamic modal close controls avoid inline scripts and form submission', () => {
|
||||
for (const relativePath of ['public/modals.html', 'public/pages/index.html', 'public/js/app.js']) {
|
||||
const source = fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8');
|
||||
assert.doesNotMatch(source, /\bonclick\s*=\s*["'][^"']*\bclose\w*Modal\s*\(/i, relativePath);
|
||||
const closeButtons = [...source.matchAll(/<button\b[^>]*\bdata-close-modal\s*=\s*["'][^"']+["'][^>]*>/g)];
|
||||
if (relativePath !== 'public/pages/index.html') assert.ok(closeButtons.length > 0, relativePath);
|
||||
for (const [button] of closeButtons) {
|
||||
assert.match(button, /\btype\s*=\s*["']button["']/, `${relativePath}: ${button}`);
|
||||
assert.doesNotMatch(button, /\bonclick\s*=/, `${relativePath}: ${button}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -127,6 +127,7 @@ test('security headers and no-store API caching are enabled', async () => {
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(response.headers.get('content-security-policy') || '', /default-src 'self'/);
|
||||
assert.match(response.headers.get('content-security-policy') || '', /script-src-attr 'none'/);
|
||||
assert.equal(response.headers.get('x-powered-by'), null);
|
||||
assert.equal(response.headers.get('cache-control'), 'no-store');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user