Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(home): let the floorplan editor create rooms in Home Assistant

nirholasa4b676e85c2e
diff --git a/api/home/[id]/areas.js b/api/home/[id]/areas.js
new file mode 100644
index 000000000..a70375741
--- /dev/null
+++ b/api/home/[id]/areas.js
@@ -0,0 +1,89 @@
+// /api/home/:id/areas: make a room in the user's own Home Assistant.
+//
+// POST { name } creates the area, or returns the one that already has it
+//
+// This is the way out of the most common real house we see: one where nothing
+// has ever been assigned to an area. Home Assistant knows the devices and has
+// no rooms to put them in, so every room-shaped surface we build (the 3D scene,
+// the floorplan, room-scoped grants) has nothing to show. Telling that person
+// to go and make areas in Home Assistant's settings first is how the feature
+// dies; they leave to do a chore and do not come back. So the floorplan editor
+// makes the room here, in their registry, and the work is theirs to keep.
+//
+// Like /assign, it is not a guarded action: nothing moves, nothing opens, and
+// an empty area is deleted in two clicks in their own UI. It is still a write
+// to their house, so it needs the `layout` capability, a CSRF token, and a row
+// in the action log.
+
+import { logAudit } from '../../_lib/audit.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { resolveHomeAccess } from '../../_lib/home/access.js';
+import { homeError } from '../../_lib/home/errors.js';
+import { withHome } from '../../_lib/home/runtime.js';
+import { logHomeAction } from '../../_lib/home/store.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+
+/** Long enough for "Upstairs bathroom", short enough that nobody pastes a novel. */
+const MAX_NAME = 64;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const access = await resolveHomeAccess(req, res, req.query?.id, 'layout');
+ if (!access.ok) return error(res, access.status, access.code, access.message);
+ const { caller, home, scoped } = access;
+
+ if (!requireCsrf(req, res)) return;
+
+ // A scoped member sees part of the house. A brand new room belongs to no
+ // scope by definition, so they would create something they could not then
+ // see, place or file into: a control that only produces confusion. The
+ // owner and admins make rooms.
+ if (scoped) {
+ return error(res, 403, 'scope_forbidden', 'Making a new room needs the owner or an admin.');
+ }
+
+ const rl = await limits.homeAct(caller.userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many home writes, slow down');
+
+ const body = await readJson(req, res);
+ if (body === undefined) return;
+
+ const name = typeof body?.name === 'string' ? body.name.trim() : '';
+ if (!name) return error(res, 400, 'name_required', 'Give the room a name, like Kitchen.');
+ if (name.length > MAX_NAME) {
+ return error(res, 400, 'name_too_long', `Keep the room name under ${MAX_NAME + 1} characters.`);
+ }
+
+ try {
+ const area = await withHome(home.id, caller.userId, (bridge) => bridge.createArea(name));
+ logHomeAction({
+ homeId: home.id,
+ userId: caller.userId,
+ actor: 'user',
+ channel: 'websocket',
+ action: 'area_registry.create',
+ entityIds: [],
+ guarded: false,
+ outcome: 'ok',
+ detail: { areaId: area.id, created: area.created },
+ });
+ logAudit({ userId: caller.userId, action: 'create_home_area', resourceId: home.id, meta: { areaId: area.id, created: area.created }, req });
+ return json(res, area.created ? 201 : 200, { ok: true, area });
+ } catch (err) {
+ logHomeAction({
+ homeId: home.id,
+ userId: caller.userId,
+ actor: 'user',
+ channel: 'websocket',
+ action: 'area_registry.create',
+ entityIds: [],
+ guarded: false,
+ outcome: 'failed',
+ detail: { name, reason: err?.code || 'error' },
+ });
+ return homeError(res, err);
+ }
+});
diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.js
index e752feb99..0862eeb9c 100644
--- a/packages/home-bridge/src/bridge.js
+++ b/packages/home-bridge/src/bridge.js
@@ -450,6 +450,59 @@ export class HomeBridge {
}
}
+ /**
+ * Make a new area in the house, so a home with none can grow rooms.
+ *
+ * The common real house has nothing assigned to an area at all, and every
+ * room-shaped feature we build is useless to it until somebody creates the
+ * first area. Sending that person to Home Assistant's own settings to do it
+ * is how the feature dies: they leave and do not come back. So the editor
+ * creates the area itself, here, in their registry.
+ *
+ * Home Assistant derives the area id from the name and refuses a duplicate.
+ * A name that already exists comes back as the EXISTING area rather than an
+ * error, because "Kitchen already exists" is not a failure from the caller's
+ * point of view: the room they asked for is there, which is what they wanted.
+ *
+ * @param {string} name
+ * @param {{ floorId?: string|null }} [options]
+ * @returns {Promise<{ id: string, name: string, floorId: string|null, created: boolean }>}
+ */
+ async createArea(name, { floorId = null } = {}) {
+ this.#assertConnected();
+ const label = typeof name === 'string' ? name.trim() : '';
+ if (!label) throw new HomeBridgeError(ERR.CALL_FAILED, 'A room needs a name.');
+ if (label.length > 64) {
+ throw new HomeBridgeError(ERR.CALL_FAILED, 'That room name is too long; keep it under 65 characters.');
+ }
+
+ const existing = (this.#registries.areas || []).find(
+ (a) => String(a.name || '').trim().toLowerCase() === label.toLowerCase(),
+ );
+ if (existing) {
+ return { id: existing.area_id, name: existing.name, floorId: existing.floor_id || null, created: false };
+ }
+
+ try {
+ const result = await this.#connection.sendMessagePromise({
+ type: 'config/area_registry/create',
+ name: label,
+ ...(floorId ? { floor_id: floorId } : {}),
+ });
+ // Same reason as assignEntityArea: the caller is about to redraw from
+ // the graph, so refresh rather than race our own registry event.
+ await this.refreshRegistries();
+ return {
+ id: result?.area_id,
+ name: result?.name || label,
+ floorId: result?.floor_id || null,
+ created: true,
+ };
+ } catch (err) {
+ throw toBridgeError(err, this.#options.baseUrl, `Could not make a room called ${label}.`);
+ }
+ }
+
/** Every area the house has, for a UI that files entities into them. */
areas() {
return (this.#registries.areas || []).map((a) => ({
diff --git a/src/home/api.js b/src/home/api.js
index 687fb2ec7..c1447fc49 100644
--- a/src/home/api.js
+++ b/src/home/api.js
@@ -107,6 +107,17 @@ export function assignEntityArea(id, { entityId, areaId }) {
return request(`/api/home/${encodeURIComponent(id)}/assign`, { method: 'POST', body: { entityId, areaId } });
}
+/**
+ * Make a room in the user's own Home Assistant.
+ *
+ * The way in for a house that has never had an area: the editor creates the
+ * room here rather than sending the person off to Home Assistant's settings.
+ * A name that already exists comes back as the existing room, not an error.
+ */
+export function createArea(id, { name }) {
+ return request(`/api/home/${encodeURIComponent(id)}/areas`, { method: 'POST', body: { name } });
+}
+
/** The caller's homes, credential free. */
export function listHomes(signal) {
return request('/api/home', { signal });
diff --git a/src/home/floorplan.js b/src/home/floorplan.js
index 6b6e6ea14..350940606 100644
--- a/src/home/floorplan.js
+++ b/src/home/floorplan.js
@@ -15,7 +15,7 @@
* States 1 to 9 of order 07 all live here; each is a branch of render().
*/
-import { assignEntityArea, clearLayout, getLayout, HomeApiError, saveLayout } from './api.js';
+import { assignEntityArea, clearLayout, createArea, getLayout, HomeApiError, saveLayout } from './api.js';
import { clear, el, noticeEl } from './connect.js';
/** Metres per grid square. Matches the scene's CELL so the two read alike. */
@@ -51,6 +51,9 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
error: null,
notice: null,
conflict: null,
+ /** The new-room form, when it is open. `{ error }` while it is. */
+ naming: null,
+ creating: false,
selected: null,
history: [],
future: [],
@@ -61,7 +64,23 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
mount.append(view);
load();
- return { destroy: () => view.remove(), reload: load };
+ return {
+ destroy: () => view.remove(),
+ reload: load,
+ /**
+ * The house changed under us, so redraw the tray from the new graph.
+ *
+ * Filing a device and making a room both write Home Assistant's own
+ * registry, and neither produces a state event that would correct a tray
+ * built from the old graph. The scene re-reads the house and hands the
+ * result back here.
+ */
+ setGraph(next) {
+ if (!next) return;
+ graph = next;
+ render();
+ },
+ };
async function load() {
state.loading = true;
@@ -277,6 +296,53 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
render();
}
+ /**
+ * Make a room that does not exist yet, in Home Assistant, and place it.
+ *
+ * State 2: a house where nothing has ever been assigned to an area. Without
+ * this the tray offers one synthetic "Everything" bucket, filing has nowhere
+ * to file to, and the only advice we can give is "go and use Home Assistant's
+ * settings first", which is a chore that loses the person. The room is
+ * created in their own registry, so it reaches their dashboards and voice
+ * assistant too, exactly like filing a device does.
+ */
+ async function createRoom(name) {
+ if (state.creating) return;
+ const thenFile = state.naming?.thenFile || null;
+ state.creating = true;
+ state.naming = { error: null, thenFile };
+ render();
+ try {
+ const res = await createArea(homeId, { name });
+ const area = res?.area;
+ if (!area?.id) throw new Error('Home Assistant did not name the new room.');
+
+ // Teach the local graph about it immediately, so nameOf, the file menu
+ // and liveRoomIds all work before the refreshed graph comes back. The
+ // authoritative copy arrives through setGraph a moment later.
+ graph = { ...(graph || {}), rooms: [...(graph?.rooms || []), { id: area.id, name: area.name, entities: [] }] };
+
+ state.naming = null;
+ state.creating = false;
+ placeRoom(area.id);
+ state.notice = area.created
+ ? { tone: 'ok', title: `${area.name} is a room in your home now`, body: 'It was made in your Home Assistant, so you can file devices into it here and use it there.' }
+ : { tone: 'info', title: `${area.name} already existed`, body: 'It is on the plan now.' };
+ render();
+ onChange?.(toDocument(), { refreshGraph: true });
+
+ // The room was made in order to hold this device, so finish the job
+ // rather than handing back a form and making them find it again.
+ if (thenFile) await fileEntity(thenFile, area.id);
+ } catch (err) {
+ // The form stays open holding what they typed: a name that was refused
+ // is a name to fix, not a reason to start over.
+ state.creating = false;
+ state.naming = { error: describeError(err).body };
+ render();
+ }
+ }
+
// ---- rendering ---------------------------------------------------------
function render() {
@@ -294,6 +360,7 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
}
if (state.notice) view.append(noticeEl(state.notice));
if (state.conflict) view.append(conflictPanel());
+ if (state.naming && canEdit) view.append(namingForm());
view.append(toolbar());
view.append(canvas());
@@ -313,6 +380,7 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
bar.append(button('Undo', undo, { disabled: !state.history.length, key: 'Ctrl+Z' }));
bar.append(button('Redo', redo, { disabled: !state.future.length, key: 'Ctrl+Shift+Z' }));
+ bar.append(button('New room', () => openNaming(), { disabled: state.creating }));
const dirty = state.history.length > 0;
bar.append(button(state.saving ? 'Saving' : 'Save floorplan', save, { primary: true, disabled: state.saving || !dirty }));
bar.append(button('Reset to default', resetPlan, { disabled: state.saving || !state.rooms.size }));
@@ -323,6 +391,73 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
return bar;
}
+ /** Open the new-room form, optionally to hold a device that needs somewhere. */
+ function openNaming(thenFile = null) {
+ state.naming = { error: null, thenFile };
+ state.notice = null;
+ render();
+ view.querySelector('.hm-plan-naming input')?.focus();
+ }
+
+ /**
+ * Name a new room.
+ *
+ * A form rather than window.prompt: prompt cannot be styled, cannot show the
+ * error the server returned without a second dialog, blocks the whole tab,
+ * and is suppressed outright in some browsers. This is three elements and it
+ * behaves like the rest of the product.
+ */
+ function namingForm() {
+ const form = el('form', 'hm-plan-naming');
+ form.setAttribute('aria-label', 'Make a new room');
+
+ const id = `hm-plan-newroom-${Math.random().toString(36).slice(2, 8)}`;
+ const label = el('label', null, state.naming.thenFile
+ ? `Name a room for ${state.naming.thenFile}`
+ : 'Name the new room');
+ label.htmlFor = id;
+ form.append(label);
+
+ const input = el('input', 'hm-plan-naming-input');
+ input.id = id;
+ input.type = 'text';
+ input.maxLength = 64;
+ input.required = true;
+ input.autocomplete = 'off';
+ input.placeholder = 'Kitchen';
+ form.append(input);
+
+ const actions = el('div', 'hm-plan-naming-actions');
+ const submit = el('button', 'hm-plan-btn is-primary', state.creating ? 'Making' : 'Make this room');
+ submit.type = 'submit';
+ submit.disabled = state.creating;
+ actions.append(submit);
+
+ const cancel = el('button', 'hm-plan-btn', 'Cancel');
+ cancel.type = 'button';
+ cancel.disabled = state.creating;
+ cancel.addEventListener('click', () => { state.naming = null; render(); });
+ actions.append(cancel);
+ form.append(actions);
+
+ if (state.naming.error) {
+ const err = el('p', 'hm-plan-naming-error', state.naming.error);
+ err.setAttribute('role', 'alert');
+ form.append(err);
+ }
+
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const name = input.value.trim();
+ if (!name) {
+ state.naming = { ...state.naming, error: 'Give the room a name, like Kitchen.' };
+ return render();
+ }
+ createRoom(name);
+ });
+ return form;
+ }
+
function conflictPanel() {
const wrap = el('div', 'hm-plan-conflict');
wrap.setAttribute('role', 'alertdialog');
@@ -485,6 +620,15 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
const wrap = el('div', 'hm-plan-tray');
wrap.append(el('h3', 'hm-plan-tray-title', 'To place'));
+ // State 2. A house with no areas has nothing to arrange, and the honest
+ // answer is not an empty panel: it is the first room.
+ if (canEdit && !liveRoomIds().some((id) => !id.startsWith('__'))) {
+ const start = el('div', 'hm-plan-tray-start');
+ start.append(el('p', null, 'Nothing in this home is in a room yet. Make the first one and the plan starts here.'));
+ start.append(button('Make a room', () => openNaming()));
+ wrap.append(start);
+ }
+
const unplaced = state.unplaced.length ? state.unplaced : liveRoomIds().filter((id) => !state.rooms.has(id));
if (unplaced.length) {
const list = el('ul', 'hm-plan-tray-rooms');
@@ -534,10 +678,10 @@ export function mountFloorplan({ mount, homeId, graph, canEdit = true, onChange
/** The keyboard route into filing, so drag is never the only path. */
function fileByPrompt(entityId) {
const rooms = liveRoomIds().filter((id) => !id.startsWith('__'));
- if (!rooms.length) {
- state.notice = { tone: 'info', title: 'No rooms yet', body: 'Make an area in Home Assistant first, then devices can be filed into it.' };
- return render();
- }
+ // State 2, the common real house: nothing has ever been assigned to an
+ // area, so there is nowhere to file this. Make the room here instead of
+ // sending them to Home Assistant's settings to do a chore.
+ if (!rooms.length) return openNaming(entityId);
const menu = el('div', 'hm-plan-filemenu');
menu.setAttribute('role', 'menu');
for (const id of rooms) {
diff --git a/src/home/home.css b/src/home/home.css
index a40d938fa..79eb80f81 100644
--- a/src/home/home.css
+++ b/src/home/home.css
@@ -95,6 +95,8 @@
.hm-field { display: block; margin-bottom: var(--space-md); }
.hm-label { display: block; font-size: var(--text-md); font-weight: var(--weight-medium); margin-bottom: 0.4rem; }
.hm-hint { font-size: var(--text-sm); color: var(--hm-ink-3); margin: 0.35rem 0 0; line-height: var(--leading-normal); }
+/* Inline validation. The wording carries the message; the colour only agrees with it. */
+.hm-hint[data-error='true'] { color: var(--hm-down); }
.hm-input {
width: 100%; box-sizing: border-box;
@@ -764,6 +766,30 @@
.hm-plan-conflict p { margin: 0 0 var(--space-sm); font-size: var(--text-sm); line-height: var(--leading-normal); }
.hm-plan-conflict-actions { display: flex; gap: var(--space-xs); flex-wrap: wrap; }
+/* Making the first room. The house with no areas at all starts here, so this
+ is a first-class panel rather than a dialog bolted on the side. */
+.hm-plan-naming {
+ display: grid; gap: var(--space-xs);
+ border: 1px solid var(--hm-line); border-radius: var(--radius-md);
+ background: var(--hm-panel); padding: var(--space-md);
+}
+.hm-plan-naming label { font-size: var(--text-sm); color: var(--hm-ink-2); }
+.hm-plan-naming-input {
+ width: 100%; box-sizing: border-box;
+ padding: 0.45rem 0.7rem; border: 1px solid var(--hm-line); border-radius: var(--radius-sm);
+ background: var(--hm-panel-2); color: var(--ink); font: inherit; font-size: var(--text-sm);
+}
+.hm-plan-naming-input:focus-visible { outline: 2px solid var(--hm-live); outline-offset: 1px; border-color: var(--hm-live); }
+.hm-plan-naming-actions { display: flex; gap: var(--space-xs); flex-wrap: wrap; }
+.hm-plan-naming-error { margin: 0; font-size: var(--text-sm); color: var(--hm-alert, #e0616a); line-height: var(--leading-normal); }
+
+.hm-plan-tray-start {
+ display: grid; gap: var(--space-xs); justify-items: start;
+ margin: 0 0 var(--space-sm);
+ padding: var(--space-sm); border: 1px dashed var(--hm-line); border-radius: var(--radius-sm);
+}
+.hm-plan-tray-start p { margin: 0; font-size: var(--text-sm); color: var(--hm-ink-2); line-height: var(--leading-normal); }
+
.hm-plan-skeleton { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-sm); }
.hm-plan-skeleton-room { height: 96px; border-radius: var(--radius-sm); background: var(--hm-panel-2); }
diff --git a/src/home/scene.js b/src/home/scene.js
index b28f872e8..08526c3e5 100644
--- a/src/home/scene.js
+++ b/src/home/scene.js
@@ -31,6 +31,7 @@ const el = {
panelEmpty: document.getElementById('hs-panel-empty'),
inspector: document.getElementById('hs-inspector'),
live: document.getElementById('hs-live'),
+ alert: document.getElementById('hs-alert'),
view3d: document.getElementById('hs-view-3d'),
view2d: document.getElementById('hs-view-2d'),
viewPlan: document.getElementById('hs-view-plan'),
@@ -59,6 +60,8 @@ const state = {
lastGraphAt: 0,
selected: null,
pending: null,
+ /** The control that asked, so a cancelled confirmation gives the keyboard back. */
+ confirmReturn: null,
busy: new Set(),
log: [],
// Latency instrumentation: the wall time from an SSE frame landing to the
@@ -87,6 +90,19 @@ window.__homeScene = {
stats() {
return state.renderer?.stats?.() || null;
},
+ /**
+ * Where an entity sits on screen right now, or null when the 3D view is not
+ * mounted or the object is off camera.
+ *
+ * Clicking an object inside the canvas is the page's primary gesture and the
+ * one interaction nothing automated can otherwise reach: a raycast needs a
+ * pixel, and a pixel guessed from outside is a test that passes by luck. This
+ * hands out the real position of a real object so the measurement pass and
+ * the e2e spec click the same place a person would.
+ */
+ project(entityId) {
+ return state.renderer?.project?.(entityId) || null;
+ },
};
boot();
@@ -427,7 +443,13 @@ async function mountPlan() {
async function refreshGraph() {
try {
const payload = await getHome(state.homeId);
- if (payload?.graph) applyGraph(payload.graph, { stale: Boolean(payload.stale) });
+ if (payload?.graph) {
+ applyGraph(payload.graph, { stale: Boolean(payload.stale) });
+ // The editor holds its own reference to the graph and builds the tray
+ // from it. Filing a device or making a room changed the registry, so
+ // without this the tray still offers a device that now has a home.
+ state.plan?.setGraph?.(payload.graph);
+ }
} catch {
// The plan is still correct locally; the graph refreshes on the next event.
}
@@ -708,8 +730,11 @@ async function act(request, { confirmed = false, remember = false } = {}) {
// The gate fired. Ask, next to the thing it would move.
state.pending = { request, message: err.message, risk: err.pending?.risk || 'physical', entityId: err.pending?.entityId || request.entityId };
pushLog({ text: `${request.service.replace(/_/g, ' ')} ${request.name}`, outcome: 'refused' });
+ // Where the keyboard was when the gate fired. Cancelling or pressing
+ // Escape puts it back there, so a keyboard user is returned to the
+ // control they pressed instead of to the top of the document.
+ state.confirmReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
renderConfirm();
- announce(err.message);
} else {
pushLog({ text: `${request.service.replace(/_/g, ' ')} ${request.name}`, outcome: 'failed' });
announce(err.message || 'That did not work.');
@@ -737,20 +762,28 @@ function renderConfirm() {
card.setAttribute('role', 'alertdialog');
card.setAttribute('aria-modal', 'false');
card.setAttribute('aria-label', 'Confirm this action');
+ // A screen reader reads an alertdialog's own description when focus lands
+ // inside it, and the description is these three paragraphs in order: the
+ // risk band, the question, and the reason the gate stopped it.
+ const cardId = `hs-confirm-${Date.now().toString(36)}`;
+ card.setAttribute('aria-describedby', `${cardId}-risk ${cardId}-q ${cardId}-why`);
const risk = document.createElement('p');
risk.className = 'hs-confirm-risk';
+ risk.id = `${cardId}-risk`;
risk.textContent = pending.risk === 'security' ? 'Opens your home' : 'Moves something physical';
card.appendChild(risk);
const text = document.createElement('p');
text.className = 'hs-confirm-text';
+ text.id = `${cardId}-q`;
const object = findObject(pending.entityId);
text.textContent = `${pending.request.service.replace(/_/g, ' ')} ${object?.name || pending.request.name}?`;
card.appendChild(text);
const why = document.createElement('p');
why.className = 'hs-confirm-text';
+ why.id = `${cardId}-why`;
why.style.color = 'var(--ink-dim)';
why.textContent = pending.message;
card.appendChild(why);
@@ -765,7 +798,12 @@ function renderConfirm() {
const remember = card.querySelector('input')?.checked;
const request = pending.request;
state.pending = null;
+ // Answering yes hands the keyboard back to the control that asked, so the
+ // next Tab continues from the device rather than from the document head.
+ const back = state.confirmReturn;
+ state.confirmReturn = null;
act(request, { confirmed: true, remember });
+ if (back?.isConnected) back.focus();
});
const no = document.createElement('button');
no.type = 'button';
@@ -773,7 +811,8 @@ function renderConfirm() {
no.textContent = 'Cancel';
no.addEventListener('click', () => {
state.pending = null;
- dismissConfirm();
+ dismissConfirm({ restoreFocus: true });
+ announce('Cancelled. Nothing moved.');
});
row.append(yes, no);
card.appendChild(row);
@@ -791,6 +830,9 @@ function renderConfirm() {
repositionConfirm();
requestAnimationFrame(repositionConfirm);
yes.focus();
+ // Assertive, and self-contained: a reader that lands on the Yes button hears
+ // the button, not the question, so the question is said in full here.
+ alertAssertive(`${risk.textContent}. ${text.textContent} ${pending.message} Answer with the Yes or Cancel button, or press Escape to cancel.`);
}
/**
@@ -829,15 +871,27 @@ function repositionConfirm() {
card.style.top = `${clamp(top, minTop, Math.max(minTop, maxTop))}px`;
}
-function dismissConfirm() {
+function dismissConfirm({ restoreFocus = false } = {}) {
+ const had = Boolean(state.confirmCard);
state.confirmCard?.remove();
state.confirmCard = null;
+ // Leaving the question standing in an assertive region means the next
+ // unrelated announcement is read after a stale "unlock the front door?".
+ if (had) writeLive(el.alert, '');
+ // Only a dismissal that ENDS the question gives the keyboard back. Re-rendering
+ // the card (a second event for the same device) dismisses and rebuilds it, and
+ // must leave the return target exactly where act() put it.
+ if (!restoreFocus) return;
+ const back = state.confirmReturn;
+ state.confirmReturn = null;
+ if (back?.isConnected) back.focus();
}
function onKeydown(event) {
if (event.key === 'Escape' && state.pending) {
state.pending = null;
- dismissConfirm();
+ dismissConfirm({ restoreFocus: true });
+ announce('Cancelled. Nothing moved.');
}
}
@@ -1015,8 +1069,36 @@ function renderLog() {
el.panel.appendChild(list);
}
+/**
+ * Ordinary state changes, politely: a light that went on, a house that went
+ * stale, a view that switched. A polite region waits for the reader to finish
+ * whatever it is saying, which is right for narration and wrong for a question.
+ *
+ * Writing the same string twice is a no-op in every screen reader, so a repeat
+ * (two lights refused for the same reason) is nudged into a different string
+ * rather than swallowed.
+ */
function announce(message) {
- el.live.textContent = message;
+ writeLive(el.live, message);
+}
+
+/**
+ * The guarded confirmation, assertively. This is the one message in the lane a
+ * person must not be able to miss: it stands between them and an unlocked front
+ * door, and a polite region can be queued behind a paragraph of room narration
+ * for long enough that the card times out unanswered.
+ */
+function alertAssertive(message) {
+ writeLive(el.alert, message);
+}
+
+function writeLive(node, message) {
+ if (!node) return;
+ const text = String(message || '');
+ // An identical assignment changes no text node, and a live region only
+ // announces a change. Clearing first makes the repeat a change again.
+ if (node.textContent === text) node.textContent = '';
+ node.textContent = text;
}
// ── helpers ──────────────────────────────────────────────────────────────────
@@ -1031,13 +1113,23 @@ function homeIdFromPath() {
}
function preferredView() {
+ // An explicit ?view= is a deliberate request for THIS visit: a link someone
+ // shared, a bookmark, or the address a wall display is pinned to. It is more
+ // specific than whatever this browser happens to remember, so it is read
+ // first and wins. Reading storage first meant one visit that ever touched
+ // the 2D button pinned every later ?view=3d link back to 2D, on a page whose
+ // own toggle treats a ?view= parameter as a choice the person made.
+ // It is deliberately not written back: a shared link should not overwrite
+ // the preference this browser chose for itself.
+ const asked = new URLSearchParams(location.search).get('view');
+ if (asked === '2d' || asked === '3d' || asked === 'plan') return asked;
try {
const stored = localStorage.getItem(VIEW_KEY);
if (stored === '2d' || stored === '3d') return stored;
} catch {
// Storage disabled: default to 3D and let the WebGL probe decide.
}
- return new URLSearchParams(location.search).get('view') === '2d' ? '2d' : '3d';
+ return '3d';
}
function findObject(entityId) {