M1.9b: settings dialog with search

settings.open (Mod+,) opens a dialog built from settings.list: sections,
controls by type (select, number with min/max, switch), catalog labels
and descriptions, search over label, description, key and section, Reset
to default, inline errors, live updates on settingsChanged. The theme
picker switches at once; editor.fontSize drives --lt-font-size-editor
through a token override that survives theme switches. Focus trap,
Escape closes. Finishes M1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 21:13:04 +02:00
parent db34e2ca52
commit 523d7f684f
17 changed files with 1751 additions and 36 deletions

View file

@ -0,0 +1,730 @@
<script setup lang="ts">
/**
* The settings dialog (`settings.open`, `Mod+,`), built from the engine's
* `settings.list`: sections on the left, the settings of the chosen
* section on the right, each with its control by type (enum → select,
* int → number field with min/max, bool → switch), label and description
* from the catalog, and "Reset to default" when it differs from the
* default.
*
* - **Search:** the field filters by label, description, key and section
* name; while it has text, every match shows, grouped by section.
* - **Changes** apply at once through `settings.set` (a number when the
* field is committed: Enter, the spinner or leaving it). A refused value
* shows its error under the control and keeps the typed text.
* - **Live:** values follow `settingsChanged` through the settings store,
* so a change over the control channel shows while the dialog is open.
* - **Keyboard:** Escape closes, Tab and Shift+Tab stay inside the dialog,
* and the focus returns to where it was.
*/
import { X } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import {
descriptionOf,
groupSections,
labelOf,
matchesQuery,
useSettingsStore,
valueLabel,
type SettingDef,
type SettingSection,
} from "../../stores/settings";
const commands = useCommandsStore();
const settings = useSettingsStore();
/** Whether the dialog is shown. */
const open = ref(false);
/** What the user typed into the search field. */
const query = ref("");
/** Id of the chosen section. */
const current = ref<string | null>(null);
/** Text typed into number fields, by key; shown while their value is refused. */
const drafts = reactive<Record<string, string>>({});
/** The dialog element. */
const dialog = ref<HTMLElement | null>(null);
/** The search field. */
const search = ref<HTMLInputElement | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/** Withdraws the `settings.open` handler; set while mounted. */
let withdraw: (() => void) | null = null;
/** Every section. */
const sections = computed<SettingSection[]>(() => groupSections(settings.defs));
/** Whether the search field has text. */
const searching = computed(() => query.value.trim() !== "");
/** The sections shown on the right: the chosen one, or every match while searching. */
const shown = computed<SettingSection[]>(() => {
if (searching.value) {
return sections.value
.map((section) => ({ ...section, settings: section.settings.filter((def) => matchesQuery(def, query.value)) }))
.filter((section) => section.settings.length > 0);
}
const chosen = sections.value.find((section) => section.id === current.value) ?? sections.value[0];
return chosen ? [chosen] : [];
});
/** Ids of the sections that have matches. */
const matching = computed(() => new Set(shown.value.map((section) => section.id)));
/** The id of the section highlighted on the left. */
const activeSection = computed(() =>
searching.value ? (shown.value[0]?.id ?? null) : (current.value ?? sections.value[0]?.id ?? null),
);
/**
* DOM id of a setting's control.
*
* @param def - the setting.
*/
function controlId(def: SettingDef): string {
return `lt-setting-${def.key.replace(/[^A-Za-z0-9]/g, "-")}`;
}
/**
* The text of a number field: the refused draft while there is an error,
* else the value.
*
* @param def - the setting.
*/
function numberText(def: SettingDef): string {
const draft = drafts[def.key];
if (draft !== undefined && settings.errors[def.key] !== undefined) {
return draft;
}
const value = settings.values[def.key];
return typeof value === "number" ? String(value) : "";
}
/**
* The value of a select.
*
* @param def - the setting.
*/
function enumValue(def: SettingDef): string {
const value = settings.values[def.key];
return typeof value === "string" ? value : "";
}
/**
* Whether a switch is on.
*
* @param def - the setting.
*/
function boolValue(def: SettingDef): boolean {
return settings.values[def.key] === true;
}
/**
* Applies a select's choice.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onSelect(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (target instanceof HTMLSelectElement) {
await settings.set(def.key, target.value);
}
}
/**
* Applies a committed number field. Text that is no whole number in range
* is refused here with the catalog's message; the engine validates
* everything else.
*
* @param def - the setting.
* @param event - the change event.
*/
async function onNumber(def: SettingDef, event: Event): Promise<void> {
const target = event.target;
if (!(target instanceof HTMLInputElement)) {
return;
}
const text = target.value.trim();
drafts[def.key] = target.value;
const value = Number(text);
const inRange =
text !== "" &&
Number.isInteger(value) &&
(def.min === null || value >= def.min) &&
(def.max === null || value <= def.max);
if (!inRange) {
settings.setError(
def.key,
def.min !== null && def.max !== null
? t("settings.error.intRange", { min: def.min, max: def.max })
: t("settings.error.int"),
);
return;
}
if (await settings.set(def.key, value)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Flips a switch.
*
* @param def - the setting.
*/
async function onToggle(def: SettingDef): Promise<void> {
await settings.set(def.key, !boolValue(def));
}
/**
* Resets a setting and drops its draft.
*
* @param def - the setting.
*/
async function onReset(def: SettingDef): Promise<void> {
if (await settings.reset(def.key)) {
Reflect.deleteProperty(drafts, def.key);
}
}
/**
* Chooses a section; clears the search so the section shows whole.
*
* @param id - the section id.
*/
function choose(id: string): void {
current.value = id;
query.value = "";
}
/** Opens the dialog (or focuses its search field) and reloads the settings. */
async function show(): Promise<void> {
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
query.value = "";
open.value = true;
}
await nextTick();
search.value?.focus();
await settings.load();
}
/** Closes the dialog and gives the focus back. */
function close(): void {
if (!open.value) {
return;
}
open.value = false;
for (const key of Object.keys(drafts)) {
Reflect.deleteProperty(drafts, key);
}
returnFocus?.focus();
returnFocus = null;
}
/** The elements Tab reaches inside the dialog, in order. */
function focusables(): HTMLElement[] {
const root = dialog.value;
if (!root) {
return [];
}
return [
...root.querySelectorAll<HTMLElement>(
"button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])",
),
];
}
/**
* Keyboard handling of the dialog: Escape closes, Tab wraps around.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
close();
return;
}
if (event.key !== "Tab") {
return;
}
const list = focusables();
const first = list[0];
const last = list.at(-1);
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement;
const inside = active instanceof HTMLElement && list.includes(active);
if (event.shiftKey && (active === first || !inside)) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (active === last || !inside)) {
event.preventDefault();
first.focus();
}
}
/**
* Keeps the focus inside the dialog when something outside would get it,
* except for another modal dialog opened above it (the palette).
*
* @param event - a focus change anywhere in the document.
*/
function onFocusIn(event: FocusEvent): void {
const root = dialog.value;
const target = event.target;
if (!open.value || !root || !(target instanceof Element) || root.contains(target)) {
return;
}
if (target.closest("[aria-modal='true']")) {
return;
}
search.value?.focus();
}
onMounted(() => {
withdraw = commands.provide("settings.open", { run: show });
document.addEventListener("focusin", onFocusIn);
});
onBeforeUnmount(() => {
withdraw?.();
withdraw = null;
document.removeEventListener("focusin", onFocusIn);
});
defineExpose({ show, close });
</script>
<template>
<div
v-if="open"
class="settings"
data-test="settings"
@mousedown.self.prevent="close()"
>
<div
ref="dialog"
class="settings__dialog"
role="dialog"
aria-modal="true"
aria-labelledby="lt-settings-title"
data-test="settings-dialog"
@keydown="onKeydown"
>
<header class="settings__header">
<h2
id="lt-settings-title"
class="settings__title"
>
{{ t("settings.dialog.title") }}
</h2>
<input
ref="search"
v-model="query"
class="settings__search"
type="search"
:aria-label="t('settings.dialog.search')"
:placeholder="t('settings.dialog.search')"
spellcheck="false"
autocomplete="off"
data-test="settings-search"
>
<button
type="button"
class="settings__close"
:aria-label="t('common.close')"
:title="t('common.close')"
data-test="settings-close"
@click="close()"
>
<X
:size="16"
aria-hidden="true"
/>
</button>
</header>
<div class="settings__body">
<nav
class="settings__nav"
:aria-label="t('settings.dialog.sections')"
>
<ul class="settings__sections">
<li
v-for="section in sections"
:key="section.id"
>
<button
type="button"
class="settings__section"
:class="{
'settings__section--active': section.id === activeSection,
'settings__section--dim': searching && !matching.has(section.id),
}"
:aria-current="section.id === activeSection ? 'true' : undefined"
:data-section="section.id"
data-test="settings-section"
@click="choose(section.id)"
>
{{ section.label }}
</button>
</li>
</ul>
</nav>
<div
class="settings__pane"
data-test="settings-pane"
>
<p
v-if="settings.loadError"
class="settings__error"
role="alert"
data-test="settings-load-error"
>
{{ t("settings.dialog.loadFailed", { message: settings.loadError }) }}
</p>
<p
v-if="searching && shown.length === 0"
class="settings__empty"
role="status"
data-test="settings-empty"
>
{{ t("settings.dialog.noMatches") }}
</p>
<section
v-for="section in shown"
:key="section.id"
class="settings__group"
:aria-labelledby="`lt-settings-group-${section.id}`"
>
<h3
:id="`lt-settings-group-${section.id}`"
class="settings__group-title"
>
{{ section.label }}
</h3>
<div
v-for="def in section.settings"
:key="def.key"
class="settings__row"
:data-key="def.key"
data-test="settings-row"
>
<div class="settings__text">
<label
:for="controlId(def)"
class="settings__label"
>{{ labelOf(def) }}</label>
<p
:id="`${controlId(def)}-description`"
class="settings__description"
>
{{ descriptionOf(def) }}
</p>
<p
v-if="settings.errors[def.key]"
:id="`${controlId(def)}-error`"
class="settings__error"
role="alert"
data-test="settings-error"
>
{{ settings.errors[def.key] }}
</p>
</div>
<div class="settings__control">
<select
v-if="def.type === 'enum'"
:id="controlId(def)"
class="settings__input"
:value="enumValue(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onSelect(def, $event)"
>
<option
v-for="option in def.enumValues"
:key="option"
:value="option"
>
{{ valueLabel(def, option) }}
</option>
</select>
<input
v-else-if="def.type === 'int'"
:id="controlId(def)"
class="settings__input settings__input--number"
type="number"
step="1"
:min="def.min ?? undefined"
:max="def.max ?? undefined"
:value="numberText(def)"
:aria-describedby="`${controlId(def)}-description`"
:aria-invalid="settings.errors[def.key] ? 'true' : undefined"
:aria-errormessage="settings.errors[def.key] ? `${controlId(def)}-error` : undefined"
data-test="settings-control"
@change="onNumber(def, $event)"
>
<button
v-else
:id="controlId(def)"
type="button"
role="switch"
class="settings__switch"
:class="{ 'settings__switch--on': boolValue(def) }"
:aria-checked="boolValue(def)"
:aria-describedby="`${controlId(def)}-description`"
data-test="settings-control"
@click="onToggle(def)"
>
<span class="settings__knob" />
</button>
<button
type="button"
class="settings__reset"
:disabled="settings.isDefault(def)"
:aria-label="t('settings.dialog.resetLabel', { name: labelOf(def) })"
data-test="settings-reset"
@click="onReset(def)"
>
{{ t("settings.dialog.reset") }}
</button>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.settings {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
z-index: 30;
}
.settings__dialog {
width: min(760px, 92vw);
height: min(520px, 84vh);
display: flex;
flex-direction: column;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
overflow: hidden;
}
.settings__header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 12px;
border-bottom: 1px solid var(--lt-border);
}
.settings__title {
margin: 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__search {
flex: 1;
min-width: 0;
padding: 4px 8px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__close {
display: flex;
padding: 4px;
color: var(--lt-fg);
background: none;
border: none;
border-radius: 4px;
cursor: pointer;
}
.settings__body {
flex: 1;
min-height: 0;
display: flex;
}
.settings__nav {
width: 180px;
flex-shrink: 0;
overflow-y: auto;
border-right: 1px solid var(--lt-border);
}
.settings__sections {
margin: 0;
padding: 4px 0;
list-style: none;
}
.settings__section {
width: 100%;
padding: 4px 12px;
font: inherit;
text-align: left;
color: var(--lt-fg);
background: none;
border: none;
cursor: pointer;
}
.settings__section--active {
background: var(--lt-editor-selection-bg);
color: var(--lt-fg);
}
.settings__section--dim {
opacity: 0.55;
}
.settings__pane {
flex: 1;
min-width: 0;
overflow-y: auto;
padding: 8px 16px 16px;
}
.settings__group-title {
margin: 8px 0;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.settings__row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 8px 0;
border-bottom: 1px solid var(--lt-border);
}
.settings__text {
min-width: 0;
}
.settings__label {
display: block;
}
.settings__description {
margin: 2px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-fg-muted);
}
.settings__error {
margin: 4px 0 0;
font-size: var(--lt-font-size-small);
color: var(--lt-error);
}
.settings__empty {
color: var(--lt-fg-muted);
}
.settings__control {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.settings__input {
padding: 3px 6px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.settings__input--number {
width: 6em;
}
.settings__input[aria-invalid="true"] {
border-color: var(--lt-error);
}
.settings__switch {
position: relative;
width: 32px;
height: 18px;
padding: 0;
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 9px;
cursor: pointer;
}
.settings__switch--on {
background: var(--lt-accent);
}
.settings__knob {
position: absolute;
top: 2px;
left: 2px;
width: 12px;
height: 12px;
background: var(--lt-fg);
border-radius: 50%;
}
.settings__switch--on .settings__knob {
left: 16px;
background: var(--lt-bg);
}
.settings__reset {
padding: 3px 8px;
font: inherit;
font-size: var(--lt-font-size-small);
color: var(--lt-fg);
background: none;
border: 1px solid var(--lt-border);
border-radius: 4px;
cursor: pointer;
}
.settings__reset:disabled {
color: var(--lt-fg-muted);
cursor: default;
}
.settings__close:focus-visible,
.settings__section:focus-visible,
.settings__search:focus-visible,
.settings__input:focus-visible,
.settings__switch:focus-visible,
.settings__reset:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
</style>