Files
NextFloor/preview/index.html
2026-11-09 10:37:41 +01:00

500 lines
32 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8" />
<!-- like Home Assistant's own page: no Referer to other sites unless a request asks for one -->
<meta name="referrer" content="same-origin" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>NextFloor – Vorschau</title>
<style>
/* Like HA: the panel's parent has no explicit height, the panel sizes itself. */
body {
margin: 0;
background: var(--primary-background-color, #111111);
color: var(--primary-text-color, #e1e1e1);
}
</style>
</head>
<body>
<nextfloor-panel></nextfloor-panel>
<script src="./basic-types.js"></script>
<script src="./pack-ids.js"></script>
<script src="./pack-names.js"></script>
<script type="module">
// Mock of the Home Assistant frontend object with invented demo data.
import { DEMO_AREAS, DEMO_BUILDING, DEMO_FLOORS, DEMO_PACK, DEMO_ENTITIES, DEMO_STATES, DEMO_PICTURES } from "./demo-data.js";
const uploadedMeshes = new Map();
const params = new URLSearchParams(location.search);
// Home Assistant's default themes, so the preview shows how NextFloor follows them (?ha=light, dark otherwise)
const light = params.get("ha") === "light";
const haTheme = light
? { "--primary-color": "#03a9f4", "--text-primary-color": "#ffffff", "--primary-text-color": "#212121", "--secondary-text-color": "#727272", "--card-background-color": "#ffffff", "--primary-background-color": "#fafafa", "--secondary-background-color": "#e5e5e5", "--divider-color": "rgba(0, 0, 0, 0.12)", "--ha-card-border-radius": "12px", "--state-light-active-color": "#ffc107", "--error-color": "#db4437", "--success-color": "#43a047", "--info-color": "#039be5", "--primary-font-family": "Roboto, 'Noto Sans', sans-serif" }
: { "--primary-color": "#03a9f4", "--text-primary-color": "#ffffff", "--primary-text-color": "#e1e1e1", "--secondary-text-color": "#9b9b9b", "--card-background-color": "#1c1c1c", "--primary-background-color": "#111111", "--secondary-background-color": "#1a1a1a", "--divider-color": "rgba(225, 225, 225, 0.12)", "--ha-card-border-radius": "12px", "--state-light-active-color": "#ffc107", "--error-color": "#db4437", "--success-color": "#43a047", "--info-color": "#039be5", "--primary-font-family": "Roboto, 'Noto Sans', sans-serif" };
for (const [k, v] of Object.entries(haTheme)) document.documentElement.style.setProperty(k, v);
document.documentElement.style.colorScheme = light ? "light" : "dark";
// the power flow lines are on with ?flows (and off without, whatever an earlier page stored)
try {
localStorage.setItem("nextfloor.flows", params.has("flows") ? "1" : "0");
} catch {}
let building = params.has("empty") ? { version: 1, floors: [], settings: { wall_exterior: 0.24, wall_interior: 0.12, grid: 0.05 } } : DEMO_BUILDING;
// ?state=<url of a plan as JSON> starts from that plan (the tutorial recorder hands the end of one episode to the next)
if (params.has("state")) building = await (await fetch(params.get("state"))).json();
// ?shared: a plan shared as a file from NextFloor (a small page that embeds this one) arrives by message, with its own packs
let sharedPacks = [];
if (params.has("shared")) {
const shared = await new Promise((resolve) => {
addEventListener("message", (e) => {
if (e.data && e.data.type === "nextfloor-share" && e.data.building && Array.isArray(e.data.building.floors)) resolve(e.data);
});
(window.parent !== window ? window.parent : window.opener)?.postMessage({ type: "nextfloor-share-ready" }, "*");
});
building = shared.building;
sharedPacks = Array.isArray(shared.packs) ? shared.packs : [];
}
window.nfDemoState = () => structuredClone(building);
// ?map and ?north=180 switch the real map and the compass on for a look (the demo ships with both off)
if (params.has("forecast")) {
building = structuredClone(building);
building.settings.forecast = { days: 5, corner: params.get("forecast") === "left" ? "top_left" : "top_right" };
}
// ?chimney: one chimney of each shape on the first roof face, for a look
if (params.has("chimney")) {
building = structuredClone(building);
const roof = building.settings.roof;
const side = params.get("chimney") === "b" ? "b" : "a";
const face = roof.type === "custom" ? `${roof.sections[0].id}:${side}` : `main:${side}`;
roof.chimneys = ["brick", "round", "wide", "steel"].map((shape, i) => ({ id: `c${i}`, face, u: 1 + i * 2, v: 2.5, shape }));
}
if (params.has("map") || params.has("north")) {
building = structuredClone(building);
if (params.has("north")) building.settings.north = Number(params.get("north")) || 0;
if (params.has("map")) building.settings.map = { on: true, lat: 50.1109, lon: 8.6821, x: 5, z: 4, opacity: 0.6, zoom: 19, url: null };
}
// development view: a whole pack laid out in rows on a plain floor (?pack=nextfloor.ikea, or ?cars for the Teslas)
const showPack = params.get("pack") || (params.has("cars") ? "nextfloor.fahrzeuge" : null);
if (showPack) {
const pack = await (await fetch(`../custom_components/nextfloor/packs/${showPack}.json`)).json();
const prefix = params.get("cars") || (params.has("cars") ? "tesla" : params.get("only") || "");
let items = pack.items.filter((i) => i.id.startsWith(prefix));
// &colors: one of every colour of every item
if (params.has("colors")) items = items.flatMap((it) => (it.colors ?? [null]).map((c, k) => ({ ...it, variant: k === 0 ? null : c?.id ?? null })));
const eg = structuredClone(DEMO_BUILDING.floors[0]);
const rowWidth = Number(params.get("row")) || 30;
let x = 0.6, z = 0.6, rowDepth = 0, maxX = 0;
const furniture = [];
items.forEach((it, i) => {
const [w, d, h] = it.size;
if (x + w > rowWidth && x > 0.6) { x = 0.6; z += rowDepth + 0.8; rowDepth = 0; }
furniture.push({ id: `show${i}`, type: `pack:${pack.id}:${it.id}`, x: x + w / 2, z: z + d / 2, w, d, h, rotation: 0, variant: it.variant ?? null });
x += w + 0.7; rowDepth = Math.max(rowDepth, d); maxX = Math.max(maxX, x);
});
const width = maxX + 0.2, depth = z + rowDepth + 0.6;
eg.rooms = [{ ...eg.rooms[0], id: "room_show", name: "Showcase", area_id: null, points: [[0, 0], [width, 0], [width, depth], [0, depth]] }];
eg.openings = [];
eg.placements = [];
eg.outdoor = [];
eg.walls = [];
eg.furniture = furniture;
window.nfShowcase = { cx: width / 2, cz: depth / 2, width, depth };
building = { ...DEMO_BUILDING, floors: [eg], settings: { ...DEMO_BUILDING.settings, roof: { type: "none" } } };
}
// model showcase (?showcase): every model of NextFloor, a page of ten at a time, to look at them live
if (params.has("showcase")) {
const lang = params.get("lang") === "en" ? "en" : "de";
const text = { de: { title: "Alle Modelle", back: "Zur Demo", prev: "‹ zurück", next: "weiter ›", set: "Gruppe", order: "Reihenfolge im Raum: von links nach rechts, vorn nach hinten" }, en: { title: "All models", back: "Back to the demo", prev: "‹ previous", next: "next ›", set: "Group", order: "Order in the room: left to right, front to back" } }[lang];
const names = (n) => n?.[lang] ?? n?.en ?? Object.values(n ?? {})[0] ?? "";
const sets = [
...window.BASIC_TYPES.map((g) => ({ id: `basic:${g.id}`, label: `${names(g.name)}`, items: g.items.map((i) => ({ type: i.type, size: i.size, name: names(i.name) })) })),
];
for (const id of window.PACK_IDS) {
try {
const pack = await (await fetch(`../custom_components/nextfloor/packs/${id}.json`)).json();
sets.push({ id: `pack:${id.replace("nextfloor.", "")}`, label: lang === "en" ? (window.PACK_EN?.[pack.id] ?? pack.name) : pack.name, items: pack.items.map((i) => ({ type: `pack:${pack.id}:${i.id}`, size: i.size, name: names(i.name) })) });
} catch {}
}
const current = sets.find((x) => x.id === params.get("set")) ?? sets[0];
const perPage = 10;
const pages = Math.max(1, Math.ceil(current.items.length / perPage));
const page = Math.min(pages, Math.max(1, Number(params.get("page")) || 1));
const shown = current.items.slice((page - 1) * perPage, page * perPage);
const eg = structuredClone(DEMO_BUILDING.floors[0]);
// the walls are cut low in this view; tall models (trees, wardrobes) must still show whole
eg.cut_height = 12;
eg.height = 12;
const rowWidth = 8;
let x = 0.6, z = 0.6, rowDepth = 0, maxX = 0;
const furniture = [];
shown.forEach((it, i) => {
const [w, d, h] = it.size;
if (x + w > rowWidth && x > 0.6) { x = 0.6; z += rowDepth + 0.8; rowDepth = 0; }
furniture.push({ id: `show${i}`, type: it.type, x: x + w / 2, z: z + d / 2, w, d, h, rotation: 0, variant: null });
x += w + 0.7; rowDepth = Math.max(rowDepth, d); maxX = Math.max(maxX, x);
});
const width = Math.max(maxX + 0.2, 4), depth = z + rowDepth + 0.6;
eg.rooms = [{ ...eg.rooms[0], id: "room_show", name: text.title, area_id: null, points: [[0, 0], [width, 0], [width, depth], [0, depth]], wall_heights: [0, 0, 0, 0], wall_thickness: undefined, wall_splits: undefined }];
for (const key of ["openings", "placements", "outdoor", "walls"]) eg[key] = [];
eg.furniture = furniture;
building = { ...DEMO_BUILDING, floors: [eg], settings: { ...DEMO_BUILDING.settings, roof: { type: "none" } } };
const go = (set, n) => { const q = new URLSearchParams(location.search); q.set("set", set); q.set("page", String(n)); location.search = q.toString(); };
const bar = document.createElement("div");
bar.style.cssText = "position:fixed;left:12px;bottom:12px;z-index:50;max-width:min(360px,calc(100vw - 24px));padding:12px 14px;border-radius:14px;background:rgba(20,22,28,.92);color:#e8eaf0;font:13px Roboto,sans-serif;box-shadow:0 6px 24px rgba(0,0,0,.45)";
const select = Object.assign(document.createElement("select"), { innerHTML: sets.map((x) => `<option value="${x.id}" ${x === current ? "selected" : ""}>${x.label} (${x.items.length})</option>`).join("") });
select.style.cssText = "width:100%;margin:6px 0;padding:6px;border-radius:8px;background:#2a2d36;color:inherit;border:1px solid #444";
select.onchange = () => go(select.value, 1);
bar.innerHTML = `<b style="font-size:15px">${text.title}</b> <span style="opacity:.6">· ${text.set}</span>`;
bar.append(select);
const list = Object.assign(document.createElement("ol"), { innerHTML: shown.map((it) => `<li>${it.name}</li>`).join("") });
list.style.cssText = "margin:6px 0 8px 18px;padding:0;columns:2;line-height:1.5";
const note = Object.assign(document.createElement("div"), { textContent: text.order });
note.style.cssText = "opacity:.55;font-size:11px;margin-bottom:8px";
const nav = document.createElement("div");
nav.style.cssText = "display:flex;gap:8px;align-items:center";
const button = (label, disabled, onClick) => Object.assign(document.createElement("button"), { textContent: label, disabled, onclick: onClick, style: "padding:6px 12px;border-radius:8px;border:0;background:#03a9f4;color:#fff;cursor:pointer;opacity:" + (disabled ? ".35" : "1") });
const link = Object.assign(document.createElement("a"), { textContent: text.back, href: `?lang=${lang}`, style: "margin-left:auto;color:#7fd0ff" });
nav.append(button(text.prev, page <= 1, () => go(current.id, page - 1)), Object.assign(document.createElement("span"), { textContent: `${page} / ${pages}` }), button(text.next, page >= pages, () => go(current.id, page + 1)), link);
bar.append(list, note, nav);
// look into the room from above: the floor opened, the walls cut away
const open = setInterval(() => {
const panel = document.querySelector("nextfloor-panel");
if (!panel?.data?.building) return;
clearInterval(open);
panel._floorId = eg.id;
panel._wallMode = "cut";
}, 200);
addEventListener("DOMContentLoaded", () => document.body.append(bar));
if (document.readyState !== "loading") document.body.append(bar);
}
if (!params.has("showcase") && !params.has("pack") && !params.has("cars") && !params.has("noshowcase")) {
const link = Object.assign(document.createElement("a"), { href: `?showcase&lang=${params.get("lang") === "en" ? "en" : "de"}`, textContent: params.get("lang") === "en" ? "▦ All models" : "▦ Alle Modelle ansehen" });
link.style.cssText = "position:fixed;right:12px;bottom:12px;z-index:40;padding:8px 14px;border-radius:999px;background:rgba(20,22,28,.9);color:#7fd0ff;font:13px Roboto,sans-serif;text-decoration:none;box-shadow:0 4px 16px rgba(0,0,0,.4)";
document.body.append(link);
}
let revision = 1;
const images = { ...DEMO_PICTURES };
const listeners = new Set();
// invented restore points
let history = [{ id: "s0", revision: 0, saved_at: Date.now() / 1000 - 3600, building: structuredClone(building) }];
// furniture packs: the invented demo pack and the packs that come with NextFloor
let importedPacks = null;
// one shared load: parallel callers must not see the list half filled
let packsLoad = null;
function previewPacks() {
packsLoad ??= (async () => {
const list = [DEMO_PACK, ...sharedPacks];
for (const id of window.PACK_IDS) {
try {
const res = await fetch(`../custom_components/nextfloor/packs/${id}.json`);
if (res.ok) list.push({ builtin: true, ...(await res.json()) });
} catch {
// served without the packs: the demo pack alone
}
}
importedPacks = list;
return list;
})();
return packsLoad.then(() => importedPacks);
}
const hass = {
language: params.get("lang") || "de",
config: { latitude: 50.1109, longitude: 8.6821 },
themes: { darkMode: !light },
user: { is_admin: !params.has("user"), name: "Demo" },
areas: DEMO_AREAS,
floors: DEMO_FLOORS,
entities: DEMO_ENTITIES,
devices: {},
states: structuredClone(DEMO_STATES),
connection: {
async subscribeMessage(cb) {
listeners.add(cb);
return async () => listeners.delete(cb);
},
},
async callService(domain, service, data) {
// enough behaviour to see the effect of the room panel and of taps in 3D
const states = { ...current.states };
for (const id of [].concat(data?.entity_id ?? [])) {
const st = states[id];
if (!st) continue;
const next = { ...st, attributes: { ...st.attributes } };
const a = next.attributes;
const setOn = (on) => {
next.state = on ? "on" : "off";
if (domain === "light" && on && a.brightness === undefined) a.brightness = 200;
if (domain === "light" && !on) delete a.brightness;
};
if (service === "toggle") setOn(st.state !== "on");
else if (service === "turn_off") setOn(false);
else if (service === "turn_on" && domain === "light") {
setOn(true);
if (data.brightness_pct !== undefined) a.brightness = Math.round((data.brightness_pct / 100) * 255);
if (data.color_temp_kelvin !== undefined) Object.assign(a, { color_temp_kelvin: data.color_temp_kelvin, color_mode: "color_temp" });
if (data.rgb_color) Object.assign(a, { rgb_color: data.rgb_color, color_mode: "hs" });
} else if (service === "open_cover") {
next.state = "open";
a.current_position = 100;
} else if (service === "close_cover") {
next.state = "closed";
a.current_position = 0;
} else if (service === "set_cover_position") {
a.current_position = data.position;
next.state = data.position > 0 ? "open" : "closed";
} else if (service === "set_temperature") a.temperature = data.temperature;
else if (service === "set_hvac_mode") next.state = data.hvac_mode;
else if (service === "media_play_pause") next.state = st.state === "playing" ? "paused" : "playing";
else if (service === "volume_set") a.volume_level = data.volume_level;
states[id] = next;
}
current = { ...current, states };
if (window.nfCard) window.nfCard.hass = current;
else if (window.nfPanel) window.nfPanel.hass = current;
},
// a model the owner uploaded: only when the page is told where to read it from (?meshdir=)
async fetchWithAuth(path, init = {}) {
const id = /mesh\/([a-z0-9_%]+)/.exec(path)?.[1];
// models uploaded in this page stay in memory, as on a real Home Assistant they stay in its configuration folder
if (id && init.method === "POST") return uploadedMeshes.set(id, init.body) && new Response(null, { status: 201 });
if (id && init.method === "DELETE") return uploadedMeshes.delete(id) && new Response(null, { status: 204 });
if (id && uploadedMeshes.has(id)) return new Response(uploadedMeshes.get(id), { status: 200 });
const dir = params.get("meshdir");
return id && dir ? fetch(`${dir}/${id}.glb`) : new Response(null, { status: 404 });
},
async callWS(msg) {
switch (msg.type) {
case "call_service": {
// the weather forecast card (?forecast): five invented days
if (msg.domain !== "weather" || msg.service !== "get_forecasts") return { response: {} };
const id = msg.target.entity_id;
const kinds = ["sunny", "partlycloudy", "rainy", "cloudy", "snowy"];
const forecast = kinds.map((condition, i) => ({ datetime: new Date(Date.now() + i * 86400000).toISOString(), condition, temperature: 12 - i * 2, templow: 4 - i, precipitation: condition === "rainy" ? 4.5 : 0, precipitation_probability: condition === "snowy" ? 60 : 0 }));
return { response: { [id]: { forecast } } };
}
case "nextfloor/building/get": {
// the online demo has no private packs: their items would stand as grey boxes, so leave them out
const packs = await previewPacks();
const known = new Set(packs.flatMap((p) => p.items.map((it) => `pack:${p.id}:${it.id}`)));
const shown = structuredClone(building);
for (const f of shown.floors) f.furniture = f.furniture.filter((m) => !m.type.startsWith("pack:") || known.has(m.type));
return { building: shown, revision };
}
case "nextfloor/building/save":
// ?savefail simulates a backend that still runs an older version
if (params.has("savefail")) throw { code: "invalid_format", message: "extra keys not allowed @ data['building']['floors'][0]['furniture'][0]['entity']" };
building = structuredClone(msg.building);
revision += 1;
for (const cb of listeners) cb({ revision });
return { revision };
case "history/history_during_period": {
// invented recorder history for the time travel: every light and door changes a few times over the span
const from = Date.parse(msg.start_time) / 1000;
const to = Date.parse(msg.end_time) / 1000;
const out = {};
(msg.entity_ids ?? []).forEach((id, k) => {
const st = this.states[id];
if (!st) return;
if (id.startsWith("sensor.") && Number.isFinite(Number(st.state))) {
// a number over the day: solar as a bell over noon, everything else wandering around its value
const rows = [];
for (let i = 0; i <= 96; i++) {
const t = from + ((to - from) * i) / 96;
const hour = new Date(t * 1000).getHours() + new Date(t * 1000).getMinutes() / 60;
const sun = Math.max(0, Math.sin(((hour - 6) / 14) * Math.PI));
const base = Number(st.state);
const v = /pv|solar/.test(id) ? Math.round(5200 * sun * (0.8 + 0.2 * Math.sin(i))) : Math.round(base * (0.6 + 0.4 * Math.abs(Math.sin(i / 7 + k))));
rows.push({ s: String(v), lu: t });
}
out[id] = rows;
return;
}
const rows = [{ s: id.startsWith("light.") || id.startsWith("binary_sensor.") ? "off" : st.state, a: st.attributes, lu: from }];
const steps = 6 + (k % 5);
for (let i = 1; i <= steps; i++) rows.push({ s: i % 2 ? (id.startsWith("cover.") ? "closed" : "on") : id.startsWith("cover.") ? "open" : "off", lu: from + ((to - from) * (i + (k % 3) / 3)) / (steps + 1) });
out[id] = rows;
});
return out;
}
case "nextfloor/history/list":
return { snapshots: history.map(({ building: b, ...rest }) => ({ ...rest, floors: b.floors.length, rooms: b.floors.reduce((n, f) => n + f.rooms.length, 0), furniture: b.floors.reduce((n, f) => n + f.furniture.length, 0) })).reverse() };
case "nextfloor/history/snapshot": {
const id = `s${history.length + 1}`;
history.push({ id, revision, saved_at: Date.now() / 1000, building: structuredClone(building), ...(msg.name ? { name: msg.name } : {}) });
return { id };
}
case "nextfloor/history/get": {
const snap = history.find((h) => h.id === msg.snapshot_id);
if (!snap) throw { code: "not_found", message: "Restore point not found" };
return { building: structuredClone(snap.building) };
}
case "nextfloor/history/delete":
history = history.filter((h) => h.id !== msg.snapshot_id);
return null;
case "nextfloor/history/restore": {
const snap = history.find((h) => h.id === msg.snapshot_id);
building = structuredClone(snap.building);
revision += 1;
for (const cb of listeners) cb({ revision });
return { revision };
}
case "nextfloor/image/get":
if (!images[msg.image_id]) throw { code: "not_found", message: "Image not found" };
return { data: images[msg.image_id] };
case "nextfloor/image/set":
images[msg.image_id] = msg.data;
return null;
case "nextfloor/packs/list":
return { packs: await previewPacks() };
case "nextfloor/packs/import": {
// plain JSON (or a wrapped {"payload": …} file), like the integration
let data = JSON.parse(msg.pack);
if (data.payload) data = data.payload;
if (data.format !== "nfpack") throw { code: "not_a_pack", message: "not a pack" };
importedPacks = [...importedPacks.filter((p) => p.id !== data.id), data];
return { id: data.id, name: data.name, publisher: data.publisher, licensee: null, items: data.items.length };
}
case "nextfloor/packs/remove":
importedPacks = importedPacks.filter((p) => p.id !== msg.pack_id);
return null;
case "recorder/statistics_during_period": {
// daily means (the week on the house card, a room's use this month): solar by the season, devices around their power now
if (msg.period === "day") {
const rows = (id) => {
const out = [];
const day = new Date(msg.start_time);
day.setHours(0, 0, 0, 0);
for (let k = 0; day.getTime() < Date.now(); k++, day.setDate(day.getDate() + 1)) {
const now = Math.max(0, Number(hass.states[id]?.state) || 0);
const mean = /pv|solar|balkon/.test(id) ? 600 + 250 * Math.sin(k) : Math.max(20, (now || 120) * (0.5 + 0.3 * Math.abs(Math.sin(k + id.length))));
out.push({ start: day.getTime(), end: day.getTime() + 86400000, mean: Math.round(mean) });
}
return out;
};
return Object.fromEntries((msg.statistic_ids ?? []).map((id) => [id, rows(id)]));
}
// today's solar curve: a sunny day, five-minute means from midnight up to now
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
const slots = Math.floor((Date.now() - midnight.getTime()) / 300000) + 1;
const peak = Number(hass.states["sensor.pv_leistung"]?.state) > 2000 ? 7100 : 3400;
const curve = Array.from({ length: slots }, (_, i) => {
const h = (i * 5) / 60;
const sun = Math.max(0, Math.sin((Math.PI * (h - 6.2)) / 13.2));
return { start: midnight.getTime() + i * 300000, end: midnight.getTime() + (i + 1) * 300000, mean: Math.round(peak * Math.pow(sun, 1.6) * (0.9 + 0.1 * Math.sin(i * 0.7))) };
});
return Object.fromEntries((msg.statistic_ids ?? []).map((id) => [id, curve]));
}
case "history/history_during_period": {
// invented motion of the last half hour: hall, kitchen, then the living-room camera
const now = Date.now() / 1000;
const on = (entity, ...minutesAgo) => [entity, minutesAgo.flatMap((m) => [{ s: "on", lu: now - m * 60 }, { s: "off", lu: now - m * 60 + 40 }])];
return Object.fromEntries([
on("binary_sensor.flur_bewegung", 26, 12),
on("binary_sensor.kueche_praesenz", 22, 9),
on("binary_sensor.wohnzimmer_kamera_bewegung", 17, 3),
on("binary_sensor.garage_auto", 28),
]);
}
default:
throw { code: "unknown_command", message: msg.type };
}
},
};
if (params.has("pv")) {
// ?pv=5400 sets the solar power (W) of the demo plant, e.g. a sunny noon
hass.states["sensor.pv_leistung"] = { ...hass.states["sensor.pv_leistung"], state: params.get("pv") };
}
if (params.has("weather")) {
// ?weather=pouring|snowy|fog|lightning-rainy|cloudy… sets the demo weather
hass.states["weather.zuhause"].state = params.get("weather");
hass.states["weather.zuhause"].attributes = { ...hass.states["weather.zuhause"].attributes, cloud_coverage: 85, wind_speed: 25, wind_speed_unit: "km/h" };
}
if (params.has("alerts")) {
// ?alerts: smoke in the kitchen while it rains on open windows
hass.states["binary_sensor.kueche_rauch"].state = "on";
hass.states["weather.zuhause"].state = "rainy";
}
let current = hass;
// window.nfDemoSet(entity, state, attributes): changes what a real Home Assistant would report (the tutorial recorder uses it)
window.nfDemoSet = (id, state, attributes = {}) => {
const old = current.states[id] ?? { entity_id: id, attributes: {} };
current = { ...current, states: { ...current.states, [id]: { ...old, state: state ?? old.state, attributes: { ...old.attributes, ...attributes } } } };
if (window.nfCard) window.nfCard.hass = current;
else if (window.nfPanel) window.nfPanel.hass = current;
};
await import("../custom_components/nextfloor/frontend/nextfloor.js");
if (params.has("site")) {
// ?site: the public online demo says what it is and where to get NextFloor
const de = hass.language === "de";
// phones: short and at the top of the 3D area, clear of the toolbars at the bottom
const narrow = innerWidth < 700;
const bar = document.createElement("div");
bar.style.cssText =
(narrow ? "position:fixed;left:50%;top:244px;" : "position:fixed;left:50%;bottom:64px;") +
"transform:translateX(-50%);z-index:10;display:flex;gap:10px;align-items:center;flex-wrap:nowrap;white-space:nowrap;justify-content:center;max-width:calc(100vw - 32px);padding:8px 14px;border-radius:999px;background:rgba(7,11,20,.88);border:1px solid rgba(0,229,255,.45);color:#cfe9ff;font:13px/1.3 Figtree,Roboto,sans-serif;box-shadow:0 0 18px rgba(0,229,255,.25)";
const link = (href, text) => `<a href="${href}" target="_blank" rel="noopener" style="color:#00e5ff;font-weight:600;text-decoration:none">${text}</a>`;
// the install button stands out; GitHub, the manual and the language as plain links
const install = (text) =>
`<a href="https://github.com/therealMRBK/NextFloor#installation" target="_blank" rel="noopener" style="background:#00e5ff;color:#06101c;font-weight:700;text-decoration:none;padding:5px 12px;border-radius:999px">${text}</a>`;
const github = link("https://github.com/therealMRBK/NextFloor", "★ GitHub");
bar.innerHTML = de
? `<span>${narrow ? "Demo" : "Demo mit erfundenen Daten – probier alles aus"}</span>${install(narrow ? "Installieren" : "Jetzt installieren")}${github}${narrow ? "" : link("https://github.com/therealMRBK/NextFloor/blob/main/docs/anleitung.md", "Anleitung")}${link("?site&lang=en", narrow ? "EN" : "English")}`
: `<span>${narrow ? "Demo" : "Demo with invented data – try everything"}</span>${install(narrow ? "Install" : "Install now")}${github}${narrow ? "" : link("https://github.com/therealMRBK/NextFloor/blob/main/docs/manual.md", "Manual")}${link("?site&lang=de", narrow ? "DE" : "Deutsch")}`;
const close = document.createElement("button");
close.textContent = "×";
close.setAttribute("aria-label", de ? "Schließen" : "Close");
close.style.cssText = "background:none;border:0;color:#cfe9ff;font-size:16px;cursor:pointer;padding:0 2px";
close.onclick = () => bar.remove();
bar.append(close);
document.body.append(bar);
}
if (params.has("card")) {
// ?card: the dashboard card next to its visual editor (like Home Assistant's card dialog)
document.querySelector("nextfloor-panel").remove();
const CardClass = customElements.get("nextfloor-card");
const wrap = document.createElement("div");
wrap.style.cssText = "display:grid;grid-template-columns:420px 1fr;gap:24px;padding:24px;font-family:Figtree,Roboto,sans-serif;--primary-text-color:#e1e1e1;--secondary-text-color:#9b9b9b;--card-background-color:#1c1c1c;--primary-color:#03a9f4;--divider-color:rgba(225,225,225,.2)";
const editorBox = document.createElement("div");
editorBox.style.cssText = "background:#1c1c1c;border-radius:12px;padding:20px";
const editor = await CardClass.getConfigElement();
const card = document.createElement("nextfloor-card");
let config = {
type: "custom:nextfloor-card",
quality: "low",
floor: params.get("floor") || building.floors.find((f) => f.id === "eg")?.id || building.floors[0]?.id || "eg",
flows: false,
controls: ["walls", "temperature"],
fullscreen_button: true,
floor_thumbs: true,
...(params.get("stack") ? { floor_stack: params.get("stack") } : {}),
...(params.has("nopanel") ? { room_panel: false } : {}),
...(params.has("roombuttons") ? { room_buttons: true } : {}),
...(params.has("night") ? { night: "00:00-23:59" } : {}),
...(params.has("kiosk") ? { idle_return: 1, idle_orbit: true } : {}),
};
card.setConfig(config);
editor.setConfig(config);
editor.addEventListener("config-changed", (e) => {
config = e.detail.config;
card.setConfig(config);
editor.setConfig(config);
});
editor.hass = hass;
card.hass = hass;
editorBox.append(editor);
wrap.append(editorBox, card);
document.body.append(wrap);
window.nfCard = card;
} else {
const panel = document.querySelector("nextfloor-panel");
panel.hass = hass;
window.addEventListener("hass-more-info", (e) => console.log("more-info", e.detail.entityId));
panel.narrow = window.innerWidth < 870;
window.nfPanel = panel;
}
</script>
</body>
</html>