first push
This commit is contained in:
commit
2a81b4a502
845 files changed
+356635
No files matched your search
@@ -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>`;
|
||||
}
|
||||
Reference in new issue
Block a user