Skip to content

Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.

Add the web UI: 3D floor plan, control panel and editor

0xProbability20d1bed7991e
diff --git a/.claude/launch.json b/.claude/launch.json
new file mode 100644
index 0000000..e2d8632
--- /dev/null
+++ b/.claude/launch.json
@@ -0,0 +1,12 @@
+{
+ "version": "0.0.1",
+ "configurations": [
+ {
+ "name": "web",
+ "runtimeExecutable": "npm",
+ "runtimeArgs": ["--prefix", "web", "run", "dev"],
+ "port": 5199,
+ "autoPort": true
+ }
+ ]
+}
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..42df411
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="color-scheme" content="dark" />
+ <title>House Control</title>
+ <link rel="stylesheet" href="./src/style.css" />
+ </head>
+ <body>
+ <div id="app"></div>
+ <script type="module" src="./src/main.js"></script>
+ </body>
+</html>
diff --git a/web/package-lock.json b/web/package-lock.json
new file mode 100644
index 0000000..33fb58f
--- /dev/null
+++ b/web/package-lock.json
@@ -0,0 +1,812 @@
+{
+ "name": "house-control-web",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "house-control-web",
+ "dependencies": {
+ "lucide": "^0.544.0",
+ "three": "^0.186.1"
+ },
+ "devDependencies": {
+ "vite": "^8.3.4"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.153.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz",
+ "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz",
+ "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz",
+ "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz",
+ "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz",
+ "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz",
+ "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz",
+ "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz",
+ "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz",
+ "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz",
+ "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz",
+ "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz",
+ "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz",
+ "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz",
+ "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz",
+ "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz",
+ "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lucide": {
+ "version": "0.544.0",
+ "resolved": "https://registry.npmjs.org/lucide/-/lucide-0.544.0.tgz",
+ "integrity": "sha512-U5ORwr5z9Sx7bNTDFaW55RbjVdQEnAcT3vws9uz3vRT1G4XXJUDAhRZdxhFoIyHEvjmTkzzlEhjSLYM5n4mb5w==",
+ "license": "ISC"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.30",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
+ "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.20",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz",
+ "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.153.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.13",
+ "@rolldown/binding-android-arm64": "1.2.13",
+ "@rolldown/binding-darwin-arm64": "1.2.13",
+ "@rolldown/binding-darwin-x64": "1.2.13",
+ "@rolldown/binding-freebsd-x64": "1.2.13",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.13",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.13",
+ "@rolldown/binding-linux-arm64-musl": "1.2.13",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.13",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.13",
+ "@rolldown/binding-linux-x64-gnu": "1.2.13",
+ "@rolldown/binding-linux-x64-musl": "1.2.13",
+ "@rolldown/binding-openharmony-arm64": "1.2.13",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.13",
+ "@rolldown/binding-win32-x64-msvc": "1.2.13"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/three": {
+ "version": "0.186.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
+ "license": "MIT"
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.4",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz",
+ "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.29",
+ "rolldown": "~1.2.12",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 0000000..703399e
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "house-control-web",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build"
+ },
+ "dependencies": {
+ "lucide": "^0.544.0",
+ "three": "^0.186.1"
+ },
+ "devDependencies": {
+ "vite": "^8.3.4"
+ }
+}
diff --git a/web/public/plans/home.json b/web/public/plans/home.json
new file mode 100644
index 0000000..e9b28a8
--- /dev/null
+++ b/web/public/plans/home.json
@@ -0,0 +1,116 @@
+{
+ "version": 1,
+ "name": "Home",
+ "wallHeight": 2.6,
+ "interiorWallHeight": 1.25,
+ "camera": { "azimuth": 34, "elevation": 47 },
+ "outdoorTemp": 29,
+
+ "rooms": [
+ { "id": "living", "name": "Living", "rect": [0, 3.6, 6.4, 4.6], "floor": "oak" },
+ { "id": "dining", "name": "Dining", "rect": [6.4, 3.6, 4.0, 4.6], "floor": "oak" },
+ { "id": "kitchen", "name": "Kitchen", "rect": [6.4, 0, 4.0, 3.6], "floor": "stone" },
+ { "id": "bedroom", "name": "Bedroom", "rect": [0, 0, 4.2, 3.6], "floor": "walnut" },
+ { "id": "bath", "name": "Bathroom", "rect": [4.2, 0, 2.2, 3.6], "floor": "tile" }
+ ],
+
+ "openings": [
+ { "type": "door", "from": [3.1, 3.6], "to": [4.0, 3.6] },
+ { "type": "door", "from": [4.7, 3.6], "to": [5.5, 3.6] },
+ { "type": "open", "from": [6.4, 4.2], "to": [6.4, 7.8] },
+ { "type": "open", "from": [7.0, 3.6], "to": [10.0, 3.6] },
+ { "type": "window", "from": [0, 1.0], "to": [0, 2.6] },
+ { "type": "window", "from": [0, 7.0], "to": [0, 7.9] },
+ { "type": "window", "from": [0.9, 0], "to": [2.3, 0], "sill": 1.5, "head": 2.2 }
+ ],
+
+ "furniture": [
+ { "type": "rug", "pos": [2.3, 6.0], "size": [2.5, 3.1], "color": "#3b4a66" },
+ { "type": "tv", "pos": [0.32, 6.0], "rot": 90, "width": 1.7 },
+ { "type": "sofa", "pos": [3.95, 6.0], "rot": -90, "width": 2.5, "color": "#8b93a7" },
+ { "type": "coffeeTable", "pos": [2.3, 6.0], "rot": 90 },
+ { "type": "armchair", "pos": [1.9, 4.35], "rot": 12, "color": "#c28a5a" },
+ { "type": "plant", "pos": [0.5, 7.65], "height": 1.5 },
+ { "type": "sideboard", "pos": [5.2, 7.85], "rot": 180, "width": 1.6 },
+
+ { "type": "diningSet", "pos": [8.5, 6.4], "width": 1.9, "chairs": 6 },
+ { "type": "plant", "pos": [9.95, 7.75], "height": 1.1 },
+ { "type": "island", "pos": [8.5, 3.75], "width": 2.2, "stools": 3 },
+
+ { "type": "kitchen", "pos": [8.05, 0.41], "width": 3.1, "upper": true },
+ { "type": "fridge", "pos": [10.02, 0.45] },
+
+ { "type": "rug", "pos": [2.1, 2.3], "size": [2.6, 1.6], "color": "#6a5a52" },
+ { "type": "bed", "pos": [2.1, 1.2], "width": 1.7, "color": "#7f8fb5" },
+ { "type": "nightstand", "pos": [0.85, 0.4] },
+ { "type": "nightstand", "pos": [3.35, 0.4] },
+ { "type": "dresser", "pos": [3.87, 2.5], "rot": -90, "width": 1.3 },
+ { "type": "plant", "pos": [0.45, 3.15], "height": 0.9 },
+
+ { "type": "vanity", "pos": [4.95, 0.38], "width": 1.0 },
+ { "type": "bathtub", "pos": [5.92, 1.35], "rot": 90 },
+ { "type": "toilet", "pos": [4.58, 2.5], "rot": 90 }
+ ],
+
+ "lights": [
+ { "id": "living.main", "name": "Ceiling", "room": "living", "type": "ceiling", "pos": [2.9, 6.0],
+ "capabilities": ["brightness", "temp"] },
+ { "id": "living.floor", "name": "Floor lamp", "room": "living", "type": "floor", "pos": [0.6, 4.2] },
+ { "id": "living.tv", "name": "TV backlight", "room": "living", "type": "strip", "pos": [0.13, 6.0], "y": 1.05,
+ "rot": 90, "length": 1.5, "capabilities": ["brightness", "color"], "color": "#7b5cff" },
+
+ { "id": "dining.pendant", "name": "Pendant", "room": "dining", "type": "pendant", "pos": [8.5, 6.4], "y": 1.75,
+ "capabilities": ["brightness", "temp"] },
+
+ { "id": "kitchen.spots", "name": "Spots", "room": "kitchen", "type": "spots", "pos": [8.4, 2.0],
+ "capabilities": ["brightness"] },
+ { "id": "kitchen.strip", "name": "Counter light", "room": "kitchen", "type": "strip", "pos": [8.05, 0.42], "y": 1.42,
+ "length": 2.9, "capabilities": ["brightness", "temp"] },
+
+ { "id": "bedroom.main", "name": "Ceiling", "room": "bedroom", "type": "ceiling", "pos": [2.1, 2.3],
+ "capabilities": ["brightness", "temp"] },
+ { "id": "bedroom.left", "name": "Bedside left", "room": "bedroom", "type": "table", "pos": [0.85, 0.4], "y": 0.5 },
+ { "id": "bedroom.right", "name": "Bedside right", "room": "bedroom", "type": "table", "pos": [3.35, 0.4], "y": 0.5 },
+
+ { "id": "bath.main", "name": "Ceiling", "room": "bath", "type": "ceiling", "pos": [5.2, 2.0],
+ "capabilities": ["brightness"] },
+ { "id": "bath.mirror", "name": "Mirror light", "room": "bath", "type": "strip", "pos": [4.95, 0.14], "y": 1.95,
+ "length": 0.8, "capabilities": ["brightness", "temp"] }
+ ],
+
+ "acs": [
+ { "id": "living.ac", "name": "Living AC", "room": "living", "wall": "west", "pos": [0, 4.45], "y": 2.2 },
+ { "id": "bedroom.ac", "name": "Bedroom AC", "room": "bedroom", "wall": "north", "pos": [3.3, 0], "y": 2.2 }
+ ],
+
+ "scenes": [
+ { "id": "bright", "name": "Bright", "icon": "sun",
+ "lights": { "*": { "on": true, "brightness": 1, "temp": 4200 } } },
+ { "id": "cozy", "name": "Cozy", "icon": "sofa",
+ "lights": {
+ "*": { "on": false },
+ "living.floor": { "on": true },
+ "living.tv": { "on": true, "brightness": 0.7, "color": "#ff7a3c" },
+ "dining.pendant": { "on": true, "brightness": 0.45, "temp": 2400 },
+ "kitchen.strip": { "on": true, "brightness": 0.6, "temp": 2700 },
+ "bedroom.left": { "on": true },
+ "bedroom.right": { "on": true }
+ } },
+ { "id": "movie", "name": "Movie", "icon": "film",
+ "lights": {
+ "*": { "on": false },
+ "living.tv": { "on": true, "brightness": 0.9, "color": "#6a4cff" },
+ "kitchen.strip": { "on": true, "brightness": 0.2, "temp": 2400 }
+ } },
+ { "id": "night", "name": "Night", "icon": "moon",
+ "lights": {
+ "*": { "on": false },
+ "bedroom.left": { "on": true },
+ "bath.mirror": { "on": true, "brightness": 0.25, "temp": 2300 }
+ },
+ "acs": { "bedroom.ac": { "sleep": true } } },
+ { "id": "away", "name": "Away", "icon": "door",
+ "lights": { "*": { "on": false } },
+ "acs": { "*": { "on": false } } }
+ ]
+}
diff --git a/web/public/plans/studio.json b/web/public/plans/studio.json
new file mode 100644
index 0000000..9cb065a
--- /dev/null
+++ b/web/public/plans/studio.json
@@ -0,0 +1,61 @@
+{
+ "version": 1,
+ "name": "Studio",
+ "wallHeight": 2.7,
+ "interiorWallHeight": 1.25,
+ "camera": { "azimuth": 30, "elevation": 50 },
+ "outdoorTemp": 31,
+
+ "rooms": [
+ { "id": "main", "name": "Studio", "rect": [0, 0, 6.2, 4.8], "floor": "walnut" },
+ { "id": "bath", "name": "Bathroom", "rect": [6.2, 0, 2.2, 2.6], "floor": "tile" },
+ { "id": "hall", "name": "Hall", "rect": [6.2, 2.6, 2.2, 2.2], "floor": "stone" }
+ ],
+
+ "openings": [
+ { "type": "door", "from": [6.2, 3.2], "to": [6.2, 4.1] },
+ { "type": "door", "from": [6.9, 2.6], "to": [7.7, 2.6] },
+ { "type": "window", "from": [0, 1.2], "to": [0, 3.6] },
+ { "type": "window", "from": [2.6, 0], "to": [4.2, 0] }
+ ],
+
+ "furniture": [
+ { "type": "rug", "pos": [2.2, 3.2], "size": [2.6, 1.9], "color": "#5b4a6e" },
+ { "type": "bed", "pos": [1.2, 1.25], "width": 1.6, "color": "#b98a7a" },
+ { "type": "nightstand", "pos": [2.45, 0.4] },
+ { "type": "sofa", "pos": [2.2, 4.25], "rot": 180, "width": 2.1, "color": "#6f8f86" },
+ { "type": "coffeeTable", "pos": [2.2, 3.1] },
+ { "type": "desk", "pos": [4.9, 0.5], "width": 1.4 },
+ { "type": "bookshelf", "pos": [0.28, 4.2], "rot": 90, "width": 0.9, "height": 1.9 },
+ { "type": "kitchen", "pos": [4.6, 4.38], "rot": 180, "width": 2.4, "upper": false },
+ { "type": "plant", "pos": [5.75, 2.4], "height": 1.3 },
+ { "type": "vanity", "pos": [7.3, 0.38], "width": 0.9 },
+ { "type": "toilet", "pos": [6.6, 1.7], "rot": 90 },
+ { "type": "sideboard", "pos": [8.1, 3.7], "rot": -90, "width": 1.1 }
+ ],
+
+ "lights": [
+ { "id": "main.ceiling", "name": "Ceiling", "room": "main", "type": "pendant", "pos": [3.1, 2.6], "y": 2.0,
+ "capabilities": ["brightness", "temp"] },
+ { "id": "main.bed", "name": "Bedside", "room": "main", "type": "table", "pos": [2.45, 0.4], "y": 0.5 },
+ { "id": "main.desk", "name": "Desk lamp", "room": "main", "type": "table", "pos": [5.4, 0.35], "y": 0.76 },
+ { "id": "main.shelf", "name": "Shelf glow", "room": "main", "type": "strip", "pos": [0.14, 4.2], "y": 1.95,
+ "rot": 90, "length": 0.9, "capabilities": ["brightness", "color"], "color": "#ff5fc4" },
+ { "id": "bath.ceiling", "name": "Ceiling", "room": "bath", "type": "ceiling", "pos": [7.3, 1.4],
+ "capabilities": ["brightness"] },
+ { "id": "hall.ceiling", "name": "Ceiling", "room": "hall", "type": "spots", "pos": [7.3, 3.7], "rot": 90 }
+ ],
+
+ "acs": [
+ { "id": "main.ac", "name": "Studio AC", "room": "main", "wall": "north", "pos": [1.2, 0], "y": 2.3 }
+ ],
+
+ "scenes": [
+ { "id": "bright", "name": "Bright", "icon": "sun", "lights": { "*": { "on": true, "brightness": 1, "temp": 4200 } } },
+ { "id": "work", "name": "Work", "icon": "table",
+ "lights": { "*": { "on": false }, "main.desk": { "on": true }, "main.ceiling": { "on": true, "brightness": 0.6, "temp": 4500 } } },
+ { "id": "chill", "name": "Chill", "icon": "sofa",
+ "lights": { "*": { "on": false }, "main.shelf": { "on": true, "brightness": 0.8, "color": "#ff5fc4" }, "main.bed": { "on": true } } },
+ { "id": "off", "name": "All off", "icon": "moon", "lights": { "*": { "on": false } }, "acs": { "*": { "on": false } } }
+ ]
+}
diff --git a/web/src/bridge.js b/web/src/bridge.js
new file mode 100644
index 0000000..251366e
--- /dev/null
+++ b/web/src/bridge.js
@@ -0,0 +1,34 @@
+// Thin bridge to the native macOS shell. In a plain browser every call is a no-op,
+// so the same bundle runs under `vite dev` and inside the menu bar app.
+
+const handler = window.webkit?.messageHandlers?.house;
+
+export const isNative = Boolean(handler);
+
+export function post(type, payload = {}) {
+ handler?.postMessage({ type, ...payload });
+}
+
+// Native -> JS entry points are attached here by main.js.
+export const incoming = (window.house = window.house || {});
+
+// Request/response on top of the one-way message channel.
+let nextId = 1;
+const pending = new Map();
+
+export function call(type, payload = {}) {
+ if (!handler) return Promise.reject(new Error('Only available inside the macOS app'));
+ return new Promise((resolve, reject) => {
+ const id = nextId++;
+ pending.set(id, { resolve, reject });
+ handler.postMessage({ type, callId: id, ...payload });
+ });
+}
+
+incoming.reply = (id, result) => {
+ const p = pending.get(id);
+ if (!p) return;
+ pending.delete(id);
+ if (result && result.error) p.reject(Object.assign(new Error(result.error), { detail: result }));
+ else p.resolve(result);
+};
diff --git a/web/src/config.js b/web/src/config.js
new file mode 100644
index 0000000..c5fbf3c
--- /dev/null
+++ b/web/src/config.js
@@ -0,0 +1,108 @@
+// Loads and normalises a floor plan ("home.json"). Everything the 3D scene and the UI
+// know about the apartment comes from this one document, so swapping the file swaps the home.
+
+const LIGHT_TYPES = ['ceiling', 'pendant', 'spots', 'floor', 'table', 'strip'];
+const WALLS = ['north', 'south', 'east', 'west'];
+
+export class ConfigError extends Error {}
+
+export const LIGHT_KINDS = LIGHT_TYPES;
+export const FLOOR_KINDS = ['oak', 'walnut', 'tile', 'stone'];
+
+// The plan exactly as written on disk (the editor works on this form).
+export async function loadRawConfig() {
+ const boot = window.__HOUSE_BOOT__;
+ if (boot?.config) return boot.config;
+ const plan = (boot?.plan !== 'custom' && boot?.plan) || new URLSearchParams(location.search).get('plan') || 'home';
+ const res = await fetch(`./plans/${plan}.json`);
+ if (!res.ok) throw new ConfigError(`Plan "${plan}" not found (HTTP ${res.status})`);
+ try {
+ return await res.json();
+ } catch (e) {
+ throw new ConfigError(`Plan "${plan}" is not valid JSON: ${e.message}`);
+ }
+}
+
+export async function loadConfig() {
+ return normalize(await loadRawConfig());
+}
+
+function need(cond, msg) {
+ if (!cond) throw new ConfigError(msg);
+}
+
+const isPoint = (p) => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite);
+
+export function normalize(raw) {
+ need(raw && typeof raw === 'object', 'Plan must be a JSON object');
+ need(Array.isArray(raw.rooms) && raw.rooms.length > 0, 'Plan needs at least one room in "rooms"');
+
+ const ids = new Set();
+ const unique = (id, what) => {
+ need(typeof id === 'string' && id, `${what} is missing an "id"`);
+ need(!ids.has(id), `Duplicate id "${id}"`);
+ ids.add(id);
+ };
+
+ const rooms = raw.rooms.map((r) => {
+ unique(r.id, 'A room');
+ need(Array.isArray(r.rect) && r.rect.length === 4 && r.rect.every(Number.isFinite),
+ `Room "${r.id}" needs "rect": [x, z, width, depth]`);
+ const [x, z, w, d] = r.rect;
+ need(w > 0 && d > 0, `Room "${r.id}" has an empty rect`);
+ return { id: r.id, name: r.name || r.id, x, z, w, d, floor: r.floor || 'oak' };
+ });
+ const roomIds = new Set(rooms.map((r) => r.id));
+
+ const openings = (raw.openings || []).map((o, i) => {
+ need(isPoint(o.from) && isPoint(o.to), `Opening #${i + 1} needs "from" and "to" points`);
+ need(o.from[0] === o.to[0] || o.from[1] === o.to[1], `Opening #${i + 1} must be axis-aligned`);
+ return { type: o.type || 'door', from: o.from, to: o.to, sill: o.sill ?? 0.85, head: o.head ?? 2.1 };
+ });
+
+ const lights = (raw.lights || []).map((l) => {
+ unique(l.id, 'A light');
+ need(roomIds.has(l.room), `Light "${l.id}" refers to unknown room "${l.room}"`);
+ need(LIGHT_TYPES.includes(l.type), `Light "${l.id}" has unknown type "${l.type}" (use ${LIGHT_TYPES.join(', ')})`);
+ need(isPoint(l.pos), `Light "${l.id}" needs "pos": [x, z]`);
+ return {
+ ...l,
+ name: l.name || l.id,
+ rot: l.rot || 0,
+ capabilities: l.capabilities || [], // plain smart plugs: on/off only
+ };
+ });
+
+ const acs = (raw.acs || []).map((a) => {
+ unique(a.id, 'An AC');
+ need(roomIds.has(a.room), `AC "${a.id}" refers to unknown room "${a.room}"`);
+ need(isPoint(a.pos), `AC "${a.id}" needs "pos": [x, z]`);
+ need(WALLS.includes(a.wall), `AC "${a.id}" needs "wall": one of ${WALLS.join(', ')}`);
+ return { ...a, name: a.name || a.id, y: a.y ?? 2.2, min: a.min ?? 16, max: a.max ?? 30 };
+ });
+
+ const scenes = (raw.scenes || []).map((s) => {
+ need(typeof s.id === 'string' && s.id, 'A scene is missing an "id"');
+ return { id: s.id, name: s.name || s.id, icon: s.icon || 'sun', lights: s.lights || {}, acs: s.acs || {} };
+ });
+
+ const minX = Math.min(...rooms.map((r) => r.x));
+ const minZ = Math.min(...rooms.map((r) => r.z));
+ const maxX = Math.max(...rooms.map((r) => r.x + r.w));
+ const maxZ = Math.max(...rooms.map((r) => r.z + r.d));
+
+ return {
+ name: raw.name || 'Home',
+ wallHeight: raw.wallHeight ?? 2.6,
+ interiorWallHeight: raw.interiorWallHeight ?? 1.25,
+ camera: { azimuth: raw.camera?.azimuth ?? 34, elevation: raw.camera?.elevation ?? 47 },
+ outdoorTemp: raw.outdoorTemp ?? 27,
+ rooms,
+ openings,
+ furniture: raw.furniture || [],
+ lights,
+ acs,
+ scenes,
+ bounds: { minX, minZ, maxX, maxZ },
+ };
+}
diff --git a/web/src/editor/editor.css b/web/src/editor/editor.css
new file mode 100644
index 0000000..4f185a2
--- /dev/null
+++ b/web/src/editor/editor.css
@@ -0,0 +1,200 @@
+html.mode-editor body { background: var(--bg); overflow: hidden; }
+html.mode-editor #app { padding: 0; display: block; }
+html.mode-editor, html.mode-editor body { user-select: none; }
+
+.editor {
+ height: 100%;
+ display: grid;
+ grid-template-columns: 268px minmax(0, 1fr) 340px;
+ grid-template-rows: 54px minmax(0, 1fr) 34px;
+ grid-template-areas: 'bar bar bar' 'side canvas right' 'foot foot foot';
+ background:
+ radial-gradient(70% 50% at 50% 0%, rgba(36, 60, 120, 0.35), transparent 70%),
+ var(--bg);
+ font-size: 13px;
+}
+
+.bar {
+ grid-area: bar;
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 0 16px;
+ border-bottom: 1px solid var(--line);
+}
+.bar-title { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; color: #cfe0ff; }
+.title-input {
+ flex: 1; min-width: 0; max-width: 360px;
+ height: 34px; padding: 0 10px; border-radius: 10px;
+ font: inherit; font-size: 16px; font-weight: 650; color: var(--text);
+ background: transparent; border: 1px solid transparent; outline: none;
+ transition: background 160ms, border-color 160ms;
+}
+.title-input:hover { background: var(--glass); }
+.title-input:focus { background: var(--glass); border-color: rgba(120, 175, 255, 0.55); }
+.bar-actions { display: flex; gap: 8px; }
+
+.btn {
+ height: 32px; padding: 0 13px; border-radius: 10px;
+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;
+ font-size: 12.5px; font-weight: 600; color: var(--muted);
+ background: var(--glass); border: 1px solid var(--line);
+ transition: background 160ms, color 160ms, transform 200ms var(--spring), opacity 160ms;
+}
+.btn:hover { background: var(--glass-hi); color: var(--text); }
+.btn:active { transform: scale(0.96); }
+.btn.primary { color: #fff; background: linear-gradient(180deg, #4f97ff, #2f7bf2); border-color: rgba(255, 255, 255, 0.22); }
+.btn.primary:hover { background: linear-gradient(180deg, #62a5ff, #3a85f8); }
+.btn:disabled { opacity: 0.4; pointer-events: none; }
+.btn.wide { width: 100%; height: 36px; margin-top: 4px; }
+
+/* ---------- sidebar ---------- */
+
+.side { grid-area: side; overflow-y: auto; padding: 10px 10px 16px; border-right: 1px solid var(--line); scrollbar-width: thin; scrollbar-color: rgba(255,255,255,.14) transparent; }
+.group {
+ display: flex; align-items: center; gap: 7px;
+ margin: 16px 6px 5px;
+ font-size: 10.5px; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase; color: var(--faint);
+}
+.group .n { flex: 1; color: rgba(222, 230, 247, 0.22); }
+.group .add {
+ width: 22px; height: 22px; border-radius: 7px; display: grid; place-items: center; color: var(--muted);
+ background: var(--glass); border: 1px solid var(--line); transition: background 160ms, color 160ms;
+}
+.group .add:hover { background: rgba(70, 130, 255, 0.35); color: #fff; }
+
+.row {
+ width: 100%; min-height: 32px; padding: 0 6px 0 10px; border-radius: 9px;
+ display: flex; align-items: center; gap: 7px;
+ text-align: left; color: var(--muted); cursor: pointer;
+ transition: background 120ms, color 120ms;
+}
+.row:hover { background: var(--glass); color: var(--text); }
+.row.active { background: rgba(70, 130, 255, 0.24); color: #fff; }
+.row-name { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 550; text-transform: capitalize; }
+.row-sub { flex: none; max-width: 46%; font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.row.active .row-sub { color: rgba(255, 255, 255, 0.6); }
+.row .linked { color: #6ee7a0; display: grid; }
+.row .del { width: 22px; height: 22px; border-radius: 7px; display: none; place-items: center; color: var(--muted); flex: none; }
+.row:hover .del { display: grid; }
+.row:hover .row-sub { display: none; }
+.row .del:hover { background: rgba(255, 90, 80, 0.3); color: #fff; }
+.home-row, .tuya-row { height: 36px; font-weight: 600; }
+.tuya-row { margin-top: 4px; }
+.pill { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 10.5px; font-weight: 700; color: var(--muted); background: rgba(255, 255, 255, 0.08); white-space: nowrap; }
+.pill.on { color: #0b2a17; background: #6ee7a0; }
+
+/* ---------- plan ---------- */
+
+.canvas { grid-area: canvas; position: relative; min-width: 0; min-height: 0; }
+.plan { width: 100%; height: 100%; display: block; outline: none; touch-action: none; }
+.hint { position: absolute; left: 0; right: 0; bottom: 10px; text-align: center; font-size: 11.5px; color: var(--faint); pointer-events: none; }
+
+.p-room rect { stroke: #dfe3ec; stroke-width: 0.11; cursor: move; transition: fill 160ms; }
+.p-room:hover rect { filter: brightness(1.2); }
+.p-room.sel rect { stroke: #6aa6ff; stroke-width: 0.14; }
+.p-label, .p-dim { text-anchor: middle; pointer-events: none; font-family: -apple-system, system-ui, sans-serif; }
+.p-label { font-size: 0.3px; font-weight: 650; fill: rgba(255, 255, 255, 0.86); }
+.p-dim { font-size: 0.2px; fill: rgba(255, 255, 255, 0.4); }
+
+.p-furn rect { fill: rgba(255, 255, 255, 0.07); stroke: rgba(255, 255, 255, 0.3); stroke-width: 0.025; cursor: move; }
+.p-furn .front { stroke: rgba(255, 255, 255, 0.45); stroke-width: 0.05; stroke-linecap: round; fill: none; pointer-events: none; }
+.p-furn:hover rect { fill: rgba(255, 255, 255, 0.14); }
+.p-furn.sel rect { fill: rgba(90, 150, 255, 0.28); stroke: #6aa6ff; stroke-width: 0.05; }
+
+.p-open { stroke-width: 0.2; stroke-linecap: butt; cursor: move; }
+.p-open.door { stroke: #e9a45a; }
+.p-open.open { stroke: #0a0e1a; stroke-dasharray: 0.16 0.1; }
+.p-open.window { stroke: #6fb0ff; }
+.p-open.sel { stroke-width: 0.3; filter: drop-shadow(0 0 0.12px #fff); }
+
+.p-ac rect { fill: #5db2ff; stroke: #0a0e1a; stroke-width: 0.04; cursor: move; }
+.p-ac .flow { stroke: #5db2ff; stroke-width: 0.04; stroke-linecap: round; opacity: 0.6; fill: none; pointer-events: none; }
+.p-ac.sel rect { stroke: #fff; stroke-width: 0.07; }
+
+.p-light { cursor: move; }
+.p-light circle, .p-light rect { fill: #ffb46b; stroke: #0a0e1a; stroke-width: 0.04; }
+.p-light .halo { fill: rgba(255, 180, 107, 0.16); stroke: none; }
+.p-light:hover .halo { fill: rgba(255, 180, 107, 0.32); }
+.p-light.linked circle:not(.halo), .p-light.linked rect { stroke: #6ee7a0; stroke-width: 0.06; }
+.p-light.sel circle:not(.halo), .p-light.sel rect { stroke: #fff; stroke-width: 0.08; }
+.p-light.sel .halo { fill: rgba(255, 255, 255, 0.2); }
+
+.p-handle { fill: #6aa6ff; stroke: #fff; stroke-width: 0.05; cursor: nwse-resize; }
+
+/* ---------- right column ---------- */
+
+.right { grid-area: right; display: flex; flex-direction: column; min-height: 0; border-left: 1px solid var(--line); }
+.preview-wrap { position: relative; flex: none; height: 250px; border-bottom: 1px solid var(--line); background: #0a0e1a; }
+.preview, .preview canvas { width: 100%; height: 100%; display: block; }
+.preview-error { padding: 16px; font-size: 12px; color: #ffb4a8; }
+.chip {
+ position: absolute; right: 10px; top: 10px;
+ height: 26px; padding: 0 10px; border-radius: 999px;
+ display: flex; align-items: center; gap: 6px;
+ font-size: 11.5px; font-weight: 600; color: var(--muted);
+ background: rgba(16, 21, 36, 0.8); border: 1px solid var(--line);
+ backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
+}
+.chip:hover { color: var(--text); }
+
+.inspector { flex: 1; min-height: 0; overflow-y: auto; padding: 14px 16px 24px; scrollbar-width: thin; scrollbar-color: rgba(255,255,255,.14) transparent; user-select: text; -webkit-user-select: text; }
+.insp-head h2 { margin: 0; font-size: 16px; font-weight: 650; text-transform: capitalize; }
+.insp-head span { display: block; margin-top: 2px; font-size: 11.5px; color: var(--faint); }
+.block { margin-top: 18px; }
+.block h3, .devices-list h3 { margin: 0 0 8px; font-size: 10.5px; font-weight: 700; letter-spacing: 0.09em; text-transform: uppercase; color: var(--faint); }
+.fields { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+.field { display: block; margin-bottom: 8px; min-width: 0; }
+.field > span { display: block; margin: 0 0 4px 2px; font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.field input:not([type='checkbox']), .field select {
+ width: 100%; height: 32px; padding: 0 9px; border-radius: 9px;
+ font: inherit; font-size: 13px; color: var(--text); font-variant-numeric: tabular-nums;
+ background: rgba(0, 0, 0, 0.28); border: 1px solid var(--line); outline: none;
+ transition: border-color 140ms, background 140ms;
+}
+.field select { appearance: none; -webkit-appearance: none; padding-right: 26px; background-image: linear-gradient(45deg, transparent 50%, rgba(255,255,255,.5) 50%), linear-gradient(135deg, rgba(255,255,255,.5) 50%, transparent 50%); background-position: calc(100% - 15px) 14px, calc(100% - 10px) 14px; background-size: 5px 5px; background-repeat: no-repeat; }
+.field input:focus, .field select:focus { border-color: rgba(120, 175, 255, 0.7); background: rgba(0, 0, 0, 0.4); }
+.field input::placeholder { color: var(--faint); }
+.checks .field { display: flex; flex-direction: row-reverse; justify-content: flex-end; align-items: center; gap: 9px; margin-bottom: 6px; }
+.checks .field > span { margin: 0; font-size: 13px; color: var(--text); }
+.checks input { width: 16px; height: 16px; accent-color: #3d8bff; }
+.note { margin: 6px 2px 0; font-size: 11.5px; line-height: 1.5; color: var(--faint); }
+.note.bad { color: #ffb4a8; }
+.steps { margin: 0; padding-left: 18px; font-size: 12px; line-height: 1.55; color: var(--muted); }
+.steps li { margin-bottom: 6px; }
+
+.devices-list { margin-top: 16px; }
+.device { display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin-bottom: 6px; border-radius: 11px; background: var(--glass); border: 1px solid var(--line); }
+.device div { flex: 1; min-width: 0; }
+.device b { display: block; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.device div span { display: block; font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: rgba(255, 255, 255, 0.22); }
+.dot.on { background: #4ade80; box-shadow: 0 0 8px #4ade80; }
+
+/* ---------- footer ---------- */
+
+.foot { grid-area: foot; display: flex; align-items: center; padding: 0 16px; border-top: 1px solid var(--line); }
+.status { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.status .ok { color: #4ade80; }
+.status .dirty { color: var(--warm); }
+.status.bad { color: #ffb4a8; }
+
+.toast {
+ position: fixed; left: 50%; bottom: 52px; z-index: 50;
+ padding: 10px 16px; border-radius: 12px;
+ font-size: 12.5px; font-weight: 600;
+ background: rgba(20, 28, 48, 0.95); border: 1px solid var(--line);
+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
+ opacity: 0; transform: translate(-50%, 10px); pointer-events: none;
+ transition: opacity 200ms, transform 300ms var(--ease);
+}
+.toast.show { opacity: 1; transform: translate(-50%, 0); }
+.toast.bad { border-color: rgba(255, 120, 110, 0.6); color: #ffd2cc; }
+
+.qr { display: grid; place-items: center; margin: 12px 0 4px; }
+.qr img { display: block; padding: 10px; border-radius: 16px; background: #fff; image-rendering: pixelated; }
+.block .fields .btn { width: 100%; }
+.block .device { margin-bottom: 8px; }
+.advanced { margin-top: 22px; padding-top: 14px; border-top: 1px solid var(--line); }
+.advanced summary { cursor: pointer; font-size: 12px; font-weight: 600; color: var(--muted); margin-bottom: 8px; }
+.advanced summary:hover { color: var(--text); }
diff --git a/web/src/editor/editor.js b/web/src/editor/editor.js
new file mode 100644
index 0000000..6ba857b
--- /dev/null
+++ b/web/src/editor/editor.js
@@ -0,0 +1,861 @@
+// Home editor (separate window): a top-down plan you can drag things around on,
+// an inspector for the selected item, a live 3D preview and the Smart Life links.
+import './editor.css';
+import { normalize, loadRawConfig, LIGHT_KINDS, FLOOR_KINDS } from '../config.js';
+import { createWorld } from '../three/world.js';
+import { FURNITURE_TYPES, footprint } from '../three/furniture.js';
+import { h, clamp } from '../ui/dom.js';
+import { icon } from '../ui/icons.js';
+import { isNative, call } from '../bridge.js';
+
+const SVG = 'http://www.w3.org/2000/svg';
+const sv = (tag, attrs = {}, ...kids) => {
+ const el = document.createElementNS(SVG, tag);
+ for (const [k, v] of Object.entries(attrs)) if (v != null) el.setAttribute(k, v);
+ el.append(...kids.filter((k) => k != null));
+ return el;
+};
+
+const KEYS = { room: 'rooms', light: 'lights', ac: 'acs', furniture: 'furniture', opening: 'openings', scene: 'scenes' };
+const TITLES = { room: 'Rooms', light: 'Lights', ac: 'Air conditioners', furniture: 'Furniture', opening: 'Doors & windows', scene: 'Scenes' };
+const FLOOR_FILL = { oak: '#4a3d2e', walnut: '#3c2f28', tile: '#39424b', stone: '#30353c' };
+const WALLS = ['north', 'east', 'south', 'west'];
+const SCENE_ICONS = ['sun', 'sofa', 'film', 'moon', 'door', 'table', 'bed', 'tv', 'sparkles'];
+const REGIONS = [
+ ['eu', 'Central Europe'], ['eu-w', 'Western Europe'], ['us', 'Western America'], ['us-e', 'Eastern America'],
+ ['cn', 'China'], ['in', 'India'], ['sg', 'Singapore'],
+];
+
+const round = (v, step = 0.05) => Math.round(v / step) * step;
+const fix = (v) => Math.round(v * 1000) / 1000;
+const slug = (t) => String(t).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item';
+
+export async function bootEditor(root) {
+ let doc = structuredClone(await loadRawConfig());
+ for (const key of Object.values(KEYS)) doc[key] ||= [];
+
+ let sel = { kind: window.__HOUSE_BOOT__?.section === 'tuya' ? 'tuya' : 'home' };
+ let dirty = false;
+ let world = null;
+ let previewLights = true;
+ const undo = [];
+ const redo = [];
+ const tuya = {
+ info: window.__HOUSE_BOOT__?.tuya || { configured: false, accessId: '', region: 'eu' },
+ account: window.__HOUSE_BOOT__?.smartLife || { connected: false, userCode: '', account: '' },
+ devices: null, busy: false, error: null, qr: null,
+ get linked() { return this.account.connected || this.info.configured; },
+ };
+
+ /* ---------- layout ---------- */
+
+ const nameInput = h('input.title-input', { value: doc.name || 'Home', spellcheck: 'false', 'aria-label': 'Home name' });
+ nameInput.addEventListener('input', () => { snapshot('name'); doc.name = nameInput.value; touch({ inspector: sel.kind === 'home' }); });
+ const status = h('div.status');
+ const saveBtn = h('button.btn.primary', { onclick: save }, icon('check', 15, 2.4), 'Save & apply');
+ const toastEl = h('div.toast');
+
+ const sidebar = h('aside.side');
+ const plan = sv('svg', { class: 'plan', tabindex: 0 });
+ const inspector = h('div.inspector');
+ const previewHost = h('div.preview');
+ const previewToggle = h('button.chip', { onclick: () => { previewLights = !previewLights; schedulePreview(0); } });
+
+ root.replaceChildren(h('div.editor',
+ h('header.bar',
+ h('div.bar-title', icon('home', 17), nameInput),
+ h('div.bar-actions',
+ h('button.btn', { title: 'Undo (⌘Z)', onclick: () => stepHistory(undo, redo) }, 'Undo'),
+ h('button.btn', { title: 'Redo (⇧⌘Z)', onclick: () => stepHistory(redo, undo) }, 'Redo'),
+ h('button.btn', { onclick: importPlan }, 'Import…'),
+ h('button.btn', { onclick: exportPlan }, 'Export…'),
+ saveBtn)),
+ sidebar,
+ h('main.canvas', plan, h('div.hint', 'Drag rooms, lamps and furniture · drag a room’s corner to resize · everything snaps to 5 cm')),
+ h('aside.right', h('div.preview-wrap', previewHost, previewToggle), inspector),
+ h('footer.foot', status),
+ toastEl));
+
+ /* ---------- history ---------- */
+
+ let lastSnapshotKey = null;
+ function snapshot(key = null) {
+ if (key && key === lastSnapshotKey) return; // coalesce a drag or a burst of typing into one step
+ lastSnapshotKey = key;
+ undo.push(JSON.stringify(doc));
+ if (undo.length > 100) undo.shift();
+ redo.length = 0;
+ }
+
+ function stepHistory(from, to) {
+ if (!from.length) return;
+ to.push(JSON.stringify(doc));
+ doc = JSON.parse(from.pop());
+ lastSnapshotKey = null;
+ if (sel.index != null && !doc[KEYS[sel.kind]]?.[sel.index]) sel = { kind: 'home' };
+ nameInput.value = doc.name || '';
+ touch();
+ }
+
+ function touch({ inspector: redrawInspector = true } = {}) {
+ dirty = true;
+ renderSidebar();
+ renderPlan();
+ if (redrawInspector) renderInspector();
+ validate();
+ schedulePreview();
+ }
+
+ function select(next) {
+ sel = next;
+ lastSnapshotKey = null;
+ renderSidebar();
+ renderPlan();
+ renderInspector();
+ }
+
+ function toast(text, bad = false) {
+ toastEl.textContent = text;
+ toastEl.className = `toast show${bad ? ' bad' : ''}`;
+ clearTimeout(toast.timer);
+ toast.timer = setTimeout(() => { toastEl.className = 'toast'; }, 2600);
+ }
+
+ /* ---------- validation + preview ---------- */
+
+ let valid = null;
+ function validate() {
+ try {
+ valid = normalize(structuredClone(doc));
+ const linked = [...doc.lights, ...doc.acs].filter((d) => d.tuya?.deviceId).length;
+ status.className = 'status';
+ status.replaceChildren(h('span.ok', '●'), ` ${doc.rooms.length} rooms · ${doc.lights.length} lights · ${doc.acs.length} ACs · `,
+ `${linked} linked to Smart Life`, dirty ? h('span.dirty', ' · unsaved changes') : '');
+ } catch (e) {
+ valid = null;
+ status.className = 'status bad';
+ status.textContent = `⚠ ${e.message}`;
+ }
+ saveBtn.disabled = !valid;
+ }
+
+ function previewStore(cfg) {
+ const state = { lights: {}, acs: {} };
+ for (const l of cfg.lights) state.lights[l.id] = { on: previewLights, brightness: 0.85, temp: 3200, color: l.color || null };
+ for (const a of cfg.acs) state.acs[a.id] = { on: previewLights, mode: 'cool', fan: 'auto', swing: 'swing', sleep: false, target: 23 };
+ return { state, on: () => () => {} };
+ }
+
+ let previewTimer = 0;
+ function schedulePreview(delay = 350) {
+ clearTimeout(previewTimer);
+ previewTimer = setTimeout(buildPreview, delay);
+ }
+
+ function buildPreview() {
+ previewToggle.replaceChildren(icon(previewLights ? 'bright' : 'moon', 14), previewLights ? 'Lights on' : 'Lights off');
+ if (!valid) return;
+ world?.dispose();
+ world = null;
+ const canvas = h('canvas');
+ previewHost.replaceChildren(canvas);
+ try {
+ world = createWorld(canvas, valid, previewStore(valid), {
+ onHover() {},
+ onPick(t) {
+ if (!t) return;
+ const index = doc[KEYS[t.kind]].findIndex((x) => x.id === t.id);
+ if (index >= 0) select({ kind: t.kind, index });
+ },
+ });
+ world.setInsets(6, 6);
+ world.setRunning(true);
+ const w = world;
+ new ResizeObserver(() => { if (world === w) w.resize(); }).observe(canvas);
+ } catch (e) {
+ previewHost.replaceChildren(h('div.preview-error', String(e.message || e)));
+ }
+ }
+
+ /* ---------- sidebar ---------- */
+
+ function rowLabel(kind, item) {
+ if (kind === 'room') return [item.name || item.id, `${fix(item.rect[2])} × ${fix(item.rect[3])} m`];
+ if (kind === 'light') return [item.name || item.id, `${roomName(item.room)} · ${item.type}`];
+ if (kind === 'ac') return [item.name || item.id, `${roomName(item.room)} · ${item.wall} wall`];
+ if (kind === 'furniture') return [item.type, roomName(roomAt(item.pos)?.id) || '—'];
+ if (kind === 'opening') return [item.type || 'door', `${fix(Math.hypot(item.to[0] - item.from[0], item.to[1] - item.from[1]))} m`];
+ return [item.name || item.id, `${Object.keys(item.lights || {}).length} rules`];
+ }
+
+ const roomName = (id) => doc.rooms.find((r) => r.id === id)?.name || id || '';
+ const roomAt = ([x, z]) => doc.rooms.find((r) => x >= r.rect[0] && x <= r.rect[0] + r.rect[2] && z >= r.rect[1] && z <= r.rect[1] + r.rect[3]);
+
+ function renderSidebar() {
+ const nodes = [h(`button.row.home-row${sel.kind === 'home' ? '.active' : ''}`, { onclick: () => select({ kind: 'home' }) },
+ icon('home', 15), h('span.row-name', 'Home settings')),
+ h(`button.row.tuya-row${sel.kind === 'tuya' ? '.active' : ''}`, { onclick: () => select({ kind: 'tuya' }) },
+ icon('plug', 15), h('span.row-name', 'Smart Life'),
+ h(`span.pill${tuya.linked ? '.on' : ''}`, tuya.linked ? 'Connected' : 'Demo mode'))];
+ for (const kind of Object.keys(KEYS)) {
+ const items = doc[KEYS[kind]];
+ nodes.push(h('div.group',
+ h('span', `${TITLES[kind]}`), h('span.n', items.length),
+ h('button.add', { title: `Add to ${TITLES[kind].toLowerCase()}`, 'aria-label': `Add ${kind}`, onclick: () => add(kind) }, icon('plus', 14, 2.4))));
+ items.forEach((item, index) => {
+ const [name, sub] = rowLabel(kind, item);
+ const active = sel.kind === kind && sel.index === index;
+ nodes.push(h(`div.row${active ? '.active' : ''}`, { role: 'button', tabindex: 0, onclick: () => select({ kind, index }) },
+ h('span.row-name', name),
+ item.tuya?.deviceId ? h('span.linked', { title: 'Linked to a Smart Life device' }, icon('plug', 12, 2.2)) : null,
+ h('span.row-sub', sub),
+ h('button.del', { title: 'Remove', 'aria-label': `Remove ${name}`, onclick: (e) => { e.stopPropagation(); remove(kind, index); } }, icon('close', 13, 2.4))));
+ });
+ }
+ const top = sidebar.scrollTop;
+ sidebar.replaceChildren(...nodes);
+ sidebar.scrollTop = top;
+ }
+
+ function uniqueId(base) {
+ const ids = new Set([...doc.rooms, ...doc.lights, ...doc.acs, ...doc.scenes].map((x) => x.id));
+ if (!ids.has(base)) return base;
+ for (let i = 2; ; i++) if (!ids.has(`${base}${i}`)) return `${base}${i}`;
+ }
+
+ function add(kind) {
+ snapshot();
+ const room = (sel.kind === 'room' && doc.rooms[sel.index]) || doc.rooms.find((r) => r.id === doc[KEYS[sel.kind]]?.[sel.index]?.room) || doc.rooms[0];
+ const center = room ? [fix(room.rect[0] + room.rect[2] / 2), fix(room.rect[1] + room.rect[3] / 2)] : [1, 1];
+ const list = doc[KEYS[kind]];
+ if (kind === 'room') {
+ const maxX = Math.max(0, ...doc.rooms.map((r) => r.rect[0] + r.rect[2]));
+ const minZ = Math.min(...doc.rooms.map((r) => r.rect[1]), 0);
+ list.push({ id: uniqueId('room'), name: 'New room', rect: [fix(maxX), fix(doc.rooms.length ? minZ : 0), 3, 3], floor: 'oak' });
+ } else if (kind === 'light') {
+ if (!room) return toast('Add a room first', true);
+ list.push({ id: uniqueId(`${room.id}.light`), name: 'New light', room: room.id, type: 'ceiling', pos: center, capabilities: [] });
+ } else if (kind === 'ac') {
+ if (!room) return toast('Add a room first', true);
+ list.push({ id: uniqueId(`${room.id}.ac`), name: `${room.name} AC`, room: room.id, wall: 'north', pos: [center[0], room.rect[1]], y: 2.2 });
+ } else if (kind === 'furniture') {
+ list.push({ type: 'sofa', pos: center, rot: 0 });
+ } else if (kind === 'opening') {
+ if (!room) return toast('Add a room first', true);
+ const z = room.rect[1] + room.rect[3];
+ list.push({ type: 'door', from: [fix(center[0] - 0.45), fix(z)], to: [fix(center[0] + 0.45), fix(z)] });
+ } else if (kind === 'scene') {
+ list.push({ id: uniqueId('scene'), name: 'New scene', icon: 'sparkles', lights: { '*': { on: false } } });
+ }
+ sel = { kind, index: list.length - 1 };
+ touch();
+ }
+
+ function remove(kind, index) {
+ snapshot();
+ const [gone] = doc[KEYS[kind]].splice(index, 1);
+ if (kind === 'room') {
+ // Devices cannot outlive their room.
+ doc.lights = doc.lights.filter((l) => l.room !== gone.id);
+ doc.acs = doc.acs.filter((a) => a.room !== gone.id);
+ }
+ if (kind === 'light' || kind === 'ac' || kind === 'room') {
+ const ids = new Set([...doc.lights, ...doc.acs].map((d) => d.id));
+ for (const sc of doc.scenes) {
+ for (const map of [sc.lights, sc.acs]) for (const id of Object.keys(map || {})) if (id !== '*' && !ids.has(id)) delete map[id];
+ }
+ }
+ sel = { kind: 'home' };
+ touch();
+ }
+
+ /* ---------- plan (SVG) ---------- */
+
+ function bounds() {
+ const rs = doc.rooms.length ? doc.rooms : [{ rect: [0, 0, 6, 4] }];
+ const minX = Math.min(...rs.map((r) => r.rect[0]));
+ const minZ = Math.min(...rs.map((r) => r.rect[1]));
+ const maxX = Math.max(...rs.map((r) => r.rect[0] + r.rect[2]));
+ const maxZ = Math.max(...rs.map((r) => r.rect[1] + r.rect[3]));
+ return { minX, minZ, maxX, maxZ };
+ }
+
+ const isSel = (kind, index) => sel.kind === kind && sel.index === index;
+
+ function renderPlan() {
+ const b = bounds();
+ const m = 1.4;
+ plan.setAttribute('viewBox', `${b.minX - m} ${b.minZ - m} ${b.maxX - b.minX + m * 2} ${b.maxZ - b.minZ + m * 2}`);
+ const kids = [
+ sv('defs', {}, sv('pattern', { id: 'grid', width: 1, height: 1, patternUnits: 'userSpaceOnUse' },
+ sv('path', { d: 'M1 0H0V1', fill: 'none', stroke: 'rgba(255,255,255,0.07)', 'stroke-width': 0.015 }),
+ sv('path', { d: 'M0.5 0V1M0 0.5H1', fill: 'none', stroke: 'rgba(255,255,255,0.03)', 'stroke-width': 0.01 }))),
+ sv('rect', { x: b.minX - 20, y: b.minZ - 20, width: 60, height: 60, fill: 'url(#grid)', 'data-kind': 'none' }),
+ ];
+
+ doc.rooms.forEach((r, i) => {
+ const [x, z, w, d] = r.rect;
+ const g = sv('g', { class: `p-room${isSel('room', i) ? ' sel' : ''}`, 'data-kind': 'room', 'data-index': i },
+ sv('rect', { x, y: z, width: w, height: d, fill: FLOOR_FILL[r.floor] || FLOOR_FILL.oak }),
+ sv('text', { x: x + w / 2, y: z + d / 2 - 0.02, class: 'p-label' }, document.createTextNode(r.name || r.id)),
+ sv('text', { x: x + w / 2, y: z + d / 2 + 0.3, class: 'p-dim' }, document.createTextNode(`${fix(w)} × ${fix(d)}`)));
+ kids.push(g);
+ });
+
+ doc.furniture.forEach((f, i) => {
+ if (!Array.isArray(f.pos)) return;
+ const [w, d] = footprint(f);
+ kids.push(sv('g', {
+ class: `p-furn${isSel('furniture', i) ? ' sel' : ''}`, 'data-kind': 'furniture', 'data-index': i,
+ transform: `translate(${f.pos[0]} ${f.pos[1]}) rotate(${-(f.rot || 0)})`,
+ },
+ sv('rect', { x: -w / 2, y: -d / 2, width: w, height: d, rx: 0.06 }),
+ // a tick marks the front of the piece
+ sv('path', { d: `M${-w / 4} ${d / 2}H${w / 4}`, class: 'front' })));
+ });
+
+ doc.openings.forEach((o, i) => {
+ kids.push(sv('line', {
+ class: `p-open ${o.type || 'door'}${isSel('opening', i) ? ' sel' : ''}`, 'data-kind': 'opening', 'data-index': i,
+ x1: o.from[0], y1: o.from[1], x2: o.to[0], y2: o.to[1],
+ }));
+ });
+
+ doc.acs.forEach((a, i) => {
+ const rot = { north: 0, east: 90, south: 180, west: 270 }[a.wall] || 0;
+ kids.push(sv('g', {
+ class: `p-ac${isSel('ac', i) ? ' sel' : ''}`, 'data-kind': 'ac', 'data-index': i,
+ transform: `translate(${a.pos[0]} ${a.pos[1]}) rotate(${rot})`,
+ }, sv('rect', { x: -0.47, y: 0.08, width: 0.94, height: 0.24, rx: 0.07 }),
+ sv('path', { d: 'M-0.3 0.42v0.22M0 0.42v0.3M0.3 0.42v0.22', class: 'flow' })));
+ });
+
+ doc.lights.forEach((l, i) => {
+ const g = sv('g', {
+ class: `p-light ${l.type}${isSel('light', i) ? ' sel' : ''}${l.tuya?.deviceId ? ' linked' : ''}`, 'data-kind': 'light', 'data-index': i,
+ transform: `translate(${l.pos[0]} ${l.pos[1]}) rotate(${-(l.rot || 0)})`,
+ });
+ if (l.type === 'strip') {
+ const len = l.length || 1;
+ g.append(sv('rect', { x: -len / 2, y: -0.07, width: len, height: 0.14, rx: 0.07 }));
+ } else {
+ g.append(sv('circle', { r: 0.34, class: 'halo' }), sv('circle', { r: l.type === 'table' ? 0.13 : 0.19 }));
+ }
+ kids.push(g);
+ });
+
+ if (sel.kind === 'room' && doc.rooms[sel.index]) {
+ const [x, z, w, d] = doc.rooms[sel.index].rect;
+ kids.push(sv('circle', { cx: x + w, cy: z + d, r: 0.16, class: 'p-handle', 'data-kind': 'resize', 'data-index': sel.index }));
+ }
+ plan.replaceChildren(...kids);
+ }
+
+ function planPoint(ev) {
+ const pt = plan.createSVGPoint();
+ pt.x = ev.clientX;
+ pt.y = ev.clientY;
+ const p = pt.matrixTransform(plan.getScreenCTM().inverse());
+ return [p.x, p.y];
+ }
+
+ // Puts an AC on the nearest wall of the room under (or nearest to) the pointer.
+ function snapAC(ac, [x, z]) {
+ const room = roomAt([x, z]) || doc.rooms.find((r) => r.id === ac.room);
+ if (!room) return;
+ const [rx, rz, rw, rd] = room.rect;
+ const options = [
+ ['north', Math.abs(z - rz)], ['south', Math.abs(z - (rz + rd))],
+ ['west', Math.abs(x - rx)], ['east', Math.abs(x - (rx + rw))],
+ ].sort((p, q) => p[1] - q[1]);
+ const wall = options[0][0];
+ ac.room = room.id;
+ ac.wall = wall;
+ const cx = fix(clamp(round(x), rx + 0.6, rx + rw - 0.6));
+ const cz = fix(clamp(round(z), rz + 0.6, rz + rd - 0.6));
+ ac.pos = wall === 'north' ? [cx, rz] : wall === 'south' ? [cx, fix(rz + rd)] : wall === 'west' ? [rx, cz] : [fix(rx + rw), cz];
+ }
+
+ let drag = null;
+ plan.addEventListener('pointerdown', (ev) => {
+ const el = ev.target.closest('[data-kind]');
+ const kind = el?.dataset.kind;
+ if (!kind || kind === 'none') { select({ kind: 'home' }); return; }
+ const index = Number(el.dataset.index);
+ const start = planPoint(ev);
+ plan.setPointerCapture(ev.pointerId);
+ if (kind === 'resize') {
+ drag = { kind, index, start, rect: [...doc.rooms[index].rect] };
+ return;
+ }
+ if (!isSel(kind, index)) select({ kind, index });
+ const item = doc[KEYS[kind]][index];
+ drag = { kind, index, start, moved: false };
+ if (kind === 'room') {
+ const [x, z, w, d] = item.rect;
+ const inside = ([px, pz]) => px >= x - 1e-6 && px <= x + w + 1e-6 && pz >= z - 1e-6 && pz <= z + d + 1e-6;
+ drag.rect = [...item.rect];
+ // Everything standing in the room travels with it.
+ drag.riders = [
+ ...doc.lights.filter((l) => l.room === item.id).map((o) => ({ o, pos: [...o.pos] })),
+ ...doc.acs.filter((a) => a.room === item.id).map((o) => ({ o, pos: [...o.pos] })),
+ ...doc.furniture.filter((f) => Array.isArray(f.pos) && inside(f.pos)).map((o) => ({ o, pos: [...o.pos] })),
+ ];
+ drag.openings = doc.openings.filter((o) => inside(o.from) && inside(o.to)).map((o) => ({ o, from: [...o.from], to: [...o.to] }));
+ } else if (kind === 'opening') {
+ drag.from = [...item.from];
+ drag.to = [...item.to];
+ } else {
+ drag.pos = [...item.pos];
+ }
+ });
+
+ plan.addEventListener('pointermove', (ev) => {
+ if (!drag) return;
+ const [px, pz] = planPoint(ev);
+ const dx = round(px - drag.start[0]);
+ const dz = round(pz - drag.start[1]);
+ if (!drag.moved && !dx && !dz) return;
+ if (!drag.moved) { drag.moved = true; snapshot(); }
+ const item = drag.kind === 'resize' ? doc.rooms[drag.index] : doc[KEYS[drag.kind]][drag.index];
+
+ if (drag.kind === 'resize') {
+ item.rect[2] = fix(Math.max(1, round(drag.rect[2] + px - drag.start[0], 0.1)));
+ item.rect[3] = fix(Math.max(1, round(drag.rect[3] + pz - drag.start[1], 0.1)));
+ } else if (drag.kind === 'room') {
+ const mx = round(px - drag.start[0], 0.1);
+ const mz = round(pz - drag.start[1], 0.1);
+ item.rect[0] = fix(drag.rect[0] + mx);
+ item.rect[1] = fix(drag.rect[1] + mz);
+ for (const r of drag.riders) r.o.pos = [fix(r.pos[0] + mx), fix(r.pos[1] + mz)];
+ for (const r of drag.openings) {
+ r.o.from = [fix(r.from[0] + mx), fix(r.from[1] + mz)];
+ r.o.to = [fix(r.to[0] + mx), fix(r.to[1] + mz)];
+ }
+ } else if (drag.kind === 'opening') {
+ item.from = [fix(drag.from[0] + dx), fix(drag.from[1] + dz)];
+ item.to = [fix(drag.to[0] + dx), fix(drag.to[1] + dz)];
+ } else if (drag.kind === 'ac') {
+ snapAC(item, [px, pz]);
+ } else {
+ item.pos = [fix(drag.pos[0] + dx), fix(drag.pos[1] + dz)];
+ if (drag.kind === 'light') {
+ const room = roomAt(item.pos);
+ if (room) item.room = room.id;
+ }
+ }
+ touch();
+ });
+
+ const endDrag = () => { drag = null; lastSnapshotKey = null; };
+ plan.addEventListener('pointerup', endDrag);
+ plan.addEventListener('pointercancel', endDrag);
+
+ /* ---------- inspector ---------- */
+
+ // A labelled input bound to a getter/setter; edits redraw everything except the form itself.
+ function bind(label, input, { get, set, parse = (v) => v, event = 'input' }) {
+ const v = get();
+ if (input.type === 'checkbox') input.checked = Boolean(v);
+ else input.value = v ?? '';
+ input.addEventListener(event, () => {
+ const raw = input.type === 'checkbox' ? input.checked : input.value;
+ const next = parse(raw);
+ if (next === undefined) return;
+ snapshot(label + sel.kind + sel.index);
+ set(next);
+ // Pickers and checkboxes can change which fields exist; typing must keep its focus.
+ touch({ inspector: event === 'change' });
+ });
+ return h('label.field', h('span', label), input);
+ }
+
+ const number = (step = 0.05) => h('input', { type: 'number', step, inputmode: 'decimal' });
+ const parseNum = (v) => (v === '' || Number.isNaN(Number(v)) ? undefined : Number(v));
+ const text = () => h('input', { type: 'text', spellcheck: 'false' });
+ const choice = (options) => h('select', options.map((o) => (Array.isArray(o) ? h('option', { value: o[0] }, o[1]) : h('option', { value: o }, o))));
+
+ const prop = (obj, key, fallback) => ({ get: () => obj[key] ?? fallback, set: (v) => { obj[key] = v; } });
+ const at = (obj, key, i) => ({ get: () => obj[key][i], set: (v) => { obj[key][i] = v; } });
+ const optional = (obj, key) => ({
+ get: () => obj[key] ?? '',
+ set: (v) => { if (v === '' || v == null) delete obj[key]; else obj[key] = v; },
+ });
+ const optNum = (v) => (v === '' ? '' : Number.isNaN(Number(v)) ? undefined : Number(v));
+
+ const row = (...fields) => h('div.fields', fields);
+ const section = (title, ...nodes) => h('section.block', h('h3', title), nodes);
+
+ function deviceLink(item) {
+ const current = item.tuya?.deviceId || '';
+ const setId = (id) => {
+ if (!id) delete item.tuya;
+ else item.tuya = { ...(item.tuya || {}), deviceId: id };
+ };
+ const options = [['', 'Not linked — simulated']];
+ for (const d of tuya.devices || []) options.push([d.id, `${d.name}${d.online ? '' : ' (offline)'}`]);
+ if (current && !options.some((o) => o[0] === current)) options.push([current, `${current} (manual)`]);
+ const picker = choice(options);
+ const manual = text();
+ manual.placeholder = 'or paste a device ID';
+ const info = h('p.note');
+ const describe = () => {
+ const d = (tuya.devices || []).find((x) => x.id === item.tuya?.deviceId);
+ info.textContent = d ? `${d.product || d.category} · functions: ${d.codes.join(', ') || 'none reported'}`
+ : tuya.linked ? (tuya.devices ? '' : 'Open “Smart Life” on the left to load your devices, then pick one here.')
+ : 'Set up the Smart Life connection to control a real device. Until then this device is simulated.';
+ };
+ describe();
+ return section('Smart Life device',
+ bind('Device', picker, { get: () => current, set: (v) => { setId(v); manual.value = v; describe(); }, event: 'change' }),
+ bind('Device ID', manual, { get: () => current, set: (v) => { setId(v.trim()); describe(); } }),
+ info);
+ }
+
+ function renderInspector() {
+ const kind = sel.kind;
+ const item = sel.index != null ? doc[KEYS[kind]]?.[sel.index] : null;
+ const nodes = [];
+ const head = (title, sub) => nodes.push(h('div.insp-head', h('h2', title), sub ? h('span', sub) : null));
+
+ if (kind === 'home') {
+ head('Home', 'Global settings of this plan');
+ doc.camera ||= { azimuth: 34, elevation: 47 };
+ nodes.push(section('Building',
+ row(bind('Wall height, m', number(0.1), { ...prop(doc, 'wallHeight', 2.6), parse: parseNum }),
+ bind('Inner walls shown, m', number(0.05), { ...prop(doc, 'interiorWallHeight', 1.25), parse: parseNum })),
+ bind('Outdoor temperature, °C', number(1), { ...prop(doc, 'outdoorTemp', 27), parse: parseNum })),
+ section('Default camera',
+ row(bind('Azimuth, °', number(1), { ...prop(doc.camera, 'azimuth', 34), parse: parseNum }),
+ bind('Elevation, °', number(1), { ...prop(doc.camera, 'elevation', 47), parse: parseNum })),
+ h('p.note', 'Walls facing the camera are cut away, so the azimuth decides which side of the home is open.')),
+ section('How it works',
+ h('p.note', 'Pick anything on the plan or in the list to edit it. “Save & apply” writes the plan to disk and reloads the menu bar panel. Coordinates are metres: x grows to the right (east), z grows downwards (south).')));
+ } else if (kind === 'tuya') {
+ head('Smart Life', 'Control the real devices of your Smart Life account');
+ nodes.push(...tuyaPanel());
+ } else if (!item) {
+ head('Nothing selected');
+ } else if (kind === 'room') {
+ head(item.name || item.id, `id: ${item.id}`);
+ nodes.push(section('Room',
+ bind('Name', text(), prop(item, 'name', '')),
+ bind('Floor', choice(FLOOR_KINDS), { ...prop(item, 'floor', 'oak'), event: 'change' })),
+ section('Position & size, m',
+ row(bind('X', number(0.1), { ...at(item, 'rect', 0), parse: parseNum }), bind('Z', number(0.1), { ...at(item, 'rect', 1), parse: parseNum })),
+ row(bind('Width', number(0.1), { ...at(item, 'rect', 2), parse: parseNum }), bind('Depth', number(0.1), { ...at(item, 'rect', 3), parse: parseNum })),
+ h('p.note', 'Rooms that share an edge get an interior wall there. Add a door or an “open” gap to connect them.')));
+ } else if (kind === 'light') {
+ head(item.name || item.id, `id: ${item.id}`);
+ item.capabilities ||= [];
+ const cap = (name) => ({
+ get: () => item.capabilities.includes(name),
+ set: (on) => { item.capabilities = item.capabilities.filter((c) => c !== name); if (on) item.capabilities.push(name); },
+ });
+ nodes.push(section('Light',
+ bind('Name', text(), prop(item, 'name', '')),
+ row(bind('Room', choice(doc.rooms.map((r) => [r.id, r.name || r.id])), { ...prop(item, 'room'), event: 'change' }),
+ bind('Fixture', choice(LIGHT_KINDS), { ...prop(item, 'type'), event: 'change' }))),
+ section('Position, m',
+ row(bind('X', number(), { ...at(item, 'pos', 0), parse: parseNum }), bind('Z', number(), { ...at(item, 'pos', 1), parse: parseNum })),
+ row(bind('Height (auto if empty)', number(), { ...optional(item, 'y'), parse: optNum }),
+ bind('Rotation, °', number(15), { ...prop(item, 'rot', 0), parse: parseNum })),
+ item.type === 'strip' ? bind('Strip length, m', number(0.1), { ...prop(item, 'length', 1), parse: parseNum }) : null),
+ section('What it can do',
+ h('div.checks',
+ bind('Dimming', h('input', { type: 'checkbox' }), { ...cap('brightness'), event: 'change' }),
+ bind('White temperature', h('input', { type: 'checkbox' }), { ...cap('temp'), event: 'change' }),
+ bind('Colour', h('input', { type: 'checkbox' }), { ...cap('color'), event: 'change' })),
+ h('p.note', 'Leave all three off for a lamp on a plain smart plug: it is then a simple on/off switch.')),
+ deviceLink(item));
+ } else if (kind === 'ac') {
+ head(item.name || item.id, `id: ${item.id}`);
+ nodes.push(section('Air conditioner',
+ bind('Name', text(), prop(item, 'name', '')),
+ row(bind('Room', choice(doc.rooms.map((r) => [r.id, r.name || r.id])), { ...prop(item, 'room'), event: 'change' }),
+ bind('Mounted on wall', choice(WALLS), { ...prop(item, 'wall', 'north'), event: 'change' }))),
+ section('Position, m',
+ row(bind('X', number(), { ...at(item, 'pos', 0), parse: parseNum }), bind('Z', number(), { ...at(item, 'pos', 1), parse: parseNum })),
+ row(bind('Height', number(), { ...prop(item, 'y', 2.2), parse: parseNum }),
+ bind('Min / max °C', text(), {
+ get: () => `${item.min ?? 16}-${item.max ?? 30}`,
+ set: ([a, b]) => { item.min = a; item.max = b; },
+ parse: (v) => { const m = /^(\d+)\s*-\s*(\d+)$/.exec(v.trim()); return m && +m[1] < +m[2] ? [+m[1], +m[2]] : undefined; },
+ })),
+ h('p.note', 'Dragging the unit on the plan snaps it to the nearest wall of its room.')),
+ deviceLink(item),
+ section('Room temperature',
+ bind('Temperature sensor (device ID, optional)', text(), {
+ get: () => item.tuya?.sensorId || '',
+ set: (v) => {
+ const id = v.trim();
+ if (id) item.tuya = { ...(item.tuya || {}), sensorId: id };
+ else if (item.tuya) delete item.tuya.sensorId;
+ },
+ }),
+ h('p.note', 'A Smart Life temperature sensor in the same room. Without one the room temperature is estimated.')));
+ } else if (kind === 'furniture') {
+ head(item.type, 'Decoration only');
+ nodes.push(section('Furniture',
+ bind('Type', choice(FURNITURE_TYPES), { ...prop(item, 'type'), event: 'change' }),
+ row(bind('X', number(), { ...at(item, 'pos', 0), parse: parseNum }), bind('Z', number(), { ...at(item, 'pos', 1), parse: parseNum })),
+ row(bind('Rotation, °', number(15), { ...prop(item, 'rot', 0), parse: parseNum }),
+ bind('Width, m', number(0.1), { ...optional(item, 'width'), parse: optNum })),
+ bind('Colour (hex, optional)', text(), optional(item, 'color')),
+ h('p.note', 'The short line on the plan marks the front. Rotation 0° faces south (towards the bottom of the plan).')));
+ } else if (kind === 'opening') {
+ head(item.type || 'door', 'A gap or a window in a wall');
+ nodes.push(section('Opening',
+ bind('Type', choice([['door', 'Door'], ['open', 'Open passage'], ['window', 'Window']]), { ...prop(item, 'type', 'door'), event: 'change' }),
+ row(bind('From X', number(), { ...at(item, 'from', 0), parse: parseNum }), bind('From Z', number(), { ...at(item, 'from', 1), parse: parseNum })),
+ row(bind('To X', number(), { ...at(item, 'to', 0), parse: parseNum }), bind('To Z', number(), { ...at(item, 'to', 1), parse: parseNum })),
+ item.type === 'window' ? row(bind('Sill, m', number(), { ...prop(item, 'sill', 0.85), parse: parseNum }),
+ bind('Head, m', number(), { ...prop(item, 'head', 2.1), parse: parseNum })) : null,
+ h('p.note', 'Both points must lie on the same wall line (same X or same Z). Windows only show on the far walls; the walls facing the camera are cut away.')));
+ } else if (kind === 'scene') {
+ head(item.name || item.id, `id: ${item.id}`);
+ item.lights ||= {};
+ const rule = (id) => ({
+ get: () => (item.lights[id]?.on === true ? 'on' : item.lights[id]?.on === false ? 'off' : ''),
+ set: (v) => {
+ if (v === '') delete item.lights[id];
+ else item.lights[id] = { ...(item.lights[id] || {}), on: v === 'on' };
+ },
+ });
+ const tri = () => choice([['', 'Leave as is'], ['on', 'On'], ['off', 'Off']]);
+ nodes.push(section('Scene',
+ row(bind('Name', text(), prop(item, 'name', '')), bind('Icon', choice(SCENE_ICONS), { ...prop(item, 'icon', 'sun'), event: 'change' }))),
+ section('Lights',
+ bind('All lights (default)', tri(), { ...rule('*'), event: 'change' }),
+ doc.lights.map((l) => bind(`${l.name} · ${roomName(l.room)}`, tri(), { ...rule(l.id), event: 'change' })),
+ h('p.note', 'Brightness, temperature and colour per light are kept from the plan file; edit them there for fine control.')),
+ section('Air conditioners',
+ bind('All ACs', choice([['', 'Leave as is'], ['off', 'Turn off'], ['on', 'Turn on']]), {
+ get: () => (item.acs?.['*']?.on === true ? 'on' : item.acs?.['*']?.on === false ? 'off' : ''),
+ set: (v) => { item.acs ||= {}; if (v === '') delete item.acs['*']; else item.acs['*'] = { on: v === 'on' }; },
+ event: 'change',
+ })));
+ }
+ const key = `${sel.kind}:${sel.index}`;
+ const top = key === inspector.dataset.key ? inspector.scrollTop : 0;
+ inspector.dataset.key = key;
+ inspector.replaceChildren(...nodes.flat().filter(Boolean));
+ inspector.scrollTop = top;
+ }
+
+ /* ---------- Smart Life ---------- */
+
+ let loginTimer = 0;
+ function stopLoginPolling() { clearInterval(loginTimer); loginTimer = 0; }
+
+ async function fetchDevices() {
+ tuya.busy = true; tuya.error = null;
+ if (sel.kind === 'tuya') renderInspector();
+ try {
+ tuya.devices = (await call('tuya.devices')).devices;
+ } catch (e) {
+ tuya.error = e.message;
+ tuya.devices = null;
+ }
+ tuya.busy = false;
+ renderSidebar();
+ if (sel.kind === 'tuya') renderInspector();
+ }
+
+ function deviceList() {
+ if (tuya.busy) return h('p.note', 'Talking to Smart Life…');
+ if (tuya.error) return h('p.note.bad', tuya.error);
+ if (!tuya.devices) return null;
+ if (!tuya.devices.length) return h('p.note.bad', 'Connected, but this account has no devices yet.');
+ const used = new Map([...doc.lights, ...doc.acs].filter((d) => d.tuya?.deviceId).map((d) => [d.tuya.deviceId, d.name]));
+ return h('div.devices-list', h('h3', `${tuya.devices.length} devices in your account`), tuya.devices.map((d) => h('div.device',
+ h(`span.dot${d.online ? '.on' : ''}`),
+ h('div', h('b', d.name), h('span', `${d.product || d.category || 'device'} · ${d.codes.join(', ') || 'no functions reported'}`)),
+ used.has(d.id) ? h('span.pill.on', used.get(d.id)) : null)));
+ }
+
+ function tuyaPanel() {
+ const nodes = [];
+ if (!isNative) nodes.push(h('p.note.bad', 'Connecting is only available inside the macOS app (this is the browser preview).'));
+
+ if (tuya.account.connected) {
+ nodes.push(section('Smart Life account',
+ h('div.device', h('span.dot.on'), h('div', h('b', tuya.account.account || 'Signed in'), h('span', `User Code ${tuya.account.userCode}`))),
+ h('div.fields',
+ h('button.btn', { onclick: fetchDevices }, 'Refresh devices'),
+ h('button.btn', { onclick: async () => {
+ stopLoginPolling();
+ tuya.account = await call('smartlife.signOut');
+ tuya.devices = null; tuya.qr = null;
+ renderSidebar(); renderInspector();
+ } }, 'Sign out')),
+ h('p.note', 'Pick a lamp or an AC on the plan, choose its device under “Smart Life device”, then press “Save & apply”.')),
+ deviceList());
+ if (!tuya.devices && !tuya.busy && !tuya.error && isNative) setTimeout(fetchDevices, 0);
+ } else {
+ const codeInput = text();
+ codeInput.value = tuya.account.userCode || '';
+ codeInput.placeholder = 'e.g. aB12cD3';
+ const message = h('p.note');
+ const qrBox = h('div.qr');
+ const start = async () => {
+ stopLoginPolling();
+ message.className = 'note';
+ message.textContent = 'Requesting a login code…';
+ qrBox.replaceChildren();
+ try {
+ const userCode = codeInput.value.trim();
+ const { token, qr } = await call('smartlife.begin', { userCode });
+ qrBox.replaceChildren(h('img', { src: qr, alt: 'Smart Life login QR code', width: 220, height: 220 }));
+ message.textContent = 'Scan this code with the Smart Life app (the scan icon on the Home tab) and confirm the login. Waiting…';
+ let tries = 0;
+ loginTimer = setInterval(async () => {
+ if (++tries > 90) { stopLoginPolling(); message.className = 'note bad'; message.textContent = 'The code expired. Press “Show QR code” again.'; return; }
+ const r = await call('smartlife.poll', { token, userCode }).catch(() => null);
+ if (!r?.connected) return;
+ stopLoginPolling();
+ tuya.account = r.info;
+ renderSidebar();
+ renderInspector();
+ }, 2000);
+ } catch (e) {
+ message.className = 'note bad';
+ message.textContent = e.message;
+ }
+ };
+ nodes.push(section('Sign in with the Smart Life app',
+ h('ol.steps',
+ h('li', 'In the Smart Life app open Me → ⚙ Settings → Account and Security and copy the User Code at the bottom.'),
+ h('li', 'Type it here and press “Show QR code”.'),
+ h('li', 'Scan the code with the Smart Life app and confirm.')),
+ h('label.field', h('span', 'User Code'), codeInput),
+ h('button.btn.primary.wide', { onclick: start, disabled: !isNative }, 'Show QR code'),
+ qrBox, message,
+ h('p.note', 'Free and needs no Tuya developer account: this is the same sign-in the Home Assistant integration uses. The session is stored only on this Mac.')));
+ }
+
+ // The developer-project route stays available for those who already have one.
+ const idInput = text();
+ idInput.value = tuya.info.accessId || '';
+ idInput.placeholder = 'Access ID / Client ID';
+ const secretInput = h('input', { type: 'password', autocomplete: 'off' });
+ secretInput.placeholder = tuya.info.hasSecret ? '•••••••• (saved — leave empty to keep)' : 'Access Secret / Client Secret';
+ const region = choice(REGIONS.map(([id, label]) => [id, `${label} (${id})`]));
+ region.value = tuya.info.region || 'eu';
+ const saveCloud = async () => {
+ try {
+ tuya.info = await call('tuya.save', { accessId: idInput.value, accessSecret: secretInput.value, region: region.value });
+ renderSidebar();
+ if (tuya.info.configured) await fetchDevices(); else renderInspector();
+ } catch (e) { toast(e.message, true); }
+ };
+ nodes.push(h('details.advanced', h('summary', 'Advanced: Tuya Cloud project instead'),
+ h('p.note', 'Only if you already have a project on platform.tuya.com with your app account linked. The QR sign-in above takes priority when both are set.'),
+ h('label.field', h('span', 'Access ID'), idInput),
+ h('label.field', h('span', 'Access Secret'), secretInput),
+ h('label.field', h('span', 'Data center'), region),
+ h('button.btn.wide', { onclick: saveCloud, disabled: !isNative }, 'Save & fetch devices'),
+ tuya.account.connected ? null : deviceList()));
+ return nodes;
+ }
+
+ /* ---------- file actions ---------- */
+
+ async function save() {
+ if (!valid) return;
+ if (!isNative) {
+ download();
+ toast('Browser preview: the plan was downloaded instead of applied');
+ return;
+ }
+ try {
+ await call('savePlan', { config: doc });
+ dirty = false;
+ validate();
+ toast('Saved — the menu bar panel now shows this home');
+ } catch (e) {
+ toast(e.message, true);
+ }
+ }
+
+ function download() {
+ const a = h('a', { href: URL.createObjectURL(new Blob([JSON.stringify(doc, null, 2)], { type: 'application/json' })), download: `${slug(doc.name)}.json` });
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+ }
+
+ async function exportPlan() {
+ if (!isNative) { download(); return; }
+ try {
+ const r = await call('exportPlan', { config: doc });
+ if (r.ok) toast('Plan exported');
+ } catch (e) { toast(e.message, true); }
+ }
+
+ async function importPlan() {
+ const load = (json) => {
+ try {
+ normalize(structuredClone(json));
+ } catch (e) {
+ toast(`Not a valid plan: ${e.message}`, true);
+ return;
+ }
+ snapshot();
+ doc = json;
+ for (const key of Object.values(KEYS)) doc[key] ||= [];
+ nameInput.value = doc.name || 'Home';
+ sel = { kind: 'home' };
+ touch();
+ toast('Plan imported — review it and press “Save & apply”');
+ };
+ if (isNative) {
+ try {
+ const r = await call('importPlan');
+ if (r.config) load(r.config);
+ } catch (e) { toast(e.message, true); }
+ return;
+ }
+ const input = h('input', { type: 'file', accept: 'application/json,.json' });
+ input.addEventListener('change', async () => {
+ try { load(JSON.parse(await input.files[0].text())); } catch (e) { toast(`Could not read the file: ${e.message}`, true); }
+ });
+ input.click();
+ }
+
+ /* ---------- keyboard ---------- */
+
+ window.addEventListener('keydown', (ev) => {
+ const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement?.tagName || '');
+ if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'z' && !typing) {
+ ev.preventDefault();
+ if (ev.shiftKey) stepHistory(redo, undo); else stepHistory(undo, redo);
+ } else if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 's') {
+ ev.preventDefault();
+ save();
+ } else if ((ev.key === 'Backspace' || ev.key === 'Delete') && !typing && sel.index != null) {
+ ev.preventDefault();
+ remove(sel.kind, sel.index);
+ } else if (ev.key.startsWith('Arrow') && !typing && sel.index != null) {
+ const item = doc[KEYS[sel.kind]][sel.index];
+ const target = item.pos || item.rect;
+ if (!target) return;
+ ev.preventDefault();
+ const stepSize = ev.shiftKey ? 0.5 : 0.05;
+ snapshot(`nudge${sel.kind}${sel.index}`);
+ if (ev.key === 'ArrowLeft') target[0] = fix(target[0] - stepSize);
+ if (ev.key === 'ArrowRight') target[0] = fix(target[0] + stepSize);
+ if (ev.key === 'ArrowUp') target[1] = fix(target[1] - stepSize);
+ if (ev.key === 'ArrowDown') target[1] = fix(target[1] + stepSize);
+ touch();
+ }
+ });
+
+ renderSidebar();
+ renderPlan();
+ renderInspector();
+ validate();
+ dirty = false;
+ validate();
+ schedulePreview(0);
+ window.__editor = { get doc() { return doc; }, select, tuya };
+}
diff --git a/web/src/main.js b/web/src/main.js
new file mode 100644
index 0000000..08fe4a9
--- /dev/null
+++ b/web/src/main.js
@@ -0,0 +1,130 @@
+import { loadConfig } from './config.js';
+import { createStore } from './store.js';
+import { createWorld } from './three/world.js';
+import { createPanel } from './ui/panel.js';
+import { h, openMenu } from './ui/dom.js';
+import { icon } from './ui/icons.js';
+import { isNative, post, incoming } from './bridge.js';
+
+const DEMO_PLANS = [
+ { id: 'home', name: 'Demo · Apartment' },
+ { id: 'studio', name: 'Demo · Studio' },
+];
+const STAGE_INSETS = [62, 50]; // header above, panel overlap below
+
+const app = document.getElementById('app');
+if (isNative) document.documentElement.classList.add('native');
+
+function fatal(title, error) {
+ console.error(error);
+ app.replaceChildren(h('div.fatal', h('h1', title),
+ 'The floor plan could not be loaded. Fix the file and reload, or pick another plan from the menu bar icon.',
+ h('code', String(error?.message || error))));
+ post('ready', { error: String(error?.message || error) });
+}
+
+async function boot() {
+ let config;
+ try {
+ config = await loadConfig();
+ } catch (error) {
+ fatal('Could not open this home', error);
+ return;
+ }
+
+ const store = createStore(config);
+ const linked = [...config.lights, ...config.acs].some((d) => d.tuya?.deviceId);
+ // Never invent a starting state for real hardware: it reports its own.
+ if (!store.restored && !linked) {
+ // First launch: start with something worth looking at.
+ const first = config.scenes.find((s) => s.id === 'cozy') || config.scenes[1] || config.scenes[0];
+ if (first) store.applyScene(first.id);
+ if (config.acs[0]) store.setAC(config.acs[0].id, { on: true, target: 23 });
+ }
+
+ let world;
+ const panel = createPanel(app, config, store, {
+ onFocus: (target) => world?.focus(target),
+ onMenu: (anchor, reason) => (reason === 'escape' ? post('close') : planMenu(anchor)),
+ });
+
+ try {
+ world = createWorld(panel.canvas, config, store, {
+ onHover: panel.showTooltip,
+ onPick(target) {
+ if (!target) return;
+ if (target.kind === 'light') store.toggleLight(target.id);
+ else if (target.kind === 'ac') panel.openSheet(target);
+ else if (target.kind === 'room') panel.selectRoom(target.id);
+ },
+ });
+ } catch (error) {
+ fatal('3D view failed to start', error);
+ return;
+ }
+
+ panel.attach(world);
+ world.setInsets(...STAGE_INSETS);
+ new ResizeObserver(() => world.resize()).observe(panel.canvas);
+
+ const show = () => { world.setRunning(true); world.intro(); };
+ const hide = () => { world.setRunning(false); };
+ incoming.shown = show;
+ incoming.hidden = () => { hide(); panel.closeSheet(); if (panel.room !== 'all') panel.selectRoom('all'); };
+ incoming.setNotch = (x) => panel.setNotch(x);
+ incoming.applyRemote = (update) => store.applyRemote(update);
+ store.onDeviceError = (id, message) => {
+ const name = store.lightCfg.get(id)?.name || store.acCfg.get(id)?.name || id;
+ panel.toast(`${name}: ${message}`);
+ };
+ // The loop pauses whenever the page is hidden; any sign of life resumes it.
+ const resume = () => { if (!document.hidden) world.setRunning(true); };
+ document.addEventListener('visibilitychange', () => (document.hidden ? hide() : resume()));
+ for (const type of ['focus', 'pageshow', 'pointermove', 'pointerdown']) window.addEventListener(type, resume, { passive: true });
+
+ function planMenu(anchor) {
+ const current = window.__HOUSE_BOOT__?.plan ?? (new URLSearchParams(location.search).get('plan') || 'home');
+ const items = DEMO_PLANS.map((p) => ({
+ label: p.name,
+ selected: p.id === current,
+ icon: p.id === current ? icon('check', 16, 2.4) : null,
+ action: () => {
+ if (isNative) post('selectPlan', { plan: p.id });
+ else location.search = `?plan=${p.id}`;
+ },
+ }));
+ if (window.__HOUSE_BOOT__?.hasCustomPlan) {
+ items.unshift({
+ label: 'My home',
+ selected: current === 'custom',
+ icon: current === 'custom' ? icon('check', 16, 2.4) : null,
+ action: () => post('selectPlan', { plan: 'custom' }),
+ });
+ }
+ if (isNative) {
+ items.push('-',
+ { label: 'Edit home…', action: () => post('openEditor') },
+ { label: 'Load floor plan…', action: () => post('loadPlan') },
+ { label: 'Reveal plan file', action: () => post('revealPlan') },
+ '-',
+ { label: 'Quit House Control', action: () => post('quit') });
+ }
+ openMenu(panel.anchorMenu, anchor, items);
+ }
+
+ const opened = window.__HOUSE_BOOT__?.openDevice || new URLSearchParams(location.search).get('device');
+ if (store.acCfg.has(opened)) panel.openSheet({ kind: 'ac', id: opened });
+ else if (store.lightCfg.has(opened)) panel.openSheet({ kind: 'light', id: opened });
+
+ if (!isNative) show();
+ post('ready', { summary: store.summary() });
+ window.__house = { store, world, panel, config }; // handy in the dev console
+}
+
+const mode = window.__HOUSE_BOOT__?.mode || new URLSearchParams(location.search).get('mode') || 'panel';
+if (mode === 'editor') {
+ document.documentElement.classList.add('mode-editor');
+ import('./editor/editor.js').then((m) => m.bootEditor(app)).catch((e) => fatal('Editor failed to start', e));
+} else {
+ boot();
+}
diff --git a/web/src/store.js b/web/src/store.js
new file mode 100644
index 0000000..e734696
--- /dev/null
+++ b/web/src/store.js
@@ -0,0 +1,245 @@
+import { post, call, isNative } from './bridge.js';
+
+const STORAGE_KEY = 'house-control:state:v1';
+
+export const AC_MODES = ['cool', 'heat', 'dry', 'fan', 'auto'];
+export const AC_FANS = ['auto', 'low', 'medium', 'high', 'turbo'];
+export const AC_SWINGS = ['swing', 'l1', 'l2', 'l3', 'l4', 'l5', 'off'];
+
+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+
+function defaultLight(cfg) {
+ return { on: false, brightness: 0.8, temp: 3000, color: cfg.color || null };
+}
+
+function defaultAC(cfg, outdoor) {
+ return {
+ on: false, target: 24, mode: 'cool', fan: 'auto', swing: 'swing',
+ sleep: false, eco: false, roomTemp: Math.min(outdoor - 2, 27),
+ };
+}
+
+export function createStore(config) {
+ const listeners = new Set();
+ const lightCfg = new Map(config.lights.map((l) => [l.id, l]));
+ const acCfg = new Map(config.acs.map((a) => [a.id, a]));
+
+ const state = { lights: {}, acs: {}, scene: null };
+ for (const l of config.lights) state.lights[l.id] = defaultLight(l);
+ for (const a of config.acs) state.acs[a.id] = defaultAC(a, config.outdoorTemp);
+ // What each real AC can do, as reported by the native side. A simulated AC can do everything.
+ const features = {};
+
+ let restored = false;
+ try {
+ const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null');
+ if (saved && saved.home === config.name) {
+ for (const [id, s] of Object.entries(saved.lights || {})) if (state.lights[id]) Object.assign(state.lights[id], s);
+ for (const [id, s] of Object.entries(saved.acs || {})) if (state.acs[id]) Object.assign(state.acs[id], s);
+ for (const [id, f] of Object.entries(saved.features || {})) if (state.acs[id]) features[id] = f;
+ state.scene = saved.scene || null;
+ restored = true;
+ }
+ } catch { /* storage unavailable: start from defaults */ }
+
+ let saveTimer = 0;
+ function persist() {
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ home: config.name, ...state, features }));
+ } catch { /* ignore */ }
+ }, 200);
+ }
+
+ function emit(change) {
+ for (const fn of listeners) fn(change);
+ if (change.type !== 'tick') {
+ persist();
+ post('summary', summary());
+ }
+ }
+
+ // One command per device is in flight at a time. Whatever changes meanwhile is merged
+ // into a single follow-up, so dragging a slider costs a couple of requests (or infrared
+ // key presses) instead of dozens. A change the device refuses is rolled back.
+ const COOL_DOWN = { light: 300, ac: 900 };
+ const outbox = new Map();
+
+ function transmit(kind, id, patch) {
+ if (!isNative) return Promise.resolve();
+ const current = kind === 'light' ? state.lights[id] : state.acs[id];
+ const sent = call('command', { kind, id, patch, state: { ...current } });
+ // Never let a lost reply block the device for good.
+ return Promise.race([sent, new Promise((resolve) => setTimeout(resolve, 20000))]);
+ }
+
+ function dispatch(kind, id, patch, before) {
+ const slot = outbox.get(id);
+ if (slot) {
+ slot.pending = { ...slot.pending, ...patch };
+ slot.before = { ...before, ...slot.before }; // the oldest value is the one to return to
+ return;
+ }
+ const entry = { pending: null, before: null };
+ outbox.set(id, entry);
+ run(kind, id, patch, before, entry);
+ }
+
+ function run(kind, id, patch, before, entry) {
+ const started = performance.now();
+ transmit(kind, id, patch)
+ .catch((error) => rollback(kind, id, patch, before, entry, error))
+ .then(() => setTimeout(() => {
+ if (!entry.pending) { outbox.delete(id); return; }
+ const [next, prior] = [entry.pending, entry.before];
+ entry.pending = entry.before = null;
+ run(kind, id, next, prior, entry);
+ }, Math.max(0, COOL_DOWN[kind] - (performance.now() - started))));
+ }
+
+ function rollback(kind, id, patch, before, entry, error) {
+ const current = kind === 'light' ? state.lights[id] : state.acs[id];
+ let any = false;
+ for (const key of error.detail?.failed || Object.keys(patch)) {
+ if (!(key in patch)) continue;
+ // Changed again in the meantime: that follow-up now falls back to the last good value.
+ if (entry.pending && key in entry.pending) { entry.before[key] = before[key]; continue; }
+ if (current[key] !== patch[key]) continue; // a real device reported something newer
+ current[key] = before[key];
+ any = true;
+ }
+ if (any) emit({ type: kind, id, reverted: true });
+ store.onDeviceError?.(id, error.message);
+ }
+
+ function sanitizeLight(id, patch) {
+ const caps = lightCfg.get(id).capabilities;
+ const out = {};
+ if ('on' in patch) out.on = Boolean(patch.on);
+ if ('brightness' in patch && caps.includes('brightness')) out.brightness = clamp(patch.brightness, 0.05, 1);
+ if ('temp' in patch && caps.includes('temp')) { out.temp = clamp(patch.temp, 2200, 6500); out.color = null; }
+ if ('color' in patch && caps.includes('color')) out.color = patch.color;
+ return out;
+ }
+
+ function writeLight(id, patch, { remote = false } = {}) {
+ const cur = state.lights[id];
+ if (!cur) return false;
+ const clean = sanitizeLight(id, patch);
+ // Only what actually changed is worth sending to the device.
+ const diff = Object.fromEntries(Object.entries(clean).filter(([k, v]) => cur[k] !== v));
+ if (!Object.keys(diff).length) return false;
+ const before = Object.fromEntries(Object.keys(diff).map((k) => [k, cur[k]]));
+ Object.assign(cur, clean);
+ if (!remote) dispatch('light', id, diff, before);
+ return true;
+ }
+
+ function writeAC(id, patch, { remote = false } = {}) {
+ const cur = state.acs[id];
+ const cfg = acCfg.get(id);
+ if (!cur) return false;
+ const clean = { ...patch };
+ if ('target' in clean) clean.target = clamp(Math.round(clean.target), cfg.min, cfg.max);
+ const diff = Object.fromEntries(Object.entries(clean).filter(([k, v]) => cur[k] !== v));
+ if (!Object.keys(diff).length) return false;
+ const before = Object.fromEntries(Object.keys(diff).map((k) => [k, cur[k]]));
+ Object.assign(cur, clean);
+ const { roomTemp, ...sendable } = diff;
+ if (!remote && Object.keys(sendable).length) dispatch('ac', id, sendable, before);
+ return true;
+ }
+
+ function summary() {
+ const lights = Object.values(state.lights);
+ const acs = Object.entries(state.acs).filter(([, a]) => a.on);
+ return {
+ lightsOn: lights.filter((l) => l.on).length,
+ lightsTotal: lights.length,
+ acOn: acs.length,
+ acTarget: acs.length ? acs[0][1].target : null,
+ acMode: acs.length ? acs[0][1].mode : null,
+ };
+ }
+
+ const store = {
+ state,
+ config,
+ restored,
+ lightCfg,
+ acCfg,
+ summary,
+ /** Set by the UI: called with (device id, message) when a real device refuses a change. */
+ onDeviceError: null,
+
+ /** What the panel may offer for this AC: modes, fan speeds, and the optional extras. */
+ acFeatures(id) {
+ return features[id] || { modes: AC_MODES, fans: AC_FANS, sleep: true, eco: true, swing: true };
+ },
+
+ on(fn) { listeners.add(fn); return () => listeners.delete(fn); },
+
+ setLight(id, patch) {
+ if (writeLight(id, patch)) { state.scene = null; emit({ type: 'light', id }); }
+ },
+ toggleLight(id) { store.setLight(id, { on: !state.lights[id].on }); },
+
+ setAllLights(on) {
+ let any = false;
+ for (const id of Object.keys(state.lights)) any = writeLight(id, { on }) || any;
+ if (any) { state.scene = null; emit({ type: 'bulk' }); }
+ },
+
+ setAC(id, patch) {
+ if (writeAC(id, patch)) emit({ type: 'ac', id });
+ },
+
+ applyScene(sceneId) {
+ const scene = config.scenes.find((s) => s.id === sceneId);
+ if (!scene) return;
+ for (const id of Object.keys(state.lights)) {
+ const patch = { ...(scene.lights['*'] || {}), ...(scene.lights[id] || {}) };
+ // A scene that sets a white temperature should not be overridden by a stale colour.
+ if (!('color' in patch) && 'temp' in patch) patch.color = null;
+ writeLight(id, patch);
+ }
+ for (const id of Object.keys(state.acs)) {
+ const patch = { ...(scene.acs['*'] || {}), ...(scene.acs[id] || {}) };
+ if (Object.keys(patch).length) writeAC(id, patch);
+ }
+ state.scene = sceneId;
+ emit({ type: 'bulk', scene: sceneId });
+ },
+
+ // State reported by real devices (native provider). Never echoed back as a command.
+ applyRemote(update) {
+ let any = false;
+ for (const [id, patch] of Object.entries(update.lights || {})) any = writeLight(id, patch, { remote: true }) || any;
+ for (const [id, patch] of Object.entries(update.acs || {})) any = writeAC(id, patch, { remote: true }) || any;
+ for (const [id, f] of Object.entries(update.features || {})) {
+ if (!state.acs[id] || JSON.stringify(features[id]) === JSON.stringify(f)) continue;
+ features[id] = f;
+ any = true;
+ }
+ if (any) emit({ type: 'bulk', remote: true });
+ },
+ };
+
+ // Without real sensors the room temperature is simulated: it drifts towards the
+ // set-point while an AC runs and back towards the outdoor-ish ambient when it is off.
+ setInterval(() => {
+ let any = false;
+ for (const [id, a] of Object.entries(state.acs)) {
+ if (acCfg.get(id).tuya?.sensorId) continue; // a real sensor reports this room
+ const ambient = Math.min(config.outdoorTemp - 2, 27);
+ const goal = a.on && a.mode !== 'fan' ? a.target : ambient;
+ const step = a.on ? 0.2 : 0.1;
+ const next = Math.abs(goal - a.roomTemp) <= step ? goal : a.roomTemp + Math.sign(goal - a.roomTemp) * step;
+ if (next !== a.roomTemp) { a.roomTemp = Math.round(next * 10) / 10; any = true; }
+ }
+ if (any) { for (const fn of listeners) fn({ type: 'tick' }); persist(); }
+ }, 3000);
+
+ return store;
+}
diff --git a/web/src/style.css b/web/src/style.css
new file mode 100644
index 0000000..e9ccfed
--- /dev/null
+++ b/web/src/style.css
@@ -0,0 +1,684 @@
+@property --mood {
+ syntax: '<color>';
+ inherits: true;
+ initial-value: #17274f;
+}
+
+:root {
+ --bg: #0a0e1a;
+ --text: #f3f5fa;
+ --muted: rgba(222, 230, 247, 0.58);
+ --faint: rgba(222, 230, 247, 0.34);
+ --glass: rgba(255, 255, 255, 0.055);
+ --glass-hi: rgba(255, 255, 255, 0.1);
+ --line: rgba(255, 255, 255, 0.085);
+ --accent: #3d8bff;
+ --warm: #ffb46b;
+ --ease: cubic-bezier(0.22, 1, 0.36, 1);
+ --spring: cubic-bezier(0.34, 1.56, 0.64, 1);
+ color-scheme: dark;
+}
+
+* { box-sizing: border-box; }
+
+html, body {
+ height: 100%;
+ margin: 0;
+ overflow: hidden;
+ font-family: -apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif;
+ color: var(--text);
+ -webkit-font-smoothing: antialiased;
+ user-select: none;
+ -webkit-user-select: none;
+ cursor: default;
+}
+
+body {
+ background:
+ radial-gradient(90% 70% at 20% 0%, #5b6f8f 0%, transparent 60%),
+ radial-gradient(80% 80% at 90% 100%, #6e5a4a 0%, transparent 60%),
+ #2b3140;
+}
+
+html.native body { background: transparent; }
+
+button { font: inherit; color: inherit; border: 0; background: none; padding: 0; cursor: pointer; }
+button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.icon { display: block; flex: none; }
+
+#app {
+ height: 100%;
+ display: grid;
+ place-items: center;
+ padding: 18px;
+}
+
+html.native #app { padding: 13px 24px 34px; place-items: stretch; }
+
+/* ---------- card ---------- */
+
+.card {
+ --stage-h: min(408px, 52%);
+ position: relative;
+ width: 440px;
+ max-width: 100%;
+ height: min(800px, 100%);
+ border-radius: 34px;
+ box-shadow:
+ 0 30px 70px -18px rgba(0, 0, 0, 0.7),
+ 0 10px 24px -8px rgba(0, 0, 0, 0.5);
+ transition: --mood 900ms ease;
+ isolation: isolate;
+}
+
+html.native .card { width: auto; height: auto; box-shadow:
+ 0 18px 30px -12px rgba(0, 0, 0, 0.55),
+ 0 4px 12px -4px rgba(0, 0, 0, 0.4); }
+
+.card-clip {
+ position: absolute;
+ inset: 0;
+ border-radius: inherit;
+ overflow: hidden;
+ overflow: clip; /* unlike hidden, cannot be scrolled by focus or scrollIntoView */
+ background: var(--bg);
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.07) inset;
+}
+
+.notch {
+ position: absolute;
+ top: -9px;
+ left: var(--notch-x, 50%);
+ width: 24px;
+ height: 24px;
+ margin-left: -12px;
+ background: color-mix(in srgb, var(--mood) 46%, var(--bg));
+ border-radius: 5px 0 0 0;
+ transform: rotate(45deg);
+ box-shadow: -1px -1px 0 rgba(255, 255, 255, 0.07);
+ transition: --mood 900ms ease;
+}
+
+.tint {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background:
+ radial-gradient(120% 34% at 50% 0%, var(--mood) 0%, transparent 100%),
+ linear-gradient(180deg, color-mix(in srgb, var(--mood) 38%, transparent) 0%, transparent 46%);
+ mix-blend-mode: screen;
+ opacity: 0.8;
+ z-index: 2;
+}
+
+.stage {
+ position: absolute;
+ inset: 0 0 auto 0;
+ height: var(--stage-h);
+ z-index: 1;
+}
+
+.stage canvas {
+ width: 100%;
+ height: 100%;
+ display: block;
+ outline: none;
+ -webkit-mask-image: linear-gradient(180deg, #000 0%, #000 80%, transparent 100%);
+ mask-image: linear-gradient(180deg, #000 0%, #000 80%, transparent 100%);
+ touch-action: none;
+}
+
+/* Keeps the header legible when the camera pushes the lit model up behind it. */
+.stage::after {
+ content: '';
+ position: absolute;
+ inset: 0 0 auto 0;
+ height: 112px;
+ background: linear-gradient(180deg, rgba(10, 14, 26, 0.86) 0%, rgba(10, 14, 26, 0.5) 55%, transparent 100%);
+ pointer-events: none;
+}
+
+.tooltip {
+ position: absolute;
+ left: 0;
+ top: 0;
+ z-index: 6;
+ padding: 6px 10px 6px 8px;
+ border-radius: 999px;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ font-weight: 600;
+ white-space: nowrap;
+ background: rgba(16, 21, 36, 0.82);
+ border: 1px solid var(--line);
+ backdrop-filter: blur(14px) saturate(1.4);
+ -webkit-backdrop-filter: blur(14px) saturate(1.4);
+ box-shadow: 0 8px 22px rgba(0, 0, 0, 0.45);
+ pointer-events: none;
+ opacity: 0;
+ transform: translate(-50%, -100%) translateY(4px) scale(0.94);
+ transition: opacity 140ms ease, transform 220ms var(--ease);
+}
+.tooltip.show { opacity: 1; transform: translate(-50%, -100%) translateY(-8px) scale(1); }
+.tooltip .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); transition: background 200ms, box-shadow 200ms; }
+.tooltip.on .dot { background: var(--dot, var(--warm)); box-shadow: 0 0 10px var(--dot, var(--warm)); }
+.tooltip span { color: var(--muted); font-weight: 500; }
+
+/* ---------- header ---------- */
+
+.top {
+ position: absolute;
+ inset: 0 0 auto 0;
+ z-index: 5;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 20px 20px 0 22px;
+ pointer-events: none;
+}
+.top > * { pointer-events: auto; }
+.home { flex: 1; min-width: 0; display: flex; align-items: center; gap: 11px; pointer-events: none; }
+.home-badge {
+ width: 34px; height: 34px; border-radius: 11px;
+ display: grid; place-items: center;
+ background: var(--glass-hi);
+ border: 1px solid var(--line);
+ color: #cfe0ff;
+}
+.home-name { font-size: 16px; font-weight: 650; letter-spacing: -0.01em; }
+.home-sub { margin-top: 1px; font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
+.home-sub b { color: var(--text); font-weight: 600; }
+.live { width: 6px; height: 6px; border-radius: 50%; background: #4ade80; box-shadow: 0 0 8px #4ade80; }
+
+.round {
+ width: 36px; height: 36px; border-radius: 50%;
+ display: grid; place-items: center;
+ background: var(--glass-hi);
+ border: 1px solid var(--line);
+ color: var(--muted);
+ transition: transform 260ms var(--spring), background 200ms, color 200ms, box-shadow 300ms;
+}
+.round:hover { background: rgba(255, 255, 255, 0.16); color: var(--text); }
+.round:active { transform: scale(0.9); }
+
+.power {
+ width: 46px; height: 46px;
+ color: var(--muted);
+}
+.power.on {
+ background: linear-gradient(180deg, #5aa2ff, #2f7bf2);
+ border-color: rgba(255, 255, 255, 0.28);
+ color: #fff;
+ box-shadow: 0 8px 22px -4px rgba(61, 139, 255, 0.75), 0 0 0 1px rgba(255, 255, 255, 0.12) inset;
+}
+.power.on:hover { background: linear-gradient(180deg, #6aacff, #3a85f8); }
+
+.top .round { transition: transform 260ms var(--spring), background 200ms, color 200ms, box-shadow 300ms, opacity 220ms; }
+.card.detail .top .round { opacity: 0; transform: scale(0.8); pointer-events: none; }
+
+/* ---------- panel ---------- */
+
+.panel, .sheet {
+ position: absolute;
+ inset: calc(var(--stage-h) - 34px) 0 0 0;
+ z-index: 4;
+ display: flex;
+ flex-direction: column;
+ padding: 0 16px 16px;
+ transition: opacity 280ms ease, transform 460ms var(--ease), visibility 0s;
+}
+
+.panel.hidden, .sheet.hidden {
+ opacity: 0;
+ visibility: hidden;
+ pointer-events: none;
+ transition: opacity 180ms ease, transform 300ms ease, visibility 0s 300ms;
+}
+.panel.hidden { transform: translateY(14px) scale(0.985); }
+.sheet.hidden { transform: translateY(26px); }
+
+.scenes { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 8px; }
+
+.scene {
+ position: relative;
+ height: 62px;
+ border-radius: 18px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ font-size: 11.5px;
+ font-weight: 600;
+ color: var(--muted);
+ background: var(--glass);
+ border: 1px solid var(--line);
+ backdrop-filter: blur(18px);
+ -webkit-backdrop-filter: blur(18px);
+ transition: transform 300ms var(--spring), background 220ms, color 220ms, border-color 220ms, box-shadow 300ms;
+}
+.scene:hover { background: var(--glass-hi); color: var(--text); }
+.scene:active { transform: scale(0.94); }
+.scene.active {
+ color: #fff;
+ background: linear-gradient(180deg, rgba(88, 150, 255, 0.34), rgba(61, 139, 255, 0.14));
+ border-color: rgba(120, 175, 255, 0.55);
+ box-shadow: 0 10px 24px -10px rgba(61, 139, 255, 0.8);
+}
+.scene.active .icon { color: #a9cbff; }
+
+.rooms {
+ display: flex;
+ gap: 6px;
+ margin: 12px -16px 0;
+ padding: 0 16px;
+ overflow-x: auto;
+ scrollbar-width: none;
+ flex: none;
+}
+.rooms::-webkit-scrollbar { display: none; }
+
+.room {
+ flex: none;
+ height: 32px;
+ padding: 0 13px;
+ border-radius: 999px;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--muted);
+ border: 1px solid transparent;
+ transition: background 220ms, color 220ms, border-color 220ms, transform 260ms var(--spring);
+}
+.room:hover { color: var(--text); background: var(--glass); }
+.room:active { transform: scale(0.95); }
+.room.active { color: var(--text); background: var(--glass-hi); border-color: var(--line); }
+.room .count {
+ min-width: 17px; height: 17px; padding: 0 5px; border-radius: 9px;
+ display: grid; place-items: center;
+ font-size: 10.5px; font-weight: 700;
+ color: #2a1a05; background: var(--warm);
+ box-shadow: 0 0 12px -2px var(--warm);
+ transition: transform 260ms var(--spring), opacity 200ms;
+}
+.room .count.zero { transform: scale(0); opacity: 0; min-width: 0; width: 0; padding: 0; margin-left: -7px; }
+
+.list-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 12px 4px 8px;
+ font-size: 12px;
+ color: var(--muted);
+ flex: none;
+}
+.list-head .title { flex: 1; }
+.list-head b { color: var(--text); font-weight: 600; }
+.pill {
+ height: 26px; padding: 0 11px; border-radius: 999px;
+ font-size: 11.5px; font-weight: 600; color: var(--muted);
+ background: var(--glass); border: 1px solid var(--line);
+ transition: background 200ms, color 200ms, transform 260ms var(--spring);
+}
+.pill:hover { background: var(--glass-hi); color: var(--text); }
+.pill:active { transform: scale(0.93); }
+
+.devices {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ margin: 0 -16px -16px;
+ padding: 0 16px 16px;
+ scrollbar-width: none;
+ -webkit-mask-image: linear-gradient(180deg, transparent 0, #000 10px, #000 calc(100% - 22px), transparent 100%);
+ mask-image: linear-gradient(180deg, transparent 0, #000 10px, #000 calc(100% - 22px), transparent 100%);
+}
+.devices::-webkit-scrollbar { display: none; }
+
+.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding-top: 2px; }
+
+.group-label {
+ grid-column: 1 / -1;
+ margin: 8px 4px 0;
+ font-size: 10.5px;
+ font-weight: 700;
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ color: var(--faint);
+}
+.group-label:first-child { margin-top: 0; }
+
+/* ---------- tiles ---------- */
+
+.tile {
+ --c: var(--warm);
+ position: relative;
+ height: 68px;
+ border-radius: 20px;
+ padding: 0 12px;
+ display: flex;
+ align-items: center;
+ gap: 11px;
+ text-align: left;
+ overflow: hidden;
+ background: var(--glass);
+ border: 1px solid var(--line);
+ transition: transform 320ms var(--spring), background 260ms, border-color 260ms, box-shadow 360ms;
+ animation: tile-in 480ms var(--ease) both;
+ animation-delay: calc(var(--i, 0) * 28ms);
+}
+@keyframes tile-in {
+ from { opacity: 0; transform: translateY(10px) scale(0.97); }
+}
+.tile:hover { background: var(--glass-hi); }
+.tile.pressed { transform: scale(0.96); }
+.tile.on {
+ background: linear-gradient(135deg, color-mix(in srgb, var(--c) 26%, transparent), color-mix(in srgb, var(--c) 8%, transparent));
+ border-color: color-mix(in srgb, var(--c) 42%, transparent);
+ box-shadow: 0 12px 26px -16px var(--c);
+}
+
+.bubble {
+ flex: none;
+ width: 38px; height: 38px; border-radius: 13px;
+ display: grid; place-items: center;
+ color: var(--muted);
+ background: rgba(255, 255, 255, 0.07);
+ transition: background 260ms, color 260ms, box-shadow 360ms, transform 320ms var(--spring);
+}
+.tile.on .bubble {
+ color: #241503;
+ background: var(--c);
+ box-shadow: 0 0 22px -3px var(--c);
+}
+.tile.ac.on .bubble { color: #06162c; }
+
+.tile-text { flex: 1; min-width: 0; }
+.tile-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.tile-sub { margin-top: 2px; font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }
+.tile.on .tile-sub { color: color-mix(in srgb, var(--c) 55%, #fff); }
+
+.tile-more {
+ flex: none;
+ width: 26px; height: 26px; margin-right: -4px; border-radius: 9px;
+ display: grid; place-items: center;
+ color: var(--faint);
+ opacity: 0;
+ transition: opacity 180ms, background 180ms, color 180ms;
+}
+.tile:hover .tile-more, .tile-more:focus-visible { opacity: 1; }
+.tile-more:hover { background: rgba(255, 255, 255, 0.12); color: var(--text); }
+
+.tile-level {
+ position: absolute;
+ left: 0; bottom: 0;
+ height: 3px;
+ width: 100%;
+ transform-origin: left;
+ transform: scaleX(var(--level, 0));
+ background: var(--c);
+ opacity: 0;
+ transition: transform 260ms var(--ease), opacity 260ms;
+}
+.tile.on.dimmable .tile-level { opacity: 0.9; }
+.tile.dragging .tile-level { transition: opacity 200ms; height: 4px; }
+.tile.dimmable { cursor: ew-resize; }
+
+.tile.ac { grid-column: 1 / -1; cursor: pointer; }
+.stepper { display: flex; align-items: center; gap: 2px; flex: none; }
+.stepper button {
+ width: 28px; height: 28px; border-radius: 10px;
+ display: grid; place-items: center; color: var(--muted);
+ transition: background 180ms, color 180ms, transform 240ms var(--spring);
+}
+.stepper button:hover { background: rgba(255, 255, 255, 0.12); color: var(--text); }
+.stepper button:active { transform: scale(0.86); }
+.stepper .value { min-width: 38px; text-align: center; font-size: 16px; font-weight: 650; font-variant-numeric: tabular-nums; }
+.tile.ac:not(.on) .stepper .value { color: var(--faint); }
+.mini-power {
+ flex: none;
+ width: 34px; height: 34px; border-radius: 50%;
+ display: grid; place-items: center;
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--muted);
+ transition: background 220ms, color 220ms, transform 260ms var(--spring), box-shadow 300ms;
+}
+.mini-power:hover { background: rgba(255, 255, 255, 0.16); color: var(--text); }
+.mini-power:active { transform: scale(0.88); }
+.tile.ac.on .mini-power { background: var(--c); color: #06162c; box-shadow: 0 0 18px -4px var(--c); }
+
+.tile:focus-visible { outline: none; border-color: rgba(120, 175, 255, 0.8); }
+
+.panel-toast {
+ position: absolute; left: 16px; right: 16px; bottom: 16px; z-index: 30;
+ padding: 11px 14px; border-radius: 16px;
+ font-size: 12.5px; font-weight: 600; line-height: 1.4; color: #ffd9d2;
+ background: rgba(60, 20, 22, 0.92); border: 1px solid rgba(255, 120, 110, 0.5);
+ backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
+ opacity: 0; transform: translateY(12px); pointer-events: none;
+ transition: opacity 220ms, transform 360ms var(--ease);
+}
+.panel-toast.show { opacity: 1; transform: none; }
+
+[hidden] { display: none !important; }
+
+/* ---------- sheets ---------- */
+
+.sheet { padding: 0 20px 18px; }
+
+.sheet-head { display: flex; align-items: center; gap: 10px; flex: none; }
+.sheet-title { flex: 1; min-width: 0; }
+.sheet-name { font-size: 15px; font-weight: 650; }
+.sheet-sub { margin-top: 1px; font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; font-variant-numeric: tabular-nums; }
+.sheet-sub b { color: var(--text); font-weight: 600; }
+
+.readout { display: flex; align-items: flex-end; gap: 12px; margin-top: 18px; flex: none; }
+.big {
+ flex: 1;
+ font-family: -apple-system, 'SF Pro Display', 'Inter', system-ui, sans-serif;
+ font-size: 68px;
+ line-height: 0.9;
+ font-weight: 300;
+ letter-spacing: -0.035em;
+ font-variant-numeric: tabular-nums;
+ display: flex;
+ align-items: baseline;
+ transition: opacity 260ms;
+}
+.big small { font-size: 19px; font-weight: 600; letter-spacing: 0; margin-left: 5px; color: var(--accent); }
+.big.off { opacity: 0.38; }
+.big .num { display: inline-block; }
+.big .num.tick-up { animation: tick-up 260ms var(--ease); }
+.big .num.tick-down { animation: tick-down 260ms var(--ease); }
+@keyframes tick-up { from { transform: translateY(12px); opacity: 0.2; } }
+@keyframes tick-down { from { transform: translateY(-12px); opacity: 0.2; } }
+
+.toggle-chip {
+ height: 44px; padding: 0 10px 0 14px; border-radius: 16px;
+ display: flex; align-items: center; gap: 10px;
+ font-size: 13px; font-weight: 600;
+ background: var(--glass); border: 1px solid var(--line);
+ transition: background 220ms, border-color 220ms;
+}
+.toggle-chip:hover { background: var(--glass-hi); }
+.toggle-chip .icon { color: var(--muted); transition: color 220ms; }
+.toggle-chip.on .icon { color: #6ee7a0; }
+.switch { width: 38px; height: 23px; border-radius: 12px; background: rgba(255, 255, 255, 0.16); position: relative; transition: background 240ms; }
+.switch::after {
+ content: ''; position: absolute; top: 2.5px; left: 2.5px; width: 18px; height: 18px; border-radius: 50%;
+ background: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
+ transition: transform 300ms var(--spring);
+}
+.on > .switch { background: #34c773; }
+.on > .switch::after { transform: translateX(15px); }
+
+.slider-row { display: flex; align-items: center; gap: 10px; margin-top: 18px; flex: none; }
+.slider-row .round { width: 40px; height: 40px; flex: none; }
+
+.slider { flex: 1; min-width: 0; }
+.slider-track {
+ position: relative;
+ height: 46px;
+ border-radius: 15px;
+ background:
+ repeating-linear-gradient(90deg, transparent 0 calc(100% / 14 - 1px), rgba(255, 255, 255, 0.13) calc(100% / 14 - 1px) calc(100% / 14)) center / 100% 9px no-repeat,
+ rgba(0, 0, 0, 0.36);
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.05) inset;
+ cursor: grab;
+ touch-action: none;
+}
+.slider.dragging .slider-track { cursor: grabbing; }
+.slider-fill {
+ position: absolute; inset: 0 auto 0 0;
+ width: calc(var(--p) * (100% - 46px) + 46px);
+ border-radius: 15px;
+ overflow: hidden;
+}
+.slider-fill::before {
+ content: ''; position: absolute; inset: 0 auto 0 0;
+ width: var(--track-w, 300px);
+ background: var(--gradient);
+}
+.slider-thumb {
+ position: absolute; top: 0; left: calc(var(--p) * (100% - 46px));
+ width: 46px; height: 46px; border-radius: 15px;
+ background: #fff;
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4), 0 0 0 0 rgba(90, 160, 255, 0);
+ transition: transform 260ms var(--spring), box-shadow 260ms;
+}
+.slider-thumb::after {
+ content: ''; position: absolute; inset: 15px 21px; border-radius: 2px; background: rgba(10, 14, 26, 0.18);
+}
+.slider.dragging .slider-thumb { transform: scale(1.06); box-shadow: 0 6px 18px rgba(0, 0, 0, 0.45), 0 0 0 3px rgba(90, 160, 255, 0.75); }
+.slider:not(.dragging) .slider-fill, .slider:not(.dragging) .slider-thumb { transition: width 320ms var(--ease), left 320ms var(--ease), transform 260ms var(--spring), box-shadow 260ms; }
+.slider-scale { display: flex; justify-content: space-between; margin: 7px 4px 0; font-size: 11.5px; color: var(--muted); font-variant-numeric: tabular-nums; }
+.slider.compact .slider-track, .slider.compact .slider-thumb { height: 38px; }
+.slider.compact .slider-thumb::after { inset: 12px 21px; }
+
+.field-label { margin: 14px 4px 0; flex: none; font-size: 11.5px; font-weight: 600; color: var(--muted); display: flex; justify-content: space-between; }
+.field-label + .slider-row { margin-top: 8px; }
+
+.options { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin-top: auto; padding-top: 16px; flex: none; }
+.option {
+ position: relative;
+ height: 96px;
+ padding: 12px 11px;
+ border-radius: 20px;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ text-align: left;
+ background: var(--glass);
+ border: 1px solid var(--line);
+ transition: background 220ms, border-color 220ms, transform 300ms var(--spring), box-shadow 300ms;
+}
+.option:hover { background: var(--glass-hi); }
+.option:active { transform: scale(0.95); }
+.option.open, .option.active {
+ background: linear-gradient(180deg, rgba(88, 150, 255, 0.26), rgba(61, 139, 255, 0.1));
+ border-color: rgba(120, 175, 255, 0.5);
+}
+.option > .icon { color: #6fb0ff; }
+.option .corner { position: absolute; top: 11px; right: 10px; color: var(--muted); transition: transform 300ms var(--ease); }
+.option.open .corner { transform: rotate(180deg); }
+.option .corner.dot { width: 8px; height: 8px; border-radius: 50%; background: rgba(255, 255, 255, 0.22); top: 14px; right: 13px; transition: background 220ms, box-shadow 220ms; }
+.option.active .corner.dot { background: #6fb0ff; box-shadow: 0 0 10px #6fb0ff; }
+.option-label { margin-top: auto; font-size: 12px; color: var(--muted); }
+.option-value { margin-top: 2px; font-size: 13px; font-weight: 650; }
+
+.menu {
+ position: absolute;
+ z-index: 20;
+ min-width: 150px;
+ padding: 6px;
+ border-radius: 18px;
+ background: rgba(15, 21, 38, 0.86);
+ border: 1px solid var(--line);
+ backdrop-filter: blur(26px) saturate(1.5);
+ -webkit-backdrop-filter: blur(26px) saturate(1.5);
+ box-shadow: 0 24px 50px -10px rgba(0, 0, 0, 0.7);
+ transform-origin: var(--origin, bottom right);
+ animation: menu-in 260ms var(--ease);
+}
+.menu.closing { animation: menu-out 150ms ease forwards; }
+@keyframes menu-in { from { opacity: 0; transform: scale(0.86) translateY(8px); } }
+@keyframes menu-out { to { opacity: 0; transform: scale(0.94) translateY(4px); } }
+.menu button {
+ width: 100%; height: 36px; padding: 0 10px 0 12px; border-radius: 12px;
+ display: flex; align-items: center; justify-content: space-between; gap: 14px;
+ font-size: 13px; font-weight: 500; color: var(--muted); text-align: left;
+ transition: background 140ms, color 140ms;
+}
+.menu button:hover { background: rgba(255, 255, 255, 0.08); color: var(--text); }
+.menu button.selected { background: rgba(70, 130, 255, 0.28); color: #fff; font-weight: 650; }
+.menu button.selected .icon { color: #8fbcff; }
+.menu hr { border: 0; height: 1px; margin: 5px 8px; background: var(--line); }
+
+.pad {
+ position: relative;
+ flex: 1 1 84px;
+ min-height: 64px;
+ max-height: 120px;
+ margin-top: 8px;
+ border-radius: 16px;
+ background:
+ linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.88) 100%),
+ linear-gradient(90deg, #ff0000 0%, #ffff00 16.6%, #00ff00 33.3%, #00ffff 50%, #0000ff 66.6%, #ff00ff 83.3%, #ff0000 100%);
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
+ cursor: crosshair;
+ touch-action: none;
+ outline: none;
+}
+.pad:focus-visible { box-shadow: 0 0 0 2px var(--accent); }
+.pad-thumb {
+ position: absolute;
+ width: 24px; height: 24px; margin: -12px 0 0 -12px;
+ border-radius: 50%;
+ border: 3px solid #fff;
+ box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5);
+ pointer-events: none;
+ transition: transform 220ms var(--spring), left 260ms var(--ease), top 260ms var(--ease);
+}
+.pad.dragging .pad-thumb { transform: scale(1.25); transition: transform 220ms var(--spring); }
+.pad.empty .pad-thumb { opacity: 0; }
+
+.swatches { display: flex; gap: 9px; margin: 10px 2px 0; flex: none; }
+.swatch {
+ flex: 1; height: 28px; border-radius: 10px;
+ background: var(--sw);
+ border: 2px solid transparent;
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
+ transition: transform 260ms var(--spring), border-color 200ms, box-shadow 260ms;
+}
+.swatch:hover { transform: translateY(-2px); }
+.swatch.selected { border-color: #fff; box-shadow: 0 6px 18px -4px var(--sw); }
+
+.sheet-note { margin-top: auto; padding: 12px 14px; border-radius: 16px; background: var(--glass); border: 1px solid var(--line); font-size: 12px; line-height: 1.45; color: var(--muted); display: flex; gap: 10px; align-items: center; }
+
+/* ---------- boot / error ---------- */
+
+.fatal {
+ width: 440px; max-width: 100%;
+ padding: 26px;
+ border-radius: 28px;
+ background: var(--bg);
+ border: 1px solid var(--line);
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--muted);
+ user-select: text;
+ -webkit-user-select: text;
+}
+.fatal h1 { margin: 0 0 8px; font-size: 16px; color: var(--text); }
+.fatal code { display: block; margin-top: 12px; padding: 12px; border-radius: 12px; background: rgba(255, 255, 255, 0.06); color: #ffb4a8; white-space: pre-wrap; font: 12px ui-monospace, 'SF Mono', monospace; }
+
+.card.booting .stage canvas { opacity: 0; }
+.stage canvas { transition: opacity 500ms ease; }
+
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after { animation-duration: 1ms !important; transition-duration: 1ms !important; }
+}
diff --git a/web/src/three/ac.js b/web/src/three/ac.js
new file mode 100644
index 0000000..4c72a8a
--- /dev/null
+++ b/web/src/three/ac.js
@@ -0,0 +1,167 @@
+// Wall-mounted AC unit with an animated airflow made of additive streaks.
+import * as THREE from 'three';
+import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
+import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
+import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
+import { box, mat, at } from './kit.js';
+
+export const MODE_COLORS = {
+ cool: '#5db2ff',
+ heat: '#ff8c3a',
+ dry: '#62e0cf',
+ fan: '#cfdcff',
+ auto: '#9bd28a',
+};
+
+const FAN_SPEED = { auto: 0.42, low: 0.26, medium: 0.42, high: 0.62, turbo: 0.9 };
+const SWING_ANGLE = { l1: 12, l2: 24, l3: 38, l4: 52, l5: 66, off: 38 };
+const WALL_ROT = { north: 0, south: Math.PI, west: Math.PI / 2, east: -Math.PI / 2 };
+
+const STREAKS = 72;
+const REACH = 2.5;
+
+export class ACUnit {
+ constructor(cfg) {
+ this.cfg = cfg;
+ this.id = cfg.id;
+
+ this.group = new THREE.Group();
+ this.group.position.set(cfg.pos[0], cfg.y, cfg.pos[1]);
+ this.group.rotation.y = WALL_ROT[cfg.wall];
+
+ const body = new THREE.Group();
+ body.position.z = 0.1 + 0.105; // sit on the inner face of the wall
+ const shell = mat('#f3f4f6', { rough: 0.35 });
+ this.led = new THREE.MeshStandardMaterial({ color: '#30343c', emissive: '#000000', roughness: 0.4 });
+ this.flap = box(0.8, 0.012, 0.075, mat('#e3e5e9', { rough: 0.35 }), { r: 0.004 });
+ this.flapPivot = new THREE.Group();
+ this.flapPivot.position.set(0, -0.145, 0.03);
+ this.flap.position.set(0, -0.006, 0.0375);
+ this.flapPivot.add(this.flap);
+ body.add(
+ at(box(0.94, 0.29, 0.21, shell, { r: 0.05 }), 0, -0.145, 0),
+ at(box(0.82, 0.03, 0.09, mat('#17191d', { rough: 0.6 }), { r: 0.006 }), 0, -0.16, 0.055),
+ at(box(0.9, 0.004, 0.006, mat('#c9ccd2'), { r: 0 }), 0, 0.02, 0.105),
+ at(box(0.085, 0.022, 0.006, this.led, { r: 0.003 }), 0.34, -0.06, 0.105),
+ this.flapPivot,
+ );
+ body.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ this.group.add(body);
+ this.body = body;
+
+ // Soft coloured wash so the mode reads on the wall and floor.
+ this.wash = new THREE.PointLight(0xffffff, 0, 3.4, 2);
+ this.wash.position.set(0, -0.5, 0.75);
+ this.group.add(this.wash);
+
+ // Fat lines (screen-space width) so the streaks stay readable over lit walls.
+ const geo = new LineSegmentsGeometry();
+ geo.setPositions(new Float32Array(STREAKS * 6));
+ geo.setColors(new Float32Array(STREAKS * 6));
+ this.flowPos = geo.attributes.instanceStart.data;
+ this.flowCol = geo.attributes.instanceColorStart.data;
+ this.flowPos.setUsage(THREE.DynamicDrawUsage);
+ this.flowCol.setUsage(THREE.DynamicDrawUsage);
+ this.flow = new LineSegments2(geo, new LineMaterial({
+ linewidth: 2.4, vertexColors: true, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, toneMapped: false,
+ }));
+ this.flow.frustumCulled = false;
+ this.flow.position.z = 0.1 + 0.15;
+ this.flow.position.y = -0.17;
+ this.flow.visible = false;
+ this.group.add(this.flow);
+
+ this.seeds = Array.from({ length: STREAKS }, (_, i) => ({
+ phase: (i * 0.618034) % 1,
+ u: ((i * 0.381966) % 1) * 2 - 1,
+ speed: 0.8 + ((i * 0.7548) % 1) * 0.5,
+ wobble: (i * 2.399) % (Math.PI * 2),
+ }));
+
+ this.hit = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.6, 0.6), new THREE.MeshBasicMaterial());
+ this.hit.position.set(0, -0.15, 0.25);
+ this.hit.visible = false;
+ this.hit.userData = { kind: 'ac', id: cfg.id };
+ this.group.add(this.hit);
+
+ this.power = 0;
+ this.goal = 0;
+ this.color = new THREE.Color(MODE_COLORS.cool);
+ this.goalColor = this.color.clone();
+ this.speed = FAN_SPEED.auto;
+ this.swing = 'swing';
+ this.angle = 38;
+ this.clock = 0;
+ this.hover = 0;
+ this.hoverGoal = 0;
+ }
+
+ anchor(out) {
+ return out.set(0, 0.12, 0.2).applyMatrix4(this.group.matrixWorld);
+ }
+
+ apply(state, { instant = false } = {}) {
+ this.goal = state.on ? 1 : 0;
+ this.goalColor.set(MODE_COLORS[state.mode] || MODE_COLORS.cool);
+ this.speed = FAN_SPEED[state.fan] ?? FAN_SPEED.auto;
+ if (state.sleep) this.speed *= 0.6;
+ this.swing = state.swing;
+ if (instant) { this.power = this.goal; this.color.copy(this.goalColor); }
+ }
+
+ update(dt) {
+ this.power += (this.goal - this.power) * (1 - Math.exp(-dt * 3.5));
+ if (Math.abs(this.goal - this.power) < 0.002) this.power = this.goal;
+ this.color.lerp(this.goalColor, 1 - Math.exp(-dt * 5));
+ this.hover += (this.hoverGoal - this.hover) * (1 - Math.exp(-dt * 14));
+ this.clock += dt;
+
+ const target = this.swing === 'swing'
+ ? 38 + Math.sin(this.clock * 0.9) * 26
+ : SWING_ANGLE[this.swing] ?? 38;
+ this.angle += (target - this.angle) * (1 - Math.exp(-dt * 4));
+
+ this.flapPivot.rotation.x = THREE.MathUtils.degToRad(this.angle * 0.9 + 10) * this.power;
+ this.led.emissive.copy(this.color);
+ this.led.emissiveIntensity = this.power * 3;
+ this.wash.color.copy(this.color);
+ this.wash.intensity = this.power * 1.4;
+ this.body.scale.setScalar(1 + this.hover * 0.06);
+
+ const running = this.power > 0.004;
+ this.flow.visible = running;
+ if (running) this.writeFlow();
+ return running || Math.abs(this.hoverGoal - this.hover) > 0.004 || this.goal !== this.power;
+ }
+
+ writeFlow() {
+ const pos = this.flowPos;
+ const col = this.flowCol;
+ const a = THREE.MathUtils.degToRad(this.angle);
+ const sin = Math.sin(a);
+ const cos = Math.cos(a);
+ const { r, g, b } = this.color;
+
+ const sample = (seed, t, out, o) => {
+ const d = REACH * t;
+ const spread = 0.36 + 0.5 * t;
+ const sway = Math.sin(this.clock * 1.6 + seed.wobble + t * 5) * 0.035 * t;
+ out[o] = seed.u * spread + sway;
+ out[o + 1] = -sin * d - 0.35 * t * t;
+ out[o + 2] = cos * d;
+ };
+
+ for (let i = 0; i < STREAKS; i++) {
+ const seed = this.seeds[i];
+ const t = (seed.phase + this.clock * this.speed * seed.speed) % 1;
+ const tail = Math.max(0, t - 0.085);
+ sample(seed, t, pos.array, i * 6);
+ sample(seed, tail, pos.array, i * 6 + 3);
+ const fade = Math.pow(Math.sin(Math.PI * t), 0.7) * this.power * 1.25;
+ col.array[i * 6] = r * fade; col.array[i * 6 + 1] = g * fade; col.array[i * 6 + 2] = b * fade;
+ col.array[i * 6 + 3] = r * fade * 0.1; col.array[i * 6 + 4] = g * fade * 0.1; col.array[i * 6 + 5] = b * fade * 0.1;
+ }
+ pos.needsUpdate = true;
+ col.needsUpdate = true;
+ }
+}
diff --git a/web/src/three/furniture.js b/web/src/three/furniture.js
new file mode 100644
index 0000000..efdb613
--- /dev/null
+++ b/web/src/three/furniture.js
@@ -0,0 +1,373 @@
+// Procedural furniture library. Every builder returns a Group standing on y = 0,
+// centred on its footprint and facing +z; the plan's "rot" turns it from there.
+import * as THREE from 'three';
+import { box, cyl, mat, at, rng } from './kit.js';
+
+const WOOD = '#a98459';
+const DARK_WOOD = '#5a4334';
+const WHITE = '#eceae5';
+const BLACK = '#1b1c21';
+const METAL = '#9a9fa8';
+
+const group = (...children) => {
+ const g = new THREE.Group();
+ g.add(...children.flat().filter(Boolean));
+ return g;
+};
+
+function darker(hex, k = 0.75) {
+ return `#${new THREE.Color(hex).multiplyScalar(k).getHexString()}`;
+}
+
+function legs(w, d, h, material, inset = 0.06, r = 0.022) {
+ const out = [];
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
+ out.push(at(cyl(r, r * 0.8, h, material, 10), sx * (w / 2 - inset), 0, sz * (d / 2 - inset)));
+ }
+ return out;
+}
+
+function seating(width, depth, color, cushions) {
+ const fabric = mat(color, { rough: 1 });
+ const dark = mat(darker(color, 0.82), { rough: 1 });
+ const arm = 0.2;
+ const inner = width - arm * 2;
+ const parts = [
+ ...legs(width, depth, 0.1, mat(BLACK, { rough: 0.5 }), 0.08),
+ at(box(width, 0.2, depth, dark, { r: 0.05 }), 0, 0.1, 0),
+ at(box(inner, 0.52, 0.24, dark, { r: 0.09 }), 0, 0.3, -depth / 2 + 0.12),
+ ];
+ for (const sx of [-1, 1]) parts.push(at(box(arm, 0.36, depth, dark, { r: 0.08 }), sx * (width / 2 - arm / 2), 0.3, 0));
+ const cw = inner / cushions;
+ for (let i = 0; i < cushions; i++) {
+ const x = -inner / 2 + cw * (i + 0.5);
+ parts.push(at(box(cw - 0.02, 0.17, depth - 0.3, fabric, { r: 0.06 }), x, 0.3, 0.1));
+ const back = at(box(cw - 0.04, 0.36, 0.16, fabric, { r: 0.07 }), x, 0.46, -depth / 2 + 0.3);
+ back.rotation.x = -0.14;
+ parts.push(back);
+ }
+ return group(parts);
+}
+
+function chair(color = BLACK) {
+ const m = mat(color, { rough: 0.7 });
+ const back = at(box(0.42, 0.4, 0.04, m, { r: 0.02 }), 0, 0.47, -0.2);
+ back.rotation.x = -0.1;
+ return group(...legs(0.42, 0.42, 0.44, m, 0.04, 0.015), at(box(0.44, 0.05, 0.44, m, { r: 0.02 }), 0, 0.42, 0), back);
+}
+
+function doorLines(width, height, y, z, count, material) {
+ const out = [];
+ for (let i = 1; i < count; i++) out.push(at(box(0.008, height, 0.006, material, { r: 0 }), -width / 2 + (width / count) * i, y, z));
+ return out;
+}
+
+const builders = {
+ rug({ size = [2, 1.4], color = '#3b4a66' }) {
+ const g = group(
+ at(box(size[0], 0.016, size[1], mat(color, { rough: 1 }), { r: 0.006 }), 0, 0, 0),
+ at(box(size[0] - 0.24, 0.018, size[1] - 0.24, mat(darker(color, 1.18), { rough: 1 }), { r: 0.006 }), 0, 0, 0),
+ );
+ g.userData.flat = true;
+ return g;
+ },
+
+ sofa({ width = 2.2, color = '#8b93a7' }) {
+ const g = seating(width, 0.95, color, width > 2 ? 3 : 2);
+ // throw pillow
+ const pillow = at(box(0.36, 0.36, 0.12, mat('#d9b98a', { rough: 1 }), { r: 0.05 }), -width / 2 + 0.42, 0.46, -0.1);
+ pillow.rotation.set(-0.25, 0.3, 0.1);
+ g.add(pillow);
+ return g;
+ },
+
+ armchair({ color = '#c28a5a' }) {
+ return seating(0.92, 0.88, color, 1);
+ },
+
+ coffeeTable({ width = 1.1 }) {
+ const wood = mat(WOOD, { rough: 0.6 });
+ return group(
+ at(box(width, 0.04, 0.58, wood, { r: 0.015 }), 0, 0.36, 0),
+ at(box(width - 0.16, 0.02, 0.44, mat(BLACK, { rough: 0.5 }), { r: 0.008 }), 0, 0.14, 0),
+ ...legs(width, 0.58, 0.36, mat(BLACK, { rough: 0.5 }), 0.07, 0.015),
+ at(box(0.24, 0.035, 0.17, mat('#c9553f', { rough: 0.9 }), { r: 0.006 }), 0.22, 0.4, 0.05),
+ at(cyl(0.05, 0.04, 0.09, mat(WHITE, { rough: 0.4 })), -0.3, 0.4, -0.08),
+ );
+ },
+
+ tv({ width = 1.7 }) {
+ const sw = width * 0.84;
+ const sh = sw * 0.5625;
+ const screen = new THREE.MeshStandardMaterial({
+ color: '#05070c', roughness: 0.25, emissive: '#27407a', emissiveIntensity: 0.35,
+ });
+ return group(
+ at(box(width, 0.36, 0.4, mat(DARK_WOOD, { rough: 0.6 }), { r: 0.015 }), 0, 0.1, 0),
+ ...legs(width, 0.4, 0.1, mat(BLACK), 0.08, 0.015),
+ ...doorLines(width, 0.3, 0.13, 0.2, 3, mat(BLACK)),
+ at(box(sw + 0.03, sh + 0.03, 0.035, mat(BLACK, { rough: 0.4 }), { r: 0.008 }), 0, 0.72, -0.15),
+ at(box(sw - 0.02, sh - 0.02, 0.01, screen, { r: 0 }), 0, 0.745, -0.129),
+ at(box(0.5, 0.07, 0.09, mat('#2a2c33', { rough: 0.7 }), { r: 0.02 }), 0, 0.46, 0.05),
+ );
+ },
+
+ sideboard({ width = 1.6 }) {
+ return group(
+ ...legs(width, 0.42, 0.16, mat(BLACK), 0.07, 0.015),
+ at(box(width, 0.6, 0.42, mat(WOOD, { rough: 0.6 }), { r: 0.015 }), 0, 0.16, 0),
+ ...doorLines(width, 0.54, 0.19, 0.21, 4, mat(DARK_WOOD)),
+ at(cyl(0.07, 0.05, 0.26, mat('#3d6b8c', { rough: 0.35 })), -width / 2 + 0.3, 0.76, 0),
+ at(box(0.3, 0.05, 0.2, mat('#d8c9a8', { rough: 0.9 }), { r: 0.006 }), width / 2 - 0.35, 0.76, 0),
+ );
+ },
+
+ diningSet({ width = 1.8, chairs = 6 }) {
+ const depth = 0.95;
+ const wood = mat('#b48d63', { rough: 0.55 });
+ const g = group(
+ at(box(width, 0.05, depth, wood, { r: 0.02 }), 0, 0.71, 0),
+ ...legs(width, depth, 0.71, mat(BLACK, { rough: 0.5 }), 0.1, 0.028),
+ at(cyl(0.16, 0.1, 0.07, mat(WHITE, { rough: 0.4 })), 0, 0.76, 0),
+ );
+ const perSide = Math.ceil(chairs / 2);
+ for (let i = 0; i < chairs; i++) {
+ const side = i < perSide ? 1 : -1;
+ const k = i < perSide ? i : i - perSide;
+ const n = i < perSide ? perSide : chairs - perSide;
+ const c = chair('#2b2e37');
+ c.position.set(-width / 2 + (width / n) * (k + 0.5), 0, side * (depth / 2 + 0.12));
+ c.rotation.y = side > 0 ? Math.PI : 0;
+ g.add(c);
+ }
+ return g;
+ },
+
+ island({ width = 2.0, stools = 3 }) {
+ const g = group(
+ at(box(width - 0.12, 0.88, 0.62, mat('#39424f', { rough: 0.7 }), { r: 0.015 }), 0, 0, -0.04),
+ at(box(width, 0.05, 0.86, mat('#e9e7e2', { rough: 0.3 }), { r: 0.015 }), 0, 0.88, 0),
+ );
+ for (let i = 0; i < stools; i++) {
+ const x = -width / 2 + (width / stools) * (i + 0.5);
+ g.add(group(
+ at(cyl(0.16, 0.16, 0.012, mat(BLACK, { rough: 0.4 })), x, 0, 0.62),
+ at(cyl(0.015, 0.015, 0.64, mat(METAL, { rough: 0.3, metal: 0.8 }), 10), x, 0, 0.62),
+ at(cyl(0.17, 0.15, 0.05, mat('#c28a5a', { rough: 0.9 })), x, 0.64, 0.62),
+ ));
+ }
+ return g;
+ },
+
+ kitchen({ width = 3, upper = true }) {
+ const front = mat('#e4e1da', { rough: 0.6 });
+ const seam = mat('#b9b6ae');
+ const n = Math.max(2, Math.round(width / 0.6));
+ const g = group(
+ at(box(width, 0.86, 0.6, front, { r: 0.008 }), 0, 0, 0),
+ ...doorLines(width, 0.78, 0.06, 0.3, n, seam),
+ at(box(width + 0.02, 0.04, 0.63, mat('#33363d', { rough: 0.35 }), { r: 0.008 }), 0, 0.86, 0.005),
+ at(box(0.58, 0.012, 0.5, mat('#0c0d10', { rough: 0.15 }), { r: 0 }), -width / 4, 0.9, 0),
+ at(box(0.5, 0.012, 0.38, mat(METAL, { rough: 0.3, metal: 0.9 }), { r: 0 }), width / 4, 0.9, 0.02),
+ at(cyl(0.015, 0.015, 0.24, mat(METAL, { rough: 0.25, metal: 0.9 }), 10), width / 4, 0.9, -0.22),
+ );
+ if (upper) {
+ g.add(
+ at(box(width, 0.72, 0.35, front, { r: 0.008 }), 0, 1.48, -0.125),
+ ...doorLines(width, 0.66, 1.51, 0.05, n, seam),
+ at(box(0.7, 0.1, 0.42, mat('#2f3239', { rough: 0.4, metal: 0.4 }), { r: 0.008 }), -width / 4, 1.42, -0.09),
+ );
+ }
+ return g;
+ },
+
+ fridge() {
+ const body = mat('#c5c9d0', { rough: 0.35, metal: 0.5 });
+ return group(
+ at(box(0.7, 1.92, 0.68, body, { r: 0.025 }), 0, 0, 0),
+ at(box(0.66, 0.008, 0.005, mat('#7c8088'), { r: 0 }), 0, 1.25, 0.34),
+ at(box(0.02, 0.5, 0.03, mat('#70747c', { metal: 0.7, rough: 0.3 }), { r: 0.008 }), -0.26, 1.34, 0.35),
+ at(box(0.02, 0.4, 0.03, mat('#70747c', { metal: 0.7, rough: 0.3 }), { r: 0.008 }), -0.26, 0.76, 0.35),
+ );
+ },
+
+ bed({ width = 1.6, color = '#7f8fb5' }) {
+ const depth = 2.1;
+ const linen = mat('#f1efea', { rough: 1 });
+ const g = group(
+ at(box(width + 0.1, 0.26, depth + 0.04, mat(DARK_WOOD, { rough: 0.7 }), { r: 0.03 }), 0, 0.04, 0),
+ at(box(width + 0.16, 1.02, 0.1, mat(darker(color, 0.6), { rough: 1 }), { r: 0.04 }), 0, 0, -depth / 2),
+ at(box(width, 0.2, depth - 0.06, linen, { r: 0.07 }), 0, 0.28, 0.02),
+ at(box(width + 0.05, 0.13, depth * 0.63, mat(color, { rough: 1 }), { r: 0.06 }), 0, 0.4, depth * 0.17),
+ at(box(width + 0.06, 0.05, 0.3, mat(darker(color, 0.8), { rough: 1 }), { r: 0.02 }), 0, 0.5, depth * 0.36),
+ );
+ for (const sx of [-1, 1]) {
+ const pillow = at(box(width / 2 - 0.14, 0.13, 0.42, linen, { r: 0.06 }), sx * width / 4, 0.46, -depth / 2 + 0.36);
+ pillow.rotation.x = -0.18;
+ g.add(pillow);
+ }
+ return g;
+ },
+
+ nightstand() {
+ return group(
+ at(box(0.46, 0.44, 0.4, mat(WOOD, { rough: 0.6 }), { r: 0.015 }), 0, 0.06, 0),
+ ...legs(0.46, 0.4, 0.06, mat(BLACK), 0.06, 0.014),
+ at(box(0.4, 0.006, 0.005, mat(DARK_WOOD), { r: 0 }), 0, 0.28, 0.2),
+ );
+ },
+
+ dresser({ width = 1.3 }) {
+ const g = group(
+ ...legs(width, 0.45, 0.1, mat(BLACK), 0.06, 0.015),
+ at(box(width, 0.74, 0.45, mat(WHITE, { rough: 0.6 }), { r: 0.015 }), 0, 0.1, 0),
+ at(cyl(0.09, 0.07, 0.18, mat('#c9a15e', { rough: 0.4 })), width / 2 - 0.3, 0.84, 0),
+ );
+ for (let i = 1; i < 3; i++) g.add(at(box(width - 0.06, 0.006, 0.005, mat('#b9b6ae'), { r: 0 }), 0, 0.1 + 0.247 * i, 0.226));
+ return g;
+ },
+
+ plant({ height = 1.2 }) {
+ const rand = rng(Math.round(height * 1000));
+ const leaves = [mat('#3f7d52', { rough: 0.9 }), mat('#4f9462', { rough: 0.9 }), mat('#35694a', { rough: 0.9 })];
+ const g = group(
+ at(cyl(0.17, 0.12, 0.3, mat('#d7d0c4', { rough: 0.8 })), 0, 0, 0),
+ at(cyl(0.15, 0.15, 0.02, mat('#3a2c22', { rough: 1 })), 0, 0.285, 0),
+ at(cyl(0.015, 0.02, height * 0.55, mat('#6b4a33', { rough: 1 }), 8), 0, 0.3, 0),
+ );
+ const count = Math.round(6 + height * 5);
+ for (let i = 0; i < count; i++) {
+ const t = i / (count - 1);
+ const y = 0.5 + t * (height - 0.62);
+ const spread = 0.28 * Math.sin(Math.PI * (0.25 + t * 0.7));
+ const a = rand() * Math.PI * 2;
+ const blob = new THREE.Mesh(new THREE.IcosahedronGeometry(0.13 + rand() * 0.1, 1), leaves[i % 3]);
+ blob.position.set(Math.cos(a) * spread * rand(), y, Math.sin(a) * spread * rand());
+ blob.scale.y = 0.75 + rand() * 0.3;
+ g.add(blob);
+ }
+ return g;
+ },
+
+ vanity({ width = 1.0 }) {
+ const mirror = new THREE.MeshStandardMaterial({ color: '#b9c7dc', roughness: 0.12, metalness: 0.9 });
+ return group(
+ at(box(width, 0.62, 0.48, mat(WOOD, { rough: 0.6 }), { r: 0.012 }), 0, 0.2, 0),
+ ...doorLines(width, 0.56, 0.23, 0.24, 2, mat(DARK_WOOD)),
+ at(box(width + 0.03, 0.04, 0.5, mat(WHITE, { rough: 0.25 }), { r: 0.012 }), 0, 0.82, 0),
+ at(cyl(0.19, 0.15, 0.1, mat(WHITE, { rough: 0.2 })), 0, 0.86, 0.02),
+ at(cyl(0.012, 0.012, 0.2, mat(METAL, { rough: 0.2, metal: 0.9 }), 10), 0, 0.86, -0.18),
+ at(box(width * 0.82, 0.8, 0.025, mirror, { r: 0.01 }), 0, 1.08, -0.225),
+ );
+ },
+
+ bathtub() {
+ return group(
+ at(box(1.7, 0.56, 0.78, mat(WHITE, { rough: 0.25 }), { r: 0.1 }), 0, 0, 0),
+ at(box(1.5, 0.02, 0.58, mat('#9fd3ec', { rough: 0.1, emissive: '#1d4f6b', emissiveIntensity: 0.25 }), { r: 0.009 }), 0, 0.545, 0),
+ at(cyl(0.014, 0.014, 0.2, mat(METAL, { rough: 0.2, metal: 0.9 }), 10), -0.74, 0.56, 0),
+ );
+ },
+
+ toilet() {
+ const c = mat(WHITE, { rough: 0.25 });
+ const bowl = at(cyl(0.19, 0.13, 0.4, c), 0, 0, 0.1);
+ bowl.scale.z = 1.25;
+ const lid = at(cyl(0.2, 0.2, 0.03, c), 0, 0.4, 0.1);
+ lid.scale.z = 1.25;
+ return group(at(box(0.38, 0.78, 0.17, c, { r: 0.03 }), 0, 0, -0.24), bowl, lid);
+ },
+
+ desk({ width = 1.4 }) {
+ const c = chair('#2b2e37');
+ c.position.z = 0.5;
+ c.rotation.y = Math.PI;
+ return group(
+ at(box(width, 0.04, 0.65, mat(WOOD, { rough: 0.55 }), { r: 0.012 }), 0, 0.72, 0),
+ ...legs(width, 0.65, 0.72, mat(BLACK), 0.06, 0.02),
+ at(box(0.56, 0.34, 0.025, mat(BLACK, { rough: 0.3 }), { r: 0.008 }), 0, 0.86, -0.18),
+ at(box(0.2, 0.1, 0.12, mat(BLACK), { r: 0.008 }), 0, 0.76, -0.18),
+ c,
+ );
+ },
+
+ wardrobe({ width = 1.6, height = 2.1 }) {
+ return group(
+ at(box(width, height, 0.6, mat(WHITE, { rough: 0.6 }), { r: 0.015 }), 0, 0, 0),
+ ...doorLines(width, height - 0.08, 0.04, 0.3, Math.max(2, Math.round(width / 0.55)), mat('#b9b6ae')),
+ );
+ },
+
+ bookshelf({ width = 1.0, height = 1.8 }) {
+ const rand = rng(Math.round(width * 100 + height * 7));
+ const wood = mat(WOOD, { rough: 0.6 });
+ const g = group(at(box(width, height, 0.04, wood, { r: 0 }), 0, 0, -0.14));
+ for (const sx of [-1, 1]) g.add(at(box(0.03, height, 0.32, wood, { r: 0 }), sx * (width / 2 - 0.015), 0, 0));
+ const shelves = Math.round(height / 0.38);
+ const colors = ['#c9553f', '#3d6b8c', '#d8c9a8', '#4f9462', '#8b93a7', '#d9b98a'];
+ for (let i = 0; i <= shelves; i++) {
+ const y = (height - 0.03) * (i / shelves);
+ g.add(at(box(width, 0.03, 0.32, wood, { r: 0 }), 0, y, 0));
+ if (i === shelves) break;
+ let x = -width / 2 + 0.06;
+ while (x < width / 2 - 0.12) {
+ const bw = 0.03 + rand() * 0.04;
+ const bh = 0.2 + rand() * 0.1;
+ g.add(at(box(bw, bh, 0.2, mat(colors[Math.floor(rand() * colors.length)], { rough: 0.9 }), { r: 0 }), x + bw / 2, y + 0.03, 0));
+ x += bw + 0.004;
+ if (rand() < 0.12) x += 0.12;
+ }
+ }
+ return g;
+ },
+};
+
+export const FURNITURE_TYPES = Object.keys(builders);
+
+// Approximate [width, depth] of each piece, for the 2D plan editor.
+export function footprint(item) {
+ const w = item.width;
+ switch (item.type) {
+ case 'rug': return item.size || [2, 1.4];
+ case 'sofa': return [w || 2.2, 0.95];
+ case 'armchair': return [0.92, 0.88];
+ case 'coffeeTable': return [w || 1.1, 0.58];
+ case 'tv': return [w || 1.7, 0.4];
+ case 'sideboard': return [w || 1.6, 0.42];
+ case 'diningSet': return [w || 1.8, 1.9];
+ case 'island': return [w || 2, 1.1];
+ case 'kitchen': return [w || 3, 0.62];
+ case 'fridge': return [0.7, 0.68];
+ case 'bed': return [(w || 1.6) + 0.1, 2.14];
+ case 'nightstand': return [0.46, 0.4];
+ case 'dresser': return [w || 1.3, 0.45];
+ case 'plant': return [0.45, 0.45];
+ case 'vanity': return [w || 1, 0.5];
+ case 'bathtub': return [1.7, 0.78];
+ case 'toilet': return [0.4, 0.66];
+ case 'desk': return [w || 1.4, 0.65];
+ case 'wardrobe': return [w || 1.6, 0.6];
+ case 'bookshelf': return [w || 1, 0.32];
+ default: return [0.6, 0.6];
+ }
+}
+
+export function buildFurniture(items) {
+ const root = new THREE.Group();
+ for (const item of items) {
+ const make = builders[item.type];
+ if (!make || !Array.isArray(item.pos)) {
+ console.warn(`[plan] skipping furniture of unknown type "${item.type}"`);
+ continue;
+ }
+ const g = make(item);
+ g.position.set(item.pos[0], item.y || 0, item.pos[1]);
+ g.rotation.y = THREE.MathUtils.degToRad(item.rot || 0);
+ const flat = g.userData.flat;
+ g.traverse((o) => {
+ if (o.isMesh) { o.castShadow = !flat; o.receiveShadow = true; }
+ });
+ root.add(g);
+ }
+ return root;
+}
diff --git a/web/src/three/house.js b/web/src/three/house.js
new file mode 100644
index 0000000..912ed44
--- /dev/null
+++ b/web/src/three/house.js
@@ -0,0 +1,148 @@
+// Turns the rooms + openings of a plan into floors, walls and windows.
+import * as THREE from 'three';
+import { box, mat, at, floorMesh } from './kit.js';
+
+const EXT_T = 0.2; // exterior wall thickness
+const INT_T = 0.1; // interior wall thickness
+const CURB = 0.14; // height of the cut-away walls on the camera side
+const EPS = 1e-4;
+
+const key = (v) => Math.round(v * 1000);
+
+// Splits every room edge into wall segments, classifying each as exterior / interior
+// and attaching the opening (door, window, ...) that covers it, if any.
+function wallSegments(config) {
+ const lines = new Map();
+ const line = (axis, c) => {
+ const k = `${axis}:${key(c)}`;
+ if (!lines.has(k)) lines.set(k, { axis, c, edges: [], openings: [] });
+ return lines.get(k);
+ };
+
+ for (const r of config.rooms) {
+ line('x', r.z).edges.push({ a: r.x, b: r.x + r.w, inside: 1 });
+ line('x', r.z + r.d).edges.push({ a: r.x, b: r.x + r.w, inside: -1 });
+ line('z', r.x).edges.push({ a: r.z, b: r.z + r.d, inside: 1 });
+ line('z', r.x + r.w).edges.push({ a: r.z, b: r.z + r.d, inside: -1 });
+ }
+ for (const o of config.openings) {
+ const alongX = o.from[1] === o.to[1];
+ const k = alongX ? `x:${key(o.from[1])}` : `z:${key(o.from[0])}`;
+ const l = lines.get(k);
+ if (!l) continue; // opening that is not on any wall: ignore
+ const p = alongX ? [o.from[0], o.to[0]] : [o.from[1], o.to[1]];
+ l.openings.push({ ...o, a: Math.min(...p), b: Math.max(...p) });
+ }
+
+ const segments = [];
+ for (const l of lines.values()) {
+ const pts = [...new Set([...l.edges, ...l.openings].flatMap((e) => [key(e.a), key(e.b)]))]
+ .sort((p, q) => p - q).map((p) => p / 1000);
+ const run = [];
+ for (let i = 0; i < pts.length - 1; i++) {
+ const mid = (pts[i] + pts[i + 1]) / 2;
+ const covering = l.edges.filter((e) => e.a < mid && mid < e.b);
+ if (!covering.length) continue;
+ const seg = {
+ axis: l.axis, c: l.c, a: pts[i], b: pts[i + 1],
+ kind: covering.length > 1 ? 'interior' : 'exterior',
+ inside: covering[0].inside,
+ opening: l.openings.find((o) => o.a < mid && mid < o.b) || null,
+ };
+ const prev = run[run.length - 1];
+ if (prev && Math.abs(prev.b - seg.a) < EPS && prev.kind === seg.kind
+ && prev.inside === seg.inside && prev.opening === seg.opening) prev.b = seg.b;
+ else run.push(seg);
+ }
+ // Free ends get a small extension so corners close up.
+ run.forEach((s, i) => {
+ s.freeA = !(run[i - 1] && Math.abs(run[i - 1].b - s.a) < EPS);
+ s.freeB = !(run[i + 1] && Math.abs(run[i + 1].a - s.b) < EPS);
+ });
+ segments.push(...run);
+ }
+ return segments;
+}
+
+export function buildHouse(config, camDir) {
+ const group = new THREE.Group();
+ const floors = [];
+ const H = config.wallHeight;
+ const Hi = Math.min(config.interiorWallHeight, H);
+ const { minX, minZ, maxX, maxZ } = config.bounds;
+
+ // Plinth the model stands on.
+ const plinth = box(maxX - minX + 0.7, 0.3, maxZ - minZ + 0.7, mat('#141927', { rough: 0.9 }), { r: 0.12 });
+ at(plinth, (minX + maxX) / 2, -0.305, (minZ + maxZ) / 2);
+ plinth.receiveShadow = true;
+ group.add(plinth);
+
+ for (const room of config.rooms) {
+ const floor = floorMesh(room, room.floor);
+ floor.userData = { kind: 'room', id: room.id };
+ floors.push(floor);
+ group.add(floor);
+ }
+
+ const wallBody = mat('#e7e3db', { rough: 0.95 });
+ const wallCap = mat('#262b3a', { rough: 0.8 });
+ const wallMats = [wallBody, wallBody, wallCap, wallBody, wallBody, wallBody];
+ const blocker = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false });
+ const glass = new THREE.MeshStandardMaterial({
+ color: '#9cc0ff', roughness: 0.08, transparent: true, opacity: 0.22,
+ emissive: '#3d5fae', emissiveIntensity: 0.5,
+ });
+ const frame = mat('#2c3142', { rough: 0.6 });
+
+ // A wall piece running from a..b along its axis, between heights y0..y1.
+ const piece = (s, a, b, y0, y1, t, materials = wallMats) => {
+ const len = b - a;
+ const geo = s.axis === 'x' ? new THREE.BoxGeometry(len, y1 - y0, t) : new THREE.BoxGeometry(t, y1 - y0, len);
+ const m = new THREE.Mesh(geo, materials);
+ const mid = (a + b) / 2;
+ m.position.set(s.axis === 'x' ? mid : s.c, (y0 + y1) / 2, s.axis === 'x' ? s.c : mid);
+ m.castShadow = m.receiveShadow = true;
+ group.add(m);
+ return m;
+ };
+
+ for (const s of wallSegments(config)) {
+ const exterior = s.kind === 'exterior';
+ const t = exterior ? EXT_T : INT_T;
+ // Outward normal of an exterior wall points away from its room.
+ const nx = s.axis === 'z' ? -s.inside : 0;
+ const nz = s.axis === 'x' ? -s.inside : 0;
+ const near = exterior && nx * camDir.x + nz * camDir.z > 0.15;
+ const a = s.a - (s.freeA ? EXT_T / 2 : 0);
+ const b = s.b + (s.freeB ? EXT_T / 2 : 0);
+ const type = s.opening?.type;
+
+ if (near) {
+ if (type !== 'door') piece(s, a, b, 0, CURB, t);
+ continue;
+ }
+ if (type === 'door' || type === 'open') continue;
+
+ const height = exterior ? H : Hi;
+ if (type === 'window' && exterior) {
+ const { sill, head } = s.opening;
+ piece(s, a, b, 0, sill, t);
+ piece(s, a, b, Math.min(head, H), H, t);
+ const pane = piece(s, a, b, sill, head, 0.03, glass);
+ pane.castShadow = false;
+ const fw = 0.05;
+ const bars = [[a, a + fw, sill, head], [b - fw, b, sill, head], [a, b, sill, sill + fw], [a, b, head - fw, head]];
+ if (b - a > 1.2) bars.push([(a + b) / 2 - fw / 2, (a + b) / 2 + fw / 2, sill, head]);
+ for (const [fa, fb, y0, y1] of bars) piece(s, fa, fb, y0, y1, 0.07, frame);
+ continue;
+ }
+ if (type === 'window') continue; // a window in an interior wall is just a gap
+
+ piece(s, a, b, 0, height, t);
+ // Interior walls are drawn cut low, but lamps should still be contained by the
+ // real, full-height wall: an invisible shadow caster fills in the missing part.
+ if (!exterior && Hi < H) piece(s, a, b, Hi, H, 0.04, blocker).receiveShadow = false;
+ }
+
+ return { group, floors };
+}
diff --git a/web/src/three/kit.js b/web/src/three/kit.js
new file mode 100644
index 0000000..3681f40
--- /dev/null
+++ b/web/src/three/kit.js
@@ -0,0 +1,153 @@
+// Small modelling kit: cached materials, primitive helpers and procedural floor textures.
+import * as THREE from 'three';
+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
+
+const materials = new Map();
+
+export function mat(color, { rough = 0.85, metal = 0, emissive = null, emissiveIntensity = 1, opacity = 1 } = {}) {
+ const key = [color, rough, metal, emissive, emissiveIntensity, opacity].join('|');
+ let m = materials.get(key);
+ if (!m) {
+ m = new THREE.MeshStandardMaterial({ color, roughness: rough, metalness: metal });
+ if (emissive) { m.emissive = new THREE.Color(emissive); m.emissiveIntensity = emissiveIntensity; }
+ if (opacity < 1) { m.transparent = true; m.opacity = opacity; }
+ materials.set(key, m);
+ }
+ return m;
+}
+
+// Box standing on y = 0, centred on x/z.
+export function box(w, h, d, material, { r = 0.02 } = {}) {
+ const radius = Math.max(0, Math.min(r, Math.min(w, h, d) / 2 - 0.001));
+ const geo = radius > 0.002 ? new RoundedBoxGeometry(w, h, d, 2, radius) : new THREE.BoxGeometry(w, h, d);
+ geo.translate(0, h / 2, 0);
+ return new THREE.Mesh(geo, material);
+}
+
+// Cylinder standing on y = 0.
+export function cyl(rTop, rBottom, h, material, seg = 28) {
+ const geo = new THREE.CylinderGeometry(rTop, rBottom, h, seg);
+ geo.translate(0, h / 2, 0);
+ return new THREE.Mesh(geo, material);
+}
+
+export function at(mesh, x = 0, y = 0, z = 0) {
+ mesh.position.set(x, y, z);
+ return mesh;
+}
+
+export function shadows(root, cast = true, receive = true) {
+ root.traverse((o) => {
+ if (o.isMesh) { o.castShadow = cast; o.receiveShadow = receive; }
+ });
+ return root;
+}
+
+// Deterministic pseudo-random so a plan always renders identically.
+export function rng(seed) {
+ let s = seed >>> 0 || 1;
+ return () => {
+ s = (s + 0x6d2b79f5) | 0;
+ let t = Math.imul(s ^ (s >>> 15), 1 | s);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/* ---------- floor textures ---------- */
+
+const TILE = 2.4; // metres covered by one texture repeat
+
+function canvasTexture(size, draw) {
+ const c = document.createElement('canvas');
+ c.width = c.height = size;
+ draw(c.getContext('2d'), size);
+ const tex = new THREE.CanvasTexture(c);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.anisotropy = 8;
+ return tex;
+}
+
+function shade(hex, amount) {
+ const c = new THREE.Color(hex);
+ const hsl = {};
+ c.getHSL(hsl);
+ c.setHSL(hsl.h, hsl.s, Math.min(1, Math.max(0, hsl.l + amount)));
+ return `#${c.getHexString()}`;
+}
+
+function planks(base) {
+ return canvasTexture(1024, (g, s) => {
+ const rand = rng(base.length * 97 + base.charCodeAt(3));
+ const rows = 16;
+ const rh = s / rows;
+ for (let r = 0; r < rows; r++) {
+ let x = -rand() * s * 0.5;
+ while (x < s) {
+ const len = s * (0.35 + rand() * 0.35);
+ g.fillStyle = shade(base, (rand() - 0.5) * 0.09);
+ g.fillRect(x, r * rh, len, rh);
+ g.fillStyle = 'rgba(0,0,0,0.28)';
+ g.fillRect(x, r * rh, 1.5, rh);
+ // faint grain
+ g.strokeStyle = 'rgba(0,0,0,0.05)';
+ for (let k = 0; k < 3; k++) {
+ const y = r * rh + rand() * rh;
+ g.beginPath(); g.moveTo(x, y); g.lineTo(x + len, y + (rand() - 0.5) * 3); g.stroke();
+ }
+ x += len;
+ }
+ g.fillStyle = 'rgba(0,0,0,0.3)';
+ g.fillRect(0, r * rh, s, 1.5);
+ }
+ });
+}
+
+function tiles(base, perSide, grout) {
+ return canvasTexture(512, (g, s) => {
+ const rand = rng(perSide * 31 + base.charCodeAt(2));
+ const t = s / perSide;
+ g.fillStyle = grout;
+ g.fillRect(0, 0, s, s);
+ for (let i = 0; i < perSide; i++) {
+ for (let j = 0; j < perSide; j++) {
+ g.fillStyle = shade(base, (rand() - 0.5) * 0.05);
+ g.fillRect(i * t + 2, j * t + 2, t - 4, t - 4);
+ }
+ }
+ });
+}
+
+const FLOORS = {
+ oak: () => planks('#c7a47c'),
+ walnut: () => planks('#94705a'),
+ tile: () => tiles('#d5dade', 4, '#aab0b8'),
+ stone: () => tiles('#a2a7ae', 3, '#7c828b'),
+};
+
+const floorMaterials = new Map();
+
+export function floorMaterial(kind) {
+ const name = FLOORS[kind] ? kind : 'oak';
+ if (!floorMaterials.has(name)) {
+ floorMaterials.set(name, new THREE.MeshStandardMaterial({
+ map: FLOORS[name](),
+ roughness: name === 'tile' || name === 'stone' ? 0.55 : 0.75,
+ }));
+ }
+ return floorMaterials.get(name);
+}
+
+// Floor quad whose UVs are in world metres, so every room shares one texture scale.
+export function floorMesh(room, kind) {
+ const geo = new THREE.PlaneGeometry(room.w, room.d);
+ geo.rotateX(-Math.PI / 2);
+ geo.translate(room.x + room.w / 2, 0, room.z + room.d / 2);
+ const pos = geo.attributes.position;
+ const uv = geo.attributes.uv;
+ for (let i = 0; i < pos.count; i++) uv.setXY(i, pos.getX(i) / TILE, pos.getZ(i) / TILE);
+ const mesh = new THREE.Mesh(geo, floorMaterial(kind));
+ mesh.receiveShadow = true;
+ return mesh;
+}
diff --git a/web/src/three/lights.js b/web/src/three/lights.js
new file mode 100644
index 0000000..a0ca681
--- /dev/null
+++ b/web/src/three/lights.js
@@ -0,0 +1,257 @@
+// Light fixtures: a small model, the real three.js light(s) it drives and the
+// animation that eases both towards the device state.
+import * as THREE from 'three';
+import { box, cyl, mat, at } from './kit.js';
+
+const STOPS = [
+ [2200, new THREE.Color('#ff9438')],
+ [3000, new THREE.Color('#ffbd7a')],
+ [4200, new THREE.Color('#ffe2c2')],
+ [6500, new THREE.Color('#dfe9ff')],
+];
+
+export function tempToColor(kelvin, out = new THREE.Color()) {
+ const k = Math.min(6500, Math.max(2200, kelvin));
+ for (let i = 0; i < STOPS.length - 1; i++) {
+ const [k0, c0] = STOPS[i];
+ const [k1, c1] = STOPS[i + 1];
+ if (k <= k1) return out.copy(c0).lerp(c1, (k - k0) / (k1 - k0));
+ }
+ return out.copy(STOPS[STOPS.length - 1][1]);
+}
+
+export function lightColor(state, out = new THREE.Color()) {
+ return state.color ? out.set(state.color) : tempToColor(state.temp, out);
+}
+
+const DARK = '#23262e';
+
+function glowMaterial() {
+ return new THREE.MeshStandardMaterial({ color: '#8d8f96', roughness: 0.6, emissive: '#000000', emissiveIntensity: 1 });
+}
+
+function spot(intensity, y) {
+ const light = new THREE.SpotLight(0xffffff, 0, 0, 1.2, 0.75, 2);
+ light.position.set(0, y, 0);
+ light.target.position.set(0, y - 1, 0);
+ light.castShadow = true;
+ light.shadow.mapSize.set(1024, 1024);
+ light.shadow.camera.near = 0.15;
+ light.shadow.camera.far = 9;
+ light.shadow.bias = -0.0006;
+ light.shadow.normalBias = 0.03;
+ light.shadow.radius = 5;
+ light.userData.max = intensity;
+ return light;
+}
+
+function point(intensity, y, { shadow = true, distance = 0, x = 0, z = 0 } = {}) {
+ const light = new THREE.PointLight(0xffffff, 0, distance, 2);
+ light.position.set(x, y, z);
+ if (shadow) {
+ light.castShadow = true;
+ light.shadow.mapSize.set(512, 512);
+ light.shadow.camera.near = 0.08;
+ light.shadow.camera.far = 9;
+ light.shadow.bias = -0.003;
+ light.shadow.normalBias = 0.03;
+ light.shadow.radius = 4;
+ }
+ light.userData.max = intensity;
+ return light;
+}
+
+// Each fixture: { parts: Mesh[], glow: Mesh[] (emissive when on), lights: Light[], hit: [w, h, d, y] }
+const fixtures = {
+ ceiling(cfg, H) {
+ const y = cfg.y ?? H - 0.14;
+ return {
+ parts: [at(cyl(0.012, 0.012, H - y - 0.05, mat(DARK), 8), 0, y + 0.05, 0)],
+ glow: [at(cyl(0.27, 0.27, 0.055, glowMaterial(), 40), 0, y, 0)],
+ lights: [spot(cfg.intensity ?? 20, y - 0.02)],
+ hit: [0.75, 0.5, 0.75, y],
+ };
+ },
+
+ pendant(cfg, H) {
+ const y = cfg.y ?? 1.8;
+ const globe = new THREE.Mesh(new THREE.SphereGeometry(0.17, 32, 20), glowMaterial());
+ globe.position.set(0, y, 0);
+ return {
+ parts: [
+ at(cyl(0.006, 0.006, H - y - 0.15, mat(DARK), 6), 0, y + 0.15, 0),
+ at(cyl(0.04, 0.05, 0.05, mat(DARK, { rough: 0.4, metal: 0.6 }), 16), 0, y + 0.14, 0),
+ ],
+ glow: [globe],
+ lights: [spot(cfg.intensity ?? 9, y - 0.05)],
+ hit: [0.6, 0.7, 0.6, y],
+ };
+ },
+
+ spots(cfg, H) {
+ const y = cfg.y ?? H - 0.16;
+ const glow = [-0.32, 0, 0.32].map((x) => at(cyl(0.055, 0.045, 0.1, glowMaterial(), 20), x, y - 0.06, 0));
+ return {
+ parts: [at(box(0.95, 0.03, 0.05, mat(DARK, { rough: 0.5 }), { r: 0.01 }), 0, y + 0.05, 0)],
+ glow,
+ lights: [spot(cfg.intensity ?? 20, y - 0.08)],
+ hit: [1.1, 0.45, 0.5, y],
+ };
+ },
+
+ floor(cfg) {
+ const shade = cyl(0.14, 0.19, 0.3, glowMaterial(), 32);
+ return {
+ parts: [
+ at(cyl(0.15, 0.16, 0.025, mat(DARK, { rough: 0.4, metal: 0.5 })), 0, 0, 0),
+ at(cyl(0.011, 0.011, 1.3, mat(DARK, { rough: 0.4, metal: 0.5 }), 8), 0, 0.02, 0),
+ ],
+ glow: [at(shade, 0, 1.28, 0)],
+ lights: [point(cfg.intensity ?? 3.4, 1.46)],
+ hit: [0.6, 1.7, 0.6, 0.85],
+ };
+ },
+
+ table(cfg) {
+ const y = cfg.y ?? 0.5;
+ return {
+ parts: [
+ at(cyl(0.065, 0.075, 0.02, mat(DARK, { rough: 0.4, metal: 0.5 })), 0, y, 0),
+ at(cyl(0.01, 0.01, 0.18, mat(DARK, { rough: 0.4, metal: 0.5 }), 8), 0, y + 0.02, 0),
+ ],
+ glow: [at(cyl(0.085, 0.125, 0.17, glowMaterial(), 28), 0, y + 0.18, 0)],
+ lights: [point(cfg.intensity ?? 1.5, y + 0.3)],
+ hit: [0.5, 0.6, 0.5, y + 0.2],
+ };
+ },
+
+ strip(cfg) {
+ const y = cfg.y ?? 1;
+ const length = cfg.length ?? 1;
+ const n = Math.max(1, Math.round(length / 1.0));
+ const lights = [];
+ for (let i = 0; i < n; i++) {
+ const x = -length / 2 + (length / n) * (i + 0.5);
+ lights.push(point((cfg.intensity ?? 1.6) / n, y, { shadow: false, distance: 3.2, x, z: 0.05 }));
+ }
+ return {
+ parts: [],
+ glow: [at(box(length, 0.022, 0.022, glowMaterial(), { r: 0.008 }), 0, y - 0.011, 0)],
+ lights,
+ hit: [length + 0.2, 0.4, 0.4, y],
+ };
+ },
+};
+
+const tmp = new THREE.Color();
+
+export class LightUnit {
+ constructor(cfg, H) {
+ this.cfg = cfg;
+ this.id = cfg.id;
+ const f = fixtures[cfg.type](cfg, H);
+
+ this.group = new THREE.Group();
+ this.group.position.set(cfg.pos[0], 0, cfg.pos[1]);
+ this.group.rotation.y = THREE.MathUtils.degToRad(cfg.rot || 0);
+
+ this.model = new THREE.Group();
+ this.pivotY = f.hit[3];
+ this.model.position.y = this.pivotY;
+ for (const m of [...f.parts, ...f.glow]) {
+ m.position.y -= this.pivotY;
+ m.castShadow = false;
+ m.receiveShadow = false;
+ this.model.add(m);
+ }
+ this.group.add(this.model);
+
+ this.glow = f.glow.map((m) => m.material);
+ this.lights = f.lights;
+ for (const l of this.lights) {
+ this.group.add(l);
+ if (l.target) this.group.add(l.target);
+ }
+
+ const [hw, hh, hd, hy] = f.hit;
+ this.hit = new THREE.Mesh(new THREE.BoxGeometry(hw, hh, hd), new THREE.MeshBasicMaterial());
+ this.hit.position.y = hy;
+ this.hit.visible = false;
+ this.hit.userData = { kind: 'light', id: cfg.id };
+ this.group.add(this.hit);
+
+ this.level = 0; // eased 0..1 output
+ this.goal = 0;
+ this.color = new THREE.Color('#ffbd7a');
+ this.goalColor = this.color.clone();
+ this.hover = 0;
+ this.hoverGoal = 0;
+ this.pulse = 0;
+ this.delay = 0;
+ this.write();
+ }
+
+ // Anchor used for tooltips.
+ anchor(out) {
+ return out.set(0, this.pivotY + 0.25, 0).applyMatrix4(this.group.matrixWorld);
+ }
+
+ apply(state, { instant = false, delay = 0 } = {}) {
+ const dimmable = this.cfg.capabilities.includes('brightness');
+ this.goal = state.on ? (dimmable ? state.brightness : 1) : 0;
+ lightColor(state, this.goalColor);
+ this.delay = delay;
+ if (instant) {
+ this.level = this.goal;
+ this.color.copy(this.goalColor);
+ this.write();
+ } else if (this.level < 0.01) {
+ this.color.copy(this.goalColor); // nothing visible yet: no need to fade the hue
+ }
+ }
+
+ bump() { this.pulse = 1; }
+
+ update(dt) {
+ if (this.delay > 0) { this.delay -= dt; return true; }
+ const k = 1 - Math.exp(-dt * (this.goal > this.level ? 7 : 5));
+ const dl = this.goal - this.level;
+ const dh = this.hoverGoal - this.hover;
+ const dc = Math.abs(this.color.r - this.goalColor.r) + Math.abs(this.color.g - this.goalColor.g)
+ + Math.abs(this.color.b - this.goalColor.b);
+ const moving = Math.abs(dl) > 0.002 || Math.abs(dh) > 0.004 || dc > 0.004 || this.pulse > 0.004;
+ if (!moving) {
+ if (this.level !== this.goal || this.hover !== this.hoverGoal || this.pulse !== 0) {
+ this.level = this.goal; this.hover = this.hoverGoal; this.pulse = 0;
+ this.color.copy(this.goalColor);
+ this.write();
+ return true;
+ }
+ return false;
+ }
+ this.level += dl * k;
+ this.hover += dh * (1 - Math.exp(-dt * 14));
+ this.pulse *= Math.exp(-dt * 7);
+ this.color.lerp(this.goalColor, 1 - Math.exp(-dt * 6));
+ this.write();
+ return true;
+ }
+
+ write() {
+ const out = Math.pow(this.level, 1.5);
+ for (const l of this.lights) {
+ l.intensity = l.userData.max * out;
+ l.color.copy(this.color);
+ }
+ // Lamp bodies stay faintly readable when off and hot enough to bloom when on.
+ const e = this.level > 0.001 ? 0.8 + 1.7 * Math.pow(this.level, 0.7) : 0;
+ for (const m of this.glow) {
+ m.emissive.copy(this.color);
+ m.emissiveIntensity = e + this.hover * 0.5;
+ if (this.level < 0.001) m.emissive.copy(tmp.set('#5b6b93'));
+ m.color.copy(tmp.set('#8d8f96')).lerp(this.color, Math.min(1, this.level * 2));
+ }
+ const s = 1 + this.hover * 0.14 + Math.sin(this.pulse * Math.PI) * 0.22;
+ this.model.scale.setScalar(s);
+ }
+}
diff --git a/web/src/three/world.js b/web/src/three/world.js
new file mode 100644
index 0000000..6c5a14d
--- /dev/null
+++ b/web/src/three/world.js
@@ -0,0 +1,384 @@
+// The 3D stage: renderer, camera rig, picking and the per-frame animation loop.
+import * as THREE from 'three';
+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+import { buildHouse } from './house.js';
+import { buildFurniture } from './furniture.js';
+import { LightUnit } from './lights.js';
+import { ACUnit } from './ac.js';
+
+export const STAGE_BG = '#0a0e1a';
+
+const rad = THREE.MathUtils.degToRad;
+const clamp = THREE.MathUtils.clamp;
+const ORBIT_AZ = 40; // degrees of freedom either side of the plan's default view
+const EL_MIN = 26;
+const EL_MAX = 70;
+
+export function createWorld(canvas, config, store, { onHover, onPick }) {
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: 'high-performance' });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFShadowMap;
+ renderer.shadowMap.autoUpdate = false; // the model is static: shadow maps are rendered once
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(STAGE_BG);
+
+ const camera = new THREE.PerspectiveCamera(24, 1, 0.5, 120);
+
+ const { minX, minZ, maxX, maxZ } = config.bounds;
+ const H = config.wallHeight;
+ const center = new THREE.Vector3((minX + maxX) / 2, 0, (minZ + maxZ) / 2);
+ const span = Math.max(maxX - minX, maxZ - minZ);
+
+ const baseAz = config.camera.azimuth;
+ const camDir = new THREE.Vector3(Math.sin(rad(baseAz)), 0, Math.cos(rad(baseAz)));
+
+ /* ---------- content ---------- */
+
+ const house = buildHouse(config, camDir);
+ scene.add(house.group);
+ scene.add(buildFurniture(config.furniture));
+
+ const lights = new Map();
+ for (const cfg of config.lights) {
+ const unit = new LightUnit(cfg, H);
+ lights.set(cfg.id, unit);
+ scene.add(unit.group);
+ }
+ const acs = new Map();
+ for (const cfg of config.acs) {
+ const unit = new ACUnit(cfg);
+ acs.set(cfg.id, unit);
+ scene.add(unit.group);
+ }
+ const hitTargets = [...[...lights.values()].map((u) => u.hit), ...[...acs.values()].map((u) => u.hit), ...house.floors];
+
+ // Night-time ambience: enough to read the model with every lamp off.
+ scene.add(new THREE.HemisphereLight(0x8ea6ff, 0x0b0e17, 0.42));
+ const moon = new THREE.DirectionalLight(0xa9c0ff, 0.6);
+ // Steep and coming from the viewer's side, so the faces we look at stay readable.
+ moon.position.copy(center).add(new THREE.Vector3(camDir.x * 3.2 + 1.5, 10, camDir.z * 3.2 - 1.5));
+ moon.target.position.copy(center);
+ moon.castShadow = true;
+ moon.shadow.mapSize.set(2048, 2048);
+ const sc = moon.shadow.camera;
+ sc.left = sc.bottom = -span * 0.85;
+ sc.right = sc.top = span * 0.85;
+ sc.near = 1;
+ sc.far = 30;
+ moon.shadow.bias = -0.0008;
+ moon.shadow.normalBias = 0.04;
+ moon.shadow.radius = 4;
+ scene.add(moon, moon.target);
+
+ /* ---------- post-processing ---------- */
+
+ const target = new THREE.WebGLRenderTarget(4, 4, { type: THREE.HalfFloatType, samples: 4 });
+ const composer = new EffectComposer(renderer, target);
+ composer.addPass(new RenderPass(scene, camera));
+ const bloom = new UnrealBloomPass(new THREE.Vector2(4, 4), 0.34, 0.5, 1.0);
+ composer.addPass(bloom);
+ composer.addPass(new OutputPass());
+
+ /* ---------- camera rig ---------- */
+
+ const rig = {
+ az: baseAz, el: config.camera.elevation, dist: 30, target: center.clone(),
+ goal: { az: baseAz, el: config.camera.elevation, dist: 30, target: center.clone() },
+ zoom: 1, focus: null,
+ };
+ let width = 1;
+ let height = 1;
+ let topInset = 0; // pixels at the top covered by the header
+ let bottomInset = 0; // pixels at the bottom covered by the panel
+
+ const v = new THREE.Vector3();
+ const right = new THREE.Vector3();
+ const up = new THREE.Vector3();
+ const fwd = new THREE.Vector3();
+
+ function basis(az, el) {
+ const a = rad(az);
+ const e = rad(el);
+ fwd.set(-Math.sin(a) * Math.cos(e), -Math.sin(e), -Math.cos(a) * Math.cos(e));
+ right.set(Math.cos(a), 0, -Math.sin(a));
+ up.crossVectors(right, fwd);
+ }
+
+ // Smallest distance at which `box` fits the usable part of the viewport.
+ function fitDistance(box, az, el, fill) {
+ basis(az, el);
+ const c = box.getCenter(new THREE.Vector3());
+ const usableH = Math.max(0.3, (height - topInset - bottomInset) / height);
+ const tanV = Math.tan(rad(camera.fov / 2)) * fill * usableH;
+ const tanH = Math.tan(rad(camera.fov / 2)) * camera.aspect * fill;
+ let dist = 0;
+ for (let i = 0; i < 8; i++) {
+ v.set(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z).sub(c);
+ const depth = v.dot(fwd);
+ dist = Math.max(dist, Math.abs(v.dot(right)) / tanH - depth, Math.abs(v.dot(up)) / tanV - depth);
+ }
+ return { dist, center: c };
+ }
+
+ function frameGoal() {
+ const f = rig.focus;
+ let box;
+ let fill = 0.96;
+ if (f?.kind === 'room') {
+ const r = config.rooms.find((x) => x.id === f.id);
+ box = new THREE.Box3(new THREE.Vector3(r.x, 0, r.z), new THREE.Vector3(r.x + r.w, H * 0.75, r.z + r.d));
+ fill = 0.84;
+ } else if (f?.kind === 'ac') {
+ const unit = acs.get(f.id);
+ const p = unit.group.position;
+ const out = new THREE.Vector3(0, 0, 1).applyQuaternion(unit.group.quaternion);
+ box = new THREE.Box3().setFromCenterAndSize(
+ new THREE.Vector3(p.x + out.x * 1.3, 1.25, p.z + out.z * 1.3), new THREE.Vector3(3.6, 2.6, 3.6));
+ fill = 0.92;
+ } else {
+ box = new THREE.Box3(new THREE.Vector3(minX, 0, minZ), new THREE.Vector3(maxX, H * 0.8, maxZ));
+ }
+ const { dist, center: c } = fitDistance(box, rig.goal.az, rig.goal.el, fill);
+ rig.goal.dist = dist * rig.zoom;
+ rig.goal.target.copy(c);
+ }
+
+ function updateRig(dt, instant = false) {
+ const k = instant ? 1 : 1 - Math.exp(-dt * 5.5);
+ const g = rig.goal;
+ const delta = Math.abs(g.az - rig.az) + Math.abs(g.el - rig.el) + Math.abs(g.dist - rig.dist) * 2
+ + rig.target.distanceTo(g.target) * 4;
+ rig.az += (g.az - rig.az) * k;
+ rig.el += (g.el - rig.el) * k;
+ rig.dist += (g.dist - rig.dist) * k;
+ rig.target.lerp(g.target, k);
+ basis(rig.az, rig.el);
+ camera.position.copy(rig.target).addScaledVector(fwd, -rig.dist);
+ camera.up.set(0, 1, 0);
+ camera.lookAt(rig.target);
+ return delta > 0.002;
+ }
+
+ /* ---------- state sync ---------- */
+
+ function syncAll(opts = {}) {
+ let i = 0;
+ for (const [id, unit] of lights) {
+ unit.apply(store.state.lights[id], { ...opts, delay: opts.stagger ? 0.25 + i++ * 0.06 : 0 });
+ }
+ for (const [id, unit] of acs) unit.apply(store.state.acs[id], opts);
+ wake();
+ }
+
+ store.on((change) => {
+ if (change.type === 'tick') return;
+ if (change.type === 'light') lights.get(change.id).apply(store.state.lights[change.id]);
+ else if (change.type === 'ac') acs.get(change.id).apply(store.state.acs[change.id]);
+ else syncAll();
+ wake();
+ });
+
+ /* ---------- picking ---------- */
+
+ const raycaster = new THREE.Raycaster();
+ const ndc = new THREE.Vector2();
+ let hovered = null;
+ let drag = null;
+
+ function pick(ev) {
+ const r = canvas.getBoundingClientRect();
+ ndc.set(((ev.clientX - r.left) / r.width) * 2 - 1, -((ev.clientY - r.top) / r.height) * 2 + 1);
+ raycaster.setFromCamera(ndc, camera);
+ const hits = raycaster.intersectObjects(hitTargets, false);
+ if (!hits.length) return null;
+ // Devices win over the floor they stand on.
+ const device = hits.find((h) => h.object.userData.kind !== 'room');
+ return (device || hits[0]).object.userData;
+ }
+
+ function unitOf(t) {
+ return t?.kind === 'light' ? lights.get(t.id) : t?.kind === 'ac' ? acs.get(t.id) : null;
+ }
+
+ function screenAnchor(t) {
+ const unit = unitOf(t);
+ if (!unit) return null;
+ unit.anchor(v).project(camera);
+ return { x: (v.x * 0.5 + 0.5) * width, y: (-v.y * 0.5 + 0.5) * height };
+ }
+
+ function setHover(t) {
+ const same = hovered?.kind === t?.kind && hovered?.id === t?.id;
+ if (same) return;
+ const prev = unitOf(hovered);
+ if (prev) prev.hoverGoal = 0;
+ hovered = t && t.kind !== 'room' ? t : null;
+ const next = unitOf(hovered);
+ if (next) next.hoverGoal = 1;
+ canvas.style.cursor = hovered ? 'pointer' : drag?.moved ? 'grabbing' : 'grab';
+ onHover(hovered ? { ...hovered, ...screenAnchor(hovered) } : null);
+ wake();
+ }
+
+ canvas.addEventListener('pointerdown', (ev) => {
+ canvas.setPointerCapture(ev.pointerId);
+ drag = { x: ev.clientX, y: ev.clientY, az: rig.goal.az, el: rig.goal.el, moved: false };
+ });
+ canvas.addEventListener('pointermove', (ev) => {
+ if (drag) {
+ const dx = ev.clientX - drag.x;
+ const dy = ev.clientY - drag.y;
+ if (!drag.moved && Math.hypot(dx, dy) > 5) { drag.moved = true; setHover(null); canvas.style.cursor = 'grabbing'; }
+ if (drag.moved) {
+ rig.goal.az = clamp(drag.az - dx * 0.35, baseAz - ORBIT_AZ, baseAz + ORBIT_AZ);
+ rig.goal.el = clamp(drag.el + dy * 0.3, EL_MIN, EL_MAX);
+ frameGoal();
+ wake();
+ }
+ return;
+ }
+ setHover(pick(ev));
+ });
+ const release = (ev) => {
+ if (!drag) return;
+ const wasDrag = drag.moved;
+ drag = null;
+ canvas.style.cursor = 'grab';
+ if (wasDrag) return;
+ const t = pick(ev);
+ if (!t) { onPick(null); return; }
+ if (t.kind === 'light') lights.get(t.id).bump();
+ onPick(t);
+ wake();
+ };
+ canvas.addEventListener('pointerup', release);
+ canvas.addEventListener('pointercancel', () => { drag = null; });
+ canvas.addEventListener('pointerleave', () => { if (!drag) setHover(null); });
+ canvas.addEventListener('wheel', (ev) => {
+ ev.preventDefault();
+ rig.zoom = clamp(rig.zoom * Math.exp(ev.deltaY * 0.0015), 0.55, 1.2);
+ frameGoal();
+ wake();
+ }, { passive: false });
+ canvas.style.cursor = 'grab';
+
+ /* ---------- loop ---------- */
+
+ let raf = 0;
+ let last = 0;
+ let awake = 0; // frames still owed after the last change
+ let running = false;
+ let shadowFrames = 3;
+
+ function wake(frames = 2) {
+ awake = Math.max(awake, frames);
+ if (running && !raf) { last = performance.now(); raf = requestAnimationFrame(frame); }
+ }
+
+ function frame(now) {
+ raf = 0;
+ const dt = Math.min(0.05, (now - last) / 1000);
+ last = now;
+ let active = updateRig(dt);
+ for (const unit of lights.values()) active = unit.update(dt) || active;
+ for (const unit of acs.values()) active = unit.update(dt) || active;
+ if (shadowFrames > 0) { renderer.shadowMap.needsUpdate = true; shadowFrames--; active = true; }
+ if (active || awake > 0) {
+ composer.render(dt);
+ awake = Math.max(0, awake - 1);
+ if (hovered && active) onHover({ ...hovered, ...screenAnchor(hovered) });
+ }
+ if (running && (active || awake > 0)) raf = requestAnimationFrame(frame);
+ }
+
+ function resize() {
+ const r = canvas.getBoundingClientRect();
+ if (!r.width || !r.height) return;
+ width = r.width;
+ height = r.height;
+ const pr = Math.min(window.devicePixelRatio || 1, 2);
+ renderer.setPixelRatio(pr);
+ renderer.setSize(width, height, false);
+ composer.setPixelRatio(pr);
+ composer.setSize(width, height);
+ camera.aspect = width / height;
+ // Centre the model between header and panel by shifting the projection window.
+ camera.setViewOffset(width, height, 0, -(topInset - bottomInset) / 2, width, height);
+ camera.updateProjectionMatrix();
+ frameGoal();
+ wake(3);
+ }
+
+ const world = {
+ lights,
+ acs,
+
+ setInsets(top, bottom) { topInset = top; bottomInset = bottom; resize(); },
+ resize,
+
+ focus(next) {
+ rig.focus = next;
+ rig.zoom = 1;
+ rig.goal.az = baseAz + (next?.kind === 'ac' ? (WALL_SIDE[acs.get(next.id).cfg.wall] ?? 0) : 0);
+ rig.goal.el = next?.kind === 'ac' ? 30 : config.camera.elevation;
+ frameGoal();
+ wake();
+ },
+
+ // Camera sweep + staggered light-up, played whenever the panel appears.
+ intro() {
+ syncAll({ instant: true });
+ for (const unit of lights.values()) { unit.level = 0; unit.write(); }
+ for (const unit of acs.values()) unit.power = 0;
+ syncAll({ stagger: true });
+ frameGoal();
+ rig.az = rig.goal.az - 16;
+ rig.el = rig.goal.el + 9;
+ rig.dist = rig.goal.dist * 1.28;
+ rig.target.copy(rig.goal.target);
+ wake(4);
+ },
+
+ setRunning(on) {
+ running = on;
+ if (on) wake(4);
+ else if (raf) { cancelAnimationFrame(raf); raf = 0; }
+ },
+
+ dispose() {
+ running = false;
+ if (raf) cancelAnimationFrame(raf);
+ raf = 0;
+ composer.dispose();
+ target.dispose();
+ renderer.dispose();
+ renderer.forceContextLoss();
+ },
+
+ // Jump every running animation to its end state (used by tests and screenshots).
+ settle(seconds = 6) {
+ for (let t = 0; t < seconds; t += 0.05) {
+ updateRig(0.05);
+ for (const unit of lights.values()) unit.update(0.05);
+ for (const unit of acs.values()) unit.update(0.05);
+ }
+ renderer.shadowMap.needsUpdate = true;
+ composer.render(0);
+ },
+ };
+
+ syncAll({ instant: true });
+ resize();
+ updateRig(0, true);
+ return world;
+}
+
+// Looking at an AC slightly from the side shows its airflow better.
+const WALL_SIDE = { north: -14, west: 14, south: 0, east: 0 };
diff --git a/web/src/ui/dom.js b/web/src/ui/dom.js
new file mode 100644
index 0000000..aea67d0
--- /dev/null
+++ b/web/src/ui/dom.js
@@ -0,0 +1,196 @@
+// Minimal hyperscript helper: h('div.class', { onclick, style, ... }, ...children)
+export function h(spec, props, ...children) {
+ const [tag, ...classes] = spec.split('.');
+ const el = document.createElement(tag || 'div');
+ if (classes.length) el.className = classes.join(' ');
+ if (props && (props instanceof Node || typeof props !== 'object' || Array.isArray(props))) {
+ children.unshift(props);
+ props = null;
+ }
+ for (const [k, v] of Object.entries(props || {})) {
+ if (v == null || v === false) continue;
+ if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
+ else if (k === 'style') Object.assign(el.style, v);
+ else if (k === 'vars') for (const [name, val] of Object.entries(v)) el.style.setProperty(name, val);
+ else el.setAttribute(k, v === true ? '' : v);
+ }
+ for (const c of children.flat(Infinity)) {
+ if (c == null || c === false) continue;
+ el.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ }
+ return el;
+}
+
+export const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+
+// Horizontal slider with a gradient fill that reveals under a chunky thumb.
+export function createSlider({ min, max, step = 1, value, gradient, compact = false, labels, onInput }) {
+ const fill = h('div.slider-fill');
+ const thumb = h('div.slider-thumb');
+ const track = h('div.slider-track', { vars: { '--gradient': gradient } }, fill, thumb);
+ const el = h(`div.slider${compact ? '.compact' : ''}`, track,
+ labels ? h('div.slider-scale', h('span', labels[0]), h('span', labels[1])) : null);
+
+ let current = value;
+ const paint = () => {
+ el.style.setProperty('--p', String(clamp((current - min) / (max - min), 0, 1)));
+ };
+ new ResizeObserver(() => el.style.setProperty('--track-w', `${track.clientWidth}px`)).observe(track);
+
+ const fromEvent = (ev) => {
+ const r = track.getBoundingClientRect();
+ const size = r.height; // the thumb is square
+ const p = clamp((ev.clientX - r.left - size / 2) / (r.width - size), 0, 1);
+ const raw = min + p * (max - min);
+ return clamp(Math.round(raw / step) * step, min, max);
+ };
+
+ track.addEventListener('pointerdown', (ev) => {
+ track.setPointerCapture(ev.pointerId);
+ el.classList.add('dragging');
+ const next = fromEvent(ev);
+ if (next !== current) { current = next; paint(); onInput(current); }
+ });
+ track.addEventListener('pointermove', (ev) => {
+ if (!el.classList.contains('dragging')) return;
+ const next = fromEvent(ev);
+ if (next !== current) { current = next; paint(); onInput(current); }
+ });
+ const end = () => el.classList.remove('dragging');
+ track.addEventListener('pointerup', end);
+ track.addEventListener('pointercancel', end);
+
+ paint();
+ return {
+ el,
+ set(v) { if (v !== current && !el.classList.contains('dragging')) { current = v; paint(); } },
+ };
+}
+
+// Popup menu anchored to an element, opening upwards (the tiles sit at the bottom of the card).
+export function openMenu(host, anchor, items, { onClose } = {}) {
+ const menu = h('div.menu');
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ document.removeEventListener('pointerdown', outside, true);
+ document.removeEventListener('keydown', onKey, true);
+ menu.classList.add('closing');
+ setTimeout(() => menu.remove(), 150);
+ onClose?.();
+ };
+ const outside = (ev) => {
+ if (menu.contains(ev.target)) return;
+ if (anchor.contains(ev.target)) ev.stopPropagation(); // the click that would re-open it
+ close();
+ };
+ const onKey = (ev) => { if (ev.key === 'Escape') { ev.stopPropagation(); close(); } };
+
+ for (const item of items) {
+ if (item === '-') { menu.append(h('hr')); continue; }
+ menu.append(h(`button${item.selected ? '.selected' : ''}`, {
+ onclick: () => { close(); item.action(); },
+ }, h('span', item.label), item.icon));
+ }
+
+ host.append(menu);
+ const hr = host.getBoundingClientRect();
+ const ar = anchor.getBoundingClientRect();
+ const mw = menu.offsetWidth;
+ const mh = menu.offsetHeight;
+ const below = ar.top - hr.top < mh + 16;
+ const left = clamp(ar.right - hr.left - mw, 10, hr.width - mw - 10);
+ menu.style.left = `${left}px`;
+ menu.style.top = below ? `${ar.bottom - hr.top + 8}px` : `${ar.top - hr.top - mh - 8}px`;
+ const ox = clamp(((ar.left + ar.width / 2 - hr.left - left) / mw) * 100, 10, 90);
+ menu.style.setProperty('--origin', `${ox}% ${below ? '0%' : '100%'}`);
+
+ setTimeout(() => {
+ document.addEventListener('pointerdown', outside, true);
+ document.addEventListener('keydown', onKey, true);
+ }, 0);
+ return close;
+}
+
+/* ---------- colour helpers + picker ---------- */
+
+export function hexToHsv(hex) {
+ const n = parseInt(String(hex).replace('#', ''), 16);
+ if (Number.isNaN(n)) return null;
+ const r = ((n >> 16) & 255) / 255;
+ const g = ((n >> 8) & 255) / 255;
+ const b = (n & 255) / 255;
+ const max = Math.max(r, g, b);
+ const d = max - Math.min(r, g, b);
+ let hue = 0;
+ if (d > 0) {
+ if (max === r) hue = ((g - b) / d) % 6;
+ else if (max === g) hue = (b - r) / d + 2;
+ else hue = (r - g) / d + 4;
+ hue = (hue * 60 + 360) % 360;
+ }
+ return { h: hue, s: max === 0 ? 0 : d / max, v: max };
+}
+
+export function hsvToHex(hue, s, v = 1) {
+ const f = (k) => {
+ const x = (k + hue / 60) % 6;
+ return Math.round((v - v * s * Math.max(0, Math.min(x, 4 - x, 1))) * 255).toString(16).padStart(2, '0');
+ };
+ return `#${f(5)}${f(3)}${f(1)}`;
+}
+
+// Hue runs left to right, saturation fades towards white at the bottom.
+// Brightness is not part of the pad: the lamp's own brightness slider owns it.
+const PAD_MIN_SAT = 0.12;
+
+export function createColorPad({ value, onInput }) {
+ const thumb = h('div.pad-thumb');
+ const el = h('div.pad', { role: 'slider', tabindex: 0, 'aria-label': 'Colour' }, thumb);
+ let dragging = false;
+
+ const place = (x, y, hex) => {
+ el.classList.remove('empty');
+ thumb.style.left = `${x * 100}%`;
+ thumb.style.top = `${y * 100}%`;
+ thumb.style.background = hex;
+ };
+ const show = (hex) => {
+ const c = hex && hexToHsv(hex);
+ if (!c) { el.classList.add('empty'); return; }
+ place(c.h / 360, clamp((1 - c.s) / (1 - PAD_MIN_SAT), 0, 1), hsvToHex(c.h, c.s, 1));
+ };
+ const pick = (ev) => {
+ const r = el.getBoundingClientRect();
+ const x = clamp((ev.clientX - r.left) / r.width, 0, 1);
+ const y = clamp((ev.clientY - r.top) / r.height, 0, 1);
+ const hex = hsvToHex(Math.min(359.9, x * 360), 1 - y * (1 - PAD_MIN_SAT), 1);
+ place(x, y, hex);
+ onInput(hex);
+ };
+
+ el.addEventListener('pointerdown', (ev) => {
+ try { el.setPointerCapture(ev.pointerId); } catch { /* capture is a nicety, not a requirement */ }
+ dragging = true;
+ el.classList.add('dragging');
+ pick(ev);
+ });
+ el.addEventListener('pointermove', (ev) => { if (dragging) pick(ev); });
+ const end = () => { dragging = false; el.classList.remove('dragging'); };
+ el.addEventListener('pointerup', end);
+ el.addEventListener('pointercancel', end);
+ el.addEventListener('keydown', (ev) => {
+ const step = { ArrowLeft: [-0.02, 0], ArrowRight: [0.02, 0], ArrowUp: [0, -0.05], ArrowDown: [0, 0.05] }[ev.key];
+ if (!step) return;
+ ev.preventDefault();
+ const x = clamp((parseFloat(thumb.style.left) || 0) / 100 + step[0], 0, 1);
+ const y = clamp((parseFloat(thumb.style.top) || 0) / 100 + step[1], 0, 1);
+ const hex = hsvToHex(Math.min(359.9, x * 360), 1 - y * (1 - PAD_MIN_SAT), 1);
+ place(x, y, hex);
+ onInput(hex);
+ });
+
+ show(value);
+ return { el, set(hex) { if (!dragging) show(hex); } };
+}
diff --git a/web/src/ui/icons.js b/web/src/ui/icons.js
new file mode 100644
index 0000000..105b915
--- /dev/null
+++ b/web/src/ui/icons.js
@@ -0,0 +1,25 @@
+import {
+ createElement, Power, Sun, Sofa, Film, Moon, DoorOpen, LampCeiling, LampFloor, LampDesk, Lightbulb,
+ Snowflake, Flame, Droplets, Fan, Wind, Leaf, ChevronDown, ChevronLeft, Plus, Minus, Thermometer,
+ SlidersHorizontal, Check, House, Settings2, AirVent, Sparkles, FolderOpen, Plug, Lamp, SunDim, SunMedium,
+ Tv, BedDouble, Palette, RefreshCw, X,
+} from 'lucide';
+
+const ICONS = {
+ power: Power, sun: Sun, sofa: Sofa, film: Film, moon: Moon, door: DoorOpen,
+ ceiling: LampCeiling, pendant: Lamp, spots: Lightbulb, floor: LampFloor, table: LampDesk, strip: Sparkles,
+ cool: Snowflake, heat: Flame, dry: Droplets, fan: Fan, auto: RefreshCw, wind: Wind, leaf: Leaf,
+ down: ChevronDown, back: ChevronLeft, plus: Plus, minus: Minus, thermo: Thermometer,
+ sliders: SlidersHorizontal, check: Check, home: House, settings: Settings2, ac: AirVent,
+ folder: FolderOpen, plug: Plug, dim: SunDim, bright: SunMedium, tv: Tv, bed: BedDouble,
+ palette: Palette, sparkles: Sparkles, close: X,
+};
+
+export function icon(name, size = 18, stroke = 1.8) {
+ const el = createElement(ICONS[name] || ICONS.sparkles);
+ el.setAttribute('width', size);
+ el.setAttribute('height', size);
+ el.setAttribute('stroke-width', stroke);
+ el.classList.add('icon');
+ return el;
+}
diff --git a/web/src/ui/panel.js b/web/src/ui/panel.js
new file mode 100644
index 0000000..4ab65da
--- /dev/null
+++ b/web/src/ui/panel.js
@@ -0,0 +1,545 @@
+// The control panel that lives in the menu bar popover: header, scenes, rooms,
+// device tiles and the detail sheets for a light or an AC.
+import * as THREE from 'three';
+import { h, clamp, createSlider, createColorPad, openMenu } from './dom.js';
+import { icon } from './icons.js';
+import { lightColor } from '../three/lights.js';
+import { MODE_COLORS } from '../three/ac.js';
+import { AC_SWINGS } from '../store.js';
+
+const MODE_LABEL = { cool: 'Cool', heat: 'Heat', dry: 'Dry', fan: 'Fan', auto: 'Auto' };
+const FAN_LABEL = { auto: 'Auto', low: 'Low', medium: 'Medium', high: 'High', turbo: 'Turbo' };
+const SWING_LABEL = { swing: 'Swing', l1: 'L1', l2: 'L2', l3: 'L3', l4: 'L4', l5: 'L5', off: 'Off' };
+const SWATCHES = ['#ff5a4f', '#ff9a3c', '#ffd84a', '#5fe08a', '#42d6e8', '#4f8dff', '#8b5cff', '#ff5fc4'];
+
+const TEMP_GRADIENT = 'linear-gradient(90deg, #2f7df6 0%, #58b4f5 34%, #f3e2c0 62%, #f6a54a 82%, #f0762c 100%)';
+const DIM_GRADIENT = 'linear-gradient(90deg, #4a4f5e 0%, #b9a98c 45%, #ffe2b0 100%)';
+const KELVIN_GRADIENT = 'linear-gradient(90deg, #ff9438 0%, #ffbd7a 30%, #ffe2c2 62%, #dfe9ff 100%)';
+
+const NAVY = new THREE.Color('#17274f');
+const tmp = new THREE.Color();
+const css = (c) => `#${c.getHexString()}`;
+
+function lightStatus(cfg, s) {
+ if (!s.on) return 'Off';
+ return cfg.capabilities.includes('brightness') ? `${Math.round(s.brightness * 100)}%` : 'On';
+}
+
+function acTemperatureColor(target, cfg) {
+ const t = clamp((target - cfg.min) / (cfg.max - cfg.min), 0, 1);
+ return tmp.set('#1c4fc0').lerp(new THREE.Color('#8a3d12'), t).clone();
+}
+
+export function createPanel(root, config, store, { onFocus, onMenu }) {
+ const { state } = store;
+ const ui = { room: 'all', sheet: null };
+ let world = null;
+ const roomName = new Map(config.rooms.map((r) => [r.id, r.name]));
+
+ /* ---------- skeleton ---------- */
+
+ const canvas = h('canvas', { tabindex: -1 });
+ const tooltip = h('div.tooltip');
+ const homeSub = h('div.home-sub');
+ const power = h('button.round.power', { title: 'Everything on / off', 'aria-label': 'Toggle everything', onclick: toggleEverything }, icon('power', 21, 2.2));
+ const gear = h('button.round', { title: 'Floor plan', 'aria-label': 'Floor plan menu', onclick: () => onMenu(gear) }, icon('settings', 17));
+
+ const scenes = h('div.scenes');
+ const rooms = h('div.rooms');
+ const listTitle = h('span.title');
+ const grid = h('div.grid');
+ const panel = h('section.panel',
+ scenes, rooms,
+ h('div.list-head', listTitle,
+ h('button.pill', { onclick: () => bulk(true) }, 'All on'),
+ h('button.pill', { onclick: () => bulk(false) }, 'All off')),
+ h('div.devices', grid));
+ const sheet = h('section.sheet.hidden');
+ sheet.inert = true;
+ const toastEl = h('div.panel-toast');
+
+ const clip = h('div.card-clip',
+ h('div.stage', canvas),
+ h('div.tint'),
+ h('header.top',
+ h('div.home', h('div.home-badge', icon('home', 17)),
+ h('div', h('div.home-name', config.name), homeSub)),
+ gear, power),
+ tooltip, panel, sheet, toastEl);
+ const card = h('div.card.booting', h('div.notch'), clip);
+ root.replaceChildren(card);
+
+ /* ---------- scenes ---------- */
+
+ const sceneButtons = new Map();
+ for (const s of config.scenes) {
+ const b = h('button.scene', { onclick: () => store.applyScene(s.id) }, icon(s.icon, 19), s.name);
+ sceneButtons.set(s.id, b);
+ scenes.append(b);
+ }
+ if (!config.scenes.length) scenes.style.display = 'none';
+
+ /* ---------- rooms ---------- */
+
+ const roomButtons = new Map();
+ for (const r of [{ id: 'all', name: 'All' }, ...config.rooms]) {
+ const count = h('span.count.zero', '0');
+ const b = h('button.room', { onclick: () => selectRoom(r.id) }, r.name, count);
+ roomButtons.set(r.id, { b, count });
+ rooms.append(b);
+ }
+
+ function selectRoom(id) {
+ if (ui.room === id) id = 'all';
+ ui.room = id;
+ layoutTiles();
+ update();
+ roomButtons.get(id).b.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
+ onFocus(id === 'all' ? null : { kind: 'room', id });
+ }
+
+ function inScope(cfg) {
+ return ui.room === 'all' || cfg.room === ui.room;
+ }
+
+ function bulk(on) {
+ if (ui.room === 'all') { store.setAllLights(on); return; }
+ for (const l of config.lights) if (l.room === ui.room) store.setLight(l.id, { on });
+ }
+
+ function toggleEverything() {
+ const anyOn = Object.values(state.lights).some((l) => l.on) || Object.values(state.acs).some((a) => a.on);
+ if (anyOn) {
+ store.setAllLights(false);
+ for (const id of Object.keys(state.acs)) store.setAC(id, { on: false });
+ } else {
+ store.setAllLights(true);
+ }
+ }
+
+ /* ---------- tiles ---------- */
+
+ const tiles = new Map();
+
+ function lightTile(cfg) {
+ const dimmable = cfg.capabilities.includes('brightness');
+ const hasSheet = cfg.capabilities.length > 0;
+ const sub = h('div.tile-sub');
+ const more = hasSheet
+ ? h('button.tile-more', { 'aria-label': `${cfg.name} settings`, onclick: (e) => { e.stopPropagation(); openSheet({ kind: 'light', id: cfg.id }); } }, icon('sliders', 15))
+ : null;
+ const el = h(`div.tile${dimmable ? '.dimmable' : ''}`, { role: 'button', tabindex: 0, 'aria-label': cfg.name },
+ h('div.bubble', icon(cfg.capabilities.length ? cfg.type : 'plug', 19)),
+ h('div.tile-text', h('div.tile-name', cfg.name), sub),
+ more,
+ h('div.tile-level'));
+
+ // Tap toggles; dragging sideways dims (HomeKit-style).
+ let gesture = null;
+ el.addEventListener('pointerdown', (ev) => {
+ if (ev.target.closest('.tile-more') || ev.button !== 0) return;
+ el.setPointerCapture(ev.pointerId);
+ const s = state.lights[cfg.id];
+ gesture = { x: ev.clientX, start: s.on ? s.brightness : 0, moved: false };
+ el.classList.add('pressed');
+ });
+ el.addEventListener('pointermove', (ev) => {
+ if (!gesture) return;
+ const dx = ev.clientX - gesture.x;
+ if (!gesture.moved && dimmable && Math.abs(dx) > 6) { gesture.moved = true; el.classList.add('dragging'); }
+ if (gesture.moved) {
+ const b = clamp(gesture.start + dx / el.clientWidth, 0, 1);
+ store.setLight(cfg.id, b < 0.04 ? { on: false } : { on: true, brightness: b });
+ }
+ });
+ const finish = (ev) => {
+ if (!gesture) return;
+ const tapped = !gesture.moved && ev.type === 'pointerup';
+ gesture = null;
+ el.classList.remove('pressed', 'dragging');
+ if (tapped) toggleLight(cfg.id);
+ };
+ el.addEventListener('pointerup', finish);
+ el.addEventListener('pointercancel', finish);
+ el.addEventListener('keydown', (ev) => {
+ if (ev.key === ' ' || ev.key === 'Enter') { ev.preventDefault(); toggleLight(cfg.id); }
+ });
+
+ return {
+ el, cfg, kind: 'light',
+ update() {
+ const s = state.lights[cfg.id];
+ el.classList.toggle('on', s.on);
+ el.style.setProperty('--c', css(lightColor(s, tmp)));
+ el.style.setProperty('--level', s.on ? String(s.brightness) : '0');
+ sub.textContent = ui.room === 'all' ? `${lightStatus(cfg, s)} · ${roomName.get(cfg.room)}` : lightStatus(cfg, s);
+ },
+ };
+ }
+
+ function acTile(cfg) {
+ const sub = h('div.tile-sub');
+ const value = h('div.value');
+ const bubble = h('div.bubble');
+ const step = (d) => (e) => {
+ e.stopPropagation();
+ const s = state.acs[cfg.id];
+ store.setAC(cfg.id, { on: true, target: s.target + d });
+ };
+ const el = h('div.tile.ac', { role: 'button', tabindex: 0, 'aria-label': cfg.name, onclick: () => openSheet({ kind: 'ac', id: cfg.id }) },
+ bubble,
+ h('div.tile-text', h('div.tile-name', cfg.name), sub),
+ h('div.stepper',
+ h('button', { 'aria-label': 'Cooler', onclick: step(-1) }, icon('minus', 15, 2.2)),
+ value,
+ h('button', { 'aria-label': 'Warmer', onclick: step(1) }, icon('plus', 15, 2.2))),
+ h('button.mini-power', { 'aria-label': `${cfg.name} power`, onclick: (e) => { e.stopPropagation(); store.setAC(cfg.id, { on: !state.acs[cfg.id].on }); } }, icon('power', 16, 2.2)));
+ el.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') openSheet({ kind: 'ac', id: cfg.id }); });
+ let shownMode = null;
+ return {
+ el, cfg, kind: 'ac',
+ update() {
+ const s = state.acs[cfg.id];
+ el.classList.toggle('on', s.on);
+ el.style.setProperty('--c', MODE_COLORS[s.mode]);
+ if (shownMode !== s.mode) { bubble.replaceChildren(icon(s.mode, 19)); shownMode = s.mode; }
+ value.textContent = `${s.target}°`;
+ sub.textContent = `${s.on ? MODE_LABEL[s.mode] : 'Off'} · Room ${s.roomTemp.toFixed(1)}°`;
+ },
+ };
+ }
+
+ for (const cfg of config.acs) tiles.set(cfg.id, acTile(cfg));
+ for (const cfg of config.lights) tiles.set(cfg.id, lightTile(cfg));
+
+ function toggleLight(id) {
+ world?.lights.get(id)?.bump();
+ store.toggleLight(id);
+ }
+
+ function layoutTiles() {
+ const nodes = [];
+ let i = 0;
+ const add = (t) => { t.el.style.setProperty('--i', i++); nodes.push(t.el); };
+ for (const room of config.rooms) {
+ if (ui.room !== 'all' && room.id !== ui.room) continue;
+ const devices = [...tiles.values()].filter((t) => t.cfg.room === room.id);
+ if (!devices.length) continue;
+ if (ui.room === 'all') nodes.push(h('div.group-label', room.name));
+ devices.filter((t) => t.kind === 'ac').forEach(add);
+ devices.filter((t) => t.kind === 'light').forEach(add);
+ }
+ if (!nodes.length) nodes.push(h('div.group-label', 'No devices in this room yet'));
+ grid.replaceChildren(...nodes);
+ grid.parentElement.scrollTop = 0;
+ }
+
+ /* ---------- sheets ---------- */
+
+ let sheetView = null;
+
+ function openSheet(target) {
+ ui.sheet = target;
+ sheetView = target.kind === 'ac' ? acSheet(target.id) : lightSheet(target.id);
+ sheet.replaceChildren(...sheetView.nodes);
+ panel.classList.add('hidden');
+ sheet.classList.remove('hidden');
+ panel.inert = true;
+ sheet.inert = false;
+ card.classList.add('detail');
+ hideTooltip();
+ onFocus(target.kind === 'ac' ? target : { kind: 'room', id: store.lightCfg.get(target.id).room });
+ update();
+ }
+
+ function closeSheet() {
+ if (!ui.sheet) return false;
+ ui.sheet = null;
+ sheetView = null;
+ sheet.classList.add('hidden');
+ panel.classList.remove('hidden');
+ panel.inert = false;
+ sheet.inert = true;
+ card.classList.remove('detail');
+ onFocus(ui.room === 'all' ? null : { kind: 'room', id: ui.room });
+ update();
+ return true;
+ }
+
+ function sheetHead(name, sub, powerBtn) {
+ return h('div.sheet-head',
+ h('button.round', { 'aria-label': 'Back', onclick: closeSheet }, icon('back', 19, 2.2)),
+ h('div.sheet-title', h('div.sheet-name', name), sub),
+ powerBtn);
+ }
+
+ function bigNumber(unit) {
+ const num = h('span.num');
+ const el = h('div.big', num, h('small', unit));
+ let shown = null;
+ return {
+ el,
+ set(value, off) {
+ el.classList.toggle('off', off);
+ if (value === shown) return;
+ if (shown !== null) {
+ num.classList.remove('tick-up', 'tick-down');
+ void num.offsetWidth;
+ num.classList.add(value > shown ? 'tick-up' : 'tick-down');
+ }
+ num.textContent = value;
+ shown = value;
+ },
+ };
+ }
+
+ function acSheet(id) {
+ const cfg = store.acCfg.get(id);
+ const s = () => state.acs[id];
+ const set = (patch) => store.setAC(id, patch);
+ const sub = h('div.sheet-sub');
+ const powerBtn = h('button.round.power', { 'aria-label': 'Power', onclick: () => set({ on: !s().on }) }, icon('power', 21, 2.2));
+ const big = bigNumber('°C');
+ const eco = h('button.toggle-chip', { onclick: () => set({ eco: !s().eco }) }, icon('leaf', 17), 'Eco Mode', h('span.switch'));
+ const slider = createSlider({
+ min: cfg.min, max: cfg.max, value: s().target, gradient: TEMP_GRADIENT,
+ labels: [`${cfg.min}°`, `${cfg.max}°`],
+ onInput: (v) => set({ on: true, target: v }),
+ });
+
+ const features = () => store.acFeatures(id);
+ const option = (key, label, labels, values, iconName) => {
+ const value = h('div.option-value');
+ let holder = h('span');
+ const el = h('button.option', { onclick: () => {
+ el.classList.add('open');
+ openMenu(clip, el, values().map((v) => ({
+ label: labels[v], selected: s()[key] === v, icon: s()[key] === v ? icon('check', 16, 2.4) : null,
+ action: () => set(key === 'mode' ? { on: true, mode: v } : { [key]: v }),
+ })), { onClose: () => el.classList.remove('open') });
+ } }, holder, h('span.corner', icon('down', 15, 2.2)), h('div.option-label', label), value);
+ let shown = null;
+ return {
+ el,
+ update() {
+ value.textContent = labels[s()[key]];
+ const ic = iconName || s().mode;
+ if (shown !== ic) {
+ const next = icon(ic, 24, 1.6);
+ holder.replaceWith(next);
+ holder = next;
+ shown = ic;
+ }
+ },
+ };
+ };
+
+ const mode = option('mode', 'Mode', MODE_LABEL, () => features().modes, null);
+ const fan = option('fan', 'Fan speed', FAN_LABEL, () => features().fans, 'fan');
+ const swing = option('swing', 'Airflow', SWING_LABEL, () => AC_SWINGS, 'wind');
+ const sleepValue = h('div.option-value');
+ const sleep = h('button.option', { onclick: () => set({ sleep: !s().sleep }) },
+ icon('moon', 24, 1.6), h('span.corner.dot'), h('div.option-label', 'Sleep'), sleepValue);
+ const options = h('div.options', mode.el, fan.el, sleep, swing.el);
+
+ return {
+ nodes: [
+ sheetHead(cfg.name, sub, powerBtn),
+ h('div.readout', big.el, eco),
+ h('div.slider-row',
+ h('button.round', { 'aria-label': 'Cooler', onclick: () => set({ on: true, target: s().target - 1 }) }, icon('minus', 18, 2.2)),
+ slider.el,
+ h('button.round', { 'aria-label': 'Warmer', onclick: () => set({ on: true, target: s().target + 1 }) }, icon('plus', 18, 2.2))),
+ options,
+ ],
+ update() {
+ const a = s();
+ // A real AC only shows the controls it has a function for.
+ const f = features();
+ const shown = [[mode.el, f.modes.length > 0], [fan.el, f.fans.length > 0], [sleep, f.sleep], [swing.el, f.swing]];
+ for (const [el, on] of shown) el.hidden = !on;
+ eco.hidden = !f.eco;
+ options.style.gridTemplateColumns = `repeat(${shown.filter(([, on]) => on).length || 1}, 1fr)`;
+ powerBtn.classList.toggle('on', a.on);
+ sub.replaceChildren(icon('thermo', 14), 'Room ', h('b', `${a.roomTemp.toFixed(1)}°C`),
+ h('span.live', { style: { background: a.on ? MODE_COLORS[a.mode] : 'rgba(255,255,255,.25)', boxShadow: a.on ? `0 0 8px ${MODE_COLORS[a.mode]}` : 'none' } }));
+ big.set(a.target, !a.on);
+ slider.set(a.target);
+ eco.classList.toggle('on', a.eco);
+ mode.update(); fan.update(); swing.update();
+ sleep.classList.toggle('active', a.sleep);
+ sleepValue.textContent = a.sleep ? 'On' : 'Off';
+ },
+ };
+ }
+
+ function lightSheet(id) {
+ const cfg = store.lightCfg.get(id);
+ const s = () => state.lights[id];
+ const set = (patch) => store.setLight(id, patch);
+ const caps = cfg.capabilities;
+ const sub = h('div.sheet-sub');
+ const powerBtn = h('button.round.power', { 'aria-label': 'Power', onclick: () => toggleLight(id) }, icon('power', 21, 2.2));
+ const big = bigNumber('%');
+ const nodes = [sheetHead(cfg.name, sub, powerBtn), h('div.readout', big.el)];
+ const sliders = {};
+
+ if (caps.includes('brightness')) {
+ sliders.brightness = createSlider({
+ min: 5, max: 100, value: Math.round(s().brightness * 100), gradient: DIM_GRADIENT,
+ onInput: (v) => set({ on: true, brightness: v / 100 }),
+ });
+ nodes.push(h('div.slider-row',
+ h('button.round', { 'aria-label': 'Dimmer', onclick: () => set({ on: true, brightness: s().brightness - 0.1 }) }, icon('dim', 18)),
+ sliders.brightness.el,
+ h('button.round', { 'aria-label': 'Brighter', onclick: () => set({ on: true, brightness: s().brightness + 0.1 }) }, icon('bright', 18))));
+ }
+ let kelvinLabel = null;
+ if (caps.includes('temp')) {
+ kelvinLabel = h('span');
+ sliders.temp = createSlider({
+ min: 2200, max: 6500, step: 100, value: s().temp, gradient: KELVIN_GRADIENT, compact: true,
+ onInput: (v) => set({ on: true, temp: v }),
+ });
+ nodes.push(h('div.field-label', h('span', 'Colour temperature'), kelvinLabel), h('div.slider-row', sliders.temp.el));
+ }
+ let swatches = [];
+ let pad = null;
+ let colorLabel = null;
+ if (caps.includes('color')) {
+ colorLabel = h('span');
+ pad = createColorPad({ value: s().color, onInput: (c) => set({ on: true, color: c }) });
+ swatches = SWATCHES.map((c) => h('button.swatch', { 'aria-label': `Colour ${c}`, vars: { '--sw': c }, onclick: () => set({ on: true, color: c }) }));
+ nodes.push(h('div.field-label', h('span', 'Colour'), colorLabel), pad.el, h('div.swatches', swatches));
+ } else {
+ nodes.push(h('div.sheet-note', icon(cfg.type, 20),
+ `${roomName.get(cfg.room)} · drag across a light tile to dim it, or click the lamp in the 3D view to toggle.`));
+ }
+
+ return {
+ nodes,
+ update() {
+ const l = s();
+ powerBtn.classList.toggle('on', l.on);
+ sub.replaceChildren(roomName.get(cfg.room), ' · ', h('b', l.on ? 'On' : 'Off'));
+ big.set(caps.includes('brightness') ? Math.round(l.brightness * 100) : l.on ? 100 : 0, !l.on);
+ sliders.brightness?.set(Math.round(l.brightness * 100));
+ sliders.temp?.set(l.temp);
+ if (kelvinLabel) kelvinLabel.textContent = l.color ? '—' : `${l.temp} K`;
+ swatches.forEach((el, i) => el.classList.toggle('selected', l.color?.toLowerCase() === SWATCHES[i]));
+ pad?.set(l.color);
+ if (colorLabel) colorLabel.textContent = l.color ? l.color.toUpperCase() : 'White';
+ },
+ };
+ }
+
+ /* ---------- tooltip ---------- */
+
+ function hideTooltip() { tooltip.classList.remove('show'); }
+
+ function showTooltip(hit) {
+ if (!hit) { hideTooltip(); return; }
+ let name;
+ let status;
+ let on;
+ let color;
+ if (hit.kind === 'light') {
+ const cfg = store.lightCfg.get(hit.id);
+ const s = state.lights[hit.id];
+ name = cfg.name; status = lightStatus(cfg, s); on = s.on; color = css(lightColor(s, tmp));
+ } else {
+ const cfg = store.acCfg.get(hit.id);
+ const s = state.acs[hit.id];
+ name = cfg.name; status = s.on ? `${MODE_LABEL[s.mode]} ${s.target}°` : 'Off'; on = s.on; color = MODE_COLORS[s.mode];
+ }
+ tooltip.replaceChildren(h('i.dot'), name, h('span', status));
+ tooltip.classList.toggle('on', on);
+ tooltip.style.setProperty('--dot', color);
+ tooltip.style.left = `${clamp(hit.x, 70, card.clientWidth - 70)}px`;
+ tooltip.style.top = `${Math.max(64, hit.y)}px`;
+ tooltip.classList.add('show');
+ }
+
+ /* ---------- derived state ---------- */
+
+ function mood() {
+ if (ui.sheet?.kind === 'ac') {
+ const a = state.acs[ui.sheet.id];
+ if (!a.on) return NAVY.clone().multiplyScalar(0.8);
+ if (a.mode === 'cool' || a.mode === 'heat' || a.mode === 'auto') return acTemperatureColor(a.target, store.acCfg.get(ui.sheet.id));
+ return new THREE.Color(MODE_COLORS[a.mode]).multiplyScalar(0.38);
+ }
+ const sum = new THREE.Color(0, 0, 0);
+ let weight = 0;
+ for (const cfg of config.lights) {
+ const s = state.lights[cfg.id];
+ if (!s.on) continue;
+ const w = cfg.capabilities.includes('brightness') ? s.brightness : 1;
+ lightColor(s, tmp);
+ sum.r += tmp.r * w; sum.g += tmp.g * w; sum.b += tmp.b * w;
+ weight += w;
+ }
+ if (!weight) return NAVY.clone();
+ sum.multiplyScalar(0.42 / weight);
+ return NAVY.clone().lerp(sum, clamp(weight / 3.5, 0.25, 0.8));
+ }
+
+ function update() {
+ const lights = Object.values(state.lights);
+ const onCount = lights.filter((l) => l.on).length;
+ const acsOn = Object.values(state.acs).filter((a) => a.on);
+ const anyOn = onCount > 0 || acsOn.length > 0;
+
+ homeSub.replaceChildren(
+ h('span.live', { style: anyOn ? {} : { background: 'rgba(255,255,255,.25)', boxShadow: 'none' } }),
+ h('b', onCount ? `${onCount} of ${lights.length}` : 'No'), ' lights on',
+ acsOn.length ? ` · AC ${acsOn[0].target}°` : '');
+ power.classList.toggle('on', anyOn);
+
+ for (const [id, b] of sceneButtons) b.classList.toggle('active', state.scene === id);
+
+ for (const [id, { b, count }] of roomButtons) {
+ b.classList.toggle('active', ui.room === id);
+ const n = config.lights.filter((l) => (id === 'all' || l.room === id) && state.lights[l.id].on).length;
+ count.textContent = n;
+ count.classList.toggle('zero', n === 0 || id === 'all');
+ }
+
+ const scoped = config.lights.filter(inScope);
+ const scopedOn = scoped.filter((l) => state.lights[l.id].on).length;
+ listTitle.replaceChildren(h('b', ui.room === 'all' ? 'Whole home' : roomName.get(ui.room)), ` · ${scopedOn} of ${scoped.length} on`);
+
+ for (const t of tiles.values()) t.update();
+ sheetView?.update();
+ const m = css(mood());
+ card.style.setProperty('--mood', m);
+ }
+
+ store.on(() => update());
+ window.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Escape' && !closeSheet()) onMenu(null, 'escape');
+ });
+
+ layoutTiles();
+ update();
+
+ return {
+ canvas,
+ card,
+ attach(w) { world = w; card.classList.remove('booting'); },
+ showTooltip,
+ openSheet,
+ closeSheet,
+ selectRoom,
+ toggleLight,
+ get room() { return ui.room; },
+ setNotch(x) { card.style.setProperty('--notch-x', `${x}px`); },
+ toast(text) {
+ toastEl.textContent = text;
+ toastEl.classList.add('show');
+ clearTimeout(toastEl.timer);
+ toastEl.timer = setTimeout(() => toastEl.classList.remove('show'), 3200);
+ },
+ anchorMenu: clip,
+ };
+}
diff --git a/web/vite.config.js b/web/vite.config.js
new file mode 100644
index 0000000..85f6d5a
--- /dev/null
+++ b/web/vite.config.js
@@ -0,0 +1,13 @@
+import { defineConfig } from 'vite';
+
+export default defineConfig({
+ base: './',
+ // 5199 by default; PORT overrides it when that one is taken.
+ server: { port: Number(process.env.PORT) || 5199, strictPort: true },
+ build: {
+ target: 'safari17',
+ outDir: 'dist',
+ emptyOutDir: true,
+ chunkSizeWarningLimit: 1500,
+ },
+});