first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -0,0 +1,248 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { alarmCause, ownAlertMet, alertColor, alertEntities, alertSources, alertText, CONTACT_GRACE_MS, contactsPending, findAlerts, isPowerOut, QUIET_ALERTS, RAIN_STATES } from "./alerts.ts";
|
||||
import type { OpeningEntities } from "./devices.ts";
|
||||
import { emptyBuilding, newFloor, type Opening } from "./model.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { box, entity as entity2, floorWith, hassOf, opening } from "./entities/fixtures.ts";
|
||||
|
||||
type Attrs = Record<string, unknown>;
|
||||
const entity = (entity_id: string, state: string, attributes: Attrs = {}) => ({ entity_id, state, attributes });
|
||||
|
||||
/** A two-room house with a smoke detector, a leak sensor, a window contact, an alarm panel and a weather entity. */
|
||||
function house() {
|
||||
const hass = {
|
||||
language: "en",
|
||||
areas: { lounge: { area_id: "lounge", name: "Lounge" }, wc: { area_id: "wc", name: "WC" } },
|
||||
entities: {
|
||||
"binary_sensor.smoke": { entity_id: "binary_sensor.smoke", area_id: "lounge" },
|
||||
"binary_sensor.leak": { entity_id: "binary_sensor.leak", area_id: "wc" },
|
||||
"binary_sensor.casement": { entity_id: "binary_sensor.casement", area_id: "lounge" },
|
||||
"sensor.smoke_level": { entity_id: "sensor.smoke_level", area_id: "lounge" },
|
||||
},
|
||||
states: {
|
||||
"binary_sensor.smoke": entity("binary_sensor.smoke", "off", { device_class: "smoke", friendly_name: "Smoke detector" }),
|
||||
"binary_sensor.leak": entity("binary_sensor.leak", "off", { device_class: "moisture", friendly_name: "Leak sensor" }),
|
||||
"binary_sensor.casement": entity("binary_sensor.casement", "off", { device_class: "window", friendly_name: "Casement" }),
|
||||
"sensor.smoke_level": entity("sensor.smoke_level", "3", { device_class: "smoke" }),
|
||||
"weather.home": entity("weather.home", "sunny"),
|
||||
"alarm_control_panel.house": entity("alarm_control_panel.house", "disarmed"),
|
||||
},
|
||||
} as unknown as HomeAssistant;
|
||||
|
||||
const building = emptyBuilding();
|
||||
const floor = newFloor("g", "Ground", 0);
|
||||
floor.rooms = [
|
||||
{ id: "lounge", name: "Lounge", area_id: "lounge", points: [[0, 0], [4, 0], [4, 3], [0, 3]], floor_material: "wood" },
|
||||
{ id: "wc", name: "WC", area_id: "wc", points: [[4, 0], [6, 0], [6, 3], [4, 3]], floor_material: "tiles" },
|
||||
];
|
||||
const window: Opening = { id: "w1", room_id: "lounge", edge: 0, offset: 1, width: 1.2, type: "window", sill: 0.9, height: 1.3, hinge: "left", leaves: 1, swing: "in", cover: null, contact: "binary_sensor.casement", contact2: null, tilt: null };
|
||||
floor.openings = [window];
|
||||
building.floors = [floor];
|
||||
const links = new Map<string, OpeningEntities>([["w1", { cover: null, contact: "binary_sensor.casement", tilt: null }]]);
|
||||
return { hass, building, links };
|
||||
}
|
||||
|
||||
const set = (hass: HomeAssistant, id: string, state: string) => {
|
||||
hass.states[id] = { ...hass.states[id], state };
|
||||
};
|
||||
|
||||
test("only binary sensors with a warning class are picked, per room", () => {
|
||||
const { hass, building } = house();
|
||||
const sources = alertSources(hass, building);
|
||||
assert.deepEqual(sources.rooms, [
|
||||
{ floorId: "g", roomId: "lounge", sensors: ["binary_sensor.smoke"] },
|
||||
{ floorId: "g", roomId: "wc", sensors: ["binary_sensor.leak"] },
|
||||
]);
|
||||
assert.deepEqual(sources.alarms, ["alarm_control_panel.house"]);
|
||||
assert.equal(sources.weather, "weather.home");
|
||||
assert.equal(alertEntities(sources).length, 4);
|
||||
});
|
||||
|
||||
test("the rain warning can be switched off, which also stops watching the weather", () => {
|
||||
const { hass, building } = house();
|
||||
building.settings.rain_warning = false;
|
||||
const sources = alertSources(hass, building);
|
||||
assert.equal(sources.weather, null);
|
||||
assert.ok(!alertEntities(sources).includes("weather.home"));
|
||||
});
|
||||
|
||||
test("a quiet house has no warnings", () => {
|
||||
const { hass, building, links } = house();
|
||||
assert.deepEqual(findAlerts(hass, building, alertSources(hass, building), links), []);
|
||||
});
|
||||
|
||||
test("sensors and the alarm panel raise warnings, pending is its own kind", () => {
|
||||
const { hass, building, links } = house();
|
||||
const sources = alertSources(hass, building);
|
||||
set(hass, "binary_sensor.smoke", "on");
|
||||
set(hass, "binary_sensor.leak", "on");
|
||||
set(hass, "alarm_control_panel.house", "pending");
|
||||
let found = findAlerts(hass, building, sources, links);
|
||||
assert.deepEqual(found.map((a) => [a.kind, a.roomId]), [["smoke", "lounge"], ["water", "wc"], ["alarm_pending", null]]);
|
||||
set(hass, "alarm_control_panel.house", "triggered");
|
||||
found = findAlerts(hass, building, sources, links);
|
||||
assert.equal(found.at(-1)?.kind, "alarm");
|
||||
assert.equal(found.at(-1)?.floorId, null);
|
||||
});
|
||||
|
||||
test("an open window warns only while it rains", () => {
|
||||
const { hass, building, links } = house();
|
||||
const sources = alertSources(hass, building);
|
||||
set(hass, "binary_sensor.casement", "on");
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "dry weather");
|
||||
for (const rain of RAIN_STATES) {
|
||||
set(hass, "weather.home", rain);
|
||||
const [warning] = findAlerts(hass, building, sources, links);
|
||||
assert.equal(warning?.kind, "window_rain");
|
||||
assert.equal(warning?.roomId, "lounge");
|
||||
assert.equal(warning?.entity, "binary_sensor.casement");
|
||||
}
|
||||
set(hass, "binary_sensor.casement", "off");
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "closed window in the rain");
|
||||
});
|
||||
|
||||
test("colours: leaks are blue, pending is orange, the rest is red", () => {
|
||||
assert.deepEqual(alertColor("smoke"), alertColor("alarm"));
|
||||
assert.ok(alertColor("water")[2] > alertColor("water")[0]);
|
||||
assert.ok(alertColor("alarm_pending")[0] > alertColor("alarm_pending")[2]);
|
||||
});
|
||||
|
||||
test("the banner text names the room when there is one", () => {
|
||||
const { hass, building } = house();
|
||||
const inRoom = alertText(hass, building, { kind: "smoke", entity: "binary_sensor.smoke", roomId: "lounge", floorId: "g" });
|
||||
assert.ok(inRoom.startsWith("Lounge · "), inRoom);
|
||||
assert.ok(inRoom.includes("Smoke detector"), inRoom);
|
||||
const houseWide = alertText(hass, building, { kind: "alarm", entity: "alarm_control_panel.house", roomId: null, floorId: null });
|
||||
assert.ok(!houseWide.includes(" · "), houseWide);
|
||||
});
|
||||
|
||||
test("an own rain sensor decides instead of the weather, and a window can be left out", () => {
|
||||
const { hass, building, links } = house();
|
||||
hass.states["sensor.rain_rate"] = { entity_id: "sensor.rain_rate", state: "0", attributes: { unit_of_measurement: "mm/h" } };
|
||||
building.settings.rain_sensor = "sensor.rain_rate";
|
||||
const sources = alertSources(hass, building);
|
||||
assert.equal(sources.rain, "sensor.rain_rate");
|
||||
assert.ok(alertEntities(sources).includes("sensor.rain_rate"));
|
||||
set(hass, "binary_sensor.casement", "on");
|
||||
set(hass, "weather.home", "pouring");
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "the station says dry, the forecast does not count");
|
||||
set(hass, "sensor.rain_rate", "1.2");
|
||||
assert.equal(findAlerts(hass, building, sources, links)[0]?.kind, "window_rain");
|
||||
building.floors[0].openings[0].rain_warning = false;
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "a window under the awning stays quiet");
|
||||
});
|
||||
|
||||
test("an inverted rain sensor reads on / above zero as dry (#107)", () => {
|
||||
const { hass, building, links } = house();
|
||||
hass.states["binary_sensor.dry"] = { entity_id: "binary_sensor.dry", state: "on", attributes: {} };
|
||||
building.settings.rain_sensor = "binary_sensor.dry";
|
||||
building.settings.rain_sensor_inverted = true;
|
||||
set(hass, "binary_sensor.casement", "on");
|
||||
const sources = alertSources(hass, building);
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "on means dry");
|
||||
set(hass, "binary_sensor.dry", "off");
|
||||
assert.equal(findAlerts(hass, building, sources, links)[0]?.kind, "window_rain");
|
||||
set(hass, "binary_sensor.dry", "unavailable");
|
||||
assert.equal(findAlerts(hass, building, sources, links).length, 0, "unknown stays quiet, inverted or not");
|
||||
});
|
||||
|
||||
test("a power outage warns for the whole house, whatever kind of sensor tells it", () => {
|
||||
const { hass, building, links } = house();
|
||||
const cases: [string, string, Record<string, unknown>, boolean][] = [
|
||||
["binary_sensor.grid", "off", { device_class: "power" }, true],
|
||||
["binary_sensor.grid", "on", { device_class: "power" }, false],
|
||||
["binary_sensor.outage", "on", { device_class: "problem" }, true],
|
||||
["sensor.inverter_mode", "off_grid", {}, true],
|
||||
["sensor.inverter_mode", "on_grid", {}, false],
|
||||
["sensor.voltage", "3", { unit_of_measurement: "V" }, true],
|
||||
["sensor.voltage", "231", { unit_of_measurement: "V" }, false],
|
||||
["sensor.voltage", "unavailable", { unit_of_measurement: "V" }, false],
|
||||
];
|
||||
for (const [id, state, attributes, out] of cases) {
|
||||
hass.states[id] = { entity_id: id, state, attributes };
|
||||
building.settings.outage_sensor = id;
|
||||
assert.equal(isPowerOut(hass, id), out, `${id} = ${state}`);
|
||||
const found = findAlerts(hass, building, alertSources(hass, building), links);
|
||||
assert.equal(found.some((a) => a.kind === "power_outage" && a.roomId === null), out);
|
||||
}
|
||||
});
|
||||
|
||||
test("a contact that stays unavailable warns after the grace time, only when switched on, and quietly", () => {
|
||||
const { hass, building, links } = house();
|
||||
const now = Date.parse("2026-11-01T12:00:00Z");
|
||||
const lost = (minutes: number) => {
|
||||
hass.states["binary_sensor.casement"] = { ...hass.states["binary_sensor.casement"], state: "unavailable", last_changed: new Date(now - minutes * 60_000).toISOString() };
|
||||
};
|
||||
// off by default: not even watched
|
||||
assert.deepEqual(alertSources(hass, building, null, links).contacts, []);
|
||||
building.settings.contact_warning = true;
|
||||
const sources = alertSources(hass, building, null, links);
|
||||
assert.deepEqual(sources.contacts, [{ floorId: "g", roomId: "lounge", entity: "binary_sensor.casement" }]);
|
||||
assert.ok(alertEntities(sources).includes("binary_sensor.casement"));
|
||||
lost(3);
|
||||
assert.equal(contactsPending(hass, sources), true);
|
||||
assert.deepEqual(findAlerts(hass, building, sources, links, now), []);
|
||||
lost(CONTACT_GRACE_MS / 60_000);
|
||||
assert.deepEqual(findAlerts(hass, building, sources, links, now), [{ kind: "contact_lost", entity: "binary_sensor.casement", roomId: "lounge", floorId: "g" }]);
|
||||
assert.ok(QUIET_ALERTS.has("contact_lost"));
|
||||
set(hass, "binary_sensor.casement", "off");
|
||||
assert.equal(contactsPending(hass, sources), false);
|
||||
assert.deepEqual(findAlerts(hass, building, sources, links, now), []);
|
||||
});
|
||||
|
||||
test("a contact shared by two openings is watched once", () => {
|
||||
const { hass, building, links } = house();
|
||||
building.settings.contact_warning = true;
|
||||
building.floors[0].openings.push({ ...building.floors[0].openings[0], id: "w2", offset: 3 });
|
||||
links.set("w2", { cover: null, contact: "binary_sensor.casement", tilt: null });
|
||||
assert.equal(alertSources(hass, building, null, links).contacts!.length, 1);
|
||||
});
|
||||
|
||||
test("a triggered alarm names the sensor that set it off and pulses its room", () => {
|
||||
const at = Date.parse("2026-11-02T20:00:00Z");
|
||||
const iso = (ms: number) => new Date(ms).toISOString();
|
||||
const hass = hassOf(
|
||||
[
|
||||
{ entity_id: "alarm_control_panel.home", state: "triggered", attributes: {}, last_changed: iso(at) },
|
||||
{ entity_id: "binary_sensor.front_door", state: "on", attributes: { device_class: "door", friendly_name: "Haustür" }, last_changed: iso(at - 3000) },
|
||||
{ entity_id: "binary_sensor.hall_motion", state: "on", attributes: { device_class: "motion" }, last_changed: iso(at - 60_000) },
|
||||
],
|
||||
{ "binary_sensor.front_door": { area_id: "flur" } },
|
||||
);
|
||||
assert.equal(alarmCause(hass, "alarm_control_panel.home"), "binary_sensor.front_door");
|
||||
const alarmo = hassOf([{ entity_id: "alarm_control_panel.alarmo", state: "triggered", attributes: { open_sensors: { "binary_sensor.window_kitchen": "on" } } }]);
|
||||
assert.equal(alarmCause(alarmo, "alarm_control_panel.alarmo"), "binary_sensor.window_kitchen", "Alarmo tells it");
|
||||
const b = emptyBuilding();
|
||||
b.floors = [{ ...newFloor("g", "EG", 0), rooms: [{ id: "r", name: "Flur", area_id: "flur", points: [[0, 0], [2, 0], [2, 2]], floor_material: "wood" }] }];
|
||||
const alerts = findAlerts(hass, b, alertSources(hass, b), new Map());
|
||||
assert.equal(alerts[0].roomId, "r");
|
||||
assert.equal(alerts[0].cause, "binary_sensor.front_door");
|
||||
});
|
||||
|
||||
test("own warnings: a state, one of several, or a number below or above a value", () => {
|
||||
const hass = hassOf([entity2("binary_sensor.robot_tank", "on"), entity2("sensor.dishwasher", "Finished"), entity2("sensor.salt", "12")]);
|
||||
assert.equal(ownAlertMet(hass, { entity: "binary_sensor.robot_tank", state: null }), true, "on by default");
|
||||
assert.equal(ownAlertMet(hass, { entity: "sensor.dishwasher", state: "done, finished" }), true);
|
||||
assert.equal(ownAlertMet(hass, { entity: "sensor.salt", state: "<20" }), true);
|
||||
assert.equal(ownAlertMet(hass, { entity: "sensor.salt", state: ">20" }), false);
|
||||
const b = emptyBuilding();
|
||||
b.settings.own_alerts = [{ id: "a", entity: "sensor.dishwasher", state: "finished", text: "Dishwasher done" }];
|
||||
const alerts = findAlerts(hass, b, alertSources(hass, b), new Map());
|
||||
assert.equal(alerts[0].kind, "own");
|
||||
assert.equal(alertText(hass, b, alerts[0]), "Dishwasher done");
|
||||
});
|
||||
|
||||
test("an unlocked door lock warns at night only, and only with the warning on", () => {
|
||||
const hass = hassOf([entity("lock.front", "unlocked")]);
|
||||
const b = emptyBuilding();
|
||||
b.floors = [{ ...floorWith([box("f", 0, 0, 3, 3)]), openings: [opening("d", "f", "door", { lock: "lock.front" })] }];
|
||||
const night = new Date(2026, 10, 3, 23, 0).getTime();
|
||||
const day = new Date(2026, 10, 3, 14, 0).getTime();
|
||||
assert.equal(findAlerts(hass, b, alertSources(hass, b), new Map(), night).filter((a) => a.kind === "unlocked_night").length, 0);
|
||||
b.settings = { ...b.settings, night_lock_warning: true };
|
||||
const sources = alertSources(hass, b);
|
||||
assert.deepEqual(findAlerts(hass, b, sources, new Map(), night).filter((a) => a.kind === "unlocked_night").map((a) => a.entity), ["lock.front"]);
|
||||
assert.equal(findAlerts(hass, b, sources, new Map(), day).filter((a) => a.kind === "unlocked_night").length, 0);
|
||||
assert.ok(alertEntities(sources).includes("lock.front"));
|
||||
});
|
||||
@@ -0,0 +1,313 @@
|
||||
// Warnings in the 3D view: smoke, gas, carbon monoxide and leak sensors of a room, an alarm panel that
|
||||
// went off, a power outage, a window left open in the rain, and a door or window contact that stopped answering.
|
||||
// A room with a warning pulses in the warning's colour.
|
||||
|
||||
import { entityAreaId, entityName, openingState, type OpeningEntities, roomEntities } from "./devices.ts";
|
||||
import { translate } from "./i18n.ts";
|
||||
import { pointInPolygon, type Building, type Opening, type OwnAlert } from "./model.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { weatherEntity } from "./weather.ts";
|
||||
|
||||
export type AlertKind = "smoke" | "gas" | "co" | "water" | "alarm" | "alarm_pending" | "window_rain" | "power_outage" | "contact_lost" | "unlocked_night" | "own";
|
||||
|
||||
export interface Alert {
|
||||
kind: AlertKind;
|
||||
entity: string;
|
||||
/** Room and floor it concerns; null for the whole house (an alarm). */
|
||||
roomId: string | null;
|
||||
floorId: string | null;
|
||||
/** An alarm: the sensor that set it off (a door, a window, a motion sensor), when it can be told. */
|
||||
cause?: string;
|
||||
/** An own warning: its text, and its colour ("#rrggbb", the stripe on the left). */
|
||||
text?: string;
|
||||
color?: string;
|
||||
/** An own warning: what a tap does (null: open the entity's details). */
|
||||
tap?: OwnAlert["tap"];
|
||||
}
|
||||
|
||||
/** Where the warnings come from. Looked up once and kept until the registries change. */
|
||||
export interface AlertSources {
|
||||
rooms: { floorId: string; roomId: string; sensors: string[] }[];
|
||||
alarms: string[];
|
||||
weather: string | null;
|
||||
/** An own rain sensor (a weather station): it decides instead of the weather entity's condition. */
|
||||
rain: string | null;
|
||||
/** The rain sensor says "dry" where it reads on / above zero (some stations and KNX sensors work that way). */
|
||||
rainInverted?: boolean;
|
||||
/** A sensor that tells a power outage (grid gone). */
|
||||
outage: string | null;
|
||||
/** The contacts of doors and windows, watched for going unavailable (empty unless that warning is on). */
|
||||
contacts?: { floorId: string; roomId: string; entity: string }[];
|
||||
/** Own warnings of the plan (House → Own warnings). */
|
||||
own?: OwnAlert[];
|
||||
/** The door locks of the plan, watched at night (empty unless that warning is on). */
|
||||
locks?: { floorId: string; roomId: string; entity: string }[];
|
||||
}
|
||||
|
||||
/** Warnings that only show in the banner: the room does not pulse and the view does not jump to it. */
|
||||
export const QUIET_ALERTS: ReadonlySet<AlertKind> = new Set<AlertKind>(["contact_lost", "unlocked_night", "own"]);
|
||||
|
||||
/**
|
||||
* Whether an own warning's condition is met: the entity is in one of the states (comma separated, any case), or its number is below
|
||||
* ("<20") or above (">80") a value. An unavailable entity never warns.
|
||||
*/
|
||||
export function ownAlertMet(hass: HomeAssistant, rule: Pick<OwnAlert, "entity" | "state">): boolean {
|
||||
const st = hass.states[rule.entity];
|
||||
if (!st || ["unavailable", "unknown"].includes(st.state)) return false;
|
||||
const want = (rule.state ?? "on").trim();
|
||||
const m = /^([<>])\s*(-?\d+(?:[.,]\d+)?)$/.exec(want);
|
||||
if (m) {
|
||||
const v = Number(st.state);
|
||||
const limit = Number(m[2].replace(",", "."));
|
||||
return Number.isFinite(v) && (m[1] === "<" ? v < limit : v > limit);
|
||||
}
|
||||
return want.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean).includes(String(st.state).toLowerCase());
|
||||
}
|
||||
|
||||
/** How long a contact has to be unavailable before it warns: a restart of Home Assistant or a short radio gap does not. */
|
||||
export const CONTACT_GRACE_MS = 10 * 60 * 1000;
|
||||
|
||||
/** Weather conditions that wet a window. */
|
||||
export const RAIN_STATES = new Set(["rainy", "pouring", "lightning-rainy", "hail", "snowy-rainy"]);
|
||||
|
||||
/** device_class of a binary sensor -> the warning it raises. */
|
||||
const SENSOR_WARNING = new Map<string, AlertKind>([
|
||||
["smoke", "smoke"],
|
||||
["gas", "gas"],
|
||||
["carbon_monoxide", "co"],
|
||||
["moisture", "water"],
|
||||
]);
|
||||
|
||||
const warningOf = (hass: HomeAssistant, entityId: string): AlertKind | undefined => {
|
||||
if (!entityId.startsWith("binary_sensor.")) return undefined;
|
||||
return SENSOR_WARNING.get(String(hass.states[entityId]?.attributes.device_class));
|
||||
};
|
||||
|
||||
/** The contact and tilt sensors of every door, window and garage door, each once. */
|
||||
function openingContacts(building: Building, links: Map<string, OpeningEntities>): NonNullable<AlertSources["contacts"]> {
|
||||
const seen = new Set<string>();
|
||||
const found: NonNullable<AlertSources["contacts"]> = [];
|
||||
for (const floor of building.floors) {
|
||||
for (const o of floor.openings) {
|
||||
const link = links.get(o.id);
|
||||
for (const entity of link ? [link.contact, link.contact2, link.tilt, link.tilt2] : []) {
|
||||
if (!entity || seen.has(entity)) continue;
|
||||
seen.add(entity);
|
||||
found.push({ floorId: floor.id, roomId: o.room_id, entity });
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Warning sensors per room, the alarm panels, and the weather entity (none when the rain warning is off). */
|
||||
export function alertSources(hass: HomeAssistant, building: Building, weatherId?: string | null, links?: Map<string, OpeningEntities>): AlertSources {
|
||||
const rooms: AlertSources["rooms"] = [];
|
||||
for (const floor of building.floors) {
|
||||
for (const room of floor.rooms) {
|
||||
const sensors = roomEntities(hass, room).filter((id) => warningOf(hass, id));
|
||||
if (sensors.length > 0) rooms.push({ floorId: floor.id, roomId: room.id, sensors });
|
||||
}
|
||||
}
|
||||
const rainWarningOn = building.settings.rain_warning !== false;
|
||||
const rain = building.settings.rain_sensor;
|
||||
return {
|
||||
rooms,
|
||||
alarms: Object.keys(hass.states).filter((id) => id.startsWith("alarm_control_panel.")),
|
||||
weather: rainWarningOn ? weatherEntity(hass, weatherId ?? building.settings.weather_entity) : null,
|
||||
rain: rainWarningOn && rain && rain !== "none" ? rain : null,
|
||||
rainInverted: !!building.settings.rain_sensor_inverted,
|
||||
outage: building.settings.outage_sensor && building.settings.outage_sensor !== "none" ? building.settings.outage_sensor : null,
|
||||
contacts: building.settings.contact_warning && links ? openingContacts(building, links) : [],
|
||||
own: (building.settings.own_alerts ?? []).filter((r) => r.entity),
|
||||
locks: building.settings.night_lock_warning
|
||||
? building.floors.flatMap((f) => f.openings.filter((o) => o.lock && o.lock !== "none").map((o) => ({ entity: o.lock!, roomId: o.room_id, floorId: f.id })))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Every entity whose change can raise or clear a warning. */
|
||||
export function alertEntities(sources: AlertSources): string[] {
|
||||
const ids = sources.rooms.flatMap((r) => r.sensors).concat(sources.alarms);
|
||||
for (const id of [sources.weather, sources.rain, sources.outage]) if (id) ids.push(id);
|
||||
for (const c of sources.contacts ?? []) ids.push(c.entity);
|
||||
for (const r of sources.own ?? []) ids.push(r.entity);
|
||||
for (const l of sources.locks ?? []) ids.push(l.entity);
|
||||
return ids;
|
||||
}
|
||||
|
||||
function sensorWarnings(hass: HomeAssistant, sources: AlertSources): Alert[] {
|
||||
const found: Alert[] = [];
|
||||
for (const { floorId, roomId, sensors } of sources.rooms) {
|
||||
for (const entity of sensors) {
|
||||
const kind = warningOf(hass, entity);
|
||||
if (kind && hass.states[entity]?.state === "on") found.push({ kind, entity, roomId, floorId });
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
const isAjar = (hass: HomeAssistant, link: OpeningEntities): boolean => {
|
||||
const s = openingState(hass, link, "window");
|
||||
return Math.max(s.open, s.tilt, s.open2, s.tilt2) >= 0.5;
|
||||
};
|
||||
|
||||
/** Whether it rains: an own rain sensor (on, or a rain rate above zero) wins over the weather entity's condition. */
|
||||
export function isRaining(hass: HomeAssistant, sources: Pick<AlertSources, "weather" | "rain" | "rainInverted">): boolean {
|
||||
if (sources.rain) {
|
||||
const st = hass.states[sources.rain];
|
||||
if (!st || st.state === "unavailable" || st.state === "unknown") return false;
|
||||
const rate = Number(st.state);
|
||||
const wet = Number.isFinite(rate) ? rate > 0 : st.state === "on" || /rain|regen|wet|nass/i.test(st.state);
|
||||
return sources.rainInverted ? !wet : wet;
|
||||
}
|
||||
const weather = sources.weather ? hass.states[sources.weather]?.state : undefined;
|
||||
return !!weather && RAIN_STATES.has(weather);
|
||||
}
|
||||
|
||||
const OUTAGE_WORDS = /^(off_grid|off-grid|outage|grid_down|grid_lost|islanding|island|backup|no_grid|stromausfall|netzausfall|inselbetrieb)$/i;
|
||||
|
||||
/**
|
||||
* Whether the power is out, from the outage sensor: a binary sensor of class power (or plug) that says off, any other binary sensor that
|
||||
* says on, a sensor with a state like "off_grid" / "backup", or a voltage that dropped below 50 V.
|
||||
*/
|
||||
export function isPowerOut(hass: HomeAssistant, id: string | null): boolean {
|
||||
const st = id ? hass.states[id] : undefined;
|
||||
if (!st || st.state === "unavailable" || st.state === "unknown") return false;
|
||||
if (id!.startsWith("binary_sensor.")) {
|
||||
const cls = String(st.attributes.device_class ?? "");
|
||||
return cls === "power" || cls === "plug" ? st.state === "off" : st.state === "on";
|
||||
}
|
||||
const value = Number(st.state);
|
||||
if (Number.isFinite(value)) return st.attributes.unit_of_measurement === "V" && value < 50;
|
||||
return OUTAGE_WORDS.test(st.state.trim());
|
||||
}
|
||||
|
||||
function rainWarnings(hass: HomeAssistant, building: Building, sources: AlertSources, links: Map<string, OpeningEntities>): Alert[] {
|
||||
if (!isRaining(hass, sources)) return [];
|
||||
const found: Alert[] = [];
|
||||
for (const floor of building.floors) {
|
||||
for (const opening of floor.openings as Opening[]) {
|
||||
const link = links.get(opening.id);
|
||||
// a window under a roof or an awning can be left out of the rain warning
|
||||
if (opening.type !== "window" || opening.rain_warning === false || !link || !isAjar(hass, link)) continue;
|
||||
found.push({ kind: "window_rain", entity: link.contact ?? link.tilt ?? link.contact2 ?? opening.id, roomId: opening.room_id, floorId: floor.id });
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
const TRIGGER_CLASSES = new Set(["door", "window", "opening", "garage_door", "motion", "occupancy", "presence", "vibration", "tamper", "sound", "glass"]);
|
||||
|
||||
/**
|
||||
* The sensor that set an alarm off: Alarmo names the open sensors itself; otherwise the door, window or motion sensor that changed to
|
||||
* "on" closest before the alarm went off (within two minutes).
|
||||
*/
|
||||
export function alarmCause(hass: HomeAssistant, panel: string): string | null {
|
||||
const st = hass.states[panel];
|
||||
const open = st?.attributes.open_sensors;
|
||||
if (open && typeof open === "object") {
|
||||
const first = Object.keys(open as Record<string, unknown>)[0];
|
||||
if (first) return first;
|
||||
}
|
||||
const at = Date.parse(st?.last_changed ?? "");
|
||||
if (!Number.isFinite(at)) return null;
|
||||
let best: string | null = null;
|
||||
let gap = 120_000;
|
||||
for (const s of Object.values(hass.states)) {
|
||||
if (!s.entity_id.startsWith("binary_sensor.") || !TRIGGER_CLASSES.has(String(s.attributes.device_class ?? "")) || s.state !== "on") continue;
|
||||
const changed = Date.parse(s.last_changed ?? "");
|
||||
const d = at - changed;
|
||||
if (Number.isFinite(changed) && d >= -5_000 && Math.abs(d) < gap) {
|
||||
gap = Math.abs(d);
|
||||
best = s.entity_id;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The room a sensor belongs to: where it is placed, else the room of its area. */
|
||||
function roomOf(hass: HomeAssistant, building: Building, entity: string): { roomId: string; floorId: string } | null {
|
||||
for (const floor of building.floors) {
|
||||
const placed = floor.placements.find((p) => p.entity_id === entity);
|
||||
const room = placed ? floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([placed.x, placed.z], r.points)) : undefined;
|
||||
if (room) return { roomId: room.id, floorId: floor.id };
|
||||
}
|
||||
const area = entityAreaId(hass, entity);
|
||||
for (const floor of building.floors) {
|
||||
const room = area ? floor.rooms.find((r) => r.area_id === area) : undefined;
|
||||
if (room) return { roomId: room.id, floorId: floor.id };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function alarmWarnings(hass: HomeAssistant, sources: AlertSources, building: Building): Alert[] {
|
||||
const found: Alert[] = [];
|
||||
for (const entity of sources.alarms) {
|
||||
const state = hass.states[entity]?.state;
|
||||
if (state === "triggered") {
|
||||
// the room of the sensor that set it off pulses, and the banner names it
|
||||
const cause = alarmCause(hass, entity);
|
||||
const where = cause ? roomOf(hass, building, cause) : null;
|
||||
found.push({ kind: "alarm", entity, roomId: where?.roomId ?? null, floorId: where?.floorId ?? null, ...(cause ? { cause } : {}) });
|
||||
}
|
||||
if (state === "pending") found.push({ kind: "alarm_pending", entity, roomId: null, floorId: null });
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A contact that has been unavailable for longer than the grace time (a deleted entity does not warn, it is just gone). */
|
||||
export function contactLost(hass: HomeAssistant, entity: string, now: number): boolean {
|
||||
const st = hass.states[entity];
|
||||
if (st?.state !== "unavailable") return false;
|
||||
const since = Date.parse(st.last_changed ?? "");
|
||||
return !Number.isFinite(since) || now - since >= CONTACT_GRACE_MS;
|
||||
}
|
||||
|
||||
/** Contacts that went unavailable but are still within the grace time: the view looks again once it has passed. */
|
||||
export function contactsPending(hass: HomeAssistant, sources: AlertSources): boolean {
|
||||
return (sources.contacts ?? []).some((c) => hass.states[c.entity]?.state === "unavailable");
|
||||
}
|
||||
|
||||
function contactWarnings(hass: HomeAssistant, sources: AlertSources, now: number): Alert[] {
|
||||
return (sources.contacts ?? []).filter((c) => contactLost(hass, c.entity, now)).map((c) => ({ kind: "contact_lost", entity: c.entity, roomId: c.roomId, floorId: c.floorId }));
|
||||
}
|
||||
|
||||
/** The warnings that are active now: room sensors, then windows in the rain, then house-wide alarms and a power outage, then lost contacts. */
|
||||
export function findAlerts(hass: HomeAssistant, building: Building, sources: AlertSources, links: Map<string, OpeningEntities>, now = Date.now()): Alert[] {
|
||||
const outage: Alert[] = sources.outage && isPowerOut(hass, sources.outage) ? [{ kind: "power_outage", entity: sources.outage, roomId: null, floorId: null }] : [];
|
||||
const own: Alert[] = (sources.own ?? []).filter((r) => ownAlertMet(hass, r)).map((r) => {
|
||||
const room = r.room_id ? building.floors.find((f) => f.rooms.some((x) => x.id === r.room_id)) : undefined;
|
||||
return { kind: "own", entity: r.entity, roomId: room ? r.room_id! : null, floorId: room?.id ?? null, text: r.text, ...(r.color ? { color: r.color } : {}), ...(r.tap ? { tap: r.tap } : {}) };
|
||||
});
|
||||
// door locks left unlocked between 22:00 and 6:00
|
||||
const hour = new Date(now).getHours();
|
||||
const night = hour >= 22 || hour < 6;
|
||||
const unlocked: Alert[] = night ? (sources.locks ?? []).filter((l) => hass.states[l.entity]?.state === "unlocked").map((l) => ({ kind: "unlocked_night", entity: l.entity, roomId: l.roomId, floorId: l.floorId })) : [];
|
||||
return [...sensorWarnings(hass, sources), ...rainWarnings(hass, building, sources, links), ...alarmWarnings(hass, sources, building), ...outage, ...contactWarnings(hass, sources, now), ...unlocked, ...own];
|
||||
}
|
||||
|
||||
const PULSE: Record<AlertKind, [number, number, number]> = {
|
||||
smoke: [1, 0.2, 0.25],
|
||||
gas: [1, 0.2, 0.25],
|
||||
co: [1, 0.2, 0.25],
|
||||
alarm: [1, 0.2, 0.25],
|
||||
water: [0.2, 0.6, 1],
|
||||
window_rain: [0.35, 0.72, 1],
|
||||
alarm_pending: [1, 0.62, 0.2],
|
||||
power_outage: [1, 0.62, 0.2],
|
||||
contact_lost: [1, 0.62, 0.2],
|
||||
unlocked_night: [1, 0.62, 0.2],
|
||||
own: [1, 0.62, 0.2],
|
||||
};
|
||||
|
||||
/** The colour a room pulses in (channels 0..1). */
|
||||
export const alertColor = (kind: AlertKind): [number, number, number] => PULSE[kind];
|
||||
|
||||
/** One line for the banner, e.g. "Kitchen · Smoke: smoke detector". */
|
||||
export function alertText(hass: HomeAssistant | undefined, building: Building, a: Alert): string {
|
||||
const name = hass ? entityName(hass, a.entity) : a.entity;
|
||||
const message = a.kind === "own" ? a.text || name : a.cause ? translate(hass, "alert_alarm_by", { name, cause: hass ? entityName(hass, a.cause) : a.cause }) : translate(hass, `alert_${a.kind}` as Parameters<typeof translate>[1], { name });
|
||||
const room = a.roomId === null ? undefined : building.floors.flatMap((f) => f.rooms).find((r) => r.id === a.roomId);
|
||||
return room ? `${room.name} · ${message}` : message;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// The calls NextFloor makes to its backend over the Home Assistant websocket
|
||||
// (custom_components/nextfloor/websocket.py).
|
||||
|
||||
import type { Building } from "./model.ts";
|
||||
import type { FurniturePack } from "./packs.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
|
||||
/** Sends one command of this integration. */
|
||||
const call = <T = unknown>(hass: HomeAssistant, command: string, payload: Record<string, unknown> = {}): Promise<T> => hass.callWS<T>({ type: `nextfloor/${command}`, ...payload });
|
||||
|
||||
export const fetchBuilding = (hass: HomeAssistant) => call<{ building: Building; revision: number; version?: string }>(hass, "building/get");
|
||||
|
||||
/** Saves the plan and returns its new revision. */
|
||||
export async function saveBuilding(hass: HomeAssistant, building: Building): Promise<number> {
|
||||
return (await call<{ revision: number }>(hass, "building/save", { building })).revision;
|
||||
}
|
||||
|
||||
/** Calls back with the new revision whenever the plan is saved anywhere. Resolves to the unsubscribe function. */
|
||||
export function subscribeBuilding(hass: HomeAssistant, onRevision: (revision: number) => void): Promise<() => Promise<void>> {
|
||||
return hass.connection.subscribeMessage<{ revision: number }>((event) => onRevision(event.revision), { type: "nextfloor/building/subscribe" });
|
||||
}
|
||||
|
||||
/** A stored picture as a data string. */
|
||||
export async function fetchImage(hass: HomeAssistant, imageId: string): Promise<string> {
|
||||
return (await call<{ data: string }>(hass, "image/get", { image_id: imageId })).data;
|
||||
}
|
||||
|
||||
export async function storeImage(hass: HomeAssistant, imageId: string, data: string): Promise<void> {
|
||||
await call(hass, "image/set", { image_id: imageId, data });
|
||||
}
|
||||
|
||||
/** An automatic copy of the plan the user can go back to. */
|
||||
export interface Snapshot {
|
||||
id: string;
|
||||
revision: number;
|
||||
/** Unix time in seconds. */
|
||||
saved_at: number;
|
||||
floors: number;
|
||||
rooms: number;
|
||||
furniture: number;
|
||||
/** A named version ("before the renovation"); unnamed points come and go by themselves. */
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export async function listHistory(hass: HomeAssistant): Promise<Snapshot[]> {
|
||||
return (await call<{ snapshots: Snapshot[] }>(hass, "history/list")).snapshots;
|
||||
}
|
||||
|
||||
/** Keeps the plan as a restore point, or as a named version; returns its id. */
|
||||
export async function takeSnapshot(hass: HomeAssistant, name?: string): Promise<string> {
|
||||
return (await call<{ id: string }>(hass, "history/snapshot", name ? { name } : {})).id;
|
||||
}
|
||||
|
||||
/** The plan of a restore point, to compare it with the current one. */
|
||||
export async function getSnapshot(hass: HomeAssistant, snapshotId: string): Promise<Building> {
|
||||
return (await call<{ building: Building }>(hass, "history/get", { snapshot_id: snapshotId })).building;
|
||||
}
|
||||
|
||||
export async function deleteSnapshot(hass: HomeAssistant, snapshotId: string): Promise<void> {
|
||||
await call(hass, "history/delete", { snapshot_id: snapshotId });
|
||||
}
|
||||
|
||||
/** Goes back to a snapshot and returns the new revision. */
|
||||
export async function restoreSnapshot(hass: HomeAssistant, snapshotId: string): Promise<number> {
|
||||
return (await call<{ revision: number }>(hass, "history/restore", { snapshot_id: snapshotId })).revision;
|
||||
}
|
||||
|
||||
export async function listPacks(hass: HomeAssistant): Promise<FurniturePack[]> {
|
||||
return (await call<{ packs: FurniturePack[] }>(hass, "packs/list")).packs;
|
||||
}
|
||||
|
||||
export interface ImportedPack {
|
||||
id: string;
|
||||
name: string;
|
||||
publisher: string;
|
||||
items: number;
|
||||
}
|
||||
|
||||
/** Imports a pack file. The backend validates it and rejects with a code such as "invalid_content". */
|
||||
export const importPack = (hass: HomeAssistant, text: string) => call<ImportedPack>(hass, "packs/import", { pack: text });
|
||||
|
||||
export async function removePack(hass: HomeAssistant, packId: string): Promise<void> {
|
||||
await call(hass, "packs/remove", { pack_id: packId });
|
||||
}
|
||||
|
||||
/** A complete backup: the plan, the packs and every stored picture. */
|
||||
export interface BackupFile {
|
||||
format: "nextfloor-backup";
|
||||
version: 1;
|
||||
exported_at?: string;
|
||||
building: Building;
|
||||
packs?: FurniturePack[];
|
||||
images?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const fetchBackup = (hass: HomeAssistant) => call<Pick<BackupFile, "format" | "version" | "building" | "packs">>(hass, "backup/export");
|
||||
|
||||
/** Replaces plan and packs from a backup (pictures are sent one by one afterwards). Packs failing validation are skipped. */
|
||||
export const restoreBackup = (hass: HomeAssistant, building: Building, packs: FurniturePack[]) =>
|
||||
call<{ revision: number; building: Building; packs: number; skipped: { id: string; reason: string }[] }>(hass, "backup/import", { building, packs });
|
||||
@@ -0,0 +1,87 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { BufferGeometry } from "three";
|
||||
import type { Floor, Room, RoofSection } from "./model.ts";
|
||||
import { newFloor } from "./model.ts";
|
||||
import { headroomLines, ROOF_THICK, roofUnderAt } from "./roof-sections.ts";
|
||||
import { buildFloorGeometry } from "./viewer/build.ts";
|
||||
|
||||
function rect(id: string, x0: number, z0: number, x1: number, z1: number): Room {
|
||||
return { id, name: id, area_id: null, points: [[x0, z0], [x1, z0], [x1, z1], [x0, z1]], floor_material: "wood" };
|
||||
}
|
||||
|
||||
/** A gable section over x 0–8, z 0–6 with its ridge along x: eaves at 3.7 m, 40° slopes, walls from 3.7 m. */
|
||||
const section: RoofSection = { id: "s", x0: -0.24, z0: -0.24, x1: 8.24, z1: 6.24, shape: "gable", axis: "x", eave_a: 3.7, eave_b: 3.7, pitch_a: 40, pitch_b: 40, base: 3.7 };
|
||||
const building = { settings: { roof: { type: "custom" as const, pitch: 35, overhang: 0.4, sections: [section] } } };
|
||||
|
||||
function maxY(g: BufferGeometry, where: (x: number, z: number) => boolean): number {
|
||||
const p = g.getAttribute("position");
|
||||
let m = -Infinity;
|
||||
for (let i = 0; i < p.count; i++) if (where(p.getX(i), p.getZ(i))) m = Math.max(m, p.getY(i));
|
||||
return m;
|
||||
}
|
||||
|
||||
test("the roof's underside follows the section's profile, minus the slab", () => {
|
||||
const tan40 = Math.tan((40 * Math.PI) / 180);
|
||||
// at the eave side the roof sits on the knee wall
|
||||
assert.ok(Math.abs(roofUnderAt(building, 4, -0.24)! - (3.7 - ROOF_THICK)) < 1e-9);
|
||||
// one metre in, it has risen by tan(40°)
|
||||
assert.ok(Math.abs(roofUnderAt(building, 4, 0.76)! - (3.7 + tan40 - ROOF_THICK)) < 1e-9);
|
||||
// outside the section there is no roof
|
||||
assert.equal(roofUnderAt(building, 20, 20), null);
|
||||
// a canopy does not count
|
||||
assert.equal(roofUnderAt({ settings: { roof: { ...building.settings.roof, sections: [{ ...section, open: true }] } } }, 4, 3), null);
|
||||
});
|
||||
|
||||
test("an attic floor's walls end under the slope: knee walls at the eaves, gables up to the ridge", () => {
|
||||
const floor: Floor = { ...newFloor("og", "OG", 2.75), height: 2.5, rooms: [rect("a", 0, 0, 8, 6)] };
|
||||
const under = (x: number, z: number) => {
|
||||
const y = roofUnderAt(building, x, z);
|
||||
return y === null ? null : y - floor.elevation;
|
||||
};
|
||||
const geo = buildFloorGeometry(floor, 0.24, 0.12, [], [], under);
|
||||
const tan40 = Math.tan((40 * Math.PI) / 180);
|
||||
const knee = 3.7 - ROOF_THICK - 2.75;
|
||||
// the long wall along z = 0 is a knee wall: its inner face (0.24 m in from the eave) ends where the slope is
|
||||
const eaveWall = maxY(geo.walls, (x, z) => z < 0.1 && x > 1 && x < 7);
|
||||
assert.ok(Math.abs(eaveWall - (knee + 0.24 * tan40)) < 0.02, `knee wall top ${eaveWall}`);
|
||||
// the gable wall along x = 0 reaches almost the full height under the ridge (ridge at 3.7 + 3·tan40 ≈ 6.2 m)
|
||||
const gable = maxY(geo.walls, (x, z) => x < 0.1 && z > 2.5 && z < 3.5);
|
||||
assert.ok(gable > 2.4, `gable top ${gable}`);
|
||||
// without a roof the same wall is a plain box
|
||||
const plain = buildFloorGeometry(floor, 0.24, 0.12);
|
||||
assert.ok(Math.abs(maxY(plain.walls, () => true) - 2.5) < 1e-6);
|
||||
});
|
||||
|
||||
test("a window stays below the slope", () => {
|
||||
const floor: Floor = {
|
||||
...newFloor("og", "OG", 2.75),
|
||||
height: 2.5,
|
||||
rooms: [rect("a", 0, 0, 8, 6)],
|
||||
openings: [{ id: "w", room_id: "a", edge: 0, offset: 4, width: 1, type: "window", sill: 0.3, height: 1.4, hinge: "left", leaves: 1, swing: "in", cover: null, contact: null, contact2: null, tilt: null }],
|
||||
};
|
||||
const under = (x: number, z: number) => {
|
||||
const y = roofUnderAt(building, x, z);
|
||||
return y === null ? null : y - floor.elevation;
|
||||
};
|
||||
const geo = buildFloorGeometry(floor, 0.24, 0.12, [], [], under);
|
||||
// the opening sits on the room edge (z = 0), 0.24 m in from the eave
|
||||
const top = geo.openings[0].top;
|
||||
const roofThere = 3.7 - ROOF_THICK - 2.75 + 0.24 * Math.tan((40 * Math.PI) / 180);
|
||||
assert.ok(top <= roofThere - 0.02 + 1e-9 && top > roofThere - 0.1, `window top ${top}`);
|
||||
});
|
||||
|
||||
test("headroom lines run along the ridge where the slope leaves 1.5 m", () => {
|
||||
const lines = headroomLines(building, 2.75, 1.5);
|
||||
// one line per slope, both along x
|
||||
assert.equal(lines.length, 2);
|
||||
for (const [p, q] of lines) {
|
||||
assert.ok(Math.abs(p[1] - q[1]) < 1e-9, "along the ridge");
|
||||
assert.ok(Math.abs(p[0] - q[0]) > 8, "across the whole section");
|
||||
// 1.5 m above the floor plus the slab: (2.75 + 1.5 + 0.14 - 3.7) / tan40 ≈ 0.82 m in from the eave
|
||||
const v = Math.min(p[1] + 0.24, 6.24 - p[1]);
|
||||
assert.ok(Math.abs(v - (2.75 + 1.5 + ROOF_THICK - 3.7) / Math.tan((40 * Math.PI) / 180)) < 1e-6, `at ${v}`);
|
||||
}
|
||||
// a flat section has no slope and no line
|
||||
assert.equal(headroomLines({ settings: { roof: { ...building.settings.roof, sections: [{ ...section, shape: "flat" }] } } }, 2.75, 1.5).length, 0);
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { backdropStyle } from "./backdrop.ts";
|
||||
import { lookNow } from "./themes.ts";
|
||||
|
||||
test("an own background is a colour or a dimmed picture; anything unsafe is left out", () => {
|
||||
assert.equal(backdropStyle(null), "");
|
||||
assert.equal(backdropStyle({ color: "#112233" }), ";background:#112233");
|
||||
assert.match(backdropStyle({ image: "/local/garden.jpg", dim: 0.5 }), /rgba\(0,0,0,0\.5\).*url\("\/local\/garden\.jpg"\)/);
|
||||
assert.equal(backdropStyle({ image: "javascript:alert(1)" }), "");
|
||||
assert.equal(backdropStyle({ image: '/local/a.jpg") ; x: url("evil' }), "");
|
||||
assert.equal(backdropStyle({ color: "red; position:fixed" }), "");
|
||||
assert.match(backdropStyle({ image: "https://example.org/bg.png", dim: 5 }), /rgba\(0,0,0,0\.8\)/, "dimming stops at 80 %");
|
||||
});
|
||||
|
||||
test("the auto look is day while the sun is up and neon otherwise", () => {
|
||||
assert.equal(lookNow("auto", "above_horizon"), "day");
|
||||
assert.equal(lookNow("auto", "below_horizon"), "neon");
|
||||
assert.equal(lookNow("auto", undefined), "neon");
|
||||
assert.equal(lookNow("blueprint", "above_horizon"), "blueprint");
|
||||
assert.equal(lookNow(undefined, undefined), "neon");
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// The own background behind the house (building settings → backdrop), as CSS for the 3D stage.
|
||||
|
||||
import type { Building } from "./model.ts";
|
||||
|
||||
/** The own background behind the house: a colour, or a picture (from Home Assistant or https) dimmed a little. */
|
||||
export function backdropStyle(b: Building["settings"]["backdrop"]): string {
|
||||
if (!b) return "";
|
||||
const dim = Math.min(0.8, Math.max(0, b.dim ?? 0.35));
|
||||
const image = b.image && /^(https:\/\/|\/local\/|\/api\/)[^"'()\\\s]+$/.test(b.image) ? b.image : null;
|
||||
const color = b.color && /^#[0-9a-f]{6}$/i.test(b.color) ? b.color : null;
|
||||
if (image) return `;background:linear-gradient(rgba(0,0,0,${dim}),rgba(0,0,0,${dim})),center / cover no-repeat url("${image}")${color ? ` ${color}` : ""}`;
|
||||
return color ? `;background:${color}` : "";
|
||||
}
|
||||
@@ -0,0 +1,715 @@
|
||||
// The furniture builder page: a pack of items built from parts, edited in centimetres beside a 3D view that draws them with
|
||||
// NextFloor's own furniture code. The pack is kept in the browser, saved as a file NextFloor imports, and shared in the
|
||||
// community store through a GitHub form (the store's own check turns it into a pull request).
|
||||
|
||||
import { css, html, LitElement, nothing, type TemplateResult } from "lit";
|
||||
import type { FurniturePack, PackItem, PackPart } from "../packs.ts";
|
||||
import { blocking, checkPack, COLOR_ROLES, exportPack, freeItemId, fromCm, importPack, LIGHTS, MAX_PARTS, MOUNTS, newItem, newPack, newPart, partCm, TEMPLATES, type PartCm, type Problem, type Shape } from "./model.ts";
|
||||
import { BuilderScene, type ViewPreset } from "./scene.ts";
|
||||
import { LANG, t, type TextKey } from "./texts.ts";
|
||||
|
||||
const STORE_KEY = "nextfloor.builder.pack";
|
||||
const STORE_REPO = "https://github.com/therealMRBK/NextFloor-Plugins";
|
||||
/** GitHub keeps URLs to about 8000 characters: a small pack goes into the form by itself, a big one through the clipboard. */
|
||||
const MAX_URL_PACK = 6000;
|
||||
|
||||
function loadStored(): FurniturePack {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORE_KEY);
|
||||
const pack = raw ? importPack(raw) : null;
|
||||
if (pack) return pack;
|
||||
} catch {
|
||||
// private mode or blocked storage: start fresh
|
||||
}
|
||||
const pack = newPack("");
|
||||
pack.items = [TEMPLATES.cabinet()];
|
||||
return pack;
|
||||
}
|
||||
|
||||
const round = (v: number, places = 1) => Math.round(v * 10 ** places) / 10 ** places;
|
||||
|
||||
export class NfBuilder extends LitElement {
|
||||
static properties = {
|
||||
_pack: { state: true },
|
||||
_item: { state: true },
|
||||
_part: { state: true },
|
||||
_dialog: { state: true },
|
||||
_note: { state: true },
|
||||
};
|
||||
|
||||
private declare _pack: FurniturePack;
|
||||
private declare _item: number;
|
||||
private declare _part: number;
|
||||
private declare _dialog: "submit" | null;
|
||||
private declare _note: string | null;
|
||||
private scene: BuilderScene | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._pack = loadStored();
|
||||
this._item = 0;
|
||||
this._part = -1;
|
||||
this._dialog = null;
|
||||
this._note = null;
|
||||
}
|
||||
|
||||
private get item(): PackItem {
|
||||
return this._pack.items[Math.min(this._item, this._pack.items.length - 1)];
|
||||
}
|
||||
|
||||
/** Change the pack (on a copy, so Lit sees it), keep it in the browser and draw the item again. */
|
||||
private change(fn: (pack: FurniturePack) => void): void {
|
||||
const pack = structuredClone(this._pack);
|
||||
fn(pack);
|
||||
this._pack = pack;
|
||||
this._item = Math.min(this._item, pack.items.length - 1);
|
||||
try {
|
||||
localStorage.setItem(STORE_KEY, exportPack(pack));
|
||||
} catch {
|
||||
// the pack stays on the page
|
||||
}
|
||||
}
|
||||
|
||||
private changeItem(fn: (item: PackItem) => void): void {
|
||||
this.change((p) => fn(p.items[this._item]));
|
||||
}
|
||||
|
||||
private changePart(fn: (part: PackPart) => void): void {
|
||||
if (this._part < 0) return;
|
||||
this.changeItem((item) => fn(item.parts[this._part]));
|
||||
}
|
||||
|
||||
protected firstUpdated(): void {
|
||||
const canvas = this.renderRoot.querySelector("canvas")!;
|
||||
this.scene = new BuilderScene(canvas);
|
||||
this.scene.pick = (i) => (this._part = i);
|
||||
this.scene.show(this.item, this._part);
|
||||
}
|
||||
|
||||
protected updated(): void {
|
||||
this.scene?.show(this.item, this._part);
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
this.scene?.dispose();
|
||||
this.scene = null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
private newPack(): void {
|
||||
this._pack = newPack(this._pack.publisher);
|
||||
this._item = 0;
|
||||
this._part = -1;
|
||||
this.change(() => undefined);
|
||||
}
|
||||
|
||||
private addItem(template: string): void {
|
||||
const made = template === "empty" ? newItem("item", t("item")) : TEMPLATES[template]();
|
||||
this.change((p) => {
|
||||
made.id = freeItemId(p, made.id);
|
||||
p.items.push(made);
|
||||
});
|
||||
this._item = this._pack.items.length - 1;
|
||||
this._part = -1;
|
||||
}
|
||||
|
||||
private duplicateItem(): void {
|
||||
const copy = structuredClone(this.item);
|
||||
this.change((p) => {
|
||||
copy.id = freeItemId(p, copy.id);
|
||||
p.items.splice(this._item + 1, 0, copy);
|
||||
});
|
||||
this._item += 1;
|
||||
}
|
||||
|
||||
private deleteItem(): void {
|
||||
if (this._pack.items.length <= 1) return;
|
||||
this.change((p) => p.items.splice(this._item, 1));
|
||||
this._item = Math.max(0, this._item - 1);
|
||||
this._part = -1;
|
||||
}
|
||||
|
||||
private addPart(shape: Shape): void {
|
||||
if (this.item.parts.length >= MAX_PARTS) return;
|
||||
this.changeItem((item) => item.parts.push(newPart(shape)));
|
||||
this._part = this.item.parts.length - 1;
|
||||
}
|
||||
|
||||
private duplicatePart(): void {
|
||||
if (this._part < 0 || this.item.parts.length >= MAX_PARTS) return;
|
||||
// the copy sits a little to the right, so it is seen
|
||||
this.changeItem((item) => {
|
||||
const copy = structuredClone(item.parts[this._part]);
|
||||
copy.x = Math.min(0.5, copy.x + Math.min(0.1, (0.5 - copy.x) / 2));
|
||||
item.parts.splice(this._part + 1, 0, copy);
|
||||
});
|
||||
this._part += 1;
|
||||
}
|
||||
|
||||
private deletePart(): void {
|
||||
if (this._part < 0 || this.item.parts.length <= 1) return;
|
||||
this.changeItem((item) => item.parts.splice(this._part, 1));
|
||||
this._part = Math.min(this._part, this.item.parts.length - 1);
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
const blob = new Blob([exportPack(this._pack)], { type: "application/json" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${this._pack.id || "pack"}.json`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||||
}
|
||||
|
||||
private open(e: Event): void {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
void file.text().then((text) => {
|
||||
const pack = importPack(text);
|
||||
if (!pack) {
|
||||
this._note = t("import_failed");
|
||||
return;
|
||||
}
|
||||
this._pack = pack;
|
||||
this._item = 0;
|
||||
this._part = -1;
|
||||
this.change(() => undefined);
|
||||
});
|
||||
(e.target as HTMLInputElement).value = "";
|
||||
}
|
||||
|
||||
private submitUrl(text: string): string {
|
||||
const params = new URLSearchParams({ template: "furniture.yml", title: `Furniture pack: ${this._pack.name}`, labels: "furniture" });
|
||||
if (text.length <= MAX_URL_PACK) params.set("pack", text);
|
||||
return `${STORE_REPO}/issues/new?${params.toString()}`;
|
||||
}
|
||||
|
||||
private async submit(): Promise<void> {
|
||||
const text = exportPack(this._pack);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
// the clipboard is blocked: the form still opens, the file can be saved and pasted
|
||||
}
|
||||
window.open(this.submitUrl(text), "_blank", "noopener");
|
||||
this._dialog = null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fields
|
||||
|
||||
private num(label: string, value: number, set: (v: number) => void, o: { step?: number; min?: number; max?: number } = {}): TemplateResult {
|
||||
return html`<label class="field"
|
||||
>${label}
|
||||
<input type="number" .value=${String(value)} step=${o.step ?? 0.5} min=${o.min ?? nothing} max=${o.max ?? nothing} @change=${(e: Event) => {
|
||||
const v = Number((e.target as HTMLInputElement).value);
|
||||
if (Number.isFinite(v)) set(v);
|
||||
}} />
|
||||
</label>`;
|
||||
}
|
||||
|
||||
private text(label: string, value: string, set: (v: string) => void, o: { hint?: string; max?: number } = {}): TemplateResult {
|
||||
return html`<label class="field wide" title=${o.hint ?? nothing}
|
||||
>${label}
|
||||
<input type="text" .value=${value} maxlength=${o.max ?? 80} @change=${(e: Event) => set((e.target as HTMLInputElement).value.trim())} />
|
||||
</label>`;
|
||||
}
|
||||
|
||||
private check(label: string, value: boolean, set: (v: boolean) => void): TemplateResult {
|
||||
return html`<label class="check wide"><input type="checkbox" .checked=${value} @change=${(e: Event) => set((e.target as HTMLInputElement).checked)} /> ${label}</label>`;
|
||||
}
|
||||
|
||||
private select<T extends string>(label: string, value: T, options: readonly (readonly [T, string])[], set: (v: T) => void): TemplateResult {
|
||||
return html`<label class="field"
|
||||
>${label}
|
||||
<select @change=${(e: Event) => set((e.target as HTMLSelectElement).value as T)}>
|
||||
${options.map(([v, text]) => html`<option value=${v} ?selected=${v === value}>${text}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A colour: a palette role (follows the look) or an own colour. */
|
||||
private colorField(label: string, value: string | undefined, set: (v: string | undefined) => void, allowSame = false): TemplateResult {
|
||||
const own = !!value && value.startsWith("#");
|
||||
const choice = value === undefined ? "" : own ? "#" : value;
|
||||
const options: [string, string][] = [...(allowSame ? [["", t("same")] as [string, string]] : []), ...COLOR_ROLES.map((r): [string, string] => [r, t(`r_${r}` as TextKey)]), ["#", t("own_color")]];
|
||||
return html`<label class="field"
|
||||
>${label}
|
||||
<span class="row">
|
||||
<select
|
||||
@change=${(e: Event) => {
|
||||
const v = (e.target as HTMLSelectElement).value;
|
||||
set(v === "" ? undefined : v === "#" ? (own ? value : "#8899aa") : v);
|
||||
}}
|
||||
>
|
||||
${options.map(([v, text]) => html`<option value=${v} ?selected=${v === choice}>${text}</option>`)}
|
||||
</select>
|
||||
${own ? html`<input type="color" .value=${value!} @input=${(e: Event) => set((e.target as HTMLInputElement).value)} />` : nothing}
|
||||
</span>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
|
||||
protected render() {
|
||||
const problems = checkPack(this._pack);
|
||||
const errors = blocking(problems);
|
||||
return html`<header>
|
||||
<div>
|
||||
<h1>${t("title")}</h1>
|
||||
<p>${t("subtitle")}</p>
|
||||
</div>
|
||||
<span class="grow"></span>
|
||||
<button @click=${() => this.newPack()}>${t("new_pack")}</button>
|
||||
<label class="button">${t("open")}<input type="file" accept=".json,application/json" hidden @change=${(e: Event) => this.open(e)} /></label>
|
||||
<button @click=${() => this.save()} ?disabled=${errors.length > 0}>${t("save")}</button>
|
||||
<button class="primary" @click=${() => (this._dialog = "submit")}>${t("submit")}</button>
|
||||
</header>
|
||||
${this._note ? html`<div class="note" @click=${() => (this._note = null)}>${this._note}</div>` : nothing}
|
||||
<main>
|
||||
<aside class="left">${this.renderPack()} ${this.renderItems()} ${this.renderItem()}</aside>
|
||||
<section class="stage">
|
||||
<canvas></canvas>
|
||||
<div class="tools">
|
||||
<span>${t("add")}</span>
|
||||
${(["box", "cyl", "loft", "sweep"] as Shape[]).map((s) => html`<button @click=${() => this.addPart(s)} ?disabled=${this.item.parts.length >= MAX_PARTS}>${t(`s_${s}` as TextKey)}</button>`)}
|
||||
</div>
|
||||
<div class="views">
|
||||
${(["iso", "front", "side", "top"] as ViewPreset[]).map((v) => html`<button @click=${() => this.scene?.setView(v)}>${t(`view_${v}` as TextKey)}</button>`)}
|
||||
<button @click=${() => this.scene?.zoom(1 / 1.25)} aria-label="+">+</button><button @click=${() => this.scene?.zoom(1.25)} aria-label="−">−</button>
|
||||
</div>
|
||||
<p class="howto">${t("howto")} ${t("saved_local")}</p>
|
||||
</section>
|
||||
<aside class="right">${this.renderParts()} ${this.renderPart()}</aside>
|
||||
</main>
|
||||
<footer>${this.renderProblems(problems)}</footer>
|
||||
${this._dialog === "submit" ? this.renderSubmit(errors) : nothing}`;
|
||||
}
|
||||
|
||||
private renderPack() {
|
||||
const p = this._pack;
|
||||
return html`<h2>${t("pack")}</h2>
|
||||
<div class="form">
|
||||
${this.text(t("pack_name"), p.name, (v) => this.change((x) => (x.name = v)))}
|
||||
${this.text(t("publisher"), p.publisher, (v) => this.change((x) => (x.publisher = v)))}
|
||||
${this.text(t("pack_id"), p.id, (v) => this.change((x) => (x.id = v.toLowerCase())), { hint: t("pack_id_hint"), max: 40 })}
|
||||
${this.num(t("release"), p.release ?? 1, (v) => this.change((x) => (x.release = Math.max(1, Math.round(v)))), { step: 1, min: 1 })}
|
||||
<label class="field wide"
|
||||
>${t("description")}
|
||||
<textarea rows="2" maxlength="400" .value=${p.description ?? ""} @change=${(e: Event) => this.change((x) => (x.description = (e.target as HTMLTextAreaElement).value.trim()))}></textarea>
|
||||
</label>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderItems() {
|
||||
return html`<h2>${t("items")}</h2>
|
||||
<div class="list">
|
||||
${this._pack.items.map(
|
||||
(item, i) => html`<button class="entry" aria-pressed=${i === this._item} @click=${() => ((this._item = i), (this._part = -1))}>${item.name[LANG] || item.name.en || item.id}</button>`,
|
||||
)}
|
||||
</div>
|
||||
<div class="row">
|
||||
<select
|
||||
@change=${(e: Event) => {
|
||||
const v = (e.target as HTMLSelectElement).value;
|
||||
(e.target as HTMLSelectElement).value = "";
|
||||
if (v) this.addItem(v);
|
||||
}}
|
||||
>
|
||||
<option value="">${t("add_item")}</option>
|
||||
${["empty", ...Object.keys(TEMPLATES)].map((k) => html`<option value=${k}>${t(`t_${k}` as TextKey)}</option>`)}
|
||||
</select>
|
||||
<button @click=${() => this.duplicateItem()}>${t("duplicate")}</button>
|
||||
<button class="danger" @click=${() => this.deleteItem()} ?disabled=${this._pack.items.length <= 1}>${t("delete")}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderItem() {
|
||||
const item = this.item;
|
||||
const [w, d, h] = item.size;
|
||||
const size = (i: 0 | 1 | 2) => (v: number) => this.changeItem((it) => (it.size[i] = Math.min(10, Math.max(0.01, v / 100))));
|
||||
return html`<h2>${t("item")}</h2>
|
||||
<div class="form">
|
||||
${this.text(t("name_de"), item.name.de ?? "", (v) => this.changeItem((it) => (it.name = { ...it.name, de: v })))}
|
||||
${this.text(t("name_en"), item.name.en ?? "", (v) => this.changeItem((it) => (it.name = { ...it.name, en: v })))}
|
||||
${this.text(t("item_id"), item.id, (v) => this.changeItem((it) => (it.id = v.toLowerCase())), { max: 40 })}
|
||||
${this.num(t("width"), round(w * 100), size(0), { step: 1, min: 1 })} ${this.num(t("depth"), round(d * 100), size(1), { step: 1, min: 1 })}
|
||||
${this.num(t("height"), round(h * 100), size(2), { step: 1, min: 1 })}
|
||||
${this.select(t("mount"), item.mount ?? "floor", MOUNTS.map((m) => [m, t(`mount_${m}` as TextKey)] as const), (v) => this.changeItem((it) => (it.mount = v === "floor" ? undefined : v)))}
|
||||
${item.mount === "wall" ? this.num(t("wall_y"), round((item.wall_y ?? 1) * 100), (v) => this.changeItem((it) => (it.wall_y = Math.min(3, Math.max(0, v / 100)))), { step: 1, min: 0 }) : nothing}
|
||||
${this.select(t("light"), item.light ?? "", [["", t("light_none")], ...LIGHTS.map((l) => [l, l] as const)], (v) => this.changeItem((it) => (it.light = (v || undefined) as PackItem["light"])))}
|
||||
${this.check(t("electric"), !!item.electric, (v) => this.changeItem((it) => (it.electric = v || undefined)))}
|
||||
${this.check(t("surface"), !!item.surface, (v) => this.changeItem((it) => (it.surface = v || undefined)))}
|
||||
${this.check(t("stretch"), !!item.stretch, (v) => this.changeItem((it) => (it.stretch = v || undefined)))}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderParts() {
|
||||
return html`<h2>${t("parts")} (${this.item.parts.length}/${MAX_PARTS})</h2>
|
||||
<div class="list parts">
|
||||
${this.item.parts.map(
|
||||
(p, i) => html`<button class="entry" aria-pressed=${i === this._part} @click=${() => (this._part = i)}>
|
||||
<span class="swatch" style=${`background:${p.color.startsWith("#") ? p.color : `var(--role-${p.color})`}`}></span>${t(`s_${p.shape}` as TextKey)} ${i + 1}
|
||||
</button>`,
|
||||
)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderPart() {
|
||||
if (this._part < 0 || !this.item.parts[this._part]) return html`<p class="muted">${t("no_part")}</p>`;
|
||||
const part = this.item.parts[this._part];
|
||||
const cm = partCm(part, this.item.size);
|
||||
const set = (key: keyof PartCm) => (v: number) => this.changePart((p) => (p[key] = fromCm(key, v, this.item.size)));
|
||||
const pct = (v: number | undefined, fallback: number) => round((v ?? fallback) * 100);
|
||||
return html`<h2>${t("part")} ${this._part + 1}</h2>
|
||||
<div class="form">
|
||||
${this.num(t("x"), cm.x, set("x"))} ${this.num(t("z"), cm.z, set("z"))} ${this.num(t("y"), cm.y, set("y"))} ${this.num(t("w"), cm.w, set("w"), { min: 0.1 })}
|
||||
${this.num(t("d"), cm.d, set("d"), { min: 0.1 })} ${this.num(t("h"), cm.h, set("h"), { min: 0.1 })}
|
||||
${this.num(t("rot"), part.rot ?? 0, (v) => this.changePart((p) => (p.rot = v ? Math.max(-360, Math.min(360, v)) : undefined)), { step: 5 })}
|
||||
${part.shape === "cyl" ? this.select(t("axis"), part.axis ?? "y", (["y", "x", "z"] as const).map((a) => [a, t(`axis_${a}` as TextKey)] as const), (v) => this.changePart((p) => (p.axis = v === "y" ? undefined : v))) : nothing}
|
||||
${part.shape === "loft"
|
||||
? html`${this.num(t("top_w"), pct(part.tw, part.w), (v) => this.changePart((p) => (p.tw = Math.min(1, Math.max(0.001, v / 100)))), { step: 1 })}
|
||||
${this.num(t("top_d"), pct(part.td, part.d), (v) => this.changePart((p) => (p.td = Math.min(1, Math.max(0.001, v / 100)))), { step: 1 })}
|
||||
${this.num(t("top_x"), pct(part.tx, part.x), (v) => this.changePart((p) => (p.tx = Math.min(0.5, Math.max(-0.5, v / 100)))), { step: 1 })}`
|
||||
: nothing}
|
||||
${part.shape === "sweep" ? this.renderStations(part) : nothing}
|
||||
${this.colorField(t("color"), part.color, (v) => this.changePart((p) => (p.color = v ?? "body")))}
|
||||
${this.colorField(t("top"), part.top, (v) => this.changePart((p) => (p.top = v)), true)}
|
||||
${this.select(
|
||||
t("edges"),
|
||||
part.edges === true ? "soft" : part.edges ? part.edges : "none",
|
||||
[["none", t("edges_none")], ["soft", t("edges_soft")], ["glow", t("edges_glow")], ["faint", t("edges_faint")]] as const,
|
||||
(v) => this.changePart((p) => (p.edges = v === "none" ? undefined : v === "soft" ? true : v)),
|
||||
)}
|
||||
${this.check(t("glow"), !!part.glow, (v) => this.changePart((p) => (p.glow = v || undefined)))}
|
||||
${this.check(t("screen"), !!part.screen, (v) => this.changePart((p) => (p.screen = v || undefined)))}
|
||||
</div>
|
||||
<p class="muted">${t("colors_role")}</p>
|
||||
<div class="row">
|
||||
<button @click=${() => this.duplicatePart()} ?disabled=${this.item.parts.length >= MAX_PARTS}>${t("duplicate")}</button>
|
||||
<button class="danger" @click=${() => this.deletePart()} ?disabled=${this.item.parts.length <= 1}>${t("delete")}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderStations(part: PackPart) {
|
||||
const stations = part.stations ?? [];
|
||||
const setStation = (i: number, k: number, v: number) =>
|
||||
this.changePart((p) => {
|
||||
const s = p.stations![i];
|
||||
s[k] = k === 0 ? Math.min(0.5, Math.max(-0.5, v / 100)) : k === 3 ? Math.min(1, Math.max(0.001, v / 100)) : Math.min(1, Math.max(0, v / 100));
|
||||
});
|
||||
return html`${this.num(t("exp"), part.exp ?? 2.6, (v) => this.changePart((p) => (p.exp = Math.min(8, Math.max(1.5, v)))), { step: 0.1 })}
|
||||
<div class="wide stations">
|
||||
<span class="muted">${t("stations")}: ${t("station")}</span>
|
||||
${stations.map(
|
||||
(s, i) => html`<div class="row">
|
||||
${s.map((v, k) => html`<input type="number" step="1" .value=${String(round(v * 100))} @change=${(e: Event) => setStation(i, k, Number((e.target as HTMLInputElement).value))} />`)}
|
||||
<button class="danger" ?disabled=${stations.length <= 2} @click=${() => this.changePart((p) => p.stations!.splice(i, 1))}>×</button>
|
||||
</div>`,
|
||||
)}
|
||||
<button
|
||||
?disabled=${stations.length >= 48}
|
||||
@click=${() =>
|
||||
this.changePart((p) => {
|
||||
const last = p.stations![p.stations!.length - 1];
|
||||
p.stations!.push([Math.min(0.5, last[0] + 0.1), last[1], last[2], last[3]]);
|
||||
p.stations!.sort((a, b) => a[0] - b[0]);
|
||||
})}
|
||||
>
|
||||
${t("add_station")}
|
||||
</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderProblems(problems: Problem[]) {
|
||||
if (!problems.length) return html`<p class="ok">✓ ${t("ok")}</p>`;
|
||||
const where = (w: string) => {
|
||||
if (w === "pack") return t("where_pack");
|
||||
const [, i, , k] = w.match(/item:(\d+)(\/part:(\d+))?/) ?? [];
|
||||
const item = this._pack.items[Number(i)];
|
||||
const name = item ? item.name[LANG] || item.id : "?";
|
||||
return k === undefined ? name : `${name} · ${t("part")} ${Number(k) + 1}`;
|
||||
};
|
||||
return html`<h2>${t("check")}</h2>
|
||||
<ul>
|
||||
${problems.map((p) => html`<li class=${p.key === "outside" ? "warn" : "error"}><b>${where(p.where)}</b>: ${t(p.key as TextKey, p.vars)}</li>`)}
|
||||
</ul>`;
|
||||
}
|
||||
|
||||
private renderSubmit(errors: Problem[]) {
|
||||
return html`<div class="dialog" role="dialog" aria-modal="true">
|
||||
<div class="box">
|
||||
<h2>${t("submit")}</h2>
|
||||
${errors.length ? html`<p class="error">${t("submit_blocked")}</p>` : html`<p>${t("submit_steps")}</p>`}
|
||||
<div class="row">
|
||||
<button class="primary" ?disabled=${errors.length > 0} @click=${() => void this.submit()}>${t("submit_go")}</button>
|
||||
<button @click=${() => (this._dialog = null)}>${t("close")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
--bg: #0b1020;
|
||||
--panel: #121a2e;
|
||||
--line: #24314f;
|
||||
--text: #e6ecff;
|
||||
--muted: #8d9bbd;
|
||||
--accent: #37e0ff;
|
||||
--danger: #ff6b7a;
|
||||
--role-body: #3a4a6a;
|
||||
--role-fabric: #4b5d8c;
|
||||
--role-cushion: #6a7fb3;
|
||||
--role-wood: #8a6a4a;
|
||||
--role-white: #dfe6f2;
|
||||
--role-metal: #9aa7bf;
|
||||
--role-dark: #1e2638;
|
||||
--role-glass: #7fd0e8;
|
||||
--role-plant: #3f9a5a;
|
||||
--role-pot: #a5674a;
|
||||
--role-accent: #37e0ff;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 14px/1.4 system-ui, sans-serif;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
header p {
|
||||
margin: 2px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
h2 {
|
||||
margin: 14px 0 6px;
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
}
|
||||
.grow {
|
||||
flex: 1;
|
||||
}
|
||||
main {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: 300px 1fr 300px;
|
||||
min-height: 0;
|
||||
}
|
||||
aside {
|
||||
overflow: auto;
|
||||
padding: 0 14px 14px;
|
||||
background: var(--panel);
|
||||
}
|
||||
.left {
|
||||
border-right: 1px solid var(--line);
|
||||
}
|
||||
.right {
|
||||
border-left: 1px solid var(--line);
|
||||
}
|
||||
.stage {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
canvas {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
touch-action: none;
|
||||
}
|
||||
.tools,
|
||||
.views {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.tools {
|
||||
top: 12px;
|
||||
}
|
||||
.views {
|
||||
bottom: 40px;
|
||||
}
|
||||
.howto {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
right: 12px;
|
||||
bottom: 6px;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
min-width: 0;
|
||||
}
|
||||
.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.check {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
}
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 6px 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
input[type="color"] {
|
||||
padding: 0;
|
||||
width: 36px;
|
||||
height: 32px;
|
||||
}
|
||||
input[type="checkbox"] {
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
button,
|
||||
.button {
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: #1b2640;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 7px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
color: #04121a;
|
||||
border-color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.list {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
.entry {
|
||||
text-align: left;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.entry[aria-pressed="true"] {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
.swatch {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 3px;
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.stations .row input {
|
||||
width: 58px;
|
||||
}
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
footer {
|
||||
max-height: 22vh;
|
||||
overflow: auto;
|
||||
padding: 0 16px 10px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
footer ul {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
.error {
|
||||
color: var(--danger);
|
||||
}
|
||||
.warn {
|
||||
color: #ffb547;
|
||||
}
|
||||
.ok {
|
||||
color: #6ee7a0;
|
||||
}
|
||||
.note {
|
||||
padding: 8px 16px;
|
||||
background: #3a1d24;
|
||||
color: var(--danger);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dialog {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
.dialog .box {
|
||||
max-width: 520px;
|
||||
margin: 16px;
|
||||
padding: 18px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
:host {
|
||||
height: auto;
|
||||
}
|
||||
main {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.stage {
|
||||
height: 60vh;
|
||||
order: -1;
|
||||
}
|
||||
.left,
|
||||
.right {
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
customElements.define("nf-builder", NfBuilder);
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { blocking, checkPack, exportPack, freeItemId, fromCm, importPack, newItem, newPack, newPart, partCm, TEMPLATES } from "./model.ts";
|
||||
|
||||
test("every template and every new part passes the integration's checks", () => {
|
||||
const pack = newPack("Anna Muster");
|
||||
pack.items = Object.entries(TEMPLATES).map(([, make]) => make());
|
||||
assert.deepEqual(blocking(checkPack(pack)), []);
|
||||
for (const shape of ["box", "cyl", "loft", "sweep"] as const) {
|
||||
const item = newItem("x", "X");
|
||||
item.parts = [newPart(shape)];
|
||||
assert.deepEqual(blocking(checkPack({ ...pack, items: [item] })), [], shape);
|
||||
}
|
||||
assert.equal(pack.id, "annamuster.furniture");
|
||||
});
|
||||
|
||||
test("the checks find what the import refuses", () => {
|
||||
const pack = newPack("me");
|
||||
const keys = (p: typeof pack) => checkPack(p).map((x) => x.key);
|
||||
assert.ok(keys({ ...pack, id: "nextfloor.mine" }).includes("reserved_id"));
|
||||
assert.ok(keys({ ...pack, id: "Bad Id" }).includes("bad_pack_id"));
|
||||
assert.ok(keys({ ...pack, publisher: " " }).includes("bad_publisher"));
|
||||
const twice = { ...pack, items: [newItem("a", "A"), newItem("a", "B")] };
|
||||
assert.ok(keys(twice).includes("duplicate_item_id"));
|
||||
const item = newItem("a", "A");
|
||||
item.parts[0] = { ...item.parts[0], z: 0.53 };
|
||||
assert.ok(checkPack({ ...pack, items: [item] }).some((p) => p.key === "bad_value" && p.vars?.field === "z"));
|
||||
item.parts = Array.from({ length: 61 }, () => newPart("box"));
|
||||
assert.ok(keys({ ...pack, items: [item] }).includes("part_count"));
|
||||
const sweep = newItem("s", "S");
|
||||
sweep.parts = [{ ...newPart("sweep"), stations: [[0, 0, 1, 1]] }];
|
||||
assert.ok(keys({ ...pack, items: [sweep] }).includes("sweep_stations"));
|
||||
});
|
||||
|
||||
test("a part reaching out of the item is only a warning", () => {
|
||||
const item = newItem("a", "A");
|
||||
item.parts = [{ ...newPart("box"), x: 0.4, w: 0.4 }];
|
||||
const problems = checkPack({ ...newPack("me"), items: [item] });
|
||||
assert.deepEqual(problems.map((p) => p.key), ["outside"]);
|
||||
assert.deepEqual(blocking(problems), []);
|
||||
});
|
||||
|
||||
test("centimetres and fractions turn into each other", () => {
|
||||
const size: [number, number, number] = [0.8, 0.5, 1.2];
|
||||
const part = { ...newPart("box"), x: 0.25, w: 0.5, y: 0.5, h: 0.25 };
|
||||
assert.deepEqual(partCm(part, size), { x: 20, z: 0, y: 60, w: 40, d: 25, h: 30 });
|
||||
assert.equal(fromCm("x", 20, size), 0.25);
|
||||
assert.equal(fromCm("h", 30, size), 0.25);
|
||||
assert.equal(fromCm("d", 10, size), 0.2);
|
||||
});
|
||||
|
||||
test("the exported file imports back unchanged, without defaults and empty fields", () => {
|
||||
const pack = newPack("me");
|
||||
pack.items = [TEMPLATES.floor_lamp(), TEMPLATES.table()];
|
||||
const text = exportPack(pack);
|
||||
const file = JSON.parse(text);
|
||||
assert.equal(file.format, "nfpack");
|
||||
assert.equal(file.version, 1);
|
||||
assert.equal("mount" in file.items[0], false);
|
||||
assert.equal(file.items[0].light, "floor");
|
||||
assert.equal(file.items[1].surface, true);
|
||||
assert.equal(JSON.stringify(file.items[1].parts).includes("false"), false);
|
||||
const back = importPack(text)!;
|
||||
assert.equal(back.items.length, 2);
|
||||
assert.deepEqual(back.items[0].parts, file.items[0].parts);
|
||||
assert.equal(importPack("{}"), null);
|
||||
assert.equal(importPack("not json"), null);
|
||||
});
|
||||
|
||||
test("new items get a free id", () => {
|
||||
const pack = newPack("me");
|
||||
assert.equal(freeItemId(pack, "cabinet"), "cabinet_2");
|
||||
assert.equal(freeItemId(pack, "table"), "table");
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
// The furniture builder's model: a pack being built, new parts and items, templates to start from, sizes in centimetres,
|
||||
// the same checks the integration runs when a pack is imported (custom_components/nextfloor/packs.py), and the file export.
|
||||
// Pure functions, no DOM: tested in model.test.ts.
|
||||
|
||||
import type { FurniturePack, PackItem, PackPart } from "../packs.ts";
|
||||
|
||||
export type Shape = PackPart["shape"];
|
||||
|
||||
/** Palette roles: colours that follow the look of the plan (neon, blueprint, day). */
|
||||
export const COLOR_ROLES = ["body", "fabric", "cushion", "wood", "white", "metal", "dark", "glass", "plant", "pot", "accent"] as const;
|
||||
export const LIGHTS = ["ceiling", "downlight", "spot", "panel", "pendant", "floor", "uplight", "table", "wall", "strip", "bollard", "garden"] as const;
|
||||
export const MOUNTS = ["floor", "surface", "wall", "ceiling"] as const;
|
||||
|
||||
export const MAX_PARTS = 60;
|
||||
export const MAX_ITEMS = 200;
|
||||
export const MAX_PACK_SIZE = 1_000_000;
|
||||
const ID = /^[a-z0-9][a-z0-9_.-]{0,39}$/;
|
||||
|
||||
/** A new part of a shape, standing in the middle of the item. */
|
||||
export function newPart(shape: Shape): PackPart {
|
||||
const base: PackPart = { shape, x: 0, z: 0, w: 0.5, d: 0.5, y: 0, h: 0.5, color: "body", edges: true };
|
||||
if (shape === "cyl") return { ...base, w: 0.4, d: 0.4 };
|
||||
if (shape === "loft") return { ...base, tw: 0.3, td: 0.3 };
|
||||
if (shape === "sweep")
|
||||
return {
|
||||
...base,
|
||||
w: 1,
|
||||
d: 1,
|
||||
h: 1,
|
||||
stations: [
|
||||
[-0.5, 0.1, 0.4, 0.6],
|
||||
[0, 0, 0.9, 1],
|
||||
[0.5, 0.1, 0.5, 0.7],
|
||||
],
|
||||
exp: 2.6,
|
||||
n: 16,
|
||||
};
|
||||
return base;
|
||||
}
|
||||
|
||||
/** A new item with one body box. */
|
||||
export function newItem(id: string, name: string): PackItem {
|
||||
return { id, name: { de: name, en: name }, size: [0.8, 0.5, 0.9], parts: [{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0, h: 1, color: "body", edges: true }] };
|
||||
}
|
||||
|
||||
export function newPack(publisher = ""): FurniturePack {
|
||||
const slug = publisher.toLowerCase().replace(/[^a-z0-9]+/g, "").slice(0, 20) || "me";
|
||||
return { id: `${slug}.furniture`, name: "My furniture", publisher: publisher || "Me", description: "", release: 1, items: [newItem("cabinet", "Cabinet")] };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- templates
|
||||
|
||||
const leg = (x: number, z: number, w: number, d: number, h: number): PackPart => ({ shape: "box", x, z, w, d, y: 0, h, color: "metal" });
|
||||
|
||||
/** Starting points: a cabinet, a table, a shelf, a floor lamp, a sofa. Names in German and English. */
|
||||
export const TEMPLATES: Record<string, () => PackItem> = {
|
||||
cabinet: () => ({
|
||||
id: "cabinet",
|
||||
name: { de: "Schrank", en: "Cabinet" },
|
||||
size: [0.8, 0.45, 1.2],
|
||||
parts: [
|
||||
{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0.05, h: 0.95, color: "wood", edges: true },
|
||||
{ shape: "box", x: -0.25, z: 0.48, w: 0.49, d: 0.04, y: 0.07, h: 0.91, color: "white", edges: "faint" },
|
||||
{ shape: "box", x: 0.25, z: 0.48, w: 0.49, d: 0.04, y: 0.07, h: 0.91, color: "white", edges: "faint" },
|
||||
{ shape: "box", x: -0.04, z: 0.5, w: 0.02, d: 0.06, y: 0.45, h: 0.15, color: "metal" },
|
||||
{ shape: "box", x: 0.04, z: 0.5, w: 0.02, d: 0.06, y: 0.45, h: 0.15, color: "metal" },
|
||||
leg(-0.45, -0.4, 0.05, 0.08, 0.05),
|
||||
leg(0.45, -0.4, 0.05, 0.08, 0.05),
|
||||
leg(-0.45, 0.4, 0.05, 0.08, 0.05),
|
||||
leg(0.45, 0.4, 0.05, 0.08, 0.05),
|
||||
],
|
||||
}),
|
||||
table: () => ({
|
||||
id: "table",
|
||||
name: { de: "Tisch", en: "Table" },
|
||||
size: [1.6, 0.9, 0.75],
|
||||
surface: true,
|
||||
parts: [
|
||||
{ shape: "box", x: 0, z: 0, w: 1, d: 1, y: 0.95, h: 0.05, color: "wood", edges: true },
|
||||
leg(-0.46, -0.44, 0.04, 0.07, 0.95),
|
||||
leg(0.46, -0.44, 0.04, 0.07, 0.95),
|
||||
leg(-0.46, 0.44, 0.04, 0.07, 0.95),
|
||||
leg(0.46, 0.44, 0.04, 0.07, 0.95),
|
||||
],
|
||||
}),
|
||||
shelf: () => ({
|
||||
id: "shelf",
|
||||
name: { de: "Regal", en: "Shelf" },
|
||||
size: [0.8, 0.35, 1.8],
|
||||
parts: [
|
||||
{ shape: "box", x: -0.48, z: 0, w: 0.04, d: 1, y: 0, h: 1, color: "wood", edges: true },
|
||||
{ shape: "box", x: 0.48, z: 0, w: 0.04, d: 1, y: 0, h: 1, color: "wood", edges: true },
|
||||
...[0, 0.24, 0.49, 0.74, 0.98].map((y): PackPart => ({ shape: "box", x: 0, z: 0, w: 0.92, d: 1, y, h: 0.02, color: "wood", edges: true })),
|
||||
],
|
||||
}),
|
||||
floor_lamp: () => ({
|
||||
id: "floor_lamp",
|
||||
name: { de: "Stehlampe", en: "Floor lamp" },
|
||||
size: [0.4, 0.4, 1.6],
|
||||
light: "floor",
|
||||
parts: [
|
||||
{ shape: "cyl", x: 0, z: 0, w: 0.7, d: 0.7, y: 0, h: 0.02, color: "metal", edges: true },
|
||||
{ shape: "cyl", x: 0, z: 0, w: 0.06, d: 0.06, y: 0.02, h: 0.78, color: "metal" },
|
||||
{ shape: "loft", x: 0, z: 0, w: 1, d: 1, y: 0.78, h: 0.22, color: "white", tw: 0.6, td: 0.6, glow: true, edges: "faint" },
|
||||
],
|
||||
}),
|
||||
sofa: () => ({
|
||||
id: "sofa",
|
||||
name: { de: "Sofa", en: "Sofa" },
|
||||
size: [2.0, 0.9, 0.8],
|
||||
parts: [
|
||||
{ shape: "box", x: 0, z: 0.05, w: 0.84, d: 0.8, y: 0.12, h: 0.38, color: "fabric", edges: true },
|
||||
{ shape: "box", x: 0, z: -0.38, w: 0.84, d: 0.24, y: 0.12, h: 0.88, color: "fabric", edges: true },
|
||||
{ shape: "box", x: -0.46, z: 0, w: 0.08, d: 1, y: 0.12, h: 0.6, color: "fabric", edges: true },
|
||||
{ shape: "box", x: 0.46, z: 0, w: 0.08, d: 1, y: 0.12, h: 0.6, color: "fabric", edges: true },
|
||||
{ shape: "box", x: -0.21, z: 0.1, w: 0.41, d: 0.7, y: 0.5, h: 0.1, color: "cushion", edges: "faint" },
|
||||
{ shape: "box", x: 0.21, z: 0.1, w: 0.41, d: 0.7, y: 0.5, h: 0.1, color: "cushion", edges: "faint" },
|
||||
leg(-0.45, -0.4, 0.03, 0.06, 0.12),
|
||||
leg(0.45, -0.4, 0.03, 0.06, 0.12),
|
||||
leg(-0.45, 0.4, 0.03, 0.06, 0.12),
|
||||
leg(0.45, 0.4, 0.03, 0.06, 0.12),
|
||||
],
|
||||
}),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- centimetres
|
||||
|
||||
/** A part's place and size in centimetres (x/z from the item's middle, y from the floor), from its fractions. */
|
||||
export interface PartCm {
|
||||
x: number;
|
||||
z: number;
|
||||
y: number;
|
||||
w: number;
|
||||
d: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
const cm = (v: number) => Math.round(v * 1000) / 10;
|
||||
|
||||
export function partCm(part: PackPart, size: PackItem["size"]): PartCm {
|
||||
const [W, D, H] = size;
|
||||
return { x: cm(part.x * W), z: cm(part.z * D), y: cm(part.y * H), w: cm(part.w * W), d: cm(part.d * D), h: cm(part.h * H) };
|
||||
}
|
||||
|
||||
/** A field typed in centimetres, back as the part's fraction (rounded to 0.1 mm, so numbers stay short). */
|
||||
export function fromCm(key: keyof PartCm, value: number, size: PackItem["size"]): number {
|
||||
const [W, D, H] = size;
|
||||
const total = key === "x" || key === "w" ? W : key === "z" || key === "d" ? D : H;
|
||||
return Math.round((value / 100 / total) * 10000) / 10000;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- checks
|
||||
|
||||
export interface Problem {
|
||||
/** Where: "pack", "item:<index>" or "item:<index>/part:<index>". */
|
||||
where: string;
|
||||
key: string;
|
||||
vars?: Record<string, string | number>;
|
||||
}
|
||||
|
||||
const inRange = (v: unknown, lo: number, hi: number) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi;
|
||||
const color = (v: unknown) => typeof v === "string" && (/^#[0-9a-fA-F]{6}$/.test(v) || (COLOR_ROLES as readonly string[]).includes(v));
|
||||
|
||||
function checkPart(p: PackPart, where: string, out: Problem[]): void {
|
||||
const bad = (field: string) => out.push({ where, key: "bad_value", vars: { field } });
|
||||
if (!["box", "cyl", "loft", "sweep"].includes(p.shape)) bad("shape");
|
||||
for (const f of ["x", "z"] as const) if (!inRange(p[f], -0.5, 0.5)) bad(f);
|
||||
for (const f of ["w", "d", "h"] as const) if (!inRange(p[f], 0.001, 1)) bad(f);
|
||||
if (!inRange(p.y, 0, 1)) bad("y");
|
||||
if (!color(p.color)) bad("color");
|
||||
if (p.top !== undefined && !color(p.top)) bad("top");
|
||||
for (const f of ["tx", "tz"] as const) if (p[f] !== undefined && !inRange(p[f], -0.5, 0.5)) bad(f);
|
||||
for (const f of ["tw", "td"] as const) if (p[f] !== undefined && !inRange(p[f], 0.001, 1)) bad(f);
|
||||
if (p.rot !== undefined && !inRange(p.rot, -360, 360)) bad("rot");
|
||||
if (p.exp !== undefined && !inRange(p.exp, 1.5, 8)) bad("exp");
|
||||
if (p.n !== undefined && !(Number.isInteger(p.n) && p.n >= 6 && p.n <= 32)) bad("n");
|
||||
if (p.shape === "sweep") {
|
||||
const s = p.stations ?? [];
|
||||
if (s.length < 2 || s.length > 48) out.push({ where, key: "sweep_stations" });
|
||||
for (const [z, y0, y1, w] of s) if (!(inRange(z, -0.5, 0.5) && inRange(y0, 0, 1) && inRange(y1, 0, 1) && inRange(w, 0.001, 1))) bad("stations");
|
||||
}
|
||||
// the outside: a part that reaches past the item's box is cut nowhere, but it looks wrong in the plan
|
||||
if (inRange(p.x, -0.5, 0.5) && inRange(p.w, 0, 1) && Math.abs(p.x) + p.w / 2 > 0.5001 && p.shape !== "sweep") out.push({ where, key: "outside" });
|
||||
if (inRange(p.y, 0, 1) && inRange(p.h, 0, 1) && p.y + p.h > 1.0001) out.push({ where, key: "outside" });
|
||||
}
|
||||
|
||||
/** Everything that would stop the integration from importing the pack, and a few warnings ("outside"). */
|
||||
export function checkPack(pack: FurniturePack): Problem[] {
|
||||
const out: Problem[] = [];
|
||||
if (!ID.test(pack.id ?? "")) out.push({ where: "pack", key: "bad_pack_id" });
|
||||
else if (pack.id.startsWith("nextfloor.")) out.push({ where: "pack", key: "reserved_id" });
|
||||
if (!pack.name?.trim() || pack.name.length > 80) out.push({ where: "pack", key: "bad_name" });
|
||||
if (!pack.publisher?.trim() || pack.publisher.length > 80) out.push({ where: "pack", key: "bad_publisher" });
|
||||
if ((pack.description ?? "").length > 400) out.push({ where: "pack", key: "long_description" });
|
||||
if (!pack.items.length || pack.items.length > MAX_ITEMS) out.push({ where: "pack", key: "item_count" });
|
||||
const ids = new Set<string>();
|
||||
pack.items.forEach((item, i) => {
|
||||
const where = `item:${i}`;
|
||||
if (!ID.test(item.id ?? "")) out.push({ where, key: "bad_item_id" });
|
||||
if (ids.has(item.id)) out.push({ where, key: "duplicate_item_id" });
|
||||
ids.add(item.id);
|
||||
const names = Object.entries(item.name ?? {});
|
||||
if (!names.length || names.some(([lang, text]) => lang.length < 2 || lang.length > 5 || !text.trim() || text.length > 80)) out.push({ where, key: "bad_item_name" });
|
||||
if (!Array.isArray(item.size) || item.size.length !== 3 || item.size.some((v) => !inRange(v, 0.01, 10))) out.push({ where, key: "bad_size" });
|
||||
if (!item.parts.length || item.parts.length > MAX_PARTS) out.push({ where, key: "part_count", vars: { max: MAX_PARTS } });
|
||||
item.parts.forEach((p, k) => checkPart(p, `${where}/part:${k}`, out));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Problems that keep the pack from being imported (the rest are warnings). */
|
||||
export const blocking = (problems: Problem[]): Problem[] => problems.filter((p) => p.key !== "outside");
|
||||
|
||||
// ---------------------------------------------------------------- files
|
||||
|
||||
/** The pack as the integration imports it: format header first, defaults and empty fields left out. */
|
||||
export function exportPack(pack: FurniturePack): string {
|
||||
const clean = (part: PackPart): PackPart => {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(part)) {
|
||||
if (v === undefined || v === null || v === false) continue;
|
||||
out[k] = typeof v === "number" ? Math.round(v * 10000) / 10000 : v;
|
||||
}
|
||||
return out as unknown as PackPart;
|
||||
};
|
||||
const items = pack.items.map((item) => {
|
||||
const out: Record<string, unknown> = { id: item.id, name: item.name, size: item.size.map((v) => Math.round(v * 1000) / 1000) };
|
||||
for (const k of ["electric", "climate", "mount", "wall_y", "surface", "stretch", "light", "hole"] as const) {
|
||||
const v = item[k as keyof PackItem];
|
||||
if (v === undefined || v === false || (k === "mount" && v === "floor")) continue;
|
||||
out[k] = v;
|
||||
}
|
||||
out.parts = item.parts.map(clean);
|
||||
if (item.symbol?.length) out.symbol = item.symbol;
|
||||
if (item.colors?.length) out.colors = item.colors;
|
||||
return out;
|
||||
});
|
||||
const file = { format: "nfpack", version: 1, id: pack.id, name: pack.name, publisher: pack.publisher, release: pack.release ?? 1, description: pack.description ?? "", items };
|
||||
return JSON.stringify(file, null, 1);
|
||||
}
|
||||
|
||||
/** A pack file read back for editing; null when it is not one. */
|
||||
export function importPack(text: string): FurniturePack | null {
|
||||
if (text.length > MAX_PACK_SIZE) return null;
|
||||
try {
|
||||
const data = JSON.parse(text) as Record<string, unknown>;
|
||||
if (data?.format !== "nfpack" || !Array.isArray(data.items)) return null;
|
||||
return { id: String(data.id ?? ""), name: String(data.name ?? ""), publisher: String(data.publisher ?? ""), description: String(data.description ?? ""), release: Number(data.release ?? 1), items: data.items as PackItem[] };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A free id for a new item ("cabinet", "cabinet_2", …). */
|
||||
export function freeItemId(pack: FurniturePack, base: string): string {
|
||||
const taken = new Set(pack.items.map((i) => i.id));
|
||||
if (!taken.has(base)) return base;
|
||||
let n = 2;
|
||||
while (taken.has(`${base}_${n}`)) n++;
|
||||
return `${base}_${n}`;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
// The builder's 3D view: the item drawn by NextFloor's own furniture code (so it looks exactly as it will in the plan), a floor
|
||||
// grid with the item's footprint, the selected part outlined in the accent colour, and a tap that picks a part. Drag turns the
|
||||
// view, the wheel or two fingers zoom.
|
||||
|
||||
import { Color, GridHelper, LineBasicMaterial, LineSegments, Mesh, MeshBasicMaterial, PerspectiveCamera, Raycaster, Scene, Vector2, Vector3, WebGLRenderer, type BufferGeometry } from "three";
|
||||
import type { PackItem } from "../packs.ts";
|
||||
import { GeoBuffer, LineBuffer } from "../viewer/geo.ts";
|
||||
import { Builder } from "../viewer/furniture/builder.ts";
|
||||
import { packModel, placement } from "../viewer/furniture/packs.ts";
|
||||
|
||||
const LAMP_LIGHT = 0xffb547;
|
||||
const ACCENT = new Color(0x37e0ff);
|
||||
|
||||
export type ViewPreset = "iso" | "front" | "side" | "top";
|
||||
|
||||
/** The distance between the first two fingers on the screen. */
|
||||
function spread(pointers: Map<number, Vector2>): number {
|
||||
const [a, b] = [...pointers.values()];
|
||||
return a && b ? a.distanceTo(b) : 0;
|
||||
}
|
||||
|
||||
export class BuilderScene {
|
||||
private readonly renderer: WebGLRenderer;
|
||||
private readonly scene = new Scene();
|
||||
private readonly camera = new PerspectiveCamera(40, 1, 0.01, 200);
|
||||
private readonly target = new Vector3();
|
||||
/** Camera around the target: azimuth, elevation (radians) and distance. */
|
||||
private theta = 0.65;
|
||||
private phi = 1.05;
|
||||
private radius = 3;
|
||||
private item: PackItem | null = null;
|
||||
private selected = -1;
|
||||
private model: Mesh | null = null;
|
||||
private edges: LineSegments | null = null;
|
||||
private highlight: LineSegments | null = null;
|
||||
private grid: GridHelper | null = null;
|
||||
/** One mesh per part, invisible, for picking. */
|
||||
private pickers: Mesh[] = [];
|
||||
private frame = 0;
|
||||
private readonly observer: ResizeObserver;
|
||||
private onPick: (index: number) => void = () => undefined;
|
||||
|
||||
private readonly canvas: HTMLCanvasElement;
|
||||
|
||||
constructor(canvas: HTMLCanvasElement) {
|
||||
this.canvas = canvas;
|
||||
this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false });
|
||||
this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
|
||||
this.renderer.setClearColor(0x0b1020, 1);
|
||||
this.observer = new ResizeObserver(() => this.resize());
|
||||
this.observer.observe(canvas);
|
||||
this.listen();
|
||||
}
|
||||
|
||||
set pick(cb: (index: number) => void) {
|
||||
this.onPick = cb;
|
||||
}
|
||||
|
||||
/** Draw an item; `selected` is the index of the outlined part (-1: none). Keeps the camera unless the item's size changed a lot. */
|
||||
show(item: PackItem, selected: number): void {
|
||||
const sizeChanged = !this.item || this.item.size.some((v, i) => Math.abs(v - item.size[i]) > 0.3 * Math.max(v, item.size[i]));
|
||||
this.item = item;
|
||||
this.selected = selected;
|
||||
this.rebuild();
|
||||
if (sizeChanged) this.fit();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
setView(preset: ViewPreset): void {
|
||||
const angles: Record<ViewPreset, [number, number]> = { iso: [0.65, 1.05], front: [0, Math.PI / 2 - 0.02], side: [Math.PI / 2, Math.PI / 2 - 0.02], top: [0, 0.02] };
|
||||
[this.theta, this.phi] = angles[preset];
|
||||
this.fit();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
zoom(factor: number): void {
|
||||
this.radius = Math.min(40, Math.max(0.2, this.radius * factor));
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
cancelAnimationFrame(this.frame);
|
||||
this.observer.disconnect();
|
||||
this.clear();
|
||||
this.renderer.dispose();
|
||||
}
|
||||
|
||||
private fit(): void {
|
||||
if (!this.item) return;
|
||||
const [w, d, h] = this.item.size;
|
||||
this.target.set(0, h / 2, 0);
|
||||
this.radius = Math.max(0.6, Math.hypot(w, d, h) * 1.6);
|
||||
}
|
||||
|
||||
private clear(): void {
|
||||
for (const o of [this.model, this.edges, this.highlight, this.grid, ...this.pickers]) {
|
||||
if (!o) continue;
|
||||
this.scene.remove(o);
|
||||
(o as { geometry?: BufferGeometry }).geometry?.dispose();
|
||||
const m = (o as { material?: { dispose(): void } }).material;
|
||||
m?.dispose();
|
||||
}
|
||||
this.pickers = [];
|
||||
this.model = this.edges = this.highlight = this.grid = null;
|
||||
}
|
||||
|
||||
private rebuild(): void {
|
||||
this.clear();
|
||||
const item = this.item;
|
||||
if (!item) return;
|
||||
const [w, d, h] = item.size;
|
||||
const at = placement({ x: 0, z: 0, rotation: 0 });
|
||||
// the whole item, as the plan draws it (a lamp lit)
|
||||
const [solids, lines] = [new GeoBuffer(), new LineBuffer()];
|
||||
packModel(new Builder(solids, lines, at), item, w, d, h, 0, item.light ? LAMP_LIGHT : null);
|
||||
// the neon palette is made for a dark room: a little more light, as the library pictures have
|
||||
this.model = new Mesh(solids.geometry(), new MeshBasicMaterial({ vertexColors: true, color: new Color(1.25, 1.25, 1.25) }));
|
||||
this.edges = new LineSegments(lines.geometry(), new LineBasicMaterial({ vertexColors: true, color: new Color(1.8, 1.8, 1.8) }));
|
||||
this.scene.add(this.model, this.edges);
|
||||
// each part alone: for picking, and the selected one outlined
|
||||
item.parts.forEach((part, i) => {
|
||||
const [g, l] = [new GeoBuffer(), new LineBuffer()];
|
||||
packModel(new Builder(g, l, at), { ...item, parts: [{ ...part, edges: true }] }, w, d, h, 0, null);
|
||||
const mesh = new Mesh(g.geometry(), new MeshBasicMaterial({ visible: false }));
|
||||
mesh.userData.part = i;
|
||||
this.pickers.push(mesh);
|
||||
this.scene.add(mesh);
|
||||
if (i === this.selected) {
|
||||
this.highlight = new LineSegments(l.geometry(), new LineBasicMaterial({ color: ACCENT, depthTest: false, transparent: true }));
|
||||
this.highlight.renderOrder = 10;
|
||||
this.scene.add(this.highlight);
|
||||
}
|
||||
});
|
||||
// a grid on the floor, one line every 10 cm, around the item's footprint
|
||||
const span = Math.ceil(Math.max(w, d) * 1.6 * 10) / 10 + 0.4;
|
||||
this.grid = new GridHelper(span, Math.round(span * 10), 0x2a3a5c, 0x182238);
|
||||
this.scene.add(this.grid);
|
||||
}
|
||||
|
||||
private invalidate(): void {
|
||||
if (this.frame) return;
|
||||
this.frame = requestAnimationFrame(() => {
|
||||
this.frame = 0;
|
||||
this.render();
|
||||
});
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
const sin = Math.sin(this.phi);
|
||||
this.camera.position.set(this.target.x + this.radius * sin * Math.sin(this.theta), this.target.y + this.radius * Math.cos(this.phi), this.target.z + this.radius * sin * Math.cos(this.theta));
|
||||
this.camera.lookAt(this.target);
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
}
|
||||
|
||||
private resize(): void {
|
||||
const { clientWidth: w, clientHeight: h } = this.canvas;
|
||||
if (!w || !h) return;
|
||||
this.renderer.setSize(w, h, false);
|
||||
this.camera.aspect = w / h;
|
||||
this.camera.updateProjectionMatrix();
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
private listen(): void {
|
||||
const pointers = new Map<number, Vector2>();
|
||||
let moved = 0;
|
||||
let pinch = 0;
|
||||
this.canvas.addEventListener("pointerdown", (e) => {
|
||||
this.canvas.setPointerCapture(e.pointerId);
|
||||
pointers.set(e.pointerId, new Vector2(e.clientX, e.clientY));
|
||||
moved = 0;
|
||||
if (pointers.size === 2) pinch = spread(pointers);
|
||||
});
|
||||
this.canvas.addEventListener("pointermove", (e) => {
|
||||
const last = pointers.get(e.pointerId);
|
||||
if (!last) return;
|
||||
const now = new Vector2(e.clientX, e.clientY);
|
||||
if (pointers.size === 2) {
|
||||
pointers.set(e.pointerId, now);
|
||||
const distance = spread(pointers);
|
||||
if (pinch > 0 && distance > 0) this.zoom(pinch / distance);
|
||||
pinch = distance;
|
||||
moved = 99;
|
||||
return;
|
||||
}
|
||||
const dx = now.x - last.x;
|
||||
const dy = now.y - last.y;
|
||||
moved += Math.abs(dx) + Math.abs(dy);
|
||||
pointers.set(e.pointerId, now);
|
||||
this.theta -= dx * 0.008;
|
||||
this.phi = Math.min(Math.PI / 2 - 0.01, Math.max(0.02, this.phi - dy * 0.008));
|
||||
this.invalidate();
|
||||
});
|
||||
const up = (e: PointerEvent) => {
|
||||
const was = pointers.has(e.pointerId);
|
||||
pointers.delete(e.pointerId);
|
||||
if (pointers.size < 2) pinch = 0;
|
||||
// a tap (no drag) picks the part under the finger
|
||||
if (was && moved < 6 && e.type === "pointerup") this.pickAt(e.clientX, e.clientY);
|
||||
};
|
||||
this.canvas.addEventListener("pointerup", up);
|
||||
this.canvas.addEventListener("pointercancel", up);
|
||||
this.canvas.addEventListener(
|
||||
"wheel",
|
||||
(e) => {
|
||||
e.preventDefault();
|
||||
this.zoom(e.deltaY > 0 ? 1.1 : 1 / 1.1);
|
||||
},
|
||||
{ passive: false },
|
||||
);
|
||||
}
|
||||
|
||||
private pickAt(x: number, y: number): void {
|
||||
const r = this.canvas.getBoundingClientRect();
|
||||
const ndc = new Vector2(((x - r.left) / r.width) * 2 - 1, -((y - r.top) / r.height) * 2 + 1);
|
||||
const ray = new Raycaster();
|
||||
ray.setFromCamera(ndc, this.camera);
|
||||
for (const m of this.pickers) m.visible = true;
|
||||
const hit = ray.intersectObjects(this.pickers, false)[0];
|
||||
for (const m of this.pickers) m.visible = false;
|
||||
this.onPick(hit ? (hit.object.userData.part as number) : -1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// The builder's texts in German and English (the page follows the browser's language; English for every other one).
|
||||
|
||||
const de = {
|
||||
title: "NextFloor Möbel-Baukasten",
|
||||
subtitle: "Eigene Möbel bauen, als Pack speichern und mit allen teilen – kostenlos.",
|
||||
new_pack: "Neu",
|
||||
open: "Öffnen …",
|
||||
save: "Pack speichern",
|
||||
submit: "Im Community-Store teilen",
|
||||
pack: "Pack",
|
||||
pack_id: "Pack-ID",
|
||||
pack_id_hint: "Klein, ohne Leerzeichen, am besten dein Name vorne: anna.kueche",
|
||||
pack_name: "Name",
|
||||
publisher: "Von",
|
||||
description: "Beschreibung",
|
||||
release: "Version",
|
||||
items: "Möbel",
|
||||
add_item: "+ Möbel",
|
||||
template: "Vorlage …",
|
||||
t_empty: "Leer",
|
||||
t_cabinet: "Schrank",
|
||||
t_table: "Tisch",
|
||||
t_shelf: "Regal",
|
||||
t_floor_lamp: "Stehlampe",
|
||||
t_sofa: "Sofa",
|
||||
duplicate: "Duplizieren",
|
||||
delete: "Löschen",
|
||||
item: "Dieses Möbel",
|
||||
item_id: "ID",
|
||||
name_de: "Name (Deutsch)",
|
||||
name_en: "Name (Englisch)",
|
||||
width: "Breite (cm)",
|
||||
depth: "Tiefe (cm)",
|
||||
height: "Höhe (cm)",
|
||||
mount: "Steht",
|
||||
mount_floor: "auf dem Boden",
|
||||
mount_surface: "auf einem Möbel",
|
||||
mount_wall: "an der Wand",
|
||||
mount_ceiling: "an der Decke",
|
||||
wall_y: "Höhe an der Wand (cm)",
|
||||
electric: "Elektrisch (Schalter und Leistung verknüpfbar)",
|
||||
surface: "Oberseite trägt andere Möbel",
|
||||
stretch: "Beim Größerziehen alles gleichmäßig strecken",
|
||||
light: "Leuchte",
|
||||
light_none: "keine",
|
||||
parts: "Teile",
|
||||
add: "Hinzufügen:",
|
||||
s_box: "Quader",
|
||||
s_cyl: "Zylinder",
|
||||
s_loft: "Schräge",
|
||||
s_sweep: "Rundkörper",
|
||||
part: "Teil",
|
||||
no_part: "Tippe ein Teil im 3D an oder füge eins hinzu.",
|
||||
x: "Links/rechts (cm)",
|
||||
z: "Vorne/hinten (cm)",
|
||||
y: "Unterkante (cm)",
|
||||
w: "Breite (cm)",
|
||||
d: "Tiefe (cm)",
|
||||
h: "Höhe (cm)",
|
||||
rot: "Drehung (°)",
|
||||
axis: "Liegt",
|
||||
axis_y: "aufrecht",
|
||||
axis_x: "quer",
|
||||
axis_z: "längs",
|
||||
top_w: "Oben breit (%)",
|
||||
top_d: "Oben tief (%)",
|
||||
top_x: "Oben versetzt (%)",
|
||||
exp: "Kantig (2 = rund)",
|
||||
stations: "Querschnitte",
|
||||
station: "Bei (%) · unten · oben · breit (%)",
|
||||
add_station: "+ Querschnitt",
|
||||
color: "Farbe",
|
||||
top: "Farbe oben",
|
||||
same: "wie Seite",
|
||||
own_color: "eigene …",
|
||||
edges: "Kanten",
|
||||
edges_none: "keine",
|
||||
edges_soft: "dezent",
|
||||
edges_glow: "leuchtend",
|
||||
edges_faint: "zart",
|
||||
glow: "Leuchtet (Lampenteil)",
|
||||
screen: "Bildschirm (Vorderseite zeigt das Bild)",
|
||||
check: "Prüfung",
|
||||
ok: "Alles in Ordnung – das Pack lässt sich in NextFloor importieren.",
|
||||
view_iso: "Schräg",
|
||||
view_front: "Vorne",
|
||||
view_side: "Seite",
|
||||
view_top: "Oben",
|
||||
saved_local: "Wird in diesem Browser gespeichert.",
|
||||
import_failed: "Das ist keine Pack-Datei.",
|
||||
submit_steps:
|
||||
"So kommt dein Pack in den Store: 1. Das Pack ist in der Zwischenablage. 2. Auf GitHub öffnet sich ein Formular – füge das Pack ins Feld „Pack“ ein und sende es ab. 3. Eine Prüfung läuft automatisch; danach schaut der Betreuer drüber und nimmt es auf.",
|
||||
submit_go: "Formular auf GitHub öffnen",
|
||||
submit_blocked: "Erst die Fehler unten beheben.",
|
||||
close: "Schließen",
|
||||
howto:
|
||||
"Teile antippen, um sie auszuwählen. Ziehen dreht die Ansicht, Mausrad oder zwei Finger zoomen. Alle Maße in Zentimetern; die Mitte des Möbels ist 0, vorne ist positiv.",
|
||||
colors_role: "Rollen-Farben passen sich dem Look an (Neon, Blueprint, Tag).",
|
||||
r_body: "Korpus",
|
||||
r_fabric: "Stoff",
|
||||
r_cushion: "Polster",
|
||||
r_wood: "Holz",
|
||||
r_white: "Weiß",
|
||||
r_metal: "Metall",
|
||||
r_dark: "Dunkel",
|
||||
r_glass: "Glas",
|
||||
r_plant: "Pflanze",
|
||||
r_pot: "Topf",
|
||||
r_accent: "Akzent",
|
||||
bad_pack_id: "Die Pack-ID: klein, a–z, 0–9, Punkt, Strich, höchstens 40 Zeichen.",
|
||||
reserved_id: "„nextfloor.“ ist für die mitgelieferten Packs reserviert.",
|
||||
bad_name: "Das Pack braucht einen Namen (höchstens 80 Zeichen).",
|
||||
bad_publisher: "Wer hat es gebaut? (höchstens 80 Zeichen)",
|
||||
long_description: "Die Beschreibung ist länger als 400 Zeichen.",
|
||||
item_count: "Ein Pack hat 1 bis 200 Möbel.",
|
||||
bad_item_id: "Die ID: klein, a–z, 0–9, Punkt, Strich, höchstens 40 Zeichen.",
|
||||
duplicate_item_id: "Zwei Möbel haben dieselbe ID.",
|
||||
bad_item_name: "Jedes Möbel braucht einen Namen.",
|
||||
bad_size: "Die Größe muss zwischen 1 cm und 10 m liegen.",
|
||||
part_count: "1 bis {max} Teile je Möbel.",
|
||||
bad_value: "Ein Wert ist außerhalb des Möbels: {field}.",
|
||||
sweep_stations: "Ein Rundkörper braucht 2 bis 48 Querschnitte.",
|
||||
outside: "Ragt aus dem Möbel heraus (nur ein Hinweis).",
|
||||
where_pack: "Pack",
|
||||
};
|
||||
|
||||
export type TextKey = keyof typeof de;
|
||||
|
||||
const en: Record<TextKey, string> = {
|
||||
title: "NextFloor furniture builder",
|
||||
subtitle: "Build your own furniture, save it as a pack and share it with everyone – free.",
|
||||
new_pack: "New",
|
||||
open: "Open …",
|
||||
save: "Save pack",
|
||||
submit: "Share in the community store",
|
||||
pack: "Pack",
|
||||
pack_id: "Pack id",
|
||||
pack_id_hint: "Lower case, no spaces, your name first is best: anna.kitchen",
|
||||
pack_name: "Name",
|
||||
publisher: "By",
|
||||
description: "Description",
|
||||
release: "Version",
|
||||
items: "Furniture",
|
||||
add_item: "+ Item",
|
||||
template: "Template …",
|
||||
t_empty: "Empty",
|
||||
t_cabinet: "Cabinet",
|
||||
t_table: "Table",
|
||||
t_shelf: "Shelf",
|
||||
t_floor_lamp: "Floor lamp",
|
||||
t_sofa: "Sofa",
|
||||
duplicate: "Duplicate",
|
||||
delete: "Delete",
|
||||
item: "This item",
|
||||
item_id: "Id",
|
||||
name_de: "Name (German)",
|
||||
name_en: "Name (English)",
|
||||
width: "Width (cm)",
|
||||
depth: "Depth (cm)",
|
||||
height: "Height (cm)",
|
||||
mount: "Stands",
|
||||
mount_floor: "on the floor",
|
||||
mount_surface: "on furniture",
|
||||
mount_wall: "on the wall",
|
||||
mount_ceiling: "from the ceiling",
|
||||
wall_y: "Height on the wall (cm)",
|
||||
electric: "Electric (switch and power can be linked)",
|
||||
surface: "Its top carries other items",
|
||||
stretch: "Stretch everything evenly when resized",
|
||||
light: "Lamp",
|
||||
light_none: "none",
|
||||
parts: "Parts",
|
||||
add: "Add:",
|
||||
s_box: "Box",
|
||||
s_cyl: "Cylinder",
|
||||
s_loft: "Taper",
|
||||
s_sweep: "Round body",
|
||||
part: "Part",
|
||||
no_part: "Tap a part in 3D, or add one.",
|
||||
x: "Left/right (cm)",
|
||||
z: "Front/back (cm)",
|
||||
y: "Bottom (cm)",
|
||||
w: "Width (cm)",
|
||||
d: "Depth (cm)",
|
||||
h: "Height (cm)",
|
||||
rot: "Turn (°)",
|
||||
axis: "Lies",
|
||||
axis_y: "upright",
|
||||
axis_x: "across",
|
||||
axis_z: "lengthwise",
|
||||
top_w: "Top width (%)",
|
||||
top_d: "Top depth (%)",
|
||||
top_x: "Top offset (%)",
|
||||
exp: "Boxy (2 = round)",
|
||||
stations: "Cross sections",
|
||||
station: "At (%) · bottom · top · width (%)",
|
||||
add_station: "+ Cross section",
|
||||
color: "Colour",
|
||||
top: "Top colour",
|
||||
same: "as the sides",
|
||||
own_color: "own …",
|
||||
edges: "Edges",
|
||||
edges_none: "none",
|
||||
edges_soft: "soft",
|
||||
edges_glow: "glowing",
|
||||
edges_faint: "faint",
|
||||
glow: "Glows (lamp part)",
|
||||
screen: "Screen (its front shows the picture)",
|
||||
check: "Check",
|
||||
ok: "All good – NextFloor can import this pack.",
|
||||
view_iso: "Angled",
|
||||
view_front: "Front",
|
||||
view_side: "Side",
|
||||
view_top: "Top",
|
||||
saved_local: "Kept in this browser.",
|
||||
import_failed: "That is not a pack file.",
|
||||
submit_steps:
|
||||
"How your pack gets into the store: 1. The pack is on your clipboard. 2. A form opens on GitHub – paste the pack into the \"Pack\" field and send it. 3. A check runs by itself; then the maintainer looks it over and takes it in.",
|
||||
submit_go: "Open the form on GitHub",
|
||||
submit_blocked: "Fix the problems below first.",
|
||||
close: "Close",
|
||||
howto: "Tap parts to select them. Drag turns the view, the wheel or two fingers zoom. All sizes in centimetres; the middle of the item is 0, the front is positive.",
|
||||
colors_role: "Role colours follow the look (neon, blueprint, day).",
|
||||
r_body: "Body",
|
||||
r_fabric: "Fabric",
|
||||
r_cushion: "Cushion",
|
||||
r_wood: "Wood",
|
||||
r_white: "White",
|
||||
r_metal: "Metal",
|
||||
r_dark: "Dark",
|
||||
r_glass: "Glass",
|
||||
r_plant: "Plant",
|
||||
r_pot: "Pot",
|
||||
r_accent: "Accent",
|
||||
bad_pack_id: "The pack id: lower case, a–z, 0–9, dot, dash, at most 40 characters.",
|
||||
reserved_id: "\"nextfloor.\" is kept for the packs that come with NextFloor.",
|
||||
bad_name: "The pack needs a name (at most 80 characters).",
|
||||
bad_publisher: "Who built it? (at most 80 characters)",
|
||||
long_description: "The description is longer than 400 characters.",
|
||||
item_count: "A pack has 1 to 200 items.",
|
||||
bad_item_id: "The id: lower case, a–z, 0–9, dot, dash, at most 40 characters.",
|
||||
duplicate_item_id: "Two items have the same id.",
|
||||
bad_item_name: "Every item needs a name.",
|
||||
bad_size: "The size must be between 1 cm and 10 m.",
|
||||
part_count: "1 to {max} parts per item.",
|
||||
bad_value: "A value lies outside the item: {field}.",
|
||||
sweep_stations: "A round body needs 2 to 48 cross sections.",
|
||||
outside: "Reaches out of the item (only a note).",
|
||||
where_pack: "Pack",
|
||||
};
|
||||
|
||||
export const LANG: "de" | "en" = (navigator.language || "en").toLowerCase().startsWith("de") ? "de" : "en";
|
||||
|
||||
export function t(key: TextKey, vars?: Record<string, string | number>): string {
|
||||
let text = (LANG === "de" ? de : en)[key];
|
||||
for (const [k, v] of Object.entries(vars ?? {})) text = text.replace(`{${k}}`, String(v));
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { BuildingController, compareVersions } from "./building-controller.ts";
|
||||
import { emptyBuilding } from "./model.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
|
||||
/** A host that counts redraws, and a Home Assistant whose backend is a small script. */
|
||||
function setup(overrides: Partial<Record<string, (msg: Record<string, unknown>) => unknown>> = {}) {
|
||||
const host = { redraws: 0, addController() {}, requestUpdate() { this.redraws++; } };
|
||||
const sent: Record<string, unknown>[] = [];
|
||||
let listener: ((m: { revision: number }) => void) | null = null;
|
||||
let revision = 10;
|
||||
const hass = {
|
||||
callWS: async (msg: Record<string, unknown>) => {
|
||||
sent.push(msg);
|
||||
const custom = overrides[String(msg.type)];
|
||||
if (custom) return custom(msg);
|
||||
switch (msg.type) {
|
||||
case "nextfloor/building/get":
|
||||
return { building: emptyBuilding(), revision, version: "1.0.0" };
|
||||
case "nextfloor/building/save":
|
||||
return { revision: ++revision };
|
||||
case "nextfloor/packs/list":
|
||||
return { packs: [] };
|
||||
default:
|
||||
throw new Error(`unexpected ${String(msg.type)}`);
|
||||
}
|
||||
},
|
||||
connection: { subscribeMessage: async (cb: (m: { revision: number }) => void) => ((listener = cb), async () => void (listener = null)) },
|
||||
} as unknown as HomeAssistant;
|
||||
const controller = new BuildingController(host as never);
|
||||
return { controller, host, hass, sent, emit: (r: number) => listener?.({ revision: r }), isListening: () => listener !== null };
|
||||
}
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
test("versions compare number by number", () => {
|
||||
assert.ok(compareVersions("1.10.1", "1.9.2") > 0);
|
||||
assert.ok(compareVersions("1.9.2", "1.10.0") < 0);
|
||||
assert.equal(compareVersions("1.0", "1.0.0"), 0);
|
||||
assert.ok(compareVersions("2.0.0", "1.99.99") > 0);
|
||||
assert.ok(compareVersions("1.2.3-beta", "1.2.3") === 0, "a suffix counts as zero");
|
||||
});
|
||||
|
||||
test("connecting loads the plan and listens for changes", async () => {
|
||||
const { controller, hass, isListening } = setup();
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
assert.ok(controller.building);
|
||||
assert.equal(controller.backendVersion, "1.0.0");
|
||||
assert.equal(isListening(), true);
|
||||
controller.hostDisconnected();
|
||||
await settle();
|
||||
assert.equal(isListening(), false);
|
||||
});
|
||||
|
||||
test("an edit shows at once, is saved after flush, and then reads as saved", async () => {
|
||||
const { controller, hass, sent } = setup();
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
const edited = emptyBuilding();
|
||||
controller.edit(edited);
|
||||
assert.equal(controller.building, edited);
|
||||
assert.equal(sent.filter((m) => m.type === "nextfloor/building/save").length, 0, "not yet, the pause has not passed");
|
||||
await controller.flush();
|
||||
assert.equal(sent.filter((m) => m.type === "nextfloor/building/save").length, 1);
|
||||
assert.equal(controller.saveState, "saved");
|
||||
assert.equal(controller.saveError, null);
|
||||
});
|
||||
|
||||
test("several quick edits are saved as one", async () => {
|
||||
const { controller, hass, sent } = setup();
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
controller.edit(emptyBuilding());
|
||||
controller.edit(emptyBuilding());
|
||||
controller.edit(emptyBuilding());
|
||||
await controller.flush();
|
||||
assert.equal(sent.filter((m) => m.type === "nextfloor/building/save").length, 1);
|
||||
});
|
||||
|
||||
test("a failed save is reported, and an old backend asks for a restart", async () => {
|
||||
const { controller, hass } = setup({
|
||||
"nextfloor/building/save": () => {
|
||||
throw { message: "extra keys not allowed @ data['foo']" };
|
||||
},
|
||||
});
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
controller.edit(emptyBuilding());
|
||||
await controller.flush();
|
||||
assert.equal(controller.saveState, "error");
|
||||
assert.match(controller.saveError ?? "", /extra keys/);
|
||||
assert.equal(controller.needsRestart, true);
|
||||
});
|
||||
|
||||
test("changes from elsewhere reload the plan, our own saves do not", async () => {
|
||||
const { controller, hass, sent, emit } = setup();
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
const loads = () => sent.filter((m) => m.type === "nextfloor/building/get").length;
|
||||
const before = loads();
|
||||
controller.edit(emptyBuilding());
|
||||
await controller.flush(); // saves revision 11
|
||||
emit(11);
|
||||
await settle();
|
||||
assert.equal(loads(), before, "echo of our own save");
|
||||
emit(99);
|
||||
await settle();
|
||||
assert.equal(loads(), before + 1, "a save from another browser");
|
||||
});
|
||||
|
||||
test("a load failure is shown as an error", async () => {
|
||||
const { controller, hass } = setup({
|
||||
"nextfloor/building/get": () => {
|
||||
throw new Error("backend down");
|
||||
},
|
||||
});
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
assert.equal(controller.error, "backend down");
|
||||
assert.equal(controller.building, null);
|
||||
});
|
||||
|
||||
test("older backends without packs just have none", async () => {
|
||||
const { controller, hass } = setup({
|
||||
"nextfloor/packs/list": () => {
|
||||
throw new Error("unknown command");
|
||||
},
|
||||
});
|
||||
controller.hostConnected();
|
||||
controller.setHass(hass);
|
||||
await settle();
|
||||
assert.deepEqual(controller.packs, []);
|
||||
assert.ok(controller.building);
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
// The plan's connection to Home Assistant: loads it, follows changes made elsewhere, and saves edits
|
||||
// after a short pause. Edits that cannot be saved are kept in the browser so a reload does not lose them.
|
||||
|
||||
import type { ReactiveController, ReactiveControllerHost } from "lit";
|
||||
import { fetchBuilding, listPacks, saveBuilding, subscribeBuilding } from "./api.ts";
|
||||
import { loadPlugins } from "./plugins/loader.ts";
|
||||
import { onPluginsChanged } from "./plugins/registry.ts";
|
||||
import { normalizeBuilding, type Building } from "./model.ts";
|
||||
import { setPacks, type FurniturePack } from "./packs.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
|
||||
export type SaveState = "idle" | "saving" | "saved" | "error";
|
||||
|
||||
/** Quiet time after the last edit before it is sent. */
|
||||
const SAVE_DELAY_MS = 700;
|
||||
const DRAFT_STORAGE_KEY = "nextfloor.unsaved";
|
||||
|
||||
/** Frontend version, injected by the build (see build.mjs). */
|
||||
declare const __NF_VERSION__: string;
|
||||
export const FRONTEND_VERSION = typeof __NF_VERSION__ === "string" ? __NF_VERSION__ : "dev";
|
||||
|
||||
/** An edit that could not be saved. */
|
||||
export interface Draft {
|
||||
building: Building;
|
||||
savedAt: number;
|
||||
}
|
||||
|
||||
function loadDraft(): Draft | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(DRAFT_STORAGE_KEY);
|
||||
return stored ? (JSON.parse(stored) as Draft) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function storeDraft(draft: Draft | null): void {
|
||||
try {
|
||||
if (draft) localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft));
|
||||
else localStorage.removeItem(DRAFT_STORAGE_KEY);
|
||||
} catch {
|
||||
// storage is full or blocked: the edit then lives until the tab closes
|
||||
}
|
||||
}
|
||||
|
||||
const messageOf = (error: unknown): string => (error && typeof error === "object" && "message" in error ? String((error as { message: unknown }).message) : String(error));
|
||||
|
||||
/** Compares "1.10.1"-like versions piece by piece: negative when a is older than b, positive when newer. */
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const split = (v: string) => v.split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
|
||||
const [left, right] = [split(a), split(b)];
|
||||
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
||||
const difference = (left[i] ?? 0) - (right[i] ?? 0);
|
||||
if (difference !== 0) return difference;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export class BuildingController implements ReactiveController {
|
||||
building: Building | null = null;
|
||||
error: string | null = null;
|
||||
saveState: SaveState = "idle";
|
||||
/** The backend's message when the last save failed. */
|
||||
saveError: string | null = null;
|
||||
/** The version the backend runs. It differs from the frontend's until Home Assistant restarts. */
|
||||
backendVersion: string | null = null;
|
||||
/** Unsaved edits of an earlier session that can be restored. */
|
||||
draft: Draft | null = null;
|
||||
/** Imported furniture packs. */
|
||||
packs: FurniturePack[] = [];
|
||||
|
||||
private readonly host: ReactiveControllerHost;
|
||||
private stopPlugins: (() => void) | null = null;
|
||||
private hass: HomeAssistant | null = null;
|
||||
private connected = false;
|
||||
private revision = -1;
|
||||
/** Revisions our own saves produced, so their echo over the subscription is ignored. */
|
||||
private readonly ownRevisions = new Set<number>();
|
||||
private stopListening: (() => Promise<void>) | null = null;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private waiting: Building | null = null;
|
||||
private inFlight: Promise<void> | null = null;
|
||||
|
||||
constructor(host: ReactiveControllerHost) {
|
||||
this.host = host;
|
||||
host.addController(this);
|
||||
}
|
||||
|
||||
/** Hand over every new hass object; the first one starts loading. */
|
||||
setHass(hass: HomeAssistant): void {
|
||||
const isFirst = this.hass === null;
|
||||
this.hass = hass;
|
||||
if (isFirst && this.connected) void this.start();
|
||||
}
|
||||
|
||||
hostConnected(): void {
|
||||
this.connected = true;
|
||||
// a plugin that loads or registers later changes markers, animations and room panels
|
||||
this.stopPlugins = onPluginsChanged(() => this.host.requestUpdate());
|
||||
if (this.hass) void this.start();
|
||||
}
|
||||
|
||||
hostDisconnected(): void {
|
||||
this.connected = false;
|
||||
this.stopPlugins?.();
|
||||
this.stopPlugins = null;
|
||||
void this.flush();
|
||||
void this.stopListening?.();
|
||||
this.stopListening = null;
|
||||
}
|
||||
|
||||
/** A local edit: visible at once, sent after a short pause. */
|
||||
edit(building: Building): void {
|
||||
this.building = building;
|
||||
void loadPlugins(building.settings.plugins);
|
||||
this.waiting = building;
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => void this.flush(), SAVE_DELAY_MS);
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
|
||||
get frontendVersion(): string {
|
||||
return FRONTEND_VERSION;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which side is behind when versions differ. "backend": Home Assistant still runs the old integration (a restart
|
||||
* helps). "frontend": the browser or companion app holds an old bundle (a reload helps). Null when they match
|
||||
* or one version is unknown.
|
||||
*/
|
||||
get versionGap(): "backend" | "frontend" | null {
|
||||
const backend = this.backendVersion;
|
||||
if (!backend || FRONTEND_VERSION === "dev" || backend === FRONTEND_VERSION) return null;
|
||||
return compareVersions(backend, FRONTEND_VERSION) > 0 ? "frontend" : "backend";
|
||||
}
|
||||
|
||||
/** Home Assistant has to restart: the backend runs another version, or rejected fields it does not know yet. */
|
||||
get needsRestart(): boolean {
|
||||
if (this.saveError && /extra keys not allowed/i.test(this.saveError)) return true;
|
||||
return !!this.backendVersion && FRONTEND_VERSION !== "dev" && this.backendVersion !== FRONTEND_VERSION;
|
||||
}
|
||||
|
||||
/** Takes over the unsaved edits of an earlier session (and saves them). */
|
||||
restoreDraft(): void {
|
||||
const draft = this.draft;
|
||||
this.draft = null;
|
||||
if (draft) this.edit(normalizeBuilding(draft.building));
|
||||
}
|
||||
|
||||
discardDraft(): void {
|
||||
this.draft = null;
|
||||
storeDraft(null);
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
|
||||
/** Sends the pending edit now. */
|
||||
async flush(): Promise<void> {
|
||||
clearTimeout(this.timer);
|
||||
if (this.inFlight) await this.inFlight;
|
||||
const building = this.waiting;
|
||||
const hass = this.hass;
|
||||
if (!building || !hass) return;
|
||||
this.waiting = null;
|
||||
this.saveState = "saving";
|
||||
this.host.requestUpdate();
|
||||
this.inFlight = this.send(hass, building);
|
||||
await this.inFlight;
|
||||
this.inFlight = null;
|
||||
}
|
||||
|
||||
private async send(hass: HomeAssistant, building: Building): Promise<void> {
|
||||
try {
|
||||
const revision = await saveBuilding(hass, building);
|
||||
this.ownRevisions.add(revision);
|
||||
this.revision = revision;
|
||||
this.saveState = this.waiting ? "saving" : "saved";
|
||||
this.saveError = null;
|
||||
storeDraft(null);
|
||||
} catch (error) {
|
||||
this.saveState = "error";
|
||||
this.saveError = messageOf(error);
|
||||
storeDraft({ building, savedAt: Date.now() }); // after a restart it can be restored and saved
|
||||
}
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
|
||||
private async start(): Promise<void> {
|
||||
const hass = this.hass;
|
||||
if (!hass) return;
|
||||
await Promise.all([this.reloadPacks(), this.reload()]);
|
||||
if (this.stopListening || !this.connected) return;
|
||||
try {
|
||||
this.stopListening = await subscribeBuilding(hass, (revision) => {
|
||||
const ours = this.ownRevisions.has(revision) || revision === this.revision;
|
||||
const busy = this.waiting !== null || this.inFlight !== null; // our own edits win and are saved next
|
||||
if (!ours && !busy) void this.reload();
|
||||
});
|
||||
} catch {
|
||||
// an older backend or a lost connection: changes from elsewhere show up after a reload
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the furniture packs again, for example after an import or removal. */
|
||||
async reloadPacks(): Promise<void> {
|
||||
if (!this.hass) return;
|
||||
try {
|
||||
this.packs = await listPacks(this.hass);
|
||||
} catch {
|
||||
this.packs = []; // a backend without packs, before its restart
|
||||
}
|
||||
setPacks(this.packs);
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
|
||||
private async reload(): Promise<void> {
|
||||
if (!this.hass) return;
|
||||
try {
|
||||
const fetched = await fetchBuilding(this.hass);
|
||||
this.building = normalizeBuilding(fetched.building);
|
||||
void loadPlugins(this.building.settings.plugins);
|
||||
this.backendVersion = fetched.version ?? null;
|
||||
this.revision = fetched.revision;
|
||||
this.error = null;
|
||||
if (this.draft === null && !this.waiting) this.draft = loadDraft();
|
||||
} catch (error) {
|
||||
this.error = messageOf(error);
|
||||
}
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { FurnitureColors } from "./furniture-colors.ts";
|
||||
// Configuration of the dashboard card, shared by the card and its visual editor (a bundle of its own).
|
||||
|
||||
import type { MarkerKind } from "./entities/kinds.ts";
|
||||
import type { StartView } from "./model.ts";
|
||||
import type { Quality, WallMode } from "./viewer/viewer3d.ts";
|
||||
|
||||
export interface CardConfig {
|
||||
type: string;
|
||||
floor?: string;
|
||||
/** Start in this room (its id from the editor): a display for one room, e.g. for the kids. */
|
||||
room?: string;
|
||||
/** A start view of this card's own (theta, phi, radius and target as the editor shows them); default: the plan's. */
|
||||
start_view?: StartView;
|
||||
height?: number;
|
||||
walls?: WallMode;
|
||||
/** Solid walls in their paint (outside, inside, per room) instead of glass. */
|
||||
solid_walls?: boolean;
|
||||
/** Pull floors apart in the house view (default true). */
|
||||
explode?: boolean;
|
||||
/** The roof lifts and fades while zooming in (default true); false keeps it on the house. */
|
||||
roof_fade?: boolean;
|
||||
quality?: Quality;
|
||||
/** Show the performance display (frames per second, draw calls). */
|
||||
stats?: boolean;
|
||||
/** HTML markers: none | important (default) | all. */
|
||||
markers?: "none" | "important" | "all";
|
||||
/** Outside the opened room only markers of these kinds show (absent: the same as in the room). */
|
||||
markers_outside?: MarkerKind[];
|
||||
/** Devices are switched by a tap only in the opened room; elsewhere a tap opens the floor or room (a long press still acts). */
|
||||
tap_in_room?: boolean;
|
||||
/** What a double tap on a room switches: auto (the plan setting, default), area, plan or off (#62). */
|
||||
room_double_tap?: "auto" | "area" | "plan" | "off";
|
||||
/** Every device with an own name shows it under its marker (#156). */
|
||||
marker_names?: boolean;
|
||||
/** The star with the central menu: all lights / blinds of the floor or house and the favourites (default true, #145). */
|
||||
central?: boolean;
|
||||
/** Own buttons in the central menu (replace the ones set in the editor): label, icon, action, target, data (D143). */
|
||||
buttons?: { label: string; icon?: string; action: "navigate" | "more_info" | "service" | "fire_dom_event"; target?: string; data?: Record<string, unknown> }[];
|
||||
/** Heatmap of the rooms: none | temperature | humidity | co2. */
|
||||
heatmap?: "none" | "temperature" | "humidity" | "co2";
|
||||
/** Look: neon | blueprint | day. */
|
||||
theme?: "auto" | "neon" | "blueprint" | "day";
|
||||
/** A clock in a corner of the view (default none). */
|
||||
clock?: "none" | "top_left" | "top_right" | "bottom_left" | "bottom_right";
|
||||
/** The 🔒 button that locks the camera on this device (default shown). */
|
||||
lock_button?: boolean;
|
||||
/** The 🚶 button that walks through the house at eye level (default shown). */
|
||||
walk_button?: boolean;
|
||||
/** The ⏪ button that replays the last day or week (default shown). */
|
||||
time_travel?: boolean;
|
||||
/** Accent colour for the neon look and the card's chips ("#rrggbb"); leave out for the stock cyan. */
|
||||
accent?: string;
|
||||
/** Furniture colours of this card per role, on top of the house-wide ones (#82). */
|
||||
furniture_colors?: FurnitureColors;
|
||||
/** Energy values at the top (default true). */
|
||||
energy?: boolean;
|
||||
/** Power flow lines always on or off; without it the card has its own switch. */
|
||||
flows?: boolean;
|
||||
/** The live cards (energy balance, car, media) always on or off; without it the card has its own switch. */
|
||||
holograms?: boolean;
|
||||
/** Tapping a room opens its details (lights, blinds, cameras); default true. */
|
||||
room_panel?: boolean;
|
||||
/** Fill the screen below the dashboard header instead of a fixed height. */
|
||||
fill?: boolean;
|
||||
/** Switches in the card: all (true) or a list of walls, floors, temperature, humidity, co2. */
|
||||
controls?: boolean | CardControl[];
|
||||
/** Start with every bar and overlay hidden (the eye button brings them back); false shows the eye, hidden by default. */
|
||||
controls_hidden?: boolean;
|
||||
/** Hide every bar and overlay after this many seconds without a touch; a touch shows them again. */
|
||||
controls_hide_after?: number;
|
||||
/** Room names in 3D (default true). */
|
||||
room_names?: boolean;
|
||||
/** An opened floor with the floors below it dimmed (default), stacked, or on its own. */
|
||||
floor_stack?: "dim" | "stacked" | "single";
|
||||
/** A button for full screen (hides the dashboard around the card). */
|
||||
fullscreen_button?: boolean;
|
||||
/** A button that opens another dashboard or view (its path, e.g. "/lovelace/home"), with an optional label. */
|
||||
dashboard?: string;
|
||||
dashboard_label?: string;
|
||||
/** Small pictures of the floors to switch between them (default: on without a start floor). */
|
||||
floor_thumbs?: boolean;
|
||||
/** A row of buttons, one per room, to open a room straight from the card (default off). */
|
||||
room_buttons?: boolean;
|
||||
/** Warnings (smoke, water, alarm, window in the rain) as pulsing rooms and a banner (default true). */
|
||||
alerts?: boolean;
|
||||
/** Jump to the room of a new warning (default false). */
|
||||
alert_jump?: boolean;
|
||||
/** Scene and script chips of the selected room (default true). */
|
||||
scenes?: boolean;
|
||||
/** How opaque the see-through walls are, 0 … 100 % (default 20). */
|
||||
glass_walls?: number;
|
||||
/** The plan's own sensors at the top of the card (default true). */
|
||||
sensor_bar?: boolean;
|
||||
/** The star menu (favourites) stands open from the start, a size larger (default false). */
|
||||
central_open?: boolean;
|
||||
/** Switching floors keeps the camera's side, height and distance (default false). */
|
||||
keep_camera?: boolean;
|
||||
/** Easy to read: stronger contrast and larger text, for wall tablets (default false). */
|
||||
readable?: boolean;
|
||||
/** Only the floor plan: no furniture (devices and their pins stay). */
|
||||
plain?: boolean;
|
||||
/** A short right click goes one step back (off by default). */
|
||||
right_back?: boolean;
|
||||
/** Only these rooms (their ids) with what stands in them; the card cannot leave them. */
|
||||
rooms?: string[];
|
||||
/** The name of a card template (Settings → Card templates) whose options this card takes, its own ones winning. */
|
||||
template?: string;
|
||||
/** The "Today" card with the day's appointments and bins (default true). */
|
||||
today?: boolean;
|
||||
/** How much closer the fitted views come, 0.6 … 2.5 (default 1). */
|
||||
zoom?: number;
|
||||
/** Announcements (action nextfloor.announce) show and speak on this card (default true). */
|
||||
announcements?: boolean;
|
||||
/** The name of this screen, for announcements meant for some screens only (default: the name set in the panel on this device). */
|
||||
screen_name?: string;
|
||||
/** Weather outside the house: rain, snow, fog, clouds, sun and moon (default on). */
|
||||
weather?: boolean;
|
||||
/** The weather entity to use (default: the first one). */
|
||||
weather_entity?: string;
|
||||
/** How much rain, hail and snow falls, 0.1 … 1 (default 1, as much as the weather says). */
|
||||
weather_density?: number;
|
||||
/** Kiosk: seconds without a touch after which the card returns to its start view (0 = never). */
|
||||
idle_return?: number;
|
||||
/** Kiosk: dim at night – "off", "sun" (sun.sun below the horizon) or a time range "22:00-06:00". */
|
||||
night?: string;
|
||||
/** Kiosk: after the idle return, turn the view slowly by itself until the next touch. */
|
||||
idle_orbit?: boolean;
|
||||
}
|
||||
|
||||
export const CARD_CONTROLS = ["walls", "floors", "temperature", "humidity", "co2"] as const;
|
||||
export type CardControl = (typeof CARD_CONTROLS)[number];
|
||||
@@ -0,0 +1,350 @@
|
||||
// The visual editor of the dashboard card. Home Assistant shows it in the card dialog, so nobody has to write YAML. It follows
|
||||
// Home Assistant's colours: the dialog is light or dark with the user's theme.
|
||||
|
||||
import { html, LitElement, nothing, type TemplateResult } from "lit";
|
||||
import { fetchBuilding } from "./api.ts";
|
||||
import { MARKER_KINDS, type MarkerKind } from "./entities/kinds.ts";
|
||||
import { FURNITURE_ROLES, STOCK_ROLE_HEX, type FurnitureColors, type FurnitureRole } from "./furniture-colors.ts";
|
||||
import { CARD_CONTROLS, type CardConfig, type CardControl } from "./card-config.ts";
|
||||
import { checkbox, choice, DEFAULTS, flagOption, followOrForce, numberChoice, switchOption, textField, type FormContext } from "./card-editor/form.ts";
|
||||
import { editorStyles } from "./card-editor/styles.ts";
|
||||
import { awaitingLanguage, translate, type I18nKey } from "./i18n.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
|
||||
export class NextFloorCardEditor extends LitElement {
|
||||
static properties = {
|
||||
hass: { attribute: false },
|
||||
_config: { state: true },
|
||||
_floors: { state: true },
|
||||
_rooms: { state: true },
|
||||
_templates: { state: true },
|
||||
};
|
||||
|
||||
declare hass: HomeAssistant | undefined;
|
||||
private declare _config: CardConfig;
|
||||
private declare _floors: { id: string; name: string }[];
|
||||
private declare _rooms: { id: string; name: string; floor: string }[];
|
||||
private declare _templates: string[];
|
||||
private loading = false;
|
||||
/** What the form helpers use: the values with defaults, translation, and writing an option. */
|
||||
private readonly form: FormContext;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._config = { type: "custom:nextfloor-card" };
|
||||
this._floors = [];
|
||||
this._rooms = [];
|
||||
this._templates = [];
|
||||
const editor = this;
|
||||
this.form = {
|
||||
get value() {
|
||||
return { ...(DEFAULTS as Required<CardConfig>), ...editor._config };
|
||||
},
|
||||
t: (key, vars) => translate(editor.hass, key, vars),
|
||||
set: (key, value) => editor.write(key, value),
|
||||
};
|
||||
}
|
||||
|
||||
setConfig(config: CardConfig): void {
|
||||
this._config = config;
|
||||
}
|
||||
|
||||
protected willUpdate(): void {
|
||||
if (!this.hass) return;
|
||||
// the floors of the plan, for the floor choice
|
||||
if (!this.loading && this._floors.length === 0) {
|
||||
this.loading = true;
|
||||
fetchBuilding(this.hass).then(
|
||||
(res) => {
|
||||
this._floors = res.building.floors.map((f) => ({ id: f.id, name: f.name }));
|
||||
this._templates = Object.keys(res.building.settings.card_templates ?? {});
|
||||
this._rooms = res.building.floors.flatMap((f) => f.rooms.map((r) => ({ id: r.id, name: r.name, floor: f.name })));
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Changes one option. Options back at their default disappear from the YAML. */
|
||||
private write<K extends keyof CardConfig>(key: K, value: CardConfig[K] | undefined): void {
|
||||
const next: CardConfig = { ...this._config };
|
||||
if (value === undefined || value === "" || DEFAULTS[key] === value) delete next[key];
|
||||
else next[key] = value;
|
||||
this.publish(next);
|
||||
}
|
||||
|
||||
private publish(config: CardConfig): void {
|
||||
this._config = config;
|
||||
this.dispatchEvent(new CustomEvent("config-changed", { detail: { config }, bubbles: true, composed: true }));
|
||||
}
|
||||
|
||||
/** The rooms this card shows (none ticked: the whole plan); ticked rooms make the card a card for those rooms only. */
|
||||
private roomsChoice(): TemplateResult {
|
||||
if (this._rooms.length === 0) return html``;
|
||||
const chosen = new Set(this._config.rooms ?? []);
|
||||
const toggle = (id: string, on: boolean) => {
|
||||
const next = this._rooms.map((r) => r.id).filter((rid) => (rid === id ? on : chosen.has(rid)));
|
||||
this.form.set("rooms", next.length ? next : undefined);
|
||||
};
|
||||
return html`<fieldset class="rooms">
|
||||
<legend>${this.form.t("card_rooms")}</legend>
|
||||
<small>${this.form.t("card_rooms_hint")}</small>
|
||||
${this._rooms.map((r) => html`<label class="toggle"><input type="checkbox" .checked=${chosen.has(r.id)} @change=${(e: Event) => toggle(r.id, (e.target as HTMLInputElement).checked)} /><span>${this._floors.length > 1 ? `${r.floor} · ` : ""}${r.name}</span></label>`)}
|
||||
</fieldset>`;
|
||||
}
|
||||
|
||||
/** Floor pictures are on by default without a start floor and off with one, but can be switched on. */
|
||||
private floorThumbsToggle(): TemplateResult {
|
||||
const byDefault = !this._config.floor;
|
||||
const hint: I18nKey = this._config.floor ? "card_floor_thumbs_hint_start" : "card_floor_thumbs_hint";
|
||||
return checkbox(this.form, this._config.floor_thumbs ?? byDefault, "card_floor_thumbs", hint, (checked) => {
|
||||
const next: CardConfig = { ...this._config };
|
||||
if (checked === byDefault) delete next.floor_thumbs;
|
||||
else next.floor_thumbs = checked;
|
||||
this.publish(next);
|
||||
});
|
||||
}
|
||||
|
||||
/** The switches in the card: on or off, and which of them. */
|
||||
private controlsSection(): TemplateResult {
|
||||
const f = this.form;
|
||||
const c = this._config.controls;
|
||||
const on = !!c && (c === true || c.length > 0);
|
||||
const chosen: CardControl[] = c === true ? [...CARD_CONTROLS] : Array.isArray(c) ? c : [];
|
||||
const setChosen = (next: CardControl[]) => f.set("controls", next.length === CARD_CONTROLS.length ? true : next.length > 0 ? next : undefined);
|
||||
const hideAfter = [0, 10, 30, 60, 120].map((n) => ({ value: n, text: n ? f.t("card_hide_after_s", { n }) : f.t("card_idle_off") }));
|
||||
return html`${checkbox(f, on, "card_controls", "card_controls_hint", (checked) => f.set("controls", checked ? true : undefined))}
|
||||
${checkbox(f, f.value.central, "card_central", "card_central_hint", (checked) => f.set("central", checked ? undefined : false))}
|
||||
${checkbox(f, f.value.lock_button !== false, "card_lock_button", undefined, (checked) => f.set("lock_button", checked ? undefined : false))}
|
||||
${checkbox(f, f.value.walk_button !== false, "card_walk_button", undefined, (checked) => f.set("walk_button", checked ? undefined : false))}
|
||||
${checkbox(f, f.value.time_travel !== false, "card_travel_button", undefined, (checked) => f.set("time_travel", checked ? undefined : false))}
|
||||
${flagOption(f, "marker_names", "card_marker_names", "card_marker_names_hint")} ${flagOption(f, "controls_hidden", "card_controls_hidden", "card_controls_hidden_hint")}
|
||||
${numberChoice(f, "controls_hide_after", "card_controls_hide_after", hideAfter)}
|
||||
${on
|
||||
? html`<div class="sub">
|
||||
${CARD_CONTROLS.map(
|
||||
(control) => html`<label class="chip">
|
||||
<input
|
||||
type="checkbox"
|
||||
.checked=${chosen.includes(control)}
|
||||
@change=${(e: Event) => setChosen((e.target as HTMLInputElement).checked ? CARD_CONTROLS.filter((x) => x === control || chosen.includes(x)) : chosen.filter((x) => x !== control))}
|
||||
/>
|
||||
${f.t(`card_control_${control}` as I18nKey)}
|
||||
</label>`,
|
||||
)}
|
||||
</div>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** Kiosk: return after being idle, night dimming (by the sun or a time range), the screensaver turn, and a link to another dashboard. */
|
||||
private kioskSection(): TemplateResult {
|
||||
const f = this.form;
|
||||
const { night } = f.value;
|
||||
const nightKind = night === "off" || night === "sun" ? night : "time";
|
||||
const minutes = [0, 1, 2, 5, 10].map((m) => ({ value: m * 60, text: m ? f.t("card_idle_min", { n: m }) : f.t("card_idle_off") }));
|
||||
const nightModes: [string, I18nKey][] = [["off", "card_night_off"], ["sun", "card_night_sun"], ["time", "card_night_time"]];
|
||||
return html`<h3>${f.t("card_section_kiosk")}</h3>
|
||||
<div class="grid">
|
||||
${numberChoice(f, "idle_return", "card_idle_return", minutes)}
|
||||
<label class="field"
|
||||
>${f.t("card_night")}
|
||||
<select @change=${(e: Event) => f.set("night", { off: undefined, sun: "sun", time: "22:00-06:00" }[(e.target as HTMLSelectElement).value])}>
|
||||
${nightModes.map(([value, text]) => html`<option value=${value} ?selected=${nightKind === value}>${f.t(text)}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
${nightKind === "time"
|
||||
? html`<label class="field wide"
|
||||
>${f.t("card_night_range")}
|
||||
<input type="text" pattern="\\d{1,2}:\\d{2}-\\d{1,2}:\\d{2}" placeholder="22:00-06:00" .value=${night} @change=${(e: Event) => f.set("night", (e.target as HTMLInputElement).value.trim() || undefined)} />
|
||||
</label>`
|
||||
: nothing}
|
||||
</div>
|
||||
<p class="hint">${f.t("card_idle_hint")}</p>
|
||||
${switchOption(f, "idle_orbit", "card_idle_orbit", "card_idle_orbit_hint")}
|
||||
<div class="grid">${textField(f, "dashboard", "card_dashboard", "/lovelace/home")} ${textField(f, "dashboard_label", "card_dashboard_label")}</div>
|
||||
<p class="hint">${f.t("card_dashboard_hint")}</p>`;
|
||||
}
|
||||
|
||||
/** Warnings, scenes and the live features (weather with its entity). */
|
||||
private featuresSection(): TemplateResult {
|
||||
const f = this.form;
|
||||
const weatherEntities = Object.keys(this.hass?.states ?? {})
|
||||
.filter((id) => id.startsWith("weather."))
|
||||
.sort();
|
||||
return html`<h3>${f.t("card_section_features")}</h3>
|
||||
${switchOption(f, "alerts", "card_alerts", "card_alerts_hint")} ${switchOption(f, "alert_jump", "card_alert_jump", "card_alert_jump_hint")}
|
||||
${switchOption(f, "scenes", "card_scenes", "card_scenes_hint")}
|
||||
${switchOption(f, "sensor_bar", "card_sensor_bar", "card_sensor_bar_hint")}
|
||||
${switchOption(f, "central_open", "card_central_open", "card_central_open_hint")}
|
||||
${switchOption(f, "keep_camera", "card_keep_camera", "card_keep_camera_hint")}
|
||||
${switchOption(f, "readable", "card_readable", "readable_hint")}
|
||||
${switchOption(f, "plain", "card_plain", "plain_hint")}
|
||||
${switchOption(f, "right_back", "right_back", "right_back_hint")}
|
||||
${this.roomsChoice()}
|
||||
${switchOption(f, "today", "card_today", "card_today_hint")}
|
||||
<label class="field"
|
||||
>${f.t("view_zoom")}
|
||||
<select @change=${(e: Event) => f.set("zoom", Number((e.target as HTMLSelectElement).value))}>
|
||||
${[0.8, 1, 1.25, 1.5, 1.75, 2, 2.5].map((z) => html`<option value=${z} ?selected=${(f.value.zoom ?? 1) === z}>${Math.round(z * 100)} %</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
${switchOption(f, "announcements", "card_announcements", "card_announcements_hint")}
|
||||
${f.value.announcements !== false ? html`<div class="grid">${textField(f, "screen_name", "screen_name")}</div>` : nothing}
|
||||
${switchOption(f, "weather", "card_weather", "card_weather_hint")}
|
||||
${f.value.weather !== false
|
||||
? html`<div class="grid">
|
||||
<label class="field wide"
|
||||
>${f.t("weather_entity")}
|
||||
<select @change=${(e: Event) => f.set("weather_entity", (e.target as HTMLSelectElement).value || undefined)}>
|
||||
<option value="" ?selected=${!f.value.weather_entity}>${f.t("card_weather_plan")}</option>
|
||||
${weatherEntities.map((id) => html`<option value=${id} ?selected=${id === f.value.weather_entity}>${String(this.hass?.states[id]?.attributes.friendly_name ?? id)}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field"
|
||||
>${f.t("card_weather_density")}
|
||||
<select @change=${(e: Event) => f.set("weather_density", Number((e.target as HTMLSelectElement).value))}>
|
||||
${[1, 0.75, 0.5, 0.3, 0.15].map((d) => html`<option value=${d} ?selected=${(f.value.weather_density ?? 1) === d}>${Math.round(d * 100)} %</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
<p class="hint wide">${f.t("card_weather_density_hint")}</p>
|
||||
</div>`
|
||||
: nothing}
|
||||
<p class="hint">${f.t("card_pro_hint")}</p>`;
|
||||
}
|
||||
|
||||
/** The card's own furniture colours per role, on top of the house-wide ones (#82). */
|
||||
private furnitureColors(f: FormContext): TemplateResult {
|
||||
const own = this._config.furniture_colors ?? {};
|
||||
const put = (role: FurnitureRole, v: string | null) => {
|
||||
const next: FurnitureColors = { ...own, [role]: v };
|
||||
if (!v) delete next[role];
|
||||
f.set("furniture_colors", Object.keys(next).length ? next : undefined);
|
||||
};
|
||||
return html`<details class="field">
|
||||
<summary>${f.t("furn_colors_card")}${Object.keys(own).length ? ` (${Object.keys(own).length})` : ""}</summary>
|
||||
${FURNITURE_ROLES.map(
|
||||
(role) => html`<label class="field"
|
||||
>${f.t(`furn_color_${role}`)}
|
||||
<input type="color" .value=${own[role] ?? STOCK_ROLE_HEX[role]} @input=${(e: Event) => put(role, (e.target as HTMLInputElement).value)} />
|
||||
${own[role] ? html`<button type="button" class="link" @click=${() => put(role, null)}>${f.t("furn_color_house")}</button>` : nothing}
|
||||
</label>`,
|
||||
)}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** The view: start floor, size, theme, accent colour, walls, quality and floor stacking. */
|
||||
private viewSection(): TemplateResult {
|
||||
const f = this.form;
|
||||
const v = f.value;
|
||||
return html`<h3>${f.t("card_section_view")}</h3>
|
||||
<div class="grid">
|
||||
${this._templates.length
|
||||
? html`<label class="field wide"
|
||||
>${f.t("card_template")}
|
||||
<select @change=${(e: Event) => f.set("template", (e.target as HTMLSelectElement).value || undefined)}>
|
||||
<option value="" ?selected=${!v.template}>${f.t("card_template_none")}</option>
|
||||
${this._templates.map((name) => html`<option value=${name} ?selected=${name === v.template}>${name}</option>`)}
|
||||
${v.template && !this._templates.includes(v.template) ? html`<option value=${v.template} selected>${v.template}</option>` : nothing}
|
||||
</select>
|
||||
</label>`
|
||||
: nothing}
|
||||
<label class="field wide"
|
||||
>${f.t("card_floor")}
|
||||
<select @change=${(e: Event) => f.set("floor", (e.target as HTMLSelectElement).value || undefined)}>
|
||||
<option value="" ?selected=${!v.floor}>${f.t("card_floor_house")}</option>
|
||||
${this._floors.map((floor) => html`<option value=${floor.id} ?selected=${floor.id === v.floor}>${floor.name}</option>`)}
|
||||
${v.floor && !this._floors.some((floor) => floor.id === v.floor) ? html`<option value=${v.floor} selected>${v.floor}</option>` : nothing}
|
||||
</select>
|
||||
</label>
|
||||
<label class="field"
|
||||
>${f.t("card_size")}
|
||||
<select @change=${(e: Event) => f.set("fill", (e.target as HTMLSelectElement).value === "fill")}>
|
||||
<option value="fixed" ?selected=${!v.fill}>${f.t("card_size_fixed")}</option>
|
||||
<option value="fill" ?selected=${v.fill}>${f.t("card_size_fill")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field" ?hidden=${v.fill}
|
||||
>${f.t("card_height")}
|
||||
<input
|
||||
type="number"
|
||||
min="150"
|
||||
max="2000"
|
||||
step="10"
|
||||
.value=${String(v.height)}
|
||||
@change=${(e: Event) => {
|
||||
const height = Math.round(Number((e.target as HTMLInputElement).value));
|
||||
if (height > 100) f.set("height", height);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
${choice(f, "theme", "theme", [["auto", "theme_auto"], ["neon", "theme_neon"], ["blueprint", "theme_blueprint"], ["day", "theme_day"]], v.theme)}
|
||||
${choice(f, "clock", "clock", [["none", "clock_none"], ["top_left", "clock_top_left"], ["top_right", "clock_top_right"], ["bottom_left", "clock_bottom_left"], ["bottom_right", "clock_bottom_right"]], v.clock ?? "none")}
|
||||
<label class="field"
|
||||
>${f.t("accent")}
|
||||
<input type="color" .value=${this._config.accent ?? "#37e0ff"} @input=${(e: Event) => f.set("accent", (e.target as HTMLInputElement).value)} />
|
||||
${this._config.accent ? html`<button type="button" class="link" @click=${() => f.set("accent", undefined)}>${f.t("accent_reset")}</button>` : nothing}
|
||||
</label>
|
||||
${this.furnitureColors(f)}
|
||||
${choice(f, "walls", "card_walls", [["auto", "walls_auto"], ["cut", "walls_cut"], ["slope", "walls_slope"]], v.walls)}
|
||||
${switchOption(f, "solid_walls", "card_solid_walls")}
|
||||
<label class="field" title=${f.t("glass_walls_hint")}
|
||||
>${f.t("glass_walls")} (${this._config.glass_walls ?? 20} %)
|
||||
<input type="range" min="0" max="100" step="5" .value=${String(this._config.glass_walls ?? 20)} @change=${(e: Event) => {
|
||||
const value = Number((e.target as HTMLInputElement).value);
|
||||
f.set("glass_walls", value === 20 ? undefined : value);
|
||||
}} />
|
||||
</label>
|
||||
${choice(f, "quality", "quality", [["auto", "quality_auto"], ["low", "quality_low"], ["high", "quality_high"]], v.quality)}
|
||||
${choice(f, "floor_stack", "card_floor_stack", [["dim", "floor_stack_dim"], ["stacked", "floor_stack_stacked"], ["single", "floor_stack_single"]], v.floor_stack)}
|
||||
</div>
|
||||
${v.fill ? html`<p class="hint">${f.t("card_fill_hint")}</p>` : nothing}
|
||||
<p class="hint">${f.t("card_quality_hint")}</p>`;
|
||||
}
|
||||
|
||||
/** Which kinds of markers show outside the opened room (off: the same as in the room). */
|
||||
private markersOutside(): TemplateResult {
|
||||
const f = this.form;
|
||||
const chosen = f.value.markers_outside;
|
||||
// switched on, every kind but the lamps to start with (they are their own target in 3D)
|
||||
return html`${checkbox(f, !!chosen, "card_markers_outside", "card_markers_outside_hint", (on) => f.set("markers_outside", on ? MARKER_KINDS.filter((k) => k !== "light") : undefined))}
|
||||
${chosen
|
||||
? html`<div class="sub">
|
||||
${MARKER_KINDS.map(
|
||||
(kind: MarkerKind) => html`<label class="chip">
|
||||
<input
|
||||
type="checkbox"
|
||||
.checked=${chosen.includes(kind)}
|
||||
@change=${(e: Event) => f.set("markers_outside", (e.target as HTMLInputElement).checked ? MARKER_KINDS.filter((k) => k === kind || chosen.includes(k)) : chosen.filter((k) => k !== kind))}
|
||||
/>
|
||||
${f.t(`marker_kind_${kind}` as I18nKey)}
|
||||
</label>`,
|
||||
)}
|
||||
</div>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** What the card shows: markers, heat map, flows, holograms, and the plain switches. */
|
||||
private showSection(): TemplateResult {
|
||||
const f = this.form;
|
||||
const v = f.value;
|
||||
return html`<h3>${f.t("card_section_show")}</h3>
|
||||
<div class="grid">
|
||||
${choice(f, "markers", "markers", [["none", "markers_none"], ["important", "markers_important"], ["all", "markers_all"]], v.markers)}
|
||||
${choice(f, "heatmap", "heatmap", [["none", "heat_off"], ["temperature", "heat_temperature"], ["humidity", "heat_humidity"], ["co2", "heat_co2"], ["mould", "heat_mould"], ["values", "heat_values"], ["wifi", "heat_wifi"]], v.heatmap)}
|
||||
${followOrForce(f, "flows", "flows", v.flows)} ${followOrForce(f, "holograms", "holos", v.holograms)}
|
||||
</div>
|
||||
${switchOption(f, "tap_in_room", "card_tap_in_room", "card_tap_in_room_hint")} ${choice(f, "room_double_tap", "room_double_tap", [["auto", "card_room_double_tap_auto"], ["area", "room_double_tap_area"], ["plan", "room_double_tap_plan"], ["off", "room_double_tap_off"]], v.room_double_tap)} ${this.markersOutside()} ${this.controlsSection()} ${this.floorThumbsToggle()} ${switchOption(f, "room_names", "card_room_names")} ${switchOption(f, "energy", "card_energy")}
|
||||
${switchOption(f, "room_buttons", "card_room_buttons", "card_room_buttons_hint")} ${switchOption(f, "room_panel", "card_room_panel", "card_room_panel_hint")} ${switchOption(f, "fullscreen_button", "card_fullscreen_button", "card_fullscreen_button_hint")}
|
||||
${switchOption(f, "explode", "card_explode")} ${switchOption(f, "roof_fade", "card_roof_fade", "card_roof_fade_hint")} ${switchOption(f, "stats", "card_stats", "card_stats_hint")}`;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
// a language beyond German and English: its texts are fetched first, and then everything renders
|
||||
if (this.hass && awaitingLanguage(this.hass, this)) return nothing;
|
||||
return html`${this.viewSection()} ${this.showSection()} ${this.featuresSection()} ${this.kioskSection()}`;
|
||||
}
|
||||
|
||||
static styles = editorStyles;
|
||||
}
|
||||
|
||||
if (!customElements.get("nextfloor-card-editor")) customElements.define("nextfloor-card-editor", NextFloorCardEditor);
|
||||
@@ -0,0 +1,120 @@
|
||||
// Form helpers of the card editor: what an option is, and how a checkbox, a choice and a text field are drawn and written.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import type { CardConfig } from "../card-config.ts";
|
||||
import type { I18nKey } from "../i18n.ts";
|
||||
|
||||
/** Options at these values are left out of the YAML. */
|
||||
export const DEFAULTS: Partial<CardConfig> = {
|
||||
height: 420,
|
||||
walls: "auto",
|
||||
solid_walls: false,
|
||||
explode: true,
|
||||
roof_fade: true,
|
||||
quality: "auto",
|
||||
stats: false,
|
||||
markers: "important",
|
||||
heatmap: "none",
|
||||
theme: "neon",
|
||||
energy: true,
|
||||
room_panel: true,
|
||||
room_buttons: false,
|
||||
fill: false,
|
||||
controls: false,
|
||||
fullscreen_button: false,
|
||||
room_names: true,
|
||||
floor_stack: "dim",
|
||||
alerts: true,
|
||||
alert_jump: false,
|
||||
scenes: true,
|
||||
announcements: true,
|
||||
sensor_bar: true,
|
||||
weather: true,
|
||||
weather_density: 1,
|
||||
idle_return: 0,
|
||||
controls_hidden: false,
|
||||
controls_hide_after: 0,
|
||||
marker_names: false,
|
||||
tap_in_room: false,
|
||||
room_double_tap: "auto",
|
||||
central: true,
|
||||
central_open: false,
|
||||
keep_camera: false,
|
||||
readable: false,
|
||||
plain: false,
|
||||
right_back: false,
|
||||
today: true,
|
||||
night: "off",
|
||||
idle_orbit: false,
|
||||
};
|
||||
|
||||
/** The yes/no options that get a plain checkbox. */
|
||||
export type SwitchOption = "solid_walls" | "explode" | "roof_fade" | "energy" | "room_panel" | "room_buttons" | "stats" | "fullscreen_button" | "room_names" | "alerts" | "alert_jump" | "scenes" | "announcements" | "sensor_bar" | "idle_orbit" | "weather" | "tap_in_room" | "central_open" | "keep_camera" | "today" | "readable" | "plain" | "right_back";
|
||||
|
||||
export type Choice = [value: string, label: I18nKey];
|
||||
|
||||
/** What the form helpers need from the editor. */
|
||||
export interface FormContext {
|
||||
/** The config with defaults filled in. */
|
||||
value: Required<Omit<CardConfig, "floor" | "flows" | "holograms" | "markers_outside">> & Pick<CardConfig, "floor" | "flows" | "holograms" | "markers_outside">;
|
||||
t(key: I18nKey, vars?: Record<string, string | number>): string;
|
||||
set<K extends keyof CardConfig>(key: K, value: CardConfig[K] | undefined): void;
|
||||
}
|
||||
|
||||
const inputValue = (e: Event) => (e.target as HTMLInputElement).value;
|
||||
const selectValue = (e: Event) => (e.target as HTMLSelectElement).value;
|
||||
const isChecked = (e: Event) => (e.target as HTMLInputElement).checked;
|
||||
|
||||
/** A checkbox with a label and an optional hint line. `onChange` decides what is written. */
|
||||
export function checkbox(form: FormContext, checked: boolean, label: I18nKey, hint: I18nKey | undefined, onChange: (on: boolean) => void): TemplateResult {
|
||||
return html`<label class="toggle">
|
||||
<input type="checkbox" .checked=${checked} @change=${(e: Event) => onChange(isChecked(e))} />
|
||||
<span>${form.t(label)}${hint ? html`<small>${form.t(hint)}</small>` : nothing}</span>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A checkbox for a yes/no option. */
|
||||
export const switchOption = (form: FormContext, key: SwitchOption, label: I18nKey, hint?: I18nKey) => checkbox(form, form.value[key], label, hint, (on) => form.set(key, on));
|
||||
|
||||
/** A checkbox that writes `true` when ticked and removes the option when not (for options that are off by default). */
|
||||
export const flagOption = (form: FormContext, key: "marker_names" | "controls_hidden", label: I18nKey, hint: I18nKey) => checkbox(form, form.value[key], label, hint, (on) => form.set(key, on || undefined));
|
||||
|
||||
/** A drop-down choice stored as the option's value. */
|
||||
export function choice<K extends keyof CardConfig>(form: FormContext, key: K, label: I18nKey, choices: Choice[], current: string): TemplateResult {
|
||||
return html`<label class="field"
|
||||
>${form.t(label)}
|
||||
<select @change=${(e: Event) => form.set(key, selectValue(e) as CardConfig[K])}>
|
||||
${choices.map(([value, text]) => html`<option value=${value} ?selected=${value === current}>${form.t(text)}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A drop-down of numbers whose zero means off (and is left out of the config). */
|
||||
export function numberChoice(form: FormContext, key: "idle_return" | "controls_hide_after", label: I18nKey, options: { value: number; text: string }[]): TemplateResult {
|
||||
return html`<label class="field"
|
||||
>${form.t(label)}
|
||||
<select @change=${(e: Event) => form.set(key, Number(selectValue(e)) || undefined)}>
|
||||
${options.map((o) => html`<option value=${o.value} ?selected=${form.value[key] === o.value}>${o.text}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A text field; an empty text removes the option. */
|
||||
export function textField(form: FormContext, key: "dashboard" | "dashboard_label" | "screen_name", label: I18nKey, placeholder = ""): TemplateResult {
|
||||
return html`<label class="field wide"
|
||||
>${form.t(label)}
|
||||
<input type="text" placeholder=${placeholder} .value=${form.value[key] ?? ""} @change=${(e: Event) => form.set(key, inputValue(e).trim() || undefined)} />
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A three-way choice for an option that follows the plan's own setting unless forced on or off. */
|
||||
export function followOrForce(form: FormContext, key: "flows" | "holograms", label: I18nKey, current: boolean | undefined): TemplateResult {
|
||||
const state = current === undefined ? "switch" : current ? "on" : "off";
|
||||
const options: [string, I18nKey][] = [["switch", "card_flows_switch"], ["on", "card_flows_on"], ["off", "card_flows_off"]];
|
||||
return html`<label class="field wide"
|
||||
>${form.t(label)}
|
||||
<select @change=${(e: Event) => form.set(key, selectValue(e) === "switch" ? undefined : selectValue(e) === "on")}>
|
||||
${options.map(([value, text]) => html`<option value=${value} ?selected=${state === value}>${form.t(text)}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { css } from "lit";
|
||||
|
||||
/** The look of the editor: it follows Home Assistant's colours, as the dialog is light or dark with the user's theme. */
|
||||
export const editorStyles = css`
|
||||
:host {
|
||||
display: block;
|
||||
color: var(--primary-text-color);
|
||||
}
|
||||
h3 {
|
||||
margin: 18px 0 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
h3:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px 12px;
|
||||
}
|
||||
[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
select,
|
||||
input[type="number"],
|
||||
input[type="text"] {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 40px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--divider-color, rgba(127, 127, 127, 0.4));
|
||||
border-radius: 8px;
|
||||
background: var(--card-background-color, transparent);
|
||||
color: var(--primary-text-color);
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
}
|
||||
.toggle {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 8px 0;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.toggle input {
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin: 1px 0 0;
|
||||
accent-color: var(--primary-color);
|
||||
}
|
||||
.sub {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 14px;
|
||||
margin: -2px 0 6px 28px;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chip input {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: 0;
|
||||
accent-color: var(--primary-color);
|
||||
}
|
||||
.toggle small,
|
||||
.hint {
|
||||
display: block;
|
||||
margin: 2px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
@media (max-width: 450px) {
|
||||
.grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { CardConfig } from "./card-config.ts";
|
||||
import { templateKey, withTemplate } from "./card-template.ts";
|
||||
|
||||
test("a template lies under the card's own options, which win; type and template stay the card's", () => {
|
||||
const templates = { kitchen: { type: "custom:other", height: 520, readable: true, markers: "all" as const, template: "loop" } };
|
||||
const own: CardConfig = { type: "custom:nextfloor-card", template: "kitchen", height: 300 };
|
||||
const merged = withTemplate(own, templates);
|
||||
assert.deepEqual(merged, { type: "custom:nextfloor-card", template: "kitchen", height: 300, readable: true, markers: "all" });
|
||||
});
|
||||
|
||||
test("no template, an unknown one or no templates at all leave the config as it is", () => {
|
||||
const own: CardConfig = { type: "custom:nextfloor-card", height: 300 };
|
||||
assert.equal(withTemplate(own, { a: { height: 1 } }), own);
|
||||
assert.equal(withTemplate({ ...own, template: "nope" }, { a: { height: 1 } }).height, 300);
|
||||
assert.equal(withTemplate({ ...own, template: "a" }, undefined).height, 300);
|
||||
});
|
||||
|
||||
test("a template's name becomes a safe key", () => {
|
||||
assert.equal(templateKey(" Küche Tablet 10″ "), "kueche_tablet_10");
|
||||
assert.equal(templateKey("wall-tablet_1"), "wall-tablet_1");
|
||||
assert.equal(templateKey("!!!"), "");
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// Card templates: a card set up once in the editor (Settings → Card templates) and chosen on a dashboard card with
|
||||
// `template: kitchen_tablet`. The card's own options win over the template's.
|
||||
|
||||
import type { CardConfig } from "./card-config.ts";
|
||||
|
||||
export type CardTemplates = Record<string, Partial<CardConfig>>;
|
||||
|
||||
/** A template name made of letters, digits, `_` and `-`. */
|
||||
export const templateKey = (name: string): string =>
|
||||
name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, "ae")
|
||||
.replace(/ö/g, "oe")
|
||||
.replace(/ü/g, "ue")
|
||||
.replace(/ß/g, "ss")
|
||||
.replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
|
||||
|
||||
/** The card's config with its template (if it names one that exists) underneath; `type` and `template` stay the card's own. */
|
||||
export function withTemplate(own: CardConfig, templates: CardTemplates | null | undefined): CardConfig {
|
||||
const name = own.template;
|
||||
const base = name ? templates?.[name] : undefined;
|
||||
if (!base) return own;
|
||||
const { type: _type, template: _template, ...rest } = base as CardConfig;
|
||||
const merged: CardConfig = { ...rest, ...own };
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
// The Lovelace card. The integration loads it automatically; no resource has to be added.
|
||||
|
||||
import { html, LitElement, nothing, type PropertyValues, type TemplateResult } from "lit";
|
||||
import { BuildingController } from "./building-controller.ts";
|
||||
import type { CardConfig, CardControl } from "./card-config.ts";
|
||||
import { KioskTimers } from "./card/kiosk.ts";
|
||||
import { roomButtons } from "./card/room-buttons.ts";
|
||||
import { cardStyles } from "./card/styles.ts";
|
||||
import "./components/room-panel.ts";
|
||||
import "./components/view3d.ts";
|
||||
import { confirmEntities, outsideEntities } from "./devices.ts";
|
||||
import { awaitingLanguage, translate } from "./i18n.ts";
|
||||
import { nightActive } from "./kiosk.ts";
|
||||
import { screenMuted, screenName } from "./panel/prefs.ts";
|
||||
import { loadCardEditor } from "./load-card-editor.ts";
|
||||
import { withTemplate, type CardTemplates } from "./card-template.ts";
|
||||
import type { Building } from "./model.ts";
|
||||
import { roomsOnly } from "./rooms-only.ts";
|
||||
import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import type { WallMode } from "./viewer/viewer3d.ts";
|
||||
import { lookNow } from "./themes.ts";
|
||||
|
||||
/** The room id the card uses for Outside (no room has it: room ids are made by uid()). */
|
||||
const OUTSIDE = "nf-outside";
|
||||
|
||||
type HeatMode = NonNullable<CardConfig["heatmap"]>;
|
||||
type Key = Parameters<typeof translate>[1];
|
||||
|
||||
interface Stage {
|
||||
floorId: string | null;
|
||||
walls: WallMode;
|
||||
heat: HeatMode;
|
||||
explode: boolean;
|
||||
showBar: boolean;
|
||||
canGoBack: boolean;
|
||||
}
|
||||
|
||||
export class NextFloorCard extends LitElement {
|
||||
static properties = {
|
||||
hass: { attribute: false },
|
||||
_config: { state: true },
|
||||
_roomId: { state: true },
|
||||
_floorId: { state: true },
|
||||
_walls: { state: true },
|
||||
_heat: { state: true },
|
||||
_explode: { state: true },
|
||||
_fullscreen: { state: true },
|
||||
_clean: { state: true },
|
||||
_night: { state: true },
|
||||
_orbit: { state: true },
|
||||
};
|
||||
|
||||
declare hass: HomeAssistant;
|
||||
private declare _config: CardConfig;
|
||||
/** The options as written on the dashboard card; `_config` is these with the card template underneath. */
|
||||
private _own: CardConfig | null = null;
|
||||
private templatesSeen: unknown;
|
||||
private declare _roomId: string | null;
|
||||
/** The configured start room has been opened once the building arrived. */
|
||||
private roomApplied = false;
|
||||
/** The floor chosen in the card: null is the house, undefined means none was chosen so the configured floor applies. */
|
||||
private declare _floorId: string | null | undefined;
|
||||
/** Choices made with the card's own switches; null means as configured. */
|
||||
private declare _walls: WallMode | null;
|
||||
private declare _heat: HeatMode | null;
|
||||
private declare _explode: boolean | null;
|
||||
private declare _fullscreen: boolean;
|
||||
/** The clean view: only the stage (option controls_hidden, the eye button, or the hide-after timer). */
|
||||
private declare _clean: boolean;
|
||||
/** Kiosk: the night dimming is on, and the screensaver turn runs (after an idle return). */
|
||||
private declare _night: boolean;
|
||||
private declare _orbit: boolean;
|
||||
|
||||
private readonly data = new BuildingController(this);
|
||||
private readonly kiosk = new KioskTimers({
|
||||
config: () => this._config,
|
||||
hass: () => this.hass,
|
||||
setClean: (clean) => (this._clean = clean),
|
||||
isClean: () => this._clean,
|
||||
setOrbit: (on) => (this._orbit = on),
|
||||
isOrbit: () => this._orbit,
|
||||
setNight: (night) => (this._night = night),
|
||||
goHome: () => this.returnHome(),
|
||||
});
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._roomId = null;
|
||||
this._floorId = undefined;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
this._fullscreen = false;
|
||||
this._clean = false;
|
||||
this._night = false;
|
||||
this._orbit = false;
|
||||
}
|
||||
|
||||
private view3d() {
|
||||
return this.shadowRoot?.querySelector("nf-view3d") as (HTMLElement & { resetView(): void; lookThrough(entityId: string): void }) | null;
|
||||
}
|
||||
|
||||
/** Back to the start view: room closed, start floor, camera reset. The screensaver may start. */
|
||||
private returnHome(): void {
|
||||
this._roomId = this._config?.room ?? null;
|
||||
this._floorId = undefined;
|
||||
this.view3d()?.resetView();
|
||||
if (this._config?.idle_orbit) this._orbit = true;
|
||||
}
|
||||
|
||||
/** Opens another dashboard or view the way Home Assistant's own links do, without a page reload. */
|
||||
private openDashboard(path: string): void {
|
||||
history.pushState(null, "", path);
|
||||
window.dispatchEvent(new CustomEvent("location-changed", { bubbles: true, composed: true, detail: { replace: false } }));
|
||||
}
|
||||
|
||||
private readonly onFullscreen = () => (this._fullscreen = !!document.fullscreenElement && this.shadowRoot?.contains(document.fullscreenElement) === true);
|
||||
|
||||
connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
document.addEventListener("fullscreenchange", this.onFullscreen);
|
||||
this.kiosk.start();
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
document.removeEventListener("fullscreenchange", this.onFullscreen);
|
||||
this.kiosk.stop();
|
||||
}
|
||||
|
||||
private toggleFullscreen(): void {
|
||||
if (document.fullscreenElement) void document.exitFullscreen();
|
||||
else void this.shadowRoot?.querySelector("ha-card")?.requestFullscreen?.();
|
||||
}
|
||||
|
||||
/** The visual editor in the dashboard, so no YAML is needed. */
|
||||
static async getConfigElement(): Promise<HTMLElement> {
|
||||
await loadCardEditor();
|
||||
return document.createElement("nextfloor-card-editor");
|
||||
}
|
||||
|
||||
static getStubConfig(): CardConfig {
|
||||
return { type: "custom:nextfloor-card" };
|
||||
}
|
||||
|
||||
setConfig(config: CardConfig): void {
|
||||
if (config.height !== undefined && !(config.height > 100)) throw new Error("height must be a number of pixels above 100");
|
||||
this._own = config;
|
||||
this._config = withTemplate(config, this.data.building?.settings.card_templates as CardTemplates | undefined);
|
||||
this._floorId = undefined;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
this._orbit = false;
|
||||
this._night = nightActive(config.night, this.hass);
|
||||
this._clean = config.controls_hidden === true;
|
||||
this.kiosk.armClean();
|
||||
this.kiosk.armIdle();
|
||||
}
|
||||
|
||||
getCardSize(): number {
|
||||
return Math.ceil((this._config?.height ?? 420) / 50);
|
||||
}
|
||||
|
||||
getGridOptions() {
|
||||
return { columns: "full", rows: this._config?.fill ? 12 : Math.ceil((this._config?.height ?? 420) / 56), min_rows: 4 };
|
||||
}
|
||||
|
||||
protected willUpdate(changed: PropertyValues): void {
|
||||
// a card template edited in the editor reaches the card as soon as the plan reloads
|
||||
const templates = this.data.building?.settings.card_templates;
|
||||
if (this._own?.template && templates !== this.templatesSeen) {
|
||||
this.templatesSeen = templates;
|
||||
this._config = withTemplate(this._own, templates as CardTemplates | undefined);
|
||||
}
|
||||
this.toggleAttribute("readable", this._config?.readable === true);
|
||||
if (changed.has("hass")) this.style.colorScheme = colorSchemeOf(this.hass);
|
||||
if (!changed.has("hass") || !this.hass) return;
|
||||
this.data.setHass(this.hass);
|
||||
const night = nightActive(this._config?.night, this.hass);
|
||||
if (night !== this._night) this._night = night;
|
||||
}
|
||||
|
||||
/** Floors can be switched: no fixed floor, or floor pictures to switch with. */
|
||||
private get canSwitch(): boolean {
|
||||
return !this._config?.floor || this.thumbs;
|
||||
}
|
||||
|
||||
private get thumbs(): boolean {
|
||||
return this._config?.floor_thumbs ?? !this._config?.floor;
|
||||
}
|
||||
|
||||
/** One level up: room, then floor, then the house. */
|
||||
private back(): void {
|
||||
if (this._roomId) this._roomId = null;
|
||||
else if (this.canSwitch) this._floorId = null;
|
||||
}
|
||||
|
||||
private roomsMemo: { source: Building | null; ids: string; result: Building | null } | null = null;
|
||||
|
||||
/** The plan this card shows: all of it, or only the rooms of `rooms:` (kept, so the same object comes back while nothing changes). */
|
||||
private plan(): Building | null {
|
||||
const source = this.data.building ?? null;
|
||||
const ids = this._config?.rooms;
|
||||
if (!source || !ids?.length) return source;
|
||||
const key = ids.join(",");
|
||||
if (!this.roomsMemo || this.roomsMemo.source !== source || this.roomsMemo.ids !== key) this.roomsMemo = { source, ids: key, result: roomsOnly(source, ids) };
|
||||
return this.roomsMemo.result;
|
||||
}
|
||||
|
||||
private readonly t = (key: Key) => translate(this.hass, key);
|
||||
|
||||
/** Which floor shows, the switches' current values, and whether the bar of switches and its back button are there. */
|
||||
private stage(): Stage {
|
||||
const b = this.plan();
|
||||
const c = this._config;
|
||||
// the configured floor is where the card starts; with floor pictures the user can switch
|
||||
const chosen = this._floorId === undefined ? (c?.floor ?? null) : this._floorId;
|
||||
const floorId = b && b.floors.length === 1 ? b.floors[0].id : b?.floors.some((f) => f.id === chosen) ? chosen : null;
|
||||
// the floor pictures have a house button of their own; a room with its panel has a close button
|
||||
const panelOpen = !!this._roomId && c?.room_panel !== false;
|
||||
const canGoBack = (!!this._roomId && c?.room_panel === false) || (!this.thumbs && this.canSwitch && !this._roomId && !!floorId && (b?.floors.length ?? 0) > 1);
|
||||
return {
|
||||
floorId,
|
||||
walls: this._walls ?? c?.walls ?? "auto",
|
||||
heat: this._heat ?? c?.heatmap ?? "none",
|
||||
explode: this._explode ?? c?.explode ?? true,
|
||||
canGoBack,
|
||||
// the bar of switches at the bottom: the back button belongs to it
|
||||
showBar: !!b && !this._clean && (canGoBack || (!!c?.controls && !panelOpen)),
|
||||
};
|
||||
}
|
||||
|
||||
private shows(control: CardControl): boolean {
|
||||
const c = this._config?.controls;
|
||||
return c === true || (Array.isArray(c) && c.includes(control));
|
||||
}
|
||||
|
||||
/** The bar of switches: back, wall mode, floor stacking, heat map. */
|
||||
private renderBar(s: Stage): TemplateResult {
|
||||
const b = this.plan()!;
|
||||
const t = this.t;
|
||||
const heats = (["temperature", "humidity", "co2"] as const).filter((m) => this.shows(m));
|
||||
const group = (label: string | undefined, buttons: [boolean, () => void, string][]) =>
|
||||
html`<div class="nf-seg" role=${label ? "group" : nothing} aria-label=${label ?? nothing}>${buttons.map(([on, act, text]) => html`<button aria-pressed=${on} @click=${act}>${text}</button>`)}</div>`;
|
||||
return html`<div class="nf-card-controls">
|
||||
${s.canGoBack ? html`<button class="nf-chip" @click=${() => this.back()}>${t("back")}</button>` : nothing}
|
||||
${this.shows("walls") ? group(undefined, [[s.walls === "auto", () => (this._walls = "auto"), t("walls_auto")], [s.walls === "cut", () => (this._walls = "cut"), t("walls_cut")], [s.walls === "slope", () => (this._walls = "slope"), t("walls_slope")]]) : nothing}
|
||||
${this.shows("floors") && b.floors.length > 1 && !s.floorId
|
||||
? group(undefined, [[s.explode, () => (this._explode = true), t("floors_apart")], [!s.explode, () => (this._explode = false), t("floors_stacked")]])
|
||||
: nothing}
|
||||
${heats.length > 0
|
||||
? group(
|
||||
t("heatmap"),
|
||||
(["none", ...heats] as HeatMode[]).map((m): [boolean, () => void, string] => [s.heat === m, () => (this._heat = m), t(m === "none" ? "heat_off" : (`heat_short_${m}` as Key))]),
|
||||
)
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** One chip per room above the model; a tap opens the room (its floor first, when another floor shows), a second tap closes it. */
|
||||
private renderRoomButtons(s: Stage): TemplateResult | typeof nothing {
|
||||
const b = this.plan();
|
||||
if (!this._config?.room_buttons || !b || this._clean) return nothing;
|
||||
const groups = roomButtons(b, s.floorId);
|
||||
if (!groups.length) return nothing;
|
||||
const several = groups.length > 1;
|
||||
const open = (floorId: string, roomId: string) => {
|
||||
if (this.canSwitch && floorId !== s.floorId) this._floorId = floorId;
|
||||
this._roomId = roomId === this._roomId ? null : roomId;
|
||||
};
|
||||
// Outside: the house view with the garden's and the roof's devices in the panel
|
||||
const outside = outsideEntities(this.hass, b.floors).length > 0;
|
||||
const openOutside = () => {
|
||||
if (this.canSwitch) this._floorId = null;
|
||||
this._roomId = this._roomId === OUTSIDE ? null : OUTSIDE;
|
||||
};
|
||||
return html`<div class="nf-card-rooms ${this._roomId && this._config?.room_panel !== false ? "nf-card-rooms-beside" : ""}" role="group" aria-label=${this.t("card_room_buttons")}>
|
||||
${groups.map(
|
||||
(g) => html`${several ? html`<span class="nf-card-rooms-floor">${g.floorName}</span>` : nothing}${g.rooms.map(
|
||||
(r) => html`<button class="nf-chip" aria-pressed=${r.id === this._roomId} @click=${() => open(g.floorId, r.id)}>${r.name}</button>`,
|
||||
)}`,
|
||||
)}
|
||||
${outside ? html`<button class="nf-chip" aria-pressed=${this._roomId === OUTSIDE} title=${this.t("outside_area_hint")} @click=${openOutside}>🌳 ${this.t("outside_area")}</button>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The corner buttons: full screen, and a link to another dashboard. */
|
||||
private renderCorners(): TemplateResult {
|
||||
const c = this._config;
|
||||
const t = this.t;
|
||||
const hidden = this._clean || (!!this._roomId && c?.room_panel !== false);
|
||||
return html`${c?.fullscreen_button && !hidden
|
||||
? html`<button class="nf-card-full" title=${t(this._fullscreen ? "fullscreen_exit" : "fullscreen")} aria-label=${t(this._fullscreen ? "fullscreen_exit" : "fullscreen")} @click=${() => this.toggleFullscreen()}>
|
||||
${this._fullscreen ? "✕" : "⛶"}
|
||||
</button>`
|
||||
: nothing}
|
||||
${c?.dashboard && !hidden
|
||||
? html`<button class="nf-card-full nf-card-dash ${c.fullscreen_button ? "nf-card-dash-2" : ""}" title=${c.dashboard_label || c.dashboard} aria-label=${c.dashboard_label || c.dashboard} @click=${() => this.openDashboard(c.dashboard!)}>
|
||||
${c.dashboard_label ? html`<span>${c.dashboard_label}</span>` : "⌂"}
|
||||
</button>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
private renderStage(s: Stage): TemplateResult {
|
||||
const b = this.plan()!;
|
||||
const c = this._config;
|
||||
const clean = () => {
|
||||
this._clean = !this._clean;
|
||||
if (this._clean) this.kiosk.stopClean();
|
||||
else this.kiosk.armClean();
|
||||
};
|
||||
const eye = c?.controls_hidden !== undefined || (c?.controls_hide_after ?? 0) > 0;
|
||||
return html`<nf-view3d
|
||||
.hass=${this.hass}
|
||||
.building=${b}
|
||||
.packs=${this.data.packs}
|
||||
.floorId=${s.floorId}
|
||||
.roomId=${this._roomId === OUTSIDE ? null : this._roomId}
|
||||
.outsideOpen=${this._roomId === OUTSIDE}
|
||||
.wallMode=${s.walls}
|
||||
.solidWalls=${c?.solid_walls === true}
|
||||
.explode=${s.explode}
|
||||
.keepRoof=${c?.roof_fade === false}
|
||||
.quality=${c?.quality ?? "auto"}
|
||||
?showStats=${c?.stats ?? false}
|
||||
.markerMode=${c?.markers ?? "important"}
|
||||
.markerNames=${c?.marker_names === true}
|
||||
.markersOutside=${c?.markers_outside ?? null}
|
||||
?tapInRoom=${c?.tap_in_room === true}
|
||||
.roomDoubleTap=${c?.room_double_tap ?? "auto"}
|
||||
.central=${c?.central !== false}
|
||||
.centralOpen=${c?.central_open === true}
|
||||
.keepCamera=${c?.keep_camera === true}
|
||||
.readable=${c?.readable === true}
|
||||
.plain=${c?.plain === true}
|
||||
.templateName=${this._own?.template ?? null}
|
||||
.rightBack=${c?.right_back === true}
|
||||
.today=${c?.today !== false}
|
||||
.zoom=${typeof c?.zoom === "number" ? c.zoom : 1}
|
||||
.buttons=${c?.buttons?.map((button, i) => ({ id: `card_${i}`, ...button })) ?? null}
|
||||
.heatMode=${s.heat}
|
||||
.theme=${lookNow(c?.theme, this.hass?.states["sun.sun"]?.state)}
|
||||
.clock=${c?.clock && c.clock !== "none" ? c.clock : null}
|
||||
.lockButton=${c?.lock_button !== false}
|
||||
.walkButton=${c?.walk_button !== false}
|
||||
.travelButton=${c?.time_travel !== false}
|
||||
.accent=${c?.accent ?? null}
|
||||
.furnitureColors=${c?.furniture_colors ?? null}
|
||||
.showEnergy=${c?.energy ?? true}
|
||||
.flows=${c?.flows ?? null}
|
||||
.holograms=${c?.holograms ?? null}
|
||||
.floorThumbs=${this.thumbs}
|
||||
.roomLabels=${c?.room_names !== false}
|
||||
.floorStack=${c?.floor_stack ?? "dim"}
|
||||
.panelOpen=${!!this._roomId && c?.room_panel !== false}
|
||||
.alerts=${c?.alerts !== false}
|
||||
.alertJump=${!!c?.alert_jump}
|
||||
.announcements=${c?.announcements !== false && !screenMuted()}
|
||||
.sensorBar=${c?.sensor_bar !== false}
|
||||
.glassWalls=${typeof c?.glass_walls === "number" ? Math.min(100, Math.max(0, c.glass_walls)) : null}
|
||||
.screenName=${c?.screen_name ?? screenName()}
|
||||
.scenes=${c?.scenes !== false}
|
||||
.clean=${this._clean}
|
||||
.cleanButton=${eye}
|
||||
@clean-toggle=${clean}
|
||||
?weather=${c?.weather !== false}
|
||||
.weatherEntityId=${c?.weather_entity ?? null}
|
||||
.weatherDensity=${c?.weather_density ?? 1}
|
||||
.dimmed=${this._night}
|
||||
.autoOrbit=${this._orbit}
|
||||
.startView=${c?.start_view ?? null}
|
||||
style=${s.showBar ? "--nf-bottom-inset: 52px" : ""}
|
||||
@room-tap=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => {
|
||||
// in the house view (or on another floor) a tap first opens the whole floor
|
||||
if (this.canSwitch && b.floors.length > 1 && e.detail.floorId && s.floorId !== e.detail.floorId) {
|
||||
this._floorId = e.detail.floorId;
|
||||
this._roomId = null;
|
||||
} else if (e.detail.roomId) this._roomId = e.detail.roomId === this._roomId ? null : e.detail.roomId;
|
||||
}}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => {
|
||||
this._floorId = e.detail.floorId;
|
||||
this._roomId = null;
|
||||
}}
|
||||
@back=${() => this.back()}
|
||||
></nf-view3d>`;
|
||||
}
|
||||
|
||||
private renderRoomPanel(): TemplateResult {
|
||||
const b = this.plan()!;
|
||||
return html`<nf-room-panel
|
||||
.building=${this.plan() ?? null}
|
||||
class="nf-card-panel"
|
||||
.hass=${this.hass}
|
||||
.room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null}
|
||||
.floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
|
||||
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null}
|
||||
.confirmEntities=${confirmEntities(this.hass, b.floors)}
|
||||
.phrases=${b.settings.announce_phrases ?? null}
|
||||
@close=${() => (this._roomId = null)}
|
||||
></nf-room-panel>`;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
// a language beyond German and English: its texts are fetched first, and then everything renders
|
||||
if (this.hass && awaitingLanguage(this.hass, this)) return nothing;
|
||||
const b = this.plan();
|
||||
const c = this._config;
|
||||
// the configured room opens once, when the building is there; the kiosk return brings it back
|
||||
if (!this.roomApplied && b && c?.room) {
|
||||
this.roomApplied = true;
|
||||
if (b.floors.some((f) => f.rooms.some((r) => r.id === c.room))) this._roomId = c.room;
|
||||
}
|
||||
const s = this.stage();
|
||||
// full screen, the screen below the dashboard header, or a fixed height
|
||||
const size = this._fullscreen ? "100vh" : c?.fill ? "calc(100vh - var(--header-height, 56px) - 16px)" : `${c?.height ?? 420}px`;
|
||||
const accent = /^#[0-9a-f]{6}$/i.test(c?.accent ?? "") ? c!.accent : null;
|
||||
const touch = () => this.kiosk.touched();
|
||||
return html`<ha-card class=${this._night ? "nf-night" : ""} style=${accent ? `--nf-accent:${accent}` : ""} @pointerdown=${touch} @keydown=${touch} @wheel=${touch}>
|
||||
<div class="nf-card-body" style="height:${size}">
|
||||
${b && b.floors.some((f) => f.rooms.length)
|
||||
? this.renderStage(s)
|
||||
: html`<p class="nf-card-msg">${this.data.error ?? (b ? translate(this.hass, "no_building") : translate(this.hass, "loading"))}</p>`}
|
||||
${this._roomId && b && c?.room_panel !== false ? this.renderRoomPanel() : nothing}
|
||||
${this.renderRoomButtons(s)}
|
||||
${s.showBar && b ? this.renderBar(s) : nothing}
|
||||
${this.renderCorners()}
|
||||
</div>
|
||||
</ha-card>`;
|
||||
}
|
||||
|
||||
static styles = [tokens, controls, cardStyles, readableStyles];
|
||||
}
|
||||
|
||||
if (!customElements.get("nextfloor-card")) {
|
||||
customElements.define("nextfloor-card", NextFloorCard);
|
||||
const registry = window as Window & { customCards?: unknown[] };
|
||||
registry.customCards = registry.customCards ?? [];
|
||||
registry.customCards.push({ type: "nextfloor-card", name: translate(undefined, "card_name"), description: translate(undefined, "card_description"), preview: false });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// The wall-tablet behaviour of the card, as plain timers: the clean view (bars hidden after a quiet spell), the return to the start
|
||||
// view after being idle (and the screensaver turn that may follow), and the night dimming that follows a time range.
|
||||
|
||||
import type { CardConfig } from "../card-config.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { nightActive } from "../kiosk.ts";
|
||||
|
||||
/** What the timers change on the card. */
|
||||
export interface KioskHost {
|
||||
config(): CardConfig | undefined;
|
||||
hass(): HomeAssistant | undefined;
|
||||
/** Whether the bars are hidden (the clean view). */
|
||||
setClean(clean: boolean): void;
|
||||
isClean(): boolean;
|
||||
/** The screensaver turn runs or stops. */
|
||||
setOrbit(on: boolean): void;
|
||||
isOrbit(): boolean;
|
||||
setNight(night: boolean): void;
|
||||
/** Back to the start view after the idle time. */
|
||||
goHome(): void;
|
||||
}
|
||||
|
||||
export class KioskTimers {
|
||||
private readonly host: KioskHost;
|
||||
private cleanTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private idleTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private nightTimer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
constructor(host: KioskHost) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
/** controls_hide_after: the bars come back on a touch and go again after the quiet spell. */
|
||||
armClean(touched = false): void {
|
||||
clearTimeout(this.cleanTimer);
|
||||
const seconds = this.host.config()?.controls_hide_after ?? 0;
|
||||
if (!(seconds > 0)) return;
|
||||
if (touched && this.host.isClean()) this.host.setClean(false);
|
||||
this.cleanTimer = setTimeout(() => this.host.setClean(true), seconds * 1000);
|
||||
}
|
||||
|
||||
stopClean(): void {
|
||||
clearTimeout(this.cleanTimer);
|
||||
}
|
||||
|
||||
/** idle_return: after the quiet spell the card goes back to its start view. */
|
||||
armIdle(): void {
|
||||
clearTimeout(this.idleTimer);
|
||||
const seconds = this.host.config()?.idle_return ?? 0;
|
||||
if (seconds > 0) this.idleTimer = setTimeout(() => this.host.goHome(), seconds * 1000);
|
||||
}
|
||||
|
||||
/** Any touch ends the screensaver and restarts the idle clock. */
|
||||
touched(): void {
|
||||
if (this.host.isOrbit()) this.host.setOrbit(false);
|
||||
this.armIdle();
|
||||
this.armClean(true);
|
||||
}
|
||||
|
||||
/** A time range for the night needs a look at the clock now and then. */
|
||||
start(): void {
|
||||
this.armIdle();
|
||||
this.nightTimer = setInterval(() => this.host.setNight(nightActive(this.host.config()?.night, this.host.hass())), 60000);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
clearTimeout(this.cleanTimer);
|
||||
clearTimeout(this.idleTimer);
|
||||
clearInterval(this.nightTimer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Building } from "../model.ts";
|
||||
import { roomButtons } from "./room-buttons.ts";
|
||||
|
||||
const house = {
|
||||
floors: [
|
||||
{ id: "eg", name: "Ground", rooms: [{ id: "a", name: "Living room" }, { id: "b", name: "" }] },
|
||||
{ id: "og", name: "Upper", rooms: [{ id: "c", name: "Study" }] },
|
||||
{ id: "dg", name: "Attic", rooms: [] },
|
||||
],
|
||||
} as unknown as Building;
|
||||
|
||||
test("the house view offers the rooms of every floor with rooms, grouped by floor", () => {
|
||||
const groups = roomButtons(house, null);
|
||||
assert.deepEqual(groups.map((g) => [g.floorId, g.rooms.length]), [["eg", 2], ["og", 1]]);
|
||||
assert.equal(groups[0].rooms[1].name, "–", "an unnamed room still gets a button");
|
||||
});
|
||||
|
||||
test("a shown floor offers only its own rooms, and a missing plan offers none", () => {
|
||||
assert.deepEqual(roomButtons(house, "og")[0].rooms.map((r) => r.id), ["c"]);
|
||||
assert.deepEqual(roomButtons(house, "dg"), []);
|
||||
assert.deepEqual(roomButtons(null, null), []);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// The room buttons of the dashboard card: one chip per room, grouped by floor when the whole house shows.
|
||||
|
||||
import type { Building } from "../model.ts";
|
||||
|
||||
export interface RoomButton {
|
||||
id: string;
|
||||
name: string;
|
||||
floorId: string;
|
||||
}
|
||||
|
||||
export interface RoomButtonGroup {
|
||||
floorId: string;
|
||||
floorName: string;
|
||||
rooms: RoomButton[];
|
||||
}
|
||||
|
||||
/** The rooms to offer: those of the shown floor, or of every floor (in the house view). Floors without rooms are left out. */
|
||||
export function roomButtons(building: Building | null | undefined, floorId: string | null): RoomButtonGroup[] {
|
||||
if (!building) return [];
|
||||
return building.floors
|
||||
.filter((f) => (floorId === null || f.id === floorId) && f.rooms.length > 0)
|
||||
.map((f) => ({ floorId: f.id, floorName: f.name, rooms: f.rooms.map((r) => ({ id: r.id, name: r.name || "–", floorId: f.id })) }));
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { css } from "lit";
|
||||
|
||||
/** The card's own styles: the stage, the bar of switches, the corner buttons, and the room panel that becomes a sheet on small screens. */
|
||||
export const cardStyles = css`
|
||||
ha-card {
|
||||
overflow: hidden;
|
||||
background: var(--nf-bg);
|
||||
height: 100%;
|
||||
}
|
||||
/* night (kiosk): the whole card dimmed */
|
||||
ha-card.nf-night .nf-card-body {
|
||||
filter: brightness(0.55);
|
||||
}
|
||||
.nf-card-body {
|
||||
position: relative;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
container-type: size;
|
||||
container-name: nf;
|
||||
}
|
||||
nf-view3d {
|
||||
flex: 1;
|
||||
}
|
||||
.nf-card-msg {
|
||||
margin: auto;
|
||||
color: var(--nf-muted);
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
/* the room buttons: a row along the top, clear of the toggles at the left and the corner buttons at the right */
|
||||
.nf-card-rooms {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 56px;
|
||||
right: 56px;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 2px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
/* with the room's side panel open the row ends where the panel starts */
|
||||
@container nf (min-width: 700px) {
|
||||
.nf-card-rooms-beside {
|
||||
right: 372px;
|
||||
}
|
||||
}
|
||||
.nf-card-rooms::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.nf-card-rooms button {
|
||||
flex: none;
|
||||
}
|
||||
.nf-card-rooms-floor {
|
||||
flex: none;
|
||||
color: var(--nf-soft);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-left: 6px;
|
||||
}
|
||||
.nf-card-controls {
|
||||
position: absolute;
|
||||
left: 60px;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.nf-card-controls > * {
|
||||
pointer-events: auto;
|
||||
}
|
||||
.nf-card-full {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 10px;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border: 0;
|
||||
border-radius: 12px;
|
||||
background: var(--nf-chrome);
|
||||
color: var(--nf-text);
|
||||
box-shadow: var(--nf-shadow);
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.nf-card-dash {
|
||||
width: auto;
|
||||
min-width: 38px;
|
||||
padding: 0 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.nf-card-dash-2 {
|
||||
right: 56px;
|
||||
}
|
||||
.nf-card-panel {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
width: min(340px, calc(100% - 20px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
pointer-events: none;
|
||||
}
|
||||
/* folded, only the title bar is left: it drops to the bottom edge instead of hanging in the picture */
|
||||
.nf-card-panel[folded] {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
/* phones and portrait tablets: the room panel becomes a sheet at the bottom */
|
||||
@container nf ((max-width: 700px) or ((orientation: portrait) and (max-width: 1000px))) {
|
||||
.nf-card-panel {
|
||||
top: auto;
|
||||
left: 8px;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
width: auto;
|
||||
height: 55%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,112 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { fanSpin } from "./entities/fans.ts";
|
||||
import { box, entity, floorWith, hassOf } from "./entities/fixtures.ts";
|
||||
import { furnitureEntities } from "./entities/furniture-links.ts";
|
||||
import { generateWalls } from "./geometry/walls.ts";
|
||||
import { canLift, ceilingAt, ceilingOf, roomsReachingUp, type Furniture } from "./model.ts";
|
||||
import { stairHoles } from "./viewer/build/build.ts";
|
||||
import { wallHeight } from "./viewer/build/placement.ts";
|
||||
import { mountBase } from "./packs.ts";
|
||||
|
||||
const piece = (id: string, type: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type, x: 1, z: 1, rotation: 0, w: 1, d: 1, h: 0.3, variant: null, entity: null, power: null, ...extra });
|
||||
|
||||
// a 4 m high floor with a low bathroom (2.12 m) next to a room without a ceiling of its own
|
||||
const bath = { ...box("bath", 0, 0, 2, 2), ceiling: 2.12 };
|
||||
const hall = box("hall", 2, 0, 6, 2);
|
||||
const floor = floorWith([bath, hall], { height: 4 });
|
||||
|
||||
test("the ceiling above a point is the room's own one, else the floor height", () => {
|
||||
assert.equal(ceilingAt(floor, 1, 1), 2.12);
|
||||
assert.equal(ceilingAt(floor, 4, 1), 4);
|
||||
// outside every room
|
||||
assert.equal(ceilingAt(floor, 10, 10), 4);
|
||||
});
|
||||
|
||||
test("a ceiling set on the piece itself wins over the room's (a lamp in a sloping ceiling)", () => {
|
||||
assert.equal(ceilingOf(floor, { x: 1, z: 1 }), 2.12);
|
||||
assert.equal(ceilingOf(floor, { x: 1, z: 1, ceiling_y: 3.4 }), 3.4);
|
||||
assert.equal(ceilingOf(floor, { x: 1, z: 1, ceiling_y: null }), 2.12);
|
||||
});
|
||||
|
||||
test("LED strips sit under the ceiling of their room", () => {
|
||||
const strip = piece("s", "led_strip", { h: 0.03 });
|
||||
assert.ok(Math.abs(mountBase(floor, strip) - (2.12 - 0.04 - 0.03)) < 1e-9);
|
||||
assert.ok(Math.abs(mountBase(floor, { ...strip, x: 4 }) - (4 - 0.04 - 0.03)) < 1e-9);
|
||||
});
|
||||
|
||||
test("ceiling fans hang from the ceiling and are not lifted from the floor", () => {
|
||||
assert.equal(canLift(piece("f", "ceiling_fan")), false);
|
||||
assert.equal(canLift(piece("t", "lamp_table")), true);
|
||||
});
|
||||
|
||||
test("a room's walls default to its ceiling; a wall shared with a room without one keeps the floor height", () => {
|
||||
const { walls } = generateWalls([bath, hall], { exterior: 0.3, interior: 0.1 });
|
||||
const outer = walls.filter((w) => w.exterior && w.roomLeft === "bath");
|
||||
assert.ok(outer.length > 0);
|
||||
for (const w of outer) assert.equal(w.height, 2.12);
|
||||
const shared = walls.find((w) => !w.exterior);
|
||||
assert.equal(shared?.height, undefined);
|
||||
// the hall's walls are full height
|
||||
assert.ok(walls.filter((w) => w.exterior && w.roomLeft === "hall").every((w) => w.height === undefined));
|
||||
});
|
||||
|
||||
test("between two rooms with their own ceilings the wall is as high as the higher one", () => {
|
||||
const { walls } = generateWalls([bath, { ...hall, ceiling: 3 }], { exterior: 0.3, interior: 0.1 });
|
||||
assert.equal(walls.find((w) => !w.exterior)?.height, 3);
|
||||
});
|
||||
|
||||
test("a height set by hand on an edge still wins over the room's ceiling", () => {
|
||||
const { walls } = generateWalls([{ ...bath, wall_heights: [1, null, null, null] }], { exterior: 0.3, interior: 0.1 });
|
||||
const heights = walls.map((w) => w.height).sort();
|
||||
assert.deepEqual(heights, [1, 2.12, 2.12, 2.12]);
|
||||
});
|
||||
|
||||
test("a fan's blades turn faster with its speed and stand still while it is off", () => {
|
||||
assert.equal(fanSpin(undefined), 0);
|
||||
assert.equal(fanSpin({ state: "off", attributes: { percentage: 0 } }), 0);
|
||||
const slow = fanSpin({ state: "on", attributes: { percentage: 25 } });
|
||||
const fast = fanSpin({ state: "on", attributes: { percentage: 100 } });
|
||||
assert.ok(slow > 0 && fast > slow);
|
||||
// a fan without speeds turns at a middle speed
|
||||
assert.ok(fanSpin({ state: "on", attributes: {} }) > slow);
|
||||
});
|
||||
|
||||
test("a ceiling fan takes the fan of its room and the light on the same device as its light kit", () => {
|
||||
const hass = hassOf(
|
||||
[entity("fan.living_fan", "on", { percentage: 50 }), entity("light.living_fan_light", "on"), entity("light.main_ceiling", "on")],
|
||||
{
|
||||
"fan.living_fan": { area_id: "area", device_id: "fan1" },
|
||||
"light.living_fan_light": { area_id: "area", device_id: "fan1" },
|
||||
"light.main_ceiling": { area_id: "area" },
|
||||
},
|
||||
);
|
||||
const room = box("r", 0, 0, 4, 3, "area");
|
||||
const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("fan", "ceiling_fan")] })]).get("fan");
|
||||
assert.deepEqual(links, { entity: "light.living_fan_light", power: null, fan: "fan.living_fan" });
|
||||
});
|
||||
|
||||
test("a ceiling fan without a light kit does not take the room's ceiling light", () => {
|
||||
const hass = hassOf([entity("fan.bedroom", "off"), entity("light.main_ceiling", "on")], { "fan.bedroom": { area_id: "area" }, "light.main_ceiling": { area_id: "area" } });
|
||||
const room = box("r", 0, 0, 4, 3, "area");
|
||||
const links = furnitureEntities(hass, [floorWith([room], { furniture: [piece("fan", "ceiling_fan")] })]).get("fan");
|
||||
assert.deepEqual(links, { entity: null, power: null, fan: "fan.bedroom" });
|
||||
});
|
||||
|
||||
test("a room whose ceiling rises above its floor opens the floors it reaches into (#55)", () => {
|
||||
const living = { ...box("living", 0, 0, 5, 4), ceiling: 5.2 };
|
||||
const ground = { ...floorWith([living, box("kitchen", 5, 0, 8, 4)], { height: 2.7 }), id: "eg", elevation: 0 };
|
||||
const upper = { ...floorWith([box("bed", 5, 0, 8, 4)], { height: 2.6 }), id: "og", elevation: 2.9 };
|
||||
const attic = { ...floorWith([], { height: 2.4 }), id: "dg", elevation: 5.6 };
|
||||
const floors = [ground, upper, attic];
|
||||
assert.deepEqual(roomsReachingUp(floors, upper), [living.points]);
|
||||
// 5.2 m stays below the attic at 5.6 m
|
||||
assert.deepEqual(roomsReachingUp(floors, attic), []);
|
||||
assert.equal(stairHoles(floors, upper).length, 1);
|
||||
assert.equal(stairHoles(floors, attic).length, 0);
|
||||
// the room's walls rise with its ceiling, a shared wall with a room without a ceiling of its own keeps the floor height
|
||||
const walls = generateWalls(ground.rooms, { exterior: 0.3, interior: 0.12 }).walls;
|
||||
const heights = walls.map((w) => wallHeight(w, ground.height));
|
||||
assert.ok(heights.includes(5.2));
|
||||
assert.ok(heights.includes(2.7));
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,137 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../entities/fixtures.ts";
|
||||
import type { Building, Floor } from "../../model.ts";
|
||||
import { BackgroundTool, type BackgroundDeps } from "./background-tool.ts";
|
||||
|
||||
class TestTool extends BackgroundTool {
|
||||
protected override async aspectOf(): Promise<number> {
|
||||
return 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
function setup(floorExtra: Partial<Floor> = {}, tool = "select") {
|
||||
let floor = floorWith([box("r", 1, 2, 7, 6)], floorExtra);
|
||||
const doc = { floors: [floor] } as unknown as Building;
|
||||
const stored: string[] = [];
|
||||
const calls = { refresh: 0, selectTool: 0 };
|
||||
const deps: BackgroundDeps = {
|
||||
host: {
|
||||
hass: {} as never,
|
||||
get doc() {
|
||||
return doc;
|
||||
},
|
||||
get floor() {
|
||||
return floor;
|
||||
},
|
||||
admin: true,
|
||||
t: (key) => key,
|
||||
change: (mutate) => {
|
||||
const copy = structuredClone(floor);
|
||||
mutate(doc, copy);
|
||||
floor = copy;
|
||||
doc.floors = [copy];
|
||||
},
|
||||
pickPoint: () => {},
|
||||
replace: () => undefined,
|
||||
},
|
||||
refresh: () => calls.refresh++,
|
||||
api: { fetchImage: async (_h, id) => `data:${id}`, storeImage: async (_h, id) => void stored.push(id) },
|
||||
readPicture: async () => ({ data: "data:new", aspect: 0.5 }),
|
||||
useSelectTool: () => calls.selectTool++,
|
||||
currentTool: () => tool,
|
||||
};
|
||||
return { tool: new TestTool(deps), floor: () => floor, stored, calls };
|
||||
}
|
||||
|
||||
test("a chosen picture is stored and becomes the background, as wide as the rooms", async () => {
|
||||
const s = setup();
|
||||
await s.tool.upload({} as File);
|
||||
const bg = s.floor().background!;
|
||||
assert.deepEqual([bg.x, bg.z, bg.width, bg.opacity], [1, 2, 6, 0.5]);
|
||||
assert.deepEqual(s.stored, [bg.image_id]);
|
||||
assert.equal(s.tool.picture(bg.image_id)?.aspect, 0.5);
|
||||
});
|
||||
|
||||
test("on a floor without rooms the picture is 12 m wide at the origin, and no file does nothing", async () => {
|
||||
const s = setup();
|
||||
s.floor().rooms = [];
|
||||
await s.tool.upload({} as File);
|
||||
assert.deepEqual([s.floor().background!.x, s.floor().background!.width], [0, 12]);
|
||||
const none = setup();
|
||||
await none.tool.upload(undefined);
|
||||
assert.equal(none.floor().background ?? null, null);
|
||||
});
|
||||
|
||||
test("stored pictures load once, and a failing load leaves the background empty", async () => {
|
||||
const s = setup();
|
||||
s.tool.ensureLoaded("a");
|
||||
s.tool.ensureLoaded("a");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
assert.equal(s.tool.picture("a")?.url, "data:a");
|
||||
assert.equal(s.tool.picture("missing"), undefined);
|
||||
assert.equal(s.tool.picture(undefined), undefined);
|
||||
});
|
||||
|
||||
test("the handles show only with the select tool and 'move and scale' on, on a floor with a picture", () => {
|
||||
const withPicture = { background: { image_id: "a", x: 0, z: 0, width: 4, opacity: 1 } };
|
||||
const s = setup(withPicture);
|
||||
assert.equal(s.tool.handlesShown, false);
|
||||
s.tool.toggleEdit();
|
||||
assert.equal(s.tool.handlesShown, true);
|
||||
assert.equal(s.calls.selectTool, 1);
|
||||
assert.equal(setup(withPicture, "rect").tool.handlesShown, false);
|
||||
const none = setup();
|
||||
none.tool.edit = true;
|
||||
assert.equal(none.tool.handlesShown, false);
|
||||
});
|
||||
|
||||
test("straighten and measure modes exclude each other and 'move and scale'", () => {
|
||||
const s = setup();
|
||||
s.tool.edit = true;
|
||||
s.tool.toggleLevel();
|
||||
assert.deepEqual([s.tool.level, s.tool.ruler, s.tool.edit], [[], null, false]);
|
||||
s.tool.toggleRuler();
|
||||
assert.deepEqual([s.tool.level, s.tool.ruler], [null, []]);
|
||||
s.tool.toggleRuler();
|
||||
assert.equal(s.tool.ruler, null);
|
||||
});
|
||||
|
||||
test("two taps straighten the picture", async () => {
|
||||
const s = setup({ background: { image_id: "a", x: 0, z: 0, width: 4, opacity: 1 } });
|
||||
s.tool.ensureLoaded("a");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
s.tool.toggleLevel();
|
||||
s.tool.tapLevel([0, 0]);
|
||||
assert.deepEqual(s.tool.level, [[0, 0]]);
|
||||
s.tool.tapLevel([10, 1]);
|
||||
assert.equal(s.tool.level, null);
|
||||
assert.ok(Math.abs(s.floor().background!.rotation! + 5.71) < 0.01);
|
||||
});
|
||||
|
||||
test("two taps and a typed length scale the picture, and then the mode ends", async () => {
|
||||
const s = setup({ background: { image_id: "a", x: 0, z: 0, width: 4, opacity: 1 } });
|
||||
s.tool.ensureLoaded("a");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
s.tool.toggleRuler();
|
||||
s.tool.tapRuler([0, 0]);
|
||||
s.tool.tapRuler([2, 0]);
|
||||
s.tool.tapRuler([5, 5]);
|
||||
assert.equal(s.tool.ruler!.length, 2, "a third tap is ignored");
|
||||
s.tool.rulerLength = 6;
|
||||
s.tool.applyRuler();
|
||||
assert.equal(s.floor().background!.width, 12);
|
||||
assert.deepEqual([s.tool.ruler, s.tool.rulerLength], [null, 0]);
|
||||
});
|
||||
|
||||
test("measuring without a typed length changes nothing and keeps the mode", async () => {
|
||||
const s = setup({ background: { image_id: "a", x: 0, z: 0, width: 4, opacity: 1 } });
|
||||
s.tool.ensureLoaded("a");
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
s.tool.toggleRuler();
|
||||
s.tool.tapRuler([0, 0]);
|
||||
s.tool.tapRuler([2, 0]);
|
||||
s.tool.applyRuler();
|
||||
assert.equal(s.floor().background!.width, 4);
|
||||
assert.equal(s.tool.ruler!.length, 2);
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
// The picture behind a floor plan: loading the stored pictures, adding a new one, and the two ways of calibrating it (straighten it
|
||||
// against a wall, or scale it with a measured length). The tool owns the state of these modes; the form and the plan canvas read it.
|
||||
|
||||
import { fetchImage, storeImage } from "../../api.ts";
|
||||
import { bounds, uid, type Background, type Vec2 } from "../../model.ts";
|
||||
import type { EditorHost } from "./host.ts";
|
||||
import { scaledToLength, straightened } from "./ops/background.ts";
|
||||
|
||||
export interface StoredPicture {
|
||||
url: string;
|
||||
/** Height divided by width. */
|
||||
aspect: number;
|
||||
}
|
||||
|
||||
export interface BackgroundDeps {
|
||||
host: EditorHost;
|
||||
refresh(): void;
|
||||
api: { fetchImage: typeof fetchImage; storeImage: typeof storeImage };
|
||||
/** Reads a chosen file, shrinks it to a size the plan can carry, and gives it as a data URL with its aspect. */
|
||||
readPicture(file: File): Promise<{ data: string; aspect: number }>;
|
||||
/** The handles need the select tool. */
|
||||
useSelectTool(): void;
|
||||
currentTool(): string;
|
||||
}
|
||||
|
||||
const MAX_SIDE = 2048;
|
||||
|
||||
/** The browser's way of shrinking a picture: draws it onto a canvas of at most 2048 pixels on its longer side. */
|
||||
export async function readPictureInBrowser(file: File): Promise<{ data: string; aspect: number }> {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const k = Math.min(1, MAX_SIDE / Math.max(bitmap.width, bitmap.height));
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.round(bitmap.width * k);
|
||||
canvas.height = Math.round(bitmap.height * k);
|
||||
canvas.getContext("2d")!.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||
return { data: canvas.toDataURL("image/jpeg", 0.85), aspect: canvas.height / canvas.width };
|
||||
}
|
||||
|
||||
export class BackgroundTool {
|
||||
private readonly deps: BackgroundDeps;
|
||||
private editMode = false;
|
||||
private levelPoints: Vec2[] | null = null;
|
||||
private rulerPoints: Vec2[] | null = null;
|
||||
private rulerMetres = 0;
|
||||
private sectionOpen = false;
|
||||
private pictures: Record<string, StoredPicture> = {};
|
||||
private readonly loading = new Set<string>();
|
||||
|
||||
constructor(deps: BackgroundDeps) {
|
||||
this.deps = deps;
|
||||
}
|
||||
|
||||
// state that the form shows and the pointer code changes; each setter asks for a redraw
|
||||
|
||||
/** "Move and scale" is on: the picture has handles. */
|
||||
get edit(): boolean {
|
||||
return this.editMode;
|
||||
}
|
||||
set edit(on: boolean) {
|
||||
this.editMode = on;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
/** Straightening: the points tapped so far (none, or the first), or null when the mode is off. */
|
||||
get level(): Vec2[] | null {
|
||||
return this.levelPoints;
|
||||
}
|
||||
set level(points: Vec2[] | null) {
|
||||
this.levelPoints = points;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
/** Measuring: the points tapped so far, or null when the mode is off. */
|
||||
get ruler(): Vec2[] | null {
|
||||
return this.rulerPoints;
|
||||
}
|
||||
set ruler(points: Vec2[] | null) {
|
||||
this.rulerPoints = points;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
/** The length in metres typed for the measured stretch. */
|
||||
get rulerLength(): number {
|
||||
return this.rulerMetres;
|
||||
}
|
||||
set rulerLength(metres: number) {
|
||||
this.rulerMetres = metres;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
/** Whether the form's section is unfolded. */
|
||||
get open(): boolean {
|
||||
return this.sectionOpen;
|
||||
}
|
||||
set open(open: boolean) {
|
||||
this.sectionOpen = open;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
/** The handles (move, scale, turn) show while "Move and scale" is on, with the select tool. */
|
||||
get handlesShown(): boolean {
|
||||
const { host } = this.deps;
|
||||
return !!host.floor?.background && host.admin && this.deps.currentTool() === "select" && this.editMode;
|
||||
}
|
||||
|
||||
/** The loaded picture of a background, or of a stored picture id. Undefined until it is loaded. */
|
||||
picture(id: string | undefined): StoredPicture | undefined {
|
||||
return id ? this.pictures[id] : undefined;
|
||||
}
|
||||
|
||||
/** Starts loading a stored picture unless it is loaded or on its way. */
|
||||
ensureLoaded(id: string): void {
|
||||
if (!this.pictures[id] && !this.loading.has(id)) void this.load(id);
|
||||
}
|
||||
|
||||
private async load(id: string): Promise<void> {
|
||||
const { host, api } = this.deps;
|
||||
if (!host.hass) return;
|
||||
this.loading.add(id);
|
||||
try {
|
||||
const url = await api.fetchImage(host.hass, id);
|
||||
const aspect = await this.aspectOf(url);
|
||||
this.pictures = { ...this.pictures, [id]: { url, aspect } };
|
||||
this.deps.refresh();
|
||||
} catch {
|
||||
// a picture that is gone (removed on the server): the background stays empty
|
||||
}
|
||||
}
|
||||
|
||||
/** The height-to-width ratio of a picture, once the browser has decoded it. */
|
||||
protected async aspectOf(url: string): Promise<number> {
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await image.decode();
|
||||
return image.naturalHeight / image.naturalWidth;
|
||||
}
|
||||
|
||||
/** Stores a chosen file as the background of the floor shown: as wide as the rooms, or 12 m when there are none. */
|
||||
async upload(file: File | undefined): Promise<void> {
|
||||
const { host, api } = this.deps;
|
||||
if (!file || !host.hass) return;
|
||||
const { data, aspect } = await this.deps.readPicture(file);
|
||||
const id = uid("img");
|
||||
await api.storeImage(host.hass, id, data);
|
||||
this.pictures = { ...this.pictures, [id]: { url: data, aspect } };
|
||||
const rooms = host.floor?.rooms ?? [];
|
||||
const box = rooms.length > 0 ? bounds(rooms.flatMap((r) => r.points)) : null;
|
||||
const placed: Background = { image_id: id, x: box ? box.x0 : 0, z: box ? box.z0 : 0, width: box ? Math.max(4, Math.round((box.x1 - box.x0) * 1000) / 1000) : 12, opacity: 0.5 };
|
||||
this.setBackground(placed);
|
||||
}
|
||||
|
||||
/** Writes a background to the floor shown; null removes it. */
|
||||
setBackground(background: Background | null): void {
|
||||
this.deps.host.change((_, floor) => Object.assign(floor, { background }));
|
||||
}
|
||||
|
||||
// calibration
|
||||
|
||||
/** Straighten mode on or off. Starting it ends the other modes. */
|
||||
toggleLevel(): void {
|
||||
this.levelPoints = this.levelPoints ? null : [];
|
||||
this.rulerPoints = null;
|
||||
this.editMode = false;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
toggleRuler(): void {
|
||||
this.rulerPoints = this.rulerPoints ? null : [];
|
||||
this.levelPoints = null;
|
||||
this.editMode = false;
|
||||
this.deps.refresh();
|
||||
}
|
||||
|
||||
toggleEdit(): void {
|
||||
this.edit = !this.editMode;
|
||||
if (this.editMode) this.deps.useSelectTool();
|
||||
}
|
||||
|
||||
/** A tap in straighten mode: the first starts, the second turns the picture. */
|
||||
tapLevel(world: Vec2): void {
|
||||
const points = [...(this.levelPoints ?? []), world];
|
||||
if (points.length < 2) {
|
||||
this.level = points;
|
||||
return;
|
||||
}
|
||||
this.level = null;
|
||||
this.straighten(points[0], points[1]);
|
||||
}
|
||||
|
||||
/** A tap in measure mode: two points mark the stretch. Further taps are ignored. */
|
||||
tapRuler(world: Vec2): void {
|
||||
if (this.rulerPoints && this.rulerPoints.length < 2) this.ruler = [...this.rulerPoints, world];
|
||||
}
|
||||
|
||||
private straighten(p: Vec2, q: Vec2): void {
|
||||
const current = this.deps.host.floor?.background;
|
||||
const picture = this.picture(current?.image_id);
|
||||
const next = current && picture ? straightened(current, picture.aspect, p, q) : null;
|
||||
if (next) this.setBackground(next);
|
||||
}
|
||||
|
||||
/** Scales the picture so that the measured stretch has the typed length. */
|
||||
applyRuler(): void {
|
||||
const current = this.deps.host.floor?.background;
|
||||
const picture = this.picture(current?.image_id);
|
||||
const points = this.rulerPoints;
|
||||
if (!current || !picture || !points || points.length < 2) return;
|
||||
const next = scaledToLength(current, picture.aspect, points[0], points[1], this.rulerMetres);
|
||||
if (!next) return;
|
||||
this.setBackground(next);
|
||||
this.rulerPoints = null;
|
||||
this.rulerMetres = 0;
|
||||
this.deps.refresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { newFloor, type Building } from "../../model.ts";
|
||||
import { BackupService, type BackupDeps, type BackupHost } from "./backup.ts";
|
||||
|
||||
const plan = (): Building => ({ version: 1, floors: [newFloor("g", "Ground", 0)], settings: { roof: { type: "none" } }, energy: {}, presence: [] }) as unknown as Building;
|
||||
const file = (text: string) => ({ text: async () => text }) as File;
|
||||
|
||||
function setup(overrides: Partial<BackupDeps["api"]> = {}, answers = { confirm: true }) {
|
||||
const log: string[] = [];
|
||||
const downloads: [string, string][] = [];
|
||||
const api = {
|
||||
listHistory: async () => [{ id: "s1", revision: 1, saved_at: 0, floors: 1, rooms: 2, furniture: 3 }],
|
||||
restoreSnapshot: async (_h: unknown, id: string) => (log.push(`restore ${id}`), 2),
|
||||
takeSnapshot: async () => void log.push("snapshot"),
|
||||
fetchBackup: async () => ({ format: "nextfloor-backup", version: 1, building: plan(), packs: [] }),
|
||||
restoreBackup: async () => ({ building: plan(), packs: 1, skipped: [{ id: "bad" }] }),
|
||||
fetchImage: async (_h: unknown, id: string) => `data:${id}`,
|
||||
storeImage: async (_h: unknown, id: string) => void log.push(`store ${id}`),
|
||||
...overrides,
|
||||
} as unknown as BackupDeps["api"];
|
||||
const deps: BackupDeps = { api, alert: (t) => log.push(`alert ${t}`), confirm: () => answers.confirm, download: (n, t) => downloads.push([n, t]), today: () => "2026-10-12" };
|
||||
const said: string[] = [];
|
||||
const adopted: Building[] = [];
|
||||
const host: BackupHost = {
|
||||
hass: { language: "en" } as never,
|
||||
doc: plan(),
|
||||
t: (key, vars) => `${key}${vars ? JSON.stringify(vars) : ""}`,
|
||||
adopt: (b) => adopted.push(b),
|
||||
say: (t) => said.push(t),
|
||||
refresh: () => undefined,
|
||||
packsChanged: () => log.push("packs"),
|
||||
};
|
||||
return { service: new BackupService(host, deps), log, downloads, said, adopted };
|
||||
}
|
||||
|
||||
test("loading the restore points fills the list, and a failing backend gives an empty one", async () => {
|
||||
const ok = setup();
|
||||
await ok.service.loadHistory();
|
||||
assert.equal(ok.service.history?.length, 1);
|
||||
const failing = setup({ listHistory: async () => Promise.reject(new Error("x")) });
|
||||
await failing.service.loadHistory();
|
||||
assert.deepEqual(failing.service.history, []);
|
||||
});
|
||||
|
||||
test("restoring a point asks first and only then goes back", async () => {
|
||||
const no = setup({}, { confirm: false });
|
||||
await no.service.restorePoint({ id: "s1", revision: 1, saved_at: 0, floors: 1, rooms: 1, furniture: 1 });
|
||||
assert.deepEqual(no.log, []);
|
||||
const yes = setup();
|
||||
await yes.service.restorePoint({ id: "s1", revision: 1, saved_at: 0, floors: 1, rooms: 1, furniture: 1 });
|
||||
assert.equal(yes.log[0], "restore s1");
|
||||
assert.equal(yes.said[0], "backup_restored");
|
||||
});
|
||||
|
||||
test("exporting the plan names the file after the kind and the day", () => {
|
||||
const s = setup();
|
||||
s.service.exportPlan(true);
|
||||
s.service.exportPlan(false);
|
||||
assert.deepEqual(s.downloads.map(([name]) => name), ["nextfloor-export_name_template-2026-10-12.json", "nextfloor-export_name_backup-2026-10-12.json"]);
|
||||
assert.equal(JSON.parse(s.downloads[0][1]).format, "nextfloor");
|
||||
});
|
||||
|
||||
test("importing a plan: bad files are refused with a reason, a good one takes a restore point first", async () => {
|
||||
const bad = setup();
|
||||
await bad.service.importPlan(file("{oops"));
|
||||
assert.ok(bad.log[0].startsWith("alert import_error_not_json"));
|
||||
await bad.service.importPlan(file('{"hello": 1}'));
|
||||
assert.ok(bad.log[1].startsWith("alert import_error_not_plan"));
|
||||
assert.equal(bad.adopted.length, 0);
|
||||
const good = setup();
|
||||
await good.service.importPlan(file(JSON.stringify(plan())));
|
||||
assert.equal(good.log[0], "snapshot");
|
||||
assert.equal(good.adopted.length, 1);
|
||||
assert.equal(good.said[0], "backup_imported");
|
||||
const declined = setup({}, { confirm: false });
|
||||
await declined.service.importPlan(file(JSON.stringify(plan())));
|
||||
assert.equal(declined.adopted.length, 0);
|
||||
await declined.service.importPlan(undefined);
|
||||
});
|
||||
|
||||
test("a full backup includes the readable pictures and is not busy afterwards", async () => {
|
||||
const s = setup({ fetchBackup: async () => ({ format: "nextfloor-backup", version: 1, building: { ...plan(), floors: [{ ...newFloor("g", "G", 0), background: { image_id: "pic1", x: 0, z: 0, width: 1, opacity: 1 } }] }, packs: [] }) as never });
|
||||
await s.service.exportFull();
|
||||
assert.equal(s.service.busy, false);
|
||||
assert.equal(s.downloads.length, 1);
|
||||
assert.deepEqual(Object.keys(JSON.parse(s.downloads[0][1]).images ?? {}), ["pic1"]);
|
||||
});
|
||||
|
||||
test("a full restore stores the pictures, tells which packs were skipped, and refuses other files", async () => {
|
||||
const s = setup();
|
||||
const backup = { format: "nextfloor-backup", version: 1, building: plan(), packs: [], images: { a: "data:a", b: "data:b" } };
|
||||
await s.service.importFull(file(JSON.stringify(backup)));
|
||||
assert.deepEqual(s.log.filter((l) => l.startsWith("store")), ["store a", "store b"]);
|
||||
assert.ok(s.log.includes("packs"));
|
||||
assert.equal(s.adopted.length, 1);
|
||||
assert.ok(s.said[0].includes("backup_full_restored") && s.said[0].includes("bad"));
|
||||
assert.equal(s.service.busy, false);
|
||||
const other = setup();
|
||||
await other.service.importFull(file('{"format":"nextfloor"}'));
|
||||
assert.ok(other.log[0].startsWith("alert backup_full_not_backup"));
|
||||
const broken = setup({ restoreBackup: async () => Promise.reject({ code: "boom" }) });
|
||||
await broken.service.importFull(file(JSON.stringify(backup)));
|
||||
assert.ok(broken.log.some((l) => l.includes("boom")));
|
||||
assert.equal(broken.service.busy, false);
|
||||
});
|
||||
@@ -0,0 +1,248 @@
|
||||
// The backup side of the editor: restore points of the plan, a file with the plan alone, and a full backup with pictures and packs.
|
||||
// Everything the browser or the backend provides comes in through `deps`, so the flows can be tested without either.
|
||||
|
||||
import { deleteSnapshot, fetchBackup, fetchImage, getSnapshot, listHistory, restoreBackup, restoreSnapshot, storeImage, takeSnapshot, type BackupFile, type Snapshot } from "../../api.ts";
|
||||
import { diffBuildings, type DiffEntry } from "./ops/plan-diff.ts";
|
||||
import type { I18nKey } from "../../i18n.ts";
|
||||
import { normalizeBuilding, type Building } from "../../model.ts";
|
||||
import { importSweetHome } from "../../import/sweethome.ts";
|
||||
import { importDxf } from "../../import/dxf.ts";
|
||||
import { importRoomPlan, isRoomPlan } from "../../import/roomplan.ts";
|
||||
import { importIfc } from "../../import/ifc.ts";
|
||||
import { download, exportFile, parseExport, shareViewHtml, storedImageIds } from "../../transfer.ts";
|
||||
import { getPacks } from "../../packs.ts";
|
||||
import type { HomeAssistant } from "../../types.ts";
|
||||
|
||||
export interface BackupDeps {
|
||||
api: {
|
||||
listHistory: typeof listHistory;
|
||||
restoreSnapshot: typeof restoreSnapshot;
|
||||
takeSnapshot: typeof takeSnapshot;
|
||||
getSnapshot?: typeof getSnapshot;
|
||||
deleteSnapshot?: typeof deleteSnapshot;
|
||||
fetchBackup: typeof fetchBackup;
|
||||
restoreBackup: typeof restoreBackup;
|
||||
fetchImage: typeof fetchImage;
|
||||
storeImage: typeof storeImage;
|
||||
};
|
||||
alert(text: string): void;
|
||||
confirm(text: string): boolean;
|
||||
prompt?(text: string): string | null;
|
||||
download(filename: string, text: string, type?: string): void;
|
||||
today(): string;
|
||||
}
|
||||
|
||||
export const browserDeps: BackupDeps = {
|
||||
api: { listHistory, restoreSnapshot, takeSnapshot, getSnapshot, deleteSnapshot, fetchBackup, restoreBackup, fetchImage, storeImage },
|
||||
alert: (text) => alert(text),
|
||||
confirm: (text) => confirm(text),
|
||||
prompt: (text) => prompt(text),
|
||||
download,
|
||||
today: () => new Date().toISOString().slice(0, 10),
|
||||
};
|
||||
|
||||
/** What the backup flows need from the editor. */
|
||||
export interface BackupHost {
|
||||
readonly hass: HomeAssistant | undefined;
|
||||
readonly doc: Building;
|
||||
t(key: I18nKey, vars?: Record<string, string | number>): string;
|
||||
/** A restored or imported plan replaces the current one. */
|
||||
adopt(building: Building): void;
|
||||
/** A line shown to the user once a flow is done. */
|
||||
say(text: string): void;
|
||||
/** The state of the section changed, so it should draw again. */
|
||||
refresh(): void;
|
||||
/** Backed-up packs are back. */
|
||||
packsChanged(): void;
|
||||
}
|
||||
|
||||
const errorText = (err: unknown): string => String((err as { message?: string } | null)?.message ?? err);
|
||||
|
||||
export class BackupService {
|
||||
private readonly host: BackupHost;
|
||||
private readonly deps: BackupDeps;
|
||||
/** The restore points, or null while they are not loaded. */
|
||||
history: Snapshot[] | null = null;
|
||||
busy = false;
|
||||
/** An older state compared with the plan: what differs, or null while nothing is compared. */
|
||||
compare: { snapshot: Snapshot; entries: DiffEntry[] } | null = null;
|
||||
|
||||
constructor(host: BackupHost, deps: BackupDeps = browserDeps) {
|
||||
this.host = host;
|
||||
this.deps = deps;
|
||||
}
|
||||
|
||||
async loadHistory(): Promise<void> {
|
||||
const { hass } = this.host;
|
||||
if (!hass) return;
|
||||
this.history = await this.deps.api.listHistory(hass).catch(() => []);
|
||||
this.host.refresh();
|
||||
}
|
||||
|
||||
timeOf(snapshot: Snapshot): string {
|
||||
return new Date(snapshot.saved_at * 1000).toLocaleString(this.host.hass?.language, { dateStyle: "short", timeStyle: "short" });
|
||||
}
|
||||
|
||||
async restorePoint(snapshot: Snapshot): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
if (!hass || !this.deps.confirm(t("backup_restore_confirm", { time: this.timeOf(snapshot) }))) return;
|
||||
await this.deps.api.restoreSnapshot(hass, snapshot.id);
|
||||
this.host.say(t("backup_restored"));
|
||||
await this.loadHistory();
|
||||
}
|
||||
|
||||
/** Keeps the plan as it is now under a name of its own: a version that stays when the automatic points go. */
|
||||
async saveVersion(): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
const name = hass ? this.deps.prompt?.(t("version_name_prompt"))?.trim() : null;
|
||||
if (!hass || !name) return;
|
||||
await this.deps.api.takeSnapshot(hass, name.slice(0, 60));
|
||||
this.host.say(t("version_saved", { name }));
|
||||
await this.loadHistory();
|
||||
}
|
||||
|
||||
/** Compares an older state with the plan as it is in the editor (unsaved changes included). */
|
||||
async compareWith(snapshot: Snapshot): Promise<void> {
|
||||
const { hass } = this.host;
|
||||
const get = this.deps.api.getSnapshot;
|
||||
if (!hass || !get) return;
|
||||
if (this.compare?.snapshot.id === snapshot.id) {
|
||||
this.compare = null;
|
||||
return this.host.refresh();
|
||||
}
|
||||
const older = normalizeBuilding(await get(hass, snapshot.id));
|
||||
this.compare = { snapshot, entries: diffBuildings(older, this.host.doc) };
|
||||
this.host.refresh();
|
||||
}
|
||||
|
||||
async deleteVersion(snapshot: Snapshot): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
const remove = this.deps.api.deleteSnapshot;
|
||||
if (!hass || !remove || !this.deps.confirm(t("version_delete_confirm", { name: snapshot.name ?? this.timeOf(snapshot) }))) return;
|
||||
await remove(hass, snapshot.id);
|
||||
if (this.compare?.snapshot.id === snapshot.id) this.compare = null;
|
||||
await this.loadHistory();
|
||||
}
|
||||
|
||||
/** The house as a page that opens in any browser (through the online demo), without the entities: to show it to someone. */
|
||||
exportShareView(): void {
|
||||
const t = this.host.t;
|
||||
const html = shareViewHtml(this.host.doc, getPacks(), t("share_view_title"), t("share_view_needs_js"));
|
||||
this.deps.download(`nextfloor-${t("share_view_file")}-${this.deps.today()}.html`, html, "text/html");
|
||||
this.host.say(t("share_view_done"));
|
||||
}
|
||||
|
||||
/** Saves the plan alone as a file; a shareable one has the entities taken out. */
|
||||
exportPlan(shareable: boolean): void {
|
||||
const kind = this.host.t(shareable ? "export_name_template" : "export_name_backup");
|
||||
this.deps.download(`nextfloor-${kind}-${this.deps.today()}.json`, JSON.stringify(exportFile(this.host.doc, shareable), null, 2));
|
||||
}
|
||||
|
||||
/** Reads a plan file chosen by the user. The current plan stays available as a restore point. */
|
||||
async importPlan(file: File | undefined): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
if (!file || !hass) return;
|
||||
let building: Building;
|
||||
let question = t("backup_import_confirm");
|
||||
try {
|
||||
if (/\.sh3d$/i.test(file.name)) {
|
||||
// a plan from Sweet Home 3D: rooms, doors, windows and free walls; its furniture stays behind
|
||||
const result = await importSweetHome(new Uint8Array(await file.arrayBuffer()));
|
||||
building = result.building;
|
||||
question = `${t("import_sh3d_found", { ...result.report })}\n\n${question}`;
|
||||
} else if (/\.ifc$/i.test(file.name)) {
|
||||
// a BIM model: storeys as floors, spaces as rooms
|
||||
const result = importIfc(await file.text());
|
||||
building = result.building;
|
||||
question = `${t("import_ifc_found", { floors: result.report.floors, rooms: result.report.rooms })}\n\n${question}`;
|
||||
} else if (/\.dxf$/i.test(file.name)) {
|
||||
// a CAD drawing: closed polylines become rooms, lines free walls
|
||||
const result = importDxf(await file.text());
|
||||
building = result.building;
|
||||
question = `${t("import_dxf_found", { rooms: result.report.rooms, walls: result.report.walls })}\n\n${question}`;
|
||||
} else {
|
||||
const text = await file.text();
|
||||
let json: unknown = null;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
/* parseExport reports it */
|
||||
}
|
||||
if (isRoomPlan(json)) {
|
||||
// an Apple RoomPlan scan (iPhone or iPad with LiDAR): walls, doors, windows and a few objects
|
||||
const result = importRoomPlan(json);
|
||||
building = result.building;
|
||||
question = `${t("import_roomplan_found", { rooms: result.report.rooms, openings: result.report.openings, skipped: result.report.furniture })}\n\n${question}`;
|
||||
} else building = parseExport(text);
|
||||
}
|
||||
} catch (err) {
|
||||
const code = (err as Error).message;
|
||||
const known: Record<string, string> = { not_json: "import_error_not_json", not_plan: "import_error_not_plan", not_zip: "import_error_sh3d", sh3d_no_xml: "import_error_sh3d", sh3d_empty: "import_error_sh3d_empty", dxf_empty: "import_error_dxf_empty", ifc_empty: "import_error_ifc_empty", roomplan_empty: "import_error_roomplan_empty" };
|
||||
this.deps.alert(known[code] ? t(known[code] as I18nKey) : t("backup_import_error", { error: code }));
|
||||
return;
|
||||
}
|
||||
if (!this.deps.confirm(question)) return;
|
||||
await this.deps.api.takeSnapshot(hass).catch(() => undefined);
|
||||
this.host.adopt(building);
|
||||
this.host.say(t("backup_imported"));
|
||||
}
|
||||
|
||||
/** Everything in one file: the plan, every stored picture, and the packs. */
|
||||
async exportFull(): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
if (!hass) return;
|
||||
this.busy = true;
|
||||
this.host.refresh();
|
||||
try {
|
||||
const base = await this.deps.api.fetchBackup(hass);
|
||||
const images: Record<string, string> = {};
|
||||
for (const id of storedImageIds(base.building)) {
|
||||
// a picture that cannot be read is left out
|
||||
await this.deps.api.fetchImage(hass, id).then((data) => (images[id] = data), () => undefined);
|
||||
}
|
||||
this.deps.download(`nextfloor-${t("export_name_full")}-${this.deps.today()}.json`, JSON.stringify({ ...base, exported_at: new Date().toISOString(), images }));
|
||||
} catch (err) {
|
||||
this.deps.alert(t("backup_import_error", { error: errorText(err) }));
|
||||
} finally {
|
||||
this.busy = false;
|
||||
this.host.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
async importFull(file: File | undefined): Promise<void> {
|
||||
const { hass, t } = this.host;
|
||||
if (!file || !hass) return;
|
||||
let data: BackupFile;
|
||||
try {
|
||||
data = JSON.parse(await file.text()) as BackupFile;
|
||||
} catch {
|
||||
this.deps.alert(t("import_error_not_json"));
|
||||
return;
|
||||
}
|
||||
if (data?.format !== "nextfloor-backup" || !data.building) {
|
||||
this.deps.alert(t("backup_full_not_backup"));
|
||||
return;
|
||||
}
|
||||
if (!this.deps.confirm(t("backup_full_confirm"))) return;
|
||||
this.busy = true;
|
||||
this.host.refresh();
|
||||
try {
|
||||
const result = await this.deps.api.restoreBackup(hass, data.building, data.packs ?? []);
|
||||
let pictures = 0;
|
||||
for (const [id, picture] of Object.entries(data.images ?? {})) {
|
||||
// a picture that cannot be stored is skipped
|
||||
await this.deps.api.storeImage(hass, id, picture).then(() => pictures++, () => undefined);
|
||||
}
|
||||
this.host.adopt(normalizeBuilding(result.building));
|
||||
this.host.packsChanged();
|
||||
const skipped = result.skipped.length > 0 ? ` ${t("backup_full_skipped", { packs: result.skipped.map((s) => s.id).join(", ") })}` : "";
|
||||
this.host.say(t("backup_full_restored", { packs: result.packs, pictures }) + skipped);
|
||||
} catch (err) {
|
||||
const { code, message } = (err ?? {}) as { code?: string; message?: string };
|
||||
this.deps.alert(t("backup_import_error", { error: message ?? code ?? String(err) }));
|
||||
} finally {
|
||||
this.busy = false;
|
||||
this.host.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
// Locating a Bluetooth tag by room, learned by walking: choose a tag (a Bluetooth address, or a Private BLE Device tracker for a phone or
|
||||
// watch), then walk through each room with it and record the room. The signals every scanner of Home Assistant (ESPHome proxies, Shelly
|
||||
// devices with Bluetooth scanning, the host's adapters) hears are kept as fingerprints; the backend sensor compares them with the live
|
||||
// signals. The editor only reads what the scanners report and shows "now: kitchen" while you walk.
|
||||
|
||||
import { LitElement, html, nothing, type PropertyValues } from "lit";
|
||||
import { uid, type BleFingerprint, type BleTag } from "../../model.ts";
|
||||
import { fingerprintsOf, locate, RECORD_SECONDS, replaceRoom, signalLevel, type Reading } from "./ops/ble.ts";
|
||||
import type { EditorHost } from "./host.ts";
|
||||
|
||||
interface Scan {
|
||||
address: string | null;
|
||||
available: boolean;
|
||||
readings: Record<string, { name: string; rssi: number }>;
|
||||
}
|
||||
|
||||
interface Discovered {
|
||||
available: boolean;
|
||||
scanners: { source: string; name: string }[];
|
||||
devices: { address: string; name: string; rssi: number; named: boolean }[];
|
||||
}
|
||||
|
||||
const POLL_MS = 1500;
|
||||
|
||||
export class NfBleLocate extends LitElement {
|
||||
static properties = {
|
||||
host: { attribute: false },
|
||||
doc: { attribute: false },
|
||||
_found: { state: true },
|
||||
_pick: { state: true },
|
||||
_name: { state: true },
|
||||
_tag: { state: true },
|
||||
_room: { state: true },
|
||||
_scan: { state: true },
|
||||
_samples: { state: true },
|
||||
_error: { state: true },
|
||||
};
|
||||
declare host: EditorHost;
|
||||
/** The plan: a new one after every change makes this draw again. */
|
||||
declare doc: unknown;
|
||||
private declare _found: Discovered | null;
|
||||
private declare _pick: string;
|
||||
private declare _name: string;
|
||||
private declare _tag: string | null;
|
||||
private declare _room: string;
|
||||
private declare _scan: Scan | null;
|
||||
/** The samples of the recording in progress (null = not recording). */
|
||||
private declare _samples: Reading[] | null;
|
||||
private declare _error: string;
|
||||
private timer = 0;
|
||||
private recordStarted = 0;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._found = null;
|
||||
this._pick = "";
|
||||
this._name = "";
|
||||
this._tag = null;
|
||||
this._room = "";
|
||||
this._scan = null;
|
||||
this._samples = null;
|
||||
this._error = "";
|
||||
}
|
||||
|
||||
// the editor's styles apply to this element's content
|
||||
protected createRenderRoot(): HTMLElement {
|
||||
return this;
|
||||
}
|
||||
|
||||
private get tags(): BleTag[] {
|
||||
return this.host.doc.settings.ble?.tags ?? [];
|
||||
}
|
||||
|
||||
private get rooms(): { id: string; label: string }[] {
|
||||
const floors = this.host.doc.floors;
|
||||
return floors.flatMap((f) => f.rooms.map((r) => ({ id: r.id, label: floors.length > 1 ? `${f.name} · ${r.name}` : r.name })));
|
||||
}
|
||||
|
||||
connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
void this.loadDevices();
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
window.clearInterval(this.timer);
|
||||
}
|
||||
|
||||
protected updated(changed: PropertyValues): void {
|
||||
if (changed.has("_tag")) this.restartPolling();
|
||||
}
|
||||
|
||||
private async loadDevices(): Promise<void> {
|
||||
try {
|
||||
this._found = await this.host.hass!.callWS<Discovered>({ type: "nextfloor/ble/devices" });
|
||||
} catch (e) {
|
||||
this._error = String((e as { message?: string })?.message ?? e);
|
||||
}
|
||||
}
|
||||
|
||||
private restartPolling(): void {
|
||||
window.clearInterval(this.timer);
|
||||
this._scan = null;
|
||||
if (!this._tag) return;
|
||||
const poll = () => void this.pollOnce();
|
||||
poll();
|
||||
this.timer = window.setInterval(poll, POLL_MS);
|
||||
}
|
||||
|
||||
private async pollOnce(): Promise<void> {
|
||||
const tag = this.tags.find((t) => t.id === this._tag);
|
||||
if (!tag || !this.host.hass) return;
|
||||
try {
|
||||
const scan = await this.host.hass.callWS<Scan>({ type: "nextfloor/ble/scan", ...(tag.entity ? { entity: tag.entity } : { address: tag.address }) });
|
||||
this._scan = scan;
|
||||
this._error = "";
|
||||
if (this._samples) {
|
||||
this._samples = [...this._samples, Object.fromEntries(Object.entries(scan.readings).map(([src, r]) => [src, r.rssi]))];
|
||||
if (Date.now() - this.recordStarted >= RECORD_SECONDS * 1000) this.finishRecording(tag, scan);
|
||||
}
|
||||
} catch (e) {
|
||||
this._error = String((e as { message?: string })?.message ?? e);
|
||||
}
|
||||
}
|
||||
|
||||
private reading(): Reading {
|
||||
return Object.fromEntries(Object.entries(this._scan?.readings ?? {}).map(([src, r]) => [src, r.rssi]));
|
||||
}
|
||||
|
||||
private startRecording(): void {
|
||||
if (!this._room) return;
|
||||
this.recordStarted = Date.now();
|
||||
this._samples = [];
|
||||
}
|
||||
|
||||
private finishRecording(tag: BleTag, scan: Scan): void {
|
||||
const samples = this._samples ?? [];
|
||||
this._samples = null;
|
||||
const fresh = fingerprintsOf(this._room, samples);
|
||||
if (fresh.length === 0) return;
|
||||
const names = Object.fromEntries(Object.entries(scan.readings).map(([src, r]) => [src, r.name]));
|
||||
this.update2(tag.id, (t) => {
|
||||
t.prints = replaceRoom(t.prints, this._room, fresh);
|
||||
t.scanners = { ...(t.scanners ?? {}), ...names };
|
||||
});
|
||||
}
|
||||
|
||||
private update2(id: string, mutate: (tag: BleTag) => void): void {
|
||||
this.host.change((d) => {
|
||||
const tag = d.settings.ble?.tags.find((t) => t.id === id);
|
||||
if (tag) mutate(tag);
|
||||
});
|
||||
}
|
||||
|
||||
private addTag(): void {
|
||||
const pick = this._pick;
|
||||
if (!pick) return;
|
||||
const entity = pick.startsWith("device_tracker.");
|
||||
const known = this._found?.devices.find((d) => d.address === pick);
|
||||
const name = this._name.trim() || known?.name || this.host.hass?.states[pick]?.attributes.friendly_name || pick;
|
||||
const tag: BleTag = { id: uid("ble"), name: String(name).slice(0, 60), prints: [], ...(entity ? { entity: pick } : { address: pick }) };
|
||||
this.host.change((d) => {
|
||||
d.settings.ble = { tags: [...(d.settings.ble?.tags ?? []), tag] };
|
||||
});
|
||||
this._tag = tag.id;
|
||||
this._pick = "";
|
||||
this._name = "";
|
||||
}
|
||||
|
||||
private removeTag(id: string): void {
|
||||
this.host.change((d) => {
|
||||
const tags = (d.settings.ble?.tags ?? []).filter((t) => t.id !== id);
|
||||
d.settings.ble = tags.length ? { tags } : null;
|
||||
});
|
||||
if (this._tag === id) this._tag = null;
|
||||
}
|
||||
|
||||
private bars(tag: BleTag) {
|
||||
const t = this.host.t;
|
||||
const scan = this._scan;
|
||||
const entries = Object.entries(scan?.readings ?? {}).sort((a, b) => b[1].rssi - a[1].rssi);
|
||||
return html`<div class="nf-ble-bars">
|
||||
${entries.length === 0
|
||||
? html`<p class="nf-sub">${scan && !scan.available ? t("ble_unavailable") : scan?.address === null && tag.entity ? t("ble_no_address") : t("ble_none_heard")}</p>`
|
||||
: entries.map(([src, r]) => html`<div class="nf-ble-row" title=${src}>
|
||||
<span class="nf-ble-name">${r.name}</span>
|
||||
<span class="nf-ble-track"><span class="nf-ble-fill" style="width:${Math.round(signalLevel(r.rssi) * 100)}%"></span></span>
|
||||
<span class="nf-ble-db">${Math.round(r.rssi)}</span>
|
||||
</div>`)}
|
||||
${entries.length === 1 ? html`<p class="nf-sub">${t("ble_one_scanner")}</p>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private learn(tag: BleTag) {
|
||||
const t = this.host.t;
|
||||
const rooms = this.rooms;
|
||||
const now = locate(tag.prints, this.reading());
|
||||
const roomLabel = (id: string | null) => rooms.find((r) => r.id === id)?.label ?? null;
|
||||
const count = (room: string) => tag.prints.filter((p: BleFingerprint) => p.room === room).length;
|
||||
const recording = this._samples !== null;
|
||||
const left = recording ? Math.max(0, RECORD_SECONDS - Math.round((Date.now() - this.recordStarted) / 1000)) : 0;
|
||||
return html`${this.bars(tag)}
|
||||
<p class="nf-ble-now"><b>${t("ble_now")}:</b> ${now.room ? roomLabel(now.room) : t("ble_unknown")}</p>
|
||||
<div class="nf-form">
|
||||
<label class="nf-field nf-wide">${t("ble_learn_room")}
|
||||
<select ?disabled=${recording} .value=${this._room} @change=${(e: Event) => (this._room = (e.target as HTMLSelectElement).value)}>
|
||||
<option value="">–</option>
|
||||
${rooms.map((r) => html`<option value=${r.id} ?selected=${this._room === r.id}>${r.label}${count(r.id) ? ` ✓ ${count(r.id)}` : ""}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn nf-primary" ?disabled=${!this._room || recording || Object.keys(this._scan?.readings ?? {}).length === 0} @click=${() => this.startRecording()}>
|
||||
${recording ? t("ble_recording", { s: left }) : t("ble_record", { s: RECORD_SECONDS })}
|
||||
</button>
|
||||
${this._room && count(this._room) ? html`<button class="nf-btn" ?disabled=${recording} @click=${() => this.update2(tag.id, (x) => (x.prints = x.prints.filter((p) => p.room !== this._room)))}>${t("ble_forget_room")}</button>` : nothing}
|
||||
</div>
|
||||
<p class="nf-sub">${t("ble_learn_hint")}</p>`;
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const t = this.host.t;
|
||||
const tags = this.tags;
|
||||
const used = new Set(tags.flatMap((x) => [x.address ?? "", x.entity ?? ""]));
|
||||
const trackers = Object.entries(this.host.hass?.states ?? {})
|
||||
.filter(([id, s]) => id.startsWith("device_tracker.") && typeof s.attributes.current_address === "string" && !used.has(id))
|
||||
.map(([id, s]) => [id, String(s.attributes.friendly_name ?? id)] as const);
|
||||
const devices = (this._found?.devices ?? []).filter((d) => !used.has(d.address));
|
||||
const scanners = this._found?.scanners.length ?? 0;
|
||||
const tag = tags.find((x) => x.id === this._tag) ?? null;
|
||||
return html`
|
||||
${this._found && !this._found.available ? html`<p class="nf-sub">${t("ble_unavailable")}</p>` : html`<p class="nf-sub">${t("ble_scanners", { n: scanners })}</p>`}
|
||||
${this._error ? html`<p class="nf-sub">${this._error}</p>` : nothing}
|
||||
${tags.map(
|
||||
(x) => html`<div class="nf-row nf-dev-row">
|
||||
<span class="nf-dev-name"><span>${x.name}</span><small>${x.entity ?? x.address} · ${t("ble_spots", { n: x.prints.length })}</small></span>
|
||||
<button class="nf-btn" @click=${() => (this._tag = this._tag === x.id ? null : x.id)}>${this._tag === x.id ? t("ble_close") : t("ble_learn")}</button>
|
||||
<button class="nf-btn" title=${t("delete")} @click=${() => this.removeTag(x.id)}>✕</button>
|
||||
</div>`,
|
||||
)}
|
||||
${tag ? html`<div class="nf-ble-learn">${this.learn(tag)}<p class="nf-sub">${t("ble_sensor_hint", { name: tag.name })}</p></div>` : nothing}
|
||||
<div class="nf-form">
|
||||
<label class="nf-field nf-wide">${t("ble_add")}
|
||||
<select .value=${this._pick} @change=${(e: Event) => (this._pick = (e.target as HTMLSelectElement).value)}>
|
||||
<option value="">–</option>
|
||||
${trackers.length ? html`<optgroup label=${t("ble_trackers")}>${trackers.map(([id, name]) => html`<option value=${id}>${name}</option>`)}</optgroup>` : nothing}
|
||||
<optgroup label=${t("ble_devices")}>${devices.map((d) => html`<option value=${d.address}>${d.named ? d.name : d.address} · ${d.address} · ${d.rssi} dBm</option>`)}</optgroup>
|
||||
</select>
|
||||
</label>
|
||||
<label class="nf-field nf-wide">${t("ble_name")}
|
||||
<input type="text" maxlength="60" .value=${this._name} @input=${(e: Event) => (this._name = (e.target as HTMLInputElement).value)} />
|
||||
</label>
|
||||
</div>
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn" @click=${() => void this.loadDevices()}>${t("ble_refresh")}</button>
|
||||
<button class="nf-btn nf-primary" ?disabled=${!this._pick || tags.length >= 10} @click=${() => this.addTag()}>${t("ble_add_button")}</button>
|
||||
</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!customElements.get("nf-ble-locate")) customElements.define("nf-ble-locate", NfBleLocate);
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"nf-ble-locate": NfBleLocate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import type { Floor } from "../../../model.ts";
|
||||
import type { BackgroundTool } from "../background-tool.ts";
|
||||
import type { CanvasContext } from "./context.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
/** The turn handle: a circle above the middle of the picture's top edge. */
|
||||
function turnHandle(x: number, y: number, width: number): TemplateResult {
|
||||
const [hx, hy] = [x + width / 2, y - 30];
|
||||
return svg`<g class="nf-rotate" data-bg-rotate="1">
|
||||
<line x1=${hx} y1=${y} x2=${hx} y2=${hy} />
|
||||
<circle cx=${hx} cy=${hy} r="16" class="nf-hit" />
|
||||
<circle cx=${hx} cy=${hy} r="8" />
|
||||
<path d="M${hx - 4} ${hy - 1}a4 4 0 1 1 2 3.5" />
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/** The two points (or the first) tapped for straightening or measuring, with the line between them. */
|
||||
function calibrationMarks(ctx: CanvasContext, tool: BackgroundTool): Layer {
|
||||
const points = tool.level?.length ? tool.level : tool.ruler;
|
||||
if (!points?.length) return nothing;
|
||||
const screen = points.map((p) => ctx.toScreen(p));
|
||||
return svg`<g class="nf-bg-ruler">
|
||||
${screen.length === 2 ? svg`<line x1=${screen[0][0]} y1=${screen[0][1]} x2=${screen[1][0]} y2=${screen[1][1]} />` : nothing}
|
||||
${screen.map(([x, y]) => svg`<circle cx=${x} cy=${y} r="6" />`)}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The picture behind the plan. While it can be edited it takes the pointer (a drag moves it), its lower right corner scales it, and a
|
||||
* handle above it turns it.
|
||||
*/
|
||||
export function backgroundLayer(ctx: CanvasContext, tool: BackgroundTool, floor: Floor | undefined): Layer {
|
||||
const bg = floor?.background;
|
||||
const picture = tool.picture(bg?.image_id);
|
||||
if (!bg || !picture) return nothing;
|
||||
const [x, y] = ctx.toScreen([bg.x, bg.z]);
|
||||
const width = bg.width * ctx.scale;
|
||||
const height = width * picture.aspect;
|
||||
const editing = tool.handlesShown;
|
||||
return svg`<g transform="rotate(${bg.rotation ?? 0} ${x + width / 2} ${y + height / 2})">
|
||||
<image href=${picture.url} x=${x} y=${y} width=${width} height=${height} opacity=${bg.opacity} preserveAspectRatio="none" pointer-events=${editing ? "auto" : "none"} data-bg="1" style=${editing ? "cursor:move" : ""} />
|
||||
${editing
|
||||
? svg`<rect class="nf-bg-frame" x=${x} y=${y} width=${width} height=${height} />
|
||||
<circle class="nf-bg-handle" data-bg-handle="1" cx=${x + width} cy=${y + height} r="9" />
|
||||
${turnHandle(x, y, width)}`
|
||||
: nothing}
|
||||
</g>${calibrationMarks(ctx, tool)}`;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import type { Vec2 } from "../../../model.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
/** What the layers drawn over the plan need: the host, the map from plan to screen, and which floor is shown. */
|
||||
export interface CanvasContext {
|
||||
host: EditorHost;
|
||||
toScreen(p: Vec2): [number, number];
|
||||
toWorld(x: number, y: number): Vec2;
|
||||
/** Pixels per metre. */
|
||||
scale: number;
|
||||
floorId: string | null;
|
||||
/** Asks for another drawing (a map tile has arrived). */
|
||||
redraw: () => void;
|
||||
}
|
||||
|
||||
/** An SVG points attribute for plan points. */
|
||||
export const pointsAttribute = (ctx: CanvasContext, points: readonly Vec2[]): string => points.map((p) => ctx.toScreen(p).join(",")).join(" ");
|
||||
|
||||
/**
|
||||
* The "+" in the middle of an edge: pressing it adds a corner there. Left out when the edge is too short on the screen to hold it.
|
||||
* The editor reads `data-plus="<kind>:<id>:<edge>"` (kind "out" for an outdoor area, "roof" for a flat roof).
|
||||
*/
|
||||
export function edgePlus(ctx: CanvasContext, a: Vec2, b: Vec2, kind: "out" | "roof", id: string, edge: number): TemplateResult | typeof nothing {
|
||||
const [[ax, ay], [bx, by]] = [ctx.toScreen(a), ctx.toScreen(b)];
|
||||
if (Math.hypot(bx - ax, by - ay) <= 36) return nothing;
|
||||
const [mx, my] = [(ax + bx) / 2, (ay + by) / 2];
|
||||
return svg`<g data-plus=${`${kind}:${id}:${edge}`} class="nf-mid"><circle cx=${mx} cy=${my} r="14" class="nf-hit" /><circle cx=${mx} cy=${my} r="6" /><path d="M${mx - 3} ${my}h6M${mx} ${my - 3}v6" /></g>`;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// What is being drawn right now: the wall or rectangle being dragged, the outline or chain of lengths being laid out, and the snap
|
||||
// guides with the point they snap to.
|
||||
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import type { Vec2 } from "../../../model.ts";
|
||||
import type { CanvasContext } from "./context.ts";
|
||||
import { formatLength } from "../../../units.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
/** The lines that show what the pointer snaps to: a vertical, a horizontal, and the point itself. */
|
||||
export interface Guides {
|
||||
point?: Vec2;
|
||||
x?: number;
|
||||
z?: number;
|
||||
}
|
||||
|
||||
/** A gesture in progress that draws a shape. */
|
||||
export type Sketch = { kind: "freewall"; start: Vec2; end: Vec2 } | { kind: "rect"; start: Vec2; end: Vec2 };
|
||||
|
||||
const metres = (ctx: CanvasContext, v: number) => formatLength(ctx.host.hass, v);
|
||||
|
||||
export function sketchLayer(ctx: CanvasContext, sketch: Sketch): TemplateResult {
|
||||
const [a, b] = [ctx.toScreen(sketch.start), ctx.toScreen(sketch.end)];
|
||||
if (sketch.kind === "freewall") {
|
||||
const length = Math.hypot(sketch.end[0] - sketch.start[0], sketch.end[1] - sketch.start[1]);
|
||||
return svg`<g pointer-events="none">
|
||||
<line class="nf-draft nf-draft-wall" x1=${a[0]} y1=${a[1]} x2=${b[0]} y2=${b[1]} />
|
||||
<text class="nf-dim" x=${(a[0] + b[0]) / 2} y=${(a[1] + b[1]) / 2 - 10}>${metres(ctx, length)}</text>
|
||||
</g>`;
|
||||
}
|
||||
const [width, depth] = [Math.abs(sketch.end[0] - sketch.start[0]), Math.abs(sketch.end[1] - sketch.start[1])];
|
||||
return svg`<g pointer-events="none">
|
||||
<rect class="nf-draft" x=${Math.min(a[0], b[0])} y=${Math.min(a[1], b[1])} width=${Math.abs(b[0] - a[0])} height=${Math.abs(b[1] - a[1])} />
|
||||
<text class="nf-dim" x=${(a[0] + b[0]) / 2} y=${Math.min(a[1], b[1]) - 8}>${metres(ctx, width)} × ${metres(ctx, depth)}</text>
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/** The outline being clicked together (free form) or the chain of lengths being measured: points, a line to the cursor, and lengths. */
|
||||
export function outlineLayer(ctx: CanvasContext, draft: readonly Vec2[], cursor: Vec2 | null, measuring: boolean): TemplateResult {
|
||||
const screen = [...draft, ...(cursor ? [cursor] : [])].map((p) => ctx.toScreen(p));
|
||||
const closable = draft.length >= 3;
|
||||
const lengths = measuring
|
||||
? draft.slice(1).map((p, i) => {
|
||||
const [a, b] = [ctx.toScreen(draft[i]), ctx.toScreen(p)];
|
||||
return svg`<text class="nf-dim" x=${(a[0] + b[0]) / 2} y=${(a[1] + b[1]) / 2 - 6}>${metres(ctx, Math.hypot(p[0] - draft[i][0], p[1] - draft[i][1]))}</text>`;
|
||||
})
|
||||
: nothing;
|
||||
const points = draft.map((p, i) => {
|
||||
const [x, y] = ctx.toScreen(p);
|
||||
const first = i === 0 && closable;
|
||||
return svg`<circle class=${first ? "nf-draft-pt nf-draft-first" : "nf-draft-pt"} cx=${x} cy=${y} r=${first ? 9 : 5} />`;
|
||||
});
|
||||
const [cx, cy] = cursor ? ctx.toScreen(cursor) : [0, 0];
|
||||
return svg`<g pointer-events="none">
|
||||
${screen.length > 1 ? svg`<polyline class="nf-draft" points=${screen.map((p) => p.join(",")).join(" ")} />` : nothing}
|
||||
${lengths}${points}
|
||||
${cursor ? svg`<circle class="nf-cursor" cx=${cx} cy=${cy} r="4" />` : nothing}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
export function guidesLayer(ctx: CanvasContext, guides: Guides, size: { w: number; h: number }): TemplateResult {
|
||||
const column = guides.x !== undefined ? ctx.toScreen([guides.x, 0])[0] : null;
|
||||
const row = guides.z !== undefined ? ctx.toScreen([0, guides.z])[1] : null;
|
||||
const [px, py] = guides.point ? ctx.toScreen(guides.point) : [0, 0];
|
||||
return svg`<g pointer-events="none">
|
||||
${column !== null ? svg`<line class="nf-guide" x1=${column} y1="0" x2=${column} y2=${size.h} />` : nothing}
|
||||
${row !== null ? svg`<line class="nf-guide" x1="0" y1=${row} x2=${size.w} y2=${row} />` : nothing}
|
||||
${guides.point ? svg`<circle class="nf-snap" cx=${px} cy=${py} r="9" />` : nothing}
|
||||
</g>`;
|
||||
}
|
||||
|
||||
export function draftLayer(ctx: CanvasContext, sketch: Sketch | null, tool: string, draft: readonly Vec2[], cursor: Vec2 | null): Layer {
|
||||
if (sketch) return sketchLayer(ctx, sketch);
|
||||
if (tool !== "polygon" && tool !== "measure") return nothing;
|
||||
return outlineLayer(ctx, draft, cursor, tool === "measure");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Furniture } from "../../../model.ts";
|
||||
import { box, entity, floorWith, hassOf } from "../../../entities/fixtures.ts";
|
||||
import { lampLit } from "./items.ts";
|
||||
|
||||
const lamp = (extra: Partial<Furniture> = {}): Furniture => ({ id: "l", type: "lamp_table", x: 1, z: 1, rotation: 0, w: 0.3, d: 0.3, h: 0.5, variant: null, entity: null, power: null, ...extra });
|
||||
const room = box("r", 0, 0, 4, 3, "area");
|
||||
|
||||
test("a lamp lights up in the plan with a light found in its room, not only one set by hand (#111)", () => {
|
||||
const on = hassOf([entity("light.table", "on")], { "light.table": { area_id: "area" } });
|
||||
assert.equal(lampLit(on, floorWith([room], { furniture: [lamp()] }), lamp()), true);
|
||||
const off = hassOf([entity("light.table", "off")], { "light.table": { area_id: "area" } });
|
||||
assert.equal(lampLit(off, floorWith([room], { furniture: [lamp()] }), lamp()), false);
|
||||
});
|
||||
|
||||
test("a lamp lights up with a further light while its main light is off, and 'none' stays dark", () => {
|
||||
const hass = hassOf([entity("light.main", "off"), entity("light.night", "on")]);
|
||||
const piece = lamp({ entity: "light.main", extra_lights: ["light.night"] });
|
||||
assert.equal(lampLit(hass, floorWith([room], { furniture: [piece] }), piece), true);
|
||||
const none = lamp({ entity: "none" });
|
||||
assert.equal(lampLit(hassOf([entity("light.table", "on")], { "light.table": { area_id: "area" } }), floorWith([room], { furniture: [none] }), none), false);
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// Furniture and devices in the plan: each piece with its symbol, the handles of the selected one, and the camera's field of view.
|
||||
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import { entityKind, entityName, kindOf } from "../../../devices.ts";
|
||||
import { pluginDrawsWedge } from "../../../plugins/registry.ts";
|
||||
import { furnitureName } from "../../../furniture-names.ts";
|
||||
import { iconPath } from "../../../icons.ts";
|
||||
import { deviceIcon } from "../fields.ts";
|
||||
import { ENERGY_DEVICES, isLamp, noteDue, type Floor, type Furniture, type Placement } from "../../../model.ts";
|
||||
import { furnitureSymbol } from "../../furniture2d.ts";
|
||||
import { drawOrder } from "../ops/items.ts";
|
||||
import type { CanvasContext } from "./context.ts";
|
||||
import { formatLength } from "../../../units.ts";
|
||||
import { furnitureEntities } from "../../../entities/furniture-links.ts";
|
||||
import { fixtureGlow } from "../../../entities/kinds.ts";
|
||||
import type { HomeAssistant } from "../../../types.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
/** The turn handle: a small circle on a stem, with a turning arrow. */
|
||||
const turnHandle = (attribute: "data-rotate" | "data-aim", id: string, from: [number, number], to: [number, number]): TemplateResult => {
|
||||
const [hx, hy] = to;
|
||||
const arrow = svg`<path d="M${hx - 4} ${hy - 1}a4 4 0 1 1 2 3.5" />`;
|
||||
const stem = svg`<line x1=${from[0]} y1=${from[1]} x2=${hx} y2=${hy} /><circle cx=${hx} cy=${hy} r="16" class="nf-hit" /><circle cx=${hx} cy=${hy} r="8" />${arrow}`;
|
||||
return attribute === "data-rotate" ? svg`<g class="nf-rotate" data-rotate=${id}>${stem}</g>` : svg`<g class="nf-rotate" data-aim=${id}>${stem}</g>`;
|
||||
};
|
||||
|
||||
/** The four corner handles that resize a piece of furniture. */
|
||||
function resizeHandles(ctx: CanvasContext, item: Furniture): TemplateResult[] {
|
||||
const a = item.rotation * RAD;
|
||||
return ([[-1, -1], [1, -1], [1, 1], [-1, 1]] as const).map(([sx, sz]) => {
|
||||
const [x, y] = ctx.toScreen([item.x + (sx * item.w * Math.cos(a)) / 2 - (sz * item.d * Math.sin(a)) / 2, item.z + (sx * item.w * Math.sin(a)) / 2 + (sz * item.d * Math.cos(a)) / 2]);
|
||||
return svg`<g class="nf-resize" data-resize=${`${item.id}:${sx}:${sz}`}><circle cx=${x} cy=${y} r="14" class="nf-hit" /><rect x=${x - 5} y=${y - 5} width="10" height="10" rx="2" /></g>`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Auto-linked entities per floor, worked out again only when the floor or the states change (a drag redraws often). */
|
||||
const linkCache = new WeakMap<Floor, { states: unknown; links: ReturnType<typeof furnitureEntities> }>();
|
||||
function floorLinks(hass: HomeAssistant, floor: Floor): ReturnType<typeof furnitureEntities> {
|
||||
const hit = linkCache.get(floor);
|
||||
if (hit && hit.states === hass.states) return hit.links;
|
||||
const links = furnitureEntities(hass, [floor]);
|
||||
linkCache.set(floor, { states: hass.states, links });
|
||||
return links;
|
||||
}
|
||||
|
||||
/** A lamp lights up in the plan as in 3D: with its light set by hand or found in the room, or with one of its further lights (#111). */
|
||||
export function lampLit(hass: HomeAssistant | undefined, floor: Floor, item: Furniture): boolean {
|
||||
if (!hass || !isLamp(item.type)) return false;
|
||||
const main = floorLinks(hass, floor).get(item.id)?.entity;
|
||||
return !!fixtureGlow(main ? hass.states[main] : undefined, (item.extra_lights ?? []).map((id) => hass.states[id]));
|
||||
}
|
||||
|
||||
export function furnitureLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null): Layer {
|
||||
const { host, scale } = ctx;
|
||||
const one = (item: Furniture) => {
|
||||
const selected = item.id === selectedId;
|
||||
const movable = selected && host.admin && !item.locked;
|
||||
const [cx, cy] = ctx.toScreen([item.x, item.z]);
|
||||
const a = item.rotation * RAD;
|
||||
const labelled = Math.min(item.w, item.d) * scale > 44;
|
||||
const lit = lampLit(host.hass, floor, item);
|
||||
const energy = (ENERGY_DEVICES as readonly string[]).includes(item.type);
|
||||
const klass = `nf-furn${selected ? " nf-furn-sel" : ""}${lit ? " nf-furn-lit" : ""}${energy ? " nf-energy-item" : ""}`;
|
||||
// the handle sits in front of the piece, and dragging it turns the piece
|
||||
const reach = item.d / 2 + Math.max(0.3, 26 / scale);
|
||||
const handleAt = ctx.toScreen([item.x - Math.sin(a) * reach, item.z + Math.cos(a) * reach]);
|
||||
const stemFrom = ctx.toScreen([item.x - Math.sin(a) * (item.d / 2), item.z + Math.cos(a) * (item.d / 2)]);
|
||||
// the size is written behind the piece, away from the turn handle
|
||||
const [lx, ly] = ctx.toScreen([item.x + Math.sin(a) * (item.d / 2 + 18 / scale), item.z - Math.cos(a) * (item.d / 2 + 18 / scale)]);
|
||||
return svg`<g data-furniture=${item.id} class=${klass}>
|
||||
<g transform="translate(${cx} ${cy}) rotate(${item.rotation}) scale(${item.mirror ? -scale : scale} ${scale})">
|
||||
<rect class="nf-furn-body" x=${-item.w / 2} y=${-item.d / 2} width=${item.w} height=${item.d} />
|
||||
<g class="nf-furn-sym">${furnitureSymbol(item.type, item.w, item.d, item)}</g>
|
||||
<line class="nf-furn-front" x1=${-item.w / 2} y1=${item.d / 2} x2=${item.w / 2} y2=${item.d / 2} />
|
||||
</g>
|
||||
${labelled ? svg`<text x=${cx} y=${cy + 4}>${furnitureName(host.hass, item.type)}</text>` : nothing}
|
||||
</g>
|
||||
${movable ? resizeHandles(ctx, item) : nothing}
|
||||
${selected ? svg`<text class="nf-dim" x=${lx} y=${ly + 4}>${formatLength(host.hass, item.w)} × ${formatLength(host.hass, item.d)}</text>` : nothing}
|
||||
${selected && item.locked ? svg`<text class="nf-lock" x=${handleAt[0]} y=${handleAt[1] + 5}>🔒</text>` : nothing}
|
||||
${movable ? turnHandle("data-rotate", item.id, stemFrom, handleAt) : nothing}`;
|
||||
};
|
||||
return svg`<g>${drawOrder(floor).map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** The device pins of the floor. */
|
||||
export function devicesLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null): Layer {
|
||||
const { host } = ctx;
|
||||
const one = (placed: Placement) => {
|
||||
// a plugin may take on entities NextFloor does not know (cameras)
|
||||
const kind = kindOf(placed.entity_id) ?? (host.hass ? entityKind(host.hass, placed.entity_id) : null);
|
||||
if (!kind) return nothing;
|
||||
const [x, y] = ctx.toScreen([placed.x, placed.z]);
|
||||
const on = host.hass?.states[placed.entity_id]?.state === "on";
|
||||
const selected = placed.entity_id === selectedId;
|
||||
// a device a plugin draws a wedge for can be turned by a handle in front of it
|
||||
const turn = (placed.rotation ?? 0) * RAD;
|
||||
const aim = selected && host.admin && !placed.locked && pluginDrawsWedge(placed.entity_id, host.hass?.states[placed.entity_id]);
|
||||
const handle: [number, number] = [x - Math.sin(turn) * 46, y + Math.cos(turn) * 46];
|
||||
const icon = deviceIcon(host, placed.entity_id, placed.icon);
|
||||
return svg`${aim ? turnHandle("data-aim", placed.entity_id, [x, y], handle) : nothing}<g data-device=${placed.entity_id} class=${`nf-device${on ? " nf-device-on" : ""}${selected ? " nf-device-sel" : ""}`} transform="translate(${x} ${y})">
|
||||
<title>${entityName(host.hass, placed.entity_id)}</title>
|
||||
<circle r="18" class="nf-hit" /><circle r="12" />
|
||||
${icon
|
||||
? svg`<foreignObject class="nf-device-icon" x="-8" y="-8" width="16" height="16"><ha-icon icon=${icon}></ha-icon></foreignObject>`
|
||||
: svg`<path d=${iconPath(kind)} transform="translate(-7.2 -7.2) scale(0.6)" />`}
|
||||
</g>
|
||||
${selected && placed.locked ? svg`<text class="nf-lock" x=${x + 16} y=${y - 12}>🔒</text>` : nothing}`;
|
||||
};
|
||||
return svg`<g>${floor.placements.map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** The notes of a floor: a small sticky note at its spot (orange once it is due), the selected one ringed. */
|
||||
export function notesLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null): Layer {
|
||||
return svg`${(floor.notes ?? []).map((note) => {
|
||||
const [x, y] = ctx.toScreen([note.x, note.z]);
|
||||
return svg`<g data-note=${note.id} class=${`nf-note${noteDue(note) ? " nf-note-due" : ""}${note.id === selectedId ? " nf-note-sel" : ""}`} transform="translate(${x} ${y})">
|
||||
<title>${note.text}</title>
|
||||
<rect x="-11" y="-11" width="22" height="22" rx="4" /><text y="5" text-anchor="middle">✎</text>
|
||||
</g>`;
|
||||
})}`;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import { mapLook, mapShown, mapTiles, templateOf, tileUrl } from "../../../map-geo.ts";
|
||||
import { tileObjectUrl } from "../../../tiles.ts";
|
||||
import type { BuildingSettings } from "../../../model.ts";
|
||||
import type { CanvasContext } from "./context.ts";
|
||||
|
||||
/**
|
||||
* The real map behind the plan: the tiles around the anchor in one group that is moved to the anchor and turned by the plan's north,
|
||||
* so a tile lies where it lies on Earth. Dimmed; the walls and rooms are drawn over it.
|
||||
*/
|
||||
export function mapLayer(ctx: CanvasContext, settings: BuildingSettings): TemplateResult | typeof nothing {
|
||||
const map = settings.map;
|
||||
if (!mapShown(map)) return nothing;
|
||||
const look = mapLook(map);
|
||||
const template = templateOf(map);
|
||||
const [ax, ay] = ctx.toScreen([look.x, look.z]);
|
||||
const k = ctx.scale;
|
||||
return svg`<g class="nf-map" opacity=${look.opacity} pointer-events="none" transform="translate(${ax} ${ay}) rotate(${settings.north ?? 0})">
|
||||
${mapTiles(map.lat, map.lon, look.zoom).map((tile) => ({ tile, href: tileObjectUrl(tileUrl(template, tile), ctx.redraw) })).filter((t) => t.href).map(({ tile, href }) => svg`<image href=${href} x=${tile.east * k} y=${-tile.north * k} width=${tile.size * k + 0.6} height=${tile.size * k + 0.6} preserveAspectRatio="none" />`)}
|
||||
</g>`;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Doors, windows and garage doors in the plan: a gap through the wall and a symbol in it (swinging leaves, panes, a garage track).
|
||||
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import { locateOpening, openingHost, pointOnRoomEdge, type Wall } from "../../../geometry/walls.ts";
|
||||
import { isFrontDoor, openingStyle, sidelightLayout, signedArea, type Floor, type Opening, type Room, type Vec2 } from "../../../model.ts";
|
||||
import type { CanvasContext } from "./context.ts";
|
||||
|
||||
type Sym = TemplateResult | TemplateResult[] | typeof nothing;
|
||||
|
||||
/** Where an opening sits: its two ends on the room edge, the direction into the room, and how far the wall reaches either side. */
|
||||
interface Frame {
|
||||
room: Room;
|
||||
edge: number;
|
||||
p0: Vec2;
|
||||
p1: Vec2;
|
||||
/** Into the room (outlines may run either way round), and which way round that is. */
|
||||
inward: Vec2;
|
||||
direction: 1 | -1;
|
||||
/** Wall thickness on the room's side and on the far side. */
|
||||
across: [number, number];
|
||||
exterior: boolean;
|
||||
/** A point of the edge moved `by` metres into the room (negative: out of it), in screen coordinates. */
|
||||
at(p: Vec2, by: number): [number, number];
|
||||
}
|
||||
|
||||
function frameOf(ctx: CanvasContext, o: Opening, floor: Floor, walls: readonly Wall[]): Frame | null {
|
||||
const host = openingHost(o, floor.rooms, floor.walls ?? []);
|
||||
if (!host) return null;
|
||||
const { room, edge } = host;
|
||||
const hit = locateOpening(walls as Wall[], o, host);
|
||||
const p0 = pointOnRoomEdge(room, edge, o.offset - o.width / 2);
|
||||
const p1 = pointOnRoomEdge(room, edge, o.offset + o.width / 2);
|
||||
const along: Vec2 = [(p1[0] - p0[0]) / (o.width || 1), (p1[1] - p0[1]) / (o.width || 1)];
|
||||
const direction = signedArea(room.points) >= 0 ? 1 : -1;
|
||||
const inward: Vec2 = [-along[1] * direction, along[0] * direction];
|
||||
let across: [number, number] = [0.06, 0.06];
|
||||
if (hit) across = hit.wall.free || hit.wall.roomLeft === room.id ? [hit.wall.left, hit.wall.right] : [hit.wall.right, hit.wall.left];
|
||||
return { room, edge, p0, p1, inward, direction, across, exterior: hit?.wall.exterior ?? false, at: (p, by) => ctx.toScreen([p[0] + inward[0] * by, p[1] + inward[1] * by]) };
|
||||
}
|
||||
|
||||
const line = (a: [number, number], b: [number, number], klass = "") => svg`<line class=${klass} x1=${a[0]} y1=${a[1]} x2=${b[0]} y2=${b[1]} />`;
|
||||
|
||||
/** A garage door: the door panel just inside the room, and its track under the ceiling drawn dashed. */
|
||||
function garageSymbol(f: Frame, o: Opening): Sym {
|
||||
const inner = f.across[0] - 0.04;
|
||||
const reach = f.across[0] + Math.min(2, o.height);
|
||||
const [a0, a1, b0, b1] = [f.at(f.p0, inner), f.at(f.p1, inner), f.at(f.p0, reach), f.at(f.p1, reach)];
|
||||
return svg`${line(a0, a1)}<path class="nf-open-track" d="M${a0[0]} ${a0[1]}L${b0[0]} ${b0[1]}M${a1[0]} ${a1[1]}L${b1[0]} ${b1[1]}" />`;
|
||||
}
|
||||
|
||||
/** A door: leaves swinging into the room (or out of it) from the hinge side, with fixed glass beside the leaf for sidelights. */
|
||||
function doorSymbol(ctx: CanvasContext, f: Frame, o: Opening): Sym {
|
||||
const out = o.swing === "out";
|
||||
const face = out ? -f.across[1] : f.across[0];
|
||||
const middle = (f.across[0] - f.across[1]) / 2;
|
||||
// "left" is seen from the room, so which end the hinge is at depends on which way round the outline runs
|
||||
const hingeAtStart = (o.hinge === "left") === f.direction > 0;
|
||||
const style = openingStyle(o, f.exterior);
|
||||
const two = o.leaves === 2;
|
||||
let [leafStart, leafEnd] = [f.p0, f.p1];
|
||||
let panes: [Vec2, Vec2][] = [];
|
||||
const lights = sidelightLayout(o.width, style, hingeAtStart, o);
|
||||
if (lights) {
|
||||
const onEdge = (k: number): Vec2 => (k <= 0.02 ? f.p0 : k >= o.width - 0.02 ? f.p1 : pointOnRoomEdge(f.room, f.edge, o.offset - o.width / 2 + k));
|
||||
[leafStart, leafEnd] = [onEdge(lights.x0), onEdge(lights.x1)];
|
||||
panes = lights.panels.map(([a, b]) => [onEdge(a), onEdge(b)]);
|
||||
}
|
||||
const centre: Vec2 = [(leafStart[0] + leafEnd[0]) / 2, (leafStart[1] + leafEnd[1]) / 2];
|
||||
const leafWidth = (two ? 0.5 : 1) * Math.hypot(leafEnd[0] - leafStart[0], leafEnd[1] - leafStart[1]);
|
||||
const glass = panes.map(([a, b]) => svg`${line(f.at(a, middle + 0.035), f.at(b, middle + 0.035), "nf-open-pane")}${line(f.at(a, middle - 0.035), f.at(b, middle - 0.035), "nf-open-pane")}`);
|
||||
const swing = (hinge: Vec2, free: Vec2) => {
|
||||
const [hx, hy] = f.at(hinge, face);
|
||||
const [fx, fy] = f.at(free, face);
|
||||
const leaf = f.at(hinge, face + (out ? -leafWidth : leafWidth));
|
||||
const radius = leafWidth * ctx.scale;
|
||||
const turn = (leaf[0] - hx) * (fy - hy) - (leaf[1] - hy) * (fx - hx) > 0 ? 1 : 0;
|
||||
return svg`<path d="M${hx} ${hy}L${leaf[0]} ${leaf[1]}A${radius} ${radius} 0 0 ${turn} ${fx} ${fy}" />`;
|
||||
};
|
||||
let body: TemplateResult;
|
||||
if (style === "passage") body = line(f.at(f.p0, middle), f.at(f.p1, middle), "nf-open-passage");
|
||||
else if (style === "sliding") body = line(f.at(leafStart, face), f.at(leafEnd, face));
|
||||
else if (two) body = svg`${swing(leafStart, centre)}${swing(leafEnd, centre)}`;
|
||||
else body = hingeAtStart ? swing(leafStart, leafEnd) : swing(leafEnd, leafStart);
|
||||
return svg`${glass}${body}`;
|
||||
}
|
||||
|
||||
/** A window: two panes in the middle of the wall, and for a double window a post between them. */
|
||||
function windowSymbol(f: Frame, o: Opening): Sym {
|
||||
const middle = (f.across[0] - f.across[1]) / 2;
|
||||
if (o.opens === "slide") {
|
||||
// a sliding window: its panes on two tracks, overlapping a little, as plans draw them
|
||||
const panes = o.leaves === 2 ? 4 : 2;
|
||||
const along = (t: number): [number, number] => [f.p0[0] + (f.p1[0] - f.p0[0]) * t, f.p0[1] + (f.p1[1] - f.p0[1]) * t];
|
||||
const parts = Array.from({ length: panes }, (_, k) => {
|
||||
const track = o.leaves === 2 ? (k === 1 || k === 2 ? 0.035 : -0.035) : k === 0 ? 0.035 : -0.035;
|
||||
return line(f.at(along(Math.max(0, k / panes - 0.03)), middle + track), f.at(along(Math.min(1, (k + 1) / panes + 0.03)), middle + track));
|
||||
});
|
||||
return svg`${parts}`;
|
||||
}
|
||||
const post = o.leaves === 2 ? line(f.at([(f.p0[0] + f.p1[0]) / 2, (f.p0[1] + f.p1[1]) / 2], f.across[0]), f.at([(f.p0[0] + f.p1[0]) / 2, (f.p0[1] + f.p1[1]) / 2], -f.across[1])) : nothing;
|
||||
return svg`${line(f.at(f.p0, middle + 0.035), f.at(f.p1, middle + 0.035))}${line(f.at(f.p0, middle - 0.035), f.at(f.p1, middle - 0.035))}${post}`;
|
||||
}
|
||||
|
||||
export function openingsLayer(ctx: CanvasContext, floor: Floor, walls: readonly Wall[], selectedId: string | null): TemplateResult {
|
||||
// selecting one piece of a pane over several edges selects all of them
|
||||
const selectedFront = floor.openings.find((o) => o.id === selectedId)?.front ?? null;
|
||||
const one = (o: Opening) => {
|
||||
const f = frameOf(ctx, o, floor, walls);
|
||||
if (!f) return nothing;
|
||||
const gap = [f.at(f.p0, f.across[0] + 0.01), f.at(f.p1, f.across[0] + 0.01), f.at(f.p1, -f.across[1] - 0.01), f.at(f.p0, -f.across[1] - 0.01)];
|
||||
const front = o.type === "door" && isFrontDoor(openingStyle(o, f.exterior));
|
||||
const on = o.id === selectedId || (!!o.front && o.front === selectedFront);
|
||||
const klass = `nf-open nf-open-${o.type}${front ? " nf-open-front" : ""}${on ? " nf-open-sel" : ""}`;
|
||||
const symbol = o.type === "garage" ? garageSymbol(f, o) : o.type === "door" ? doorSymbol(ctx, f, o) : windowSymbol(f, o);
|
||||
return svg`<g data-opening=${o.id} class=${klass}><polygon class="nf-open-gap" points=${gap.map((p) => p.join(",")).join(" ")} />${symbol}</g>`;
|
||||
};
|
||||
return svg`<g>${floor.openings.map(one)}</g>`;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// The basic layers of the plan: the grid, the floor below, walls, rooms with their names, outdoor areas, free walls, the meter, and
|
||||
// the handles of the selected room, outdoor area and walls.
|
||||
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { bounds, centroid, isFixed, polygonArea, roomsReachingUp, type Floor, type FreeWall, type OutdoorArea, type Room, type Vec2 } from "../../../model.ts";
|
||||
import type { Wall } from "../../../geometry/walls.ts";
|
||||
import { edgePlus, pointsAttribute, type CanvasContext } from "./context.ts";
|
||||
import { formatArea, formatLength } from "../../../units.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
/** A round handle that can be grabbed: an invisible larger circle around the visible one. */
|
||||
export const gripAt = (x: number, y: number, radius = 6): TemplateResult => svg`<circle cx=${x} cy=${y} r="16" class="nf-hit" /><circle cx=${x} cy=${y} r=${radius} />`;
|
||||
|
||||
/** The grid: fine lines when zoomed in, coarser when zoomed out, and the origin. */
|
||||
export function gridLayer(ctx: CanvasContext, size: { w: number; h: number }): Layer {
|
||||
const { scale } = ctx;
|
||||
const minor = scale >= 90 ? 0.1 : scale >= 30 ? 0.5 : 1;
|
||||
const major = scale >= 20 ? 1 : 5;
|
||||
const topLeft = ctx.toWorld(0, 0);
|
||||
const bottomRight = ctx.toWorld(size.w, size.h);
|
||||
const lines: TemplateResult[] = [];
|
||||
const addLines = (step: number, klass: string) => {
|
||||
for (let x = Math.ceil(topLeft[0] / step) * step; x <= bottomRight[0]; x += step) {
|
||||
const sx = ctx.toScreen([x, 0])[0];
|
||||
lines.push(svg`<line class=${klass} x1=${sx} y1="0" x2=${sx} y2=${size.h} />`);
|
||||
}
|
||||
for (let z = Math.ceil(topLeft[1] / step) * step; z <= bottomRight[1]; z += step) {
|
||||
const sy = ctx.toScreen([0, z])[1];
|
||||
lines.push(svg`<line class=${klass} x1="0" y1=${sy} x2=${size.w} y2=${sy} />`);
|
||||
}
|
||||
};
|
||||
if (minor < major) addLines(minor, "nf-grid-minor");
|
||||
addLines(major, "nf-grid-major");
|
||||
const [ox, oy] = ctx.toScreen([0, 0]);
|
||||
lines.push(svg`<circle class="nf-origin" cx=${ox} cy=${oy} r="3" />`);
|
||||
return svg`<g pointer-events="none">${lines}</g>`;
|
||||
}
|
||||
|
||||
/** The rooms of the floor below, faintly, as orientation; rooms below that rise through this floor are hatched – it stays open there. */
|
||||
export function floorBelowLayer(ctx: CanvasContext): Layer {
|
||||
const floors = ctx.host.doc.floors;
|
||||
const at = floors.findIndex((f) => f.id === ctx.floorId);
|
||||
const below = at > 0 ? floors[at - 1] : undefined;
|
||||
if (!below) return nothing;
|
||||
const voids = roomsReachingUp(floors, floors[at]);
|
||||
return svg`<g pointer-events="none">${below.rooms.map((r) => svg`<polygon class="nf-ghost" points=${pointsAttribute(ctx, r.points)} />`)}${voids.map(
|
||||
(points) => svg`<polygon class="nf-void" points=${pointsAttribute(ctx, points)} />`,
|
||||
)}</g>`;
|
||||
}
|
||||
|
||||
/** The wall pieces; outer ones are drawn stronger, and walls lower than the floor lighter. */
|
||||
export function wallsLayer(ctx: CanvasContext, walls: readonly Wall[]): Layer {
|
||||
const full = ctx.host.floor?.height ?? 2.5;
|
||||
return svg`<g pointer-events="none">${walls.map((w) => {
|
||||
const low = w.height !== undefined && w.height < full - 0.01;
|
||||
return svg`<polygon class=${`nf-wall${w.exterior ? " nf-wall-ext" : ""}${low ? " nf-wall-low" : ""}`} points=${pointsAttribute(ctx, w.footprint)} />`;
|
||||
})}</g>`;
|
||||
}
|
||||
|
||||
/** Outdoor areas, labelled with their kind when large enough. */
|
||||
export function outdoorLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null): Layer {
|
||||
const one = (area: OutdoorArea) => {
|
||||
const [cx, cy] = ctx.toScreen(centroid(area.points));
|
||||
const box = bounds(area.points);
|
||||
const labelled = Math.min(box.x1 - box.x0, box.z1 - box.z0) * ctx.scale > 40;
|
||||
return svg`<g data-outdoor=${area.id} class=${`nf-out nf-out-${area.type}${area.id === selectedId ? " nf-out-sel" : ""}`}>
|
||||
<polygon points=${pointsAttribute(ctx, area.points)} />
|
||||
${labelled ? svg`<text x=${cx} y=${cy + 4}>${ctx.host.t(`out_${area.type}` as I18nKey)}</text>` : nothing}
|
||||
</g>`;
|
||||
};
|
||||
return svg`<g>${floor.outdoor.map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** Corner handles of the selected outdoor area (a rectangle stays one while it is dragged) and a "+" on every edge that adds a corner. */
|
||||
export function outdoorHandlesLayer(ctx: CanvasContext, area: OutdoorArea | undefined, tool: string): Layer {
|
||||
const { host } = ctx;
|
||||
if (!area || !host.admin || tool !== "select" || host.doc.settings.lock_plan) return nothing;
|
||||
const pts = area.points;
|
||||
return svg`${pts.map((p, i) => edgePlus(ctx, p, pts[(i + 1) % pts.length], "out", area.id, i))}${pts.map((p, i) => svg`<g class="nf-vertex" data-out-vertex=${`${area.id}:${i}`}>${gripAt(...ctx.toScreen(p))}</g>`)}`;
|
||||
}
|
||||
|
||||
/** Rooms with their names and areas, and the wall of the selected room that its list row points at. */
|
||||
export function roomsLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null, litEdge: number | null): Layer {
|
||||
const selected = floor.rooms.find((r) => r.id === selectedId);
|
||||
const lit = selected && litEdge !== null && litEdge < selected.points.length ? [ctx.toScreen(selected.points[litEdge]), ctx.toScreen(selected.points[(litEdge + 1) % selected.points.length])] : null;
|
||||
return svg`<g>${floor.rooms.map((r) => svg`<polygon data-room=${r.id} class=${r.id === selectedId ? "nf-room nf-room-sel" : "nf-room"} points=${pointsAttribute(ctx, r.points)} />`)}</g>
|
||||
${lit ? svg`<line class="nf-edge-hi" pointer-events="none" x1=${lit[0][0]} y1=${lit[0][1]} x2=${lit[1][0]} y2=${lit[1][1]} />` : nothing}
|
||||
<g pointer-events="none">${floor.rooms.map((r) => {
|
||||
const [cx, cy] = ctx.toScreen(centroid(r.points));
|
||||
return svg`<text class="nf-room-name" x=${cx} y=${cy - 2}>${r.name}</text>
|
||||
<text class="nf-room-area" x=${cx} y=${cy + 14}>${formatArea(ctx.host.hass, polygonArea(r.points))}</text>`;
|
||||
})}</g>`;
|
||||
}
|
||||
|
||||
/** The electricity meter, a small box with a bolt. */
|
||||
export function meterLayer(ctx: CanvasContext, floor: Floor): Layer {
|
||||
const meter = ctx.host.doc.energy?.meter;
|
||||
if (!meter || meter.floor_id !== floor.id) return nothing;
|
||||
const [x, y] = ctx.toScreen([meter.x, meter.z]);
|
||||
return svg`<g class="nf-meter" transform="translate(${x} ${y})" pointer-events="none">
|
||||
<rect x="-11" y="-11" width="22" height="22" rx="5" />
|
||||
<path d="M1.5 -7 L-4 1 H0 L-1.5 7 L4 -1 H0 Z" />
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/** Free-standing walls with a wide invisible line to grab, and end handles when selected. */
|
||||
export function freeWallsLayer(ctx: CanvasContext, floor: Floor, selectedId: string | null): Layer {
|
||||
const { host } = ctx;
|
||||
const one = (wall: FreeWall) => {
|
||||
const [a, b] = [ctx.toScreen(wall.a), ctx.toScreen(wall.b)];
|
||||
const selected = wall.id === selectedId;
|
||||
const ends = selected && host.admin && !isFixed(wall, true, host.doc.settings);
|
||||
return svg`<g data-free-wall=${wall.id} class=${`nf-free-wall${selected ? " nf-free-wall-sel" : ""}`}>
|
||||
<line class="nf-hit" x1=${a[0]} y1=${a[1]} x2=${b[0]} y2=${b[1]} />
|
||||
<line class="nf-free-wall-line" x1=${a[0]} y1=${a[1]} x2=${b[0]} y2=${b[1]} />
|
||||
</g>
|
||||
${ends ? svg`<g class="nf-vertex" data-wall-end=${`${wall.id}:a`}>${gripAt(a[0], a[1])}</g><g class="nf-vertex" data-wall-end=${`${wall.id}:b`}>${gripAt(b[0], b[1])}</g>` : nothing}`;
|
||||
};
|
||||
return svg`<g>${(floor.walls ?? []).map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** Short ticks across a wall where it has been cut by hand. */
|
||||
export function cutMarksLayer(ctx: CanvasContext, room: Room): Layer {
|
||||
const pts = room.points;
|
||||
const marks = (room.wall_splits ?? []).flatMap((cuts, i) => {
|
||||
if (!cuts || i >= pts.length) return [];
|
||||
const [a, b] = [pts[i], pts[(i + 1) % pts.length]];
|
||||
const length = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
|
||||
const [ux, uz] = [(b[0] - a[0]) / length, (b[1] - a[1]) / length];
|
||||
return cuts.map((d) => {
|
||||
const [x, y] = ctx.toScreen([a[0] + ux * d, a[1] + uz * d]);
|
||||
return svg`<line class="nf-split-mark" x1=${x - uz * 7} y1=${y + ux * 7} x2=${x + uz * 7} y2=${y - ux * 7} />`;
|
||||
});
|
||||
});
|
||||
return svg`${marks}`;
|
||||
}
|
||||
|
||||
/** The handles of the selected room: a grip at each corner, and at each edge its length and a "+" that adds a corner. */
|
||||
export function roomHandlesLayer(ctx: CanvasContext, room: Room, selectedCorner: number | null): Layer {
|
||||
const pts = room.points;
|
||||
const [cx, cy] = ctx.toScreen(centroid(pts));
|
||||
const edge = (a: Vec2, b: Vec2, i: number) => {
|
||||
const [[ax, ay], [bx, by]] = [ctx.toScreen(a), ctx.toScreen(b)];
|
||||
const [mx, my] = [(ax + bx) / 2, (ay + by) / 2];
|
||||
const onScreen = Math.hypot(bx - ax, by - ay);
|
||||
// the length is written outside the room: along the edge's normal, away from the middle
|
||||
let [nx, ny] = [-(by - ay), bx - ax];
|
||||
const norm = Math.hypot(nx, ny) || 1;
|
||||
[nx, ny] = [nx / norm, ny / norm];
|
||||
if (nx * (mx - cx) + ny * (my - cy) < 0) [nx, ny] = [-nx, -ny];
|
||||
return svg`${onScreen > 50 ? svg`<text class="nf-dim" x=${mx + nx * 16} y=${my + ny * 16 + 4}>${formatLength(ctx.host.hass, Math.hypot(b[0] - a[0], b[1] - a[1]))}</text>` : nothing}
|
||||
${onScreen > 36 ? svg`<g data-mid=${i} class="nf-mid"><circle cx=${mx} cy=${my} r="14" class="nf-hit" /><circle cx=${mx} cy=${my} r="6" /><path d="M${mx - 3} ${my}h6M${mx} ${my - 3}v6" /></g>` : nothing}`;
|
||||
};
|
||||
const corner = (p: Vec2, i: number) => {
|
||||
const [x, y] = ctx.toScreen(p);
|
||||
return svg`<g data-vertex=${i} class=${i === selectedCorner ? "nf-vertex nf-vertex-sel" : "nf-vertex"}>${gripAt(x, y)}</g><text class="nf-vertex-no" x=${x + 9} y=${y - 9}>${i + 1}</text>`;
|
||||
};
|
||||
return svg`<g>${pts.map((p, i) => edge(p, pts[(i + 1) % pts.length], i))}${pts.map(corner)}</g>`;
|
||||
}
|
||||
|
||||
/** Every room edge labelled with its length, a little inside the room, along the edge (the switch "Measurements"). */
|
||||
export function dimensionsLayer(ctx: CanvasContext, floor: Floor): Layer {
|
||||
const labels = floor.rooms.flatMap((room) => {
|
||||
if (room.points.length < 3) return [];
|
||||
const [cx, cz] = centroid(room.points);
|
||||
return room.points.map((a, i) => {
|
||||
const b = room.points[(i + 1) % room.points.length];
|
||||
const length = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
if (length < 0.4) return nothing;
|
||||
const mid: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
|
||||
// a little towards the room's middle, so the label stays inside it
|
||||
const towards = Math.hypot(cx - mid[0], cz - mid[1]) || 1;
|
||||
const inset = Math.min(0.35, towards / 2);
|
||||
const at: Vec2 = [mid[0] + ((cx - mid[0]) / towards) * inset, mid[1] + ((cz - mid[1]) / towards) * inset];
|
||||
const [x, y] = ctx.toScreen(at);
|
||||
let angle = (Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI;
|
||||
if (angle > 90) angle -= 180;
|
||||
if (angle < -90) angle += 180;
|
||||
return svg`<text class="nf-dim" x=${x} y=${y} transform=${`rotate(${angle.toFixed(1)} ${x} ${y})`} text-anchor="middle" dominant-baseline="middle">${formatLength(ctx.host.hass, length)}</text>`;
|
||||
});
|
||||
});
|
||||
return svg`<g pointer-events="none">${labels}</g>`;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// What the roof and energy tools draw over the plan: roof sections with their ridges and handles, solar modules, roof windows,
|
||||
// the head-room lines of an attic floor, and the markers of the energy devices.
|
||||
|
||||
import { sectionCorners } from "../../../roof/frame.ts";
|
||||
import { nothing, svg, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { ENERGY_DEVICES, type EnergyRoute, type Floor, type RoofSection, type RoutePoint, type Vec2 } from "../../../model.ts";
|
||||
import { dormerParent, effectiveDormer, headroomLines, ridgeHeight, sectionCutsBelow, sectionFrame, sectionGeometry } from "../../../roof-sections.ts";
|
||||
import { chimneyPlace, chimneySize, fieldCenter, fieldFace, fieldModules, roofFaces, windowCorners } from "../../../solar.ts";
|
||||
import type { RoofController } from "../roof-controller.ts";
|
||||
import { edgePlus, pointsAttribute, type CanvasContext } from "./context.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
/** A round handle with a larger invisible circle around it, so that a finger can grab it. */
|
||||
const grip = (x: number, y: number) => svg`<circle cx=${x} cy=${y} r="16" class="nf-hit" /><circle cx=${x} cy=${y} r="6" />`;
|
||||
|
||||
/** The handle of a point of a free outline. */
|
||||
const vertexHandle = (ctx: CanvasContext, at: Vec2, id: string): TemplateResult => svg`<g class="nf-vertex" data-roof-vertex=${id}>${grip(...ctx.toScreen(at))}</g>`;
|
||||
|
||||
/** The handle of a corner of a rectangular section. */
|
||||
const cornerHandle = (ctx: CanvasContext, at: Vec2, id: string): TemplateResult => svg`<g class="nf-vertex" data-roof-corner=${id}>${grip(...ctx.toScreen(at))}</g>`;
|
||||
|
||||
/** The label written in the middle of a section: lock, number, kind and ridge height. */
|
||||
function sectionLabel(ctx: CanvasContext, roof: RoofController, section: RoofSection, index: number): string {
|
||||
const { t, hass } = ctx.host;
|
||||
const kind = section.dormer ? t("roof_dormer") : section.open ? t("roof_open_short") : t(`roof_shape_${section.shape}` as I18nKey);
|
||||
return `${roof.isFixed(section) ? "🔒 " : ""}${index + 1} · ${kind} · ${formatNumber(hass, ridgeHeight(section), 1)} m`;
|
||||
}
|
||||
|
||||
/** The sections of a custom roof: outline, ridges and hips, a label, and for the selected one handles at its corners or points. */
|
||||
export function roofSectionsLayer(ctx: CanvasContext, roof: RoofController): Layer {
|
||||
const settings = ctx.host.doc.settings.roof;
|
||||
const sections = settings.type === "custom" ? (settings.sections ?? []) : [];
|
||||
const editable = ctx.host.admin;
|
||||
const one = (section: RoofSection, index: number) => {
|
||||
const selected = section.id === roof.sectionId;
|
||||
const frame = sectionFrame(section);
|
||||
const custom = (section.shape === "flat" || section.shape === "parapet") && section.points && section.points.length >= 3 ? section.points : null;
|
||||
// a dormer or cross gable is drawn as deep as it really reaches: its ridge meets the slope there
|
||||
const parent = dormerParent(sections, section);
|
||||
const shown = parent ? sectionFrame(effectiveDormer(parent, section)) : frame;
|
||||
const outline: Vec2[] = custom ?? [shown.at(shown.u0, 0), shown.at(shown.u1, 0), shown.at(shown.u1, shown.w), shown.at(shown.u0, shown.w)];
|
||||
const geometry = section.shape === "flat" || section.shape === "parapet" ? null : sectionGeometry(section, { u0: 0, u1: 0, a: 0, b: 0 });
|
||||
const ridges = (geometry?.ridges ?? []).map(([p, q]) => {
|
||||
const [ax, ay] = ctx.toScreen(frame.at(p[0], p[1]));
|
||||
const [bx, by] = ctx.toScreen(frame.at(q[0], q[1]));
|
||||
return svg`<line x1=${ax} y1=${ay} x2=${bx} y2=${by} />`;
|
||||
});
|
||||
const [lx, ly] = ctx.toScreen(frame.at((frame.u0 + frame.u1) / 2, frame.w / 2));
|
||||
const movable = selected && editable && !roof.isFixed(section);
|
||||
const corners = [[0, 0], [1, 0], [1, 1], [0, 1]] as const;
|
||||
const flatRoof = section.shape === "flat" || section.shape === "parapet";
|
||||
const [x0, x1, z0, z1] = [Math.min(section.x0, section.x1), Math.max(section.x0, section.x1), Math.min(section.z0, section.z1), Math.max(section.z0, section.z1)];
|
||||
// a flat roof can be reshaped: a "+" on every edge adds a corner (a rectangle becomes a free shape)
|
||||
const ring: Vec2[] = custom ?? (section.rotation ? sectionCorners(section) : [[x0, z0], [x1, z0], [x1, z1], [x0, z1]]);
|
||||
const plusses = movable && flatRoof ? ring.map((p, i) => edgePlus(ctx, p, ring[(i + 1) % ring.length], "roof", section.id, i)) : nothing;
|
||||
const handles = !movable
|
||||
? nothing
|
||||
: svg`${plusses}${custom
|
||||
? custom.map((p, k) => vertexHandle(ctx, p, `${section.id}:${k}`))
|
||||
: corners.map(([kx, kz]) => cornerHandle(ctx, [kx ? x1 : x0, kz ? z1 : z0], `${section.id}:${kx}:${kz}`))}`;
|
||||
return svg`<g data-roof=${section.id} class=${`nf-roof-sec${selected ? " nf-roof-sel" : ""}`}>
|
||||
<polygon points=${pointsAttribute(ctx, outline)} />
|
||||
<g class="nf-roof-ridge">${ridges}</g>
|
||||
<text x=${lx} y=${ly - 14}>${sectionLabel(ctx, roof, section, index)}</text>
|
||||
</g>${handles}`;
|
||||
};
|
||||
return svg`<g class="nf-roof-layer">${sections.map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** The turn handle of a free-standing field: a circle out in the direction the rows face. */
|
||||
function turnHandle(ctx: CanvasContext, fieldId: string, centre: Vec2, rotation: number, reach: number): TemplateResult {
|
||||
const angle = (rotation * Math.PI) / 180;
|
||||
const [fx, fy] = ctx.toScreen(centre);
|
||||
const [hx, hy] = ctx.toScreen([centre[0] + Math.sin(angle) * reach, centre[1] - Math.cos(angle) * reach]);
|
||||
return svg`<g class="nf-rotate" data-solar-turn=${fieldId}>
|
||||
<line x1=${fx} y1=${fy} x2=${hx} y2=${hy} />
|
||||
<circle cx=${hx} cy=${hy} r="16" class="nf-hit" />
|
||||
<circle cx=${hx} cy=${hy} r="8" />
|
||||
<path d="M${hx - 4} ${hy - 1}a4 4 0 1 1 2 3.5" />
|
||||
</g>`;
|
||||
}
|
||||
|
||||
/** Every solar module as a small rectangle; the selected field shows its switched-off modules dashed so they can be switched on again. */
|
||||
export function solarLayer(ctx: CanvasContext, roof: RoofController): Layer {
|
||||
const { doc, admin } = ctx.host;
|
||||
const fields = doc.settings.roof.solar ?? [];
|
||||
if (fields.length === 0) return nothing;
|
||||
const faces = roofFaces(doc);
|
||||
const one = (field: (typeof fields)[number]) => {
|
||||
const face = fieldFace(doc, field, faces);
|
||||
if (!face || (face.wall && face.wall.floorId !== ctx.floorId)) return nothing;
|
||||
const selected = field.id === roof.solarId;
|
||||
let turn: Layer = nothing;
|
||||
if (selected && face.unbounded && admin && !field.locked) {
|
||||
const centre = fieldCenter(face, field);
|
||||
const farthest = Math.max(...fieldModules(face, field, true).flatMap((m) => m.corners.map((p) => Math.hypot(p[0] - centre[0], p[2] - centre[1]))));
|
||||
turn = turnHandle(ctx, field.id, centre, field.rotation ?? 0, 0.9 + farthest * 0.5);
|
||||
}
|
||||
const module = (m: ReturnType<typeof fieldModules>[number]) => {
|
||||
let outline: Vec2[];
|
||||
if (face.wall) {
|
||||
// on a wall the modules stand upright: in the plan a strip outside the wall, as deep as the modules stand off it (at least 30 cm to grab)
|
||||
const depth = Math.max(0.3, ...m.corners.map((p) => (p[0] - face.o[0]) * face.n[0] + (p[2] - face.o[2]) * face.n[2]));
|
||||
const [a, b] = [m.corners[0], m.corners[1]];
|
||||
const out = (p: typeof a): Vec2 => [p[0] + face.n[0] * depth, p[2] + face.n[2] * depth];
|
||||
outline = [[a[0], a[2]], out(a), out(b), [b[0], b[2]]];
|
||||
} else outline = m.corners.map((p) => [p[0], p[2]] as Vec2);
|
||||
return svg`<polygon data-cell=${m.cell} class=${m.skipped ? "nf-solar-off" : ""} points=${pointsAttribute(ctx, outline)} />`;
|
||||
};
|
||||
const klass = `nf-solar${selected ? " nf-solar-sel" : ""}${selected && roof.picking ? " nf-solar-pick" : ""}`;
|
||||
return svg`<g data-solar=${field.id} class=${klass}>${fieldModules(face, field, selected).map(module)}</g>${turn}`;
|
||||
};
|
||||
return svg`<g class="nf-solar-layer">${fields.map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** Roof windows over the plan, the selected one highlighted. */
|
||||
export function roofWindowsLayer(ctx: CanvasContext, roof: RoofController): Layer {
|
||||
const windows = ctx.host.doc.settings.roof.windows ?? [];
|
||||
if (windows.length === 0) return nothing;
|
||||
const faces = new Map(roofFaces(ctx.host.doc).map((f) => [f.key, f]));
|
||||
const one = (w: (typeof windows)[number]) => {
|
||||
const face = faces.get(w.face);
|
||||
const corners = face ? windowCorners(face, w) : null;
|
||||
if (!corners) return nothing;
|
||||
return svg`<g data-roofwin=${w.id} class=${`nf-roofwin${w.id === roof.windowId ? " nf-roofwin-sel" : ""}`}><polygon points=${pointsAttribute(ctx, corners.map((p) => [p[0], p[2]] as Vec2))} /></g>`;
|
||||
};
|
||||
return svg`<g class="nf-roofwin-layer">${windows.map(one)}</g>`;
|
||||
}
|
||||
|
||||
const ENERGY_ICONS: Record<string, string> = { inverter: "⚡", home_battery: "🔋", wallbox: "🔌", meter: "📟", grid_point: "🏁" };
|
||||
|
||||
/** The energy tool: a round marker with a symbol on every energy device of the floor, the selected one also with its name. */
|
||||
export function energyMarkersLayer(ctx: CanvasContext, floor: Floor | undefined, selectedId: string | null): Layer {
|
||||
if (!floor) return nothing;
|
||||
const devices = floor.furniture.filter((m) => (ENERGY_DEVICES as readonly string[]).includes(m.type));
|
||||
const one = (m: (typeof devices)[number]) => {
|
||||
const [x, y] = ctx.toScreen([m.x, m.z]);
|
||||
const selected = m.id === selectedId;
|
||||
const name = ctx.host.t(`furn_${m.type}` as I18nKey);
|
||||
return svg`<g data-energy-device=${m.id} class=${`nf-energy-marker${selected ? " nf-energy-marker-sel" : ""}`}>
|
||||
<circle cx=${x} cy=${y} r="17" />
|
||||
<text x=${x} y=${y + 6} class="nf-energy-icon">${ENERGY_ICONS[m.type] ?? "⚡"}</text>
|
||||
${selected ? svg`<text x=${x} y=${y + 32} class="nf-energy-name">${name}</text>` : nothing}
|
||||
<title>${name}</title>
|
||||
</g>`;
|
||||
};
|
||||
return svg`<g class="nf-energy-markers">${devices.map(one)}</g>`;
|
||||
}
|
||||
|
||||
/** On an attic floor: dashed lines where the roof slope leaves 1.5 m and 2 m of head room, labelled. */
|
||||
export function headroomLayer(ctx: CanvasContext, floor: Floor): Layer {
|
||||
const { doc, hass } = ctx.host;
|
||||
const sections = doc.settings.roof.sections ?? [];
|
||||
if (!sections.some((s) => sectionCutsBelow(s, floor.elevation + floor.height))) return nothing;
|
||||
const lines = [1.5, 2].flatMap((height) =>
|
||||
headroomLines({ settings: doc.settings }, floor.elevation, height).map(([p, q]) => {
|
||||
const [x1, y1] = ctx.toScreen(p);
|
||||
const [x2, y2] = ctx.toScreen(q);
|
||||
return svg`<line class="nf-headroom" x1=${x1} y1=${y1} x2=${x2} y2=${y2} />
|
||||
<text class="nf-headroom-label" x=${(x1 + x2) / 2} y=${(y1 + y2) / 2 - 4}>${formatNumber(hass, height, 1)} m</text>`;
|
||||
}),
|
||||
);
|
||||
return svg`${lines}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cable routes on the floor shown: each run of points on this floor as a line, a dot per point, and a short stub where the
|
||||
* cable goes to another floor. The route being drawn is highlighted and numbered.
|
||||
*/
|
||||
export function energyRoutesLayer(ctx: CanvasContext, floor: Floor | undefined, routes: readonly EnergyRoute[], draft: { key: string; points: RoutePoint[] } | null): Layer {
|
||||
if (!floor) return nothing;
|
||||
const one = (points: readonly RoutePoint[], drawing: boolean) => {
|
||||
const parts: TemplateResult[] = [];
|
||||
points.forEach((p, i) => {
|
||||
if (p.floor_id !== floor.id) return;
|
||||
const [x, y] = ctx.toScreen([p.x, p.z]);
|
||||
const next = points[i + 1];
|
||||
if (next?.floor_id === floor.id) {
|
||||
const [x2, y2] = ctx.toScreen([next.x, next.z]);
|
||||
parts.push(svg`<line x1=${x} y1=${y} x2=${x2} y2=${y2} />`);
|
||||
}
|
||||
// where the cable leaves this floor (or comes from another), a ring marks the riser
|
||||
const riser = (next && next.floor_id !== floor.id) || (i > 0 && points[i - 1].floor_id !== floor.id);
|
||||
parts.push(svg`<circle cx=${x} cy=${y} r=${riser ? 7 : 4} class=${riser ? "nf-route-riser" : ""} />`);
|
||||
if (drawing) parts.push(svg`<text x=${x + 8} y=${y - 8}>${i + 1}</text>`);
|
||||
});
|
||||
return svg`<g class=${`nf-route${drawing ? " nf-route-drawing" : ""}`}>${parts}</g>`;
|
||||
};
|
||||
return svg`<g class="nf-routes">${routes.filter((r) => r.key !== draft?.key).map((r) => one(r.points, false))}${draft ? one(draft.points, true) : nothing}</g>`;
|
||||
}
|
||||
|
||||
/** Chimneys over the plan as their footprint (square or round), the selected one highlighted. */
|
||||
export function chimneysLayer(ctx: CanvasContext, roof: RoofController): Layer {
|
||||
const chimneys = ctx.host.doc.settings.roof.chimneys ?? [];
|
||||
if (chimneys.length === 0) return nothing;
|
||||
const faces = new Map(roofFaces(ctx.host.doc).map((f) => [f.key, f]));
|
||||
const one = (c: (typeof chimneys)[number]) => {
|
||||
const face = faces.get(c.face);
|
||||
if (!face) return nothing;
|
||||
const { shape, w, d } = chimneySize(c);
|
||||
const { center: m, along: a, across: x } = chimneyPlace(face, c);
|
||||
const ring: Vec2[] =
|
||||
shape === "round" || shape === "steel"
|
||||
? Array.from({ length: 16 }, (_, i) => [m[0] + (Math.cos((i / 16) * 2 * Math.PI) * Math.min(w, d)) / 2, m[1] + (Math.sin((i / 16) * 2 * Math.PI) * Math.min(w, d)) / 2] as Vec2)
|
||||
: [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([su, sd]) => [m[0] + (a[0] * w * su) / 2 + (x[0] * d * sd) / 2, m[1] + (a[1] * w * su) / 2 + (x[1] * d * sd) / 2] as Vec2);
|
||||
return svg`<g data-chimney=${c.id} class=${`nf-chimney${c.id === roof.chimneyId ? " nf-roofwin-sel" : ""}`}><polygon points=${pointsAttribute(ctx, ring)} /></g>`;
|
||||
};
|
||||
return svg`<g class="nf-roofwin-layer">${chimneys.map(one)}</g>`;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, hassOf } from "../../entities/fixtures.ts";
|
||||
import { entityOptions, isBinary, isNumeric, isPowerSensor, powerSensorOf } from "./entities.ts";
|
||||
|
||||
test("numbers and switches are told apart by their domain", () => {
|
||||
for (const id of ["sensor.a", "input_number.b", "number.c"]) assert.equal(isNumeric(id), true, id);
|
||||
for (const id of ["binary_sensor.a", "light.a", "sensor"]) assert.equal(isNumeric(id), false, id);
|
||||
assert.equal(isBinary("binary_sensor.door"), true);
|
||||
assert.equal(isBinary("input_boolean.guest"), true);
|
||||
assert.equal(isBinary("switch.a"), false);
|
||||
});
|
||||
|
||||
test("power sensors: by device class, or by a watt or kilowatt unit", () => {
|
||||
const hass = hassOf([
|
||||
entity("sensor.meter", "5", { device_class: "power" }),
|
||||
entity("sensor.mqtt", "5", { unit_of_measurement: "kW" }),
|
||||
entity("sensor.temp", "20", { device_class: "temperature", unit_of_measurement: "°C" }),
|
||||
entity("light.lamp", "on", { device_class: "power" }),
|
||||
]);
|
||||
assert.equal(isPowerSensor(hass, "sensor.meter"), true);
|
||||
assert.equal(isPowerSensor(hass, "sensor.mqtt"), true);
|
||||
assert.equal(isPowerSensor(hass, "sensor.temp"), false);
|
||||
assert.equal(isPowerSensor(hass, "light.lamp"), false, "not a numeric domain");
|
||||
assert.equal(isPowerSensor(undefined, "sensor.meter"), false);
|
||||
});
|
||||
|
||||
test("options carry the area and come out sorted by label", () => {
|
||||
const hass = hassOf(
|
||||
[entity("light.b", "on", { friendly_name: "Beta" }), entity("light.a", "on", { friendly_name: "Alpha" }), entity("switch.c", "on", { friendly_name: "Gamma" })],
|
||||
{ "light.a": { entity_id: "light.a", area_id: "kitchen", device_id: null } as never },
|
||||
{ areas: { kitchen: { area_id: "kitchen", name: "Kitchen" } } },
|
||||
);
|
||||
const options = entityOptions(hass, (id) => id.startsWith("light."));
|
||||
assert.deepEqual(options, [{ id: "light.a", label: "Alpha · Kitchen" }, { id: "light.b", label: "Beta" }]);
|
||||
assert.deepEqual(entityOptions(undefined, () => true), []);
|
||||
});
|
||||
|
||||
test("Symcon options expose their object-tree path, never an object id as their label", () => {
|
||||
const hass = hassOf([entity("sensor.4711", "21.4", { friendly_name: "Temperatur", symcon_path: "Haus / Küche / Temperatur" })]);
|
||||
assert.deepEqual(entityOptions(hass, () => true), [{ id: "sensor.4711", label: "Temperatur", detail: "Objektbaum: Haus / Küche / Temperatur" }]);
|
||||
});
|
||||
|
||||
test("an energy device's own power sensor wins over the found one, and 'none' means not set", () => {
|
||||
const found = new Map([["m1", { power: "sensor.found" }]]);
|
||||
assert.equal(powerSensorOf({ id: "m1", power: "sensor.own" }, found), "sensor.own");
|
||||
assert.equal(powerSensorOf({ id: "m1", power: "none" }, found), "sensor.found");
|
||||
assert.equal(powerSensorOf({ id: "m1" }, found), "sensor.found");
|
||||
assert.equal(powerSensorOf({ id: "m2" }, found), null);
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
// Which entities a form offers for which job, and how they are listed.
|
||||
|
||||
import { entityName } from "../../devices.ts";
|
||||
import type { HomeAssistant } from "../../types.ts";
|
||||
|
||||
export interface EntityOption {
|
||||
id: string;
|
||||
label: string;
|
||||
/** A human-readable location, e.g. the path of an IP-Symcon variable in the object tree. */
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** Entities that carry a number: sensors and the number helpers. */
|
||||
export const isNumeric = (id: string): boolean => /^(sensor|input_number|number)\./.test(id);
|
||||
|
||||
/** Entities that are on or off: binary sensors and the toggle helper. */
|
||||
export const isBinary = (id: string): boolean => /^(binary_sensor|input_boolean)\./.test(id);
|
||||
|
||||
/** A power sensor: device class power, or a plain sensor in W or kW (templates, MQTT and many meters have no class). */
|
||||
export function isPowerSensor(hass: HomeAssistant | undefined, id: string): boolean {
|
||||
if (!isNumeric(id)) return false;
|
||||
const attributes = hass?.states[id]?.attributes;
|
||||
return attributes?.device_class === "power" || attributes?.unit_of_measurement === "W" || attributes?.unit_of_measurement === "kW";
|
||||
}
|
||||
|
||||
/** The area an entity is in: its own, or that of its device. */
|
||||
function areaNameOf(hass: HomeAssistant | undefined, id: string): string | undefined {
|
||||
const entry = hass?.entities?.[id];
|
||||
const area = entry?.area_id ?? (entry?.device_id ? hass?.devices?.[entry.device_id]?.area_id : null);
|
||||
return area ? hass?.areas?.[area]?.name : undefined;
|
||||
}
|
||||
|
||||
/** The entities that pass `accept`, as options named "Name · Area", sorted by that label. */
|
||||
export function entityOptions(hass: HomeAssistant | undefined, accept: (id: string) => boolean): EntityOption[] {
|
||||
return Object.keys(hass?.states ?? {})
|
||||
.filter(accept)
|
||||
.map((id) => {
|
||||
const area = areaNameOf(hass, id);
|
||||
const state = hass?.states[id];
|
||||
const path = typeof state?.attributes.symcon_path === "string" ? state.attributes.symcon_path : undefined;
|
||||
const option: EntityOption = {
|
||||
id,
|
||||
label: area ? `${entityName(hass, id)} · ${area}` : entityName(hass, id),
|
||||
};
|
||||
// In Symcon this is the complete object-tree path. The browser only uses the synthetic id internally;
|
||||
// a person always picks a named variable from the tree path, never types an object id.
|
||||
if (path) option.detail = `Objektbaum: ${path}`;
|
||||
return option;
|
||||
})
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
/** The power sensor of an energy device: set by hand, or the one found on its Home Assistant device. */
|
||||
export function powerSensorOf(item: { id: string; power?: string | null }, found: Map<string, { power: string | null }>): string | null {
|
||||
return item.power && item.power !== "none" ? item.power : (found.get(item.id)?.power ?? null);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// The form fields the editor's panels are made of. Each takes the host (for translation and the read-only state) and the value
|
||||
// with the function that stores a change; the markup they produce is the same everywhere, so the panels only say what is edited.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { unsafeHTML } from "lit/directives/unsafe-html.js";
|
||||
import { entityName } from "../../devices.ts";
|
||||
import type { I18nKey } from "../../i18n.ts";
|
||||
import { MARKER_SHOWS, type MarkerShow, type PinOffset } from "../../model.ts";
|
||||
import type { EntityOption } from "./entities.ts";
|
||||
import type { EditorHost } from "./host.ts";
|
||||
import { pluginMdiIcon } from "../../plugins/registry.ts";
|
||||
import "../entity-picker.ts";
|
||||
|
||||
const valueOf = (e: Event) => (e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement).value;
|
||||
|
||||
/** A number typed with a comma or a point; NaN if it is not one. */
|
||||
export const typedNumber = (text: string): number => Number.parseFloat(text.replace(",", "."));
|
||||
|
||||
/** Rounded to thousandths, which is as exact as a plan needs to be. */
|
||||
export const toThousandths = (v: number): number => Math.round(v * 1000) / 1000;
|
||||
|
||||
export interface FieldOptions {
|
||||
/** Takes the whole row of the form instead of half of it. */
|
||||
wide?: boolean;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const fieldClass = (o: FieldOptions) => (o.wide ? "nf-field nf-wide" : "nf-field");
|
||||
|
||||
/** A labelled number input. Only valid numbers are passed on. */
|
||||
export function numberField(host: EditorHost, label: string, value: number, onChange: (v: number) => void, step = 0.01, min?: number): TemplateResult {
|
||||
return html`<label class="nf-field"
|
||||
>${label}
|
||||
<input
|
||||
type="number"
|
||||
inputmode="decimal"
|
||||
step=${step}
|
||||
min=${min ?? nothing}
|
||||
.value=${String(toThousandths(value))}
|
||||
?disabled=${!host.admin}
|
||||
@change=${(e: Event) => {
|
||||
const v = typedNumber(valueOf(e));
|
||||
if (Number.isFinite(v)) onChange(v);
|
||||
}}
|
||||
/>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A labelled text input; the stored text is trimmed. */
|
||||
export function textField(host: EditorHost, label: string, value: string, onChange: (v: string) => void, o: FieldOptions & { placeholder?: string; maxlength?: number } = {}): TemplateResult {
|
||||
return html`<label class=${fieldClass(o)} title=${o.title ?? nothing}
|
||||
>${label}
|
||||
<input type="text" .value=${value} placeholder=${o.placeholder ?? nothing} maxlength=${o.maxlength ?? nothing} ?disabled=${!host.admin} @change=${(e: Event) => onChange(valueOf(e).trim())} />
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A labelled drop-down of fixed choices. */
|
||||
export function selectField<T extends string>(host: EditorHost, label: string, value: T, choices: readonly (readonly [T, string])[], onChange: (v: T) => void, o: FieldOptions = {}): TemplateResult {
|
||||
return html`<label class=${fieldClass(o)} title=${o.title ?? nothing}
|
||||
>${label}
|
||||
<select ?disabled=${!host.admin} @change=${(e: Event) => onChange(valueOf(e) as T)}>
|
||||
${choices.map(([v, text]) => html`<option value=${v} ?selected=${v === value}>${text}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** A checkbox with its text. */
|
||||
export function checkField(host: EditorHost, label: string, checked: boolean, onChange: (on: boolean) => void, o: FieldOptions = {}): TemplateResult {
|
||||
return html`<label class="nf-check ${o.wide === false ? "" : "nf-wide"}" title=${o.title ?? nothing}
|
||||
><input type="checkbox" .checked=${checked} ?disabled=${!host.admin} @change=${(e: Event) => onChange((e.target as HTMLInputElement).checked)} />
|
||||
${label}</label
|
||||
>`;
|
||||
}
|
||||
|
||||
/** A colour ("#rrggbb"), or null for the default `fallback`; a button goes back to the default. */
|
||||
export function colorField(host: EditorHost, label: string, value: string | null | undefined, fallback: string, onChange: (v: string | null) => void): TemplateResult {
|
||||
return html`<label class="nf-field"
|
||||
>${label}
|
||||
<span class="nf-color-row"
|
||||
><input type="color" .value=${value ?? fallback} ?disabled=${!host.admin} @change=${(e: Event) => onChange((e.target as HTMLInputElement).value)} />
|
||||
${value ? html`<button type="button" class="nf-link" ?disabled=${!host.admin} @click=${() => onChange(null)}>${host.t("wall_paint_default")}</button>` : nothing}</span
|
||||
></label
|
||||
>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A searchable picker for an entity. `auto` is what "automatic" would choose: a name, null for "nothing found", or undefined when
|
||||
* there is no automatic choice. The stored value is null for automatic, "none" for none, and the entity id otherwise.
|
||||
*/
|
||||
export function entityField(host: EditorHost, label: string, value: string | null, auto: string | null | undefined, options: EntityOption[], onChange: (v: string | null) => void): TemplateResult {
|
||||
const autoText = auto === undefined ? null : auto ? host.t("entity_auto", { name: entityName(host.hass, auto) }) : host.t("entity_auto_none");
|
||||
// the fixed choices (automatic, none) come first, then the entities filtered as one types
|
||||
const fixed = [...(autoText !== null ? [{ id: "__auto", label: autoText }] : []), { id: "none", label: host.t("entity_none") }];
|
||||
const current = value ?? (autoText !== null ? "__auto" : "none");
|
||||
return html`<label class="nf-field nf-wide"
|
||||
>${label}
|
||||
<nf-entity-picker
|
||||
.options=${options}
|
||||
.fixed=${fixed}
|
||||
.value=${current}
|
||||
.placeholder=${host.t("entity_search")}
|
||||
?disabled=${!host.admin}
|
||||
@change=${(e: CustomEvent<{ value: string }>) => {
|
||||
e.stopPropagation();
|
||||
onChange(e.detail.value === "__auto" ? null : e.detail.value);
|
||||
}}
|
||||
></nf-entity-picker>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** The icon a device shows in the editor, as in 3D: the one picked in the plan, else a plugin's; null: its kind's drawing. */
|
||||
export function deviceIcon(host: EditorHost, entityId: string, own?: string | null): string | null {
|
||||
if (own) return (own.startsWith("mdi:") ? own : `mdi:${own}`).replace(/[^a-z0-9:-]/gi, "");
|
||||
return host.hass ? pluginMdiIcon(host.hass, entityId) : null;
|
||||
}
|
||||
|
||||
/** The icon of a marker: a Material Design icon name, with a small preview. */
|
||||
export function iconField(host: EditorHost, value: string | null | undefined, onChange: (v: string | null) => void): TemplateResult {
|
||||
const preview = value ? (value.startsWith("mdi:") ? value : `mdi:${value}`).replace(/[^a-z0-9:-]/gi, "") : "";
|
||||
return html`<label class="nf-field nf-wide" title=${host.t("marker_icon_hint")}
|
||||
>${host.t("marker_icon")}
|
||||
<span class="nf-icon-row">
|
||||
<input type="text" placeholder="mdi:thermometer" .value=${value ?? ""} ?disabled=${!host.admin} @change=${(e: Event) => onChange(valueOf(e).trim().replace(/^mdi:/, "") || null)} />
|
||||
${preview ? unsafeHTML(`<ha-icon icon="${preview}"></ha-icon>`) : nothing}
|
||||
</span>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** How the marker of a device or a piece of furniture shows in 3D. */
|
||||
export function markerField(host: EditorHost, value: MarkerShow | null, onChange: (v: MarkerShow | null) => void): TemplateResult {
|
||||
return html`<label class="nf-field nf-wide" title=${host.t("marker_show_hint")}
|
||||
>${host.t("marker_show")}
|
||||
<select ?disabled=${!host.admin} @change=${(e: Event) => onChange((valueOf(e) || null) as MarkerShow | null)}>
|
||||
<option value="" ?selected=${!value}>${host.t("marker_show_auto")}</option>
|
||||
${MARKER_SHOWS.map((m) => html`<option value=${m} ?selected=${m === value}>${host.t(`marker_show_${m}` as I18nKey)}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** Moving a pin by hand (devices close together): metres along x and z and up, folded until used. */
|
||||
export function pinShiftField(host: EditorHost, value: PinOffset | null | undefined, onChange: (v: PinOffset | null) => void): TemplateResult {
|
||||
const v = value ?? {};
|
||||
const set = (key: keyof PinOffset) => (n: number) => {
|
||||
const next = { ...v, [key]: Math.round(Math.max(-5, Math.min(5, n)) * 100) / 100 };
|
||||
onChange(next.x || next.z || next.y ? next : null);
|
||||
};
|
||||
return html`<details class="nf-wide nf-pin-shift" ?open=${!!value}>
|
||||
<summary>${host.t("pin_shift")}</summary>
|
||||
<div class="nf-form">
|
||||
${numberField(host, "↔ x", v.x ?? 0, set("x"), 0.05)} ${numberField(host, "↕ z", v.z ?? 0, set("z"), 0.05)} ${numberField(host, host.t("pin_shift_up"), v.y ?? 0, set("y"), 0.05)}
|
||||
${value ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => onChange(null)}>${host.t("height_auto")}</button>` : nothing}
|
||||
<p class="nf-sub nf-wide">${host.t("pin_shift_hint")}</p>
|
||||
</div>
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** A row of buttons at the bottom of a form. */
|
||||
export const actions = (...buttons: (TemplateResult | typeof nothing)[]): TemplateResult => html`<div class="nf-actions">${buttons}</div>`;
|
||||
|
||||
/** A help line under a form. */
|
||||
export const hint = (text: string, extraClass = ""): TemplateResult => html`<p class="nf-sub ${extraClass}">${text}</p>`;
|
||||
|
||||
/** A percentage between 10 and 150 for how strongly a lamp glows. 100 % is stored as "no value of its own". */
|
||||
export function glowField(host: EditorHost, value: number | null | undefined, onChange: (v: number | null) => void, o: { label?: I18nKey; hint?: I18nKey; lowest?: number } = {}): TemplateResult {
|
||||
const lowest = o.lowest ?? 10;
|
||||
return html`<label class="nf-field" title=${host.t(o.hint ?? "glow_scale_hint")}
|
||||
>${host.t(o.label ?? "glow_scale")}
|
||||
<input
|
||||
type="number"
|
||||
min=${lowest}
|
||||
max="150"
|
||||
step="5"
|
||||
.value=${String(Math.round((value ?? 1) * 100))}
|
||||
?disabled=${!host.admin}
|
||||
@change=${(e: Event) => {
|
||||
const typed = Number(valueOf(e));
|
||||
const fraction = Math.min(150, Math.max(lowest, valueOf(e).trim() === "" || Number.isNaN(typed) ? 100 : typed)) / 100;
|
||||
onChange(Math.abs(fraction - 1) < 0.001 ? null : fraction);
|
||||
}}
|
||||
/>
|
||||
</label>`;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// First steps in the editor: a short tour on the first start (four cards, skippable), and the sheet of the editor's keys (press ?).
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import type { I18nKey } from "../../i18n.ts";
|
||||
|
||||
const TOUR_KEY = "nextfloor.tour_done";
|
||||
|
||||
/** The keys of the editor and what they do (the texts are in the language files). */
|
||||
export const KEYS: readonly (readonly [string, I18nKey])[] = [
|
||||
["Ctrl Z", "keys_undo"],
|
||||
["Ctrl Shift Z · Ctrl Y", "keys_redo"],
|
||||
["Ctrl D", "keys_duplicate"],
|
||||
["Entf / Delete", "keys_delete"],
|
||||
["← ↑ → ↓", "keys_nudge"],
|
||||
["Shift + ←↑→↓", "keys_nudge_10"],
|
||||
["Alt + ←↑→↓", "keys_nudge_1"],
|
||||
["R · Shift R", "keys_rotate"],
|
||||
["L", "keys_lock"],
|
||||
["Enter", "keys_close_shape"],
|
||||
["Esc", "keys_escape"],
|
||||
["Shift", "keys_straight"],
|
||||
["?", "keys_sheet"],
|
||||
];
|
||||
|
||||
export const TOUR_STEPS: readonly (readonly [I18nKey, I18nKey])[] = [
|
||||
["tour_1_title", "tour_1"],
|
||||
["tour_2_title", "tour_2"],
|
||||
["tour_3_title", "tour_3"],
|
||||
["tour_4_title", "tour_4"],
|
||||
];
|
||||
|
||||
/** Whether the tour is still due on this browser (storage may be blocked: then it is not shown again and again). */
|
||||
export function tourDue(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(TOUR_KEY) !== "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function tourDone(): void {
|
||||
try {
|
||||
localStorage.setItem(TOUR_KEY, "1");
|
||||
} catch {
|
||||
// no storage: the tour simply closes
|
||||
}
|
||||
}
|
||||
|
||||
export function renderKeySheet(t: (key: I18nKey) => string, close: () => void): TemplateResult {
|
||||
return html`<div class="nf-keys" role="dialog" aria-label=${t("keys_title")} @click=${(e: Event) => e.target === e.currentTarget && close()}>
|
||||
<div class="nf-keys-card">
|
||||
<div class="nf-h3row"><h3>⌨ ${t("keys_title")}</h3><button class="nf-btn nf-field-btn" aria-label=${t("close")} @click=${close}>✕</button></div>
|
||||
<dl>
|
||||
${KEYS.map(([keys, text]) => html`<dt>${keys.split(" · ").map((k, i) => html`${i ? " · " : ""}<kbd>${k}</kbd>`)}</dt><dd>${t(text)}</dd>`)}
|
||||
</dl>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The buttons the tour names, in the words the editor shows them with. */
|
||||
function buttonNames(t: (key: I18nKey, vars?: Record<string, string | number>) => string): Record<string, string> {
|
||||
return {
|
||||
rect: t("tool_rect"),
|
||||
free: t("tool_polygon"),
|
||||
rooms: t("area_rooms", { n: "…" }).replace(/\s*\(…\)\s*$/, ""),
|
||||
opening: t("tool_opening"),
|
||||
furniture: t("tool_furniture"),
|
||||
split: t("split_3d"),
|
||||
check: t("check_open"),
|
||||
};
|
||||
}
|
||||
|
||||
export function renderTour(t: (key: I18nKey, vars?: Record<string, string | number>) => string, step: number | null, go: (step: number | null) => void): TemplateResult | typeof nothing {
|
||||
if (step === null || step >= TOUR_STEPS.length) return nothing;
|
||||
const [title, text] = TOUR_STEPS[step];
|
||||
const last = step === TOUR_STEPS.length - 1;
|
||||
return html`<div class="nf-tour" role="dialog" aria-label=${t("tour_title")}>
|
||||
<div class="nf-tour-step">${step + 1} / ${TOUR_STEPS.length}</div>
|
||||
<h3>${t(title)}</h3>
|
||||
<p>${t(text, buttonNames(t))}</p>
|
||||
<div class="nf-actions">
|
||||
${step > 0 ? html`<button class="nf-btn" @click=${() => go(step - 1)}>‹ ${t("tour_back")}</button>` : nothing}
|
||||
<button class="nf-btn nf-primary" @click=${() => go(last ? null : step + 1)}>${t(last ? "tour_done" : "tour_next")}</button>
|
||||
${last ? nothing : html`<button class="nf-link" @click=${() => go(null)}>${t("tour_skip")}</button>`}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// The row that bends a wall into an arc: how far it bulges, and the buttons to bend it or leave it straight.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { numberField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
/** The arc being set up for one wall (`key` names the wall), with the typed bulge and why the last try did not bend it. */
|
||||
export interface ArcEdit {
|
||||
key: string;
|
||||
bulge: number;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface ArcActions {
|
||||
edit: ArcEdit | null;
|
||||
setEdit(edit: ArcEdit | null): void;
|
||||
/** Bends the wall named by the edit's key by the edit's bulge. */
|
||||
apply(edit: ArcEdit): void;
|
||||
}
|
||||
|
||||
/** The ◠ button that opens the arc row of a wall, or closes it again. */
|
||||
export function arcButton(host: EditorHost, key: string, actions: ArcActions): TemplateResult | typeof nothing {
|
||||
if (!host.admin) return nothing;
|
||||
const open = actions.edit?.key === key;
|
||||
return html`<button class="nf-btn" aria-pressed=${open} title=${host.t("arc_hint")} @click=${() => actions.setEdit(open ? null : { key, bulge: 0.5, error: null })}>
|
||||
◠ ${host.t("arc")}
|
||||
</button>`;
|
||||
}
|
||||
|
||||
/** The arc row of a wall while it is open: the bulge and the button that bends the wall. */
|
||||
export function arcRow(host: EditorHost, key: string, actions: ArcActions): TemplateResult | typeof nothing {
|
||||
const edit = actions.edit;
|
||||
if (!host.admin || edit?.key !== key) return nothing;
|
||||
const t = host.t;
|
||||
return html`<span class="nf-wide nf-split-row" title=${t("arc_bulge_hint")}
|
||||
>${numberField(host, t("arc_bulge"), edit.bulge, (bulge) => actions.setEdit({ ...edit, bulge, error: null }), 0.05)}
|
||||
<button class="nf-btn nf-primary" ?disabled=${Math.abs(edit.bulge) < 0.01} @click=${() => actions.apply(edit)}>${t("arc_apply")}</button></span
|
||||
>
|
||||
${edit.error ? html`<p class="nf-sub nf-wide nf-notice">${edit.error}</p>` : nothing}`;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber } from "../../../i18n.ts";
|
||||
import type { Floor } from "../../../model.ts";
|
||||
import type { BackgroundTool } from "../background-tool.ts";
|
||||
import { hint, numberField, toThousandths, typedNumber } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
const MIN_WIDTH = 0.1;
|
||||
|
||||
/** A wide button that is pressed while its mode is on. */
|
||||
const modeButton = (pressed: boolean, label: string, onClick: () => void) => html`<button class="nf-btn nf-wide ${pressed ? "nf-primary" : ""}" aria-pressed=${pressed} @click=${onClick}>${label}</button>`;
|
||||
|
||||
/** The measuring tools below the calibrating buttons: what to tap, and once two points are set, the length to type. */
|
||||
function rulerSteps(host: EditorHost, tool: BackgroundTool): TemplateResult | typeof nothing {
|
||||
const points = tool.ruler;
|
||||
if (!points) return nothing;
|
||||
if (points.length < 2) return hint(host.t(points.length > 0 ? "bg_ruler_second" : "bg_ruler_first"), "nf-wide");
|
||||
const measured = Math.hypot(points[1][0] - points[0][0], points[1][1] - points[0][1]);
|
||||
const apply = () => tool.applyRuler();
|
||||
return html`${hint(host.t("bg_ruler_length_hint", { m: formatNumber(host.hass, measured, 2) }), "nf-wide")}
|
||||
<label class="nf-field"
|
||||
>${host.t("bg_ruler_length")}
|
||||
<input
|
||||
type="number"
|
||||
min="0.01"
|
||||
step="0.01"
|
||||
.value=${tool.rulerLength ? String(tool.rulerLength) : ""}
|
||||
@input=${(e: Event) => (tool.rulerLength = typedNumber((e.target as HTMLInputElement).value) || 0)}
|
||||
@keydown=${(e: KeyboardEvent) => e.key === "Enter" && apply()}
|
||||
/>
|
||||
</label>
|
||||
<button class="nf-btn nf-primary" ?disabled=${!(tool.rulerLength > 0)} @click=${apply}>${host.t("bg_ruler_apply")}</button>`;
|
||||
}
|
||||
|
||||
/** The buttons that change how the picture sits in the plan: move and scale, straighten, measure. Only for admins. */
|
||||
function calibration(host: EditorHost, tool: BackgroundTool): TemplateResult | typeof nothing {
|
||||
if (!host.admin) return nothing;
|
||||
const t = host.t;
|
||||
const levelling = tool.level;
|
||||
return html`${modeButton(tool.edit, t(tool.edit ? "background_edit_done" : "background_edit"), () => tool.toggleEdit())}
|
||||
${hint(t(tool.edit ? "background_handles_hint" : "background_fixed_hint"), "nf-wide")}
|
||||
${modeButton(!!levelling, `📐 ${t(levelling ? "bg_level_cancel" : "bg_level")}`, () => tool.toggleLevel())}
|
||||
${levelling ? hint(t(levelling.length > 0 ? "bg_level_second" : "bg_level_first"), "nf-wide") : nothing}
|
||||
${modeButton(!!tool.ruler, `📏 ${t(tool.ruler ? "bg_ruler_cancel" : "bg_ruler")}`, () => tool.toggleRuler())}
|
||||
${rulerSteps(host, tool)}`;
|
||||
}
|
||||
|
||||
/** The section for the floor's background picture: add one, place it, calibrate it, set how see-through it is, remove it. */
|
||||
export function renderBackgroundForm(host: EditorHost, tool: BackgroundTool, floor: Floor): TemplateResult {
|
||||
const bg = floor.background;
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<NonNullable<typeof bg>>) => bg && tool.setBackground({ ...bg, ...patch });
|
||||
return html`<details class="nf-section" ?open=${tool.open} @toggle=${(e: Event) => (tool.open = (e.target as HTMLDetailsElement).open)}>
|
||||
<summary>${t("background")}</summary>
|
||||
<div class="nf-form">
|
||||
<label class="nf-btn nf-wide nf-upload"
|
||||
>${t("background_upload")}<input
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
@change=${(e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
void tool.upload(file);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
${bg
|
||||
? html`${numberField(host, t("x"), bg.x, (v) => set({ x: v }))} ${numberField(host, t("z"), bg.z, (v) => set({ z: v }))}
|
||||
${numberField(host, t("background_width"), bg.width, (v) => set({ width: Math.max(MIN_WIDTH, v) }), 0.01, MIN_WIDTH)}
|
||||
${numberField(host, t("background_rotation"), bg.rotation ?? 0, (v) => set({ rotation: Math.round(v * 10) / 10 }), 0.5)}
|
||||
${calibration(host, tool)}
|
||||
<label class="nf-field"
|
||||
>${t("background_opacity")}
|
||||
<input type="range" min="0.05" max="1" step="0.05" .value=${String(toThousandths(bg.opacity))} @change=${(e: Event) => set({ opacity: Number.parseFloat((e.target as HTMLInputElement).value) })} />
|
||||
</label>
|
||||
<button class="nf-btn nf-danger nf-wide" @click=${() => tool.setBackground(null)}>${t("background_remove")}</button>`
|
||||
: nothing}
|
||||
</div>
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { furnitureName } from "../../../furniture-names.ts";
|
||||
import type { DiffEntry } from "../ops/plan-diff.ts";
|
||||
import type { BackupService } from "../backup.ts";
|
||||
import { actions, hint } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
/** A button that opens a file chooser and hands the chosen file on; the input is emptied so the same file can be chosen again. */
|
||||
const filePicker = (label: string, onFile: (file: File | undefined) => void, accept = "application/json,.json") => html`<label class="nf-btn nf-upload"
|
||||
>${label}<input
|
||||
type="file"
|
||||
accept=${accept}
|
||||
@change=${(e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
onFile(file);
|
||||
}}
|
||||
/>
|
||||
</label>`;
|
||||
|
||||
const DIFF_ICON: Record<string, string> = { added: "+", removed: "−", renamed: "✎", reshaped: "⤢", moved: "↔" };
|
||||
|
||||
/** What differs between a restore point and the plan, floor by floor. */
|
||||
function renderDiff(host: EditorHost, entries: readonly DiffEntry[]): TemplateResult {
|
||||
const t = host.t;
|
||||
if (!entries.length) return html`<p class="nf-sub nf-diff">${t("version_same")}</p>`;
|
||||
const nameOf = (e: DiffEntry): string => {
|
||||
if (e.kind.startsWith("furniture")) return furnitureName(host.hass, e.name) || e.name;
|
||||
if (e.kind.startsWith("device")) return String(host.hass?.states[e.name]?.attributes.friendly_name ?? e.name);
|
||||
if (e.kind.startsWith("opening")) return t(e.name === "door" ? "opening_door" : e.name === "garage" ? "opening_garage" : "opening_window");
|
||||
return e.name;
|
||||
};
|
||||
const floors = [...new Set(entries.map((e) => e.floor))];
|
||||
return html`<div class="nf-diff">
|
||||
${hint(t("version_diff_n", { n: entries.length }))}
|
||||
${floors.map(
|
||||
(floor) => html`<h4 class="nf-check-floor">${floor}</h4>
|
||||
<ul class="nf-diff-list">
|
||||
${entries
|
||||
.filter((e) => e.floor === floor)
|
||||
.map((e) => {
|
||||
const verb = e.kind.slice(e.kind.indexOf("_") + 1);
|
||||
const detail = typeof e.detail === "number" ? `${e.detail > 0 ? "+" : ""}${formatNumber(host.hass, e.detail, 1)}` : (e.detail ?? "");
|
||||
return html`<li><span aria-hidden="true">${DIFF_ICON[verb] ?? "•"}</span> ${t(`diff_${e.kind}` as I18nKey, { name: nameOf(e), detail })}</li>`;
|
||||
})}
|
||||
</ul>`,
|
||||
)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** Restore points, a plan file, and the full backup. The restore points load when the section is opened. */
|
||||
export function renderBackup(host: EditorHost, service: BackupService): TemplateResult {
|
||||
const t = host.t;
|
||||
const points = service.history;
|
||||
const list =
|
||||
points === null
|
||||
? hint(t("loading"))
|
||||
: points.length === 0
|
||||
? hint(t("backup_none"))
|
||||
: html`<div class="nf-room-list">
|
||||
${points.map(
|
||||
(p) => html`<div class="nf-row nf-dev-row">
|
||||
<span>${p.name ? html`<b>📌 ${p.name}</b> · ` : nothing}${service.timeOf(p)} <span class="nf-muted">· ${t("backup_summary", { rooms: p.rooms, furniture: p.furniture })}</span></span>
|
||||
<span class="nf-version-actions">
|
||||
<button class="nf-link" aria-pressed=${service.compare?.snapshot.id === p.id} @click=${() => void service.compareWith(p)}>${t("version_compare")}</button>
|
||||
<button class="nf-link" @click=${() => service.restorePoint(p)}>${t("backup_restore")}</button>
|
||||
${p.name ? html`<button class="nf-link" title=${t("delete")} @click=${() => void service.deleteVersion(p)}>✕</button>` : nothing}
|
||||
</span>
|
||||
</div>
|
||||
${service.compare?.snapshot.id === p.id ? renderDiff(host, service.compare.entries) : nothing}`,
|
||||
)}
|
||||
</div>`;
|
||||
return html`<details class="nf-section" @toggle=${(e: Event) => (e.target as HTMLDetailsElement).open && void service.loadHistory()}>
|
||||
<summary>${t("backup")}</summary>
|
||||
<h4 class="nf-lib-head">${t("backup_history")}</h4>
|
||||
${actions(html`<button class="nf-btn" title=${t("version_save_hint")} @click=${() => void service.saveVersion()}>📌 ${t("version_save")}</button>`)}
|
||||
${list}
|
||||
<h4 class="nf-lib-head">${t("backup_file")}</h4>
|
||||
${actions(
|
||||
html`<button class="nf-btn" @click=${() => service.exportPlan(false)}>${t("backup_export")}</button>`,
|
||||
html`<button class="nf-btn" title=${t("backup_export_share_hint")} @click=${() => service.exportPlan(true)}>${t("backup_export_share")}</button>`,
|
||||
html`<button class="nf-btn" title=${t("share_view_hint")} @click=${() => service.exportShareView()}>🔗 ${t("share_view")}</button>`,
|
||||
filePicker(t("backup_import"), (file) => void service.importPlan(file), "application/json,.json,.sh3d,.dxf,.ifc"),
|
||||
)}
|
||||
${hint(t("backup_hint"))} ${hint(t("import_other_hint"))}
|
||||
<h4 class="nf-lib-head">${t("backup_full")}</h4>
|
||||
${actions(
|
||||
html`<button class="nf-btn" ?disabled=${service.busy} @click=${() => service.exportFull()}>${service.busy ? "…" : t("backup_full_export")}</button>`,
|
||||
filePicker(t("backup_full_import"), (file) => void service.importFull(file)),
|
||||
)}
|
||||
${hint(t("backup_full_hint"))}
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// The compass of the plan: where north lies, with a dial and the quick turns. Turning it never touches the drawing, the roof
|
||||
// fields or the furniture; only what depends on the compass follows (the sun's light, wind, the compass labels of roof faces).
|
||||
|
||||
import { html, svg, type TemplateResult } from "lit";
|
||||
import { numberField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { turnedNorth } from "../ops/settings.ts";
|
||||
|
||||
export function renderCompass(host: EditorHost, north: number, set: (north: number) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const turn = (by: number) => () => set(turnedNorth(north, by));
|
||||
const dial = svg`<svg class="nf-compass-dial" viewBox="-50 -50 100 100" role="img" aria-label=${t("compass_title")}>
|
||||
<circle r="46" class="nf-compass-ring" />
|
||||
<path d="M0 -50l3 6h-6z" class="nf-compass-up" />
|
||||
<g transform="rotate(${north})">
|
||||
<path d="M0 -38L8 0H-8z" class="nf-compass-n" />
|
||||
<path d="M0 38L8 0H-8z" class="nf-compass-s" />
|
||||
<text y="-27" class="nf-compass-label">${t("compass_n_short")}</text>
|
||||
<text y="36" class="nf-compass-label nf-compass-label-s">${t("compass_s_short")}</text>
|
||||
</g>
|
||||
</svg>`;
|
||||
return html`<div class="nf-compass nf-wide">
|
||||
${dial}
|
||||
<div class="nf-compass-side">
|
||||
<b>${t("compass_title")}</b>
|
||||
${numberField(host, t("north"), north, (v) => set(turnedNorth(v, 0)), 1)}
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("compass_swap_hint")} @click=${turn(180)}>⇅ ${t("compass_swap")}</button>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(-90)}>↺ 90°</button>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(90)}>↻ 90°</button>
|
||||
</div>
|
||||
<span class="nf-sub">${t("compass_hint")}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// The device list of a room: the entities of its area to place, the rows with their pins, and the room's climate sensors.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { CLIMATE_CLASSES, entityAreaId, entityKind, entityName, groupByDevice, isPlaceable, isRoomClimateSensor, kindOf, otherAreaEntities, roomClimateSensors, unassignedEntities, type ClimateKey, roomEntities } from "../../../devices.ts";
|
||||
import { iconPath } from "../../../icons.ts";
|
||||
import { pointInPolygon, type Room } from "../../../model.ts";
|
||||
import { entityOptions, isNumeric } from "../entities.ts";
|
||||
import { deviceIcon, entityField, hint } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "../ops/device-list.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
|
||||
/** What the list makes the editor do. */
|
||||
export interface DeviceListActions {
|
||||
select(entityId: string): void;
|
||||
place(entityIds: string[]): void;
|
||||
remove(entityId: string): void;
|
||||
patchRoom(patch: Partial<Room>): void;
|
||||
spreadLights(room: Room): void;
|
||||
confirm(text: string): boolean;
|
||||
}
|
||||
|
||||
/** How many entities of other areas are listed at once; the search narrows the rest. */
|
||||
const LIST_LIMIT = 50;
|
||||
|
||||
type Row = (id: string, extra?: boolean, areaName?: string) => TemplateResult;
|
||||
|
||||
/** One of the little buttons at the end of a row that switches a list of the room on or off for this entity. */
|
||||
function roomFlag(host: EditorHost, list: readonly string[], id: string, key: "hidden" | "no_state" | "panel", symbols: [string, string], titles: [string, string], actions: DeviceListActions): TemplateResult {
|
||||
const on = list.includes(id);
|
||||
return html`<button class="nf-pin ${on ? "nf-pin-on" : ""}" aria-pressed=${on} title=${host.t((on ? titles[0] : titles[1]) as never)} @click=${() => actions.patchRoom({ [key]: withToggled(list, id) })}>${on ? symbols[0] : symbols[1]}</button>`;
|
||||
}
|
||||
|
||||
/** The row of an entity: its name (to select its pin), the room flags, and a button to place or remove it. */
|
||||
function rowFor(host: EditorHost, room: Room, here: Set<string>, elsewhere: Map<string, string>, areaName: string | undefined, actions: DeviceListActions): Row {
|
||||
const [hidden, noState, pinned] = [room.hidden ?? [], room.no_state ?? [], room.panel ?? []];
|
||||
return (id, extra = false, nameArea = areaName) => {
|
||||
const placed = here.has(id);
|
||||
const other = placed ? undefined : elsewhere.get(id);
|
||||
const isHidden = hidden.includes(id);
|
||||
const icon = deviceIcon(host, id);
|
||||
return html`<div class="nf-row nf-dev-row ${extra ? "nf-dev-extra" : ""} ${isHidden ? "nf-dev-hidden" : ""}">
|
||||
<button class="nf-dev-name ${placed ? "" : "nf-muted"}" ?disabled=${!placed} @click=${() => actions.select(id)}>
|
||||
${icon
|
||||
? html`<ha-icon class="nf-dev-icon" style="--mdc-icon-size:16px" .icon=${icon}></ha-icon>`
|
||||
: html`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d=${iconPath((host.hass ? entityKind(host.hass, id) : kindOf(id)) ?? "sensor")} /></svg>`}
|
||||
<span>${entityName(host.hass, id, nameArea)}${other ? html`<small class="nf-muted"> · ${host.t("devices_placed_in", { room: other })}</small>` : nothing}</span>
|
||||
</button>
|
||||
${host.admin ? roomFlag(host, hidden, id, "hidden", ["🙈", "👁"], ["panel_unhide", "panel_hide"], actions) : nothing}
|
||||
${host.admin && !isHidden ? roomFlag(host, noState, id, "no_state", ["∅", "Aa"], ["panel_state_show", "panel_state_hide"], actions) : nothing}
|
||||
${host.admin && !placed ? roomFlag(host, pinned, id, "panel", ["★", "☆"], ["panel_unpin", "panel_pin"], actions) : nothing}
|
||||
${host.admin
|
||||
? placed
|
||||
? html`<button class="nf-link" @click=${() => actions.remove(id)}>${host.t("devices_remove")}</button>`
|
||||
: html`<button class="nf-link" @click=${() => actions.place([id])}>${host.t("devices_place")}</button>`
|
||||
: nothing}
|
||||
</div>`;
|
||||
};
|
||||
}
|
||||
|
||||
/** Entities of other areas, or without an area, as extra rows (computed only when shown). */
|
||||
function extras(host: EditorHost, state: SideState, room: Room, row: Row, source: "other" | "none"): TemplateResult {
|
||||
const { hass } = host;
|
||||
if (!hass) return html``;
|
||||
const narrow = (n: number) => (n > 0 ? hint(host.t("devices_narrow", { n })) : nothing);
|
||||
const none = hint(host.t("devices_none"));
|
||||
const query = state.deviceQuery;
|
||||
if (source === "other") {
|
||||
const areas = otherAreaEntities(hass, room.area_id).map((a) => ({ ...a, ids: a.ids.filter((id) => matchesQuery(query, `${entityName(hass, id, a.name)} ${id} ${a.name}`)) }));
|
||||
const { taken, left } = takeFirst(areas, LIST_LIMIT);
|
||||
const blocks = areas.map((a, i) => (taken[i].length > 0 ? html`<div class="nf-dev-area">${a.name}</div>${taken[i].map((id) => row(id, false, a.name))}` : nothing));
|
||||
return taken.some((ids) => ids.length > 0) ? html`<div class="nf-room-list">${blocks}</div>${narrow(left)}` : none;
|
||||
}
|
||||
const ids = unassignedEntities(hass).filter((id) => matchesQuery(query, `${entityName(hass, id)} ${id} `));
|
||||
return ids.length > 0 ? html`<div class="nf-room-list">${ids.slice(0, LIST_LIMIT).map((id) => row(id))}</div>${narrow(ids.length - Math.min(ids.length, LIST_LIMIT))}` : none;
|
||||
}
|
||||
|
||||
/** The entities of the room's area, grouped by device with the device's main entity first. */
|
||||
function areaList(host: EditorHost, state: SideState, room: Room, row: Row, here: Set<string>, areaName: string | undefined, actions: DeviceListActions): TemplateResult {
|
||||
const { hass } = host;
|
||||
const ids = hass ? roomEntities(hass, room).filter((id) => isPlaceable(entityKind(hass, id))) : [];
|
||||
if (!room.area_id) return hint(host.t("devices_none_area"));
|
||||
if (ids.length === 0) return hint(host.t("devices_none"));
|
||||
const groups = hass ? groupByDevice(hass, ids) : [];
|
||||
// the automatic placement only takes the main entity of each device
|
||||
const unplaced = groups.map((g) => g.primary).filter((id) => !here.has(id));
|
||||
const query = state.deviceQuery;
|
||||
const ceilingLights = (host.floor?.placements ?? []).filter((p) => kindOf(p.entity_id) === "light" && (p.mount ?? "ceiling") === "ceiling" && pointInPolygon([p.x, p.z], room.points)).length;
|
||||
const search = html`<input class="nf-search" type="search" placeholder=${host.t("devices_search")} .value=${query} @input=${(e: Event) => (state.deviceQuery = (e.target as HTMLInputElement).value)} />`;
|
||||
const matches = (id: string) => matchesQuery(query, entityName(hass, id, areaName), id);
|
||||
const group = (g: (typeof groups)[number]) => {
|
||||
const others = g.others.filter(matches);
|
||||
const open = state.isUnfolded(g.primary) || (!!query.trim() && others.length > 0);
|
||||
if (!matches(g.primary) && others.length === 0) return nothing;
|
||||
return html`${row(g.primary)}
|
||||
${g.others.length > 0 ? html`<button class="nf-more" @click=${() => state.toggleUnfolded(g.primary)}>${open ? host.t("devices_less") : host.t("devices_more", { n: g.others.length })}</button>` : nothing}
|
||||
${open ? (query.trim() ? others : g.others).map((id) => row(id, true)) : nothing}`;
|
||||
};
|
||||
const placeAll = () => actions.confirm(host.t("devices_place_all_confirm", { n: unplaced.length })) && actions.place(unplaced);
|
||||
return html`${host.admin && ceilingLights >= 2 ? html`<button class="nf-btn nf-wide-btn" @click=${() => actions.spreadLights(room)}>${host.t("lights_spread")}</button>` : nothing}
|
||||
${ids.length > 8 ? search : nothing}
|
||||
<div class="nf-room-list">${groups.map(group)}</div>
|
||||
${host.admin && unplaced.length > 1 ? html`<button class="nf-link nf-place-all" @click=${placeAll}>${host.t("devices_place_all_n", { n: unplaced.length })}</button>` : nothing}
|
||||
${hint(host.t("devices_hint"))}`;
|
||||
}
|
||||
|
||||
/** The "Devices" section of a room. */
|
||||
export function renderDeviceList(host: EditorHost, state: SideState, room: Room, actions: DeviceListActions): TemplateResult {
|
||||
const { hass } = host;
|
||||
const areaName = room.area_id ? hass?.areas?.[room.area_id]?.name : undefined;
|
||||
const here = placedInRoom(host.floor, room);
|
||||
const row = rowFor(host, room, here, placedElsewhere(host.doc, room), areaName, actions);
|
||||
const source = host.admin ? state.deviceSource : "area";
|
||||
const areaCount = hass ? groupByDevice(hass, roomEntities(hass, room).filter((id) => isPlaceable(entityKind(hass, id)))).length : 0;
|
||||
const sources: ["area" | "other" | "none", string][] = [["area", `${host.t("devices_src_area")}${areaCount > 0 ? ` (${areaCount})` : ""}`], ["other", host.t("devices_src_other")], ["none", host.t("devices_src_none")]];
|
||||
const search = html`<input class="nf-search" type="search" placeholder=${host.t("devices_search")} .value=${state.deviceQuery} @input=${(e: Event) => (state.deviceQuery = (e.target as HTMLInputElement).value)} />`;
|
||||
return html`<section>
|
||||
<h3>${host.t("devices")}</h3>
|
||||
${hint(host.t("devices_panel_hint"))}
|
||||
${host.admin ? html`<div class="nf-seg nf-dev-source">${sources.map(([s, label]) => html`<button aria-pressed=${source === s} @click=${() => (state.deviceSource = s)}>${label}</button>`)}</div>` : nothing}
|
||||
${source !== "area" ? html`${search}${extras(host, state, room, row, source)}` : areaList(host, state, room, row, here, areaName, actions)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** A room's temperature, humidity and CO2 sensors: chosen, or found automatically. */
|
||||
export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: Partial<Room>) => void): TemplateResult | typeof nothing {
|
||||
const { hass } = host;
|
||||
if (!hass) return nothing;
|
||||
const chosen = !!room.climate && Object.values(room.climate).some((x) => x != null);
|
||||
const change = (key: ClimateKey, value: string | string[] | null) => {
|
||||
const next = { ...(room.climate ?? {}), [key]: value };
|
||||
patch({ climate: Object.values(next).every((x) => x == null) ? null : next });
|
||||
};
|
||||
const field = (key: ClimateKey, label: string) => {
|
||||
const found = roomClimateSensors(hass, host.floor ?? null, { ...room, climate: null }, key);
|
||||
const wanted = entityOptions(hass, (id) => isNumeric(id) && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key]);
|
||||
// the room's own sensors first, then the others; device temperatures (a printer, a heat pump) come last
|
||||
const options = rankedBy(wanted, (id) => (entityAreaId(hass, id) === room.area_id ? 0 : 1) + (isRoomClimateSensor(hass, id) ? 0 : 2));
|
||||
const picked = [room.climate?.[key] ?? null].flat();
|
||||
// several sensors are averaged: once one is chosen, another can be added; "none" in a slot drops it
|
||||
const save = (list: (string | null)[]) => {
|
||||
const ids = list.filter((id): id is string => !!id && id !== "none");
|
||||
change(key, list[0] === "none" ? "none" : ids.length > 1 ? ids : (ids[0] ?? null));
|
||||
};
|
||||
const real = picked[0] && picked[0] !== "none";
|
||||
const slots = real ? [...picked, null] : picked;
|
||||
return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x)))));
|
||||
};
|
||||
return html`<details class="nf-points" ?open=${chosen}>
|
||||
<summary>${host.t("climate")}</summary>
|
||||
<div class="nf-form">${field("temperature", host.t("climate_temperature"))} ${field("humidity", host.t("climate_humidity"))} ${field("co2", host.t("climate_co2"))}</div>
|
||||
${hint(host.t("climate_hint"))}
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// The form of a placed device: where it hangs, how high, how it is turned, and how its marker shows.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { defaultHeight, entityKind, entityName, hasScreen, kindOf, TOGGLE_KINDS } from "../../../devices.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { iconPath } from "../../../icons.ts";
|
||||
import { ceilingAt, FURNITURE_TYPES, isLamp, type LampMount, type Placement } from "../../../model.ts";
|
||||
import { packItemLabel, packLabel } from "../../../furniture-names.ts";
|
||||
import { isClimateFurniture, isElectric, isPackType, packType, type FurniturePack } from "../../../packs.ts";
|
||||
import { checkField, deviceIcon, glowField, iconField, markerField, pinShiftField, numberField, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { lightEffectFields } from "../light-effect-fields.ts";
|
||||
import { pluginDeviceSettings, pluginText, settingsWithDefaults } from "../../../plugins/registry.ts";
|
||||
|
||||
export interface DeviceActions {
|
||||
update(patch: Partial<Placement>): void;
|
||||
centre(): void;
|
||||
remove(): void;
|
||||
asFurniture(placed: Placement, type: string): void;
|
||||
packs: readonly FurniturePack[];
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
}
|
||||
|
||||
const SPEAKER_LIKE = /speaker|sound|subwoofer|receiver|smart_|display|tv|media|turntable|projector|console/;
|
||||
|
||||
/** Furniture that can stand for a device of this kind: a speaker for a media player, a lamp for a light, and so on. */
|
||||
export function furnitureFor(host: EditorHost, entityId: string, packs: readonly FurniturePack[]): { type: string; label: string }[] {
|
||||
const kind = kindOf(entityId);
|
||||
const language = host.hass?.language ?? "en";
|
||||
const all = [
|
||||
...FURNITURE_TYPES.map((type) => ({ type: type as string, label: host.t(`furn_${type}` as I18nKey) })),
|
||||
...packs.flatMap((pack) => pack.items.map((item) => ({ type: packType(pack.id, item.id), label: `${packItemLabel(item, packType(pack.id, item.id), language)} · ${packLabel(pack, language)}` }))),
|
||||
];
|
||||
const fits = (type: string): boolean => {
|
||||
if (kind === "light") return isLamp(type);
|
||||
if (kind === "climate") return type === "radiator" || isClimateFurniture(type);
|
||||
if (entityId.startsWith("vacuum.")) return type === "robot_vacuum" || (isPackType(type) && type.endsWith(":robot_vacuum"));
|
||||
if (kind === "media") return hasScreen(type) || (isElectric(type) && SPEAKER_LIKE.test(type));
|
||||
return isElectric(type) && !isLamp(type);
|
||||
};
|
||||
return all.filter((x) => fits(x.type)).sort((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
/** The "show as furniture" drop-down: replaces the pin by a piece of furniture linked to the entity. */
|
||||
function asFurniture(host: EditorHost, placed: Placement, actions: DeviceActions): TemplateResult | typeof nothing {
|
||||
if (!host.admin) return nothing;
|
||||
const options = furnitureFor(host, placed.entity_id, actions.packs);
|
||||
if (options.length === 0) return nothing;
|
||||
return html`<label class="nf-field nf-wide" title=${host.t("as_furniture_hint")}
|
||||
>${host.t("as_furniture")}
|
||||
<select @change=${(e: Event) => (e.target as HTMLSelectElement).value && actions.asFurniture(placed, (e.target as HTMLSelectElement).value)}>
|
||||
<option value="" selected>${host.t("as_furniture_pick")}</option>
|
||||
${options.map((o) => html`<option value=${o.type}>${o.label}</option>`)}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** The fields plugins add for this device (a camera's field of view, say), stored with the placement per plugin. */
|
||||
function pluginFields(host: EditorHost, placed: Placement, set: (patch: Partial<Placement>) => void): TemplateResult[] {
|
||||
const language = host.hass?.language ?? "en";
|
||||
return pluginDeviceSettings(placed.entity_id, host.hass?.states[placed.entity_id]).map(({ pluginId, name, settings }) => {
|
||||
const values = settingsWithDefaults(settings, placed.plugin?.[pluginId]);
|
||||
const store = (key: string, value: string | number | boolean) => set({ plugin: { ...(placed.plugin ?? {}), [pluginId]: { ...(placed.plugin?.[pluginId] ?? {}), [key]: value } } });
|
||||
const fields = settings.map((s) => {
|
||||
const label = pluginText(s.label, language);
|
||||
const title = s.hint ? pluginText(s.hint, language) : undefined;
|
||||
if (s.type === "boolean") return checkField(host, label, values[s.key] === true, (on) => store(s.key, on), { title });
|
||||
if (s.type === "select") {
|
||||
const choices = (s.options ?? []).map(([v, l]): [string, string] => [v, pluginText(l, language)]);
|
||||
return selectField(host, label, String(values[s.key]), choices, (v) => store(s.key, v), { wide: true, title });
|
||||
}
|
||||
const clamp = (v: number) => Math.min(s.max ?? Infinity, Math.max(s.min ?? -Infinity, v));
|
||||
return numberField(host, label, Number(values[s.key]), (v) => store(s.key, clamp(v)), s.step ?? 1, s.min);
|
||||
});
|
||||
return html`<h4 class="nf-lib-head nf-wide">🔌 ${name}</h4>${fields}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** The form of the selected device. */
|
||||
export function renderDeviceForm(host: EditorHost, placed: Placement, actions: DeviceActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const kind = kindOf(placed.entity_id) ?? (host.hass ? entityKind(host.hass, placed.entity_id) : null);
|
||||
const light = kind === "light";
|
||||
const mount = placed.mount ?? "ceiling";
|
||||
const automatic = kind ? defaultHeight(kind, host.floor ? ceilingAt(host.floor, placed.x, placed.z) : 2.5, light ? mount : null) : 1;
|
||||
const set = (patch: Partial<Placement>) => actions.update(patch);
|
||||
const icon = deviceIcon(host, placed.entity_id, placed.icon);
|
||||
const mountChange = (value: LampMount) => set({ mount: value, y: null });
|
||||
const lampMounts = (["ceiling", "floor", "table", "wall"] as const).map((m): [LampMount, string] => [m, t(`lamp_${m}`)]);
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("device")}</h3>${actions.lockButton}</div>
|
||||
<p class="nf-dev-title">
|
||||
${icon
|
||||
? html`<ha-icon class="nf-dev-icon" .icon=${icon}></ha-icon>`
|
||||
: html`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d=${kind ? iconPath(kind) : ""} /></svg>`}
|
||||
${entityName(host.hass, placed.entity_id)}
|
||||
</p>
|
||||
<div class="nf-form">
|
||||
${light ? html`${selectField(host, t("lamp_mount"), mount, lampMounts, mountChange, { wide: true })}${glowField(host, placed.glow_scale, (v) => set({ glow_scale: v }))}` : nothing}
|
||||
${light ? lightEffectFields(host, placed, host.hass?.states[placed.entity_id]?.attributes.effect_list, set) : nothing}
|
||||
${placed.entity_id.startsWith("media_player.") ? glowField(host, placed.sound_rings, (v) => set({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing}
|
||||
${numberField(host, t("x"), placed.x, (v) => set({ x: v }))} ${numberField(host, t("z"), placed.z, (v) => set({ z: v }))}
|
||||
${numberField(host, t("marker_height"), placed.y ?? automatic, (v) => set({ y: Math.max(0, v) }), 0.05, 0)}
|
||||
${numberField(host, t("rotation"), placed.rotation ?? 0, (v) => set({ rotation: ((v % 360) + 360) % 360 }), 1)}
|
||||
${light ? checkField(host, t("device_simple"), !!placed.simple, (on) => set({ simple: on || undefined }), { title: t("device_simple_hint") }) : nothing}
|
||||
${kind && TOGGLE_KINDS.has(kind) ? checkField(host, t("device_confirm"), !!placed.confirm, (on) => set({ confirm: on }), { title: t("device_confirm_hint") }) : nothing}
|
||||
${checkField(host, t("device_outside"), !!placed.outside, (on) => set({ outside: on || undefined }), { title: t("device_outside_hint") })}
|
||||
${markerField(host, placed.marker ?? null, (v) => set({ marker: v }))}
|
||||
${pinShiftField(host, placed.pin_offset, (v) => set({ pin_offset: v }))}
|
||||
${textField(host, t("device_name"), placed.name ?? "", (v) => set({ name: v || null }), { wide: true, maxlength: 60, title: t("device_name_hint"), placeholder: entityName(host.hass, placed.entity_id) })}
|
||||
${placed.name ? checkField(host, t("show_name"), !!placed.show_name, (on) => set({ show_name: on || undefined })) : nothing}
|
||||
${iconField(host, placed.icon, (v) => set({ icon: v }))}
|
||||
${pluginFields(host, placed, set)}
|
||||
</div>
|
||||
${host.admin
|
||||
? html`<div class="nf-actions">
|
||||
<button class="nf-btn" @click=${() => actions.centre()}>${t("device_centre")}</button>
|
||||
${placed.y !== null ? html`<button class="nf-btn" @click=${() => set({ y: null })}>${t("height_auto")}</button>` : nothing}
|
||||
${asFurniture(host, placed, actions)}
|
||||
<button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("devices_remove")}</button>
|
||||
</div>`
|
||||
: nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// The wall list in the room form: one row per wall (or per part of a wall another room splits) with its height, thickness, and the
|
||||
// buttons to remove, cut or join it. Hovering a row lights the wall up in the plan.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import type { Room } from "../../../model.ts";
|
||||
import { hint, numberField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { edgeLength, thicknessFromTyped } from "../ops/edges.ts";
|
||||
import { formatLength } from "../../../units.ts";
|
||||
import { arcButton, arcRow, type ArcActions } from "./arc.ts";
|
||||
|
||||
export interface EdgeActions {
|
||||
/** Shows the wall from the front, with its doors, windows and furniture. */
|
||||
openWall(room: Room, edge: number): void;
|
||||
/** Where the parts of a wall start, along it; one part when it is whole. */
|
||||
partsOf(room: Room, edge: number): number[];
|
||||
/** Whether the wall is an outer wall (it then has the outer default thickness). */
|
||||
isOuter(room: Room, edge: number): boolean;
|
||||
setHeight(room: Room, edge: number, part: number | undefined, height: number | null): void;
|
||||
/** Makes the whole wall slope: its height at the start and at the end of the edge (either may be above the floor height). */
|
||||
setSlope(room: Room, edge: number, start: number, end: number): void;
|
||||
/** Makes a sloping wall level again. */
|
||||
clearSlope(room: Room, edge: number): void;
|
||||
setThickness(room: Room, edge: number, thickness: number | null, part?: number, partCount?: number): void;
|
||||
/** Bending a wall into an arc (the key of a room wall is `room:<id>:<edge>`). */
|
||||
arc: ArcActions;
|
||||
cut(room: Room, edge: number, part: number | undefined): void;
|
||||
moveCut(room: Room, edge: number, from: number, to: number): void;
|
||||
join(room: Room, edge: number, at: number, part: number): void;
|
||||
/** The wall highlighted in the plan. */
|
||||
lit: number | null;
|
||||
light(edge: number | null): void;
|
||||
}
|
||||
|
||||
const FULL_STEP = 0.005;
|
||||
|
||||
/** The key of a room wall in the arc row. */
|
||||
export const arcKey = (room: Room, edge: number): string => `room:${room.id}:${edge}`;
|
||||
|
||||
export function renderEdgeHeights(host: EditorHost, room: Room, actions: EdgeActions): TemplateResult {
|
||||
const t = host.t;
|
||||
// a room with its own ceiling: its walls are "full" at that height
|
||||
const floorHeight = room.ceiling ?? host.floor!.height;
|
||||
const count = room.points.length;
|
||||
const { wall_exterior, wall_interior } = host.doc.settings;
|
||||
const rowsOf = (edge: number) => {
|
||||
const entry = room.wall_heights?.[edge] ?? null;
|
||||
const starts = actions.partsOf(room, edge);
|
||||
const parts: (number | undefined)[] = starts.length > 1 ? starts.map((_, k) => k) : [undefined];
|
||||
return parts.map((part) => {
|
||||
const height = Array.isArray(entry) ? (entry[part ?? 0] ?? null) : entry;
|
||||
const thickEntry = room.wall_thickness?.[edge] ?? null;
|
||||
const thick = Array.isArray(thickEntry) ? (thickEntry[part ?? 0] ?? null) : thickEntry;
|
||||
const length = part === undefined ? edgeLength(room, edge) : (starts[part + 1] ?? edgeLength(room, edge)) - starts[part];
|
||||
const set = (v: number | null) => actions.setHeight(room, edge, part, v);
|
||||
const standard = actions.isOuter(room, edge) ? wall_exterior : wall_interior;
|
||||
const title = `${t("wall_n", { a: edge + 1, b: ((edge + 1) % count) + 1 })}${part === undefined ? "" : ` · ${t("wall_part", { n: part + 1 })}`}`;
|
||||
const cutHere = part !== undefined && part > 0 && (room.wall_splits?.[edge] ?? []).some((d) => Math.abs(d - starts[part]) < 1e-3);
|
||||
const slopeEnd = room.wall_slopes?.[edge];
|
||||
const sloping = part === undefined && typeof slopeEnd === "number" && typeof entry === "number";
|
||||
const start = height ?? floorHeight;
|
||||
const light = () => actions.light(edge);
|
||||
const dark = () => actions.light(null);
|
||||
return html`<div class="nf-edge-height${edge === actions.lit ? " nf-edge-on" : ""}${height !== null ? " nf-edge-low" : ""}" @mouseenter=${light} @mouseleave=${dark} @focusin=${light} @focusout=${dark}>
|
||||
<span><b>${title}</b><br /><span class="nf-muted">${formatLength(host.hass, length)}</span></span>
|
||||
${height === 0
|
||||
? html`<span class="nf-muted">${t("wall_none")}</span>`
|
||||
: sloping
|
||||
? html`<span class="nf-wide nf-split-row" title=${t("wall_slope_hint")}
|
||||
>${numberField(host, t("wall_slope_start"), entry as number, (v) => actions.setSlope(room, edge, v, slopeEnd as number), 0.05, 0.05)}
|
||||
${numberField(host, t("wall_slope_end"), slopeEnd as number, (v) => actions.setSlope(room, edge, entry as number, v), 0.05, 0.05)}</span
|
||||
>`
|
||||
: numberField(host, t("wall_height"), start, (v) => set(v >= floorHeight - FULL_STEP ? null : Math.max(0.05, v)), 0.05, 0.05)}
|
||||
${host.admin && sloping ? html`<button class="nf-btn" title=${t("wall_slope_off")} @click=${() => actions.clearSlope(room, edge)}>▭</button>` : nothing}
|
||||
${host.admin && height !== null && !sloping ? html`<button class="nf-btn" title=${t("wall_height_full")} @click=${() => set(null)}>↥</button>` : nothing}
|
||||
${host.admin && part === undefined && height !== 0 && !sloping
|
||||
? html`<button class="nf-btn" title=${t("wall_slope_hint")} @click=${() => actions.setSlope(room, edge, start, start >= floorHeight - FULL_STEP ? start + 1 : floorHeight)}>∠ ${t("wall_slope")}</button>`
|
||||
: nothing}
|
||||
${host.admin && height !== 0 ? html`<button class="nf-btn" title=${t("wall_none_hint")} @click=${() => set(0)}>${t("wall_none")}</button>` : nothing}
|
||||
${host.admin && length >= 0.4 ? html`<button class="nf-btn" title=${t("wall_split_hint")} @click=${() => actions.cut(room, edge, part)}>✂</button>` : nothing}
|
||||
${part === undefined && length >= 0.4 ? arcButton(host, arcKey(room, edge), actions.arc) : nothing}
|
||||
${(part === undefined || part === 0) && height !== 0 ? html`<button class="nf-btn" title=${t("wall_view_hint")} @click=${() => actions.openWall(room, edge)}>▣ ${t("wall_view")}</button>` : nothing}
|
||||
${height !== 0
|
||||
? html`<span class="nf-wide nf-split-row" title=${t("wall_thickness_hint")}
|
||||
>${numberField(host, t("edge_thickness"), thick ?? standard, (v) => actions.setThickness(room, edge, thicknessFromTyped(v, standard), part, starts.length), 0.01, 0.02)}
|
||||
${host.admin && thick != null ? html`<button class="nf-btn" title=${t("wall_thickness_reset")} @click=${() => actions.setThickness(room, edge, null, part, starts.length)}>↺</button>` : nothing}</span
|
||||
>`
|
||||
: nothing}
|
||||
${part === undefined ? arcRow(host, arcKey(room, edge), actions.arc) : nothing}
|
||||
${cutHere
|
||||
? html`<span class="nf-wide nf-split-row"
|
||||
>${numberField(host, t("wall_split_at"), starts[part!], (v) => actions.moveCut(room, edge, starts[part!], v), 0.05, 0.1)}
|
||||
${host.admin ? html`<button class="nf-btn" title=${t("wall_join_hint")} @click=${() => actions.join(room, edge, starts[part!], part!)}>⨉</button>` : nothing}</span
|
||||
>`
|
||||
: nothing}
|
||||
</div>`;
|
||||
});
|
||||
};
|
||||
return html`<div class="nf-edge-box">
|
||||
<h4>${t("wall_heights")}</h4>
|
||||
${room.points.flatMap((_, edge) => rowsOf(edge))} ${hint(t("room_wall_hint"))}
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// The energy tool's side panel: what is still to do, the devices, and the balance sensors.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { deviceSensors, energySummary } from "../../../energy.ts";
|
||||
import { furnitureEntities } from "../../../devices.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { ENERGY_DEVICES, type Building, type Floor, type Furniture, type RoutePoint } from "../../../model.ts";
|
||||
import { entityOptions, isNumeric, isPowerSensor, powerSensorOf } from "../entities.ts";
|
||||
import { checkField, entityField, hint } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { energyChecklist, type ChecklistTarget } from "../ops/energy-checklist.ts";
|
||||
import { energyConnections, routeOf, type EnergyConnection } from "../../../live/energy-flow.ts";
|
||||
|
||||
/** What the panel can make the editor do. */
|
||||
export interface EnergyActions {
|
||||
/** Follows a checklist row: selects the field or device, or adds one. */
|
||||
follow(target: ChecklistTarget): void;
|
||||
addDevice(type: string): void;
|
||||
openDevice(floor: Floor, item: Furniture): void;
|
||||
importPrefs(): void;
|
||||
/** What the last import did, shown under its button. */
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
const MARKS = { ok: "✓", todo: "○", opt: "·" } as const;
|
||||
|
||||
const foundDevices = (host: EditorHost) => (host.hass ? furnitureEntities(host.hass, host.doc.floors) : new Map<string, { power: string | null }>());
|
||||
const energyDeviceTypes = ENERGY_DEVICES as readonly string[];
|
||||
const deviceName = (host: EditorHost, item: Furniture) => item.name || host.t(`furn_${item.type}` as I18nKey);
|
||||
|
||||
/** The checklist, ticked off live: every row jumps to what is missing. */
|
||||
export function renderEnergyChecklist(host: EditorHost, actions: EnergyActions): TemplateResult {
|
||||
const rows = energyChecklist(host.doc, foundDevices(host));
|
||||
const done = rows.filter((r) => r.state === "ok").length;
|
||||
return html`<section class="nf-checklist">
|
||||
<h3>☑ ${host.t("chk_title")} <span class="nf-sub">${done}/${rows.length}</span></h3>
|
||||
${hint(host.t("chk_hint"))}
|
||||
${rows.map(
|
||||
(row) => html`<button class="nf-chk nf-chk-${row.state}" ?disabled=${!host.admin && row.state !== "ok"} @click=${() => actions.follow(row.target)}>
|
||||
<span>${MARKS[row.state]}</span>${host.t(row.label)}
|
||||
</button>`,
|
||||
)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The energy devices of all floors, and a button for each kind that adds one on the floor shown. */
|
||||
export function renderEnergyDevices(host: EditorHost, actions: EnergyActions): TemplateResult {
|
||||
const listed = host.doc.floors.flatMap((floor) => floor.furniture.filter((m) => energyDeviceTypes.includes(m.type)).map((item) => ({ floor, item })));
|
||||
return html`<section>
|
||||
<h3>⚡ ${host.t("energy_devices")}</h3>
|
||||
${hint(host.t("energy_devices_hint"))}
|
||||
${listed.length > 0
|
||||
? html`<div class="nf-room-list">
|
||||
${listed.map(
|
||||
({ floor, item }) => html`<div class="nf-row">
|
||||
<button class="nf-dev-name" @click=${() => actions.openDevice(floor, item)}><span>${deviceName(host, item)} · ${floor.name}</span></button>
|
||||
</div>`,
|
||||
)}
|
||||
</div>`
|
||||
: nothing}
|
||||
<div class="nf-actions">
|
||||
${ENERGY_DEVICES.map((type) => html`<button class="nf-btn" ?disabled=${!host.admin || !host.floor} @click=${() => actions.addDevice(type)}>+ ${host.t(`furn_${type}` as I18nKey)}</button>`)}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** A warning with a button that flips the sign of a sensor. */
|
||||
const signWarning = (host: EditorHost, text: I18nKey, flip: () => void) =>
|
||||
html`<p class="nf-sub nf-pack-error">${host.t(text)} <button class="nf-btn" ?disabled=${!host.admin} @click=${flip}>${host.t("energy_sign_flip")}</button></p>`;
|
||||
|
||||
/** Grid, solar, battery and house sensors: from the devices in the plan unless chosen here. */
|
||||
export function renderEnergyBalance(host: EditorHost, actions: EnergyActions): TemplateResult {
|
||||
const { energy } = host.doc;
|
||||
const attribute = (id: string, key: string) => host.hass?.states[id]?.attributes[key] as string | undefined;
|
||||
const power = entityOptions(host.hass, (id) => isPowerSensor(host.hass, id));
|
||||
const charge = entityOptions(host.hass, (id) => isNumeric(id) && attribute(id, "device_class") === "battery");
|
||||
const tariff = entityOptions(host.hass, (id) => isNumeric(id) && (attribute(id, "device_class") === "monetary" || /\/(kWh|MWh)$/.test(attribute(id, "unit_of_measurement") ?? "")));
|
||||
const found = foundDevices(host);
|
||||
const sensors = deviceSensors(host.doc, (item) => powerSensorOf(item, found));
|
||||
const store = (patch: Partial<Building["energy"]>) => host.replace({ ...structuredClone(host.doc), energy: { ...host.doc.energy, ...patch } });
|
||||
const meters = entityOptions(host.hass, (id) => isNumeric(id) && ["gas", "water", "volume_flow_rate"].includes(attribute(id, "device_class") ?? ""));
|
||||
const pick = (key: "grid" | "solar" | "battery" | "battery_soc" | "consumption" | "tariff" | "gas" | "water") => (v: string | null) => store({ [key]: v === "none" ? null : v });
|
||||
|
||||
// the usual trap is a sign the wrong way round: exporting without any sun, or a battery charging at night
|
||||
const sum = host.hass ? energySummary(host.hass, host.doc, [], sensors) : null;
|
||||
const night = !!sum && (sum.solar ?? 0) < 20;
|
||||
const gridWrong = night && sum.grid !== null && sum.grid < -50;
|
||||
const batteryWrong = night && sum.battery !== null && sum.battery < -50 && (sum.grid ?? 0) <= 0;
|
||||
const invert = (value: boolean, patch: (on: boolean) => Partial<Building["energy"]>) => checkField(host, host.t("energy_invert"), value, (on) => store(patch(on)));
|
||||
|
||||
return html`<section>
|
||||
<h3>⚖ ${host.t("energy_balance")}</h3>
|
||||
${hint(host.t("energy_balance_hint"))}
|
||||
${gridWrong ? signWarning(host, "energy_sign_grid", () => store({ grid_invert: !energy.grid_invert })) : nothing}
|
||||
${batteryWrong ? signWarning(host, "energy_sign_battery", () => store({ battery_invert: !energy.battery_invert })) : nothing}
|
||||
<div class="nf-form">
|
||||
${entityField(host, host.t("energy_grid"), energy.grid, sensors.grid, power, pick("grid"))}
|
||||
${invert(energy.grid_invert, (on) => ({ grid_invert: on }))}
|
||||
${entityField(host, host.t("energy_solar_sensor"), energy.solar, sensors.solar[0] ?? null, power, pick("solar"))}
|
||||
${entityField(host, host.t("energy_battery_sensor"), energy.battery, sensors.battery[0] ?? null, power, pick("battery"))}
|
||||
${invert(energy.battery_invert, (on) => ({ battery_invert: on }))}
|
||||
${entityField(host, host.t("energy_battery_soc"), energy.battery_soc, sensors.soc[0] ?? null, charge, pick("battery_soc"))}
|
||||
${entityField(host, host.t("energy_consumption_sensor"), energy.consumption, null, power, pick("consumption"))}
|
||||
${entityField(host, host.t("energy_tariff_sensor"), energy.tariff, undefined, tariff, pick("tariff"))}
|
||||
${entityField(host, host.t("energy_gas"), energy.gas ?? null, undefined, meters, pick("gas"))}
|
||||
${entityField(host, host.t("energy_water"), energy.water ?? null, undefined, meters, pick("water"))}
|
||||
${hint(host.t("energy_meters_hint"), "nf-wide")}
|
||||
</div>
|
||||
<div class="nf-actions"><button class="nf-btn" ?disabled=${!host.admin || !host.hass} @click=${() => actions.importPrefs()}>${host.t("energy_import_prefs")}</button></div>
|
||||
${actions.note ? hint(actions.note) : nothing} ${hint(host.t("energy_hint"))}
|
||||
</section>
|
||||
<section>
|
||||
<h3>⚙ ${host.t("energy_advanced")}</h3>
|
||||
${hint(host.t("energy_advanced_hint"))}
|
||||
<div class="nf-form">
|
||||
${checkField(host, host.t("energy_advanced_on"), !!energy.advanced, (on) => store({ advanced: on }))}
|
||||
${energy.advanced ? checkField(host, host.t("energy_show_unmetered"), !!energy.show_unmetered, (on) => store({ show_unmetered: on })) : nothing}
|
||||
</div>
|
||||
${energy.advanced ? hint(host.t("energy_show_unmetered_hint")) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** What the energy flow in 3D needs, once the devices above are placed and have their sensors. */
|
||||
export const renderEnergyTeaser = (host: EditorHost): TemplateResult => html`<section class="nf-teaser nf-teaser-on">
|
||||
<div class="nf-teaser-head"><b>⚡ ${host.t("feature_name_energy")}</b></div>
|
||||
${hint(host.t("feature_text_energy"))}
|
||||
</section>`;
|
||||
|
||||
/** Where to report a problem and where to propose an idea. */
|
||||
export function renderHelpLinks(host: EditorHost): TemplateResult {
|
||||
const link = (path: string, icon: string, label: I18nKey) => html`<a class="nf-btn" href="https://github.com/therealMRBK/NextFloor/${path}" target="_blank" rel="noopener">${icon} ${host.t(label)}</a>`;
|
||||
return html`<section class="nf-help">
|
||||
<h3>${host.t("help_title")}</h3>
|
||||
${hint(host.t("help_hint"))}
|
||||
<div class="nf-actions">${link("issues/new/choose", "🐞", "help_issue")}${link("discussions/categories/ideas", "💡", "help_idea")}</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** Drawing a cable route: the connection and the points tapped so far (each on the floor it was tapped on). */
|
||||
export interface RouteDraft {
|
||||
key: string;
|
||||
points: RoutePoint[];
|
||||
}
|
||||
|
||||
export interface RouteActions {
|
||||
draft: RouteDraft | null;
|
||||
start(key: string): void;
|
||||
undoPoint(): void;
|
||||
finish(): void;
|
||||
cancel(): void;
|
||||
clear(key: string): void;
|
||||
setCable(key: string, cable: boolean): void;
|
||||
}
|
||||
|
||||
/** What a connection joins, in words. */
|
||||
function connectionName(host: EditorHost, c: EnergyConnection): string {
|
||||
const t = host.t;
|
||||
const furniture = host.doc.floors.flatMap((f) => f.furniture).find((m) => m.id === c.id);
|
||||
const name = furniture ? deviceName(host, furniture) : "";
|
||||
switch (c.kind) {
|
||||
case "solar": {
|
||||
const fields = host.doc.settings.roof.solar ?? [];
|
||||
const i = fields.findIndex((f) => f.id === c.id);
|
||||
return t("route_conn_solar", { name: fields[i]?.name || `${t("solar_field")} ${i + 1}` });
|
||||
}
|
||||
case "battery":
|
||||
return c.id ? t("route_conn_device", { name }) : t("route_conn_battery");
|
||||
case "inverter":
|
||||
return c.id ? t("route_conn_device", { name }) : t("route_conn_inverter");
|
||||
case "grid":
|
||||
return t("route_conn_grid");
|
||||
case "meter":
|
||||
return t("route_conn_meter", { name });
|
||||
}
|
||||
}
|
||||
|
||||
/** The connections whose cable can be drawn: a route per connection, shown as a faint line or as a visible cable. */
|
||||
export function renderEnergyRoutes(host: EditorHost, actions: RouteActions): TemplateResult | typeof nothing {
|
||||
const connections = energyConnections(host.doc);
|
||||
if (!connections.length) return nothing;
|
||||
const t = host.t;
|
||||
const draft = actions.draft;
|
||||
return html`<section>
|
||||
<h3>〰 ${t("energy_routes")}</h3>
|
||||
${hint(t("energy_routes_hint"))}
|
||||
<div class="nf-room-list">
|
||||
${connections.map((c) => {
|
||||
const route = routeOf(host.doc, c.key);
|
||||
const drawing = draft?.key === c.key;
|
||||
return html`<div class="nf-row nf-route-row">
|
||||
<span class="nf-dev-name"><span>${connectionName(host, c)} · ${route ? t("route_points", { n: route.points.length }) : t("route_none")}</span></span>
|
||||
${drawing
|
||||
? html`<p class="nf-sub nf-wide">${t("route_drawing", { n: draft.points.length })}</p>
|
||||
<div class="nf-actions nf-wide">
|
||||
<button class="nf-btn" ?disabled=${!draft.points.length} @click=${() => actions.undoPoint()}>↶ ${t("route_undo")}</button>
|
||||
<button class="nf-btn nf-primary" @click=${() => actions.finish()}>${t("route_done")}</button>
|
||||
<button class="nf-btn" @click=${() => actions.cancel()}>${t("cancel")}</button>
|
||||
</div>`
|
||||
: html`<div class="nf-actions">
|
||||
<button class="nf-btn" ?disabled=${!host.admin || !!draft} @click=${() => actions.start(c.key)}>✎ ${t(route ? "route_redraw" : "route_draw")}</button>
|
||||
${route ? html`<button class="nf-btn" ?disabled=${!host.admin || !!draft} @click=${() => actions.clear(c.key)}>⨉</button>` : nothing}
|
||||
</div>
|
||||
${route ? checkField(host, t("route_cable"), !!route.cable, (cable) => actions.setCable(c.key, cable), { title: t("route_cable_hint") }) : nothing}`}
|
||||
</div>`;
|
||||
})}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// The side panel's floor part: the floors of the house as chips, and the form of the selected floor.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { DEFAULT_PAINT_OUTSIDE, type Floor } from "../../../model.ts";
|
||||
import type { HassFloor } from "../../../types.ts";
|
||||
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { floorAreas, totalOf } from "../../../geometry/living-area.ts";
|
||||
import { formatArea } from "../../../units.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { freeHaFloors, linkableHaFloors, unplacedAreas } from "../ops/floors.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
|
||||
/** What the floor form makes the editor do. */
|
||||
export interface FloorActions {
|
||||
openFloor(id: string): void;
|
||||
addFloor(from: HassFloor | null): void;
|
||||
moveFloor(direction: -1 | 1): void;
|
||||
deleteFloor(): void;
|
||||
/** Copies the open floor on top of the house, with what the choices take along. */
|
||||
duplicateFloor(options: { furniture: boolean; devices: boolean; outdoor: boolean }): void;
|
||||
addAreaRooms(floor: Floor): void;
|
||||
closeGaps(): void;
|
||||
/** Moves everything on the floor (or house) by the typed distance. */
|
||||
shift(): void;
|
||||
turn(): void;
|
||||
/** Makes the editor's current 3D camera the one this floor opens with. */
|
||||
rememberView(): void;
|
||||
/** Opens the plan on paper (every floor, with the areas) to print or save as PDF. */
|
||||
print(): void;
|
||||
}
|
||||
|
||||
/** The living area of the floor and the house, and the button for the plan on paper. */
|
||||
function areaRow(host: EditorHost, floor: Floor, floorActions: FloorActions): TemplateResult | typeof nothing {
|
||||
if (floor.layer || !floor.rooms.length) return nothing;
|
||||
const t = host.t;
|
||||
const here = totalOf(floorAreas(host.doc, floor)).living;
|
||||
const house = totalOf(host.doc.floors.flatMap((f) => floorAreas(host.doc, f))).living;
|
||||
return html`<p class="nf-sub nf-wide" title=${t("living_area_hint")}>
|
||||
${t(host.doc.floors.length > 1 ? "living_area_floor_house" : "living_area_floor", { floor: formatArea(host.hass, here), house: formatArea(host.hass, house) })}
|
||||
</p>
|
||||
<div class="nf-actions nf-wide"><button class="nf-btn" title=${t("print_plan_hint")} @click=${() => floorActions.print()}>🖨️ ${t("print_plan")}</button></div>`;
|
||||
}
|
||||
|
||||
/** The chips of the floors, top floor first, and the button that adds one: straight away, or after choosing a floor of Home Assistant. */
|
||||
function floorChips(host: EditorHost, state: SideState, floorActions: FloorActions, selected: string | null): TemplateResult {
|
||||
const free = freeHaFloors(host.doc, host.hass?.floors);
|
||||
const addClicked = () => (free.length > 0 ? (state.floorMenu = !state.floorMenu) : floorActions.addFloor(null));
|
||||
return html`<div class="nf-floor-list">
|
||||
${[...host.doc.floors].reverse().map((f) => html`<button class="nf-chip" aria-pressed=${f.id === selected} @click=${() => floorActions.openFloor(f.id)}>${f.name}</button>`)}
|
||||
${host.admin ? html`<button class="nf-btn" aria-expanded=${state.floorMenu} @click=${addClicked}>+ ${host.t("add_floor")}</button>` : nothing}
|
||||
</div>
|
||||
${host.admin && state.floorMenu
|
||||
? html`<div class="nf-floor-menu">
|
||||
${hint(host.t("floor_from_ha"))}
|
||||
${free.map((f) => html`<button class="nf-btn" @click=${() => floorActions.addFloor(f)}>${f.name}${f.level != null ? html` <span class="nf-sub">· ${host.t("level", { n: f.level })}</span>` : nothing}</button>`)}
|
||||
<button class="nf-btn" @click=${() => floorActions.addFloor(null)}>${host.t("floor_empty")}</button>
|
||||
</div>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** The typed move of the whole floor, its turn, and the floor's own start view. */
|
||||
function shiftRow(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
|
||||
const axis = (label: string, value: number, set: (v: number) => void) =>
|
||||
html`<input type="number" step="0.05" .value=${String(value)} aria-label=${label} @change=${(e: Event) => set(Number((e.target as HTMLInputElement).value) || 0)} />`;
|
||||
return html`<div class="nf-field nf-wide nf-shift" title=${host.t("floor_shift_hint")}>
|
||||
<span>${host.t("floor_shift")}</span>
|
||||
${axis("X", state.shiftX, (v) => (state.shiftX = v))} ${axis("Z", state.shiftZ, (v) => (state.shiftZ = v))}
|
||||
<button class="nf-btn" ?disabled=${!state.shiftX && !state.shiftZ} @click=${() => floorActions.shift()}>${host.t("floor_shift_apply")}</button>
|
||||
<button class="nf-btn" title=${host.t("floor_turn_hint")} @click=${() => floorActions.turn()}>${host.t("floor_turn")}</button>
|
||||
<button class="nf-btn" title=${host.t("floor_start_view_hint")} @click=${() => floorActions.rememberView()}>${host.t("floor_start_view")}</button>
|
||||
${floor.start_view ? html`<button class="nf-btn" title=${host.t("floor_start_view_reset")} @click=${() => host.change((_, f) => (f.start_view = null))}>↺</button>` : nothing}
|
||||
<label class="nf-check nf-wide" title=${host.t("floor_shift_all_hint")}
|
||||
><input type="checkbox" .checked=${state.shiftAll} @change=${(e: Event) => (state.shiftAll = (e.target as HTMLInputElement).checked)} />
|
||||
${host.t("floor_shift_all")}</label
|
||||
>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** What a copy of the floor takes along, and the button that makes it. */
|
||||
function copyChoices(host: EditorHost, state: SideState, floorActions: FloorActions, choice: { furniture: boolean; devices: boolean; outdoor: boolean }): TemplateResult {
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<typeof choice>) => (state.floorCopy = { ...choice, ...patch });
|
||||
return html`<div class="nf-form nf-wide nf-copy-floor">
|
||||
${hint(t("floor_copy_hint"), "nf-wide")}
|
||||
${checkField(host, t("floor_copy_furniture"), choice.furniture, (furniture) => set({ furniture }))}
|
||||
${checkField(host, t("floor_copy_devices"), choice.devices, (devices) => set({ devices }), { title: t("floor_copy_devices_hint") })}
|
||||
${checkField(host, t("floor_copy_outdoor"), choice.outdoor, (outdoor) => set({ outdoor }))}
|
||||
<div class="nf-actions nf-wide">
|
||||
<button class="nf-btn nf-primary" @click=${() => floorActions.duplicateFloor(choice)}>${t("floor_copy_make")}</button>
|
||||
<button class="nf-btn" @click=${() => (state.floorCopy = null)}>${t("cancel")}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
|
||||
const t = host.t;
|
||||
const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch));
|
||||
const links = linkableHaFloors(host.doc, floor, host.hass?.floors);
|
||||
const lacking = unplacedAreas(host.doc, floor, host.hass?.areas);
|
||||
const haChoices: [string, string][] = [["", t("no_ha_floor")], ...links.map((f): [string, string] => [f.floor_id, f.name])];
|
||||
return html`<div class="nf-form">
|
||||
${textField(host, t("floor_name"), floor.name, (v) => update({ name: v }), { wide: true })}
|
||||
${numberField(host, t("elevation"), floor.elevation, (v) => update({ elevation: v }))}
|
||||
${host.admin ? shiftRow(host, state, floorActions, floor) : nothing}
|
||||
${numberField(host, t("height"), floor.height, (v) => update({ height: Math.max(1, v) }), 0.05, 1)}
|
||||
${Object.keys(host.hass?.floors ?? {}).length > 0 ? selectField(host, t("ha_floor"), floor.ha_floor ?? "", haChoices, (v) => update({ ha_floor: v || null }), { wide: true }) : nothing}
|
||||
${checkField(host, t("floor_layer"), !!floor.layer, (on) => update({ layer: on || undefined }), { title: t("floor_layer_hint") })}
|
||||
${entityField(host, t("floor_power"), floor.power_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "power"), (v) => update({ power_entity: v && v !== "none" ? v : null }))}
|
||||
${floor.power_entity ? hint(t("floor_power_hint"), "nf-wide") : nothing}
|
||||
${floor.layer ? nothing : colorField(host, t("wall_paint_floor"), floor.wall_paint_outside, host.doc.settings.wall_paint_outside ?? DEFAULT_PAINT_OUTSIDE, (v) => update({ wall_paint_outside: v }))}
|
||||
${areaRow(host, floor, floorActions)}
|
||||
${host.admin && lacking.length > 0
|
||||
? html`<div class="nf-actions nf-wide"><button class="nf-btn nf-primary" title=${t("area_rooms_hint")} @click=${() => floorActions.addAreaRooms(floor)}>${t("area_rooms", { n: lacking.length })}</button></div>`
|
||||
: nothing}
|
||||
${host.admin
|
||||
? html`<div class="nf-actions nf-wide">
|
||||
<button class="nf-btn" @click=${() => floorActions.moveFloor(1)}>${t("move_up")}</button>
|
||||
<button class="nf-btn" @click=${() => floorActions.moveFloor(-1)}>${t("move_down")}</button>
|
||||
<button class="nf-btn" @click=${() => (state.floorCopy = state.floorCopy ? null : { furniture: true, devices: false, outdoor: false })}>${t("floor_copy")}</button>
|
||||
<button class="nf-btn nf-danger" @click=${() => floorActions.deleteFloor()}>${t("delete_floor")}</button>
|
||||
</div>
|
||||
${state.floorCopy ? copyChoices(host, state, floorActions, state.floorCopy) : nothing}
|
||||
<div class="nf-actions nf-wide"><button class="nf-btn" title=${t("gaps_hint")} ?disabled=${floor.rooms.length < 2} @click=${() => floorActions.closeGaps()}>${t("gaps_close")}</button></div>
|
||||
${state.notice ? html`<p class="nf-sub nf-wide nf-notice">${state.notice}</p>` : nothing}`
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The "Floors" section of the side panel. */
|
||||
export function renderFloors(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor | undefined, selectedId: string | null): TemplateResult {
|
||||
return html`<section>
|
||||
<h3>${host.t("floors")}</h3>
|
||||
${floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// The entities a piece of furniture is linked to: what lights it, powers it, shows on its screen, or tells its state.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { canHangOff, deviceMeter, meterParent, subMeterIds } from "../../../energy.ts";
|
||||
import { furnitureEntities, hasScreen, isCooling, isMediaFurniture, isSpeakerFurniture, isStatusSensor, robotRoomSensor } from "../../../devices.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { ENERGY_DEVICES, isLamp, type Furniture, type VacuumCalibration } from "../../../model.ts";
|
||||
import { isClimateFurniture, isPackType, packDisplay } from "../../../packs.ts";
|
||||
import { entityOptions, isBinary, isNumeric, isPowerSensor } from "../entities.ts";
|
||||
import { checkField, entityField, glowField, hint, iconField, markerField, pinShiftField, numberField, selectField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { lightEffectFields } from "../light-effect-fields.ts";
|
||||
import { lightEffectSource } from "../../../light-effects.ts";
|
||||
import { calibrationFrom, calibrationFromRooms, gridPlaces, gridRooms, mapCamera, nudgeCalibration, type CalibrationNudge, type Place } from "../../../live/vacuum-map.ts";
|
||||
|
||||
/** What the forms of a piece of furniture make the editor do. */
|
||||
export interface FurnitureLinkActions {
|
||||
update(patch: Partial<Furniture>): void;
|
||||
}
|
||||
|
||||
const STATE_DOMAINS = /^(binary_sensor|switch|input_boolean|light|fan|person|device_tracker|sensor)\./;
|
||||
const noneAsNull = (v: string | null) => (v === "none" ? null : v);
|
||||
|
||||
/** "State from": an entity lights the top of the item (two entities light its halves), for any furniture. */
|
||||
export function stateLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const options = entityOptions(host.hass, (id) => STATE_DOMAINS.test(id));
|
||||
const first = !!item.state_entity && item.state_entity !== "none";
|
||||
const second = first && !!item.state_entity2 && item.state_entity2 !== "none";
|
||||
const splits: ["left_right" | "top_bottom", string][] = [["left_right", t("furn_state_left_right")], ["top_bottom", t("furn_state_top_bottom")]];
|
||||
return html`${entityField(host, t("furn_state_entity"), item.state_entity ?? null, undefined, options, (v) => actions.update({ state_entity: noneAsNull(v) }))}
|
||||
${first ? entityField(host, t("furn_state_entity2"), item.state_entity2 ?? null, undefined, options, (v) => actions.update({ state_entity2: noneAsNull(v) })) : nothing}
|
||||
${second ? selectField(host, t("furn_state_split"), item.state_split === "top_bottom" ? "top_bottom" : "left_right", splits, (v) => actions.update({ state_split: v })) : nothing}
|
||||
${hint(t("furn_state_hint"), "nf-wide")}`;
|
||||
}
|
||||
|
||||
/** The domains an item's main entity can come from, and the label of that field, by what the item is. */
|
||||
function mainEntity(item: Furniture, hass: EditorHost["hass"]): { accept: (id: string) => boolean; label: I18nKey } {
|
||||
const media = isMediaFurniture(item.type);
|
||||
// a pack item that only has a status light (a printer's panel, a wallbox's LED) links like any device
|
||||
const tvLike = media && (!isPackType(item.type) || packDisplay(item.type));
|
||||
if (isLamp(item.type)) return { accept: (id) => /^(light|switch|input_boolean)\./.test(id), label: "furn_entity_light" };
|
||||
// before the TV check: a thermostat has a display too, but it links to a climate entity
|
||||
if (item.type === "radiator" || isClimateFurniture(item.type)) return { accept: (id) => id.startsWith("climate."), label: "furn_entity_climate" };
|
||||
if (tvLike) return { accept: (id) => /^(media_player|switch|input_boolean|light)\./.test(id), label: "furn_entity_tv" };
|
||||
if (item.type === "robot_vacuum") return { accept: (id) => id.startsWith("vacuum."), label: "furn_entity_vacuum" };
|
||||
if (/:(robot_mower|mower_dock)$/.test(item.type)) return { accept: (id) => id.startsWith("lawn_mower."), label: "furn_entity_mower" };
|
||||
// a lawn sprinkler or an irrigation valve box: the valve (or the switch of a pump or a smart plug) that lets the water run
|
||||
if (/:(sprinkler|valve_box)$/.test(item.type)) return { accept: (id) => /^(valve|switch|input_boolean)\./.test(id), label: "furn_entity_water" };
|
||||
return { accept: (id) => /^(switch|media_player|fan|input_boolean|climate|vacuum|cover|valve)\./.test(id) || isStatusSensor(hass?.states[id]), label: "furn_entity" };
|
||||
}
|
||||
|
||||
/** What "automatic" would choose for a link: the item is looked at again with that link cleared. */
|
||||
function automaticLink(host: EditorHost, item: Furniture, key: "entity" | "power" | "fan"): string | null {
|
||||
if (!host.hass) return null;
|
||||
const probe = structuredClone(host.doc.floors);
|
||||
for (const floor of probe) for (const f of floor.furniture) if (f.id === item.id) f[key === "fan" ? "fan_entity" : key] = null;
|
||||
return furnitureEntities(host.hass, probe).get(item.id)?.[key] ?? null;
|
||||
}
|
||||
|
||||
const powerLabel = (type: string): I18nKey => (type === "meter" ? "energy_grid" : type === "inverter" ? "energy_solar_sensor" : type === "home_battery" ? "energy_battery_sensor" : "furn_power");
|
||||
|
||||
const linkBlock = (...rows: (TemplateResult | typeof nothing)[]): TemplateResult => html`<div class="nf-form nf-links">${rows}</div>`;
|
||||
|
||||
/**
|
||||
* A robot vacuum's own map, tied to the plan. The dock is the anchor — the plan knows where it stands, the camera
|
||||
* knows where it stands in the robot's grid — so one tap on the robot is all a calibration needs.
|
||||
*/
|
||||
/**
|
||||
* Where the robot and its dock are right now. Some integrations only fill the map camera's attributes while they
|
||||
* render a frame, so asking for the picture is what makes the position current; the wait is for that frame to
|
||||
* arrive, and short enough not to be noticed when it does not change anything.
|
||||
*/
|
||||
async function currentPlaces(host: EditorHost): Promise<{ at: [number, number] | null; dock: [number, number] | null }> {
|
||||
const camera = host.hass ? mapCamera(host.hass) : null;
|
||||
if (!host.hass || !camera) return { at: null, dock: null };
|
||||
const stamp = () => {
|
||||
const attributes = host.hass?.states[camera]?.attributes ?? {};
|
||||
return `${String(attributes.render_count ?? "")}|${JSON.stringify(attributes.vacuum_position ?? null)}`;
|
||||
};
|
||||
const before = stamp();
|
||||
try {
|
||||
await host.hass.fetchWithAuth?.(`/api/camera_proxy/${camera}`);
|
||||
} catch {
|
||||
// the picture is only a way to make the robot render; without it the attributes may simply be older
|
||||
}
|
||||
for (let i = 0; i < 8 && stamp() === before; i++) await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
return gridPlaces(host.hass, camera);
|
||||
}
|
||||
|
||||
/** Buttons that shift, turn and scale a calibration by hand, for a fitted map that sits a little off (#109). */
|
||||
function nudgeRow(host: EditorHost, cal: VacuumCalibration): TemplateResult {
|
||||
const t = host.t;
|
||||
const step = (nudge: CalibrationNudge) => host.change((doc) => void (doc.settings.vacuum_map = nudgeCalibration(cal, nudge)));
|
||||
const btn = (label: string, title: string, nudge: CalibrationNudge) =>
|
||||
html`<button class="nf-btn" title=${title} aria-label=${title} ?disabled=${!host.admin} @click=${() => step(nudge)}>${label}</button>`;
|
||||
const [move, turn, grow] = [t("robot_cal_nudge_move"), t("robot_cal_nudge_turn"), t("robot_cal_nudge_grow")];
|
||||
return html`${hint(t("robot_cal_nudge"), "nf-wide")}
|
||||
<div class="nf-wide" style="display:flex;flex-wrap:wrap;gap:6px">
|
||||
${btn("←", move, { move: [-0.1, 0] })}${btn("→", move, { move: [0.1, 0] })}${btn("↑", move, { move: [0, -0.1] })}${btn("↓", move, { move: [0, 0.1] })}
|
||||
${btn("⟲", turn, { turn: -1 })}${btn("⟳", turn, { turn: 1 })}${btn("−", grow, { grow: 0.99 })}${btn("+", grow, { grow: 1.01 })}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function robotMapBlock(host: EditorHost, item: Furniture): TemplateResult {
|
||||
const t = host.t;
|
||||
const cal = host.doc.settings.vacuum_map ?? null;
|
||||
const places = host.hass ? gridPlaces(host.hass, mapCamera(host.hass)) : { at: null, dock: null };
|
||||
const cells = cal ? Math.hypot(cal.gb[0] - cal.ga[0], cal.gb[1] - cal.ga[1]) : 0;
|
||||
const metres = cal && cells > 0 ? Math.hypot(cal.b[0] - cal.a[0], cal.b[1] - cal.a[1]) / cells : 0;
|
||||
const pick = () => {
|
||||
// the place is taken from the tap, the robot's own position from right after it: it is only exact while the
|
||||
// robot stands still, which is what the hint asks of it
|
||||
host.pickPoint((point) => {
|
||||
if (!point) return;
|
||||
void currentPlaces(host).then((fresh) => {
|
||||
if (!fresh.at || !fresh.dock) return;
|
||||
const dock: Place = { plan: [item.x, item.z], grid: fresh.dock };
|
||||
const res = calibrationFrom(dock, { plan: point, grid: fresh.at }, cal?.mirror ?? false);
|
||||
if (res.cal) host.change((doc) => void (doc.settings.vacuum_map = res.cal));
|
||||
});
|
||||
});
|
||||
};
|
||||
// the robot's named rooms against the rooms of the floor it stands on: no driving, no tapping (#109)
|
||||
const camera = host.hass ? mapCamera(host.hass) : null;
|
||||
const robotRooms = host.hass ? gridRooms(host.hass, camera) : [];
|
||||
const floor = host.doc.floors.find((f) => f.furniture.some((f2) => f2.id === item.id));
|
||||
const fromRooms = () => {
|
||||
if (!floor) return;
|
||||
const res = calibrationFromRooms(floor.rooms, robotRooms, cal?.mirror ?? false);
|
||||
if (res.cal) {
|
||||
const fitted = res.cal;
|
||||
host.change((doc) => void (doc.settings.vacuum_map = fitted));
|
||||
} else alert(t(res.reason === "rooms" ? "robot_cal_rooms_none" : "robot_cal_rooms_bad", { n: res.matched.length }));
|
||||
};
|
||||
return linkBlock(
|
||||
hint(places.at && places.dock ? (cal ? t("robot_cal_done", { m: metres.toFixed(2) }) : t("robot_cal_none")) : t("robot_cal_need"), "nf-wide"),
|
||||
robotRooms.length >= 2
|
||||
? html`<button class="nf-btn nf-wide" ?disabled=${!host.admin || !floor} @click=${fromRooms}>${t("robot_cal_rooms", { n: robotRooms.length })}</button>`
|
||||
: nothing,
|
||||
html`<button class="nf-btn nf-wide" ?disabled=${!host.admin || !places.at || !places.dock} @click=${pick}>${t("robot_cal_do")}</button>`,
|
||||
cal
|
||||
? checkField(host, t("robot_cal_mirror"), !!cal.mirror, (on) => host.change((doc) => void (doc.settings.vacuum_map = { ...cal, mirror: on })))
|
||||
: nothing,
|
||||
cal ? nudgeRow(host, cal) : nothing,
|
||||
cal ? html`<button class="nf-btn nf-wide" ?disabled=${!host.admin} @click=${() => host.change((doc) => void (doc.settings.vacuum_map = null))}>${t("robot_cal_forget")}</button>` : nothing,
|
||||
hint(t("robot_cal_hint"), "nf-wide"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Advanced energy mode: the sub-meter an inverter or home battery sits behind (a balcony plant in a flat), else the main meter. */
|
||||
function deviceMeterLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing {
|
||||
const t = host.t;
|
||||
const doc = host.doc;
|
||||
if (!doc.energy.advanced) return nothing;
|
||||
const subs = subMeterIds(doc);
|
||||
const meters = doc.floors.flatMap((floor) => floor.furniture.filter((m) => subs.has(m.id)).map((m) => [m.id, `${m.name || t("furn_meter")} · ${floor.name}`] as const));
|
||||
return linkBlock(
|
||||
selectField(host, t("meter_parent"), deviceMeter(doc, item) ?? "", [["", t("meter_main")], ...meters], (v) => actions.update({ parent_meter: v || null }), { wide: true }),
|
||||
hint(t("meter_device_hint"), "nf-wide"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Advanced energy mode: the meter a meter hangs off, and for a sub-meter its sign and the floors it feeds. */
|
||||
function subMeterLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing {
|
||||
const t = host.t;
|
||||
const doc = host.doc;
|
||||
if (!doc.energy.advanced) return nothing;
|
||||
const parents = doc.floors.flatMap((floor) => floor.furniture.filter((m) => canHangOff(doc, item, m)).map((m) => [m.id, `${m.name || t("furn_meter")} · ${floor.name}`] as const));
|
||||
const sub = !!meterParent(doc, item);
|
||||
const fed = item.meter_floors ?? [];
|
||||
const feed = (id: string, on: boolean) => actions.update({ meter_floors: on ? [...fed.filter((f) => f !== id), id] : fed.filter((f) => f !== id) });
|
||||
return linkBlock(
|
||||
selectField(host, t("meter_parent"), sub ? item.parent_meter! : "", [["", t("meter_parent_none")], ...parents], (v) => actions.update({ parent_meter: v || null }), { wide: true }),
|
||||
sub ? checkField(host, t("energy_invert"), !!item.meter_invert, (on) => actions.update({ meter_invert: on })) : nothing,
|
||||
sub ? html`<div class="nf-sub nf-wide">${t("meter_floors")}</div>${doc.floors.map((floor) => checkField(host, floor.name, fed.includes(floor.id), (on) => feed(floor.id, on)))}` : nothing,
|
||||
hint(t("meter_sub_hint"), "nf-wide"),
|
||||
);
|
||||
}
|
||||
|
||||
/** A waste bin, a mailbox or a plant: the sensor it shows (and for a plant, when it counts as thirsty). */
|
||||
export function careLink(host: EditorHost, item: Furniture, kind: "bin" | "mail" | "plant", actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const accept = kind === "mail" ? (id: string) => /^(binary_sensor|sensor|input_boolean)\./.test(id) : (id: string) => /^(sensor|binary_sensor|calendar)\./.test(id);
|
||||
return html`<div class="nf-form nf-links">
|
||||
${entityField(host, t(`care_entity_${kind}` as I18nKey), item.care_entity ?? null, undefined, entityOptions(host.hass, accept), (v) => actions.update({ care_entity: noneAsNull(v) }))}
|
||||
${kind === "plant" ? numberField(host, t("care_thirsty_below"), item.thirsty_below ?? 20, (v) => actions.update({ thirsty_below: Math.min(90, Math.max(1, Math.round(v))) }), 1, 1) : nothing}
|
||||
${hint(t(`care_hint_${kind}` as I18nKey), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A curtain, roller screen, awning or gate: the cover entity its moving parts follow. */
|
||||
export function coverLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
return html`<div class="nf-form nf-links">
|
||||
${entityField(host, t("furn_cover_entity"), item.cover_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => actions.update({ cover_entity: noneAsNull(v) }))}
|
||||
${checkField(host, t("furn_cover_inverted"), !!item.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }), { title: t("furn_cover_inverted_hint") })}
|
||||
${hint(t("furn_cover_hint"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A light switch or socket: one entity per button or socket, in order from the left. */
|
||||
export function gangLinks(host: EditorHost, item: Furniture, gangs: number, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const socket = /socket/.test(item.type);
|
||||
const options = entityOptions(host.hass, (id) => /^(light|switch|input_boolean|fan)\./.test(id));
|
||||
const current = item.gang_entities ?? [];
|
||||
const set = (i: number) => (v: string | null) => {
|
||||
const next = Array.from({ length: gangs }, (_, k) => current[k] ?? null);
|
||||
next[i] = noneAsNull(v);
|
||||
actions.update({ gang_entities: next });
|
||||
};
|
||||
return html`<div class="nf-form nf-links">
|
||||
${Array.from({ length: gangs }, (_, i) => entityField(host, gangs === 1 ? t(socket ? "gang_socket_one" : "gang_switch_one") : t(socket ? "gang_socket" : "gang_switch", { n: i + 1 }), current[i] ?? null, undefined, options, set(i)))}
|
||||
${hint(t(socket ? "gang_socket_hint" : "gang_switch_hint"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The links of electric furniture: the main entity and the power sensor, and what is special to the kind of device. */
|
||||
/** A fridge's thermometers: one in the fridge, one in the freezer compartment; the marker shows them and warns when too warm. */
|
||||
function coolingLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const temps = entityOptions(host.hass, (id) => {
|
||||
const a = host.hass?.states[id]?.attributes;
|
||||
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
|
||||
});
|
||||
return linkBlock(
|
||||
entityField(host, t("fridge_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })),
|
||||
entityField(host, t("freezer_temp"), item.temp_entity2 ?? null, undefined, temps, (v) => actions.update({ temp_entity2: noneAsNull(v) })),
|
||||
hint(t("fridge_temp_hint"), "nf-wide"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Any other electric device: its own thermometer (an inverter, a battery, a PC), shown on its pin (#112). */
|
||||
function deviceTempLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const temps = entityOptions(host.hass, (id) => {
|
||||
const a = host.hass?.states[id]?.attributes;
|
||||
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
|
||||
});
|
||||
return linkBlock(
|
||||
entityField(host, t("device_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })),
|
||||
hint(t("device_temp_hint"), "nf-wide"),
|
||||
);
|
||||
}
|
||||
|
||||
/** Further bulbs of a lamp (night light, ambient ring): up to four lights of the same fixture, one more field than are set. */
|
||||
function extraLightFields(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const current = item.extra_lights ?? [];
|
||||
const options = entityOptions(host.hass, (id) => id.startsWith("light.") && id !== item.entity && id !== item.color_entity);
|
||||
const set = (i: number) => (v: string | null) => {
|
||||
const next = [...current];
|
||||
if (v && v !== "none") next[i] = v;
|
||||
else next.splice(i, 1);
|
||||
actions.update({ extra_lights: next.filter(Boolean).length ? next.filter(Boolean) : undefined });
|
||||
};
|
||||
const rows = Math.min(4, current.length + 1);
|
||||
return html`${Array.from({ length: rows }, (_, i) => entityField(host, t("lamp_extra_light", { n: i + 2 }), current[i] ?? null, undefined, options, set(i)))}${hint(t("lamp_extra_hint"), "nf-wide")}`;
|
||||
}
|
||||
|
||||
export function furnitureLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing {
|
||||
const { hass } = host;
|
||||
if (!hass) return nothing;
|
||||
const t = host.t;
|
||||
const lamp = isLamp(item.type);
|
||||
const main = mainEntity(item, hass);
|
||||
const power = entityOptions(hass, (id) => isPowerSensor(hass, id));
|
||||
const set = (key: keyof Furniture) => (v: string | null) => actions.update({ [key]: noneAsNull(v) });
|
||||
const kindOptions = (accept: (id: string) => boolean) => entityOptions(hass, accept);
|
||||
const strings = (host.doc.settings.roof.strings ?? []).filter((s) => s.inverter === item.id).map((s) => s.name);
|
||||
const hasLink = !!item.entity && item.entity !== "none";
|
||||
const doors = item.type === "fridge_smart" ? kindOptions((id) => id.startsWith("binary_sensor.")) : [];
|
||||
const hintKey: I18nKey = item.type === "ceiling_fan" ? "fan_hint" : lamp ? (item.type === "lamp_pendant" ? "lamp_hint_pendant" : "lamp_hint") : isMediaFurniture(item.type) ? "furn_links_hint_tv" : item.type === "robot_vacuum" ? "robot_hint" : "furn_links_hint";
|
||||
return html`${linkBlock(
|
||||
item.type === "grid_point" ? hint(t("grid_point_hint"), "nf-wide") : entityField(host, t(main.label), item.entity ?? null, automaticLink(host, item, "entity"), kindOptions(main.accept), (v) => actions.update({ entity: v })),
|
||||
item.type === "ceiling_fan"
|
||||
? entityField(host, t("furn_fan_entity"), item.fan_entity ?? null, automaticLink(host, item, "fan"), kindOptions((id) => id.startsWith("fan.")), (v) => actions.update({ fan_entity: v }))
|
||||
: nothing,
|
||||
!lamp && !(ENERGY_DEVICES as readonly string[]).includes(item.type) && !hasScreen(item.type) ? stateLinks(host, item, actions) : nothing,
|
||||
lamp && hasLink
|
||||
? html`${entityField(host, t("furn_color_entity"), item.color_entity ?? null, undefined, kindOptions((id) => id.startsWith("light.") && id !== item.entity), set("color_entity"))}${hint(t("furn_color_entity_hint"), "nf-wide")}`
|
||||
: nothing,
|
||||
lamp && hasLink ? extraLightFields(host, item, actions) : nothing,
|
||||
lamp ? glowField(host, item.glow_scale, (v) => actions.update({ glow_scale: v })) : nothing,
|
||||
lamp ? lightEffectFields(host, item, lightEffectSource(hass, item, item.entity && item.entity !== "none" ? item.entity : automaticLink(host, item, "entity"))?.attributes.effect_list, actions.update) : nothing,
|
||||
hasScreen(item.type) ? glowField(host, item.ambilight, (v) => actions.update({ ambilight: v }), { label: "ambilight", hint: "ambilight_hint", lowest: 0 }) : nothing,
|
||||
(isMediaFurniture(item.type) || isSpeakerFurniture(item.type)) ? glowField(host, item.sound_rings, (v) => actions.update({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing,
|
||||
item.type === "grid_point" ? nothing : entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, automaticLink(host, item, "power"), power, (v) => actions.update({ power: v })),
|
||||
)}
|
||||
${isCooling(item.type) ? coolingLinks(host, item, actions) : lamp || item.type === "grid_point" ? nothing : deviceTempLink(host, item, actions)}
|
||||
${item.type === "meter" ? subMeterLinks(host, item, actions) : nothing}
|
||||
${item.type === "inverter" || item.type === "home_battery" ? deviceMeterLink(host, item, actions) : nothing}
|
||||
${item.type === "meter" && !meterParent(host.doc, item) ? linkBlock(entityField(host, t("furn_export"), item.export ?? null, undefined, power, set("export")), hint(t("furn_export_hint"), "nf-wide")) : nothing}
|
||||
${item.type === "inverter" && (host.doc.settings.roof.solar ?? []).length > 0 ? hint(strings.length > 0 ? t("inverter_strings", { names: strings.join(", ") }) : t("inverter_strings_none"), "nf-wide") : nothing}
|
||||
${item.type === "home_battery"
|
||||
? linkBlock(
|
||||
entityField(host, t("furn_soc"), item.soc ?? null, undefined, kindOptions((id) => isNumeric(id) && (hass.states[id]?.attributes.device_class === "battery" || hass.states[id]?.attributes.unit_of_measurement === "%")), set("soc")),
|
||||
entityField(host, t("furn_charge"), item.charge ?? null, undefined, power, set("charge")),
|
||||
hint(t("furn_charge_hint"), "nf-wide"),
|
||||
)
|
||||
: nothing}
|
||||
${item.type === "wallbox" ? linkBlock(entityField(host, t("furn_wallbox_status"), item.status ?? null, undefined, kindOptions((id) => isBinary(id) || isNumeric(id)), set("status"))) : nothing}
|
||||
${!lamp || item.entity
|
||||
? html`${checkField(host, t("device_confirm"), !!item.confirm, (on) => actions.update({ confirm: on }), { title: t("device_confirm_hint") })}
|
||||
<div class="nf-form">${markerField(host, item.marker ?? null, (v) => actions.update({ marker: v }))}${iconField(host, item.icon, (v) => actions.update({ icon: v }))}${lamp ? nothing : pinShiftField(host, item.pin_offset, (v) => actions.update({ pin_offset: v }))}</div>`
|
||||
: nothing}
|
||||
${item.type === "robot_vacuum"
|
||||
? linkBlock(entityField(host, t("furn_robot_room"), item.room_sensor ?? null, robotRoomSensor(hass, furnitureEntities(hass, host.doc.floors).get(item.id)?.entity ?? null, null), kindOptions(isNumeric), (v) => actions.update({ room_sensor: v })))
|
||||
: nothing}
|
||||
${item.type === "robot_vacuum" && hasLink ? robotMapBlock(host, item) : nothing}
|
||||
${item.type === "fridge_smart"
|
||||
? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v })), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v })))}
|
||||
${hint(t("fridge_hint"))}`
|
||||
: nothing}
|
||||
${hint(t(hintKey))}`;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// The form of a piece of furniture: its name and kind, size and place, looks (paint, shape), and the entities it is linked to.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { colourLabel, furnitureName, packItemLabel, packLabel } from "../../../furniture-names.ts";
|
||||
import { holeInRoom } from "../../../geometry/holes.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { BUTTON_ACTIONS, canLift, uid, CEILING_TYPES, ceilingAt, ceilingOf, FURNITURE_TYPES, furnitureFootprint, isLamp, type ButtonAction, type Furniture } from "../../../model.ts";
|
||||
import { hasMovingParts, hasPicture, householdKind, isElectric, mountBase, packItem, packType, type FurniturePack } from "../../../packs.ts";
|
||||
import { checkField, entityField, hint, iconField, markerField, pinShiftField, numberField, selectField, textField } from "../fields.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { storeImage } from "../../../api.ts";
|
||||
import { readPictureInBrowser } from "../background-tool.ts";
|
||||
import { roofUnderAt } from "../../../roof/proposal.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { careLink, coverLink, furnitureLinks, gangLinks, stateLinks, type FurnitureLinkActions } from "./furniture-links.ts";
|
||||
import { dataField, TARGET_EXAMPLES } from "./house.ts";
|
||||
import { parkingForm } from "./parking.ts";
|
||||
import { stairForm } from "./stairs.ts";
|
||||
import { DEFAULT_STAIR } from "../../../geometry/stairs.ts";
|
||||
|
||||
export interface FurnitureActions extends FurnitureLinkActions {
|
||||
rotate(delta: number): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
/** Turns the item back into a plain device pin. */
|
||||
toDevice(item: Furniture): void;
|
||||
/** Turns a vehicle into a parking spot holding it. */
|
||||
toSpot(item: Furniture): void;
|
||||
/** Moves the item to another floor, at the same spot. */
|
||||
toFloor(floorId: string): void;
|
||||
packs: readonly FurniturePack[];
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
}
|
||||
|
||||
/** Furniture without a top to light: no "state from" box. */
|
||||
const NO_STATE_TYPES = new Set(["parking", "stairwell", "rug", "grid_point"]);
|
||||
|
||||
/** The looks a type can have besides its paint, as the variants it offers and the text of each. */
|
||||
const VARIANTS: Record<string, { label: I18nKey; values: readonly string[]; text(value: string): string }> = {
|
||||
inverter: { label: "furn_model", values: ["", "slim", "hybrid"], text: (v) => `inverter_${v || "std"}` },
|
||||
home_battery: { label: "furn_model", values: ["", "wall", "cube"], text: (v) => `battery_${v || "std"}` },
|
||||
lamp_pendant: { label: "pendant_shape", values: ["", "globe", "cone", "drum"], text: (v) => `pendant_${v || "shade"}` },
|
||||
sofa: { label: "sofa_shape", values: ["", "l", "u"], text: (v) => `sofa_${v || "straight"}` },
|
||||
};
|
||||
|
||||
/** The kind drop-down: the built-in kinds, then those of every pack, and the item's own kind when its pack is gone. */
|
||||
function kindField(host: EditorHost, item: Furniture, packs: readonly FurniturePack[], actions: FurnitureActions): TemplateResult {
|
||||
const language = host.hass?.language ?? "en";
|
||||
const known = packs.some((p) => item.type.startsWith(`pack:${p.id}:`));
|
||||
return html`<label class="nf-field nf-wide"
|
||||
>${host.t("furniture_type")}
|
||||
<select ?disabled=${!host.admin} @change=${(e: Event) => actions.update({ type: (e.target as HTMLSelectElement).value })}>
|
||||
${FURNITURE_TYPES.map((type) => html`<option value=${type} ?selected=${type === item.type}>${host.t(`furn_${type}` as I18nKey)}</option>`)}
|
||||
${packs.map(
|
||||
(pack) => html`<optgroup label=${packLabel(pack, host.hass?.language ?? "de")}>
|
||||
${pack.items.map((it) => html`<option value=${packType(pack.id, it.id)} ?selected=${packType(pack.id, it.id) === item.type}>${packItemLabel(it, packType(pack.id, it.id), language)}</option>`)}
|
||||
</optgroup>`,
|
||||
)}
|
||||
${item.type.startsWith("pack:") && !known ? html`<option value=${item.type} selected>${furnitureName(host.hass, item.type)}</option>` : nothing}
|
||||
</select>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** The paint of a vehicle: the colours its pack offers, kept as the variant of the furniture. */
|
||||
function paintField(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult | typeof nothing {
|
||||
const colours = packItem(item.type === "parking" ? (item.vehicle ?? "") : item.type)?.colors;
|
||||
if (!colours?.length) return nothing;
|
||||
const language = host.hass?.language ?? "en";
|
||||
const current = colours.find((c) => c.id === item.variant) ?? colours[0];
|
||||
const nameOf = (c: (typeof colours)[number]) => colourLabel(c, language);
|
||||
return html`<div class="nf-form">
|
||||
<div class="nf-field nf-wide">
|
||||
<span>${host.t("paint_colour")}: ${nameOf(current)}</span>
|
||||
<div class="nf-swatches" role="radiogroup" aria-label=${host.t("paint_colour")}>
|
||||
${colours.map((c, i) => html`<button type="button" class="nf-swatch" role="radio" aria-checked=${c.id === current.id} title=${nameOf(c)} style=${`--sw:${c.hex}`} ?disabled=${!host.admin} @click=${() => actions.update({ variant: i === 0 ? null : c.id })}></button>`)}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A form with a drop-down for the shapes of a type, for the types that have some. */
|
||||
function variantField(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult | typeof nothing {
|
||||
const variants = VARIANTS[item.type];
|
||||
if (!variants) return nothing;
|
||||
const choices = variants.values.map((v): [string, string] => [v, host.t(variants.text(v) as I18nKey)]);
|
||||
return html`<div class="nf-form">${selectField(host, host.t(variants.label), item.variant ?? "", choices, (v) => actions.update({ variant: v || null, ...(item.type === "sofa" && v && item.d < 1.4 ? { d: 1.7, w: Math.max(item.w, v === "u" ? 3 : 2.4) } : {}) }), { wide: true })}</div>`;
|
||||
}
|
||||
|
||||
/** The name of the item, and whether it is written under its marker. */
|
||||
function nameFields(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const standard = host.t(`furn_${item.type}` as I18nKey);
|
||||
const placeholder = standard === `furn_${item.type}` ? "" : standard;
|
||||
return html`<label class="nf-field nf-wide"
|
||||
>${host.t("furn_name")}
|
||||
<input type="text" maxlength="60" .value=${item.name ?? ""} ?disabled=${!host.admin} placeholder=${placeholder} @change=${(e: Event) => actions.update({ name: (e.target as HTMLInputElement).value.trim() || null })} />
|
||||
</label>
|
||||
${item.name ? checkField(host, host.t("show_name"), !!item.show_name, (on) => actions.update({ show_name: on || undefined })) : nothing}`;
|
||||
}
|
||||
|
||||
/** Size, place and turn, and what depends on the kind: mirror, strip tilt, mount height. */
|
||||
function geometryFields(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<Furniture>) => actions.update(patch);
|
||||
const floor = host.floor;
|
||||
return html`${numberField(host, t("x"), item.x, (v) => set({ x: v }))} ${numberField(host, t("z"), item.z, (v) => set({ z: v }))}
|
||||
${numberField(host, t("width"), item.w, (v) => set({ w: Math.max(0.05, v) }), 0.01, 0.05)} ${numberField(host, t("depth"), item.d, (v) => set({ d: Math.max(0.05, v) }), 0.01, 0.05)}
|
||||
${numberField(host, t("height_m"), item.h, (v) => set({ h: Math.max(0.005, v) }), 0.01, 0)}
|
||||
${numberField(host, t("rotation"), item.rotation, (v) => set({ rotation: ((v % 360) + 360) % 360 }), 1)}
|
||||
${numberField(host, t("tilt_x"), item.tilt_x ?? 0, (v) => set({ tilt_x: Math.max(-90, Math.min(90, Math.round(v))) || null }), 1, -90)}
|
||||
${numberField(host, t("tilt_z"), item.tilt_z ?? 0, (v) => set({ tilt_z: Math.max(-90, Math.min(90, Math.round(v))) || null }), 1, -90)}
|
||||
${isLamp(item.type) ? nothing : checkField(host, t("furn_mirror"), !!item.mirror, (mirror) => set({ mirror }), { wide: false, title: t("furn_mirror_hint") })}
|
||||
${item.type === "led_strip"
|
||||
? html`${numberField(host, t("strip_tilt"), item.tilt ?? 0, (v) => set({ tilt: Math.max(-90, Math.min(90, Math.round(v))) }), 5)}
|
||||
${item.upright ? nothing : numberField(host, t("strip_rise"), item.rise ?? 0, (v) => set({ rise: Math.max(-80, Math.min(80, Math.round(v))) }), 5)}
|
||||
${checkField(host, t("strip_upright"), !!item.upright, (upright) => set({ upright }), { wide: false, title: t("strip_upright_hint") })}`
|
||||
: nothing}
|
||||
${canLift(item) && floor
|
||||
? html`${numberField(host, t("mount_height"), item.mount_y ?? mountBase(floor, item), (v) => set({ mount_y: Math.max(0, v) }), 0.01, 0)}
|
||||
${item.mount_y != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => set({ mount_y: null })}>${t("height_auto")}</button>` : nothing}`
|
||||
: nothing}
|
||||
${hangs(item) && floor
|
||||
? html`${numberField(host, t("ceiling_here"), ceilingOf(floor, item), (v) => set({ ceiling_y: Math.abs(v - ceilingAt(floor, item.x, item.z)) < 0.005 ? null : Math.max(0.5, v) }), 0.01, 0.5)}
|
||||
${item.ceiling_y != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => set({ ceiling_y: null })}>${t("height_auto")}</button>` : nothing}
|
||||
${slopeAbove(host, item) !== null
|
||||
? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("ceiling_slope_hint")} @click=${() => set({ ceiling_y: slopeAbove(host, item) })}>📐 ${t("ceiling_slope")}</button>`
|
||||
: nothing}
|
||||
${hint(t("ceiling_here_hint"), "nf-wide")}`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** The underside of a roof slope right above an item, when it is lower than the room's ceiling (an attic room): its height on the floor. */
|
||||
function slopeAbove(host: EditorHost, item: Furniture): number | null {
|
||||
const floor = host.floor;
|
||||
if (!floor) return null;
|
||||
const under = roofUnderAt(host.doc, item.x, item.z);
|
||||
if (under === null) return null;
|
||||
const y = Math.round((under - floor.elevation) * 1000) / 1000;
|
||||
return y > 0.5 && y < ceilingAt(floor, item.x, item.z) - 0.02 ? y : null;
|
||||
}
|
||||
|
||||
/** Items that hang from the ceiling: their own ceiling height can be set (a lamp in a sloping ceiling). */
|
||||
const hangs = (item: Furniture): boolean => CEILING_TYPES.has(item.type) || packItem(item.type)?.mount === "ceiling";
|
||||
|
||||
/** Notes under the form for stairs and stairwells, with a warning when a stairwell lies outside every room. */
|
||||
function typeNotes(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult | typeof nothing {
|
||||
if (item.type === "stairs" && item.stair) return nothing;
|
||||
if (item.type === "stairs")
|
||||
return html`${hint(host.t("stairs_hint"))}${host.admin ? html`<div class="nf-actions"><button class="nf-btn nf-primary" title=${host.t("stair_upgrade_hint")} @click=${() => actions.update({ stair: { ...DEFAULT_STAIR } })}>${host.t("stair_upgrade")}</button></div>` : nothing}`;
|
||||
if (item.type !== "stairwell") return nothing;
|
||||
const outside = host.floor && !host.floor.rooms.some((r) => r.points.length >= 3 && holeInRoom(furnitureFootprint(item), r.points));
|
||||
return html`${hint(host.t("stairwell_hint"))}${outside ? html`<p class="nf-sub nf-pack-error">${host.t("stairwell_outside")}</p>` : nothing}`;
|
||||
}
|
||||
|
||||
/** The buttons at the bottom: turn, back to a device pin, copy, delete. */
|
||||
function buttons(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult | typeof nothing {
|
||||
if (!host.admin) return nothing;
|
||||
const t = host.t;
|
||||
const linked = !!item.entity && item.entity !== "none" && item.type !== "parking";
|
||||
const others = host.doc.floors.filter((f) => f.id !== host.floor?.id);
|
||||
return html`<div class="nf-actions">
|
||||
<button class="nf-btn" @click=${() => actions.rotate(-90)}>${t("rotate_left")}</button>
|
||||
<button class="nf-btn" @click=${() => actions.rotate(90)}>${t("rotate_right")}</button>
|
||||
${linked ? html`<button class="nf-btn" title=${t("as_device_hint")} @click=${() => actions.toDevice(item)}>${t("as_device")}</button>` : nothing}
|
||||
<button class="nf-btn" @click=${() => actions.duplicate()}>${t("duplicate")}</button>
|
||||
<button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("delete")}</button>
|
||||
</div>
|
||||
${others.length ? html`<div class="nf-form">${selectField(host, t("furn_to_floor"), "", [["", "–"], ...others.map((f): [string, string] => [f.id, f.name])], (id) => id && actions.toFloor(id), { wide: true, title: t("furn_to_floor_hint") })}</div>` : nothing}`;
|
||||
}
|
||||
|
||||
/** What a tap on the item does: its usual tap, or an own action like the star menu's own buttons. */
|
||||
function tapField(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const tap = item.tap ?? null;
|
||||
const choices: [string, string][] = [["", host.t("furn_tap_default")], ...BUTTON_ACTIONS.map((a): [string, string] => [a, host.t(`own_action_${a}` as I18nKey)])];
|
||||
const set = (patch: Partial<NonNullable<Furniture["tap"]>>) => actions.update({ tap: { action: tap?.action ?? "navigate", target: tap?.target ?? null, data: tap?.data ?? null, ...patch } });
|
||||
return html`<div class="nf-form">
|
||||
${selectField(host, host.t("furn_tap"), tap?.action ?? "", choices, (v) => (v ? set({ action: v as ButtonAction }) : actions.update({ tap: null })), { wide: true, title: host.t("furn_tap_hint") })}
|
||||
${tap && tap.action !== "fire_dom_event"
|
||||
? textField(host, host.t(`own_target_${tap.action}` as I18nKey), tap.target ?? "", (v) => set({ target: v || null }), { wide: true, placeholder: TARGET_EXAMPLES[tap.action] })
|
||||
: nothing}
|
||||
${tap && (tap.action === "service" || tap.action === "fire_dom_event") ? dataField(host, tap, (data) => set({ data })) : nothing}
|
||||
${tap && !isElectric(item.type) && !packItem(item.type)?.gangs
|
||||
? html`${markerField(host, item.marker ?? null, (v) => actions.update({ marker: v }))}${iconField(host, item.icon, (v) => actions.update({ icon: v }))}${pinShiftField(host, item.pin_offset, (v) => actions.update({ pin_offset: v }))}`
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A picture frame: its photo (uploaded and stored with the plan, a URL, or an image or camera entity), the mat and how it fits. */
|
||||
function pictureFields(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const value = item.picture ?? "";
|
||||
const stored = value.startsWith("image:");
|
||||
const upload = async (e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
if (!file || !host.hass) return;
|
||||
const { data } = await readPictureInBrowser(file);
|
||||
const id = uid("img");
|
||||
await storeImage(host.hass, id, data);
|
||||
actions.update({ picture: `image:${id}` });
|
||||
};
|
||||
const entities = entityOptions(host.hass, (id) => /^(image|camera|media_player)\./.test(id));
|
||||
return html`<div class="nf-form nf-links">
|
||||
${host.admin
|
||||
? html`<label class="nf-btn nf-wide nf-upload">📷 ${t(stored ? "picture_replace" : "picture_upload")}<input type="file" accept="image/*" hidden @change=${upload} /></label>`
|
||||
: nothing}
|
||||
${stored
|
||||
? html`<p class="nf-sub nf-wide">${t("picture_stored")} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.update({ picture: null })}>${t("delete")}</button></p>`
|
||||
: html`${textField(host, t("picture_url"), /^[a-z_]+\.[a-z0-9_]+$/.test(value) ? "" : value, (v) => actions.update({ picture: v || null }), { wide: true, placeholder: "/local/holiday.jpg" })}
|
||||
${entityField(host, t("picture_entity"), /^[a-z_]+\.[a-z0-9_]+$/.test(value) ? value : null, undefined, entities, (v) => actions.update({ picture: v && v !== "none" ? v : null }))}`}
|
||||
${numberField(host, t("picture_border"), item.picture_border ?? 0, (v) => actions.update({ picture_border: Math.max(0, Math.min(40, Math.round(v))) || null }), 1, 0)}
|
||||
${selectField(host, t("picture_fit"), item.picture_fit ?? "cover", [["cover", t("picture_fit_cover")], ["contain", t("picture_fit_contain")]], (v) => actions.update({ picture_fit: v === "contain" ? "contain" : null }))}
|
||||
${hint(t("picture_hint"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const CONDITION_DOMAINS = /^(input_boolean|input_select|switch|binary_sensor|sensor|calendar|schedule|sun|person|device_tracker|input_text|select)\./;
|
||||
|
||||
/** Shown only while an entity is in a state: seasonal decoration behind a helper, a calendar, the sun. */
|
||||
function showWhenField(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const cond = item.show_when ?? null;
|
||||
const set = (patch: Partial<NonNullable<Furniture["show_when"]>>) => actions.update({ show_when: { entity: cond?.entity ?? "", state: cond?.state ?? null, invert: cond?.invert || undefined, ...patch } });
|
||||
return html`<div class="nf-form">
|
||||
${entityField(host, t("furn_show_when"), cond?.entity || null, undefined, entityOptions(host.hass, (id) => CONDITION_DOMAINS.test(id)), (v) => (v && v !== "none" ? set({ entity: v }) : actions.update({ show_when: null })))}
|
||||
${cond?.entity
|
||||
? html`${textField(host, t("furn_show_when_state"), cond.state ?? "", (v) => set({ state: v || null }), { wide: true, placeholder: host.hass?.states[cond.entity]?.state ?? "on" })}
|
||||
${checkField(host, t("furn_show_when_invert"), !!cond.invert, (on) => set({ invert: on || undefined }))}`
|
||||
: nothing}
|
||||
${hint(t("furn_show_when_hint"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The form of the selected piece of furniture. */
|
||||
export function renderFurnitureForm(host: EditorHost, item: Furniture, actions: FurnitureActions): TemplateResult {
|
||||
const gangs = packItem(item.type)?.gangs ?? 0;
|
||||
const links = gangs ? gangLinks(host, item, gangs, actions) : isElectric(item.type) ? furnitureLinks(host, item, actions) : !NO_STATE_TYPES.has(item.type) ? html`<div class="nf-form nf-links">${stateLinks(host, item, actions)}</div>` : nothing;
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${item.name || host.t("furniture")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">${nameFields(host, item, actions)} ${kindField(host, item, actions.packs, actions)} ${geometryFields(host, item, actions)}</div>
|
||||
${typeNotes(host, item, actions)} ${item.type === "stairs" && item.stair ? stairForm(host, item, actions) : nothing} ${variantField(host, item, actions)} ${paintField(host, item, actions)}
|
||||
${links} ${item.type.endsWith(":sprinkler") ? html`<div class="nf-form">${numberField(host, host.t("spray_reach"), item.spray ?? 3, (v) => actions.update({ spray: Math.min(15, Math.max(0.5, v)) }), 0.5, 0.5)}${hint(host.t("spray_hint"), "nf-wide")}</div>` : nothing}
|
||||
${hasPicture(item.type) ? pictureFields(host, item, actions) : nothing}
|
||||
${packItem(item.type)?.pet
|
||||
? html`<div class="nf-form nf-links">${entityField(host, host.t("pet_room_sensor"), item.room_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(sensor|device_tracker|input_select|select)\./.test(id)), (v) => actions.update({ room_sensor: v && v !== "none" ? v : null }))}${hint(host.t("pet_room_hint"), "nf-wide")}</div>`
|
||||
: nothing}
|
||||
${householdKind(item.type) ? careLink(host, item, householdKind(item.type)!, actions) : nothing} ${hasMovingParts(packItem(item.type)) ? coverLink(host, item, actions) : nothing} ${item.type === "parking" ? parkingForm(host, item, actions.packs, actions) : nothing}
|
||||
${item.type.startsWith("pack:nextfloor.fahrzeuge:") && host.admin
|
||||
? html`<section>${hint(host.t("vehicle_to_spot_hint"))}<div class="nf-actions"><button class="nf-btn nf-primary" @click=${() => actions.toSpot(item)}>🅿 ${host.t("vehicle_to_spot")}</button></div></section>`
|
||||
: nothing}
|
||||
${host.admin ? tapField(host, item, actions) : nothing} ${showWhenField(host, item, actions)} ${buttons(host, item, actions)}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// The house-wide settings forms: favourites, own buttons, station presets, the start camera, and who is tracked by which sensor.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { entityName, outsideEntities } from "../../../devices.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { BUTTON_ACTIONS, uid, type ButtonAction, type Circuit, type CustomButton, type ForecastCard, type MediaPreset, type OwnAlert, type StartView } from "../../../model.ts";
|
||||
import { entityOptions, isNumeric } from "../entities.ts";
|
||||
import { actions, checkField, colorField, entityField, hint, iconField, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { likelyRoomSensors, parseButtonData, patchPresence, startViewYaml } from "../ops/house.ts";
|
||||
import { moveWithin, orUndefined, patchAt, removeAt } from "../ops/lists.ts";
|
||||
|
||||
/** What can be favourites: things that run or switch. */
|
||||
const FAVORITE_DOMAINS = ["scene", "script", "automation", "button", "input_button", "switch", "input_boolean", "light", "fan", "cover", "lock"];
|
||||
const MAX_FAVORITES = 40;
|
||||
const MAX_BUTTONS = 20;
|
||||
const MAX_PRESETS = 30;
|
||||
const PRESET_TYPES = ["music", "url", "playlist", "SPOTIFY", "AMAZON_MUSIC", "TUNEIN", "APPLE_MUSIC"];
|
||||
|
||||
export const TARGET_EXAMPLES: Record<ButtonAction, string> = { navigate: "/lovelace/rollos", more_info: "cover.wohnzimmer", service: "script.turn_on", fire_dom_event: "" };
|
||||
|
||||
const iconButton = (title: string, label: string, onClick: () => void, disabled = false) => html`<button class="nf-pin" title=${title} ?disabled=${disabled} @click=${onClick}>${label}</button>`;
|
||||
|
||||
/** Scenes, scripts and switches that show in the star menu of the 3D view, in the order given here. */
|
||||
function favorites(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.favorites ?? [];
|
||||
const store = (next: string[]) => host.change((d) => (d.settings.favorites = orUndefined(next)));
|
||||
const floors = host.doc.floors;
|
||||
const only = host.doc.settings.favorite_floors ?? {};
|
||||
const options = entityOptions(host.hass, (id) => FAVORITE_DOMAINS.includes(id.split(".")[0]) && !list.includes(id));
|
||||
const row = (id: string, i: number) => html`<div class="nf-row nf-dev-row">
|
||||
<span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>
|
||||
${floors.length > 1
|
||||
? html`<select title=${host.t("favorite_floor")} .value=${only[id] ?? ""} @change=${(e: Event) => {
|
||||
const v = (e.target as HTMLSelectElement).value;
|
||||
const next = { ...only };
|
||||
if (v) next[id] = v;
|
||||
else delete next[id];
|
||||
host.change((d) => (d.settings.favorite_floors = Object.keys(next).length ? next : undefined));
|
||||
}}>
|
||||
<option value="">${host.t("favorite_all_floors")}</option>
|
||||
${floors.map((f) => html`<option value=${f.id} ?selected=${only[id] === f.id}>${f.name}</option>`)}
|
||||
</select>`
|
||||
: nothing}
|
||||
${iconButton(host.t("move_up"), "↑", () => store(moveWithin(list, i, -1)), i === 0)}
|
||||
${iconButton(host.t("move_down"), "↓", () => store(moveWithin(list, i, 1)), i === list.length - 1)}
|
||||
${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}
|
||||
</div>`;
|
||||
return html`<summary>${host.t("favorites")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</summary>
|
||||
${hint(host.t("favorites_hint"))} ${list.map(row)}
|
||||
${list.length < MAX_FAVORITES
|
||||
? html`<div class="nf-form">${entityField(host, host.t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** Devices the Outside panel leaves out (they stay where they are in the plan). */
|
||||
function outsideHidden(host: EditorHost, paneView?: () => StartView | null): TemplateResult {
|
||||
const list = host.doc.settings.outside_hidden ?? [];
|
||||
const store = (next: string[]) => host.change((d) => (d.settings.outside_hidden = orUndefined(next)));
|
||||
// worked out once: asking for every entity would run the whole search once per entity of Home Assistant (#101)
|
||||
const outside = new Set(host.hass ? outsideEntities(host.hass, host.doc.floors) : []);
|
||||
const options = entityOptions(host.hass, (id) => !list.includes(id) && outside.has(id));
|
||||
return html`${paneView ? outsideView(host, paneView) : nothing}
|
||||
<h4>${host.t("outside_hidden")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</h4>
|
||||
${hint(host.t("outside_hidden_hint"))}
|
||||
${list.map((id, i) => html`<div class="nf-row nf-dev-row"><span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}</div>`)}
|
||||
<div class="nf-form">${entityField(host, host.t("outside_hidden_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>`;
|
||||
}
|
||||
|
||||
/** The camera Outside opens with: the editor's 3D pane as it stands now (#83). */
|
||||
function outsideView(host: EditorHost, paneView: () => StartView | null): TemplateResult {
|
||||
const saved = host.doc.settings.outside_view ?? null;
|
||||
const remember = () => {
|
||||
const view = paneView();
|
||||
if (view) host.change((d) => (d.settings.outside_view = view));
|
||||
};
|
||||
return html`${hint(host.t("outside_view_hint"))}
|
||||
${actions(
|
||||
html`<button class="nf-btn" @click=${remember}>${host.t("outside_view_set")}</button>`,
|
||||
saved ? html`<button class="nf-btn" @click=${() => host.change((d) => (d.settings.outside_view = null))}>${host.t("outside_view_reset")}</button>` : nothing,
|
||||
)}`;
|
||||
}
|
||||
|
||||
/** Own warnings: a text in the warning bar while an entity is in a state (the robot's water tank is empty, the dishwasher is done). */
|
||||
function ownAlerts(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.own_alerts ?? [];
|
||||
const store = (next: OwnAlert[]) => host.change((d) => (d.settings.own_alerts = orUndefined(next)));
|
||||
const edit = (i: number, patch: Partial<OwnAlert>) => store(patchAt(list, i, patch));
|
||||
const rooms: [string, string][] = [["", host.t("own_alert_house")], ...host.doc.floors.flatMap((f) => f.rooms.map((r): [string, string] => [r.id, `${r.name} · ${f.name}`]))];
|
||||
const card = (a: OwnAlert, i: number) => html`<div class="nf-form nf-own-button">
|
||||
${entityField(host, host.t("own_alert_entity"), a.entity || null, undefined, entityOptions(host.hass, () => true), (v) => edit(i, { entity: v && v !== "none" ? v : "" }))}
|
||||
${textField(host, host.t("own_alert_state"), a.state ?? "", (v) => edit(i, { state: v || null }), { placeholder: host.hass?.states[a.entity]?.state ?? "on · <20 · >80" })}
|
||||
${textField(host, host.t("own_alert_text"), a.text, (v) => edit(i, { text: v || host.t("own_alert_new") }), { wide: true, maxlength: 120 })}
|
||||
${selectField(host, host.t("room"), a.room_id ?? "", rooms, (v) => edit(i, { room_id: v || null }), { wide: true })}
|
||||
${colorField(host, host.t("own_alert_color"), a.color ?? null, "#ffb547", (color) => edit(i, { color }))}
|
||||
${selectField(host, host.t("own_alert_tap"), a.tap ?? "", [["", host.t("own_alert_tap_info")], ["toggle", host.t("own_alert_tap_toggle")], ["room", host.t("own_alert_tap_room")]], (v) => edit(i, { tap: (v || null) as OwnAlert["tap"] }))}
|
||||
<div class="nf-actions nf-wide"><button class="nf-btn nf-danger" @click=${() => store(removeAt(list, i))}>${host.t("delete")}</button></div>
|
||||
</div>`;
|
||||
return html`<h4>⚠ ${host.t("own_alerts")}</h4>
|
||||
${hint(host.t("own_alerts_hint"))} ${list.map(card)}
|
||||
${list.length < 40 ? actions(html`<button class="nf-btn" @click=${() => store([...list, { id: uid("alert"), entity: "", state: null, text: host.t("own_alert_new") }])}>+ ${host.t("own_alert_add")}</button>`) : nothing}`;
|
||||
}
|
||||
|
||||
/** The fuse box: circuits by name, each with the rooms it feeds (chips to add and remove). */
|
||||
function circuits(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.circuits ?? [];
|
||||
const store = (next: Circuit[]) => host.change((d) => (d.settings.circuits = orUndefined(next)));
|
||||
const edit = (i: number, patch: Partial<Circuit>) => store(patchAt(list, i, patch));
|
||||
const rooms = host.doc.floors.flatMap((f) => f.rooms.map((r) => ({ id: r.id, label: host.doc.floors.length > 1 ? `${r.name} · ${f.name}` : r.name })));
|
||||
const nameOf = (id: string) => rooms.find((r) => r.id === id)?.label ?? id;
|
||||
const card = (c: Circuit, i: number) => html`<div class="nf-form nf-own-button">
|
||||
${textField(host, host.t("circuit_name"), c.name, (v) => edit(i, { name: v || host.t("circuit_new") }), { wide: true, maxlength: 80 })}
|
||||
<div class="nf-wide">${c.rooms.map((id) => html`<span class="nf-chip">${nameOf(id)} <button class="nf-btn nf-field-btn" title=${host.t("delete")} @click=${() => edit(i, { rooms: c.rooms.filter((r) => r !== id) })}>✕</button></span>`)}</div>
|
||||
${selectField(host, host.t("circuit_add_room"), "", [["", "–"], ...rooms.filter((r) => !c.rooms.includes(r.id)).map((r): [string, string] => [r.id, r.label])], (v) => v && edit(i, { rooms: [...c.rooms, v] }), { wide: true })}
|
||||
<div class="nf-actions nf-wide"><button class="nf-btn nf-danger" @click=${() => store(removeAt(list, i))}>${host.t("delete")}</button></div>
|
||||
</div>`;
|
||||
return html`<h4>🔌 ${host.t("circuits")}</h4>
|
||||
${hint(host.t("circuits_hint"))} ${list.map(card)}
|
||||
${list.length < 120 ? actions(html`<button class="nf-btn" @click=${() => store([...list, { id: uid("circuit"), name: host.t("circuit_new"), rooms: [] }])}>+ ${host.t("circuit_add")}</button>`) : nothing}`;
|
||||
}
|
||||
|
||||
/** The calendars of the "Today" card: their appointments of the day show top right in the 3D view, with the bins due. */
|
||||
function calendars(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.calendars ?? [];
|
||||
const store = (next: string[]) => host.change((d) => (d.settings.calendars = orUndefined(next)));
|
||||
const options = entityOptions(host.hass, (id) => id.startsWith("calendar.") && !list.includes(id));
|
||||
const row = (id: string, i: number) => html`<div class="nf-row nf-dev-row">
|
||||
<span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>
|
||||
${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}
|
||||
</div>`;
|
||||
const t = host.t;
|
||||
const days = host.doc.settings.today_days ?? 1;
|
||||
return html`<h4>📅 ${t("today_calendars")}</h4>
|
||||
${hint(t("today_calendars_hint"))} ${list.map(row)}
|
||||
${list.length < 12 ? html`<div class="nf-form">${entityField(host, t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>` : nothing}
|
||||
${list.length
|
||||
? html`<div class="nf-form">
|
||||
${selectField(host, t("today_days"), String(days), [1, 2, 3, 5, 7].map((n): [string, string] => [String(n), t(n === 1 ? "today_days_one" : "today_days_n", { n })]), (v) => host.change((d) => (d.settings.today_days = Number(v) > 1 ? Number(v) : undefined)))}
|
||||
</div>`
|
||||
: nothing}
|
||||
${forecastCard(host)}`;
|
||||
}
|
||||
|
||||
/** The weather forecast card (#84): off, or a number of days in a top corner; the weather entity is the one of the settings. */
|
||||
function forecastCard(host: EditorHost): TemplateResult {
|
||||
const t = host.t;
|
||||
const card = host.doc.settings.forecast ?? null;
|
||||
const set = (next: ForecastCard | null) => host.change((d) => (d.settings.forecast = next ?? undefined));
|
||||
return html`<h4>🌦 ${t("forecast")}</h4>
|
||||
${hint(t("forecast_hint"))}
|
||||
<div class="nf-form">
|
||||
${selectField(host, t("forecast_days"), card ? String(card.days) : "0", [0, 3, 5, 7].map((n): [string, string] => [String(n), n ? t("today_days_n", { n }) : t("forecast_off")]), (v) =>
|
||||
set(Number(v) > 0 ? { days: Number(v), corner: card?.corner ?? "top_right" } : null),
|
||||
)}
|
||||
${card
|
||||
? selectField(host, t("forecast_corner"), card.corner, [["top_right", t("clock_top_right")], ["top_left", t("clock_top_left")]], (v) => set({ ...card, corner: v === "top_left" ? "top_left" : "top_right" }))
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** Stations and playlists that start on a speaker from its quick menu. */
|
||||
function mediaPresets(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.media_presets ?? [];
|
||||
const store = (next: MediaPreset[]) => host.change((d) => (d.settings.media_presets = orUndefined(next)));
|
||||
const edit = (i: number, patch: Partial<MediaPreset>) => store(patchAt(list, i, patch));
|
||||
// the speakers of the plan: media players placed as devices or linked to furniture
|
||||
const speakers = [...new Set(host.doc.floors.flatMap((f) => [...f.placements.map((p) => p.entity_id), ...f.furniture.map((m) => m.entity ?? "")]).filter((id) => id.startsWith("media_player.")))];
|
||||
const card = (p: MediaPreset, i: number) => html`<div class="nf-form nf-own-button">
|
||||
${textField(host, host.t("own_button_label"), p.label, (v) => edit(i, { label: v || "Radio" }), { maxlength: 60 })}
|
||||
${textField(host, host.t("preset_type"), p.type, (v) => edit(i, { type: v || "music" }), { title: host.t("preset_type_hint") })}
|
||||
${textField(host, host.t("preset_content"), p.content, (v) => edit(i, { content: v }), { wide: true, title: host.t("preset_content_hint"), placeholder: "https://… · spotify:playlist:… · Rock Antenne" })}
|
||||
${speakers.length > 1
|
||||
? html`<div class="nf-sub nf-wide">${host.t("preset_speakers")}</div>
|
||||
${speakers.map((id) => checkField(host, entityName(host.hass, id), !!p.speakers?.includes(id), (on) => edit(i, { speakers: orUndefined(on ? [...(p.speakers ?? []), id] : (p.speakers ?? []).filter((s) => s !== id)) }), { wide: false }))}`
|
||||
: nothing}
|
||||
<div class="nf-actions nf-wide"><button class="nf-btn nf-danger" @click=${() => store(removeAt(list, i))}>${host.t("delete")}</button></div>
|
||||
</div>`;
|
||||
return html`<h4>${host.t("presets")}</h4>
|
||||
${hint(host.t("presets_hint"))}
|
||||
<datalist id="nf-preset-types">${PRESET_TYPES.map((type) => html`<option value=${type}></option>`)}</datalist>
|
||||
${list.map(card)}
|
||||
${list.length < MAX_PRESETS ? actions(html`<button class="nf-btn" @click=${() => store([...list, { id: uid("preset"), label: "Radio", type: "music", content: "" }])}>+ ${host.t("preset_add")}</button>`) : nothing}`;
|
||||
}
|
||||
|
||||
/** The extra data of an own button, as JSON; a text that is not an object is flagged on the field instead of being stored. */
|
||||
export function dataField(host: EditorHost, button: Pick<CustomButton, "action" | "data">, onData: (data: Record<string, unknown> | null) => void): TemplateResult {
|
||||
const example = button.action === "fire_dom_event" ? '{"browser_mod": {"service": "browser_mod.popup", "data": {"title": "Rollos", "content": {"type": "custom:my-cover-card"}}}}' : '{"entity_id": "script.party"}';
|
||||
const onChange = (e: Event) => {
|
||||
const area = e.target as HTMLTextAreaElement;
|
||||
area.setCustomValidity("");
|
||||
const parsed = parseButtonData(area.value);
|
||||
if (parsed.ok) return onData(parsed.value);
|
||||
area.setCustomValidity(host.t("own_data_bad"));
|
||||
area.reportValidity();
|
||||
};
|
||||
return html`<label class="nf-field nf-wide" title=${host.t("own_data_hint")}
|
||||
>${host.t("own_data")}
|
||||
<textarea rows="4" spellcheck="false" placeholder=${example} .value=${button.data ? JSON.stringify(button.data, null, 1) : ""} @change=${onChange}></textarea>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** Own buttons of the star menu: label, icon, what they do, the target, and extra data. */
|
||||
function ownButtons(host: EditorHost): TemplateResult {
|
||||
const list = host.doc.settings.buttons ?? [];
|
||||
const store = (next: CustomButton[]) => host.change((d) => (d.settings.buttons = orUndefined(next)));
|
||||
const edit = (i: number, patch: Partial<CustomButton>) => store(patchAt(list, i, patch));
|
||||
const actionChoices = BUTTON_ACTIONS.map((a): [ButtonAction, string] => [a, host.t(`own_action_${a}` as I18nKey)]);
|
||||
const card = (b: CustomButton, i: number) => html`<div class="nf-form nf-own-button">
|
||||
${textField(host, host.t("own_button_label"), b.label, (v) => edit(i, { label: v || host.t("own_button_new") }), { maxlength: 60 })}
|
||||
${selectField(host, host.t("own_button_action"), b.action, actionChoices, (action) => edit(i, { action }))} ${iconField(host, b.icon ?? null, (icon) => edit(i, { icon }))}
|
||||
${b.action !== "fire_dom_event"
|
||||
? textField(host, host.t(`own_target_${b.action}` as I18nKey), b.target ?? "", (v) => edit(i, { target: v || null }), { wide: true, placeholder: TARGET_EXAMPLES[b.action] })
|
||||
: nothing}
|
||||
${b.action === "service" || b.action === "fire_dom_event" ? dataField(host, b, (data) => edit(i, { data })) : nothing}
|
||||
${entityField(host, host.t("own_button_state"), b.state_entity ?? null, undefined, entityOptions(host.hass, (id) => /^(switch|light|input_boolean|binary_sensor|fan|cover|media_player|climate|lock|person|device_tracker)\./.test(id)), (v) => edit(i, { state_entity: v && v !== "none" ? v : null }))}
|
||||
<div class="nf-actions nf-wide">
|
||||
<button class="nf-btn" ?disabled=${i === 0} @click=${() => store(moveWithin(list, i, -1))}>↑</button>
|
||||
<button class="nf-btn nf-danger" @click=${() => store(removeAt(list, i))}>${host.t("delete")}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
return html`<h4>${host.t("own_buttons")}</h4>
|
||||
${hint(host.t("own_buttons_hint"))} ${list.map(card)}
|
||||
${list.length < MAX_BUTTONS
|
||||
? actions(html`<button class="nf-btn" @click=${() => store([...list, { id: uid("btn"), label: host.t("own_button_new"), action: "navigate", target: null }])}>+ ${host.t("own_button_add")}</button>`)
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** Which facts the room panel shows in its header. */
|
||||
function roomFacts(host: EditorHost): TemplateResult {
|
||||
const off = host.doc.settings.room_facts_off ?? [];
|
||||
const facts = (["sun", "comfort", "air", "circuits"] as const).map((k) =>
|
||||
checkField(host, host.t(`room_fact_${k}` as I18nKey), !off.includes(k), (on) => host.change((d) => (d.settings.room_facts_off = orUndefined(on ? off.filter((x) => x !== k) : [...off, k])))),
|
||||
);
|
||||
return html`<h4>${host.t("room_facts")}</h4><div class="nf-form">${facts}</div>`;
|
||||
}
|
||||
|
||||
/** The favourites section with the own buttons and station presets below it (they all belong to the star menu). */
|
||||
export function renderFavorites(host: EditorHost): TemplateResult {
|
||||
return html`<details class="nf-section">${favorites(host)} ${ownButtons(host)} ${ownAlerts(host)} ${circuits(host)} ${calendars(host)} ${mediaPresets(host)} ${roomFacts(host)}</details>`;
|
||||
}
|
||||
|
||||
/** Outside as a section of its own (#83): the camera it opens with first, then the devices its panel leaves out. */
|
||||
export function renderOutside(host: EditorHost, paneView: () => StartView | null): TemplateResult {
|
||||
return html`<details class="nf-section">
|
||||
<summary>🌳 ${host.t("outside_area")}</summary>
|
||||
${outsideHidden(host, paneView)}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** The camera the house opens with: the editor's 3D pane as it stands now, or the default. */
|
||||
export function renderStartView(host: EditorHost, paneView: () => StartView | null): TemplateResult {
|
||||
const saved = host.doc.settings.start_view ?? null;
|
||||
const remember = () => {
|
||||
const view = paneView();
|
||||
if (view) host.change((d) => (d.settings.start_view = view));
|
||||
};
|
||||
return html`<details class="nf-section">
|
||||
<summary>${host.t("start_view")}</summary>
|
||||
${hint(host.t("start_view_hint"))}
|
||||
${actions(
|
||||
html`<button class="nf-btn nf-primary" @click=${remember}>${host.t("start_view_set")}</button>`,
|
||||
saved ? html`<button class="nf-btn" @click=${() => host.change((d) => (d.settings.start_view = null))}>${host.t("start_view_reset")}</button>` : nothing,
|
||||
)}
|
||||
${saved ? html`${hint(host.t("start_view_saved"))} ${hint(host.t("start_view_card"))}<code class="nf-code">${startViewYaml(saved)}</code>` : nothing}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** Which room sensor says where each person is. */
|
||||
export function renderPresence(host: EditorHost): TemplateResult {
|
||||
const linked = host.doc.presence.map((l) => l.person);
|
||||
const persons = [...new Set([...Object.keys(host.hass?.states ?? {}).filter((id) => id.startsWith("person.")).sort(), ...linked])];
|
||||
const numeric = entityOptions(host.hass, isNumeric);
|
||||
const rooms = host.doc.floors.flatMap((f) => f.rooms.map((r) => ({ id: r.id, label: host.doc.floors.length > 1 ? `${f.name} · ${r.name}` : r.name })));
|
||||
const change = (person: string, patch: { sensor?: string | null; room?: string | null }) =>
|
||||
host.replace({ ...structuredClone(host.doc), presence: patchPresence(host.doc.presence, person, patch) });
|
||||
const row = (person: string) => {
|
||||
const link = host.doc.presence.find((p) => p.person === person);
|
||||
const extra = !person.startsWith("person.");
|
||||
return html`${entityField(host, `${entityName(host.hass, person)} · ${host.t("presence_sensor")}`, link?.sensor ?? null, undefined, likelyRoomSensors(numeric, person), (sensor) => change(person, { sensor }))}
|
||||
<label class="nf-field">${host.t("presence_room")}
|
||||
<select ?disabled=${!host.admin} .value=${link?.room ?? ""} @change=${(e: Event) => change(person, { room: (e.target as HTMLSelectElement).value || null })}>
|
||||
<option value="">${host.t("presence_room_none")}</option>
|
||||
${rooms.map((r) => html`<option value=${r.id} ?selected=${link?.room === r.id}>${r.label}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
${extra ? html`<button class="nf-btn" ?disabled=${!host.admin} @click=${() => host.replace({ ...structuredClone(host.doc), presence: host.doc.presence.filter((l) => l.person !== person) })}>${host.t("delete")}</button>` : nothing}`;
|
||||
};
|
||||
const more = entityOptions(host.hass, (id) => /^(input_boolean|binary_sensor|device_tracker)\./.test(id) && !persons.includes(id));
|
||||
return html`<details class="nf-section">
|
||||
<summary>${host.t("presence")}</summary>
|
||||
<div class="nf-form">${persons.length > 0 ? persons.map(row) : html`<p class="nf-sub nf-wide">${host.t("no_persons")}</p>`}</div>
|
||||
<div class="nf-form">${entityField(host, host.t("presence_add"), null, undefined, more, (v) => v && v !== "none" && host.replace({ ...structuredClone(host.doc), presence: [...host.doc.presence, { person: v, sensor: null }] }))}</div>
|
||||
${hint(host.t("presence_hint"))}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** Locating Bluetooth tags by room: pick a tag, walk through the rooms, record them (the element does the work). */
|
||||
export function renderBleLocate(host: EditorHost, doc: unknown): TemplateResult {
|
||||
return html`<details class="nf-section">
|
||||
<summary>${host.t("ble")}</summary>
|
||||
${hint(host.t("ble_hint"))}
|
||||
<nf-ble-locate .host=${host} .doc=${doc}></nf-ble-locate>
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
// The furniture library in the side panel while furnishing: built-in models and every pack together, sorted by what they are (seating,
|
||||
// beds, kitchen …). A search box, chips that narrow it to the room and to linkable, lit or outdoor items, favourites and the recently
|
||||
// used ones on top, a card with a picture and the size for each item, and one card with size chips for a model that comes in several
|
||||
// sizes. The big picture beside a card while the pointer rests on it stays as before.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { iconPath } from "../../../icons.ts";
|
||||
import { FURNITURE_GROUPS, FURNITURE_SIZE, LAMP_MODEL, isLamp, type FurnitureType } from "../../../model.ts";
|
||||
import { furnitureName, packItemLabel, packLabel } from "../../../furniture-names.ts";
|
||||
import { translate, type I18nKey } from "../../../i18n.ts";
|
||||
import { furnitureSize, isElectric, packType, type FurniturePack } from "../../../packs.ts";
|
||||
import { load3d } from "../../../load3d.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { CATEGORIES, cardsOf, isOutdoorCategory, mainCategory, roomCategories, sizeLabel, withRecent, type CatalogCard, type CatalogEntry, type Category } from "../ops/catalog.ts";
|
||||
import { hasAllWords, wordsOf } from "../ops/library.ts";
|
||||
import { thumbs } from "../thumbs.ts";
|
||||
|
||||
const STORAGE_KEY = "nextfloor.library2";
|
||||
/** A stand-in for English names: the search also matches the English name of an item. */
|
||||
const ENGLISH = { language: "en" } as Parameters<typeof translate>[0];
|
||||
|
||||
export interface Preview {
|
||||
type: string;
|
||||
/** The picture, or null while it is drawn. */
|
||||
url: string | null;
|
||||
left: number;
|
||||
top: number;
|
||||
}
|
||||
|
||||
type Flag = "room" | "linkable" | "lit" | "outdoor";
|
||||
|
||||
interface Saved {
|
||||
/** Sections opened or closed by hand; the others follow the room (its main kind is open). */
|
||||
folded: Record<string, boolean>;
|
||||
favourites: string[];
|
||||
recent: string[];
|
||||
flags: Flag[];
|
||||
}
|
||||
|
||||
export class LibraryState {
|
||||
private readonly onChange: () => void;
|
||||
private text = "";
|
||||
private saved: Saved;
|
||||
private shown: Preview | null = null;
|
||||
/** The size picked on a card with several sizes (card key -> type). */
|
||||
private readonly picked = new Map<string, string>();
|
||||
|
||||
constructor(onChange: () => void) {
|
||||
this.onChange = onChange;
|
||||
this.saved = { folded: {}, favourites: [], recent: [], flags: ["room"] };
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw) this.saved = { ...this.saved, ...(JSON.parse(raw) as Partial<Saved>) };
|
||||
} catch {
|
||||
// no storage: the defaults stand
|
||||
}
|
||||
}
|
||||
|
||||
private store(patch: Partial<Saved>): void {
|
||||
this.saved = { ...this.saved, ...patch };
|
||||
this.onChange();
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(this.saved));
|
||||
} catch {
|
||||
// no storage
|
||||
}
|
||||
}
|
||||
|
||||
get query(): string {
|
||||
return this.text;
|
||||
}
|
||||
set query(text: string) {
|
||||
this.text = text;
|
||||
this.onChange();
|
||||
}
|
||||
|
||||
isOpen(key: string, byDefault: boolean): boolean {
|
||||
return this.saved.folded[key] ?? byDefault;
|
||||
}
|
||||
toggle(key: string, byDefault: boolean): void {
|
||||
this.store({ folded: { ...this.saved.folded, [key]: !this.isOpen(key, byDefault) } });
|
||||
}
|
||||
|
||||
has(flag: Flag): boolean {
|
||||
return this.saved.flags.includes(flag);
|
||||
}
|
||||
flip(flag: Flag): void {
|
||||
this.store({ flags: this.has(flag) ? this.saved.flags.filter((f) => f !== flag) : [...this.saved.flags, flag] });
|
||||
}
|
||||
|
||||
get favourites(): readonly string[] {
|
||||
return this.saved.favourites;
|
||||
}
|
||||
isFavourite(type: string): boolean {
|
||||
return this.saved.favourites.includes(type);
|
||||
}
|
||||
toggleFavourite(type: string): void {
|
||||
this.store({ favourites: this.isFavourite(type) ? this.saved.favourites.filter((t) => t !== type) : [type, ...this.saved.favourites] });
|
||||
}
|
||||
|
||||
get recent(): readonly string[] {
|
||||
return this.saved.recent;
|
||||
}
|
||||
used(type: string): void {
|
||||
this.store({ recent: withRecent(this.saved.recent, type) });
|
||||
}
|
||||
|
||||
pickedOf(card: CatalogCard): CatalogEntry {
|
||||
const type = this.picked.get(card.key);
|
||||
return card.entries.find((e) => e.type === type) ?? card.entries[0];
|
||||
}
|
||||
pick(card: CatalogCard, type: string): void {
|
||||
this.picked.set(card.key, type);
|
||||
this.onChange();
|
||||
}
|
||||
|
||||
get preview(): Preview | null {
|
||||
return this.shown;
|
||||
}
|
||||
|
||||
hidePreview(): void {
|
||||
this.shown = null;
|
||||
this.onChange();
|
||||
}
|
||||
|
||||
/** Draws a picture of the item (by the 3D bundle) and shows it left of the card the pointer is on. */
|
||||
async showPreview(type: string, button: HTMLElement, packs: readonly FurniturePack[]): Promise<void> {
|
||||
const box = button.getBoundingClientRect();
|
||||
const place = { left: Math.max(8, box.left - 196), top: Math.max(8, Math.min(window.innerHeight - 200, box.top + box.height / 2 - 95)) };
|
||||
this.shown = { type, url: null, ...place };
|
||||
this.onChange();
|
||||
try {
|
||||
const [w, d, h] = furnitureSize(type);
|
||||
const url = (await load3d()).furniturePreview({ type, w, d, h, variant: null, lamp: LAMP_MODEL[type] ?? null }, 180, [...packs]);
|
||||
if (this.shown?.type === type) this.shown = { type, url, ...place };
|
||||
} catch {
|
||||
this.shown = null;
|
||||
}
|
||||
this.onChange();
|
||||
}
|
||||
}
|
||||
|
||||
export interface LibraryActions {
|
||||
add(type: string): void;
|
||||
/** Opens the furniture studio for a piece of one's own. */
|
||||
studio(): void;
|
||||
packs: readonly FurniturePack[];
|
||||
}
|
||||
|
||||
interface Shown {
|
||||
card: CatalogCard;
|
||||
/** Names to show and to search by. */
|
||||
label: string;
|
||||
search: string;
|
||||
from: string;
|
||||
}
|
||||
|
||||
/** Every item of the library as cards, with the names to show and search. */
|
||||
function catalogue(host: EditorHost, packs: readonly FurniturePack[]): Shown[] {
|
||||
const language = host.hass?.language ?? "en";
|
||||
const builtIn = [...new Set(Object.values(FURNITURE_GROUPS).flat())];
|
||||
const entries: CatalogEntry[] = [
|
||||
...builtIn.map((type) => ({ type, source: "builtin", id: type, size: FURNITURE_SIZE[type as FurnitureType], lamp: isLamp(type), electric: isElectric(type) })),
|
||||
...packs.flatMap((pack) => pack.items.map((item) => ({ type: packType(pack.id, item.id), source: pack.id, id: item.id, size: item.size, lamp: !!item.light, electric: !!item.electric, vehicle: !!item.vehicle, climate: !!item.climate }))),
|
||||
];
|
||||
const packTitle = new Map(packs.map((p) => [p.id, packLabel(p, language)]));
|
||||
const itemNames = new Map(packs.flatMap((p) => p.items.map((it) => [packType(p.id, it.id), it] as const)));
|
||||
return cardsOf(entries).map((card) => {
|
||||
const first = card.entries[0];
|
||||
const item = itemNames.get(first.type);
|
||||
// a card with several sizes is named without the size ("Vanity unit 60 cm" -> "Vanity unit")
|
||||
const name = item ? packItemLabel(item, first.type, language) : host.t(`furn_${first.type}` as I18nKey);
|
||||
const label = card.entries.length > 1 ? name.replace(/\s*\(?\d+([.,]\d+)?\s*(cm|x\s*\d+|×\s*\d+)?\)?\s*$/i, "").trim() || name : name;
|
||||
const search = card.entries
|
||||
.map((e) => {
|
||||
const it = itemNames.get(e.type);
|
||||
return it ? [...Object.values(it.name), packItemLabel(it, e.type, language)].join(" ") : translate(ENGLISH, `furn_${e.type}` as I18nKey);
|
||||
})
|
||||
.join(" ");
|
||||
return { card, label, search: `${search} ${host.t(`lib_cat_${card.category}` as I18nKey)}`, from: packTitle.get(first.source) ?? "NextFloor" };
|
||||
});
|
||||
}
|
||||
|
||||
const matches = (shown: Shown, words: readonly string[]): boolean => hasAllWords(words, `${shown.label} ${shown.search} ${shown.from} ${shown.card.entries.map((e) => e.id.replace(/_/g, " ")).join(" ")}`);
|
||||
|
||||
const badgeOf = (entry: CatalogEntry): "light" | "switch" | null => (entry.lamp ? "light" : entry.electric ? "switch" : null);
|
||||
|
||||
function card(host: EditorHost, state: LibraryState, shown: Shown, actions: LibraryActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const entry = state.pickedOf(shown.card);
|
||||
const [w, d] = entry.size;
|
||||
const badge = badgeOf(entry);
|
||||
const show = (e: Event) => void state.showPreview(entry.type, e.currentTarget as HTMLElement, actions.packs);
|
||||
const add = () => {
|
||||
state.used(entry.type);
|
||||
actions.add(entry.type);
|
||||
};
|
||||
const fav = state.isFavourite(entry.type);
|
||||
return html`<div class="nf-card">
|
||||
<button
|
||||
class="nf-card-main"
|
||||
title=${badge ? t(badge === "light" ? "lib_badge_light" : "lib_badge_electric") : shown.label}
|
||||
@click=${add}
|
||||
@mouseenter=${show}
|
||||
@focus=${show}
|
||||
@mouseleave=${() => state.hidePreview()}
|
||||
@blur=${() => state.hidePreview()}
|
||||
>
|
||||
${thumbs.enabled ? html`<nf-thumb .type=${entry.type}></nf-thumb>` : nothing}
|
||||
<span class="nf-card-name"
|
||||
>${shown.label}${badge
|
||||
? html`<svg class="nf-lib-badge" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d=${iconPath(badge)} /></svg>`
|
||||
: nothing}</span
|
||||
>
|
||||
<span class="nf-card-meta">${Math.round(w * 100)} × ${Math.round(d * 100)} cm · ${shown.from}</span>
|
||||
</button>
|
||||
<button class="nf-card-star" aria-pressed=${fav} title=${t(fav ? "lib_fav_remove" : "lib_fav_add")} @click=${() => state.toggleFavourite(entry.type)}>${fav ? "★" : "☆"}</button>
|
||||
${shown.card.entries.length > 1
|
||||
? html`<div class="nf-card-sizes" role="group" aria-label=${t("lib_sizes")}>
|
||||
${shown.card.entries.map((e) => html`<button class="nf-size" aria-pressed=${e === entry} @click=${() => state.pick(shown.card, e.type)}>${sizeLabel(e, shown.card.entries)}</button>`)}
|
||||
</div>`
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function grid(host: EditorHost, state: LibraryState, list: readonly Shown[], actions: LibraryActions): TemplateResult {
|
||||
return html`<div class="nf-cards">${list.map((s) => card(host, state, s, actions))}</div>`;
|
||||
}
|
||||
|
||||
function section(host: EditorHost, state: LibraryState, key: string, title: string, list: readonly Shown[], actions: LibraryActions, byDefault: boolean): TemplateResult | typeof nothing {
|
||||
if (list.length === 0) return nothing;
|
||||
const open = state.isOpen(key, byDefault);
|
||||
return html`<button class="nf-lib-head nf-lib-toggle" aria-expanded=${open} @click=${() => state.toggle(key, byDefault)}>
|
||||
<span class="nf-lib-caret">${open ? "▾" : "▸"}</span>${title} <span class="nf-lib-count">${list.length}</span>
|
||||
</button>
|
||||
${open ? grid(host, state, list, actions) : nothing}`;
|
||||
}
|
||||
|
||||
/** The single cards for a list of types (favourites, recently used), in that order. */
|
||||
function cardsFor(types: readonly string[], all: readonly Shown[]): Shown[] {
|
||||
return types.flatMap((type) => {
|
||||
const shown = all.find((s) => s.card.entries.some((e) => e.type === type));
|
||||
return shown ? [{ ...shown, card: { ...shown.card, key: `one:${type}`, entries: shown.card.entries.filter((e) => e.type === type) } }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The sections in order: the room's main kind first, then what else fits the room, then the rest. */
|
||||
function orderFor(roomName: string | undefined): Category[] {
|
||||
const main = mainCategory(roomName);
|
||||
const fits = roomCategories(roomName);
|
||||
const rank = (c: Category) => (c === main ? 0 : fits?.has(c) ? 1 : 2);
|
||||
return [...CATEGORIES].sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
/** The library with its search box, filter chips and the sections by kind. */
|
||||
export function renderLibrary(host: EditorHost, state: LibraryState, roomName: string | undefined, actions: LibraryActions): TemplateResult {
|
||||
const t = host.t;
|
||||
thumbs.packs = actions.packs;
|
||||
const all = catalogue(host, actions.packs);
|
||||
const words = wordsOf(state.query);
|
||||
const fits = roomCategories(roomName);
|
||||
const byRoom = !!fits && state.has("room") && words.length === 0;
|
||||
const filtered = all.filter((s) => {
|
||||
const entry = s.card.entries[0];
|
||||
if (byRoom && !fits.has(s.card.category)) return false;
|
||||
if (state.has("linkable") && !entry.lamp && !entry.electric) return false;
|
||||
if (state.has("lit") && !entry.lamp) return false;
|
||||
if (state.has("outdoor") && !isOutdoorCategory(s.card.category)) return false;
|
||||
return words.length === 0 || matches(s, words);
|
||||
});
|
||||
const chip = (flag: Flag, label: string) => html`<button class="nf-chip nf-lib-chip" aria-pressed=${state.has(flag)} @click=${() => state.flip(flag)}>${label}</button>`;
|
||||
const searching = words.length > 0;
|
||||
return html`<section>
|
||||
<h3>${t("furniture_add")}</h3>
|
||||
<p class="nf-sub">${roomName ? t("furniture_into", { room: roomName }) : t("furniture_pick_room")}</p>
|
||||
<button class="nf-btn nf-lib-studio" title=${t("studio_hint")} @click=${() => actions.studio()}>🛠️ ${t("studio_new")}</button>
|
||||
<input
|
||||
class="nf-search"
|
||||
type="search"
|
||||
placeholder=${t("furniture_search")}
|
||||
.value=${state.query}
|
||||
@input=${(e: Event) => (state.query = (e.target as HTMLInputElement).value)}
|
||||
@keydown=${(e: KeyboardEvent) => e.key === "Escape" && (state.query = "")}
|
||||
/>
|
||||
<div class="nf-lib-chips">
|
||||
${fits ? chip("room", t("lib_for_room", { room: roomName ?? "" })) : nothing} ${chip("linkable", `⚡ ${t("lib_linkable")}`)} ${chip("lit", `💡 ${t("lib_lit")}`)}
|
||||
${chip("outdoor", `🌳 ${t("lib_outdoor")}`)}
|
||||
</div>
|
||||
${searching && filtered.length === 0 ? html`<p class="nf-sub">${t("furniture_search_none")}</p>` : nothing}
|
||||
${searching
|
||||
? grid(host, state, filtered, actions)
|
||||
: html`${section(host, state, "favourites", `★ ${t("lib_favourites")}`, cardsFor(state.favourites, all), actions, true)}
|
||||
${section(host, state, "recent", `🕘 ${t("lib_recent")}`, cardsFor(state.recent.slice(0, 6), all), actions, false)}
|
||||
${orderFor(roomName).map((c: Category) => section(host, state, c, t(`lib_cat_${c}` as I18nKey), filtered.filter((s) => s.card.category === c), actions, c === (mainCategory(roomName) ?? "lights")))}
|
||||
${byRoom ? html`<button class="nf-btn nf-lib-all" @click=${() => state.flip("room")}>${t("lib_all_rooms")}</button>` : nothing}`}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The big picture shown beside a library card while the pointer rests on it. */
|
||||
export function renderPreview(host: EditorHost, preview: Preview | null): TemplateResult | typeof nothing {
|
||||
if (!preview) return nothing;
|
||||
return html`<div class="nf-preview" style="left:${preview.left}px;top:${preview.top}px" aria-hidden="true">
|
||||
${preview.url ? html`<img src=${preview.url} alt="" />` : html`<span class="nf-preview-wait"></span>`}
|
||||
<b>${furnitureName(host.hass, preview.type)}</b>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// The real map under the plan: switch it on, put it where the house stands, and set how strongly it shows.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { DEFAULT_MAP_OPACITY, DEFAULT_MAP_ZOOM, mapShown } from "../../../map-geo.ts";
|
||||
import type { Building, MapSettings } from "../../../model.ts";
|
||||
import { checkField, hint, numberField, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { movedMap, newMap, tileTemplateFrom } from "../ops/map.ts";
|
||||
|
||||
const ZOOMS = ["15", "16", "17", "18", "19"] as const;
|
||||
/** The distances the arrow buttons move the map by (m). */
|
||||
const STEPS = ["1", "5", "20"] as const;
|
||||
/** The distance chosen for the arrow buttons; it stays while the page is open. */
|
||||
let moveStep: (typeof STEPS)[number] = "5";
|
||||
|
||||
export function renderMapSettings(host: EditorHost, doc: Building, set: (map: MapSettings | null) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const map = doc.settings.map ?? null;
|
||||
const place = host.hass?.config;
|
||||
const on = mapShown(map);
|
||||
const turnOn = (value: boolean) => {
|
||||
if (!value) return set(map ? { ...map, on: false } : null);
|
||||
set(map ? { ...map, on: true } : newMap(doc, { lat: place?.latitude, lon: place?.longitude }));
|
||||
};
|
||||
const change = (patch: Partial<MapSettings>) => map && set({ ...map, ...patch });
|
||||
const nudge = (dx: number, dz: number) => () => map && set(movedMap(map, dx * Number(moveStep), dz * Number(moveStep)));
|
||||
return html`<div class="nf-map-settings nf-wide">
|
||||
${checkField(host, t("map_on"), on, turnOn, { title: t("map_hint") })}
|
||||
${map && map.on
|
||||
? html`<div class="nf-form">
|
||||
${numberField(host, t("map_lat"), map.lat, (v) => change({ lat: Math.max(-85, Math.min(85, v)) }), 0.0001)}
|
||||
${numberField(host, t("map_lon"), map.lon, (v) => change({ lon: Math.max(-180, Math.min(180, v)) }), 0.0001)}
|
||||
${place?.latitude !== undefined && place.longitude !== undefined
|
||||
? html`<button class="nf-btn nf-wide" ?disabled=${!host.admin} @click=${() => change({ lat: place.latitude, lon: place.longitude })}>${t("map_use_ha")}</button>`
|
||||
: nothing}
|
||||
${numberField(host, t("map_opacity"), Math.round((map.opacity ?? DEFAULT_MAP_OPACITY) * 100), (v) => change({ opacity: Math.max(5, Math.min(100, v)) / 100 }), 5, 5)}
|
||||
${selectField(host, t("map_zoom"), String(map.zoom ?? DEFAULT_MAP_ZOOM), ZOOMS.map((z) => [z, z === "15" ? `${z} · ${t("map_zoom_coarse")}` : z === "19" ? `${z} · ${t("map_zoom_fine")}` : z] as const), (z) => change({ zoom: Number(z) }))}
|
||||
<div class="nf-wide nf-map-move">
|
||||
<span class="nf-sub">${t("map_move")}</span>
|
||||
<div class="nf-map-arrows">
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("map_move")} @click=${nudge(0, -1)}>▲</button>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("map_move")} @click=${nudge(-1, 0)}>◀</button>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("map_move")} @click=${nudge(1, 0)}>▶</button>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("map_move")} @click=${nudge(0, 1)}>▼</button>
|
||||
</div>
|
||||
${selectField(host, t("map_step"), moveStep, STEPS.map((s) => [s, `${s} m`] as const), (v) => (moveStep = v), { wide: false })}
|
||||
</div>
|
||||
${textField(host, t("map_url"), map.url ?? "", (v) => {
|
||||
const url = tileTemplateFrom(v);
|
||||
if (url !== undefined) change({ url });
|
||||
}, { wide: true, placeholder: "https://…/{z}/{x}/{y}.png", maxlength: 300 })}
|
||||
${hint(t("map_hint"), "nf-wide")}
|
||||
</div>`
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// The form of a note in the plan: its text, the day it is due (its pin turns orange from then on), and its spot.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { NOTE_Y, noteDue, uid, type PlanNote } from "../../../model.ts";
|
||||
import { storeImage } from "../../../api.ts";
|
||||
import { readPictureInBrowser } from "../background-tool.ts";
|
||||
import { actions, hint, numberField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
export interface NoteActions {
|
||||
patch(patch: Partial<PlanNote>): void;
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
export function renderNoteForm(host: EditorHost, note: PlanNote, act: NoteActions): TemplateResult {
|
||||
const t = host.t;
|
||||
return html`<section>
|
||||
<h3>✎ ${t("note")}</h3>
|
||||
<div class="nf-form">
|
||||
<label class="nf-field nf-wide"
|
||||
>${t("note_text")}
|
||||
<textarea rows="4" maxlength="500" .value=${note.text} ?disabled=${!host.admin} placeholder=${t("note_placeholder")} @change=${(e: Event) => act.patch({ text: (e.target as HTMLTextAreaElement).value.trim() })}></textarea>
|
||||
</label>
|
||||
<label class="nf-field"
|
||||
>${t("note_due")}
|
||||
<input type="date" .value=${note.due ?? ""} ?disabled=${!host.admin} @change=${(e: Event) => act.patch({ due: (e.target as HTMLInputElement).value || null })} />
|
||||
</label>
|
||||
${noteDue(note) ? html`<p class="nf-sub nf-warn nf-wide">${t("note_is_due")}</p>` : hint(t("note_due_hint"), "nf-wide")}
|
||||
${numberField(host, t("x"), note.x, (v) => act.patch({ x: v }))} ${numberField(host, t("z"), note.z, (v) => act.patch({ z: v }))}
|
||||
${numberField(host, t("note_height"), note.y ?? NOTE_Y, (v) => act.patch({ y: Math.max(0, Math.min(20, Math.round(v * 100) / 100)) }), 0.1, 0)}
|
||||
${hint(t("note_height_hint"), "nf-wide")}
|
||||
${photoFields(host, note, act)}
|
||||
</div>
|
||||
${actions(html`<button class="nf-btn nf-danger" ?disabled=${!host.admin} @click=${() => act.remove()}>${t("delete")}</button>`)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** A note's photo: uploaded and stored with the plan, or a URL; shown when the note is opened in the 3D view (#113). */
|
||||
function photoFields(host: EditorHost, note: PlanNote, act: NoteActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const stored = !!note.photo?.startsWith("image:");
|
||||
const upload = async (e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
if (!file || !host.hass) return;
|
||||
const { data } = await readPictureInBrowser(file);
|
||||
const id = uid("img");
|
||||
await storeImage(host.hass, id, data);
|
||||
act.patch({ photo: `image:${id}` });
|
||||
};
|
||||
return html`${host.admin
|
||||
? html`<label class="nf-btn nf-wide nf-upload">📷 ${t(stored ? "picture_replace" : "note_photo_upload")}<input type="file" accept="image/*" hidden @change=${upload} /></label>`
|
||||
: nothing}
|
||||
${stored
|
||||
? html`<p class="nf-sub nf-wide">${t("picture_stored")} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => act.patch({ photo: null })}>${t("delete")}</button></p>`
|
||||
: textField(host, t("picture_url"), note.photo ?? "", (v) => act.patch({ photo: v.trim() || null }), { wide: true, placeholder: "/local/valve.jpg" })}
|
||||
${hint(t("note_photo_hint"), "nf-wide")}`;
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
// The form of a door, window or garage door: its kind and size, how it looks, and the entities that make it live (blind, contacts,
|
||||
// handle sensors, tilt).
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { entityName, openingEntities, windowPosition } from "../../../devices.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { DOOR_STYLES, OPENING_PRESETS, openingPreset, openingStyle, WINDOW_OPENINGS, WINDOW_STYLES, type Opening, type OpeningPreset, type OpeningStyle } from "../../../model.ts";
|
||||
import { entityOptions, isNumeric } from "../entities.ts";
|
||||
import { checkField, entityField, hint, numberField, selectField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
/** What the form makes the editor do, and what it asks of it. */
|
||||
export interface OpeningActions {
|
||||
update(patch: Partial<Opening>): void;
|
||||
setPreset(opening: Opening, preset: OpeningPreset): void;
|
||||
remove(): void;
|
||||
/** Whether the opening is in an outer wall, which decides the automatic style of a door. */
|
||||
isExterior(opening: Opening): boolean;
|
||||
/** Whether a window's sill lies below the ground (a cellar window, which gets a light well). */
|
||||
isBelowGround?(opening: Opening): boolean;
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
}
|
||||
|
||||
type SensorKind = NonNullable<Opening["sensor"]>;
|
||||
const CONTACT_CLASSES = ["door", "window", "opening", "garage_door"];
|
||||
const HANDLE_NAME = /griff|handle|fenster|window|drehgriff/i;
|
||||
|
||||
/** The opening angles a door offers (null = the usual swing), with an angle set by hand or in an imported plan kept in the list. */
|
||||
function doorAngles(current: number | null | undefined): (number | null)[] {
|
||||
const angles: (number | null)[] = [null, 15, 30, 45, 60, 90, 120, 180];
|
||||
if (current && !angles.includes(current)) angles.push(current);
|
||||
return angles.sort((a, b) => (a ?? 0) - (b ?? 0));
|
||||
}
|
||||
|
||||
/** The entity lists the form offers, worked out once per draw. */
|
||||
function choices(host: EditorHost) {
|
||||
const { hass } = host;
|
||||
const stateOf = (id: string) => hass?.states[id];
|
||||
const deviceClass = (id: string) => stateOf(id)?.attributes.device_class as string | undefined;
|
||||
const isContact = (id: string) => id.startsWith("binary_sensor.") && CONTACT_CLASSES.includes(deviceClass(id) ?? "");
|
||||
return {
|
||||
covers: entityOptions(hass, (id) => id.startsWith("cover.")),
|
||||
// numbers that can report where a blind is
|
||||
positions: entityOptions(hass, (id) => /^(sensor|number|input_number)\./.test(id) && Number.isFinite(Number(stateOf(id)?.state))),
|
||||
// plain contacts, and handle sensors with three states (open, tilted, closed)
|
||||
contacts: entityOptions(hass, (id) => isContact(id) || (isNumeric(id) && windowPosition(stateOf(id)) !== null)),
|
||||
plainContacts: entityOptions(hass, isContact),
|
||||
// handle sensors say open, tilted or closed as text, or in a window_state attribute, or are named like a handle
|
||||
handles: entityOptions(hass, (id) => {
|
||||
if (id.startsWith("binary_sensor.")) return typeof stateOf(id)?.attributes.window_state === "string";
|
||||
return isNumeric(id) && (windowPosition(stateOf(id)) !== null || HANDLE_NAME.test(`${id} ${entityName(hass, id)}`));
|
||||
}),
|
||||
numbers: entityOptions(hass, isNumeric),
|
||||
locks: entityOptions(hass, (id) => id.startsWith("lock.")),
|
||||
};
|
||||
}
|
||||
|
||||
/** What "automatic" would pick for a link of the opening: the opening is looked at again with that link cleared. */
|
||||
function automaticLink(host: EditorHost, opening: Opening, key: "cover" | "contact"): string | null {
|
||||
if (!host.hass) return null;
|
||||
const probe = structuredClone(host.doc.floors);
|
||||
for (const floor of probe) for (const o of floor.openings) if (o.id === opening.id) o[key] = null;
|
||||
return openingEntities(host.hass, probe).get(opening.id)?.[key] ?? null;
|
||||
}
|
||||
|
||||
const noneAsNull = (v: string | null) => (v === "none" ? null : v);
|
||||
|
||||
/** The style of a door or window: automatic (by wall), or one of the built-in looks. */
|
||||
function styleField(host: EditorHost, o: Opening, actions: OpeningActions): TemplateResult {
|
||||
const styles: readonly OpeningStyle[] = o.type === "door" ? DOOR_STYLES : WINDOW_STYLES;
|
||||
const automatic = openingStyle({ type: o.type, style: null }, actions.isExterior(o));
|
||||
const current = o.style && (styles as readonly string[]).includes(o.style) ? o.style : "";
|
||||
const options: [string, string][] = [["", host.t("style_auto", { style: host.t(`style_${automatic}` as I18nKey) })], ...styles.map((s): [string, string] => [s, host.t(`style_${s}` as I18nKey)])];
|
||||
return selectField(host, host.t("opening_style"), current, options, (v) => actions.update({ style: (v || null) as OpeningStyle | null }), { wide: true });
|
||||
}
|
||||
|
||||
/** A width in metres for a sidelight, empty for "as wide as it comes". */
|
||||
function sidelightWidth(host: EditorHost, o: Opening, key: "sidelight_width" | "sidelight_width2", label: I18nKey, actions: OpeningActions): TemplateResult {
|
||||
return html`<label class="nf-field"
|
||||
>${host.t(label)}
|
||||
<input
|
||||
type="number"
|
||||
step="0.05"
|
||||
min="0.1"
|
||||
max="3"
|
||||
placeholder=${host.t("sidelight_auto")}
|
||||
.value=${o[key] == null ? "" : String(o[key])}
|
||||
?disabled=${!host.admin}
|
||||
@change=${(e: Event) => {
|
||||
const v = Number((e.target as HTMLInputElement).value);
|
||||
actions.update({ [key]: Number.isFinite(v) && v > 0 ? Math.min(3, Math.max(0.1, Math.round(v * 100) / 100)) : null });
|
||||
}}
|
||||
/>
|
||||
</label>`;
|
||||
}
|
||||
|
||||
/** Front doors with sidelights: on which side the single one sits, and the widths. */
|
||||
function sidelightFields(host: EditorHost, o: Opening, actions: OpeningActions): TemplateResult | typeof nothing {
|
||||
if (o.type !== "door") return nothing;
|
||||
const style = openingStyle(o, actions.isExterior(o));
|
||||
if (style === "sidelight") {
|
||||
return html`${checkField(host, host.t("sidelight_hinge"), !!o.sidelight_hinge, (on) => actions.update({ sidelight_hinge: on }), { wide: false, title: host.t("sidelight_hinge_hint") })}
|
||||
${sidelightWidth(host, o, "sidelight_width", "sidelight_width", actions)}`;
|
||||
}
|
||||
if (style === "sidelights") return html`${sidelightWidth(host, o, "sidelight_width", "sidelight_width_left", actions)} ${sidelightWidth(host, o, "sidelight_width2", "sidelight_width_right", actions)}`;
|
||||
return nothing;
|
||||
}
|
||||
|
||||
/**
|
||||
* A glass wall: how many panes its mullions make. Empty keeps the old spacing of about 0.9 m, 0 gives one single pane for
|
||||
* the full-width glazing modern houses have.
|
||||
*/
|
||||
function glassWallPanes(host: EditorHost, o: Opening, actions: OpeningActions): TemplateResult | typeof nothing {
|
||||
if (o.type !== "window" || openingStyle(o, actions.isExterior(o)) !== "glass_wall") return nothing;
|
||||
return html`<label class="nf-field"
|
||||
>${host.t("glass_panes")}
|
||||
<input
|
||||
type="number"
|
||||
step="1"
|
||||
min="0"
|
||||
max="40"
|
||||
placeholder=${host.t("glass_panes_auto")}
|
||||
.value=${o.panes == null ? "" : String(o.panes)}
|
||||
?disabled=${!host.admin}
|
||||
@change=${(e: Event) => {
|
||||
const raw = (e.target as HTMLInputElement).value.trim();
|
||||
const v = Number(raw);
|
||||
actions.update({ panes: raw === "" || !Number.isFinite(v) ? null : Math.min(40, Math.max(0, Math.round(v))) });
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
${hint(host.t("glass_panes_hint"), "nf-wide")}`;
|
||||
}
|
||||
|
||||
/** The sensors of one sash of a window: what kind they are, the entity, the tilt, and for the main sash the tilt angle. */
|
||||
function sashSensors(host: EditorHost, o: Opening, sash: 1 | 2, actions: OpeningActions, lists: ReturnType<typeof choices>): TemplateResult {
|
||||
const main = sash === 1;
|
||||
const t = host.t;
|
||||
const tilt = main ? o.tilt : (o.tilt2 ?? null);
|
||||
const contact = main ? o.contact : o.contact2;
|
||||
const kind: SensorKind = (main ? o.sensor : o.sensor2) ?? (tilt && tilt !== "none" ? "contact_tilt" : "contact");
|
||||
const kinds = (["contact", "handle", "contact_tilt"] as const).map((k): [SensorKind, string] => [k, t(`sensor_kind_${k}`)]);
|
||||
const changeKind = (next: SensorKind) => {
|
||||
const clearTilt = next === "contact_tilt" ? {} : main ? { tilt: null } : { tilt2: null };
|
||||
actions.update({ ...(main ? { sensor: next } : { sensor2: next }), ...clearTilt });
|
||||
};
|
||||
const setContact = (v: string | null) => actions.update(main ? { contact: v } : { contact2: noneAsNull(v) });
|
||||
const tiltAngle = o.tilt_angle && o.tilt_angle !== "none";
|
||||
return html`${selectField(host, t("sensor_kind"), kind, kinds, changeKind, { wide: true })}
|
||||
${kind === "handle"
|
||||
? entityField(host, t("handle_entity"), contact, undefined, lists.handles, (v) => setContact(v === "none" ? (main ? "none" : null) : v))
|
||||
: entityField(host, t("contact_entity"), contact, main ? automaticLink(host, o, "contact") : undefined, lists.plainContacts, setContact)}
|
||||
${kind === "contact_tilt" ? entityField(host, t("tilt_entity"), tilt, undefined, lists.contacts, (v) => actions.update(main ? { tilt: noneAsNull(v) } : { tilt2: noneAsNull(v) })) : nothing}
|
||||
${main
|
||||
? html`${entityField(host, t("tilt_angle_entity"), o.tilt_angle ?? null, undefined, lists.numbers, (v) => actions.update({ tilt_angle: noneAsNull(v) }))}
|
||||
${tiltAngle
|
||||
? html`${numberField(host, t("tilt_angle_max"), o.tilt_max ?? 15, (v) => actions.update({ tilt_max: Math.min(90, Math.max(1, v)) }), 1, 1)}
|
||||
${numberField(host, t("tilt_angle_offset"), o.tilt_offset ?? 0, (v) => actions.update({ tilt_offset: v }), 0.5)}
|
||||
${checkField(host, t("tilt_angle_invert"), !!o.tilt_invert, (on) => actions.update({ tilt_invert: on }))}`
|
||||
: nothing}`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** The blind of the opening: the cover entity, where it reports its position, and whether to ask before moving it. */
|
||||
function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, lists: ReturnType<typeof choices>): TemplateResult {
|
||||
const t = host.t;
|
||||
const window = o.type === "window";
|
||||
const automatic = automaticLink(host, o, "cover");
|
||||
const hasBlind = o.cover !== "none" && (o.cover || automatic);
|
||||
return html`${entityField(host, t(window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }))}
|
||||
${hasBlind
|
||||
? html`${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }))}
|
||||
${o.position ? checkField(host, t("cover_position_invert"), !!o.position_inverted, (on) => actions.update({ position_inverted: on })) : nothing}
|
||||
${checkField(host, t("device_confirm"), !!o.confirm, (on) => actions.update({ confirm: on }), { title: t("cover_confirm_hint") })}
|
||||
${window
|
||||
? html`${selectField(host, t("blind_kind"), o.blind ?? "roller", [["roller", t("blind_roller")], ["venetian", t("blind_venetian")], ["inside", t("blind_inside")]], (v) => actions.update({ blind: v === "roller" ? null : (v as Opening["blind"]) }))}
|
||||
${entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) }))}`
|
||||
: nothing}
|
||||
${!window && o.type !== "garage" ? entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) })) : nothing}
|
||||
${numberField(host, t("cover_my"), o.my_position ?? 0, (v) => actions.update({ my_position: v > 0 ? Math.min(100, Math.round(v)) : null }), 5, 0)}
|
||||
${hint(t("blind_hint"), "nf-wide")}`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** The contacts of a door or garage door; a double door has one per leaf, and a door can be marked as shut when it reports closed. */
|
||||
function doorContacts(host: EditorHost, o: Opening, actions: OpeningActions, lists: ReturnType<typeof choices>): TemplateResult {
|
||||
const t = host.t;
|
||||
const two = o.leaves === 2;
|
||||
return html`${entityField(host, t(two ? "contact_main" : "contact_entity"), o.contact, automaticLink(host, o, "contact"), lists.contacts, (v) => actions.update({ contact: v }))}
|
||||
${two && o.type !== "garage" ? entityField(host, t("contact_second"), o.contact2, undefined, lists.contacts, (v) => actions.update({ contact2: noneAsNull(v) })) : nothing}
|
||||
${o.type === "door" ? checkField(host, t("door_shut"), !!o.shut, (on) => actions.update({ shut: on }), { title: t("door_shut_hint") }) : nothing}
|
||||
${o.type === "door" && o.style !== "sliding" && o.style !== "passage"
|
||||
? selectField(host, t("door_angle"), String(o.open_angle ?? ""), doorAngles(o.open_angle).map((a) => [String(a ?? ""), a ? `${a}°` : t("door_angle_default")] as const), (v) => actions.update({ open_angle: v ? Number(v) : null }), { title: t("door_angle_hint") })
|
||||
: nothing}
|
||||
${o.type === "door" ? html`${entityField(host, t("opening_lock"), o.lock ?? null, undefined, lists.locks, (v) => actions.update({ lock: noneAsNull(v) }))}${hint(t("opening_lock_hint"), "nf-wide")}` : nothing}`;
|
||||
}
|
||||
|
||||
/** The form of the selected opening. */
|
||||
export function renderOpeningForm(host: EditorHost, o: Opening, actions: OpeningActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const lists = choices(host);
|
||||
const preset = openingPreset(o);
|
||||
const [window, garage, door] = [o.type === "window", o.type === "garage", o.type === "door"];
|
||||
const at = (patch: Partial<Opening>) => actions.update(patch);
|
||||
const presets = (Object.keys(OPENING_PRESETS) as OpeningPreset[]).map((p) => html`<button class="nf-chip" aria-pressed=${p === preset} @click=${() => actions.setPreset(o, p)}>${t(`preset_${p}` as I18nKey)}</button>`);
|
||||
const hingeChoices: [Opening["hinge"], string][] = [["left", t("hinge_left")], ["right", t("hinge_right")]];
|
||||
const markChoices: [string, string][] = [["", t("opening_mark_open")], ["closed", t("opening_mark_closed")]];
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t(`preset_${preset}` as I18nKey)}</h3>${actions.lockButton}</div>
|
||||
${host.admin ? html`<div class="nf-presets" role="group" aria-label=${t("opening_type")}>${presets}</div>` : nothing}
|
||||
${host.admin && !garage
|
||||
? html`<div class="nf-actions">
|
||||
<button class="nf-btn" title=${t("flip_hinge_hint")} @click=${() => at({ hinge: o.hinge === "left" ? "right" : "left" })}>⇆ ${t(o.leaves === 2 ? "flip_main_leaf" : "flip_hinge")}</button>
|
||||
${door ? html`<button class="nf-btn" title=${t("flip_swing_hint")} @click=${() => at({ swing: o.swing === "out" ? "in" : "out" })}>⇅ ${t("flip_swing")}</button>` : nothing}
|
||||
</div>`
|
||||
: nothing}
|
||||
<div class="nf-form">
|
||||
${numberField(host, t("width"), o.width, (v) => at({ width: Math.max(0.3, v) }), 0.01, 0.3)}
|
||||
${numberField(host, t("opening_position"), o.offset, (v) => at({ offset: Math.max(0, v) }), 0.01, 0)}
|
||||
${window ? numberField(host, t("sill"), o.sill, (v) => at({ sill: Math.max(0, v) }), 0.01, 0) : nothing}
|
||||
${numberField(host, t("opening_height"), o.height, (v) => at({ height: Math.max(0.3, v) }), 0.01, 0.3)}
|
||||
${garage ? nothing : styleField(host, o, actions)} ${sidelightFields(host, o, actions)} ${glassWallPanes(host, o, actions)}
|
||||
${window && o.style !== "glass_wall"
|
||||
? selectField(host, t("window_opens"), o.opens ?? "turn", WINDOW_OPENINGS.map((w) => [w, t(`window_opens_${w}` as I18nKey)] as const), (v) => at({ opens: v === "turn" ? null : v }), { wide: true, title: t("window_opens_hint") })
|
||||
: nothing}
|
||||
${selectField(host, t("opening_mark"), o.mark === "closed" ? "closed" : "", markChoices, (v) => at({ mark: v === "closed" ? "closed" : null }), { wide: true, title: t("opening_mark_hint") })}
|
||||
${garage ? nothing : selectField(host, t(o.leaves === 2 ? "main_leaf" : "hinge"), o.hinge, hingeChoices, (hinge) => at({ hinge }), { wide: true })}
|
||||
${window
|
||||
? selectField(host, t("sill_boards"), o.sill_boards ?? "auto", [["auto", t("sill_boards_auto")], ["none", t("sill_boards_none")], ["inside", t("sill_boards_inside")], ["outside", t("sill_boards_outside")]] as const, (v) => at({ sill_boards: v === "auto" ? null : v }), { wide: true })
|
||||
: nothing}
|
||||
${window ? checkField(host, t("opening_rain_warning"), o.rain_warning !== false, (on) => at({ rain_warning: on ? undefined : false }), { wide: true }) : nothing}
|
||||
${window && actions.isBelowGround?.(o) ? checkField(host, t("opening_light_well"), o.light_well !== false, (on) => at({ light_well: on ? null : false }), { wide: true }) : nothing}
|
||||
${blindFields(host, o, actions, lists)}
|
||||
${window
|
||||
? html`${o.leaves === 2 ? html`<h4 class="nf-lib-head nf-wide">${t("leaf_main")}</h4>` : nothing}${sashSensors(host, o, 1, actions, lists)}
|
||||
${o.leaves === 2 ? html`<h4 class="nf-lib-head nf-wide">${t("leaf_second")}</h4>${sashSensors(host, o, 2, actions, lists)}` : nothing}`
|
||||
: doorContacts(host, o, actions, lists)}
|
||||
</div>
|
||||
${hint(t(window ? "opening_hint" : garage ? "garage_hint" : "door_hint"))}
|
||||
${host.admin ? html`<div class="nf-actions"><button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("delete")}</button></div>` : nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// The form of an outdoor area (lawn, terrace, pool, fence, pergola ...) and the measuring tool's panel.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { bounds, cutsOut, isAxisRect, uid, type FenceGate, type FreeWall, OUTDOOR_TOP, OUTDOOR_TYPES, outdoorStanding, SLOPE_DIRS, type Direction, type OutdoorArea, type OutdoorType, type SlopeDir, type Vec2 } from "../../../model.ts";
|
||||
import { checkField, entityField, hint, numberField, selectField, toThousandths } from "../fields.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { wallEndForLength, wallHeightPatch } from "../ops/items.ts";
|
||||
import { arcButton, arcRow, type ArcActions } from "./arc.ts";
|
||||
|
||||
export interface OutdoorActions {
|
||||
update(patch: Partial<OutdoorArea>): void;
|
||||
setRectangle(field: "x" | "z" | "w" | "d", value: number): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
removeCorner(index: number): void;
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
}
|
||||
|
||||
const between = (low: number, high: number, v: number) => Math.min(high, Math.max(low, toThousandths(v)));
|
||||
|
||||
export function renderOutdoorForm(host: EditorHost, area: OutdoorArea, actions: OutdoorActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<OutdoorArea>) => actions.update(patch);
|
||||
const box = bounds(area.points);
|
||||
const types = OUTDOOR_TYPES.map((type): [OutdoorType, string] => [type, t(`out_${type}` as I18nKey)]);
|
||||
const slopeDirs = SLOPE_DIRS.map((d): [SlopeDir, string] => [d, t(`slope_${d.replace("-", "n")}` as I18nKey)]);
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("outdoor")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">
|
||||
${selectField(host, t("outdoor_type"), area.type, types, (type) => set({ type }), { wide: true })}
|
||||
${selectField(host, t("area"), area.area_id ?? "", [["", t("no_area")], ...Object.values(host.hass?.areas ?? {}).sort((a, b) => a.name.localeCompare(b.name)).map((a): [string, string] => [a.area_id, a.name])], (id) => set({ area_id: id || null }), { wide: true, title: t("outdoor_area_hint") })}
|
||||
${area.type === "pool" || area.type === "wild" || area.type === "bed"
|
||||
? html`${entityField(host, t("pool_temp"), area.temp_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "temperature"), (v) => set({ temp_entity: v && v !== "none" ? v : null }))}
|
||||
${entityField(host, t("pool_pump"), area.pump_entity ?? null, undefined, entityOptions(host.hass, (id) => /^(switch|fan|valve|input_boolean|binary_sensor)\./.test(id)), (v) => set({ pump_entity: v && v !== "none" ? v : null }))}`
|
||||
: nothing}
|
||||
${isAxisRect(area.points)
|
||||
? html`${numberField(host, t("x"), box.x0, (v) => actions.setRectangle("x", v))} ${numberField(host, t("z"), box.z0, (v) => actions.setRectangle("z", v))}
|
||||
${numberField(host, t("width"), box.x1 - box.x0, (v) => actions.setRectangle("w", v), 0.01, 0.1)} ${numberField(host, t("depth"), box.z1 - box.z0, (v) => actions.setRectangle("d", v), 0.01, 0.1)}`
|
||||
: nothing}
|
||||
${outdoorStanding(area.type) ? numberField(host, t("outdoor_height"), area.height ?? OUTDOOR_TOP[area.type], (v) => set({ height: between(0.1, 6, v) }), 0.05, 0.1) : nothing}
|
||||
${numberField(host, t("outdoor_offset"), area.offset ?? 0, (v) => set({ offset: between(-10, 10, v) || null }), 0.05)}
|
||||
${area.type !== "pool"
|
||||
? html`${numberField(host, t("outdoor_slope"), area.slope ?? 0, (v) => set({ slope: between(0, 20, v) || null }), 0.05, 0)}
|
||||
${selectField(host, t("outdoor_slope_dir"), area.slope_dir ?? "x", slopeDirs, (slope_dir) => set({ slope_dir }))}`
|
||||
: nothing}
|
||||
${numberField(host, t("outdoor_opacity"), Math.round((area.opacity ?? 1) * 100), (v) => set({ opacity: v >= 100 || !(v > 0) ? null : Math.max(10, Math.min(95, v)) / 100 }), 5, 10)}
|
||||
${checkField(host, t("outdoor_outline"), area.outline !== false, (on) => set({ outline: on ? undefined : false }), { title: t("outdoor_outline_hint") })}
|
||||
${area.type === "fence" || area.type === "pergola" ? checkField(host, t("outdoor_open"), !!area.open, (on) => set({ open: on || undefined }), { title: t("outdoor_open_hint") }) : nothing}
|
||||
${area.type === "pergola" ? checkField(host, t("outdoor_bracing"), !!area.bracing, (on) => set({ bracing: on || undefined })) : nothing}
|
||||
${checkField(host, t("outdoor_cut"), cutsOut(area), (on) => set({ cut: on === (area.type === "pool") ? undefined : on }), { title: t("outdoor_cut_hint") })}
|
||||
</div>
|
||||
${area.type === "fence" ? fenceGates(host, area, set) : nothing}
|
||||
${host.admin
|
||||
? html`<div class="nf-actions">
|
||||
${area.points.map((_, i) => html`<button class="nf-chip" title=${t("delete_point")} ?disabled=${area.points.length <= 3} @click=${() => actions.removeCorner(i)}>${i + 1} ×</button>`)}
|
||||
</div>
|
||||
${hint(t("outdoor_corners_hint"))}`
|
||||
: nothing}
|
||||
${area.slope ? hint(t("outdoor_slope_hint")) : nothing} ${hint(t("outdoor_hint"))}
|
||||
${host.admin
|
||||
? html`<div class="nf-actions"><button class="nf-btn" @click=${() => actions.duplicate()}>${t("duplicate")}</button><button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("delete")}</button></div>`
|
||||
: nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The gates of a fence: each a gap in one edge with a leaf (or two) that follows an entity or a contact. */
|
||||
function fenceGates(host: EditorHost, area: OutdoorArea, set: (patch: Partial<OutdoorArea>) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const gates = area.gates ?? [];
|
||||
const store = (next: FenceGate[]) => set({ gates: next.length ? next : undefined });
|
||||
const edges = area.points.map((_, i): [string, string] => [String(i), `${i + 1} → ${((i + 1) % area.points.length) + 1}`]);
|
||||
const edgeLength = (i: number) => {
|
||||
const [a, b] = [area.points[i], area.points[(i + 1) % area.points.length]];
|
||||
return a && b ? Math.hypot(b[0] - a[0], b[1] - a[1]) : 0;
|
||||
};
|
||||
const patch = (i: number, change: Partial<FenceGate>) => store(gates.map((g, k) => (k === i ? { ...g, ...change } : g)));
|
||||
const drivers = entityOptions(host.hass, (id) => /^(cover|switch|input_boolean|lock)\./.test(id));
|
||||
const contacts = entityOptions(host.hass, (id) => id.startsWith("binary_sensor."));
|
||||
const kinds: [string, string][] = [["single", t("gate_single")], ["double", t("gate_double")], ["sliding", t("gate_sliding")]];
|
||||
const add = () => {
|
||||
const edge = 0;
|
||||
const length = edgeLength(edge);
|
||||
store([...gates, { id: uid("gate"), edge, offset: toThousandths(length / 2), width: Math.min(1.2, Math.max(0.5, toThousandths(length * 0.4))), kind: "single" }]);
|
||||
};
|
||||
return html`<h4 class="nf-lib-head">${t("fence_gates")}</h4>
|
||||
${gates.map(
|
||||
(g, i) => html`<div class="nf-form">
|
||||
${selectField(host, t("gate_edge"), String(g.edge), edges, (v) => patch(i, { edge: Number(v) }))}
|
||||
${selectField(host, t("gate_kind"), g.kind, kinds, (kind) => patch(i, { kind: kind as FenceGate["kind"], width: kind === "single" && g.width > 1.6 ? 1 : g.width }))}
|
||||
${numberField(host, t("gate_offset"), g.offset, (v) => patch(i, { offset: Math.max(0, Math.min(edgeLength(g.edge), toThousandths(v))) }), 0.05, 0)}
|
||||
${numberField(host, t("gate_width"), g.width, (v) => patch(i, { width: Math.max(0.3, Math.min(12, toThousandths(v))) }), 0.05, 0.3)}
|
||||
${entityField(host, t("gate_entity"), g.entity ?? null, undefined, drivers, (v) => patch(i, { entity: v && v !== "none" ? v : null }))}
|
||||
${entityField(host, t("gate_contact"), g.contact ?? null, undefined, contacts, (v) => patch(i, { contact: v && v !== "none" ? v : null }))}
|
||||
${host.admin ? html`<button class="nf-btn nf-danger nf-wide" @click=${() => store(gates.filter((_, k) => k !== i))}>${t("delete")}</button>` : nothing}
|
||||
</div>`,
|
||||
)}
|
||||
${host.admin && gates.length < 20 ? html`<button class="nf-btn" @click=${add}>${t("gate_add")}</button>` : nothing}
|
||||
${hint(t("fence_gates_hint"))}`;
|
||||
}
|
||||
|
||||
export interface MeasureState {
|
||||
draft: readonly Vec2[];
|
||||
length: number;
|
||||
rectSize: readonly [number, number];
|
||||
}
|
||||
|
||||
export interface MeasureActions {
|
||||
setLength(metres: number): void;
|
||||
step(direction: Direction): void;
|
||||
close(): void;
|
||||
undo(): void;
|
||||
setRectSize(size: [number, number]): void;
|
||||
addRectangle(): void;
|
||||
}
|
||||
|
||||
const ARROWS: [Direction, string][] = [["up", "↑"], ["left", "←"], ["right", "→"], ["down", "↓"]];
|
||||
const KEY_DIRECTION: Record<string, Direction> = { ArrowRight: "right", ArrowLeft: "left", ArrowUp: "up", ArrowDown: "down" };
|
||||
|
||||
/** The measuring tool: lay out a room as a chain of lengths in directions, or add a rectangle of a typed size. */
|
||||
export function renderMeasureForm(host: EditorHost, state: MeasureState, actions: MeasureActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const { draft } = state;
|
||||
const metres = (v: number) => formatNumber(host.hass, v, 2);
|
||||
const [first, last] = [draft[0], draft[draft.length - 1]];
|
||||
const gap = first && draft.length > 1 ? Math.hypot(last[0] - first[0], last[1] - first[1]) : 0;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const direction = KEY_DIRECTION[e.key];
|
||||
if (direction) {
|
||||
e.preventDefault();
|
||||
actions.step(direction);
|
||||
} else if (e.key === "Enter") actions.close();
|
||||
};
|
||||
const chain = first
|
||||
? html`${hint(t("measure_from", { x: metres(first[0]), z: metres(first[1]) }))}
|
||||
<div class="nf-form">
|
||||
<label class="nf-field nf-wide"
|
||||
>${t("measure_length")}
|
||||
<input class="nf-measure-input" type="number" inputmode="decimal" step="0.01" min="0.05" .value=${String(state.length)} @input=${(e: Event) => actions.setLength(Number.parseFloat((e.target as HTMLInputElement).value.replace(",", ".")) || 0)} @keydown=${onKey} />
|
||||
</label>
|
||||
<div class="nf-arrows nf-wide">${ARROWS.map(([d, label]) => html`<button class="nf-btn nf-arrow-${d}" title=${t(`dir_${d}`)} @click=${() => actions.step(d)}>${label}</button>`)}</div>
|
||||
</div>
|
||||
${draft.length > 1 ? html`<ol class="nf-measure-list">${draft.slice(1).map((p, i) => html`<li>${metres(Math.hypot(p[0] - draft[i][0], p[1] - draft[i][1]))} m</li>`)}</ol>` : nothing}
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn nf-primary" ?disabled=${draft.length < 3} @click=${() => actions.close()}>${t("measure_close")}</button>
|
||||
<button class="nf-btn" ?disabled=${draft.length < 2} @click=${() => actions.undo()}>${t("measure_undo")}</button>
|
||||
</div>
|
||||
${draft.length >= 3 ? hint(t("measure_gap", { gap: metres(gap) })) : nothing}`
|
||||
: hint(t("measure_start"));
|
||||
return html`<section>
|
||||
<h3>${t("measure")}</h3>
|
||||
${chain}
|
||||
<h4 class="nf-lib-head">${t("rect_by_size")}</h4>
|
||||
<div class="nf-form">
|
||||
${numberField(host, t("width"), state.rectSize[0], (v) => actions.setRectSize([Math.max(0.1, v), state.rectSize[1]]), 0.01, 0.1)}
|
||||
${numberField(host, t("depth"), state.rectSize[1], (v) => actions.setRectSize([state.rectSize[0], Math.max(0.1, v)]), 0.01, 0.1)}
|
||||
<button class="nf-btn nf-wide" @click=${() => actions.addRectangle()}>${t("rect_add")}</button>
|
||||
</div>
|
||||
${hint(t("measure_hint"))}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
export interface FreeWallActions {
|
||||
update(patch: Partial<FreeWall>): void;
|
||||
remove(): void;
|
||||
/** Bending the wall into an arc (its key is `wall:<id>`). */
|
||||
arc: ArcActions;
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
}
|
||||
|
||||
/** The form of a free-standing wall: length, thickness and height. */
|
||||
export function renderFreeWallForm(host: EditorHost, wall: FreeWall, actions: FreeWallActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const floorHeight = host.floor?.height ?? 2.5;
|
||||
const length = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]);
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("free_wall")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">
|
||||
${numberField(host, t("wall_length"), length, (v) => actions.update({ b: wallEndForLength(wall, v) }), 0.01, 0.1)}
|
||||
${numberField(host, t("wall_thickness"), wall.thickness ?? host.doc.settings.wall_interior, (v) => actions.update({ thickness: between(0.02, 1, v) }), 0.01, 0.02)}
|
||||
${numberField(host, t("wall_height"), wall.height ?? floorHeight, (v) => actions.update(wallHeightPatch(v, floorHeight)), 0.05, 0.05)}
|
||||
${checkField(host, t("free_wall_slope"), wall.height_end != null, (on) => actions.update(on ? { height: wall.height ?? floorHeight, height_end: Math.max(0.2, (wall.height ?? floorHeight) / 2) } : { height_end: null }), { title: t("free_wall_slope_hint") })}
|
||||
${wall.height_end != null ? numberField(host, t("free_wall_height_end"), wall.height_end, (v) => actions.update({ height_end: Math.max(0.05, v) }), 0.05, 0.05) : nothing}
|
||||
</div>
|
||||
${host.admin ? html`<div class="nf-actions">${arcButton(host, `wall:${wall.id}`, actions.arc)}<button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("delete")}</button></div>` : nothing}
|
||||
<div class="nf-form">${arcRow(host, `wall:${wall.id}`, actions.arc)}</div>
|
||||
${hint(t("free_wall_hint"))}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// The form of a parking spot: the presence sensor, the vehicle shown there (also by the state of a type sensor), its size, and the
|
||||
// car's own integration.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber } from "../../../i18n.ts";
|
||||
import { pointInPolygon, type Furniture } from "../../../model.ts";
|
||||
import { packItemLabel, packLabel } from "../../../furniture-names.ts";
|
||||
import { packItem, packType, type FurniturePack } from "../../../packs.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { entityField, hint, numberField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import type { FurnitureLinkActions } from "./furniture-links.ts";
|
||||
|
||||
const PRESENCE = /^(binary_sensor|device_tracker|input_boolean|switch|sensor)\./;
|
||||
const TYPE_SENSOR = /^(sensor|input_select|select|input_text)\./;
|
||||
const CAR_DEVICE = /^(device_tracker|sensor|binary_sensor|lock|climate)\./;
|
||||
|
||||
interface Vehicle {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** The vehicles of the packs, named with their pack. */
|
||||
const vehiclesOf = (packs: readonly FurniturePack[], language: string): Vehicle[] =>
|
||||
packs.flatMap((pack) => pack.items.filter((item) => item.vehicle).map((item) => ({ id: packType(pack.id, item.id), label: `${packItemLabel(item, packType(pack.id, item.id), language)} · ${packLabel(pack, language)}` })));
|
||||
|
||||
/** GPS trackers (a car's own integration, a phone) come before the many network trackers of a router. */
|
||||
function presenceRank(host: EditorHost, id: string): number {
|
||||
if (!id.startsWith("device_tracker.")) return 1;
|
||||
return host.hass?.states[id]?.attributes.source_type === "router" ? 2 : 0;
|
||||
}
|
||||
|
||||
function vehicleSelect(host: EditorHost, vehicles: readonly Vehicle[], value: string | null, onChange: (v: string | null) => void): TemplateResult {
|
||||
return html`<select ?disabled=${!host.admin} @change=${(e: Event) => onChange((e.target as HTMLSelectElement).value || null)}>
|
||||
<option value="" ?selected=${!value}>${host.t("parking_vehicle_none")}</option>
|
||||
${vehicles.map((v) => html`<option value=${v.id} ?selected=${v.id === value}>${v.label}</option>`)}
|
||||
</select>`;
|
||||
}
|
||||
|
||||
/** Which vehicle shows for which state of the type sensor (a car that reports its model, say). */
|
||||
function typeRows(host: EditorHost, spot: Furniture, vehicles: readonly Vehicle[], actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const sensorState = spot.type_entity ? host.hass?.states[spot.type_entity] : undefined;
|
||||
const known = Array.isArray(sensorState?.attributes.options) ? (sensorState.attributes.options as string[]) : [];
|
||||
const rows = spot.types ?? [];
|
||||
const set = (next: { state: string; vehicle: string }[]) => actions.update({ types: next });
|
||||
const edit = (i: number, patch: Partial<{ state: string; vehicle: string }>) => set(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
|
||||
return html`<div class="nf-wide">
|
||||
<div class="nf-sub">${t("parking_types")}</div>
|
||||
${rows.map(
|
||||
(row, i) => html`<div class="nf-parking-row">
|
||||
<input type="text" list="nf-parking-states" placeholder=${t("parking_type_state")} .value=${row.state} ?disabled=${!host.admin} @change=${(e: Event) => edit(i, { state: (e.target as HTMLInputElement).value })} />
|
||||
${vehicleSelect(host, vehicles, row.vehicle, (v) => edit(i, { vehicle: v ?? "" }))}
|
||||
<button class="nf-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => set(rows.filter((_, j) => j !== i))}>✕</button>
|
||||
</div>`,
|
||||
)}
|
||||
<datalist id="nf-parking-states">${known.map((o) => html`<option value=${o}></option>`)}</datalist>
|
||||
${host.admin ? html`<button class="nf-btn" @click=${() => set([...rows, { state: known[rows.length] ?? "", vehicle: vehicles[0]?.id ?? "" }])}>${t("parking_add_type")}</button>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The form of a parking spot. `packs` are the furniture packs, whose vehicles can stand there. */
|
||||
export function parkingForm(host: EditorHost, spot: Furniture, packs: readonly FurniturePack[], actions: FurnitureLinkActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const vehicles = vehiclesOf(packs, host.hass?.language ?? "en");
|
||||
const presence = entityOptions(host.hass, (id) => PRESENCE.test(id)).sort((a, b) => presenceRank(host, a.id) - presenceRank(host, b.id));
|
||||
const typeSensors = entityOptions(host.hass, (id) => TYPE_SENSOR.test(id));
|
||||
const car = spot.car ?? {};
|
||||
// the height of the vehicle against that of the room: a warning when it would not fit
|
||||
const floor = host.floor;
|
||||
const inRoom = floor?.rooms.find((r) => r.points.length >= 3 && pointInPolygon([spot.x, spot.z], r.points));
|
||||
const pack = spot.vehicle ? packItem(spot.vehicle) : undefined;
|
||||
const carHeight = pack ? pack.size[2] * (spot.scale ?? 1) : 0;
|
||||
const tooTall = !!inRoom && !!floor && carHeight > floor.height + 1e-6;
|
||||
return html`<div class="nf-form nf-links">
|
||||
${entityField(host, t("parking_entity"), spot.entity ?? null, undefined, presence, (v) => actions.update({ entity: v === "none" ? null : v }))}
|
||||
<label class="nf-field nf-wide">${t("parking_vehicle")} ${vehicleSelect(host, vehicles, spot.vehicle ?? null, (v) => actions.update({ vehicle: v }))}</label>
|
||||
${vehicles.length > 0 ? nothing : hint(t("parking_no_pack"), "nf-wide")}
|
||||
${numberField(host, t("parking_scale"), Math.round((spot.scale ?? 1) * 100), (v) => actions.update({ scale: Math.min(150, Math.max(30, v)) / 100 }), 5, 30)}
|
||||
${entityField(host, t("parking_type_entity"), spot.type_entity ?? null, undefined, typeSensors, (v) => actions.update({ type_entity: v === "none" ? null : v }))}
|
||||
${spot.type_entity ? typeRows(host, spot, vehicles, actions) : nothing}
|
||||
</div>
|
||||
${tooTall ? html`<p class="nf-sub nf-warn">${t("parking_too_tall", { car: formatNumber(host.hass, carHeight, 2), room: formatNumber(host.hass, floor!.height, 2) })}</p>` : nothing}
|
||||
${hint(t("parking_hint"))}
|
||||
${host.hass
|
||||
? html`${entityField(host, t("live_car_device"), car.device ?? null, null, entityOptions(host.hass, (id) => CAR_DEVICE.test(id)), (v) => actions.update({ car: { ...car, device: v } }))}
|
||||
${hint(t("live_car_device_hint"), "nf-wide")}
|
||||
${entityField(host, t("live_car_departure_entity"), car.departure ?? null, undefined, entityOptions(host.hass, (id) => /^(sensor|input_datetime|time|datetime)\./.test(id)), (v) => actions.update({ car: { ...car, departure: v === "none" ? null : v } }))}`
|
||||
: nothing}`;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// The plan check in the side panel: what is missing or off, floor by floor, each with a button that shows the place or fixes it.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { hint } from "../fields.ts";
|
||||
import { entityName } from "../../../devices.ts";
|
||||
import type { CheckFinding } from "../ops/plan-check.ts";
|
||||
|
||||
export interface PlanCheckActions {
|
||||
fix(finding: CheckFinding): void;
|
||||
/** Stops listing these devices as missing. */
|
||||
ignore(entityIds: string[]): void;
|
||||
/** Lists every ignored device again. */
|
||||
resetIgnored(): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
const ICON: Record<CheckFinding["kind"], string> = {
|
||||
room_no_area: "🏷️",
|
||||
areas_unplaced: "➕",
|
||||
devices_unplaced: "📍",
|
||||
rooms_overlap: "⧉",
|
||||
opening_off_wall: "🚪",
|
||||
entity_missing: "❓",
|
||||
furniture_entity_missing: "❓",
|
||||
standby: "🔌",
|
||||
battery_low: "🪫",
|
||||
};
|
||||
|
||||
/** The text of a finding; a room without an area that has a free area of its name says so. */
|
||||
function textOf(host: EditorHost, f: CheckFinding): string {
|
||||
const key = f.kind === "room_no_area" && f.vars.area ? "check_room_no_area_named" : `check_${f.kind}`;
|
||||
return host.t(key as I18nKey, f.vars);
|
||||
}
|
||||
|
||||
function fixLabel(host: EditorHost, f: CheckFinding): string {
|
||||
const t = host.t;
|
||||
switch (f.fix.do) {
|
||||
case "set_area":
|
||||
return t("check_fix_set_area", { area: String(f.vars.area) });
|
||||
case "add_area_rooms":
|
||||
return t("check_fix_add_rooms");
|
||||
case "place_devices":
|
||||
return t("check_fix_place", { n: f.fix.entityIds.length });
|
||||
case "ignore_devices":
|
||||
return t("check_fix_ignore");
|
||||
case "remove_placements":
|
||||
return t("check_fix_remove", { n: f.fix.entityIds.length });
|
||||
default:
|
||||
return t("check_fix_show");
|
||||
}
|
||||
}
|
||||
|
||||
export function renderPlanCheck(host: EditorHost, findings: readonly CheckFinding[], act: PlanCheckActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const floors = host.doc.floors.filter((fl) => findings.some((f) => f.floorId === fl.id));
|
||||
return html`<section class="nf-check-panel">
|
||||
<div class="nf-h3row"><h3>✓ ${t("check_title")}</h3><button class="nf-btn nf-field-btn" title=${t("close")} @click=${() => act.close()}>✕</button></div>
|
||||
${findings.length === 0
|
||||
? html`<p class="nf-sub nf-check-ok">✅ ${t("check_all_good")}</p>`
|
||||
: html`${hint(t("check_hint", { n: findings.length }))}
|
||||
${floors.map(
|
||||
(fl) => html`<h4 class="nf-check-floor">${fl.name}</h4>
|
||||
<ul class="nf-check-list">
|
||||
${findings
|
||||
.filter((f) => f.floorId === fl.id)
|
||||
.map(
|
||||
(f) => html`<li>
|
||||
<span class="nf-check-icon" aria-hidden="true">${ICON[f.kind]}</span><span class="nf-check-text">${textOf(host, f)}</span>
|
||||
<button class="nf-btn ${f.changes ? "nf-primary" : ""}" ?disabled=${f.changes && !host.admin} @click=${() => act.fix(f)}>${fixLabel(host, f)}</button>
|
||||
${f.entityIds ? names(host, f.entityIds, act) : nothing}
|
||||
</li>`,
|
||||
)}
|
||||
</ul>`,
|
||||
)}`}
|
||||
${(host.doc.settings.check_ignore ?? []).length > 0
|
||||
? html`<p class="nf-sub"><button class="nf-btn" ?disabled=${!host.admin} @click=${() => act.resetIgnored()}>${t("check_reset_ignored", { n: host.doc.settings.check_ignore!.length })}</button></p>`
|
||||
: nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The devices behind a finding, one by one, each with "Ignore" (look first, then place or leave out – #103). */
|
||||
function names(host: EditorHost, ids: string[], act: PlanCheckActions): TemplateResult {
|
||||
const t = host.t;
|
||||
return html`<details class="nf-check-names">
|
||||
<summary>${t("check_show_devices", { n: ids.length })}</summary>
|
||||
<ul>
|
||||
${ids.map((id) => html`<li><span title=${id}>${host.hass ? entityName(host.hass, id) : id}</span> <small>${id}</small>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} @click=${() => act.ignore([id])}>${t("check_fix_ignore")}</button></li>`)}
|
||||
</ul>
|
||||
<button class="nf-btn" ?disabled=${!host.admin} @click=${() => act.ignore(ids)}>${t("check_ignore_all", { n: ids.length })}</button>
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** The button that opens the check, with the number of findings when it was last run. */
|
||||
export const planCheckButton = (host: EditorHost, open: () => void): TemplateResult | typeof nothing =>
|
||||
html`<button class="nf-btn nf-check-open" title=${host.t("check_open_hint")} @click=${open}>✓ ${host.t("check_open")}</button>`;
|
||||
@@ -0,0 +1,49 @@
|
||||
// Pieces the roof and solar forms share: the floor buttons, the lock button, the face names, and rows of exclusive buttons.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { faceCompass, GROUND, type RoofFace } from "../../../solar.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import type { RoofController } from "../roof-controller.ts";
|
||||
|
||||
/** What the roof forms need besides the host and the controller. */
|
||||
export interface RoofPanelDeps {
|
||||
host: EditorHost;
|
||||
roof: RoofController;
|
||||
/** The floor the plan shows. */
|
||||
floorId: string | null;
|
||||
setFloorId(id: string): void;
|
||||
toggleLockPlan(): void;
|
||||
}
|
||||
|
||||
/** One button per floor, top floor first: the plan shows that floor's rooms to draw along. Nothing for a single floor. */
|
||||
export function floorButtons(deps: RoofPanelDeps): TemplateResult | typeof nothing {
|
||||
const floors = deps.roof.floorsTopDown();
|
||||
if (floors.length < 2) return nothing;
|
||||
return html`<div class="nf-seg nf-dev-source">${floors.map((f) => html`<button aria-pressed=${f.id === deps.floorId} @click=${() => deps.setFloorId(f.id)}>${f.name}</button>`)}</div>`;
|
||||
}
|
||||
|
||||
/** The "fix" button of a section, window or field, which keeps it from being moved by accident. */
|
||||
export function lockButton(host: EditorHost, locked: boolean, toggle: () => void): TemplateResult | typeof nothing {
|
||||
if (!host.admin) return nothing;
|
||||
return html`<button class="nf-btn nf-fix" aria-pressed=${locked} title=${host.t("fix_hint")} @click=${toggle}>${locked ? `🔒 ${host.t("unfix")}` : `🔓 ${host.t("fix")}`}</button>`;
|
||||
}
|
||||
|
||||
/** A row of buttons of which one is pressed. */
|
||||
export function choiceButtons<T extends string | boolean>(host: EditorHost, options: readonly (readonly [T, string])[], current: T, pick: (value: T) => void): TemplateResult {
|
||||
return html`<div class="nf-seg nf-dev-source">${options.map(([value, label]) => html`<button aria-pressed=${value === current} ?disabled=${!host.admin} @click=${() => pick(value)}>${label}</button>`)}</div>`;
|
||||
}
|
||||
|
||||
/** "Main roof · south · 35°", "Section 2 · flat roof", "Wall ground floor · east · 6.2 m", or "Free-standing". */
|
||||
export function faceLabel(host: EditorHost, face: RoofFace): string {
|
||||
const { t, doc, hass } = host;
|
||||
const compass = t(`compass_${faceCompass(face, doc.settings.north ?? 0)}` as I18nKey);
|
||||
if (face.key === GROUND) return t("solar_ground");
|
||||
if (face.wall) {
|
||||
const floor = doc.floors.find((f) => f.id === face.wall!.floorId);
|
||||
return `${t("solar_wall")} ${floor?.name ?? ""} · ${compass} · ${formatNumber(hass, face.lu, 1)} m`;
|
||||
}
|
||||
const sections = doc.settings.roof.sections ?? [];
|
||||
const part = face.section ? t("solar_section", { n: sections.findIndex((s) => s.id === face.section) + 1 }) : t("solar_main");
|
||||
return face.flat ? `${part} · ${t("solar_flat")}` : `${part} · ${compass} · ${Math.round(face.pitch)}°`;
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// The roof tool's side panel: the list of sections, one section's form, the roof windows and their form.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { CHIMNEY_SHAPES, ROOF_SHAPES, type ChimneyShape, type RoofChimney, type RoofEnd, type RoofSection, type RoofShape, type RoofWindow } from "../../../model.ts";
|
||||
import { ridgeHeight, sectionFloor } from "../../../roof-sections.ts";
|
||||
import { sectionOverhang } from "../../../roof/geometry.ts";
|
||||
import { chimneySize, proposeChimney, proposeWindow, roofFaces } from "../../../solar.ts";
|
||||
import { entityOptions, isBinary, isNumeric } from "../entities.ts";
|
||||
import { actions, checkField, entityField, hint, numberField, selectField, textField, toThousandths } from "../fields.ts";
|
||||
import { sectionNumber } from "../ops/roof.ts";
|
||||
import { choiceButtons, faceLabel, floorButtons, lockButton, type RoofPanelDeps } from "./roof-parts.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { formatLength } from "../../../units.ts";
|
||||
|
||||
const heading = (title: string, lock: TemplateResult | typeof nothing) => html`<div class="nf-h3row"><h3>${title}</h3>${lock}</div>`;
|
||||
const backButton = (label: string, onClick: () => void) => html`<button class="nf-btn nf-back" @click=${onClick}>‹ ${label}</button>`;
|
||||
const clamped = (low: number, high: number) => (v: number) => Math.max(low, Math.min(high, toThousandths(v)));
|
||||
|
||||
/** One section: shape and direction, eaves, pitch, base, overhang, and the buttons for outline, dormers, copy and delete. */
|
||||
function sectionForm(deps: RoofPanelDeps, section: RoofSection): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<RoofSection>) => roof.patchSection(patch);
|
||||
const flat = section.shape === "flat" || section.shape === "parapet";
|
||||
const pent = section.shape === "pent";
|
||||
// side a is the top when the ridge runs across the plan, and the left when it runs up and down
|
||||
const named = section.axis === "x" ? [t("roof_side_top"), t("roof_side_bottom")] : [t("roof_side_left"), t("roof_side_right")];
|
||||
const [sideA, sideB] = section.flip ? [named[1], named[0]] : named;
|
||||
const planLocked = !!host.doc.settings.lock_plan;
|
||||
const metres = (label: string, value: number, apply: (v: number) => void, step = 0.05, min = 0) => numberField(host, label, value, (v) => apply(Math.max(min, toThousandths(v))), step, min);
|
||||
const floors = [...host.doc.floors].filter((f) => f.rooms.length > 0).sort((a, b) => b.elevation - a.elevation);
|
||||
const onFloor = sectionFloor(host.doc, section)?.id;
|
||||
const moveToFloor = (id: string) => {
|
||||
const floor = host.doc.floors.find((f) => f.id === id);
|
||||
if (!floor) return;
|
||||
// the section moves onto that floor's wall tops: base and eaves shift by the same amount
|
||||
const top = toThousandths(floor.elevation + floor.height);
|
||||
const shift = top - section.base;
|
||||
set({ base: top, eave_a: toThousandths(section.eave_a + shift), eave_b: toThousandths(section.eave_b + shift) });
|
||||
};
|
||||
const lock = planLocked
|
||||
? html`<button class="nf-btn nf-fix" aria-pressed="true" title=${t("lock_plan_hint")} @click=${() => deps.toggleLockPlan()}>🔒 ${t("plan_locked")}</button>`
|
||||
: lockButton(host, !!section.locked, () => set({ locked: !section.locked }));
|
||||
const shapeChoices = ROOF_SHAPES.map((shape): [RoofShape, string] => [shape, t(`roof_shape_${shape}` as I18nKey)]);
|
||||
const dormerButton = (side: "a" | "b", label: string) => html`<button class="nf-btn" title=${t("roof_dormer_hint")} @click=${() => roof.addDormer(side)}>+ ${t("roof_dormer")} ${label}</button>`;
|
||||
return html`${backButton(t("roof_sections"), () => (roof.sectionId = null))}
|
||||
<section>
|
||||
${floorButtons(deps)}
|
||||
${heading(`${section.dormer ? t("roof_dormer") : t("roof_section")} ${sectionNumber(host.doc.settings.roof.sections ?? [], section.id)}`, host.admin ? lock : nothing)}
|
||||
${selectField(host, t("roof_shape"), section.shape, shapeChoices, (shape) => set({ shape, ...(shape === "gable" || shape === "hip" || shape === "halfhip" ? {} : { ends: null }) }), { wide: true })}
|
||||
${section.shape === "gable" || section.shape === "hip" || section.shape === "halfhip" ? endFields(host, section, set) : nothing}
|
||||
${flat ? nothing : choiceButtons(host, [["x", t("roof_axis_x")], ["z", t("roof_axis_z")]] as const, section.axis, (axis) => set({ axis }))}
|
||||
${checkField(host, t("roof_open"), !!section.open, (open) => set({ open }), { title: t("roof_open_hint") })}
|
||||
<div class="nf-form">
|
||||
${flat
|
||||
? metres(t("roof_height"), section.eave_a, (v) => set({ eave_a: v, eave_b: v }))
|
||||
: html`${metres(`${t("roof_eave")} ${pent ? "" : sideA}`, section.eave_a, (v) => set({ eave_a: v }))}
|
||||
${pent ? nothing : metres(`${t("roof_eave")} ${sideB}`, section.eave_b, (v) => set({ eave_b: v }))}
|
||||
${metres(`${t("roof_pitch_short")} ${pent ? "" : sideA}`, section.pitch_a, (v) => set({ pitch_a: Math.min(75, v) }), 1)}
|
||||
${pent ? nothing : metres(`${t("roof_pitch_short")} ${sideB}`, section.pitch_b, (v) => set({ pitch_b: Math.min(75, v) }), 1)}`}
|
||||
${metres(t("roof_base"), section.base, (v) => set({ base: v }))}
|
||||
${section.points?.length ? nothing : numberField(host, t("roof_rotation"), section.rotation ?? 0, (v) => set({ rotation: (((Math.round(v) % 360) + 540) % 360) - 180 || null }), 1)}
|
||||
${selectField(host, t("roof_on_floor"), onFloor ?? "", floors.map((f): [string, string] => [f.id, f.name]), moveToFloor, { title: t("roof_on_floor_hint") })}
|
||||
${hint(t("roof_base_hint"), "nf-wide")}
|
||||
${metres(t("roof_overhang"), section.overhang ?? host.doc.settings.roof.overhang, (v) => set({ overhang: Math.min(2, v) }))}
|
||||
</div>
|
||||
<details class="nf-section" ?open=${!!section.overhang_sides}>
|
||||
<summary>${t("roof_overhang_sides")}</summary>
|
||||
<div class="nf-form">
|
||||
${(["a", "b", "u0", "u1"] as const).map((side) =>
|
||||
metres(t(`roof_overhang_${side}` as I18nKey), sectionOverhang(host.doc, section, section.overhang ?? host.doc.settings.roof.overhang)[side], (v) => set({ overhang_sides: { ...(section.overhang_sides ?? {}), [side]: Math.min(2, Math.max(0, v)) } })),
|
||||
)}
|
||||
${host.admin && section.overhang_sides ? html`<button class="nf-btn" @click=${() => set({ overhang_sides: null })}>${t("roof_overhang_auto")}</button>` : nothing}
|
||||
</div>
|
||||
${hint(t("roof_overhang_sides_hint"))}
|
||||
</details>
|
||||
${flat && host.admin
|
||||
? html`${actions(
|
||||
html`<button class="nf-btn" title=${t("roof_outline_hint")} @click=${() => roof.takeOutline()}>${t("roof_outline")}</button>`,
|
||||
section.points ? html`<button class="nf-btn" @click=${() => set({ points: null })}>${t("roof_rect")}</button>` : nothing,
|
||||
)}
|
||||
${section.points
|
||||
? actions(...section.points.map((_, i) => html`<button class="nf-chip" title=${t("delete_point")} ?disabled=${(section.points?.length ?? 0) <= 3} @click=${() => roof.removeCorner(i)}>${i + 1} ×</button>`))
|
||||
: nothing}
|
||||
${hint(t(section.points ? "roof_points_hint" : "roof_outline_hint"))}`
|
||||
: nothing}
|
||||
${hint(`${t("roof_ridge_height")}: ${formatLength(host.hass, ridgeHeight(section))} · ${t("roof_section_hint")}`)}
|
||||
${host.admin
|
||||
? actions(
|
||||
flat ? nothing : html`<button class="nf-btn" title=${t("roof_swap_hint")} @click=${() => set({ flip: !section.flip })}>⇅ ${t("roof_swap")}</button>`,
|
||||
!flat && !section.dormer && !section.open ? html`${dormerButton("a", sideA)}${pent ? nothing : dormerButton("b", sideB)}` : nothing,
|
||||
html`<button class="nf-btn" @click=${() => roof.duplicateSection()}>${t("duplicate")}</button>`,
|
||||
html`<button class="nf-btn nf-danger" @click=${() => roof.removeSection()}>${t("delete")}</button>`,
|
||||
)
|
||||
: nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** One roof window: its face, size and place, the entities that drive it, and its name. */
|
||||
function windowForm(deps: RoofPanelDeps, win: RoofWindow): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const faces = roofFaces(host.doc);
|
||||
const set = (patch: Partial<RoofWindow>) => roof.patchWindow(patch);
|
||||
const covers = entityOptions(host.hass, (id) => id.startsWith("cover."));
|
||||
const contacts = entityOptions(host.hass, (id) => isBinary(id) || isNumeric(id));
|
||||
const link = (label: I18nKey, value: string | null | undefined, options: typeof covers, key: "cover" | "contact" | "tilt" | "window") =>
|
||||
entityField(host, t(label), value ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v }));
|
||||
const moveToFace = (key: string) => {
|
||||
const next = faces.find((f) => f.key === key);
|
||||
if (next) set({ ...proposeWindow(next, win.id), w: win.w, h: win.h, cover: win.cover, contact: win.contact, tilt: win.tilt, window: win.window, name: win.name });
|
||||
};
|
||||
const index = (host.doc.settings.roof.windows ?? []).findIndex((w) => w.id === win.id) + 1;
|
||||
return html`${backButton(t("roof_sections"), () => (roof.windowId = null))}
|
||||
<section>
|
||||
${heading(`🪟 ${t("roof_window")} ${index}`, lockButton(host, !!win.locked, () => set({ locked: !win.locked })))}
|
||||
<div class="nf-form">
|
||||
${selectField(host, t("solar_face"), win.face, faces.map((f): [string, string] => [f.key, faceLabel(host, f)]), moveToFace, { wide: true })}
|
||||
${numberField(host, t("width"), win.w ?? 0.78, (v) => set({ w: clamped(0.3, 4)(v) }), 0.01, 0.3)}
|
||||
${numberField(host, t("height_m"), win.h ?? 1.18, (v) => set({ h: clamped(0.3, 4)(v) }), 0.01, 0.3)}
|
||||
${numberField(host, t("solar_u"), win.u, (v) => set({ u: toThousandths(v) }), 0.05)} ${numberField(host, t("solar_v"), win.v, (v) => set({ v: toThousandths(v) }), 0.05)}
|
||||
${link("cover_entity", win.cover, covers, "cover")} ${link("contact_entity", win.contact, contacts, "contact")}
|
||||
${link("roof_window_tilt", win.tilt, contacts, "tilt")} ${link("roof_window_motor", win.window, covers, "window")}
|
||||
${textField(host, t("roof_window_name"), win.name ?? "", (v) => set({ name: v || null }), { wide: true, maxlength: 64 })}
|
||||
</div>
|
||||
${hint(t("roof_window_motor_hint"))} ${hint(t("roof_window_hint"))}
|
||||
${host.admin ? actions(html`<button class="nf-btn nf-danger" @click=${() => roof.removeWindow()}>${t("delete")}</button>`) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The roof windows of the house, with a button that adds one. */
|
||||
function windowList(deps: RoofPanelDeps): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const windows = host.doc.settings.roof.windows ?? [];
|
||||
const faces = new Map(roofFaces(host.doc).map((f) => [f.key, f]));
|
||||
const open = (id: string) => {
|
||||
roof.windowId = id;
|
||||
roof.sectionId = null;
|
||||
};
|
||||
return html`<section>
|
||||
<h3>🪟 ${host.t("roof_windows")}</h3>
|
||||
${hint(host.t(faces.size > 0 ? "roof_windows_hint" : "solar_no_roof"))}
|
||||
${windows.length > 0
|
||||
? html`<div class="nf-room-list">
|
||||
${windows.map((w, i) => {
|
||||
const face = faces.get(w.face);
|
||||
return html`<div class="nf-row"><button class="nf-dev-name" @click=${() => open(w.id)}><span>${host.t("roof_window")} ${i + 1} · ${face ? faceLabel(host, face) : host.t("solar_face_gone")}</span></button></div>`;
|
||||
})}
|
||||
</div>`
|
||||
: nothing}
|
||||
${actions(html`<button class="nf-btn" ?disabled=${!host.admin || faces.size === 0} @click=${() => roof.addWindow()}>+ ${host.t("roof_window")}</button>`)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** One chimney: its face, shape, size and place, and its name. */
|
||||
function chimneyForm(deps: RoofPanelDeps, c: RoofChimney): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const faces = roofFaces(host.doc);
|
||||
const set = (patch: Partial<RoofChimney>) => roof.patchChimney(patch);
|
||||
const size = chimneySize(c);
|
||||
const moveToFace = (key: string) => {
|
||||
const next = faces.find((f) => f.key === key);
|
||||
if (next) set({ ...proposeChimney(next, c.id), shape: c.shape, w: c.w, d: c.d, h: c.h, name: c.name });
|
||||
};
|
||||
const round = size.shape === "round" || size.shape === "steel";
|
||||
const index = (host.doc.settings.roof.chimneys ?? []).findIndex((x) => x.id === c.id) + 1;
|
||||
return html`${backButton(t("roof_sections"), () => (roof.chimneyId = null))}
|
||||
<section>
|
||||
${heading(`🧱 ${t("chimney")} ${index}`, lockButton(host, !!c.locked, () => set({ locked: !c.locked })))}
|
||||
<div class="nf-form">
|
||||
${selectField(host, t("chimney_shape"), size.shape, CHIMNEY_SHAPES.map((s): [ChimneyShape, string] => [s, t(`chimney_${s}` as I18nKey)]), (shape) => set({ shape, w: null, d: null, h: null }), { wide: true })}
|
||||
${selectField(host, t("solar_face"), c.face, faces.map((f): [string, string] => [f.key, faceLabel(host, f)]), moveToFace, { wide: true })}
|
||||
${round
|
||||
? numberField(host, t("chimney_diameter"), size.w, (v) => set({ w: clamped(0.1, 3)(v), d: clamped(0.1, 3)(v) }), 0.01, 0.1)
|
||||
: html`${numberField(host, t("width"), size.w, (v) => set({ w: clamped(0.1, 3)(v) }), 0.01, 0.1)} ${numberField(host, t("chimney_depth"), size.d, (v) => set({ d: clamped(0.1, 3)(v) }), 0.01, 0.1)}`}
|
||||
${numberField(host, t("chimney_height"), size.h, (v) => set({ h: clamped(0.2, 5)(v) }), 0.05, 0.2)}
|
||||
${numberField(host, t("solar_u"), c.u, (v) => set({ u: toThousandths(v) }), 0.05)} ${numberField(host, t("solar_v"), c.v, (v) => set({ v: toThousandths(v) }), 0.05)}
|
||||
${textField(host, t("roof_window_name"), c.name ?? "", (v) => set({ name: v || null }), { wide: true, maxlength: 64 })}
|
||||
</div>
|
||||
${hint(t("chimney_hint"))}
|
||||
${host.admin ? actions(html`<button class="nf-btn nf-danger" @click=${() => roof.removeChimney()}>${t("delete")}</button>`) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The chimneys of the house, with a button that adds one. */
|
||||
function chimneyList(deps: RoofPanelDeps): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const chimneys = host.doc.settings.roof.chimneys ?? [];
|
||||
const faces = new Map(roofFaces(host.doc).map((f) => [f.key, f]));
|
||||
const open = (id: string) => {
|
||||
roof.chimneyId = id;
|
||||
roof.sectionId = null;
|
||||
};
|
||||
return html`<section>
|
||||
<h3>🧱 ${host.t("chimneys")}</h3>
|
||||
${faces.size > 0 ? nothing : hint(host.t("solar_no_roof"))}
|
||||
${chimneys.length > 0
|
||||
? html`<div class="nf-room-list">
|
||||
${chimneys.map((c, i) => {
|
||||
const face = faces.get(c.face);
|
||||
return html`<div class="nf-row"><button class="nf-dev-name" @click=${() => open(c.id)}><span>${host.t("chimney")} ${i + 1} · ${host.t(`chimney_${chimneySize(c).shape}` as I18nKey)} · ${face ? faceLabel(host, face) : host.t("solar_face_gone")}</span></button></div>`;
|
||||
})}
|
||||
</div>`
|
||||
: nothing}
|
||||
${actions(html`<button class="nf-btn" ?disabled=${!host.admin || faces.size === 0} @click=${() => roof.addChimney()}>+ ${host.t("chimney")}</button>`)}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The roof tool's panel: a window's form, a section's form, or the overview of all sections and windows. */
|
||||
/** A gable, hip or half-hip section with its own shape at each end of the ridge. */
|
||||
function endFields(host: EditorHost, section: RoofSection, set: (patch: Partial<RoofSection>) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const own = section.shape as RoofEnd;
|
||||
const [start, end] = section.ends ?? [own, own];
|
||||
const choices: [RoofEnd, string][] = (["gable", "hip", "halfhip"] as const).map((e) => [e, t(`roof_shape_${e}` as I18nKey)]);
|
||||
const choose = (pair: [RoofEnd, RoofEnd]) => set({ ends: pair[0] === own && pair[1] === own ? null : pair });
|
||||
const halfhip = start === "halfhip" || end === "halfhip";
|
||||
return html`<div class="nf-form">
|
||||
${selectField(host, t("roof_end_start"), start, choices, (v) => choose([v, end]))}
|
||||
${selectField(host, t("roof_end_end"), end, choices, (v) => choose([start, v]))}
|
||||
${halfhip
|
||||
? html`<label class="nf-field nf-wide" title=${t("roof_halfhip_hint")}
|
||||
>${t("roof_halfhip")} · ${Math.round((section.halfhip ?? 0.55) * 100)} %
|
||||
<input type="range" min="20" max="90" step="5" .value=${String(Math.round((section.halfhip ?? 0.55) * 100))} ?disabled=${!host.admin} @change=${(e: Event) => set({ halfhip: Number((e.target as HTMLInputElement).value) / 100 })} />
|
||||
</label>`
|
||||
: nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function renderRoofPanel(deps: RoofPanelDeps): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const settings = host.doc.settings.roof;
|
||||
const custom = settings.type === "custom";
|
||||
if (roof.window) return windowForm(deps, roof.window);
|
||||
if (roof.chimney) return chimneyForm(deps, roof.chimney);
|
||||
if (custom && roof.section) return sectionForm(deps, roof.section);
|
||||
const sections = custom ? (settings.sections ?? []) : [];
|
||||
const t = host.t;
|
||||
const label = (s: RoofSection, i: number) =>
|
||||
`${i + 1} · ${s.dormer ? t("roof_dormer") : t(`roof_shape_${s.shape}` as I18nKey)} · ${formatNumber(host.hass, Math.abs(s.x1 - s.x0), 1)} × ${formatNumber(host.hass, Math.abs(s.z1 - s.z0), 1)} m · ${t("roof_ridge_height")} ${formatNumber(host.hass, ridgeHeight(s), 1)} m`;
|
||||
return html`<section>
|
||||
${floorButtons(deps)}
|
||||
<h3>${t("roof_sections")}</h3>
|
||||
${hint(t("roof_sections_hint"))}
|
||||
${custom
|
||||
? html`<div class="nf-room-list">${sections.map((s, i) => html`<div class="nf-row"><button class="nf-dev-name" @click=${() => (roof.sectionId = s.id)}><span>${label(s, i)}</span></button></div>`)}</div>
|
||||
${actions(
|
||||
html`<button class="nf-btn" ?disabled=${!host.admin} @click=${() => roof.useSections(true)}>${t("roof_sections_regen")}</button>`,
|
||||
html`<button class="nf-btn" ?disabled=${!host.admin} @click=${() => host.change((doc) => (doc.settings.roof.type = "gable"))}>${t("roof_sections_off")}</button>`,
|
||||
)}`
|
||||
: actions(html`<button class="nf-btn nf-primary" ?disabled=${!host.admin} @click=${() => roof.useSections()}>${t("roof_sections_start")}</button>`)}
|
||||
</section>
|
||||
${windowList(deps)} ${chimneyList(deps)}`;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// The side panel's room part: the list of rooms, and the form of one room with its corners, packages and spot grid.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { bounds, DEFAULT_PAINT_INSIDE, FLOOR_MATERIALS, isAxisRect, polygonArea, type Floor, type FurnitureType, type Room } from "../../../model.ts";
|
||||
import { PACKAGES, type PackageId } from "../../../packages.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import type { RectField } from "../ops/rooms.ts";
|
||||
import { SPOT_TYPES, spotCount, spotItems } from "../ops/spots.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
import { formatArea, formatLength } from "../../../units.ts";
|
||||
import { generateWalls, innerSize, type Wall } from "../../../geometry/walls.ts";
|
||||
import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts";
|
||||
import { roomSpeaker } from "../../../live/announce.ts";
|
||||
|
||||
/** What the room form makes the editor do, and the parts of it that the editor still draws itself. */
|
||||
export interface RoomActions {
|
||||
select(roomId: string): void;
|
||||
patch(patch: Partial<Room>): void;
|
||||
setArea(areaId: string): void;
|
||||
setRect(field: RectField, value: number): void;
|
||||
setCorner(index: number, axis: 0 | 1, value: number): void;
|
||||
removeCorner(index: number): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
rememberView(): void;
|
||||
applyPackage(pkg: PackageId): void;
|
||||
openSpots(): void;
|
||||
placeSpots(): void;
|
||||
/** The lock button of the room (it shows the lock on the whole plan). */
|
||||
lockButton: TemplateResult | typeof nothing;
|
||||
/** The editor's own sections of the form: heights of the walls, and the climate sensors. */
|
||||
wallHeights: TemplateResult | typeof nothing;
|
||||
climate: TemplateResult | typeof nothing;
|
||||
/** The selected corner of this room, if any. */
|
||||
corner: number | null;
|
||||
}
|
||||
|
||||
/** All rooms of the floor with their size, to pick one. */
|
||||
export function renderRoomList(host: EditorHost, floor: Floor, actions: Pick<RoomActions, "select">): TemplateResult | typeof nothing {
|
||||
if (floor.rooms.length === 0) return nothing;
|
||||
return html`<section>
|
||||
<h3>${host.t("rooms")}</h3>
|
||||
<div class="nf-room-list">
|
||||
${floor.rooms.map(
|
||||
(room) => html`<button class="nf-row" @click=${() => actions.select(room.id)}>
|
||||
<span>${room.name}</span><span class="nf-muted">${formatArea(host.hass, polygonArea(room.points))}</span>
|
||||
</button>`,
|
||||
)}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The planning form of a spot grid: type, columns, rows, the light to follow, and how many spots that makes. */
|
||||
function spotForm(host: EditorHost, state: SideState, room: Room, actions: RoomActions): TemplateResult {
|
||||
const draft = state.spots!;
|
||||
const change = (patch: Partial<typeof draft>) => (state.spots = { ...draft, ...patch });
|
||||
const count = spotItems(room, draft).length;
|
||||
const lights = entityOptions(host.hass, (id) => /^(light|switch|input_boolean)\./.test(id));
|
||||
const types = SPOT_TYPES.map((type): [FurnitureType, string] => [type, host.t(`furn_${type}` as I18nKey)]);
|
||||
return html`<div class="nf-form nf-spot-form">
|
||||
${selectField(host, host.t("spots_type"), draft.type, types, (type) => change({ type }), { wide: true })}
|
||||
${numberField(host, host.t("spots_cols"), draft.cols, (v) => change({ cols: spotCount(v) }), 1, 1)}
|
||||
${numberField(host, host.t("spots_rows"), draft.rows, (v) => change({ rows: spotCount(v) }), 1, 1)}
|
||||
${entityField(host, host.t("furn_entity_light"), draft.entity, undefined, lights, (v) => change({ entity: v === "none" ? null : v }))}
|
||||
<div class="nf-actions nf-wide">
|
||||
<button class="nf-btn nf-primary" ?disabled=${count === 0} @click=${() => actions.placeSpots()}>${host.t("spots_add", { n: count })}</button>
|
||||
<button class="nf-btn" @click=${() => (state.spots = null)}>${host.t("cancel")}</button>
|
||||
</div>
|
||||
${hint(host.t("spots_hint"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The corners of a room as number pairs. They are unfolded when the room is no rectangle, so the shape can be typed in. */
|
||||
function corners(host: EditorHost, room: Room, rectangle: boolean, actions: RoomActions): TemplateResult {
|
||||
return html`<details class="nf-points" ?open=${!rectangle}>
|
||||
<summary>${host.t("points")} (${room.points.length})</summary>
|
||||
${room.points.map(
|
||||
(point, i) => html`<div class="nf-point ${i === actions.corner ? "nf-point-sel" : ""}">
|
||||
<span class="nf-muted">${i + 1}</span>
|
||||
${numberField(host, host.t("x"), point[0], (v) => actions.setCorner(i, 0, v))} ${numberField(host, host.t("z"), point[1], (v) => actions.setCorner(i, 1, v))}
|
||||
${host.admin ? html`<button class="nf-btn" title=${host.t("delete_point")} ?disabled=${room.points.length <= 3} @click=${() => actions.removeCorner(i)}>×</button>` : nothing}
|
||||
</div>`,
|
||||
)}
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** The room's living area (counted like the Wohnflächenverordnung), with its floor area when part of it lies under a slope. */
|
||||
function livingLine(host: EditorHost, room: Room, walls: readonly Wall[]): TemplateResult | typeof nothing {
|
||||
const floor = host.floor;
|
||||
// only this room: the form draws again on every step of a drag
|
||||
const a = floor ? roomArea(host.doc, floor, room, walls) : undefined;
|
||||
if (!a || a.floor <= 0) return nothing;
|
||||
const t = host.t;
|
||||
if (!countsAsLiving(room)) return html`<p class="nf-sub nf-wide">${t("living_area_none", { floor: formatArea(host.hass, a.floor) })}</p>`;
|
||||
return html`<p class="nf-sub nf-wide" title=${t("living_area_hint")}>
|
||||
${a.low > 0.05
|
||||
? t("living_area_low", { living: formatArea(host.hass, a.living), floor: formatArea(host.hass, a.floor), low: formatArea(host.hass, a.low) })
|
||||
: t("living_area", { living: formatArea(host.hass, a.living) })}
|
||||
</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The room's own ceiling height: a low bathroom on a high floor, or a living room open to the floor above (#55) – its walls rise
|
||||
* with it and the floor above stays open over it. At the floor height it is the floor's again.
|
||||
*/
|
||||
function ceilingField(host: EditorHost, room: Room, floor: Floor, actions: RoomActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const set = (v: number) => actions.patch({ ceiling: Math.abs(v - floor.height) < 0.005 ? null : Math.min(20, Math.max(1, Math.round(v * 1000) / 1000)) });
|
||||
return html`${numberField(host, t("room_ceiling"), room.ceiling ?? floor.height, set, 0.01, 1)}
|
||||
${room.ceiling != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.patch({ ceiling: null })}>${t("height_auto")}</button>` : nothing}
|
||||
${hint(t("room_ceiling_tip"), "nf-wide")}
|
||||
${room.ceiling != null && room.ceiling > floor.height + 0.005
|
||||
? html`<p class="nf-sub nf-wide">${t("room_ceiling_through", { ceiling: formatNumber(host.hass, room.ceiling, 2), floor: formatNumber(host.hass, floor.height, 2) })}</p>`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** Announcements in the room: its speaker (automatic, chosen, or none) and a quiet time. */
|
||||
function announceFields(host: EditorHost, room: Room, floor: Floor | null, actions: RoomActions): TemplateResult {
|
||||
const t = host.t;
|
||||
if (!host.hass) return html``;
|
||||
const auto = roomSpeaker(host.hass, floor, { ...room, announce_speaker: null });
|
||||
const speakers = entityOptions(host.hass, (id) => /^(media_player|assist_satellite)\./.test(id) || (id.startsWith("notify.") && id.endsWith("_announce")));
|
||||
const quiet = room.announce_quiet ?? null;
|
||||
// the first time typed fills the other with the usual night (20:00–07:00), so a half quiet time is never stored
|
||||
const setQuiet = (part: "from" | "to", value: string) => {
|
||||
if (!value) return actions.patch({ announce_quiet: null });
|
||||
actions.patch({ announce_quiet: { from: quiet?.from ?? "20:00", to: quiet?.to ?? "07:00", [part]: value } });
|
||||
};
|
||||
return html`${entityField(host, t("room_announce_speaker"), room.announce_speaker ?? null, auto, speakers, (v) => actions.patch({ announce_speaker: v }))}
|
||||
<div class="nf-field nf-wide nf-quiet-time">
|
||||
${t("room_announce_quiet")}
|
||||
<span>
|
||||
<input type="time" .value=${quiet?.from ?? ""} ?disabled=${!host.admin} aria-label=${`${t("room_announce_quiet")} 1`} @change=${(e: Event) => setQuiet("from", (e.target as HTMLInputElement).value)} />
|
||||
–
|
||||
<input type="time" .value=${quiet?.to ?? ""} ?disabled=${!host.admin} aria-label=${`${t("room_announce_quiet")} 2`} @change=${(e: Event) => setQuiet("to", (e.target as HTMLInputElement).value)} />
|
||||
${quiet ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.patch({ announce_quiet: null })}>×</button>` : nothing}
|
||||
</span>
|
||||
</div>
|
||||
${hint(t("room_announce_hint"), "nf-wide")}`;
|
||||
}
|
||||
|
||||
/** The form of the selected room. */
|
||||
export function renderRoomForm(host: EditorHost, state: SideState, room: Room, actions: RoomActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const rectangle = isAxisRect(room.points);
|
||||
const box = bounds(room.points);
|
||||
const areas = Object.values(host.hass?.areas ?? {}).sort((a, b) => a.name.localeCompare(b.name));
|
||||
const areaChoices: [string, string][] = [["", t("no_area")], ...areas.map((a): [string, string] => [a.area_id, a.name])];
|
||||
// from wall face to wall face (the outline runs along the middle of inner walls)
|
||||
const walls = host.floor ? generateWalls(host.floor.rooms, { exterior: host.doc.settings.wall_exterior, interior: host.doc.settings.wall_interior }, host.floor.walls ?? []).walls : [];
|
||||
const inner = host.floor ? innerSize(room, walls) : null;
|
||||
const materials = FLOOR_MATERIALS.map((m): [string, string] => [m, t(`mat_${m}` as I18nKey)]);
|
||||
const packageButton = (pkg: PackageId) =>
|
||||
html`<button class="nf-btn" @click=${() => actions.applyPackage(pkg)}><b>${t(`pkg_${pkg}` as I18nKey)}</b><span>${t(`pkg_${pkg}_desc` as I18nKey)}</span></button>`;
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("room")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">
|
||||
${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })}
|
||||
${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
|
||||
${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)}
|
||||
${room.area_id
|
||||
? selectField(host, t("sub_area_add"), "", areaChoices.filter(([id]) => id !== room.area_id && !(room.sub_areas ?? []).includes(id)), (id) => id && actions.patch({ sub_areas: [...(room.sub_areas ?? []), id] }), { wide: true, title: t("sub_area_hint") })
|
||||
: nothing}
|
||||
${selectField(host, t("material"), room.floor_material, materials, (floor_material) => actions.patch({ floor_material }), { wide: true })}
|
||||
${colorField(host, t("wall_paint_room"), room.wall_paint, host.doc.settings.wall_paint_inside ?? DEFAULT_PAINT_INSIDE, (wall_paint) => actions.patch({ wall_paint }))}
|
||||
${host.floor ? ceilingField(host, room, host.floor, actions) : nothing}
|
||||
${numberField(host, t("room_floor_offset"), room.floor_offset ?? 0, (v) => actions.patch({ floor_offset: Math.abs(v) < 0.005 ? null : Math.max(-2, Math.min(2, Math.round(v * 1000) / 1000)) }), 0.01)}
|
||||
${hint(t("room_floor_offset_hint"), "nf-wide")}
|
||||
${entityField(host, t("room_clean"), room.clean_entity ?? null, undefined, entityOptions(host.hass, (id) => /^(script|button|input_button)\./.test(id)), (v) => actions.patch({ clean_entity: v && v !== "none" ? v : null }))}
|
||||
${room.clean_entity ? nothing : hint(t("room_clean_hint"), "nf-wide")}
|
||||
${entityField(host, t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => /^(climate|switch|valve|binary_sensor|input_boolean)\./.test(id)), (v) => actions.patch({ floor_heating: v && v !== "none" ? v : null }))}
|
||||
${room.floor_heating ? hint(t("floor_heating_hint"), "nf-wide") : nothing}
|
||||
${announceFields(host, room, host.floor ?? null, actions)}
|
||||
${inner ? html`<p class="nf-sub nf-wide" title=${t("room_inner_hint")}>${t("room_inner", { w: formatLength(host.hass, inner[0]), d: formatLength(host.hass, inner[1]) })}</p>` : nothing}
|
||||
${livingLine(host, room, walls)}
|
||||
${checkField(host, t("room_living"), countsAsLiving(room), (on) => actions.patch({ living: on === countsAsLiving({ name: room.name, living: null }) ? null : on }), { title: t("living_area_hint") })}
|
||||
${rectangle
|
||||
? html`${numberField(host, t("x"), box.x0, (v) => actions.setRect("x", v))} ${numberField(host, t("z"), box.z0, (v) => actions.setRect("z", v))}
|
||||
${numberField(host, t("width"), box.x1 - box.x0, (v) => actions.setRect("w", v), 0.01, 0.05)}
|
||||
${numberField(host, t("depth"), box.z1 - box.z0, (v) => actions.setRect("d", v), 0.01, 0.05)}`
|
||||
: nothing}
|
||||
</div>
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn" title=${t("room_start_view_hint")} ?disabled=${!host.admin} @click=${() => actions.rememberView()}>${t("room_start_view")}</button>
|
||||
${room.start_view ? html`<button class="nf-btn" title=${t("room_start_view_reset")} ?disabled=${!host.admin} @click=${() => actions.patch({ start_view: null })}>↺</button>` : nothing}
|
||||
</div>
|
||||
${actions.wallHeights} ${actions.climate} ${corners(host, room, rectangle, actions)}
|
||||
${host.admin
|
||||
? html`<div class="nf-actions">
|
||||
<button class="nf-btn nf-primary" @click=${() => (state.packages = !state.packages)}>${t("pkg_open")}</button>
|
||||
<button class="nf-btn" @click=${() => actions.openSpots()}>${t("spots_place")}</button>
|
||||
<button class="nf-btn" @click=${() => actions.duplicate()}>${t("duplicate")}</button>
|
||||
<button class="nf-btn nf-danger" @click=${() => actions.remove()}>${t("delete")}</button>
|
||||
</div>`
|
||||
: nothing}
|
||||
${state.spots ? spotForm(host, state, room, actions) : nothing}
|
||||
${state.packages ? html`<div class="nf-packages">${PACKAGES.map(packageButton)}${hint(t("pkg_hint"))}</div>` : nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { weatherEntity } from "../../../weather.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { DEFAULT_PAINT_INSIDE, DEFAULT_PAINT_OUTSIDE, DEFAULT_WEATHER_EFFECTS, WEATHER_EFFECTS, type Building, type RoofType } from "../../../model.ts";
|
||||
import { entityName } from "../../../devices.ts";
|
||||
import { FURNITURE_ROLES, STOCK_ROLE_HEX } from "../../../furniture-colors.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { renderCompass } from "./compass.ts";
|
||||
import { renderMapSettings } from "./map.ts";
|
||||
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { clamp, withEffect } from "../ops/settings.ts";
|
||||
|
||||
/** What choosing the "own sections" roof needs from the editor: it proposes sections from the rooms and opens the roof tool. */
|
||||
export interface SettingsActions {
|
||||
useRoofSections(): void;
|
||||
}
|
||||
|
||||
const ROOF_TYPES = ["none", "flat", "gable", "custom"] as const;
|
||||
|
||||
type Backdrop = NonNullable<Building["settings"]["backdrop"]>;
|
||||
|
||||
/** An own background behind the house: on or off, a colour, a picture and how much it is dimmed. */
|
||||
function backdropFields(host: EditorHost, b: Backdrop | null, onChange: (b: Backdrop | null) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const on = !!b;
|
||||
const patch = (p: Partial<Backdrop>) => onChange({ color: null, image: null, dim: 0.35, ...(b ?? {}), ...p });
|
||||
return html`<div class="nf-sub nf-wide">${t("backdrop")}</div>
|
||||
${checkField(host, t("backdrop"), on, (v) => onChange(v ? { color: "#101828", image: null, dim: 0.35 } : null))}
|
||||
${on
|
||||
? html`<label class="nf-field"
|
||||
>${t("backdrop_color")}
|
||||
<input type="color" .value=${b?.color ?? "#101828"} ?disabled=${!host.admin} @change=${(e: Event) => patch({ color: (e.target as HTMLInputElement).value })}
|
||||
/></label>
|
||||
${numberField(host, t("backdrop_dim"), Math.round((b?.dim ?? 0.35) * 100), (v) => patch({ dim: clamp(v, 0, 80) / 100 }), 5, 0)}
|
||||
${textField(host, t("backdrop_image"), b?.image ?? "", (v) => patch({ image: v || null }), { wide: true, placeholder: "/local/hintergrund.jpg" })}
|
||||
${hint(t("backdrop_hint"), "nf-wide")}`
|
||||
: nothing}`;
|
||||
}
|
||||
|
||||
/** Wall thickness, grid, north, roof shape, the weather source and its effects. */
|
||||
/** The plan's own sensors at the top of the 3D view: the chosen ones as chips to remove, and a picker to add one. */
|
||||
function statusFields(host: EditorHost, ids: string[], set: (ids: string[]) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const options = entityOptions(host.hass, (id) => !ids.includes(id) && /^(sensor|binary_sensor|alarm_control_panel|weather|input_|counter|lock|climate|person|sun)\b/.test(id));
|
||||
return html`<div class="nf-sub nf-wide">${t("status_entities")}</div>
|
||||
${ids.length
|
||||
? html`<div class="nf-chips nf-wide">
|
||||
${ids.map(
|
||||
(id) => html`<span class="nf-chip">${entityName(host.hass, id)}
|
||||
${host.admin ? html`<button class="nf-chip-x" title=${t("delete")} aria-label=${`${t("delete")}: ${entityName(host.hass, id)}`} @click=${() => set(ids.filter((x) => x !== id))}>×</button>` : nothing}</span
|
||||
>`,
|
||||
)}
|
||||
</div>`
|
||||
: nothing}
|
||||
${ids.length < 12 ? entityField(host, t("status_add"), null, undefined, options, (v) => v && v !== "none" && set([...ids, v])) : nothing}
|
||||
${hint(t("status_entities_hint"), "nf-wide")}`;
|
||||
}
|
||||
|
||||
export function renderSettings(host: EditorHost, actions: SettingsActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const s = host.doc.settings;
|
||||
const set = (patch: Partial<Building["settings"]>) => host.replace({ ...structuredClone(host.doc), settings: { ...structuredClone(host.doc.settings), ...patch } });
|
||||
const setRoof = (patch: Partial<Building["settings"]["roof"]>) => set({ roof: { ...s.roof, ...patch } });
|
||||
const roofChoices = ROOF_TYPES.map((type): [RoofType, string] => [type, t(`roof_${type}` as I18nKey)]);
|
||||
const current = s.weather_effects ?? DEFAULT_WEATHER_EFFECTS;
|
||||
const gable = s.roof.type === "gable";
|
||||
return html`<details class="nf-section">
|
||||
<summary>${t("settings")}</summary>
|
||||
<div class="nf-form">
|
||||
${numberField(host, t("wall_exterior"), s.wall_exterior, (v) => set({ wall_exterior: clamp(v, 0.02, 1) }), 0.01, 0.02)}
|
||||
${numberField(host, t("wall_interior"), s.wall_interior, (v) => set({ wall_interior: clamp(v, 0.02, 1) }), 0.01, 0.02)}
|
||||
${colorField(host, t("wall_paint_outside"), s.wall_paint_outside, DEFAULT_PAINT_OUTSIDE, (v) => set({ wall_paint_outside: v }))}
|
||||
${colorField(host, t("wall_paint_inside"), s.wall_paint_inside, DEFAULT_PAINT_INSIDE, (v) => set({ wall_paint_inside: v }))}
|
||||
${hint(t("wall_paint_hint"), "nf-wide")}
|
||||
${FURNITURE_ROLES.map((role) =>
|
||||
colorField(host, t(`furn_color_${role}`), s.furniture_colors?.[role], STOCK_ROLE_HEX[role], (v) => {
|
||||
const colors = { ...s.furniture_colors, [role]: v };
|
||||
if (!v) delete colors[role];
|
||||
set({ furniture_colors: Object.keys(colors).length ? colors : null });
|
||||
}),
|
||||
)}
|
||||
${hint(t("furn_color_hint"), "nf-wide")}
|
||||
${numberField(host, t("grid"), s.grid, (v) => set({ grid: clamp(v, 0.01, 1) }), 0.01, 0.01)}
|
||||
${selectField(host, t("units"), s.units === "imperial" ? "imperial" : "metric", [["metric", t("units_metric")], ["imperial", t("units_imperial")]] as const, (v) => set({ units: v === "imperial" ? "imperial" : null }), { title: t("units_hint") })}
|
||||
${renderCompass(host, s.north, (north) => set({ north }))}
|
||||
${renderMapSettings(host, host.doc, (map) => set({ map }))}
|
||||
${selectField(host, t("roof"), s.roof.type, roofChoices, (type) => (type === "custom" ? actions.useRoofSections() : setRoof({ type })), { wide: true })}
|
||||
${gable
|
||||
? selectField(host, t("roof_ridge"), s.roof.ridge === "short" ? "short" : "long", [["long", t("roof_ridge_long")], ["short", t("roof_ridge_short")]], (ridge) => setRoof({ ridge: ridge === "short" ? "short" : null }), { wide: true })
|
||||
: nothing}
|
||||
${gable ? numberField(host, t("roof_pitch"), s.roof.pitch, (v) => setRoof({ pitch: clamp(v, 5, 60) }), 1, 5) : nothing}
|
||||
${s.roof.type !== "none" ? numberField(host, t("roof_overhang"), s.roof.overhang, (v) => setRoof({ overhang: clamp(v, 0, 2) }), 0.05, 0) : nothing}
|
||||
${host.hass ? entityField(host, t("weather_entity"), s.weather_entity ?? null, weatherEntity(host.hass, null), entityOptions(host.hass, (id) => id.startsWith("weather.")), (v) => set({ weather_entity: v })) : nothing}
|
||||
<div class="nf-sub nf-wide">${t("weather_effects")}</div>
|
||||
${WEATHER_EFFECTS.map((effect) => checkField(host, t(`weather_effect_${effect}` as I18nKey), current.includes(effect), (on) => set({ weather_effects: withEffect(current, effect, on) }), { wide: false }))}
|
||||
${checkField(host, t("rain_warning"), s.rain_warning !== false, (on) => set({ rain_warning: on }))}
|
||||
${host.hass && s.rain_warning !== false
|
||||
? entityField(host, t("rain_sensor"), s.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ rain_sensor: v === "none" ? null : v }))
|
||||
: nothing}
|
||||
${host.hass && s.rain_warning !== false && s.rain_sensor && s.rain_sensor !== "none" ? checkField(host, t("rain_sensor_inverted"), !!s.rain_sensor_inverted, (on) => set({ rain_sensor_inverted: on || undefined }), { title: t("rain_sensor_inverted_hint") }) : nothing}
|
||||
${host.hass ? entityField(host, t("outage_sensor"), s.outage_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ outage_sensor: v === "none" ? null : v })) : nothing}
|
||||
${hint(t("outage_hint"), "nf-wide")}
|
||||
${checkField(host, t("contact_warning"), !!s.contact_warning, (on) => set({ contact_warning: on || undefined }), { title: t("contact_warning_hint") })}
|
||||
${checkField(host, t("night_lock_warning"), !!s.night_lock_warning, (on) => set({ night_lock_warning: on || undefined }), { title: t("night_lock_warning_hint") })}
|
||||
${selectField(host, t("room_double_tap"), s.room_double_tap ?? "area", [["area", t("room_double_tap_area")], ["plan", t("room_double_tap_plan")], ["off", t("room_double_tap_off")]] as const, (v) => set({ room_double_tap: v === "plan" || v === "off" ? v : null }), { title: t("room_double_tap_hint") })}
|
||||
${checkField(host, t("motion_markers_active"), !!s.motion_markers_active, (on) => set({ motion_markers_active: on || undefined }), { title: t("motion_markers_active_hint") })}
|
||||
${host.hass ? statusFields(host, s.status_entities ?? [], (status_entities) => set({ status_entities: status_entities.length ? status_entities : null })) : nothing}
|
||||
${host.hass ? entityField(host, t("announce_tts"), s.announce_tts ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("tts.")), (v) => set({ announce_tts: v === "none" ? null : v })) : nothing}
|
||||
<label class="nf-field nf-wide"
|
||||
>${t("announce_phrases")}
|
||||
<textarea
|
||||
rows="4"
|
||||
?disabled=${!host.admin}
|
||||
.value=${(s.announce_phrases ?? []).join("\n")}
|
||||
placeholder=${[1, 2, 3, 4, 5].map((n) => t(`announce_phrase_${n}` as I18nKey)).join("\n")}
|
||||
@change=${(e: Event) => {
|
||||
const lines = (e.target as HTMLTextAreaElement).value.split("\n").map((l) => l.trim().slice(0, 200)).filter(Boolean).slice(0, 30);
|
||||
set({ announce_phrases: lines.length ? lines : null });
|
||||
}}
|
||||
></textarea>
|
||||
</label>
|
||||
${hint(t("announce_phrases_hint"), "nf-wide")}
|
||||
${checkField(host, t("sun_patches"), s.sun_patches !== false, (on) => set({ sun_patches: on }), { title: t("sun_patches_hint") })}
|
||||
${checkField(host, t("sun_arc"), s.sun_arc === true, (on) => set({ sun_arc: on }), { title: t("sun_arc_hint") })}
|
||||
${backdropFields(host, s.backdrop ?? null, (backdrop) => set({ backdrop }))}
|
||||
</div>
|
||||
${hint(`${t("north_hint")} ${t("weather_entity_hint")}`)}
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// The side panel for solar fields: the overview with the strings, and the form of one field.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { entityName, furnitureEntities } from "../../../devices.ts";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import type { SolarField } from "../../../model.ts";
|
||||
import { fieldFace, fieldModules, GROUND, proposeField, roofFaces, rowCounts, turnGroundField, wallFaces } from "../../../solar.ts";
|
||||
import { entityOptions, isPowerSensor } from "../entities.ts";
|
||||
import { actions, checkField, entityField, hint, numberField, selectField, textField, toThousandths } from "../fields.ts";
|
||||
import { columnsPatch, columnsText, fieldOnFace, rowsPatch } from "../ops/solar.ts";
|
||||
import { choiceButtons, faceLabel, floorButtons, lockButton, type RoofPanelDeps } from "./roof-parts.ts";
|
||||
|
||||
const DEFAULT_WP = 400;
|
||||
|
||||
/** Number of modules and peak power of a field, as the summary line writes them. */
|
||||
function fieldYield(face: ReturnType<typeof fieldFace> | undefined, field: SolarField) {
|
||||
const modules = face ? fieldModules(face, field).length : 0;
|
||||
return { modules, kwp: (modules * (field.wp ?? DEFAULT_WP)) / 1000 };
|
||||
}
|
||||
|
||||
/** The solar fields of the house with their strings, and buttons to add a field on a roof, on the ground, or on a wall. */
|
||||
export function renderSolarList(deps: RoofPanelDeps): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const fields = host.doc.settings.roof.solar ?? [];
|
||||
const strings = host.doc.settings.roof.strings ?? [];
|
||||
const roofFaceList = roofFaces(host.doc);
|
||||
const faceOf = new Map(fields.map((f) => [f.id, fieldFace(host.doc, f, roofFaceList)] as const));
|
||||
const row = (field: SolarField, i: number) => {
|
||||
const face = faceOf.get(field.id);
|
||||
const sum = fieldYield(face, field);
|
||||
const summary = t("solar_summary", { n: sum.modules, kwp: formatNumber(host.hass, sum.kwp, 1) });
|
||||
return html`<div class="nf-row">
|
||||
<button class="nf-dev-name" @click=${() => roof.selectField(field.id)}>
|
||||
<span>${field.name || `${t("solar_field")} ${i + 1}`} · ${face ? faceLabel(host, face) : t("solar_face_gone")} · ${summary}</span>
|
||||
</button>
|
||||
</div>`;
|
||||
};
|
||||
const stringLine = (s: (typeof strings)[number]) => {
|
||||
const own = fields.filter((f) => f.string === s.id);
|
||||
const sums = own.map((f) => fieldYield(faceOf.get(f.id), f));
|
||||
const modules = sums.reduce((a, x) => a + x.modules, 0);
|
||||
const kwp = sums.reduce((a, x) => a + x.kwp, 0);
|
||||
return html`<p class="nf-sub">🔗 <b>${s.name}</b> · ${t("solar_string_sum", { fields: own.length, n: modules, kwp: formatNumber(host.hass, kwp, 1) })}</p>`;
|
||||
};
|
||||
return html`<section>
|
||||
${floorButtons(deps)}
|
||||
<h3>☀ ${t("solar_fields")}</h3>
|
||||
${hint(t(roofFaceList.length > 0 ? "solar_hint" : "solar_no_roof"))}
|
||||
${fields.length > 0 ? html`<div class="nf-room-list">${fields.map(row)}</div>` : nothing}
|
||||
${actions(
|
||||
html`<button class="nf-btn nf-primary" ?disabled=${!host.admin || roofFaceList.length === 0} @click=${() => roof.addField()}>+ ${t("solar_add")}</button>`,
|
||||
html`<button class="nf-btn" ?disabled=${!host.admin} @click=${() => roof.addGroundField()}>+ ${t("solar_add_ground")}</button>`,
|
||||
html`<button class="nf-btn" ?disabled=${!host.admin || !deps.floorId} @click=${() => roof.addWallField()}>+ ${t("solar_add_wall")}</button>`,
|
||||
)}
|
||||
${strings.length > 0 ? html`<h4 class="nf-lib-head">${t("solar_strings")}</h4>${strings.map(stringLine)}` : nothing}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** The string a field belongs to: choose, create or leave it, and for a string its name, sensor and inverter. */
|
||||
function stringSection(deps: RoofPanelDeps, field: SolarField): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const power = entityOptions(host.hass, (id) => isPowerSensor(host.hass, id));
|
||||
const strings = host.doc.settings.roof.strings ?? [];
|
||||
const current = strings.find((s) => s.id === field.string);
|
||||
const choices: [string, string][] = [["", t("solar_string_none")], ...strings.map((s): [string, string] => [s.id, s.name]), ["new", `+ ${t("solar_string_new")}`]];
|
||||
const picker = selectField(host, t("solar_string"), field.string ?? "", choices, (v) => roof.setString(v === "" ? null : v), { wide: true });
|
||||
if (!current) return html`${picker}${entityField(host, t("solar_entity"), field.entity ?? null, undefined, power, (v) => roof.patchField({ entity: v === "none" ? null : v }))}`;
|
||||
// each inverter by its own name, else its entity's name, numbered only as a last resort
|
||||
const linked = host.hass ? furnitureEntities(host.hass, host.doc.floors) : null;
|
||||
const inverters = host.doc.floors
|
||||
.flatMap((floor) => floor.furniture.filter((m) => m.type === "inverter").map((item) => ({ item, floor })))
|
||||
.map(({ item, floor }, i) => {
|
||||
const entity = linked?.get(item.id)?.entity;
|
||||
const own = item.name?.trim() || (entity ? entityName(host.hass, entity) : "");
|
||||
return [item.id, `${own || `${t("furn_inverter")} ${i + 1}`} · ${floor.name}`] as [string, string];
|
||||
});
|
||||
return html`${picker}
|
||||
${textField(host, t("solar_string_name"), current.name, (v) => roof.patchString({ name: v || current.name }), { wide: true })}
|
||||
${entityField(host, t("solar_string_entity"), current.entity ?? null, undefined, power, (v) => roof.patchString({ entity: v === "none" ? null : v }))}
|
||||
${selectField(host, t("solar_string_inverter"), current.inverter ?? "", [["", t(inverters.length > 0 ? "solar_string_inverter_none" : "solar_string_inverter_missing")], ...inverters], (v) => roof.patchString({ inverter: v || null }), { wide: true })}`;
|
||||
}
|
||||
|
||||
/** One solar field: its face, rows and columns, module size, place, tilt, and the string it feeds. */
|
||||
export function renderSolarForm(deps: RoofPanelDeps, field: SolarField): TemplateResult {
|
||||
const { host, roof } = deps;
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<SolarField>) => roof.patchField(patch);
|
||||
const faces = roofFaces(host.doc);
|
||||
const face = fieldFace(host.doc, field, faces);
|
||||
const ground = field.face === GROUND;
|
||||
const rows = rowCounts(field);
|
||||
const sum = fieldYield(face, field);
|
||||
const planned = rows.reduce((a, b) => a + b, 0) - (field.skip?.length ?? 0);
|
||||
const index = (host.doc.settings.roof.solar ?? []).findIndex((f) => f.id === field.id) + 1;
|
||||
const facesChoices: [string, string][] = [
|
||||
...(face ? [] : [["", t("solar_face_gone")] as [string, string]]),
|
||||
...faces.map((f): [string, string] => [f.key, faceLabel(host, f)]),
|
||||
[GROUND, t("solar_ground")],
|
||||
...wallFaces(host.doc).map((f): [string, string] => [f.key, faceLabel(host, f)]),
|
||||
];
|
||||
const moveTo = (key: string) => {
|
||||
const patch = fieldOnFace(host.doc, field, key);
|
||||
if (patch) set(patch);
|
||||
};
|
||||
const bounded = (low: number, high: number, round: (v: number) => number = toThousandths) => (v: number) => Math.max(low, Math.min(high, round(v)));
|
||||
const turnGround = (rotation: number) => set(turnGroundField(host.doc, field, rotation));
|
||||
const turnFlat = (rotation: number) => set({ rotation: ((Math.round(rotation) % 360) + 360) % 360 || null });
|
||||
const flipText = face?.wall ? "solar_flip_wall" : "solar_flip";
|
||||
const moduleSize = (key: "module_w" | "module_h", label: I18nKey, fallback: number) => numberField(host, t(label), field[key] ?? fallback, (v) => set({ [key]: bounded(0.3, 3)(v) }), 0.01, 0.3);
|
||||
const unevenRows = !!field.layout?.length && new Set(field.layout).size > 1;
|
||||
return html`<button class="nf-btn nf-back" @click=${() => (roof.solarId = null)}>‹ ${t("solar_fields")}</button>
|
||||
<section>
|
||||
${floorButtons(deps)}
|
||||
<div class="nf-h3row">
|
||||
<h3>☀ ${field.name || `${t("solar_field")} ${index}`}</h3>
|
||||
${lockButton(host, !!field.locked, () => set({ locked: !field.locked }))}
|
||||
</div>
|
||||
<div class="nf-form">
|
||||
${textField(host, t("solar_name"), field.name ?? "", (v) => set({ name: v || null }), { wide: true, placeholder: t("solar_name_hint") })}
|
||||
${selectField(host, t("solar_face"), face ? field.face : "", facesChoices, moveTo, { wide: true })}
|
||||
${numberField(host, t("solar_rows"), rows.length, (v) => set(rowsPatch(field, v)), 1, 1)}
|
||||
<label class="nf-field" title=${t("solar_cols_hint")}
|
||||
>${t("solar_cols")}
|
||||
<input
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
?disabled=${!host.admin}
|
||||
.value=${columnsText(field)}
|
||||
@change=${(e: Event) => {
|
||||
const patch = columnsPatch((e.target as HTMLInputElement).value);
|
||||
if (patch) set(patch);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
${hint(`${face && !face.unbounded ? `${t("solar_face_size", { w: formatNumber(host.hass, face.lu, 1), h: formatNumber(host.hass, face.ls, 1) })} · ` : ""}${t("solar_cols_hint")}`)}
|
||||
${unevenRows ? choiceButtons(host, (["left", "center", "right"] as const).map((a) => [a, t(`solar_align_${a}` as I18nKey)] as const), field.align ?? "left", (align) => set({ align })) : nothing}
|
||||
${choiceButtons(host, [[true, t("solar_portrait")], [false, t("solar_landscape")]] as const, field.portrait !== false, (portrait) => set({ portrait }))}
|
||||
${choiceButtons(host, [["black", t("solar_look_black")], ["blue", t("solar_look_blue")]] as const, field.look === "blue" ? "blue" : "black", (look) => set({ look }))}
|
||||
<div class="nf-form">
|
||||
${moduleSize("module_w", "solar_module_w", 1.13)} ${moduleSize("module_h", "solar_module_h", 1.72)}
|
||||
${numberField(host, t("solar_wp"), field.wp ?? DEFAULT_WP, (v) => set({ wp: bounded(50, 1500, Math.round)(v) }), 5, 50)}
|
||||
</div>
|
||||
${actions(
|
||||
html`<button class="nf-btn" aria-pressed=${roof.picking} ?disabled=${!host.admin} @click=${() => (roof.picking = !roof.picking)}>${roof.picking ? "✓ " : ""}${t("solar_pick")}</button>`,
|
||||
field.skip?.length ? html`<button class="nf-btn" ?disabled=${!host.admin} @click=${() => set({ skip: null })}>${t("solar_pick_all")}</button>` : nothing,
|
||||
)}
|
||||
${roof.picking ? hint(t("solar_pick_hint")) : nothing}
|
||||
<div class="nf-form">
|
||||
${ground
|
||||
? html`${numberField(host, t("solar_base"), field.base ?? 0, (v) => set({ base: v > 0.001 ? Math.min(60, toThousandths(v)) : null }), 0.05, 0)}
|
||||
${numberField(host, t("solar_rotation"), field.rotation ?? 0, turnGround, 5)}
|
||||
${actions(
|
||||
html`<button class="nf-chip" ?disabled=${!host.admin} @click=${() => turnGround((field.rotation ?? 0) - 15)}>↺ 15°</button>`,
|
||||
html`<button class="nf-chip" ?disabled=${!host.admin} @click=${() => turnGround((field.rotation ?? 0) + 15)}>↻ 15°</button>`,
|
||||
)}`
|
||||
: html`${numberField(host, t("solar_u"), field.u, (v) => set({ u: toThousandths(v) }), 0.05)} ${numberField(host, t(face?.wall ? "solar_v_wall" : "solar_v"), field.v, (v) => set({ v: toThousandths(v) }), 0.05)}`}
|
||||
${face?.flat && !ground ? numberField(host, t("solar_rotation"), field.rotation ?? 0, turnFlat, 5) : nothing}
|
||||
${face?.wall ? numberField(host, t("solar_tilt_wall"), field.tilt ?? 0, (v) => set({ tilt: bounded(0, 90, Math.round)(v) }), 5, 0) : nothing}
|
||||
${face?.flat ? numberField(host, t("solar_tilt"), field.tilt ?? 15, (v) => set({ tilt: bounded(0, 45, Math.round)(v) }), 1, 0) : nothing}
|
||||
${face?.flat && !face.unbounded ? checkField(host, t("solar_rack_ew"), field.rack === "ew", (on) => set({ rack: on ? "ew" : null }), { title: t("solar_rack_ew_hint") }) : nothing}
|
||||
${face && !face.flat && !face.wall ? numberField(host, t("solar_rack_tilt"), field.tilt ?? 0, (v) => set({ tilt: bounded(0, 45, Math.round)(v) || null }), 1, 0) : nothing}
|
||||
${face?.wall || face?.flat ? checkField(host, t(flipText), !!field.flip, (flip) => set({ flip })) : nothing}
|
||||
</div>
|
||||
${face?.flat && !ground
|
||||
? actions(
|
||||
html`<button class="nf-chip" ?disabled=${!host.admin} @click=${() => turnFlat((field.rotation ?? 0) - 90)}>↺ 90°</button>`,
|
||||
html`<button class="nf-chip" ?disabled=${!host.admin} @click=${() => turnFlat((field.rotation ?? 0) + 90)}>↻ 90°</button>`,
|
||||
)
|
||||
: nothing}
|
||||
<p class="nf-sub">
|
||||
${t("solar_summary", { n: sum.modules, kwp: formatNumber(host.hass, sum.kwp, 1) })}${sum.modules < planned ? html` · <b>${t("solar_partial", { n: sum.modules, total: planned })}</b>` : nothing}
|
||||
</p>
|
||||
<h4 class="nf-lib-head">🔗 ${t("solar_string")}</h4>
|
||||
<div class="nf-form">${stringSection(deps, field)}</div>
|
||||
${hint(t("solar_string_hint"))} ${hint(t("solar_form_hint"))}
|
||||
${host.admin
|
||||
? actions(
|
||||
html`<button class="nf-btn" ?disabled=${!face} @click=${() => face && set({ ...proposeField(face, field.id), portrait: field.portrait })}>${t("solar_fit")}</button>`,
|
||||
html`<button class="nf-btn nf-danger" @click=${() => roof.removeField()}>${t("delete")}</button>`,
|
||||
)
|
||||
: nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// The stair part of the furniture form: shape and turn, build, steps, flight width, up or down, railing, and the
|
||||
// resulting rise, going and step measure with a warning when they are uncomfortable.
|
||||
|
||||
import { html, svg, type TemplateResult } from "lit";
|
||||
import { DEFAULT_STAIR, STAIR_BUILDS, STAIR_OPENINGS, STAIR_RAILS, STAIR_SHAPES, STAIR_SIZES, stairConfig, stairLayout, treadCentre, type StairConfig, type StairShape } from "../../../geometry/stairs.ts";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import type { Furniture } from "../../../model.ts";
|
||||
import { formatNumber } from "../../../i18n.ts";
|
||||
import { checkField, hint, numberField, selectField } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
export interface StairActions {
|
||||
update(patch: Partial<Furniture>): void;
|
||||
}
|
||||
|
||||
/** Rise, average going on the walking line and the step measure (2 × rise + going) in metres. */
|
||||
/** The riser the landing of an L or U stair stands on now (the position of its landing tread in the layout). */
|
||||
function landingNow(cfg: StairConfig, item: Furniture): number {
|
||||
const layout = stairLayout(cfg, item.w, item.d, item.h);
|
||||
const at = layout.treads.findIndex((t) => t.landing);
|
||||
return at >= 0 ? at + 1 : 1;
|
||||
}
|
||||
|
||||
export function stairMeasures(item: Pick<Furniture, "w" | "d" | "h" | "stair">): { rise: number; going: number; measure: number; steps: number } {
|
||||
const layout = stairLayout(stairConfig(item), item.w, item.d, item.h);
|
||||
const walk = layout.treads.map(treadCentre);
|
||||
let length = 0;
|
||||
for (let i = 1; i < walk.length; i++) length += Math.hypot(walk[i][0] - walk[i - 1][0], walk[i][1] - walk[i - 1][1]);
|
||||
const going = walk.length > 1 ? length / (walk.length - 1) : 0;
|
||||
return { rise: layout.rise, going, measure: 2 * layout.rise + going, steps: layout.steps };
|
||||
}
|
||||
|
||||
/** A tiny picture of a shape for its button. */
|
||||
function shapeIcon(shape: StairShape): TemplateResult {
|
||||
const [w, d] = STAIR_SIZES[shape];
|
||||
const layout = stairLayout({ ...DEFAULT_STAIR, shape }, w, d, 2.8);
|
||||
const s = 26 / Math.max(w, d);
|
||||
return html`<svg viewBox="-14 -14 28 28" width="28" height="28" aria-hidden="true">
|
||||
${layout.treads.map((t) => svg`<polygon points=${t.poly.map(([x, z]) => `${x * s},${z * s}`).join(" ")} fill=${t.landing ? "currentColor" : "none"} fill-opacity="0.25" stroke="currentColor" stroke-width="0.8" />`)}
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
export function stairForm(host: EditorHost, item: Furniture, actions: StairActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const cfg = stairConfig(item);
|
||||
const set = (patch: Partial<StairConfig>) => actions.update({ stair: { ...cfg, ...patch } });
|
||||
const turned = cfg.shape !== "straight";
|
||||
const pickShape = (shape: StairShape) => {
|
||||
const [w, d] = STAIR_SIZES[shape];
|
||||
actions.update({ stair: { ...cfg, shape, run_width: null }, w, d });
|
||||
};
|
||||
const below = host.floor ? host.doc.floors.filter((f) => f.elevation < host.floor!.elevation).sort((p, q) => q.elevation - p.elevation)[0] : undefined;
|
||||
const above = host.floor ? host.doc.floors.filter((f) => f.elevation > host.floor!.elevation).sort((p, q) => p.elevation - q.elevation)[0] : undefined;
|
||||
const toggleDown = (down: boolean) => {
|
||||
// the height follows the floor it leads to, when that floor is drawn
|
||||
const target = down ? (below && host.floor ? host.floor.elevation - below.elevation : null) : above && host.floor ? above.elevation - host.floor.elevation : null;
|
||||
actions.update({ stair: { ...cfg, down }, ...(target ? { h: Math.round(target * 1000) / 1000 } : {}) });
|
||||
};
|
||||
const m = stairMeasures(item);
|
||||
const cm = (v: number) => formatNumber(host.hass, v * 100, 1);
|
||||
// DIN 18065 / the usual rule: the step measure 2 × rise + going should lie between 59 and 65 cm, the rise not above 21 cm
|
||||
const comfortable = m.measure >= 0.59 && m.measure <= 0.65 && m.rise <= 0.21;
|
||||
return html`<div class="nf-form">
|
||||
<div class="nf-field nf-wide">
|
||||
<span>${t("stair_shape")}</span>
|
||||
<div class="nf-swatches nf-stair-shapes" role="radiogroup" aria-label=${t("stair_shape")}>
|
||||
${STAIR_SHAPES.map(
|
||||
(shape) => html`<button type="button" class="nf-btn nf-stair-shape" role="radio" aria-checked=${shape === cfg.shape} title=${t(`stair_shape_${shape}` as I18nKey)} ?disabled=${!host.admin} @click=${() => pickShape(shape)}>
|
||||
${shapeIcon(shape)}<span>${t(`stair_shape_${shape}` as I18nKey)}</span>
|
||||
</button>`,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
${turned ? selectField(host, t("stair_turn"), cfg.turn, [["left", t("stair_turn_left")], ["right", t("stair_turn_right")]] as const, (turn) => set({ turn })) : ""}
|
||||
${selectField(host, t("stair_build"), cfg.build, STAIR_BUILDS.map((b) => [b, t(`stair_build_${b}` as I18nKey)] as const), (build) => set({ build }))}
|
||||
${cfg.build !== "solid" ? checkField(host, t("stair_risers"), cfg.risers, (risers) => set({ risers }), { wide: false }) : ""}
|
||||
${numberField(host, t("stair_steps"), cfg.steps ?? m.steps, (v) => set({ steps: Math.round(Math.min(40, Math.max(2, v))) }), 1, 2)}
|
||||
${cfg.steps != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => set({ steps: null })}>${t("height_auto")}</button>` : ""}
|
||||
${turned && cfg.shape !== "spiral"
|
||||
? html`${numberField(host, t("stair_run_width"), cfg.run_width ?? stairLayout(cfg, item.w, item.d, item.h).flight, (v) => set({ run_width: Math.max(0.4, v) }), 0.01, 0.4)}
|
||||
${cfg.run_width != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => set({ run_width: null })}>${t("height_auto")}</button>` : ""}`
|
||||
: ""}
|
||||
${cfg.shape === "l" || cfg.shape === "u"
|
||||
? html`${numberField(host, t("stair_landing_after"), cfg.landing_after ?? landingNow(cfg, item), (v) => set({ landing_after: Math.round(Math.min(m.steps - 1, Math.max(1, v))) }), 1, 1)}
|
||||
${cfg.landing_after != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => set({ landing_after: null })}>${t("height_auto")}</button>` : ""}
|
||||
${hint(t("stair_landing_hint", { h: cm(((cfg.landing_after ?? landingNow(cfg, item)) * Math.abs(item.h)) / m.steps) }), "nf-wide")}`
|
||||
: ""}
|
||||
${selectField(host, t("stair_rail"), cfg.rail, STAIR_RAILS.map((r) => [r, t(`stair_rail_${r}` as I18nKey)] as const), (rail) => set({ rail }))}
|
||||
${checkField(host, t("stair_down"), cfg.down, toggleDown, { title: t("stair_down_hint") })}
|
||||
${selectField(host, t("stair_opening"), cfg.opening, STAIR_OPENINGS.map((o) => [o, t(`stair_opening_${o}` as I18nKey)] as const), (opening) => set({ opening }), { wide: true, title: t("stair_opening_hint") })}
|
||||
<p class="nf-sub nf-wide ${comfortable ? "" : "nf-pack-error"}">
|
||||
${t("stair_measures", { steps: m.steps, rise: cm(m.rise), going: cm(m.going), measure: cm(m.measure) })} ${comfortable ? "✓" : `– ${t("stair_uncomfortable")}`}
|
||||
</p>
|
||||
${hint(t(cfg.down ? "stair_down_note" : cfg.opening === "headroom" ? "stair_up_note" : "stair_up_note_plain"), "nf-wide")}
|
||||
</div>`;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// The furniture studio in the editor's side panel: a template, its measurements and fronts, a front view that follows every change,
|
||||
// and a button that puts the piece into the plan (it is kept in the "own furniture" pack, so it shows up in the library as well).
|
||||
|
||||
import { html, nothing, svg, type TemplateResult } from "lit";
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import { buildItem, cleanRecipe, STUDIO_KINDS, switchKind, type StudioBase, type StudioHandle, type StudioKind, type StudioLamp, type StudioMount, type StudioRecipe } from "../../../studio/recipes.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { actions, checkField, colorField, hint, numberField, selectField, textField } from "../fields.ts";
|
||||
|
||||
export interface StudioDraft {
|
||||
recipe: StudioRecipe;
|
||||
/** The item being changed, or null for a new one. */
|
||||
itemId: string | null;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface StudioActions {
|
||||
change(recipe: StudioRecipe): void;
|
||||
save(): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** The palette roles offered for body and fronts; they follow the plan's look. Any other value is an own colour. */
|
||||
const ROLES = ["white", "wood", "body", "metal", "dark", "glass", "accent"] as const;
|
||||
/** How the roles look in the front view (the 3D view draws them in the current look). */
|
||||
const SWATCH: Record<string, string> = { white: "#dfe6f2", wood: "#8a6a4a", body: "#3a4a6a", metal: "#9aa7bf", dark: "#1e2638", glass: "#7fd0e8", accent: "#37e0ff", fabric: "#4b5d8c", cushion: "#6a7fb3" };
|
||||
const swatch = (color: string) => SWATCH[color] ?? color;
|
||||
|
||||
/** The item drawn from the front, parts at the back first: what the studio builds, before it goes into the plan. */
|
||||
function frontView(recipe: StudioRecipe): TemplateResult {
|
||||
const item = buildItem(recipe, "preview", "en");
|
||||
const [W, , H] = item.size;
|
||||
const scale = 180 / Math.max(W, H);
|
||||
const [vw, vh] = [W * scale, H * scale];
|
||||
const parts = [...item.parts].sort((a, b) => a.z + a.d / 2 - (b.z + b.d / 2));
|
||||
return html`<svg class="nf-studio-view" viewBox="-4 -4 ${vw + 8} ${vh + 8}" role="img" aria-hidden="true">
|
||||
${parts.map((p) => {
|
||||
const w = p.w * vw;
|
||||
const h = p.h * vh;
|
||||
const x = (p.x + 0.5) * vw - w / 2;
|
||||
const y = vh - (p.y + p.h) * vh;
|
||||
const round = p.shape === "cyl" ? Math.min(w, h) / 2 : p.shape === "loft" ? 3 : 1;
|
||||
return svg`<rect x=${x} y=${y} width=${Math.max(0.6, w)} height=${Math.max(0.6, h)} rx=${round} fill=${p.screen ? "#0b1020" : swatch(p.color)} stroke="rgba(10,16,32,0.55)" stroke-width="0.8" class=${p.glow ? "nf-studio-glow" : ""} />`;
|
||||
})}
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
function colorRow(host: EditorHost, label: string, value: string, set: (v: string) => void): TemplateResult {
|
||||
const t = host.t;
|
||||
const own = !(ROLES as readonly string[]).includes(value);
|
||||
const choices = [...ROLES.map((r) => [r, t(r === "body" ? "studio_color_plan" : (`studio_color_${r}` as I18nKey))] as const), ["own", t("studio_color_own")] as const];
|
||||
return html`${selectField(host, label, own ? "own" : value, choices, (v) => set(v === "own" ? swatch(value) : v))}
|
||||
${own ? colorField(host, t("studio_color_own"), value, "#8a6a4a", (v) => set(v ?? "wood")) : nothing}`;
|
||||
}
|
||||
|
||||
/** The studio form. */
|
||||
export function renderStudio(host: EditorHost, draft: StudioDraft, act: StudioActions): TemplateResult {
|
||||
const t = host.t;
|
||||
const r = draft.recipe;
|
||||
const set = (patch: Partial<StudioRecipe>) => act.change(cleanRecipe({ ...r, ...patch }));
|
||||
const cm = (key: I18nKey, value: number, field: "w" | "d" | "h") => numberField(host, t(key), value, (v) => set({ [field]: v }), 1, 1);
|
||||
const count = (key: I18nKey, value: number, field: "doors" | "drawers" | "shelves") => numberField(host, t(key), value, (v) => set({ [field]: v }), 1, 0);
|
||||
const kindFields = (): TemplateResult => {
|
||||
switch (r.kind) {
|
||||
case "cabinet":
|
||||
return html`${count("studio_doors", r.doors, "doors")} ${count("studio_drawers", r.drawers, "drawers")}
|
||||
${r.doors + r.drawers === 0 ? count("studio_shelves", r.shelves, "shelves") : nothing}
|
||||
${selectField<StudioHandle>(host, t("studio_handle"), r.handle, [["bar", t("studio_handle_bar")], ["knob", t("studio_handle_knob")], ["none", t("studio_handle_none")]], (v) => set({ handle: v }))}
|
||||
${selectField<StudioBase>(host, t("studio_base"), r.base, [["plinth", t("studio_base_plinth")], ["legs", t("studio_base_legs")], ["none", t("studio_base_none")]], (v) => set({ base: v }))}`;
|
||||
case "shelf":
|
||||
return html`${count("studio_shelves", r.shelves, "shelves")} ${checkField(host, t("studio_back"), r.back, (on) => set({ back: on }))}`;
|
||||
case "lamp":
|
||||
return selectField<StudioLamp>(host, t("studio_lamp"), r.lamp, [["floor", t("studio_lamp_floor")], ["table", t("studio_lamp_table")], ["pendant", t("studio_lamp_pendant")], ["wall", t("studio_lamp_wall")]], (v) => set({ lamp: v }));
|
||||
case "device":
|
||||
return html`${checkField(host, t("studio_display"), r.display, (on) => set({ display: on }))}
|
||||
${selectField<StudioMount>(host, t("studio_mount"), r.mount, [["floor", t("studio_mount_floor")], ["surface", t("studio_mount_surface")], ["wall", t("studio_mount_wall")]], (v) => set({ mount: v }))}
|
||||
${r.mount === "floor" ? selectField<StudioBase>(host, t("studio_base"), r.base, [["none", t("studio_base_none")], ["legs", t("studio_base_legs")], ["plinth", t("studio_base_plinth")]], (v) => set({ base: v })) : nothing}`;
|
||||
}
|
||||
};
|
||||
return html`<section class="nf-studio">
|
||||
<h3>🛠️ ${t(draft.itemId ? "studio_title_edit" : "studio_title")}</h3>
|
||||
${hint(t("studio_hint"))}
|
||||
<div class="nf-lib-chips" role="group" aria-label=${t("studio_kind")}>
|
||||
${STUDIO_KINDS.map((k: StudioKind) => html`<button class="nf-chip" aria-pressed=${r.kind === k} ?disabled=${!!draft.itemId && r.kind !== k} @click=${() => r.kind !== k && act.change(switchKind(r, k))}>${t(`studio_kind_${k}` as I18nKey)}</button>`)}
|
||||
</div>
|
||||
${frontView(r)}
|
||||
<div class="nf-form">
|
||||
${textField(host, t("studio_name"), r.name, (v) => set({ name: v }), { wide: true, maxlength: 60, placeholder: t(`studio_kind_${r.kind}` as I18nKey) })}
|
||||
${cm("studio_width", r.w, "w")} ${cm("studio_depth", r.d, "d")} ${cm("studio_height", r.h, "h")} ${kindFields()}
|
||||
${colorRow(host, t(r.kind === "lamp" ? "studio_color_lamp_body" : "studio_color_body"), r.body, (v) => set({ body: v }))}
|
||||
${r.kind === "cabinet" || r.kind === "shelf" || r.kind === "lamp" || r.display
|
||||
? colorRow(host, t(r.kind === "lamp" ? "studio_color_shade" : r.kind === "device" ? "studio_color_display" : r.kind === "shelf" ? "studio_color_boards" : "studio_color_front"), r.front, (v) => set({ front: v }))
|
||||
: nothing}
|
||||
</div>
|
||||
${draft.error ? html`<p class="nf-sub nf-warn">${draft.error}</p>` : nothing}
|
||||
${actions(
|
||||
html`<button class="nf-btn nf-primary" ?disabled=${draft.busy || !host.admin} @click=${() => act.save()}>${t(draft.itemId ? "studio_save" : "studio_place")}</button>`,
|
||||
html`<button class="nf-btn" ?disabled=${draft.busy} @click=${() => act.close()}>${t("cancel")}</button>`,
|
||||
)}
|
||||
</section>`;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Settings → Card templates: dashboard cards set up once, with the card's own settings dialog, and chosen on a card by name.
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { ref } from "lit/directives/ref.js";
|
||||
import { templateKey } from "../../../card-template.ts";
|
||||
import { hint } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
type Templates = Record<string, Record<string, unknown>>;
|
||||
|
||||
/** The card templates of the plan, each with an embedded card editor, a reload button and a delete button. */
|
||||
export function renderCardTemplates(host: EditorHost): TemplateResult {
|
||||
const t = host.t;
|
||||
const templates: Templates = (host.doc.settings.card_templates as Templates | null | undefined) ?? {};
|
||||
const names = Object.keys(templates);
|
||||
const store = (next: Templates) => host.change((d) => void (d.settings.card_templates = Object.keys(next).length ? next : undefined));
|
||||
// the card's settings dialog lives in its own bundle; ask for it once
|
||||
void host.loadCardEditor?.();
|
||||
const reload = (template?: string) => void host.hass?.callService("nextfloor", "reload_screens", template ? { template } : {});
|
||||
const add = (input: HTMLInputElement) => {
|
||||
const key = templateKey(input.value);
|
||||
if (!key || key in templates || names.length >= 20) return;
|
||||
input.value = "";
|
||||
store({ ...templates, [key]: {} });
|
||||
};
|
||||
return html`<details class="nf-section">
|
||||
<summary>${t("card_templates")}${names.length ? html` <span class="nf-lib-count">${names.length}</span>` : nothing}</summary>
|
||||
${hint(t("card_templates_hint"))}
|
||||
${names.map(
|
||||
(name) => html`<details class="nf-section">
|
||||
<summary>${name}</summary>
|
||||
<nextfloor-card-editor
|
||||
.hass=${host.hass}
|
||||
${ref((el) => el && (el as unknown as { setConfig(c: unknown): void }).setConfig({ type: "custom:nextfloor-card", ...templates[name] }))}
|
||||
@config-changed=${(e: CustomEvent<{ config: Record<string, unknown> }>) => {
|
||||
e.stopPropagation();
|
||||
const { type: _type, template: _template, ...rest } = e.detail.config;
|
||||
store({ ...templates, [name]: rest });
|
||||
}}
|
||||
></nextfloor-card-editor>
|
||||
${host.admin
|
||||
? html`<div class="nf-actions">
|
||||
<button class="nf-btn" @click=${() => reload(name)}>${t("template_reload")}</button>
|
||||
<button class="nf-btn nf-danger" @click=${() => store(Object.fromEntries(Object.entries(templates).filter(([k]) => k !== name)))}>${t("delete")}</button>
|
||||
</div>`
|
||||
: nothing}
|
||||
${hint(t("template_use", { name }))}
|
||||
</details>`,
|
||||
)}
|
||||
${host.admin
|
||||
? html`<div class="nf-form">
|
||||
<label class="nf-field nf-wide">${t("template_name")}<input type="text" maxlength="40" placeholder="kitchen_tablet" @keydown=${(e: KeyboardEvent) => e.key === "Enter" && add(e.target as HTMLInputElement)} /></label>
|
||||
</div>
|
||||
<div class="nf-actions">
|
||||
<button class="nf-btn" @click=${(e: Event) => add(((e.target as HTMLElement).closest("details")?.querySelector("input[type=text]") as HTMLInputElement) ?? document.createElement("input"))}>${t("template_add")}</button>
|
||||
<button class="nf-btn" @click=${() => reload()}>${t("template_reload_all")}</button>
|
||||
</div>`
|
||||
: nothing}
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { EditHistory } from "./history.ts";
|
||||
|
||||
test("a new history has nothing to undo or redo", () => {
|
||||
const history = new EditHistory<number[]>();
|
||||
assert.equal(history.canUndo, false);
|
||||
assert.equal(history.canRedo, false);
|
||||
assert.equal(history.undo([1]), null);
|
||||
assert.equal(history.redo([1]), null);
|
||||
});
|
||||
|
||||
test("undo steps back through the recorded states, redo forward again", () => {
|
||||
const history = new EditHistory<{ n: number }>();
|
||||
history.record({ n: 1 });
|
||||
history.record({ n: 2 });
|
||||
assert.deepEqual(history.undo({ n: 3 }), { n: 2 });
|
||||
assert.deepEqual(history.undo({ n: 2 }), { n: 1 });
|
||||
assert.equal(history.canUndo, false);
|
||||
assert.deepEqual(history.redo({ n: 1 }), { n: 2 });
|
||||
assert.deepEqual(history.redo({ n: 2 }), { n: 3 });
|
||||
assert.equal(history.canRedo, false);
|
||||
});
|
||||
|
||||
test("a new change ends the redo line", () => {
|
||||
const history = new EditHistory<number>();
|
||||
history.record(1);
|
||||
history.undo(2);
|
||||
assert.equal(history.canRedo, true);
|
||||
history.record(1);
|
||||
assert.equal(history.canRedo, false);
|
||||
});
|
||||
|
||||
test("only the newest states are kept", () => {
|
||||
const history = new EditHistory<number>(3);
|
||||
for (let i = 0; i < 10; i++) history.record(i);
|
||||
const seen: number[] = [];
|
||||
for (let state = history.undo(99); state !== null; state = history.undo(state)) seen.push(state);
|
||||
assert.deepEqual(seen, [9, 8, 7]);
|
||||
});
|
||||
|
||||
test("a recorded state is a copy: changing the original afterwards does not alter it", () => {
|
||||
const history = new EditHistory<{ list: number[] }>();
|
||||
const doc = { list: [1] };
|
||||
history.record(doc);
|
||||
doc.list.push(2);
|
||||
assert.deepEqual(history.undo(doc), { list: [1] });
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
// Undo and redo for the editor. States are kept as JSON text, so a snapshot can never change behind the history's back.
|
||||
|
||||
export class EditHistory<T> {
|
||||
private readonly limit: number;
|
||||
private undoStack: string[] = [];
|
||||
private redoStack: string[] = [];
|
||||
|
||||
constructor(limit = 100) {
|
||||
this.limit = limit;
|
||||
}
|
||||
|
||||
get canUndo(): boolean {
|
||||
return this.undoStack.length > 0;
|
||||
}
|
||||
|
||||
get canRedo(): boolean {
|
||||
return this.redoStack.length > 0;
|
||||
}
|
||||
|
||||
/** Remembers `before`, the state a change started from. A new change ends the redo line. */
|
||||
record(before: T): void {
|
||||
this.undoStack.push(JSON.stringify(before));
|
||||
if (this.undoStack.length > this.limit) this.undoStack.shift();
|
||||
this.redoStack = [];
|
||||
}
|
||||
|
||||
/** The state before the last change, or null when there is none. `current` becomes redoable. */
|
||||
undo(current: T): T | null {
|
||||
const text = this.undoStack.pop();
|
||||
if (text === undefined) return null;
|
||||
this.redoStack.push(JSON.stringify(current));
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
/** The state that was undone last, or null. `current` becomes undoable again. */
|
||||
redo(current: T): T | null {
|
||||
const text = this.redoStack.pop();
|
||||
if (text === undefined) return null;
|
||||
this.undoStack.push(JSON.stringify(current));
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { I18nKey } from "../../i18n.ts";
|
||||
import type { Building, Floor, Vec2 } from "../../model.ts";
|
||||
import type { HomeAssistant } from "../../types.ts";
|
||||
|
||||
/** What the editor's forms may use of the editor: the plan, the selected floor, translation, and the two ways of changing the plan. */
|
||||
export interface EditorHost {
|
||||
readonly hass: HomeAssistant | undefined;
|
||||
readonly doc: Building;
|
||||
readonly floor: Floor | undefined;
|
||||
/** Whether the user may change the plan; forms are read-only otherwise. */
|
||||
readonly admin: boolean;
|
||||
t(key: I18nKey, vars?: Record<string, string | number>): string;
|
||||
/** Changes a copy of the plan (with the selected floor at hand) and stores it as one undoable step. */
|
||||
change(mutate: (doc: Building, floor: Floor) => void): void;
|
||||
/** Replaces the whole plan as one undoable step. */
|
||||
replace(next: Building): void;
|
||||
/** Asks for one tap on the plan (a calibration place); the callback gets it in metres, or null if dropped. */
|
||||
pickPoint(onPick: (at: Vec2 | null) => void): void;
|
||||
/** Loads the card's settings dialog (its own bundle), for the card templates; set by the panel. */
|
||||
readonly loadCardEditor?: () => Promise<unknown>;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { LIGHT_ANIMATIONS, type LightEffectConfig } from "../../light-effects.ts";
|
||||
import { pluginLightAnimationNames } from "../../plugins/registry.ts";
|
||||
import type { EditorHost } from "./host.ts";
|
||||
|
||||
/** A small local-only mapping editor. Unknown stored identifiers remain untouched until edited. */
|
||||
export function lightEffectFields(host: EditorHost, config: LightEffectConfig, effects: unknown, update: (patch: LightEffectConfig) => void): TemplateResult {
|
||||
const mapping = config.effect_animations ?? {};
|
||||
// animations plugins add are offered after the built-in ones, by their own name
|
||||
const extra = pluginLightAnimationNames();
|
||||
const known = (value: string) => (LIGHT_ANIMATIONS as readonly string[]).includes(value) || extra.includes(value);
|
||||
const names = [...new Set([...Object.keys(mapping), ...(Array.isArray(effects) ? effects.filter((s): s is string => typeof s === "string") : [])])];
|
||||
const set = (name: string, animation: string, input: HTMLInputElement | HTMLSelectElement, adding = false): boolean => {
|
||||
const exists = Object.prototype.hasOwnProperty.call(mapping, name);
|
||||
const nameLength = Array.from(name).length; // Match Python len(), not UTF-16 code units.
|
||||
const error = adding && exists ? "light_effect_exists"
|
||||
: animation !== "" && (nameLength < 1 || nameLength > 255) ? "light_effect_name_limit"
|
||||
: animation !== "" && !exists && Object.keys(mapping).length >= 100 ? "light_effect_count_limit" : undefined;
|
||||
input.setCustomValidity?.(error ? host.t(error) : "");
|
||||
if (error) {
|
||||
const feedback = input.closest?.("details")?.querySelector<HTMLElement>("[data-effect-feedback]");
|
||||
if (feedback) feedback.textContent = host.t(error);
|
||||
input.reportValidity?.();
|
||||
if (!adding) input.value = exists ? mapping[name] : "";
|
||||
return false;
|
||||
}
|
||||
const next = { ...mapping };
|
||||
if (animation === "") delete next[name];
|
||||
else Object.defineProperty(next, name, { value: animation, enumerable: true, configurable: true, writable: true });
|
||||
update({ effect_animations: next });
|
||||
return true;
|
||||
};
|
||||
return html`<details class="nf-wide">
|
||||
<summary>${host.t("light_effects")}</summary>
|
||||
<p class="nf-sub">${host.t("light_effects_hint")}</p>
|
||||
<label class="nf-check"><input type="checkbox" .checked=${config.animations_enabled !== false} ?disabled=${!host.admin}
|
||||
@change=${(e: Event) => update({ animations_enabled: (e.target as HTMLInputElement).checked })} />${host.t("light_effects_enabled")}</label>
|
||||
${names.map((name) => html`<label class="nf-field nf-wide">${name}
|
||||
<select ?disabled=${!host.admin} @change=${(e: Event) => { const input = e.target as HTMLSelectElement; set(name, input.value, input); }}>
|
||||
<option value="" ?selected=${!Object.prototype.hasOwnProperty.call(mapping, name)}>${host.t("light_effect_unmapped")}</option>
|
||||
${Object.prototype.hasOwnProperty.call(mapping, name) && !known(mapping[name])
|
||||
? html`<option selected value=${mapping[name]}>${mapping[name]} (${host.t("light_effect_unmapped")})</option>` : nothing}
|
||||
${LIGHT_ANIMATIONS.map((animation) => html`<option value=${animation} ?selected=${Object.prototype.hasOwnProperty.call(mapping, name) && mapping[name] === animation}>${host.t(`light_animation_${animation}`)}</option>`)}
|
||||
${extra.map((animation) => html`<option value=${animation} ?selected=${Object.prototype.hasOwnProperty.call(mapping, name) && mapping[name] === animation}>${animation} (${host.t("plugin")})</option>`)}
|
||||
</select></label>`)}
|
||||
<label class="nf-field nf-wide">${host.t("light_effect_add")}<input type="text" ?disabled=${!host.admin} placeholder="Regenbogen"
|
||||
@input=${(e: Event) => (e.target as HTMLInputElement).setCustomValidity("")}
|
||||
@change=${(e: Event) => { const input = e.target as HTMLInputElement; if (set(input.value, "none", input, true)) input.value = ""; }} /></label>
|
||||
<p class="nf-sub" data-effect-feedback role="status" aria-live="polite">${host.t("light_effect_name_limit")} ${host.t("light_effect_count_limit")}</p>
|
||||
</details>`;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import type { Background, Vec2 } from "../../../model.ts";
|
||||
import { dragRotation, pictureCentre, pictureLocal, scaledToLength, straightened, wrapHalfTurn } from "./background.ts";
|
||||
|
||||
const bg = (extra: Partial<Background> = {}): Background => ({ image_id: "i", x: 0, z: 0, width: 4, opacity: 1, ...extra });
|
||||
const near = (a: number, b: number, eps = 1e-3) => assert.ok(Math.abs(a - b) < eps, `${a} is not ${b}`);
|
||||
|
||||
test("the picture's middle follows from its position, width and aspect", () => {
|
||||
assert.deepEqual(pictureCentre(bg({ x: 1, z: 2 }), 0.5), [3, 3]);
|
||||
});
|
||||
|
||||
test("a line that is nearly along x is straightened by turning the picture about the first point", () => {
|
||||
const picture = bg();
|
||||
const p: Vec2 = [0, 0];
|
||||
const q: Vec2 = [10, 1];
|
||||
const result = straightened(picture, 0.5, p, q)!;
|
||||
near(result.rotation!, -5.71, 0.01);
|
||||
// the middle keeps its distance from the turning point
|
||||
const before = Math.hypot(...pictureCentre(picture, 0.5));
|
||||
const after = Math.hypot(...pictureCentre(result, 0.5));
|
||||
near(before, after, 0.01);
|
||||
assert.equal(result.width, 4);
|
||||
});
|
||||
|
||||
test("a line that is already straight, or too short, changes nothing", () => {
|
||||
assert.equal(straightened(bg(), 0.5, [0, 0], [5, 0]), null);
|
||||
assert.equal(straightened(bg(), 0.5, [0, 0], [0, 0.01]), null);
|
||||
});
|
||||
|
||||
test("a line nearly along z is turned to run along z, in the right direction", () => {
|
||||
const result = straightened(bg(), 0.5, [0, 0], [1, 10])!;
|
||||
// the line points a little east of south: the picture turns anticlockwise to bring it straight
|
||||
assert.ok(result.rotation! > 0 && result.rotation! < 10);
|
||||
});
|
||||
|
||||
test("scaling to a measured length keeps the point fixed and the turn", () => {
|
||||
const picture = bg({ rotation: 30 });
|
||||
const a: Vec2 = [1, 1];
|
||||
const result = scaledToLength(picture, 0.5, a, [3, 1], 8)!;
|
||||
assert.equal(result.width, 16);
|
||||
assert.equal(result.rotation, 30);
|
||||
// a point of the picture that was at `a` is still at `a`: its distance from the middle scaled by the same factor
|
||||
const [c1, c2] = [pictureCentre(picture, 0.5), pictureCentre(result, 0.5)];
|
||||
near(c2[0] - a[0], 4 * (c1[0] - a[0]));
|
||||
near(c2[1] - a[1], 4 * (c1[1] - a[1]));
|
||||
});
|
||||
|
||||
test("scaling needs a positive length and a stretch that can be measured", () => {
|
||||
assert.equal(scaledToLength(bg(), 0.5, [0, 0], [1, 0], 0), null);
|
||||
assert.equal(scaledToLength(bg(), 0.5, [0, 0], [1, 0], -3), null);
|
||||
assert.equal(scaledToLength(bg(), 0.5, [2, 2], [2, 2], 5), null);
|
||||
});
|
||||
|
||||
test("a plan point in the picture's own frame, with and without a turn", () => {
|
||||
assert.deepEqual(pictureLocal(bg({ x: 1, z: 1 }), 0.5, [2, 3]), [1, 2]);
|
||||
// the picture's middle is (2, 1); a point 2 east of it lies 2 up the picture when that is turned a quarter clockwise
|
||||
const turned = pictureLocal(bg({ rotation: 90 }), 0.5, [4, 1]);
|
||||
near(turned[0], 2, 1e-9);
|
||||
near(turned[1], -1, 1e-9);
|
||||
});
|
||||
|
||||
test("angles wrap into a half turn each way, and dragging the handle snaps with Shift", () => {
|
||||
assert.equal(wrapHalfTurn(190), -170);
|
||||
assert.equal(wrapHalfTurn(-190), 170);
|
||||
assert.equal(wrapHalfTurn(180), -180);
|
||||
assert.equal(dragRotation(10, 0, Math.PI / 6, true), 45);
|
||||
assert.equal(dragRotation(0, 0, (7 * Math.PI) / 180, true), 15 * Math.round(7 / 15));
|
||||
assert.equal(dragRotation(0, 0, (7.04 * Math.PI) / 180, false), 7);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The picture behind a floor plan (a scan of the architect's drawing, say): its size follows from the picture's aspect, and the
|
||||
// helpers here straighten it, scale it to a measured length, and map plan points into it.
|
||||
|
||||
import type { Background, Vec2 } from "../../../model.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** The picture's own height in metres. */
|
||||
export const pictureHeight = (bg: Background, aspect: number): number => bg.width * aspect;
|
||||
|
||||
/** The middle of the picture in the plan. */
|
||||
export const pictureCentre = (bg: Background, aspect: number): Vec2 => [bg.x + bg.width / 2, bg.z + pictureHeight(bg, aspect) / 2];
|
||||
|
||||
/** A point turned about another by an angle in radians (clockwise in the plan, where z points down). */
|
||||
function turnAbout(point: Vec2, about: Vec2, angle: number): Vec2 {
|
||||
const [dx, dz] = [point[0] - about[0], point[1] - about[1]];
|
||||
return [about[0] + dx * Math.cos(angle) - dz * Math.sin(angle), about[1] + dx * Math.sin(angle) + dz * Math.cos(angle)];
|
||||
}
|
||||
|
||||
/** An angle in degrees brought into -180 up to 180. */
|
||||
export const wrapHalfTurn = (degrees: number): number => (((((degrees + 180) % 360) + 360) % 360) - 180);
|
||||
|
||||
/** The picture placed so that its middle is at `centre`. */
|
||||
function centredAt(centre: Vec2, width: number, height: number): Pick<Background, "x" | "z"> {
|
||||
return { x: thousandths(centre[0] - width / 2), z: thousandths(centre[1] - height / 2) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the picture about the first of two tapped points so that the line between them runs exactly along x or z, whichever is
|
||||
* nearer. Null when the points are too close together or the line already is straight.
|
||||
*/
|
||||
export function straightened(bg: Background, aspect: number, p: Vec2, q: Vec2): Background | null {
|
||||
if (Math.hypot(q[0] - p[0], q[1] - p[1]) < 0.05) return null;
|
||||
const angle = Math.atan2(q[1] - p[1], q[0] - p[0]);
|
||||
const correction = Math.round(angle / (Math.PI / 2)) * (Math.PI / 2) - angle;
|
||||
if (Math.abs(correction) < 1e-4) return null;
|
||||
// turning about p carries the picture's middle along
|
||||
const centre = turnAbout(pictureCentre(bg, aspect), p, correction);
|
||||
const rotation = Math.round(wrapHalfTurn((bg.rotation ?? 0) + (correction * 180) / Math.PI) * 100) / 100;
|
||||
return { ...bg, rotation, ...centredAt(centre, bg.width, pictureHeight(bg, aspect)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales the picture about the first of two points so that the stretch between them measures `real` metres. The turn is kept.
|
||||
* Null when the stretch is too short to measure or the real length is no positive number.
|
||||
*/
|
||||
export function scaledToLength(bg: Background, aspect: number, a: Vec2, b: Vec2, real: number): Background | null {
|
||||
const measured = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
if (!(real > 0) || measured < 1e-4) return null;
|
||||
const k = real / measured;
|
||||
const [cx, cz] = pictureCentre(bg, aspect);
|
||||
const centre: Vec2 = [a[0] + k * (cx - a[0]), a[1] + k * (cz - a[1])];
|
||||
const width = bg.width * k;
|
||||
return { ...bg, width: thousandths(width), ...centredAt(centre, width, pictureHeight(bg, aspect) * k) };
|
||||
}
|
||||
|
||||
/** A plan point measured in the picture's own frame: from its top left corner, along its (turned) sides, in metres. */
|
||||
export function pictureLocal(bg: Background, aspect: number, world: Vec2): Vec2 {
|
||||
const turned = turnAbout(world, pictureCentre(bg, aspect), (-(bg.rotation ?? 0) * Math.PI) / 180);
|
||||
return [turned[0] - bg.x, turned[1] - bg.z];
|
||||
}
|
||||
|
||||
/** The rotation the picture gets while its turn handle is dragged: whole 15° steps with Shift, tenths of a degree otherwise. */
|
||||
export function dragRotation(startRotation: number, startAngle: number, nowAngle: number, snap: boolean): number {
|
||||
const raw = startRotation + ((nowAngle - startAngle) * 180) / Math.PI;
|
||||
return wrapHalfTurn(snap ? Math.round(raw / 15) * 15 : Math.round(raw * 10) / 10);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { distance, fingerprintsOf, locate, medianReading, replaceRoom, signalLevel } from "./ble.ts";
|
||||
|
||||
const prints = [
|
||||
{ room: "kitchen", rssi: { a: -50, b: -80, c: -90 } },
|
||||
{ room: "kitchen", rssi: { a: -55, b: -78, c: -92 } },
|
||||
{ room: "bath", rssi: { a: -85, b: -45, c: -70 } },
|
||||
{ room: "hall", rssi: { a: -75, b: -75, c: -50 } },
|
||||
];
|
||||
|
||||
test("the distance is zero for the same pattern, a missing scanner counts as far, and differences are capped", () => {
|
||||
assert.equal(distance({ a: -60 }, { a: -60 }), 0);
|
||||
assert.ok(Math.abs(distance({ a: -60, b: -50 }, { a: -60 }) - Math.sqrt((40 * 40) / 2)) < 1e-9);
|
||||
assert.equal(distance({}, {}), Infinity);
|
||||
});
|
||||
|
||||
test("the nearest room wins, also when a room has several spots", () => {
|
||||
const k = locate(prints, { a: -53, b: -79, c: -91 });
|
||||
assert.equal(k.room, "kitchen");
|
||||
assert.ok(k.distance < 5 && k.margin > 20);
|
||||
assert.equal(locate(prints, { a: -84, b: -47, c: -71 }).room, "bath");
|
||||
assert.equal(locate(prints, { a: -76, b: -74, c: -52 }).room, "hall");
|
||||
});
|
||||
|
||||
test("nothing heard, no fingerprints or nothing close gives no room", () => {
|
||||
assert.equal(locate(prints, {}).room, null);
|
||||
assert.equal(locate([], { a: -60 }).room, null);
|
||||
assert.equal(locate(prints, { a: -30, b: -30, c: -30 }).room, null);
|
||||
});
|
||||
|
||||
test("the median drops a scanner that missed most samples", () => {
|
||||
assert.deepEqual(medianReading([{ a: -60, b: -70 }, { a: -64, b: -72 }, { a: -62 }, { a: -61 }]), { a: -61.5 });
|
||||
assert.deepEqual(medianReading([]), {});
|
||||
});
|
||||
|
||||
test("a walk through a room becomes up to three fingerprints of its own stretches", () => {
|
||||
const walk = Array.from({ length: 20 }, (_, i) => ({ a: -50 - i, b: -80 + i }));
|
||||
const fps = fingerprintsOf("kitchen", walk);
|
||||
assert.equal(fps.length, 3);
|
||||
assert.ok(fps[0].rssi.a > fps[2].rssi.a);
|
||||
assert.deepEqual(fingerprintsOf("kitchen", [{ a: -60 }, { a: -61 }]).length, 1);
|
||||
assert.deepEqual(fingerprintsOf("kitchen", [{}, {}, {}]), []);
|
||||
});
|
||||
|
||||
test("recording a room again replaces its fingerprints and keeps the others", () => {
|
||||
const out = replaceRoom(prints, "kitchen", [{ room: "kitchen", rssi: { a: -40 } }]);
|
||||
assert.equal(out.filter((p) => p.room === "kitchen").length, 1);
|
||||
assert.equal(out.length, 3);
|
||||
});
|
||||
|
||||
test("signal bars run from nothing at −95 dBm to full at −45", () => {
|
||||
assert.equal(signalLevel(-100), 0);
|
||||
assert.equal(signalLevel(-70), 0.5);
|
||||
assert.equal(signalLevel(-40), 1);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
// Locating a Bluetooth tag by room, the editor's side: the same comparison the backend sensor makes (custom_components/nextfloor/ble.py),
|
||||
// so the editor can show "now: kitchen" while you walk, and the recording of a room into fingerprints.
|
||||
|
||||
import type { BleFingerprint } from "../../../model.ts";
|
||||
|
||||
export type Reading = Record<string, number>;
|
||||
|
||||
/** A scanner that does not hear the tag counts as this (dBm); differences are capped at MAX_DIFF. */
|
||||
export const MISSING = -100;
|
||||
export const MAX_DIFF = 40;
|
||||
/** Above this distance (RMS in dB) no room is a good match. */
|
||||
export const UNKNOWN_DISTANCE = 18;
|
||||
|
||||
/** How long a room is recorded, how often it is sampled, and into how many spots the samples are split. */
|
||||
export const RECORD_SECONDS = 30;
|
||||
export const SAMPLE_EVERY_MS = 1500;
|
||||
export const SPOTS_PER_ROOM = 3;
|
||||
|
||||
export function distance(a: Reading, b: Reading): number {
|
||||
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
||||
if (keys.size === 0) return Infinity;
|
||||
let total = 0;
|
||||
for (const k of keys) total += Math.min(Math.abs((a[k] ?? MISSING) - (b[k] ?? MISSING)), MAX_DIFF) ** 2;
|
||||
return Math.sqrt(total / keys.size);
|
||||
}
|
||||
|
||||
export interface Located {
|
||||
room: string | null;
|
||||
distance: number;
|
||||
/** How far the runner-up room is behind the winner (dB). */
|
||||
margin: number;
|
||||
}
|
||||
|
||||
export function locate(prints: readonly BleFingerprint[], reading: Reading): Located {
|
||||
if (Object.keys(reading).length === 0) return { room: null, distance: Infinity, margin: 0 };
|
||||
const best = new Map<string, number>();
|
||||
for (const fp of prints) {
|
||||
const d = distance(fp.rssi, reading);
|
||||
if (d < (best.get(fp.room) ?? Infinity)) best.set(fp.room, d);
|
||||
}
|
||||
const ranked = [...best].sort((p, q) => p[1] - q[1]);
|
||||
if (ranked.length === 0) return { room: null, distance: Infinity, margin: 0 };
|
||||
const [room, dist] = ranked[0];
|
||||
if (dist > UNKNOWN_DISTANCE) return { room: null, distance: dist, margin: 0 };
|
||||
return { room, distance: dist, margin: ranked.length > 1 ? ranked[1][1] - dist : UNKNOWN_DISTANCE };
|
||||
}
|
||||
|
||||
const median = (values: number[]): number => {
|
||||
const s = [...values].sort((a, b) => a - b);
|
||||
const m = s.length >> 1;
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
};
|
||||
|
||||
/** The median signal per scanner over some samples; a scanner that missed the tag in most of them is left out. */
|
||||
export function medianReading(samples: readonly Reading[]): Reading {
|
||||
const out: Reading = {};
|
||||
const keys = new Set(samples.flatMap((s) => Object.keys(s)));
|
||||
for (const k of keys) {
|
||||
const values = samples.filter((s) => k in s).map((s) => s[k]);
|
||||
if (values.length * 2 > samples.length) out[k] = Math.round(median(values) * 10) / 10;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Turns the samples taken while walking through a room into up to `spots` fingerprints (one per stretch of the walk). */
|
||||
export function fingerprintsOf(room: string, samples: readonly Reading[], spots = SPOTS_PER_ROOM): BleFingerprint[] {
|
||||
const heard = samples.filter((s) => Object.keys(s).length > 0);
|
||||
if (heard.length === 0) return [];
|
||||
const n = Math.max(1, Math.min(spots, Math.floor(heard.length / 3)));
|
||||
const out: BleFingerprint[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const chunk = heard.slice(Math.floor((i * heard.length) / n), Math.floor(((i + 1) * heard.length) / n));
|
||||
const rssi = medianReading(chunk);
|
||||
if (Object.keys(rssi).length > 0) out.push({ room, rssi });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The prints of a tag with the ones of `room` replaced by new ones. */
|
||||
export const replaceRoom = (prints: readonly BleFingerprint[], room: string, fresh: readonly BleFingerprint[]): BleFingerprint[] => [
|
||||
...prints.filter((p) => p.room !== room),
|
||||
...fresh,
|
||||
];
|
||||
|
||||
/** The signal bar for a dBm value: 0 … 1 (−95 and below nothing, −45 and above full). */
|
||||
export const signalLevel = (dbm: number): number => Math.max(0, Math.min(1, (dbm + 95) / 50));
|
||||
@@ -0,0 +1,101 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
import { CATEGORIES, cardsOf, categoryOf, mainCategory, roomCategories, sizeLabel, withRecent, type CatalogEntry } from "./catalog.ts";
|
||||
|
||||
const pack = (id: string, extra: Partial<CatalogEntry> = {}, source = "nextfloor.demo"): CatalogEntry => ({ type: `pack:${source}:${id}`, source, id, size: [1, 0.6, 0.8], ...extra });
|
||||
|
||||
/** Every item of the packs that ship with NextFloor. */
|
||||
function builtinPackEntries(): CatalogEntry[] {
|
||||
const dir = new URL("../../../../../custom_components/nextfloor/packs/", import.meta.url);
|
||||
return readdirSync(dir).flatMap((file) => {
|
||||
const p = JSON.parse(readFileSync(new URL(file, dir), "utf8")) as { id: string; items: { id: string; size: [number, number, number]; light?: string; electric?: boolean; vehicle?: boolean; climate?: boolean }[] };
|
||||
return p.items.map((it) => pack(it.id, { size: it.size, lamp: !!it.light, electric: !!it.electric, vehicle: !!it.vehicle, climate: !!it.climate }, p.id));
|
||||
});
|
||||
}
|
||||
|
||||
test("items are sorted by what they are, not by the pack they come from", () => {
|
||||
assert.equal(categoryOf({ type: "sofa", source: "living", id: "sofa", size: [2, 0.9, 0.8] }), "seating");
|
||||
assert.equal(categoryOf({ type: "lamp_floor", source: "lights", id: "lamp_floor", size: [0.4, 0.4, 1.6], lamp: true }), "lights");
|
||||
assert.equal(categoryOf(pack("vanity_80")), "bath");
|
||||
assert.equal(categoryOf(pack("base_60")), "kitchen");
|
||||
assert.equal(categoryOf(pack("tesla_model_3", { vehicle: true })), "vehicles");
|
||||
assert.equal(categoryOf(pack("thermostat_wall", { climate: true })), "climate");
|
||||
});
|
||||
|
||||
test("a glowing item is filed by what it is, a lamp among the lights", () => {
|
||||
assert.equal(categoryOf(pack("aquarium_240", { lamp: true })), "pets");
|
||||
assert.equal(categoryOf(pack("fireplace_wall", { lamp: true })), "climate");
|
||||
assert.equal(categoryOf(pack("inverter", { lamp: true })), "energy");
|
||||
assert.equal(categoryOf(pack("floor_lamp_arc", { lamp: true })), "lights");
|
||||
assert.equal(categoryOf(pack("orb_lamp", { lamp: true })), "lights");
|
||||
assert.equal(categoryOf(pack("unknown_glow", { lamp: true })), "lights");
|
||||
});
|
||||
|
||||
test("words inside other words do not mislead the sorting", () => {
|
||||
assert.equal(categoryOf(pack("display_8")), "media", "display_ is not play_");
|
||||
assert.equal(categoryOf(pack("cat_steps")), "pets", "cat steps are not stairs");
|
||||
assert.equal(categoryOf(pack("whirlpool_indoor")), "bath", "a whirlpool is not a garden pool");
|
||||
assert.equal(categoryOf(pack("console")), "tables");
|
||||
assert.equal(categoryOf(pack("game_console")), "media");
|
||||
});
|
||||
|
||||
test("every built-in pack item lands in a category, and few are left as decoration", () => {
|
||||
const entries = builtinPackEntries();
|
||||
assert.ok(entries.length > 500);
|
||||
const decor = entries.filter((e) => categoryOf(e) === "decor");
|
||||
assert.ok(decor.length <= 15, `too many unsorted items: ${decor.map((e) => e.id).join(", ")}`);
|
||||
const used = new Set(entries.map(categoryOf));
|
||||
for (const c of CATEGORIES) assert.ok(used.has(c) || c === "decor", `no item in ${c}`);
|
||||
});
|
||||
|
||||
test("a room's name picks the categories that fit it, lights always among them", () => {
|
||||
const kitchen = roomCategories("Küche")!;
|
||||
assert.ok(kitchen.has("kitchen") && kitchen.has("lights") && !kitchen.has("beds"));
|
||||
assert.ok(roomCategories("Master Bedroom")!.has("beds"));
|
||||
assert.ok(roomCategories("Gäste-WC")!.has("bath"));
|
||||
assert.ok(roomCategories("Terrasse")!.has("garden"));
|
||||
assert.equal(roomCategories("Raum 3"), null);
|
||||
assert.equal(roomCategories(undefined), null);
|
||||
});
|
||||
|
||||
test("one model in several sizes becomes one card, smallest first", () => {
|
||||
const cards = cardsOf([pack("bed_160", { size: [1.6, 2, 0.4] }), pack("bed_90", { size: [0.9, 2, 0.4] }), pack("bed_140", { size: [1.4, 2, 0.4] }), pack("bed_canopy")]);
|
||||
assert.equal(cards.length, 2);
|
||||
assert.deepEqual(cards[0].entries.map((e) => e.id), ["bed_90", "bed_140", "bed_160"]);
|
||||
assert.deepEqual(cards[0].entries.map((e) => sizeLabel(e, cards[0].entries)), ["90", "140", "160"]);
|
||||
});
|
||||
|
||||
test("vehicles, built-in types and items of other packs keep their own cards", () => {
|
||||
const cards = cardsOf([
|
||||
pack("tesla_model_y", { vehicle: true }),
|
||||
pack("tesla_model_y_2025", { vehicle: true }),
|
||||
pack("sofa_3", {}, "nextfloor.a"),
|
||||
pack("sofa_2", {}, "nextfloor.b"),
|
||||
{ type: "sofa", source: "living", id: "sofa", size: [2, 0.9, 0.8] },
|
||||
]);
|
||||
assert.equal(cards.length, 5);
|
||||
});
|
||||
|
||||
test("sizes sharing a width are told apart by the size in their id", () => {
|
||||
const all = [pack("cube_2x2", { size: [0.77, 0.39, 0.77] }), pack("cube_4x2", { size: [0.77, 0.39, 1.47] })];
|
||||
assert.deepEqual(all.map((e) => sizeLabel(e, all)), ["2x2", "4x2"]);
|
||||
});
|
||||
|
||||
test("the recently used list keeps the newest first, once each", () => {
|
||||
assert.deepEqual(withRecent(["a", "b", "c"], "b"), ["b", "a", "c"]);
|
||||
assert.deepEqual(withRecent(["a", "b"], "c", 2), ["c", "a"]);
|
||||
});
|
||||
|
||||
test("a room opens with its main kind of furniture", () => {
|
||||
assert.equal(mainCategory("Küche"), "kitchen");
|
||||
assert.equal(mainCategory("Kinderzimmer"), "kids");
|
||||
assert.equal(mainCategory("Schlafzimmer"), "beds");
|
||||
assert.equal(mainCategory("Raum 3"), null);
|
||||
});
|
||||
|
||||
test("a word inside a room name does not pick the wrong room", () => {
|
||||
assert.equal(mainCategory("Fitnessraum"), "fitness", "fitness is not a dining room");
|
||||
assert.equal(mainCategory("Wohn-/Esszimmer"), "seating");
|
||||
assert.equal(mainCategory("Esszimmer"), "tables");
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
// The furniture library sorted by what an item is (sofas, beds, kitchen …) instead of where it comes from, the categories that fit a
|
||||
// room by its name, and items of one model in several sizes folded into one card. Pure functions over ids, names and sizes.
|
||||
|
||||
export const CATEGORIES = [
|
||||
"lights",
|
||||
"seating",
|
||||
"tables",
|
||||
"storage",
|
||||
"beds",
|
||||
"kitchen",
|
||||
"appliances",
|
||||
"bath",
|
||||
"media",
|
||||
"office",
|
||||
"tech",
|
||||
"climate",
|
||||
"energy",
|
||||
"garden",
|
||||
"plants",
|
||||
"kids",
|
||||
"fitness",
|
||||
"pets",
|
||||
"workshop",
|
||||
"music",
|
||||
"season",
|
||||
"pictures",
|
||||
"vehicles",
|
||||
"building",
|
||||
"decor",
|
||||
] as const;
|
||||
|
||||
export type Category = (typeof CATEGORIES)[number];
|
||||
|
||||
/** What the catalogue needs to know about an item. */
|
||||
export interface CatalogEntry {
|
||||
type: string;
|
||||
/** The built-in group ("living", "kitchen" …) or the pack id ("nextfloor.a_kueche"). */
|
||||
source: string;
|
||||
/** Item id inside its pack, or the built-in type. */
|
||||
id: string;
|
||||
/** Size in metres [w, d, h]. */
|
||||
size: readonly [number, number, number];
|
||||
lamp?: boolean;
|
||||
electric?: boolean;
|
||||
vehicle?: boolean;
|
||||
climate?: boolean;
|
||||
}
|
||||
|
||||
// built-in types first: their group says little ("living" holds sofas and plants), so each type is named
|
||||
const BUILT_IN: Record<string, Category> = {
|
||||
sofa: "seating",
|
||||
armchair: "seating",
|
||||
stool: "seating",
|
||||
chair: "seating",
|
||||
bench: "seating",
|
||||
corner_bench: "seating",
|
||||
bar_stool: "seating",
|
||||
office_chair: "office",
|
||||
coffee_table: "tables",
|
||||
table: "tables",
|
||||
table_round: "tables",
|
||||
desk: "office",
|
||||
worktop: "kitchen",
|
||||
tv_board: "media",
|
||||
tv_wall: "media",
|
||||
sideboard: "storage",
|
||||
shelf: "storage",
|
||||
tall_cabinet: "storage",
|
||||
wardrobe: "storage",
|
||||
dresser: "storage",
|
||||
nightstand: "beds",
|
||||
coat_rack: "storage",
|
||||
plant: "plants",
|
||||
rug: "decor",
|
||||
kitchen: "kitchen",
|
||||
kitchen_wall: "kitchen",
|
||||
kitchen_tall: "kitchen",
|
||||
island: "kitchen",
|
||||
sink: "kitchen",
|
||||
stove: "kitchen",
|
||||
dishwasher: "appliances",
|
||||
fridge: "appliances",
|
||||
washer: "appliances",
|
||||
dryer: "appliances",
|
||||
robot_vacuum: "appliances",
|
||||
bed: "beds",
|
||||
bunk_bed: "beds",
|
||||
bathtub: "bath",
|
||||
shower: "bath",
|
||||
wc: "bath",
|
||||
washbasin: "bath",
|
||||
radiator: "climate",
|
||||
stairs: "building",
|
||||
parking: "vehicles",
|
||||
ceiling_fan: "lights",
|
||||
};
|
||||
|
||||
// pack items by words in their id, checked in this order (the first hit wins)
|
||||
const RULES: [RegExp, Category][] = [
|
||||
[/xmas|advent|window_star|candle_arch|reindeer|pumpkin|easter|snowman|gift_pile|lights_outdoor/, "season"],
|
||||
[/^frame_|^canvas$|^poster$|picture_ledge/, "pictures"],
|
||||
[/piano|drum_kit|guitar|synth|mic_stand|vinyl|easel|studio_monitor|mixing_desk/, "music"],
|
||||
[/lamp|pendant|light_pillar|light_bars|mood_spot|ceiling_panel|garden_spots|wall_light|light_cove|niche_led|shelf_led|monitor_light|workshop_light|painting_light|cabinet_light|moon_light|torch|lantern|ceiling_fan_light/, "lights"],
|
||||
[/cat_|dog_|pet_|litter|scratch|hamster|rabbit|bird_cage|small_animal|aquarium|terrarium/, "pets"],
|
||||
[/stairs|steps|landing|rail_|column|pilaster|beam|chimney|glass_wall|sliding_wall|half_wall|platform|niche_shelf|window_seat|divider_slats|gallery/, "building"],
|
||||
[/tree|shrub|conifer|hedge|brush|monstera|plant|herb_garden|herb_planter|flower|raised_bed|greenhouse|ficus|cactus|bonsai|living_wall|vertical_garden/, "plants"],
|
||||
[/kids|toy|teepee|(^|_)play_|rocking_horse|ball_pit|house_bed|cot\b|^cot|crib|changing_table|baby|loft_bed|star_projector|moon_light/, "kids"],
|
||||
[/treadmill|fitness|power_rack|rowing|rower|spin_bike|dumbbell|punching|yoga|elliptical|gym|exercise|wall_bars|bike_trainer|kettlebell|weight_bench|massage_chair/, "fitness"],
|
||||
[/heat_pump|boiler|buffer_tank|manifold|ventilation|radiator|towel_heater|thermostat|air_purifier|humidifier|dehumidifier|tower_fan|ceiling_fan|hot_water|water_softener|water_pump|fireplace|wood_stove|patio_heater|sauna|oil_|expansion_vessel|water_tank|infrared|cold_bath/, "climate"],
|
||||
[/wallbox|inverter|battery|solar|meter|fuse_box|grid/, "energy"],
|
||||
[/workbench|tool_|compressor|drill|tyre|paint_cabinet|heavy_shelf|shelf_rack|garage_opener|workshop|bike_stand|bike_holder|bike_rack|lawn_mower|mower|welder|ev_bike_charger|tool_chest|parts_cabinet/, "workshop"],
|
||||
[/speaker|subwoofer|soundbar|receiver|turntable|record|game_console|multiroom|hifi|cinema|acoustic|bass_trap|popcorn|projector|projection|screen|display_|smart_display|media|tv|arcade|star_ceiling|av_/, "media"],
|
||||
[/desk|office|filing|whiteboard|monitor|bookcase|phone_booth|sim_cockpit|chair_gaming|gaming/, "office"],
|
||||
[/server|nas|router|wifi|access_point|network|printer|filament|tower_pc|smoke_detector|siren|baby_monitor|sunrise_clock|light_switch|socket|co_detector|presence_|water_leak|air_quality|doorbell/, "tech"],
|
||||
[/grill|lounge|lounger|parasol|pergola|hot_tub|fire_bowl|torch|lantern|play_tower|garden|trampoline|sprinkler|valve|rain_barrel|outdoor|hammock|(^|_)pool|swing|bin_box|^bin_|mailbox|rotary_line|kamado|pizza_oven|fire_pit|sandbox|wood_pile|bird_house|cistern|pond|water_feature|beach_chair/, "garden"],
|
||||
[/vanity_\d|vanity_double|double_vanity|basin|bath|shower|toilet|bidet|towel|mirror_cabinet|mirror_round|mirror_80|mirror_led|whirlpool|washer_under|laundry|urinal|wt_\d|handtuch|seife|wc/, "bath"],
|
||||
[/fridge|freezer|dishwasher|washer|dryer|microwave|coffee_machine|kettle|toaster|mixer|oven|steam|vacuum|ironing|drying_rack|trash|water_cooler|drip_tray|espresso|air_fryer|water_bar|thermo_cooker/, "appliances"],
|
||||
[/base_|drawer_|sink|hob|cooker|hood|pantry|kitchen|island|breakfast_bar|wall_\d|wall_glass|wall_corner|row_|spice|cabinet_light|trolley|bar_cart|utility_sink/, "kitchen"],
|
||||
[/bed|boxspring|futon|nightstand|canopy|mattress/, "beds"],
|
||||
[/sofa|chair|armchair|stool|bench|pouf|bean_bag|recliner|wingback|chaise|seat|ektorp|poang|cosy_corner|swing_bench|hanging_chair|nook|floor_cushion|tatami/, "seating"],
|
||||
[/table|dining|coffee_|side_round|lack_|^console$|bekant|alex/, "tables"],
|
||||
[/wardrobe|closet|clothes_rail|chest|dresser|shelf|cabinet|sideboard|lowboard|highboard|kallax|billy|ivar|pax|besta|cube_|coat_stand|shoe_bench|divider|display_cabinet|wall_unit|malm_chest|locker/, "storage"],
|
||||
];
|
||||
|
||||
/** The category of an item. */
|
||||
export function categoryOf(entry: CatalogEntry): Category {
|
||||
if (entry.vehicle) return "vehicles";
|
||||
if (entry.climate) return "climate";
|
||||
if (!entry.type.startsWith("pack:")) return entry.lamp ? "lights" : (BUILT_IN[entry.type] ?? "decor");
|
||||
// a glowing item (an aquarium, a fireplace) has a light too, so what it is decides before that it glows
|
||||
const hit = RULES.find(([pattern]) => pattern.test(entry.id));
|
||||
return hit ? hit[1] : entry.lamp ? "lights" : "decor";
|
||||
}
|
||||
|
||||
// room names in German and English, and what belongs there besides lights (always offered)
|
||||
const ROOMS: [RegExp, Category[]][] = [
|
||||
[/k(u|ü)che|kitchen|kochen/, ["kitchen", "appliances", "tables", "seating", "storage", "plants", "decor"]],
|
||||
[/wohn|living|lounge|salon/, ["seating", "tables", "storage", "media", "plants", "decor", "climate", "tech"]],
|
||||
[/\bess|dining/, ["tables", "seating", "storage", "plants", "decor", "media"]],
|
||||
[/schlaf|bed|gast|guest/, ["beds", "storage", "seating", "tables", "decor", "plants", "climate", "media"]],
|
||||
[/kind|kids|child|baby|spiel|play|nursery/, ["kids", "beds", "storage", "seating", "tables", "decor"]],
|
||||
[/bad|bath|wc|toilet|dusch|shower|sauna/, ["bath", "appliances", "storage", "climate", "plants"]],
|
||||
[/b(u|ü)ro|office|arbeit|study|work/, ["office", "tech", "storage", "seating", "tables", "plants"]],
|
||||
[/kino|cinema|media|game|gaming|hifi/, ["media", "seating", "tables", "storage", "office"]],
|
||||
[/fitness|gym|sport|training/, ["fitness", "media", "storage", "climate"]],
|
||||
[/garage|carport|stellplatz|parking/, ["vehicles", "workshop", "energy", "storage", "garden"]],
|
||||
[/werkstatt|workshop|hobby|keller|cellar|basement|lager|storage/, ["workshop", "storage", "appliances", "energy", "climate", "fitness", "tech"]],
|
||||
[/hauswirtschaft|hwr|utility|laundry|wasch|technik|heiz|boiler/, ["appliances", "climate", "energy", "storage", "tech", "bath"]],
|
||||
[/flur|diele|hall|entr|eingang|corridor|treppe|stair/, ["storage", "seating", "decor", "plants", "building"]],
|
||||
[/garten|garden|terrass|terrace|balkon|balcony|patio|hof|yard|pool/, ["garden", "plants", "seating", "tables", "pets", "kids"]],
|
||||
];
|
||||
|
||||
/** The categories that fit a room by its name; null when the name says nothing (then the whole library shows). */
|
||||
export function roomCategories(roomName: string | null | undefined): Set<Category> | null {
|
||||
const name = (roomName ?? "").toLowerCase();
|
||||
const hit = ROOMS.find(([pattern]) => pattern.test(name));
|
||||
return hit ? new Set<Category>(["lights", ...hit[1]]) : null;
|
||||
}
|
||||
|
||||
/** The category a room is mostly furnished from (a kitchen's kitchen units, a bedroom's beds); null when the name says nothing. */
|
||||
export function mainCategory(roomName: string | null | undefined): Category | null {
|
||||
const name = (roomName ?? "").toLowerCase();
|
||||
return ROOMS.find(([pattern]) => pattern.test(name))?.[1][0] ?? null;
|
||||
}
|
||||
|
||||
/** Items that stand outside: garden, plants, vehicles. */
|
||||
export const isOutdoorCategory = (category: Category): boolean => category === "garden" || category === "plants" || category === "vehicles";
|
||||
|
||||
/** One card of the library: an item, or one model in several sizes (the first is the one placed unless a size is picked). */
|
||||
export interface CatalogCard {
|
||||
key: string;
|
||||
category: Category;
|
||||
entries: CatalogEntry[];
|
||||
}
|
||||
|
||||
const sizeSuffix = /_(\d+(?:x\d+)?)$/;
|
||||
|
||||
/** Folds items of one model in several sizes (vanity_60, vanity_80 …) into one card; built-in types and vehicles stay on their own. */
|
||||
export function cardsOf(entries: readonly CatalogEntry[]): CatalogCard[] {
|
||||
const cards = new Map<string, CatalogCard>();
|
||||
for (const entry of entries) {
|
||||
const category = categoryOf(entry);
|
||||
const base = entry.type.startsWith("pack:") && !entry.vehicle ? entry.id.replace(sizeSuffix, "") : entry.id;
|
||||
const key = `${entry.source}:${base}`;
|
||||
const card = cards.get(key);
|
||||
if (card && card.category === category) card.entries.push(entry);
|
||||
else cards.set(card ? `${key}:${entry.id}` : key, { key: card ? `${key}:${entry.id}` : key, category, entries: [entry] });
|
||||
}
|
||||
for (const card of cards.values()) card.entries.sort((a, b) => a.size[0] - b.size[0] || a.size[1] - b.size[1]);
|
||||
return [...cards.values()];
|
||||
}
|
||||
|
||||
/** The label of a size chip: the width in cm, or the size in the item's id (2x2, 4x4) when several share a width. */
|
||||
export function sizeLabel(entry: CatalogEntry, all: readonly CatalogEntry[]): string {
|
||||
const cm = (m: number) => Math.round(m * 100);
|
||||
const sameWidth = all.some((e) => e !== entry && cm(e.size[0]) === cm(entry.size[0]));
|
||||
return sameWidth ? (sizeSuffix.exec(entry.id)?.[1] ?? `${cm(entry.size[0])}×${cm(entry.size[2])}`) : `${cm(entry.size[0])}`;
|
||||
}
|
||||
|
||||
/** The list a type was used in, with the newest first and at most `max` long. */
|
||||
export function withRecent(recent: readonly string[], type: string, max = 12): string[] {
|
||||
return [type, ...recent.filter((t) => t !== type)].slice(0, max);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture, Placement } from "../../../model.ts";
|
||||
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "./device-list.ts";
|
||||
|
||||
const pin = (id: string, x: number, z: number): Placement => ({ entity_id: id, x, z, y: null });
|
||||
const lamp = (id: string, entity: string, x: number, z: number): Furniture => ({ id, type: "lamp_ceiling", x, z, rotation: 0, w: 0.3, d: 0.3, h: 0.1, variant: null, entity });
|
||||
|
||||
test("pins and ceiling lamps inside the room count as placed in it", () => {
|
||||
const room = box("a", 0, 0, 4, 4);
|
||||
const floor = floorWith([room, box("b", 4, 0, 8, 4)], { placements: [pin("sensor.in", 1, 1), pin("sensor.out", 6, 1)], furniture: [lamp("l1", "light.in", 2, 2), lamp("l2", "light.out", 6, 2), { ...lamp("l3", "", 1, 1), entity: null }] });
|
||||
assert.deepEqual([...placedInRoom(floor, room)].sort(), ["light.in", "sensor.in"]);
|
||||
assert.deepEqual([...placedInRoom(undefined, room)], []);
|
||||
});
|
||||
|
||||
test("entities in other rooms, on any floor, are listed with that room's name", () => {
|
||||
const a = box("a", 0, 0, 4, 4);
|
||||
const upper = floorWith([{ ...box("c", 0, 0, 4, 4), name: "Attic" }], { id: "u", placements: [pin("sensor.up", 1, 1)] } as never);
|
||||
const ground = floorWith([a, { ...box("b", 4, 0, 8, 4), name: "Kitchen" }], { placements: [pin("sensor.here", 1, 1), pin("sensor.k", 6, 1)], furniture: [lamp("l", "light.k", 7, 2)] });
|
||||
const doc = { floors: [ground, upper] } as unknown as Building;
|
||||
const elsewhere = placedElsewhere(doc, a);
|
||||
assert.deepEqual([...elsewhere.entries()].sort(), [["light.k", "Kitchen"], ["sensor.k", "Kitchen"], ["sensor.up", "Attic"]]);
|
||||
assert.equal(elsewhere.has("sensor.here"), false);
|
||||
});
|
||||
|
||||
test("toggling adds an id or takes it out", () => {
|
||||
assert.deepEqual(withToggled(undefined, "a"), ["a"]);
|
||||
assert.deepEqual(withToggled(["a", "b"], "a"), ["b"]);
|
||||
assert.deepEqual(withToggled(["a"], "b"), ["a", "b"]);
|
||||
});
|
||||
|
||||
test("the search matches any of the texts, ignoring case, and an empty search matches all", () => {
|
||||
assert.equal(matchesQuery("", "x"), true);
|
||||
assert.equal(matchesQuery(" ", undefined), true);
|
||||
assert.equal(matchesQuery("lamp", "Floor Lamp", "light.x"), true);
|
||||
assert.equal(matchesQuery("LIGHT.X", "Floor Lamp", "light.x"), true);
|
||||
assert.equal(matchesQuery("fan", "Floor Lamp", "light.x"), false);
|
||||
});
|
||||
|
||||
test("options are ordered by rank and keep their order within a rank", () => {
|
||||
const options = [{ id: "c" }, { id: "a" }, { id: "b" }, { id: "d" }];
|
||||
assert.deepEqual(rankedBy(options, (id) => (id === "b" || id === "d" ? 0 : 1)).map((o) => o.id), ["b", "d", "c", "a"]);
|
||||
});
|
||||
|
||||
test("taking the first entries of several groups reports what did not fit", () => {
|
||||
const { taken, left } = takeFirst([{ ids: [1, 2, 3] }, { ids: [4, 5] }, { ids: [6] }], 4);
|
||||
assert.deepEqual(taken, [[1, 2, 3], [4], []]);
|
||||
assert.equal(left, 2);
|
||||
assert.deepEqual(takeFirst([{ ids: [1] }], 10), { taken: [[1]], left: 0 });
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
// What the device list of a room needs to know: which entities are placed in it, which in another room, and how options are ranked.
|
||||
|
||||
import { isLamp, pointInPolygon, type Building, type Floor, type Room } from "../../../model.ts";
|
||||
|
||||
/** An entity placed in the room: as a device pin, or as the light of a lamp. */
|
||||
export function placedInRoom(floor: Floor | undefined, room: Room): Set<string> {
|
||||
const placed = new Set<string>();
|
||||
for (const p of floor?.placements ?? []) if (pointInPolygon([p.x, p.z], room.points)) placed.add(p.entity_id);
|
||||
for (const m of floor?.furniture ?? []) if (isLamp(m.type) && m.entity && pointInPolygon([m.x, m.z], room.points)) placed.add(m.entity);
|
||||
return placed;
|
||||
}
|
||||
|
||||
/** Entities that are placed in a room other than this one, with the name of that room: placing them here moves them. */
|
||||
export function placedElsewhere(doc: Building, room: Room): Map<string, string> {
|
||||
const elsewhere = new Map<string, string>();
|
||||
for (const floor of doc.floors) {
|
||||
const spots: [string, number, number][] = [
|
||||
...floor.placements.map((p): [string, number, number] => [p.entity_id, p.x, p.z]),
|
||||
...floor.furniture.filter((m) => isLamp(m.type) && m.entity).map((m): [string, number, number] => [m.entity!, m.x, m.z]),
|
||||
];
|
||||
for (const [id, x, z] of spots) {
|
||||
const home = floor.rooms.find((r) => pointInPolygon([x, z], r.points));
|
||||
if (home && home.id !== room.id) elsewhere.set(id, home.name);
|
||||
}
|
||||
}
|
||||
return elsewhere;
|
||||
}
|
||||
|
||||
/** A list with an id added, or removed when it is there. Empty lists give undefined in the saved plan, so callers decide. */
|
||||
export const withToggled = (list: readonly string[] | undefined, id: string): string[] => ((list ?? []).includes(id) ? (list ?? []).filter((x) => x !== id) : [...(list ?? []), id]);
|
||||
|
||||
/** Whether an entity matches what was typed in the search box: its name (without the room's name), its id or its area. Empty matches all. */
|
||||
export function matchesQuery(query: string, ...texts: (string | undefined)[]): boolean {
|
||||
const q = query.trim().toLowerCase();
|
||||
return !q || texts.some((t) => (t ?? "").toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
/** Options for a climate sensor ordered by how likely they are the room's own: its area first, then the dedicated sensors of a room. */
|
||||
export function rankedBy<T extends { id: string }>(options: readonly T[], rank: (id: string) => number): T[] {
|
||||
return options.map((o) => ({ o, r: rank(o.id) })).sort((a, b) => a.r - b.r).map(({ o }) => o);
|
||||
}
|
||||
|
||||
/** Takes the first `limit` entries of areas' entity lists in order, and reports how many did not fit. */
|
||||
export function takeFirst<T>(groups: readonly { ids: readonly T[] }[], limit: number): { taken: T[][]; left: number } {
|
||||
let room = limit;
|
||||
let left = 0;
|
||||
const taken = groups.map((g) => {
|
||||
const part = g.ids.slice(0, Math.max(0, room));
|
||||
room -= part.length;
|
||||
left += g.ids.length - part.length;
|
||||
return [...part];
|
||||
});
|
||||
return { taken, left };
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { aimReach, dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./drags.ts";
|
||||
|
||||
test("the pointer's distance is counted in whole grid steps", () => {
|
||||
assert.deepEqual(steppedDelta([0, 0], [0.26, -0.24], 0.1), [0.30000000000000004, -0.2]);
|
||||
assert.equal(dragStep(0.1, false), 0.1);
|
||||
assert.equal(dragStep(0.1, true), 0.01);
|
||||
});
|
||||
|
||||
test("a drag starts once the pointer has left the circle around its start", () => {
|
||||
assert.equal(hasLeftStart([0, 0], [3, 3]), false);
|
||||
assert.equal(hasLeftStart([0, 0], [4, 4]), true);
|
||||
assert.equal(hasLeftStart([0, 0], [3, 3], 4), true);
|
||||
});
|
||||
|
||||
test("with Shift a wall is held straight along the axis the pointer is nearer to", () => {
|
||||
assert.deepEqual(straightEnd([0, 0], [5, 1], true), [5, 0]);
|
||||
assert.deepEqual(straightEnd([0, 0], [1, 5], true), [0, 5]);
|
||||
assert.deepEqual(straightEnd([0, 0], [5, 1], false), [5, 1]);
|
||||
});
|
||||
|
||||
test("a piece lands on the grid after the pointer moved it", () => {
|
||||
assert.deepEqual(gridPositionAfter([1.04, 2], [0, 0], [0.52, 0.3], 0.1), [1.6, 2.3]);
|
||||
assert.deepEqual(shifted([1, 1], [0.0004, 2]), [1, 3]);
|
||||
});
|
||||
|
||||
test("facing: 0° looks towards +z, and the angle turns with the pointer in steps", () => {
|
||||
assert.equal(facingAngle([0, 0], [0, 5], 15), 0);
|
||||
assert.equal(facingAngle([0, 0], [-5, 0], 15), 90);
|
||||
assert.equal(facingAngle([0, 0], [0, -5], 15), 180);
|
||||
assert.equal(facingAngle([0, 0], [5, 0], 15), 270);
|
||||
assert.equal(facingAngle([0, 0], [-5, 0.3], 1), 87);
|
||||
});
|
||||
|
||||
test("the ground field's heading counts from up in the plan", () => {
|
||||
assert.equal(headingAngle([0, 0], [0, -5], 15), 0);
|
||||
assert.equal(headingAngle([0, 0], [5, 0], 15), 90);
|
||||
assert.equal(headingAngle([0, 0], [-5, 0], 15), -90);
|
||||
});
|
||||
|
||||
test("a camera's reach follows the pointer's distance within its limits", () => {
|
||||
assert.equal(aimReach([0, 0], [3, 4]), 5);
|
||||
assert.equal(aimReach([0, 0], [0.1, 0]), 0.5);
|
||||
assert.equal(aimReach([0, 0], [100, 0]), 50);
|
||||
});
|
||||
|
||||
test("dragging a corner of a rectangular area drags its neighbours along one axis each", () => {
|
||||
const rect: [number, number][] = [[0, 0], [4, 0], [4, 2], [0, 2]];
|
||||
assert.deepEqual(outlineWithCornerAt(rect, 2, [5.0004, 3]), [[0, 0], [5, 0], [5, 3], [0, 3]]);
|
||||
const triangle: [number, number][] = [[0, 0], [4, 0], [0, 3]];
|
||||
assert.deepEqual(outlineWithCornerAt(triangle, 1, [6, 1]), [[0, 0], [6, 1], [0, 3]]);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The arithmetic behind dragging in the plan: given where the drag started and where the pointer is now, what the thing dragged
|
||||
// becomes. All of these are pure, so the gesture code only has to pick the right one.
|
||||
|
||||
import { isAxisRect, type Vec2 } from "../../../model.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
/** How far the pointer moved from the start, in whole steps of the grid (a finer step with Alt). */
|
||||
export function steppedDelta(start: Vec2, now: Vec2, step: number): Vec2 {
|
||||
return [Math.round((now[0] - start[0]) / step) * step, Math.round((now[1] - start[1]) / step) * step];
|
||||
}
|
||||
|
||||
/** The grid step of a drag: the plan's grid, or 1 cm while Alt is held. */
|
||||
export const dragStep = (grid: number, fine: boolean): number => (fine ? 0.01 : grid);
|
||||
|
||||
/** A drag counts as a drag once the pointer has left a small circle around where it went down. */
|
||||
export const hasLeftStart = (a: readonly [number, number], b: readonly [number, number], pixels = 5): boolean => Math.hypot(a[0] - b[0], a[1] - b[1]) >= pixels;
|
||||
|
||||
/** The end of a wall being drawn. With Shift it is held straight: horizontal or vertical, whichever the pointer is nearer to. */
|
||||
export function straightEnd(start: Vec2, end: Vec2, straight: boolean): Vec2 {
|
||||
if (!straight) return end;
|
||||
return Math.abs(end[0] - start[0]) > Math.abs(end[1] - start[1]) ? [end[0], start[1]] : [start[0], end[1]];
|
||||
}
|
||||
|
||||
/** A point moved by a distance, rounded to a millimetre. */
|
||||
export const shifted = (p: Vec2, by: Vec2): Vec2 => [thousandths(p[0] + by[0]), thousandths(p[1] + by[1])];
|
||||
|
||||
/**
|
||||
* Where a piece that was at `from` ends up when the pointer moved from `start` to `now`: its own position moved by that distance and
|
||||
* then put on the grid.
|
||||
*/
|
||||
export function gridPositionAfter(from: Vec2, start: Vec2, now: Vec2, step: number): Vec2 {
|
||||
return [thousandths(Math.round((from[0] + now[0] - start[0]) / step) * step), thousandths(Math.round((from[1] + now[1] - start[1]) / step) * step)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The angle (degrees, 0 to 360) that turns the front of a piece at `centre` towards the pointer, in steps (15° normally, 1° with Alt).
|
||||
* Pieces face +z at 0°, so the angle is measured from there.
|
||||
*/
|
||||
export function facingAngle(centre: Vec2, pointer: Vec2, step: number): number {
|
||||
const raw = (Math.atan2(-(pointer[0] - centre[0]), pointer[1] - centre[1]) * 180) / Math.PI;
|
||||
return (((Math.round(raw / step) * step) % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
/** The same for the handle of a ground solar field, which points the other way round (up in the plan is 0°). */
|
||||
export function headingAngle(centre: Vec2, pointer: Vec2, step: number): number {
|
||||
const raw = (Math.atan2(pointer[0] - centre[0], -(pointer[1] - centre[1])) * 180) / Math.PI;
|
||||
return Math.round(raw / step) * step;
|
||||
}
|
||||
|
||||
/** How far a camera's view reaches while its handle is dragged: the distance to the pointer in tenths of a metre, between 0.5 and 50. */
|
||||
export const aimReach = (centre: Vec2, pointer: Vec2): number => Math.min(50, Math.max(0.5, Math.round(Math.hypot(pointer[0] - centre[0], pointer[1] - centre[1]) * 10) / 10));
|
||||
|
||||
/**
|
||||
* The outline of an outdoor area after one corner was dragged to `to`. A rectangle stays a rectangle: the corners that share an x or a
|
||||
* z with the dragged one follow along that axis.
|
||||
*/
|
||||
export function outlineWithCornerAt(points: readonly Vec2[], index: number, to: Vec2): Vec2[] {
|
||||
const keepsRectangle = isAxisRect([...points]);
|
||||
const was = points[index];
|
||||
const target: Vec2 = [thousandths(to[0]), thousandths(to[1])];
|
||||
return points.map((p, j): Vec2 => {
|
||||
if (j === index) return target;
|
||||
if (!keepsRectangle) return [p[0], p[1]];
|
||||
return [Math.abs(p[0] - was[0]) < 1e-6 ? target[0] : p[0], Math.abs(p[1] - was[1]) < 1e-6 ? target[1] : p[1]];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box } from "../../../entities/fixtures.ts";
|
||||
import type { Room } from "../../../model.ts";
|
||||
import { clearWallSlope, cutEdge, edgeLength, setWallSlope, joinAtCut, moveCut, setPartHeight, setWallHeight, setWallThickness, thicknessFromTyped } from "./edges.ts";
|
||||
|
||||
const room = (extra: Partial<Room> = {}): Room => ({ ...box("r", 0, 0, 6, 4), ...extra });
|
||||
|
||||
test("edge lengths follow the corners round the room", () => {
|
||||
const r = room();
|
||||
assert.deepEqual([0, 1, 2, 3].map((i) => edgeLength(r, i)), [6, 4, 6, 4]);
|
||||
});
|
||||
|
||||
test("a wall height is set per edge, and a list with nothing in it disappears", () => {
|
||||
const r = room();
|
||||
setWallHeight(r, 1, 1.2);
|
||||
assert.deepEqual(r.wall_heights, [null, 1.2, null, null]);
|
||||
setWallHeight(r, 1, null);
|
||||
assert.equal(r.wall_heights, undefined);
|
||||
});
|
||||
|
||||
test("a wall of several parts keeps a height per part, and equal parts collapse to one height", () => {
|
||||
const r = room();
|
||||
setPartHeight(r, 0, 1, 1, 2);
|
||||
assert.deepEqual(r.wall_heights![0], [null, 1]);
|
||||
setPartHeight(r, 0, 0, 1, 2);
|
||||
assert.equal(r.wall_heights![0], 1);
|
||||
setPartHeight(r, 0, 0, null, 2);
|
||||
setPartHeight(r, 0, 1, null, 2);
|
||||
assert.equal(r.wall_heights, undefined);
|
||||
// a single height spreads over the parts when one of them changes
|
||||
const s = room({ wall_heights: [2, null, null, null] });
|
||||
setPartHeight(s, 0, 1, 0.5, 3);
|
||||
assert.deepEqual(s.wall_heights![0], [2, 0.5, 2]);
|
||||
});
|
||||
|
||||
test("cutting an edge puts the cut in the middle of the piece, and short pieces are left alone", () => {
|
||||
const r = room();
|
||||
assert.equal(cutEdge(r, 0, undefined, [0]), true);
|
||||
assert.deepEqual(r.wall_splits![0], [3]);
|
||||
assert.equal(cutEdge(r, 0, 1, [0, 3]), true, "the part after the cut is 3 m long");
|
||||
assert.deepEqual(r.wall_splits![0], [3, 4.5]);
|
||||
const short = room({ points: [[0, 0], [0.3, 0], [0.3, 4], [0, 4]] });
|
||||
assert.equal(cutEdge(short, 0, undefined, [0]), false);
|
||||
assert.equal(short.wall_splits, undefined);
|
||||
});
|
||||
|
||||
test("a new part starts with the height of the part it was cut from", () => {
|
||||
const r = room({ wall_heights: [[1, 2], null, null, null] });
|
||||
cutEdge(r, 0, 1, [0, 2]);
|
||||
assert.deepEqual(r.wall_heights![0], [1, 2, 2]);
|
||||
});
|
||||
|
||||
test("a cut moves along the edge but keeps clear of the ends and of other cuts", () => {
|
||||
const r = room({ wall_splits: [[2, 4], null, null, null] });
|
||||
moveCut(r, 0, 2, 2.504, [0, 2, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [2.5, 4]);
|
||||
moveCut(r, 0, 2.5, 3.95, [0, 2.5, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [2.5, 4], "too close to the other cut: stays");
|
||||
moveCut(r, 0, 2.5, -3, [0, 2.5, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [0.1, 4]);
|
||||
moveCut(r, 0, 4, 99, [0, 0.1, 4]);
|
||||
assert.deepEqual(r.wall_splits![0], [0.1, 5.9]);
|
||||
});
|
||||
|
||||
test("joining at a cut drops it, merges the part's height into the one before, and cleans up", () => {
|
||||
const r = room({ wall_splits: [[3], null, null, null], wall_heights: [[1, 2], null, null, null] });
|
||||
joinAtCut(r, 0, 3, 1);
|
||||
assert.equal(r.wall_splits, undefined);
|
||||
assert.equal(r.wall_heights![0], 1);
|
||||
const two = room({ wall_splits: [[2, 4], null, null, null], wall_heights: [[1, 2, 3], null, null, null] });
|
||||
joinAtCut(two, 0, 2, 1);
|
||||
assert.deepEqual(two.wall_splits![0], [4]);
|
||||
assert.deepEqual(two.wall_heights![0], [1, 3]);
|
||||
});
|
||||
|
||||
test("a wall thickness is stored per edge and reset with null", () => {
|
||||
const r = room();
|
||||
setWallThickness(r, 2, 0.4);
|
||||
assert.deepEqual(r.wall_thickness, [null, null, 0.4, null]);
|
||||
setWallThickness(r, 2, null);
|
||||
assert.equal(r.wall_thickness, undefined);
|
||||
assert.equal(thicknessFromTyped(0.2449, 0.245), null);
|
||||
assert.equal(thicknessFromTyped(0.3, 0.12), 0.3);
|
||||
assert.equal(thicknessFromTyped(9, 0.12), 1.5);
|
||||
assert.equal(thicknessFromTyped(0, 0.12), 0.02);
|
||||
});
|
||||
|
||||
test("a wall slopes from its start to its end height; a level height, parts or clearing end the slope", () => {
|
||||
const r = room();
|
||||
setWallSlope(r, 1, 2.5, 4.7);
|
||||
assert.deepEqual([r.wall_heights, r.wall_slopes], [[null, 2.5, null, null], [null, 4.7, null, null]]);
|
||||
// heights are kept in sane limits
|
||||
setWallSlope(r, 1, 0, 99);
|
||||
assert.deepEqual([r.wall_heights?.[1], r.wall_slopes?.[1]], [0.05, 30]);
|
||||
// a level height ends the slope, and with nothing else set the lists disappear
|
||||
setWallHeight(r, 1, null);
|
||||
assert.deepEqual([r.wall_heights, r.wall_slopes], [undefined, undefined]);
|
||||
// heights per part and a slope exclude each other
|
||||
setWallSlope(r, 0, 2, 3);
|
||||
setPartHeight(r, 0, 1, 1.5, 2);
|
||||
assert.equal(r.wall_slopes, undefined);
|
||||
assert.deepEqual(r.wall_heights?.[0], [2, 1.5]);
|
||||
});
|
||||
|
||||
test("levelling a slope keeps its start height, and the full floor height when that is not lower", () => {
|
||||
const r = room();
|
||||
setWallSlope(r, 2, 1.2, 3);
|
||||
clearWallSlope(r, 2, 2.5);
|
||||
assert.deepEqual([r.wall_heights?.[2], r.wall_slopes], [1.2, undefined]);
|
||||
setWallSlope(r, 2, 4.7, 2.5);
|
||||
clearWallSlope(r, 2, 2.5);
|
||||
assert.equal(r.wall_heights, undefined, "from the floor height up it is a full wall again");
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
// Per-wall settings of a room: the height of each wall (or of each part of a wall that another room splits), the points where a wall
|
||||
// is cut by hand, and the thickness of one wall. All functions change the room they are given, which is a copy made by the editor.
|
||||
|
||||
import type { Room } from "../../../model.ts";
|
||||
|
||||
type Height = number | null | (number | null)[];
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const hundredths = (v: number) => Math.round(v * 100) / 100;
|
||||
|
||||
/** A per-edge list brought to exactly one entry per edge. */
|
||||
function perEdge<T>(list: readonly (T | null)[] | undefined, count: number): (T | null)[] {
|
||||
const out = [...(list ?? [])].slice(0, count);
|
||||
while (out.length < count) out.push(null);
|
||||
return out;
|
||||
}
|
||||
|
||||
const allNull = (list: readonly unknown[]) => list.every((x) => x === null);
|
||||
|
||||
/** The length of an edge of a room. */
|
||||
export function edgeLength(room: Room, edge: number): number {
|
||||
const [a, b] = [room.points[edge], room.points[(edge + 1) % room.points.length]];
|
||||
return Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
}
|
||||
|
||||
/** Sets the height of a whole edge; null is "as high as the floor", and a list with nothing set is dropped. */
|
||||
export function setWallHeight(room: Room, edge: number, height: number | null): void {
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
list[edge] = height;
|
||||
room.wall_heights = allNull(list) ? undefined : (list as Room["wall_heights"]);
|
||||
// a level height ends a slope
|
||||
setSlopeEnd(room, edge, null);
|
||||
}
|
||||
|
||||
function setSlopeEnd(room: Room, edge: number, end: number | null): void {
|
||||
if (end === null && !room.wall_slopes) return;
|
||||
const slopes = perEdge<number>(room.wall_slopes, room.points.length);
|
||||
slopes[edge] = end;
|
||||
room.wall_slopes = allNull(slopes) ? undefined : (slopes as number[]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a wall slope: `start` is its height at the first corner of the edge, `end` at the next one. The top runs straight between them
|
||||
* (a lean-to, clerestory windows); both may be above the floor height. Heights are kept between 5 cm and 30 m.
|
||||
*/
|
||||
export function setWallSlope(room: Room, edge: number, start: number, end: number): void {
|
||||
const [from, to] = [start, end].map((h) => Math.min(30, Math.max(0.05, thousandths(h))));
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
list[edge] = from;
|
||||
room.wall_heights = list as Room["wall_heights"];
|
||||
setSlopeEnd(room, edge, to);
|
||||
}
|
||||
|
||||
/** Levels a sloping wall again: it keeps its start height, and the full floor height when that is not lower. */
|
||||
export function clearWallSlope(room: Room, edge: number, floorHeight: number): void {
|
||||
const start = room.wall_heights?.[edge];
|
||||
setSlopeEnd(room, edge, null);
|
||||
if (typeof start === "number" && start >= floorHeight - 0.005) setWallHeight(room, edge, null);
|
||||
}
|
||||
|
||||
/** Sets the height of one part of an edge that has several parts. Parts that all end up the same collapse to one height. */
|
||||
export function setPartHeight(room: Room, edge: number, part: number, height: number | null, partCount: number): void {
|
||||
const list = perEdge<Height>(room.wall_heights, room.points.length);
|
||||
const current = list[edge];
|
||||
const parts: (number | null)[] = Array.isArray(current) ? [...current] : new Array<number | null>(partCount).fill(typeof current === "number" ? current : null);
|
||||
while (parts.length < partCount) parts.push(null);
|
||||
parts[part] = height;
|
||||
list[edge] = parts.every((h) => h === parts[0]) ? parts[0] : parts;
|
||||
room.wall_heights = allNull(list) ? undefined : (list as Room["wall_heights"]);
|
||||
// heights per part and a slope over the whole wall exclude each other
|
||||
setSlopeEnd(room, edge, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cuts an edge (or one part of it) in the middle. The new part keeps the height of the one it was cut from. Nothing happens when the
|
||||
* piece is shorter than 40 cm. Returns whether it was cut.
|
||||
*/
|
||||
export function cutEdge(room: Room, edge: number, part: number | undefined, starts: readonly number[]): boolean {
|
||||
const length = edgeLength(room, edge);
|
||||
const from = part === undefined ? 0 : starts[part];
|
||||
const to = part === undefined ? length : (starts[part + 1] ?? length);
|
||||
if (to - from < 0.4) return false;
|
||||
const at = hundredths((from + to) / 2);
|
||||
const splits = perEdge<number[]>(room.wall_splits, room.points.length);
|
||||
splits[edge] = [...(splits[edge] ?? []), at].sort((a, b) => a - b);
|
||||
room.wall_splits = splits as Room["wall_splits"];
|
||||
const heights = room.wall_heights?.[edge];
|
||||
if (Array.isArray(heights)) heights.splice((part ?? 0) + 1, 0, heights[part ?? 0] ?? null);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Moves a cut along its edge, kept 10 cm from the ends and from other cuts (it stays where it was if it would come closer). */
|
||||
export function moveCut(room: Room, edge: number, from: number, to: number, otherStarts: readonly number[]): void {
|
||||
const length = edgeLength(room, edge);
|
||||
const others = otherStarts.filter((s) => Math.abs(s - from) > 1e-3 && s > 0);
|
||||
let at = Math.max(0.1, Math.min(length - 0.1, hundredths(to)));
|
||||
if (others.some((s) => Math.abs(s - at) < 0.1)) at = from;
|
||||
const list = room.wall_splits?.[edge];
|
||||
if (!list) return;
|
||||
const index = list.findIndex((d) => Math.abs(d - from) < 1e-3);
|
||||
if (index >= 0) list[index] = at;
|
||||
list.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/** Takes a cut away: the part behind it joins the one before, whose height stays. */
|
||||
export function joinAtCut(room: Room, edge: number, at: number, part: number): void {
|
||||
const splits = room.wall_splits;
|
||||
if (!splits?.[edge]) return;
|
||||
const left = splits[edge]!.filter((d) => Math.abs(d - at) > 1e-3);
|
||||
splits[edge] = left.length > 0 ? left : null;
|
||||
if (splits.every((l) => !l)) room.wall_splits = undefined;
|
||||
const heights = room.wall_heights?.[edge];
|
||||
if (Array.isArray(heights)) {
|
||||
heights.splice(part, 1);
|
||||
if (heights.every((h) => h === heights[0])) room.wall_heights![edge] = heights[0] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The thickness of one wall; null brings back the thickness of the house for walls of that kind. */
|
||||
export function setWallThickness(room: Room, edge: number, thickness: number | null, part?: number, partCount = 1): void {
|
||||
const list = perEdge<number | (number | null)[]>(room.wall_thickness, room.points.length);
|
||||
if (part === undefined || partCount < 2) list[edge] = thickness;
|
||||
else {
|
||||
// one part of a split edge: the others keep what the edge had
|
||||
const current = list[edge];
|
||||
const parts: (number | null)[] = Array.isArray(current) ? [...current] : new Array<number | null>(partCount).fill(typeof current === "number" ? current : null);
|
||||
while (parts.length < partCount) parts.push(null);
|
||||
parts[part] = thickness;
|
||||
list[edge] = parts.every((v) => v === parts[0]) ? parts[0] : parts;
|
||||
}
|
||||
room.wall_thickness = allNull(list) ? undefined : (list as Room["wall_thickness"]);
|
||||
}
|
||||
|
||||
/** A thickness typed for a wall: kept between 2 cm and 1.5 m, and null when it equals the default. */
|
||||
export function thicknessFromTyped(typed: number, standard: number): number | null {
|
||||
const value = Math.min(1.5, Math.max(0.02, thousandths(typed)));
|
||||
return Math.abs(value - standard) < 0.0005 ? null : value;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, floorWith, hassOf } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import { energyChecklist } from "./energy-checklist.ts";
|
||||
import { importEnergyPrefs } from "./energy-import.ts";
|
||||
|
||||
const device = (id: string, type: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type, x: 0, z: 0, rotation: 0, w: 1, d: 1, h: 1, variant: null, ...extra });
|
||||
const plan = (furniture: Furniture[], energy = {}, solar: unknown[] = []): Building =>
|
||||
({ version: 1, floors: [floorWith([], { furniture })], settings: { roof: { type: "none", solar } }, energy, presence: [] }) as unknown as Building;
|
||||
const none = new Map<string, { power: string | null }>();
|
||||
|
||||
test("an empty plan lists everything to do, with the battery and grid point optional", () => {
|
||||
const rows = energyChecklist(plan([]), none);
|
||||
assert.deepEqual(rows.map((r) => [r.label, r.state]), [["chk_solar_add", "todo"], ["chk_meter_add", "todo"], ["chk_inverter_add", "todo"], ["chk_battery_opt", "opt"], ["chk_grid_opt", "opt"]]);
|
||||
assert.deepEqual(rows[1].target, { kind: "add-device", type: "meter" });
|
||||
});
|
||||
|
||||
test("devices without a sensor ask for one, with a sensor (own or found) they are done", () => {
|
||||
const furniture = [device("m", "meter"), device("i", "inverter"), device("b", "home_battery")];
|
||||
const open = energyChecklist(plan(furniture, {}, [{ id: "f1" }]), none);
|
||||
assert.deepEqual(open.map((r) => r.state), ["ok", "todo", "todo", "todo", "opt"]);
|
||||
assert.equal(open[1].label, "chk_meter_sensor");
|
||||
const done = energyChecklist(plan([device("m", "meter", { power: "sensor.m" }), device("i", "inverter"), device("b", "home_battery", { power: "sensor.b", soc: "sensor.soc" })], {}, [{ id: "f1" }]), new Map([["i", { power: "sensor.found" }]]));
|
||||
assert.deepEqual(done.map((r) => r.state), ["ok", "ok", "ok", "ok", "opt"]);
|
||||
});
|
||||
|
||||
test("sensors chosen in the balance settings count for the devices", () => {
|
||||
const rows = energyChecklist(plan([device("m", "meter"), device("i", "inverter"), device("b", "home_battery")], { grid: "sensor.g", solar: "sensor.s", battery: "sensor.b" }), none);
|
||||
assert.deepEqual(rows.slice(1, 4).map((r) => r.state), ["ok", "ok", "ok"]);
|
||||
});
|
||||
|
||||
test("the inverter row points at the first inverter that still lacks a sensor", () => {
|
||||
const furniture = [device("i1", "inverter", { power: "sensor.a" }), device("i2", "inverter")];
|
||||
const row = energyChecklist(plan(furniture), none)[2];
|
||||
assert.equal(row.state, "todo");
|
||||
assert.ok(row.target.kind === "device" && row.target.item.id === "i2");
|
||||
});
|
||||
|
||||
function importSetup(furniture: Furniture[], statesOk = true) {
|
||||
const hass = Object.assign(
|
||||
hassOf(
|
||||
[entity("sensor.grid_power", "10", { device_class: "power" }), entity("sensor.pv_power", "5", { device_class: "power" })],
|
||||
{ "sensor.grid_power": { device_id: "dg" }, "sensor.pv_power": { device_id: "dp" }, "sensor.grid_energy": { device_id: "dg" }, "sensor.pv_energy": { device_id: "dp" } },
|
||||
),
|
||||
{
|
||||
callWS: async () => {
|
||||
if (!statesOk) throw new Error("no");
|
||||
return { energy_sources: [{ type: "grid", flow_from: [{ stat_energy_from: "sensor.grid_energy" }] }, { type: "solar", stat_energy_from: "sensor.pv_energy" }] };
|
||||
},
|
||||
},
|
||||
);
|
||||
const doc = plan(furniture);
|
||||
const set: string[] = [];
|
||||
const added: string[] = [];
|
||||
const deps = {
|
||||
hass,
|
||||
doc: () => doc,
|
||||
canAdd: () => true,
|
||||
addDevice: (type: string) => {
|
||||
added.push(type);
|
||||
doc.floors[0].furniture.push(device(`new-${type}`, type));
|
||||
},
|
||||
setField: (id: string, key: string, sensor: string) => {
|
||||
set.push(`${id}.${key}=${sensor}`);
|
||||
const item = doc.floors[0].furniture.find((m) => m.id === id)!;
|
||||
(item as unknown as Record<string, string>)[key] = sensor;
|
||||
},
|
||||
};
|
||||
return { deps, set, added };
|
||||
}
|
||||
|
||||
test("the import fills the sensors found in the energy dashboard and creates the missing devices", async () => {
|
||||
const s = importSetup([device("m", "meter")]);
|
||||
const result = await importEnergyPrefs(s.deps);
|
||||
assert.deepEqual(result.kind === "done" && result.filled, 2);
|
||||
assert.deepEqual(s.added, ["inverter"]);
|
||||
assert.deepEqual(s.set, ["m.power=sensor.grid_power", "new-inverter.power=sensor.pv_power"]);
|
||||
});
|
||||
|
||||
test("what is already set stays, and a failing dashboard call is reported", async () => {
|
||||
const kept = importSetup([device("m", "meter", { power: "sensor.mine" }), device("i", "inverter", { power: "sensor.mine2" })]);
|
||||
const result = await importEnergyPrefs(kept.deps);
|
||||
assert.deepEqual(result, { kind: "done", filled: 0 });
|
||||
assert.deepEqual(kept.set, []);
|
||||
const broken = importSetup([], false);
|
||||
assert.deepEqual(await importEnergyPrefs(broken.deps), { kind: "failed" });
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// What the energy tool still needs, as a list that gets ticked off while the plan fills in. Pure: the form turns each row into a
|
||||
// button that jumps to the thing to do.
|
||||
|
||||
import type { I18nKey } from "../../../i18n.ts";
|
||||
import type { Building, Floor, Furniture } from "../../../model.ts";
|
||||
import { powerSensorOf } from "../entities.ts";
|
||||
|
||||
export type ChecklistTarget =
|
||||
| { kind: "solar-field"; id: string }
|
||||
| { kind: "add-solar-field" }
|
||||
| { kind: "device"; floor: Floor; item: Furniture }
|
||||
| { kind: "add-device"; type: string };
|
||||
|
||||
export interface ChecklistRow {
|
||||
/** Done, still to do, or optional. */
|
||||
state: "ok" | "todo" | "opt";
|
||||
label: I18nKey;
|
||||
target: ChecklistTarget;
|
||||
}
|
||||
|
||||
type Found = Map<string, { power: string | null }>;
|
||||
|
||||
export function energyChecklist(doc: Building, found: Found): ChecklistRow[] {
|
||||
const items = doc.floors.flatMap((floor) => floor.furniture.map((item) => ({ floor, item })));
|
||||
const ofType = (type: string) => items.filter((entry) => entry.item.type === type);
|
||||
const hasPower = (entry: (typeof items)[number]) => !!powerSensorOf(entry.item, found);
|
||||
const device = (entry: (typeof items)[number]): ChecklistTarget => ({ kind: "device", ...entry });
|
||||
const [fields, meters, inverters, batteries, grid] = [doc.settings.roof.solar ?? [], ofType("meter"), ofType("inverter"), ofType("home_battery"), ofType("grid_point")];
|
||||
|
||||
const meterOk = !!doc.energy.grid || meters.some(hasPower);
|
||||
const inverterOk = !!doc.energy.solar || (inverters.length > 0 && inverters.every(hasPower));
|
||||
const batteryOk = !!doc.energy.battery || batteries.every((b) => hasPower(b) && b.item.soc && b.item.soc !== "none");
|
||||
|
||||
return [
|
||||
fields.length > 0
|
||||
? { state: "ok", label: "chk_solar", target: { kind: "solar-field", id: fields[0].id } }
|
||||
: { state: "todo", label: "chk_solar_add", target: { kind: "add-solar-field" } },
|
||||
meters.length > 0
|
||||
? { state: meterOk ? "ok" : "todo", label: meterOk ? "chk_meter" : "chk_meter_sensor", target: device(meters[0]) }
|
||||
: { state: "todo", label: "chk_meter_add", target: { kind: "add-device", type: "meter" } },
|
||||
inverters.length > 0
|
||||
? { state: inverterOk ? "ok" : "todo", label: inverterOk ? "chk_inverter" : "chk_inverter_sensor", target: device(inverters.find((i) => !hasPower(i)) ?? inverters[0]) }
|
||||
: { state: "todo", label: "chk_inverter_add", target: { kind: "add-device", type: "inverter" } },
|
||||
batteries.length > 0
|
||||
? { state: batteryOk ? "ok" : "todo", label: batteryOk ? "chk_battery" : "chk_battery_sensor", target: device(batteries[0]) }
|
||||
: { state: "opt", label: "chk_battery_opt", target: { kind: "add-device", type: "home_battery" } },
|
||||
grid.length > 0 ? { state: "ok", label: "chk_grid", target: device(grid[0]) } : { state: "opt", label: "chk_grid_opt", target: { kind: "add-device", type: "grid_point" } },
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import { longestFreeWall, newEnergyDevice, roomForEnergyDevice } from "./energy-devices.ts";
|
||||
|
||||
const plan = (floor: ReturnType<typeof floorWith>): Building => ({ version: 1, floors: [floor], settings: { wall_interior: 0.12, wall_exterior: 0.3 }, energy: {}, presence: [] }) as unknown as Building;
|
||||
const ctx = (selected?: ReturnType<typeof box>) => ({ roomLabel: (r: { name: string }) => r.name, selected, fallback: [9, 9] as [number, number] });
|
||||
|
||||
function house() {
|
||||
const living = box("Living", 0, 0, 5, 4);
|
||||
const garage = box("Garage", 5, 0, 8, 4);
|
||||
const utility = box("Technik", 0, 4, 3, 7);
|
||||
const hall = box("Flur", 3, 4, 8, 7);
|
||||
return floorWith([living, garage, utility, hall]);
|
||||
}
|
||||
|
||||
test("each kind of device goes to the room it belongs to", () => {
|
||||
const floor = house();
|
||||
assert.equal(roomForEnergyDevice("wallbox", floor, ctx())?.id, "Garage");
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx())?.id, "Technik");
|
||||
assert.equal(roomForEnergyDevice("home_battery", floor, ctx())?.id, "Technik");
|
||||
assert.equal(roomForEnergyDevice("meter", floor, ctx())?.id, "Technik");
|
||||
});
|
||||
|
||||
test("a meter takes the hall when there is no utility room, and a garage is found by the parking spot in it", () => {
|
||||
const floor = floorWith([box("Wohnen", 0, 0, 5, 4), box("Flur", 5, 0, 8, 4), box("Halle", 0, 4, 6, 8)]);
|
||||
assert.equal(roomForEnergyDevice("meter", floor, ctx())?.id, "Flur");
|
||||
const withCar = { ...floor, furniture: [{ id: "p", type: "parking", x: 3, z: 6 } as Furniture] };
|
||||
assert.equal(roomForEnergyDevice("wallbox", withCar, ctx())?.id, "Halle");
|
||||
});
|
||||
|
||||
test("without any hint the selected room is used, and without one the largest", () => {
|
||||
const floor = floorWith([box("A", 0, 0, 2, 2), box("B", 2, 0, 8, 6)]);
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx(floor.rooms[0]))?.id, "A");
|
||||
assert.equal(roomForEnergyDevice("inverter", floor, ctx())?.id, "B");
|
||||
assert.equal(roomForEnergyDevice("inverter", floorWith([]), ctx()), undefined);
|
||||
});
|
||||
|
||||
test("the longest wall is chosen, walls with openings only when nothing else is left, and the direction points inward", () => {
|
||||
const room = box("R", 0, 0, 6, 2);
|
||||
const wall = longestFreeWall(room, new Set())!;
|
||||
assert.deepEqual(wall.mid, [3, 0]);
|
||||
assert.deepEqual(wall.inward, [0, 1]);
|
||||
assert.deepEqual(longestFreeWall(room, new Set([0]))!.mid, [3, 2], "the top wall has an opening, so the bottom one is taken");
|
||||
assert.ok(longestFreeWall(room, new Set([0, 1, 2, 3])), "all walls are open: any will do");
|
||||
});
|
||||
|
||||
test("a wallbox ends up flush against a wall of the garage", () => {
|
||||
const floor = house();
|
||||
const device = newEnergyDevice("wallbox", plan(floor), floor, ctx());
|
||||
assert.equal(device.type, "wallbox");
|
||||
assert.ok(device.x > 5 && device.x < 8 && device.z >= 0 && device.z <= 4, `${device.x},${device.z}`);
|
||||
const atWall = [device.x - 5, 8 - device.x, device.z, 4 - device.z].some((gap) => gap < 0.5);
|
||||
assert.ok(atWall);
|
||||
assert.ok(device.id.startsWith("furniture"));
|
||||
});
|
||||
|
||||
test("without a room the device goes where the caller says; the grid point falls back too when there is no meter", () => {
|
||||
const empty = floorWith([]);
|
||||
const loose = newEnergyDevice("inverter", plan(empty), empty, ctx());
|
||||
assert.deepEqual([loose.x, loose.z], [9, 9]);
|
||||
const grid = newEnergyDevice("grid_point", plan(empty), empty, ctx());
|
||||
assert.deepEqual([grid.x, grid.z], [9, 9]);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// Where a new energy device goes. A wallbox belongs in the garage, an inverter or battery in the utility room, a meter in the
|
||||
// utility room or the hall; the device stands against the room's longest free wall, and the grid connection outside the house.
|
||||
|
||||
import { snapToWall } from "../../../geometry/snap.ts";
|
||||
import { centroid, pointInPolygon, signedArea, uid, type Building, type Floor, type Furniture, type Room, type Vec2 } from "../../../model.ts";
|
||||
import { furnitureSize } from "../../../packs.ts";
|
||||
import { suggestGridSpot } from "../../../energy.ts";
|
||||
|
||||
const GARAGE = /garage|carport/;
|
||||
const UTILITY = /hwr|hauswirt|technik|keller|abstell|utility|basement|boiler|heiz/;
|
||||
const HALL = /flur|diele|eingang|hall|entr|lobby/;
|
||||
|
||||
/** How far in front of the wall the device is dropped before it snaps flush against it. */
|
||||
const WALL_GAP = 0.25;
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
|
||||
export interface EnergySpotContext {
|
||||
/** The text a room is recognised by: its name and the name of its Home Assistant area. */
|
||||
roomLabel(room: Room): string;
|
||||
/** The room selected in the editor, tried when no better room is found. */
|
||||
selected?: Room;
|
||||
/** Where to put things when the plan gives no hint (the middle of what is on screen). */
|
||||
fallback: Vec2;
|
||||
}
|
||||
|
||||
/** The room a device of this type belongs in, or the selected room, or the largest one. */
|
||||
export function roomForEnergyDevice(type: string, floor: Floor, ctx: EnergySpotContext): Room | undefined {
|
||||
const rooms = floor.rooms.filter((r) => r.points.length >= 3);
|
||||
const named = (pattern: RegExp) => rooms.find((r) => pattern.test(ctx.roomLabel(r).toLowerCase()));
|
||||
const parkedIn = rooms.find((r) => floor.furniture.some((m) => m.type === "parking" && pointInPolygon([m.x, m.z], r.points)));
|
||||
const garage = named(GARAGE) ?? parkedIn;
|
||||
const utility = named(UTILITY);
|
||||
const fitting = type === "wallbox" ? garage : type === "meter" ? (utility ?? named(HALL) ?? garage) : (utility ?? garage);
|
||||
const largest = [...rooms].sort((a, b) => Math.abs(signedArea(b.points)) - Math.abs(signedArea(a.points)))[0];
|
||||
return fitting ?? ctx.selected ?? largest;
|
||||
}
|
||||
|
||||
/** The middle of the longest wall of the room and the direction into the room. Walls with an opening are avoided when others exist. */
|
||||
export function longestFreeWall(room: Room, openedEdges: ReadonlySet<number>): { mid: Vec2; inward: Vec2 } | null {
|
||||
const [cx, cz] = centroid(room.points);
|
||||
const anyFree = room.points.some((_, i) => !openedEdges.has(i));
|
||||
let best: { mid: Vec2; inward: Vec2; length: number } | null = null;
|
||||
room.points.forEach((p, i) => {
|
||||
if (anyFree && openedEdges.has(i)) return;
|
||||
const q = room.points[(i + 1) % room.points.length];
|
||||
const length = Math.hypot(q[0] - p[0], q[1] - p[1]);
|
||||
if (best && length <= best.length) return;
|
||||
const mid: Vec2 = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
|
||||
// `+ 0` turns a negative zero into a plain zero
|
||||
let inward: Vec2 = [-(q[1] - p[1]) / length + 0, (q[0] - p[0]) / length + 0];
|
||||
if ((cx - mid[0]) * inward[0] + (cz - mid[1]) * inward[1] < 0) inward = [0 - inward[0], 0 - inward[1]];
|
||||
best = { mid, inward, length };
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A new energy device of this type on the floor, placed where it belongs and snapped to the wall. */
|
||||
export function newEnergyDevice(type: string, building: Building, floor: Floor, ctx: EnergySpotContext): Furniture {
|
||||
const [w, d, h] = furnitureSize(type);
|
||||
const base = { id: uid("furniture"), type, rotation: 0, w, d, h, variant: null };
|
||||
if (type === "grid_point") {
|
||||
// the grid connection starts just outside the wall nearest to the meter, and can be dragged from there
|
||||
const spot = suggestGridSpot(building);
|
||||
const [x, z] = spot ? [spot.x, spot.z] : ctx.fallback;
|
||||
return { ...base, x: thousandths(x), z: thousandths(z) };
|
||||
}
|
||||
const room = roomForEnergyDevice(type, floor, ctx);
|
||||
let [x, z] = room ? centroid(room.points) : ctx.fallback;
|
||||
if (room) {
|
||||
// in front of the longest wall, so that it snaps to that wall: from the middle of the room no wall is near enough
|
||||
const opened = new Set(floor.openings.filter((o) => o.room_id === room.id).map((o) => o.edge));
|
||||
const wall = longestFreeWall(room, opened);
|
||||
if (wall) [x, z] = [wall.mid[0] + wall.inward[0] * (d / 2 + WALL_GAP), wall.mid[1] + wall.inward[1] * (d / 2 + WALL_GAP)];
|
||||
}
|
||||
const item: Furniture = { ...base, x: thousandths(x), z: thousandths(z) };
|
||||
const snapped = room ? snapToWall({ ...floor, furniture: [...floor.furniture, item] }, item, building.settings.wall_interior) : null;
|
||||
return snapped ? { ...item, x: thousandths(snapped.x), z: thousandths(snapped.z), rotation: snapped.rotation } : item;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Filling the energy balance from Home Assistant's energy dashboard: its statistics lead to power sensors of the same devices, and
|
||||
// those go onto the devices of the plan (meter, inverter, battery). Only empty fields are filled, so what the user chose stays.
|
||||
|
||||
import { proposeEnergySensors, type EnergyPrefs } from "../../../energy.ts";
|
||||
import type { Building, Furniture } from "../../../model.ts";
|
||||
import type { HomeAssistant } from "../../../types.ts";
|
||||
|
||||
export interface EnergyImportDeps {
|
||||
hass: HomeAssistant;
|
||||
/** The current plan; read again after a device was added. */
|
||||
doc(): Building;
|
||||
/** Whether a floor is selected, which is where missing devices are created. */
|
||||
canAdd(): boolean;
|
||||
addDevice(type: string): void;
|
||||
setField(furnitureId: string, key: "power" | "soc", sensor: string): void;
|
||||
}
|
||||
|
||||
export type EnergyImportResult = { kind: "failed" } | { kind: "done"; filled: number };
|
||||
|
||||
/** The device of this type anywhere in the plan. */
|
||||
const deviceOfType = (doc: Building, type: string): Furniture | undefined => doc.floors.flatMap((f) => f.furniture).find((m) => m.type === type);
|
||||
|
||||
const isEmpty = (value: string | null | undefined) => !value || value === "none";
|
||||
|
||||
export async function importEnergyPrefs(deps: EnergyImportDeps): Promise<EnergyImportResult> {
|
||||
let prefs: EnergyPrefs;
|
||||
try {
|
||||
prefs = await deps.hass.callWS<EnergyPrefs>({ type: "energy/get_prefs" });
|
||||
} catch {
|
||||
return { kind: "failed" };
|
||||
}
|
||||
const found = proposeEnergySensors(deps.hass, prefs);
|
||||
let filled = 0;
|
||||
const fill = (type: string, key: "power" | "soc", sensor: string | null | undefined) => {
|
||||
if (!sensor) return;
|
||||
let device = deviceOfType(deps.doc(), type);
|
||||
if (!device && deps.canAdd()) {
|
||||
deps.addDevice(type);
|
||||
device = deviceOfType(deps.doc(), type);
|
||||
}
|
||||
if (!device || !isEmpty(device[key])) return;
|
||||
deps.setField(device.id, key, sensor);
|
||||
filled++;
|
||||
};
|
||||
fill("meter", "power", found.grid);
|
||||
fill("inverter", "power", found.solar);
|
||||
fill("home_battery", "power", found.battery);
|
||||
fill("home_battery", "soc", found.battery_soc);
|
||||
return { kind: "done", filled };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import type { Building } from "../../../model.ts";
|
||||
import { copyOfFloor, floorsSwapped, floorsWith, freeHaFloors, linkableHaFloors, moveFurnitureToFloor, newFloorFor, unlinked, unplacedAreas } from "./floors.ts";
|
||||
|
||||
const names = { first: "Ground floor", next: (n: number) => `Floor ${n}` };
|
||||
const level = (id: string, elevation: number, extra = {}) => floorWith([], { id, elevation, ...extra } as never);
|
||||
const house = (...floors: ReturnType<typeof level>[]) => ({ floors }) as unknown as Building;
|
||||
|
||||
test("the first floor gets its own name, later ones are numbered, and a Home Assistant floor lends its name and level", () => {
|
||||
assert.equal(newFloorFor(house(), null, names).name, "Ground floor");
|
||||
assert.equal(newFloorFor(house(level("g", 0)), null, names).name, "Floor 1");
|
||||
const fromHa = newFloorFor(house(level("g", 0)), { floor_id: "upstairs", name: "Upstairs", level: 1 }, names);
|
||||
assert.deepEqual([fromHa.name, fromHa.ha_floor, fromHa.elevation], ["Upstairs", "upstairs", 2.75]);
|
||||
assert.notEqual(newFloorFor(house(), null, names).id, newFloorFor(house(), null, names).id);
|
||||
});
|
||||
|
||||
test("a new floor without a level goes on top of the house", () => {
|
||||
const added = newFloorFor(house(level("g", 0)), null, names);
|
||||
assert.equal(added.elevation, 2.75);
|
||||
});
|
||||
|
||||
test("floors stay ordered from bottom to top when one is added", () => {
|
||||
const floors = [level("a", 0), level("b", 3), level("c", 6)];
|
||||
assert.deepEqual(floorsWith(floors, level("x", 1)).map((f) => f.id), ["a", "x", "b", "c"]);
|
||||
assert.deepEqual(floorsWith(floors, level("x", 9)).map((f) => f.id), ["a", "b", "c", "x"]);
|
||||
assert.deepEqual(floorsWith(floors, level("x", -3)).map((f) => f.id), ["x", "a", "b", "c"]);
|
||||
assert.deepEqual(floorsWith([], level("x", 0)).map((f) => f.id), ["x"]);
|
||||
});
|
||||
|
||||
test("floors swap with the neighbour in the direction, and stay put at the ends", () => {
|
||||
const floors = [level("a", 0), level("b", 3), level("c", 6)];
|
||||
assert.deepEqual(floorsSwapped(floors, "b", 1).map((f) => f.id), ["a", "c", "b"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "b", -1).map((f) => f.id), ["b", "a", "c"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "c", 1).map((f) => f.id), ["a", "b", "c"]);
|
||||
assert.deepEqual(floorsSwapped(floors, "nope", 1).map((f) => f.id), ["a", "b", "c"]);
|
||||
});
|
||||
|
||||
test("Home Assistant floors that are not used yet come lowest first, unnumbered ones last", () => {
|
||||
const registry = { a: { floor_id: "a", name: "Attic", level: 2 }, g: { floor_id: "g", name: "Ground", level: 0 }, z: { floor_id: "z", name: "Zeta" }, b: { floor_id: "b", name: "Basement", level: -1 } };
|
||||
const doc = house(level("x", 0, { ha_floor: "g" }));
|
||||
assert.deepEqual(freeHaFloors(doc, registry).map((f) => f.floor_id), ["b", "a", "z"]);
|
||||
assert.deepEqual(freeHaFloors(doc, undefined), []);
|
||||
assert.deepEqual(linkableHaFloors(doc, doc.floors[0], registry).map((f) => f.floor_id).sort(), ["a", "b", "g", "z"]);
|
||||
assert.deepEqual(linkableHaFloors(house(level("x", 0, { ha_floor: "g" }), level("y", 3)), doc.floors[0], registry).map((f) => f.floor_id).sort(), ["a", "b", "g", "z"]);
|
||||
assert.deepEqual(linkableHaFloors(house(level("x", 0, { ha_floor: "g" }), level("y", 3, { ha_floor: "a" })), doc.floors[0], registry).map((f) => f.floor_id).sort(), ["b", "g", "z"]);
|
||||
});
|
||||
|
||||
test("areas without a room: only those of the floor's Home Assistant floor, by name", () => {
|
||||
const areas = {
|
||||
k: { area_id: "k", name: "Kitchen", floor_id: "g" },
|
||||
b: { area_id: "b", name: "Bath", floor_id: "g" },
|
||||
a: { area_id: "a", name: "Attic room", floor_id: "up" },
|
||||
h: { area_id: "h", name: "Hall", floor_id: "g" },
|
||||
};
|
||||
const ground = floorWith([box("room", 0, 0, 1, 1, "h")], { id: "x", ha_floor: "g" } as never);
|
||||
const doc = { floors: [ground] } as unknown as Building;
|
||||
assert.deepEqual(unplacedAreas(doc, ground, areas).map((a) => a.area_id), ["b", "k"]);
|
||||
assert.deepEqual(unplacedAreas(doc, { ...ground, ha_floor: null }, areas), []);
|
||||
assert.deepEqual(unplacedAreas(doc, ground, undefined), []);
|
||||
});
|
||||
|
||||
test("a floor copy gets new ids, goes on top of the house and keeps its doors on the copied rooms", () => {
|
||||
let n = 0;
|
||||
const id = (prefix: string) => `${prefix}_${++n}`;
|
||||
const room = { ...box("r1", 0, 0, 4, 3), area_id: "living" };
|
||||
const ground = floorWith([room], {
|
||||
id: "g",
|
||||
ha_floor: "eg",
|
||||
walls: [{ id: "w1", a: [0, 1], b: [2, 1] }],
|
||||
openings: [opening("o1", "r1", "door"), opening("o2", "r1", "window", { wall: "w1" })],
|
||||
furniture: [
|
||||
{ id: "f1", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 1, h: 0.8, variant: null, entity: "media_player.tv", state_entity: "binary_sensor.seat" },
|
||||
{ id: "f2", type: "meter", x: 0, z: 0, rotation: 0, w: 0.5, d: 0.2, h: 1, variant: null },
|
||||
],
|
||||
placements: [{ entity_id: "light.a", x: 1, z: 1 } as never],
|
||||
});
|
||||
const upper = floorWith([], { id: "u", elevation: 2.75, height: 2.5 });
|
||||
const doc = house(ground, upper);
|
||||
const copy = copyOfFloor(doc, ground, "Ground (copy)", { furniture: true, devices: false, outdoor: false }, id);
|
||||
assert.equal(copy.elevation, 5.25, "above the highest floor");
|
||||
assert.equal(copy.ha_floor, null);
|
||||
assert.equal(copy.rooms[0].area_id, null);
|
||||
assert.notEqual(copy.rooms[0].id, "r1");
|
||||
assert.deepEqual(copy.openings.map((o) => o.room_id), [copy.rooms[0].id, copy.rooms[0].id]);
|
||||
assert.equal(copy.openings[1].wall, copy.walls![0].id);
|
||||
assert.deepEqual(copy.furniture.map((f) => f.type), ["sofa"], "the meter stays behind");
|
||||
assert.equal(copy.furniture[0].entity, "none");
|
||||
assert.equal(copy.furniture[0].state_entity, null);
|
||||
assert.deepEqual(copy.placements, []);
|
||||
assert.equal(ground.rooms[0].area_id, "living", "the original is untouched");
|
||||
});
|
||||
|
||||
test("furniture moves to another floor at the same spot", () => {
|
||||
const sofa = { id: "f1", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 1, h: 0.8, variant: null };
|
||||
const doc = house(floorWith([], { id: "g", furniture: [sofa] }), floorWith([], { id: "u", elevation: 2.75 }));
|
||||
assert.equal(moveFurnitureToFloor(doc, "g", "f1", "u"), true);
|
||||
assert.deepEqual([doc.floors[0].furniture.length, doc.floors[1].furniture[0].x], [0, 1]);
|
||||
assert.equal(moveFurnitureToFloor(doc, "g", "f1", "u"), false);
|
||||
});
|
||||
|
||||
test("a copied piece of furniture keeps no link to Home Assistant", () => {
|
||||
const linked = {
|
||||
id: "f1",
|
||||
type: "fridge_smart",
|
||||
x: 1,
|
||||
z: 1,
|
||||
rotation: 0,
|
||||
w: 0.9,
|
||||
d: 0.7,
|
||||
h: 1.8,
|
||||
variant: null,
|
||||
entity: "switch.fridge",
|
||||
power: "sensor.fridge_power",
|
||||
temp_entity: "sensor.fridge_temp",
|
||||
door_left: "binary_sensor.freezer_door",
|
||||
door_right: "binary_sensor.fridge_door",
|
||||
state_entity: "binary_sensor.seat",
|
||||
color_entity: "light.bulb",
|
||||
care_entity: "sensor.bin",
|
||||
cover_entity: "cover.curtain",
|
||||
fan_entity: "fan.ceiling",
|
||||
room_sensor: "sensor.vacuum_room",
|
||||
type_entity: "sensor.car_kind",
|
||||
gang_entities: ["light.a", "light.b"],
|
||||
pictures: [{ entity: "media_player.tv", state: "*", image: "x" }],
|
||||
car: { device: "sensor.car_soc", soc: "sensor.car_soc" },
|
||||
tap: { action: "more-info", target: "light.a" },
|
||||
} as never;
|
||||
const copy = unlinked(linked);
|
||||
const text = JSON.stringify(copy);
|
||||
assert.doesNotMatch(text, /[a-z_]+\.[a-z0-9_]+/, "no entity id survives");
|
||||
assert.deepEqual([copy.entity, copy.power, copy.fan_entity, copy.room_sensor], ["none", "none", "none", "none"]);
|
||||
assert.deepEqual([copy.w, copy.d, copy.h, copy.x], [0.9, 0.7, 1.8, 1]);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
// The floors of the house: adding one (also from a floor of Home Assistant's registry), ordering them, and finding what is still to be
|
||||
// connected to Home Assistant.
|
||||
|
||||
import { floorElevation, newFloor, uid, type Building, type Floor, type Furniture } from "../../../model.ts";
|
||||
import type { HassArea, HassFloor } from "../../../types.ts";
|
||||
|
||||
/** A new floor, named after a Home Assistant floor when it comes from one, and placed at that floor's level or on top of the house. */
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }): Floor {
|
||||
const count = doc.floors.length;
|
||||
const name = from?.name ?? (count === 0 ? names.first : names.next(count));
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(doc.floors, from?.level)), ha_floor: from?.floor_id ?? null };
|
||||
}
|
||||
|
||||
/** The floors with a new one slotted in below the first floor that lies higher: floors are kept from bottom to top. */
|
||||
export function floorsWith(floors: readonly Floor[], added: Floor): Floor[] {
|
||||
const above = floors.findIndex((f) => f.elevation > added.elevation);
|
||||
const at = above < 0 ? floors.length : above;
|
||||
return [...floors.slice(0, at), added, ...floors.slice(at)];
|
||||
}
|
||||
|
||||
/** The floors with the one of this id swapped with its neighbour above (1) or below (-1). Unchanged at the ends. */
|
||||
export function floorsSwapped(floors: readonly Floor[], id: string, direction: -1 | 1): Floor[] {
|
||||
const from = floors.findIndex((f) => f.id === id);
|
||||
const to = from + direction;
|
||||
if (from < 0 || to < 0 || to >= floors.length) return [...floors];
|
||||
const next = [...floors];
|
||||
[next[from], next[to]] = [next[to], next[from]];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Floors of Home Assistant that no floor of the plan stands for yet, lowest first. */
|
||||
export function freeHaFloors(doc: Building, registry: Readonly<Record<string, HassFloor>> | undefined): HassFloor[] {
|
||||
const used = new Set(doc.floors.map((f) => f.ha_floor));
|
||||
return Object.values(registry ?? {})
|
||||
.filter((f) => !used.has(f.floor_id))
|
||||
.sort((a, b) => (a.level ?? 99) - (b.level ?? 99) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Areas on the Home Assistant floor of this floor that have no room in the plan yet, by name. */
|
||||
export function unplacedAreas(doc: Building, floor: Floor, areas: Readonly<Record<string, HassArea>> | undefined): HassArea[] {
|
||||
if (!floor.ha_floor) return [];
|
||||
const placed = new Set(doc.floors.flatMap((f) => f.rooms.map((r) => r.area_id)));
|
||||
return Object.values(areas ?? {})
|
||||
.filter((a) => a.floor_id === floor.ha_floor && !placed.has(a.area_id))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** The Home Assistant floors a floor may be linked to: its own and the ones no other floor uses. */
|
||||
export function linkableHaFloors(doc: Building, floor: Floor, registry: Readonly<Record<string, HassFloor>> | undefined): HassFloor[] {
|
||||
return Object.values(registry ?? {}).filter((f) => f.floor_id === floor.ha_floor || !doc.floors.some((other) => other.ha_floor === f.floor_id));
|
||||
}
|
||||
|
||||
/** What a floor copy takes along besides its rooms, walls, doors and windows. */
|
||||
export interface FloorCopyOptions {
|
||||
furniture: boolean;
|
||||
/** Device pins: off by default, since the same entity would then show twice. */
|
||||
devices: boolean;
|
||||
outdoor: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A copy of a floor with new ids for everything on it, put on top of the house (above the highest floor). Rooms lose
|
||||
* their Home Assistant area and the floor its Home Assistant floor, since each can stand for one room or floor only;
|
||||
* doors and windows keep pointing at the copied rooms and walls.
|
||||
*/
|
||||
export function copyOfFloor(doc: Building, floor: Floor, name: string, options: FloorCopyOptions, id: (prefix: string) => string = uid): Floor {
|
||||
const copy = structuredClone(floor);
|
||||
const top = doc.floors.reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const rooms = new Map<string, string>();
|
||||
const walls = new Map<string, string>();
|
||||
copy.id = id("floor");
|
||||
copy.name = name;
|
||||
copy.elevation = Math.round(top * 1000) / 1000;
|
||||
copy.ha_floor = null;
|
||||
copy.start_view = null;
|
||||
copy.rooms = copy.rooms.map((r) => {
|
||||
const fresh = id("room");
|
||||
rooms.set(r.id, fresh);
|
||||
return { ...r, id: fresh, area_id: null };
|
||||
});
|
||||
copy.walls = (copy.walls ?? []).map((w) => {
|
||||
const fresh = id("wall");
|
||||
walls.set(w.id, fresh);
|
||||
return { ...w, id: fresh };
|
||||
});
|
||||
copy.openings = copy.openings.filter((o) => rooms.has(o.room_id)).map((o) => ({ ...o, id: id("opening"), room_id: rooms.get(o.room_id)!, wall: o.wall ? (walls.get(o.wall) ?? null) : o.wall }));
|
||||
// energy devices (meters, inverters …) belong to the real house once, so they stay behind
|
||||
const energy = new Set(["meter", "inverter", "home_battery", "wallbox", "grid_point"]);
|
||||
copy.furniture = options.furniture ? copy.furniture.filter((f) => !energy.has(f.type)).map((f) => unlinked({ ...f, id: id("furniture") })) : [];
|
||||
copy.placements = options.devices ? copy.placements : [];
|
||||
copy.outdoor = options.outdoor ? copy.outdoor.map((a) => ({ ...a, id: id("outdoor") })) : [];
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Links that are found automatically while they are null: a copy sets them to "none", or it would find the original's entities again. */
|
||||
const AUTO_LINKS = ["entity", "power", "fan_entity", "room_sensor"] as const;
|
||||
/** Links that are simply empty while null. */
|
||||
const PLAIN_LINKS = [
|
||||
"door_left",
|
||||
"door_right",
|
||||
"soc",
|
||||
"charge",
|
||||
"export",
|
||||
"status",
|
||||
"temp_entity",
|
||||
"temp_entity2",
|
||||
"state_entity",
|
||||
"state_entity2",
|
||||
"color_entity",
|
||||
"care_entity",
|
||||
"cover_entity",
|
||||
"type_entity",
|
||||
"parent_meter",
|
||||
"car",
|
||||
"tap",
|
||||
] as const;
|
||||
/** Lists of links, dropped as a whole. */
|
||||
const LINK_LISTS = ["gang_entities", "pictures", "types", "meter_floors", "show_when", "extra_lights"] as const;
|
||||
|
||||
/** A piece of furniture with every link to Home Assistant removed, its size, place and look kept. */
|
||||
export function unlinked(item: Furniture): Furniture {
|
||||
const out = { ...item } as Record<string, unknown>;
|
||||
// the fan and the vacuum's room sensor are looked up in the item's room, which a copy no longer links to an area
|
||||
for (const key of AUTO_LINKS) if (key === "entity" || key === "power" || out[key] != null) out[key] = "none";
|
||||
for (const key of PLAIN_LINKS) if (out[key] != null) out[key] = null;
|
||||
for (const key of LINK_LISTS) delete out[key];
|
||||
return out as unknown as Furniture;
|
||||
}
|
||||
|
||||
/** Moves a piece of furniture to another floor, at the same spot in the plan. Returns false when it or the floor is missing. */
|
||||
export function moveFurnitureToFloor(doc: Building, fromFloorId: string, itemId: string, toFloorId: string): boolean {
|
||||
const from = doc.floors.find((f) => f.id === fromFloorId);
|
||||
const to = doc.floors.find((f) => f.id === toFloorId);
|
||||
if (!from || !to || from === to) return false;
|
||||
const index = from.furniture.findIndex((f) => f.id === itemId);
|
||||
if (index < 0) return false;
|
||||
const [item] = from.furniture.splice(index, 1);
|
||||
to.furniture.push(item);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { likelyRoomSensors, parseButtonData, patchPresence, startViewYaml } from "./house.ts";
|
||||
import { moveWithin, orUndefined, patchAt, removeAt } from "./lists.ts";
|
||||
|
||||
test("moving within a list keeps every item and stops at the ends", () => {
|
||||
assert.deepEqual(moveWithin([1, 2, 3, 4], 1, 1), [1, 3, 2, 4]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3, 4], 2, -1), [1, 3, 2, 4]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 0, -1), [1, 2, 3]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 2, 1), [1, 2, 3]);
|
||||
assert.deepEqual(moveWithin([1, 2, 3], 0, 9), [2, 3, 1]);
|
||||
});
|
||||
|
||||
test("removing and patching leave the original alone", () => {
|
||||
const list = [{ a: 1 }, { a: 2 }];
|
||||
assert.deepEqual(removeAt(list, 0), [{ a: 2 }]);
|
||||
assert.deepEqual(patchAt(list, 1, { a: 9 }), [{ a: 1 }, { a: 9 }]);
|
||||
assert.deepEqual(list, [{ a: 1 }, { a: 2 }]);
|
||||
assert.equal(orUndefined([]), undefined);
|
||||
assert.deepEqual(orUndefined([1]), [1]);
|
||||
});
|
||||
|
||||
test("a presence link is replaced, added or removed; its room keeps it alive without a sensor", () => {
|
||||
const links = [{ person: "person.a", sensor: "sensor.a" }];
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: "sensor.b" }), [{ person: "person.a", sensor: "sensor.b" }]);
|
||||
assert.deepEqual(patchPresence(links, "person.b", { sensor: "sensor.c" }), [...links, { person: "person.b", sensor: "sensor.c" }]);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: null }), []);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { sensor: "none" }), []);
|
||||
assert.deepEqual(patchPresence(links, "person.a", { room: "kitchen" }), [{ person: "person.a", sensor: "sensor.a", room: "kitchen" }]);
|
||||
assert.deepEqual(patchPresence([{ person: "person.a", sensor: "sensor.a", room: "k" }], "person.a", { sensor: null }), [{ person: "person.a", sensor: null, room: "k" }], "the room alone is enough");
|
||||
assert.deepEqual(patchPresence([{ person: "person.a", sensor: null, room: "k" }], "person.a", { room: null }), []);
|
||||
assert.equal(links.length, 1);
|
||||
});
|
||||
|
||||
test("sensors named after the person and a room come first", () => {
|
||||
const options = [
|
||||
{ id: "sensor.other_room", label: "" },
|
||||
{ id: "sensor.anna_phone_area", label: "" },
|
||||
{ id: "sensor.anna_battery", label: "" },
|
||||
{ id: "sensor.bermuda_anna_room", label: "" },
|
||||
];
|
||||
assert.deepEqual(likelyRoomSensors(options, "person.anna").map((o) => o.id), ["sensor.anna_phone_area", "sensor.bermuda_anna_room", "sensor.other_room", "sensor.anna_battery"]);
|
||||
});
|
||||
|
||||
test("the start view becomes one line of card YAML", () => {
|
||||
assert.equal(startViewYaml({ theta: 1, phi: 2, radius: 3 }), "start_view: { theta: 1, phi: 2, radius: 3 }");
|
||||
assert.equal(startViewYaml({ theta: 1, phi: 2, radius: 3, target: { x: 4, y: 5, z: 6 } }), "start_view: { theta: 1, phi: 2, radius: 3, target: { x: 4, y: 5, z: 6 } }");
|
||||
});
|
||||
|
||||
test("button data: empty is none, objects pass, everything else is refused", () => {
|
||||
assert.deepEqual(parseButtonData(" "), { ok: true, value: null });
|
||||
assert.deepEqual(parseButtonData('{"entity_id": "script.party"}'), { ok: true, value: { entity_id: "script.party" } });
|
||||
for (const bad of ["[1]", "5", "null", "{oops", '"text"']) assert.deepEqual(parseButtonData(bad), { ok: false }, bad);
|
||||
});
|
||||
|
||||
import { clamp, turnedNorth, withEffect, wrapDegrees } from "./settings.ts";
|
||||
|
||||
test("settings are kept within their limits", () => {
|
||||
assert.equal(clamp(5, 0, 1), 1);
|
||||
assert.equal(clamp(-5, 0, 1), 0);
|
||||
assert.equal(clamp(0.5, 0, 1), 0.5);
|
||||
assert.equal(wrapDegrees(370), 10);
|
||||
assert.equal(wrapDegrees(-10), 350);
|
||||
assert.equal(turnedNorth(0, 180), 180, "north and south swapped");
|
||||
assert.equal(turnedNorth(200, 180), 20);
|
||||
assert.equal(turnedNorth(10, -90), 280);
|
||||
assert.equal(wrapDegrees(359.6), 0);
|
||||
});
|
||||
|
||||
test("weather effects can be added once and removed", () => {
|
||||
assert.deepEqual(withEffect(["rain"], "snow", true), ["rain", "snow"]);
|
||||
assert.deepEqual(withEffect(["rain", "snow"], "rain", true), ["rain", "snow"]);
|
||||
assert.deepEqual(withEffect(["rain", "snow"], "rain", false), ["snow"]);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Settings of the house as a whole: who is tracked by which sensor, the start camera, the data of an own button.
|
||||
|
||||
import type { PresenceLink, StartView } from "../../../model.ts";
|
||||
import type { EntityOption } from "../entities.ts";
|
||||
|
||||
/**
|
||||
* The presence links with `person` changed by `patch` (sensor: null or "none" clears it, room: null clears it). A link that has
|
||||
* neither a sensor nor a room left is removed.
|
||||
*/
|
||||
export function patchPresence(links: readonly PresenceLink[], person: string, patch: { sensor?: string | null; room?: string | null }): PresenceLink[] {
|
||||
const old = links.find((l) => l.person === person);
|
||||
const sensor = "sensor" in patch ? (patch.sensor && patch.sensor !== "none" ? patch.sensor : null) : (old?.sensor ?? null);
|
||||
const room = "room" in patch ? patch.room || null : (old?.room ?? null);
|
||||
const others = links.filter((l) => l.person !== person);
|
||||
if (!sensor && !room) return others;
|
||||
const next: PresenceLink = room ? { person, sensor, room } : { person, sensor };
|
||||
return old ? links.map((l) => (l.person === person ? next : l)) : [...others, next];
|
||||
}
|
||||
|
||||
/** Room sensors that look like they belong to this person (named after them, ESPresense and Bermuda style) come first. */
|
||||
export function likelyRoomSensors(options: readonly EntityOption[], person: string): EntityOption[] {
|
||||
const slug = person.slice(person.indexOf(".") + 1);
|
||||
const likely = (o: EntityOption) => o.id.includes(slug) && /(area|room|raum|bermuda|espresense)/.test(o.id);
|
||||
return [...options.filter(likely), ...options.filter((o) => !likely(o))];
|
||||
}
|
||||
|
||||
/** The start view as the line to put into a card's YAML. */
|
||||
export function startViewYaml(view: StartView): string {
|
||||
const target = view.target ? `, target: { x: ${view.target.x}, y: ${view.target.y}, z: ${view.target.z} }` : "";
|
||||
return `start_view: { theta: ${view.theta}, phi: ${view.phi}, radius: ${view.radius}${target} }`;
|
||||
}
|
||||
|
||||
export type ParsedData = { ok: true; value: Record<string, unknown> | null } | { ok: false };
|
||||
|
||||
/** The extra data of a button, typed as JSON: empty means none, and anything but an object is refused. */
|
||||
export function parseButtonData(text: string): ParsedData {
|
||||
const raw = text.trim();
|
||||
if (!raw) return { ok: true, value: null };
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? { ok: true, value: value as Record<string, unknown> } : { ok: false };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
|
||||
import type { Building, Furniture, Placement } from "../../../model.ts";
|
||||
import { drawOrder, copyOfFurniture, copyOfOutdoorArea, deviceForFurniture, insertOutdoorCorner, removeOutdoorCorner, edgeOf, furnitureForDevice, newFloorOpening, newFreeWall, newFurniture, newOpening, newOutdoorArea, offsetOnEdge, openingKindPatch, parkingSpotFor, placeInRoom, removeDevice, roomCentre, wallEndForLength, wallHeightPatch } from "./items.ts";
|
||||
import { NO_CHANGE, NOTHING_TO_MOVE, nudge, type Nudge } from "./nudge.ts";
|
||||
|
||||
const sofa = (extra: Partial<Furniture> = {}): Furniture => ({ id: "s", type: "sofa", x: 1, z: 1, rotation: 0, w: 2, d: 0.9, h: 0.8, variant: null, ...extra });
|
||||
const pin = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra });
|
||||
const applied = (n: Nudge, floor: ReturnType<typeof floorWith>) => {
|
||||
assert.ok(typeof n === "object", `expected a change, got ${String(n)}`);
|
||||
const copy = structuredClone(floor);
|
||||
n.apply(copy);
|
||||
return copy;
|
||||
};
|
||||
|
||||
test("free walls: rounding, a typed length that keeps the direction, and the height that means 'as high as the floor'", () => {
|
||||
const wall = newFreeWall([0, 0.1234], [3, 4.0004]);
|
||||
assert.deepEqual([wall.a, wall.b], [[0, 0.123], [3, 4]]);
|
||||
assert.deepEqual(wallEndForLength({ ...wall, a: [0, 0], b: [3, 4] }, 10), [6, 8]);
|
||||
assert.deepEqual(wallEndForLength({ ...wall, a: [0, 0], b: [3, 4] }, 0), [0.06, 0.08], "never shorter than 10 cm");
|
||||
assert.deepEqual(wallHeightPatch(2.5, 2.5), { height: null });
|
||||
assert.deepEqual(wallHeightPatch(1, 2.5), { height: 1 });
|
||||
assert.deepEqual(wallHeightPatch(0, 2.5), { height: 0.05 });
|
||||
});
|
||||
|
||||
test("a floor opening is the drawn rectangle, and an outdoor area its outline; copies move half a metre", () => {
|
||||
const hole = newFloorOpening([1, 1], [3, 4]);
|
||||
assert.deepEqual([hole.type, hole.x, hole.z, hole.w, hole.d], ["stairwell", 2, 2.5, 2, 3]);
|
||||
const area = newOutdoorArea([[0, 0], [1, 0], [1, 1.23456]]);
|
||||
assert.equal(area.type, "lawn");
|
||||
assert.equal(area.points[2][1], 1.235);
|
||||
assert.deepEqual(copyOfOutdoorArea(area).points[0], [0.5, 0.5]);
|
||||
});
|
||||
|
||||
test("new furniture has its type's size, and stairs reach to the floor above", () => {
|
||||
const ground = floorWith([box("r", 0, 0, 4, 4)], { elevation: 0, height: 2.5 });
|
||||
const upper = floorWith([], { id: "u", elevation: 2.8 } as never);
|
||||
const doc = { floors: [ground, upper] } as unknown as Building;
|
||||
const chair = newFurniture("sofa", doc, ground, [1.23456, 2]);
|
||||
assert.deepEqual([chair.type, chair.x, chair.z, chair.rotation], ["sofa", 1.235, 2, 0]);
|
||||
assert.equal(newFurniture("stairs", doc, ground, [0, 0]).h, 2.8);
|
||||
assert.equal(newFurniture("stairs", doc, upper, [0, 0]).h, 2.75, "no floor above: a little over the ceiling");
|
||||
});
|
||||
|
||||
test("a copy of furniture is moved by 30 cm and independent; a vehicle becomes a parking spot that holds it", () => {
|
||||
const original = sofa({ name: "Ledersofa" });
|
||||
const copy = copyOfFurniture(original);
|
||||
assert.deepEqual([copy.x, copy.z], [1.3, 1.3]);
|
||||
assert.notEqual(copy.id, original.id);
|
||||
const spot = parkingSpotFor({ ...sofa({ type: "tesla", w: 2, d: 5, name: "Model Y" }) });
|
||||
assert.equal(spot.type, "parking");
|
||||
assert.equal(spot.vehicle, "tesla");
|
||||
assert.equal(spot.name, "Model Y");
|
||||
assert.ok(spot.w >= 2.5 && spot.d >= 5.4);
|
||||
});
|
||||
|
||||
test("device and furniture can stand in for each other and keep place, turn, name and lock", () => {
|
||||
const furniture = furnitureForDevice(pin("media_player.tv", 2, 3, { rotation: 90, name: "TV", locked: true }), "tv");
|
||||
assert.deepEqual([furniture.x, furniture.z, furniture.rotation, furniture.entity, furniture.name, furniture.locked], [2, 3, 90, "media_player.tv", "TV", true]);
|
||||
const back = deviceForFurniture(sofa({ rotation: 180, name: "Lamp" }), "light.x");
|
||||
assert.deepEqual([back.entity_id, back.rotation, back.name, back.y], ["light.x", 180, "Lamp", null]);
|
||||
assert.equal("name" in deviceForFurniture(sofa(), "light.x"), false);
|
||||
});
|
||||
|
||||
test("removing a device takes its ceiling lamp too, on every floor", () => {
|
||||
const doc = {
|
||||
floors: [floorWith([], { placements: [pin("light.a", 1, 1), pin("sensor.b", 1, 1)], furniture: [sofa({ id: "l", type: "lamp_ceiling", entity: "light.a" }), sofa({ id: "keep" })] }), floorWith([], { id: "u", placements: [pin("light.a", 2, 2)] } as never)],
|
||||
} as unknown as Building;
|
||||
removeDevice(doc, "light.a");
|
||||
assert.deepEqual(doc.floors[0].placements.map((p) => p.entity_id), ["sensor.b"]);
|
||||
assert.deepEqual(doc.floors[0].furniture.map((f) => f.id), ["keep"]);
|
||||
assert.equal(doc.floors[1].placements.length, 0);
|
||||
});
|
||||
|
||||
test("placing entities in a room: lights become ceiling lamps, others pins, and ones placed elsewhere move over", () => {
|
||||
const room = box("r", 0, 0, 5, 4);
|
||||
const floor = floorWith([room, box("q", 5, 0, 9, 4)], { placements: [pin("sensor.moves", 7, 2)] });
|
||||
const doc = { floors: [floor] } as unknown as Building;
|
||||
placeInRoom(doc, floor, room, ["light.new", "sensor.moves", "switch.s"]);
|
||||
const lamps = floor.furniture.filter((f) => f.type === "lamp_ceiling");
|
||||
assert.deepEqual(lamps.map((l) => l.entity), ["light.new"]);
|
||||
assert.deepEqual(floor.placements.map((p) => p.entity_id).sort(), ["sensor.moves", "switch.s"]);
|
||||
assert.ok(floor.placements.every((p) => p.x > 0 && p.x < 5), "inside the room");
|
||||
assert.deepEqual(roomCentre(room), [2.5, 2]);
|
||||
});
|
||||
|
||||
test("an opening dropped on an edge snaps to the grid and stays inside the edge", () => {
|
||||
assert.equal(offsetOnEdge(4, 1.23, 0.9, 0.1), 1.2);
|
||||
assert.equal(offsetOnEdge(4, 0, 0.9, 0.1), 0.45);
|
||||
assert.equal(offsetOnEdge(4, 9, 0.9, 0.1), 3.55);
|
||||
assert.equal(offsetOnEdge(4, 1.234, 0.9, 0), 1.234);
|
||||
assert.equal(offsetOnEdge(0.5, 3, 0.9, 0.1), 0.25, "narrower than the opening: its middle");
|
||||
});
|
||||
|
||||
test("a new door or window follows its preset, narrowed to fit short edges", () => {
|
||||
const host = { roomId: "r", edge: 2, length: 4, offset: (width: number) => width / 2 };
|
||||
const door = newOpening("door", host);
|
||||
assert.deepEqual([door.type, door.width, door.height, door.leaves, door.offset, door.edge], ["door", 0.9, 2.05, 1, 0.45, 2]);
|
||||
const narrow = newOpening("window_double", { ...host, length: 1, wall: "w" });
|
||||
assert.equal(narrow.width, 0.9);
|
||||
assert.equal(narrow.wall, "w");
|
||||
assert.equal(newOpening("garage", { ...host, length: 0.2 }).width, 0.3);
|
||||
});
|
||||
|
||||
test("changing the kind of an opening keeps its width only when its shape stays the same", () => {
|
||||
const door = newOpening("door", { roomId: "r", edge: 0, length: 5, offset: () => 1 });
|
||||
assert.equal("width" in openingKindPatch({ ...door, width: 1.1 }, "door"), false);
|
||||
const patch = openingKindPatch({ ...door, width: 1.1 }, "window");
|
||||
assert.deepEqual([patch.type, patch.width, patch.sill, patch.style], ["window", 1.2, 0.9, null]);
|
||||
assert.equal(openingKindPatch(door, "front").style, "front");
|
||||
// a lift-and-slide door slides; changing it back into a terrace door turns again
|
||||
const slide = openingKindPatch(door, "lift_slide");
|
||||
assert.deepEqual([slide.type, slide.opens, slide.sill], ["window", "slide", 0]);
|
||||
assert.equal(openingKindPatch({ ...door, ...slide } as typeof door, "terrace").opens, null);
|
||||
});
|
||||
|
||||
test("a new glass wall or lift-and-slide door keeps its preset's look and way of opening; doors stay automatic", () => {
|
||||
const host = { roomId: "r", edge: 0, length: 5, offset: () => 1 };
|
||||
assert.equal(newOpening("glass_wall", host).style, "glass_wall");
|
||||
assert.equal(newOpening("lift_slide", host).opens, "slide");
|
||||
assert.equal(newOpening("door", host).style, undefined);
|
||||
assert.equal(newOpening("front", host).style, undefined);
|
||||
});
|
||||
|
||||
test("the edge an opening sits on, for rooms and free walls", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 3)], { walls: [{ id: "w1", a: [0, 5], b: [3, 5], thickness: null }] } as never);
|
||||
assert.deepEqual(edgeOf({ ...opening("o", "r", "door"), edge: 1 }, floor), [[4, 0], [4, 3]]);
|
||||
assert.deepEqual(edgeOf({ ...opening("o", "x", "door"), wall: "w1" }, floor), [[0, 5], [3, 5]]);
|
||||
assert.equal(edgeOf({ ...opening("o", "nope", "door"), edge: 0 }, floor), null);
|
||||
});
|
||||
|
||||
test("arrow keys move furniture, devices, walls and outdoor areas by the step", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)], {
|
||||
furniture: [sofa()],
|
||||
placements: [pin("light.a", 2, 2)],
|
||||
walls: [{ id: "w", a: [0, 0], b: [1, 0], thickness: null }],
|
||||
outdoor: [{ id: "o", type: "lawn", points: [[0, 0], [1, 0], [1, 1]] }],
|
||||
} as never);
|
||||
assert.deepEqual(applied(nudge(floor, { kind: "furniture", id: "s" }, 0.1, -0.05), floor).furniture[0].x, 1.1);
|
||||
assert.equal(applied(nudge(floor, { kind: "device", id: "light.a" }, 0.1, -0.05), floor).placements[0].z, 1.95);
|
||||
const wall = applied(nudge(floor, { kind: "wall", id: "w" }, 1, 0), floor).walls![0];
|
||||
assert.deepEqual([wall.a, wall.b], [[1, 0], [2, 0]]);
|
||||
assert.deepEqual(applied(nudge(floor, { kind: "outdoor", id: "o" }, 0, 1), floor).outdoor[0].points[2], [1, 2]);
|
||||
assert.equal(nudge(floor, { kind: "device", id: "light.missing" }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
test("a room moves with the devices inside it, a selected corner moves alone", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 4)], { placements: [pin("light.in", 1, 1), pin("light.out", 9, 9)] });
|
||||
const room = applied(nudge(floor, { kind: "room", id: "r", corner: null }, 1, 0), floor);
|
||||
assert.deepEqual(room.rooms[0].points[0], [1, 0]);
|
||||
assert.deepEqual(room.placements.map((p) => p.x), [2, 9]);
|
||||
const corner = applied(nudge(floor, { kind: "room", id: "r", corner: 2 }, 0, 0.5), floor);
|
||||
assert.deepEqual(corner.rooms[0].points.map((p) => p[1]), [0, 0, 4.5, 4]);
|
||||
assert.deepEqual(corner.placements.map((p) => p.x), [1, 9]);
|
||||
assert.equal(nudge(floor, { kind: "room", id: "nope", corner: null }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
test("an opening slides along its wall only: across it nothing changes, and it stays within the edge", () => {
|
||||
const floor = floorWith([box("r", 0, 0, 4, 3)], { openings: [{ ...opening("o", "r", "door"), edge: 0, offset: 1, width: 1 }] });
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, 0.5, 0), floor).openings[0].offset, 1.5);
|
||||
assert.equal(nudge(floor, { kind: "opening", id: "o" }, 0, 1), NO_CHANGE, "edge 0 runs along x");
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, 10, 0), floor).openings[0].offset, 3.5);
|
||||
assert.equal(applied(nudge(floor, { kind: "opening", id: "o" }, -10, 0), floor).openings[0].offset, 0.5);
|
||||
assert.equal(nudge(floor, { kind: "opening", id: "gone" }, 1, 0), NOTHING_TO_MOVE);
|
||||
});
|
||||
|
||||
import { outdoorRectangleAfter } from "./items.ts";
|
||||
|
||||
test("an outdoor area's rectangle follows typed values and never gets thinner than 10 cm", () => {
|
||||
const area = newOutdoorArea([[0, 0], [4, 0], [4, 2], [0, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "x", 1), [[1, 0], [5, 0], [5, 2], [1, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "w", 6), [[0, 0], [6, 0], [6, 2], [0, 2]]);
|
||||
assert.deepEqual(outdoorRectangleAfter(area, "d", 0), [[0, 0], [4, 0], [4, 0.1], [0, 0.1]]);
|
||||
});
|
||||
|
||||
test("an outdoor area gets a corner in the middle of an edge and gives one back, but never drops below three", () => {
|
||||
const pool = newOutdoorArea([[0, 0], [4, 0], [4, 3], [0, 3]]);
|
||||
insertOutdoorCorner(pool, 1, [4.0004, 1.5]);
|
||||
assert.deepEqual(pool.points, [[0, 0], [4, 0], [4, 1.5], [4, 3], [0, 3]]);
|
||||
insertOutdoorCorner(pool, 4, [0, 1.5]);
|
||||
assert.equal(pool.points.length, 6, "the closing edge (last corner back to the first) can be split too");
|
||||
assert.deepEqual(pool.points[5], [0, 1.5]);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(removeOutdoorCorner(pool, 2), true);
|
||||
assert.equal(pool.points.length, 3);
|
||||
assert.equal(removeOutdoorCorner(pool, 0), false);
|
||||
});
|
||||
|
||||
test("what stands higher is drawn on top, so a click hits the speaker on the desk (#105)", () => {
|
||||
const desk = { ...sofa({ id: "desk", type: "desk", w: 1.6, d: 0.8, h: 0.75 }), x: 2, z: 2 };
|
||||
const speaker = { ...sofa({ id: "speaker", type: "sofa", w: 0.1, d: 0.1, h: 0.2, mount_y: 0.75 }), x: 2, z: 2 };
|
||||
const floor = floorWith([], { furniture: [speaker, desk] });
|
||||
assert.deepEqual(drawOrder(floor).map((f) => f.id), ["desk", "speaker"]);
|
||||
const same = floorWith([], { furniture: [sofa({ id: "a", x: 1 }), sofa({ id: "b", x: 3 })] });
|
||||
assert.deepEqual(drawOrder(same).map((f) => f.id), ["a", "b"], "equal heights keep their order");
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
// Making and changing the things on a floor: furniture, devices, outdoor areas, free walls, floor openings and doors and windows.
|
||||
|
||||
import { autoPlace } from "../../../devices.ts";
|
||||
import { mountBase } from "../../../packs.ts";
|
||||
import { DEFAULT_STAIR } from "../../../geometry/stairs.ts";
|
||||
import { openingHost } from "../../../geometry/walls.ts";
|
||||
import {
|
||||
bounds,
|
||||
centroid,
|
||||
FURNITURE_SIZE,
|
||||
isLamp,
|
||||
AUTO_STYLES,
|
||||
OPENING_PRESETS,
|
||||
openingPreset,
|
||||
uid,
|
||||
type Building,
|
||||
type Floor,
|
||||
type FreeWall,
|
||||
type Furniture,
|
||||
type Opening,
|
||||
type OpeningPreset,
|
||||
type OutdoorArea,
|
||||
type Placement,
|
||||
type Room,
|
||||
type Vec2,
|
||||
} from "../../../model.ts";
|
||||
import { furnitureSize } from "../../../packs.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const quarterTurns = (degrees: number, by: number) => (((degrees + by) % 360) + 360) % 360;
|
||||
|
||||
// free walls, outdoor areas and floor openings
|
||||
|
||||
export function newFreeWall(a: Vec2, b: Vec2): FreeWall {
|
||||
return { id: uid("wall"), a: [thousandths(a[0]), thousandths(a[1])], b: [thousandths(b[0]), thousandths(b[1])], thickness: null };
|
||||
}
|
||||
|
||||
/** The far end of a free wall after its length was typed: the wall keeps its start and its direction. */
|
||||
export function wallEndForLength(wall: FreeWall, length: number): Vec2 {
|
||||
const current = Math.hypot(wall.b[0] - wall.a[0], wall.b[1] - wall.a[1]) || 1;
|
||||
const k = Math.max(0.1, length) / current;
|
||||
return [thousandths(wall.a[0] + (wall.b[0] - wall.a[0]) * k), thousandths(wall.a[1] + (wall.b[1] - wall.a[1]) * k)];
|
||||
}
|
||||
|
||||
/** A wall as high as the floor is stored as "no height of its own". */
|
||||
export const wallHeightPatch = (height: number, floorHeight: number): { height: number | null } => ({ height: height >= floorHeight - 0.005 ? null : Math.max(0.05, height) });
|
||||
|
||||
/** A floor opening (stairwell, gallery) drawn as a rectangle: a hole in the floor of this level. */
|
||||
export function newFloorOpening(lo: Vec2, hi: Vec2): Furniture {
|
||||
return { id: uid("hole"), type: "stairwell", x: thousandths((lo[0] + hi[0]) / 2), z: thousandths((lo[1] + hi[1]) / 2), w: thousandths(hi[0] - lo[0]), d: thousandths(hi[1] - lo[1]), h: 0.02, rotation: 0, variant: null };
|
||||
}
|
||||
|
||||
export const newOutdoorArea = (points: readonly Vec2[]): OutdoorArea => ({ id: uid("outdoor"), type: "lawn", points: points.map(([x, z]) => [thousandths(x), thousandths(z)]) });
|
||||
|
||||
/** A new corner in the middle of an outdoor area's edge (edge i runs from corner i to the next), so that a rectangle can become any shape. */
|
||||
export function insertOutdoorCorner(area: OutdoorArea, edge: number, at: Vec2): void {
|
||||
area.points.splice(edge + 1, 0, [thousandths(at[0]), thousandths(at[1])]);
|
||||
}
|
||||
|
||||
/** Takes a corner away; an area keeps at least three. */
|
||||
export function removeOutdoorCorner(area: OutdoorArea, index: number): boolean {
|
||||
if (area.points.length <= 3 || index < 0 || index >= area.points.length) return false;
|
||||
area.points.splice(index, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
export const copyOfOutdoorArea = (area: OutdoorArea): OutdoorArea => ({ ...area, id: uid("outdoor"), points: area.points.map(([x, z]) => [thousandths(x + 0.5), thousandths(z + 0.5)]) });
|
||||
|
||||
// furniture
|
||||
|
||||
/** A new piece of furniture of this type at `at`. Stairs reach up to the next floor above, or a little above the ceiling of the top one. */
|
||||
export function newFurniture(type: string, doc: Building, floor: Floor, at: Vec2): Furniture {
|
||||
const [w, d, height] = furnitureSize(type);
|
||||
const above = doc.floors.filter((f) => f.elevation > floor.elevation).sort((p, q) => p.elevation - q.elevation)[0];
|
||||
const h = type === "stairs" ? thousandths(above ? above.elevation - floor.elevation : floor.height + 0.25) : height;
|
||||
const item: Furniture = { id: uid("furniture"), type, x: thousandths(at[0]), z: thousandths(at[1]), rotation: 0, w, d, h, variant: null };
|
||||
// new stairs are shaped stairs: shape, turn and steps are set in the form, and they open only the floor they need
|
||||
if (type === "stairs") item.stair = { ...DEFAULT_STAIR };
|
||||
return item;
|
||||
}
|
||||
|
||||
/** A copy of a piece of furniture 30 cm to the south east. */
|
||||
export const copyOfFurniture = (item: Furniture): Furniture => ({ ...structuredClone(item), id: uid("furniture"), x: thousandths(item.x + 0.3), z: thousandths(item.z + 0.3) });
|
||||
|
||||
export const turnedBy = (degrees: number, delta: number): number => quarterTurns(degrees, delta);
|
||||
|
||||
/** A vehicle that was placed as plain furniture becomes a parking spot holding it: presence and the car's live data live there. */
|
||||
export function parkingSpotFor(vehicle: Furniture): Furniture {
|
||||
const [w, d, h] = furnitureSize("parking");
|
||||
return {
|
||||
id: uid("furniture"),
|
||||
type: "parking",
|
||||
x: vehicle.x,
|
||||
z: vehicle.z,
|
||||
rotation: vehicle.rotation,
|
||||
w: Math.max(w, thousandths(vehicle.w + 0.5)),
|
||||
d: Math.max(d, thousandths(vehicle.d + 0.4)),
|
||||
h,
|
||||
variant: null,
|
||||
vehicle: vehicle.type,
|
||||
...(vehicle.name ? { name: vehicle.name } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// devices
|
||||
|
||||
/** A piece of furniture of this type standing for a placed device, where its pin was. */
|
||||
export function furnitureForDevice(placed: Placement, type: string): Furniture {
|
||||
const [w, d, h] = furnitureSize(type);
|
||||
return { id: uid("furniture"), type, x: placed.x, z: placed.z, rotation: placed.rotation ?? 0, w, d, h, variant: null, entity: placed.entity_id, name: placed.name ?? null, animations_enabled: placed.animations_enabled, effect_animations: structuredClone(placed.effect_animations), ...(placed.locked ? { locked: true } : {}) };
|
||||
}
|
||||
|
||||
/** A plain device pin where a piece of furniture linked by hand stood. */
|
||||
export const deviceForFurniture = (item: Furniture, entityId: string): Placement => ({ entity_id: entityId, x: item.x, z: item.z, y: null, rotation: item.rotation, animations_enabled: item.animations_enabled, effect_animations: structuredClone(item.effect_animations), ...(item.name ? { name: item.name } : {}) });
|
||||
|
||||
/** Takes a device off every floor, with the ceiling lamp that stands for it. */
|
||||
export function removeDevice(doc: Building, entityId: string): void {
|
||||
for (const floor of doc.floors) {
|
||||
floor.placements = floor.placements.filter((p) => p.entity_id !== entityId);
|
||||
floor.furniture = floor.furniture.filter((m) => !(isLamp(m.type) && m.entity === entityId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts entities into a room. One that was placed elsewhere moves here. Lights become ceiling lamps, which can be tapped directly in
|
||||
* 3D; everything else becomes a pin.
|
||||
*/
|
||||
export function placeInRoom(doc: Building, floor: Floor, room: Room, entityIds: readonly string[]): void {
|
||||
const moving = new Set(entityIds);
|
||||
for (const f of doc.floors) {
|
||||
f.placements = f.placements.filter((p) => !moving.has(p.entity_id));
|
||||
f.furniture = f.furniture.filter((m) => !(isLamp(m.type) && m.entity && moving.has(m.entity)));
|
||||
}
|
||||
const taken: Vec2[] = [...floor.placements.map((p): Vec2 => [p.x, p.z]), ...floor.furniture.filter((m) => isLamp(m.type)).map((m): Vec2 => [m.x, m.z])];
|
||||
for (const spot of autoPlace(room, entityIds, taken)) {
|
||||
if (!spot.entity_id.startsWith("light.")) {
|
||||
floor.placements.push(spot);
|
||||
continue;
|
||||
}
|
||||
const [w, d, h] = FURNITURE_SIZE.lamp_ceiling;
|
||||
floor.furniture.push({ id: uid("furniture"), type: "lamp_ceiling", x: spot.x, z: spot.z, rotation: 0, w, d, h, variant: null, entity: spot.entity_id, power: null });
|
||||
}
|
||||
}
|
||||
|
||||
/** The middle of the room a point lies in, as a place for a device. */
|
||||
export function roomCentre(room: Room): Vec2 {
|
||||
const [x, z] = centroid(room.points);
|
||||
return [thousandths(x), thousandths(z)];
|
||||
}
|
||||
|
||||
// doors and windows
|
||||
|
||||
/** Where along an edge (from its start, in metres) an opening of this width sits when dropped at `along`, kept inside the edge. */
|
||||
export function offsetOnEdge(edgeLength: number, along: number, width: number, grid: number): number {
|
||||
const half = Math.min(width, edgeLength) / 2;
|
||||
const snapped = grid > 0 ? Math.round(along / grid) * grid : along;
|
||||
return thousandths(Math.min(edgeLength - half, Math.max(half, snapped)));
|
||||
}
|
||||
|
||||
/** A new opening of this kind on an edge: as wide as the preset, but never wider than the edge allows. */
|
||||
export function newOpening(preset: OpeningPreset, host: { roomId: string; edge: number; wall?: string; length: number; offset(width: number): number }): Opening {
|
||||
const kind = OPENING_PRESETS[preset] as { type: Opening["type"]; leaves: 1 | 2; sill: number; height: number; width: number; style?: Opening["style"]; opens?: Opening["opens"] };
|
||||
const width = thousandths(Math.min(kind.width, Math.max(0.3, host.length - 0.1)));
|
||||
return {
|
||||
id: uid("opening"),
|
||||
room_id: host.roomId,
|
||||
edge: host.edge,
|
||||
...(host.wall ? { wall: host.wall } : {}),
|
||||
offset: host.offset(width),
|
||||
width,
|
||||
type: kind.type,
|
||||
sill: kind.sill,
|
||||
height: kind.height,
|
||||
hinge: "left",
|
||||
leaves: kind.leaves,
|
||||
swing: "in",
|
||||
// the preset's own look (a glass wall; room and front doors stay automatic by their wall) and way of opening
|
||||
...(kind.style && !AUTO_STYLES.has(kind.style) ? { style: kind.style } : {}),
|
||||
...(kind.opens ? { opens: kind.opens } : {}),
|
||||
cover: null,
|
||||
contact: null,
|
||||
contact2: null,
|
||||
tilt: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What changing an opening into another kind sets. It keeps its own width unless it already was of that kind's shape. */
|
||||
export function openingKindPatch(opening: Opening, preset: OpeningPreset): Partial<Opening> {
|
||||
const kind = OPENING_PRESETS[preset] as { type: Opening["type"]; leaves: 1 | 2; sill: number; height: number; width: number; style?: Opening["style"]; opens?: Opening["opens"] };
|
||||
const widthChange = openingPreset(opening) === preset ? {} : { width: kind.width };
|
||||
return { type: kind.type, leaves: kind.leaves, sill: kind.sill, height: kind.height, style: kind.style ?? null, opens: kind.opens ?? null, ...widthChange };
|
||||
}
|
||||
|
||||
/** The wall edge an opening sits on, as its two end points. */
|
||||
export function edgeOf(opening: Opening, floor: Floor): [Vec2, Vec2] | null {
|
||||
const host = openingHost(opening, floor.rooms, floor.walls ?? []);
|
||||
if (!host) return null;
|
||||
return [host.room.points[host.edge], host.room.points[(host.edge + 1) % host.room.points.length]];
|
||||
}
|
||||
|
||||
/** The outline of an outdoor area as a rectangle after its left, top, width or depth was typed. Sizes never get below 10 cm. */
|
||||
export function outdoorRectangleAfter(area: OutdoorArea, field: "x" | "z" | "w" | "d", value: number): Vec2[] {
|
||||
const box = bounds(area.points);
|
||||
let { x0, z0, x1, z1 } = box;
|
||||
if (field === "x") [x0, x1] = [value, value + (x1 - x0)];
|
||||
else if (field === "z") [z0, z1] = [value, value + (z1 - z0)];
|
||||
else if (field === "w") x1 = x0 + Math.max(0.1, value);
|
||||
else z1 = z0 + Math.max(0.1, value);
|
||||
return [[x0, z0], [x1, z0], [x1, z1], [x0, z1]].map(([x, z]) => [thousandths(x), thousandths(z)] as Vec2);
|
||||
}
|
||||
|
||||
/**
|
||||
* The furniture of a floor in the order the plan draws it: what stands higher is drawn later, so it lies on top and is the one a click
|
||||
* hits (a speaker on a desk, a lamp on a shelf – #105). Pieces at the same height keep their order.
|
||||
*/
|
||||
export function drawOrder(floor: Floor): Furniture[] {
|
||||
return floor.furniture
|
||||
.map((item, index) => ({ item, index, base: mountBase(floor, item) }))
|
||||
.sort((a, b) => a.base - b.base || a.index - b.index)
|
||||
.map((e) => e.item);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { fold, hasAllWords, wordsOf } from "./library.ts";
|
||||
|
||||
test("accents and case do not matter", () => {
|
||||
assert.equal(fold("Küche ÉCLAIR"), "kuche eclair");
|
||||
assert.ok(hasAllWords(wordsOf("kuhlschrank"), "Kühlschrank refrigerator"));
|
||||
assert.ok(hasAllWords(wordsOf("REFRIGERATOR"), "Kühlschrank refrigerator"));
|
||||
});
|
||||
|
||||
test("every word must be found somewhere, in any order", () => {
|
||||
assert.ok(hasAllWords(wordsOf("sink kuche"), "Doppelspüle sink_double Küche"));
|
||||
assert.ok(!hasAllWords(wordsOf("fridge nothing"), "Kühlschrank fridge"));
|
||||
assert.ok(hasAllWords(wordsOf(" "), "anything"));
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
// The search of the furniture library: every word of the query must appear somewhere in an item's names, its id or its kind;
|
||||
// accents and case do not matter ("kuche" finds "Küche").
|
||||
|
||||
/** Lower case without accents. */
|
||||
export const fold = (text: string): string => text.toLowerCase().normalize("NFD").replace(/\p{M}/gu, "");
|
||||
|
||||
/** The words of a query, folded. */
|
||||
export const wordsOf = (query: string): string[] => fold(query).split(/\s+/).filter(Boolean);
|
||||
|
||||
/** Whether every word is found in the text (an empty query finds everything). */
|
||||
export const hasAllWords = (words: readonly string[], haystack: string): boolean => {
|
||||
const text = fold(haystack);
|
||||
return words.every((w) => text.includes(w));
|
||||
};
|
||||
Loaded 100 of 845 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user