Vue kit: UiDialog for the Data Library and scene sharing dialogs

UiDialog is a native <dialog> its owner opens and closes with open: true
opens it with showModal() (on mount, for one mounted open), false closes
it, and unmounting closes it. Each change is applied once the content has
rendered and then emitted as opened or closed, so the Data Library still
focuses its search field on open and returns focus to Browse on close.
Escape's cancel is prevented and emitted as dismiss; backdropDismiss makes
a click on the dialog itself a dismiss too, as the Data Library's was. When
the browser closes the dialog on its own while open is still true,
browserClose tells the owner, as the Data Library's close listener did;
closing on unmount reports nothing. A DOM without showModal() leaves it
closed. Attributes, classes, styles and listeners go to the dialog, and
element is exposed.

The two dialogs share no declarations, so there are no kit rules.
dialogs.test.mjs fails if a view writes a <dialog> by hand; the panels drawn
as role="dialog" are other controls.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-19 01:16:46 -08:00
1 parent 2d7b7be890
commit ec4a5b6afe
10 files changed
+388 -42

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
import { after, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { installVueDom } from '../../testSupport/vueDom.mjs';
let mount;
let nextTick;
let UiDialog;
let uninstall;
before(async () => {
uninstall = installVueDom();
({ mount } = await import('@vue/test-utils'));
({ nextTick } = await import('vue'));
UiDialog = (await import('./UiDialog.vue')).default;
});
after(() => uninstall());
/**
* A dialog that records what it emits, each with whether the dialog was open
* then; its content is a paragraph. One is mounted at a time.
*/
function dialog(props = {}, attrs = {}) {
const events = [];
const record = (name) => () =>
events.push(
name,
document.querySelector('dialog').open ? 'shown' : 'hidden',
);
const wrapper = mount(UiDialog, {
attachTo: document.body,
props: {
...props,
onDismiss: record('dismiss'),
onBrowserClose: record('browserClose'),
onOpened: record('opened'),
onClosed: record('closed'),
},
attrs,
slots: { default: '<p class="content">Words</p>' },
});
return { wrapper, events };
}
test('a dialog mounted closed stays closed until open', async () => {
const { wrapper, events } = dialog();
const element = wrapper.element;
assert.equal(element.tagName, 'DIALOG');
assert.equal(element.open, false);
assert.equal(wrapper.vm.element, element, 'element is exposed');
await wrapper.setProps({ open: true });
assert.equal(element.open, true);
assert.deepEqual(events, ['opened', 'shown']);
await wrapper.setProps({ open: false });
assert.equal(element.open, false);
assert.deepEqual(events, ['opened', 'shown', 'closed', 'hidden']);
wrapper.unmount();
});
test('a dialog mounted open opens modal on mount; unmounting closes it', async () => {
const modal = [];
const showModal = HTMLDialogElement.prototype.showModal;
HTMLDialogElement.prototype.showModal = function () {
modal.push(this);
return showModal.call(this);
};
try {
const { wrapper, events } = dialog({ open: true });
const element = wrapper.element;
assert.deepEqual(modal, [element]);
assert.equal(element.open, true);
assert.deepEqual(events, ['opened', 'shown']);
wrapper.unmount();
assert.equal(element.open, false);
assert.deepEqual(events, ['opened', 'shown'], 'no dismiss on unmount');
} finally {
HTMLDialogElement.prototype.showModal = showModal;
}
});
test('the open state follows the content: opened comes after it renders', async () => {
const { wrapper } = dialog();
let seen;
await wrapper.setProps({
open: true,
onOpened: () => {
seen = wrapper.element.querySelector('.content')?.textContent;
},
});
assert.equal(seen, 'Words');
wrapper.unmount();
});
test('Escape is prevented and emitted as dismiss; the owner decides', async () => {
const { wrapper, events } = dialog({ open: true });
events.length = 0;
const cancel = new Event('cancel', { cancelable: true });
wrapper.element.dispatchEvent(cancel);
assert.equal(cancel.defaultPrevented, true);
assert.equal(wrapper.element.open, true);
assert.deepEqual(events, ['dismiss', 'shown']);
wrapper.unmount();
});
test('a close the browser made while open is reported once; the owner’s is not', async () => {
const { wrapper, events } = dialog({ open: true });
events.length = 0;
wrapper.element.close();
assert.deepEqual(events, ['browserClose', 'hidden']);
events.length = 0;
// The owner then closes it too: nothing to close, closed is still emitted.
await wrapper.setProps({ open: false });
assert.deepEqual(events, ['closed', 'hidden']);
await wrapper.setProps({ open: true });
events.length = 0;
await wrapper.setProps({ open: false });
assert.deepEqual(events, ['closed', 'hidden'], 'no browserClose');
wrapper.unmount();
});
test('a backdrop click dismisses only when asked, and only on the dialog', async () => {
const plain = dialog({ open: true });
plain.events.length = 0;
plain.wrapper.element.click();
assert.deepEqual(plain.events, []);
plain.wrapper.unmount();
const backdrop = dialog({ open: true, backdropDismiss: true });
backdrop.events.length = 0;
backdrop.wrapper.get('.content').element.click();
assert.deepEqual(backdrop.events, [], 'a click inside is content');
backdrop.wrapper.element.click();
assert.deepEqual(backdrop.events, ['dismiss', 'shown']);
backdrop.wrapper.unmount();
});
test('attributes, classes, styles and listeners pass through to the dialog', async () => {
const clicks = [];
const { wrapper } = dialog(
{},
{
id: 'library',
class: 'library-dialog',
style: { width: '40px' },
'aria-label': 'Library',
'data-panel-surface': '',
onClick: () => clicks.push('click'),
},
);
const element = wrapper.element;
assert.equal(element.id, 'library');
assert.ok(element.classList.contains('library-dialog'));
assert.equal(element.style.width, '40px');
assert.equal(element.getAttribute('aria-label'), 'Library');
assert.equal(element.getAttribute('data-panel-surface'), '');
element.click();
assert.deepEqual(clicks, ['click']);
wrapper.unmount();
});
test('a DOM without showModal leaves the dialog closed rather than failing', async () => {
const showModal = HTMLDialogElement.prototype.showModal;
HTMLDialogElement.prototype.showModal = undefined;
try {
const { wrapper, events } = dialog({ open: true });
assert.equal(wrapper.element.open, false);
assert.deepEqual(events, ['opened', 'hidden']);
await wrapper.setProps({ open: false });
await nextTick();
wrapper.unmount();
} finally {
HTMLDialogElement.prototype.showModal = showModal;
}
});
+72
View File
@@ -0,0 +1,72 @@
<script setup>
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from 'vue';
// Core's modal dialog: a native `<dialog>` the owner opens and closes with
// `open`. True opens it with showModal() (once mounted, so a dialog mounted
// open opens straight away), false closes it, and unmounting closes it.
// Each change is applied after the content has rendered and is then emitted
// (`opened`, `closed`), so the owner can move focus into the content it
// shows or back to the control that opened it. Escape's `cancel` is
// prevented and emitted as `dismiss`, so the owner decides; with
// `backdropDismiss`, a click on the backdrop (the dialog element itself,
// outside its content) is a `dismiss` too. When the browser closes the
// dialog on its own while `open` is still true (an Escape it does not let
// the page cancel), `browserClose` tells the owner. A DOM without
// showModal() (a test's) leaves the dialog closed rather than failing.
// Attributes, classes, styles and listeners pass through to the dialog; the
// content is the default slot. `element` is the dialog element.
const props = defineProps({
open: { type: Boolean, default: false },
backdropDismiss: { type: Boolean, default: false },
});
const emit = defineEmits(['dismiss', 'browserClose', 'opened', 'closed']);
const element = useTemplateRef('element');
let unmounting = false;
function show() {
const dialog = element.value;
if (!dialog) return;
if (!dialog.open) dialog.showModal?.();
emit('opened');
}
onMounted(() => {
if (props.open) show();
});
watch(
() => props.open,
(open) => {
if (open) return show();
const dialog = element.value;
if (!dialog) return;
// The browser may already have closed it.
if (dialog.open) dialog.close();
emit('closed');
},
{ flush: 'post' },
);
onBeforeUnmount(() => {
unmounting = true;
if (element.value?.open) element.value.close();
});
function onCancel(event) {
event.preventDefault();
emit('dismiss');
}
function onClose() {
if (!unmounting && props.open) emit('browserClose');
}
function onClick(event) {
if (props.backdropDismiss && event.target === event.currentTarget)
emit('dismiss');
}
defineExpose({ element });
</script>
<template>
<dialog ref="element" @cancel="onCancel" @close="onClose" @click="onClick">
<slot />
</dialog>
</template>
+66
View File
@@ -0,0 +1,66 @@
// Every modal dialog in a Vue view is a UiDialog: no SFC template hand-writes
// `<dialog>`. Panels drawn as `role="dialog"` (key setup, the welcome
// launcher, the CCTV popup, Story Explore's filter) and the render failure's
// `alertdialog` are other controls.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SRC_ROOT = fileURLToPath(new URL('../../', import.meta.url));
const REPO_ROOT = path.resolve(SRC_ROOT, '..');
const KIT = 'src/ui/kit/UiDialog.vue';
/** Every SFC under src. */
function sfcFiles(directory = SRC_ROOT) {
const files = [];
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) files.push(...sfcFiles(absolute));
else if (entry.isFile() && entry.name.endsWith('.vue'))
files.push(absolute);
}
return files.sort();
}
/** The template block: everything outside script and style. */
function template(source) {
return source.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/g, '');
}
// An opening tag's attributes, quoted values may hold `>` (`() => x`).
const ATTRS = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`;
const HAND_WRITTEN_DIALOG = new RegExp(String.raw`<dialog\b${ATTRS}>`, 'gi');
/** Hand-written dialogs in an SFC's template. */
function handWrittenDialogs(source) {
return [...template(source).matchAll(HAND_WRITTEN_DIALOG)].map((m) =>
m[0].replace(/\s+/g, ' '),
);
}
test('the scan finds each hand-written dialog', () => {
for (const markup of [
'<template><dialog id="x" @cancel.prevent="on"><p /></dialog></template>',
'<template><dialog\n :open="a > b"\n class="x"\n>…</dialog></template>',
])
assert.equal(handWrittenDialogs(markup).length, 1, markup);
for (const markup of [
'<template><UiDialog :open="on" @dismiss="off"><p /></UiDialog></template>',
'<template><div role="dialog" aria-modal="true" /></template>',
"<script>const html = '<dialog open>';</script><template><p /></template>",
])
assert.equal(handWrittenDialogs(markup).length, 0, markup);
});
test('no SFC hand-writes a dialog; each is a UiDialog', () => {
const found = [];
for (const file of sfcFiles()) {
const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/');
if (relative === KIT) continue;
for (const markup of handWrittenDialogs(readFileSync(file, 'utf8')))
found.push(`${relative}: ${markup}`);
}
assert.deepEqual(found, []);
});