Skip to content

Self-hosted house planner: true-scale 2D floor plan, 3D, satellite map overlay, sewer, electrical, water and underfloor heating with calculations, priced bill of materials. React + PHP, no database. By the team behind homedesignsai.pro

Initial public release

egmalt200bfd006342
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..7482a5c
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,22 @@
+.git
+.gitignore
+.env
+.env.*
+.vscode
+.idea
+.DS_Store
+node_modules
+dist
+dist-ssr
+storage
+plans
+docs
+scripts
+storage.example
+Dockerfile
+docker-compose.yml
+.dockerignore
+public/data/.htaccess
+public/plans/.htaccess
+public/storage
+*.log
diff --git a/.env.deploy.example b/.env.deploy.example
new file mode 100644
index 0000000..9996109
--- /dev/null
+++ b/.env.deploy.example
@@ -0,0 +1,30 @@
+# Скопируйте в .env.deploy (он в .gitignore) и заполните.
+
+# Адрес сайта: печатается после заливки и нужен plan-pull.sh / plan-push.sh.
+DEPLOY_URL=https://plan.example.com
+
+# Способ заливки: ssh (rsync по SSH) или ftp (lftp mirror).
+DEPLOY_METHOD=ssh
+
+# SSH: user@host или алиас из ~/.ssh/config; путь к корню сайта на сервере.
+DEPLOY_PATH=www/plan.example.com
+# Доп. опции ssh, например порт или ключ:
+# DEPLOY_SSH_OPTS="-p 2222 -i ~/.ssh/id_ed25519"
+
+# FTP (если DEPLOY_METHOD=ftp):
+# FTP_HOST=ftp.example.com
+# FTP_USER=
+# FTP_PASSWORD=
+# FTP_PATH=www/plan.example.com
+# FTP_SSL_VERIFY=yes
+
+# Пароль планировщика для plan-pull.sh / plan-push.sh (тот, что задан в api/setup.php).
+# HOUSE_URL по умолчанию равен DEPLOY_URL.
+# HOUSE_PASSWORD=
+
+# Пример: Beget (виртуальный хостинг с Apache и SSH).
+# DEPLOY_SSH=<логин>@<логин>.beget.tech
+# DEPLOY_PATH=<домен>/public_html
+# Хранилище мастер установки создаст в <домен>/storage — вне корня сайта.
+# По FTP: FTP_HOST=<логин>.beget.tech, FTP_PATH=<домен>/public_html, пользователь FTP из панели.
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..f17950d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,68 @@
+name: Bug report
+description: Something does not work as expected
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for the report. English or Russian is fine. Do not post passwords, cookie tokens, real addresses or cadastral numbers. Security problems go to a private report, see SECURITY.md.
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened
+ description: What you did, what you expected and what you got instead.
+ validations:
+ required: true
+ - type: textarea
+ id: steps
+ attributes:
+ label: Steps to reproduce
+ placeholder: |
+ 1. Open «План»
+ 2. Draw a wall …
+ 3. …
+ validations:
+ required: true
+ - type: dropdown
+ id: area
+ attributes:
+ label: Area
+ options:
+ - 2D plan editor
+ - 3D
+ - Map
+ - Estimate / catalog / Petrovich cart
+ - Networks (sewer, electrical, water, underfloor heating)
+ - Versions, login, saving
+ - Setup / deploy / Docker
+ - Scripts (plan-pull, plan-push, plan-validate)
+ - Other
+ validations:
+ required: true
+ - type: dropdown
+ id: install
+ attributes:
+ label: How is it running
+ options:
+ - Docker
+ - Shared hosting (Apache / LiteSpeed)
+ - nginx
+ - Local php -S
+ - Other
+ - type: input
+ id: versions
+ attributes:
+ label: Versions
+ description: House Planner version or commit, PHP version, browser and OS.
+ placeholder: 0.1.0, PHP 8.3, Chrome 140 on macOS
+ - type: textarea
+ id: plan
+ attributes:
+ label: Plan fragment or screenshot
+ description: A minimal JSON fragment that reproduces the problem, a screenshot, or the browser console error. Remove personal data.
+ - type: textarea
+ id: logs
+ attributes:
+ label: Server response or logs
+ description: HTTP status and error code from the API, or `docker compose logs` output.
+ render: text
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000..cb15d72
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,8 @@
+blank_issues_enabled: false
+contact_links:
+ - name: Security vulnerability
+ url: https://github.com/egmalt/house-planner/security/advisories/new
+ about: Report security problems privately, not in public issues.
+ - name: FAQ
+ url: https://github.com/egmalt/house-planner/blob/main/docs/guide/en/faq.md
+ about: Hosting, passwords, backups, your own plot, the catalog, offline use.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..85926d8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,37 @@
+name: Feature request
+description: Suggest an improvement or a new capability
+labels: [enhancement]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ English or Russian is fine. Check the roadmap in README and existing issues first.
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What are you trying to do, and what gets in the way today?
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposal
+ description: "How it could work: UI, plan format fields, calculation."
+ validations:
+ required: true
+ - type: textarea
+ id: references
+ attributes:
+ label: Norms and references
+ description: For calculations and checks, the norm (СП, ПУЭ, ГОСТ, СанПиН) and clause, a manufacturer's datasheet or another source.
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
+ - type: checkboxes
+ id: help
+ attributes:
+ label: Contribution
+ options:
+ - label: I would like to implement this myself
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..60e8f61
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,17 @@
+## What and why
+
+<!-- What this pull request changes and the reason. Link the issue: Closes #123 -->
+
+## How it was checked
+
+<!-- Browser steps, plan used, screenshots for visible changes (desktop and, if UI changed, phone width under 700 px). -->
+
+## Checklist
+
+- [ ] `npx tsc -b`, `npm run build`, `npm run plan:validate` and `npm run lint` pass
+- [ ] Plan format changes are backward compatible and described in `docs/plan-format.md`; `CLIENT_VERSION` and `MIN_CLIENT_VERSION` raised together if old clients could lose data
+- [ ] API changes are described in `docs/api.md`
+- [ ] UI uses primitives from `src/ui/` and tokens from `src/styles/tokens.css`; no comments in CSS
+- [ ] Norm-based checks name the document and clause
+- [ ] No personal data: addresses, cadastral numbers, names, private domains, passwords
+- [ ] `CHANGELOG.md` updated under "Unreleased" for user-visible changes
diff --git a/.github/repo-meta.json b/.github/repo-meta.json
new file mode 100644
index 0000000..48946e0
--- /dev/null
+++ b/.github/repo-meta.json
@@ -0,0 +1,26 @@
+{
+ "description": "Self-hosted house planner: true-scale 2D floor plan, 3D, satellite map overlay, sewer, electrical, water and underfloor heating with calculations, priced bill of materials. React + PHP, no database. By the team behind homedesignsai.pro",
+ "homepage": "https://homedesignsai.pro",
+ "topics": [
+ "house-planner",
+ "floor-plan",
+ "floorplan-editor",
+ "home-design",
+ "architecture",
+ "3d",
+ "react",
+ "typescript",
+ "threejs",
+ "react-three-fiber",
+ "konva",
+ "maplibre",
+ "php",
+ "self-hosted",
+ "bill-of-materials",
+ "construction",
+ "electrical-design",
+ "underfloor-heating",
+ "plumbing",
+ "cad"
+ ]
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..449583e
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,32 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+
+ - name: Install
+ run: npm ci
+
+ - name: Type check
+ run: npx tsc -b
+
+ - name: Build
+ run: npm run build
+
+ - name: Validate demo plan
+ run: npm run plan:validate
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
new file mode 100644
index 0000000..506ef90
--- /dev/null
+++ b/.github/workflows/docker.yml
@@ -0,0 +1,81 @@
+name: docker
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ image:
+ runs-on: ubuntu-latest
+ env:
+ HOUSE_PASSWORD: ci-password-123
+ HOUSE_PORT: 8080
+ BASE: http://127.0.0.1:8080
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Build image
+ run: docker compose build
+
+ - name: Start
+ run: docker compose up -d
+
+ - name: Wait for the server
+ run: |
+ for i in $(seq 1 60); do
+ code=$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/plan.php" || true)
+ [ "$code" = 401 ] && exit 0
+ sleep 1
+ done
+ echo "server is not ready, last code: $code"
+ exit 1
+
+ - name: Check responses
+ run: |
+ set -u
+ fail=0
+ expect() {
+ local want="$1" desc="$2"; shift 2
+ local got
+ got=$(curl -s -o /tmp/body -w '%{http_code}' "$@" || true)
+ if [ "$got" = "$want" ]; then
+ echo "ok $want $desc"
+ else
+ echo "FAIL $desc: expected $want, got $got"
+ head -c 500 /tmp/body; echo
+ fail=1
+ fi
+ }
+ expect 200 "GET / (app)" "$BASE/"
+ expect 401 "GET /api/plan.php without cookie" "$BASE/api/plan.php"
+ expect 200 "POST /api/login.php" -c /tmp/jar -X POST \
+ -H 'Content-Type: application/json' -H 'X-Requested-With: XMLHttpRequest' \
+ --data "{\"password\":\"$HOUSE_PASSWORD\"}" "$BASE/api/login.php"
+ if grep -q hauth /tmp/jar; then echo "ok login cookie set"; else echo "FAIL login cookie not set"; fail=1; fi
+ expect 200 "GET /api/plan.php with cookie" -b /tmp/jar "$BASE/api/plan.php"
+ expect 401 "GET /data/house.json without cookie" "$BASE/data/house.json"
+ expect 403 "GET /api/_lib.php" "$BASE/api/_lib.php"
+ exit $fail
+
+ - name: Restart and check the plan survives
+ run: |
+ docker compose restart
+ for i in $(seq 1 60); do
+ code=$(curl -s -o /dev/null -w '%{http_code}' -b /tmp/jar "$BASE/api/plan.php" || true)
+ [ "$code" = 200 ] && { echo "ok 200 GET /api/plan.php with cookie after restart"; exit 0; }
+ sleep 1
+ done
+ echo "FAIL after restart: expected 200, got $code"
+ exit 1
+
+ - name: Container logs
+ if: failure()
+ run: docker compose logs
+
+ - name: Stop
+ if: always()
+ run: docker compose down -v
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..28188c4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,31 @@
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
+
+.vscode/*
+!.vscode/extensions.json
+.idea
+.DS_Store
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
+
+.env
+.env.*
+!.env.deploy.example
+/plans/
+/storage/
+/public/storage/
+**/storage/config.php
+public/data/.htaccess
+public/plans/.htaccess
diff --git a/.oxlintrc.json b/.oxlintrc.json
new file mode 100644
index 0000000..6fa991d
--- /dev/null
+++ b/.oxlintrc.json
@@ -0,0 +1,8 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "plugins": ["react", "typescript", "oxc"],
+ "rules": {
+ "react/rules-of-hooks": "error",
+ "react/only-export-components": ["warn", { "allowConstantExport": true }]
+ }
+}
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..41c2210
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,28 @@
+# Changelog
+
+All notable changes to this project are documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+## [0.1.0] - 2026-10-01
+
+Initial public release.
+
+### Added
+
+- 2D plan editor in real millimetres: walls with materials, doors, windows, garage gates, furniture catalog, site zones, room labels with net area, snapping, ruler, undo/redo, view rotation and "north up", whole-building selection.
+- 3D view with *Model* and *Materials* looks, RAL wall and accent colours, low-wall modes, iso/top/front cameras.
+- Satellite map overlay with geo-referencing, site boundary from GeoJSON, neighbouring parcels, imagery alignment, optional server-locked site data.
+- Utility networks as layers with editors, calculations and estimate groups: sewer with septic tank, electrical with circuits and checks (ПУЭ, ГОСТ Р 50571), home-run water supply, hydronic underfloor heating with automatic loop layout.
+- Estimate on an A4 sheet with "bought" marks, CSV export and petrovich.ru cart links.
+- Area summary: total and living area, rooms, footprint, plot coverage.
+- Server storage in PHP without a database: revisions with optimistic concurrency, named snapshots, single-password login, data files closed by cookie, setup wizard.
+- Read-only mode on phones and touch-only devices.
+- Scripts: `deploy.sh` (SSH or FTP with verification), `plan-pull.sh` / `plan-push.sh`, `plan-validate.mts`.
+- Docker image with Apache and PHP, data in a named volume.
+- Documentation: plan format, HTTP API, user guides in English and Russian.
+
+[Unreleased]: https://github.com/egmalt/house-planner/compare/v0.1.0...HEAD
+[0.1.0]: https://github.com/egmalt/house-planner/releases/tag/v0.1.0
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..43175d4
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,136 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+We as members, contributors, and leaders pledge to make participation in our
+community a harassment-free experience for everyone, regardless of age, body
+size, visible or invisible disability, ethnicity, sex characteristics, gender
+identity and expression, level of experience, education, socio-economic status,
+nationality, personal appearance, race, caste, color, religion, or sexual
+identity and orientation.
+
+We pledge to act and interact in ways that contribute to an open, welcoming,
+diverse, inclusive, and healthy community.
+
+## Our Standards
+
+Examples of behavior that contributes to a positive environment for our
+community include:
+
+* Demonstrating empathy and kindness toward other people
+* Being respectful of differing opinions, viewpoints, and experiences
+* Giving and gracefully accepting constructive feedback
+* Accepting responsibility and apologizing to those affected by our mistakes,
+ and learning from the experience
+* Focusing on what is best not just for us as individuals, but for the overall
+ community
+
+Examples of unacceptable behavior include:
+
+* The use of sexualized language or imagery, and sexual attention or advances of
+ any kind
+* Trolling, insulting or derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or email address,
+ without their explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Enforcement Responsibilities
+
+Community leaders are responsible for clarifying and enforcing our standards of
+acceptable behavior and will take appropriate and fair corrective action in
+response to any behavior that they deem inappropriate, threatening, offensive,
+or harmful.
+
+Community leaders have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are
+not aligned to this Code of Conduct, and will communicate reasons for moderation
+decisions when appropriate.
+
+## Scope
+
+This Code of Conduct applies within all community spaces, and also applies when
+an individual is officially representing the community in public spaces.
+Examples of representing our community include using an official e-mail address,
+posting via an official social media account, or acting as an appointed
+representative at an online or offline event.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported to the community leaders responsible for enforcement at
+[[email protected]](mailto:[email protected]), or privately through
+a [private vulnerability report](https://github.com/egmalt/house-planner/security/advisories/new)
+on this repository (it reaches only the maintainers; mark the report as a code
+of conduct issue in its title), or by GitHub's
+[report abuse](https://docs.github.com/en/communities/maintaining-your-safety-on-github/reporting-abuse-or-spam)
+feature. All complaints will be reviewed and investigated promptly and fairly.
+
+All community leaders are obligated to respect the privacy and security of the
+reporter of any incident.
+
+## Enforcement Guidelines
+
+Community leaders will follow these Community Impact Guidelines in determining
+the consequences for any action they deem in violation of this Code of Conduct:
+
+### 1. Correction
+
+**Community Impact**: Use of inappropriate language or other behavior deemed
+unprofessional or unwelcome in the community.
+
+**Consequence**: A private, written warning from community leaders, providing
+clarity around the nature of the violation and an explanation of why the
+behavior was inappropriate. A public apology may be requested.
+
+### 2. Warning
+
+**Community Impact**: A violation through a single incident or series of
+actions.
+
+**Consequence**: A warning with consequences for continued behavior. No
+interaction with the people involved, including unsolicited interaction with
+those enforcing the Code of Conduct, for a specified period of time. This
+includes avoiding interactions in community spaces as well as external channels
+like social media. Violating these terms may lead to a temporary or permanent
+ban.
+
+### 3. Temporary Ban
+
+**Community Impact**: A serious violation of community standards, including
+sustained inappropriate behavior.
+
+**Consequence**: A temporary ban from any sort of interaction or public
+communication with the community for a specified period of time. No public or
+private interaction with the people involved, including unsolicited interaction
+with those enforcing the Code of Conduct, is allowed during this period.
+Violating these terms may lead to a permanent ban.
+
+### 4. Permanent Ban
+
+**Community Impact**: Demonstrating a pattern of violation of community
+standards, including sustained inappropriate behavior, harassment of an
+individual, or aggression toward or disparagement of classes of individuals.
+
+**Consequence**: A permanent ban from any sort of public interaction within the
+community.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
+version 2.1, available at
+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
+
+Community Impact Guidelines were inspired by
+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
+
+For answers to common questions about this code of conduct, see the FAQ at
+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
+[https://www.contributor-covenant.org/translations][translations].
+
+[homepage]: https://www.contributor-covenant.org
+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
+[Mozilla CoC]: https://github.com/mozilla/diversity
+[FAQ]: https://www.contributor-covenant.org/faq
+[translations]: https://www.contributor-covenant.org/translations
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8a98395
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,95 @@
+# Contributing
+
+Thanks for your interest in House Planner. Bug reports, fixes, new calculations, catalog improvements and translations are all welcome. Issues and pull requests can be written in English or Russian.
+
+By participating you agree to follow the [Code of Conduct](CODE_OF_CONDUCT.md). Report security problems privately, as described in [SECURITY.md](SECURITY.md).
+
+## Development setup
+
+You need Node.js 22, PHP 8.1+ and, for the plan scripts, `bash`, `curl` and `python3`.
+
+```bash
+git clone https://github.com/egmalt/house-planner.git
+cd house-planner
+npm ci
+```
+
+Run the PHP API and Vite in two terminals:
+
+```bash
+npm run dev:api # terminal 1: php -S 127.0.0.1:8000 -t public scripts/dev-router.php
+npm run dev # terminal 2: Vite on http://localhost:5173
+```
+
+Open <http://localhost:5173/api/setup.php> once, keep the first storage option and set any password, then work at <http://localhost:5173/>. Vite proxies `/api`, `/data` and `/plans` to the PHP server, so PHP files in `public/api/` are used as is, without a build, and frontend changes reload instantly.
+
+Notes:
+
+- The storage is `$HOUSE_STORAGE` if set, otherwise `./storage` in the repository root (git-ignored). For a throwaway setup: `HOUSE_STORAGE=/tmp/house-dev npm run dev:api`.
+- `scripts/dev-router.php` makes the PHP built-in server behave like Apache with the project's `.htaccess`: `api/_*.php`, `storage/` and dotfiles return `403`, `data/` and `plans/` need the login cookie.
+- The setup wizard writes `public/data/.htaccess` and `public/plans/.htaccess`. They are git-ignored, skipped by `scripts/deploy.sh` and removed in the Docker build.
+- To check the production build, use Docker (`docker compose up -d --build`, see the [install guide](docs/guide/en/install.md#docker)) or `npm run build && php -S 127.0.0.1:8000 -t dist`.
+
+## Project layout
+
+| Path | What |
+|---|---|
+| `src/model/` | plan schema (zod), geometry, editing operations, wall estimate |
+| `src/canvas/` | 2D editor on Konva: walls, openings, zones, snapping, ruler, selection |
+| `src/view3d/` | 3D scene on React Three Fiber, looks, RAL palette |
+| `src/map/` | satellite map on MapLibre, geo-referencing, imagery alignment |
+| `src/networks/` | sewer, water, electrical (`electric/`) and underfloor heating (`heating/`): editors, calculations, pricing |
+| `src/estimate/` | estimate sheet, catalog matching, CSV, Petrovich cart |
+| `src/stats/` | room detection and area summary |
+| `src/furniture/` | furniture catalog, 2D symbols, 3D models ([README](src/furniture/README.md)) |
+| `src/storage/`, `src/store/` | server sync, versions, Zustand store with undo |
+| `src/ui/`, `src/styles/` | shared primitives and design tokens ([docs/ui.md](docs/ui.md)) |
+| `public/api/` | PHP API: plan storage, login, setup, Petrovich cart ([docs/api.md](docs/api.md)) |
+| `public/data/` | price catalog and the «Участок и дом» page data |
+| `public/plans/demo.json` | demo plan that seeds an empty storage |
+| `scripts/` | deploy, plan pull/push, plan validation |
+| `docker/`, `Dockerfile`, `docker-compose.yml` | container image |
+
+## Before opening a pull request
+
+Run the same checks as CI:
+
+```bash
+npx tsc -b
+npm run build
+npm run plan:validate
+npm run lint
+```
+
+Then check the change in the browser: the plan section, 3D and the estimate at least, and the phone width (under 700 px) if you touched the UI.
+
+## Guidelines
+
+**Keep it focused.** One topic per pull request. Describe what changed and why, and attach a screenshot for visible changes.
+
+**Use what is already installed.** If React, three.js, drei, Konva, MapLibre, zod or Zustand already solve the problem, use them instead of writing your own. New dependencies need a reason in the PR description.
+
+**UI.** Build from the primitives in `src/ui/` and the tokens in `src/styles/tokens.css` ([docs/ui.md](docs/ui.md)), not new colours, shadows or buttons. CSS files contain no comments. Interface strings go through i18next: add every new string to both `src/i18n/locales/en/` and `src/i18n/locales/ru/`, never inline in components.
+
+**Plan format.** `src/model/schema.ts` is the source of truth. When you add or change fields:
+
+- keep old plans valid (new fields optional, unknown fields preserved);
+- update [docs/plan-format.md](docs/plan-format.md);
+- if older clients could lose the new data when saving, raise `CLIENT_VERSION` in `src/model/schema.ts` and `MIN_CLIENT_VERSION` in `public/api/_lib.php` together;
+- make sure `npm run plan:validate` still passes.
+
+**API.** Any change to `public/api/` goes together with [docs/api.md](docs/api.md): methods, headers, status codes and error codes. The API must keep working on plain shared hosting: PHP 8.1+, no Composer, no database, no extensions beyond `json` and `curl`.
+
+**Calculations and norms.** When a check is based on a norm (СП, ПУЭ, ГОСТ, СанПиН), name the document and clause in the warning or in the PR. Calculations are reference only, so keep the wording neutral.
+
+**Catalog.** Each item in `public/data/catalog.json` needs `name`, `kind`, `price`, `unit`, a source (`vendor`, `url`) and `checkedAt`. Do not add affiliate links.
+
+**No personal data.** No real addresses, cadastral numbers, names, phone numbers or private domains in code, demo data, screenshots or tests. Use the fictional demo plot for examples.
+
+## Commit messages
+
+Short imperative subject in English or Russian, details in the body if needed. Reference issues as `#123`.
+
+## License
+
+By contributing you agree that your contributions are licensed under the [MIT License](LICENSE).
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..b22f045
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,31 @@
+FROM node:22-alpine AS build
+WORKDIR /app
+COPY package.json package-lock.json ./
+RUN npm ci --no-audit --no-fund
+COPY index.html vite.config.ts tsconfig.json tsconfig.app.json tsconfig.node.json ./
+COPY public ./public
+COPY src ./src
+RUN npm run build \
+ && rm -f dist/data/.htaccess dist/plans/.htaccess
+
+FROM php:8.3-apache
+ENV HOUSE_STORAGE=/var/lib/house-planner
+RUN a2enmod rewrite headers \
+ && a2dismod -f autoindex status \
+ && mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
+COPY docker/apache/ports.conf /etc/apache2/ports.conf
+COPY docker/apache/site.conf /etc/apache2/sites-available/000-default.conf
+COPY docker/php/house-planner.ini $PHP_INI_DIR/conf.d/zz-house-planner.ini
+COPY docker/house-boot.php /usr/local/lib/house-planner/boot.php
+COPY docker/healthcheck.php /usr/local/lib/house-planner/healthcheck.php
+COPY docker/entrypoint.sh /usr/local/bin/house-entrypoint
+COPY --from=build /app/dist/ /var/www/html/
+RUN mkdir -p "$HOUSE_STORAGE" \
+ && chown root:root /var/www/html && chmod 755 /var/www/html \
+ && chown -R www-data:www-data "$HOUSE_STORAGE" /var/www/html/data /var/www/html/plans
+VOLUME /var/lib/house-planner
+EXPOSE 8080
+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
+ CMD ["php", "/usr/local/lib/house-planner/healthcheck.php"]
+ENTRYPOINT ["house-entrypoint"]
+CMD ["apache2-foreground"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..359fa8c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 egmalt
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c3ac0c7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,153 @@
+# House Planner
+
+A self-hosted planner for a private house: true-scale 2D floor plan, 3D preview, satellite overlay, utility networks and a priced bill of materials, all stored on your own PHP hosting.
+
+Made by the team behind [homedesignsai.pro](https://homedesignsai.pro) — an AI that helps you design your home.
+
+[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
+[![Build](https://img.shields.io/github/actions/workflow/status/egmalt/house-planner/ci.yml?branch=main&label=build)](https://github.com/egmalt/house-planner/actions/workflows/ci.yml)
+[![Node 22](https://img.shields.io/badge/node-22-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
+[![React 19](https://img.shields.io/badge/React-19-61DAFB?logo=react&logoColor=black)](https://react.dev/)
+[![TypeScript](https://img.shields.io/badge/TypeScript-6-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
+[![PHP 8.x](https://img.shields.io/badge/PHP-8.x-777BB4?logo=php&logoColor=white)](https://www.php.net/)
+[![Self-hosted](https://img.shields.io/badge/self--hosted-yes-blueviolet)](docs/guide/en/install.md)
+[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
+[![Live demo](https://img.shields.io/badge/live%20demo-app.homedesignsai.pro-f26b1d)](https://app.homedesignsai.pro)
+
+**English** | [Русский](README.ru.md)
+
+![House Planner: 3D view of the demo house in the Materials look](docs/screenshots/hero.png)
+
+<table>
+<tr><td align="center"><img src="docs/screenshots/plan.png" width="300" alt="2D plan editor"><br><sub>2D plan editor</sub></td><td align="center"><img src="docs/screenshots/3d.png" width="300" alt="3D with low walls"><br><sub>3D with low walls</sub></td><td align="center" rowspan="2"><img src="docs/screenshots/mobile.png" width="150" alt="Read-only phone view"><br><sub>Read-only phone view</sub></td></tr>
+<tr><td align="center"><img src="docs/screenshots/map.png" width="300" alt="Plan on the satellite map"><br><sub>Plan on the satellite map</sub></td><td align="center"><img src="docs/screenshots/estimate.png" width="300" alt="Estimate on an A4 sheet"><br><sub>Estimate on an A4 sheet</sub></td></tr>
+<tr><td align="center"><img src="docs/screenshots/networks.png" width="300" alt="Electrical layer with circuits"><br><sub>Electrical layer with circuits</sub></td><td align="center"><img src="docs/screenshots/heating.png" width="300" alt="Underfloor heating loops"><br><sub>Underfloor heating loops</sub></td><td align="center"><img src="docs/screenshots/versions.png" width="300" alt="Versions and snapshots"><br><sub>Versions and snapshots</sub></td></tr>
+</table>
+
+**[Live demo](https://app.homedesignsai.pro)**: a shared copy without login that resets every hour, see [demo mode](docs/guide/en/demo.md). The interface is available in English and Russian.
+
+## Features
+
+**2D plan editor**
+- Real-scale drawing in millimetres: walls with thickness and material, doors, windows, garage gates, furniture from a catalog with real dimensions, site zones (gravel fill, lawn, paving).
+- Snapping to wall ends and a 100 mm grid, dimension lines, a measuring tool (`M`, chained segments), undo/redo.
+- View rotation in 15° steps and "north up", building selection (`B`) to move or rotate the whole house, room labels with net area detected from the walls.
+- Area summary: total and living area, rooms, bedrooms, bathrooms, building footprint, plot coverage.
+
+**3D**
+- Two looks: *Model* (clean massing) and *Materials* (textures by wall material and facade finish).
+- Wall and accent colours from the RAL palette, low-wall modes (1 m and floor level) to see the layout from above, iso/top/front cameras.
+
+**Site and map**
+- Plan overlaid on satellite imagery with geo-referencing (`lat/lng` of the plan origin plus rotation).
+- Site boundary from GeoJSON (for example, a cadastral parcel), neighbouring parcels from `data/parcel.geojson`, manual imagery alignment.
+- Optional server-side locked site data: the legal boundary cannot be moved from the editor.
+
+**Utility networks** (each one is a layer with its own editor, calculation and estimate group)
+- **Sewer** with a septic tank: routing from fixtures, risers, cleanouts, outlets; slopes, invert levels, fittings, clearance checks.
+- **Electrical**: sockets, switches, lights, panel and circuits; auto-routing along walls, cable lengths, breakers and RCDs, load and voltage-drop checks, wet-zone rules (ПУЭ, ГОСТ Р 50571).
+- **Water supply**: well or borehole, pump, filter, boiler, cold/hot manifolds, home-run piping to fixtures, insulation and heating cable outside.
+- **Hydronic underfloor heating**: automatic loop layout per room, edge zones, loop splitting at 80 m, heat output vs. heat loss, flow rates and balancing, manifold placement.
+
+**Bill of materials**
+- Quantities are computed from the plan and networks, prices come from a JSON catalog, an A4 print layout.
+- "Bought" checkboxes with actual price and date, CSV export (Excel-friendly), one-click cart on petrovich.ru (a Russian DIY retailer).
+
+**Storage and access**
+- The plan lives on the server as JSON; every save is a numbered version, plus named snapshots you can restore.
+- Optimistic concurrency (`If-Match` / `409`), so several tabs and scripts can edit safely.
+- Single-password login, data files closed by an auth cookie, phones get a read-only view.
+
+## Quick start
+
+### Docker
+
+```bash
+git clone https://github.com/egmalt/house-planner.git
+cd house-planner
+docker compose up -d --build
+```
+
+Open <http://localhost:8080/> and set a password in the wizard at `/api/setup.php`. To skip the wizard, pass the password on first start: `HOUSE_PASSWORD='long-password' docker compose up -d --build`. The port is set by `HOUSE_PORT` (default `8080`). The plan, all versions and the config live in the `house-data` volume and survive rebuilds and restarts. `HOUSE_PASSWORD` is applied only to an empty storage; to change the password later, remove `config.php` from the volume (`docker compose exec house-planner rm /var/lib/house-planner/config.php`) and start again with a new `HOUSE_PASSWORD` or the wizard. Backups and HTTPS behind a reverse proxy: [installation guide](docs/guide/en/install.md#docker).
+
+### Development mode
+
+Requires Node.js 22 and PHP 8.1+. Two terminals:
+
+```bash
+npm i
+npm run dev:api # terminal 1: PHP API on 127.0.0.1:8000, straight from public/
+```
+
+```bash
+npm run dev # terminal 2: Vite on http://localhost:5173 with hot reload
+```
+
+Open <http://localhost:5173/api/setup.php>, set a password, then work at <http://localhost:5173/>. Vite proxies `/api`, `/data` and `/plans` to the PHP server; no build is needed. The storage is `$HOUSE_STORAGE` if set, otherwise `./storage` in the repository root (git-ignored). `scripts/dev-router.php` repeats the `.htaccess` rules for the PHP built-in server; it is for your own machine only.
+
+More details: [installation guide](docs/guide/en/install.md).
+
+## Self-hosting
+
+Any shared hosting with **PHP 8.1+** (with the `curl` extension for the Petrovich cart) and **Apache or LiteSpeed** with `mod_rewrite` works. No database, no Node.js on the server.
+
+1. **Build** locally: `npm ci && npm run build`. The result is the static `dist/` folder with the PHP API in `dist/api/`.
+2. **Upload** the contents of `dist/` to the site root: via `scripts/deploy.sh` (rsync over SSH or FTP mirror, settings in `.env.deploy`, see [`.env.deploy.example`](.env.deploy.example)) or any FTP client.
+3. **Run the wizard**: open `https://your-site/api/setup.php` once. It picks a storage location, asks for a password (8+ characters), writes `storage/config.php` with the password hash and a random cookie token, and closes `data/` and `plans/` behind that cookie. After that the wizard returns `403`. Set the `HOUSE_SETUP_KEY` environment variable if you want the wizard to require an extra key.
+4. **Storage** is looked up in this order: `$HOUSE_STORAGE`, `<site root>/../storage` (outside the web root, preferred), `<site root>/storage` (inside, denied by `.htaccess`). It holds `config.php`, `current.json`, every version in `versions/`, and snapshots in `snapshots/`.
+5. **HTTPS**: enable it on the hosting (Let's Encrypt is usually one click). The login cookie is `HttpOnly`, `SameSite=Lax` and gets `Secure` automatically on HTTPS.
+
+On nginx without Apache, `.htaccess` is ignored: deny `/storage`, `/data` and `/plans` in the server config yourself. Step-by-step instructions, updates and backups: [deployment guide](docs/guide/en/deploy.md).
+
+## Plan format
+
+A plan is one JSON document in integer millimetres: `site` (size, boundary, geo-reference, zones), `materials`, `walls` (axis line `a → b`, thickness, height, material), `openings` (doors, windows, gates by offset along a wall), `furniture`, `rooms`, `estimate` and `networks` (`sewer`, `electric`, `water`, `heating`). The zod schema in [`src/model/schema.ts`](src/model/schema.ts) is the source of truth; `npm run plan:validate` checks the demo plan with it.
+
+Full description (in Russian): [docs/plan-format.md](docs/plan-format.md). HTTP API: [docs/api.md](docs/api.md).
+
+## Working with an AI assistant
+
+Because the plan is plain JSON with a strict schema, any LLM assistant can edit it: "add a 5 m wall from the house corner to the east", "put a 1200 mm window in the middle of wall w2", "route the bathroom sink to the riser". The loop is:
+
+```bash
+scripts/plan-pull.sh # server → plans/server.json
+# edit plans/server.json by hand or with an assistant
+node scripts/plan-validate.mts plans/server.json
+scripts/plan-push.sh # → new version on the server
+```
+
+`plan-push.sh` uses the same versioned API as the browser: if the plan changed meanwhile, it saves the server copy as `*.conflict.json` and exits with code `2` instead of overwriting. Open tabs pick up the new version automatically. Guide with prompts and pitfalls: [editing the plan via JSON](docs/guide/en/plan-via-chat.md).
+
+## Tech stack
+
+React 19, TypeScript, Vite, Zustand + zundo (undo), zod, Konva / react-konva (2D), three.js with React Three Fiber, drei and postprocessing (3D), three-bvh-csg (openings), clipper2 (polygon offsets), MapLibre GL and proj4 (map), plain PHP for the API with file storage and `flock`.
+
+## Roadmap
+
+- Roof: shapes, slopes, rafters and roofing materials in 3D and in the estimate.
+- Foundation: slab, strip and pile foundations with volumes and rebar.
+- Water supply hydraulics: pressure and head calculation, pump selection.
+- Export to PDF and DXF.
+- More interface languages: English and Russian today, translations are welcome.
+
+## Disclaimers
+
+- **Prices** in `public/data/catalog.json` are an example collected from stores in Saint Petersburg, Russia, on the date in each item's `checkedAt`. They are not an offer and will go stale; replace them with your own.
+- **Building codes** (СП, ПУЭ, СанПиН, ГОСТ) are used as reference checks only. The calculations do not replace a design by a licensed engineer.
+- The demo plan is a fictional Nordic single-storey house with a garage on a 30 × 45 m plot in Estonia.
+
+## FAQ
+
+Hosting, passwords, backups, updates, your own plot, the catalog, mobile, offline use: see the [FAQ](docs/guide/en/faq.md). Day-to-day editor usage: [usage guide](docs/guide/en/usage.md).
+
+## Contributing
+
+Issues and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first; by participating you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). Security issues: [SECURITY.md](SECURITY.md). Changes: [CHANGELOG.md](CHANGELOG.md).
+
+## Credits
+
+House Planner is built and maintained by the team behind [homedesignsai.pro](https://homedesignsai.pro). Contact: [[email protected]](mailto:[email protected]).
+
+## License
+
+[MIT](LICENSE). Third-party textures and furniture models keep their own licenses, see `public/textures/LICENSE.txt` and `public/models/furniture/LICENSES.md`.
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000..b4f057d
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,153 @@
+# House Planner
+
+Планировщик частного дома на своём хостинге: 2D-план в реальном масштабе, 3D, план на спутниковой карте, инженерные сети и смета с ценами — всё хранится на вашем PHP-хостинге.
+
+От команды [homedesignsai.pro](https://homedesignsai.pro) — ИИ, который помогает с дизайном дома.
+
+[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
+[![Build](https://img.shields.io/github/actions/workflow/status/egmalt/house-planner/ci.yml?branch=main&label=build)](https://github.com/egmalt/house-planner/actions/workflows/ci.yml)
+[![Node 22](https://img.shields.io/badge/node-22-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
+[![React 19](https://img.shields.io/badge/React-19-61DAFB?logo=react&logoColor=black)](https://react.dev/)
+[![TypeScript](https://img.shields.io/badge/TypeScript-6-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
+[![PHP 8.x](https://img.shields.io/badge/PHP-8.x-777BB4?logo=php&logoColor=white)](https://www.php.net/)
+[![Self-hosted](https://img.shields.io/badge/self--hosted-yes-blueviolet)](docs/guide/ru/install.md)
+[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
+[![Live demo](https://img.shields.io/badge/live%20demo-app.homedesignsai.pro-f26b1d)](https://app.homedesignsai.pro)
+
+[English](README.md) | **Русский**
+
+![House Planner: демо-дом в 3D, вид «Материалы»](docs/screenshots/hero.png)
+
+<table>
+<tr><td align="center"><img src="docs/screenshots/plan.png" width="300" alt="2D-редактор плана"><br><sub>2D-редактор плана</sub></td><td align="center"><img src="docs/screenshots/3d.png" width="300" alt="3D с низкими стенами"><br><sub>3D с низкими стенами</sub></td><td align="center" rowspan="2"><img src="docs/screenshots/mobile.png" width="150" alt="Просмотр с телефона"><br><sub>Просмотр с телефона</sub></td></tr>
+<tr><td align="center"><img src="docs/screenshots/map.png" width="300" alt="План на спутниковой карте"><br><sub>План на спутниковой карте</sub></td><td align="center"><img src="docs/screenshots/estimate.png" width="300" alt="Смета на листе A4"><br><sub>Смета на листе A4</sub></td></tr>
+<tr><td align="center"><img src="docs/screenshots/networks.png" width="300" alt="Электрика: группы и трассы"><br><sub>Электрика: группы и трассы</sub></td><td align="center"><img src="docs/screenshots/heating.png" width="300" alt="Петли тёплого пола"><br><sub>Петли тёплого пола</sub></td><td align="center"><img src="docs/screenshots/versions.png" width="300" alt="Версии и снимки"><br><sub>Версии и снимки</sub></td></tr>
+</table>
+
+**[Живое демо](https://app.homedesignsai.pro)**: общая копия без входа, сбрасывается каждый час, см. [демо-режим](docs/guide/ru/demo.md). Интерфейс на английском и русском.
+
+## Возможности
+
+**2D-редактор плана**
+- Черчение в миллиметрах в реальном масштабе: стены с толщиной и материалом, двери, окна, гаражные ворота, мебель из каталога с реальными размерами, зоны участка (отсыпка, газон, мощение).
+- Привязка к концам стен и сетке 100 мм, размерные линии, линейка (`M`, цепочкой), отмена и повтор.
+- Поворот вида шагом 15° и «Север вверх», выделение здания (`B`), чтобы сдвинуть или повернуть дом целиком, подписи комнат с площадью в чистоте по стенам.
+- Сводка площадей: общая и жилая, комнаты, спальни, санузлы, пятно застройки, процент застройки участка.
+
+**3D**
+- Два вида: «Макет» (чистые объёмы) и «Материалы» (текстуры по материалу стен и отделке фасада).
+- Цвет стен и акцента из палитры RAL, низкие стены (1 м и уровень пола), чтобы смотреть планировку сверху, камеры 3/4, сверху, спереди.
+
+**Участок и карта**
+- План поверх спутникового снимка по геопривязке (широта и долгота начала координат плана и поворот).
+- Граница участка из GeoJSON (например, кадастровый участок), смежные участки из `data/parcel.geojson`, ручное выравнивание снимка.
+- Необязательные неизменяемые данные участка на сервере: юридическую границу нельзя сдвинуть из редактора.
+
+**Инженерные сети** (каждая — слой со своим редактором, расчётом и группой в смете)
+- **Канализация** с септиком: трасса от приборов, стояки, ревизии, выпуски; уклоны, отметки лотка, фитинги, проверки расстояний.
+- **Электрика**: розетки, выключатели, светильники, щит и группы; автотрасса по стенам, длины кабеля, автоматы и УЗО, проверки нагрузки и падения напряжения, правила для мокрых зон (ПУЭ, ГОСТ Р 50571).
+- **Водопровод** лучевой: скважина или колодец, насос, фильтр, бойлер, коллекторы холодной и горячей воды, отдельная линия к каждому прибору, теплоизоляция и греющий кабель снаружи.
+- **Водяной тёплый пол**: автораскладка петель по комнатам, краевые зоны, разрезка петель длиннее 80 м, теплоотдача против теплопотерь, расходы и балансировка, место коллектора.
+
+**Смета**
+- Количества считаются по плану и сетям, цены — из JSON-каталога, лист A4 для печати.
+- Галочки «Куплено» с фактической ценой и датой, выгрузка CSV для Excel, корзина в Петровиче одной кнопкой.
+
+**Хранение и доступ**
+- План хранится на сервере в JSON; каждое сохранение — пронумерованная версия, плюс именованные снимки с восстановлением.
+- Оптимистичная блокировка (`If-Match` / `409`): несколько вкладок и скрипты правят без потерь.
+- Вход по одному паролю, файлы данных закрыты кукой, на телефоне — режим просмотра.
+
+## Быстрый старт
+
+### Docker
+
+```bash
+git clone https://github.com/egmalt/house-planner.git
+cd house-planner
+docker compose up -d --build
+```
+
+Откройте <http://localhost:8080/> и задайте пароль в мастере `/api/setup.php`. Без мастера — передать пароль при первом старте: `HOUSE_PASSWORD='длинный-пароль' docker compose up -d --build`. Порт задаёт `HOUSE_PORT` (по умолчанию `8080`). План, все версии и конфигурация лежат в томе `house-data` и переживают пересборку и перезапуск. `HOUSE_PASSWORD` применяется только к пустому хранилищу; чтобы потом сменить пароль, удалите `config.php` из тома (`docker compose exec house-planner rm /var/lib/house-planner/config.php`) и запустите снова с новым `HOUSE_PASSWORD` или через мастер. Резервные копии и HTTPS за обратным прокси — в [руководстве по установке](docs/guide/ru/install.md#docker).
+
+### Режим разработки
+
+Нужны Node.js 22 и PHP 8.1+. Два терминала:
+
+```bash
+npm i
+npm run dev:api # терминал 1: PHP API на 127.0.0.1:8000 прямо из public/
+```
+
+```bash
+npm run dev # терминал 2: Vite на http://localhost:5173 с горячей перезагрузкой
+```
+
+Откройте <http://localhost:5173/api/setup.php>, задайте пароль и работайте на <http://localhost:5173/>. Vite проксирует `/api`, `/data` и `/plans` на PHP-сервер, сборка не нужна. Хранилище — `$HOUSE_STORAGE`, если задан, иначе `./storage` в корне репозитория (в `.gitignore`). `scripts/dev-router.php` повторяет правила `.htaccess` для встроенного сервера PHP; он только для своей машины.
+
+Подробнее — в [руководстве по установке](docs/guide/ru/install.md).
+
+## Свой хостинг
+
+Подойдёт любой виртуальный хостинг с **PHP 8.1+** (с расширением `curl` для корзины Петровича) и **Apache или LiteSpeed** с `mod_rewrite`. Ни базы данных, ни Node.js на сервере не нужно.
+
+1. **Сборка** локально: `npm ci && npm run build`. Получается статическая папка `dist/` с PHP API в `dist/api/`.
+2. **Заливка** содержимого `dist/` в корень сайта: `scripts/deploy.sh` (rsync по SSH или зеркало по FTP, настройки в `.env.deploy`, пример — [`.env.deploy.example`](.env.deploy.example)) или любой FTP-клиент.
+3. **Мастер установки**: один раз откройте `https://ваш-сайт/api/setup.php`. Он выбирает место хранилища, спрашивает пароль (от 8 символов), пишет `storage/config.php` с хешем пароля и случайным токеном куки и закрывает этой кукой `data/` и `plans/`. Дальше мастер отвечает `403`. Переменная окружения `HOUSE_SETUP_KEY` заставит мастер спросить дополнительный ключ.
+4. **Хранилище** ищется по порядку: `$HOUSE_STORAGE`, `<корень сайта>/../storage` (вне корня сайта, предпочтительно), `<корень сайта>/storage` (внутри, закрыто `.htaccess`). В нём `config.php`, `current.json`, все версии в `versions/` и снимки в `snapshots/`.
+5. **HTTPS**: включите на хостинге (Let's Encrypt обычно одной кнопкой). Кука входа — `HttpOnly`, `SameSite=Lax`, на HTTPS автоматически получает `Secure`.
+
+На nginx без Apache `.htaccess` не работает: закройте `/storage`, `/data` и `/plans` в конфигурации сервера. Пошагово, с обновлением и резервными копиями — в [руководстве по заливке](docs/guide/ru/deploy.md).
+
+## Формат плана
+
+План — один JSON-документ в целых миллиметрах: `site` (размер, граница, геопривязка, зоны), `materials`, `walls` (осевая линия `a → b`, толщина, высота, материал), `openings` (двери, окна, ворота со смещением вдоль стены), `furniture`, `rooms`, `estimate` и `networks` (`sewer`, `electric`, `water`, `heating`). Источник истины — zod-схема в [`src/model/schema.ts`](src/model/schema.ts); `npm run plan:validate` проверяет ею демо-план.
+
+Полное описание: [docs/plan-format.md](docs/plan-format.md). HTTP API: [docs/api.md](docs/api.md).
+
+## Работа с ИИ-ассистентом
+
+План — обычный JSON со строгой схемой, поэтому его может править любой LLM-ассистент: «добавь стену 5 м из угла дома на восток», «окно 1200 по центру стены w2», «проведи раковину в санузле к стояку». Цикл:
+
+```bash
+scripts/plan-pull.sh # сервер → plans/server.json
+# правка plans/server.json руками или ассистентом
+node scripts/plan-validate.mts plans/server.json
+scripts/plan-push.sh # → новая версия на сервере
+```
+
+`plan-push.sh` ходит в тот же API с версиями, что и браузер: если план за это время изменился, он сохраняет серверную копию в `*.conflict.json` и выходит с кодом `2`, ничего не перезаписывая. Открытые вкладки подхватывают новую версию сами. Руководство с промптом и подводными камнями — [правка плана через JSON](docs/guide/ru/plan-via-chat.md).
+
+## Стек
+
+React 19, TypeScript, Vite, Zustand + zundo (отмена), zod, Konva / react-konva (2D), three.js с React Three Fiber, drei и postprocessing (3D), three-bvh-csg (проёмы), clipper2 (смещение полигонов), MapLibre GL и proj4 (карта), PHP без фреймворка для API с хранением в файлах и `flock`.
+
+## Планы
+
+- Кровля: формы, уклоны, стропильная система и кровельные материалы в 3D и в смете.
+- Фундамент: плита, лента, сваи — объёмы и арматура.
+- Водопровод с расчётом напора и подбором насоса.
+- Экспорт в PDF и DXF.
+- Больше языков интерфейса: сейчас английский и русский, переводы приветствуются.
+
+## Оговорки
+
+- **Цены** в `public/data/catalog.json` — пример, собранный по магазинам Санкт-Петербурга на дату из поля `checkedAt` каждой позиции. Это не оферта, цены устаревают — заменяйте своими.
+- **Нормы** (СП, ПУЭ, СанПиН, ГОСТ) используются как справочные проверки. Расчёты не заменяют проект, сделанный специалистом.
+- Демо-план — вымышленный одноэтажный дом в северном стиле с гаражом на участке 30 × 45 м в Эстонии.
+
+## Частые вопросы
+
+Хостинг, пароль, резервные копии, обновление, свой участок, каталог, телефон, работа без интернета — в [FAQ](docs/guide/ru/faq.md). Повседневная работа в редакторе — в [руководстве пользователя](docs/guide/ru/usage.md).
+
+## Участие
+
+Задачи и пул-реквесты приветствуются. Сначала прочитайте [CONTRIBUTING.md](CONTRIBUTING.md); участвуя, вы соглашаетесь с [кодексом поведения](CODE_OF_CONDUCT.md). Об уязвимостях — [SECURITY.md](SECURITY.md). Изменения — [CHANGELOG.md](CHANGELOG.md).
+
+## Авторы
+
+House Planner делает и поддерживает команда [homedesignsai.pro](https://homedesignsai.pro). Связь: [[email protected]](mailto:[email protected]).
+
+## Лицензия
+
+[MIT](LICENSE). У сторонних текстур и моделей мебели свои лицензии — см. `public/textures/LICENSE.txt` и `public/models/furniture/LICENSES.md`.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..5251271
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,31 @@
+# Security Policy
+
+## Supported versions
+
+Security fixes go into the latest release on the `main` branch. Self-hosted installations should update to it; see [updating](docs/guide/en/deploy.md#updating).
+
+| Version | Supported |
+|---|---|
+| 0.1.x | yes |
+
+## Reporting a vulnerability
+
+Please do not open a public issue for security problems. Report them privately through GitHub: **Security → Report a vulnerability** on this repository, or directly at <https://github.com/egmalt/house-planner/security/advisories/new>. If you cannot use GitHub, email [[email protected]](mailto:[email protected]) with "Security" in the subject.
+
+Include what you can: the affected file or endpoint, steps to reproduce, the impact you see, and a suggested fix if you have one. Reports in English or Russian are fine.
+
+You can expect an acknowledgement within 7 days and a status update after the issue is assessed. Once a fix is released, the advisory is published with credit to the reporter, unless you prefer to stay anonymous.
+
+## Scope
+
+In scope: the PHP API in `public/api/` (authentication, the login cookie, CSRF protection, storage access, the setup wizard, the Petrovich cart proxy), the `.htaccess` rules that close `storage/`, `data/` and `plans/`, the Docker image, the deploy and plan scripts in `scripts/`, and the frontend.
+
+Out of scope: misconfiguration of a particular hosting (for example, nginx without the equivalent of the `.htaccess` rules), the PHP built-in server used for local development, attacks that need the planner password, and third-party services (petrovich.ru, imagery tiles).
+
+## Hardening a deployment
+
+- Serve the site over HTTPS only; the login cookie gets the `Secure` flag on HTTPS.
+- Keep the storage folder outside the web root (`../storage`) when the hosting allows it.
+- Set `HOUSE_SETUP_KEY`, or in Docker `HOUSE_PASSWORD`, so nobody else can run the setup wizard before you.
+- Use a long password: there is one password per installation, and the login endpoint only slows down guessing with a 1-second delay.
+- On nginx, deny `/storage`, `/data`, `/plans` and `/api/_*` yourself, see [deploy.md](docs/guide/en/deploy.md#nginx).
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..b90542d
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,16 @@
+services:
+ house-planner:
+ build: .
+ image: house-planner:latest
+ ports:
+ - "${HOUSE_PORT:-8080}:8080"
+ environment:
+ HOUSE_PASSWORD: ${HOUSE_PASSWORD:-}
+ HOUSE_SETUP_KEY: ${HOUSE_SETUP_KEY:-}
+ HOUSE_DEMO: ${HOUSE_DEMO:-}
+ volumes:
+ - house-data:/var/lib/house-planner
+ restart: unless-stopped
+
+volumes:
+ house-data:
diff --git a/docker/apache/ports.conf b/docker/apache/ports.conf
new file mode 100644
index 0000000..3cc6764
--- /dev/null
+++ b/docker/apache/ports.conf
@@ -0,0 +1 @@
+Listen 8080
diff --git a/docker/apache/site.conf b/docker/apache/site.conf
new file mode 100644
index 0000000..62a86f4
--- /dev/null
+++ b/docker/apache/site.conf
@@ -0,0 +1,17 @@
+ServerName localhost
+ServerTokens Prod
+ServerSignature Off
+TraceEnable Off
+
+<VirtualHost *:8080>
+ DocumentRoot /var/www/html
+
+ <Directory /var/www/html>
+ Options -Indexes +FollowSymLinks
+ AllowOverride All
+ Require all granted
+ </Directory>
+
+ ErrorLog ${APACHE_LOG_DIR}/error.log
+ CustomLog ${APACHE_LOG_DIR}/access.log combined
+</VirtualHost>
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
new file mode 100755
index 0000000..fdfdc0c
--- /dev/null
+++ b/docker/entrypoint.sh
@@ -0,0 +1,12 @@
+#!/bin/sh
+set -e
+
+: "${HOUSE_STORAGE:=/var/lib/house-planner}"
+export HOUSE_STORAGE
+
+mkdir -p "$HOUSE_STORAGE"
+php /usr/local/lib/house-planner/boot.php
+unset HOUSE_PASSWORD
+chown -R www-data:www-data "$HOUSE_STORAGE" /var/www/html/data /var/www/html/plans
+
+exec docker-php-entrypoint "$@"
diff --git a/docker/healthcheck.php b/docker/healthcheck.php
new file mode 100644
index 0000000..d3872d2
--- /dev/null
+++ b/docker/healthcheck.php
@@ -0,0 +1,12 @@
+<?php
+
+$ctx = stream_context_create(['http' => ['ignore_errors' => true, 'timeout' => 4]]);
+foreach (['/' => [200], '/api/plan.php' => [200, 401, 503]] as $path => $codes) {
+ $http_response_header = [];
+ @file_get_contents('http://127.0.0.1:8080' . $path, false, $ctx);
+ $code = preg_match('#^HTTP/\S+ (\d{3})#', $http_response_header[0] ?? '', $m) ? (int)$m[1] : 0;
+ if (!in_array($code, $codes, true)) {
+ fwrite(STDERR, $path . ' -> ' . $code . "\n");
+ exit(1);
+ }
+}
diff --git a/docker/house-boot.php b/docker/house-boot.php
new file mode 100644
index 0000000..3cd06d1
--- /dev/null
+++ b/docker/house-boot.php
@@ -0,0 +1,46 @@
+<?php
+
+require '/var/www/html/api/_install.php';
+
+function say(string $msg): void
+{
+ fwrite(STDERR, '[house-planner] ' . $msg . "\n");
+}
+
+$storage = find_storage();
+$password = (string)getenv('HOUSE_PASSWORD');
+$demo = is_demo();
+
+if ($storage !== null) {
+ $config = require $storage . '/config.php';
+ $token = is_array($config) ? (string)($config['hauth'] ?? '') : '';
+ if ($token === '') {
+ say('в ' . $storage . '/config.php нет токена hauth');
+ exit(1);
+ }
+ $demo ? demo_open_gates() : write_gates($token);
+ say('хранилище ' . $storage . ($password !== '' ? ', HOUSE_PASSWORD не применяется: установка уже выполнена' : ''));
+ exit(0);
+}
+
+if ($password === '' && $demo) {
+ $password = bin2hex(random_bytes(16));
+}
+
+if ($password === '') {
+ write_gates(null);
+ say('не установлено: откройте /api/setup.php и задайте пароль');
+ exit(0);
+}
+
+if (mb_strlen($password) < MIN_PASSWORD) {
+ say('HOUSE_PASSWORD короче ' . MIN_PASSWORD . ' символов');
+ exit(1);
+}
+
+$dir = storage_candidates()[0];
+install($dir, $password);
+if ($demo) {
+ demo_open_gates();
+}
+say('установлено, хранилище ' . $dir . ($demo ? ', демо-режим: вход без пароля, сброс каждый час' : ''));
diff --git a/docker/php/house-planner.ini b/docker/php/house-planner.ini
new file mode 100644
index 0000000..a6e4616
--- /dev/null
+++ b/docker/php/house-planner.ini
@@ -0,0 +1,9 @@
+expose_php = Off
+display_errors = Off
+log_errors = On
+error_log = /proc/self/fd/2
+memory_limit = 128M
+post_max_size = 4M
+upload_max_filesize = 4M
+max_execution_time = 150
+date.timezone = UTC
diff --git a/docs/api.md b/docs/api.md
new file mode 100644
index 0000000..dbdf611
--- /dev/null
+++ b/docs/api.md
@@ -0,0 +1,136 @@
+# API хранения плана (`/api/plan.php`)
+
+План живёт на сервере, а не только в браузере. Отдельного бэкенда нет: PHP-файлы в `public/api/` (общий код в `public/api/_lib.php`, общие функции установки — создание хранилища, запись `config.php` и закрывающих `.htaccess` — в `public/api/_install.php`, их используют мастер `setup.php` и загрузчик Docker-образа) собираются в `dist/api/` и заливаются `scripts/deploy.sh`. Нужен PHP 8.1+ (код совместим и с 7.4, но устаревшие версии не проверяются) с `curl` (для корзины Петровича); для закрытия статики — Apache или LiteSpeed с `mod_rewrite`. Формат самого плана описан в `docs/plan-format.md`; сервер проверяет только, что это JSON-объект с `site` (объект), `walls` и `openings` (массивы), остальное — дело zod-схемы клиента.
+
+**Хранилище.** Папка `storage/`, которую создаёт мастер установки `api/setup.php`. Ищется по порядку: путь из переменной окружения `HOUSE_STORAGE`, `<корень сайта>/../storage` (вне webroot, предпочтительно), `<корень сайта>/storage` (внутри сайта, закрыта `.htaccess` с `Require all denied`). Рабочей считается первая папка, где есть `config.php`. Там `config.php` — хеш пароля, токен куки входа и настройки (пример — `storage.example/config.example.php`, в репозиторий настоящий не попадает), `current.json` — текущий план, `versions/<YYYYMMDDTHHMMSSZ>-<rev>.json` — каждая записанная версия (хранятся все), `versions.jsonl` — индекс версий построчно, `.lock` — файл блокировки. Если `current.json` нет, первый же запрос засевает его из файла `seed` в конфиге (по умолчанию `plans/demo.json` в корне сайта) как `rev 1` с автором `seed`. Пока хранилища нет, любой запрос к API отвечает `503 not_installed`.
+
+**Неизменяемые данные участка (необязательно).** Если положить в хранилище `site-fixed.json` вида `{ "site": { boundary, street, geo, zones } }` (пример — `storage.example/site-fixed.example.json`), сервер накладывает эти поля поверх плана при каждой отдаче (`GET`, `?rev=N`, план в ответе `409`) и при каждой записи. `boundary`, `street` и `geo` всегда берутся из файла, что бы ни прислал клиент. Зоны из файла с `locked: true` идут первыми в `site.zones`; присланные клиентом зоны с `locked: true` или с тем же `id` отбрасываются, остальные зоны клиента сохраняются как есть. `site.imagery` (поправка спутниковой подложки) не фиксируется. Так юридическую границу участка нельзя случайно сдвинуть из приложения или через `plan-push.sh` — только правкой файла на сервере. Если файла нет, наложение не делается.
+
+**Служебные поля плана.** Сервер дописывает в сохранённый план три поля верхнего уровня: `rev` (целое, растёт на 1 с каждой записью), `updatedAt` (ISO 8601 UTC с миллисекундами) и `author` (метка автора). Присланные клиентом значения этих полей игнорируются и перезаписываются. Zod-схема клиента лишние поля пропускает.
+
+**Доступ.** Каждый запрос должен нести куку `hauth` — её ставит `POST /api/login.php` (см. ниже). Значение куки — случайный токен из `storage/config.php`, сверка через `hash_equals`. Без неё или с неверной — `401`. Запросы на запись дополнительно требуют непустой заголовок `X-Requested-With` (клиент шлёт `XMLHttpRequest`), иначе `403` — это защита от CSRF через обычную форму. В `public/api/.htaccess` стоит `RewriteEngine On`: он отключает для `/api/` возможные правила переадресации из корневого `.htaccess`, так что API всегда отвечает `401` в JSON, а не `302`. Прямой запрос к файлам с подчёркиванием в начале (`_lib.php`, `_install.php`) — `403`. Все ответы идут с `Cache-Control: no-store` и `Content-Type: application/json`.
+
+**Закрытые данные.** Статика с данными дома тоже закрыта кукой: мастер установки пишет `data/.htaccess` и `plans/.htaccess`, которые сверяют `hauth` с тем же токеном через `RewriteCond %{HTTP_COOKIE}` и без куки отвечают `401`. В репозитории этих файлов нет, `scripts/deploy.sh` их на сервере не трогает. Это `/data/house.json`, `/data/catalog.json`, `/data/parcel.geojson` и `/plans/*.json`. Засев хранилища читает план с диска, а не по HTTP, поэтому закрытие на него не влияет. На nginx без Apache `.htaccess` не работает — закройте `/storage`, `/data` и `/plans` в конфигурации сервера.
+
+## Методы
+
+| запрос | ответ |
+|---|---|
+| `GET /api/plan.php` | `200`, тело — текущий план целиком, заголовки `ETag: "<rev>"` и `X-Plan-Rev: <rev>` |
+| `GET /api/plan.php?versions` | `200`, `{ "rev": <текущий>, "versions": [ { rev, updatedAt, author, walls, openings, bytes, file }, … ] }`, новые сверху; `walls`/`openings` — число стен и проёмов |
+| `GET /api/plan.php?rev=N` | `200`, план версии `N` с её `ETag`; нет такой — `404` |
+| `PUT` или `POST /api/plan.php` | тело — JSON плана, заголовки `If-Match: <rev>` (можно `"<rev>"`), `X-Requested-With`, необязательный `X-Plan-Author: <метка>` (по умолчанию `web`, до 40 символов, буквы, цифры, пробел, `.@_-`). Успех — `200`, `{ "rev": <новый>, "updatedAt": "…" }` и новый `ETag` |
+
+**Версия клиента.** Каждый `PUT`/`POST` должен нести заголовок `X-Client-Version: <целое>`. Если его нет или он меньше минимальной версии (константа `MIN_CLIENT_VERSION` в `public/api/_lib.php`, сейчас `2`; можно переопределить ключом `min_client_version` в `storage/config.php`), сервер ничего не пишет и отвечает `426 { "error": "client_outdated", "message": "…", "minClientVersion": 2 }`. Клиент на `426` перезагружает страницу. Это защита от старых открытых вкладок, которые не знают новых полей плана (например, `site.zones`) и затирали бы их при сохранении. Когда формат плана расширяется, версию в клиенте и `MIN_CLIENT_VERSION` поднимают вместе. `plan-push.sh` шлёт `X-Client-Version` из константы `CLIENT_VERSION` в `src/model/schema.ts`.
+
+Запись: `If-Match` сравнивается с `rev` текущего плана под эксклюзивным `flock` на `storage/.lock`. Совпало — план получает `rev+1`, пишется файл версии, затем `current.json` (оба через временный файл и `rename`, т. е. атомарно), затем строка в `versions.jsonl`. Не совпало — ничего не пишется, ответ `409`:
+
+```json
+{ "error": "conflict", "message": "план уже изменён: rev 7, прислан 5", "rev": 7, "updatedAt": "…", "plan": { …текущий план… } }
+```
+
+Клиент в этом случае должен показать расхождение и переложить свои правки поверх `plan`, а потом писать с `If-Match: 7`. Молча перезаписывать нельзя: в тот же файл могут писать другая вкладка или `plan-push.sh`.
+
+## Именованные снимки
+
+Все ревизии и так хранятся в `versions/`, снимок — это ревизия с человеческим именем, чтобы откатиться «к версии от 30.09», не выискивая номер. Снимки лежат в `storage/snapshots/<дата>-<slug>.json` (дата в часовом поясе `timezone` из конфига, slug — имя транслитом, при совпадении добавляется `-2`, `-3`), журнал — `storage/snapshots.jsonl`. Автоматически снимки не удаляются никогда.
+
+`POST /api/plan.php?snapshot` с телом `{ "name": "30.09.2026 — дом из блоков" }` копирует текущий `current.json` в снимок и отвечает `201 { id, name, rev, createdAt, author, walls, openings }`. Доступ как у записи плана: кука `hauth`, `X-Requested-With`, `X-Client-Version`; автор берётся из `X-Plan-Author` (по умолчанию `web`). Пустое имя или длиннее 200 символов — `422 invalid_name`. `If-Match` не нужен: снимок ничего не меняет в плане.
+
+`GET /api/plan.php?snapshots` — `{ "snapshots": [ … ] }`, новые сверху. `GET /api/plan.php?snapshot=<id>` — сам план снимка (с наложением неизменяемых данных участка) и `ETag` его ревизии; нет такого — `404`.
+
+Восстановление — обычный `PUT` плана из снимка поверх текущего с `If-Match: <текущий rev>` (не rev снимка) и `X-Plan-Author: restore:<id>`. Получается новая ревизия, история и сам снимок остаются.
+
+## Вход и выход
+
+Вход встроен в приложение: без куки клиент получает `401` от `plan.php` и показывает свою форму пароля.
+
+`POST /api/login.php` с телом `{ "password": "…" }` и заголовком `X-Requested-With`. Сервер проверяет пароль через `password_verify` по хешу из `storage/config.php`. Совпало — `200 { "ok": true }` и `Set-Cookie: hauth=<токен>; Max-Age=31536000; Path=/; HttpOnly; SameSite=Lax` (плюс `Secure`, если запрос пришёл по HTTPS). Не совпало (или пароль пуст, или тело не JSON) — пауза 1 с против перебора и `401 { "error": "wrong_password" }`. Без `X-Requested-With` — `403 csrf`, другой метод — `405`.
+
+`POST /api/logout.php` с `X-Requested-With` стирает куку (`hauth=; Max-Age=0`) и отвечает `200 { "ok": true }`. Кука `HttpOnly`, из JS её не видно, поэтому признак входа для клиента — статус ответа `GET /api/plan.php`.
+
+## Корзина Петровича (`/api/petrovich-cart.php`)
+
+Собирает корзину на petrovich.ru и возвращает ссылку на смету, которую кто угодно открывает без входа и одной кнопкой переносит позиции в свою корзину.
+
+`POST /api/petrovich-cart.php` с телом `{ "city": "spb" | "vbg", "items": [ { "code": "128015", "qty": 2, "name": "…" } ] }`. Доступ как у записи плана: кука `hauth`, `X-Requested-With`, `X-Client-Version` (иначе `401`, `403`, `426`). `code` — код товара Петровича (цифры из `petrovich.ru/product/<code>/`), `qty` — количество в единицах продажи, дробное округляется вверх, повторяющиеся коды складываются, `name` необязателен. Не больше 150 разных позиций, иначе `413 too_many_items`.
+
+Порядок работы: свежая анонимная сессия (страница товара → `init.js` → куки), GUID товаров пачками по 50 кодов через `catalog/v5/search-d` в выбранном городе, коды, которых нет в выдаче, добираются по одному через `catalog/v5/products/{code}`. Товары с `is_not_in_stock` в городе пропускаются. Остальные добавляются по одной `POST /cart/v2/products/{guid}` с паузой 300–500 мс, потом `GET /cart/v2/link` даёт ссылку, корзина очищается `DELETE /cart/v2/items`. Весь запрос ограничен 120 с. Одновременно идёт один запрос: второй получает `429 busy`.
+
+Ответ `200`:
+
+```json
+{ "url": "https://petrovich.ru/estimate/000000000/", "city": "spb",
+ "added": [ { "code": "128015", "qty": 2, "name": "Коробка установочная …", "price": 21 } ],
+ "missing": [ { "code": "999999999", "reason": "not_found" } ],
+ "total": 94 }
+```
+
+`reason` в `missing`: `not_found` — такого кода нет, `no_stock` — нет в наличии в городе, `add_failed` — Петрович не принял позицию (в `detail` его ответ). `price` — розничная цена Петровича в городе за единицу, `total` — сумма `price × qty` по добавленным, без скидок корзины. Если не добавилось ничего — `422 nothing_added` с тем же `missing`, ссылки нет. Капча Qrator, `403` или `429` от Петровича — `502 petrovich_blocked`; прочие сбои Петровича — `502 petrovich_unavailable | petrovich_bad_reply | petrovich_no_link`; не уложились в 120 с — `504 timeout`. Ошибки входа: `400 bad_json`, `422 invalid_city | invalid_items`. Каждый вызов создаёт новую смету у Петровича, удалить её анонимно нельзя, поэтому ручку не дёргать в цикле.
+
+## Демо-режим
+
+Включается ключом `'demo' => true` в `storage/config.php` или переменной окружения `HOUSE_DEMO=1` (в Docker — `docker run -e HOUSE_DEMO=1`). Код — `public/api/_demo.php`. Отличия от обычного режима:
+
+**Признак для клиента.** Каждый JSON-ответ API в демо несёт заголовок `X-House-Demo: 1`; тело плана не меняется. Клиент читает заголовок из `GET /api/plan.php` и показывает плашку со ссылкой на репозиторий, кнопку корзины Петровича выключает. В обычном режиме заголовка нет.
+
+**Без входа.** Кука `hauth` не проверяется ни в `plan.php`, ни в других ручках, `401` не бывает, экран входа не показывается. `POST /api/login.php` сразу отвечает `200 { "ok": true, "demo": true }` без проверки пароля. `data/` и `plans/` открыты: при сбросе (и при старте Docker-контейнера) их `.htaccess` переписываются на открытый вариант. `setup.php` ведёт себя как обычно: после установки `403`.
+
+**Сброс.** План раз в час возвращается к `plans/demo.json` в корне сайта: новая ревизия `rev+1` с автором `demo-reset` (номер ревизии не откатывается, открытые вкладки получат `409` и перечитают план). Заодно удаляются версии и снимки старше часа и старые счётчики лимита. Время последнего сброса — mtime файла `storage/.demo-reset`. Сброс делает cron-скрипт `php scripts/demo-reset.php --webroot=<корень сайта>` (от пользователя веб-сервера; без `--webroot` берётся `public/` рядом со скриптом), а если cron нет — ленивый сброс: первый запрос к `plan.php` после того, как с прошлого сброса прошло больше 60 минут, сначала сбрасывает план, потом обрабатывается. В Docker работает только ленивый сброс.
+
+**Ограничения.** План не больше 1 МБ (`413 too_large`). Не больше 30 записей (`PUT`/`POST` плана и снимков) в минуту с одного IP (`REMOTE_ADDR`, за обратным прокси — адрес прокси), счётчик — файлы `storage/ratelimit/<sha256 IP>.json`; превышение — `429 rate_limited` с `Retry-After` и полем `retryAfter` в секундах. Снимков не больше 20 (`403 demo_limit`), лишние уходят при часовом сбросе. Корзина Петровича отключена: `POST /api/petrovich-cart.php` — `403 demo_disabled`. Константы — в начале `_demo.php`.
+
+## Коды ошибок
+
+Тело любой ошибки — `{ "error": "<код>", "message": "<по-русски>" }`.
+
+| HTTP | `error` | когда |
+|---|---|---|
+| 400 | `bad_json` | тело не парсится как JSON |
+| 401 | `unauthorized` | нет куки `hauth` или она неверна |
+| 401 | `wrong_password` | `login.php`: неверный пароль |
+| 403 | `csrf` | запись, вход или выход без `X-Requested-With` |
+| 403 | `demo_disabled` | демо: корзина Петровича отключена |
+| 403 | `demo_limit` | демо: уже 20 снимков |
+| 404 | `not_found` | `?rev=N` без такой версии |
+| 405 | `method_not_allowed` | метод не GET/HEAD/PUT/POST |
+| 409 | `conflict` | `If-Match` не равен текущему `rev`; в теле `rev` и `plan` |
+| 413 | `too_large` | тело больше 2 МБ (в демо — 1 МБ) |
+| 422 | `invalid_plan` | не объект или нет `site`/`walls`/`openings` нужного типа |
+| 426 | `client_outdated` | запись без `X-Client-Version` или с версией меньше минимальной |
+| 428 | `if_match_required` | запись без `If-Match` |
+| 429 | `rate_limited` | демо: больше 30 записей в минуту с одного IP; есть `Retry-After` |
+| 503 | `not_installed` | хранилище не найдено — откройте `api/setup.php` |
+| 500 | `no_seed`, `lock_failed`, `write_failed`, `corrupt` | проблема на сервере |
+
+## Пример клиента
+
+```ts
+const res = await fetch('/api/plan.php', { credentials: 'same-origin', cache: 'no-store' });
+const plan = await res.json();
+const rev = Number(res.headers.get('X-Plan-Rev'));
+
+const put = await fetch('/api/plan.php', {
+ method: 'PUT',
+ credentials: 'same-origin',
+ headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'If-Match': String(rev) },
+ body: JSON.stringify(plan),
+});
+if (put.status === 409) { const { rev: serverRev, plan: serverPlan } = await put.json(); }
+```
+
+## Установка
+
+`api/setup.php` открывается один раз после первой заливки. Он показывает, куда можно положить хранилище (вне корня сайта, если есть права, иначе внутри с запретом `.htaccess`), принимает пароль (не короче 8 символов), создаёт папку `storage/`, пишет `config.php` с `password_hash` и случайным токеном куки, а также `data/.htaccess` и `plans/.htaccess` с этим токеном. После этого `setup.php` отвечает `403`. Если задана переменная окружения `HOUSE_SETUP_KEY`, мастер дополнительно спрашивает этот ключ — так установку не перехватит посторонний между заливкой и первым входом. Сменить пароль: удалить `config.php` в хранилище и снова открыть `setup.php`; план и версии остаются, старые куки перестают действовать.
+
+**Docker.** В образе хранилище — том `house-data`, смонтированный в `/var/lib/house-planner` (`HOUSE_STORAGE`). При каждом старте контейнера загрузчик (`docker/house-boot.php`, на тех же функциях из `_install.php`) переписывает `data/.htaccess` и `plans/.htaccess` под токен из `config.php`. Если `config.php` ещё нет и задана переменная `HOUSE_PASSWORD` (не короче 8 символов), он выполняет установку сам, без мастера; если пароля нет — закрывает `data/` и `plans/` полностью и ждёт мастера `api/setup.php`. После установки `HOUSE_PASSWORD` больше ни на что не влияет. С `HOUSE_DEMO=1` загрузчик ставит планировщик без `HOUSE_PASSWORD` (пароль случайный, он не нужен) и вместо закрывающих `.htaccess` пишет открытые — см. «Демо-режим».
+
+## Скрипты
+
+**`scripts/plan-pull.sh`** входит через `POST /api/login.php` и забирает текущий план (`GET /api/plan.php`) в `plans/server.json` в корне проекта, печатает `rev`, время, автора и число стен. `--rev N` берёт конкретную версию, `--out <файл>` пишет в другой файл. Адрес и пароль — переменные `HOUSE_URL` (по умолчанию `DEPLOY_URL`) и `HOUSE_PASSWORD`, из окружения или `.env.deploy`.
+
+**`scripts/plan-push.sh [файл]`** заливает файл (по умолчанию `plans/server.json`) как новую версию через тот же `PUT /api/plan.php`, так что проверка `rev`, блокировка, атомарная запись и версия работают одинаково для браузера и для скрипта. Базовый `rev` берётся из поля `rev` в файле (его туда кладёт pull) или из `--rev N`; метка автора — `cli`, меняется через `--author`. `X-Client-Version` берётся из `CLIENT_VERSION` в `src/model/schema.ts`. При успехе печатает новый `rev` и, если отправлялся `plans/server.json`, перетягивает его с сервера. При конфликте кладёт серверный план рядом как `<файл>.conflict.json` и выходит с кодом `2`; тогда правки надо перенести на него и отправить снова.
+
+**`node scripts/plan-validate.mts <файл>`** проверяет план той же zod-схемой, что и клиент (`npm run plan:validate` — для демо-плана).
+
+Обычный цикл правки плана вне браузера: `scripts/plan-pull.sh`, правка `plans/server.json`, `scripts/plan-validate.mts plans/server.json`, `scripts/plan-push.sh`.
diff --git a/docs/guide/en/demo.md b/docs/guide/en/demo.md
new file mode 100644
index 0000000..03fcb2e
--- /dev/null
+++ b/docs/guide/en/demo.md
@@ -0,0 +1,37 @@
+# Public demo
+
+**English** | [Русский](../ru/demo.md)
+
+Demo mode turns an installation into an open sandbox: the planner opens without a password, every visitor sees everyone's edits, and once an hour the plan goes back to the original `plans/demo.json`. This is how the demo on the project site works; you don't need it for your own house — install a regular copy.
+
+## What changes
+
+No login: the API doesn't check the cookie, the password screen never shows, `data/` and `plans/` are open. A thin bar at the top says the demo is shared and resets hourly and links to GitHub. Every hour the plan resets to `plans/demo.json`, and versions and snapshots older than an hour are deleted. Abuse limits: plan size up to 1 MB, at most 30 saves per minute per IP (then `429`), at most 20 snapshots, the Petrovich cart is disabled (the button is inactive, the API answers `403 demo_disabled`). Details and response codes are in [docs/api.md](../../api.md#демо-режим) (Russian).
+
+## Docker
+
+```bash
+HOUSE_DEMO=1 docker compose up -d --build
+```
+
+No password needed: the boot script installs the planner with a random password and opens `data/` and `plans/`. The reset is lazy: the first request after an hour since the previous reset triggers it.
+
+## Shared hosting
+
+Install the planner as usual ([deploy.md](deploy.md)), then add this key to `storage/config.php`:
+
+```php
+'demo' => true,
+```
+
+and a cron job running as the web server user:
+
+```cron
+0 * * * * php /home/user/house-planner/scripts/demo-reset.php --webroot=/home/user/www/plan.example.com
+```
+
+`--webroot` is the site root where `dist/` was uploaded; the script loads `api/_lib.php` and `plans/demo.json` from there and finds the storage the same way the API does (`HOUSE_STORAGE`, `../storage`, `storage`). The first run opens `data/` and `plans/` right away. Without cron the lazy reset works as in Docker.
+
+## Turning it off
+
+Remove the `demo` key (or the `HOUSE_DEMO` variable), then lock the static files again: in Docker run `docker compose exec house-planner rm /var/lib/house-planner/config.php` and `HOUSE_PASSWORD=<password> docker compose up -d` (the demo install's password is random and unknown); on shared hosting delete `config.php` in the storage and run `api/setup.php` with a new password (the plan and versions stay). Rotating the cookie token this way is recommended, since `data/` and `plans/` were open during the demo.
diff --git a/docs/guide/en/deploy.md b/docs/guide/en/deploy.md
new file mode 100644
index 0000000..151a1af
--- /dev/null
+++ b/docs/guide/en/deploy.md
@@ -0,0 +1,119 @@
+# Deploying to shared hosting
+
+**English** | [Русский](../ru/deploy.md)
+
+Target: any hosting with PHP 8.1+ (with `curl`) and Apache or LiteSpeed with `mod_rewrite`. The site is a folder of static files plus `api/*.php`; the plan lives in a `storage/` folder that the setup wizard creates. For Docker see [install.md](install.md#docker).
+
+## 1. Build
+
+```bash
+npm ci
+npm run build
+```
+
+The result is `dist/`: `index.html`, `assets/`, `api/` (PHP), `data/` (catalog and site notes), `plans/demo.json` (seed), `models/`, `textures/`. Paths are relative, so the site works both at a domain root and in a subfolder.
+
+## 2. Upload
+
+### With `scripts/deploy.sh`
+
+Copy [`.env.deploy.example`](../../../.env.deploy.example) to `.env.deploy` and fill it in. Over SSH (rsync):
+
+```bash
+DEPLOY_URL=https://plan.example.com
+DEPLOY_METHOD=ssh
+DEPLOY_PATH=www/plan.example.com
+# DEPLOY_SSH_OPTS="-p 2222 -i ~/.ssh/id_ed25519"
+```
+
+Over FTP (needs `lftp`):
+
+```bash
+DEPLOY_METHOD=ftp
+FTP_HOST=ftp.example.com
+FTP_USER=...
+FTP_PASSWORD=...
+FTP_PATH=www/plan.example.com
+```
+
+Then:
+
+```bash
+scripts/deploy.sh # build, upload, verify
+scripts/deploy.sh --no-build # upload the existing dist/
+```
+
+The script builds, mirrors `dist/` to the site root with deletion of stale files, and compares checksums (SSH) or sizes (FTP) of every file with the server. It never touches `storage/`, `data/.htaccess` and `plans/.htaccess` on the server. A lock prevents two deploys from running at once.
+
+### By hand
+
+Upload the **contents** of `dist/` to the site root with any FTP client. On updates, do not delete or overwrite `storage/` (if it is inside the site root), `data/.htaccess` and `plans/.htaccess`: they hold your password hash and cookie token.
+
+## 3. Install
+
+Open `https://plan.example.com/api/setup.php`:
+
+1. Choose where to keep the storage. Outside the site root (`../storage`) is preferred; inside the site root it is closed by `.htaccess`.
+2. Set a password, at least 8 characters.
+3. Done: the wizard writes `storage/config.php`, closes `data/` and `plans/` behind the login cookie and answers `403` from then on.
+
+To make sure nobody else runs the wizard between upload and your first visit, set the `HOUSE_SETUP_KEY` environment variable in the hosting panel; the wizard will ask for it.
+
+## 4. HTTPS
+
+Enable a certificate in the hosting panel (most hosts issue Let's Encrypt in one click) and turn on the HTTP → HTTPS redirect there. The login cookie gets `Secure` automatically on HTTPS requests. Without HTTPS the password travels in clear text, so do not skip this step for a public site.
+
+## Where things are on the server
+
+| Path | What | In deploy |
+|---|---|---|
+| `storage/config.php` | password hash, cookie token, seed path, time zone | never touched |
+| `storage/current.json` | current plan | never touched |
+| `storage/versions/`, `versions.jsonl` | every saved revision and its index | never touched |
+| `storage/snapshots/`, `snapshots.jsonl` | named snapshots | never touched |
+| `storage/site-fixed.json` | optional locked site data (boundary, geo, street, locked zones) | never touched |
+| `data/.htaccess`, `plans/.htaccess` | cookie check for data files, written by setup | never touched |
+| `data/catalog.json` | price catalog | replaced from `public/data/` |
+| `data/house.json` | «Участок и дом» page | replaced from `public/data/` |
+| `data/parcel.geojson` | optional neighbouring parcels for the map | replaced from `public/data/`, deleted if absent there |
+| `plans/demo.json` | seed for an empty storage | replaced |
+
+Keep your own `house.json`, `catalog.json` and `parcel.geojson` in `public/data/` locally, otherwise the next deploy overwrites or removes the server copies. If they contain personal data, keep them out of git (for example with `.git/info/exclude`).
+
+## nginx
+
+`.htaccess` does nothing on nginx. Put the storage outside the web root and deny the data folders yourself, letting only requests with the login cookie through:
+
+```nginx
+location ^~ /storage/ { deny all; }
+location ~ ^/api/_ { deny all; }
+location ~ ^/(data|plans)/ {
+ if ($cookie_hauth != "<token from storage/config.php>") { return 401; }
+}
+location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/run/php/php-fpm.sock; }
+```
+
+## Updating
+
+```bash
+git pull
+npm ci
+scripts/deploy.sh
+```
+
+The plan, versions and password stay. If the plan format changed, the new client and server raise the minimum client version together; old open tabs reload themselves instead of overwriting new fields. Read [CHANGELOG.md](../../../CHANGELOG.md) before updating.
+
+## Backups
+
+Everything that matters is the storage folder. Copy it whole, for example:
+
+```bash
+ssh [email protected] 'tar -C www -czf - storage' > house-backup-$(date +%F).tar.gz
+```
+
+For a quick copy of the plan alone, use «⋯» → «Экспорт JSON» or `scripts/plan-pull.sh`. To restore, put the folder back, or import the JSON as a new revision.
+
+## Changing the password
+
+Delete `config.php` in the storage folder and open `/api/setup.php` again. The plan and history stay; existing logins stop working because a new cookie token is generated.
diff --git a/docs/guide/en/faq.md b/docs/guide/en/faq.md
new file mode 100644
index 0000000..ad4dfd0
--- /dev/null
+++ b/docs/guide/en/faq.md
@@ -0,0 +1,83 @@
+# FAQ
+
+**English** | [Русский](../ru/faq.md)
+
+### Do I need a server or a database?
+
+You need a web server with PHP 8.1+; you do not need a database. The plan, its versions and the config are plain files in a `storage/` folder. Cheap shared hosting with Apache or LiteSpeed is enough, and so is the Docker image or `php -S` on your own computer. Node.js is needed only to build the frontend. See [install.md](install.md).
+
+### How do I change the password?
+
+Delete `config.php` in the storage folder and open `/api/setup.php` again. The plan and history stay; everyone is logged out because a new cookie token is generated. In Docker: `docker compose exec house-planner rm /var/lib/house-planner/config.php`, then restart with a new `HOUSE_PASSWORD` or use the wizard. Details: [install.md](install.md#docker), [deploy.md](deploy.md#changing-the-password).
+
+### Can several people use it? Are there user accounts?
+
+There is one password per installation and no accounts or roles: everyone who knows the password can edit. Concurrent editing is safe, though: every save carries the revision it was based on, so two tabs, two people or a script never silently overwrite each other. Each revision records an author label (`web`, `cli`, or whatever `plan-push.sh --author` sets). For separate projects, run separate installations: another folder on the hosting or another Docker container with its own port and volume.
+
+### Where is my data, and how do I back it up?
+
+In the storage folder: `config.php`, `current.json` (current plan), `versions/` (every saved revision, kept forever), `snapshots/` (named snapshots). On shared hosting it is usually `../storage` next to the site root; in Docker it is the `house-data` volume. Back up the whole folder. For a copy of the plan alone use «⋯» → «Экспорт JSON» or `scripts/plan-pull.sh`. Commands: [deploy.md](deploy.md#backups).
+
+### How do I update to a new version?
+
+`git pull`, `npm ci`, `scripts/deploy.sh` (or upload the new `dist/` by hand without touching `storage/`, `data/.htaccess`, `plans/.htaccess`). In Docker: `git pull && docker compose up -d --build`. The storage is not affected. Check [CHANGELOG.md](../../../CHANGELOG.md) first.
+
+### How do I load my own plot?
+
+1. Get the parcel polygon in WGS84 longitude/latitude as GeoJSON. In Russia you can export it from the public cadastral map (НСПД) or draw it in any GIS tool (QGIS, geojson.io).
+2. Open «Карта», expand «Граница из GeoJSON», paste a `Polygon`, `Feature` or `FeatureCollection`, keep «Вычислить geo по полигону» on and choose which vertex becomes the plan origin.
+3. «Пересчитать», check the area and size, then «Применить к плану». The boundary becomes `site.boundary` in millimetres and `site.geo` ties the plan to the map.
+4. If the satellite image is offset from the boundary, align the image with the shift and rotation controls; only the image correction is stored.
+
+Neighbouring parcels can be shown from `public/data/parcel.geojson` (a `FeatureCollection`). To lock the legal boundary so it cannot be moved from the editor or a script, put `site-fixed.json` into the storage folder, see `storage.example/site-fixed.example.json` and [docs/api.md](../../api.md).
+
+### How do I add a material to the catalog?
+
+The catalog is `public/data/catalog.json`, an array of items:
+
+```json
+{ "id": "block-d500-600x300x200", "name": "Gas block D500 600×300×200", "kind": "block",
+ "vendor": "Store name", "url": "https://…", "sku": "123456",
+ "thickness": 300, "length": 600, "height": 200,
+ "price": 290, "unit": "шт", "checkedAt": "2026-10-01" }
+```
+
+`kind` decides where the item is used (`sip`, `pir`, `block`, `timber`, `door`, `window`, `gate`, `insulation`, `sewer`, `water`, `heating`, `electric` and others); `unit` is `шт` (piece), `м²`, `м` and so on; `preferred: true` wins over cheaper matches; `sku` is the Petrovich product code. The matching rules for each network are in [docs/plan-format.md](../../plan-format.md). The catalog is loaded at runtime, so after editing it is enough to upload `data/catalog.json`; no rebuild is needed. A material used only in one plan can instead go into the plan's own `materials` with a `price`.
+
+### Are the prices real?
+
+They are an example collected from stores in Saint Petersburg on the date in each item's `checkedAt`. They are not an offer, they go stale, and they may not match your region. Treat the catalog as a template and keep your own.
+
+### Are the building code checks reliable?
+
+They are reference checks based on Russian codes (СП 30.13330, ПУЭ, ГОСТ Р 50571, СанПиН) and simplified engineering formulas. They catch typical mistakes early, but do not replace a design by a licensed engineer or local regulations.
+
+### Does it work on a phone?
+
+Yes, for viewing. On screens narrower than 700 px or touch-only devices the app switches to read-only: plan, 3D, map, estimate and the site page work; nothing is written to the server. Editing needs a mouse or trackpad.
+
+### How does the Petrovich cart work?
+
+«Смета» → «Собрать корзину в Петровиче». The server-side `api/petrovich-cart.php` opens an anonymous session on petrovich.ru, finds the products by code, adds them to a cart, gets a public estimate link and clears the cart. You get one link per section (house, garage, electrical, sewer, water, underfloor heating, other); anyone can open it and move the items to their own cart in one click.
+
+Limitations:
+
+- Only lines with a Petrovich product code (`sku`, or a `petrovich.ru/product/<code>/` URL) are included. Other stores are skipped.
+- Two cities: Saint Petersburg and Vyborg. Items out of stock in the chosen city are skipped and listed.
+- Up to 150 distinct items per request, one request at a time (a second one gets `429`), 120 s timeout.
+- Prices in the reply are Petrovich retail prices without cart discounts.
+- It uses Petrovich's website API, not an official integration: it may break when they change it, and their bot protection may block your hosting's IP (`502 petrovich_blocked`).
+- Every call creates a new estimate on their side that cannot be deleted anonymously, so do not call it in a loop.
+- Needs the PHP `curl` extension.
+
+### Can I use it without internet?
+
+Mostly. Run it locally (Docker or `php -S`) and the editor, 3D, networks and estimate work on a local network without internet access. Internet is needed for satellite imagery (Esri World Imagery tiles), for the Petrovich cart and for product links. The app loads no fonts or scripts from third-party CDNs.
+
+### Which interface languages are there?
+
+English and Russian. The language follows the browser and can be switched in the "⋯" menu → Language; the choice is remembered. Translations to other languages are welcome: strings live in `src/i18n/locales/<language>/`, see [CONTRIBUTING.md](../../../CONTRIBUTING.md).
+
+### What is the license?
+
+[MIT](../../../LICENSE): use, modify and host it, including commercially, keeping the copyright notice. Bundled textures and furniture models have their own licenses, listed in `public/textures/LICENSE.txt` and `public/models/furniture/LICENSES.md`.
diff --git a/docs/guide/en/install.md b/docs/guide/en/install.md
new file mode 100644
index 0000000..6164989
--- /dev/null
+++ b/docs/guide/en/install.md
@@ -0,0 +1,103 @@
+# Installation
+
+**English** | [Русский](../ru/install.md)
+
+House Planner is a static React app plus a small PHP API that keeps the plan in files. There is no database and no Node.js process on the server. Pick one of three ways to run it.
+
+| Option | Good for | Needs |
+|---|---|---|
+| [Docker](#docker) | a home server, a VPS, trying it out | Docker with Compose |
+| [Local PHP server](#local-php-server) | development, a quick look | Node.js 22, PHP 8.1+ |
+| [Shared hosting](#shared-hosting) | a permanent site with HTTPS | PHP 8.1+ hosting with Apache or LiteSpeed |
+
+## Docker
+
+```bash
+git clone https://github.com/egmalt/house-planner.git
+cd house-planner
+docker compose up -d --build
+```
+
+Open <http://localhost:8080/>. On the first run the app asks you to finish setup: open `/api/setup.php` and set a password (at least 8 characters).
+
+**Password from the environment.** To skip the wizard, pass the password on the first start:
+
+```bash
+HOUSE_PASSWORD='a-long-password' docker compose up -d --build
+```
+
+The password is applied only when the storage is empty. Once installed, `HOUSE_PASSWORD` is ignored, so it is safe to leave it in your `.env`.
+
+**Port.** The container listens on `8080`; the host port is `HOUSE_PORT` (default `8080`):
+
+```bash
+HOUSE_PORT=9000 docker compose up -d
+```
+
+Compose also reads these variables from a `.env` file next to `docker-compose.yml`.
+
+**Data.** The config, the current plan, every version and every snapshot live in the named volume `house-data`, mounted at `/var/lib/house-planner`. Rebuilding the image and `docker compose restart` keep it. `docker compose down -v` deletes it, so do not use `-v` unless you mean it.
+
+**Changing the password.** Delete the config inside the volume and install again; the plan and history stay:
+
+```bash
+docker compose exec house-planner rm /var/lib/house-planner/config.php
+HOUSE_PASSWORD='new-password' docker compose up -d --force-recreate
+```
+
+or, without `HOUSE_PASSWORD`, run `docker compose restart` and open `/api/setup.php`. Existing logins stop working because the cookie token is regenerated.
+
+**Protecting the wizard.** Between the first start and setting the password, anyone who can reach the port can open `/api/setup.php`. Either start with `HOUSE_PASSWORD`, or set `HOUSE_SETUP_KEY` so the wizard asks for that key too.
+
+**Backup.**
+
+```bash
+docker compose exec -T house-planner tar -C /var/lib/house-planner -czf - . > house-backup-$(date +%F).tar.gz
+```
+
+**HTTPS.** The container serves plain HTTP. Put it behind a reverse proxy that terminates TLS (Caddy, Traefik, nginx) and forward to `HOUSE_PORT`. The login cookie gets the `Secure` flag when the request comes over HTTPS.
+
+## Local PHP server
+
+Development mode, no build needed. Two terminals:
+
+```bash
+npm i
+npm run dev:api # terminal 1: PHP API on 127.0.0.1:8000 from public/
+```
+
+```bash
+npm run dev # terminal 2: Vite on http://localhost:5173
+```
+
+Open <http://localhost:5173/api/setup.php>, keep the first storage option, set a password, then open <http://localhost:5173/>. Vite proxies `/api`, `/data` and `/plans` to PHP. The storage is `$HOUSE_STORAGE` if set, otherwise `./storage` in the repository root (git-ignored).
+
+`scripts/dev-router.php` repeats the `.htaccess` rules for the PHP built-in server (no direct access to `api/_*.php` and `storage/`, cookie check for `data/` and `plans/`). Still, the built-in server is for your own machine only.
+
+To run the production build locally instead: `npm run build && php -S 127.0.0.1:8000 -t dist`, then <http://127.0.0.1:8000/api/setup.php>.
+
+## Shared hosting
+
+Any hosting with PHP 8.1+ (with the `curl` extension, used by the Petrovich cart) and Apache or LiteSpeed with `mod_rewrite` works. Build locally, upload `dist/`, open `/api/setup.php`. Full walkthrough with `scripts/deploy.sh`, FTP, HTTPS, updates and backups: [deploy.md](deploy.md).
+
+## What setup does
+
+`/api/setup.php` runs once. It:
+
+1. Offers storage locations in order: `$HOUSE_STORAGE`, `<site root>/../storage` (outside the web root, preferred), `<site root>/storage` (inside, closed by `Require all denied`).
+2. Creates the storage folder with `config.php` (password hash, random cookie token, seed plan path, time zone).
+3. Writes `data/.htaccess` and `plans/.htaccess`, which return `401` without the login cookie.
+4. Returns `403` on every later visit.
+
+On the first API request the storage is seeded from `plans/demo.json`: a fictional Nordic single-storey house with a garage on a 30 × 45 m plot in Estonia. Replace it with your own plan in the editor, or import a JSON file from the "⋯" menu.
+
+## Requirements in short
+
+| Component | Version |
+|---|---|
+| Node.js (build only) | 22 |
+| PHP | 8.1+ with `json`, `curl` (for the Petrovich cart) |
+| Web server | Apache 2.4 or LiteSpeed with `mod_rewrite`; nginx works if you deny `/storage`, `/data`, `/plans` yourself |
+| Browser | a current Chrome, Firefox, Safari or Edge with WebGL 2 |
+
+Next: [usage guide](usage.md).
diff --git a/docs/guide/en/plan-via-chat.md b/docs/guide/en/plan-via-chat.md
new file mode 100644
index 0000000..1e940f3
--- /dev/null
+++ b/docs/guide/en/plan-via-chat.md
@@ -0,0 +1,84 @@
+# Editing the plan as JSON (and with an AI assistant)
+
+**English** | [Русский](../ru/plan-via-chat.md)
+
+The whole project — site, walls, openings, furniture, networks, estimate — is one JSON document in integer millimetres. Anything you can do in the editor you can also do by editing that file, by hand or with an LLM assistant. This is often faster for bulk or precise changes: "move all interior walls 50 mm", "add sockets every 2 m along the living room walls", "replace the wall material everywhere".
+
+## Two ways to get the file
+
+**From the browser.** «⋯» → «Экспорт JSON» downloads the current plan; «Импорт JSON» validates a file and saves it as a new revision. Good for one-off edits.
+
+**With scripts.** `scripts/plan-pull.sh` and `scripts/plan-push.sh` talk to the same API as the browser, so versioning and conflict detection work the same way. Good for repeated edits and for assistants that can run shell commands (Claude Code, Codex CLI, Aider and similar).
+
+## Setting up the scripts
+
+The scripts need `bash`, `curl` and `python3`. Create `.env.deploy` in the repository root (it is git-ignored) or export the variables:
+
+```bash
+HOUSE_URL=https://plan.example.com
+HOUSE_PASSWORD=your-planner-password
+```
+
+`HOUSE_URL` falls back to `DEPLOY_URL` if that is already set for deployment. For a local Docker run use `http://localhost:8080`.
+
+## The loop
+
+```bash
+scripts/plan-pull.sh # → plans/server.json
+# edit plans/server.json
+node scripts/plan-validate.mts plans/server.json # same zod schema as the app
+scripts/plan-push.sh # → new revision on the server
+```
+
+`plan-pull.sh` prints the revision, time, author and the number of walls and openings. `--rev N` fetches an older revision, `--out file` writes somewhere else. The `plans/` folder at the repository root is git-ignored.
+
+`plan-push.sh [file]` sends the file with `If-Match: <rev>`, taking `rev` from the file itself (pull puts it there) or from `--rev N`. The author label defaults to `cli`; set it with `--author`, for example `--author assistant`, so you can tell those revisions apart in «Версии».
+
+**Conflicts.** If the plan changed on the server after your pull, nothing is overwritten. The script saves the server copy as `plans/server.conflict.json` and exits with code `2`. Move your edits onto that copy (or pull again and repeat them) and push again.
+
+Open browser tabs pick up the new revision; if one of them was in the middle of an edit, it reapplies the edit on top of your version.
+
+## Working with an assistant
+
+Give the assistant three things:
+
+1. The format: [docs/plan-format.md](../../plan-format.md) (in Russian; any modern model reads it fine) and, for exact types, [src/model/schema.ts](../../../src/model/schema.ts).
+2. The current plan, `plans/server.json`.
+3. The rules below.
+
+A system prompt that works well:
+
+```text
+You edit a house plan stored as JSON (format: docs/plan-format.md, schema: src/model/schema.ts).
+Rules:
+- All coordinates and sizes are integer millimetres. Axes: X along plot side 0–1, Y points down on screen.
+- Walls are axis lines a→b; corners join only if the end points are exactly equal.
+- Openings reference walls by wallId; offset is measured from wall point a; offset + width must not exceed the wall length.
+- Every id is unique within its array; materialId and network material ids must exist.
+- Do not change rev, updatedAt, author: the server manages them; rev is the base revision for If-Match.
+- Change only what was asked. Keep unknown fields as they are.
+After editing run: node scripts/plan-validate.mts plans/server.json, fix errors, then scripts/plan-push.sh --author assistant.
+```
+
+If the assistant can run commands, let it run the whole loop: pull, edit, validate, push, and report the new revision. If it cannot, paste the JSON (or the relevant part) into the chat, take the result back, and validate and push it yourself.
+
+## Recipes
+
+| Request | What changes in JSON |
+|---|---|
+| "Add a 5 m wall from the house corner to the east" | new item in `walls` with `a` at the corner (copy it from an existing wall end) and `b = a + (5000, 0)` |
+| "A 1200 mm window centred on wall w2" | new item in `openings` with `wallId: "w2"`, `type: "window"`, `offset = (length of w2 − 1200) / 2`, `width: 1200`, `height`, `sill` |
+| "Make the bedroom door open the other way" | flip `side` (`left` ↔ `right`) or `hinge` (`start` ↔ `end`) of that door |
+| "Add a material from this product link" | new item in `materials` with `name`, `kind`, `thickness`, `price`, `pricePer`, `url`, `checkedAt`; then set `materialId` on the walls |
+| "Label the room at the south-west corner as Kitchen" | new item in `rooms` with a point inside the room and `kind: "kitchen"` |
+| "Mark the SIP panels as bought at 5400" | `estimate.purchases["auto:wall:sip-174"] = { "done": true, "actualPrice": 5400 }` |
+
+Length of a wall is not stored: it is `√((b.x − a.x)² + (b.y − a.y)²)`.
+
+## Pitfalls
+
+- An invalid plan is rejected by the app on load and by `plan-validate.mts`; always validate before pushing.
+- Deleting a wall in JSON does not delete its openings: remove them too, or validation fails on the dangling `wallId`.
+- If the server has `site-fixed.json`, the boundary, street side, geo-reference and locked zones come from that file; edits to them in JSON are silently replaced. See [docs/api.md](../../api.md).
+- Big plans fit in a chat, but for small changes it is cheaper to send only the relevant arrays and merge the answer back.
+- Every push is a new revision kept forever, so a bad push is fixed by restoring the previous revision in «Версии».
diff --git a/docs/guide/en/usage.md b/docs/guide/en/usage.md
new file mode 100644
index 0000000..98c1617
--- /dev/null
+++ b/docs/guide/en/usage.md
@@ -0,0 +1,67 @@
+# Using the planner
+
+**English** | [Русский](../ru/usage.md)
+
+The interface is in English and Russian; the language follows the browser and can be switched in "⋯" → Language. Labels below are the English ones.
+
+## Layout
+
+The header switches sections: "Plan", "3D", "Map", "Estimate" and "Plot & house" (site and house notes). The address is a hash (`#/plan`, `#/3d`, `#/map`, `#/estimate`, `#/info`), so each section can be bookmarked. On the right of the header: the save indicator and the "⋯" menu with JSON export/import and versions.
+
+Every finished edit is sent to the server immediately. If the save fails, the edit is rolled back to the server copy; if someone else changed the plan in the meantime, the app reloads the server plan and reapplies your edit on top.
+
+## Plan editor
+
+| Tool | Key | What it does |
+|---|---|---|
+| "Select" | `V` | select, drag wall ends, openings, furniture, zones |
+| "Wall" | `W` | click start, click end; walls chain until `Enter` or `Esc` |
+| "Door" | `D` | click on a wall; default 960×2070 entrance or 800×2000 interior door |
+| "Window" | `O` | click on a wall; default 1200×1400 with an 800 mm sill |
+| "Zone" | | click polygon vertices, `Enter` to finish: fill, lawn, paving |
+| "Building" | `B` | select the whole building to move or rotate it |
+| Ruler | `M` | click A, click B; hold `⌘`/`Ctrl` to chain segments |
+
+Other keys: `⌘Z` / `⌘⇧Z` (or `Ctrl`) undo and redo, `⌘A` select all on unlocked layers, `Delete` removes the selection, `Shift` snaps the angle to 45° steps while drawing, `F` flips a door or gate to the other side, `H` moves the door hinge, `R` rotates selected furniture, `Esc` cancels.
+
+Snapping works to wall ends and a 100 mm grid. Wall length, thickness, height and material are edited in the inspector on the right; lengths can be typed directly. Right-click inside a room and choose "Label room" to add a room label; the room outline and net area are found from the walls.
+
+**Furniture.** The "Furniture" button opens a catalog of items with real sizes: drag one onto the plan. Plumbing fixtures from it (toilet, sink, shower, washer, boiler) become endpoints for the sewer and water networks.
+
+**View.** Rotate the view in 15° steps, switch between "Plan up" and "North up", show the whole plot, show wall lengths permanently, and put the satellite image under the plan.
+
+**Summary.** "Summary" shows total and living area, number of rooms, bedrooms and bathrooms, footprint, height, plot coverage and wall cost.
+
+## Layers and networks
+
+"Layers" lists walls, furniture, zones and the four networks. Each layer can be hidden, dimmed or locked against accidental edits. The pencil next to a network enters its editor; `Esc` or the cross leaves it.
+
+**Sewer.** Modes: select, route, cleanout, riser, outlet, septic. Start a route on a fixture, click to add nodes, finish on a node. Where the route leaves the house the outlet is placed on the wall. Diameters and slopes get defaults (110 from the toilet down, 50 for the rest; 2 % inside, 1 % outside). The panel shows invert levels, the depth at the septic tank, fittings and warnings: slopes below СП 30.13330 minimums, shallow outside pipes, a septic tank closer than 5 m to the foundation or 1 m to the boundary.
+
+**Electrical.** Place the panel, sockets, switches and lights on walls, group them into circuits with breaker type, rating and cable. "Auto-route" routes cables from the panel along the walls. The calculation gives cable lengths per type, conduit, boxes, breakers, RCDs and panel size, and warns about oversized breakers, overloads, voltage drop over 5 %, wet zones without RCD, sockets in bathroom zones 0–2.
+
+**Water supply.** Draw cold, hot and recirculation lines; place a source, pump, filter, boiler and manifolds. Clicking a fixture runs a separate 16 mm PEX line from the nearest manifold. Checks cover burial depth without heating cable, distance to the sewer and from the well to the septic tank.
+
+**Underfloor heating.** "Lay out by rooms" lays out loops room by room: step by room type, fixed furniture cut out, edge loops at outside walls, loops over 80 m split, small loops merged when there are more than 12. The panel compares floor heat output with heat loss, gives loop lengths, flow settings and the mixing unit pump, and fills the estimate.
+
+## 3D
+
+"Mock-up" shows clean massing, "Materials" shows textures by wall material and facade finish. Cameras: 3/4, top, front. Wall cut: full height, 1 m, or floor only, to see the layout from above. Wall and accent colours are picked from the RAL palette and saved in the plan.
+
+## Map
+
+The plan is drawn over satellite imagery using `site.geo`. "Boundary from GeoJSON" takes a parcel polygon in longitude/latitude, computes the geo-reference and replaces the boundary. If the imagery is offset from the cadastral data, align it with the shift and rotation controls; only the imagery correction is stored, the plan does not move. Neighbouring parcels are drawn from `data/parcel.geojson` if that file exists. More in the [FAQ](faq.md#how-do-i-load-my-own-plot).
+
+## Estimate
+
+One A4 sheet: wall materials, doors, windows and gates, network groups, and manual lines. Prices come from `data/catalog.json` or from the plan's own materials. Tick "Purchased" to mark a line as bought and record the actual price. "Download CSV" exports a semicolon-separated file that opens in Excel. Print with the browser (`⌘P` / `Ctrl+P`): the sheet is laid out for A4. "Build Petrovich cart" builds carts on petrovich.ru, see the [FAQ](faq.md#how-does-the-petrovich-cart-work).
+
+## Versions and snapshots
+
+Every save is a numbered revision on the server. "⋯" → "Versions" shows two lists: "Saved" (named snapshots) and "All changes" (every revision with author and time). Create a snapshot with a name, restore any snapshot or revision: the restore is written as a new revision, nothing is lost.
+
+## Phone and tablet
+
+On screens narrower than 700 px or touch-only devices the app is read-only: you can view the plan, 3D, map and estimate, but nothing is written to the server.
+
+Next: [editing the plan as JSON](plan-via-chat.md).
diff --git a/docs/guide/ru/demo.md b/docs/guide/ru/demo.md
new file mode 100644
index 0000000..fdfb88a
--- /dev/null
+++ b/docs/guide/ru/demo.md
@@ -0,0 +1,37 @@
+# Публичное демо
+
+[English](../en/demo.md) | **Русский**
+
+Демо-режим превращает установку в открытую песочницу: планировщик открывается без пароля, правки видят все посетители, а раз в час план возвращается к исходному `plans/demo.json`. Так устроено демо на сайте проекта; для своего дома демо не нужно — ставьте обычную копию.
+
+## Что меняется
+
+Вход не нужен: API не спрашивает куку, экран пароля не показывается, `data/` и `plans/` открыты. Сверху страницы — тонкая плашка «Демо: изменения видят все и сбрасываются каждый час» со ссылкой на GitHub. Раз в час план сбрасывается к `plans/demo.json`, версии и снимки старше часа удаляются. Ограничения против злоупотреблений: план не больше 1 МБ, не больше 30 сохранений в минуту с одного IP (дальше `429`), не больше 20 снимков, корзина Петровича отключена (кнопка неактивна, API отвечает `403 demo_disabled`). Подробности и коды ответов — в [docs/api.md](../../api.md#демо-режим).
+
+## Docker
+
+```bash
+HOUSE_DEMO=1 docker compose up -d --build
+```
+
+Пароль задавать не нужно: загрузчик сам установит планировщик со случайным паролем и откроет `data/` и `plans/`. План сбрасывается лениво — первым запросом после того, как с прошлого сброса прошёл час.
+
+## Виртуальный хостинг
+
+Установите планировщик как обычно ([deploy.md](deploy.md)), затем допишите в `storage/config.php` ключ:
+
+```php
+'demo' => true,
+```
+
+и добавьте cron от пользователя веб-сервера:
+
+```cron
+0 * * * * php /home/user/house-planner/scripts/demo-reset.php --webroot=/home/user/www/plan.example.com
+```
+
+`--webroot` — корень сайта, куда залит `dist/`; скрипт берёт оттуда `api/_lib.php` и `plans/demo.json`, хранилище ищет так же, как API (`HOUSE_STORAGE`, `../storage`, `storage`). Первый запуск сразу открывает `data/` и `plans/`. Без cron работает ленивый сброс, как в Docker.
+
+## Как выключить
+
+Уберите ключ `demo` (или переменную `HOUSE_DEMO`), затем закройте статику заново: в Docker — `docker compose exec house-planner rm /var/lib/house-planner/config.php` и `HOUSE_PASSWORD=<пароль> docker compose up -d` (пароль демо-установки случайный и никому не известен), на хостинге — удалить `config.php` в хранилище и пройти `api/setup.php` с новым паролем (план и версии останутся). Токен куки после демо лучше сменить именно так: пока шло демо, `data/` и `plans/` были открыты.
diff --git a/docs/guide/ru/deploy.md b/docs/guide/ru/deploy.md
new file mode 100644
index 0000000..62494d0
--- /dev/null
+++ b/docs/guide/ru/deploy.md
@@ -0,0 +1,119 @@
+# Заливка на виртуальный хостинг
+
+[English](../en/deploy.md) | **Русский**
+
+Подойдёт любой хостинг с PHP 8.1+ (с `curl`) и Apache или LiteSpeed с `mod_rewrite`. Сайт — папка статики плюс `api/*.php`; план живёт в папке `storage/`, которую создаёт мастер установки. Про Docker — в [install.md](install.md#docker).
+
+## 1. Сборка
+
+```bash
+npm ci
+npm run build
+```
+
+Результат — `dist/`: `index.html`, `assets/`, `api/` (PHP), `data/` (каталог и страница участка), `plans/demo.json` (засев), `models/`, `textures/`. Пути относительные, сайт работает и в корне домена, и в подпапке.
+
+## 2. Заливка
+
+### Скриптом `scripts/deploy.sh`
+
+Скопируйте [`.env.deploy.example`](../../../.env.deploy.example) в `.env.deploy` и заполните. По SSH (rsync):
+
+```bash
+DEPLOY_URL=https://plan.example.com
+DEPLOY_METHOD=ssh
+DEPLOY_PATH=www/plan.example.com
+# DEPLOY_SSH_OPTS="-p 2222 -i ~/.ssh/id_ed25519"
+```
+
+По FTP (нужен `lftp`):
+
+```bash
+DEPLOY_METHOD=ftp
+FTP_HOST=ftp.example.com
+FTP_USER=...
+FTP_PASSWORD=...
+FTP_PATH=www/plan.example.com
+```
+
+Дальше:
+
+```bash
+scripts/deploy.sh # сборка, заливка, сверка
+scripts/deploy.sh --no-build # залить готовый dist/
+```
+
+Скрипт собирает проект, зеркалит `dist/` в корень сайта с удалением лишних файлов и сверяет каждый файл с сервером: по SSH — контрольные суммы, по FTP — размеры. `storage/`, `data/.htaccess` и `plans/.htaccess` на сервере он не трогает никогда. Замок не даёт запустить две заливки одновременно.
+
+### Вручную
+
+Залейте **содержимое** `dist/` в корень сайта любым FTP-клиентом. При обновлениях не удаляйте и не перезаписывайте `storage/` (если оно внутри корня сайта), `data/.htaccess` и `plans/.htaccess`: там хеш пароля и токен куки.
+
+## 3. Установка
+
+Откройте `https://plan.example.com/api/setup.php`:
+
+1. Выберите место хранилища. Предпочтительно вне корня сайта (`../storage`); внутри корня оно закрыто `.htaccess`.
+2. Задайте пароль не короче 8 символов.
+3. Готово: мастер пишет `storage/config.php`, закрывает `data/` и `plans/` кукой входа и дальше отвечает `403`.
+
+Чтобы между заливкой и первым заходом мастер не запустил кто-то другой, задайте в панели хостинга переменную окружения `HOUSE_SETUP_KEY` — мастер спросит этот ключ.
+
+## 4. HTTPS
+
+Включите сертификат в панели хостинга (Let's Encrypt обычно выдаётся одной кнопкой) и там же переадресацию HTTP → HTTPS. Кука входа получает `Secure` автоматически при запросе по HTTPS. Без HTTPS пароль идёт открытым текстом — для сайта в интернете этот шаг обязателен.
+
+## Что где лежит на сервере
+
+| Путь | Что | При заливке |
+|---|---|---|
+| `storage/config.php` | хеш пароля, токен куки, засев, часовой пояс | не трогается |
+| `storage/current.json` | текущий план | не трогается |
+| `storage/versions/`, `versions.jsonl` | все ревизии и их индекс | не трогается |
+| `storage/snapshots/`, `snapshots.jsonl` | именованные снимки | не трогается |
+| `storage/site-fixed.json` | необязательные неизменяемые данные участка (граница, привязка, улица, закреплённые зоны) | не трогается |
+| `data/.htaccess`, `plans/.htaccess` | проверка куки для файлов данных, пишет мастер | не трогается |
+| `data/catalog.json` | каталог цен | заменяется из `public/data/` |
+| `data/house.json` | страница «Участок и дом» | заменяется из `public/data/` |
+| `data/parcel.geojson` | необязательные смежные участки для карты | заменяется из `public/data/`, удаляется, если его там нет |
+| `plans/demo.json` | засев пустого хранилища | заменяется |
+
+Свои `house.json`, `catalog.json` и `parcel.geojson` держите локально в `public/data/`, иначе следующая заливка перезапишет или удалит серверные копии. Если в них личные данные, не добавляйте их в git (например, через `.git/info/exclude`).
+
+## nginx
+
+На nginx `.htaccess` не работает. Вынесите хранилище за корень сайта и закройте папки с данными сами, пропуская только запросы с кукой входа:
+
+```nginx
+location ^~ /storage/ { deny all; }
+location ~ ^/api/_ { deny all; }
+location ~ ^/(data|plans)/ {
+ if ($cookie_hauth != "<токен из storage/config.php>") { return 401; }
+}
+location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/run/php/php-fpm.sock; }
+```
+
+## Обновление
+
+```bash
+git pull
+npm ci
+scripts/deploy.sh
+```
+
+План, версии и пароль сохраняются. Если менялся формат плана, новые клиент и сервер вместе поднимают минимальную версию клиента; старые открытые вкладки сами перезагружаются, а не затирают новые поля. Перед обновлением загляните в [CHANGELOG.md](../../../CHANGELOG.md).
+
+## Резервные копии
+
+Всё ценное — папка хранилища. Копируйте её целиком, например:
+
+```bash
+ssh [email protected] 'tar -C www -czf - storage' > house-backup-$(date +%F).tar.gz
+```
+
+Быстрая копия одного плана — «⋯» → «Экспорт JSON» или `scripts/plan-pull.sh`. Восстановление — вернуть папку на место или импортировать JSON новой ревизией.
+
+## Смена пароля
+
+Удалите `config.php` в хранилище и снова откройте `/api/setup.php`. План и история остаются; прежние входы перестают действовать, потому что создаётся новый токен куки.
diff --git a/docs/guide/ru/faq.md b/docs/guide/ru/faq.md
new file mode 100644
index 0000000..2751487
--- /dev/null
+++ b/docs/guide/ru/faq.md
@@ -0,0 +1,83 @@
+# Частые вопросы
+
+[English](../en/faq.md) | **Русский**
+
+### Нужен ли сервер и база данных?
+
+Нужен веб-сервер с PHP 8.1+, базы данных не нужно. План, его версии и конфигурация — обычные файлы в папке `storage/`. Хватит дешёвого виртуального хостинга с Apache или LiteSpeed, Docker-образа или `php -S` на своём компьютере. Node.js нужен только для сборки. См. [install.md](install.md).
+
+### Как сменить пароль?
+
+Удалите `config.php` в хранилище и снова откройте `/api/setup.php`. План и история остаются, все входы сбрасываются: создаётся новый токен куки. В Docker: `docker compose exec house-planner rm /var/lib/house-planner/config.php`, затем перезапуск с новым `HOUSE_PASSWORD` или мастер. Подробно — [install.md](install.md#docker), [deploy.md](deploy.md#смена-пароля).
+
+### Можно ли нескольким людям? Есть ли учётные записи?
+
+Пароль один на установку, учётных записей и ролей нет: кто знает пароль, тот и правит. Одновременная работа при этом безопасна: каждое сохранение несёт ревизию, от которой правили, поэтому две вкладки, два человека или скрипт молча друг друга не перезапишут. У каждой ревизии есть метка автора (`web`, `cli` или то, что задано в `plan-push.sh --author`). Для разных проектов поднимайте разные установки: другая папка на хостинге или другой Docker-контейнер со своим портом и томом.
+
+### Где хранятся данные и как делать резервные копии?
+
+В папке хранилища: `config.php`, `current.json` (текущий план), `versions/` (все сохранённые ревизии, хранятся всегда), `snapshots/` (именованные снимки). На хостинге это обычно `../storage` рядом с корнем сайта, в Docker — том `house-data`. Копируйте папку целиком. Копия одного плана — «⋯» → «Экспорт JSON» или `scripts/plan-pull.sh`. Команды — в [deploy.md](deploy.md#резервные-копии).
+
+### Как обновиться?
+
+`git pull`, `npm ci`, `scripts/deploy.sh` (или залить новый `dist/` вручную, не трогая `storage/`, `data/.htaccess`, `plans/.htaccess`). В Docker: `git pull && docker compose up -d --build`. Хранилище не затрагивается. Перед обновлением загляните в [CHANGELOG.md](../../../CHANGELOG.md).
+
+### Как загрузить свой участок?
+
+1. Получите полигон участка в GeoJSON в долготе и широте (WGS84): выгрузите из публичной кадастровой карты (НСПД) или нарисуйте в любой ГИС (QGIS, geojson.io).
+2. Откройте «Карта», разверните «Граница из GeoJSON», вставьте `Polygon`, `Feature` или `FeatureCollection`, оставьте «Вычислить geo по полигону» и выберите вершину, которая станет началом координат плана.
+3. «Пересчитать», проверьте площадь и размеры, затем «Применить к плану». Граница станет `site.boundary` в миллиметрах, а `site.geo` привяжет план к карте.
+4. Если спутниковый снимок сдвинут относительно границы, выровняйте снимок сдвигом и поворотом; хранится только поправка снимка.
+
+Смежные участки показываются из `public/data/parcel.geojson` (`FeatureCollection`). Чтобы юридическую границу нельзя было сдвинуть ни из редактора, ни скриптом, положите в хранилище `site-fixed.json` — пример в `storage.example/site-fixed.example.json`, описание в [docs/api.md](../../api.md).
+
+### Как добавить материал в каталог?
+
+Каталог — `public/data/catalog.json`, массив позиций:
+
+```json
+{ "id": "block-d500-600x300x200", "name": "Газобетонный блок D500 600×300×200", "kind": "block",
+ "vendor": "Название магазина", "url": "https://…", "sku": "123456",
+ "thickness": 300, "length": 600, "height": 200,
+ "price": 290, "unit": "шт", "checkedAt": "2026-10-01" }
+```
+
+`kind` определяет, где позиция используется (`sip`, `pir`, `block`, `timber`, `door`, `window`, `gate`, `insulation`, `sewer`, `water`, `heating`, `electric` и другие); `unit` — `шт`, `м²`, `м` и т. д.; `preferred: true` выигрывает у более дешёвых совпадений; `sku` — код товара Петровича. Правила подбора для каждой сети — в [docs/plan-format.md](../../plan-format.md). Каталог грузится при работе, поэтому после правки достаточно залить `data/catalog.json`, пересборка не нужна. Материал, нужный только в одном плане, можно вместо этого добавить в `materials` самого плана с `price`.
+
+### Цены настоящие?
+
+Это пример, собранный по магазинам Санкт-Петербурга на дату из поля `checkedAt` каждой позиции. Это не оферта, цены устаревают и могут не подходить для вашего региона. Считайте каталог шаблоном и ведите свой.
+
+### Насколько можно доверять проверкам по нормам?
+
+Это справочные проверки по СП 30.13330, ПУЭ, ГОСТ Р 50571, СанПиН и упрощённые инженерные формулы. Они рано ловят типичные ошибки, но не заменяют проект, сделанный специалистом, и местные требования.
+
+### Работает ли на телефоне?
+
+Да, на просмотр. На экране уже 700 px или на устройстве только с сенсором приложение переходит в режим просмотра: план, 3D, карта, смета и страница участка работают, на сервер ничего не пишется. Для правки нужна мышь или тачпад.
+
+### Как работает корзина Петровича?
+
+«Смета» → «Собрать корзину в Петровиче». Серверный `api/petrovich-cart.php` открывает анонимную сессию на petrovich.ru, находит товары по кодам, кладёт их в корзину, получает публичную ссылку на смету и очищает корзину. Ссылка выдаётся на каждый раздел (дом, гараж, электрика, канализация, водопровод, тёплый пол, прочее); открыть её может кто угодно и одной кнопкой перенести позиции в свою корзину.
+
+Ограничения:
+
+- Попадают только позиции с кодом товара Петровича (`sku` или ссылка вида `petrovich.ru/product/<код>/`). Другие магазины пропускаются.
+- Два города: Санкт-Петербург и Выборг. Чего нет в наличии в выбранном городе, пропускается и показывается списком.
+- До 150 разных позиций за запрос, один запрос за раз (второй получает `429`), предел 120 с.
+- Цены в ответе — розничные цены Петровича без скидок корзины.
+- Используется API сайта Петровича, а не официальная интеграция: может сломаться при их изменениях, а защита от ботов может заблокировать IP хостинга (`502 petrovich_blocked`).
+- Каждый вызов создаёт у них новую смету, удалить её анонимно нельзя, поэтому не дёргайте в цикле.
+- Нужно расширение PHP `curl`.
+
+### Можно ли без интернета?
+
+В основном да. Запущенный локально (Docker или `php -S`) редактор, 3D, сети и смета работают в локальной сети без выхода в интернет. Интернет нужен для спутниковой подложки (тайлы Esri World Imagery), корзины Петровича и ссылок на товары. Шрифты и скрипты со сторонних CDN приложение не грузит.
+
+### На каких языках интерфейс?
+
+На английском и русском. Язык берётся из браузера и переключается в меню «⋯» → «Язык», выбор запоминается. Переводы на другие языки приветствуются: строки лежат в `src/i18n/locales/<язык>/`, см. [CONTRIBUTING.md](../../../CONTRIBUTING.md).
+
+### Какая лицензия?
+
+[MIT](../../../LICENSE): можно использовать, менять и размещать, в том числе в коммерческих целях, сохраняя уведомление об авторских правах. У текстур и моделей мебели свои лицензии — в `public/textures/LICENSE.txt` и `public/models/furniture/LICENSES.md`.
diff --git a/docs/guide/ru/install.md b/docs/guide/ru/install.md
new file mode 100644
index 0000000..701eb71
--- /dev/null
+++ b/docs/guide/ru/install.md
@@ -0,0 +1,103 @@
+# Установка
+
+[English](../en/install.md) | **Русский**
+
+House Planner — статическое React-приложение и небольшой PHP API, который хранит план в файлах. Базы данных нет, Node.js на сервере не нужен. Запустить можно тремя способами.
+
+| Способ | Для чего | Что нужно |
+|---|---|---|
+| [Docker](#docker) | домашний сервер, VPS, попробовать | Docker с Compose |
+| [Локальный PHP-сервер](#локальный-php-сервер) | разработка, быстрый просмотр | Node.js 22, PHP 8.1+ |
+| [Виртуальный хостинг](#виртуальный-хостинг) | постоянный сайт с HTTPS | хостинг с PHP 8.1+ и Apache или LiteSpeed |
+
+## Docker
+
+```bash
+git clone https://github.com/egmalt/house-planner.git
+cd house-planner
+docker compose up -d --build
+```
+
+Откройте <http://localhost:8080/>. При первом запуске приложение попросит завершить установку: откройте `/api/setup.php` и задайте пароль (не короче 8 символов).
+
+**Пароль через окружение.** Чтобы обойтись без мастера, передайте пароль при первом старте:
+
+```bash
+HOUSE_PASSWORD='длинный-пароль' docker compose up -d --build
+```
+
+Пароль применяется, только пока хранилище пустое. После установки `HOUSE_PASSWORD` ни на что не влияет, его можно оставить в `.env`.
+
+**Порт.** Внутри контейнера — `8080`, порт на хосте задаёт `HOUSE_PORT` (по умолчанию `8080`):
+
+```bash
+HOUSE_PORT=9000 docker compose up -d
+```
+
+Эти переменные Compose читает и из файла `.env` рядом с `docker-compose.yml`.
+
+**Данные.** Конфигурация, текущий план, все версии и снимки лежат в именованном томе `house-data`, смонтированном в `/var/lib/house-planner`. Пересборка образа и `docker compose restart` их не трогают. `docker compose down -v` том удаляет — без нужды `-v` не используйте.
+
+**Смена пароля.** Удалите конфигурацию в томе и установите заново, план и история останутся:
+
+```bash
+docker compose exec house-planner rm /var/lib/house-planner/config.php
+HOUSE_PASSWORD='новый-пароль' docker compose up -d --force-recreate
+```
+
+или без `HOUSE_PASSWORD`: `docker compose restart` и мастер `/api/setup.php`. Прежние входы перестают действовать: токен куки создаётся новый.
+
+**Защита мастера.** Пока пароль не задан, `/api/setup.php` может открыть любой, у кого есть доступ к порту. Либо стартуйте сразу с `HOUSE_PASSWORD`, либо задайте `HOUSE_SETUP_KEY` — тогда мастер дополнительно спросит этот ключ.
+
+**Резервная копия.**
+
+```bash
+docker compose exec -T house-planner tar -C /var/lib/house-planner -czf - . > house-backup-$(date +%F).tar.gz
+```
+
+**HTTPS.** Контейнер отдаёт обычный HTTP. Поставьте перед ним обратный прокси с TLS (Caddy, Traefik, nginx) и направьте его на `HOUSE_PORT`. Кука входа получает флаг `Secure`, когда запрос пришёл по HTTPS.
+
+## Локальный PHP-сервер
+
+Режим разработки, сборка не нужна. Два терминала:
+
+```bash
+npm i
+npm run dev:api # терминал 1: PHP API на 127.0.0.1:8000 из public/
+```
+
+```bash
+npm run dev # терминал 2: Vite на http://localhost:5173
+```
+
+Откройте <http://localhost:5173/api/setup.php>, оставьте первый вариант хранилища, задайте пароль и откройте <http://localhost:5173/>. Vite проксирует `/api`, `/data` и `/plans` на PHP. Хранилище — `$HOUSE_STORAGE`, если задан, иначе `./storage` в корне репозитория (в `.gitignore`).
+
+`scripts/dev-router.php` повторяет правила `.htaccess` для встроенного сервера PHP (нет прямого доступа к `api/_*.php` и `storage/`, проверка куки для `data/` и `plans/`). Но встроенный сервер всё равно только для своей машины.
+
+Проверить боевую сборку локально: `npm run build && php -S 127.0.0.1:8000 -t dist`, затем <http://127.0.0.1:8000/api/setup.php>.
+
+## Виртуальный хостинг
+
+Подойдёт любой хостинг с PHP 8.1+ (с расширением `curl` — для корзины Петровича) и Apache или LiteSpeed с `mod_rewrite`. Собрать локально, залить `dist/`, открыть `/api/setup.php`. Подробно про `scripts/deploy.sh`, FTP, HTTPS, обновления и резервные копии — в [deploy.md](deploy.md).
+
+## Что делает мастер установки
+
+`/api/setup.php` запускается один раз:
+
+1. Предлагает место хранилища по порядку: `$HOUSE_STORAGE`, `<корень сайта>/../storage` (вне корня сайта, предпочтительно), `<корень сайта>/storage` (внутри, закрыто `Require all denied`).
+2. Создаёт папку хранилища и `config.php` в ней: хеш пароля, случайный токен куки, путь к засеву, часовой пояс.
+3. Пишет `data/.htaccess` и `plans/.htaccess`, которые без куки входа отвечают `401`.
+4. При следующих заходах отвечает `403`.
+
+Первый запрос к API засевает хранилище из `plans/demo.json`: вымышленный одноэтажный дом в северном стиле с гаражом на участке 30 × 45 м в Эстонии. Замените его своим планом в редакторе или импортируйте JSON из меню «⋯».
+
+## Требования кратко
+
+| Компонент | Версия |
+|---|---|
+| Node.js (только сборка) | 22 |
+| PHP | 8.1+ с `json` и `curl` (для корзины Петровича) |
+| Веб-сервер | Apache 2.4 или LiteSpeed с `mod_rewrite`; на nginx закройте `/storage`, `/data`, `/plans` в его конфигурации |
+| Браузер | свежий Chrome, Firefox, Safari или Edge с WebGL 2 |
+
+Дальше: [работа с планировщиком](usage.md).
diff --git a/docs/guide/ru/plan-via-chat.md b/docs/guide/ru/plan-via-chat.md
new file mode 100644
index 0000000..901ce19
--- /dev/null
+++ b/docs/guide/ru/plan-via-chat.md
@@ -0,0 +1,84 @@
+# Правка плана через JSON и с ИИ-ассистентом
+
+[English](../en/plan-via-chat.md) | **Русский**
+
+Весь проект — участок, стены, проёмы, мебель, сети, смета — это один JSON-документ в целых миллиметрах. Всё, что делается в редакторе, можно сделать правкой этого файла руками или с ИИ-ассистентом. Для массовых и точных правок так часто быстрее: «сдвинь все внутренние стены на 50 мм», «розетки через каждые 2 м по стенам гостиной», «замени материал стен везде».
+
+## Два способа получить файл
+
+**Из браузера.** «⋯» → «Экспорт JSON» скачивает текущий план; «Импорт JSON» проверяет файл и сохраняет его новой ревизией. Подходит для разовых правок.
+
+**Скриптами.** `scripts/plan-pull.sh` и `scripts/plan-push.sh` ходят в тот же API, что и браузер, поэтому версии и проверка конфликтов работают так же. Подходит для регулярных правок и для ассистентов, которые умеют запускать команды (Claude Code, Codex CLI, Aider и подобные).
+
+## Настройка скриптов
+
+Нужны `bash`, `curl` и `python3`. Создайте `.env.deploy` в корне репозитория (он в `.gitignore`) или задайте переменные окружения:
+
+```bash
+HOUSE_URL=https://plan.example.com
+HOUSE_PASSWORD=пароль-планировщика
+```
+
+Если `HOUSE_URL` не задан, берётся `DEPLOY_URL` из настроек заливки. Для локального Docker — `http://localhost:8080`.
+
+## Цикл правки
+
+```bash
+scripts/plan-pull.sh # → plans/server.json
+# правка plans/server.json
+node scripts/plan-validate.mts plans/server.json # та же zod-схема, что в приложении
+scripts/plan-push.sh # → новая ревизия на сервере
+```
+
+`plan-pull.sh` печатает ревизию, время, автора, число стен и проёмов. `--rev N` забирает старую ревизию, `--out файл` пишет в другой файл. Папка `plans/` в корне репозитория в `.gitignore`.
+
+`plan-push.sh [файл]` отправляет файл с `If-Match: <rev>`; `rev` берётся из самого файла (его туда кладёт pull) или из `--rev N`. Метка автора по умолчанию `cli`, задаётся `--author`, например `--author assistant` — так правки ассистента видны в «Версиях».
+
+**Конфликты.** Если после pull план на сервере изменился, ничего не перезаписывается: скрипт сохраняет серверную копию в `plans/server.conflict.json` и выходит с кодом `2`. Перенесите правки на эту копию (или сделайте pull и повторите их) и отправьте снова.
+
+Открытые вкладки подхватывают новую ревизию; если в какой-то шла правка, она повторяется поверх вашей версии.
+
+## Работа с ассистентом
+
+Дайте ассистенту три вещи:
+
+1. Формат: [docs/plan-format.md](../../plan-format.md) и для точных типов — [src/model/schema.ts](../../../src/model/schema.ts).
+2. Текущий план, `plans/server.json`.
+3. Правила ниже.
+
+Системный промпт, который хорошо работает:
+
+```text
+Ты правишь план дома в JSON (формат — docs/plan-format.md, схема — src/model/schema.ts).
+Правила:
+- Все координаты и размеры — целые миллиметры. Ось X — вдоль стороны участка 0–1, ось Y — вниз по экрану.
+- Стена — осевая линия a→b; углы сходятся, только если концы совпадают точно.
+- Проём ссылается на стену через wallId; offset — от точки a стены; offset + width не больше длины стены.
+- Все id уникальны в своём массиве; materialId и id материалов сетей должны существовать.
+- Не трогай rev, updatedAt, author: их ведёт сервер; rev — базовая ревизия для If-Match.
+- Меняй только то, о чём просили. Незнакомые поля оставляй как есть.
+После правки запусти node scripts/plan-validate.mts plans/server.json, исправь ошибки, затем scripts/plan-push.sh --author assistant.
+```
+
+Если ассистент умеет запускать команды, пусть проходит цикл целиком: pull, правка, проверка, push и отчёт с новой ревизией. Если не умеет — вставьте JSON (или нужную часть) в чат, заберите результат, проверьте и отправьте сами.
+
+## Типовые правки
+
+| Просьба | Что меняется в JSON |
+|---|---|
+| «Добавь стену 5 м из угла дома на восток» | новая запись в `walls`: `a` — в углу (координаты из конца существующей стены), `b = a + (5000, 0)` |
+| «Окно 1200 по центру стены w2» | новая запись в `openings`: `wallId: "w2"`, `type: "window"`, `offset = (длина w2 − 1200) / 2`, `width: 1200`, `height`, `sill` |
+| «Пусть дверь в спальню открывается в другую сторону» | поменять `side` (`left` ↔ `right`) или `hinge` (`start` ↔ `end`) у этой двери |
+| «Добавь материал по ссылке» | новая запись в `materials`: `name`, `kind`, `thickness`, `price`, `pricePer`, `url`, `checkedAt`; затем `materialId` у нужных стен |
+| «Подпиши комнату в юго-западном углу как кухню» | новая запись в `rooms`: точка внутри комнаты, `kind: "kitchen"` |
+| «Отметь СИП-панели купленными по 5400» | `estimate.purchases["auto:wall:sip-174"] = { "done": true, "actualPrice": 5400 }` |
+
+Длина стены не хранится, она равна `√((b.x − a.x)² + (b.y − a.y)²)`.
+
+## Подводные камни
+
+- Невалидный план приложение не загрузит, а `plan-validate.mts` не пропустит — проверяйте перед отправкой.
+- Удаление стены в JSON не удаляет её проёмы: уберите их тоже, иначе проверка упадёт на несуществующем `wallId`.
+- Если на сервере лежит `site-fixed.json`, граница, сторона улицы, геопривязка и закреплённые зоны берутся из него, правки этих полей в JSON молча заменяются. См. [docs/api.md](../../api.md).
+- Большой план помещается в чат, но для мелких правок дешевле передавать только нужные массивы и вливать ответ обратно.
+- Каждый push — новая ревизия, которая хранится всегда; неудачную отправку откатывают восстановлением прошлой ревизии в «Версиях».
diff --git a/docs/guide/ru/usage.md b/docs/guide/ru/usage.md
new file mode 100644
index 0000000..c6d65d9
--- /dev/null
+++ b/docs/guide/ru/usage.md
@@ -0,0 +1,67 @@
+# Работа с планировщиком
+
+[English](../en/usage.md) | **Русский**
+
+## Устройство экрана
+
+Интерфейс на английском и русском: язык берётся из браузера и переключается в «⋯» → «Язык». Ниже — подписи русской версии.
+
+Разделы переключаются в шапке: «План», «3D», «Карта», «Смета», «Участок и дом». Адрес раздела — hash (`#/plan`, `#/3d`, `#/map`, `#/estimate`, `#/info`), любой раздел можно добавить в закладки. Справа в шапке — индикатор сохранения и меню «⋯»: экспорт и импорт JSON, версии.
+
+Каждая завершённая правка сразу уходит на сервер. Не записалось — правка откатывается к серверной копии. Если план за это время изменили в другой вкладке или скриптом, приложение перечитывает серверный план и повторяет правку поверх.
+
+## Редактор плана
+
+| Инструмент | Клавиша | Что делает |
+|---|---|---|
+| «Выбор» | `V` | выделение, перетаскивание концов стен, проёмов, мебели, зон |
+| «Стена» | `W` | клик — начало, клик — конец; стены идут цепочкой до `Enter` или `Esc` |
+| «Дверь» | `D` | клик по стене; входная 960×2070 или межкомнатная 800×2000 |
+| «Окно» | `O` | клик по стене; 1200×1400 с подоконником 800 |
+| «Зона» | | вершины кликами, `Enter` — готово: отсыпка, газон, мощение |
+| «Здание» | `B` | выделить дом целиком, чтобы сдвинуть или повернуть |
+| Линейка | `M` | клик A, клик B; с `⌘`/`Ctrl` — цепочка отрезков |
+
+Ещё: `⌘Z` / `⌘⇧Z` (или `Ctrl`) — отмена и повтор, `⌘A` — выделить всё на незаблокированных слоях, `Delete` — удалить выделенное, `Shift` — шаг угла 45° при рисовании, `F` — перевернуть дверь или ворота на другую сторону, `H` — перевесить петли двери, `R` — повернуть мебель, `Esc` — отмена.
+
+Привязка — к концам стен и к сетке 100 мм. Длина, толщина, высота и материал стены правятся в инспекторе справа, длину можно ввести числом. Правый клик внутри комнаты → «Подписать комнату»: контур и площадь в чистоте редактор находит по стенам.
+
+**Мебель.** Кнопка «Мебель» открывает каталог предметов с реальными размерами, их перетаскивают на план. Сантехника из каталога (унитаз, раковина, душ, стиралка, котёл) служит точками подключения для канализации и водопровода.
+
+**Вид.** Поворот вида шагом 15°, «План вверх» и «Север вверх», показать весь участок, всегда показывать длины стен, спутниковый снимок под планом.
+
+**Сводка.** Общая и жилая площадь, число комнат, спален и санузлов, пятно застройки, высота, процент застройки участка, стоимость стен.
+
+## Слои и сети
+
+В «Слоях» — стены, мебель, зоны и четыре сети. Любой слой можно скрыть, приглушить или заблокировать от случайных правок. Карандаш у сети включает её редактор, выход — `Esc` или крестик.
+
+**Канализация.** Режимы: выбор, трасса, ревизия, стояк, выпуск, септик. Трасса начинается с прибора, клики ставят узлы, заканчивается на узле. Где трасса выходит из дома, выпуск ставится сам на пересечении со стеной. Диаметры и уклоны по умолчанию: 110 от унитаза и ниже по стоку, остальное 50; 2 % внутри, 1 % снаружи. В панели — отметки лотка, глубина входа в септик, фитинги и предупреждения: уклон меньше минимума по СП 30.13330, мелкая наружная труба, септик ближе 5 м к фундаменту или 1 м к границе.
+
+**Электрика.** Щит, розетки, выключатели и светильники ставятся на стены и собираются в группы с типом автомата, номиналом и кабелем. «Автотрасса» прокладывает кабель от щита по стенам. Расчёт даёт длины кабеля по маркам, гофру, подрозетники, автоматы, УЗО и размер щита и предупреждает о завышенном автомате, перегрузке, падении напряжения больше 5 %, мокрых группах без УЗО, розетках в зонах 0–2 санузла (ПУЭ, ГОСТ Р 50571.7.701).
+
+**Водопровод.** Линии холодной, горячей воды и рециркуляции; источник, насос, фильтр, бойлер, коллекторы. Клик по прибору — отдельная линия Ø16 PEX от ближайшего коллектора. Проверки: глубина наружной трубы без греющего кабеля, расстояние до канализации, от скважины до септика.
+
+**Тёплый пол.** «Разложить по комнатам» раскладывает петли: шаг по типу комнаты, неподвижная мебель вырезается, краевые петли у наружных стен, петли длиннее 80 м режутся, мелкие объединяются, если петель больше 12. В панели — теплоотдача пола против теплопотерь, длины петель, настройки расходомеров, насос смесительного узла; всё уходит в смету.
+
+## 3D
+
+«Макет» — чистые объёмы, «Материалы» — текстуры по материалу стен и отделке фасада. Камеры: 3/4, сверху, спереди. Срез стен: полные, 1 м или только пол — чтобы смотреть планировку сверху. Цвет стен и акцента выбирается из палитры RAL и сохраняется в плане.
+
+## Карта
+
+План рисуется поверх спутникового снимка по `site.geo`. «Граница из GeoJSON» принимает полигон участка в долготе и широте, вычисляет привязку и заменяет границу. Если снимок сдвинут относительно кадастра, его выравнивают сдвигом и поворотом; хранится только поправка снимка, план не двигается. Смежные участки рисуются из `data/parcel.geojson`, если такой файл есть. Подробнее — в [FAQ](faq.md#как-загрузить-свой-участок).
+
+## Смета
+
+Один лист A4: материалы стен, двери, окна и ворота, группы сетей, ручные позиции. Цены — из `data/catalog.json` или из материалов самого плана. Галочка «Куплено» отмечает позицию и запоминает фактическую цену. «Скачать CSV» — файл с разделителем `;`, открывается в Excel. Печать — обычной печатью браузера (`⌘P` / `Ctrl+P`), лист свёрстан под A4. «Собрать корзину в Петровиче» — см. [FAQ](faq.md#как-работает-корзина-петровича).
+
+## Версии и снимки
+
+Каждое сохранение — пронумерованная ревизия на сервере. «⋯» → «Версии»: «Сохранённые» (именованные снимки) и «Все изменения» (каждая ревизия с автором и временем). Снимок создаётся с именем; восстановить можно любой снимок или ревизию — восстановление пишется новой ревизией, ничего не теряется.
+
+## Телефон и планшет
+
+На экране уже 700 px или на устройстве только с сенсором приложение работает на просмотр: план, 3D, карта и смета видны, на сервер ничего не пишется.
+
+Дальше: [правка плана через JSON](plan-via-chat.md).
diff --git a/docs/plan-format.md b/docs/plan-format.md
new file mode 100644
index 0000000..a6c3147
--- /dev/null
+++ b/docs/plan-format.md
@@ -0,0 +1,194 @@
+# Формат плана
+
+План — один JSON-документ. Живая копия хранится на сервере (`/api/plan.php`, см. `docs/api.md`), `public/plans/demo.json` — только начальный засев хранилища (демо-план с вымышленным участком). Клиент валидирует план zod-схемой из `src/model/schema.ts` (это источник истины; при расхождении с этим документом верна схема). Все длины и координаты — **целые миллиметры**. Соглашение осей `y-down-clockwise`: начало `(0, 0)` в вершине 0 участка, ось **X** — вдоль стороны 0–1, ось **Y** — X, повёрнутая на 90° по часовой при взгляде сверху, то есть вниз по экрану (как в Konva и three.js). В демо-плане улица — внизу плана (большие `y`). Для 3D: `x → x`, `y → z`, высота — отдельное поле `height`.
+
+**Как править вне браузера.** `scripts/plan-pull.sh` → правка `plans/server.json` → `scripts/plan-push.sh`. План хранится только на сервере: каждая завершённая правка в редакторе сразу уходит PUT, в браузере ничего не сохраняется. Если записать не удалось, правка откатывается к серверной версии; при конфликте (план изменили в другой вкладке или скриптом) клиент перечитывает серверный план и повторяет свою правку поверх. На телефоне (ширина < 700 px или сенсорный экран без мыши) редактор работает только на просмотр и на сервер ничего не пишет. Невалидный план клиент не загрузит, поэтому проверяйте ссылки `wallId`/`materialId`. Проём, вылезший за стену после её укорачивания, редактор сдвигает к концу стены.
+
+## Верхний уровень
+
+```json
+{ "version": 1, "name": "…", "site": {…}, "materials": [], "walls": [], "openings": [], "estimate": {…}, "networks": {…} }
+```
+
+`version` — всегда `1`. `name` — название плана, показывается в шапке. `rev`, `updatedAt`, `author` ставит сервер при каждой записи (присланные значения он затирает); `rev` нужен как `If-Match` при записи. `resetEpoch` — номер сброса: если у локальной копии в браузере он меньше, чем в засеве `public/plans/demo.json`, копия отбрасывается (сохраняется в локальных версиях «до сброса») и берётся серверный план или засев.
+
+## site — участок
+
+| поле | тип | смысл |
+|---|---|---|
+| `width`, `depth` | мм | габарит участка по X и по Y (для рамки, если нет `boundary`) |
+| `boundary` | `[{x,y}, …]`, ≥3 точек, необяз. | реальный полигон границы в мм плана; если задан, рисуется вместо прямоугольника |
+| `geo` | `{ lat, lng, rotationDeg }`, необяз. | геопривязка: `lat/lng` — точка начала координат плана `(0,0)`, `rotationDeg` — угол оси X плана от направления на восток против часовой, в градусах (ось Y — X, повёрнутая на 90° по часовой) |
+| `convention` | строка | соглашение осей, сейчас всегда `y-down-clockwise` |
+| `zones` | `[{ id, name, kind, polygon }]`, необяз. | зоны участка: `kind` — `fill` (отсыпка), `lawn` (газон), `paving` (мощение), `other`; `polygon` — вершины в мм плана (≥3), без повтора первой точки; `locked: true` — зона из данных участка (например, отсыпка), её накладывает сервер, редактор её только показывает |
+| `street` | `{ side: [i, j], note? }`, необяз. | сторона участка к улице — индексы вершин `boundary` |
+| `imagery` | `{ offsetE, offsetN, rotationDeg }`, необяз. | поправка спутникового снимка относительно кадастра (сдвиг в м на восток/север и поворот); кадастр и план не двигаются |
+| `note` | строка, необяз. | заметка |
+
+## materials — материалы
+
+```json
+{ "id": "sip-174", "name": "СИП-панель OSB-3, 174 мм", "kind": "sip", "thickness": 174,
+ "panelWidth": 1250, "panelHeight": 2500, "price": 5510, "pricePer": "pcs",
+ "url": "https://prosip.ru/kupit-sip-panely", "source": "prosip.ru, СПб", "checkedAt": "2026-09-30", "color": "#e8b86a", "note": "…" }
+```
+
+Обязательны `id`, `name`, `kind`, `thickness`. `kind`: `sip | pir | brick | block | timber | frame | concrete | glass | other` — от него зависит цвет стены на плане, если не задан `color`. `unitLength`×`unitHeight` — размер лица штучного изделия (блок, кирпич) в мм, `jointMm` — толщина шва (по умолчанию 10); по ним считается количество штук: площадь стен с запасом ÷ ((unitLength+шов)×(unitHeight+шов)), для блока 390×190 это 12,5 шт/м². `finish` — отделка фасада для 3D: `osb | plaster | timber | planken` (необязательно). `panelWidth`×`panelHeight` — размер панели в том положении, как она стоит в стене (ширина вдоль стены, высота по вертикали); по ним считается раскладка. `length`/`height` — габарит изделия, если нужен справочно. `price` — цена за единицу `pricePer`: `pcs` (штука) | `m2` | `m3` | `m`. `url` — страница товара, `source` — магазин/источник, `checkedAt` — дата проверки цены (ISO). Нет `price` — в смете «цена не задана».
+
+**Как считается смета стен** (`computeWallEstimate(plan)` в `src/model/estimate.ts`, одна строка на материал, id строки `auto:wall:<materialId>`, для стен без материала — `auto:wall:none`). Площадь = Σ длина × высота по стенам материала, минус площадь проёмов (ширина × высота). Панели = Σ по стенам `ceil(длина / panelWidth) × ceil(высота / panelHeight)`, проёмы не вычитаются (панели режутся). Количество к закупке — с запасом `estimate.wasteSipPct` % (по умолчанию 7): для `pcs` — панели с запасом, округлённые вверх; для `m2` — чистая площадь × запас; `m3` — площадь × толщина × запас; `m` — длина × запас. Стоимость = количество × `price`.
+
+## walls — стены
+
+```json
+{ "id": "w1", "a": { "x": 16000, "y": 3100 }, "b": { "x": 24000, "y": 3100 }, "thickness": 174, "height": 2800, "materialId": "sip-174" }
+```
+
+`a` и `b` — концы **осевой линии** стены; толщина откладывается поровну в обе стороны. Чтобы стены сходились в углу, концы соседних стен должны совпадать точно (редактор привязывается к концам и к сетке 100 мм). `thickness` обычно равна толщине материала. `materialId` необязателен, но если задан — должен существовать. Длина стены не хранится, считается из `a`/`b`. Направление `a → b` важно для проёмов.
+
+## openings — двери и окна
+
+```json
+{ "id": "d1", "wallId": "w3", "type": "door", "offset": 3550, "width": 900, "height": 2100, "sill": 0, "hinge": "start", "side": "right" }
+{ "id": "win1", "wallId": "w1", "type": "window", "offset": 1500, "width": 1500, "height": 1400, "sill": 900 }
+```
+
+`type`: `door | window | gate`; `gate` — секционные или подъёмные ворота, рисуются без дуги, штриховой линией полотна на 600 мм внутрь (сторона — `side`, петель нет). Стандартные размеры, которые ставит редактор: входная дверь 960×2070, межкомнатная 800×2000, ворота 2500×2200, окно 1200×1400 с подоконником 800. `offset` — расстояние от точки `a` стены до ближнего края проёма вдоль стены; `offset + width` не больше длины стены. `height` — высота проёма, `sill` — высота низа проёма от пола (для двери 0, для окна подоконник, по умолчанию 0). Только для дверей: `hinge` — у какого края петли (`start` — ближний к `a`, `end` — дальний), `side` — куда открывается полотно относительно направления `a → b` при взгляде на план сверху (`left` или `right`). Удаление стены в редакторе удаляет и её проёмы.
+
+## furniture — мебель
+
+```json
+{ "id": "f1", "type": "bed-1600", "x": 15200, "y": 28400, "rotationDeg": 90, "w": 1700, "d": 2100, "h": 1000, "color": "#d9c29a" }
+```
+
+`type` — тип из каталога `FURNITURE_CATALOG` (`src/furniture/catalog.ts`), `x`/`y` — центр предмета в мм плана, `rotationDeg` — поворот по часовой (в осях плана), `w`/`d`/`h` — ширина, глубина, высота; если не заданы, берутся из каталога. `color` необязателен. Массив можно не указывать.
+
+## rooms — подписи комнат (необязательно)
+
+```json
+{ "id": "r1", "name": "Спальня 1", "x": 14200, "y": 26500, "kind": "bedroom" }
+```
+
+Точка-подпись внутри контура комнаты: `x`/`y` в мм плана, `kind`: `living | bedroom | kitchen | bath | tech | hall | storage | garage`. Контур и площадь в чистоте редактор находит сам по стенам (`detectRooms` из `src/stats`) и рисует под названием. В редакторе подпись добавляется правым кликом внутри комнаты → «Подписать комнату», перетаскивается, двойной клик — переименовать (пустое имя удаляет подпись).
+
+## estimate — смета (необязательно)
+
+```json
+{ "lines": [ { "id": "l1", "name": "Бетон М300", "category": "фундамент", "qty": 6.5, "unit": "м³", "price": 7200, "url": "…", "note": "…" } ],
+ "purchases": { "auto:wall:sip-174": { "done": true, "date": "2026-10-02", "actualPrice": 5400, "qty": 69, "shop": "…" } },
+ "wasteSipPct": 7 }
+```
+
+`lines` — ручные строки сметы помимо автоматических строк стен: `id`, `name`, `category` (`фундамент | стены | перекрытия | кровля | окна-двери | утепление | крепёж | инженерия | работы | прочее`), `qty`, `unit` (строка), необязательные `materialId`, `price`, `url`, `note`. `purchases` — отметки о покупке, ключ — `id` строки (ручной или автоматической `auto:wall:<materialId>`): `done`, необязательные `date`, `actualPrice`, `qty`, `shop`, `note`. `wasteSipPct` — запас на подрезку стеновых материалов, %.
+
+## networks — инженерные сети (необязательно)
+
+```json
+{ "sewer": {
+ "floorLevel": 600,
+ "nodes": [
+ { "id": "sn1", "x": 15200, "y": 27400, "kind": "fixture", "fixture": "toilet", "furnitureId": "f7" },
+ { "id": "sn2", "x": 15200, "y": 29000, "kind": "riser", "height": 3000 },
+ { "id": "sn3", "x": 15200, "y": 30500, "kind": "outlet" },
+ { "id": "sn4", "x": 15200, "y": 36000, "kind": "septic", "model": "Тверь 0,75", "w": 2500, "d": 1100, "rotationDeg": 0, "label": "Септик" }
+ ],
+ "pipes": [
+ { "id": "sp1", "from": "sn1", "to": "sn2", "diameter": 110, "slope": 2, "location": "inside" },
+ { "id": "sp2", "from": "sn3", "to": "sn4", "diameter": 110, "slope": 1, "depth": 1200, "location": "outside", "material": "pipe-110-out" }
+ ],
+ "materials": [
+ { "id": "pipe-110-out", "name": "Труба ПВХ наружная 110×3,2, 3 м", "kind": "pipe", "diameter": 110, "length": 3000, "price": 1190, "pricePer": "pcs", "url": "…", "source": "…", "checkedAt": "2026-09-30" }
+ ] } }
+```
+
+Сети лежат отдельно от стен: `networks.sewer` — канализация, `networks.electric` — электрика, `networks.heating` — тёплый пол (ниже), под водопровод зарезервировано `networks.water` (пока не рисуется). Все поля, которых нет в схеме, сохраняются как есть.
+
+**Узлы** `nodes`: `id`, `x`/`y` в мм плана, `kind`: `fixture` (прибор), `riser` (стояк), `cleanout` (ревизия), `outlet` (выпуск через фундамент), `septic` (септик), `junction` (стык, тройник). Для прибора `fixture`: `toilet | sink | bath | shower | washer | kitchen | boiler`, `furnitureId` — мебель, к которой узел привязан (необяз.). `label` — подпись. У стояка `height` — длина вертикали в мм (по умолчанию 3000, идёт в трубу 110 внутри). У септика `model` (подпись на плане, например «Тверь»), габарит `w`×`d` в мм и `rotationDeg`, как у мебели; `depth` — глубина лотка входа, если известна из паспорта.
+
+**Трубы** `pipes`: `from` → `to` — направление стока (стрелка на плане), `diameter`: `50 | 110 | 160`, `slope` — уклон в процентах (`2` = 2 %, 20 мм на метр), `location`: `inside | outside` (наружные рисуются пунктиром), `depth` — заглубление лотка у начала трубы от уровня земли в мм (для наружной; если не задано — не меньше 1000 мм), `material` — `id` из `networks.sewer.materials`. `floorLevel` — отметка чистого пола над землёй в мм (по умолчанию 600), от неё считаются перепады. Длина трубы не хранится — считается по узлам.
+
+**Материалы сети** `networks.sewer.materials` — цены именно для канализации, отдельно от `materials` стен: `id`, `name`, `kind` (`pipe | elbow | tee | reducer | cleanout | clamp | sleeve | corrugation | septic | other`), `diameter`, `angle` (для отвода и тройника), `length` (длина штучной трубы), `price`, `pricePer` (`pcs | m`), `url`, `source`, `checkedAt`. Позиция расчёта берёт цену так: материал с `id`, равным ключу позиции (`pipe-110-inside`, `elbow-110-45`, `tee-110x50`, `reducer-110x50`, `cleanout-110`, `clamp-110`, `sleeve-110`, `corrugation-110`, `septic`), у наружных фитингов к ключу добавляется `-out` (`elbow-110-45-out`); затем по `kind` + `diameter` (+ `angle`); затем из `public/data/catalog.json` по id вида `sewer-<тип>-<in|out>-<диаметр>[-<угол>]` (труба — самая дешёвая за метр, штуки считаются по её длине; упаковка «(2 шт.)» пересчитывается в упаковки), септик — по словам из `model` в названии; иначе «цена не задана».
+
+**Редактор.** «Слои» → карандаш у «Канализации»: сверху холста панель режимов (Выбор, Трасса, Ревизия, Стояк, Выпуск, Септик), выход — Esc или крестик. Трасса: клик по прибору (унитаз, раковина, ванна, душ, стиралка, мойка, котёл из `furniture`) или узлу, дальше клики ставят узлы и трубы; клик по трубе врезает стык, по узлу или прибору — заканчивает трассу. При выходе трассы за контур дома выпуск ставится сам на пересечении со стеной. Диаметр по умолчанию: от унитаза и ниже по стоку 110, наружные 110, остальное 50; уклон 3 % для Ø50, 2 % для Ø110 внутри, 1 % снаружи.
+
+**Что считается** (`src/networks/sewerCalc.ts`, в смете — группа «Канализация», id строк `auto:sewer:<ключ>`): длины труб по диаметрам раздельно внутри и снаружи, с учётом вертикали стояков; фитинги по узлам — отводы 45° и 87° по углу поворота трассы, тройники на стыках (110/50, если отвод тоньше магистрали), переходы 110/50 при смене диаметра без тройника, ревизии на узлах `cleanout` и стояках, гильзы на выпусках, гофра на унитаз, хомуты внутри с шагом 10 диаметров трубы (0,5 м для Ø50, 1,1 м для Ø110). Перепады: отметки лотка идут от пола вниз по уклонам, итог — глубина выпуска у стены и глубина входа в септик. Предупреждения: уклон меньше минимума по СП 30.13330 (Ø50 — 2,5 %, Ø110 внутри — 1,2 %, наружная Ø110 — 1 %, Ø160 — 0,8 %), поворот около 90° на горизонтали одним отводом 87° (лучше два по 45° или ревизия), наружная труба мельче 1000 мм (утеплять), септик ближе 5 м к фундаменту или ближе 1 м к границе участка, труба тоньше, чем сток в неё.
+
+### networks.electric — электрика
+
+```json
+{ "electric": {
+ "panel": { "id": "panel", "x": 12000, "y": 20100, "wallId": "w4", "modules": 24 },
+ "points": [
+ { "id": "ep1", "kind": "socket", "x": 13200, "y": 20100, "height": 300, "wallId": "w4", "circuitId": "c1" },
+ { "id": "ep2", "kind": "socket_ip44", "x": 15000, "y": 26000, "height": 1100, "wallId": "w9", "circuitId": "c2", "label": "стиралка", "powerW": 2200 },
+ { "id": "ep3", "kind": "light", "x": 14000, "y": 23000, "height": 2700, "circuitId": "c3" }
+ ],
+ "circuits": [
+ { "id": "c1", "name": "Розетки гостиная", "kind": "socket", "breaker": { "type": "RCBO", "rating": 16, "curve": "C" }, "cable": "3x2.5", "phase": "L1" },
+ { "id": "c3", "name": "Свет", "kind": "light", "breaker": { "type": "MCB", "rating": 10, "curve": "C" }, "cable": "3x1.5" }
+ ],
+ "routes": [ { "circuitId": "c1", "path": [ { "x": 12000, "y": 20000 }, { "x": 13200, "y": 20000 }, { "x": 13200, "y": 20100 } ] } ],
+ "materials": [ { "id": "cable-3x2.5", "name": "ВВГнг(А)-LS 3×2,5, бухта 100 м", "length": 100000, "price": 9800, "pricePer": "pcs" } ]
+} }
+```
+
+**Точки** `points`: `kind` — `socket` (розетка), `socket2` (двойная), `socket_ip44` (влагозащищённая), `power` (силовая: плита, духовка, котёл), `outdoor` (уличная), `switch` / `switch2` (выключатель на 1 и 2 клавиши), `light` (потолочный светильник), `light_wall` (бра), `junction` (распаечная коробка). `x`/`y` — точка на грани стены, `wallId` — стена, к которой привязана (у потолочного светильника нет). `height` — высота установки от чистого пола в мм: по умолчанию розетки 300, IP44 1100, силовая 600, выключатели 900, бра 2000, коробки на 150 ниже потолка, потолочный свет — высота стен. `circuitId` — группа, `label` — подпись, `powerW` — мощность в ваттах для расчёта нагрузки (по умолчанию розетка 300, двойная 500, IP44 500, силовая 3500, уличная 1000, светильник 50, бра 30).
+
+**Группы** `circuits`: `kind` — `light | socket | power | wet | outdoor | garage`; `breaker.type` — `MCB` (автомат), `RCBO` (дифавтомат), `RCD` (автомат плюс своё УЗО); `rating` в амперах, `curve` — `B | C | D`; `cable` — марка вида `3x1.5`, `3x2.5`, `3x6`, `5x6` (жилы × сечение); `phase` — `L1 | L2 | L3`. **Щит** `panel`: точка на стене, `modules` — число модулей, если щит уже куплен. **Трассы** `routes`: горизонтальная трасса группы в плане, ломаная `path`, на одну группу может быть несколько записей (ветки). Идёт на 150 мм ниже потолка, к каждой точке — вертикальный опуск. Кнопка «Автотрасса» строит их от щита по осям стен (кратчайшие пути по графу стен, ветки жадно дотягиваются до ближайшей точки), потолочные светильники подключаются напрямую от ближайшей стены.
+
+**Что считается** (`src/networks/electric/calc.ts`, в смете — группа «Электрика», id строк `auto:electric:<ключ>`): длина кабеля группы = трасса (без трассы — оценка по манхэттенскому остовному дереву от щита) + опуски от уровня трассы до высоты каждой точки и до щита + 1,5 м на разделку в щите + 15 % запаса; кабель по маркам в метрах (ВВГнг(А)-LS); металлорукав или гофра Ø16/20/25 по сечению; устройства по типам; подрозетники для полых стен (двойная розетка — 2); автоматы, дифавтоматы и УЗО по номиналам; вводной автомат и реле напряжения; щит по числу модулей +20 % запаса (12/18/24/36/48/54/72/96). Ключи позиций для цен: `cable-3x2.5`, `conduit-16`, `dev-socket` (`dev-<kind>`), `box-flush`, `mcb-C16-1p`, `rcbo-C16-1p`, `rcd-40-2p`, `main-2p`, `main-3p`, `relay-voltage`, `panel-24`. Цена берётся из `networks.electric.materials` (по `id` или `subtype`, равным ключу), затем из `public/data/catalog.json` у позиций с `kind: "electric"`: по `id`/`subtype`, равным ключу, либо по `subtype` (`cable | conduit | socket | switch | breaker | rcbo | rcd | panel | box | relay`) и параметрам — жилы и сечение кабеля (`cores`/`section` или из названия «3х2,5»), номинал, характеристика и полюса автомата (`rating`, `curve`, `poles` или «1P C16»), ток утечки (`leakage` или «30 мА»), тип розетки по названию (двойная, IP44, силовая, уличная), `modules` щита (берётся ближайший не меньше нужного), `diameter` гофры; из подходящих — `preferred` или Петрович, самая дешёвая за единицу; если кабель или гофра продаются бухтой (`pricePer: "pcs"` или единица «шт»/«бухта» и `length` в мм), считается число бухт. Предупреждения: автомат больше допустимого для сечения (1,5 — 10 А, 2,5 — 16 А, 4 — 25 А, 6 — 32 А), нагрузка больше номинала автомата, мокрая, уличная или гаражная группа либо точка IP44 без УЗО, розетка в санузле без IP44, розетка или выключатель над ванной или душем (зона 0/1) и розетка ближе 600 мм к ним (зона 2), падение напряжения больше 5 %, больше 10 розеток в группе, силовая точка не отдельной группой, розетки в группе света, точка без группы, щит меньше нужного числа модулей.
+
+### networks.water — водопровод
+
+```json
+{ "water": {
+ "nodes": [
+ { "id": "wn1", "x": 5000, "y": 36000, "kind": "source", "source": "borehole", "label": "Скважина" },
+ { "id": "wn2", "x": 12000, "y": 34600, "kind": "entry" },
+ { "id": "wn3", "x": 12400, "y": 34000, "kind": "pump", "model": "Джилекс Джамбо 60/35" },
+ { "id": "wn4", "x": 12800, "y": 34000, "kind": "filter" },
+ { "id": "wn5", "x": 13200, "y": 33800, "kind": "collector", "line": "cold", "outputs": 4 },
+ { "id": "wn6", "x": 13600, "y": 33800, "kind": "boiler", "model": "80 л" },
+ { "id": "wn7", "x": 13600, "y": 33500, "kind": "collector", "line": "hot", "outputs": 3 },
+ { "id": "wn8", "x": 12300, "y": 34240, "kind": "fixture", "fixture": "toilet", "furnitureId": "f1" }
+ ],
+ "pipes": [
+ { "id": "wp1", "from": "wn1", "to": "wn2", "line": "cold", "diameter": 32, "material": "PE", "location": "outside", "depth": 1800 },
+ { "id": "wp2", "from": "wn5", "to": "wn8", "line": "cold", "diameter": 16, "material": "PEX", "location": "inside" }
+ ] } }
+```
+
+Узлы `nodes`: `kind` — `source` (скважина или колодец, уточняется полем `source`: `borehole | well`), `entry` (ввод в дом), `pump` (насосная станция), `filter`, `boiler`, `collector`, `fixture` (прибор, `fixture` и `furnitureId` как у канализации), `junction`, `tap_outdoor` (уличный кран). У коллектора `line` — `cold | hot` (по умолчанию `cold`) и `outputs` — число выходов; у любого узла `label`, `model`. Трубы `pipes`: `from` → `to` по направлению подачи воды, `line` — `cold` (синяя), `hot` (красная), `recirc` (рециркуляция, красный пунктир), `diameter` — `16 | 20 | 25 | 32`, `material` — `PEX | PPR | PE` (по умолчанию PEX внутри и PE снаружи), `location` — `inside | outside` (наружные рисуются пунктиром), `depth` — глубина заложения наружной трубы в мм, `heated` — проложен греющий кабель. `materials` — цены сети в том же формате, что у канализации.
+
+**Редактор водопровода.** «Слои» → карандаш у «Водопровода»: режимы Выбор, Холодная, Горячая, Рецирк. и выбор узла, который ставит клик по пустому месту (узел, источник, ввод, насос, фильтр, бойлер, коллектор, уличный кран). Магистраль рисуется кликами; при переходе снаружи внутрь дома ввод ставится сам на пересечении со стеной. Клик по прибору из `furniture` — лучевая разводка: отдельная линия Ø16 PEX от ближайшего коллектора этой воды, углом вдоль ближней стены. Горячая вода — от коллектора ГВС (`line: "hot"`), который питается от бойлера. Умолчания: снаружи Ø32 PE, магистраль внутри Ø20 PEX, к приборам и рециркуляция Ø16 PEX.
+
+**Что считается** (`src/networks/waterCalc.ts`, в смете — группа «Водопровод», id строк `auto:water:<ключ>`): длины по линиям, диаметрам, материалам, внутри и снаружи; пресс-угольники на поворотах, тройники, переходы при смене диаметра, водорозетки на приборы, коллекторы по числу выходов и фитинги на выходы, переходники на резьбу у насоса, фильтра и бойлера, оголовок скважины, уличный кран, гильзы на пересечениях труб со стенами и на вводе, теплоизоляция на горячую, рециркуляцию и наружную трубу, греющий кабель на наружных трубах с `heated`. Цена: `networks.water.materials` по `id` = ключ позиции (`pipe-16-PEX-inside`, `elbow-16`, `tee-20`, `socket-16`, `collector-4`, `collector-out-16`, `sleeve-32`, `insul-16`, `heat-cable`, `head`, `tap-outdoor`) или по `kind` + `diameter`, затем каталог `kind: "water"` (id `water-<ключ>` или `subtype` = вид позиции + `diameter`/`material`), иначе «цена не задана». Проверки: наружная труба мельче 1,5 м без греющего кабеля; наружная труба ближе 1,5 м к наружной канализации; источник ближе 50 м к септику (СанПиН, если септик выше по потоку) и ближе 15 м (минимум по паспорту станций); прибор без холодной воды, не подключённый прибор, прибор на тройнике вместо своего выхода коллектора, переполненный коллектор.
+
+### networks.heating — тёплый пол
+
+```json
+{ "heating": {
+ "collector": { "id": "collector", "x": 14343, "y": 33118, "outputs": 13, "label": "котельная" },
+ "loops": [
+ { "id": "hl5", "roomId": "n-r2", "roomName": "кухня",
+ "polygon": [ { "x": 16000, "y": 31000 }, { "x": 19000, "y": 31000 }, { "x": 19000, "y": 34000 }, { "x": 16000, "y": 34000 } ],
+ "stepMm": 150, "pattern": "spiral", "pipe": "16x2 PEX-a",
+ "supplyPath": [ { "x": 14343, "y": 33118 }, { "x": 15600, "y": 33118 }, { "x": 16000, "y": 33000 } ],
+ "excluded": [ [ { "x": 17200, "y": 33600 }, { "x": 18000, "y": 33600 }, { "x": 18000, "y": 34000 }, { "x": 17200, "y": 34000 } ] ] }
+ ],
+ "params": { "supplyT": 45, "returnT": 35, "screedMm": 60, "insulation": "XPS 100" }
+} }
+```
+
+Водяной тёплый пол. **Коллектор** `collector`: точка в мм плана, `outputs` — число выходов, `label` — подпись. **Петли** `loops`: `polygon` — контур укладки (комната минус 100 мм от стен), `excluded` — зоны без трубы внутри контура (мебель на полу), `stepMm` — шаг `100 | 150 | 200`, `pattern` — `spiral` (улитка, встречные подача и обратка) или `snake` (змейка), `pipe` — труба (`16x2 PEX-a`, `16x2 PE-RT` или любая строка вида «16x2 …»), `supplyPath` — подводка от коллектора до входа в петлю (ломаная, считается дважды: подача и обратка), `roomId` — `id` подписи комнаты из `rooms`, `roomName` — подпись петли, `parts` — дополнительные контуры той же петли в соседних помещениях (`polygon`, `roomId`, `roomName`, `excluded`), `linkPath` — переход трубы от основного контура к `parts` (считается дважды), `edge: true` — краевая петля у наружных стен (предел пола 35 °C), `off: true` — петля исключена из расчёта и сметы, но остаётся на плане. **Параметры** `params` (все необязательные): `supplyT`/`returnT` — подача и обратка, °C (45/35), `floorT` — предел температуры поверхности пола (по умолчанию по нормам: 29 °C, санузел 33, краевая зона 35), `screedMm` — толщина стяжки (60), `insulation` — утеплитель («XPS 100»), `screedMix` — `cement-sand` (цемент М500 + песок 1:3) или `cps` (ЦПС М300), `fixing` — `staples` (скобы-гарпуны в ЭППС, по умолчанию) или `mesh` (армосетка + хомуты). `materials` — свои цены, как у других сетей.
+
+**Автораскладка** (кнопка «Разложить по комнатам», `src/networks/heating/layout.ts`): комнаты из `detectRooms`, класс по названию, затем по `kind`: санузел, душ, туалет — шаг 100, плитка; кухня, прихожая, коридор, котельная — плитка, шаг 150; жилые — ламинат, шаг 150; сауна, парилка, гараж и комнаты без подписи — без пола. Контур — чистый контур комнаты минус 100 мм; из него вычитается неподвижная мебель (кухонные модули, мойка, плита, посудомойка, холодильник, шкафы, ванна, душевой поддон, котлы, печь, камин). В жилых комнатах больше 12 м² полоса 1 м у наружных стен выделяется в краевую петлю с шагом 100, если она сама влезает в одну петлю. Петля длиннее 80 м вместе с подводками режется на полосы равной площади вдоль длинной стороны. Если пол комнаты не покрывает теплопотери, раскладка пробует шаг 100 на всю комнату без разрезки петель, затем полосу 1 м у наружных стен с шагом 100, затем шаг 100 на всю комнату с разрезкой; если не помогло — остаётся предупреждение. Если петель больше 12 (один коллектор), мелкие петли с одинаковым шагом из разных помещений объединяются в одну (`parts` + `linkPath`), пока общая длина не больше 80 м, а переход не длиннее 6 м. Коллектор — в котельной (название с «котёл/котельная» или `kind: tech`) на стене, ближайшей к центру дома, без котельной — в центре дома; уже стоящий коллектор не двигается. Подводка идёт из комнаты в комнату через двери вдоль стен (в 60 мм от чистого контура), при отсутствии пути — углом. Перетаскивание коллектора перекладывает подводки. Раскладка пишет план только по нажатию кнопки.
+
+**Что считается** (`src/networks/heating/calc.ts`, в смете — группа «Тёплый пол», id строк `auto:heating:<ключ>`): длина петли = площадь контура без исключённых зон / шаг + подводка × 2, плюс 5 %; предупреждение больше 80 м, ошибка больше 100 м. Теплоотдача q = K(шаг, покрытие) × Δθ × поправка на стяжку, где Δθ — логарифмический перепад подачи, обратки и воздуха (20 °C, санузел 24 °C), K для плитки 6,7/5,9/5,2 и для ламината 4,2/3,8/3,4 Вт/(м²·К) при шаге 100/150/200; сверху ограничение по температуре пола q ≤ 8,92 × (tпола − tвозд)^1,1. Теплопотери по укрупнённой норме для Северо-Запада: 50 Вт/м² без наружных стен, 60 — одна наружная сторона, 70 — угловая; предупреждение, если пол комнаты даёт меньше 95 % потерь. Котёл — теплопотери × 1,2 до ближайшего типоразмера. Расход петли = 0,86 × мощность × 1,1 / (подача − обратка) л/ч, настройка расходомера — в л/мин; потери давления по Дарси (ламинарный режим или Блазиус) +30 % на местные сопротивления, дросселирование = самая тяжёлая петля − своя; насос смесительного узла — самая тяжёлая петля + 5 кПа. Материалы и ключи цен: труба бухтами 500 и 200 м с раскладкой петель по бухтам без стыков (`pipe-16x2-pex-a-500`, `pipe-16x2-pex-a-200`), коллектор с расходомерами на N выходов (`collector-N`, при больше 12 петель — два), насосно-смесительный узел без насоса (`mixing-unit`) и циркуляционный насос 25/60 (`pump-25-60`), шкаф коллекторный (`cabinet-N`), евроконусы по 2 на петлю (`eurocone-16`), демпферная лента по периметру комнат +10 % (`damper-tape`, м), утеплитель по площади +5 % (`insulation-xps-100`, м²), плёнка +15 % (`film`), армосетка +10 % и хомуты (`mesh`, `ties`) или скобы-гарпуны через 0,4 м (`staples`), стяжка в килограммах — цемент М500 400 кг/м³ и песок 1200 кг/м³ +5 % (`cement-m500`, `sand`) или ЦПС 2000 кг/м³ (`cps`), мешки считаются по `weight` позиции каталога, фиброволокно 0,9 кг/м³ (`fiber`). Цена берётся из `networks.heating.materials` (по `id`, равному ключу, или подходящей позиции), затем из `public/data/catalog.json` у позиций с `kind: "heating"`: по `id`, равному ключу, либо по `subtype` каталога (`pipe`, `collector`, `mixing` — узлы и насосы, `cabinet`, `fitting` — евроконусы, `damper`, `insulation`, `film`, `mesh` — сетка и скобы, `screed` — цемент, песок, ЦПС, фибра) плюс слова в названии и параметры: у трубы тип (PE-Xa / PE-RT по `material` или названию), `diameter` 16 и `coil`; у коллектора и шкафа `outlets` не меньше нужного (если такого нет — два по половине); у утеплителя `thickness`; у плёнки `thickness` 0,2. Упаковки пересчитываются: листы по `length`×`height`, плёнка по `width` (и `roll`), лента по `roll`, мешки по `weight`, скобы по `pack`. Из подходящих — `preferred`, затем самая дешёвая за единицу; иначе «цена не задана». Предупреждение, если утеплитель тоньше 100 мм (для Северо-Запада минимум ЭППС 100, правильно 150).
+
+## Идентификаторы
+
+Любые непустые строки, уникальные в своём массиве. Редактор новые стены называет `w<N>`; для ручной правки удобно так же: `w…` стены, `d…` двери, `win…` окна, материалы — осмысленным слагом (`sip-174`).
+
+## Частые правки через чат
+
+«Добавь стену 5 м из СИП от угла дома на восток» — новая запись в `walls` с `a` в нужном углу (координаты угла берутся из существующих стен) и `b = a + (5000, 0)`. «Окно 1200 по центру стены w2» — `offset = (длина w2 − 1200) / 2`. «Добавь материал по ссылке» — запись в `materials` с `url`, толщиной и ценой со страницы товара, потом `materialId` у нужных стен.
diff --git a/docs/screenshots/3d.png b/docs/screenshots/3d.png
new file mode 100644
index 0000000..3264fad
Binary files /dev/null and b/docs/screenshots/3d.png differ
diff --git a/docs/screenshots/estimate.png b/docs/screenshots/estimate.png
new file mode 100644
index 0000000..a275e79
Binary files /dev/null and b/docs/screenshots/estimate.png differ
diff --git a/docs/screenshots/heating.png b/docs/screenshots/heating.png
new file mode 100644
index 0000000..9d29191
Binary files /dev/null and b/docs/screenshots/heating.png differ
diff --git a/docs/screenshots/hero.png b/docs/screenshots/hero.png
new file mode 100644
index 0000000..63a63f9
Binary files /dev/null and b/docs/screenshots/hero.png differ
diff --git a/docs/screenshots/map.png b/docs/screenshots/map.png
new file mode 100644
index 0000000..7e68c6b
Binary files /dev/null and b/docs/screenshots/map.png differ
diff --git a/docs/screenshots/mobile.png b/docs/screenshots/mobile.png
new file mode 100644
index 0000000..6ee3e00
Binary files /dev/null and b/docs/screenshots/mobile.png differ
diff --git a/docs/screenshots/networks.png b/docs/screenshots/networks.png
new file mode 100644
index 0000000..eef50ed
Binary files /dev/null and b/docs/screenshots/networks.png differ
diff --git a/docs/screenshots/plan.png b/docs/screenshots/plan.png
new file mode 100644
index 0000000..de73bac
Binary files /dev/null and b/docs/screenshots/plan.png differ
diff --git a/docs/screenshots/versions.png b/docs/screenshots/versions.png
new file mode 100644
index 0000000..8ddfdb6
Binary files /dev/null and b/docs/screenshots/versions.png differ
diff --git a/docs/ui.md b/docs/ui.md
new file mode 100644
index 0000000..93feac3
--- /dev/null
+++ b/docs/ui.md
@@ -0,0 +1,48 @@
+# Общий дизайн: токены и примитивы
+
+Весь интерфейс (план, 3D, карта, смета, «Участок и дом») собирается из одних токенов и одних примитивов. Своих цветов, теней, радиусов и своих кнопок в разделах не заводим: нужен новый вариант — добавляем его в примитив или токен, а не копию в своём CSS. CSS пишется без комментариев.
+
+## Токены — `src/styles/tokens.css`
+
+Подключены глобально в `src/main.tsx` (вместе с `src/styles/ui.css`), в разделах импортировать не нужно, просто пользоваться `var(--…)`.
+
+| группа | переменные |
+|---|---|
+| фон и поверхности | `--bg` (фон приложения), `--surface` (карточки), `--surface-2` (ховер), `--surface-3` (подложка сегментов) |
+| текст | `--ink`, `--ink-2`, `--muted` |
+| линии | `--line`, `--line-strong` |
+| акцент | `--accent`, `--accent-hover`, `--accent-soft`, `--accent-ink` |
+| статусы | `--ok`/`--ok-soft`, `--warn`/`--warn-soft`, `--danger`/`--danger-soft` |
+| радиусы | `--radius-xs` 6, `--radius-sm` 9, `--radius` 12, `--radius-lg` 16, `--radius-pill` |
+| тени | `--shadow-sm`, `--shadow`, `--shadow-lg` |
+| отступы | `--space-1`…`--space-6` = 4, 8, 12, 16, 24, 32 |
+| шрифт | `--font`, `--font-mono`, `--text-xs` 11, `--text-sm` 12.5, `--text-md` 14, `--text-lg` 17, `--text-xl` 22 |
+| контролы | `--control-h-sm` 28, `--control-h` 32, `--control-h-lg` 38 |
+| раскладка | `--header-h` 52 (шапка), `--header-top`, `--chrome-top` (верх для плавающих панелей под шапкой), `--chrome-left`, `--z-chrome`, `--z-popover` |
+
+Тема одна, светлая. Шапка приложения плавающая: полноэкранный раздел (3D, карта) рисует холст на всю вкладку, а свои панели ставит не выше `var(--chrome-top)`.
+
+## Примитивы — `src/ui/`
+
+Импорт из `src/ui` (barrel `src/ui/index.ts`): `import { Button, Panel, Table, Th, Td } from '../ui'`.
+
+| компонент | пропсы | для чего |
+|---|---|---|
+| `Button` | `variant: default \| primary \| ghost \| danger`, `size: sm \| md`, `pressed`, `icon`, остальное как у `<button>` | любые кнопки; `primary` — одна главная на экран |
+| `IconButton` | `label` (обязателен, идёт в title/aria-label), `active`, `size`, children — svg | иконочные кнопки на тулбарах |
+| `Segmented` | `options: {value,label,href?,title?}[]`, `value`, `onChange`, `size` | переключатели режимов; с `href` — ссылки (так сделаны вкладки шапки) |
+| `Card` | `padded` (по умолчанию true), `ref` | белая карточка с тенью |
+| `Panel` | `title`, `eyebrow`, `actions`, `footer`, `ref` | карточка с шапкой и прокручиваемым телом |
+| `Badge` | `tone: neutral \| accent \| ok \| warn \| danger` | статусы и счётчики |
+| `Input` | `label`, `suffix` (ед. изм.), `size`, `invalid`, `ref`, остальное как у `<input>` | поля ввода и числа |
+| `Checkbox` | `label`, `checked`, `onChange(checked: boolean)` | галочки (куплено и т. п.) |
+| `Table`, `Th`, `Td`, `Tr` | `Table dense`, `Th/Td num` (числа вправо, моноширинные цифры), `Tr muted` | таблицы; шапка липкая |
+| `CanvasToolbar`, `ToolbarSeparator` | `placement: top-left \| top-right \| top-center \| bottom-*`, `direction: row \| column` | плавающий тулбар поверх холста/3D/карты, сам встаёт под шапку |
+| `Menu`, `MenuItem`, `MenuSection` | `Menu trigger={({open,toggle}) => …} width align`, children — узлы или `(close) => узлы`; `MenuItem hint`; `MenuSection title` | выпадающие меню (так сделано «⋯» в шапке) |
+| `cx` | `cx('a', cond && 'b')` | склейка классов |
+
+Служебные классы из `ui.css`: `.eyebrow` (мелкий заголовок капсом), `.muted` (серый текст), `.num` (число вправо).
+
+## Навигация
+
+Разделы переключаются только в шапке, адрес раздела — hash: `#/plan`, `#/3d`, `#/map`, `#/estimate`, `#/info`. Список — `src/ui/useSection.ts`. Раздел монтируется лениво из `src/<раздел>/index.tsx` (default export) и получает `plan` из стора, редактируемые разделы ещё `onChange(nextPlan)` — это та же запись, что и в редакторе: с отменой (⌘Z) и автосохранением на сервер. Экспорт/импорт JSON, сброс к исходному и версии — в меню «⋯» справа в шапке.
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..e09b20a
--- /dev/null
+++ b/index.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <link rel="icon" type="image/svg+xml" href="./favicon.svg" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
+ <title>House Planner</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..d6aa6f8
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,4081 @@
+{
+ "name": "house-planner",
+ "version": "0.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "house-planner",
+ "version": "0.0.0",
+ "dependencies": {
+ "@react-three/drei": "^10.7.9",
+ "@react-three/fiber": "^9.8.1",
+ "@react-three/postprocessing": "^3.1.3",
+ "clipper2-ts": "^2.0.1-18",
+ "i18next": "^26.4.2",
+ "i18next-browser-languagedetector": "^8.2.1",
+ "konva": "^10.7.0",
+ "maplibre-gl": "^6.11.2",
+ "n8ao": "^2.0.1",
+ "proj4": "^2.22.0",
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "react-i18next": "^17.0.15",
+ "react-konva": "^19.3.0",
+ "react-markdown": "^10.1.0",
+ "remark-gfm": "^4.0.1",
+ "three": "^0.186.1",
+ "three-bvh-csg": "^0.0.18",
+ "zod": "^4.6.5",
+ "zundo": "^2.3.0",
+ "zustand": "^5.0.15"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "@types/proj4": "^2.5.6",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.7",
+ "@types/three": "^0.186.0",
+ "@vitejs/plugin-react": "^6.1.1",
+ "oxlint": "^1.81.0",
+ "typescript": "~6.0.2",
+ "vite": "^8.3.0"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@mapbox/jsonlint-lines-primitives": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz",
+ "integrity": "sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 22"
+ }
+ },
+ "node_modules/@mapbox/point-geometry": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz",
+ "integrity": "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==",
+ "license": "ISC"
+ },
+ "node_modules/@mapbox/tiny-sdf": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz",
+ "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/unitbezier": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz",
+ "integrity": "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/@mapbox/vector-tile": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz",
+ "integrity": "sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@mapbox/point-geometry": "~1.1.0",
+ "@types/geojson": "^7946.0.16",
+ "pbf": "^5.0.0"
+ }
+ },
+ "node_modules/@maplibre/geojson-vt": {
+ "version": "6.1.1",
+ "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz",
+ "integrity": "sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ==",
+ "license": "ISC",
+ "dependencies": {
+ "kdbush": "^4.1.0"
+ }
+ },
+ "node_modules/@maplibre/maplibre-gl-style-spec": {
+ "version": "26.4.4",
+ "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz",
+ "integrity": "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==",
+ "license": "ISC",
+ "dependencies": {
+ "@mapbox/jsonlint-lines-primitives": "^2.0.3",
+ "@mapbox/unitbezier": "^1.0.0",
+ "json-stringify-pretty-compact": "^4.0.0",
+ "minimist": "^1.2.8",
+ "quickselect": "^3.0.0",
+ "tinyqueue": "^3.0.0"
+ },
+ "bin": {
+ "gl-style-format": "dist/gl-style-format.mjs",
+ "gl-style-migrate": "dist/gl-style-migrate.mjs",
+ "gl-style-validate": "dist/gl-style-validate.mjs"
+ }
+ },
+ "node_modules/@maplibre/mlt": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.3.0.tgz",
+ "integrity": "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==",
+ "license": "(MIT OR Apache-2.0)",
+ "dependencies": {
+ "@mapbox/point-geometry": "^1.1.0"
+ }
+ },
+ "node_modules/@maplibre/vt-pbf": {
+ "version": "4.3.2",
+ "resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz",
+ "integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==",
+ "license": "MIT",
+ "dependencies": {
+ "@mapbox/point-geometry": "^1.1.0",
+ "@types/geojson": "^7946.0.16",
+ "pbf": "^5.1.0"
+ }
+ },
+ "node_modules/@mediapipe/tasks-vision": {
+ "version": "0.10.17",
+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.17.tgz",
+ "integrity": "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@monogrid/gainmap-js": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/@monogrid/gainmap-js/-/gainmap-js-3.4.0.tgz",
+ "integrity": "sha512-2Z0FATFHaoYJ8b+Y4y4Hgfn3FRFwuU5zRrk+9dFWp4uGAdHGqVEdP7HP+gLA3X469KXHmfupJaUbKo1b/aDKIg==",
+ "license": "MIT",
+ "dependencies": {
+ "promise-worker-transferable": "^1.0.4"
+ },
+ "peerDependencies": {
+ "three": ">= 0.159.0"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.151.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
+ "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm-eabi": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.86.0.tgz",
+ "integrity": "sha512-63Ozq6yQn79B2UxjSZ9huJmI+3/ZPI7hxAe6TyFh9oQL447KnIMoffOdtog+h4KILbQr61ZRvFPW5gYbAUgpgQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm64": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.86.0.tgz",
+ "integrity": "sha512-JdLGp44phbf/0Du236Dt06yfK6Qw8xhTFeDvHJdjk167r59OfP5+BL31mgMYVnswS8e+j6tFuccSY0QDC/lgCw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-arm64": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.86.0.tgz",
+ "integrity": "sha512-h+vkOr4ik6KLFCXdtNVEj9xfnXfNUpPoF95QjORdhiSpLqQePzcN81kGHjAgsw1/G7WBWK5KsFKbI2UK8EyzMA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-x64": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.86.0.tgz",
+ "integrity": "sha512-wbglRuH5eKsp68keTOOeKDHU1astWSRYFsh2bwKQTAPb44rD6kVgzYI1ZrAJRTc6/7PH55ZXFCQx0rQXrj0UdA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-freebsd-x64": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.86.0.tgz",
+ "integrity": "sha512-yTQ7QSOlNfQsrfbeVweTiegQJLKPjUKgXp/JpGiFzza6Hp29S9LAoH77TM3L0RjK39iQRZB5lk5iq2t241Mfag==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-gnueabihf": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.86.0.tgz",
+ "integrity": "sha512-QYJGy0E2Tv8GAayyBIeHFTwQb8u+zrvrOYrifuDGZDr9ad5XsDhiMScpZymhS9fwWjqrgG2ZUwT4vpY0ISqp4Q==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-musleabihf": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.86.0.tgz",
+ "integrity": "sha512-oQo83CafLT8p3qh0AGkN0tSUIh5Hm63mfDsoqUmBQUBnSZLNBAbyRaAftfGY5a0cKZ34dG6jAtMYgcY5kZqt5g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-gnu": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.86.0.tgz",
+ "integrity": "sha512-EM6wy5c2UM12qPb7iDJDBAZvHyfEJGH6iosFgaFiaRZpirz99//EHcUyD2KAskz07x1TULuiAtsojf4nvWWksw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-musl": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.86.0.tgz",
+ "integrity": "sha512-vCiUQb9ZNzZalxYRU4mlZwUqT5f+c7Sk9DwUOplWHtik3Dl4r3DVnUB5tBeRuTAUe6MUVCTylNW7TkkN8J1oTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-ppc64-gnu": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.86.0.tgz",
+ "integrity": "sha512-T0AzE89yjTYmOhB/hb6i+rWTpe2mYt+xiguBhs9DEPIJTZ1H8OYqsE4VxJHHw2Wlq8Mztwvp2P8NV87ZOuhPRw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-gnu": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.86.0.tgz",
+ "integrity": "sha512-s49r0K2f5Oc7fJoMUO1WkdhYK5Ob79uYRwWQ/XNoGysaOq3RUGmGUbHSuXiyydTTA+P9xEdDEnnlZVXiaSJhlw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-musl": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.86.0.tgz",
+ "integrity": "sha512-JIa2tYR8ayb3nvcMSZzn4O/xTy13S7MHllu7cBD+B5qDQXXSRy/Vwk1aNpiTjZmBJGwKCHOy/NvnY5Xcwg27uQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-s390x-gnu": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.86.0.tgz",
+ "integrity": "sha512-XwXMyBsAuWZkhZU74UNcfQKr1CJJAKnS80dZzOnjl6A4fKcf91IjFgidegQugMHA5SN8ulwDXEDV1yPntjXgQQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-gnu": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.86.0.tgz",
+ "integrity": "sha512-C1WjukSyMnr66b+w1/tV8RFVv6d9v0MzDf4p9IxVXknqgmTHBgZh1pccN1eHzFr0b9Tbb3OXoPsAAdAuHAQfeA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-musl": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.86.0.tgz",
+ "integrity": "sha512-ap6KLmvC38c6MdYzsIh25cXQupqYvjd37tMNftzrX1DCtkX1Gcf2B+S2B17dD4lKa5c5gJog7DQJyDo82PBKyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-openharmony-arm64": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.86.0.tgz",
+ "integrity": "sha512-996Q9w/2GLwNyy5Djs39Jt09aFlr4b7TPhoj7dvo5FHmcyiF68nPz73HNc5UAYKIYeK+M9JzPQ4Wg1r1dXvP6A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-arm64-msvc": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.86.0.tgz",
+ "integrity": "sha512-9uTCHYTknNkug5+46ViSoUMuOuGWK61D87QnblU6CXaWKJC630Z7dbls61vdHxya/cR2ycQZ6Mm6ckgF6Cag5g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-ia32-msvc": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.86.0.tgz",
+ "integrity": "sha512-a47ga7EKVfMU8rO0i1m3mGwfNRj3FhQyt1d/ukO/E9u1HHF3KpR3tyb3VhuJBGEVPF8uR4exSyHUyx7xbE+uxw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-x64-msvc": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.86.0.tgz",
+ "integrity": "sha512-az4dzifCRzES1crwu6pDFXzJTIanrdxXFL9TbiJWrx9LKcuacbR83aPvxDA1LKLNswi/RoqitC7Afcflhu3zBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@react-three/drei": {
+ "version": "10.7.9",
+ "resolved": "https://registry.npmjs.org/@react-three/drei/-/drei-10.7.9.tgz",
+ "integrity": "sha512-wP4Y6o58KFi+hT1zCfjJarRtPCT6WW/lo53WMiA/aCORuUvBzW916XsCtadnIB1KB+3IQNcDU5JeVh/gYb8MYw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.26.0",
+ "@mediapipe/tasks-vision": "0.10.17",
+ "@monogrid/gainmap-js": "^3.0.6",
+ "@use-gesture/react": "^10.3.1",
+ "camera-controls": "^3.1.0",
+ "cross-env": "^7.0.3",
+ "detect-gpu": "^5.0.56",
+ "glsl-noise": "^0.0.0",
+ "hls.js": "^1.5.17",
+ "maath": "^0.10.8",
+ "meshline": "^3.3.1",
+ "stats-gl": "^2.2.8",
+ "stats.js": "^0.17.0",
+ "suspend-react": "^0.1.3",
+ "three-mesh-bvh": "^0.8.3",
+ "three-stdlib": "^2.35.6",
+ "troika-three-text": "^0.52.4",
+ "tunnel-rat": "^0.1.2",
+ "use-sync-external-store": "^1.4.0",
+ "utility-types": "^3.11.0",
+ "zustand": "^5.0.1"
+ },
+ "peerDependencies": {
+ "@react-three/fiber": "^9.0.0",
+ "react": "^19",
+ "react-dom": "^19",
+ "three": ">=0.159"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@react-three/drei/node_modules/three-mesh-bvh": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.8.3.tgz",
+ "integrity": "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">= 0.159.0"
+ }
+ },
+ "node_modules/@react-three/fiber": {
+ "version": "9.8.1",
+ "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-9.8.1.tgz",
+ "integrity": "sha512-GbNP4r6F/gpclFKkLGHzXcuwFWAzLyKsmrQGcDuwK3wQnwLH6F1TfGtEYjHy8OQoGsajwT19B9jtVLLjjfH09w==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.17.8",
+ "@types/webxr": "*",
+ "base64-js": "^1.5.1",
+ "buffer": "^6.0.3",
+ "its-fine": "^2.1.1",
+ "react-use-measure": "^2.1.7",
+ "scheduler": "^0.28.0",
+ "suspend-react": "^0.1.3",
+ "use-sync-external-store": "^1.4.0",
+ "zustand": "^5.0.3"
+ },
+ "peerDependencies": {
+ "expo": ">=43.0",
+ "expo-asset": ">=8.4",
+ "expo-file-system": ">=11.0",
+ "expo-gl": ">=11.0",
+ "react": ">=19 <19.4",
+ "react-dom": ">=19 <19.4",
+ "react-native": ">=0.78",
+ "three": ">=0.156"
+ },
+ "peerDependenciesMeta": {
+ "expo": {
+ "optional": true
+ },
+ "expo-asset": {
+ "optional": true
+ },
+ "expo-file-system": {
+ "optional": true
+ },
+ "expo-gl": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ },
+ "react-native": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@react-three/postprocessing": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@react-three/postprocessing/-/postprocessing-3.1.3.tgz",
+ "integrity": "sha512-LhCTSC+nli1agIIIgrhJalvJcdSy7/DOXG5EDGxKVlVsrqUxMPYlMnRN/QqgSAjGPKmnnuiEmpVQtOkTKwiidw==",
+ "license": "MIT",
+ "dependencies": {
+ "maath": "^0.10.8",
+ "n8ao": "^2.0.0"
+ },
+ "peerDependencies": {
+ "@react-three/fiber": ">=9.7.0",
+ "postprocessing": "^6.36.0",
+ "react": "^19.0.0",
+ "three": ">= 0.156.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
+ "integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
+ "integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
+ "integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
+ "integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
+ "integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
+ "integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
+ "integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
+ "integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
+ "integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
+ "integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
+ "integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
+ "integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
+ "integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
+ "integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
+ "integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
+ "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/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/debug": {
+ "version": "4.1.13",
+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/ms": "*"
+ }
+ },
+ "node_modules/@types/draco3d": {
+ "version": "1.4.10",
+ "resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz",
+ "integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/estree-jsx": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",
+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "*"
+ }
+ },
+ "node_modules/@types/geojson": {
+ "version": "7946.0.16",
+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/hast": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz",
+ "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/mdast": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/ms": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "24.19.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.0.tgz",
+ "integrity": "sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": ">=7.24.0 <7.24.7"
+ }
+ },
+ "node_modules/@types/offscreencanvas": {
+ "version": "2019.7.3",
+ "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz",
+ "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/proj4": {
+ "version": "2.5.6",
+ "resolved": "https://registry.npmjs.org/@types/proj4/-/proj4-2.5.6.tgz",
+ "integrity": "sha512-zfMrPy9fx+8DchqM0kIUGeu2tTVB5ApO1KGAYcSGFS8GoqRIkyL41xq2yCx/iV3sOLzo7v4hEgViSLTiPI1L0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^19.3.0"
+ }
+ },
+ "node_modules/@types/react-reconciler": {
+ "version": "0.33.1",
+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.33.1.tgz",
+ "integrity": "sha512-0kF59ji2mKuHUd5wytHSpmORybMYVerJvq0K10pz9ZFoOlJ3e+w1LBjLshWpCrokeyQOioRodNbO4PH4ddvRfg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*"
+ }
+ },
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.186.0",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.186.0.tgz",
+ "integrity": "sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "fflate": "~0.8.3",
+ "meshoptimizer": "~1.1.1"
+ }
+ },
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "license": "MIT"
+ },
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "license": "MIT"
+ },
+ "node_modules/@ungap/structured-clone": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz",
+ "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==",
+ "license": "ISC"
+ },
+ "node_modules/@use-gesture/core": {
+ "version": "10.3.1",
+ "resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.1.tgz",
+ "integrity": "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==",
+ "license": "MIT"
+ },
+ "node_modules/@use-gesture/react": {
+ "version": "10.3.1",
+ "resolved": "https://registry.npmjs.org/@use-gesture/react/-/react-10.3.1.tgz",
+ "integrity": "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==",
+ "license": "MIT",
+ "dependencies": {
+ "@use-gesture/core": "10.3.1"
+ },
+ "peerDependencies": {
+ "react": ">= 16.8.0"
+ }
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "6.1.1",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.1.tgz",
+ "integrity": "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rolldown/pluginutils": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "oxc-transform-react": "^0.145.0",
+ "vite": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@rolldown/plugin-babel": {
+ "optional": true
+ },
+ "babel-plugin-react-compiler": {
+ "optional": true
+ },
+ "oxc-transform-react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bail": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/bidi-js": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
+ "license": "MIT",
+ "dependencies": {
+ "require-from-string": "^2.0.2"
+ }
+ },
+ "node_modules/buffer": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.2.1"
+ }
+ },
+ "node_modules/camera-controls": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/camera-controls/-/camera-controls-3.1.2.tgz",
+ "integrity": "sha512-xkxfpG2ECZ6Ww5/9+kf4mfg1VEYAoe9aDSY+IwF0UEs7qEzwy0aVRfs2grImIECs/PoBtWFrh7RXsQkwG922JA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=22.0.0",
+ "npm": ">=10.5.1"
+ },
+ "peerDependencies": {
+ "three": ">=0.126.1"
+ }
+ },
+ "node_modules/ccount": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-html4": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/clipper2-ts": {
+ "version": "2.0.1-18",
+ "resolved": "https://registry.npmjs.org/clipper2-ts/-/clipper2-ts-2.0.1-18.tgz",
+ "integrity": "sha512-WuRO1ZHzyYTVHY78r4wVWVydvQ+1lx9qZ+DeZa/8zhvrxIgCVzElJ6lwSMGtUUKFPefhvfJsHZ5C9RNkgisCOQ==",
+ "license": "BSL-1.0",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/cross-env": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
+ "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
+ "license": "MIT",
+ "dependencies": {
+ "cross-spawn": "^7.0.1"
+ },
+ "bin": {
+ "cross-env": "src/bin/cross-env.js",
+ "cross-env-shell": "src/bin/cross-env-shell.js"
+ },
+ "engines": {
+ "node": ">=10.14",
+ "npm": ">=6",
+ "yarn": ">=1"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decode-named-character-reference": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/detect-gpu": {
+ "version": "5.0.70",
+ "resolved": "https://registry.npmjs.org/detect-gpu/-/detect-gpu-5.0.70.tgz",
+ "integrity": "sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==",
+ "license": "MIT",
+ "dependencies": {
+ "webgl-constants": "^1.1.1"
+ }
+ },
+ "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/devlop": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/draco3d": {
+ "version": "1.5.7",
+ "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",
+ "integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/earcut": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.2.4.tgz",
+ "integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==",
+ "license": "ISC"
+ },
+ "node_modules/escape-string-regexp": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",
+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/estree-util-is-identifier-name": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",
+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "license": "MIT"
+ },
+ "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/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "license": "MIT"
+ },
+ "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/gl-matrix": {
+ "version": "3.4.4",
+ "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz",
+ "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==",
+ "license": "MIT"
+ },
+ "node_modules/glsl-noise": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/glsl-noise/-/glsl-noise-0.0.0.tgz",
+ "integrity": "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==",
+ "license": "MIT"
+ },
+ "node_modules/hast-util-to-jsx-runtime": {
+ "version": "2.3.6",
+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",
+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "devlop": "^1.0.0",
+ "estree-util-is-identifier-name": "^3.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "mdast-util-mdx-expression": "^2.0.0",
+ "mdast-util-mdx-jsx": "^3.0.0",
+ "mdast-util-mdxjs-esm": "^2.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "style-to-js": "^1.0.0",
+ "unist-util-position": "^5.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-whitespace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hls.js": {
+ "version": "1.7.3",
+ "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.3.tgz",
+ "integrity": "sha512-MsPlx6yVW4Qv4C7mEVou4/gk/5cN2dVxOTnrNjPSmyH2f0Ln+/UkG10Ax1PE6OvrmTVPKgQYozTtBaPOuCzq7A==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/html-parse-stringify": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz",
+ "integrity": "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://locize.com"
+ }
+ },
+ "node_modules/html-url-attributes": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/i18next": {
+ "version": "26.4.2",
+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.4.2.tgz",
+ "integrity": "sha512-RX+R0VLg13IbvRuJSxnqykUFS9vQZTl8wYpWPCIUDWVrSGjsQywB5Y+pjzrkboxGAuYfJZVH1InFTdgBdxq6ug==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://www.locize.com/i18next"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
+ },
+ {
+ "type": "individual",
+ "url": "https://www.locize.com"
+ }
+ ],
+ "license": "MIT",
+ "peerDependencies": {
+ "typescript": "^5 || ^6 || ^7"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/i18next-browser-languagedetector": {
+ "version": "8.2.1",
+ "resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-8.2.1.tgz",
+ "integrity": "sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.23.2"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/immediate": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
+ "license": "MIT"
+ },
+ "node_modules/inline-style-parser": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",
+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",
+ "license": "MIT"
+ },
+ "node_modules/is-alphabetical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-alphabetical": "^2.0.0",
+ "is-decimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-plain-obj": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz",
+ "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==",
+ "license": "MIT"
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/its-fine": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-2.1.1.tgz",
+ "integrity": "sha512-C5ZoVkeqSt0Aje0tzESO+iT/EQpNFNL39GkP7mCACtoZUFD6GcyerFCr6kp0ZtiII4W9HoYkY48Soy5xE/uHKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/react-reconciler": "^0.28.9"
+ },
+ "peerDependencies": {
+ "react": "^19.0.0"
+ }
+ },
+ "node_modules/its-fine/node_modules/@types/react-reconciler": {
+ "version": "0.28.9",
+ "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.9.tgz",
+ "integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*"
+ }
+ },
+ "node_modules/json-stringify-pretty-compact": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/json-stringify-pretty-compact/-/json-stringify-pretty-compact-4.0.0.tgz",
+ "integrity": "sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==",
+ "license": "MIT"
+ },
+ "node_modules/kdbush": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz",
+ "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==",
+ "license": "ISC"
+ },
+ "node_modules/konva": {
+ "version": "10.7.0",
+ "resolved": "https://registry.npmjs.org/konva/-/konva-10.7.0.tgz",
+ "integrity": "sha512-2CwuytBrOlTh7WHCSeXyUeysB2rpwHruUUDD5etYtrzijkCVH+00+CQz5fJUGI0hm7mzxxDLYLw4Wpo+8QGJ4g==",
+ "funding": [
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/lavrton"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/konva"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/lavrton"
+ }
+ ],
+ "license": "MIT",
+ "peerDependencies": {
+ "canvas": "^3.0.0",
+ "skia-canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ },
+ "skia-canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/lie": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
+ "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,
+ "libc": [
+ "glibc"
+ ],
+ "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,
+ "libc": [
+ "musl"
+ ],
+ "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,
+ "libc": [
+ "glibc"
+ ],
+ "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,
+ "libc": [
+ "musl"
+ ],
+ "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/longest-streak": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",
+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/maath": {
+ "version": "0.10.8",
+ "resolved": "https://registry.npmjs.org/maath/-/maath-0.10.8.tgz",
+ "integrity": "sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/three": ">=0.134.0",
+ "three": ">=0.134.0"
+ }
+ },
+ "node_modules/maplibre-gl": {
+ "version": "6.11.2",
+ "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.11.2.tgz",
+ "integrity": "sha512-Xh06pxoipjX/Ad1sUPGhiNh9go9naCNGZZ1IJm3sIeqK1kYGuMaMDSTIGDQ2igOLfVyukJU7kvEOA089VO7Z7g==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@mapbox/point-geometry": "^1.1.0",
+ "@mapbox/tiny-sdf": "^2.2.0",
+ "@mapbox/unitbezier": "^1.0.0",
+ "@mapbox/vector-tile": "^3.0.0",
+ "@maplibre/geojson-vt": "^6.1.1",
+ "@maplibre/maplibre-gl-style-spec": "^26.4.4",
+ "@maplibre/mlt": "^1.3.0",
+ "@maplibre/vt-pbf": "^4.3.2",
+ "@types/geojson": "^7946.0.16",
+ "bidi-js": "^1.1.0",
+ "earcut": "^3.2.3",
+ "gl-matrix": "^3.4.4",
+ "kdbush": "^4.1.0",
+ "murmurhash-js": "^1.0.0",
+ "pbf": "^5.1.2",
+ "potpack": "^2.1.0",
+ "quickselect": "^3.0.0",
+ "tinyqueue": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=16.14.0",
+ "npm": ">=8.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/maplibre/maplibre-gl-js?sponsor=1"
+ }
+ },
+ "node_modules/maplibre-gl/node_modules/potpack": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-2.1.0.tgz",
+ "integrity": "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==",
+ "license": "ISC"
+ },
+ "node_modules/markdown-table": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/mdast-util-find-and-replace": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",
+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "escape-string-regexp": "^5.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-from-markdown": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",
+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark": "^4.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",
+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-gfm-autolink-literal": "^2.0.0",
+ "mdast-util-gfm-footnote": "^2.0.0",
+ "mdast-util-gfm-strikethrough": "^2.0.0",
+ "mdast-util-gfm-table": "^2.0.0",
+ "mdast-util-gfm-task-list-item": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-autolink-literal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",
+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-find-and-replace": "^3.0.0",
+ "micromark-util-character": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-strikethrough": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz",
+ "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-table": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",
+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "markdown-table": "^3.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-gfm-task-list-item": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",
+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-expression": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",
+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdx-jsx": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",
+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "devlop": "^1.1.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "parse-entities": "^4.0.0",
+ "stringify-entities": "^4.0.0",
+ "unist-util-stringify-position": "^4.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-mdxjs-esm": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",
+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree-jsx": "^1.0.0",
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "mdast-util-to-markdown": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-phrasing": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",
+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-hast": {
+ "version": "13.2.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "trim-lines": "^3.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-markdown": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.3.tgz",
+ "integrity": "sha512-wgyJtgUkUcdU7zci7uuwc/tzoAhm0TswWhaXuvnWolqug+8jY7bgNkBBL0dYBnHgc/tHL7lCzRdPsdUxUKKBqw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "@types/unist": "^3.0.0",
+ "longest-streak": "^3.0.0",
+ "mdast-util-phrasing": "^4.0.0",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-decode-string": "^2.0.0",
+ "micromark-util-html-tag-name": "^2.0.0",
+ "unist-util-visit": "^5.0.0",
+ "zwitch": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mdast-util-to-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",
+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/meshline": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/meshline/-/meshline-3.3.1.tgz",
+ "integrity": "sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">=0.137"
+ }
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "license": "MIT"
+ },
+ "node_modules/mgrs": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/mgrs/-/mgrs-1.0.0.tgz",
+ "integrity": "sha512-awNbTOqCxK1DBGjalK3xqWIstBZgN6fxsMSiXLs9/spqWkF2pAhb2rrYCFSsr1/tT7PhcDGjZndG8SWYn0byYA==",
+ "license": "MIT"
+ },
+ "node_modules/micromark": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz",
+ "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/debug": "^4.0.0",
+ "debug": "^4.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-edit-map": "^1.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-core-commonmark": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz",
+ "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-factory-destination": "^2.0.0",
+ "micromark-factory-label": "^2.0.0",
+ "micromark-factory-space": "^2.1.0",
+ "micromark-factory-title": "^2.0.0",
+ "micromark-factory-whitespace": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-edit-map": "^1.0.0",
+ "micromark-util-html-tag-name": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-subtokenize": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.3"
+ }
+ },
+ "node_modules/micromark-extension-gfm": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",
+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-extension-gfm-autolink-literal": "^2.0.0",
+ "micromark-extension-gfm-footnote": "^2.0.0",
+ "micromark-extension-gfm-strikethrough": "^2.0.0",
+ "micromark-extension-gfm-table": "^2.0.0",
+ "micromark-extension-gfm-tagfilter": "^2.0.0",
+ "micromark-extension-gfm-task-list-item": "^2.0.0",
+ "micromark-util-combine-extensions": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-autolink-literal": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",
+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-footnote": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",
+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-core-commonmark": "^2.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-normalize-identifier": "^2.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-strikethrough": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",
+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-classify-character": "^2.0.0",
+ "micromark-util-resolve-all": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-table": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz",
+ "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-tagfilter": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",
+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-extension-gfm-task-list-item": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",
+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/micromark-factory-destination": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",
+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-label": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",
+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-space": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz",
+ "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-title": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",
+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-factory-whitespace": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",
+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-factory-space": "^2.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-character": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-chunked": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",
+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-classify-character": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",
+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-combine-extensions": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",
+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-numeric-character-reference": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",
+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-decode-string": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",
+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "decode-named-character-reference": "^1.0.0",
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-decode-numeric-character-reference": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-edit-map": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz",
+ "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-encode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-html-tag-name": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",
+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-normalize-identifier": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",
+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-resolve-all": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",
+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-sanitize-uri": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-subtokenize": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",
+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "devlop": "^1.0.0",
+ "micromark-util-chunked": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-symbol": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-types": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz",
+ "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==",
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/murmurhash-js": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/murmurhash-js/-/murmurhash-js-1.0.0.tgz",
+ "integrity": "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==",
+ "license": "MIT"
+ },
+ "node_modules/n8ao": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/n8ao/-/n8ao-2.0.1.tgz",
+ "integrity": "sha512-MoP1QKUdj4/3cKEnhFl917t0eQwWGER1l43ckz5mNOPyYWGRDGQbVoTOQz/VBvy01in6QVNG+AL6Xxx5AjZBYA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "postprocessing": ">=6.30.0",
+ "three": ">=0.137"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.19",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
+ "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/oxlint": {
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.86.0.tgz",
+ "integrity": "sha512-og0lhgvZfgGF//gOOmZXvtr+GmBbAGEnbEhv/QUg7UW2Wi4wHMnJbnMD+zuHgPdJxdklfgpPupdlAaAySyxrZg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "oxlint": "bin/oxlint"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ },
+ "optionalDependencies": {
+ "@oxlint/binding-android-arm-eabi": "1.86.0",
+ "@oxlint/binding-android-arm64": "1.86.0",
+ "@oxlint/binding-darwin-arm64": "1.86.0",
+ "@oxlint/binding-darwin-x64": "1.86.0",
+ "@oxlint/binding-freebsd-x64": "1.86.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.86.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.86.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.86.0",
+ "@oxlint/binding-linux-arm64-musl": "1.86.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.86.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.86.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.86.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.86.0",
+ "@oxlint/binding-linux-x64-gnu": "1.86.0",
+ "@oxlint/binding-linux-x64-musl": "1.86.0",
+ "@oxlint/binding-openharmony-arm64": "1.86.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.86.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.86.0",
+ "@oxlint/binding-win32-x64-msvc": "1.86.0"
+ },
+ "peerDependencies": {
+ "oxlint-tsgolint": ">=7.0.2003",
+ "vite-plus": "*"
+ },
+ "peerDependenciesMeta": {
+ "oxlint-tsgolint": {
+ "optional": true
+ },
+ "vite-plus": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/parse-entities": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^2.0.0",
+ "character-entities-legacy": "^3.0.0",
+ "character-reference-invalid": "^2.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "is-alphanumerical": "^2.0.0",
+ "is-decimal": "^2.0.0",
+ "is-hexadecimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
+ "license": "MIT"
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/pbf": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
+ "integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "resolve-protobuf-schema": "^2.1.0"
+ },
+ "bin": {
+ "pbf": "bin/pbf"
+ }
+ },
+ "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.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "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.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postprocessing": {
+ "version": "6.39.5",
+ "resolved": "https://registry.npmjs.org/postprocessing/-/postprocessing-6.39.5.tgz",
+ "integrity": "sha512-YmH+t74J2X1lwYjKzK/tgs9C9kqWWPB9JwZiDF5mEf4BdCEAmEFbO8lXBA7NM0/j4g+x6FgD/Tt5/kT7ogbEDA==",
+ "license": "Zlib",
+ "peer": true,
+ "peerDependencies": {
+ "three": ">= 0.168.0 < 0.187.0"
+ }
+ },
+ "node_modules/potpack": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz",
+ "integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==",
+ "license": "ISC"
+ },
+ "node_modules/proj4": {
+ "version": "2.22.0",
+ "resolved": "https://registry.npmjs.org/proj4/-/proj4-2.22.0.tgz",
+ "integrity": "sha512-MVvH09QrYm3A235rcX39WDiCKanrBiblu28l0KYIn/B2DofmYhvP/LLS43kE66jNDfx/P1l/nah3JmsAq8UgbQ==",
+ "license": "MIT",
+ "dependencies": {
+ "mgrs": "1.0.0",
+ "wkt-parser": "^1.5.5"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ahocevar"
+ },
+ "peerDependencies": {
+ "geotiff": "*"
+ },
+ "peerDependenciesMeta": {
+ "geotiff": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/promise-worker-transferable": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/promise-worker-transferable/-/promise-worker-transferable-1.0.4.tgz",
+ "integrity": "sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "is-promise": "^2.1.0",
+ "lie": "^3.0.2"
+ }
+ },
+ "node_modules/property-information": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.2.0.tgz",
+ "integrity": "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/protocol-buffers-schema": {
+ "version": "3.6.1",
+ "resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",
+ "integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
+ "license": "MIT"
+ },
+ "node_modules/quickselect": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",
+ "integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",
+ "license": "ISC"
+ },
+ "node_modules/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.28.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.0"
+ }
+ },
+ "node_modules/react-i18next": {
+ "version": "17.0.15",
+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.15.tgz",
+ "integrity": "sha512-7uYpx/oBkesLto7cOzOmfITlUBaXHCAcFahmgETMfWr8nbbWRRnVGvz8wsH/xpbNcyoH+NpCcnOQEqWPMO6/hw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.29.7",
+ "html-parse-stringify": "^4.0.1",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "peerDependencies": {
+ "i18next": ">= 26.2.0",
+ "react": ">= 16.8.0",
+ "typescript": "^5 || ^6 || ^7"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ },
+ "react-native": {
+ "optional": true
+ },
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/react-konva": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-konva/-/react-konva-19.3.0.tgz",
+ "integrity": "sha512-YEDAdM0PUUUJcTzXAKXMRO2+krSE+hhjGsupWjy6UBtzyFI6f2LkwSYQresl7WwvD+j3fbMy0uj3jtnytKqk9Q==",
+ "funding": [
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/lavrton"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/konva"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/lavrton"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@types/react-reconciler": "^0.33.0",
+ "its-fine": "^2.0.0",
+ "react-reconciler": "0.34.0",
+ "scheduler": "0.28.0"
+ },
+ "peerDependencies": {
+ "konva": "^8.0.1 || ^7.2.5 || ^9.0.0 || ^10.0.0",
+ "react": "^19.3.0",
+ "react-dom": "^19.3.0"
+ }
+ },
+ "node_modules/react-markdown": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "devlop": "^1.0.0",
+ "hast-util-to-jsx-runtime": "^2.0.0",
+ "html-url-attributes": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-rehype": "^11.0.0",
+ "unified": "^11.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18",
+ "react": ">=18"
+ }
+ },
+ "node_modules/react-reconciler": {
+ "version": "0.34.0",
+ "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.34.0.tgz",
+ "integrity": "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.28.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.0"
+ }
+ },
+ "node_modules/react-use-measure": {
+ "version": "2.1.7",
+ "resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",
+ "integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": ">=16.13",
+ "react-dom": ">=16.13"
+ },
+ "peerDependenciesMeta": {
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/remark-gfm": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-gfm": "^3.0.0",
+ "micromark-extension-gfm": "^3.0.0",
+ "remark-parse": "^11.0.0",
+ "remark-stringify": "^11.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-parse": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",
+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-from-markdown": "^2.0.0",
+ "micromark-util-types": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-rehype": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",
+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "unified": "^11.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/remark-stringify": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",
+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mdast": "^4.0.0",
+ "mdast-util-to-markdown": "^2.0.0",
+ "unified": "^11.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/resolve-protobuf-schema": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
+ "integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "protocol-buffers-schema": "^3.3.1"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
+ "integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.151.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.11",
+ "@rolldown/binding-android-arm64": "1.2.11",
+ "@rolldown/binding-darwin-arm64": "1.2.11",
+ "@rolldown/binding-darwin-x64": "1.2.11",
+ "@rolldown/binding-freebsd-x64": "1.2.11",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.11",
+ "@rolldown/binding-linux-arm64-musl": "1.2.11",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.11",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-musl": "1.2.11",
+ "@rolldown/binding-openharmony-arm64": "1.2.11",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.11",
+ "@rolldown/binding-win32-x64-msvc": "1.2.11"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.28.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
+ "license": "MIT"
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/stats-gl": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/stats-gl/-/stats-gl-2.4.2.tgz",
+ "integrity": "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/three": "*",
+ "three": "^0.170.0"
+ },
+ "peerDependencies": {
+ "@types/three": "*",
+ "three": "*"
+ }
+ },
+ "node_modules/stats-gl/node_modules/three": {
+ "version": "0.170.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
+ "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==",
+ "license": "MIT"
+ },
+ "node_modules/stats.js": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz",
+ "integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==",
+ "license": "MIT"
+ },
+ "node_modules/stringify-entities": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities-html4": "^2.0.0",
+ "character-entities-legacy": "^3.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/style-to-js": {
+ "version": "1.1.21",
+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "style-to-object": "1.0.14"
+ }
+ },
+ "node_modules/style-to-object": {
+ "version": "1.0.14",
+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",
+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",
+ "license": "MIT",
+ "dependencies": {
+ "inline-style-parser": "0.2.7"
+ }
+ },
+ "node_modules/suspend-react": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz",
+ "integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": ">=17.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/three-bvh-csg": {
+ "version": "0.0.18",
+ "resolved": "https://registry.npmjs.org/three-bvh-csg/-/three-bvh-csg-0.0.18.tgz",
+ "integrity": "sha512-M3GCZMmGFgASGuDf+YMamM83nVlD/vdwzVHcYbFxgW+g1S7/nKPiuY00YVHOMbjmJPh8mLevGZL65ItHUuGt2w==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">=0.179.0",
+ "three-mesh-bvh": ">=0.9.7"
+ }
+ },
+ "node_modules/three-mesh-bvh": {
+ "version": "0.9.15",
+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.15.tgz",
+ "integrity": "sha512-9xdEDkCzFoT8VPFH9DznwFSdbaIEjMvM106Iqq7TJurrIheUKDcdW4prfJTCxryih4XS/UxWs0H3K4MLMRFyOQ==",
+ "license": "MIT",
+ "peer": true,
+ "peerDependencies": {
+ "three": ">= 0.159.0"
+ }
+ },
+ "node_modules/three-stdlib": {
+ "version": "2.36.1",
+ "resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.1.tgz",
+ "integrity": "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/draco3d": "^1.4.0",
+ "@types/offscreencanvas": "^2019.6.4",
+ "@types/webxr": "^0.5.2",
+ "draco3d": "^1.4.1",
+ "fflate": "^0.6.9",
+ "potpack": "^1.0.1"
+ },
+ "peerDependencies": {
+ "three": ">=0.128.0"
+ }
+ },
+ "node_modules/three-stdlib/node_modules/fflate": {
+ "version": "0.6.11",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.11.tgz",
+ "integrity": "sha512-3JyEFWGjFn7zHmoa9+zG1BmW7X2okcmAB+0Cnu9UFbVs/jCBnl2A8o065ZlXiw145K3eBM3uLuzrYXC0RK7eDg==",
+ "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/tinyqueue": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-3.0.0.tgz",
+ "integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",
+ "license": "ISC"
+ },
+ "node_modules/trim-lines": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/troika-three-text": {
+ "version": "0.52.5",
+ "resolved": "https://registry.npmjs.org/troika-three-text/-/troika-three-text-0.52.5.tgz",
+ "integrity": "sha512-Ry3jRhic9pzcY4JduSvRRyDmVOSqEW19gT4vtK+aCiPNVcDlmkxvGG0YbFd36RTDq1wExOupXnvNF/j1oiHHDA==",
+ "license": "MIT",
+ "dependencies": {
+ "bidi-js": "^1.0.2",
+ "troika-three-utils": "^0.52.5",
+ "troika-worker-utils": "^0.52.0",
+ "webgl-sdf-generator": "1.1.1"
+ },
+ "peerDependencies": {
+ "three": ">=0.125.0"
+ }
+ },
+ "node_modules/troika-three-utils": {
+ "version": "0.52.5",
+ "resolved": "https://registry.npmjs.org/troika-three-utils/-/troika-three-utils-0.52.5.tgz",
+ "integrity": "sha512-WsePbcX8RtfidRfsxK1eCZCjF81ZDzAKHH/evLs0hdV2wpoCb0vArGZHdzdOJrSS3k4zfdtbKDaBh8+phkrYnw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">=0.125.0"
+ }
+ },
+ "node_modules/troika-worker-utils": {
+ "version": "0.52.0",
+ "resolved": "https://registry.npmjs.org/troika-worker-utils/-/troika-worker-utils-0.52.0.tgz",
+ "integrity": "sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw==",
+ "license": "MIT"
+ },
+ "node_modules/trough": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",
+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/tunnel-rat": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/tunnel-rat/-/tunnel-rat-0.1.2.tgz",
+ "integrity": "sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==",
+ "license": "MIT",
+ "dependencies": {
+ "zustand": "^4.3.2"
+ }
+ },
+ "node_modules/tunnel-rat/node_modules/zustand": {
+ "version": "4.5.7",
+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+ "license": "MIT",
+ "dependencies": {
+ "use-sync-external-store": "^1.2.2"
+ },
+ "engines": {
+ "node": ">=12.7.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8",
+ "immer": ">=9.0.6",
+ "react": ">=16.8"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "immer": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/typescript": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
+ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
+ "devOptional": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.24.6",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unified": {
+ "version": "11.0.5",
+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "bail": "^2.0.0",
+ "devlop": "^1.0.0",
+ "extend": "^3.0.0",
+ "is-plain-obj": "^4.0.0",
+ "trough": "^2.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-is": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-stringify-position": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",
+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/use-sync-external-store": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz",
+ "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/utility-types": {
+ "version": "3.11.0",
+ "resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",
+ "integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/vfile": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-message": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.1",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
+ "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.9",
+ "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
+ }
+ }
+ },
+ "node_modules/webgl-constants": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/webgl-constants/-/webgl-constants-1.1.1.tgz",
+ "integrity": "sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg=="
+ },
+ "node_modules/webgl-sdf-generator": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/webgl-sdf-generator/-/webgl-sdf-generator-1.1.1.tgz",
+ "integrity": "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==",
+ "license": "MIT"
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/wkt-parser": {
+ "version": "1.5.6",
+ "resolved": "https://registry.npmjs.org/wkt-parser/-/wkt-parser-1.5.6.tgz",
+ "integrity": "sha512-cqHU3lzGt/gt2OqIORP0uVy5yeOX43WABmgFkmJsmcqH3HhQo9PiJG6ftytwGKmpQUbegeX7+pQc2BuNCRfcrw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ahocevar"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "node_modules/zundo": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/zundo/-/zundo-2.3.0.tgz",
+ "integrity": "sha512-4GXYxXA17SIKYhVbWHdSEU04P697IMyVGXrC2TnzoyohEAWytFNOKqOp5gTGvaW93F/PM5Y0evbGtOPF0PWQwQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/charkour"
+ },
+ "peerDependencies": {
+ "zustand": "^4.3.0 || ^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "zustand": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/zustand": {
+ "version": "5.0.15",
+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz",
+ "integrity": "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ },
+ "peerDependencies": {
+ "@types/react": ">=18.0.0",
+ "immer": ">=9.0.6",
+ "react": ">=18.0.0",
+ "use-sync-external-store": ">=1.2.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "immer": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "use-sync-external-store": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/zwitch": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..73f3e4c
--- /dev/null
+++ b/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "house-planner",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "dev:api": "php -S 127.0.0.1:8000 -t public scripts/dev-router.php",
+ "build": "tsc -b && vite build",
+ "lint": "oxlint",
+ "preview": "vite preview",
+ "plan:validate": "node scripts/plan-validate.mts public/plans/demo.json",
+ "deploy": "scripts/deploy.sh"
+ },
+ "dependencies": {
+ "@react-three/drei": "^10.7.9",
+ "@react-three/fiber": "^9.8.1",
+ "@react-three/postprocessing": "^3.1.3",
+ "clipper2-ts": "^2.0.1-18",
+ "i18next": "^26.4.2",
+ "i18next-browser-languagedetector": "^8.2.1",
+ "konva": "^10.7.0",
+ "maplibre-gl": "^6.11.2",
+ "n8ao": "^2.0.1",
+ "proj4": "^2.22.0",
+ "react": "^19.2.8",
+ "react-dom": "^19.2.8",
+ "react-i18next": "^17.0.15",
+ "react-konva": "^19.3.0",
+ "react-markdown": "^10.1.0",
+ "remark-gfm": "^4.0.1",
+ "three": "^0.186.1",
+ "three-bvh-csg": "^0.0.18",
+ "zod": "^4.6.5",
+ "zundo": "^2.3.0",
+ "zustand": "^5.0.15"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "@types/proj4": "^2.5.6",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.7",
+ "@types/three": "^0.186.0",
+ "@vitejs/plugin-react": "^6.1.1",
+ "oxlint": "^1.81.0",
+ "typescript": "~6.0.2",
+ "vite": "^8.3.0"
+ }
+}
diff --git a/public/api/.htaccess b/public/api/.htaccess
new file mode 100644
index 0000000..3f29b86
--- /dev/null
+++ b/public/api/.htaccess
@@ -0,0 +1,7 @@
+RewriteEngine On
+<FilesMatch "^_">
+Require all denied
+</FilesMatch>
+<Files ".htaccess">
+Require all denied
+</Files>
diff --git a/public/api/_demo.php b/public/api/_demo.php
new file mode 100644
index 0000000..f0a066b
--- /dev/null
+++ b/public/api/_demo.php
@@ -0,0 +1,172 @@
+<?php
+
+const DEMO_PLAN_MAX_BYTES = 1048576;
+const DEMO_RESET_SECONDS = 3600;
+const DEMO_WRITES_PER_MINUTE = 30;
+const DEMO_MAX_SNAPSHOTS = 20;
+const DEMO_HEADER = 'X-House-Demo: 1';
+
+function is_demo(): bool
+{
+ static $demo = null;
+ if ($demo === null) {
+ $env = strtolower(trim((string)getenv('HOUSE_DEMO')));
+ $demo = in_array($env, ['1', 'true', 'yes', 'on'], true)
+ || (find_storage() !== null && !empty(load_config()['demo']));
+ }
+ return $demo;
+}
+
+function demo_plan_file(): string
+{
+ return webroot_dir() . '/plans/demo.json';
+}
+
+function demo_marker(): string
+{
+ return storage_dir() . '/.demo-reset';
+}
+
+function demo_reset_due(): bool
+{
+ $m = demo_marker();
+ clearstatcache(true, $m);
+ return !is_file($m) || time() - (int)filemtime($m) >= DEMO_RESET_SECONDS;
+}
+
+function demo_open_htaccess(): string
+{
+ return "<IfModule mod_headers.c>\n"
+ . "Header always set Cache-Control \"no-store\"\n"
+ . "</IfModule>\n";
+}
+
+function demo_open_gates(): void
+{
+ $want = demo_open_htaccess();
+ foreach (['data', 'plans'] as $sub) {
+ $d = webroot_dir() . '/' . $sub;
+ $f = $d . '/.htaccess';
+ if (!is_dir($d) || (is_file($f) && (string)file_get_contents($f) === $want)) {
+ continue;
+ }
+ $tmp = $f . '.tmp.' . bin2hex(random_bytes(4));
+ if (@file_put_contents($tmp, $want) === strlen($want) && @rename($tmp, $f)) {
+ @chmod($f, 0644);
+ } else {
+ @unlink($tmp);
+ }
+ }
+}
+
+function demo_prune(int $keepAfter, string $keepFile): array
+{
+ $dir = storage_dir();
+ $kept = [];
+ $dropped = 0;
+ foreach (list_versions() as $e) {
+ $file = basename((string)($e['file'] ?? ''));
+ $t = strtotime((string)($e['updatedAt'] ?? '')) ?: 0;
+ if ($file === $keepFile || $t >= $keepAfter) {
+ $kept[] = $e;
+ continue;
+ }
+ if ($file !== '' && preg_match('/^\d{8}T\d{6}Z-\d+\.json$/', $file)) {
+ @unlink($dir . '/versions/' . $file);
+ }
+ $dropped++;
+ }
+ $lines = '';
+ foreach ($kept as $e) {
+ $lines .= json_encode($e, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
+ }
+ atomic_write($dir . '/versions.jsonl', $lines);
+
+ $snapKept = [];
+ $snapDropped = 0;
+ foreach (list_snapshots() as $e) {
+ $t = strtotime((string)($e['createdAt'] ?? '')) ?: 0;
+ if ($t >= $keepAfter) {
+ $snapKept[] = $e;
+ continue;
+ }
+ $f = snapshot_file((string)($e['id'] ?? ''));
+ if ($f !== null) {
+ @unlink($f);
+ }
+ $snapDropped++;
+ }
+ if (is_file($dir . '/snapshots.jsonl')) {
+ $lines = '';
+ foreach ($snapKept as $e) {
+ $lines .= json_encode($e, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
+ }
+ atomic_write($dir . '/snapshots.jsonl', $lines);
+ }
+
+ foreach (glob($dir . '/ratelimit/*.json') ?: [] as $f) {
+ if (time() - (int)@filemtime($f) > 120) {
+ @unlink($f);
+ }
+ }
+ return ['versionsDropped' => $dropped, 'snapshotsDropped' => $snapDropped];
+}
+
+function demo_reset(bool $onlyIfDue): ?array
+{
+ return with_lock(function () use ($onlyIfDue) {
+ if ($onlyIfDue && !demo_reset_due()) {
+ return null;
+ }
+ $src = demo_plan_file();
+ if (!is_file($src)) {
+ fail(500, 'no_seed', tr('demo plan %s is missing', 'нет демо-плана %s', basename($src)));
+ }
+ $plan = validate_plan((string)file_get_contents($src));
+ $cur = read_current();
+ $rev = $cur ? (int)($cur->rev ?? 0) + 1 : 1;
+ $entry = commit_plan($plan, $rev, 'demo-reset');
+ $stats = demo_prune(time() - DEMO_RESET_SECONDS, $entry['file']);
+ touch(demo_marker());
+ demo_open_gates();
+ return ['rev' => $rev, 'updatedAt' => $entry['updatedAt']] + $stats;
+ });
+}
+
+function demo_rate_limit(): void
+{
+ $dir = storage_dir() . '/ratelimit';
+ if (!is_dir($dir) && !@mkdir($dir, 0700, true)) {
+ fail(500, 'no_storage', tr('missing storage/ratelimit folder', 'нет папки storage/ratelimit'));
+ }
+ $ip = (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown');
+ $h = fopen($dir . '/' . hash('sha256', $ip) . '.json', 'c+');
+ if (!$h || !flock($h, LOCK_EX)) {
+ fail(500, 'lock_failed', tr('could not acquire lock', 'не удалось взять блокировку'));
+ }
+ $now = microtime(true);
+ $hits = json_decode((string)stream_get_contents($h), true);
+ $hits = array_values(array_filter(is_array($hits) ? $hits : [], fn($t) => is_numeric($t) && $now - $t < 60));
+ if (count($hits) >= DEMO_WRITES_PER_MINUTE) {
+ flock($h, LOCK_UN);
+ fclose($h);
+ $retry = max(1, (int)ceil(60 - ($now - min($hits))));
+ send_json(429, [
+ 'error' => 'rate_limited',
+ 'message' => tr('demo: at most %d writes per minute, retry in %d s', 'демо: не больше %d записей в минуту, повторите через %d с', DEMO_WRITES_PER_MINUTE, $retry),
+ 'retryAfter' => $retry,
+ ], ['Retry-After: ' . $retry]);
+ }
+ $hits[] = round($now, 3);
+ ftruncate($h, 0);
+ rewind($h);
+ fwrite($h, json_encode($hits));
+ fflush($h);
+ flock($h, LOCK_UN);
+ fclose($h);
+}
+
+function demo_disabled(string $message): void
+{
+ fail(403, 'demo_disabled', $message . tr(' — install your own copy: %s', ' — поставьте свою копию: %s', 'https://github.com/egmalt/house-planner'));
+}
diff --git a/public/api/_i18n.php b/public/api/_i18n.php
new file mode 100644
index 0000000..ddae601
--- /dev/null
+++ b/public/api/_i18n.php
@@ -0,0 +1,37 @@
+<?php
+
+function ui_lang(): string
+{
+ static $lang = null;
+ if ($lang !== null) {
+ return $lang;
+ }
+ $cookie = $_COOKIE['lang'] ?? '';
+ if ($cookie === 'en' || $cookie === 'ru') {
+ return $lang = $cookie;
+ }
+ $best = 'en';
+ $bestQ = -1.0;
+ foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '') as $part) {
+ $bits = explode(';', trim($part));
+ $code = strtolower(substr(trim($bits[0]), 0, 2));
+ if ($code !== 'en' && $code !== 'ru') {
+ continue;
+ }
+ $q = 1.0;
+ if (isset($bits[1]) && preg_match('/q=([\d.]+)/', $bits[1], $m)) {
+ $q = (float) $m[1];
+ }
+ if ($q > $bestQ) {
+ $best = $code;
+ $bestQ = $q;
+ }
+ }
+ return $lang = $best;
+}
+
+function tr(string $en, string $ru, ...$args): string
+{
+ $s = ui_lang() === 'ru' ? $ru : $en;
+ return $args ? vsprintf($s, $args) : $s;
+}
diff --git a/public/api/_install.php b/public/api/_install.php
new file mode 100644
index 0000000..306397e
--- /dev/null
+++ b/public/api/_install.php
@@ -0,0 +1,78 @@
+<?php
+
+require_once __DIR__ . '/_lib.php';
+
+const MIN_PASSWORD = 8;
+
+function write_file(string $path, string $data, int $mode): void
+{
+ $tmp = $path . '.tmp.' . bin2hex(random_bytes(4));
+ if (file_put_contents($tmp, $data) !== strlen($data) || !rename($tmp, $path)) {
+ @unlink($tmp);
+ throw new RuntimeException(tr('could not write %s', 'не удалось записать %s', $path));
+ }
+ @chmod($path, $mode);
+}
+
+function gate_htaccess(string $token): string
+{
+ return "<IfModule mod_rewrite.c>\n"
+ . "RewriteEngine On\n"
+ . "RewriteCond %{HTTP_COOKIE} !(^|;\\s*)" . AUTH_COOKIE . "=" . $token . "(;|$)\n"
+ . "RewriteRule ^ - [R=401,L]\n"
+ . "</IfModule>\n"
+ . "<IfModule !mod_rewrite.c>\n"
+ . "Require all denied\n"
+ . "</IfModule>\n"
+ . "<IfModule mod_headers.c>\n"
+ . "Header always set Cache-Control \"no-store\"\n"
+ . "</IfModule>\n";
+}
+
+function deny_htaccess(): string
+{
+ return "Require all denied\n";
+}
+
+function config_php(array $c): string
+{
+ return "<?php\n\nreturn " . var_export($c, true) . ";\n";
+}
+
+function write_gates(?string $token): array
+{
+ $written = [];
+ foreach (['data', 'plans'] as $sub) {
+ $d = webroot_dir() . '/' . $sub;
+ if (is_dir($d)) {
+ write_file($d . '/.htaccess', $token === null ? deny_htaccess() : gate_htaccess($token), 0644);
+ $written[] = $sub . '/.htaccess';
+ }
+ }
+ return $written;
+}
+
+function install(string $dir, string $password): array
+{
+ if (!is_dir($dir) && !mkdir($dir, 0700, true)) {
+ throw new RuntimeException(tr('could not create %s', 'не удалось создать %s', $dir));
+ }
+ if (!is_dir($dir . '/versions') && !mkdir($dir . '/versions', 0700, true)) {
+ throw new RuntimeException(tr('could not create %s', 'не удалось создать %s', $dir . '/versions'));
+ }
+ write_file($dir . '/.htaccess', deny_htaccess(), 0644);
+ write_file($dir . '/index.html', '', 0644);
+
+ $token = bin2hex(random_bytes(32));
+ $config = [
+ 'password_hash' => password_hash($password, PASSWORD_DEFAULT),
+ 'hauth' => $token,
+ 'seed' => 'plans/demo.json',
+ 'timezone' => 'Europe/Moscow',
+ 'min_client_version' => MIN_CLIENT_VERSION,
+ 'installed_at' => gmdate('c'),
+ ];
+ $written = write_gates($token);
+ write_file($dir . '/config.php', config_php($config), 0600);
+ return [$token, $written];
+}
diff --git a/public/api/_lib.php b/public/api/_lib.php
new file mode 100644
index 0000000..081ac43
--- /dev/null
+++ b/public/api/_lib.php
@@ -0,0 +1,449 @@
+<?php
+
+require_once __DIR__ . '/_i18n.php';
+require_once __DIR__ . '/_demo.php';
+
+const PLAN_MAX_BYTES = 2097152;
+const MIN_CLIENT_VERSION = 2;
+const PLAN_JSON_FLAGS = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT;
+const AUTH_COOKIE = 'hauth';
+
+function webroot_dir(): string
+{
+ return dirname(__DIR__);
+}
+
+function storage_candidates(): array
+{
+ $out = [];
+ $env = getenv('HOUSE_STORAGE');
+ if (is_string($env) && $env !== '') {
+ $out[] = rtrim($env, '/');
+ }
+ $out[] = dirname(webroot_dir()) . '/storage';
+ $out[] = webroot_dir() . '/storage';
+ return $out;
+}
+
+function find_storage(): ?string
+{
+ foreach (storage_candidates() as $dir) {
+ if (is_file($dir . '/config.php')) {
+ return $dir;
+ }
+ }
+ return null;
+}
+
+function storage_dir(): string
+{
+ static $dir = null;
+ if ($dir === null) {
+ $dir = find_storage() ?? storage_candidates()[0];
+ }
+ return $dir;
+}
+
+function seed_file(): string
+{
+ $seed = (string)(load_config()['seed'] ?? '');
+ if ($seed === '') {
+ return webroot_dir() . '/plans/demo.json';
+ }
+ return $seed[0] === '/' ? $seed : webroot_dir() . '/' . $seed;
+}
+
+function is_https(): bool
+{
+ if (!empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off') {
+ return true;
+ }
+ return strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
+}
+
+function auth_cookie(string $value, int $maxAge): string
+{
+ $parts = [AUTH_COOKIE . '=' . $value, 'Max-Age=' . $maxAge, 'Path=/', 'HttpOnly', 'SameSite=Lax'];
+ if ($maxAge <= 0) {
+ $parts[] = 'Expires=Thu, 01 Jan 1970 00:00:00 GMT';
+ }
+ if (is_https()) {
+ $parts[] = 'Secure';
+ }
+ return 'Set-Cookie: ' . implode('; ', $parts);
+}
+
+function send_json(int $code, $body, array $headers = []): void
+{
+ http_response_code($code);
+ header('Content-Type: application/json; charset=utf-8');
+ header('Cache-Control: no-store');
+ if (is_demo()) {
+ header(DEMO_HEADER);
+ }
+ foreach ($headers as $h) {
+ header($h);
+ }
+ echo json_encode($body, PLAN_JSON_FLAGS), "\n";
+ exit;
+}
+
+function send_raw_json(int $code, string $json, array $headers = []): void
+{
+ http_response_code($code);
+ header('Content-Type: application/json; charset=utf-8');
+ header('Cache-Control: no-store');
+ if (is_demo()) {
+ header(DEMO_HEADER);
+ }
+ foreach ($headers as $h) {
+ header($h);
+ }
+ echo $json;
+ exit;
+}
+
+function fail(int $code, string $error, string $message, array $extra = []): void
+{
+ send_json($code, array_merge(['error' => $error, 'message' => $message], $extra));
+}
+
+function load_config(): array
+{
+ static $config = null;
+ if ($config !== null) {
+ return $config;
+ }
+ $dir = find_storage();
+ if ($dir === null) {
+ fail(503, 'not_installed', tr('planner is not installed: open api/setup.php', 'планировщик не установлен: откройте api/setup.php'));
+ }
+ $c = require $dir . '/config.php';
+ $config = is_array($c) ? $c : [];
+ if (!empty($config['timezone']) && is_string($config['timezone'])) {
+ @date_default_timezone_set($config['timezone']);
+ }
+ return $config;
+}
+
+function require_auth(array $config): void
+{
+ if (is_demo()) {
+ return;
+ }
+ $want = (string)($config['hauth'] ?? '');
+ $got = (string)($_COOKIE[AUTH_COOKIE] ?? '');
+ if ($want === '' || $got === '' || !hash_equals($want, $got)) {
+ fail(401, 'unauthorized', tr('login required: POST api/login.php', 'нужен вход: POST api/login.php'));
+ }
+}
+
+function etag_headers(int $rev): array
+{
+ return ['ETag: "' . $rev . '"', 'X-Plan-Rev: ' . $rev];
+}
+
+function parse_rev_header(string $v): ?int
+{
+ $v = trim($v);
+ if (strncmp($v, 'W/', 2) === 0) {
+ $v = substr($v, 2);
+ }
+ $v = trim($v, "\" \t");
+ return ctype_digit($v) ? (int)$v : null;
+}
+
+function author_label(): string
+{
+ $a = (string)($_SERVER['HTTP_X_PLAN_AUTHOR'] ?? '');
+ $a = preg_replace('/[^\w .@:-]+/u', '', $a);
+ $a = trim(mb_substr((string)$a, 0, 100));
+ return $a === '' ? 'web' : $a;
+}
+
+function plan_max_bytes(): int
+{
+ return is_demo() ? DEMO_PLAN_MAX_BYTES : PLAN_MAX_BYTES;
+}
+
+function validate_plan(string $raw)
+{
+ if (strlen($raw) > plan_max_bytes()) {
+ fail(413, 'too_large', tr('plan is larger than %d MB', 'план больше %d МБ', plan_max_bytes() >> 20));
+ }
+ $p = json_decode($raw);
+ if (json_last_error() !== JSON_ERROR_NONE) {
+ fail(400, 'bad_json', tr('invalid JSON: %s', 'некорректный JSON: %s', json_last_error_msg()));
+ }
+ if (!is_object($p)) {
+ fail(422, 'invalid_plan', tr('plan must be an object', 'план должен быть объектом'));
+ }
+ if (!isset($p->site) || !is_object($p->site)) {
+ fail(422, 'invalid_plan', tr('missing site object', 'нет объекта site'));
+ }
+ if (!isset($p->walls) || !is_array($p->walls)) {
+ fail(422, 'invalid_plan', tr('missing walls array', 'нет массива walls'));
+ }
+ if (!isset($p->openings) || !is_array($p->openings)) {
+ fail(422, 'invalid_plan', tr('missing openings array', 'нет массива openings'));
+ }
+ return $p;
+}
+
+function atomic_write(string $path, string $data): void
+{
+ $tmp = $path . '.tmp.' . getmypid() . '.' . bin2hex(random_bytes(4));
+ if (file_put_contents($tmp, $data) !== strlen($data)) {
+ @unlink($tmp);
+ fail(500, 'write_failed', tr('could not write %s', 'не удалось записать %s', basename($path)));
+ }
+ @chmod($tmp, 0600);
+ if (!rename($tmp, $path)) {
+ @unlink($tmp);
+ fail(500, 'write_failed', tr('could not rename %s', 'не удалось переименовать %s', basename($path)));
+ }
+}
+
+function with_lock(callable $fn)
+{
+ $dir = storage_dir();
+ if (!is_dir($dir . '/versions') && !mkdir($dir . '/versions', 0700, true)) {
+ fail(500, 'no_storage', tr('missing storage/versions folder', 'нет папки storage/versions'));
+ }
+ $h = fopen($dir . '/.lock', 'c');
+ if (!$h || !flock($h, LOCK_EX)) {
+ fail(500, 'lock_failed', tr('could not acquire lock', 'не удалось взять блокировку'));
+ }
+ try {
+ return $fn();
+ } finally {
+ flock($h, LOCK_UN);
+ fclose($h);
+ }
+}
+
+function read_current()
+{
+ $f = storage_dir() . '/current.json';
+ if (!is_file($f)) {
+ return null;
+ }
+ $p = json_decode((string)file_get_contents($f));
+ return is_object($p) ? $p : null;
+}
+
+function iso_now(): string
+{
+ $t = microtime(true);
+ return gmdate('Y-m-d\TH:i:s', (int)$t) . sprintf('.%03dZ', (int)(($t - floor($t)) * 1000));
+}
+
+function commit_plan($plan, int $rev, string $author): array
+{
+ $dir = storage_dir();
+ $updatedAt = iso_now();
+ $plan = apply_fixed_site($plan);
+ $plan->rev = $rev;
+ $plan->updatedAt = $updatedAt;
+ $plan->author = $author;
+ $json = json_encode($plan, PLAN_JSON_FLAGS) . "\n";
+ $stamp = gmdate('Ymd\THis\Z', strtotime($updatedAt));
+ $file = $stamp . '-' . $rev . '.json';
+ atomic_write($dir . '/versions/' . $file, $json);
+ atomic_write($dir . '/current.json', $json);
+ $entry = [
+ 'rev' => $rev,
+ 'updatedAt' => $updatedAt,
+ 'author' => $author,
+ 'walls' => count($plan->walls),
+ 'openings' => count($plan->openings),
+ 'bytes' => strlen($json),
+ 'file' => $file,
+ ];
+ file_put_contents($dir . '/versions.jsonl', json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND);
+ return $entry;
+}
+
+function ensure_seeded(): void
+{
+ if (is_file(storage_dir() . '/current.json')) {
+ return;
+ }
+ with_lock(function () {
+ if (is_file(storage_dir() . '/current.json')) {
+ return;
+ }
+ $src = seed_file();
+ if (!is_file($src)) {
+ fail(500, 'no_seed', tr('storage is empty and seed file %s is missing', 'хранилище пусто и нет файла засева %s', basename($src)));
+ }
+ $plan = validate_plan((string)file_get_contents($src));
+ commit_plan($plan, 1, 'seed');
+ });
+}
+
+function list_versions(): array
+{
+ $f = storage_dir() . '/versions.jsonl';
+ $out = [];
+ if (!is_file($f)) {
+ return $out;
+ }
+ foreach (file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
+ $e = json_decode($line, true);
+ if (is_array($e)) {
+ $out[] = $e;
+ }
+ }
+ return $out;
+}
+
+function version_file(int $rev): ?string
+{
+ $m = glob(storage_dir() . '/versions/*-' . $rev . '.json');
+ return $m ? $m[0] : null;
+}
+
+function require_client_version(array $config): void
+{
+ $min = (int)($config['min_client_version'] ?? MIN_CLIENT_VERSION);
+ $v = trim((string)($_SERVER['HTTP_X_CLIENT_VERSION'] ?? ''));
+ if (!ctype_digit($v) || (int)$v < $min) {
+ fail(426, 'client_outdated', tr('client is outdated, reload the page', 'клиент устарел, перезагрузи страницу'), ['minClientVersion' => $min]);
+ }
+}
+
+function load_fixed_site()
+{
+ static $fixed = false;
+ if ($fixed === false) {
+ $fixed = null;
+ $f = storage_dir() . '/site-fixed.json';
+ if (is_file($f)) {
+ $d = json_decode((string)file_get_contents($f));
+ if (!is_object($d) || !isset($d->site) || !is_object($d->site)) {
+ fail(500, 'corrupt', tr('site-fixed.json is corrupt', 'site-fixed.json повреждён'));
+ }
+ $fixed = $d->site;
+ }
+ }
+ return $fixed;
+}
+
+function apply_fixed_site($plan)
+{
+ $fixed = load_fixed_site();
+ if ($fixed === null || !is_object($plan)) {
+ return $plan;
+ }
+ if (!isset($plan->site) || !is_object($plan->site)) {
+ $plan->site = new stdClass();
+ }
+ foreach (['boundary', 'street', 'geo'] as $k) {
+ if (property_exists($fixed, $k)) {
+ $plan->site->$k = $fixed->$k;
+ }
+ }
+ $locked = [];
+ foreach ((isset($fixed->zones) && is_array($fixed->zones)) ? $fixed->zones : [] as $z) {
+ if (is_object($z) && !empty($z->locked)) {
+ $locked[] = $z;
+ }
+ }
+ $ids = [];
+ foreach ($locked as $z) {
+ $ids[(string)($z->id ?? '')] = true;
+ }
+ $zones = $locked;
+ foreach ((isset($plan->site->zones) && is_array($plan->site->zones)) ? $plan->site->zones : [] as $z) {
+ if (!is_object($z) || !empty($z->locked) || isset($ids[(string)($z->id ?? '')])) {
+ continue;
+ }
+ $zones[] = $z;
+ }
+ if ($zones || isset($plan->site->zones)) {
+ $plan->site->zones = $zones;
+ }
+ return $plan;
+}
+
+function send_plan_file(string $f, ?int $rev = null): void
+{
+ $p = json_decode((string)file_get_contents($f));
+ if (!is_object($p)) {
+ fail(500, 'corrupt', tr('%s is corrupt', '%s повреждён', basename($f)));
+ }
+ $p = apply_fixed_site($p);
+ send_raw_json(200, json_encode($p, PLAN_JSON_FLAGS) . "\n", etag_headers($rev ?? (int)($p->rev ?? 0)));
+}
+
+function snapshots_dir(): string
+{
+ return storage_dir() . '/snapshots';
+}
+
+function snapshot_slug(string $name): string
+{
+ static $tr = ['а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'ts', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya'];
+ $s = strtr(mb_strtolower($name, 'UTF-8'), $tr);
+ $s = trim((string)preg_replace('/[^a-z0-9]+/', '-', $s), '-');
+ $s = rtrim(substr($s, 0, 60), '-');
+ return $s === '' ? 'snapshot' : $s;
+}
+
+function list_snapshots(): array
+{
+ $f = storage_dir() . '/snapshots.jsonl';
+ $out = [];
+ if (!is_file($f)) {
+ return $out;
+ }
+ foreach (file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
+ $e = json_decode($line, true);
+ if (is_array($e)) {
+ $out[] = $e;
+ }
+ }
+ return $out;
+}
+
+function snapshot_file(string $id): ?string
+{
+ if (!preg_match('/^\d{4}-\d{2}-\d{2}-[a-z0-9-]{1,70}$/', $id)) {
+ return null;
+ }
+ $f = snapshots_dir() . '/' . $id . '.json';
+ return is_file($f) ? $f : null;
+}
+
+function create_snapshot(string $name, string $author): array
+{
+ return with_lock(function () use ($name, $author) {
+ $dir = snapshots_dir();
+ if (!is_dir($dir) && !mkdir($dir, 0700, true)) {
+ fail(500, 'no_storage', tr('missing storage/snapshots folder', 'нет папки storage/snapshots'));
+ }
+ $raw = (string)file_get_contents(storage_dir() . '/current.json');
+ $cur = json_decode($raw);
+ if (!is_object($cur)) {
+ fail(500, 'corrupt', tr('current.json is corrupt', 'current.json повреждён'));
+ }
+ $base = (new DateTime('now'))->format('Y-m-d') . '-' . snapshot_slug($name);
+ $id = $base;
+ for ($n = 2; is_file($dir . '/' . $id . '.json'); $n++) {
+ $id = $base . '-' . $n;
+ }
+ atomic_write($dir . '/' . $id . '.json', $raw);
+ $entry = [
+ 'id' => $id,
+ 'name' => $name,
+ 'rev' => (int)($cur->rev ?? 0),
+ 'createdAt' => iso_now(),
+ 'author' => $author,
+ 'walls' => is_array($cur->walls ?? null) ? count($cur->walls) : 0,
+ 'openings' => is_array($cur->openings ?? null) ? count($cur->openings) : 0,
+ ];
+ file_put_contents(storage_dir() . '/snapshots.jsonl', json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND);
+ return $entry;
+ });
+}
diff --git a/public/api/login.php b/public/api/login.php
new file mode 100644
index 0000000..a0976fb
--- /dev/null
+++ b/public/api/login.php
@@ -0,0 +1,28 @@
+<?php
+
+require __DIR__ . '/_lib.php';
+
+if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
+ header('Allow: POST');
+ fail(405, 'method_not_allowed', tr('POST only', 'только POST'));
+}
+if (trim((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === '') {
+ fail(403, 'csrf', tr('X-Requested-With header required', 'нужен заголовок X-Requested-With'));
+}
+
+$config = load_config();
+if (is_demo()) {
+ send_json(200, ['ok' => true, 'demo' => true]);
+}
+$token = (string)($config['hauth'] ?? '');
+$hash = (string)($config['password_hash'] ?? '');
+$body = json_decode((string)file_get_contents('php://input', false, null, 0, 4096), true);
+$password = is_array($body) && is_string($body['password'] ?? null) ? $body['password'] : '';
+
+if ($token === '' || $hash === '' || $password === '' || !password_verify($password, $hash)) {
+ sleep(1);
+ fail(401, 'wrong_password', tr('wrong password', 'неверный пароль'));
+}
+
+header(auth_cookie($token, 31536000), true);
+send_json(200, ['ok' => true]);
diff --git a/public/api/logout.php b/public/api/logout.php
new file mode 100644
index 0000000..6b8a80c
--- /dev/null
+++ b/public/api/logout.php
@@ -0,0 +1,14 @@
+<?php
+
+require __DIR__ . '/_lib.php';
+
+if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
+ header('Allow: POST');
+ fail(405, 'method_not_allowed', tr('POST only', 'только POST'));
+}
+if (trim((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === '') {
+ fail(403, 'csrf', tr('X-Requested-With header required', 'нужен заголовок X-Requested-With'));
+}
+
+header(auth_cookie('', 0), true);
+send_json(200, ['ok' => true]);
diff --git a/public/api/petrovich-cart.php b/public/api/petrovich-cart.php
new file mode 100644
index 0000000..eaa1006
--- /dev/null
+++ b/public/api/petrovich-cart.php
@@ -0,0 +1,223 @@
+<?php
+
+require __DIR__ . '/_lib.php';
+
+const PET_API = 'https://api.petrovich.ru';
+const PET_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36';
+const PET_MAX_ITEMS = 150;
+const PET_TIMEOUT = 120;
+const PET_BATCH = 50;
+
+$config = load_config();
+if (is_demo()) {
+ demo_disabled(tr('the Petrovich cart is disabled in the demo', 'в демо корзина Петровича отключена'));
+}
+require_auth($config);
+
+if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
+ header('Allow: POST');
+ fail(405, 'method_not_allowed', tr('POST only', 'только POST'));
+}
+if (trim((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === '') {
+ fail(403, 'csrf', tr('X-Requested-With header required', 'нужен заголовок X-Requested-With'));
+}
+require_client_version($config);
+
+$body = json_decode((string)file_get_contents('php://input', false, null, 0, 262144));
+if (!is_object($body)) {
+ fail(400, 'bad_json', tr('body must be a JSON object', 'тело должно быть JSON-объектом'));
+}
+$city = (string)($body->city ?? '');
+if ($city !== 'spb' && $city !== 'vbg') {
+ fail(422, 'invalid_city', tr('city: spb or vbg', 'city: spb или vbg'));
+}
+if (!isset($body->items) || !is_array($body->items) || !$body->items) {
+ fail(422, 'invalid_items', tr('non-empty items array required', 'нужен непустой массив items'));
+}
+
+$items = [];
+foreach ($body->items as $i => $it) {
+ $code = is_object($it) ? trim((string)($it->code ?? '')) : '';
+ $qty = is_object($it) && is_numeric($it->qty ?? null) ? (float)$it->qty : 0;
+ if (!preg_match('/^\d{3,10}$/', $code) || $qty <= 0) {
+ fail(422, 'invalid_items', tr('items[%d]: numeric code and qty > 0 required', 'items[%d]: нужен числовой code и qty > 0', $i));
+ }
+ $q = (int)ceil($qty - 1e-9);
+ if (isset($items[$code])) {
+ $items[$code]['qty'] += $q;
+ } else {
+ $items[$code] = ['code' => $code, 'qty' => $q, 'name' => is_string($it->name ?? null) ? $it->name : null];
+ }
+}
+if (count($items) > PET_MAX_ITEMS) {
+ fail(413, 'too_many_items', tr('at most %d items per request', 'не больше %d позиций за запрос', PET_MAX_ITEMS));
+}
+
+$lock = fopen(storage_dir() . '/.petrovich.lock', 'c');
+if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
+ fail(429, 'busy', tr('the Petrovich cart is already being built, retry in a minute', 'корзина Петровича уже собирается, повтори через минуту'));
+}
+
+set_time_limit(PET_TIMEOUT + 15);
+ignore_user_abort(true);
+$deadline = microtime(true) + PET_TIMEOUT;
+
+$ch = curl_init();
+curl_setopt_array($ch, [
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_FOLLOWLOCATION => true,
+ CURLOPT_MAXREDIRS => 5,
+ CURLOPT_COOKIEFILE => '',
+ CURLOPT_USERAGENT => PET_UA,
+ CURLOPT_CONNECTTIMEOUT => 10,
+ CURLOPT_ENCODING => '',
+]);
+
+function pet_blocked(string $why): void
+{
+ fail(502, 'petrovich_blocked', tr('Petrovich refused access: %s', 'Петрович не пускает: %s', $why));
+}
+
+function pet_http(string $method, string $url, $json = null): array
+{
+ global $ch, $deadline;
+ $left = (int)ceil($deadline - microtime(true));
+ if ($left <= 0) {
+ fail(504, 'timeout', tr('timed out after %d s', 'не уложились в %d с', PET_TIMEOUT));
+ }
+ $headers = ['Origin: https://petrovich.ru', 'Referer: https://petrovich.ru/', 'Accept: application/json, text/plain, */*'];
+ $post = null;
+ if ($json !== null) {
+ $post = json_encode($json);
+ $headers[] = 'Content-Type: application/json';
+ }
+ curl_setopt_array($ch, [
+ CURLOPT_URL => $url,
+ CURLOPT_CUSTOMREQUEST => $method,
+ CURLOPT_HTTPGET => $method === 'GET',
+ CURLOPT_POSTFIELDS => $post,
+ CURLOPT_HTTPHEADER => $headers,
+ CURLOPT_TIMEOUT => min(30, $left),
+ ]);
+ if ($method === 'GET') {
+ curl_setopt($ch, CURLOPT_POSTFIELDS, null);
+ curl_setopt($ch, CURLOPT_HTTPGET, true);
+ }
+ $raw = curl_exec($ch);
+ if ($raw === false) {
+ if (microtime(true) >= $deadline) {
+ fail(504, 'timeout', tr('timed out after %d s', 'не уложились в %d с', PET_TIMEOUT));
+ }
+ fail(502, 'petrovich_unavailable', tr('Petrovich did not respond: %s', 'Петрович не ответил: %s', curl_error($ch)));
+ }
+ $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
+ if ($code === 403 || $code === 429 || ($code !== 200 && (stripos($raw, 'qrator') !== false || stripos($raw, 'captcha') !== false))) {
+ pet_blocked('HTTP ' . $code);
+ }
+ return [$code, $raw];
+}
+
+function pet_api(string $method, string $path, array $query, $json = null)
+{
+ global $city;
+ $query += ['city_code' => $city, 'client_id' => 'pet_site'];
+ [$code, $raw] = pet_http($method, PET_API . $path . '?' . http_build_query($query), $json);
+ $d = json_decode($raw);
+ if (!is_object($d)) {
+ fail(502, 'petrovich_bad_reply', tr('Petrovich returned non-JSON for %s (HTTP %s)', 'Петрович ответил не JSON на %s (HTTP %s)', $path, $code));
+ }
+ return $d;
+}
+
+function pet_state($d): int
+{
+ return (int)($d->state->code ?? 0);
+}
+
+function pet_start_session(): void
+{
+ [$code, $page] = pet_http('GET', 'https://petrovich.ru/product/106004/');
+ if (!preg_match('#(https://api\.petrovich\.ru/session/v3/init\.js[^"\']*)#', $page, $m)) {
+ pet_blocked(tr('no init.js on the page (HTTP %s)', 'нет init.js на странице (HTTP %s)', $code));
+ }
+ [, $reply] = pet_http('GET', html_entity_decode($m[1]));
+ if (strpos($reply, '"started":true') === false) {
+ pet_blocked(tr('session did not start', 'сессия не стартовала'));
+ }
+}
+
+function pet_pause(): void
+{
+ usleep(random_int(300000, 500000));
+}
+
+function pet_in_stock($p): bool
+{
+ if (!empty($p->is_not_in_stock)) {
+ return false;
+ }
+ return true;
+}
+
+pet_start_session();
+
+$found = [];
+foreach (array_chunk(array_keys($items), PET_BATCH) as $chunk) {
+ $d = pet_api('GET', '/catalog/v5/search-d', ['q' => implode(',', $chunk), 'limit' => PET_BATCH]);
+ foreach ((array)($d->data->products ?? []) as $p) {
+ $c = (string)($p->code ?? '');
+ if ($c !== '' && isset($items[$c]) && !empty($p->product_guid)) {
+ $found[$c] = $p;
+ }
+ }
+ pet_pause();
+}
+foreach ($items as $c => $_) {
+ if (isset($found[$c])) {
+ continue;
+ }
+ $d = pet_api('GET', '/catalog/v5/products/' . $c, []);
+ if (pet_state($d) === 20001 && !empty($d->data->product->product_guid)) {
+ $found[$c] = $d->data->product;
+ }
+ pet_pause();
+}
+
+$added = [];
+$missing = [];
+$total = 0;
+foreach ($items as $c => $it) {
+ $p = $found[$c] ?? null;
+ if (!$p) {
+ $missing[] = ['code' => (string)$c, 'reason' => 'not_found'];
+ continue;
+ }
+ if (!pet_in_stock($p)) {
+ $missing[] = ['code' => (string)$c, 'reason' => 'no_stock', 'name' => (string)($p->title ?? '')];
+ continue;
+ }
+ $d = pet_api('POST', '/cart/v2/products/' . $p->product_guid, [], ['qty' => $it['qty']]);
+ if (pet_state($d) !== 200) {
+ $missing[] = ['code' => (string)$c, 'reason' => 'add_failed', 'name' => (string)($p->title ?? ''), 'detail' => (string)($d->state->title ?? '')];
+ } else {
+ $price = isset($p->price->retail) ? (float)$p->price->retail : null;
+ $added[] = ['code' => (string)$c, 'qty' => $it['qty'], 'name' => (string)($p->title ?? $it['name'] ?? ''), 'price' => $price];
+ if ($price !== null) {
+ $total += $price * $it['qty'];
+ }
+ }
+ pet_pause();
+}
+
+if (!$added) {
+ send_json(422, ['error' => 'nothing_added', 'message' => tr('no items were added', 'ни одной позиции не добавлено'), 'url' => null, 'added' => [], 'missing' => $missing]);
+}
+
+$link = pet_api('GET', '/cart/v2/link', []);
+$url = (string)($link->data->shareLink ?? '');
+pet_api('DELETE', '/cart/v2/items', []);
+if ($url === '') {
+ fail(502, 'petrovich_no_link', tr('Petrovich did not return an estimate link', 'Петрович не выдал ссылку на смету'), ['added' => $added, 'missing' => $missing]);
+}
+
+send_json(200, ['url' => $url, 'city' => $city, 'added' => $added, 'missing' => $missing, 'total' => round($total, 2)]);
diff --git a/public/api/plan.php b/public/api/plan.php
new file mode 100644
index 0000000..e717c5f
--- /dev/null
+++ b/public/api/plan.php
@@ -0,0 +1,107 @@
+<?php
+
+require __DIR__ . '/_lib.php';
+
+$config = load_config();
+require_auth($config);
+if (is_demo() && demo_reset_due()) {
+ demo_reset(true);
+}
+
+$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
+
+if ($method === 'GET' || $method === 'HEAD') {
+ ensure_seeded();
+
+ if (isset($_GET['versions'])) {
+ $list = array_reverse(list_versions());
+ $cur = read_current();
+ send_json(200, ['rev' => $cur ? (int)$cur->rev : 0, 'versions' => $list]);
+ }
+
+ if (isset($_GET['rev'])) {
+ $rev = parse_rev_header((string)$_GET['rev']);
+ $f = $rev === null ? null : version_file($rev);
+ if ($f === null) {
+ fail(404, 'not_found', tr('no version rev=%s', 'нет версии rev=%s', $_GET['rev']));
+ }
+ send_plan_file($f, $rev);
+ }
+
+ if (isset($_GET['snapshots'])) {
+ send_json(200, ['snapshots' => array_reverse(list_snapshots())]);
+ }
+
+ if (isset($_GET['snapshot'])) {
+ $f = snapshot_file((string)$_GET['snapshot']);
+ if ($f === null) {
+ fail(404, 'not_found', tr('no snapshot %s', 'нет снимка %s', $_GET['snapshot']));
+ }
+ send_plan_file($f);
+ }
+
+ send_plan_file(storage_dir() . '/current.json');
+}
+
+if ($method !== 'PUT' && $method !== 'POST') {
+ header('Allow: GET, HEAD, PUT, POST');
+ fail(405, 'method_not_allowed', tr('method not allowed', 'метод не поддерживается'));
+}
+
+if (trim((string)($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === '') {
+ fail(403, 'csrf', tr('X-Requested-With header required', 'нужен заголовок X-Requested-With'));
+}
+
+require_client_version($config);
+if (is_demo()) {
+ demo_rate_limit();
+}
+
+if ($method === 'POST' && isset($_GET['snapshot'])) {
+ $b = json_decode((string)file_get_contents('php://input', false, null, 0, 65536));
+ $name = is_object($b) && is_string($b->name ?? null) ? trim($b->name) : '';
+ if ($name === '' || mb_strlen($name) > 200) {
+ fail(422, 'invalid_name', tr('name field required, 1–200 characters', 'нужно поле name, 1–200 символов'));
+ }
+ ensure_seeded();
+ if (is_demo() && count(list_snapshots()) >= DEMO_MAX_SNAPSHOTS) {
+ fail(403, 'demo_limit', tr('demo allows at most %d snapshots, old ones are removed at the hourly reset', 'в демо не больше %d снимков, старые удаляются при часовом сбросе', DEMO_MAX_SNAPSHOTS));
+ }
+ send_json(201, create_snapshot($name, author_label()));
+}
+
+$len = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
+if ($len > plan_max_bytes()) {
+ fail(413, 'too_large', tr('plan is larger than %d MB', 'план больше %d МБ', plan_max_bytes() >> 20));
+}
+
+$ifMatch = parse_rev_header((string)($_SERVER['HTTP_IF_MATCH'] ?? ''));
+if ($ifMatch === null) {
+ fail(428, 'if_match_required', tr('If-Match: <rev> header required', 'нужен заголовок If-Match: <rev>'));
+}
+
+$raw = (string)file_get_contents('php://input', false, null, 0, plan_max_bytes() + 1);
+$plan = validate_plan($raw);
+$author = author_label();
+
+ensure_seeded();
+
+$result = with_lock(function () use ($plan, $ifMatch, $author) {
+ $cur = read_current();
+ if (!$cur) {
+ fail(500, 'corrupt', tr('current.json is corrupt', 'current.json повреждён'));
+ }
+ $curRev = (int)$cur->rev;
+ if ($curRev !== $ifMatch) {
+ send_json(409, [
+ 'error' => 'conflict',
+ 'message' => tr('plan has already changed: rev %s, sent %s', 'план уже изменён: rev %s, прислан %s', $curRev, $ifMatch),
+ 'rev' => $curRev,
+ 'updatedAt' => $cur->updatedAt ?? null,
+ 'plan' => apply_fixed_site($cur),
+ ], etag_headers($curRev));
+ }
+ return commit_plan($plan, $curRev + 1, $author);
+});
+
+send_json(200, ['rev' => $result['rev'], 'updatedAt' => $result['updatedAt']], etag_headers($result['rev']));
diff --git a/public/api/setup.php b/public/api/setup.php
new file mode 100644
index 0000000..7e8a045
--- /dev/null
+++ b/public/api/setup.php
@@ -0,0 +1,152 @@
+<?php
+
+require __DIR__ . '/_install.php';
+
+function setup_page(int $code, string $title, string $body): void
+{
+ http_response_code($code);
+ header('Content-Type: text/html; charset=utf-8');
+ header('Cache-Control: no-store');
+ header('X-Robots-Tag: noindex');
+ echo '<!doctype html><html lang="' . ui_lang() . '"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
+ echo '<meta name="robots" content="noindex,nofollow"><title>' . h(tr('Planner setup', 'Установка планировщика')) . '</title><style>';
+ echo '*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;padding:16px;background:#f4f1ec;color:#2b2d33;font:15px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}';
+ echo '.setup{width:100%;max-width:520px;background:#fff;border:1px solid #ece8e1;border-radius:16px;padding:28px 24px}';
+ echo '.setup h1{margin:0 0 12px;font-size:20px}.setup label{display:block;margin:14px 0 4px;font-weight:600}';
+ echo '.setup input[type=password],.setup input[type=text]{width:100%;padding:10px 12px;font:inherit;border:1px solid #d8d2c8;border-radius:10px}';
+ echo '.setup button{margin-top:18px;width:100%;padding:12px;font:inherit;font-weight:600;color:#fff;background:#f26b1d;border:0;border-radius:10px;cursor:pointer}';
+ echo '.setup code{background:#f4f1ec;padding:1px 5px;border-radius:5px;word-break:break-all}.setup .err{color:#d9412b}.setup .warn{color:#a35a00}.setup .muted{color:#8a8f98}';
+ echo '.setup .opt{display:flex;gap:8px;align-items:flex-start;margin:6px 0;font-weight:400}';
+ echo '</style></head><body><main class="setup"><h1>' . htmlspecialchars($title) . '</h1>' . $body . '</main></body></html>';
+ exit;
+}
+
+function h(string $s): string
+{
+ return htmlspecialchars($s, ENT_QUOTES);
+}
+
+function dir_writable_for(string $dir): bool
+{
+ if (is_dir($dir)) {
+ return is_writable($dir);
+ }
+ $parent = dirname($dir);
+ return is_dir($parent) && is_writable($parent);
+}
+
+function storage_options(): array
+{
+ $out = [];
+ $inside = webroot_dir() . '/storage';
+ foreach (storage_candidates() as $i => $dir) {
+ $out[] = [
+ 'id' => (string)$i,
+ 'dir' => $dir,
+ 'inside' => $dir === $inside,
+ 'writable' => dir_writable_for($dir),
+ ];
+ }
+ return $out;
+}
+
+function server_honours_htaccess(): bool
+{
+ $sw = strtolower((string)($_SERVER['SERVER_SOFTWARE'] ?? ''));
+ return strpos($sw, 'apache') !== false || strpos($sw, 'litespeed') !== false;
+}
+
+$existing = find_storage();
+if ($existing !== null) {
+ setup_page(403, tr('Already installed', 'Уже установлено'), tr('<p>Storage found: <code>%s</code>. Setup is locked.</p>', '<p>Хранилище найдено: <code>%s</code>. Установка заблокирована.</p>', h($existing))
+ . tr('<p class="muted">To change the password, delete <code>config.php</code> in the storage and open this page again: the plan and versions stay in place.</p>', '<p class="muted">Чтобы сменить пароль, удалите <code>config.php</code> в хранилище и откройте эту страницу снова: план и версии останутся на месте.</p>')
+ . tr('<p><a href="../">Open the planner</a></p>', '<p><a href="../">Открыть планировщик</a></p>'));
+}
+
+$key = getenv('HOUSE_SETUP_KEY');
+$needKey = is_string($key) && $key !== '';
+$options = storage_options();
+$errors = [];
+
+if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
+ $password = (string)($_POST['password'] ?? '');
+ $repeat = (string)($_POST['repeat'] ?? '');
+ $choice = (string)($_POST['storage'] ?? '');
+ if ($needKey && !hash_equals($key, (string)($_POST['key'] ?? ''))) {
+ $errors[] = tr('wrong setup key', 'неверный ключ установки');
+ }
+ if (mb_strlen($password) < MIN_PASSWORD) {
+ $errors[] = tr('password is shorter than %d characters', 'пароль короче %d символов', MIN_PASSWORD);
+ }
+ if ($password !== $repeat) {
+ $errors[] = tr('passwords do not match', 'пароли не совпадают');
+ }
+ $picked = null;
+ foreach ($options as $o) {
+ if ($o['id'] === $choice) {
+ $picked = $o;
+ }
+ }
+ if ($picked === null || !$picked['writable']) {
+ $errors[] = tr('the selected storage folder is not writable', 'выбранная папка хранилища недоступна для записи');
+ }
+ if (!$errors) {
+ try {
+ [, $written] = install($picked['dir'], $password);
+ } catch (Throwable $e) {
+ $errors[] = $e->getMessage();
+ }
+ if (!$errors) {
+ $warn = '';
+ if (!server_honours_htaccess()) {
+ $warn = tr('<p class="warn">The server does not look like Apache or LiteSpeed, so it probably ignores <code>.htaccess</code> files. '
+ . 'Block access to <code>/storage</code>, <code>/data</code> and <code>/plans</code> in the web server config.</p>', '<p class="warn">Сервер не похож на Apache или LiteSpeed: файлы <code>.htaccess</code> он, скорее всего, не читает. '
+ . 'Закройте доступ к <code>/storage</code>, <code>/data</code> и <code>/plans</code> в конфигурации веб-сервера.</p>');
+ }
+ if ($picked['inside']) {
+ $warn .= tr('<p class="warn">The storage is inside the site and protected only by <code>.htaccess</code>. If possible, move it one level above the site root.</p>', '<p class="warn">Хранилище лежит внутри сайта и закрыто только <code>.htaccess</code>. Если есть возможность, перенесите его на уровень выше корня сайта.</p>');
+ }
+ setup_page(200, tr('Done', 'Готово'), tr('<p>Storage: <code>%s</code></p>', '<p>Хранилище: <code>%s</code></p>', h($picked['dir']))
+ . tr('<p>Protected by the login cookie: %s.</p>', '<p>Закрыты по куке входа: %s.</p>', $written ? '<code>' . implode('</code>, <code>', array_map('h', $written)) . '</code>' : tr('no data and plans folders', 'нет папок data и plans'))
+ . $warn
+ . tr('<p>This page will not open again. <a href="../">Go to the planner</a> and sign in with the new password.</p>', '<p>Повторно эта страница не откроется. <a href="../">Перейти к планировщику</a> и войти с новым паролем.</p>'));
+ }
+ }
+}
+
+$first = null;
+foreach ($options as $o) {
+ if ($o['writable'] && !$o['inside'] && $first === null) {
+ $first = $o['id'];
+ }
+}
+if ($first === null) {
+ foreach ($options as $o) {
+ if ($o['writable'] && $first === null) {
+ $first = $o['id'];
+ }
+ }
+}
+
+$body = tr('<p class="muted">First run: set a password and a location for the plan storage. After setup this page is locked.</p>', '<p class="muted">Первый запуск: задайте пароль и место для хранилища плана. После установки эта страница блокируется.</p>');
+foreach ($errors as $e) {
+ $body .= '<p class="err">' . h($e) . '</p>';
+}
+$body .= '<form method="post" autocomplete="off">';
+if ($needKey) {
+ $body .= '<label for="key">' . tr('Setup key', 'Ключ установки') . '</label><input id="key" name="key" type="text" required>';
+}
+$body .= '<label for="password">' . tr('Password', 'Пароль') . '</label><input id="password" name="password" type="password" minlength="' . MIN_PASSWORD . '" required autofocus>';
+$body .= '<label for="repeat">' . tr('Repeat password', 'Повторите пароль') . '</label><input id="repeat" name="repeat" type="password" minlength="' . MIN_PASSWORD . '" required>';
+$body .= '<label>' . tr('Storage', 'Хранилище') . '</label>';
+foreach ($options as $o) {
+ $note = $o['inside'] ? tr('inside the site, protected by .htaccess', 'внутри сайта, закрывается .htaccess') : tr('outside the site root', 'вне корня сайта');
+ $body .= '<label class="opt"><input type="radio" name="storage" value="' . h($o['id']) . '"'
+ . ($o['id'] === $first ? ' checked' : '') . ($o['writable'] ? '' : ' disabled') . '>'
+ . '<span><code>' . h($o['dir']) . '</code><br><span class="muted">' . $note . ($o['writable'] ? '' : tr(', not writable', ', нет прав на запись')) . '</span></span></label>';
+}
+$body .= '<button type="submit"' . ($first === null ? ' disabled' : '') . '>' . tr('Install', 'Установить') . '</button></form>';
+if ($first === null) {
+ $body .= tr('<p class="err">No writable folder. Create one of the listed folders and give PHP write access.</p>', '<p class="err">Нет папки, доступной для записи. Создайте одну из перечисленных и дайте PHP права на запись.</p>');
+}
+setup_page(200, tr('Planner setup', 'Установка планировщика'), $body);
diff --git a/public/data/catalog.json b/public/data/catalog.json
new file mode 100644
index 0000000..b230b58
--- /dev/null
+++ b/public/data/catalog.json
@@ -0,0 +1 @@
+[{"id": "sip-124-2500x1250-prosip", "name": "СИП-панель 2500×1250×124 (ОСП 12 мм, ППС 100 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 124, "length": 2500, "height": 1250, "price": 4670, "unit": "шт", "pricePer": "1494 ₽/м² (3.125 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2500x1250-prosip", "name": "СИП-панель 2500×1250×174 (ОСП 12 мм, ППС 150 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 174, "length": 2500, "height": 1250, "price": 5510, "unit": "шт", "pricePer": "1763 ₽/м² (3.125 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2500x1250-prosip", "name": "СИП-панель 2500×1250×224 (ОСП 12 мм, ППС 200 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 224, "length": 2500, "height": 1250, "price": 6340, "unit": "шт", "pricePer": "2029 ₽/м² (3.125 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-124-2800x1250-prosip", "name": "СИП-панель 2800×1250×124 (ОСП 12 мм, ППС 100 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 124, "length": 2800, "height": 1250, "price": 5160, "unit": "шт", "pricePer": "1474 ₽/м² (3.5 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2800x1250-prosip", "name": "СИП-панель 2800×1250×174 (ОСП 12 мм, ППС 150 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 174, "length": 2800, "height": 1250, "price": 6100, "unit": "шт", "pricePer": "1743 ₽/м² (3.5 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2800x1250-prosip", "name": "СИП-панель 2800×1250×224 (ОСП 12 мм, ППС 200 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 224, "length": 2800, "height": 1250, "price": 7040, "unit": "шт", "pricePer": "2011 ₽/м² (3.5 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-118-2500x1250-prosip", "name": "СИП-панель 2500×1250×118 (ОСП 9 мм, ППС 100 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 118, "length": 2500, "height": 1250, "price": 4190, "unit": "шт", "pricePer": "1341 ₽/м² (3.125 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-168-2500x1250-prosip", "name": "СИП-панель 2500×1250×168 (ОСП 9 мм, ППС 150 мм)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 168, "length": 2500, "height": 1250, "price": 5030, "unit": "шт", "pricePer": "1610 ₽/м² (3.125 м² в панели)", "source": "prosip.ru/, прайс на странице", "note": "Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2500x625-prosip", "name": "СИП-панель 2500×625×174 (половинка)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 174, "length": 2500, "height": 625, "price": 2750, "unit": "шт", "pricePer": "1766 ₽/м²", "source": "prosip.ru/, прайс на странице", "note": "Фактическая ширина листа ОСП в половинке 623 мм (по прайсу). Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2500x625-prosip", "name": "СИП-панель 2500×625×224 (половинка)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 224, "length": 2500, "height": 625, "price": 3170, "unit": "шт", "pricePer": "2035 ₽/м²", "source": "prosip.ru/, прайс на странице", "note": "Фактическая ширина листа ОСП в половинке 623 мм (по прайсу). Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2800x625-prosip", "name": "СИП-панель 2800×625×174 (половинка)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 174, "length": 2800, "height": 625, "price": 3050, "unit": "шт", "pricePer": "1748 ₽/м²", "source": "prosip.ru/, прайс на странице", "note": "Фактическая ширина листа ОСП в половинке 623 мм (по прайсу). Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2800x625-prosip", "name": "СИП-панель 2800×625×224 (половинка)", "kind": "sip", "url": "https://prosip.ru/", "vendor": "ПроСИП", "region": "Ленинградская область", "thickness": 224, "length": 2800, "height": 625, "price": 3520, "unit": "шт", "pricePer": "2018 ₽/м²", "source": "prosip.ru/, прайс на странице", "note": "Фактическая ширина листа ОСП в половинке 623 мм (по прайсу). Производитель ПроСИП, Ленобласть (пос. им. Свердлова). ОСП-3 Калевала ЭкоДом Е0,5 + ППС ПСБ-С-25(Т), паз 25 мм по периметру. Раскрой и выборка пазов — 15% от цены панели. Петрович СИП-панели не продаёт.", "checkedAt": "2026-09-30"}, {"id": "sip-124-2500x1250-sip47", "name": "СИП-панель 2500×1250×124 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 124, "length": 2500, "height": 1250, "price": 4300, "unit": "шт", "pricePer": "1376 ₽/м²; половинка 2500×625 — 2400 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2500x1250-sip47", "name": "СИП-панель 2500×1250×174 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 174, "length": 2500, "height": 1250, "price": 4800, "unit": "шт", "pricePer": "1536 ₽/м²; половинка 2500×625 — 2650 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2500x1250-sip47", "name": "СИП-панель 2500×1250×224 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 224, "length": 2500, "height": 1250, "price": 5400, "unit": "шт", "pricePer": "1728 ₽/м²; половинка 2500×625 — 2950 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-124-2800x1250-sip47", "name": "СИП-панель 2800×1250×124 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 124, "length": 2800, "height": 1250, "price": 4800, "unit": "шт", "pricePer": "1371 ₽/м²; половинка 2800×625 — 2650 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2800x1250-sip47", "name": "СИП-панель 2800×1250×174 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 174, "length": 2800, "height": 1250, "price": 5400, "unit": "шт", "pricePer": "1543 ₽/м²; половинка 2800×625 — 2950 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-224-2800x1250-sip47", "name": "СИП-панель 2800×1250×224 ОСП 12/ППС-25", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 224, "length": 2800, "height": 1250, "price": 6000, "unit": "шт", "pricePer": "1714 ₽/м²; половинка 2800×625 — 3250 ₽", "source": "sip47.ru/sip-paneli/, таблица «ПСБ-С-25 до 17 кг/м³»", "note": "Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-csp-124-3000x1200-sip47", "name": "СИП-панель ЦСП 3000×1200×124", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 124, "length": 3000, "height": 1200, "price": 9700, "unit": "шт", "pricePer": "2694 ₽/м² (3,6 м²)", "source": "sip47.ru/sip-paneli/, таблица ЦСП (Г1)", "note": "Облицовка ЦСП 12 мм (Кострома), ППС-25. Единственная найденная в СПб/ЛО панель высотой 3000 мм; ширина 1200, а не 1250 — модуль раскладки другой. Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-csp-174-3000x1200-sip47", "name": "СИП-панель ЦСП 3000×1200×174", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 174, "length": 3000, "height": 1200, "price": 9950, "unit": "шт", "pricePer": "2764 ₽/м² (3,6 м²)", "source": "sip47.ru/sip-paneli/, таблица ЦСП (Г1)", "note": "Облицовка ЦСП 12 мм (Кострома), ППС-25. Единственная найденная в СПб/ЛО панель высотой 3000 мм; ширина 1200, а не 1250 — модуль раскладки другой. Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-csp-224-3000x1200-sip47", "name": "СИП-панель ЦСП 3000×1200×224", "kind": "sip", "url": "https://sip47.ru/sip-paneli/", "vendor": "Фабрика Сипа (sip47)", "region": "Ленинградская область", "thickness": 224, "length": 3000, "height": 1200, "price": 10250, "unit": "шт", "pricePer": "2847 ₽/м² (3,6 м²)", "source": "sip47.ru/sip-paneli/, таблица ЦСП (Г1)", "note": "Облицовка ЦСП 12 мм (Кострома), ППС-25. Единственная найденная в СПб/ЛО панель высотой 3000 мм; ширина 1200, а не 1250 — модуль раскладки другой. Фабрика Сипа (sip47), Ленобласть, Ломоносовский р-н, д. Малое Забородье. Базовый прайс производства: ОСП-3 Калевала-ЭкоДом Е0,5 + ППС ПСБ-С-25 до 17 кг/м³ (Knauf Therm). Паз 25 мм. Раскрой — 500 ₽ за панель.", "checkedAt": "2026-09-30"}, {"id": "sip-174-2500x1250-sipteh-msk", "name": "СИП-панель Taleon 2500×1250×174 (ОСП 12)", "kind": "sip", "url": "https://sip-teh.ru/sip-panel/price/", "vendor": "СИПТЕХ", "region": "Москва", "thickness": 174, "length": 2500, "height": 1250, "price": 4686, "unit": "шт", "pricePer": "1500 ₽/м²", "source": "sip-teh.ru/sip-panel/price/ («Цены актуальны» на дату проверки, при заказе от 50 шт, склад МО)", "checkedAt": "2026-09-30"}, {"id": "sip-csp-120-3000x1250-ekodom-msk", "name": "СИП-панель ЦСП 3000×1250×120 (ЦСП 10 мм)", "kind": "sip", "url": "https://ekodom-oz.ru/ceny/paneli-sip/", "vendor": "Эко Дом (Орехово-Зуево)", "region": "Москва и МО", "thickness": 120, "length": 3000, "height": 1250, "price": 7600, "unit": "шт", "pricePer": "2027 ₽/м² (3,75 м²)", "source": "ekodom-oz.ru/ceny/paneli-sip/, прайс ЦСП от 20.06.2026", "note": "Единственный найденный формат 3000×1250 — только с ЦСП, не с ОСП. ОСП-панелей 3000×1250 в прайсах не найдено.", "checkedAt": "2026-09-30"}, {"id": "sip-csp-170-3000x1250-ekodom-msk", "name": "СИП-панель ЦСП 3000×1250×170 (ЦСП 10 мм)", "kind": "sip", "url": "https://ekodom-oz.ru/ceny/paneli-sip/", "vendor": "Эко Дом (Орехово-Зуево)", "region": "Москва и МО", "thickness": 170, "length": 3000, "height": 1250, "price": 8200, "unit": "шт", "pricePer": "2187 ₽/м² (3,75 м²)", "source": "ekodom-oz.ru/ceny/paneli-sip/, прайс ЦСП от 20.06.2026", "note": "Единственный найденный формат 3000×1250 — только с ЦСП, не с ОСП. ОСП-панелей 3000×1250 в прайсах не найдено.", "checkedAt": "2026-09-30"}, {"id": "sip-csp-220-3000x1250-ekodom-msk", "name": "СИП-панель ЦСП 3000×1250×220 (ЦСП 10 мм)", "kind": "sip", "url": "https://ekodom-oz.ru/ceny/paneli-sip/", "vendor": "Эко Дом (Орехово-Зуево)", "region": "Москва и МО", "thickness": 220, "length": 3000, "height": 1250, "price": 8800, "unit": "шт", "pricePer": "2347 ₽/м² (3,75 м²)", "source": "ekodom-oz.ru/ceny/paneli-sip/, прайс ЦСП от 20.06.2026", "note": "Единственный найденный формат 3000×1250 — только с ЦСП, не с ОСП. ОСП-панелей 3000×1250 в прайсах не найдено.", "checkedAt": "2026-09-30"}, {"id": "osb3-9-2500x1250", "name": "Плита OSB-3 9х1250х2500 мм", "kind": "osb", "url": "https://petrovich.ru/product/106004/", "vendor": "Петрович", "sku": "106004", "region": "Санкт-Петербург", "thickness": 9, "length": 2500, "height": 1250, "price": 983, "priceCard": 949, "unit": "лист", "pricePer": "315 ₽/м² (3,125 м²)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/106004 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Производитель по карточке — Беларусь (для 9 мм); марку карточка не называет."}, {"id": "osb3-12-2500x1250", "name": "Плита OSB-3 12х1250х2500 мм", "kind": "osb", "url": "https://petrovich.ru/product/106007/", "vendor": "Петрович", "sku": "106007", "region": "Санкт-Петербург", "thickness": 12, "length": 2500, "height": 1250, "price": 1241, "priceCard": 1199, "unit": "лист", "pricePer": "397 ₽/м² (3,125 м²)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/106007 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30"}, {"id": "osb3-15-2500x1250", "name": "Плита OSB-3 15х1250х2500 мм", "kind": "osb", "url": "https://petrovich.ru/product/148359/", "vendor": "Петрович", "sku": "148359", "region": "Санкт-Петербург", "thickness": 15, "length": 2500, "height": 1250, "price": 1407, "priceCard": 1359, "unit": "лист", "pricePer": "450 ₽/м² (3,125 м²)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/148359 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30"}, {"id": "osb3-12-2500x1250-kalevala", "name": "Плита OSB-3 12х1250х2500 мм Калевала", "kind": "osb", "url": "https://petrovich.ru/product/670149/", "vendor": "Петрович", "sku": "670149", "region": "Санкт-Петербург", "thickness": 12, "length": 2500, "height": 1250, "price": 1241, "priceCard": 1199, "unit": "лист", "pricePer": "397 ₽/м² (3,125 м²)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/670149 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Калевала."}, {"id": "brus-150x150x6000-raw", "name": "Брус 150х150х6000 мм естественной влажности сорт 1-2 хвойные породы деловой ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/101144/", "vendor": "Петрович", "sku": "101144", "region": "Санкт-Петербург", "thickness": 150, "length": 6000, "height": 150, "price": 3880, "priceCard": 3749, "unit": "шт", "pricePer": "28741 ₽/м³ (0.135 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/101144 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Брус естественной влажности, сорт 1–2. Для ростверка/обвязки свай по SIPwall допускается доска 50×200 (50×150) естественной влажности; брус сечением 150×200/200×200 — по sip47."}, {"id": "brus-200x200x6000-raw", "name": "Брус 200х200х6000 мм естественной влажности сорт 1-2 хвойные породы деловой ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/101146/", "vendor": "Петрович", "sku": "101146", "region": "Санкт-Петербург", "thickness": 200, "length": 6000, "height": 200, "price": 6758, "priceCard": 6529, "unit": "шт", "pricePer": "28158 ₽/м³ (0.24 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/101146 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Естественной влажности, сорт 1–2."}, {"id": "brus-glulam-140x160x6000", "name": "Брус сухой строганый 140х160х6000 мм сорт АВ хвойные породы клееный", "kind": "timber", "url": "https://petrovich.ru/product/101149/", "vendor": "Петрович", "sku": "101149", "region": "Санкт-Петербург", "thickness": 140, "length": 6000, "height": 160, "price": 9833, "priceCard": 9500, "unit": "шт", "pricePer": "73381 ₽/м³ (0.134 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/101149 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Сухой строганый клееный, сорт АВ. Единственный сухой брус крупного сечения в СПб-Петровиче."}, {"id": "board-dry-45x145x6000", "name": "Доска сухая строганая 45х145х6000 мм хвойные породы сорт АВ ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/999590/", "vendor": "Петрович", "sku": "999590", "region": "Санкт-Петербург", "thickness": 45, "length": 6000, "height": 145, "price": 1967, "priceCard": 1900, "unit": "шт", "pricePer": "50436 ₽/м³ (0.039 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/999590 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Сухая строганая, 4 стороны, сорт АВ. Под панель 174 мм (ППС 150): соединительный/обвязочный брусок, 145 мм входит в паз."}, {"id": "board-dry-45x195x6000", "name": "Доска сухая строганая 45х195х6000 мм хвойные породы сорт АВ ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/999591/", "vendor": "Петрович", "sku": "999591", "region": "Санкт-Петербург", "thickness": 45, "length": 6000, "height": 195, "price": 2484, "priceCard": 2400, "unit": "шт", "pricePer": "46868 ₽/м³ (0.053 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/999591 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Сухая строганая, 4 стороны. Под панель 224 мм (ППС 200) и лаги перекрытия (SIPwall: лаги 224 — две доски 37×197)."}, {"id": "board-raw-50x150x6000", "name": "Доска обрезная нестроганая 50х150х6000 мм сорт 1-2 хвойные породы деловая экспортная ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/999571/", "vendor": "Петрович", "sku": "999571", "region": "Санкт-Петербург", "thickness": 50, "length": 6000, "height": 150, "price": 1479, "priceCard": 1429, "unit": "шт", "pricePer": "32867 ₽/м³ (0.045 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/999571 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Обрезная нестроганая, естественной влажности. Для ростверка на сваях (SIPwall — доска 50×150/50×200 естественной влажности)."}, {"id": "board-antisept-50x150x6000", "name": "Доска обрезная антисептированная 50х150х6000 мм естественной влажности сорт 1-2 хвойные породы ФГИС ЛК", "kind": "timber", "url": "https://petrovich.ru/product/613115/", "vendor": "Петрович", "sku": "613115", "region": "Санкт-Петербург", "thickness": 50, "length": 6000, "height": 150, "price": 1520, "priceCard": 1469, "unit": "шт", "pricePer": "33778 ₽/м³ (0.045 м³ в шт)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/613115 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Антисептированная, естественной влажности."}, {"id": "door-entrance-960x2050", "name": "Дверь входная Ferroni Стройгост 5 РФ правая антик серебро - дуб белый 960х2050 мм", "kind": "door", "url": "https://petrovich.ru/product/783155/", "vendor": "Петрович", "sku": "783155", "region": "Санкт-Петербург", "thickness": 45, "length": 960, "height": 2050, "price": 10900, "priceCard": 10900, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/783155 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Металлическая, без терморазрыва (толщина полотна 45 мм, металл 0,8 мм) — для неотапливаемого тамбура/хозблока. Размер по коробке 960×2050, проём 1000×2100.", "opening": {"width": 1000, "height": 2100}}, {"id": "door-entrance-860x2050", "name": "Дверь входная Ferroni Стройгост 5 РФ правая антик серебро - дуб белый 860х2050 мм", "kind": "door", "url": "https://petrovich.ru/product/783153/", "vendor": "Петрович", "sku": "783153", "region": "Санкт-Петербург", "thickness": 45, "length": 860, "height": 2050, "price": 10900, "priceCard": 10900, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/783153 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Та же серия, по коробке 860×2050, проём 900×2100.", "opening": {"width": 900, "height": 2100}}, {"id": "door-entrance-thermo-960x2050", "name": "Дверь входная с терморазрывом Ferroni Isoterma правая антик серебро - эмалит белый с зеркалом 960х2050 мм", "kind": "door", "url": "https://petrovich.ru/product/1100815/", "vendor": "Петрович", "sku": "1100815", "region": "Санкт-Петербург", "thickness": 110, "length": 960, "height": 2050, "price": 40036, "priceCard": 38870, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1100815 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "С терморазрывом, 3 контура уплотнения, толщина с коробкой 141 мм — вариант для уличного входа в отапливаемый дом.", "opening": {"width": 1000, "height": 2100}}, {"id": "door-interior-600x2000-dpg", "name": "Дверь межкомнатная ДПГ 600х2000 мм финишпленка белая глухая с замком", "kind": "door", "url": "https://petrovich.ru/product/685397/", "vendor": "Петрович", "sku": "685397", "region": "Санкт-Петербург", "thickness": 35, "length": 600, "height": 2000, "price": 3975, "priceCard": 3859, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/685397 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Полотно 600×2000, толщина 35 мм; «размер по коробке» в карточке 638×2019. Коробка и наличник продаются отдельно; размер проёма в карточке не указан — брать по коробке плюс монтажный зазор."}, {"id": "door-interior-700x2000-dpg", "name": "Дверь межкомнатная ДПГ 700х2000 мм финишпленка белая глухая с замком", "kind": "door", "url": "https://petrovich.ru/product/685398/", "vendor": "Петрович", "sku": "685398", "region": "Санкт-Петербург", "thickness": 35, "length": 700, "height": 2000, "price": 3975, "priceCard": 3859, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/685398 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Полотно 700×2000, толщина 35 мм; «размер по коробке» в карточке 738×2019. Коробка и наличник продаются отдельно; размер проёма в карточке не указан — брать по коробке плюс монтажный зазор."}, {"id": "door-interior-800x2000-dpg", "name": "Дверь межкомнатная ДПГ 800х2000 мм финишпленка белая глухая с замком", "kind": "door", "url": "https://petrovich.ru/product/685399/", "vendor": "Петрович", "sku": "685399", "region": "Санкт-Петербург", "thickness": 35, "length": 800, "height": 2000, "price": 3975, "priceCard": 3859, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/685399 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Полотно 800×2000, толщина 35 мм; «размер по коробке» в карточке 838×2019. Коробка и наличник продаются отдельно; размер проёма в карточке не указан — брать по коробке плюс монтажный зазор."}, {"id": "door-interior-800x2000", "name": "Дверь межкомнатная 800х2000 мм финишпленка белая глухая", "kind": "door", "url": "https://petrovich.ru/product/858381/", "vendor": "Петрович", "sku": "858381", "region": "Санкт-Петербург", "thickness": 35, "length": 800, "height": 2000, "price": 2347, "priceCard": 2279, "unit": "шт", "availability": "Софийская 13 шт", "source": "api.petrovich.ru/catalog/v5/products/858381 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Полотно 800×2000, толщина 35 мм; «размер по коробке» в карточке 838×2019. Коробка и наличник продаются отдельно; размер проёма в карточке не указан — брать по коробке плюс монтажный зазор."}, {"id": "door-interior-900x2000", "name": "Дверь межкомнатная 900х2000 мм финишпленка белая глухая", "kind": "door", "url": "https://petrovich.ru/product/998291/", "vendor": "Петрович", "sku": "998291", "region": "Санкт-Петербург", "thickness": 35, "length": 900, "height": 2000, "price": 2347, "priceCard": 2279, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/998291 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Полотно 900×2000, толщина 35 мм; «размер по коробке» в карточке 938×2019. Коробка и наличник продаются отдельно; размер проёма в карточке не указан — брать по коробке плюс монтажный зазор."}, {"id": "window-pvc-900w-900h", "name": "Пластиковое окно VEKA WHS Halo 60 900х900 мм 1 створка правая поворотно-откидная однокамерное", "kind": "window", "url": "https://petrovich.ru/product/681116/", "vendor": "Петрович", "sku": "681116", "region": "Санкт-Петербург", "thickness": 60, "length": 900, "height": 900, "price": 9714, "priceCard": 9431, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/681116 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "VEKA WHS Halo 60 (монтажная глубина 60 мм по названию серии). В названии Петровича «900х900» — высота × ширина; в карточке Ширина 900, Высота 900. 1 створка поворотно-откидная, однокамерный стеклопакет 716×716. Размер проёма под окно карточка не даёт."}, {"id": "window-pvc-800w-1160h", "name": "Пластиковое окно VEKA WHS Halo 60 1160х800 мм 1 створка поворотно-откидная правая однокамерное", "kind": "window", "url": "https://petrovich.ru/product/167176/", "vendor": "Петрович", "sku": "167176", "region": "Санкт-Петербург", "thickness": 60, "length": 800, "height": 1160, "price": 11830, "priceCard": 11485, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/167176 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "VEKA WHS Halo 60 (монтажная глубина 60 мм по названию серии). В названии Петровича «1160х800» — высота × ширина; в карточке Ширина 800, Высота 1160. 1 створка поворотно-откидная, однокамерный стеклопакет. Размер проёма под окно карточка не даёт."}, {"id": "window-pvc-1000w-1160h", "name": "Пластиковое окно VEKA WHS Halo 60 1160х1000 мм 2 створки левая глухая правая поворотно-откидная двухкамерное", "kind": "window", "url": "https://petrovich.ru/product/681103/", "vendor": "Петрович", "sku": "681103", "region": "Санкт-Петербург", "thickness": 60, "length": 1000, "height": 1160, "price": 12610, "priceCard": 12243, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/681103 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "VEKA WHS Halo 60 (монтажная глубина 60 мм по названию серии). В названии Петровича «1160х1000» — высота × ширина; в карточке Ширина 1000, Высота 1160. 2 створки (глухая + поворотно-откидная), двухкамерный стеклопакет. Размер проёма под окно карточка не даёт."}, {"id": "window-pvc-1200w-1160h", "name": "Пластиковое окно VEKA WHS Halo 60 1160х1200 мм 2 створки левая глухая правая поворотно-откидная двухкамерное", "kind": "window", "url": "https://petrovich.ru/product/681104/", "vendor": "Петрович", "sku": "681104", "region": "Санкт-Петербург", "thickness": 60, "length": 1200, "height": 1160, "price": 15355, "priceCard": 14908, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/681104 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "VEKA WHS Halo 60 (монтажная глубина 60 мм по названию серии). В названии Петровича «1160х1200» — высота × ширина; в карточке Ширина 1200, Высота 1160. 2 створки, двухкамерный стеклопакет. Размер проёма под окно карточка не даёт."}, {"id": "window-pvc-1200w-1440h", "name": "Пластиковое окно VEKA WHS Halo 60 1440х1200 мм 2 створки левая глухая правая поворотно-откидная двухкамерное", "kind": "window", "url": "https://petrovich.ru/product/681105/", "vendor": "Петрович", "sku": "681105", "region": "Санкт-Петербург", "thickness": 60, "length": 1200, "height": 1440, "price": 18177, "priceCard": 17648, "unit": "шт", "availability": "Отсутствует в городе", "source": "api.petrovich.ru/catalog/v5/products/681105 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "VEKA WHS Halo 60 (монтажная глубина 60 мм по названию серии). В названии Петровича «1440х1200» — высота × ширина; в карточке Ширина 1200, Высота 1440. 2 створки, двухкамерный. Размер проёма под окно карточка не даёт."}, {"id": "pile-screw-108x2500", "name": "Свая винтовая d108х2500 мм", "kind": "foundation", "url": "https://petrovich.ru/product/609375/", "vendor": "Петрович", "sku": "609375", "region": "Санкт-Петербург", "thickness": 108, "length": 2500, "price": 3410, "priceCard": 3311, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/609375 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Винтовая свая d108×2500. Лопасть 300 мм, стенка 4 мм. Только свая — оголовок и монтаж отдельно.", "foundationType": "screw-pile"}, {"id": "pile-screw-108x3000", "name": "Свая винтовая d108х3000 мм", "kind": "foundation", "url": "https://petrovich.ru/product/629103/", "vendor": "Петрович", "sku": "629103", "region": "Санкт-Петербург", "thickness": 108, "length": 3000, "price": 4316, "priceCard": 4190, "unit": "шт", "availability": "Таллинское 2 шт", "source": "api.petrovich.ru/catalog/v5/products/629103 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Винтовая свая d108×3000. Лопасть 300 мм.", "foundationType": "screw-pile"}, {"id": "pile-screw-89x2500", "name": "Свая винтовая d89х2500 мм", "kind": "foundation", "url": "https://petrovich.ru/product/162435/", "vendor": "Петрович", "sku": "162435", "region": "Санкт-Петербург", "thickness": 89, "length": 2500, "price": 2349, "priceCard": 2281, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/162435 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Винтовая свая d89×2500. Лопасть 250 мм, стенка 3,5 мм.", "foundationType": "screw-pile"}, {"id": "wool-rockwool-lightbatts-50", "name": "Утеплитель Роквул Лайт Баттс 50х600х1000 мм 6 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/106939/", "vendor": "Петрович", "sku": "106939", "region": "Санкт-Петербург", "thickness": 50, "length": 1000, "height": 600, "price": 2225, "priceCard": 2160, "unit": "упак", "pricePer": "371 ₽/м² (6 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/106939 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 10 плит в упаковке."}, {"id": "wool-rockwool-lightbatts-100", "name": "Утеплитель Роквул Лайт Баттс 100х600х1000 мм 3 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/106938/", "vendor": "Петрович", "sku": "106938", "region": "Санкт-Петербург", "thickness": 100, "length": 1000, "height": 600, "price": 2225, "priceCard": 2160, "unit": "упак", "pricePer": "742 ₽/м² (3 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/106938 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 5 плит в упаковке."}, {"id": "wool-rockwool-scandic-150", "name": "Утеплитель Роквул Лайт Баттс Скандик 150х600х1200 мм 3,6 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/159396/", "vendor": "Петрович", "sku": "159396", "region": "Санкт-Петербург", "thickness": 150, "length": 1200, "height": 600, "price": 2935, "priceCard": 2850, "unit": "упак", "pricePer": "815 ₽/м² (3.6 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/159396 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 5 плит в упаковке."}, {"id": "wool-rockwool-karkas-100", "name": "Утеплитель Роквул Каркас Баттс 100х600х1000 мм 3,6 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/1072400/", "vendor": "Петрович", "sku": "1072400", "region": "Санкт-Петербург", "thickness": 100, "length": 1000, "height": 600, "price": 2039, "priceCard": 1980, "unit": "упак", "pricePer": "566 ₽/м² (3.6 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1072400 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 6 плит в упаковке."}, {"id": "wool-rockwool-optima-100", "name": "Утеплитель Роквул Лайт Баттс Оптима 100х600х1000 мм 3 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/977419/", "vendor": "Петрович", "sku": "977419", "region": "Санкт-Петербург", "thickness": 100, "length": 1000, "height": 600, "price": 1485, "priceCard": 1439, "unit": "упак", "pricePer": "495 ₽/м² (3 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/977419 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 5 плит в упаковке."}, {"id": "wool-tn-teplyi-karkas-100", "name": "Утеплитель Технониколь Теплый каркас 100х610х1200 мм 3,66 кв.м", "kind": "insulation", "url": "https://petrovich.ru/product/1145151/", "vendor": "Петрович", "sku": "1145151", "region": "Санкт-Петербург", "thickness": 100, "length": 1200, "height": 610, "price": 1299, "priceCard": 1259, "unit": "упак", "pricePer": "355 ₽/м² (3.66 м² в упаковке)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1145151 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "Каменная вата. 5 плит в упаковке."}, {"id": "xps-penoplex-fundament-100", "name": "Экструдированный пенополистирол Пеноплэкс Фундамент 100х585х1185 мм", "kind": "insulation", "url": "https://petrovich.ru/product/506118/", "vendor": "Петрович", "sku": "506118", "region": "Санкт-Петербург", "thickness": 100, "length": 1185, "height": 585, "price": 865, "priceCard": 839, "unit": "лист", "pricePer": "1248 ₽/м² (0,693 м² в листе)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/506118 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "XPS Пеноплэкс Фундамент — утепление УШП/цоколя/отмостки. Продаётся поштучно (лист), в упаковке 4 листа."}, {"id": "xps-penoplex-fundament-50", "name": "Экструдированный пенополистирол Пеноплэкс Фундамент 50х585х1185 мм", "kind": "insulation", "url": "https://petrovich.ru/product/170045/", "vendor": "Петрович", "sku": "170045", "region": "Санкт-Петербург", "thickness": 50, "length": 1185, "height": 585, "price": 370, "priceCard": 359, "unit": "лист", "pricePer": "534 ₽/м² (0,693 м² в листе)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/170045 (city_code=spb) + микроразметка страницы", "checkedAt": "2026-09-30", "note": "XPS Пеноплэкс Фундамент — утепление УШП/цоколя/отмостки. Продаётся поштучно (лист), в упаковке 7 листа."}, {"id": "ushp-spb-topfundament", "name": "УШП под ключ", "kind": "foundation", "foundationType": "ushp", "url": "https://top-fundament.ru/fundamenty/fundament-ushp", "vendor": "Топ Фундамент", "region": "Санкт-Петербург и ЛО", "price": 5500, "unit": "м²", "pricePer": "₽ за м² плиты, «от»", "source": "top-fundament.ru/fundamenty/fundament-ushp", "note": "На странице три уровня: от 5 500, 6 500, 7 500 ₽/м². Что входит (тёплый пол, коммуникации) — уточнять.", "checkedAt": "2026-09-30"}, {"id": "ushp-spb-fundament98", "name": "УШП под ключ", "kind": "foundation", "foundationType": "ushp", "url": "https://fundament98.ru/fundaments/ushp.html", "vendor": "Фундамент98", "region": "Санкт-Петербург и ЛО", "price": 6000, "unit": "м²", "pricePer": "₽ за м², «от»", "source": "fundament98.ru/fundaments/ushp.html", "note": "В перечне работ: канализация, закладные под вводы, трубы тёплого пола с коллектором, арматурная сетка, бетон В22,5 М300.", "checkedAt": "2026-09-30"}, {"id": "ushp-spb-svaifund", "name": "УШП под ключ", "kind": "foundation", "foundationType": "ushp", "url": "https://sankt-peterburg.svaifund.ru/fundament-ushp/", "vendor": "СваиФунд", "region": "Санкт-Петербург и ЛО", "price": 3000, "unit": "м²", "pricePer": "₽ за м², «от»; плита 10×10×300 мм — от 300 000 ₽", "source": "sankt-peterburg.svaifund.ru/fundament-ushp/", "note": "Заметно ниже рынка (у остальных 5 500–6 000 ₽/м²) — скорее всего без тёплого пола и коммуникаций. Считать нижней границей.", "checkedAt": "2026-09-30"}, {"id": "gate-alutech-trend-2500-2250-s-ruchnym-upravleniem", "name": "Секционные гаражные ворота ALUTECH Trend 2500×2250, ручные", "kind": "gate", "url": "https://spb.alutech.ru/vorota/garazhnye/sekcionnye/alutech-trend-2500-2250-s-ruchnym-upravleniem/", "vendor": "ALUTECH (официальный сайт СПб)", "region": "Санкт-Петербург", "thickness": 40, "length": 2500, "height": 2250, "opening": {"width": 2500, "height": 2250}, "price": 104010, "unit": "шт", "pricePer": "18491 ₽/м² проёма", "source": "spb.alutech.ru, JSON-LD Product/Offer + блок цены", "checkedAt": "2026-09-30", "note": "Цена без скидки 122360 ₽. Ручное управление, пружины растяжения, панель 40 мм S-гофр, RAL 9016. Ближайший стандарт к проёму 2500×2200. Официальный розничный сайт ALUTECH в СПб (spb.alutech.ru), цена из JSON-LD Offer, «без учёта монтажа». Размер в названии — размер проёма (ширина×высота). Стандартный ряд высот Trend — 2000/2125/2250/2375/2500; ровно 2200 — только под заказ по замеру. Петрович секционных гаражных ворот не продаёт (в разделе «Ворота и калитки» только уличные распашные/откатные)."}, {"id": "gate-alutech-trend-2500-2250", "name": "Секционные гаражные ворота ALUTECH Trend 2500×2250 с автоматикой", "kind": "gate", "url": "https://spb.alutech.ru/vorota/garazhnye/sekcionnye/alutech-trend-2500-2250/", "vendor": "ALUTECH (официальный сайт СПб)", "region": "Санкт-Петербург", "thickness": 40, "length": 2500, "height": 2250, "opening": {"width": 2500, "height": 2250}, "price": 136220, "unit": "шт", "pricePer": "24217 ₽/м² проёма", "source": "spb.alutech.ru, JSON-LD Product/Offer + блок цены", "checkedAt": "2026-09-30", "note": "Электропривод LG-800, пружины растяжения, панель 40 мм, RAL 7016. Официальный розничный сайт ALUTECH в СПб (spb.alutech.ru), цена из JSON-LD Offer, «без учёта монтажа». Размер в названии — размер проёма (ширина×высота). Стандартный ряд высот Trend — 2000/2125/2250/2375/2500; ровно 2200 — только под заказ по замеру. Петрович секционных гаражных ворот не продаёт (в разделе «Ворота и калитки» только уличные распашные/откатные)."}, {"id": "gate-alutech-trend-2500-2125", "name": "Секционные гаражные ворота ALUTECH Trend 2500×2125, ручные", "kind": "gate", "url": "https://spb.alutech.ru/vorota/garazhnye/sekcionnye/alutech-trend-2500-2125/", "vendor": "ALUTECH (официальный сайт СПб)", "region": "Санкт-Петербург", "thickness": 40, "length": 2500, "height": 2125, "opening": {"width": 2500, "height": 2125}, "price": 118380, "unit": "шт", "pricePer": "22283 ₽/м² проёма", "source": "spb.alutech.ru, JSON-LD Product/Offer + блок цены", "checkedAt": "2026-09-30", "note": "Ручное, панель 45 мм L-гофр, цвет «золотой дуб». Официальный розничный сайт ALUTECH в СПб (spb.alutech.ru), цена из JSON-LD Offer, «без учёта монтажа». Размер в названии — размер проёма (ширина×высота). Стандартный ряд высот Trend — 2000/2125/2250/2375/2500; ровно 2200 — только под заказ по замеру. Петрович секционных гаражных ворот не продаёт (в разделе «Ворота и калитки» только уличные распашные/откатные)."}, {"id": "gate-alutech-trend-3000-2250-avtomaticheskie", "name": "Секционные гаражные ворота ALUTECH Trend 3000×2250 с автоматикой", "kind": "gate", "url": "https://spb.alutech.ru/vorota/garazhnye/sekcionnye/alutech-trend-3000-2250-avtomaticheskie/", "vendor": "ALUTECH (официальный сайт СПб)", "region": "Санкт-Петербург", "thickness": 40, "length": 3000, "height": 2250, "opening": {"width": 3000, "height": 2250}, "price": 141660, "unit": "шт", "pricePer": "20987 ₽/м² проёма", "source": "spb.alutech.ru, JSON-LD Product/Offer + блок цены", "checkedAt": "2026-09-30", "note": "Цена без скидки 166660 ₽. Привод ASG600/3KIT-L, панель 40 мм, «тёмный дуб». Официальный розничный сайт ALUTECH в СПб (spb.alutech.ru), цена из JSON-LD Offer, «без учёта монтажа». Размер в названии — размер проёма (ширина×высота). Стандартный ряд высот Trend — 2000/2125/2250/2375/2500; ровно 2200 — только под заказ по замеру. Петрович секционных гаражных ворот не продаёт (в разделе «Ворота и калитки» только уличные распашные/откатные)."}, {"id": "gate-doorhan-rsd01-2400x2100", "name": "Секционные гаражные ворота DoorHan RSD01 2400×2100 (пружины растяжения)", "kind": "gate", "url": "https://spb.gild24.ru/catalog/avtomaticheskie_vorota/sekcionnye/garazhnye/", "vendor": "Гильдия ворот (DoorHan)", "region": "Санкт-Петербург", "thickness": 40, "length": 2400, "height": 2100, "opening": {"width": 2400, "height": 2100}, "price": 31542, "unit": "шт", "pricePer": "6258 ₽/м² проёма", "source": "spb.gild24.ru, таблица «RSD01 Ширина × Высота»", "checkedAt": "2026-09-30", "note": "Официальный дилер DoorHan в СПб (gild24). Цена из прайс-таблицы серии на странице раздела, ширины в таблице только до 2400; «цена может меняться в зависимости от курса ЦБ», дата прайса не указана — цены заметно ниже ALUTECH, перед заказом подтвердить. Без привода и монтажа."}, {"id": "gate-doorhan-rsd02-2400x2200", "name": "Секционные гаражные ворота DoorHan RSD02 2400×2200 (торсионный механизм)", "kind": "gate", "url": "https://spb.gild24.ru/catalog/avtomaticheskie_vorota/sekcionnye/garazhnye/s_torsionnym_mehanizmom/", "vendor": "Гильдия ворот (DoorHan)", "region": "Санкт-Петербург", "thickness": 40, "length": 2400, "height": 2200, "opening": {"width": 2400, "height": 2200}, "price": 32637, "unit": "шт", "pricePer": "6181 ₽/м² проёма", "source": "spb.gild24.ru, таблица «RSD02 Ширина × Высота»", "checkedAt": "2026-09-30", "note": "Официальный дилер DoorHan в СПб (gild24). Цена из прайс-таблицы серии на странице раздела, ширины в таблице только до 2400; «цена может меняться в зависимости от курса ЦБ», дата прайса не указана — цены заметно ниже ALUTECH, перед заказом подтвердить. Без привода и монтажа. Панели 40 мм, торсионный механизм."}, {"id": "pir-sip-174-2500x1250-ilya", "name": "СИП-ПИР панель ОСП-3 Калевала / PIR 2500×1250×174", "kind": "pir", "subtype": "sip-pir", "url": "https://www.ilya-stroy.ru/sip-panels/sip-paneli-kalevala-s-ppu-pir/sip-panel-kalevala-ppu-pir/", "vendor": "Илья-Строй", "region": "Москва и МО", "thickness": 174, "length": 2500, "height": 1250, "weight": 55, "lambda": 0.02, "fireGroup": "Г1 (карточка) / Г3–Г1 (раздел)", "price": 13885, "unit": "шт", "pricePer": "4443 ₽/м² (3,125 м²)", "source": "ilya-stroy.ru, карточка и таблица раздела «СИП-панели Калевала с ППУ (PIR)»", "checkedAt": "2026-09-30", "note": "Облицовка ОСП-3 12 мм, паз 40 мм (или 50 мм для усиленного каркаса). В карточке «Класс горючести — Г1», в описании раздела «Г3–Г1» — подтверждать сертификатом."}, {"id": "pir-sip-174-2800x1250-ilya", "name": "СИП-ПИР панель ОСП-3 Калевала / PIR 2800×1250×174", "kind": "pir", "subtype": "sip-pir", "url": "https://www.ilya-stroy.ru/sip-panels/", "vendor": "Илья-Строй", "region": "Москва и МО", "thickness": 174, "length": 2800, "height": 1250, "lambda": 0.02, "fireGroup": "Г3–Г1 (по описанию раздела)", "price": 15386, "unit": "шт", "pricePer": "4396 ₽/м² (3,5 м²)", "source": "ilya-stroy.ru/sip-panels/, таблица «Калевала с ППУ (PIR)» (у Талион те же цены)", "checkedAt": "2026-09-30", "note": "Под стену гаража высотой 2,8 м — ровно одна панель по высоте. Облицовка ОСП-3 12 мм, паз 40 мм (или 50 мм для усиленного каркаса). В карточке «Класс горючести — Г1», в описании раздела «Г3–Г1» — подтверждать сертификатом."}, {"id": "pir-sip-greenboard-174-2800x600-ilya", "name": "СИП-ПИР панель GreenBoard / PIR 2800×600×174", "kind": "pir", "subtype": "sip-pir", "url": "https://www.ilya-stroy.ru/sip-panels/", "vendor": "Илья-Строй", "region": "Москва и МО", "thickness": 174, "length": 2800, "height": 600, "lambda": 0.02, "fireGroup": "Г3–Г1 (по описанию раздела)", "price": 6807, "unit": "шт", "pricePer": "4052 ₽/м² (1,68 м²)", "source": "ilya-stroy.ru/sip-panels/, таблица «Green Board с ППУ (PIR)»", "checkedAt": "2026-09-30", "note": "Облицовка — фибролит GreenBoard 12 мм (цементно-стружечный, трудногорючий) вместо ОСП: снаружи негорючая поверхность лучше ОСП для противопожарных разрывов. Есть 3000×600×174 — 7 203 ₽. Облицовка ОСП-3 12 мм, паз 40 мм (или 50 мм для усиленного каркаса). В карточке «Класс горючести — Г1», в описании раздела «Г3–Г1» — подтверждать сертификатом."}, {"id": "pir-metal-wall-100-metpan", "name": "Стеновая сэндвич-панель PIR 100 мм (сталь 0,45–0,7 мм), рабочая ширина 1160/1190", "kind": "pir", "subtype": "metal-sandwich", "url": "https://metpan.ru/catalog/sendvich-paneli/sendvich-paneli-iz-penopoliizotsianurata/", "vendor": "МЕТПАН (СПб)", "region": "Санкт-Петербург", "thickness": 100, "length": 2800, "height": 1190, "lambda": 0.022, "fireGroup": "утеплитель Г1 (по сайту), обшивка — сталь (НГ)", "price": 3348, "unit": "м²", "pricePer": "3348 ₽/м² «от»; при заказе от 300 м² — 2 480 ₽/м²", "source": "metpan.ru, карточки раздела и таблица цен от 300 м²", "checkedAt": "2026-09-30", "note": "Длина — под заказ до 13 500 мм (в каталоге указана 2800 как высота стены гаража). Толщины и цены «от» за м²: 50 — 3 078, 80 — 3 213, 100 — 3 348, 120 — 3 578, 150 — 3 780. Панель не несущая: нужен стальной или деревянный каркас (стойки, ригели), плюс фасонные элементы и саморезы.", "preferred": true}, {"id": "pir-metal-wall-100-spsever", "name": "Стеновая сэндвич-панель PIR 100 мм (сталь 0,5–0,6 мм)", "kind": "pir", "subtype": "metal-sandwich", "url": "https://sp-sever.ru/panels/spanel_pir", "vendor": "СП-Север (СПб)", "region": "Санкт-Петербург", "thickness": 100, "length": 2800, "height": 1000, "fireGroup": "огнестойкость панели RE15 (50 мм) – RE45; группа горючести на странице не указана", "price": 3149, "unit": "м²", "pricePer": "3149 ₽/м² по таблице; в карточках той же страницы 1 757 ₽/м²", "source": "sp-sever.ru/panels/spanel_pir, таблица «Цены на стеновые сэндвич-панели с наполнителем PIR» и карточки", "checkedAt": "2026-09-30", "note": "На странице две цены: карточки (50 мм — 1 361, 100 — 1 757, 150 — 2 200 ₽/м²) и таблица (50 — 2 391, 100 — 3 149, 150 — 4 012 ₽/м²); в каталог взята таблица, карточки — вероятно акция, уточнять. Коэффициент теплопередачи панели 100 мм — 0,041 Вт/(м²·К) по таблице сайта. Рабочая ширина на странице не указана (у отрасли 1000/1160/1190). Не несущая, нужен каркас."}, {"id": "logicpir-banya-50-petrovich", "name": "Плита теплоизоляционная Технониколь LOGICPIR Баня Ф/Ф 50×590×1190", "kind": "pir", "subtype": "pir-board", "url": "https://petrovich.ru/product/1214673/", "vendor": "Петрович", "sku": "1214673", "region": "Санкт-Петербург", "thickness": 50, "length": 1190, "height": 590, "weight": 1.481, "lambda": 0.023, "fireGroup": "Г1", "price": 939, "priceCard": 909, "unit": "лист", "pricePer": "1341 ₽/м² (0,70 м²)", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1214673 (spb)", "checkedAt": "2026-09-30", "note": "Это не панель, а утеплитель для каркаса (фольга с двух сторон, L-кромка, 5 листов в упаковке). Единственная PIR-плита Технониколь в наличии в СПб-Петровиче; обычный LOGICPIR 50 мм (арт.", "facing": "фольга/фольга, L-кромка"}, {"id": "logicpir-50-petrovich-g4", "name": "Плита теплоизоляционная Технониколь LOGICPIR Ф/Ф 50×590×1190 (Г4)", "kind": "pir", "subtype": "pir-board", "url": "https://petrovich.ru/product/624380/", "vendor": "Петрович", "sku": "624380", "region": "Санкт-Петербург", "thickness": 50, "length": 1190, "height": 590, "weight": 1.48, "lambda": 0.022, "fireGroup": "Г4", "price": 825, "unit": "лист", "pricePer": "1175 ₽/м² (0,70 м²)", "availability": "Отсутствует в городе", "source": "api.petrovich.ru/catalog/v5/products/624380 (spb)", "checkedAt": "2026-09-30", "note": "Показан ради горючести: розничный LOGICPIR без индекса «Баня»/«PROF Г1» — Г4, как ППС. Прежняя цена 1 110 ₽.", "facing": "фольга/фольга, L-кромка"}, {"id": "pir-plate-30-1190x590-petrovich-banya", "name": "Плита теплоизоляционная Технониколь Logicpir Баня 30×590×1190 мм", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Санкт-Петербург", "url": "https://petrovich.ru/product/1214674/", "price": 689, "priceCard": 669, "unit": "лист", "pricePer": "981 ₽/м², 32711 ₽/м³", "thickness": 30, "length": 1190, "height": 590, "facing": "фольга/фольга", "availability": "СПб: «Отсутствует в городе»", "checkedAt": "2026-09-30", "note": "API Петровича. Упаковка 8 листов.", "lambda": 0.023, "vendor": "Петрович", "fireGroup": "Г1", "subtype": "pir-board"}, {"id": "pir-plate-50-1190x590-vseinstrumenti", "name": "Термоплита Технониколь LOGICPIR Ф/Ф 1190×590×50 мм, упаковка 5 шт (TN722950)", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Москва (цена показана для Москвы)", "url": "https://www.vseinstrumenti.ru/product/teploizolyatsiya-tehnonikol-logicpir-f-f-g1-1190h590h50-mm-tn650052-1780568/", "price": 6250, "unit": "упак (5 шт, 3.51 м²)", "pricePer": "1781 ₽/м²", "thickness": 50, "length": 1190, "height": 590, "facing": "фольга/фольга, L-кромка", "availability": "97 шт на складе, самовывоз сегодня, курьер завтра от 290 ₽ (для Москвы)", "checkedAt": "2026-09-30", "note": "WebFetch карточки (регион страницы — Москва, СПб-поддомен редиректит на www). Старая цена 7 686 ₽. В названии URL стоит «g1», но в характеристиках карточки — Г4.", "lambda": 0.021, "vendor": "ВсеИнструменты.ру", "fireGroup": "Г4", "subtype": "pir-board"}, {"id": "pir-plate-30-1190x590-vseinstrumenti", "name": "Термоплита Технониколь LOGICPIR Ф/Ф 1190×590×30 мм, упаковка 8 шт (TN722947)", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Москва (цена показана для Москвы)", "url": "https://www.vseinstrumenti.ru/product/teploizolyatsiya-tehnonikol-logicpir-f-f-g1-1190h590h30-mm-tn650050-1780572/", "price": 7320, "unit": "упак (8 шт, 5.62 м²)", "pricePer": "1302 ₽/м²", "thickness": 30, "length": 1190, "height": 590, "facing": "фольга/фольга, L-кромка", "availability": "от поставщика, самовывоз 15 октября, курьер с 16 октября (для Москвы)", "checkedAt": "2026-09-30", "note": "WebFetch карточки. Обычная цена 8 420 ₽. Мира 8а). Толще 50 мм PIR-плит в разделе ВсеИнструменты нет; сэндвич-панелей ПИР нет.", "lambda": 0.022, "vendor": "ВсеИнструменты.ру", "fireGroup": "Г4", "subtype": "pir-board"}, {"id": "pir-plate-30-1190x590-lemana-balkon", "name": "Теплоизоляционная PIR-плита 30 мм Logicpir Балкон 590×1190 мм 0.7021 м²", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Москва", "url": "https://lemanapro.ru/product/teploizolyacionnaya-pir-plita-30-mm-logicpir-balkon-590x1190-mm-07021-m-18212757/", "price": 642, "unit": "шт", "pricePer": "914 ₽/м²", "thickness": 30, "length": 1190, "height": 590, "facing": "фольга/фольга", "checkedAt": "2026-09-30", "note": "Сайт закрыт Qrator (401 и для curl, и для WebFetch). Цена взята из заголовка страницы в поисковой выдаче («купить по цене 642 ₽ в Москве»), саму карточку открыть не удалось. Раздел spb.lemanapro.ru/catalogue/pir-plity/tehnonikol/ в заголовке пишет «от 643 руб.» — вероятно, та же плита в СПб. Горючесть и λ не проверены.", "vendor": "Лемана ПРО", "subtype": "pir-board"}, {"id": "pir-plate-50-1185x585-lemana-banya", "name": "Теплоизоляционная PIR-плита 50 мм Logicpir Баня 585×1185 мм 0.693 м²", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Москва", "url": "https://lemanapro.ru/product/teploizolyacionnaya-pir-plita-50-mm-logicpir-banya-585x1185-mm-0693-m-18212765/", "price": 853, "unit": "шт", "pricePer": "1231 ₽/м²", "thickness": 50, "length": 1185, "height": 585, "facing": "фольга/фольга", "checkedAt": "2026-09-30", "note": "Цена из заголовка страницы в поисковой выдаче (Москва, 853 ₽/шт). Та же позиция есть на spb.lemanapro.ru/product/…-18212765/, но цена СПб недоступна (401). Горючесть и λ не проверены.", "vendor": "Лемана ПРО", "subtype": "pir-board"}, {"id": "pir-sandwich-100-2000x1190-lemana-profholod", "name": "Сэндвич-панель PIR Профхолод 2000×1190×100 мм белый (91396021)", "kind": "pir", "category": "стеновая сэндвич-панель металл/PIR/металл", "region": "Уфа, Барнаул (в СПб не найдена)", "url": "https://ufa.lemanapro.ru/product/sendvich-panel-pir-profholod-2000x1190x100mm-belyy-91396021/", "price": 10199, "unit": "шт", "pricePer": "4285 ₽/м² (2.38 м² в панели)", "thickness": 100, "length": 2000, "height": 1190, "facing": "оцинкованная профилированная сталь с полиэфирным покрытием, белая", "availability": "продаётся в региональных магазинах (Уфа, Барнаул, Новосибирск, Тюмень)", "checkedAt": "2026-09-30", "note": "Единственная стеновая ПИР-панель, найденная в рознице из списка. Цена из заголовков страниц в выдаче (Уфа 10 199 ₽, Барнаул 10 199 ₽/шт), страница закрыта Qrator. Утеплитель PIR PREMIER, назначение по описанию — быстровозводимые здания, холодильные камеры.", "vendor": "Лемана ПРО", "subtype": "metal-sandwich"}, {"id": "pir-plate-50-1190x590-tophouse", "name": "LOGICPIR Ф/Ф L-1190×590×50 мм (5 плит), ТехноНиколь", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Санкт-Петербург", "url": "https://www.tophouse.ru/price/logicpir-f-f-l-1190h590h50mm-5-plit-uteplitel-lodzhik-pir-plita-34527", "price": 6077.54, "unit": "упак (5 шт, 3.51 м²)", "pricePer": "1731 ₽/м²", "thickness": 50, "length": 1190, "height": 590, "facing": "фольга/фольга, L-кромка", "checkedAt": "2026-09-30", "note": "Вне основного списка площадок, строительный магазин СПб; цена из листинга tophouse.ru/products/utepliteli-izolyacia/pir-panels (curl, серверный рендер). Там же PROF Ф/Ф Г1 2385×1185 30–60 мм по 40–62 тыс. ₽ за упаковку, количество плит в упаковке в листинге не указано.", "vendor": "ТОП ХАУС (tophouse.ru)", "subtype": "pir-board"}, {"id": "pir-plate-40-1190x590-grandline-spb", "name": "Плита теплоизоляционная Logicpir Ф/Ф L-1190×590×40 (4,212 м²)", "kind": "pir", "category": "утеплитель (PIR-плита), не панель", "region": "Санкт-Петербург", "url": "https://spb.grandline.ru/logicpir-ff-l-1190h590h40-42126-m2-543005.html", "price": 5283.6, "unit": "упак (4.212 м²)", "pricePer": "1254 ₽/м²", "thickness": 40, "length": 1190, "height": 590, "facing": "фольга/фольга, L-кромка", "availability": "поступление на склад при заказе сегодня — 12.10.2026", "checkedAt": "2026-09-30", "note": "Вне основного списка площадок. curl, серверный рендер; цена со скидкой 15% (без скидки 6 216 ₽). Назначение в карточке — стены, фасад, кровля, балконы.", "lambda": "0,022–0,025", "vendor": "Grand Line (spb.grandline.ru)", "fireGroup": "Г4", "subtype": "pir-board"}, {"id": "pir-house-doorhan-44pro-spb", "name": "Домокомплект DoorHan 44 ПРО, 44 м², панели ПИР 100 мм", "kind": "pir", "region": "Санкт-Петербург", "url": "https://spb.doorhan-house.ru/", "price": 2371387, "pricePer": "от 2 371 387 ₽ за домокомплект ≈53 895 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 44, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan серии ПРО: металлокаркас из утеплённых рам, ограждающие панели с утеплителем ПИР 100 мм, цоколь, фасонные элементы, метизы, лестница для 2-этажных. Сайт называет дома и «домокомплектом», и «под ключ» — состав цены уточнять. Доставка в цену не входит. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, офис продаж модульных домов в Санкт-Петербурге", "subtype": "house-kit"}, {"id": "pir-house-doorhan-59pro-spb", "name": "Домокомплект DoorHan 59 ПРО, 59 м², панели ПИР 100 мм", "kind": "pir", "region": "Санкт-Петербург", "url": "https://spb.doorhan-house.ru/", "price": 2907117, "pricePer": "от 2 907 117 ₽ за домокомплект ≈49 273 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 59, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan серии ПРО: металлокаркас из утеплённых рам, ограждающие панели с утеплителем ПИР 100 мм, цоколь, фасонные элементы, метизы, лестница для 2-этажных. Сайт называет дома и «домокомплектом», и «под ключ» — состав цены уточнять. Доставка в цену не входит. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, офис продаж модульных домов в Санкт-Петербурге", "subtype": "house-kit"}, {"id": "pir-house-doorhan-88pro-spb", "name": "Домокомплект DoorHan 88 ПРО, 88 м², панели ПИР 100 мм", "kind": "pir", "region": "Санкт-Петербург", "url": "https://spb.doorhan-house.ru/", "price": 3665481, "pricePer": "от 3 665 481 ₽ за домокомплект ≈41 653 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 88, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan серии ПРО: металлокаркас из утеплённых рам, ограждающие панели с утеплителем ПИР 100 мм, цоколь, фасонные элементы, метизы, лестница для 2-этажных. Сайт называет дома и «домокомплектом», и «под ключ» — состав цены уточнять. Доставка в цену не входит. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, офис продаж модульных домов в Санкт-Петербурге", "subtype": "house-kit"}, {"id": "pir-house-doorhan-103pro-spb", "name": "Домокомплект DoorHan 103 ПРО, 103 м², панели ПИР 100 мм", "kind": "pir", "region": "Санкт-Петербург", "url": "https://spb.doorhan-house.ru/", "price": 4339195, "pricePer": "от 4 339 195 ₽ за домокомплект ≈42 128 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 103, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan серии ПРО: металлокаркас из утеплённых рам, ограждающие панели с утеплителем ПИР 100 мм, цоколь, фасонные элементы, метизы, лестница для 2-этажных. Сайт называет дома и «домокомплектом», и «под ключ» — состав цены уточнять. Доставка в цену не входит. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, офис продаж модульных домов в Санкт-Петербурге", "subtype": "house-kit"}, {"id": "pir-house-doorhan-133pro-spb", "name": "Домокомплект DoorHan 133 ПРО, 133 м², панели ПИР 100 мм", "kind": "pir", "region": "Санкт-Петербург", "url": "https://spb.doorhan-house.ru/", "price": 5275349, "pricePer": "от 5 275 349 ₽ за домокомплект ≈39 664 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 133, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan серии ПРО: металлокаркас из утеплённых рам, ограждающие панели с утеплителем ПИР 100 мм, цоколь, фасонные элементы, метизы, лестница для 2-этажных. Сайт называет дома и «домокомплектом», и «под ключ» — состав цены уточнять. Доставка в цену не входит. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, офис продаж модульных домов в Санкт-Петербурге", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-29", "name": "Домокомплект DoorHan 29, 29 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 1569511, "pricePer": "от 1 569 511 ₽ за домокомплект ≈54 121 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 29, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-44", "name": "Домокомплект DoorHan 44, 44 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 2083404, "pricePer": "от 2 083 404 ₽ за домокомплект ≈47 350 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 44, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-59", "name": "Домокомплект DoorHan 59, 59 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 2618506, "pricePer": "от 2 618 506 ₽ за домокомплект ≈44 381 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 59, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-74", "name": "Домокомплект DoorHan 74, 74 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 3250862, "pricePer": "от 3 250 862 ₽ за домокомплект ≈43 931 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 74, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-88-2", "name": "Домокомплект DoorHan 88-2, 88 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 3416698, "pricePer": "от 3 416 698 ₽ за домокомплект ≈38 826 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 88, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-118-1", "name": "Домокомплект DoorHan 118-1, 118 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 4275979, "pricePer": "от 4 275 979 ₽ за домокомплект ≈36 237 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 118, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-118-2", "name": "Домокомплект DoorHan 118-2, 118 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 4275979, "pricePer": "от 4 275 979 ₽ за домокомплект ≈36 237 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 118, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-148-2", "name": "Домокомплект DoorHan 148-2, 148 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "price": 5468780, "pricePer": "от 5 468 780 ₽ за домокомплект ≈36 951 ₽/м²", "unit": "домокомплект", "thickness": 100, "area": 148, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "pir-house-dhhouse-88", "name": "Домокомплект DoorHan 88, 88 м², панели ПИР 100 мм", "kind": "pir", "region": "Ленинградская область", "url": "https://spb.dh-house.ru/", "pricePer": "цена по запросу", "unit": "домокомплект", "thickness": 100, "area": 88, "checkedAt": "2026-09-30", "note": "Домокомплект модульного дома DoorHan: ограждающие панели с утеплителем ПИР 100 мм и цоколем, металлокаркас. Цена «от», доставка отдельно. Цена за м² посчитана делением цены на площадь. На сайте опечатка в цене: «от 3 661 7863 ₽»; в карточке 118-1 на 103 м² — «от 34 165 584 ₽», тоже опечатка. Уточнять.", "vendor": "DoorHan, официальный партнёр (house-doorhan.ru), Кудрово", "subtype": "house-kit"}, {"id": "smartblock-row-390x200x200-smartblok", "name": "Смарт-Блок рядовой 390×200×200 (несъёмная бетонная опалубка)", "kind": "block", "url": "https://xn----7sbe2ajfduoho.xn--p1ai/", "vendor": "ООО «Смарт-Блок» (производитель, смарт-блоки.рф)", "region": "Московская область, Королёв", "thickness": 200, "length": 390, "height": 200, "price": 228, "unit": "шт", "pricePer": "≈15 000 ₽/м³ (на странице); ≈2 920 ₽/м² стены при 12,8 шт/м²", "source": "смарт-блоки.рф, карточка «Смарт-Блок Рядовой», розничная цена", "note": "Пустотелый вибропрессованный бетонный блок, масса ≈16 кг. Первый ряд на раствор М300, дальше на плиточный клей со швом 1–3 мм; армирование Ø8 А500С горизонтально в 1, 5, 9, 13 рядах и вертикально; каждые 5–6 рядов пустоты заливают бетоном В20–В25 (инструкция производителя, версия 5 от 01.11.2024). Готовая несущая стена — монолитный железобетон 200 мм, НГ. Производитель предлагает 200 мм + ППС-16Ф 150 мм = 350 мм, R = 3,78 м²·°С/Вт. Патент РФ № 2791088. Тел.", "checkedAt": "2026-09-30", "preferred": true, "delivery": "из Подмосковья — по запросу", "bestReason": "Оригинальный «Смарт-Блок»"}, {"id": "smartblock-corner-400x400x200-smartblok", "name": "Смарт-Блок угловой 400×400×200", "kind": "block", "url": "https://xn----7sbe2ajfduoho.xn--p1ai/", "vendor": "ООО «Смарт-Блок» (производитель, смарт-блоки.рф)", "region": "Московская область, Королёв", "thickness": 200, "length": 400, "height": 200, "price": 510, "unit": "шт", "pricePer": "по запросу", "source": "смарт-блоки.рф, карточка «Смарт-Блок Угловой», розничная цена", "note": "Масса ≈26,5 кг, опалубка углов несущих стен, в плане 400×400. Заливается бетоном вместе с рядовыми.", "checkedAt": "2026-09-30", "preferred": true, "delivery": "из Подмосковья — по запросу", "bestReason": "Оригинальный «Смарт-Блок»"}, {"id": "smartblock-dobor-200x200x200-smartblok", "name": "Смарт-Блок доборный 200×200×200", "kind": "block", "url": "https://xn----7sbe2ajfduoho.xn--p1ai/", "vendor": "ООО «Смарт-Блок» (производитель, смарт-блоки.рф)", "region": "Московская область, Королёв", "thickness": 200, "length": 200, "height": 200, "price": 162, "unit": "шт", "pricePer": "по запросу", "source": "смарт-блоки.рф, карточка «Смарт-Блок Доборный», розничная цена", "note": "Масса ≈10,7 кг, половинный элемент для перевязки у углов и откосов проёмов.", "checkedAt": "2026-09-30", "preferred": true, "delivery": "из Подмосковья — по запросу", "bestReason": "Оригинальный «Смарт-Блок»"}, {"id": "smartblock-partition-390x120x200-smartblok", "name": "Смарт-Блок перегородочный 390×120×200", "kind": "block", "url": "https://xn----7sbe2ajfduoho.xn--p1ai/", "vendor": "ООО «Смарт-Блок» (производитель, смарт-блоки.рф)", "region": "Московская область, Королёв", "thickness": 120, "length": 390, "height": 200, "price": 158, "unit": "шт", "pricePer": "≈2 025 ₽/м² перегородки при 12,8 шт/м²", "source": "смарт-блоки.рф, карточка «Смарт-Блок Перегородочный», розничная цена", "note": "Масса ≈11,6 кг, бетоном не заполняется (инструкция производителя). Поддон 120 шт, ≈1 392 кг. Над дверями перегородок — перевёрнутый блок на двух уголках 50×50×5, зазор 20–30 мм под потолком запенивается.", "checkedAt": "2026-09-30", "preferred": true, "delivery": "из Подмосковья — по запросу", "bestReason": "Оригинальный «Смарт-Блок»"}, {"id": "smartblock-row-390x200x200-gssmarket", "name": "Смарт-Блок рядовой 390×200×200 (дилер ГССМаркет)", "kind": "block", "url": "https://gssmarket.ru/ryadovoj-blok-390h200h200mm", "vendor": "ГССМаркет (дилер из списка производителя)", "region": "Московская область, Пушкино", "thickness": 200, "length": 390, "height": 200, "price": 192, "unit": "шт", "pricePer": "≈2 460 ₽/м² стены при 12,8 шт/м²", "source": "gssmarket.ru, карточка товара", "note": "Тот же блок производителя «Смарт-Блок», на 16% дешевле розницы завода. Тел.", "checkedAt": "2026-09-30", "preferred": true, "delivery": "из Подмосковья — по запросу", "bestReason": "Оригинальный «Смарт-Блок»"}, {"id": "smartblock-fund-595x300x200-depostroy", "name": "Смарт-Блок фундаментный 595×300×200 (дилер ДепоСтрой)", "kind": "block", "url": "https://depostroy.ru/smart-blok-fundamentnyy-595h300h200-nesemnaya-betonnaya-opalubka", "vendor": "ДепоСтрой (дилер из списка производителя)", "region": "Московская область, Королёв", "thickness": 300, "length": 595, "height": 200, "price": 479, "unit": "шт", "pricePer": "у завода 522 ₽/шт, ≈21 900 ₽/м³", "source": "depostroy.ru, карточка товара", "note": "Масса 27,3 кг, 24 шт на поддоне. Для ленточного фундамента и цоколя. Рядовой и перегородочный у дилера — по запросу. Тел.", "checkedAt": "2026-09-30"}, {"id": "teploblok-400-teplobloki-sz", "name": "Теплоблок 400×200×400 под покраску (200 несущая + 150 ППС + 50 фасад)", "kind": "block", "url": "https://teplobloki-sz.ru/teplobloki", "vendor": "Теплоблоки Северо-Запад (производитель)", "region": "Санкт-Петербург", "thickness": 400, "length": 400, "height": 200, "price": 580, "unit": "шт", "pricePer": "7 250 ₽/м² стены (12,5 шт/м²)", "source": "teplobloki-sz.ru/teplobloki, прайс на странице", "note": "Трёхслойный блок: несущий слой 200 мм, пенополистирол 25–35 плотности 150 мм, фасадный слой 50 мм (песок, гранитная крошка, цемент М500). Масса 27 кг. Цветной фасад — 600 ₽/шт, керамзитный под штукатурку 400 мм — 550 ₽/шт, 300 мм под отделку — 460 ₽/шт. ППС внутри блока горючий, класс пожарной опасности конструкции на сайте не заявлен. Доставка в регионы, стоимость по запросу. Тел.", "checkedAt": "2026-09-30"}, {"id": "opalubka-600x300x160-teplobloki-sz", "name": "Блок несъёмной опалубки бетонный 600×300×160", "kind": "block", "url": "https://teplobloki-sz.ru/nesyemnaya_opalubka", "vendor": "Теплоблоки Северо-Запад (производитель)", "region": "Санкт-Петербург", "thickness": 300, "length": 600, "height": 160, "price": 320, "unit": "шт", "pricePer": "≈3 330 ₽/м² стены (10,41 шт/м²), бетон 0,1 м³/м²", "source": "teplobloki-sz.ru/nesyemnaya_opalubka, цена на странице", "note": "Местный аналог Смарт-Блока, но толще (стена 300 мм) и под заборы/цоколь; перегородочного блока нет. В15 (М200), F150, 30 кг, 36 шт на поддоне, угловые элементы есть. НГ.", "checkedAt": "2026-09-30"}, {"id": "opalubka-500x200x200-comstroy", "name": "Блок несъёмной опалубки бетонный 500×200×200", "kind": "block", "url": "https://comstroy-spb.ru/catalog/zhelezobetonnye_izdeliya_zhbi/nesyomnaya_opalubka/", "vendor": "КомСтрой СПб", "region": "Санкт-Петербург", "thickness": 200, "length": 500, "height": 200, "price": 250, "unit": "шт", "pricePer": "2 500 ₽/м² стены (10 шт/м²)", "source": "comstroy-spb.ru, раздел «Несъёмная опалубка», цены на 01.06.2026", "note": "Местный аналог Смарт-Блока той же толщины 200 мм, 16,8 кг. Также 500×300×200 — 285 ₽ (20 кг), 500×400×200 — 310 ₽ (30 кг). Позиционируется под фундаменты; углового и перегородочного элементов нет. НГ.", "checkedAt": "2026-09-30"}, {"id": "icf-eps-ttksistema", "name": "Несъёмная опалубка из пенополистирола (ICF), стенки 50/50–70/100", "kind": "block", "url": "https://ttksistema.ru/nesemnaya-opalubka/", "vendor": "ТТК Система", "region": "Санкт-Петербург", "thickness": 250, "length": 1200, "height": null, "price": 1589, "unit": "м²", "pricePer": "1 589–3 189 ₽/м² стены в зависимости от плотности", "source": "ttksistema.ru/nesemnaya-opalubka, цены на странице", "note": "Длина блока 1200, ширина 150–300, стенки ППС 50/50, 50/75, 50/100, 70/100 мм, бетона ≈0,125 м³/м². ППС самозатухающий, но это Г3–Г4: дом без негорючей облицовки считается V степени, С2–С3. Только юрлицам, минимальный заказ 100 000 ₽. Толщина в поле — типовая, высота блока на странице не указана.", "checkedAt": "2026-09-30"}, {"id": "sewer-pipe-in-50-500", "name": "Труба канализационная Valfex Base d50x500 мм пластиковая для внутренней канализации (200500050)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983650/", "vendor": "Петрович", "sku": "983650", "region": "Санкт-Петербург", "diameter": 50, "length": 500, "price": 68, "priceCard": 66, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983650 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 1,8 мм."}, {"id": "sewer-pipe-in-50-1000", "name": "Труба канализационная Valfex Base d50x1000 мм пластиковая для внутренней канализации", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983651/", "vendor": "Петрович", "sku": "983651", "region": "Санкт-Петербург", "diameter": 50, "length": 1000, "price": 105, "priceCard": 105, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983651 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 1,8 мм."}, {"id": "sewer-pipe-in-50-2000", "name": "Труба канализационная Valfex Base d50x2000 мм пластиковая для внутренней канализации", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983652/", "vendor": "Петрович", "sku": "983652", "region": "Санкт-Петербург", "diameter": 50, "length": 2000, "price": 179, "priceCard": 179, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983652 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 1,8 мм. Длины 3 м в Ø50 у Петровича нет ни у одного бренда."}, {"id": "sewer-pipe-in-110-500", "name": "Труба канализационная Valfex Base d110x500 мм пластиковая для внутренней канализации (201100050)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983663/", "vendor": "Петрович", "sku": "983663", "region": "Санкт-Петербург", "diameter": 110, "length": 500, "price": 186, "priceCard": 181, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983663 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 2,7 мм."}, {"id": "sewer-pipe-in-110-1000", "name": "Труба канализационная Valfex Base d110x1000 мм пластиковая для внутренней канализации (201100100)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983664/", "vendor": "Петрович", "sku": "983664", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 277, "priceCard": 277, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983664 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 2,7 мм."}, {"id": "sewer-pipe-in-110-2000", "name": "Труба канализационная Valfex Base d110x2000 мм пластиковая для внутренней канализации (201100200)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/983665/", "vendor": "Петрович", "sku": "983665", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 552, "priceCard": 552, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983665 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП серый, стенка 2,7 мм."}, {"id": "sewer-pipe-in-110-3000", "name": "Труба канализационная Ostendorf HTEM d110х3000 мм пластиковая для внутренней канализации (115070)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/1052982/", "vendor": "Петрович", "sku": "1052982", "region": "Санкт-Петербург", "diameter": 110, "length": 3000, "price": 1414, "priceCard": 1373, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1052982 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Внутренняя, ПП Ostendorf HT; у Valfex длины 3 м нет."}, {"id": "sewer-elbow-in-50-45", "name": "Отвод Valfex d50 мм 45° пластиковый для внутренней канализации (20102050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983645/", "vendor": "Петрович", "sku": "983645", "region": "Санкт-Петербург", "diameter": 50, "angle": 45, "price": 20, "priceCard": 19, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983645 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-elbow-in-50-87", "name": "Отвод Valfex d50 мм 87° пластиковый для внутренней канализации (20101050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983646/", "vendor": "Петрович", "sku": "983646", "region": "Санкт-Петербург", "diameter": 50, "angle": 87, "price": 23, "priceCard": 22, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983646 (city_code=spb)", "checkedAt": "2026-09-30", "note": "На горизонтали не ставить (СП 30 п. 18.4), только на подъём к прибору."}, {"id": "sewer-tee-in-50-45", "name": "Тройник Valfex d50х50 мм 45° пластиковый для внутренней канализации (22050050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983647/", "vendor": "Петрович", "sku": "983647", "region": "Санкт-Петербург", "diameter": 50, "angle": 45, "price": 46, "priceCard": 45, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983647 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-tee-in-50-87", "name": "Тройник Valfex d50х50 мм 87° пластиковый для внутренней канализации (24050050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983648/", "vendor": "Петрович", "sku": "983648", "region": "Санкт-Петербург", "diameter": 50, "angle": 87, "price": 46, "priceCard": 45, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983648 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-elbow-in-110-45", "name": "Отвод Valfex d110 мм 45° пластиковый для внутренней канализации (20102110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983656/", "vendor": "Петрович", "sku": "983656", "region": "Санкт-Петербург", "diameter": 110, "angle": 45, "price": 81, "priceCard": 79, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983656 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-elbow-in-110-87", "name": "Отвод Valfex d110 мм 87° пластиковый для внутренней канализации (20101110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983657/", "vendor": "Петрович", "sku": "983657", "region": "Санкт-Петербург", "diameter": 110, "angle": 87, "price": 95, "priceCard": 92, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983657 (city_code=spb)", "checkedAt": "2026-09-30", "note": "На горизонтали не ставить (СП 30 п. 18.4)."}, {"id": "sewer-tee-in-110-45", "name": "Тройник Valfex d110 мм 45° пластиковый для внутренней канализации (22110110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983658/", "vendor": "Петрович", "sku": "983658", "region": "Санкт-Петербург", "diameter": 110, "angle": 45, "price": 157, "priceCard": 152, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983658 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-tee-in-110-87", "name": "Тройник Valfex d110 мм 87° пластиковый для внутренней канализации (24110110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983659/", "vendor": "Петрович", "sku": "983659", "region": "Санкт-Петербург", "diameter": 110, "angle": 87, "price": 135, "priceCard": 131, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983659 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-tee-in-110x50-45", "name": "Тройник Valfex d110х50 мм 45° пластиковый для внутренней канализации (22110050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983660/", "vendor": "Петрович", "sku": "983660", "region": "Санкт-Петербург", "diameter": 110, "angle": 45, "price": 103, "priceCard": 100, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983660 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Тройник 110×50."}, {"id": "sewer-tee-in-110x50-87", "name": "Тройник Valfex d110х50 мм 87° пластиковый для внутренней канализации (24110050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983661/", "vendor": "Петрович", "sku": "983661", "region": "Санкт-Петербург", "diameter": 110, "angle": 87, "price": 91, "priceCard": 88, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983661 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Тройник 110×50."}, {"id": "sewer-reducer-in-110x50", "name": "Переходник Valfex d110х50 мм пластиковый эксцентрический для внутренней канализации (25110050)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983654/", "vendor": "Петрович", "sku": "983654", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 65, "priceCard": 63, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983654 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Переход эксцентрический 110×50."}, {"id": "sewer-cap-in-50", "name": "Заглушка Valfex d50 мм пластиковая для внутренней канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983642/", "vendor": "Петрович", "sku": "983642", "region": "Санкт-Петербург", "diameter": 50, "angle": 0, "price": 9, "priceCard": 9, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983642 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-cap-in-110", "name": "Заглушка Valfex d110 мм пластиковая для внутренней канализации (20108110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983653/", "vendor": "Петрович", "sku": "983653", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 24, "priceCard": 23, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983653 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-wc-cuff-110", "name": "Манжета для унитаза d110 мм эксцентриковая", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/502727/", "vendor": "Петрович", "sku": "502727", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 260, "priceCard": 252, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/502727 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Манжета эксцентриковая для подключения унитаза."}, {"id": "sewer-wc-corrugated-110", "name": "Слив для унитаза d110 мм пластиковый гофрированный для внутренней канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/502726/", "vendor": "Петрович", "sku": "502726", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 357, "priceCard": 357, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/502726 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Гофра для унитаза, альтернатива манжете."}, {"id": "sewer-clamp-50-plastic", "name": "Хомут сантехнический 50 мм пластик с дюбелем для крепления трубы (2 шт.)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/109196/", "vendor": "Петрович", "sku": "109196", "region": "Санкт-Петербург", "diameter": 50, "angle": 0, "price": 82, "priceCard": 79, "unit": "упак", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/109196 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Хомут пластиковый, упаковка 2 шт."}, {"id": "sewer-clamp-110-plastic", "name": "Хомут сантехнический 110 мм пластик с дюбелем для крепления трубы (2 шт.)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/109194/", "vendor": "Петрович", "sku": "109194", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 133, "priceCard": 129, "unit": "упак", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/109194 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Хомут пластиковый, упаковка 2 шт."}, {"id": "sewer-clamp-50-steel", "name": "Хомут сантехнический 1 1/2 48-53 мм оцинкованная сталь со шпилькой и дюбелем", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/109197/", "vendor": "Петрович", "sku": "109197", "region": "Санкт-Петербург", "diameter": 50, "angle": 0, "price": 83, "priceCard": 81, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/109197 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Хомут стальной 48–53 мм со шпилькой и дюбелем."}, {"id": "sewer-clamp-110-steel", "name": "Хомут сантехнический 4\" 108-114 мм оцинкованная сталь со шпилькой и дюбелем", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/109203/", "vendor": "Петрович", "sku": "109203", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 131, "priceCard": 127, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/109203 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Хомут стальной 108–114 мм со шпилькой и дюбелем."}, {"id": "sewer-air-valve-110", "name": "Клапан вакуумный Valfex d110 мм пластиковый для внутренней канализации (26000110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983706/", "vendor": "Петрович", "sku": "983706", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 172, "priceCard": 167, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983706 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аэратор (вакуумный клапан). При септике основной стояк выводится на кровлю, клапан — только на дополнительных стояках (СП 30 п. 18.25)."}, {"id": "sewer-air-valve-50", "name": "Клапан вакуумный Ostendorf HT d50 мм пластиковый для внутренней канализации (881780)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/103458/", "vendor": "Петрович", "sku": "103458", "region": "Санкт-Петербург", "diameter": 50, "angle": 0, "price": 868, "priceCard": 843, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/103458 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аэратор Ø50, Ostendorf; у Valfex Ø50 нет."}, {"id": "sewer-vent-cap-110", "name": "Грибок (дефлектор) Valfex d110 мм пластиковый для внутренней канализации (26106110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/983637/", "vendor": "Петрович", "sku": "983637", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 105, "priceCard": 102, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983637 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Грибок на фановую трубу; по СП 30 дефлектор на вентстояке не допускается — брать только как защиту от мусора по согласованию."}, {"id": "sewer-cleanout-in-110", "name": "Ревизия Valfex d110 мм пластиковая для внутренней канализации (20103110)", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/983703/", "vendor": "Петрович", "sku": "983703", "region": "Санкт-Петербург", "diameter": 110, "price": 192, "priceCard": 186, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/983703 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-cleanout-in-50", "name": "Ревизия Ostendorf HTRE d50 мм пластиковая для внутренней канализации (112600)", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/106785/", "vendor": "Петрович", "sku": "106785", "region": "Санкт-Петербург", "diameter": 50, "price": 417, "priceCard": 405, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/106785 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Ревизия Ø50 Ostendorf; у Valfex Ø50 нет."}, {"id": "sewer-pipe-out-110-1000", "name": "Труба канализационная Хемкор d110х1000 мм для наружной канализации (1491226)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/1227732/", "vendor": "Петрович", "sku": "1227732", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 304, "priceCard": 304, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1227732 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная ПВХ рыжая Хемкор."}, {"id": "sewer-pipe-out-110-2000", "name": "Труба канализационная Хемкор d110х2000 мм для наружной канализации (1491227)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/1227731/", "vendor": "Петрович", "sku": "1227731", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 436, "priceCard": 436, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1227731 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная ПВХ рыжая Хемкор."}, {"id": "sewer-pipe-out-110-3000", "name": "Труба канализационная Хемкор d110х3000 мм для наружной канализации (1491228)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/1227730/", "vendor": "Петрович", "sku": "1227730", "region": "Санкт-Петербург", "diameter": 110, "length": 3000, "price": 829, "priceCard": 829, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1227730 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная ПВХ рыжая Хемкор."}, {"id": "sewer-pipe-out-110-1000-ostendorf", "name": "Труба канализационная Ostendorf KGEM d110x1000 мм для наружной канализации (220010)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/108476/", "vendor": "Петрович", "sku": "108476", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 620, "priceCard": 620, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/108476 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная Ostendorf KG, дороже Хемкора вдвое."}, {"id": "sewer-pipe-out-110-2000-ostendorf", "name": "Труба канализационная Ostendorf KGEM d110x2000 мм для наружной канализации (220020)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/108477/", "vendor": "Петрович", "sku": "108477", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 1142, "priceCard": 1142, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/108477 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная Ostendorf KG."}, {"id": "sewer-pipe-out-110-3000-ostendorf", "name": "Труба канализационная Ostendorf KGEM d110x3000 мм для наружной канализации (220030)", "kind": "sewer", "subtype": "pipe", "url": "https://petrovich.ru/product/1052983/", "vendor": "Петрович", "sku": "1052983", "region": "Санкт-Петербург", "diameter": 110, "length": 3000, "price": 1825, "priceCard": 1772, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1052983 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Наружная Ostendorf KG."}, {"id": "sewer-elbow-out-110-45", "name": "Отвод Valfex d110 мм 45° пластиковый для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016569/", "vendor": "Петрович", "sku": "1016569", "region": "Санкт-Петербург", "diameter": 110, "angle": 45, "price": 69, "priceCard": 69, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016569 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-elbow-out-110-87", "name": "Отвод Valfex d110 мм 87,5° пластиковый для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016572/", "vendor": "Петрович", "sku": "1016572", "region": "Санкт-Петербург", "diameter": 110, "angle": 87, "price": 139, "priceCard": 135, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016572 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Угол 87,5°; на наружной сети поворот через колодец или 2×45°."}, {"id": "sewer-tee-out-110-45", "name": "Тройник Valfex d110 мм 45° пластиковый для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016571/", "vendor": "Петрович", "sku": "1016571", "region": "Санкт-Петербург", "diameter": 110, "angle": 45, "price": 190, "priceCard": 190, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016571 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-tee-out-110-87", "name": "Тройник Valfex d110 мм 87,5° пластиковый для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016579/", "vendor": "Петрович", "sku": "1016579", "region": "Санкт-Петербург", "diameter": 110, "angle": 87, "price": 195, "priceCard": 189, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016579 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Угол 87,5°."}, {"id": "sewer-cap-out-110", "name": "Заглушка Valfex d110 мм пластиковая для наружной канализации (30108110)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016564/", "vendor": "Петрович", "sku": "1016564", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 29, "priceCard": 28, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016564 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-coupling-out-110-repair", "name": "Муфта Valfex d110 мм пластиковая ремонтная для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016574/", "vendor": "Петрович", "sku": "1016574", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 84, "priceCard": 82, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016574 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Муфта ремонтная (надвижная), Valfex."}, {"id": "sewer-check-valve-out-110", "name": "Клапан обратный Valfex d110 мм пластиковый для наружной канализации", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/1016565/", "vendor": "Петрович", "sku": "1016565", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 2557, "priceCard": 2483, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016565 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Обратный клапан наружный."}, {"id": "sewer-well-cuff-110", "name": "Манжета Ostendorf 110 мм для врезки в колодец (634615)", "kind": "sewer", "subtype": "fitting", "url": "https://petrovich.ru/product/684348/", "vendor": "Петрович", "sku": "684348", "region": "Санкт-Петербург", "diameter": 110, "angle": 0, "price": 2937, "priceCard": 2851, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/684348 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Манжета для врезки трубы 110 в стенку колодца."}, {"id": "sewer-cleanout-out-110", "name": "Ревизия Valfex d110 мм пластиковая для наружной канализации", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/1016578/", "vendor": "Петрович", "sku": "1016578", "region": "Санкт-Петербург", "diameter": 110, "price": 220, "priceCard": 214, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1016578 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Ревизия наружная, ставится в колодец или под люк."}, {"id": "sewer-well-315-1000", "name": "Колодец дренажный смотровой 315/276х1000 мм с тремя отводами 110 мм с дном и крышкой", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/613202/", "vendor": "Петрович", "sku": "613202", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 1928, "priceCard": 1872, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/613202 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Колодец ревизионный 315/276, высота 1 м, три отвода 110, с дном и крышкой."}, {"id": "sewer-well-368-1000", "name": "Колодец дренажный смотровой 368/315х1000 мм с тремя отводами 110 мм с дном и крышкой", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/103746/", "vendor": "Петрович", "sku": "103746", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 2902, "priceCard": 2817, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/103746 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Колодец ревизионный 368/315, 1 м, три отвода 110."}, {"id": "sewer-well-368-1500", "name": "Колодец дренажный смотровой 368/315х1500 мм с тремя отводами 110 мм с дном и крышкой", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/103748/", "vendor": "Петрович", "sku": "103748", "region": "Санкт-Петербург", "diameter": 110, "length": 1500, "price": 3894, "priceCard": 3781, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/103748 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Колодец ревизионный 368/315, 1,5 м, три отвода 110."}, {"id": "sewer-well-368-2000", "name": "Колодец дренажный смотровой 368/315х2000 мм с тремя отводами 110 мм с дном и крышкой", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/504518/", "vendor": "Петрович", "sku": "504518", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 5096, "priceCard": 4948, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/504518 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Колодец ревизионный 368/315, 2 м, три отвода 110."}, {"id": "sewer-well-hatch-730", "name": "Люк полимерно-песчаный газонный легкий для смотровых колодцев 730х55 мм", "kind": "sewer", "subtype": "cleanout", "url": "https://petrovich.ru/product/953921/", "vendor": "Петрович", "sku": "953921", "region": "Санкт-Петербург", "price": 1211, "priceCard": 1176, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/953921 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Люк газонный лёгкий 730 мм для колодца."}, {"id": "sewer-ins-shell-110-50", "name": "Теплоизоляция для труб Knauf Therm Скорлупа 110х50х1000 мм белая (1 шт.)", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/1068536/", "vendor": "Петрович", "sku": "1068536", "region": "Санкт-Петербург", "diameter": 110, "length": 1000, "price": 359, "priceCard": 349, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1068536 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Скорлупа ППС Knauf Therm, стенка 50 мм, под трубу 110 — для наружного участка при мелком заложении."}, {"id": "sewer-ins-pe-110-9", "name": "Теплоизоляция для труб Стенофлекс ПЭ 110х9х2000 мм серая", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/678807/", "vendor": "Петрович", "sku": "678807", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 235, "priceCard": 228, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/678807 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Трубка вспененный ПЭ 9 мм — шумо- и конденсатоизоляция внутри, для утепления в грунте мало."}, {"id": "sewer-ins-pe-114-13", "name": "Теплоизоляция для труб Стенофлекс ПЭ 114х13х2000 мм серая", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/108122/", "vendor": "Петрович", "sku": "108122", "region": "Санкт-Петербург", "diameter": 110, "length": 2000, "price": 325, "priceCard": 315, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/108122 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Трубка вспененный ПЭ 13 мм."}, {"id": "sewer-heat-cable-160w-10m", "name": "Кабель греющий саморегулирующийся для труб Teploluxe Freezstop outside 160 Вт 10 м для обогрева трубопровода (100037057000)", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/1173970/", "vendor": "Петрович", "sku": "1173970", "region": "Санкт-Петербург", "length": 10000, "price": 7559, "priceCard": 7559, "unit": "шт", "availability": "Доставим завтра", "source": "api.petrovich.ru/catalog/v5/products/1173970 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Греющий кабель саморегулирующийся наружный, 16 Вт/м, готовый комплект 10 м."}, {"id": "sewer-heat-cable-170w-10m", "name": "Кабель греющий саморегулирующийся для труб EKF StopFrost 170 Вт 10 м для обогрева трубопровода (SF-17-10)", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/1056130/", "vendor": "Петрович", "sku": "1056130", "region": "Санкт-Петербург", "length": 10000, "price": 7500, "priceCard": 7500, "unit": "шт", "availability": "Доставим 8 октября", "source": "api.petrovich.ru/catalog/v5/products/1056130 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "sewer-heat-cable-17w-m", "name": "Кабель греющий саморегулирующийся для кровли и труб Камкабель TENon Medium 17 Вт/м (1Х1П74Ж0110000250М)", "kind": "sewer", "subtype": "insulation", "url": "https://petrovich.ru/product/1220078/", "vendor": "Петрович", "sku": "1220078", "region": "Санкт-Петербург", "price": 245, "priceCard": 245, "unit": "пог. м", "availability": "Доставим завтра", "source": "api.petrovich.ru/catalog/v5/products/1220078 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Кабель саморегулирующийся на отрез, 17 Вт/м; нужна концевая заделка и питающий комплект."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-classic-08-manufacturer", "name": "Станция очистки ТВЕРЬ Classic 0,8 (самотёчный отвод)", "url": "https://spb.septiki-tver.ru/avtonomnaya-kanalizatsiya-dlya-doma/tver-classic/tver-classic-085p/", "vendor": "ТД «Инженерное оборудование» (производитель, СПб)", "region": "Санкт-Петербург / Ленобласть", "price": 169800, "priceInstalled": null, "capacity": 0.8, "users": 5, "salvo": 240, "length": 2000, "width": 1100, "height": 1670, "inletDepth": 320, "power": "компрессор Secoh SLL-40, 40/41 Вт (≈0,98 кВт·ч/сут при круглосуточной работе)", "forcedOutlet": false, "source": "Карточка товара: 169 800 р., до 5 чел., 0,8 м³/сут, залп 240 л, залегание трубы 0,32 м (допускается 0,32–1,62 м), габариты 2,0×1,1×1,67 м, 132 кг, компрессор 41 Вт; паспорт ТВЕРЬ Classic 2026 (табл. 3): 2000×1100×1670, 40/41 Вт; монтажная схема 0,8П: лоток подводящего 0,32 м, отводящего 0,42 м, котлован 2,30×1,40×1,70 м, песок ≥4 м³", "note": "Бывшее название — Тверь-0,85П / 0,8П. Серии «Стандарт» у производителя нет: «стандартная комплектация» = самотёчный отвод, «стандартная горловина» = подводящая на 0,32 м (наращивание +0,1/+0,2 м). Монтаж под ключ по СПб и ЛО, цена монтажа на сайте не указана (по заявке/выезду); скидка 10 000 ₽ на монтаж при заказе с кессоном. Работает при отключении света (переливная схема)."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-classic-08n-manufacturer", "name": "Станция очистки ТВЕРЬ Classic 0,8Н (принудительный отвод)", "url": "https://spb.septiki-tver.ru/avtonomnaya-kanalizatsiya-dlya-doma/tver-classic/tver-classic-085pn/", "vendor": "ТД «Инженерное оборудование» (производитель, СПб)", "region": "Санкт-Петербург / Ленобласть", "price": 184300, "priceInstalled": null, "capacity": 0.8, "users": 5, "salvo": 240, "length": 2400, "width": 1100, "height": 1670, "inletDepth": 320, "power": "компрессор 40/41 Вт + дренажный насос Pedrollo TOP 2 (в комплект не входит, покупается отдельно)", "forcedOutlet": true, "source": "Карточка товара: 184 300 р., до 5 чел., 0,8 м³/сут, 2,4×1,1×1,67 м, 160 кг, залп 240 л, лоток подводящего от 0,32 м, компрессор 41 Вт; паспорт ТВЕРЬ Classic Н 2026: 0,8Н — 2400×1100×1670, 160 кг, насос — опция", "note": "Отдельный насосный отсек, отвод очищенной воды напорным патрубком 32 мм до 60 м — вариант для высоких грунтовых вод/скалы, когда самотёком сбросить некуда. Насос в цену не входит. Монтаж по СПб/ЛО по заявке."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-classic-08-septikspb", "name": "Септик Тверь Classic 0,8", "url": "https://www.septikspb.com/product/tver-klassik-08/", "vendor": "СептикСервис (septikspb.com)", "region": "Санкт-Петербург / Ленобласть", "price": 169800, "priceInstalled": 203400, "capacity": 0.8, "users": 5, "salvo": 210, "length": 2000, "width": 1100, "height": 1670, "inletDepth": null, "power": "60 Вт (по карточке дилера)", "forcedOutlet": false, "source": "Карточка: цена оборудования 169 800 р., «под ключ» с монтажом 203 400 р.; 800 л/сут, залп 210 л, 2000×1100×1670 мм, 130 кг; у дилера указано «2-4 чел.»", "note": "В монтаж под ключ: доставка с материалами, котлован (стандартные грунты), установка, до 2 м канализационной трубы и до 5 м кабеля, пусконаладка. ≈ +6,5 тыс. ₽ (оценка). Цифры залпа/людей у дилера расходятся с производителем (240 л, 5 чел.)."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-classic-08n-septikspb", "name": "Септик Тверь Classic 0,8Н (принудительный)", "url": "https://www.septikspb.com/product/tver-klassik-08-pn/", "vendor": "СептикСервис (septikspb.com)", "region": "Санкт-Петербург / Ленобласть", "price": 184300, "priceInstalled": 219000, "capacity": 0.8, "users": 5, "salvo": 210, "length": 2400, "width": 1100, "height": 1670, "inletDepth": null, "power": "60 Вт (по карточке дилера) + насос", "forcedOutlet": true, "source": "Карточка: цена оборудования 184 300 р., «под ключ» 219 000 р.; 800 л/сут, залп 210 л, 2400×1100×1670 мм, 150 кг", "note": "Там же есть Тверь Classic 0,8 КНС (встроенная насосная станция) — 188 300 / 223 000 р., 2400×1100×1670: https://www.septikspb.com/product/tver-klassik-08-np/ ."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": 1800, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-08-kolodcov", "name": "Септик ТВЕРЬ-0,8 (самотёчный)", "url": "https://www.kolodcov.ru/avtonomnie_kanalisacii/view/septik-tver/TVER-0-75/", "vendor": "Колодцов (kolodcov.ru)", "region": "Санкт-Петербург / Ленобласть", "price": 169800, "priceInstalled": 203400, "capacity": 0.85, "users": 5, "salvo": 225, "length": 2100, "width": 1100, "height": 1670, "inletDepth": 300, "power": "0,9 кВт·ч/сут (по карточке дилера)", "forcedOutlet": false, "source": "Карточка: цена септика 169 800 р., монтаж 33 600 р. (итог 203 400 — сумма, посчитана); 5 чел., 850 л/сут, залп 225 л, 2100×1100×1670 мм, рабочий объём 1,8 м³, подводящая 30 см, отводящая 40 см, 135 кг", "note": "подводящей траншеи с трубами, 2 п.м. отводящей. Прайс-лист дилера от 01.06.2026: https://www.kolodcov.ru/files/Prajs-list_TVER_01.06.2026.pdf"}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-tver-085p-septikcity", "name": "Септик Тверь 0,85П (старая маркировка)", "url": "https://spb.septikcity.ru/catalog/tver/tver-0-85p/", "vendor": "Септик Сити (spb.septikcity.ru)", "region": "Санкт-Петербург / Ленобласть", "price": 112500, "priceInstalled": 148500, "capacity": 0.85, "users": 5, "salvo": 225, "length": null, "width": null, "height": null, "inletDepth": 320, "power": "0,96 кВт·ч/сут", "forcedOutlet": false, "source": "Карточка: 112 500 руб/шт; монтаж: шеф 9 000, песок/суглинок/глина 36 000, плывун 39 000 (итог 148 500 = 112 500 + 36 000, посчитано); 0,85 м³/сут, залп 225 л, подводящая 320 мм, отводящая 420 мм, 0,96 кВт/сут", "note": "Цена заметно ниже прайса производителя (169 800) — вероятно, старая модель/устаревшая цена, подтверждать звонком. Доставка: свыше 100 км от КАД 6 300 ₽. Принудительная 0,85ПН — 125 000 руб + монтаж 38 000 (плывун 41 000), отводящая 550 мм: https://spb.septikcity.ru/catalog/tver/tver-0-85pn/"}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-astra-5-septikspb", "name": "Станция биоочистки Юнилос Астра 5", "url": "https://www.septikspb.com/product/unilos-astra-5/", "vendor": "СептикСервис (septikspb.com)", "region": "Санкт-Петербург / Ленобласть", "price": 155070, "priceInstalled": 200070, "capacity": 1, "users": 5, "salvo": 250, "length": 2360, "width": 1120, "height": 1030, "inletDepth": null, "power": "60 Вт (по карточке дилера)", "forcedOutlet": false, "source": "Карточка: цена оборудования 155 070 р. (без скидки 172 300), под ключ 200 070 р.; 1000 л/сут, залп 250 л, 2360×1120×1030 мм (высота, видимо, без горловины — у дилера так), 220 кг, 3-5 чел.", "note": "Для сравнения. Энергозависима (в отличие от Твери). Доставка 50 км бесплатно, далее за км."}, {"kind": "sewer", "subtype": "septic", "unit": "шт", "volume": null, "diameter": null, "checkedAt": "2026-09-30", "id": "sewer-septic-topas-5-lokadom", "name": "Станция биоочистки Топас 5", "url": "https://lokadom.ru/catalog/septiki/topas/topas_5/", "vendor": "Локадом (lokadom.ru)", "region": "Санкт-Петербург / Ленобласть", "price": 167040, "priceInstalled": 196040, "capacity": 1, "users": 5, "salvo": 220, "length": 1150, "width": 1170, "height": 2400, "inletDepth": 450, "power": "1,5 кВт·ч/сут", "forcedOutlet": false, "source": "Карточка: 167 040 руб (без скидки 185 600), под ключ с доставкой и монтажом 196 040; 1,0 м³/сут, залп 220 л, 1,5 кВт/сут, до 5 чел.; 1,15×1,17×2,40 м, 250 кг; врезка подводящей 450–850 мм; котлован 1800×1800×2500", "note": "Для сравнения. Топас 5 Пр — 182 340 руб, под ключ 211 340. Монтаж: скальный грунт — индивидуально."}, {"id": "water-pipe-16-PEX-inside", "name": "Труба PE-Xa Stout 16 х 2,2 мм из сшитого полиэтилена PN10 серая (SPX-0001-001622)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/601606/", "vendor": "Петрович", "sku": "601606", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "pipe", "price": 175, "priceCard": 175, "unit": "пог. м", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/601606 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами. Нарезка от метра."}, {"id": "water-pipe-in-16-PEX-stout-100m", "name": "Труба PE-Xa Stout 16 х 2,2 мм из сшитого полиэтилена PN10 серая (100 м) (SPX-0001-001622)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/500794/", "vendor": "Петрович", "sku": "500794", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "length": 100000, "group": "pipe", "price": 19000, "priceCard": 19000, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500794 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Бухта 100 м, 190 ₽/м."}, {"id": "water-pipe-in-16-PEX-rehau-100m", "name": "Труба PE-Xa Рехау Rautitan Flex 16х2,2 мм из сшитого полиэтилена PN10 (100 м) (11303703100)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/1023705/", "vendor": "Петрович", "sku": "1023705", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "length": 100000, "group": "pipe", "price": 18922, "priceCard": 18922, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1023705 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Rehau Rautitan Flex, бухта 100 м, 189 ₽/м; фитинги Rehau MX — отдельная система, со Stout не смешивать."}, {"id": "water-pipe-20-PEX-inside", "name": "Труба PE-Xa Stout 20 х 2,8 мм из сшитого полиэтилена PN10 серая (SPX-0001-002028)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/601607/", "vendor": "Петрович", "sku": "601607", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "pipe", "price": 262, "priceCard": 262, "unit": "пог. м", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/601607 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами. Магистраль до коллекторов и бойлера."}, {"id": "water-pipe-in-20-PEX-stout-100m", "name": "Труба PE-Xa Stout 20 х 2,8 мм из сшитого полиэтилена PN10 серая (100 м) (SPX-0001-002028)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/500795/", "vendor": "Петрович", "sku": "500795", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "length": 100000, "group": "pipe", "price": 28300, "priceCard": 28300, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500795 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Бухта 100 м, 283 ₽/м."}, {"id": "water-pipe-in-20-PEX-rehau", "name": "Труба PE-Xa Rehau Rautitan Flex 20х2,8 мм из сшитого полиэтилена PN10 (11303803100)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/1024094/", "vendor": "Петрович", "sku": "1024094", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "pipe", "price": 283, "priceCard": 283, "unit": "пог. м", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1024094 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Rehau Rautitan Flex, нарезка от метра."}, {"id": "water-pipe-32-PE-outside", "name": "Труба ПНД ПЭ-100 для систем водоснабжения КМ Эксперт d32 SDR11 синяя (100 м)", "kind": "water", "subtype": "pipe", "url": "https://petrovich.ru/product/1229054/", "vendor": "Петрович", "sku": "1229054", "region": "Санкт-Петербург", "diameter": 32, "material": "PE", "length": 100000, "group": "pipe", "price": 7723, "priceCard": 7723, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1229054 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Ввод от скважины: ПЭ-100 SDR11 (PN16), бухта 100 м (77 ₽/м)."}, {"id": "water-elbow-16", "name": "Угол Stout 16 х 16 мм латунный (SFA-0007-000016)", "kind": "water", "subtype": "elbow", "url": "https://petrovich.ru/product/500814/", "vendor": "Петрович", "sku": "500814", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 481, "priceCard": 481, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500814 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-elbow-20", "name": "Угол Stout 20 х 20 мм латунный (SFA-0007-000020)", "kind": "water", "subtype": "elbow", "url": "https://petrovich.ru/product/500815/", "vendor": "Петрович", "sku": "500815", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 653, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500815 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-tee-16", "name": "Тройник Stout 16 х 16 х 16 мм латунный (SFA-0013-000016)", "kind": "water", "subtype": "tee", "url": "https://petrovich.ru/product/500809/", "vendor": "Петрович", "sku": "500809", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 605, "priceCard": 605, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500809 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-tee-20", "name": "Тройник Stout 20 х 20 х 20 мм латунный (SFA-0013-000020)", "kind": "water", "subtype": "tee", "url": "https://petrovich.ru/product/500810/", "vendor": "Петрович", "sku": "500810", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 803, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500810 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-tee-20x16x20", "name": "Тройник Stout 20 х 16 х 20 мм латунный (SFA-0014-201620)", "kind": "water", "subtype": "tee", "url": "https://petrovich.ru/product/500812/", "vendor": "Петрович", "sku": "500812", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 720, "priceCard": 720, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500812 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Проходной тройник магистрали 20 с отводом 16 (тройниковая схема)."}, {"id": "water-socket-16", "name": "Водорозетка Stout 16 мм х 1/2 ВР(г) латунная (SFA-0009-001612)", "kind": "water", "subtype": "socket", "url": "https://petrovich.ru/product/500822/", "vendor": "Петрович", "sku": "500822", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 699, "priceCard": 699, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500822 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-socket-20", "name": "Водорозетка Stout 20 мм х 1/2 ВР(г) латунная (SFA-0009-002012)", "kind": "water", "subtype": "socket", "url": "https://petrovich.ru/product/500823/", "vendor": "Петрович", "sku": "500823", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 821, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500823 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-reducer-20x16", "name": "Соединитель прямой Stout 20 х 16 мм латунный (SFA-0004-002016)", "kind": "water", "subtype": "reducer", "url": "https://petrovich.ru/product/500800/", "vendor": "Петрович", "sku": "500800", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 337, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500800 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Аксиальная система Stout (сдвижная гильза, PE-Xa) — одна система с трубой и фитингами."}, {"id": "water-collector-out-16", "name": "Соединитель прямой Stout 16 мм х 1/2 ВР(г) с накидной гайкой латунный (SFA-0019-001612)", "kind": "water", "subtype": "collector-out", "url": "https://petrovich.ru/product/500824/", "vendor": "Петрович", "sku": "500824", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 464, "priceCard": 464, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500824 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Соединитель 16 × 1/2 ВР с накидной гайкой — на выход коллектора 1/2 НР."}, {"id": "water-collector-out-20", "name": "Соединитель прямой Stout 20 мм х 1/2 ВР(г) с накидной гайкой латунный (SFA-0019-002012)", "kind": "water", "subtype": "collector-out", "url": "https://petrovich.ru/product/500825/", "vendor": "Петрович", "sku": "500825", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 573, "priceCard": 573, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500825 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Соединитель 20 × 1/2 ВР с накидной гайкой — на выход коллектора 1/2 НР."}, {"id": "water-adapter-16", "name": "Соединитель прямой Stout 16 мм х 1/2 НР(ш) латунный (SFA-0001-001612)", "kind": "water", "subtype": "adapter", "url": "https://petrovich.ru/product/500801/", "vendor": "Петрович", "sku": "500801", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 324, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500801 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Переход на наружную резьбу 1/2."}, {"id": "water-adapter-20", "name": "Соединитель прямой Stout 20 мм х 1/2 НР(ш) латунный (SFA-0001-002012)", "kind": "water", "subtype": "adapter", "url": "https://petrovich.ru/product/500802/", "vendor": "Петрович", "sku": "500802", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 391, "priceCard": 391, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500802 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Переход на наружную резьбу 1/2."}, {"id": "water-press-sleeve-16", "name": "Гильза монтажная Stout 16 мм латунная (SFA-0020-000016)", "kind": "water", "subtype": "press-sleeve", "url": "https://petrovich.ru/product/500796/", "vendor": "Петрович", "sku": "500796", "region": "Санкт-Петербург", "diameter": 16, "material": "PEX", "group": "fitting", "price": 122, "priceCard": 122, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500796 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Монтажная гильза, по одной на каждый конец трубы у фитинга."}, {"id": "water-press-sleeve-20", "name": "Гильза монтажная Stout 20 мм латунная (SFA-0020-000020)", "kind": "water", "subtype": "press-sleeve", "url": "https://petrovich.ru/product/500797/", "vendor": "Петрович", "sku": "500797", "region": "Санкт-Петербург", "diameter": 20, "material": "PEX", "group": "fitting", "price": 125, "priceCard": 125, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/500797 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Монтажная гильза, по одной на каждый конец трубы у фитинга."}, {"id": "water-pe-adapter-32-1m", "name": "Муфта ПНД Valfex компрессионная переходная 32х1 НР(ш)", "kind": "water", "subtype": "adapter", "url": "https://petrovich.ru/product/1070309/", "vendor": "Петрович", "sku": "1070309", "region": "Санкт-Петербург", "diameter": 32, "material": "PE", "group": "fitting", "price": 41, "priceCard": 40, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1070309 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Компрессионная муфта ПНД 32 × 1 НР — ввод на насосную группу."}, {"id": "water-pe-adapter-32-1f", "name": "Муфта ПНД Valfex компрессионная переходная 32х1 ВР(г)", "kind": "water", "subtype": "adapter", "url": "https://petrovich.ru/product/1070317/", "vendor": "Петрович", "sku": "1070317", "region": "Санкт-Петербург", "diameter": 32, "material": "PE", "group": "fitting", "price": 55, "priceCard": 53, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1070317 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Компрессионная муфта ПНД 32 × 1 ВР."}, {"id": "water-pe-tee-32", "name": "Тройник ПНД Valfex компрессионный 32х32х32 мм", "kind": "water", "subtype": "tee", "url": "https://petrovich.ru/product/1070305/", "vendor": "Петрович", "sku": "1070305", "region": "Санкт-Петербург", "diameter": 32, "material": "PE", "group": "fitting", "price": 118, "priceCard": 118, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1070305 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Компрессионный тройник ПНД 32."}, {"id": "water-collector-2", "name": "Коллектор Stout 3/4 ВР(г) х 2 выхода 1/2 НР(ш) х 3/4 НР(ш) с шаровыми кранами (SMB 6211 341202)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/635145/", "vendor": "Петрович", "sku": "635145", "region": "Санкт-Петербург", "outlets": 2, "group": "collector", "price": 1930, "priceCard": 1930, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/635145 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Гребёнка 3/4 с шаровыми кранами, 2 выхода 1/2 НР."}, {"id": "water-collector-3", "name": "Коллектор Stout 3/4 ВР(г) х 3 выхода 1/2 НР(ш) х 3/4 НР(ш) с шаровыми кранами (SMB 6211 341203)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/635146/", "vendor": "Петрович", "sku": "635146", "region": "Санкт-Петербург", "outlets": 3, "group": "collector", "price": 2691, "priceCard": 2691, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/635146 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Гребёнка 3/4 с шаровыми кранами, 3 выхода 1/2 НР."}, {"id": "water-collector-4", "name": "Коллектор Stout 3/4 ВР(г) х 4 выхода 1/2 НР(ш) ЕК х 3/4 НР(ш) с шаровыми кранами (SMB 6211 341204)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/635147/", "vendor": "Петрович", "sku": "635147", "region": "Санкт-Петербург", "outlets": 4, "group": "collector", "price": 3649, "priceCard": 3649, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/635147 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Гребёнка 3/4 с шаровыми кранами, 4 выхода 1/2 НР (ЕК). По одной на холодную и горячую."}, {"id": "water-collector-4-valtec", "name": "Коллектор Valtec 3/4 ВР(г) х 4 выхода 1/2 НР(ш) х 3/4 НР(ш) регулируемый (VTc.560.N.0504)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/143787/", "vendor": "Петрович", "sku": "143787", "region": "Санкт-Петербург", "outlets": 4, "group": "collector", "price": 2597, "priceCard": 2597, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/143787 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-collector-5", "name": "Коллектор на 5 выходов: Stout 3 + 2 выхода с шаровыми кранами (635146 + 635145)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/635146/", "vendor": "Петрович", "region": "Санкт-Петербург", "outlets": 5, "group": "collector", "price": 4621, "unit": "компл", "source": "https://petrovich.ru/product/635146/", "checkedAt": "2026-09-30", "note": "Stout с кранами на 5–6 выходов в Петровиче нет; гребёнки свинчиваются между собой (3/4 ВР × 3/4 НР)."}, {"id": "water-collector-6", "name": "Коллектор на 6 выходов: Stout 3 + 3 выхода с шаровыми кранами (635146 × 2)", "kind": "water", "subtype": "collector", "url": "https://petrovich.ru/product/635146/", "vendor": "Петрович", "region": "Санкт-Петербург", "outlets": 6, "group": "collector", "price": 5382, "unit": "компл", "source": "https://petrovich.ru/product/635146/", "checkedAt": "2026-09-30", "note": "Две гребёнки Stout по 3 выхода, свинчиваются."}, {"id": "water-sleeve-16", "name": "Гильза через стену: труба канализационная Valfex Ø50 × 500 мм (983650)", "kind": "water", "subtype": "sleeve", "url": "https://petrovich.ru/product/983650/", "vendor": "Петрович", "region": "Санкт-Петербург", "diameter": 16, "group": "sleeve", "price": 68, "unit": "шт", "source": "https://petrovich.ru/product/983650/", "checkedAt": "2026-09-30", "note": "Отрезок ПП Ø50 как футляр для PEX 16/20 в изоляции через стены и перекрытия."}, {"id": "water-sleeve-20", "name": "Гильза через стену: труба канализационная Valfex Ø50 × 500 мм (983650)", "kind": "water", "subtype": "sleeve", "url": "https://petrovich.ru/product/983650/", "vendor": "Петрович", "region": "Санкт-Петербург", "diameter": 20, "group": "sleeve", "price": 68, "unit": "шт", "source": "https://petrovich.ru/product/983650/", "checkedAt": "2026-09-30", "note": "Отрезок ПП Ø50 как футляр."}, {"id": "water-sleeve-32", "name": "Гильза через фундамент: труба канализационная Valfex Ø50 × 500 мм (983650)", "kind": "water", "subtype": "sleeve", "url": "https://petrovich.ru/product/983650/", "vendor": "Петрович", "region": "Санкт-Петербург", "diameter": 32, "group": "sleeve", "price": 68, "unit": "шт", "source": "https://petrovich.ru/product/983650/", "checkedAt": "2026-09-30", "note": "Для ввода ПНД 32 с греющим кабелем и изоляцией лучше футляр Ø110 (наружная канализационная из sewer.json); зазор 0,2 м или сальник по СП 30 п. 8.8."}, {"id": "water-insul-16", "name": "Теплоизоляция для труб Стенофлекс ПЭ 18х6х1000 мм синяя (упаковка 10 шт.)", "kind": "water", "subtype": "insulation", "url": "https://petrovich.ru/product/692310/", "vendor": "Петрович", "sku": "692310", "region": "Санкт-Петербург", "diameter": 16, "length": 10000, "group": "insulation", "price": 235, "priceCard": 229, "unit": "упак", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/692310 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Стенофлекс ПЭ 18×6, упаковка 10 трубок по 1 м (10 м). Energoflex в Петровиче не продаётся — это аналог того же класса."}, {"id": "water-insul-20", "name": "Теплоизоляция для труб Стенофлекс ПЭ 22х6х1000 мм синяя (упаковка 10 шт.)", "kind": "water", "subtype": "insulation", "url": "https://petrovich.ru/product/692312/", "vendor": "Петрович", "sku": "692312", "region": "Санкт-Петербург", "diameter": 20, "length": 10000, "group": "insulation", "price": 279, "priceCard": 270, "unit": "упак", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/692312 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Стенофлекс ПЭ 22×6, упаковка 10 × 1 м."}, {"id": "water-insul-32", "name": "Трубка Energoflex Super 35/13-2 (вспененный ПЭ, 13 мм)", "kind": "water", "subtype": "insulation", "url": "https://masterwatt.ru/catalog/trubki/trubka-super-35-13-2-seryy-upakovka-108-m-st-art-e35-13/", "vendor": "Мастер-Ватт", "region": "Санкт-Петербург", "diameter": 32, "group": "insulation", "price": 99, "unit": "м", "source": "https://masterwatt.ru/catalog/trubki/trubka-super-35-13-2-seryy-upakovka-108-m-st-art-e35-13/", "checkedAt": "2026-09-30", "note": "Цена за метр, склад в Москве, мин. заказ 2 м. На вводе в грунте изоляция 13 мм — только в паре с греющим кабелем; в СПб Energoflex есть в «Сан Саныч» и у дистрибьютора energoflex-ot.ru."}, {"id": "water-insul-32-stenoflex", "name": "Теплоизоляция для труб Стенофлекс ПЭ 34х13х2000 мм серая", "kind": "water", "subtype": "insulation", "url": "https://petrovich.ru/product/678810/", "vendor": "Петрович", "sku": "678810", "region": "Санкт-Петербург", "diameter": 32, "length": 2000, "group": "insulation", "price": 100, "priceCard": 97, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/678810 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-heat-cable", "name": "Кабель греющий Spyheat SHFD-13-250, 19 м, 250 Вт, со встроенным термостатом (144003)", "kind": "water", "subtype": "heat-cable", "url": "https://petrovich.ru/product/144003/", "vendor": "Петрович", "region": "Санкт-Петербург", "group": "heat-cable", "price": 171, "unit": "м", "source": "https://petrovich.ru/product/144003/", "checkedAt": "2026-09-30", "note": "Цена за метр из набора 19 м за 3242 ₽; наружный монтаж вдоль ввода под изоляцию."}, {"id": "water-heat-cable-inpipe-20m", "name": "Кабель греющий для труб с питьевой водой SelfTec SelfTec DW 200 Вт 20 м с муфтой для ввода в трубу (SelfTec 10/20)", "kind": "water", "subtype": "heat-cable-inpipe", "url": "https://petrovich.ru/product/785592/", "vendor": "Петрович", "sku": "785592", "region": "Санкт-Петербург", "group": "heat-cable", "price": 30126, "priceCard": 30126, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/785592 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Пищевой кабель SelfTec DW внутрь трубы ПНД 32, 20 м, с сальником ввода — дороже, но не требует разрытия при замене."}, {"id": "water-heat-cable-gland", "name": "Комплект для ввода греющего кабеля в трубу 1/2\" 3/4\" 1\" (EFPLV1)", "kind": "water", "subtype": "heat-cable-inpipe", "url": "https://petrovich.ru/product/134469/", "vendor": "Петрович", "sku": "134469", "region": "Санкт-Петербург", "group": "heat-cable", "price": 1625, "priceCard": 1625, "unit": "упак", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/134469 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Сальник ввода кабеля в трубу 1/2–1\"."}, {"id": "water-pump-borehole-vodomet-55-75", "name": "Насос скважинный Джилекс ВОДОМЁТ ПРОФ 55/75 для чистой воды 55 л/мин", "kind": "water", "subtype": "pump", "url": "https://petrovich.ru/product/617085/", "vendor": "Петрович", "sku": "617085", "region": "Санкт-Петербург", "group": "pump", "price": 20660, "priceCard": 20660, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/617085 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Погружной скважинный 4\", 55 л/мин, напор до 75 м: для скважины в граните 60–90 м с динамическим уровнем до ~30–40 м. С гидроаккумулятором и реле."}, {"id": "water-pump-borehole-belamos-tf3-60", "name": "Насос скважинный Belamos TF3-60 для чистой воды 45 л/мин", "kind": "water", "subtype": "pump", "url": "https://petrovich.ru/product/156375/", "vendor": "Петрович", "sku": "156375", "region": "Санкт-Петербург", "group": "pump", "price": 12851, "priceCard": 12477, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/156375 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Погружной 3\", 45 л/мин, дешевле; проверить напор под фактический динамический уровень."}, {"id": "water-pump-station-jumbo-70-50", "name": "Насосная станция Джилекс ДЖАМБО 70/50 П-24 70 л/мин (3016)", "kind": "water", "subtype": "pump", "url": "https://petrovich.ru/product/617088/", "vendor": "Петрович", "sku": "617088", "region": "Санкт-Петербург", "group": "pump", "price": 19990, "priceCard": 19990, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/617088 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Поверхностная станция с баком 24 л — только для колодца или скважины на песок с уровнем воды до 8 м, для гранитной скважины не подходит."}, {"id": "water-accumulator-50", "name": "Гидроаккумулятор Belamos 50 VT 50 л", "kind": "water", "subtype": "accumulator", "url": "https://petrovich.ru/product/156365/", "vendor": "Петрович", "sku": "156365", "region": "Санкт-Петербург", "volume": 50, "group": "pump", "price": 5633, "priceCard": 5469, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/156365 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-accumulator-100", "name": "Гидроаккумулятор Belamos 100 VT 100 л", "kind": "water", "subtype": "accumulator", "url": "https://petrovich.ru/product/156369/", "vendor": "Петрович", "sku": "156369", "region": "Санкт-Петербург", "volume": 100, "group": "pump", "price": 10464, "priceCard": 10159, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/156369 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-accumulator-80-flamco", "name": "Гидроаккумулятор Flamco Airfix R 80/4,0 80 л (FL 24809 RU)", "kind": "water", "subtype": "accumulator", "url": "https://petrovich.ru/product/617195/", "vendor": "Петрович", "sku": "617195", "region": "Санкт-Петербург", "volume": 80, "group": "pump", "price": 18054, "priceCard": 18054, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/617195 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Flamco Airfix R 80 л, премиум."}, {"id": "water-pressure-kit", "name": "Комплект автоматики для гидроаккумуляторов Джилекс (9039)", "kind": "water", "subtype": "pressure-switch", "url": "https://petrovich.ru/product/1012310/", "vendor": "Петрович", "sku": "1012310", "region": "Санкт-Петербург", "group": "pump", "price": 2270, "priceCard": 2270, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1012310 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Реле давления, манометр, пятиходовой штуцер, кабель — комплект автоматики."}, {"id": "water-filter-strainer-34", "name": "Фильтр косой Valtec 3/4 ВР(г) х 3/4 ВР(г) (VT.192.N.05)", "kind": "water", "subtype": "filter", "url": "https://petrovich.ru/product/143461/", "vendor": "Петрович", "sku": "143461", "region": "Санкт-Петербург", "group": "filter", "price": 711, "priceCard": 711, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/143461 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Механический сетчатый фильтр грубой очистки на вводе."}, {"id": "water-filter-housing-34", "name": "Корпус фильтра Гейзер Премьер для холодной и горячей воды нержавеющая сталь 10SL 3/4 НР(ш) х 3/4 НР(ш) серый", "kind": "water", "subtype": "filter", "url": "https://petrovich.ru/product/1046709/", "vendor": "Петрович", "sku": "1046709", "region": "Санкт-Петербург", "group": "filter", "price": 9940, "priceCard": 9940, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1046709 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Корпус 10SL 3/4, нерж.; ставится после сетчатого."}, {"id": "water-filter-cartridge-fe", "name": "Картридж фильтра Гейзер Fe Каталон Дуплекс для холодной и горячей воды предфильтр нитяной 5 мкм 10SL", "kind": "water", "subtype": "filter", "url": "https://petrovich.ru/product/1046714/", "vendor": "Петрович", "sku": "1046714", "region": "Санкт-Петербург", "group": "filter", "price": 626, "priceCard": 608, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1046714 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Картридж обезжелезивания 5 мкм 10SL — только для малого железа, для гранитной скважины нужна колонна."}, {"id": "water-filter-deferrization-1054", "name": "Фильтр сорбционно-обезжелезивающий CF-1054 + клапан BNT2650T", "kind": "water", "subtype": "filter", "url": "https://promvodsnab.ru/filtry-dlya-vody/sistemy-ochistki-zasypnye/osvetlitelnyj/filtr-cf-1054bnt2650t/", "vendor": "Промводснаб (СПб)", "region": "Санкт-Петербург", "group": "filter", "price": 57549, "unit": "шт", "source": "https://promvodsnab.ru/filtry-dlya-vody/sistemy-ochistki-zasypnye/osvetlitelnyj/filtr-cf-1054bnt2650t/", "checkedAt": "2026-09-30", "note": "Колонна 10×54 с автоматикой: железо, марганец, сероводород."}, {"id": "water-filter-softener-1054", "name": "Умягчитель воды 1054 RX (колонна 10×54, Runxin)", "kind": "water", "subtype": "filter", "url": "https://promvodsnab.ru/filtry-dlya-vody/sistemy-ochistki-zasypnye/umyagchitel/sistema-umyagcheniya-pvs-so-csw-tm-1054-rx/", "vendor": "Промводснаб (СПб)", "region": "Санкт-Петербург", "group": "filter", "price": 33777, "unit": "шт", "source": "https://promvodsnab.ru/filtry-dlya-vody/sistemy-ochistki-zasypnye/umyagchitel/sistema-umyagcheniya-pvs-so-csw-tm-1054-rx/", "checkedAt": "2026-09-30", "note": "Ставится после обезжелезивателя при жёсткости выше ~4 °Ж; расход — таблетированная соль."}, {"id": "water-filter-salt-25", "name": "Соль Аквафор Экстра таблетированная 25 кг", "kind": "water", "subtype": "filter", "url": "https://petrovich.ru/product/1129710/", "vendor": "Петрович", "sku": "1129710", "region": "Санкт-Петербург", "group": "filter", "price": 911, "priceCard": 911, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1129710 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-boiler-electric-80", "name": "Водонагреватель накопительный Thermex Giro электрический 80 л 1,5 кВт универсальный", "kind": "water", "subtype": "boiler", "url": "https://petrovich.ru/product/604503/", "vendor": "Петрович", "sku": "604503", "region": "Санкт-Петербург", "volume": 80, "group": "boiler", "price": 9169, "priceCard": 9169, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/604503 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-boiler-electric-100", "name": "Водонагреватель накопительный Thermex Giro электрический 100 л 1,5 кВт универсальный", "kind": "water", "subtype": "boiler", "url": "https://petrovich.ru/product/604501/", "vendor": "Петрович", "sku": "604501", "region": "Санкт-Петербург", "volume": 100, "group": "boiler", "price": 11784, "priceCard": 11784, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/604501 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-boiler-electric-100-solo", "name": "Водонагреватель накопительный Thermex Solo V электрический 100 л 2 кВт вертикальный", "kind": "water", "subtype": "boiler", "url": "https://petrovich.ru/product/616629/", "vendor": "Петрович", "sku": "616629", "region": "Санкт-Петербург", "volume": 100, "group": "boiler", "price": 18790, "priceCard": 18790, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/616629 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Thermex Solo 100 л, 2 кВт, эмаль."}, {"id": "water-boiler-indirect-100", "name": "Бойлер косвенного нагрева Drazice OKC 100 NTR (100 л, настенный)", "kind": "water", "subtype": "boiler", "url": "https://www.teplograd.ru/catalog/serie/drazice_okc/drazice_okc_100_ntr", "vendor": "ТеплоГрад (СПб)", "region": "Санкт-Петербург", "volume": 100, "group": "boiler", "price": 50490, "unit": "шт", "source": "https://www.teplograd.ru/catalog/serie/drazice_okc/drazice_okc_100_ntr", "checkedAt": "2026-09-30", "note": "Косвенный нагрев от котла в котельной; в Петровиче бойлеров косвенного нагрева нет. Stout 100 л — около 62–63 тыс. ₽ (stout.ru)."}, {"id": "water-valve-12", "name": "Кран шаровой латунный Valtec Base-ГОСТ 1/2 ВР(г) х 1/2 НР(ш) полнопроходной бабочка прямой (VT.218S.N.04)", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/1230413/", "vendor": "Петрович", "sku": "1230413", "region": "Санкт-Петербург", "group": "valve", "price": 554, "priceCard": 554, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1230413 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Шаровой кран 1/2 полнопроходной."}, {"id": "water-valve-34", "name": "Кран шаровой латунный Valtec 3/4 ВР(г) х 3/4 НР(ш) бабочка с полусгоном прямой (VT.127.N.05)", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/1100483/", "vendor": "Петрович", "sku": "1100483", "region": "Санкт-Петербург", "group": "valve", "price": 596, "priceCard": 596, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1100483 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Шаровой кран 3/4 с полусгоном — на вводе и перед бойлером."}, {"id": "water-valve-appliance", "name": "Кран шаровой латунный Valtec 1/2 НР(ш) х 1/2 НР(ш) к бытовой технике мини угловой (VT.392.N.04)", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/143519/", "vendor": "Петрович", "sku": "143519", "region": "Санкт-Петербург", "group": "valve", "price": 555, "priceCard": 555, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/143519 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Кран к бытовой технике (стиральная машина, посудомойка)."}, {"id": "water-check-valve-34", "name": "Клапан обратный Valtec 3/4 ВР(г) х 3/4 ВР(г) (VT.161.N.05)", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/143458/", "vendor": "Петрович", "sku": "143458", "region": "Санкт-Петербург", "group": "valve", "price": 581, "priceCard": 581, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/143458 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Обратный клапан 3/4."}, {"id": "water-check-valve-1-borehole", "name": "Клапан обратный Джилекс 1\" латунное седло (9009)", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/1012302/", "vendor": "Петрович", "sku": "1012302", "region": "Санкт-Петербург", "group": "valve", "price": 1310, "priceCard": 1310, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/1012302 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Обратный клапан 1\" с латунным седлом над погружным насосом."}, {"id": "water-valve-pe-32", "name": "Кран шаровой ПНД компрессионный 32х32 мм", "kind": "water", "subtype": "valve", "url": "https://petrovich.ru/product/156288/", "vendor": "Петрович", "sku": "156288", "region": "Санкт-Петербург", "diameter": 32, "material": "PE", "group": "valve", "price": 231, "priceCard": 224, "unit": "шт", "availability": "Доступно сегодня", "source": "api.petrovich.ru/catalog/v5/products/156288 (city_code=spb)", "checkedAt": "2026-09-30"}, {"id": "water-head", "name": "Обустройство скважины под ключ: обсадка, насос, кессон или адаптер, оголовок", "kind": "water", "subtype": "well", "url": "https://drillspb.ru/", "vendor": "drillspb.ru", "region": "Санкт-Петербург", "group": "well", "price": 69900, "unit": "компл", "source": "https://drillspb.ru/", "checkedAt": "2026-09-30", "note": "Пакет drillspb; у lenburenie адаптер от 80 000, кессон от 180 000; у gmontage от 45 000."}, {"id": "heat-pipe-stout-pexa-16x2-200", "name": "Труба для теплого пола PE-Xa Stout 16х2 мм из сшитого полиэтилена PN10 (200 м) (SPX-0002-001620)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/500793/", "vendor": "Петрович", "sku": "500793", "region": "Санкт-Петербург", "price": 32800, "priceCard": 32800, "unit": "шт", "availability": "Доступно сегодня", "material": "PE-Xa", "diameter": 16, "wall": 2, "coil": 200, "pricePer": "164.0 ₽/м (200 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/500793 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout SPX-0002-001620, PE-Xa, PN10."}, {"id": "heat-pipe-stout-pexa-16x2-500", "name": "Труба для теплого пола PE-Xa Stout 16х2 мм из сшитого полиэтилена PN10 (500 м) (SPX-0002-501620)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/635310/", "vendor": "Петрович", "sku": "635310", "region": "Санкт-Петербург", "price": 82000, "priceCard": 82000, "unit": "шт", "availability": "Доступно сегодня", "material": "PE-Xa", "diameter": 16, "wall": 2, "coil": 500, "pricePer": "164.0 ₽/м (500 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/635310 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout SPX-0002-501620, PE-Xa, PN10. Бухта 500 м выгоднее двух по 200 м на ~35%."}, {"id": "heat-pipe-valtec-pex-evoh-16x2-200", "name": "Труба для теплого пола PE-X Valtec 16х2 мм из сшитого полиэтилена с антидиффузионным слоем EVOH (200 м) красная (VP1620.3.200)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/143181/", "vendor": "Петрович", "sku": "143181", "region": "Санкт-Петербург", "price": 16600, "priceCard": 16600, "unit": "шт", "availability": "Доступно сегодня", "material": "PE-X (EVOH)", "diameter": 16, "wall": 2, "coil": 200, "pricePer": "83.0 ₽/м (200 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/143181 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec VP1620.3.200, PE-X с антидиффузионным слоем EVOH, красная. Бухты 500 м Valtec в Петровиче нет."}, {"id": "heat-pipe-valtec-pert-16x2-200", "name": "Труба для теплого пола PERT Valtec 16х2 мм из термостойкого полиэтилена (200 м) белая (VR1620.200C)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/1086238/", "vendor": "Петрович", "sku": "1086238", "region": "Санкт-Петербург", "price": 8070, "priceCard": 8070, "unit": "шт", "availability": "Доступно сегодня", "material": "PE-RT", "diameter": 16, "wall": 2, "coil": 200, "pricePer": "40.4 ₽/м (200 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/1086238 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec VR1620.200C, PE-RT белая. Самая дешёвая бухта 200 м из брендовых; кислородного барьера в названии нет — проверить перед покупкой."}, {"id": "heat-pipe-rehau-therm-17x2-500", "name": "Труба для теплого пола Рехау Therm 17х2 мм полиэтиленовая (500 м) (11361403500)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/1024329/", "vendor": "Петрович", "sku": "1024329", "region": "Санкт-Петербург", "price": 82095, "priceCard": 82095, "unit": "шт", "availability": "Доступно сегодня", "material": "PE-Xa (Rehau Therm)", "diameter": 17, "wall": 2, "coil": 500, "pricePer": "164.2 ₽/м (500 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/1024329 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Rehau Therm 17×2 (11361403500) — у этой линейки Rehau типоразмер 17×2 вместо 16×2, евроконусы нужны под 17×2. 16×2 Rehau в бухтах 200/500 м в Петровиче нет. Uponor в Петровиче нет."}, {"id": "heat-pipe-stm-pexb-16x2-500", "name": "Труба для теплого пола PEX-b СТМ 16x2 мм из сшитого полиэтилена с антидиффузионным слоем EVOH (500 м) красная (CPEX16205-500)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/1082946/", "vendor": "Петрович", "sku": "1082946", "region": "Санкт-Петербург", "price": 35990, "priceCard": 35990, "unit": "шт", "availability": "Доставим 8 октября", "material": "PE-Xb (EVOH)", "diameter": 16, "wall": 2, "coil": 500, "pricePer": "72.0 ₽/м (500 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/1082946 (city_code=spb)", "checkedAt": "2026-09-30", "note": "СТМ CPEX16205-500, бюджетный вариант."}, {"id": "heat-pipe-stm-pert-16x2-500", "name": "Труба для теплого пола PERT СТМ 16х2 мм из термостойкого полиэтилена (500 м) серая (CPER16025-500)", "kind": "heating", "subtype": "pipe", "url": "https://petrovich.ru/product/1083965/", "vendor": "Петрович", "sku": "1083965", "region": "Санкт-Петербург", "price": 23297, "priceCard": 23297, "unit": "шт", "availability": "Доставим 8 октября", "material": "PE-RT", "diameter": 16, "wall": 2, "coil": 500, "pricePer": "46.6 ₽/м (500 м в бухте)", "source": "api.petrovich.ru/catalog/v5/products/1083965 (city_code=spb)", "checkedAt": "2026-09-30", "note": "СТМ CPER16025-500, самая дешёвая бухта 500 м."}, {"id": "heat-collector-stout-6", "name": "Коллекторная группа с расходомерами нержавеющая сталь Stout 1 ВР(г) х 6 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/602630/", "vendor": "Петрович", "sku": "602630", "region": "Санкт-Петербург", "price": 23703, "priceCard": 23703, "unit": "шт", "availability": "Доступно сегодня", "outlets": 6, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/602630 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout, нержавейка, расходомеры на подаче, термостатические вентили на обратке, воздухоотводчики и сливы."}, {"id": "heat-collector-stout-8", "name": "Коллекторная группа с расходомерами нержавеющая сталь Stout 1 ВР(г) х 8 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/635199/", "vendor": "Петрович", "sku": "635199", "region": "Санкт-Петербург", "price": 24650, "priceCard": 24650, "unit": "шт", "availability": "Доступно сегодня", "outlets": 8, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/635199 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout, нержавейка, расходомеры, воздухоотводчики и сливы."}, {"id": "heat-collector-stout-10", "name": "Коллекторная группа с расходомерами нержавеющая сталь Stout 1 ВР(г) х 10 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/635201/", "vendor": "Петрович", "sku": "635201", "region": "Санкт-Петербург", "price": 29904, "priceCard": 29904, "unit": "шт", "availability": "Доступно сегодня", "outlets": 10, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/635201 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout, нержавейка, расходомеры, воздухоотводчики и сливы."}, {"id": "heat-collector-valtec-6", "name": "Коллекторная группа с расходомерами нержавеющая сталь Valtec 1 ВР(г) х 6 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/150401/", "vendor": "Петрович", "sku": "150401", "region": "Санкт-Петербург", "price": 39598, "priceCard": 39598, "unit": "шт", "availability": "Доступно сегодня", "outlets": 6, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/150401 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec, нержавейка. 10 выходов у Valtec в Петровиче не найдено."}, {"id": "heat-collector-valtec-8", "name": "Коллекторная группа с расходомерами нержавеющая сталь Valtec 1 ВР(г) х 8 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/150404/", "vendor": "Петрович", "sku": "150404", "region": "Санкт-Петербург", "price": 32770, "priceCard": 32770, "unit": "шт", "availability": "Доступно сегодня", "outlets": 8, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/150404 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec, нержавейка. Дешевле 6-выходного — цена Петровича такая на дату проверки."}, {"id": "heat-collector-rommer-8", "name": "Коллекторная группа с расходомерами Rommer 1 ВР(г) х 8 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/1081690/", "vendor": "Петрович", "sku": "1081690", "region": "Санкт-Петербург", "price": 13799, "priceCard": 13397, "unit": "шт", "availability": "Доступно сегодня", "outlets": 8, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/1081690 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Rommer (бюджетная линейка того же дистрибьютора, что Stout)."}, {"id": "heat-collector-sanext-6", "name": "Коллекторная группа с расходомерами Sanext 1 ВР(г) х 6 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/1173922/", "vendor": "Петрович", "sku": "1173922", "region": "Санкт-Петербург", "price": 9563.49, "priceCard": 9563.49, "unit": "шт", "availability": "Доставим 3 октября", "outlets": 6, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/1173922 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Sanext, бюджетный."}, {"id": "heat-collector-sanext-10", "name": "Коллекторная группа с расходомерами Sanext 1 ВР(г) х 10 выходов 3/4 НР(ш) ЕК х 1 ВР(г)", "kind": "heating", "subtype": "collector", "url": "https://petrovich.ru/product/1173918/", "vendor": "Петрович", "sku": "1173918", "region": "Санкт-Петербург", "price": 14376.36, "priceCard": 14376.36, "unit": "шт", "availability": "Доставим 3 октября", "outlets": 10, "inlet": "1\"", "outlet": "3/4\" ЕК", "source": "api.petrovich.ru/catalog/v5/products/1173918 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Sanext, бюджетный."}, {"id": "heat-mixing-valtec-combi", "name": "Насосно-смесительный узел Valtec Combi для теплого пола без насоса (VT.COMBI.0.180)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/141041/", "vendor": "Петрович", "sku": "141041", "region": "Санкт-Петербург", "price": 36623, "priceCard": 36623, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "pumpLength": 180, "source": "api.petrovich.ru/catalog/v5/products/141041 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec Combi VT.COMBI.0.180 — прямой аналог Combimix (Combimix VT.COMBI.S в Петровиче нет), термоголовка с погружным датчиком, байпас. Насос в комплект не входит, монтажная длина 180 мм."}, {"id": "heat-mixing-valtec-valmix", "name": "Насосно-смесительный узел Valtec Valmix для теплого пола без насоса (VT.VALMIX.0.130)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/614805/", "vendor": "Петрович", "sku": "614805", "region": "Санкт-Петербург", "price": 14475, "priceCard": 14475, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "pumpLength": 130, "source": "api.petrovich.ru/catalog/v5/products/614805 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec Valmix VT.VALMIX.0.130, трёхходовой термостатический смеситель. Без насоса, под насос 130 мм."}, {"id": "heat-mixing-valtec-technomix", "name": "Насосно-смесительный узел Valtec Technomix для теплого пола без насоса (VT.TECHNOMIX.0.130)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/614892/", "vendor": "Петрович", "sku": "614892", "region": "Санкт-Петербург", "price": 29219, "priceCard": 29219, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "pumpLength": 130, "source": "api.petrovich.ru/catalog/v5/products/614892 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Valtec Technomix VT.TECHNOMIX.0.130. Без насоса, под насос 130 мм."}, {"id": "heat-mixing-stout-sdg-0120-001000", "name": "Насосно-смесительный узел Stout для теплого пола с термостатическим клапаном без насоса (SDG-0120-001000)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/1047595/", "vendor": "Петрович", "sku": "1047595", "region": "Санкт-Петербург", "price": 27225, "priceCard": 27225, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "source": "api.petrovich.ru/catalog/v5/products/1047595 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout SDG-0120-001000, термостатический клапан. Без насоса."}, {"id": "heat-mixing-stout-sdg-0120-007000", "name": "Насосно-смесительный узел Stout для теплого пола с термостатическим клапаном без насоса (SDG-0120-007000)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/1047598/", "vendor": "Петрович", "sku": "1047598", "region": "Санкт-Петербург", "price": 26053, "priceCard": 26053, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "source": "api.petrovich.ru/catalog/v5/products/1047598 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout SDG-0120-007000, термостатический клапан. Без насоса."}, {"id": "heat-mixing-meibes-kombimix-pump", "name": "Насосно-смесительный узел Meibes Kombimix UK MK с насосом (M26102.4OSRU)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/635333/", "vendor": "Петрович", "sku": "635333", "region": "Санкт-Петербург", "price": 112025, "priceCard": 112025, "unit": "шт", "availability": "Доступно сегодня", "connection": "1\"", "source": "api.petrovich.ru/catalog/v5/products/635333 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Meibes Kombimix UK MK с насосом в комплекте — для справки, дорого."}, {"id": "heat-mixing-pump-valtec-25-60-130", "name": "Циркуляционный насос для систем отопления Valtec 25-60 DN25 подъем 6 м 130 мм с гайками (VRS.256.13.0)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/150424/", "vendor": "Петрович", "sku": "150424", "region": "Санкт-Петербург", "price": 4311, "priceCard": 4311, "unit": "шт", "availability": "Доступно сегодня", "pumpLength": 130, "source": "api.petrovich.ru/catalog/v5/products/150424 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Циркуляционный насос к узлам Valtec Valmix/Technomix и Stout (монтажная длина 130 мм)."}, {"id": "heat-mixing-pump-dzhileks-25-60-180", "name": "Циркуляционный насос для систем отопления Джилекс Циркуль 25/60 DN25 подъем 6 м 180 мм с гайками (2560)", "kind": "heating", "subtype": "mixing", "url": "https://petrovich.ru/product/986370/", "vendor": "Петрович", "sku": "986370", "region": "Санкт-Петербург", "price": 3480, "priceCard": 3480, "unit": "шт", "availability": "Доступно сегодня", "pumpLength": 180, "source": "api.petrovich.ru/catalog/v5/products/986370 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Циркуляционный насос к Valtec Combi (монтажная длина 180 мм)."}, {"id": "heat-cabinet-stout-shrn-2", "name": "Коллекторный шкаф Stout ШРН-2 накладной 6-7 выходов (SCC-0001-000067)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/126675/", "vendor": "Петрович", "sku": "126675", "region": "Санкт-Петербург", "price": 4334, "priceCard": 4334, "unit": "шт", "availability": "Доступно сегодня", "mount": "наружный", "outlets": "6-7", "length": 554, "height": 651, "source": "api.petrovich.ru/catalog/v5/products/126675 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout ШРН-2 накладной. Под коллектор 6 выходов с узлом смешения может не хватить — узел добавляет ~200–250 мм ширины, брать на размер больше."}, {"id": "heat-cabinet-stout-shrn-3", "name": "Коллекторный шкаф Stout ШРН-3 накладной 8 выходов (SCC-0001-000810)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/126677/", "vendor": "Петрович", "sku": "126677", "region": "Санкт-Петербург", "price": 5066, "priceCard": 5066, "unit": "шт", "availability": "Доступно сегодня", "mount": "наружный", "outlets": 8, "length": 704, "height": 651, "source": "api.petrovich.ru/catalog/v5/products/126677 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout ШРН-3 накладной."}, {"id": "heat-cabinet-stout-shrn-4", "name": "Коллекторный шкаф Stout ШРН-4 накладной 11 выходов (SCC-0001-001112)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/616995/", "vendor": "Петрович", "sku": "616995", "region": "Санкт-Петербург", "price": 6474, "priceCard": 6474, "unit": "шт", "availability": "Доступно сегодня", "mount": "наружный", "outlets": 11, "length": 854, "height": 651, "source": "api.petrovich.ru/catalog/v5/products/616995 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout ШРН-4 накладной — под коллектор 6–8 выходов с насосно-смесительным узлом."}, {"id": "heat-cabinet-stout-shrv-2", "name": "Коллекторный шкаф Stout ШРВ-2 встраиваемый 6-7 выходов (SCC-0002-000067)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/126671/", "vendor": "Петрович", "sku": "126671", "region": "Санкт-Петербург", "price": 4927, "priceCard": 4927, "unit": "шт", "availability": "Доступно сегодня", "mount": "встроенный", "outlets": "6-7", "length": 594, "height": 670, "source": "api.petrovich.ru/catalog/v5/products/126671 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout ШРВ-2 встраиваемый."}, {"id": "heat-cabinet-stout-shrv-3", "name": "Коллекторный шкаф Stout ШРВ-3 встраиваемый 8 выходов (SCC-0002-000810)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/126673/", "vendor": "Петрович", "sku": "126673", "region": "Санкт-Петербург", "price": 5638, "priceCard": 5638, "unit": "шт", "availability": "Доступно сегодня", "mount": "встроенный", "outlets": 8, "length": 744, "height": 670, "source": "api.petrovich.ru/catalog/v5/products/126673 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout ШРВ-3 встраиваемый."}, {"id": "heat-cabinet-wester-shrv-4", "name": "Коллекторный шкаф Wester встраиваемый 10 выходов (ШРВ-4)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/1150374/", "vendor": "Петрович", "sku": "1150374", "region": "Санкт-Петербург", "price": 5189, "priceCard": 5189, "unit": "шт", "availability": "Доставим 7 октября", "mount": "встроенный", "outlets": 10, "length": 850, "height": 648, "source": "api.petrovich.ru/catalog/v5/products/1150374 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Wester ШРВ-4 встраиваемый."}, {"id": "heat-cabinet-wester-shrn-4", "name": "Коллекторный шкаф Wester накладной 10 выходов (ШРН-4)", "kind": "heating", "subtype": "cabinet", "url": "https://petrovich.ru/product/1150384/", "vendor": "Петрович", "sku": "1150384", "region": "Санкт-Петербург", "price": 4507, "priceCard": 4507, "unit": "шт", "availability": "Доставим 7 октября", "mount": "наружный", "outlets": 10, "length": 848, "height": 652, "source": "api.petrovich.ru/catalog/v5/products/1150384 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Wester ШРН-4 накладной."}, {"id": "heat-fitting-eurocone-stout-16x2", "name": "Евроконус Stout 16 мм х 2,0 мм х 3/4 для труб из сшитого полиэтилена PE-Xa (SFC-0020-001620)", "kind": "heating", "subtype": "fitting", "url": "https://petrovich.ru/product/624367/", "vendor": "Петрович", "sku": "624367", "region": "Санкт-Петербург", "price": 406, "priceCard": 406, "unit": "шт", "availability": "Доступно сегодня", "diameter": 16, "wall": 2, "thread": "3/4\"", "source": "api.petrovich.ru/catalog/v5/products/624367 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout SFC-0020-001620, евроконус 16×2 под 3/4 ЕК. Нужно 2 шт на петлю."}, {"id": "heat-fitting-eurocone-sanext-16x2", "name": "Евроконус Sanext 16 мм х 3/4 ВР(г) для труб из сшитого полиэтилена (4933)", "kind": "heating", "subtype": "fitting", "url": "https://petrovich.ru/product/1175888/", "vendor": "Петрович", "sku": "1175888", "region": "Санкт-Петербург", "price": 310.67, "priceCard": 310.67, "unit": "шт", "availability": "Доставим 3 октября", "diameter": 16, "wall": 2, "thread": "3/4\"", "source": "api.petrovich.ru/catalog/v5/products/1175888 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Sanext 4933."}, {"id": "heat-fitting-eurocone-rehau-16", "name": "Евроконус Рехау 16 мм х 3/4 для труб из сшитого полиэтилена (12663523003)", "kind": "heating", "subtype": "fitting", "url": "https://petrovich.ru/product/1205225/", "vendor": "Петрович", "sku": "1205225", "region": "Санкт-Петербург", "price": 692, "priceCard": 692, "unit": "шт", "availability": "Доступно сегодня", "diameter": 16, "thread": "3/4\"", "source": "api.petrovich.ru/catalog/v5/products/1205225 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Rehau 12663523003 для PE-X 16 мм."}, {"id": "heat-damper-km-expert-8x100-12", "name": "Лента демпферная кромочная для полов КМ Эксперт самоклеящаяся 8х100 мм 12 м", "kind": "heating", "subtype": "damper", "url": "https://petrovich.ru/product/1153984/", "vendor": "Петрович", "sku": "1153984", "region": "Санкт-Петербург", "price": 966, "priceCard": 966, "unit": "шт", "availability": "Доступно сегодня", "thickness": 8, "width": 100, "roll": 12, "pricePer": "80 ₽/пог. м (12 м в рулоне)", "source": "api.petrovich.ru/catalog/v5/products/1153984 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Самоклеящаяся. Цена за рулон 12 м."}, {"id": "heat-damper-km-8x100-20", "name": "Лента демпферная кромочная для полов КМ 8х100 мм 20 м", "kind": "heating", "subtype": "damper", "url": "https://petrovich.ru/product/997079/", "vendor": "Петрович", "sku": "997079", "region": "Санкт-Петербург", "price": 274, "priceCard": 266, "unit": "рул", "availability": "Доступно сегодня", "thickness": 8, "width": 100, "roll": 20, "pricePer": "14 ₽/пог. м (20 м в рулоне)", "source": "api.petrovich.ru/catalog/v5/products/997079 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Без клеевого слоя, самая дешёвая."}, {"id": "heat-damper-knauf-fe-8x100-40", "name": "Лента демпферная кромочная для полов Knauf FE с фартуком 8х100 мм 40 м", "kind": "heating", "subtype": "damper", "url": "https://petrovich.ru/product/104493/", "vendor": "Петрович", "sku": "104493", "region": "Санкт-Петербург", "price": 1282, "priceCard": 1282, "unit": "рул", "availability": "Доступно сегодня", "thickness": 8, "width": 100, "roll": 40, "pricePer": "32 ₽/пог. м (40 м в рулоне)", "source": "api.petrovich.ru/catalog/v5/products/104493 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Knauf FE с фартуком. На дом 9×11 с перегородками нужно ~100–120 м."}, {"id": "heat-xps-penoplex-komfort-50", "name": "Экструдированный пенополистирол Пеноплэкс Комфорт 50х585х1185 мм", "kind": "heating", "subtype": "insulation", "url": "https://petrovich.ru/product/170040/", "vendor": "Петрович", "sku": "170040", "region": "Санкт-Петербург", "price": 349, "priceCard": 339, "unit": "лист", "availability": "Доступно сегодня", "thickness": 50, "length": 1185, "height": 585, "pack": 7, "pricePack": 2443, "pricePer": "503 ₽/м² (0.693 м² в листе); упаковка 7 шт = 4.85 м², 2443 ₽", "source": "api.petrovich.ru/catalog/v5/products/170040 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Пеноплэкс Комфорт. Упаковка 7 листов = 4,85 м², 2 443 ₽. Для пола по грунту лучше Фундамент (в каталоге как xps-penoplex-fundament-50/100)."}, {"id": "heat-xps-penoplex-komfort-100", "name": "Экструдированный пенополистирол Пеноплэкс Комфорт 100х585х1185 мм", "kind": "heating", "subtype": "insulation", "url": "https://petrovich.ru/product/170041/", "vendor": "Петрович", "sku": "170041", "region": "Санкт-Петербург", "price": 795, "priceCard": 771, "unit": "лист", "availability": "Доступно сегодня", "thickness": 100, "length": 1185, "height": 585, "pack": 4, "pricePack": 3180, "pricePer": "1147 ₽/м² (0.693 м² в листе); упаковка 4 шт = 2.77 м², 3180 ₽", "source": "api.petrovich.ru/catalog/v5/products/170041 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Пеноплэкс Комфорт. Упаковка 4 листа = 2,77 м², 3 180 ₽."}, {"id": "heat-xps-tn-carbon-eco-50", "name": "Экструдированный пенополистирол Технониколь Carbon Eco Г4 50х580х1180 мм", "kind": "heating", "subtype": "insulation", "url": "https://petrovich.ru/product/147312/", "vendor": "Петрович", "sku": "147312", "region": "Санкт-Петербург", "price": 319, "priceCard": 309, "unit": "лист", "availability": "Доступно сегодня", "thickness": 50, "length": 1180, "height": 580, "pack": 8, "pricePack": 2552, "pricePer": "466 ₽/м² (0.684 м² в листе); упаковка 8 шт = 5.48 м², 2552 ₽", "source": "api.petrovich.ru/catalog/v5/products/147312 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Технониколь Carbon Eco."}, {"id": "heat-xps-tn-carbon-eco-100", "name": "Экструдированный пенополистирол Технониколь Carbon Eco Г4 100х580х1180 мм", "kind": "heating", "subtype": "insulation", "url": "https://petrovich.ru/product/147315/", "vendor": "Петрович", "sku": "147315", "region": "Санкт-Петербург", "price": 665, "priceCard": 645, "unit": "лист", "availability": "Доступно сегодня", "thickness": 100, "length": 1180, "height": 580, "pack": 4, "pricePack": 2660, "pricePer": "972 ₽/м² (0.684 м² в листе); упаковка 4 шт = 2.74 м², 2660 ₽", "source": "api.petrovich.ru/catalog/v5/products/147315 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Технониколь Carbon Eco. Самый дешёвый ЭППС 100 мм за м²."}, {"id": "heat-film-pe-izostrong-150", "name": "Пленка техническая полиэтиленовая Изостронг 150 мкм ширина 1,5 м рукав 3 м (пог.м)", "kind": "heating", "subtype": "film", "url": "https://petrovich.ru/product/105944/", "vendor": "Петрович", "sku": "105944", "region": "Санкт-Петербург", "price": 81, "priceCard": 79, "unit": "пог. м", "availability": "Доступно сегодня", "thickness": 0.15, "width": 3000, "pricePer": "27 ₽/м² (3 м² в пог. м)", "source": "api.petrovich.ru/catalog/v5/products/105944 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Полиэтилен 150 мкм, рукав 1,5 м (полотно 3 м), рулон 100 м = 300 м². Продаётся погонными метрами: 81 ₽/пог. м = 27 ₽/м²."}, {"id": "heat-film-pe-izostrong-200", "name": "Пленка техническая полиэтиленовая Изостронг 200 мкм ширина 1,5 м рукав 3 м (пог.м)", "kind": "heating", "subtype": "film", "url": "https://petrovich.ru/product/105945/", "vendor": "Петрович", "sku": "105945", "region": "Санкт-Петербург", "price": 104, "priceCard": 101, "unit": "пог. м", "availability": "Доступно сегодня", "thickness": 0.2, "width": 3000, "pricePer": "35 ₽/м² (3 м² в пог. м)", "source": "api.petrovich.ru/catalog/v5/products/105945 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Полиэтилен 200 мкм, рукав 1,5 м (полотно 3 м). 104 ₽/пог. м = 34 ₽/м²."}, {"id": "heat-film-tn-vapor-100x3", "name": "Пароизоляционная пленка Технониколь 100х3 м", "kind": "heating", "subtype": "film", "url": "https://petrovich.ru/product/609381/", "vendor": "Петрович", "sku": "609381", "region": "Санкт-Петербург", "price": 13380, "priceCard": 12990, "unit": "рул", "availability": "Доступно сегодня", "width": 3000, "roll": 100, "pricePer": "45 ₽/м² (300 м² в рулоне)", "source": "api.petrovich.ru/catalog/v5/products/609381 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Технониколь, рулон 300 м² целиком — 45 ₽/м²."}, {"id": "heat-mesh-staple-rosterm-300", "name": "Скоба-фиксатор Ростерм для полимерных труб в кассете для такера (300 шт.) (100033043)", "kind": "heating", "subtype": "mesh", "url": "https://petrovich.ru/product/1159330/", "vendor": "Петрович", "sku": "1159330", "region": "Санкт-Петербург", "price": 1051, "priceCard": 1020, "unit": "шт", "availability": "Индустриальный 3 шт", "pack": 300, "source": "api.petrovich.ru/catalog/v5/products/1159330 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Скобы-гарпуны Ростерм 16–20 мм в кассете для такера, 300 шт. На 80 м² (~550–600 м трубы) при креплении через 30–40 см нужно ~1 500–2 000 скоб (5–7 упаковок)."}, {"id": "heat-mesh-staple-henco-60-300", "name": "Скоба-фиксатор Henco 60 мм для металлопластиковых труб черная (300 шт.) (UFH-TACK-60)", "kind": "heating", "subtype": "mesh", "url": "https://petrovich.ru/product/770294/", "vendor": "Петрович", "sku": "770294", "region": "Санкт-Петербург", "price": 3425, "priceCard": 3325, "unit": "шт", "availability": "Доступно сегодня", "length": 60, "pack": 300, "source": "api.petrovich.ru/catalog/v5/products/770294 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Скобы-гарпуны Henco 60 мм, 300 шт — для ЭППС 50+ мм."}, {"id": "heat-mesh-tacker-sanext", "name": "Такер Sanext для крепления труб теплого пола (4971)", "kind": "heating", "subtype": "mesh", "url": "https://petrovich.ru/product/1173522/", "vendor": "Петрович", "sku": "1173522", "region": "Санкт-Петербург", "price": 3873.45, "priceCard": 3873.45, "unit": "шт", "availability": "Доставим 3 октября", "source": "api.petrovich.ru/catalog/v5/products/1173522 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Такер для скоб-гарпунов."}, {"id": "heat-mesh-steel-100x100-d3.5-1x2.5", "name": "Сетка арматурная 100х100 мм d3,5-3,8 мм 1х2,5 м", "kind": "heating", "subtype": "mesh", "url": "https://petrovich.ru/product/107514/", "vendor": "Петрович", "sku": "107514", "region": "Санкт-Петербург", "price": 551, "priceCard": 525, "unit": "шт", "availability": "Доступно сегодня", "cell": 100, "wire": 3.5, "length": 2500, "height": 1000, "pricePer": "220 ₽/м² (2.5 м² в карте)", "source": "api.petrovich.ru/catalog/v5/products/107514 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Кладочная/арматурная сетка 100×100 Вр-1 3,5–3,8 мм, карта 1×2,5 м — вариант крепления трубы к сетке стяжками вместо гарпунов."}, {"id": "heat-mesh-composite-100x100-d2.5-1x2", "name": "Сетка стеклопластиковая композитная 100х100 мм d2,5 мм 1х2 м карта", "kind": "heating", "subtype": "mesh", "url": "https://petrovich.ru/product/689428/", "vendor": "Петрович", "sku": "689428", "region": "Санкт-Петербург", "price": 210, "priceCard": 204, "unit": "шт", "availability": "Доступно сегодня", "cell": 100, "wire": 2.5, "length": 2000, "height": 1000, "pricePer": "105 ₽/м² (2 м² в карте)", "source": "api.petrovich.ru/catalog/v5/products/689428 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Стеклопластиковая сетка 100×100, карта 1×2 м."}, {"id": "heat-screed-fiber-km-expert-0.5", "name": "Фиброволокно армирующее для бетонов полипропиленовое КМ Эксперт 0,5 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/627664/", "vendor": "Петрович", "sku": "627664", "region": "Санкт-Петербург", "price": 300, "priceCard": 294, "unit": "шт", "availability": "Доступно сегодня", "weight": 0.5, "pricePer": "600.0 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/627664 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Полипропиленовая фибра 12 мм, 0,5 кг. Расход 0,6–0,9 кг на 1 м³ раствора: на 80 м² × 65 мм (5,2 м³) ~4–5 кг."}, {"id": "heat-screed-fiber-km-1", "name": "Фиброволокно армирующее для бетонов и растворов полипропиленовое КМ 1 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/623680/", "vendor": "Петрович", "sku": "623680", "region": "Санкт-Петербург", "price": 455, "priceCard": 455, "unit": "шт", "availability": "Ожидает поставки", "weight": 1, "pricePer": "455.0 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/623680 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Полипропиленовая фибра 18 мм, 1 кг."}, {"id": "heat-screed-cps-m300-petrolit-25", "name": "Смесь цементно-песчаная (ЦПС) М300 Петролит Профи 25 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/133344/", "vendor": "Петрович", "sku": "133344", "region": "Санкт-Петербург", "price": 326, "priceCard": 315, "unit": "шт", "availability": "Доступно сегодня", "weight": 25, "pricePer": "13.0 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/133344 (city_code=spb)", "checkedAt": "2026-09-30", "note": "ЦПС М300, слой 10–60 мм. Расход ~20 кг/м² на 10 мм: на 80 м² × 65 мм ≈ 10,4 т = ~416 мешков по 25 кг."}, {"id": "heat-screed-cps-m300-mixmaster-25", "name": "Смесь цементно-песчаная (ЦПС) М300 MixMaster Универсал 25 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/145155/", "vendor": "Петрович", "sku": "145155", "region": "Санкт-Петербург", "price": 269, "priceCard": 260, "unit": "шт", "availability": "Доступно сегодня", "weight": 25, "pricePer": "10.8 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/145155 (city_code=spb)", "checkedAt": "2026-09-30", "note": "ЦПС М300, слой 10–50 мм по паспорту, 25 кг."}, {"id": "heat-screed-cps-m300-mixmaster-40", "name": "Смесь цементно-песчаная (ЦПС) М300 MixMaster Универсал 40 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/966553/", "vendor": "Петрович", "sku": "966553", "region": "Санкт-Петербург", "price": 381, "priceCard": 370, "unit": "шт", "availability": "Доступно сегодня", "weight": 40, "pricePer": "9.5 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/966553 (city_code=spb)", "checkedAt": "2026-09-30", "note": "ЦПС М300 40 кг — дешевле за кг (9,5 ₽/кг против 10,8–13). На 80 м² × 65 мм ≈ 260 мешков."}, {"id": "heat-screed-cement-m500-d0-50", "name": "Цемент ЦЕМРОС М500 Д0 ЦЕМ I 42,5 50 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/149143/", "vendor": "Петрович", "sku": "149143", "region": "Санкт-Петербург", "price": 642, "priceCard": 642, "unit": "шт", "availability": "Доступно сегодня", "weight": 50, "pricePer": "12.8 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/149143 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Цемент ЦЕМ I 42,5 (М500 Д0) 50 кг. Самозамес 1:3 на 5,2 м³ раствора ≈ 2,3 т цемента (46 мешков)."}, {"id": "heat-screed-sand-50", "name": "Песок строительный 50 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/105703/", "vendor": "Петрович", "sku": "105703", "region": "Санкт-Петербург", "price": 213, "priceCard": 210, "unit": "шт", "availability": "Доступно сегодня", "weight": 50, "pricePer": "4.3 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/105703 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Песок строительный в мешках. Для самозамеса на 5,2 м³ выгоднее насыпью машиной (~7 т)."}, {"id": "heat-screed-sand-sifted-50", "name": "Песок строительный сеяный 50 кг", "kind": "heating", "subtype": "screed", "url": "https://petrovich.ru/product/105702/", "vendor": "Петрович", "sku": "105702", "region": "Санкт-Петербург", "price": 285, "priceCard": 275, "unit": "шт", "availability": "Доступно сегодня", "weight": 50, "pricePer": "5.7 ₽/кг", "source": "api.petrovich.ru/catalog/v5/products/105702 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Песок сеяный в мешках."}, {"id": "heat-boiler-gas-baxi-eco-four-1.14f", "name": "Котел газовый Baxi Eco Four 1.14 F (14 кВт) одноконтурный с закрытой камерой (CSE46514354)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/635124/", "vendor": "Петрович", "sku": "635124", "region": "Санкт-Петербург", "price": 74390, "priceCard": 74390, "unit": "шт", "availability": "Доступно сегодня", "power": 14, "fuel": "газ", "circuits": 1, "source": "api.petrovich.ru/catalog/v5/products/635124 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Baxi Eco Four 1.14 F, 14 кВт, одноконтурный, закрытая камера, бак 6 л, 730×400×300. Для справки."}, {"id": "heat-boiler-gas-baxi-eco-4s-10f", "name": "Котел газовый Baxi Eco 4S 10 F (10 кВт) двухконтурный с закрытой камерой (7659668)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/607456/", "vendor": "Петрович", "sku": "607456", "region": "Санкт-Петербург", "price": 68470, "priceCard": 68470, "unit": "шт", "availability": "Доступно сегодня", "power": 10, "fuel": "газ", "circuits": 2, "source": "api.petrovich.ru/catalog/v5/products/607456 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Baxi Eco 4S 10 F, 10 кВт, двухконтурный — 12–15 кВт настенных Baxi в Петровиче нет, ближайшие 10 и 18 кВт. Для справки."}, {"id": "heat-boiler-el-stout-status-12", "name": "Котел электрический Stout Status (12 кВт) 380 В одноконтурный (SEB-3101-000012)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/1230286/", "vendor": "Петрович", "sku": "1230286", "region": "Санкт-Петербург", "price": 70102, "priceCard": 70102, "unit": "шт", "availability": "Доступно сегодня", "power": 12, "fuel": "электричество", "circuits": 1, "voltage": 380, "source": "api.petrovich.ru/catalog/v5/products/1230286 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout Status 12 кВт 380 В, бак 10 л, насос встроен."}, {"id": "heat-boiler-el-stout-status-14", "name": "Котел электрический Stout Status (14 кВт) 380 В одноконтурный (SEB-3101-000014)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/1230285/", "vendor": "Петрович", "sku": "1230285", "region": "Санкт-Петербург", "price": 72698, "priceCard": 72698, "unit": "шт", "availability": "Доступно сегодня", "power": 14, "fuel": "электричество", "circuits": 1, "voltage": 380, "source": "api.petrovich.ru/catalog/v5/products/1230285 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Stout Status 14 кВт 380 В."}, {"id": "heat-boiler-el-thermex-sonne-12", "name": "Котел электрический Thermex Sonne 12 Wi-Fi (12 кВт) 220/380 В одноконтурный (511703)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/1093543/", "vendor": "Петрович", "sku": "1093543", "region": "Санкт-Петербург", "price": 42430, "priceCard": 42430, "unit": "шт", "availability": "Доступно сегодня", "power": 12, "fuel": "электричество", "circuits": 1, "voltage": "220/380", "source": "api.petrovich.ru/catalog/v5/products/1093543 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Thermex Sonne 12 Wi-Fi, самый дешёвый 12 кВт."}, {"id": "heat-boiler-el-protherm-12ke", "name": "Котел электрический Protherm 12 КЕ /14 RU.UA (12 кВт) 380 В одноконтурный (10023648)", "kind": "heating", "subtype": "boiler", "url": "https://petrovich.ru/product/1086499/", "vendor": "Петрович", "sku": "1086499", "region": "Санкт-Петербург", "price": 84160, "priceCard": 84160, "unit": "шт", "availability": "Доставим завтра", "power": 12, "fuel": "электричество", "circuits": 1, "voltage": 380, "source": "api.petrovich.ru/catalog/v5/products/1086499 (city_code=spb)", "checkedAt": "2026-09-30", "note": "Protherm Скат 12 КЕ /14."}, {"id": "cable-vvgng-ls-3x1.5-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х1,5", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/103085/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "103085", "cores": 3, "section": 1.5, "price": 112, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 103085", "note": "Освещение: группы 1,5 мм² на автомат 10 А. Отпуск метражом.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x1.5-100m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х1,5 (100 м)", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/103086/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "103086", "cores": 3, "section": 1.5, "length": 100000, "price": 10882, "unit": "шт", "pricePer": "108.82 ₽/м (бухта 100 м)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 103086", "note": "Бухта 100 м.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x1.5-50m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х1,5 (50 м)", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/638109/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "638109", "cores": 3, "section": 1.5, "length": 50000, "price": 5323, "unit": "шт", "pricePer": "106.46 ₽/м (бухта 50 м)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 638109", "note": "Бухта 50 м.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x2.5-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х2,5", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/103087/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "103087", "cores": 3, "section": 2.5, "price": 175, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 103087", "note": "Розеточные группы 2,5 мм² на 16 А, стиральная, посудомойка, бойлер.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x2.5-100m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х2,5 (100 м)", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/103088/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "103088", "cores": 3, "section": 2.5, "length": 100000, "price": 16984, "unit": "шт", "pricePer": "169.84 ₽/м (бухта 100 м)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 103088", "note": "Бухта 100 м.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x2.5-50m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х2,5 (50 м)", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/638113/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "638113", "cores": 3, "section": 2.5, "length": 50000, "price": 8241, "unit": "шт", "pricePer": "164.82 ₽/м (бухта 50 м)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 638113", "note": "Бухта 50 м.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x6-m-kamkabel", "name": "Кабель Камкабель ВВГнг(А)-LS 3х6", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/997029/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "997029", "cores": 3, "section": 6, "price": 422, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 997029", "note": "Однофазная плита/варочная 6 мм² на 32 А. Бухтой у Петровича 3×6 нет, только метраж.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x6-m-konkord", "name": "Кабель Конкорд ВВГнг(А)-LS 3х6", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/680622/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "680622", "cores": 3, "section": 6, "price": 387, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 680622", "note": "Альтернатива Камкабелю, дешевле;", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-5x2.5-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 5х2,5", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/125600/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "125600", "cores": 5, "section": 2.5, "price": 283, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 125600", "note": "Трёхфазные потребители до 16 А: электрокотёл 6–9 кВт, варочная 3ф.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-5x6-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 5х6", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/125604/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "125604", "cores": 5, "section": 6, "price": 638, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 125604", "note": "Питающая линия щита/котла 3ф 25–32 А, печь-каменка 9 кВт по трассе.", "checkedAt": "2026-09-30"}, {"id": "cable-vbshvng-ls-3x6-m", "name": "Кабель ГОСТКАБЕЛЬ ВБШвнг(А)-LS 3х6 барабан", "kind": "electric", "subtype": "cable-armored", "url": "https://petrovich.ru/product/1062845/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1062845", "cores": 3, "section": 6, "armored": true, "price": 372, "unit": "пог. м", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 1062845", "note": "Бронированный медный кабель в земле: однофазная линия в гараж. Вместо АВБбШв (алюминий) — у Петровича только медный ВБШв. Режут с барабана, цена за метр.", "checkedAt": "2026-09-30"}, {"id": "cable-vbshvng-ls-5x6-m", "name": "Кабель Кабэкс ВБШвнг(А)-LS 5х6 барабан", "kind": "electric", "subtype": "cable-armored", "url": "https://petrovich.ru/product/1233598/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1233598", "cores": 5, "section": 6, "armored": true, "price": 676, "unit": "пог. м", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 1233598", "note": "Бронированный медный кабель в земле: трёхфазная линия в гараж или ввод от опоры до щита. Режут с барабана, цена за метр.", "checkedAt": "2026-09-30"}, {"id": "cable-vbshvng-ls-3x2.5-m", "name": "Кабель Кабэкс ВБШвнг(А)-LS 3х2,5 барабан", "kind": "electric", "subtype": "cable-armored", "url": "https://petrovich.ru/product/1233591/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1233591", "cores": 3, "section": 2.5, "armored": true, "price": 213, "unit": "пог. м", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 1233591", "note": "Бронированный кабель в земле для наружного освещения участка / малой нагрузки гаража.", "checkedAt": "2026-09-30"}, {"id": "cable-rkgm-1x2.5-m", "name": "Провод Камкабель РКГМ 1х2,5", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/997068/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "997068", "cores": 1, "section": 2.5, "heatResistant": true, "price": 114, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 997068", "note": "Термостойкий провод для парилки (изоляция на 170 °C и выше требуется в верхней зоне сауны). РКГМ одножильный: на печь-каменку 380 В идут 5 жил (L1 L2 L3 N PE) от распредкоробки за стеной парилки. Металлорукав и металлические оболочки внутри парилки не допускаются (ГОСТ Р 50571.12-96). Многожильного «РКГМ 5×2,5» в продаже нет.", "checkedAt": "2026-09-30"}, {"id": "cable-rkgm-1x2.5-100m", "name": "Провод Камкабель РКГМ 1х2,5 (100 м)", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/997015/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "997015", "cores": 1, "section": 2.5, "heatResistant": true, "length": 100000, "price": 11088, "unit": "шт", "pricePer": "110.88 ₽/м (бухта 100 м)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 997015", "note": "Бухта 100 м.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-2wall-63-m", "name": "Труба двустенная гофрированная ПНД/ПВД d63/52 мм SN6 с протяжкой м.п.", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/613199/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "613199", "diameter": 63, "price": 147, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 613199", "note": "Двустенная гофра ПНД/ПВД SN6 для кабеля в земле (ввод и линия в гараж), с протяжкой. Метражом.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-2wall-63-50m", "name": "Труба двустенная гофрированная ПНД/ПВД d63/52 мм SN6 с протяжкой бухта 50 м", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/613198/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "613198", "diameter": 63, "length": 50000, "price": 7330, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 613198", "note": "Бухта 50 м — хватает на трассу до гаража (~8 м + подъёмы) и ввод.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-corr-32-25m", "name": "Труба гофрированная ПНД 32 мм Геопласт легкая безгалогенная с зондом черная (25 м) (5178)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/685862/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "685862", "diameter": 32, "length": 25000, "price": 1418, "unit": "шт", "pricePer": "56.72 ₽/м (25 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 685862", "note": "Гофра ПНД 32 мм, безгалогенная, бухта 25 м: вводной кабель 5×6/5×10 внутри дома, пересечение стен.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-smooth-32-100m", "name": "Труба гладкая ПНД 32 мм Геопласт черная (100 м) (5116)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/685869/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "685869", "diameter": 32, "length": 100000, "price": 5706, "unit": "шт", "pricePer": "57.06 ₽/м (100 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 685869", "note": "Гладкая жёсткая ПНД 32 мм, бухта 100 м: гильзы через фундамент/стену, ввод в трубе по СП 256 п. 15.1.", "checkedAt": "2026-09-30"}, {"id": "conduit-pvc-corr-16-100m", "name": "Труба гофрированная ПВХ 16 мм DKC легкая с зондом серая (100 м) (91916)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/140028/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "140028", "diameter": 16, "length": 100000, "price": 2389, "unit": "шт", "pricePer": "23.89 ₽/м (100 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 140028", "note": "Гофра ПВХ 16 мм с зондом: для 3×1,5 и 3×2,5 в штробе и за потолком.", "checkedAt": "2026-09-30"}, {"id": "conduit-pvc-corr-20-100m", "name": "Труба гофрированная ПВХ 20 мм DKC легкая с зондом серая (100 м) (91920)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/140030/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "140030", "diameter": 20, "length": 100000, "price": 2904, "unit": "шт", "pricePer": "29.04 ₽/м (100 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 140030", "note": "Гофра ПВХ 20 мм с зондом: для 3×6 и 5×2,5.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-corr-16-100m", "name": "Труба гофрированная ПНД 16 мм DKC легкая с зондом черная (100 м) (71716)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/140025/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "140025", "diameter": 16, "length": 100000, "price": 3053, "unit": "шт", "pricePer": "30.53 ₽/м (100 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 140025", "note": "Гофра ПНД 16 мм (чёрная): в стяжке пола и снаружи.", "checkedAt": "2026-09-30"}, {"id": "conduit-pnd-corr-20-100m", "name": "Труба гофрированная ПНД 20 мм DKC легкая с зондом черная (100 м) (71720)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/140026/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "140026", "diameter": 20, "length": 100000, "price": 3838, "unit": "шт", "pricePer": "38.38 ₽/м (100 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 140026", "note": "Гофра ПНД 20 мм (чёрная): в стяжке пола и снаружи.", "checkedAt": "2026-09-30"}, {"id": "conduit-metal-hose-15-50m", "name": "Металлорукав в ПВХ оболочке Р3-ЦПнг с протяжкой 15 мм IEK (50 м) (CMP10-15-050-C)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/806117/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "806117", "diameter": 15, "length": 50000, "price": 4744, "unit": "шт", "pricePer": "94.88 ₽/м (50 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 806117", "note": "Металлорукав в ПВХ Р3-ЦПнг 15 мм: открытая прокладка в котельной, гараже, опуски к оборудованию. В парилке не применять.", "checkedAt": "2026-09-30"}, {"id": "conduit-metal-hose-20-50m", "name": "Металлорукав в ПВХ оболочке Р3-ЦПнг с протяжкой 20 мм IEK (50 м) (CMP10-20-050-C)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/806119/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "806119", "diameter": 20, "length": 50000, "price": 8951, "unit": "шт", "pricePer": "179.02 ₽/м (50 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 806119", "note": "Металлорукав в ПВХ 20 мм.", "checkedAt": "2026-09-30"}, {"id": "box-socket-concrete-68x45", "name": "Коробка установочная Systeme Electric для бетона d68х45 мм IP30 (IMT351001)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/128015/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "128015", "diameter": 68, "depth": 45, "price": 21, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 128015", "note": "Подрозетник для бетона/блока под сверление коронкой 68 мм.", "checkedAt": "2026-09-30"}, {"id": "box-socket-concrete-68x61", "name": "Коробка установочная Systeme Electric для бетона d68х61 мм IP30 (IMT351011)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/128016/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "128016", "diameter": 68, "depth": 61, "price": 25, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 128016", "note": "Глубокий подрозетник: под выключатель со скруткой, отвод из подрозетника.", "checkedAt": "2026-09-30"}, {"id": "box-socket-connector-10", "name": "Соединитель коробки установочной Systeme Electric IP20 (10 шт.) (IMT35180)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/107833/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "107833", "price": 171, "unit": "упак", "pricePer": "17.1 ₽/шт (10 шт в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 107833", "note": "Соединитель подрозетников в блок (упак 10 шт) — для рамок на 2–4 поста.", "checkedAt": "2026-09-30"}, {"id": "box-junction-concrete-100x100", "name": "Коробка распределительная для бетона 100x100х48 мм IP30 Systeme Electric (IMT351221)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/128019/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "128019", "length": 100, "height": 100, "depth": 48, "price": 95, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 128019", "note": "Распаечная коробка в стену 100×100.", "checkedAt": "2026-09-30"}, {"id": "box-junction-concrete-88x48", "name": "Коробка распределительная для бетона d88х48 мм IP30 Systeme Electric (IMT351211)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/128018/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "128018", "diameter": 88, "depth": 48, "price": 61, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 128018", "note": "Распаечная коробка круглая в стену.", "checkedAt": "2026-09-30"}, {"id": "terminal-wago-221-413-50", "name": "Клемма на 3 провода Wago 221-413 0,2-4 кв.мм с рычажками без пасты (50 шт.) (ЦБ-00015765/808442)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/938931/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "938931", "price": 3131, "unit": "упак", "pricePer": "62.62 ₽/шт (50 шт в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 938931", "note": "Клеммы Wago 221-413 на 3 провода до 4 мм², упак 50 шт — распайка и светильники.", "checkedAt": "2026-09-30"}, {"id": "terminal-wago-222-415-40", "name": "Клемма на 5 проводов Wago 0,08-2,5 кв.мм с рычажками без пасты (40 шт.) (222-415/2652)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/102660/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "102660", "price": 3272, "unit": "упак", "pricePer": "81.8 ₽/шт (40 шт в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 102660", "note": "Клеммы Wago 222-415 на 5 проводов до 2,5 мм², упак 40 шт.", "checkedAt": "2026-09-30"}, {"id": "terminal-wago-2273-203-100", "name": "Клемма на 3 провода Wago 0,5-2,5 кв.мм самозажимная без пасты (100 шт.) (2273-203/2666)", "kind": "electric", "subtype": "box", "url": "https://petrovich.ru/product/132536/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "132536", "price": 2215, "unit": "упак", "pricePer": "22.15 ₽/шт (100 шт в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 132536", "note": "Самозажимные Wago 2273-203 на 3 провода до 2,5 мм², упак 100 шт — дешёвый вариант для светильников.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c10", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 10А тип C 4,5 кА 230/400 В (MVA20-1-010-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100484/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100484", "poles": 1, "current": 10, "curve": "C", "price": 249, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100484", "note": "Освещение.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c16", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 16А тип C 4,5 кА 230/400 В (MVA20-1-016-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100488/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100488", "poles": 1, "current": 16, "curve": "C", "price": 210, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100488", "note": "Розетки, стиральная, посудомойка, бойлер, духовка.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c25", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 25А тип C 4,5 кА 220 В (MVA20-1-025-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100496/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100496", "poles": 1, "current": 25, "curve": "C", "price": 211, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100496", "note": "Варочная 1ф до 5 кВт на 4–6 мм².", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c32", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 32А тип C 4,5 кА 230/400 В (MVA20-1-032-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100500/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100500", "poles": 1, "current": 32, "curve": "C", "price": 262, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100500", "note": "Плита 1ф на 6 мм².", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-3p-c16", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 3P 16А тип C 4,5 кА 400 В (MVA20-3-016-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100554/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100554", "poles": 3, "current": 16, "curve": "C", "price": 635, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100554", "note": "Печь-каменка 6–9 кВт 380 В, электрокотёл до 9 кВт, гараж 3ф.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-3p-c25", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 3P 25А тип C 4,5 кА 400 В (MVA20-3-025-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100562/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100562", "poles": 3, "current": 25, "curve": "C", "price": 620, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100562", "note": "Вводной при 15 кВт/3ф (типовое ТУ сетевой: 25 А); линия в гараж 3ф.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-3p-c32", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 3P 32А тип C 4,5 кА 400 В (MVA20-3-032-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100566/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100566", "poles": 3, "current": 32, "curve": "C", "price": 627, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100566", "note": "Электрокотёл 12–15 кВт.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-3p-c40", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 3P 40А тип C 4,5 кА 400 В (MVA20-3-040-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100570/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100570", "poles": 3, "current": 40, "curve": "C", "price": 806, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100570", "note": "Вводной, если ТУ дают 40 А.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-1p-c10", "name": "Автоматический выключатель модульный ABB S201 1P 10А тип C 6 кА 220 В (2CDS251001R0104)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100482/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100482", "poles": 1, "current": 10, "curve": "C", "price": 783, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100482", "note": "ABB S201, альтернатива IEK.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-1p-c16", "name": "Автоматический выключатель модульный ABB S201 1P 16А тип C 6 кА 230/400 В (2CDS251001R0164)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100486/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100486", "poles": 1, "current": 16, "curve": "C", "price": 679, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100486", "note": "ABB S201.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-1p-c25", "name": "Автоматический выключатель модульный ABB S201 1P 25А тип C 6 кА 220 В (2CDS251001R0254)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100494/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100494", "poles": 1, "current": 25, "curve": "C", "price": 628, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100494", "note": "ABB S201.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-1p-c32", "name": "Автоматический выключатель модульный ABB S201 1P 32А тип C 6 кА 220 В (2CDS251001R0324)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100498/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100498", "poles": 1, "current": 32, "curve": "C", "price": 917, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100498", "note": "ABB S201.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-3p-c16", "name": "Автоматический выключатель модульный ABB S203 3P 16А тип C 6 кА 400 В (2CDS253001R0164)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100552/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100552", "poles": 3, "current": 16, "curve": "C", "price": 2359, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100552", "note": "ABB S203.", "checkedAt": "2026-09-30"}, {"id": "rcbo-iek-avdt32-c16-30ma-a", "name": "Автомат дифференциальный IEK Karat АВДТ-32 16А 1P+N тип A 30 мА 6 кА (MAD22-5-016-C-30)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/102250/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "102250", "poles": 2, "current": 16, "curve": "C", "leakage": 30, "rcdType": "A", "price": 1142, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 102250", "note": "Розеточные группы, стиральная, посудомойка, бойлер, санузел. Тип A — для техники с электроникой.", "checkedAt": "2026-09-30"}, {"id": "rcbo-iek-avdt32-c25-30ma-a", "name": "Автомат дифференциальный IEK Karat АВДТ-32 25А 1P+N тип A 30 мА 6 кА (MAD22-5-025-C-30)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/102256/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "102256", "poles": 2, "current": 25, "curve": "C", "leakage": 30, "rcdType": "A", "price": 1566, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 102256", "note": "Варочная/тёплый пол большой мощности.", "checkedAt": "2026-09-30"}, {"id": "rcbo-iek-ad12-c16-30ma-ac", "name": "Автомат дифференциальный IEK Karat АД-12 16А 1P+N тип AC 30 мА 4,5 кА (MAD10-2-016-C-030)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/102259/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "102259", "poles": 2, "current": 16, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 959, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 102259", "note": "Дешёвый вариант (тип AC) для обычных розеток.", "checkedAt": "2026-09-30"}, {"id": "rcbo-iek-ad12-c25-30ma-ac", "name": "Автомат дифференциальный IEK Karat АД-12 25А 1P+N тип AC 30 мА 4,5 кА (MAD10-2-025-C-030)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/102260/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "102260", "poles": 2, "current": 25, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 1045, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 102260", "note": "Тип AC, 25 А.", "checkedAt": "2026-09-30"}, {"id": "rcbo-iek-avdt32-b16-10ma-a", "name": "Автомат дифференциальный IEK Karat 16А 1P+N тип A 10 мА 6 кА (MAD22-5-016-B-10)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/1144895/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1144895", "poles": 2, "current": 16, "curve": "B", "leakage": 10, "rcdType": "A", "price": 1487, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 1144895", "note": "10 мА: санузел/ванная, тёплый пол в мокрой зоне. Характеристика B.", "checkedAt": "2026-09-30"}, {"id": "rcbo-abb-ds201-c10-30ma", "name": "Автомат дифференциальный ABB DS201 10А 1P+N тип AC 30 мА 6 кА (2CSR255080R1104)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/986218/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986218", "poles": 2, "current": 10, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 5861, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 986218", "note": "ABB DS201 C10: освещение санузла/улицы с дифзащитой. У IEK C10 30 мА в каталоге Петровича не найден.", "checkedAt": "2026-09-30"}, {"id": "rcbo-abb-ds201-c16-30ma", "name": "Автомат дифференциальный ABB DS201 16А 1P+N тип AC 30 мА 6 кА (2CSR255080R1164)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/986219/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986219", "poles": 2, "current": 16, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 6490, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 986219", "note": "ABB DS201.", "checkedAt": "2026-09-30"}, {"id": "rcbo-abb-ds201-c25-30ma", "name": "Автомат дифференциальный ABB DS201 25А 1P+N тип AC 30 мА 6 кА (2CSR255080R1254)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/986221/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986221", "poles": 2, "current": 25, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 9219, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 986221", "note": "ABB DS201.", "checkedAt": "2026-09-30"}, {"id": "rcbo-abb-ds201-c32-30ma", "name": "Автомат дифференциальный ABB DS201 32А 1P+N тип AC 30 мА 6 кА (2CSR255080R1324)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/986222/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986222", "poles": 2, "current": 32, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 5727, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 986222", "note": "ABB DS201 C32 — плита 1ф с дифзащитой.", "checkedAt": "2026-09-30"}, {"id": "rcd-iek-2p-25a-30ma", "name": "УЗО IEK Karat ВД1-63 25А 1P+N тип AC 30 мА 4,5 кА (MDV10-2-025-030)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/108914/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "108914", "poles": 2, "current": 25, "leakage": 30, "rcdType": "AC", "price": 1238, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 108914", "note": "УЗО на группу из 2–3 автоматов.", "checkedAt": "2026-09-30"}, {"id": "rcd-iek-2p-40a-30ma", "name": "УЗО IEK Karat ВД1-63 40А 1P+N тип AC 30 мА 4,5 кА (MDV10-2-040-030)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/108920/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "108920", "poles": 2, "current": 40, "leakage": 30, "rcdType": "AC", "price": 1745, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 108920", "note": "УЗО 40 А 30 мА на фазу — над группой розеточных автоматов.", "checkedAt": "2026-09-30"}, {"id": "rcd-iek-2p-63a-30ma", "name": "УЗО IEK Karat ВД1-63 63А 1P+N тип AC 30 мА 4,5 кА (MDV10-2-063-030)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/108924/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "108924", "poles": 2, "current": 63, "leakage": 30, "rcdType": "AC", "price": 1620, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 108924", "note": "УЗО 63 А 30 мА.", "checkedAt": "2026-09-30"}, {"id": "rcd-iek-4p-25a-30ma", "name": "УЗО IEK Karat ВД1-63 25А 3P+N тип AC 30 мА 4,5 кА (MDV10-4-025-030)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/108929/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "108929", "poles": 4, "current": 25, "leakage": 30, "rcdType": "AC", "price": 2351, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 108929", "note": "4P 25 А 30 мА: трёхфазная линия гаража, котёл 3ф.", "checkedAt": "2026-09-30"}, {"id": "rcd-abb-2p-16a-10ma", "name": "УЗО ABB S F202 16А 1P+N тип AC 10 мА 10 кА (2CSF202001R0160)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/108909/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "108909", "poles": 2, "current": 16, "leakage": 10, "rcdType": "AC", "price": 8230, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 108909", "note": "УЗО 10 мА ABB — ванная/санузел, если не дифавтомат.", "checkedAt": "2026-09-30"}, {"id": "rcd-ekf-4p-40a-100ma-s", "name": "УЗО EKF PROxima ВД-100N (S) 40А 3P+N тип AC 100 мА 6 кА селективное (E1046MS40100)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/1141022/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1141022", "poles": 4, "current": 40, "leakage": 100, "rcdType": "AC", "selective": true, "price": 4475, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 1141022", "note": "Селективное (S) 100 мА на вводе — противопожарное, селективно с 30 мА ниже по схеме (ПУЭ 7.1.73).", "checkedAt": "2026-09-30"}, {"id": "rcd-ekf-4p-63a-100ma-s", "name": "УЗО EKF PROxima ВД-100 63А 3P+N тип AC 100 мА 4,5 кА селективное (elcb-4-63-100S-em-pro)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/994976/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "994976", "poles": 4, "current": 63, "leakage": 100, "rcdType": "AC", "selective": true, "price": 2635, "unit": "шт", "availability": "Доставим 8 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 994976", "note": "Селективное 100 мА 63 А;", "checkedAt": "2026-09-30"}, {"id": "rcd-ekf-4p-80a-300ma-s", "name": "УЗО EKF PROxima ВД-100 80А 3P+N тип AC 300 мА 4,5 кА селективное (elcb-4-80-300S-em-pro)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/994979/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "994979", "poles": 4, "current": 80, "leakage": 300, "rcdType": "AC", "selective": true, "price": 5128, "unit": "шт", "availability": "Доставим 8 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 994979", "note": "Противопожарное селективное 300 мА (СП 256 п. 10.13). 63 А версия в СПб отсутствует;", "checkedAt": "2026-09-30"}, {"id": "relay-voltage", "name": "Реле напряжения модульное Новатек РН-106 220 В 60 А тип AC", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/656135/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "656135", "modules": 0, "device": "voltage-relay", "current": 60, "price": 3651, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 656135", "note": "Реле напряжения однофазное 60 А. На 3 фазы — 3 шт (по одному на фазу), чтобы не отключать весь дом при перекосе одной фазы.", "checkedAt": "2026-09-30"}, {"id": "relay-voltage-ekf-mrv63", "name": "Реле напряжения модульное EKF PROxima 230 В 63 А тип AC с дисплеем (MRV-63A)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/1036883/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1036883", "modules": 0, "device": "voltage-relay", "current": 63, "price": 3694, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1036883", "note": "Реле напряжения однофазное 63 А с дисплеем, альтернатива РН-106.", "checkedAt": "2026-09-30"}, {"id": "relay-voltage-novatek-rnpp311m", "name": "Реле напряжения модульное Новатек РНПП-311М 400 В 5 А тип AC/DC", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/656134/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "656134", "modules": 0, "device": "voltage-relay", "current": 5, "price": 3215, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 656134", "note": "Трёхфазное реле контроля 400 В 5 А — управляет контактором, нужно для трёхфазных нагрузок (котёл, каменка).", "checkedAt": "2026-09-30"}, {"id": "spd-ekf-t1t2-4p", "name": "Ограничитель напряжения модульный EKF PROxima T1-T2 275 В 20 кА 4P (OV12-31-506)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/986755/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986755", "modules": 0, "device": "spd", "poles": 4, "class": "T1+T2", "price": 18299, "unit": "шт", "availability": "Доставим 8 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 986755", "note": "УЗИП класс I+II, 4P, для ввода от ВЛ в TN-C-S. Ставится до УЗО (СП 256 прил. А.5.3).", "checkedAt": "2026-09-30"}, {"id": "spd-ekf-t2-3p", "name": "Ограничитель напряжения модульный EKF PROxima 400 В 20 кА 3P (opv-c3)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/986741/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986741", "modules": 0, "device": "spd", "poles": 3, "class": "T2", "price": 7550, "unit": "шт", "availability": "Доставим 8 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 986741", "note": "УЗИП класс II 3P, дешевле; при воздушном вводе предпочтительнее T1+T2.", "checkedAt": "2026-09-30"}, {"id": "panel-iek-tekfor-shrv-54", "name": "Щит распределительный встраиваемый IEK Tekfor ЩРВ-П-54 пластиковый IP41 535х398х102 мм 54 модуля прозрачная дверь (TF5-KP12-V-54-41-K01-K03)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/1084061/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1084061", "modules": 54, "mount": "встраиваемый", "ip": 41, "length": 398, "height": 535, "thickness": 102, "price": 5217, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1084061", "note": "Щит для дома: 54 модуля с запасом (ввод, УЗИП, реле, 3 фазы групп). Встраиваемый в блок 190.", "checkedAt": "2026-09-30"}, {"id": "panel-keaz-optibox-shrn-54", "name": "Щит распределительный навесной КЭАЗ OptiBox ЩРН пластиковый IP41 535х398х102 мм 54 модуля (117935)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/964757/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "964757", "modules": 54, "mount": "навесной", "ip": 41, "length": 398, "height": 535, "thickness": 102, "price": 8505, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 964757", "note": "Навесной 54 модуля.", "checkedAt": "2026-09-30"}, {"id": "panel-iek-tekfor-shrn-36", "name": "Щит распределительный навесной IEK Tekfor ЩРН-П-36 пластиковый IP41 535х290х102 мм 36 модулей прозрачная дверь (TF5-KP12-N-36-41-K01-K03)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/1084063/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1084063", "modules": 36, "mount": "навесной", "ip": 41, "length": 290, "height": 535, "thickness": 102, "price": 4918, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1084063", "note": "Навесной 36 модулей.", "checkedAt": "2026-09-30"}, {"id": "panel-ekf-shrn-p-36", "name": "Щит распределительный навесной EKF PROxima ЩРН-П-36 пластиковый IP41 460х270х100 мм 36 модулей (pb40-т-36)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/503890/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "503890", "modules": 36, "mount": "навесной", "ip": 41, "length": 270, "height": 460, "thickness": 100, "price": 1950, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 503890", "note": "Самый дешёвый щит на 36 модулей.", "checkedAt": "2026-09-30"}, {"id": "panel-ekf-shrv-p-36", "name": "Щит распределительный встраиваемый EKF PROxima ЩРВ-П-36 пластиковый IP41 482х300х100 мм 36 модулей (pb40-v-36)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/503889/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "503889", "modules": 36, "mount": "встраиваемый", "ip": 41, "length": 300, "height": 482, "thickness": 100, "price": 4379, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 503889", "note": "Встраиваемый 36 модулей.", "checkedAt": "2026-09-30"}, {"id": "panel-ekf-shrn-12-metal-ip54", "name": "Щит распределительный навесной EKF Basic ЩРН-12 металлический IP54 265х310х120 мм 12 модулей (mb24-12-bas)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/660877/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "660877", "modules": 12, "mount": "навесной", "ip": 54, "length": 310, "height": 265, "thickness": 120, "price": 3470, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 660877", "note": "Щиток гаража: металлический IP54 на 12 модулей (неотапливаемый гараж из ПИР).", "checkedAt": "2026-09-30"}, {"id": "panel-ekf-shrn-p-12", "name": "Щит распределительный навесной EKF PROxima ЩРН-П-12 пластиковый IP41 200х256х95 мм 12 модулей (pb40-n-12)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/634125/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "634125", "modules": 12, "mount": "навесной", "ip": 41, "length": 256, "height": 200, "thickness": 95, "price": 659, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 634125", "note": "Щиток гаража пластиковый, дешевле.", "checkedAt": "2026-09-30"}, {"id": "panel-iek-kmpn-36-ip65", "name": "Щит распределительный навесной IEK Tekfor КМПн-36 пластиковый IP65 560х300х153 мм 36 модулей прозрачная дверь (TF5-KP72-N-36-65-K03-K02)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/1084067/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1084067", "modules": 36, "mount": "навесной", "ip": 65, "length": 300, "height": 560, "thickness": 153, "price": 10571, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1084067", "note": "Щит IP65 36 модулей — если гараж сырой/не отапливается или щит ставится снаружи.", "checkedAt": "2026-09-30"}, {"id": "panel-busbar-n-20", "name": "Шина нулевая на 2-х угловых изоляторах EKF PROxima 6х9 мм 20 отверстий синяя (sn0-2-63-20-r)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/688691/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "688691", "modules": 0, "price": 241, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 688691", "note": "Шина нулевая N 20 отверстий на изоляторах.", "checkedAt": "2026-09-30"}, {"id": "panel-busbar-n-12", "name": "Шина нулевая на 2-х угловых изоляторах EKF PROxima 6х9 мм 12 отверстий синяя (sn0-63-12-2-r)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/688677/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "688677", "modules": 0, "price": 185, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 688677", "note": "Шина N/PE 12 отверстий; нужно 2 шт (N и PE) на щит, плюс по одной на каждое УЗО с группой.", "checkedAt": "2026-09-30"}, {"id": "panel-comb-3ph-pin-54", "name": "Шина соединительная трехрядная EKF PROxima тип PIN 63 А на 54 модуля 1 м (pin-03-63)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/688684/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "688684", "modules": 0, "price": 2236, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 688684", "note": "Гребёнка трёхрядная PIN 63 А, 1 м (54 модуля) — режется.", "checkedAt": "2026-09-30"}, {"id": "panel-comb-1ph-pin-54", "name": "Шина соединительная однорядная EKF PROxima тип PIN 63 А на 54 модуля 1 м (pin-01-63)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/688683/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "688683", "modules": 0, "price": 836, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 688683", "note": "Гребёнка однорядная PIN 63 А, 1 м.", "checkedAt": "2026-09-30"}, {"id": "panel-din-rail-100", "name": "DIN-рейка перфорированная IEK 100 см (YDN10-0100)", "kind": "electric", "subtype": "panel", "url": "https://petrovich.ru/product/687395/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "687395", "modules": 0, "length": 1000, "price": 193, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 687395", "note": "DIN-рейка 1 м.", "checkedAt": "2026-09-30"}, {"id": "grounding-ekf-hz-6m", "name": "Комплект заземления универсальный EKF HZ (6 м) (gc-21601)", "kind": "electric", "subtype": "grounding", "url": "https://petrovich.ru/product/955758/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "955758", "length": 6000, "price": 8537, "unit": "шт", "pricePer": "1422.83 ₽/м (6 м в упаковке)", "availability": "Ожидает поставки", "source": "petrovich.ru, API карточки catalog/v5, арт. 955758", "note": "Модульный комплект заземления 6 м (штыри, муфты, зажим, паста). Сейчас «ожидает поставки».", "checkedAt": "2026-09-30"}, {"id": "grounding-ezetek-fe-6m", "name": "Комплект заземления Ezetek FE-6 (6 м) (60017)", "kind": "electric", "subtype": "grounding", "url": "https://petrovich.ru/product/1041716/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1041716", "length": 6000, "price": 7738.18, "unit": "шт", "pricePer": "1289.7 ₽/м (6 м в упаковке)", "availability": "Доставим 3 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 1041716", "note": "Омеднённая сталь, 6 м;", "checkedAt": "2026-09-30"}, {"id": "grounding-ezetek-ez-6m", "name": "Комплект заземления Ezetek EZ-6 с насадкой SDS-max (6 м) (60282)", "kind": "electric", "subtype": "grounding", "url": "https://petrovich.ru/product/1041708/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1041708", "length": 6000, "price": 20319.81, "unit": "шт", "pricePer": "3386.64 ₽/м (6 м в упаковке)", "availability": "Доставим 3 октября", "source": "petrovich.ru, API карточки catalog/v5, арт. 1041708", "note": "Оцинкованная сталь с насадкой SDS-max, 6 м — дорогой вариант.", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-white", "name": "Розетка Systeme Electric AtlasDesign встраиваемая белая с заземлением (ATN000143)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650614/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650614", "series": "AtlasDesign", "ip": 20, "price": 217, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650614", "note": "Механизм с лицевой панелью, без рамки (рамка ATN000101–104 отдельно).", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-white-shutters", "name": "Розетка Systeme Electric AtlasDesign встраиваемая белая с заземлением со шторками (ATN000145)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650615/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650615", "series": "AtlasDesign", "ip": 20, "price": 277, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650615", "note": "Со шторками — рекомендовано в жилых комнатах (СП 256 п. 15.35).", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-double-white", "name": "Розетка двойная Systeme Electric AtlasDesign встраиваемая белая с заземлением (ATN000124)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650617/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650617", "series": "AtlasDesign", "ip": 20, "price": 378, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650617", "note": "Двойная в одном посту (рамка одноместная). На кухне считается за две (СП 256 п. 15.28).", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-aqua-ip44", "name": "Розетка Systeme Electric AtlasDesign Aqua встраиваемая белая с заземлением со шторками с крышкой (ATN440146)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650630/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650630", "series": "AtlasDesign Aqua", "ip": 44, "price": 393, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650630", "note": "IP44 с крышкой и шторками: санузел (зона 3/вне зон), кухня у мойки, котельная. Нужна рамка Aqua ATN440101.", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-profi54-ip54", "name": "Розетка Systeme Electric AtlasDesign Profi54 накладная белая с заземлением со шторками с крышкой (ATN540145)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/987586/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "987586", "series": "AtlasDesign Profi54", "ip": 54, "price": 557, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 987586", "note": "Накладная IP54 для гаража/улицы/котельной.", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-profi54-double-ip54", "name": "Розетка двойная Systeme Electric AtlasDesign Profi54 накладная белая с заземлением со шторками с крышкой (ATN540126)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/987588/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "987588", "series": "AtlasDesign Profi54", "ip": 54, "price": 964, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 987588", "note": "Двойная накладная IP54 для гаража.", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-cable-outlet", "name": "Вывод кабеля Systeme Electric AtlasDesign встраиваемый белый (ATN000199)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650627/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650627", "series": "AtlasDesign", "price": 253, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650627", "note": "Вывод кабеля — подключение варочной/духовки/бойлера без вилки.", "checkedAt": "2026-09-30"}, {"id": "socket-atlas-rj45", "name": "Розетка компьютерная Systeme Electric AtlasDesign встраиваемая белая RJ45 (ATN000183)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/650620/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650620", "series": "AtlasDesign", "price": 809, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650620", "note": "Компьютерная RJ45 кат. 5e.", "checkedAt": "2026-09-30"}, {"id": "socket-legrand-valena-white", "name": "Розетка Legrand Valena встраиваемая белая с заземлением (694280)", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/104779/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "104779", "series": "Valena", "ip": 20, "price": 320, "unit": "шт", "availability": "Таллинское 4 шт", "source": "petrovich.ru, API карточки catalog/v5, арт. 104779", "note": "Альтернативная серия Legrand Valena;", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-1g", "name": "Выключатель Systeme Electric AtlasDesign одноклавишный встраиваемый белый (ATN000111)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/650607/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650607", "series": "AtlasDesign", "gangs": 1, "price": 208, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650607", "note": "Одноклавишный.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-2g", "name": "Выключатель Systeme Electric AtlasDesign двухклавишный встраиваемый белый (ATN000151)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/650609/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650609", "series": "AtlasDesign", "gangs": 2, "price": 271, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650609", "note": "Двухклавишный.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-1g-lit", "name": "Выключатель Systeme Electric AtlasDesign одноклавишный встраиваемый белый с подсветкой (ATN000113)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/650608/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650608", "series": "AtlasDesign", "gangs": 1, "price": 378, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650608", "note": "Одноклавишный с подсветкой.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-1g-2way", "name": "Переключатель Systeme Electric AtlasDesign одноклавишный встраиваемый белый (ATN000161)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/650611/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650611", "series": "AtlasDesign", "gangs": 1, "price": 350, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650611", "note": "Переключатель (проходной) — коридор, прихожая + гостиная.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-2g-2way", "name": "Переключатель Systeme Electric AtlasDesign двухклавишный встраиваемый белый (ATN000165)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/655048/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "655048", "series": "AtlasDesign", "gangs": 2, "price": 622, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 655048", "note": "Двухклавишный проходной.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-aqua-1g-2way-ip44", "name": "Переключатель Systeme Electric AtlasDesign Aqua одноклавишный встраиваемый белый (ATN440161)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/650631/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650631", "series": "AtlasDesign Aqua", "ip": 44, "price": 393, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650631", "note": "IP44 проходной: сауна/санузел снаружи, котельная.", "checkedAt": "2026-09-30"}, {"id": "switch-atlas-profi54-1g-ip54", "name": "Выключатель Systeme Electric AtlasDesign Profi54 одноклавишный накладной белый (ATN540111)", "kind": "electric", "subtype": "switch", "url": "https://petrovich.ru/product/987574/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "987574", "series": "AtlasDesign Profi54", "ip": 54, "gangs": 1, "price": 488, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 987574", "note": "Накладной IP54 — гараж, улица.", "checkedAt": "2026-09-30"}, {"id": "frame-atlas-1", "name": "Рамка Systeme Electric AtlasDesign одноместная белая (ATN000101)", "kind": "electric", "subtype": "frame", "url": "https://petrovich.ru/product/650623/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650623", "series": "AtlasDesign", "posts": 1, "price": 67, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650623", "note": "Рамка одноместная.", "checkedAt": "2026-09-30"}, {"id": "frame-atlas-2", "name": "Рамка Systeme Electric AtlasDesign двухместная белая (ATN000102)", "kind": "electric", "subtype": "frame", "url": "https://petrovich.ru/product/650624/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650624", "series": "AtlasDesign", "posts": 2, "price": 111, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650624", "note": "Рамка двухместная.", "checkedAt": "2026-09-30"}, {"id": "frame-atlas-3", "name": "Рамка Systeme Electric AtlasDesign трехместная белая (ATN000103)", "kind": "electric", "subtype": "frame", "url": "https://petrovich.ru/product/650625/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650625", "series": "AtlasDesign", "posts": 3, "price": 212, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650625", "note": "Рамка трёхместная.", "checkedAt": "2026-09-30"}, {"id": "frame-atlas-4", "name": "Рамка Systeme Electric AtlasDesign четырехместная белая (ATN000104)", "kind": "electric", "subtype": "frame", "url": "https://petrovich.ru/product/650626/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650626", "series": "AtlasDesign", "posts": 4, "price": 329, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650626", "note": "Рамка четырёхместная — кухонный фартук.", "checkedAt": "2026-09-30"}, {"id": "frame-atlas-aqua-1", "name": "Рамка Systeme Electric AtlasDesign Aqua одноместная белая (ATN440101)", "kind": "electric", "subtype": "frame", "url": "https://petrovich.ru/product/650632/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "650632", "series": "AtlasDesign Aqua", "posts": 1, "ip": 44, "price": 113, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 650632", "note": "Рамка Aqua IP44 одноместная.", "checkedAt": "2026-09-30"}, {"id": "socket-power-32a-3p-ip44", "name": "Розетка силовая угловая настенная EKF PROxima 3Р+РЕ+N 32 А 380 В IP44", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/660916/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "660916", "ip": 44, "current": 32, "price": 651, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 660916", "note": "Силовая розетка 3P+N+PE 32 А 380 В настенная — гараж (сварка, компрессор), мастерская.", "checkedAt": "2026-09-30"}, {"id": "socket-power-32a-1p-ip44", "name": "Розетка силовая угловая настенная EKF PROxima 2Р+РЕ 32 А 220 В IP44", "kind": "electric", "subtype": "socket", "url": "https://petrovich.ru/product/667591/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "667591", "ip": 44, "current": 32, "price": 527, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 667591", "note": "Силовая розетка 2P+PE 32 А 220 В настенная.", "checkedAt": "2026-09-30"}, {"id": "light-ledvance-ip65-10w", "name": "Светильник светодиодный потолочный Ledvance Eco class 4000К 10 Вт 4,8 кв.м белый IP65 (4058075688377)", "kind": "electric", "subtype": "light", "url": "https://petrovich.ru/product/998863/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "998863", "ip": 65, "power": 10, "price": 730, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 998863", "note": "Накладной светодиодный IP65: санузел, котельная, кладовые.", "checkedAt": "2026-09-30"}, {"id": "light-ritter-dbp8-ip65", "name": "Светильник светодиодный накладной Rev Ritter ДБП-8 4000К 8 Вт IP65 белый (28920 3)", "kind": "electric", "subtype": "light", "url": "https://petrovich.ru/product/163606/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "163606", "ip": 65, "power": 8, "price": 241, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 163606", "note": "Накладной IP65 8 Вт — кладовые, гараж.", "checkedAt": "2026-09-30"}, {"id": "light-feron-facade-ip54", "name": "Светильник фасадный настенный Feron Техно черный E27 60 Вт IP54 (06294)", "kind": "electric", "subtype": "light", "url": "https://petrovich.ru/product/684538/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "684538", "ip": 54, "price": 2057, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 684538", "note": "Фасадный E27 IP54 — вход, гараж снаружи.", "checkedAt": "2026-09-30"}, {"id": "light-svet-nbb-ip65-sauna", "name": "Светильник накладной Svet НББ 01-60-001 E27 60 Вт IP65 белый (1300-00010)", "kind": "electric", "subtype": "light", "url": "https://petrovich.ru/product/636631/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "636631", "ip": 65, "price": 785, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 636631", "note": "Для бани/сауны (раздел Петровича «Светильники для бани и сауны»), E27 до 60 Вт; в парилке ставить выше 0,5 м и вне зоны 1 печи, лампа — термостойкая.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-3x4-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 3х4", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/133798/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "133798", "cores": 3, "section": 4, "price": 268, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 133798", "note": "Линии на 25 А: варочная до 5 кВт, тёплый пол большой площади.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-5x1.5-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 5х1,5", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/670987/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "670987", "cores": 5, "section": 1.5, "price": 186, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 670987", "note": "Трёхфазные линии малой мощности, управление.", "checkedAt": "2026-09-30"}, {"id": "cable-vvgng-ls-5x4-m", "name": "Кабель Кабэкс ВВГнг(А)-LS 5х4", "kind": "electric", "subtype": "cable", "url": "https://petrovich.ru/product/125602/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "125602", "cores": 5, "section": 4, "price": 431, "unit": "пог. м", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 125602", "note": "Трёхфазные линии на 25 А: котёл 9–12 кВт, линия в гараж внутри дома.", "checkedAt": "2026-09-30"}, {"id": "conduit-pvc-corr-25-50m", "name": "Труба гофрированная ПВХ 25 мм DKC легкая с зондом серая (50 м) (91925)", "kind": "electric", "subtype": "conduit", "url": "https://petrovich.ru/product/140032/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "140032", "diameter": 25, "length": 50000, "price": 2368, "unit": "шт", "pricePer": "47.36 ₽/м (50 м в упаковке)", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 140032", "note": "Гофра ПВХ 25 мм с зондом, бухта 50 м: 5×4, 5×6.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c6", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 6А тип C 4,5 кА 230/400 В (MVA20-1-006-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100480/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100480", "poles": 1, "current": 6, "curve": "C", "price": 263, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100480", "note": "Слаботочка, управление, котёл/автоматика.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c20", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 20А тип C 4,5 кА 230/400 В (MVA20-1-020-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100492/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100492", "poles": 1, "current": 20, "curve": "C", "price": 263, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100492", "note": "IEK 1P C20.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-1p-c40", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 1P 40А тип C 4,5 кА 220 В (MVA20-1-040-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100504/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100504", "poles": 1, "current": 40, "curve": "C", "price": 273, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100504", "note": "IEK 1P C40.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-1p-c20", "name": "Автоматический выключатель модульный ABB S201 1P 20А тип C 6 кА 220 В (2CDS251001R0204)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100490/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100490", "poles": 1, "current": 20, "curve": "C", "price": 668, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100490", "note": "ABB S201 C20.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-2p-c10", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 2P 10А тип C 4,5 кА 400 В (MVA20-2-010-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100517/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100517", "poles": 2, "current": 10, "curve": "C", "price": 564, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100517", "note": "IEK 2P C10.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-2p-c16", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 2P 16А тип C 4,5 кА 400 В (MVA20-2-016-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100521/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100521", "poles": 2, "current": 16, "curve": "C", "price": 537, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100521", "note": "IEK 2P C16.", "checkedAt": "2026-09-30"}, {"id": "breaker-iek-2p-c32", "name": "Автоматический выключатель модульный IEK Karat ВА 47-29 2P 32А тип C 4,5 кА 400 В (MVA20-2-032-C)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100532/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100532", "poles": 2, "current": 32, "curve": "C", "price": 524, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100532", "note": "IEK 2P C32.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-2p-c20", "name": "Автоматический выключатель модульный ABB S202 2P 20А тип C 6 кА 400 В (2CDS252001R0204)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100523/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100523", "poles": 2, "current": 20, "curve": "C", "price": 2874, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 100523", "note": "ABB S202 2P C20.", "checkedAt": "2026-09-30"}, {"id": "breaker-abb-2p-c40", "name": "Автоматический выключатель модульный ABB SH202 2P 40А тип C 6 кА 400 В (2CDS212001R0404)", "kind": "electric", "subtype": "breaker", "url": "https://petrovich.ru/product/100535/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "100535", "poles": 2, "current": 40, "curve": "C", "price": 2415, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 100535", "note": "Вводной 2P C40 при однофазном вводе (ABB SH202). IEK 2P C40 в Петровиче снят.", "checkedAt": "2026-09-30"}, {"id": "rcd-ekf-4p-40a-30ma", "name": "УЗО EKF Basic ВДТ-40 40А 3P+N тип AC 30 мА 4,5 кА (elcb-4-40-30e-sim)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/1036732/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1036732", "poles": 4, "current": 40, "leakage": 30, "rcdType": "AC", "price": 1904, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1036732", "note": "УЗО 4P 40 А 30 мА, дешёвое EKF Basic. IEK ВД1-63 4P 40 А в Петровиче снят.", "checkedAt": "2026-09-30"}, {"id": "rcd-ekf-averes-4p-40a-30ma", "name": "УЗО EKF Averes DV 40А 3P+N тип AC 30 мА 10 кА (rccb-4-40-30-ac-av)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/1036814/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "1036814", "poles": 4, "current": 40, "leakage": 30, "rcdType": "AC", "price": 6887, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 1036814", "note": "EKF Averes 10 кА.", "checkedAt": "2026-09-30"}, {"id": "rcd-chint-4p-63a-30ma", "name": "УЗО Chint NXL-63 63А 3P+N тип AC 30 мА 6 кА компактное (280792)", "kind": "electric", "subtype": "rcd", "url": "https://petrovich.ru/product/971187/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "971187", "poles": 4, "current": 63, "leakage": 30, "rcdType": "AC", "price": 2803, "unit": "шт", "availability": "Доступно сегодня", "source": "petrovich.ru, API карточки catalog/v5, арт. 971187", "note": "УЗО 4P 63 А 30 мА;", "checkedAt": "2026-09-30"}, {"id": "rcbo-abb-ds201-c20-30ma", "name": "Автомат дифференциальный ABB DS201 20А 1P+N тип AC 30 мА 6 кА (2CSR255080R1204)", "kind": "electric", "subtype": "rcbo", "url": "https://petrovich.ru/product/986220/", "vendor": "Петрович", "region": "Санкт-Петербург", "sku": "986220", "poles": 2, "current": 20, "curve": "C", "leakage": 30, "rcdType": "AC", "price": 6953, "unit": "шт", "availability": "Доставим завтра", "source": "petrovich.ru, API карточки catalog/v5, арт. 986220", "note": "ABB DS201 C20.", "checkedAt": "2026-09-30"}]
\ No newline at end of file
diff --git a/public/data/house.json b/public/data/house.json
new file mode 100644
index 0000000..31a5ed7
--- /dev/null
+++ b/public/data/house.json
@@ -0,0 +1,123 @@
+{
+ "title": "Plot & house",
+ "subtitle": "Demo plot 30 × 45 m · Lot 12, Demo Lane · fictional data",
+ "updated": "2026-10-01",
+ "sections": [
+ {
+ "id": "parcel",
+ "title": "Plot",
+ "lead": "Example plot passport. Replace it with your own data in public/data/house.json.",
+ "blocks": [
+ {
+ "type": "facts",
+ "title": "Key facts",
+ "items": [
+ { "label": "Address", "value": "Demo Lane 12", "hint": "Fictional address" },
+ { "label": "Lot", "value": "Lot 12 of a new subdivision", "hint": "Neighbours: Lot 11 and Lot 13" },
+ { "label": "Area", "value": "1350 m²", "hint": "30 × 45 m, rectangular" },
+ { "label": "Land use", "value": "Residential, one detached house" },
+ { "label": "Terrain", "value": "Flat former field, no trees or structures" },
+ { "label": "Access", "value": "From Demo Lane along the 30 m side", "hint": "Gravel road, north-east of the plot" },
+ { "label": "Utilities", "value": "Electricity at the road; water from a private borehole; sewage to an on-site treatment plant" },
+ { "label": "Location", "value": "Rural area near Kiili, Harju County, Estonia", "hint": "Used only to place the demo on satellite imagery" }
+ ]
+ },
+ {
+ "type": "map",
+ "title": "Plot layout",
+ "caption": "Top view in plan axes, street at the bottom. Building zone: 3 m from the neighbours and the rear, 5 m from the street.",
+ "north": 152,
+ "parcel": {
+ "label": "Lot 12",
+ "note": "30 × 45 m",
+ "points": [[0, 0], [30, 0], [30, 45], [0, 45]]
+ },
+ "sides": [
+ { "at": [15, 0], "len": 30, "angle": 0 },
+ { "at": [30, 22.5], "len": 45, "angle": 90 },
+ { "at": [15, 45], "len": 30, "angle": 0 },
+ { "at": [0, 22.5], "len": 45, "angle": 90 }
+ ],
+ "neighbors": [
+ { "label": "Lot 11", "note": "vacant", "points": [[-30, 0], [0, 0], [0, 45], [-30, 45]] },
+ { "label": "Lot 13", "note": "vacant", "points": [[30, 0], [60, 0], [60, 45], [30, 45]] }
+ ],
+ "zone": {
+ "label": "Building zone ≈ 888 m²",
+ "points": [[3, 3], [27, 3], [27, 40], [3, 40]]
+ },
+ "street": {
+ "label": "Demo Lane",
+ "at": [15, 50.5],
+ "angle": 0,
+ "band": [[-20, 47.5], [50, 47.5], [50, 50.5], [-20, 50.5]]
+ }
+ },
+ {
+ "type": "links",
+ "title": "Links",
+ "items": [
+ { "title": "Esri World Imagery", "url": "https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9", "note": "Satellite basemap used on the Map tab" }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "norms",
+ "title": "Setbacks and rules",
+ "lead": "Example values that the planner checks against. Local zoning and the building code always take precedence.",
+ "blocks": [
+ {
+ "type": "note",
+ "tone": "info",
+ "text": "**Check the local detailed plan first.** Setbacks, maximum footprint and height are set by the municipality for each subdivision; the numbers below are typical defaults, not legal advice."
+ },
+ {
+ "type": "facts",
+ "title": "Distances on the plot",
+ "items": [
+ { "label": "House — neighbouring boundary", "value": "3 m" },
+ { "label": "House — street boundary", "value": "5 m" },
+ { "label": "Garage, shed — boundary", "value": "1 m" },
+ { "label": "Between buildings (fire separation)", "value": "6 m", "hint": "Less is possible with fire-rated walls" },
+ { "label": "Treatment plant — house / boundary", "value": "5 m / 1 m" },
+ { "label": "Borehole — treatment plant", "value": "50 m", "hint": "15 m is the usual minimum in plant passports" },
+ { "label": "Water pipe depth", "value": "≥ 1.5 m", "hint": "Below frost depth, or with a heating cable" },
+ { "label": "Sewer pipe depth outside", "value": "≥ 1.0 m", "hint": "Shallower pipes need insulation" }
+ ]
+ },
+ {
+ "type": "table",
+ "title": "Rooms and daylight",
+ "source": "Planner check: window area ≥ 1/8 of the floor area in living rooms and bedrooms",
+ "columns": ["Room", "Floor, m²", "Windows, m²", "Ratio"],
+ "rows": [
+ ["Living / Kitchen", "38.8", "7.6", "1 : 5.1"],
+ ["Master bedroom", "15.4", "2.7", "1 : 5.7"],
+ ["Bedroom 2", "11.1", "3.5", "1 : 3.2"],
+ ["Bedroom 3", "10.3", "2.1", "1 : 4.9"]
+ ]
+ }
+ ]
+ },
+ {
+ "id": "docs",
+ "title": "Documents",
+ "lead": "Typical paperwork for a new house; the statuses are an example.",
+ "blocks": [
+ {
+ "type": "list",
+ "items": [
+ { "title": "Land registry extract", "status": "have", "note": "Owner, area and permitted use of the plot" },
+ { "title": "Detailed plan / design conditions", "status": "have", "note": "Setbacks, footprint, height, roof shape" },
+ { "title": "Topographic survey", "status": "in progress", "note": "Base for the site plan and levels" },
+ { "title": "Grid connection agreement", "status": "needed", "note": "Main fuse size, metering point at the boundary" },
+ { "title": "Borehole and treatment plant approval", "status": "needed", "note": "Positions as shown on the plan" },
+ { "title": "Building permit", "status": "later", "note": "Submitted with the main design" },
+ { "title": "Occupancy permit", "status": "later", "note": "After completion and as-built drawings" }
+ ]
+ }
+ ]
+ }
+ ]
+}
diff --git a/public/data/parcel.geojson b/public/data/parcel.geojson
new file mode 100644
index 0000000..dd44c29
--- /dev/null
+++ b/public/data/parcel.geojson
@@ -0,0 +1,128 @@
+{
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "properties": {
+ "role": "parcel",
+ "label": "Lot 12",
+ "note": "30 × 45 m, 1350 m²"
+ },
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [
+ 24.85772793,
+ 59.30016929
+ ],
+ [
+ 24.85726266,
+ 59.30029539
+ ],
+ [
+ 24.85763249,
+ 59.30065232
+ ],
+ [
+ 24.85809776,
+ 59.30052622
+ ],
+ [
+ 24.85772793,
+ 59.30016929
+ ]
+ ]
+ ]
+ }
+ },
+ {
+ "type": "Feature",
+ "properties": {
+ "role": "neighbor",
+ "label": "Lot 11"
+ },
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [
+ 24.85819319,
+ 59.30004319
+ ],
+ [
+ 24.85772793,
+ 59.30016929
+ ],
+ [
+ 24.85809776,
+ 59.30052622
+ ],
+ [
+ 24.85856303,
+ 59.30040012
+ ],
+ [
+ 24.85819319,
+ 59.30004319
+ ]
+ ]
+ ]
+ }
+ },
+ {
+ "type": "Feature",
+ "properties": {
+ "role": "neighbor",
+ "label": "Lot 13"
+ },
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [
+ 24.85726266,
+ 59.30029539
+ ],
+ [
+ 24.8567974,
+ 59.30042148
+ ],
+ [
+ 24.85716722,
+ 59.30077841
+ ],
+ [
+ 24.85763249,
+ 59.30065232
+ ],
+ [
+ 24.85726266,
+ 59.30029539
+ ]
+ ]
+ ]
+ }
+ },
+ {
+ "type": "Feature",
+ "properties": {
+ "role": "street",
+ "label": "Demo Lane"
+ },
+ "geometry": {
+ "type": "LineString",
+ "coordinates": [
+ [
+ 24.85882853,
+ 59.3003688
+ ],
+ [
+ 24.85696746,
+ 59.30087319
+ ]
+ ]
+ }
+ }
+ ]
+}
diff --git a/public/favicon.svg b/public/favicon.svg
new file mode 100644
index 0000000..7b517af
--- /dev/null
+++ b/public/favicon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#f26b1d"/><path d="M8 16 16 9l8 7v8H8z" fill="#fff"/></svg>
diff --git a/public/icons.svg b/public/icons.svg
new file mode 100644
index 0000000..e952219
--- /dev/null
+++ b/public/icons.svg
@@ -0,0 +1,24 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+ <symbol id="bluesky-icon" viewBox="0 0 16 17">
+ <g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
+ <defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
+ </symbol>
+ <symbol id="discord-icon" viewBox="0 0 20 19">
+ <path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
+ </symbol>
+ <symbol id="documentation-icon" viewBox="0 0 21 20">
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
+ </symbol>
+ <symbol id="github-icon" viewBox="0 0 19 19">
+ <path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
+ </symbol>
+ <symbol id="social-icon" viewBox="0 0 20 20">
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
+ <path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
+ </symbol>
+ <symbol id="x-icon" viewBox="0 0 19 19">
+ <path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
+ </symbol>
+</svg>
diff --git a/public/models/furniture/LICENSES.md b/public/models/furniture/LICENSES.md
new file mode 100644
index 0000000..ad455a6
--- /dev/null
+++ b/public/models/furniture/LICENSES.md
@@ -0,0 +1,9 @@
+# Лицензии моделей мебели
+
+Все файлы `*.glb` в этой папке взяты из **Furniture Kit 2.0** от Kenney (www.kenney.nl), скачано 30.09.2026 с https://kenney.nl/assets/furniture-kit.
+
+Лицензия: Creative Commons Zero (CC0 1.0), http://creativecommons.org/publicdomain/zero/1.0/ — свободное использование в личных, учебных и коммерческих проектах, указание авторства не обязательно. Материалы моделей при загрузке заменяются на палитру проекта (src/furniture/materials3d.ts), геометрия не менялась.
+
+Файлы: bathroomSink, bathroomSinkSquare, bathtub, bedDouble, bedSingle, cabinetBedDrawer, cabinetTelevision, chair, chairDesk, coatRack, desk, kitchenCabinet, kitchenCabinetCornerInner, kitchenCabinetDrawer, kitchenCabinetUpper, kitchenFridgeLarge, kitchenSink, kitchenStove, loungeChair, loungeSofa, loungeSofaCorner, pottedPlant, shower, table, tableCoffee, televisionModern, toilet, washer.
+
+Остальные предметы (шкафы, комод, стеллаж, круглый стол, посудомойка, бойлер, котлы, камин, печь, обувница) — процедурные модели из примитивов в src/furniture/procedural.tsx, собственные.
diff --git a/public/models/furniture/bathroomSink.glb b/public/models/furniture/bathroomSink.glb
new file mode 100644
index 0000000..a35d3c1
Binary files /dev/null and b/public/models/furniture/bathroomSink.glb differ
diff --git a/public/models/furniture/bathroomSinkSquare.glb b/public/models/furniture/bathroomSinkSquare.glb
new file mode 100644
index 0000000..867c054
Binary files /dev/null and b/public/models/furniture/bathroomSinkSquare.glb differ
diff --git a/public/models/furniture/bathtub.glb b/public/models/furniture/bathtub.glb
new file mode 100644
index 0000000..ece65b9
Binary files /dev/null and b/public/models/furniture/bathtub.glb differ
diff --git a/public/models/furniture/bedDouble.glb b/public/models/furniture/bedDouble.glb
new file mode 100644
index 0000000..1b0efac
Binary files /dev/null and b/public/models/furniture/bedDouble.glb differ
diff --git a/public/models/furniture/bedSingle.glb b/public/models/furniture/bedSingle.glb
new file mode 100644
index 0000000..eb79d7a
Binary files /dev/null and b/public/models/furniture/bedSingle.glb differ
diff --git a/public/models/furniture/cabinetBedDrawer.glb b/public/models/furniture/cabinetBedDrawer.glb
new file mode 100644
index 0000000..3159b35
Binary files /dev/null and b/public/models/furniture/cabinetBedDrawer.glb differ
diff --git a/public/models/furniture/cabinetTelevision.glb b/public/models/furniture/cabinetTelevision.glb
new file mode 100644
index 0000000..eb73b4c
Binary files /dev/null and b/public/models/furniture/cabinetTelevision.glb differ
diff --git a/public/models/furniture/chair.glb b/public/models/furniture/chair.glb
new file mode 100644
index 0000000..2d57af4
Binary files /dev/null and b/public/models/furniture/chair.glb differ
diff --git a/public/models/furniture/chairDesk.glb b/public/models/furniture/chairDesk.glb
new file mode 100644
index 0000000..131101f
Binary files /dev/null and b/public/models/furniture/chairDesk.glb differ
diff --git a/public/models/furniture/coatRack.glb b/public/models/furniture/coatRack.glb
new file mode 100644
index 0000000..3cddd8b
Binary files /dev/null and b/public/models/furniture/coatRack.glb differ
diff --git a/public/models/furniture/desk.glb b/public/models/furniture/desk.glb
new file mode 100644
index 0000000..8ca1870
Binary files /dev/null and b/public/models/furniture/desk.glb differ
diff --git a/public/models/furniture/kitchenCabinet.glb b/public/models/furniture/kitchenCabinet.glb
new file mode 100644
index 0000000..6292e58
Binary files /dev/null and b/public/models/furniture/kitchenCabinet.glb differ
diff --git a/public/models/furniture/kitchenCabinetCornerInner.glb b/public/models/furniture/kitchenCabinetCornerInner.glb
new file mode 100644
index 0000000..0f2b196
Binary files /dev/null and b/public/models/furniture/kitchenCabinetCornerInner.glb differ
diff --git a/public/models/furniture/kitchenCabinetDrawer.glb b/public/models/furniture/kitchenCabinetDrawer.glb
new file mode 100644
index 0000000..f614bbf
Binary files /dev/null and b/public/models/furniture/kitchenCabinetDrawer.glb differ
diff --git a/public/models/furniture/kitchenCabinetUpper.glb b/public/models/furniture/kitchenCabinetUpper.glb
new file mode 100644
index 0000000..995eaa2
Binary files /dev/null and b/public/models/furniture/kitchenCabinetUpper.glb differ
diff --git a/public/models/furniture/kitchenFridgeLarge.glb b/public/models/furniture/kitchenFridgeLarge.glb
new file mode 100644
index 0000000..4d28fb7
Binary files /dev/null and b/public/models/furniture/kitchenFridgeLarge.glb differ
diff --git a/public/models/furniture/kitchenSink.glb b/public/models/furniture/kitchenSink.glb
new file mode 100644
index 0000000..58daf66
Binary files /dev/null and b/public/models/furniture/kitchenSink.glb differ
diff --git a/public/models/furniture/kitchenStove.glb b/public/models/furniture/kitchenStove.glb
new file mode 100644
index 0000000..264166d
Binary files /dev/null and b/public/models/furniture/kitchenStove.glb differ
diff --git a/public/models/furniture/loungeChair.glb b/public/models/furniture/loungeChair.glb
new file mode 100644
index 0000000..fb3537d
Binary files /dev/null and b/public/models/furniture/loungeChair.glb differ
diff --git a/public/models/furniture/loungeSofa.glb b/public/models/furniture/loungeSofa.glb
new file mode 100644
index 0000000..7761b15
Binary files /dev/null and b/public/models/furniture/loungeSofa.glb differ
diff --git a/public/models/furniture/loungeSofaCorner.glb b/public/models/furniture/loungeSofaCorner.glb
new file mode 100644
index 0000000..6cfc3c9
Binary files /dev/null and b/public/models/furniture/loungeSofaCorner.glb differ
diff --git a/public/models/furniture/pottedPlant.glb b/public/models/furniture/pottedPlant.glb
new file mode 100644
index 0000000..774d659
Binary files /dev/null and b/public/models/furniture/pottedPlant.glb differ
diff --git a/public/models/furniture/shower.glb b/public/models/furniture/shower.glb
new file mode 100644
index 0000000..1182c52
Binary files /dev/null and b/public/models/furniture/shower.glb differ
diff --git a/public/models/furniture/table.glb b/public/models/furniture/table.glb
new file mode 100644
index 0000000..8add1ba
Binary files /dev/null and b/public/models/furniture/table.glb differ
diff --git a/public/models/furniture/tableCoffee.glb b/public/models/furniture/tableCoffee.glb
new file mode 100644
index 0000000..945caf4
Binary files /dev/null and b/public/models/furniture/tableCoffee.glb differ
diff --git a/public/models/furniture/televisionModern.glb b/public/models/furniture/televisionModern.glb
new file mode 100644
index 0000000..f047576
Binary files /dev/null and b/public/models/furniture/televisionModern.glb differ
diff --git a/public/models/furniture/toilet.glb b/public/models/furniture/toilet.glb
new file mode 100644
index 0000000..81589c8
Binary files /dev/null and b/public/models/furniture/toilet.glb differ
diff --git a/public/models/furniture/washer.glb b/public/models/furniture/washer.glb
new file mode 100644
index 0000000..1a5922b
Binary files /dev/null and b/public/models/furniture/washer.glb differ
diff --git a/public/plans/demo.json b/public/plans/demo.json
new file mode 100644
index 0000000..1044f7c
--- /dev/null
+++ b/public/plans/demo.json
@@ -0,0 +1,5411 @@
+{
+ "version": 1,
+ "name": "Demo: Nordic single-storey house with garage",
+ "resetEpoch": 2,
+ "site": {
+ "convention": "y-down-clockwise",
+ "width": 30000,
+ "depth": 45000,
+ "geo": {
+ "lat": 59.30016929,
+ "lng": 24.85772793,
+ "rotationDeg": 152.08
+ },
+ "boundary": [
+ {
+ "x": 0,
+ "y": 0
+ },
+ {
+ "x": 30000,
+ "y": 0
+ },
+ {
+ "x": 30000,
+ "y": 45000
+ },
+ {
+ "x": 0,
+ "y": 45000
+ }
+ ],
+ "zones": [
+ {
+ "id": "zone-lawn",
+ "name": "Lawn",
+ "kind": "lawn",
+ "polygon": [
+ {
+ "x": 500,
+ "y": 500
+ },
+ {
+ "x": 29500,
+ "y": 500
+ },
+ {
+ "x": 29500,
+ "y": 44500
+ },
+ {
+ "x": 500,
+ "y": 44500
+ }
+ ]
+ },
+ {
+ "id": "zone-terrace",
+ "name": "Terrace",
+ "kind": "paving",
+ "polygon": [
+ {
+ "x": 9600,
+ "y": 13800
+ },
+ {
+ "x": 17600,
+ "y": 13800
+ },
+ {
+ "x": 17600,
+ "y": 17000
+ },
+ {
+ "x": 9600,
+ "y": 17000
+ }
+ ]
+ },
+ {
+ "id": "zone-drive",
+ "name": "Driveway",
+ "kind": "paving",
+ "polygon": [
+ {
+ "x": 22000,
+ "y": 38600
+ },
+ {
+ "x": 29000,
+ "y": 38600
+ },
+ {
+ "x": 29000,
+ "y": 45000
+ },
+ {
+ "x": 22000,
+ "y": 45000
+ }
+ ]
+ },
+ {
+ "id": "zone-path",
+ "name": "Front path",
+ "kind": "paving",
+ "polygon": [
+ {
+ "x": 14500,
+ "y": 26600
+ },
+ {
+ "x": 15900,
+ "y": 26600
+ },
+ {
+ "x": 15900,
+ "y": 45000
+ },
+ {
+ "x": 14500,
+ "y": 45000
+ }
+ ]
+ },
+ {
+ "id": "zone-gravel",
+ "name": "Gravel parking",
+ "kind": "fill",
+ "polygon": [
+ {
+ "x": 17000,
+ "y": 40000
+ },
+ {
+ "x": 21500,
+ "y": 40000
+ },
+ {
+ "x": 21500,
+ "y": 45000
+ },
+ {
+ "x": 17000,
+ "y": 45000
+ }
+ ]
+ }
+ ],
+ "street": {
+ "side": [
+ 2,
+ 3
+ ],
+ "note": "Demo Lane"
+ },
+ "imagery": {
+ "offsetE": 0,
+ "offsetN": 0,
+ "rotationDeg": 0
+ },
+ "note": "Demo plot 30 × 45 m in an open field near Kiili, Harju County, Estonia. Fictional lot; street side 2–3 (bottom of the plan) faces the gravel road."
+ },
+ "materials": [
+ {
+ "id": "teploblok-400",
+ "name": "Teploblok 400 × 200 × 400, three-layer block (200 structural + 150 EPS + 50 facade)",
+ "kind": "block",
+ "thickness": 400,
+ "unitLength": 400,
+ "unitHeight": 200,
+ "jointMm": 10,
+ "price": 580,
+ "pricePer": "pcs",
+ "url": "https://teplobloki-sz.ru/teplobloki",
+ "source": "teplobloki-sz.ru, price list",
+ "checkedAt": "2026-09-30",
+ "finish": "plaster",
+ "note": "External walls, painted facade layer"
+ },
+ {
+ "id": "partition-120",
+ "name": "Smart-Block partition block 390 × 120 × 200",
+ "kind": "block",
+ "thickness": 120,
+ "unitLength": 390,
+ "unitHeight": 200,
+ "jointMm": 3,
+ "price": 158,
+ "pricePer": "pcs",
+ "url": "https://xn----7sbe2ajfduoho.xn--p1ai/",
+ "source": "Smart-Block, manufacturer retail price",
+ "checkedAt": "2026-09-30",
+ "note": "Interior partitions, plastered both sides"
+ },
+ {
+ "id": "smartblock-200",
+ "name": "Smart-Block 390 × 200 × 200, concrete-filled (garage)",
+ "kind": "block",
+ "thickness": 200,
+ "unitLength": 390,
+ "unitHeight": 200,
+ "jointMm": 3,
+ "price": 192,
+ "pricePer": "pcs",
+ "url": "https://gssmarket.ru/ryadovoj-blok-390h200h200mm",
+ "source": "GSSMarket, dealer price",
+ "checkedAt": "2026-09-30",
+ "finish": "plaster",
+ "note": "Unheated detached garage"
+ }
+ ],
+ "walls": [
+ {
+ "id": "ext-back",
+ "a": {
+ "x": 4200,
+ "y": 17200
+ },
+ "b": {
+ "x": 19000,
+ "y": 17200
+ },
+ "thickness": 400,
+ "height": 2800,
+ "materialId": "teploblok-400",
+ "note": "Garden facade (south-west)"
+ },
+ {
+ "id": "ext-right",
+ "a": {
+ "x": 19000,
+ "y": 17200
+ },
+ "b": {
+ "x": 19000,
+ "y": 26400
+ },
+ "thickness": 400,
+ "height": 2800,
+ "materialId": "teploblok-400",
+ "note": "Kitchen / utility gable"
+ },
+ {
+ "id": "ext-front",
+ "a": {
+ "x": 19000,
+ "y": 26400
+ },
+ "b": {
+ "x": 4200,
+ "y": 26400
+ },
+ "thickness": 400,
+ "height": 2800,
+ "materialId": "teploblok-400",
+ "note": "Street facade (north-east)"
+ },
+ {
+ "id": "ext-left",
+ "a": {
+ "x": 4200,
+ "y": 26400
+ },
+ "b": {
+ "x": 4200,
+ "y": 17200
+ },
+ "thickness": 400,
+ "height": 2800,
+ "materialId": "teploblok-400",
+ "note": "Bedroom gable"
+ },
+ {
+ "id": "p1",
+ "a": {
+ "x": 8000,
+ "y": 17200
+ },
+ "b": {
+ "x": 8000,
+ "y": 21800
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p2",
+ "a": {
+ "x": 9800,
+ "y": 17200
+ },
+ "b": {
+ "x": 9800,
+ "y": 21800
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p3",
+ "a": {
+ "x": 8000,
+ "y": 19700
+ },
+ "b": {
+ "x": 9800,
+ "y": 19700
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p4",
+ "a": {
+ "x": 4200,
+ "y": 21800
+ },
+ "b": {
+ "x": 19000,
+ "y": 21800
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p5",
+ "a": {
+ "x": 4200,
+ "y": 23000
+ },
+ "b": {
+ "x": 13800,
+ "y": 23000
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p6",
+ "a": {
+ "x": 8000,
+ "y": 23000
+ },
+ "b": {
+ "x": 8000,
+ "y": 26400
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p7",
+ "a": {
+ "x": 11400,
+ "y": 23000
+ },
+ "b": {
+ "x": 11400,
+ "y": 26400
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p8",
+ "a": {
+ "x": 13800,
+ "y": 23000
+ },
+ "b": {
+ "x": 13800,
+ "y": 26400
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p9",
+ "a": {
+ "x": 16400,
+ "y": 21800
+ },
+ "b": {
+ "x": 16400,
+ "y": 26400
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p11",
+ "a": {
+ "x": 13800,
+ "y": 21800
+ },
+ "b": {
+ "x": 13800,
+ "y": 23000
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "p10",
+ "a": {
+ "x": 16400,
+ "y": 24000
+ },
+ "b": {
+ "x": 19000,
+ "y": 24000
+ },
+ "thickness": 120,
+ "height": 2800,
+ "materialId": "partition-120"
+ },
+ {
+ "id": "g-back",
+ "a": {
+ "x": 22100,
+ "y": 32100
+ },
+ "b": {
+ "x": 28900,
+ "y": 32100
+ },
+ "thickness": 200,
+ "height": 2800,
+ "materialId": "smartblock-200"
+ },
+ {
+ "id": "g-right",
+ "a": {
+ "x": 28900,
+ "y": 32100
+ },
+ "b": {
+ "x": 28900,
+ "y": 38500
+ },
+ "thickness": 200,
+ "height": 2800,
+ "materialId": "smartblock-200"
+ },
+ {
+ "id": "g-front",
+ "a": {
+ "x": 28900,
+ "y": 38500
+ },
+ "b": {
+ "x": 22100,
+ "y": 38500
+ },
+ "thickness": 200,
+ "height": 2800,
+ "materialId": "smartblock-200",
+ "note": "Gate wall, faces the street"
+ },
+ {
+ "id": "g-left",
+ "a": {
+ "x": 22100,
+ "y": 38500
+ },
+ "b": {
+ "x": 22100,
+ "y": 32100
+ },
+ "thickness": 200,
+ "height": 2800,
+ "materialId": "smartblock-200"
+ }
+ ],
+ "openings": [
+ {
+ "id": "d-front",
+ "wallId": "ext-front",
+ "type": "door",
+ "offset": 3340,
+ "width": 960,
+ "height": 2100,
+ "sill": 0,
+ "hinge": "start",
+ "side": "right",
+ "note": "Entrance door with thermal break, 960 × 2100"
+ },
+ {
+ "id": "d-terrace",
+ "wallId": "ext-back",
+ "type": "door",
+ "offset": 9800,
+ "width": 1000,
+ "height": 2200,
+ "sill": 0,
+ "hinge": "end",
+ "side": "left",
+ "note": "Glazed terrace door, opens outward"
+ },
+ {
+ "id": "d-lk",
+ "wallId": "p4",
+ "type": "door",
+ "offset": 10600,
+ "width": 900,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "left",
+ "note": "Glazed door hall → living"
+ },
+ {
+ "id": "d-corr",
+ "wallId": "p11",
+ "type": "door",
+ "offset": 150,
+ "width": 900,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "right",
+ "note": "Glazed door hall → bedroom corridor"
+ },
+ {
+ "id": "d-living2",
+ "wallId": "p4",
+ "type": "door",
+ "offset": 8100,
+ "width": 900,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "end",
+ "side": "left",
+ "note": "Glazed door corridor → living"
+ },
+ {
+ "id": "d-master",
+ "wallId": "p4",
+ "type": "door",
+ "offset": 2800,
+ "width": 800,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "end",
+ "side": "left"
+ },
+ {
+ "id": "d-ensuite",
+ "wallId": "p1",
+ "type": "door",
+ "offset": 1100,
+ "width": 700,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "left"
+ },
+ {
+ "id": "d-wic",
+ "wallId": "p1",
+ "type": "door",
+ "offset": 3100,
+ "width": 700,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "end",
+ "side": "left"
+ },
+ {
+ "id": "d-bed2",
+ "wallId": "p5",
+ "type": "door",
+ "offset": 2800,
+ "width": 800,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "end",
+ "side": "right"
+ },
+ {
+ "id": "d-bed3",
+ "wallId": "p5",
+ "type": "door",
+ "offset": 4000,
+ "width": 800,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "right"
+ },
+ {
+ "id": "d-bath",
+ "wallId": "p5",
+ "type": "door",
+ "offset": 7600,
+ "width": 700,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "right"
+ },
+ {
+ "id": "d-pantry",
+ "wallId": "p9",
+ "type": "door",
+ "offset": 500,
+ "width": 800,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "left"
+ },
+ {
+ "id": "d-utility",
+ "wallId": "p9",
+ "type": "door",
+ "offset": 2500,
+ "width": 800,
+ "height": 2000,
+ "sill": 0,
+ "hinge": "start",
+ "side": "left"
+ },
+ {
+ "id": "d-garage",
+ "wallId": "g-left",
+ "type": "door",
+ "offset": 3600,
+ "width": 900,
+ "height": 2100,
+ "sill": 0,
+ "hinge": "start",
+ "side": "right",
+ "note": "Side door towards the house"
+ },
+ {
+ "id": "win-master",
+ "wallId": "ext-back",
+ "type": "window",
+ "offset": 1100,
+ "width": 1800,
+ "height": 1500,
+ "sill": 800
+ },
+ {
+ "id": "win-ensuite",
+ "wallId": "ext-back",
+ "type": "window",
+ "offset": 4550,
+ "width": 600,
+ "height": 600,
+ "sill": 1500
+ },
+ {
+ "id": "win-living",
+ "wallId": "ext-back",
+ "type": "window",
+ "offset": 6200,
+ "width": 2400,
+ "height": 1500,
+ "sill": 700
+ },
+ {
+ "id": "win-dining",
+ "wallId": "ext-back",
+ "type": "window",
+ "offset": 11300,
+ "width": 2000,
+ "height": 1500,
+ "sill": 800
+ },
+ {
+ "id": "win-kitchen",
+ "wallId": "ext-right",
+ "type": "window",
+ "offset": 1300,
+ "width": 1000,
+ "height": 1000,
+ "sill": 1100
+ },
+ {
+ "id": "win-utility",
+ "wallId": "ext-right",
+ "type": "window",
+ "offset": 7700,
+ "width": 600,
+ "height": 600,
+ "sill": 1500
+ },
+ {
+ "id": "win-bath",
+ "wallId": "ext-front",
+ "type": "window",
+ "offset": 5700,
+ "width": 900,
+ "height": 600,
+ "sill": 1500
+ },
+ {
+ "id": "win-bed3",
+ "wallId": "ext-front",
+ "type": "window",
+ "offset": 8300,
+ "width": 1500,
+ "height": 1400,
+ "sill": 800
+ },
+ {
+ "id": "win-bed2",
+ "wallId": "ext-front",
+ "type": "window",
+ "offset": 12300,
+ "width": 1500,
+ "height": 1400,
+ "sill": 800
+ },
+ {
+ "id": "win-bed2-side",
+ "wallId": "ext-left",
+ "type": "window",
+ "offset": 1200,
+ "width": 1000,
+ "height": 1400,
+ "sill": 800
+ },
+ {
+ "id": "win-hall",
+ "wallId": "ext-front",
+ "type": "window",
+ "offset": 2800,
+ "width": 300,
+ "height": 1500,
+ "sill": 600
+ },
+ {
+ "id": "gate-1",
+ "wallId": "g-front",
+ "type": "gate",
+ "offset": 600,
+ "width": 2500,
+ "height": 2250,
+ "sill": 0,
+ "side": "right",
+ "note": "Sectional door 2500 × 2250"
+ },
+ {
+ "id": "gate-2",
+ "wallId": "g-front",
+ "type": "gate",
+ "offset": 3700,
+ "width": 2500,
+ "height": 2250,
+ "sill": 0,
+ "side": "right",
+ "note": "Sectional door 2500 × 2250"
+ },
+ {
+ "id": "win-garage",
+ "wallId": "g-back",
+ "type": "window",
+ "offset": 2900,
+ "width": 1000,
+ "height": 600,
+ "sill": 1500
+ }
+ ],
+ "furniture": [
+ {
+ "id": "f-m-bed",
+ "type": "bed-1600",
+ "x": 5450,
+ "y": 19500,
+ "rotationDeg": 270,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-m-ns1",
+ "type": "nightstand",
+ "x": 4600,
+ "y": 18400,
+ "rotationDeg": 270,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-m-ns2",
+ "type": "nightstand",
+ "x": 4600,
+ "y": 20600,
+ "rotationDeg": 270,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-m-dresser",
+ "type": "dresser",
+ "x": 5300,
+ "y": 21515,
+ "rotationDeg": 180,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-m-chair",
+ "type": "armchair",
+ "x": 7460,
+ "y": 17860,
+ "rotationDeg": 0,
+ "color": "#4b4f54"
+ },
+ {
+ "id": "f-es-shower",
+ "type": "shower",
+ "x": 9290,
+ "y": 17850,
+ "rotationDeg": 0
+ },
+ {
+ "id": "f-es-wc",
+ "type": "toilet",
+ "x": 9400,
+ "y": 19000,
+ "rotationDeg": 90
+ },
+ {
+ "id": "f-es-basin",
+ "type": "washbasin",
+ "x": 8360,
+ "y": 17630,
+ "rotationDeg": 0
+ },
+ {
+ "id": "f-wic-wardrobe",
+ "type": "wardrobe",
+ "x": 9440,
+ "y": 20750,
+ "rotationDeg": 90,
+ "w": 1800,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-k-fridge",
+ "type": "fridge",
+ "x": 18475,
+ "y": 17700,
+ "rotationDeg": 90
+ },
+ {
+ "id": "f-k-base1",
+ "type": "kitchen-base",
+ "x": 18500,
+ "y": 18300,
+ "rotationDeg": 90,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-k-sink",
+ "type": "kitchen-sink",
+ "x": 18500,
+ "y": 19000,
+ "rotationDeg": 90,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-k-dw",
+ "type": "dishwasher",
+ "x": 18500,
+ "y": 19700,
+ "rotationDeg": 90
+ },
+ {
+ "id": "f-k-stove",
+ "type": "stove",
+ "x": 18500,
+ "y": 20300,
+ "rotationDeg": 90
+ },
+ {
+ "id": "f-k-drawers",
+ "type": "kitchen-drawers",
+ "x": 18500,
+ "y": 20900,
+ "rotationDeg": 90,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-k-base2",
+ "type": "kitchen-base",
+ "x": 18500,
+ "y": 21470,
+ "rotationDeg": 90,
+ "w": 540,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-k-upper",
+ "type": "kitchen-upper",
+ "x": 18635,
+ "y": 20600,
+ "rotationDeg": 90,
+ "w": 1200,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-dining",
+ "type": "dining-6",
+ "x": 16200,
+ "y": 19400,
+ "rotationDeg": 0,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-tv",
+ "type": "tv-stand",
+ "x": 10070,
+ "y": 19500,
+ "rotationDeg": 270,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-sofa",
+ "type": "sofa",
+ "x": 13100,
+ "y": 19500,
+ "rotationDeg": 90,
+ "color": "#8a9099"
+ },
+ {
+ "id": "f-coffee",
+ "type": "coffee-table",
+ "x": 11450,
+ "y": 19500,
+ "rotationDeg": 90,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-books",
+ "type": "bookcase",
+ "x": 11000,
+ "y": 21565,
+ "rotationDeg": 180,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-plant1",
+ "type": "plant",
+ "x": 10200,
+ "y": 17750,
+ "rotationDeg": 0
+ },
+ {
+ "id": "f-h-wardrobe",
+ "type": "hall-wardrobe",
+ "x": 14160,
+ "y": 24400,
+ "rotationDeg": 270,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-h-shoes",
+ "type": "shoe-cabinet",
+ "x": 16180,
+ "y": 25700,
+ "rotationDeg": 90,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-b2-bed",
+ "type": "bed-1600",
+ "x": 5750,
+ "y": 24110,
+ "rotationDeg": 0,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-b2-ns",
+ "type": "nightstand",
+ "x": 4625,
+ "y": 23260,
+ "rotationDeg": 0,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-b2-wardrobe",
+ "type": "wardrobe",
+ "x": 7640,
+ "y": 25650,
+ "rotationDeg": 90,
+ "w": 1000,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-b2-plant",
+ "type": "plant",
+ "x": 4650,
+ "y": 25950,
+ "rotationDeg": 0
+ },
+ {
+ "id": "f-b3-bed",
+ "type": "bed-1600",
+ "x": 10000,
+ "y": 24110,
+ "rotationDeg": 0,
+ "color": "#e8e2d6"
+ },
+ {
+ "id": "f-b3-ns",
+ "type": "nightstand",
+ "x": 11115,
+ "y": 23260,
+ "rotationDeg": 0,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-b3-wardrobe",
+ "type": "wardrobe",
+ "x": 8360,
+ "y": 25650,
+ "rotationDeg": 270,
+ "w": 1000,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-ba-tub",
+ "type": "bathtub",
+ "x": 12310,
+ "y": 25825,
+ "rotationDeg": 180
+ },
+ {
+ "id": "f-ba-wc",
+ "type": "toilet",
+ "x": 13400,
+ "y": 24300,
+ "rotationDeg": 90
+ },
+ {
+ "id": "f-ba-vanity",
+ "type": "vanity",
+ "x": 11700,
+ "y": 24300,
+ "rotationDeg": 270,
+ "color": "#c9a27a"
+ },
+ {
+ "id": "f-p-shelf",
+ "type": "bookcase",
+ "x": 18625,
+ "y": 22900,
+ "rotationDeg": 90,
+ "w": 1800,
+ "color": "#e8e2d6",
+ "note": "Pantry shelving"
+ },
+ {
+ "id": "f-u-hp",
+ "type": "floor-boiler",
+ "x": 18475,
+ "y": 24500,
+ "rotationDeg": 90,
+ "note": "Air-to-water heat pump, indoor unit"
+ },
+ {
+ "id": "f-u-washer",
+ "type": "washer",
+ "x": 18350,
+ "y": 25900,
+ "rotationDeg": 180
+ },
+ {
+ "id": "f-u-heater",
+ "type": "water-heater",
+ "x": 17200,
+ "y": 24295,
+ "rotationDeg": 0,
+ "note": "Electric water heater, 80 L"
+ },
+ {
+ "id": "f-g-bench",
+ "type": "desk",
+ "x": 24200,
+ "y": 32500,
+ "rotationDeg": 0,
+ "w": 1600,
+ "color": "#c9a27a",
+ "note": "Workbench"
+ }
+ ],
+ "rooms": [
+ {
+ "id": "r-living",
+ "name": "Living / Kitchen",
+ "kind": "living",
+ "x": 11800,
+ "y": 21000
+ },
+ {
+ "id": "r-master",
+ "name": "Master bedroom",
+ "kind": "bedroom",
+ "x": 6100,
+ "y": 17950
+ },
+ {
+ "id": "r-ensuite",
+ "name": "En-suite",
+ "kind": "bath",
+ "x": 8600,
+ "y": 19250
+ },
+ {
+ "id": "r-wic",
+ "name": "Walk-in closet",
+ "kind": "storage",
+ "x": 8600,
+ "y": 21350
+ },
+ {
+ "id": "r-hall",
+ "name": "Hall",
+ "kind": "hall",
+ "x": 15100,
+ "y": 22500
+ },
+ {
+ "id": "r-corridor",
+ "name": "Corridor",
+ "kind": "hall",
+ "x": 10800,
+ "y": 22400
+ },
+ {
+ "id": "r-bed2",
+ "name": "Bedroom 2",
+ "kind": "bedroom",
+ "x": 6150,
+ "y": 25750
+ },
+ {
+ "id": "r-bed3",
+ "name": "Bedroom 3",
+ "kind": "bedroom",
+ "x": 9500,
+ "y": 25750
+ },
+ {
+ "id": "r-bath",
+ "name": "Bathroom",
+ "kind": "bath",
+ "x": 12600,
+ "y": 23300
+ },
+ {
+ "id": "r-pantry",
+ "name": "Pantry",
+ "kind": "storage",
+ "x": 17200,
+ "y": 22300
+ },
+ {
+ "id": "r-utility",
+ "name": "Utility / Boiler",
+ "kind": "tech",
+ "x": 17300,
+ "y": 25200
+ },
+ {
+ "id": "r-garage",
+ "name": "Garage",
+ "kind": "garage",
+ "x": 25500,
+ "y": 35300
+ }
+ ],
+ "palette": {
+ "name": "Nordic white",
+ "walls": "RAL 9010",
+ "accent": "RAL 7016",
+ "roof": "RAL 7016",
+ "windows": "RAL 7016",
+ "gates": "RAL 7016",
+ "plinth": "RAL 7016"
+ },
+ "estimate": {
+ "lines": [
+ {
+ "id": "l-slab",
+ "name": "Insulated slab foundation, house 15.2 × 9.6 m, turnkey",
+ "category": "фундамент",
+ "qty": 146,
+ "unit": "m²",
+ "price": 5500,
+ "url": "https://top-fundament.ru/fundamenty/fundament-ushp",
+ "note": "Starting price per m² of slab"
+ },
+ {
+ "id": "l-garage-slab",
+ "name": "Garage slab on grade 7.0 × 6.6 m",
+ "category": "фундамент",
+ "qty": 46,
+ "unit": "m²",
+ "price": 3000,
+ "url": "https://sankt-peterburg.svaifund.ru/fundament-ushp/"
+ },
+ {
+ "id": "l-terrace",
+ "name": "Terrace paving on gravel base, 8.0 × 3.2 m",
+ "category": "прочее",
+ "qty": 25.6,
+ "unit": "m²"
+ },
+ {
+ "id": "l-drive",
+ "name": "Driveway and front path, concrete pavers",
+ "category": "прочее",
+ "qty": 70,
+ "unit": "m²"
+ },
+ {
+ "id": "l-roof",
+ "name": "Standing-seam steel roof, RAL 7016",
+ "category": "кровля",
+ "qty": 210,
+ "unit": "m²",
+ "note": "House and garage incl. overhangs"
+ },
+ {
+ "id": "l-paint",
+ "name": "Facade paint, RAL 9010, two coats",
+ "category": "прочее",
+ "qty": 190,
+ "unit": "m²"
+ },
+ {
+ "id": "l-masonry",
+ "name": "Masonry labour: external walls and partitions",
+ "category": "работы",
+ "qty": 1,
+ "unit": "lot",
+ "note": "Ask local contractors for a quote"
+ }
+ ],
+ "purchases": {},
+ "wasteSipPct": 5,
+ "notes": [
+ "All quantities are generated from the plan; prices are examples, check them before ordering.",
+ "Foundation: insulated slab with underfloor heating pipes in the screed.",
+ "Garage is unheated; the power cable runs underground in a duct.",
+ "Septic and borehole positions follow the 50 m separation rule."
+ ]
+ },
+ "networks": {
+ "sewer": {
+ "floorLevel": 450,
+ "nodes": [
+ {
+ "id": "s-es-shower",
+ "x": 9290,
+ "y": 17850,
+ "kind": "fixture",
+ "fixture": "shower",
+ "furnitureId": "f-es-shower",
+ "label": "En-suite shower"
+ },
+ {
+ "id": "s-es-basin",
+ "x": 8360,
+ "y": 17550,
+ "kind": "fixture",
+ "fixture": "sink",
+ "furnitureId": "f-es-basin",
+ "label": "En-suite basin"
+ },
+ {
+ "id": "s-es-wc",
+ "x": 9590,
+ "y": 19000,
+ "kind": "fixture",
+ "fixture": "toilet",
+ "furnitureId": "f-es-wc",
+ "label": "En-suite WC"
+ },
+ {
+ "id": "s-t1",
+ "x": 9600,
+ "y": 19300,
+ "kind": "junction",
+ "label": "Tee 45°"
+ },
+ {
+ "id": "s-c1",
+ "x": 9600,
+ "y": 21900,
+ "kind": "junction",
+ "label": "Bend 45°"
+ },
+ {
+ "id": "s-c2",
+ "x": 10100,
+ "y": 22400,
+ "kind": "junction",
+ "label": "Bend 45°"
+ },
+ {
+ "id": "s-c3",
+ "x": 12900,
+ "y": 22400,
+ "kind": "junction",
+ "label": "Bend 45°"
+ },
+ {
+ "id": "s-c4",
+ "x": 13600,
+ "y": 23100,
+ "kind": "junction",
+ "label": "Bend 45°"
+ },
+ {
+ "id": "s-ba-wc",
+ "x": 13400,
+ "y": 24300,
+ "kind": "fixture",
+ "fixture": "toilet",
+ "furnitureId": "f-ba-wc",
+ "label": "Bathroom WC"
+ },
+ {
+ "id": "s-ba-basin",
+ "x": 11600,
+ "y": 24300,
+ "kind": "fixture",
+ "fixture": "sink",
+ "furnitureId": "f-ba-vanity",
+ "label": "Bathroom basin"
+ },
+ {
+ "id": "s-ba-tub",
+ "x": 12310,
+ "y": 25825,
+ "kind": "fixture",
+ "fixture": "bath",
+ "furnitureId": "f-ba-tub",
+ "label": "Bathtub"
+ },
+ {
+ "id": "s-riser",
+ "x": 13600,
+ "y": 26000,
+ "kind": "riser",
+ "height": 4000,
+ "label": "Soil stack Ø110, vented through the roof"
+ },
+ {
+ "id": "s-k-sink",
+ "x": 18600,
+ "y": 19000,
+ "kind": "fixture",
+ "fixture": "kitchen",
+ "furnitureId": "f-k-sink",
+ "label": "Kitchen sink"
+ },
+ {
+ "id": "s-k-dw",
+ "x": 18300,
+ "y": 19700,
+ "kind": "fixture",
+ "fixture": "kitchen",
+ "furnitureId": "f-k-dw",
+ "label": "Dishwasher"
+ },
+ {
+ "id": "s-k1",
+ "x": 18600,
+ "y": 19700,
+ "kind": "junction",
+ "label": "Tee 45°"
+ },
+ {
+ "id": "s-u-hp",
+ "x": 18300,
+ "y": 24900,
+ "kind": "fixture",
+ "fixture": "boiler",
+ "furnitureId": "f-u-hp",
+ "label": "Heat pump safety valve drain"
+ },
+ {
+ "id": "s-u-washer",
+ "x": 18350,
+ "y": 25700,
+ "kind": "fixture",
+ "fixture": "washer",
+ "furnitureId": "f-u-washer",
+ "label": "Washing machine"
+ },
+ {
+ "id": "s-u1",
+ "x": 18600,
+ "y": 25300,
+ "kind": "junction",
+ "label": "Tee 45°"
+ },
+ {
+ "id": "s-u2",
+ "x": 17900,
+ "y": 26000,
+ "kind": "junction",
+ "label": "Bend 45°"
+ },
+ {
+ "id": "s-out",
+ "x": 13600,
+ "y": 26600,
+ "kind": "outlet",
+ "label": "Outlet through the foundation in a sleeve"
+ },
+ {
+ "id": "s-o1",
+ "x": 13600,
+ "y": 27600,
+ "kind": "cleanout",
+ "label": "Inspection chamber"
+ },
+ {
+ "id": "s-septic",
+ "x": 2200,
+ "y": 43300,
+ "kind": "septic",
+ "model": "Compact treatment plant, 5 PE",
+ "w": 1200,
+ "d": 1200,
+ "rotationDeg": 0,
+ "label": "Treatment plant"
+ }
+ ],
+ "pipes": [
+ {
+ "id": "sp1",
+ "from": "s-es-shower",
+ "to": "s-t1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp2",
+ "from": "s-es-basin",
+ "to": "s-t1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp3",
+ "from": "s-es-wc",
+ "to": "s-t1",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp4",
+ "from": "s-t1",
+ "to": "s-c1",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp5",
+ "from": "s-c1",
+ "to": "s-c2",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp6",
+ "from": "s-c2",
+ "to": "s-c3",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp7",
+ "from": "s-c3",
+ "to": "s-c4",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp8",
+ "from": "s-c4",
+ "to": "s-riser",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp9",
+ "from": "s-ba-wc",
+ "to": "s-riser",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp10",
+ "from": "s-ba-basin",
+ "to": "s-riser",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp11",
+ "from": "s-ba-tub",
+ "to": "s-riser",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp12",
+ "from": "s-k-sink",
+ "to": "s-k1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp13",
+ "from": "s-k-dw",
+ "to": "s-k1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp14",
+ "from": "s-k1",
+ "to": "s-u1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp15",
+ "from": "s-u-hp",
+ "to": "s-u1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp16",
+ "from": "s-u-washer",
+ "to": "s-u1",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp17",
+ "from": "s-u1",
+ "to": "s-u2",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp18",
+ "from": "s-u2",
+ "to": "s-riser",
+ "diameter": 50,
+ "slope": 3,
+ "location": "inside"
+ },
+ {
+ "id": "sp19",
+ "from": "s-riser",
+ "to": "s-out",
+ "diameter": 110,
+ "slope": 2,
+ "location": "inside"
+ },
+ {
+ "id": "sp20",
+ "from": "s-out",
+ "to": "s-o1",
+ "diameter": 110,
+ "slope": 2,
+ "location": "outside",
+ "depth": 1200
+ },
+ {
+ "id": "sp21",
+ "from": "s-o1",
+ "to": "s-septic",
+ "diameter": 110,
+ "slope": 2,
+ "location": "outside"
+ }
+ ]
+ },
+ "water": {
+ "nodes": [
+ {
+ "id": "w-src",
+ "x": 29200,
+ "y": 800,
+ "kind": "source",
+ "source": "borehole",
+ "label": "Borehole, 50 m from the treatment plant"
+ },
+ {
+ "id": "w-j1",
+ "x": 21000,
+ "y": 25000,
+ "kind": "junction",
+ "label": "Turn to the house"
+ },
+ {
+ "id": "w-entry",
+ "x": 19000,
+ "y": 25000,
+ "kind": "entry",
+ "label": "Entry in a Ø50 sleeve below frost depth"
+ },
+ {
+ "id": "w-pump",
+ "x": 18500,
+ "y": 25000,
+ "kind": "pump",
+ "model": "Pressure tank 50 L + pressure switch",
+ "label": "Hydrophore"
+ },
+ {
+ "id": "w-filter",
+ "x": 18050,
+ "y": 25000,
+ "kind": "filter",
+ "label": "Sediment + 20\" cartridge filter"
+ },
+ {
+ "id": "w-cold",
+ "x": 17600,
+ "y": 25000,
+ "kind": "collector",
+ "line": "cold",
+ "outputs": 11,
+ "label": "Cold manifold"
+ },
+ {
+ "id": "w-heater",
+ "x": 17200,
+ "y": 24300,
+ "kind": "boiler",
+ "furnitureId": "f-u-heater",
+ "model": "80 L",
+ "label": "Water heater"
+ },
+ {
+ "id": "w-hot",
+ "x": 16900,
+ "y": 24700,
+ "kind": "collector",
+ "line": "hot",
+ "outputs": 5,
+ "label": "Hot manifold"
+ },
+ {
+ "id": "w-tap",
+ "x": 15200,
+ "y": 17000,
+ "kind": "tap_outdoor",
+ "label": "Frost-free garden tap on the terrace"
+ },
+ {
+ "id": "w-k-sink",
+ "x": 18500,
+ "y": 19000,
+ "kind": "fixture",
+ "fixture": "kitchen",
+ "furnitureId": "f-k-sink",
+ "label": "Kitchen sink"
+ },
+ {
+ "id": "w-k-dw",
+ "x": 18500,
+ "y": 19700,
+ "kind": "fixture",
+ "fixture": "kitchen",
+ "furnitureId": "f-k-dw",
+ "label": "Dishwasher"
+ },
+ {
+ "id": "w-u-washer",
+ "x": 18350,
+ "y": 25800,
+ "kind": "fixture",
+ "fixture": "washer",
+ "furnitureId": "f-u-washer",
+ "label": "Washing machine"
+ },
+ {
+ "id": "w-ba-wc",
+ "x": 13500,
+ "y": 24300,
+ "kind": "fixture",
+ "fixture": "toilet",
+ "furnitureId": "f-ba-wc",
+ "label": "Bathroom WC"
+ },
+ {
+ "id": "w-ba-basin",
+ "x": 11600,
+ "y": 24300,
+ "kind": "fixture",
+ "fixture": "sink",
+ "furnitureId": "f-ba-vanity",
+ "label": "Bathroom basin"
+ },
+ {
+ "id": "w-ba-tub",
+ "x": 12310,
+ "y": 25700,
+ "kind": "fixture",
+ "fixture": "bath",
+ "furnitureId": "f-ba-tub",
+ "label": "Bathtub"
+ },
+ {
+ "id": "w-es-wc",
+ "x": 9500,
+ "y": 19000,
+ "kind": "fixture",
+ "fixture": "toilet",
+ "furnitureId": "f-es-wc",
+ "label": "En-suite WC"
+ },
+ {
+ "id": "w-es-basin",
+ "x": 8360,
+ "y": 17600,
+ "kind": "fixture",
+ "fixture": "sink",
+ "furnitureId": "f-es-basin",
+ "label": "En-suite basin"
+ },
+ {
+ "id": "w-es-shower",
+ "x": 9290,
+ "y": 17850,
+ "kind": "fixture",
+ "fixture": "shower",
+ "furnitureId": "f-es-shower",
+ "label": "En-suite shower"
+ },
+ {
+ "id": "wc-k-sink-a",
+ "x": 17560,
+ "y": 22300,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-k-sink-b",
+ "x": 18350,
+ "y": 22300,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-k-sink-a",
+ "x": 16830,
+ "y": 22345,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-k-sink-b",
+ "x": 18350,
+ "y": 22345,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-k-dw-a",
+ "x": 17500,
+ "y": 22390,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-k-dw-b",
+ "x": 18350,
+ "y": 22390,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-wc-a",
+ "x": 17470,
+ "y": 22435,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-wc-b",
+ "x": 13650,
+ "y": 22435,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-basin-a",
+ "x": 17440,
+ "y": 22480,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-basin-b",
+ "x": 11750,
+ "y": 22480,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-ba-basin-a",
+ "x": 16710,
+ "y": 22525,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-ba-basin-b",
+ "x": 11750,
+ "y": 22525,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-tub-a",
+ "x": 17380,
+ "y": 22570,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-ba-tub-b",
+ "x": 12460,
+ "y": 22570,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-ba-tub-a",
+ "x": 16650,
+ "y": 22615,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-ba-tub-b",
+ "x": 12460,
+ "y": 22615,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-wc-a",
+ "x": 17320,
+ "y": 22660,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-wc-b",
+ "x": 9650,
+ "y": 22660,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-basin-a",
+ "x": 17290,
+ "y": 22705,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-basin-b",
+ "x": 8510,
+ "y": 22705,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-es-basin-a",
+ "x": 16560,
+ "y": 22750,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-es-basin-b",
+ "x": 8510,
+ "y": 22750,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-shower-a",
+ "x": 17230,
+ "y": 22795,
+ "kind": "junction"
+ },
+ {
+ "id": "wc-es-shower-b",
+ "x": 9440,
+ "y": 22795,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-es-shower-a",
+ "x": 16500,
+ "y": 22840,
+ "kind": "junction"
+ },
+ {
+ "id": "wh-es-shower-b",
+ "x": 9440,
+ "y": 22840,
+ "kind": "junction"
+ },
+ {
+ "id": "w-tap-a",
+ "x": 15200,
+ "y": 23600,
+ "kind": "junction"
+ }
+ ],
+ "pipes": [
+ {
+ "id": "wp-src",
+ "from": "w-src",
+ "to": "w-j1",
+ "line": "cold",
+ "diameter": 32,
+ "material": "PE",
+ "location": "outside",
+ "depth": 1800
+ },
+ {
+ "id": "wp-in",
+ "from": "w-j1",
+ "to": "w-entry",
+ "line": "cold",
+ "diameter": 32,
+ "material": "PE",
+ "location": "outside",
+ "depth": 1800
+ },
+ {
+ "id": "wp-pump",
+ "from": "w-entry",
+ "to": "w-pump",
+ "line": "cold",
+ "diameter": 25,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wp-filter",
+ "from": "w-pump",
+ "to": "w-filter",
+ "line": "cold",
+ "diameter": 25,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wp-cold",
+ "from": "w-filter",
+ "to": "w-cold",
+ "line": "cold",
+ "diameter": 25,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wp-heater",
+ "from": "w-cold",
+ "to": "w-heater",
+ "line": "cold",
+ "diameter": 20,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wp-hot",
+ "from": "w-heater",
+ "to": "w-hot",
+ "line": "hot",
+ "diameter": 20,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-sink-1",
+ "from": "w-cold",
+ "to": "wc-k-sink-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-sink-2",
+ "from": "wc-k-sink-a",
+ "to": "wc-k-sink-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-sink-3",
+ "from": "wc-k-sink-b",
+ "to": "w-k-sink",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-k-sink-1",
+ "from": "w-hot",
+ "to": "wh-k-sink-a",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-k-sink-2",
+ "from": "wh-k-sink-a",
+ "to": "wh-k-sink-b",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-k-sink-3",
+ "from": "wh-k-sink-b",
+ "to": "w-k-sink",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-dw-1",
+ "from": "w-cold",
+ "to": "wc-k-dw-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-dw-2",
+ "from": "wc-k-dw-a",
+ "to": "wc-k-dw-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-k-dw-3",
+ "from": "wc-k-dw-b",
+ "to": "w-k-dw",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wl-washer",
+ "from": "w-cold",
+ "to": "w-u-washer",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-wc-1",
+ "from": "w-cold",
+ "to": "wc-ba-wc-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-wc-2",
+ "from": "wc-ba-wc-a",
+ "to": "wc-ba-wc-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-wc-3",
+ "from": "wc-ba-wc-b",
+ "to": "w-ba-wc",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-basin-1",
+ "from": "w-cold",
+ "to": "wc-ba-basin-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-basin-2",
+ "from": "wc-ba-basin-a",
+ "to": "wc-ba-basin-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-basin-3",
+ "from": "wc-ba-basin-b",
+ "to": "w-ba-basin",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-basin-1",
+ "from": "w-hot",
+ "to": "wh-ba-basin-a",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-basin-2",
+ "from": "wh-ba-basin-a",
+ "to": "wh-ba-basin-b",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-basin-3",
+ "from": "wh-ba-basin-b",
+ "to": "w-ba-basin",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-tub-1",
+ "from": "w-cold",
+ "to": "wc-ba-tub-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-tub-2",
+ "from": "wc-ba-tub-a",
+ "to": "wc-ba-tub-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-ba-tub-3",
+ "from": "wc-ba-tub-b",
+ "to": "w-ba-tub",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-tub-1",
+ "from": "w-hot",
+ "to": "wh-ba-tub-a",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-tub-2",
+ "from": "wh-ba-tub-a",
+ "to": "wh-ba-tub-b",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-ba-tub-3",
+ "from": "wh-ba-tub-b",
+ "to": "w-ba-tub",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-wc-1",
+ "from": "w-cold",
+ "to": "wc-es-wc-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-wc-2",
+ "from": "wc-es-wc-a",
+ "to": "wc-es-wc-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-wc-3",
+ "from": "wc-es-wc-b",
+ "to": "w-es-wc",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-basin-1",
+ "from": "w-cold",
+ "to": "wc-es-basin-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-basin-2",
+ "from": "wc-es-basin-a",
+ "to": "wc-es-basin-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-basin-3",
+ "from": "wc-es-basin-b",
+ "to": "w-es-basin",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-basin-1",
+ "from": "w-hot",
+ "to": "wh-es-basin-a",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-basin-2",
+ "from": "wh-es-basin-a",
+ "to": "wh-es-basin-b",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-basin-3",
+ "from": "wh-es-basin-b",
+ "to": "w-es-basin",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-shower-1",
+ "from": "w-cold",
+ "to": "wc-es-shower-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-shower-2",
+ "from": "wc-es-shower-a",
+ "to": "wc-es-shower-b",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wc-es-shower-3",
+ "from": "wc-es-shower-b",
+ "to": "w-es-shower",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-shower-1",
+ "from": "w-hot",
+ "to": "wh-es-shower-a",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-shower-2",
+ "from": "wh-es-shower-a",
+ "to": "wh-es-shower-b",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wh-es-shower-3",
+ "from": "wh-es-shower-b",
+ "to": "w-es-shower",
+ "line": "hot",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wl-tap-1",
+ "from": "w-cold",
+ "to": "w-tap-a",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ },
+ {
+ "id": "wl-tap-2",
+ "from": "w-tap-a",
+ "to": "w-tap",
+ "line": "cold",
+ "diameter": 16,
+ "material": "PEX",
+ "location": "inside"
+ }
+ ]
+ },
+ "electric": {
+ "panel": {
+ "id": "panel",
+ "x": 16340,
+ "y": 23600,
+ "wallId": "p9",
+ "modules": 48
+ },
+ "points": [
+ {
+ "id": "ep1",
+ "kind": "light",
+ "x": 6170,
+ "y": 19570,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Master bedroom"
+ },
+ {
+ "id": "ep2",
+ "kind": "light",
+ "x": 8900,
+ "y": 18520,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "En-suite"
+ },
+ {
+ "id": "ep3",
+ "kind": "light",
+ "x": 8900,
+ "y": 20750,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Walk-in closet"
+ },
+ {
+ "id": "ep4",
+ "kind": "light",
+ "x": 6200,
+ "y": 22400,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Corridor"
+ },
+ {
+ "id": "ep5",
+ "kind": "light",
+ "x": 10600,
+ "y": 22400,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Corridor"
+ },
+ {
+ "id": "ep6",
+ "kind": "light",
+ "x": 6170,
+ "y": 24630,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Bedroom 2"
+ },
+ {
+ "id": "ep7",
+ "kind": "light",
+ "x": 9700,
+ "y": 24630,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Bedroom 3"
+ },
+ {
+ "id": "ep8",
+ "kind": "light",
+ "x": 12600,
+ "y": 24630,
+ "height": 2800,
+ "circuitId": "c-l1",
+ "label": "Bathroom"
+ },
+ {
+ "id": "ep9",
+ "kind": "switch",
+ "x": 6850,
+ "y": 21740,
+ "height": 900,
+ "wallId": "p4",
+ "circuitId": "c-l1"
+ },
+ {
+ "id": "ep10",
+ "kind": "switch",
+ "x": 7940,
+ "y": 19150,
+ "height": 900,
+ "wallId": "p1",
+ "circuitId": "c-l1",
+ "label": "En-suite (outside the door)"
+ },
+ {
+ "id": "ep11",
+ "kind": "switch",
+ "x": 7940,
+ "y": 20150,
+ "height": 900,
+ "wallId": "p1",
+ "circuitId": "c-l1",
+ "label": "Walk-in closet"
+ },
+ {
+ "id": "ep12",
+ "kind": "switch",
+ "x": 6850,
+ "y": 23060,
+ "height": 900,
+ "wallId": "p5",
+ "circuitId": "c-l1"
+ },
+ {
+ "id": "ep13",
+ "kind": "switch",
+ "x": 9150,
+ "y": 23060,
+ "height": 900,
+ "wallId": "p5",
+ "circuitId": "c-l1"
+ },
+ {
+ "id": "ep14",
+ "kind": "switch",
+ "x": 12650,
+ "y": 22940,
+ "height": 900,
+ "wallId": "p5",
+ "circuitId": "c-l1",
+ "label": "Bathroom (outside the door)"
+ },
+ {
+ "id": "ep15",
+ "kind": "switch2",
+ "x": 6200,
+ "y": 21860,
+ "height": 900,
+ "wallId": "p4",
+ "circuitId": "c-l1",
+ "label": "Corridor"
+ },
+ {
+ "id": "ep16",
+ "kind": "light",
+ "x": 11700,
+ "y": 19500,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Living"
+ },
+ {
+ "id": "ep17",
+ "kind": "light",
+ "x": 16200,
+ "y": 19400,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Dining"
+ },
+ {
+ "id": "ep18",
+ "kind": "light",
+ "x": 17700,
+ "y": 19400,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Kitchen"
+ },
+ {
+ "id": "ep19",
+ "kind": "light",
+ "x": 15100,
+ "y": 22800,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Hall"
+ },
+ {
+ "id": "ep20",
+ "kind": "light",
+ "x": 15100,
+ "y": 25000,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Entrance"
+ },
+ {
+ "id": "ep21",
+ "kind": "light",
+ "x": 17630,
+ "y": 22900,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Pantry"
+ },
+ {
+ "id": "ep22",
+ "kind": "light",
+ "x": 17630,
+ "y": 25130,
+ "height": 2800,
+ "circuitId": "c-l2",
+ "label": "Utility"
+ },
+ {
+ "id": "ep23",
+ "kind": "switch2",
+ "x": 15850,
+ "y": 21740,
+ "height": 900,
+ "wallId": "p4",
+ "circuitId": "c-l2",
+ "label": "Living / dining"
+ },
+ {
+ "id": "ep24",
+ "kind": "switch",
+ "x": 16000,
+ "y": 21740,
+ "height": 900,
+ "wallId": "p4",
+ "circuitId": "c-l2",
+ "label": "Kitchen"
+ },
+ {
+ "id": "ep25",
+ "kind": "switch2",
+ "x": 14550,
+ "y": 26200,
+ "height": 900,
+ "wallId": "ext-front",
+ "circuitId": "c-l2",
+ "label": "Hall / entrance"
+ },
+ {
+ "id": "ep26",
+ "kind": "switch",
+ "x": 16340,
+ "y": 23250,
+ "height": 900,
+ "wallId": "p9",
+ "circuitId": "c-l2",
+ "label": "Pantry (outside the door)"
+ },
+ {
+ "id": "ep27",
+ "kind": "switch",
+ "x": 16340,
+ "y": 25250,
+ "height": 900,
+ "wallId": "p9",
+ "circuitId": "c-l2",
+ "label": "Utility (outside the door)"
+ },
+ {
+ "id": "ep28",
+ "kind": "socket2",
+ "x": 9860,
+ "y": 19000,
+ "height": 300,
+ "wallId": "p2",
+ "circuitId": "c-s1",
+ "label": "TV"
+ },
+ {
+ "id": "ep29",
+ "kind": "socket2",
+ "x": 9860,
+ "y": 20000,
+ "height": 300,
+ "wallId": "p2",
+ "circuitId": "c-s1",
+ "label": "TV"
+ },
+ {
+ "id": "ep30",
+ "kind": "socket",
+ "x": 10500,
+ "y": 17400,
+ "height": 300,
+ "wallId": "ext-back",
+ "circuitId": "c-s1"
+ },
+ {
+ "id": "ep31",
+ "kind": "socket",
+ "x": 13300,
+ "y": 17400,
+ "height": 300,
+ "wallId": "ext-back",
+ "circuitId": "c-s1",
+ "label": "Sofa"
+ },
+ {
+ "id": "ep32",
+ "kind": "socket",
+ "x": 12000,
+ "y": 21740,
+ "height": 300,
+ "wallId": "p4",
+ "circuitId": "c-s1"
+ },
+ {
+ "id": "ep33",
+ "kind": "socket",
+ "x": 13800,
+ "y": 21740,
+ "height": 300,
+ "wallId": "p4",
+ "circuitId": "c-s1"
+ },
+ {
+ "id": "ep34",
+ "kind": "socket",
+ "x": 17800,
+ "y": 17400,
+ "height": 300,
+ "wallId": "ext-back",
+ "circuitId": "c-s1",
+ "label": "Dining"
+ },
+ {
+ "id": "ep35",
+ "kind": "socket2",
+ "x": 18800,
+ "y": 18300,
+ "height": 1100,
+ "wallId": "ext-right",
+ "circuitId": "c-s2",
+ "label": "Worktop"
+ },
+ {
+ "id": "ep36",
+ "kind": "socket2",
+ "x": 18800,
+ "y": 20900,
+ "height": 1100,
+ "wallId": "ext-right",
+ "circuitId": "c-s2",
+ "label": "Worktop"
+ },
+ {
+ "id": "ep37",
+ "kind": "socket2",
+ "x": 18800,
+ "y": 21450,
+ "height": 1100,
+ "wallId": "ext-right",
+ "circuitId": "c-s2",
+ "label": "Worktop"
+ },
+ {
+ "id": "ep38",
+ "kind": "socket",
+ "x": 18800,
+ "y": 17700,
+ "height": 300,
+ "wallId": "ext-right",
+ "circuitId": "c-s2",
+ "label": "Fridge",
+ "powerW": 300
+ },
+ {
+ "id": "ep39",
+ "kind": "socket",
+ "x": 18800,
+ "y": 20300,
+ "height": 2000,
+ "wallId": "ext-right",
+ "circuitId": "c-s2",
+ "label": "Cooker hood",
+ "powerW": 200
+ },
+ {
+ "id": "ep40",
+ "kind": "socket",
+ "x": 4400,
+ "y": 18300,
+ "height": 700,
+ "wallId": "ext-left",
+ "circuitId": "c-s3",
+ "label": "Bedside"
+ },
+ {
+ "id": "ep41",
+ "kind": "socket",
+ "x": 4400,
+ "y": 20700,
+ "height": 700,
+ "wallId": "ext-left",
+ "circuitId": "c-s3",
+ "label": "Bedside"
+ },
+ {
+ "id": "ep42",
+ "kind": "socket",
+ "x": 5900,
+ "y": 21740,
+ "height": 900,
+ "wallId": "p4",
+ "circuitId": "c-s3",
+ "label": "Dresser"
+ },
+ {
+ "id": "ep43",
+ "kind": "socket",
+ "x": 7700,
+ "y": 17400,
+ "height": 300,
+ "wallId": "ext-back",
+ "circuitId": "c-s3",
+ "label": "Reading chair"
+ },
+ {
+ "id": "ep44",
+ "kind": "socket",
+ "x": 9740,
+ "y": 20100,
+ "height": 300,
+ "wallId": "p2",
+ "circuitId": "c-s3",
+ "label": "Walk-in closet"
+ },
+ {
+ "id": "ep45",
+ "kind": "socket",
+ "x": 4700,
+ "y": 23060,
+ "height": 700,
+ "wallId": "p5",
+ "circuitId": "c-s4",
+ "label": "Bedside"
+ },
+ {
+ "id": "ep46",
+ "kind": "socket",
+ "x": 4400,
+ "y": 25600,
+ "height": 300,
+ "wallId": "ext-left",
+ "circuitId": "c-s4"
+ },
+ {
+ "id": "ep47",
+ "kind": "socket",
+ "x": 7940,
+ "y": 24400,
+ "height": 300,
+ "wallId": "p6",
+ "circuitId": "c-s4"
+ },
+ {
+ "id": "ep48",
+ "kind": "socket",
+ "x": 11150,
+ "y": 23060,
+ "height": 700,
+ "wallId": "p5",
+ "circuitId": "c-s4",
+ "label": "Bedside"
+ },
+ {
+ "id": "ep49",
+ "kind": "socket",
+ "x": 11340,
+ "y": 24000,
+ "height": 300,
+ "wallId": "p7",
+ "circuitId": "c-s4"
+ },
+ {
+ "id": "ep50",
+ "kind": "socket",
+ "x": 9000,
+ "y": 26200,
+ "height": 300,
+ "wallId": "ext-front",
+ "circuitId": "c-s4"
+ },
+ {
+ "id": "ep51",
+ "kind": "socket",
+ "x": 5800,
+ "y": 22940,
+ "height": 300,
+ "wallId": "p5",
+ "circuitId": "c-s4",
+ "label": "Corridor"
+ },
+ {
+ "id": "ep52",
+ "kind": "socket",
+ "x": 13860,
+ "y": 23300,
+ "height": 300,
+ "wallId": "p8",
+ "circuitId": "c-s4",
+ "label": "Hall"
+ },
+ {
+ "id": "ep53",
+ "kind": "socket_ip44",
+ "x": 8060,
+ "y": 17700,
+ "height": 1100,
+ "wallId": "p1",
+ "circuitId": "c-w1",
+ "label": "En-suite basin"
+ },
+ {
+ "id": "ep54",
+ "kind": "socket_ip44",
+ "x": 11460,
+ "y": 23500,
+ "height": 1100,
+ "wallId": "p7",
+ "circuitId": "c-w1",
+ "label": "Bathroom basin"
+ },
+ {
+ "id": "ep55",
+ "kind": "socket_ip44",
+ "x": 18800,
+ "y": 25800,
+ "height": 1100,
+ "wallId": "ext-right",
+ "circuitId": "c-w2",
+ "label": "Washing machine",
+ "powerW": 2200
+ },
+ {
+ "id": "ep56",
+ "kind": "power",
+ "x": 17700,
+ "y": 24060,
+ "height": 1900,
+ "wallId": "p10",
+ "circuitId": "c-w3",
+ "label": "Water heater",
+ "powerW": 2000
+ },
+ {
+ "id": "ep57",
+ "kind": "power",
+ "x": 18800,
+ "y": 20300,
+ "height": 600,
+ "wallId": "ext-right",
+ "circuitId": "c-p1",
+ "label": "Induction hob + oven",
+ "powerW": 7000
+ },
+ {
+ "id": "ep58",
+ "kind": "power",
+ "x": 18800,
+ "y": 19700,
+ "height": 300,
+ "wallId": "ext-right",
+ "circuitId": "c-p2",
+ "label": "Dishwasher",
+ "powerW": 2000
+ },
+ {
+ "id": "ep59",
+ "kind": "power",
+ "x": 18450,
+ "y": 24060,
+ "height": 600,
+ "wallId": "p10",
+ "circuitId": "c-p3",
+ "label": "Heat pump indoor unit",
+ "powerW": 3500
+ },
+ {
+ "id": "ep60",
+ "kind": "power",
+ "x": 16460,
+ "y": 25700,
+ "height": 600,
+ "wallId": "p9",
+ "circuitId": "c-p4",
+ "label": "Borehole pump controller",
+ "powerW": 1100
+ },
+ {
+ "id": "ep61",
+ "kind": "outdoor",
+ "x": 16200,
+ "y": 17000,
+ "height": 600,
+ "wallId": "ext-back",
+ "circuitId": "c-o1",
+ "label": "Terrace"
+ },
+ {
+ "id": "ep62",
+ "kind": "light_wall",
+ "x": 13700,
+ "y": 17000,
+ "height": 2200,
+ "wallId": "ext-back",
+ "circuitId": "c-o1",
+ "label": "Terrace"
+ },
+ {
+ "id": "ep63",
+ "kind": "light_wall",
+ "x": 15300,
+ "y": 17000,
+ "height": 2200,
+ "wallId": "ext-back",
+ "circuitId": "c-o1",
+ "label": "Terrace"
+ },
+ {
+ "id": "ep64",
+ "kind": "light_wall",
+ "x": 14450,
+ "y": 26600,
+ "height": 2200,
+ "wallId": "ext-front",
+ "circuitId": "c-o1",
+ "label": "Front door"
+ },
+ {
+ "id": "ep65",
+ "kind": "switch",
+ "x": 15200,
+ "y": 17400,
+ "height": 900,
+ "wallId": "ext-back",
+ "circuitId": "c-o1",
+ "label": "Terrace lights"
+ },
+ {
+ "id": "ep66",
+ "kind": "socket",
+ "x": 23000,
+ "y": 32200,
+ "height": 900,
+ "wallId": "g-back",
+ "circuitId": "c-g1",
+ "label": "Workbench"
+ },
+ {
+ "id": "ep67",
+ "kind": "socket",
+ "x": 27900,
+ "y": 32200,
+ "height": 300,
+ "wallId": "g-back",
+ "circuitId": "c-g1"
+ },
+ {
+ "id": "ep68",
+ "kind": "socket",
+ "x": 28800,
+ "y": 37000,
+ "height": 2500,
+ "wallId": "g-right",
+ "circuitId": "c-g1",
+ "label": "Door operators"
+ },
+ {
+ "id": "ep69",
+ "kind": "light",
+ "x": 24000,
+ "y": 35300,
+ "height": 2800,
+ "circuitId": "c-g1",
+ "label": "Garage"
+ },
+ {
+ "id": "ep70",
+ "kind": "light",
+ "x": 27000,
+ "y": 35300,
+ "height": 2800,
+ "circuitId": "c-g1",
+ "label": "Garage"
+ },
+ {
+ "id": "ep71",
+ "kind": "switch",
+ "x": 22200,
+ "y": 33850,
+ "height": 900,
+ "wallId": "g-left",
+ "circuitId": "c-g1",
+ "label": "Garage lights"
+ }
+ ],
+ "circuits": [
+ {
+ "id": "c-l1",
+ "name": "Lighting — bedrooms wing",
+ "kind": "light",
+ "breaker": {
+ "type": "MCB",
+ "rating": 10,
+ "curve": "C"
+ },
+ "cable": "3x1.5",
+ "phase": "L1"
+ },
+ {
+ "id": "c-l2",
+ "name": "Lighting — living, hall, utility",
+ "kind": "light",
+ "breaker": {
+ "type": "MCB",
+ "rating": 10,
+ "curve": "C"
+ },
+ "cable": "3x1.5",
+ "phase": "L2"
+ },
+ {
+ "id": "c-s1",
+ "name": "Sockets — living & dining",
+ "kind": "socket",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L3"
+ },
+ {
+ "id": "c-s2",
+ "name": "Sockets — kitchen worktop",
+ "kind": "socket",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L1"
+ },
+ {
+ "id": "c-s3",
+ "name": "Sockets — master suite",
+ "kind": "socket",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L2"
+ },
+ {
+ "id": "c-s4",
+ "name": "Sockets — bedrooms 2–3, hall",
+ "kind": "socket",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L3"
+ },
+ {
+ "id": "c-w1",
+ "name": "Bathrooms (IP44)",
+ "kind": "wet",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L1"
+ },
+ {
+ "id": "c-w2",
+ "name": "Washing machine",
+ "kind": "wet",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L2"
+ },
+ {
+ "id": "c-w3",
+ "name": "Water heater 80 L",
+ "kind": "wet",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L3"
+ },
+ {
+ "id": "c-p1",
+ "name": "Induction hob & oven",
+ "kind": "power",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 32,
+ "curve": "C"
+ },
+ "cable": "3x6",
+ "phase": "L1"
+ },
+ {
+ "id": "c-p2",
+ "name": "Dishwasher",
+ "kind": "power",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L2"
+ },
+ {
+ "id": "c-p3",
+ "name": "Heat pump",
+ "kind": "power",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L3"
+ },
+ {
+ "id": "c-p4",
+ "name": "Borehole pump",
+ "kind": "power",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L1"
+ },
+ {
+ "id": "c-o1",
+ "name": "Outdoor & terrace",
+ "kind": "outdoor",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L2"
+ },
+ {
+ "id": "c-g1",
+ "name": "Garage (buried cable)",
+ "kind": "garage",
+ "breaker": {
+ "type": "RCBO",
+ "rating": 16,
+ "curve": "C"
+ },
+ "cable": "3x2.5",
+ "phase": "L3"
+ }
+ ],
+ "routes": [
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 23000
+ },
+ {
+ "x": 12650,
+ "y": 23000
+ },
+ {
+ "x": 12650,
+ "y": 22940
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 12650,
+ "y": 23000
+ },
+ {
+ "x": 9150,
+ "y": 23000
+ },
+ {
+ "x": 9150,
+ "y": 23060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 9700,
+ "y": 23000
+ },
+ {
+ "x": 9700,
+ "y": 24630
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 9150,
+ "y": 23000
+ },
+ {
+ "x": 6850,
+ "y": 23000
+ },
+ {
+ "x": 6850,
+ "y": 23060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 6850,
+ "y": 23000
+ },
+ {
+ "x": 6170,
+ "y": 23000
+ },
+ {
+ "x": 6170,
+ "y": 24630
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 11400,
+ "y": 23000
+ },
+ {
+ "x": 11400,
+ "y": 24630
+ },
+ {
+ "x": 12600,
+ "y": 24630
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 10600,
+ "y": 21800
+ },
+ {
+ "x": 10600,
+ "y": 22400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 10600,
+ "y": 21800
+ },
+ {
+ "x": 6850,
+ "y": 21800
+ },
+ {
+ "x": 6850,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 6850,
+ "y": 21800
+ },
+ {
+ "x": 6200,
+ "y": 21800
+ },
+ {
+ "x": 6200,
+ "y": 21860
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 6200,
+ "y": 21800
+ },
+ {
+ "x": 6200,
+ "y": 22400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 8000,
+ "y": 21800
+ },
+ {
+ "x": 8000,
+ "y": 20150
+ },
+ {
+ "x": 7940,
+ "y": 20150
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 8000,
+ "y": 20750
+ },
+ {
+ "x": 8900,
+ "y": 20750
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 8000,
+ "y": 20150
+ },
+ {
+ "x": 8000,
+ "y": 19150
+ },
+ {
+ "x": 7940,
+ "y": 19150
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 8000,
+ "y": 19150
+ },
+ {
+ "x": 8000,
+ "y": 18520
+ },
+ {
+ "x": 8900,
+ "y": 18520
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l1",
+ "path": [
+ {
+ "x": 8000,
+ "y": 19570
+ },
+ {
+ "x": 6170,
+ "y": 19570
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23250
+ },
+ {
+ "x": 16340,
+ "y": 23250
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 25250
+ },
+ {
+ "x": 16340,
+ "y": 25250
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16400,
+ "y": 23250
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 16000,
+ "y": 21800
+ },
+ {
+ "x": 16000,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16000,
+ "y": 21800
+ },
+ {
+ "x": 15850,
+ "y": 21800
+ },
+ {
+ "x": 15850,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 15850,
+ "y": 21800
+ },
+ {
+ "x": 15100,
+ "y": 21800
+ },
+ {
+ "x": 15100,
+ "y": 22800
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 17630,
+ "y": 21800
+ },
+ {
+ "x": 17630,
+ "y": 22900
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16400,
+ "y": 24000
+ },
+ {
+ "x": 17630,
+ "y": 24000
+ },
+ {
+ "x": 17630,
+ "y": 25130
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 16400,
+ "y": 25250
+ },
+ {
+ "x": 16400,
+ "y": 26400
+ },
+ {
+ "x": 14550,
+ "y": 26400
+ },
+ {
+ "x": 14550,
+ "y": 26200
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 14550,
+ "y": 26400
+ },
+ {
+ "x": 13800,
+ "y": 26400
+ },
+ {
+ "x": 13800,
+ "y": 25000
+ },
+ {
+ "x": 15100,
+ "y": 25000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 17630,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 19400
+ },
+ {
+ "x": 17700,
+ "y": 19400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 19000,
+ "y": 19400
+ },
+ {
+ "x": 19000,
+ "y": 17200
+ },
+ {
+ "x": 16200,
+ "y": 17200
+ },
+ {
+ "x": 16200,
+ "y": 19400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-l2",
+ "path": [
+ {
+ "x": 15100,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 19500
+ },
+ {
+ "x": 11700,
+ "y": 19500
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 12000,
+ "y": 21800
+ },
+ {
+ "x": 12000,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 12000,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 20000
+ },
+ {
+ "x": 9860,
+ "y": 20000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 9800,
+ "y": 20000
+ },
+ {
+ "x": 9800,
+ "y": 19000
+ },
+ {
+ "x": 9860,
+ "y": 19000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 9800,
+ "y": 19000
+ },
+ {
+ "x": 9800,
+ "y": 17200
+ },
+ {
+ "x": 10500,
+ "y": 17200
+ },
+ {
+ "x": 10500,
+ "y": 17400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 10500,
+ "y": 17200
+ },
+ {
+ "x": 13300,
+ "y": 17200
+ },
+ {
+ "x": 13300,
+ "y": 17400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s1",
+ "path": [
+ {
+ "x": 13300,
+ "y": 17200
+ },
+ {
+ "x": 17800,
+ "y": 17200
+ },
+ {
+ "x": 17800,
+ "y": 17400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s2",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21450
+ },
+ {
+ "x": 18800,
+ "y": 21450
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s2",
+ "path": [
+ {
+ "x": 19000,
+ "y": 21450
+ },
+ {
+ "x": 19000,
+ "y": 20900
+ },
+ {
+ "x": 18800,
+ "y": 20900
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s2",
+ "path": [
+ {
+ "x": 19000,
+ "y": 20900
+ },
+ {
+ "x": 19000,
+ "y": 20300
+ },
+ {
+ "x": 18800,
+ "y": 20300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s2",
+ "path": [
+ {
+ "x": 19000,
+ "y": 20300
+ },
+ {
+ "x": 19000,
+ "y": 18300
+ },
+ {
+ "x": 18800,
+ "y": 18300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s2",
+ "path": [
+ {
+ "x": 19000,
+ "y": 18300
+ },
+ {
+ "x": 19000,
+ "y": 17700
+ },
+ {
+ "x": 18800,
+ "y": 17700
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s3",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 21800
+ },
+ {
+ "x": 9800,
+ "y": 20100
+ },
+ {
+ "x": 9740,
+ "y": 20100
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s3",
+ "path": [
+ {
+ "x": 9800,
+ "y": 21800
+ },
+ {
+ "x": 5900,
+ "y": 21800
+ },
+ {
+ "x": 5900,
+ "y": 21740
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s3",
+ "path": [
+ {
+ "x": 5900,
+ "y": 21800
+ },
+ {
+ "x": 4200,
+ "y": 21800
+ },
+ {
+ "x": 4200,
+ "y": 20700
+ },
+ {
+ "x": 4400,
+ "y": 20700
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s3",
+ "path": [
+ {
+ "x": 4200,
+ "y": 20700
+ },
+ {
+ "x": 4200,
+ "y": 18300
+ },
+ {
+ "x": 4400,
+ "y": 18300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s3",
+ "path": [
+ {
+ "x": 4200,
+ "y": 18300
+ },
+ {
+ "x": 4200,
+ "y": 17200
+ },
+ {
+ "x": 7700,
+ "y": 17200
+ },
+ {
+ "x": 7700,
+ "y": 17400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 23300
+ },
+ {
+ "x": 13860,
+ "y": 23300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 13800,
+ "y": 23000
+ },
+ {
+ "x": 11150,
+ "y": 23000
+ },
+ {
+ "x": 11150,
+ "y": 23060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 11400,
+ "y": 23000
+ },
+ {
+ "x": 11400,
+ "y": 24000
+ },
+ {
+ "x": 11340,
+ "y": 24000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 11150,
+ "y": 23000
+ },
+ {
+ "x": 8000,
+ "y": 23000
+ },
+ {
+ "x": 8000,
+ "y": 24400
+ },
+ {
+ "x": 7940,
+ "y": 24400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 8000,
+ "y": 23000
+ },
+ {
+ "x": 5800,
+ "y": 23000
+ },
+ {
+ "x": 5800,
+ "y": 22940
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 5800,
+ "y": 23000
+ },
+ {
+ "x": 4700,
+ "y": 23000
+ },
+ {
+ "x": 4700,
+ "y": 23060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 8000,
+ "y": 24400
+ },
+ {
+ "x": 8000,
+ "y": 26400
+ },
+ {
+ "x": 9000,
+ "y": 26400
+ },
+ {
+ "x": 9000,
+ "y": 26200
+ }
+ ]
+ },
+ {
+ "circuitId": "c-s4",
+ "path": [
+ {
+ "x": 4700,
+ "y": 23000
+ },
+ {
+ "x": 4200,
+ "y": 23000
+ },
+ {
+ "x": 4200,
+ "y": 25600
+ },
+ {
+ "x": 4400,
+ "y": 25600
+ }
+ ]
+ },
+ {
+ "circuitId": "c-w1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 13800,
+ "y": 23000
+ },
+ {
+ "x": 11400,
+ "y": 23000
+ },
+ {
+ "x": 11400,
+ "y": 23500
+ },
+ {
+ "x": 11460,
+ "y": 23500
+ }
+ ]
+ },
+ {
+ "circuitId": "c-w1",
+ "path": [
+ {
+ "x": 13800,
+ "y": 21800
+ },
+ {
+ "x": 8000,
+ "y": 21800
+ },
+ {
+ "x": 8000,
+ "y": 17700
+ },
+ {
+ "x": 8060,
+ "y": 17700
+ }
+ ]
+ },
+ {
+ "circuitId": "c-w2",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 24000
+ },
+ {
+ "x": 19000,
+ "y": 24000
+ },
+ {
+ "x": 19000,
+ "y": 25800
+ },
+ {
+ "x": 18800,
+ "y": 25800
+ }
+ ]
+ },
+ {
+ "circuitId": "c-w3",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 24000
+ },
+ {
+ "x": 17700,
+ "y": 24000
+ },
+ {
+ "x": 17700,
+ "y": 24060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-p1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 20300
+ },
+ {
+ "x": 18800,
+ "y": 20300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-p2",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 19700
+ },
+ {
+ "x": 18800,
+ "y": 19700
+ }
+ ]
+ },
+ {
+ "circuitId": "c-p3",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 24000
+ },
+ {
+ "x": 18450,
+ "y": 24000
+ },
+ {
+ "x": 18450,
+ "y": 24060
+ }
+ ]
+ },
+ {
+ "circuitId": "c-p4",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 25700
+ },
+ {
+ "x": 16460,
+ "y": 25700
+ }
+ ]
+ },
+ {
+ "circuitId": "c-o1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 26400
+ },
+ {
+ "x": 14450,
+ "y": 26400
+ },
+ {
+ "x": 14450,
+ "y": 26600
+ }
+ ]
+ },
+ {
+ "circuitId": "c-o1",
+ "path": [
+ {
+ "x": 16400,
+ "y": 23600
+ },
+ {
+ "x": 16400,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 21800
+ },
+ {
+ "x": 19000,
+ "y": 17200
+ },
+ {
+ "x": 16200,
+ "y": 17200
+ },
+ {
+ "x": 16200,
+ "y": 17000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-o1",
+ "path": [
+ {
+ "x": 16200,
+ "y": 17200
+ },
+ {
+ "x": 15300,
+ "y": 17200
+ },
+ {
+ "x": 15300,
+ "y": 17000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-o1",
+ "path": [
+ {
+ "x": 15300,
+ "y": 17200
+ },
+ {
+ "x": 15200,
+ "y": 17200
+ },
+ {
+ "x": 15200,
+ "y": 17400
+ }
+ ]
+ },
+ {
+ "circuitId": "c-o1",
+ "path": [
+ {
+ "x": 15200,
+ "y": 17200
+ },
+ {
+ "x": 13700,
+ "y": 17200
+ },
+ {
+ "x": 13700,
+ "y": 17000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 16340,
+ "y": 23600
+ },
+ {
+ "x": 23000,
+ "y": 23600
+ },
+ {
+ "x": 23000,
+ "y": 32200
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 23000,
+ "y": 32200
+ },
+ {
+ "x": 23000,
+ "y": 32100
+ },
+ {
+ "x": 22100,
+ "y": 32100
+ },
+ {
+ "x": 22100,
+ "y": 33850
+ },
+ {
+ "x": 22200,
+ "y": 33850
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 22100,
+ "y": 33850
+ },
+ {
+ "x": 22100,
+ "y": 35300
+ },
+ {
+ "x": 24000,
+ "y": 35300
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 23000,
+ "y": 32100
+ },
+ {
+ "x": 27900,
+ "y": 32100
+ },
+ {
+ "x": 27900,
+ "y": 32200
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 27900,
+ "y": 32100
+ },
+ {
+ "x": 28900,
+ "y": 32100
+ },
+ {
+ "x": 28900,
+ "y": 37000
+ },
+ {
+ "x": 28800,
+ "y": 37000
+ }
+ ]
+ },
+ {
+ "circuitId": "c-g1",
+ "path": [
+ {
+ "x": 28900,
+ "y": 35300
+ },
+ {
+ "x": 27000,
+ "y": 35300
+ }
+ ]
+ }
+ ]
+ },
+ "heating": {
+ "collector": {
+ "id": "collector",
+ "x": 12000,
+ "y": 22880,
+ "outputs": 12,
+ "label": "Manifold cabinet in the corridor wall"
+ },
+ "loops": [
+ {
+ "id": "hl1",
+ "roomId": "r-corridor",
+ "roomName": "Corridor",
+ "polygon": [
+ {
+ "x": 13640,
+ "y": 21960
+ },
+ {
+ "x": 13640,
+ "y": 22840
+ },
+ {
+ "x": 4500,
+ "y": 22840
+ },
+ {
+ "x": 4500,
+ "y": 21960
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 12000,
+ "y": 22840
+ }
+ ]
+ },
+ {
+ "id": "hl2",
+ "roomId": "r-bath",
+ "roomName": "Bathroom",
+ "polygon": [
+ {
+ "x": 13640,
+ "y": 23160
+ },
+ {
+ "x": 13640,
+ "y": 26100
+ },
+ {
+ "x": 11560,
+ "y": 26100
+ },
+ {
+ "x": 11560,
+ "y": 23160
+ }
+ ],
+ "stepMm": 100,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 12150,
+ "y": 22880
+ },
+ {
+ "x": 12150,
+ "y": 23160
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 13160,
+ "y": 26100
+ },
+ {
+ "x": 11560,
+ "y": 26100
+ },
+ {
+ "x": 11560,
+ "y": 25450
+ },
+ {
+ "x": 13160,
+ "y": 25450
+ }
+ ]
+ ]
+ },
+ {
+ "id": "hl3",
+ "roomId": "r-hall",
+ "roomName": "Hall",
+ "polygon": [
+ {
+ "x": 16240,
+ "y": 21960
+ },
+ {
+ "x": 16240,
+ "y": 26100
+ },
+ {
+ "x": 13960,
+ "y": 26100
+ },
+ {
+ "x": 13960,
+ "y": 21960
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22400
+ },
+ {
+ "x": 13960,
+ "y": 22400
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 14460,
+ "y": 25200
+ },
+ {
+ "x": 13960,
+ "y": 25200
+ },
+ {
+ "x": 13960,
+ "y": 23600
+ },
+ {
+ "x": 14460,
+ "y": 23600
+ }
+ ]
+ ]
+ },
+ {
+ "id": "hl4",
+ "roomId": "r-bed3",
+ "roomName": "Bedroom 3",
+ "polygon": [
+ {
+ "x": 11240,
+ "y": 23160
+ },
+ {
+ "x": 11240,
+ "y": 26100
+ },
+ {
+ "x": 8160,
+ "y": 26100
+ },
+ {
+ "x": 8160,
+ "y": 23160
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 8600,
+ "y": 22880
+ },
+ {
+ "x": 8600,
+ "y": 23160
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 8660,
+ "y": 26100
+ },
+ {
+ "x": 8160,
+ "y": 26100
+ },
+ {
+ "x": 8160,
+ "y": 25150
+ },
+ {
+ "x": 8660,
+ "y": 25150
+ }
+ ]
+ ]
+ },
+ {
+ "id": "hl5",
+ "roomId": "r-living",
+ "roomName": "Living / Kitchen · 2/4",
+ "polygon": [
+ {
+ "x": 14329,
+ "y": 21640
+ },
+ {
+ "x": 12144,
+ "y": 21640
+ },
+ {
+ "x": 12144,
+ "y": 17500
+ },
+ {
+ "x": 14329,
+ "y": 17500
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21640
+ }
+ ]
+ },
+ {
+ "id": "hl6",
+ "roomId": "r-living",
+ "roomName": "Living / Kitchen · 1/4",
+ "polygon": [
+ {
+ "x": 12144,
+ "y": 21640
+ },
+ {
+ "x": 9960,
+ "y": 21640
+ },
+ {
+ "x": 9960,
+ "y": 17500
+ },
+ {
+ "x": 12144,
+ "y": 17500
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21680
+ },
+ {
+ "x": 12144,
+ "y": 21680
+ },
+ {
+ "x": 12144,
+ "y": 21640
+ }
+ ]
+ },
+ {
+ "id": "hl7",
+ "roomId": "r-bed2",
+ "roomName": "Bedroom 2",
+ "polygon": [
+ {
+ "x": 7840,
+ "y": 23160
+ },
+ {
+ "x": 7840,
+ "y": 26100
+ },
+ {
+ "x": 4500,
+ "y": 26100
+ },
+ {
+ "x": 4500,
+ "y": 23160
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 7400,
+ "y": 22880
+ },
+ {
+ "x": 7400,
+ "y": 23160
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 7840,
+ "y": 26100
+ },
+ {
+ "x": 7340,
+ "y": 26100
+ },
+ {
+ "x": 7340,
+ "y": 25150
+ },
+ {
+ "x": 7840,
+ "y": 25150
+ }
+ ]
+ ]
+ },
+ {
+ "id": "hl8",
+ "roomId": "r-living",
+ "roomName": "Living / Kitchen · 3/4",
+ "polygon": [
+ {
+ "x": 16514,
+ "y": 21640
+ },
+ {
+ "x": 14329,
+ "y": 21640
+ },
+ {
+ "x": 14329,
+ "y": 17500
+ },
+ {
+ "x": 16514,
+ "y": 17500
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21680
+ },
+ {
+ "x": 14329,
+ "y": 21680
+ },
+ {
+ "x": 14329,
+ "y": 21640
+ }
+ ]
+ },
+ {
+ "id": "hl9",
+ "roomId": "r-living",
+ "roomName": "Living / Kitchen · 4/4",
+ "polygon": [
+ {
+ "x": 18700,
+ "y": 21640
+ },
+ {
+ "x": 16514,
+ "y": 21640
+ },
+ {
+ "x": 16514,
+ "y": 17500
+ },
+ {
+ "x": 18700,
+ "y": 17500
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21920
+ },
+ {
+ "x": 12750,
+ "y": 21680
+ },
+ {
+ "x": 16514,
+ "y": 21680
+ },
+ {
+ "x": 16514,
+ "y": 21640
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 18700,
+ "y": 21640
+ },
+ {
+ "x": 18200,
+ "y": 21640
+ },
+ {
+ "x": 18200,
+ "y": 18000
+ },
+ {
+ "x": 18150,
+ "y": 18000
+ },
+ {
+ "x": 18150,
+ "y": 17500
+ },
+ {
+ "x": 18700,
+ "y": 17500
+ }
+ ]
+ ]
+ },
+ {
+ "id": "hl10",
+ "roomId": "r-master",
+ "roomName": "Master bedroom · 2/2",
+ "polygon": [
+ {
+ "x": 7840,
+ "y": 21640
+ },
+ {
+ "x": 4500,
+ "y": 21640
+ },
+ {
+ "x": 4500,
+ "y": 19569
+ },
+ {
+ "x": 7840,
+ "y": 19569
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21640
+ }
+ ]
+ },
+ {
+ "id": "hl11",
+ "roomId": "r-master",
+ "roomName": "Master bedroom · 1/2",
+ "polygon": [
+ {
+ "x": 7840,
+ "y": 19569
+ },
+ {
+ "x": 4500,
+ "y": 19569
+ },
+ {
+ "x": 4500,
+ "y": 17500
+ },
+ {
+ "x": 7840,
+ "y": 17500
+ }
+ ],
+ "stepMm": 150,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21680
+ },
+ {
+ "x": 7880,
+ "y": 21680
+ },
+ {
+ "x": 7880,
+ "y": 19569
+ },
+ {
+ "x": 7400,
+ "y": 19569
+ }
+ ]
+ },
+ {
+ "id": "hl12",
+ "roomId": "r-ensuite",
+ "roomName": "En-suite",
+ "polygon": [
+ {
+ "x": 9640,
+ "y": 17500
+ },
+ {
+ "x": 9640,
+ "y": 19540
+ },
+ {
+ "x": 8160,
+ "y": 19540
+ },
+ {
+ "x": 8160,
+ "y": 17500
+ }
+ ],
+ "stepMm": 100,
+ "pattern": "spiral",
+ "pipe": "16x2 PEX-a",
+ "supplyPath": [
+ {
+ "x": 12000,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 22880
+ },
+ {
+ "x": 13680,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21920
+ },
+ {
+ "x": 7400,
+ "y": 21680
+ },
+ {
+ "x": 7880,
+ "y": 21680
+ },
+ {
+ "x": 7880,
+ "y": 18650
+ },
+ {
+ "x": 8160,
+ "y": 18650
+ }
+ ],
+ "excluded": [
+ [
+ {
+ "x": 9640,
+ "y": 18300
+ },
+ {
+ "x": 8840,
+ "y": 18300
+ },
+ {
+ "x": 8840,
+ "y": 17500
+ },
+ {
+ "x": 9640,
+ "y": 17500
+ }
+ ]
+ ]
+ }
+ ],
+ "params": {
+ "supplyT": 50,
+ "returnT": 40,
+ "screedMm": 60,
+ "insulation": "XPS 150",
+ "screedMix": "cps",
+ "fixing": "staples"
+ }
+ }
+ }
+}
diff --git a/public/textures/LICENSE.txt b/public/textures/LICENSE.txt
new file mode 100644
index 0000000..38c4325
--- /dev/null
+++ b/public/textures/LICENSE.txt
@@ -0,0 +1,8 @@
+Textures from ambientCG.com, licensed under CC0 1.0 Universal.
+osb: Chipboard005
+brick: Bricks085
+plaster: Plaster001
+concrete: Concrete034
+grass: Grass004
+timber: Planks021
+planken: WoodFloor044
diff --git a/public/textures/brick/color.jpg b/public/textures/brick/color.jpg
new file mode 100644
index 0000000..b75d0d0
Binary files /dev/null and b/public/textures/brick/color.jpg differ
diff --git a/public/textures/brick/normal.jpg b/public/textures/brick/normal.jpg
new file mode 100644
index 0000000..19482cd
Binary files /dev/null and b/public/textures/brick/normal.jpg differ
diff --git a/public/textures/brick/roughness.jpg b/public/textures/brick/roughness.jpg
new file mode 100644
index 0000000..7598417
Binary files /dev/null and b/public/textures/brick/roughness.jpg differ
diff --git a/public/textures/concrete/color.jpg b/public/textures/concrete/color.jpg
new file mode 100644
index 0000000..2779b33
Binary files /dev/null and b/public/textures/concrete/color.jpg differ
diff --git a/public/textures/concrete/normal.jpg b/public/textures/concrete/normal.jpg
new file mode 100644
index 0000000..fbcce51
Binary files /dev/null and b/public/textures/concrete/normal.jpg differ
diff --git a/public/textures/concrete/roughness.jpg b/public/textures/concrete/roughness.jpg
new file mode 100644
index 0000000..c7939c1
Binary files /dev/null and b/public/textures/concrete/roughness.jpg differ
diff --git a/public/textures/grass/color.jpg b/public/textures/grass/color.jpg
new file mode 100644
index 0000000..463a71f
Binary files /dev/null and b/public/textures/grass/color.jpg differ
diff --git a/public/textures/grass/normal.jpg b/public/textures/grass/normal.jpg
new file mode 100644
index 0000000..2c30af8
Binary files /dev/null and b/public/textures/grass/normal.jpg differ
diff --git a/public/textures/grass/roughness.jpg b/public/textures/grass/roughness.jpg
new file mode 100644
index 0000000..7d60ac0
Binary files /dev/null and b/public/textures/grass/roughness.jpg differ
diff --git a/public/textures/osb/color.jpg b/public/textures/osb/color.jpg
new file mode 100644
index 0000000..0b151b2
Binary files /dev/null and b/public/textures/osb/color.jpg differ
diff --git a/public/textures/osb/normal.jpg b/public/textures/osb/normal.jpg
new file mode 100644
index 0000000..15b5c34
Binary files /dev/null and b/public/textures/osb/normal.jpg differ
diff --git a/public/textures/osb/roughness.jpg b/public/textures/osb/roughness.jpg
new file mode 100644
index 0000000..c9472f4
Binary files /dev/null and b/public/textures/osb/roughness.jpg differ
diff --git a/public/textures/planken/color.jpg b/public/textures/planken/color.jpg
new file mode 100644
index 0000000..ac80736
Binary files /dev/null and b/public/textures/planken/color.jpg differ
diff --git a/public/textures/planken/normal.jpg b/public/textures/planken/normal.jpg
new file mode 100644
index 0000000..d8a42a5
Binary files /dev/null and b/public/textures/planken/normal.jpg differ
diff --git a/public/textures/planken/roughness.jpg b/public/textures/planken/roughness.jpg
new file mode 100644
index 0000000..b153888
Binary files /dev/null and b/public/textures/planken/roughness.jpg differ
diff --git a/public/textures/plaster/color.jpg b/public/textures/plaster/color.jpg
new file mode 100644
index 0000000..6c005ad
Binary files /dev/null and b/public/textures/plaster/color.jpg differ
diff --git a/public/textures/plaster/normal.jpg b/public/textures/plaster/normal.jpg
new file mode 100644
index 0000000..28cd522
Binary files /dev/null and b/public/textures/plaster/normal.jpg differ
diff --git a/public/textures/plaster/roughness.jpg b/public/textures/plaster/roughness.jpg
new file mode 100644
index 0000000..93996de
Binary files /dev/null and b/public/textures/plaster/roughness.jpg differ
diff --git a/public/textures/timber/color.jpg b/public/textures/timber/color.jpg
new file mode 100644
index 0000000..e9c3cec
Binary files /dev/null and b/public/textures/timber/color.jpg differ
diff --git a/public/textures/timber/normal.jpg b/public/textures/timber/normal.jpg
new file mode 100644
index 0000000..4597c01
Binary files /dev/null and b/public/textures/timber/normal.jpg differ
diff --git a/public/textures/timber/roughness.jpg b/public/textures/timber/roughness.jpg
new file mode 100644
index 0000000..882c209
Binary files /dev/null and b/public/textures/timber/roughness.jpg differ
diff --git a/scripts/_deploy-lib.sh b/scripts/_deploy-lib.sh
new file mode 100755
index 0000000..3cf1660
--- /dev/null
+++ b/scripts/_deploy-lib.sh
@@ -0,0 +1,152 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+ENV_FILE="${DEPLOY_ENV:-$ROOT/.env.deploy}"
+[ -f "$ENV_FILE" ] && set -a && . "$ENV_FILE" && set +a
+
+DEPLOY_METHOD="${DEPLOY_METHOD:-ssh}"
+DEPLOY_SSH="${DEPLOY_SSH:-}"
+DEPLOY_SSH_OPTS="${DEPLOY_SSH_OPTS:-}"
+DEPLOY_PATH="${DEPLOY_PATH:-}"
+DEPLOY_URL="${DEPLOY_URL:-}"
+LOCK_DIR="${DEPLOY_LOCK:-${TMPDIR:-/tmp}/house-planner-deploy.lock}"
+LOCK_WAIT="${DEPLOY_LOCK_WAIT:-600}"
+FTP_HOST="${FTP_HOST:-}"
+FTP_USER="${FTP_USER:-}"
+FTP_PASSWORD="${FTP_PASSWORD:-}"
+FTP_PATH="${FTP_PATH:-}"
+FTP_SSL_VERIFY="${FTP_SSL_VERIFY:-yes}"
+
+die() { echo "$*" >&2; exit 1; }
+
+file_size() { stat -c %s "$1" 2>/dev/null || stat -f %z "$1"; }
+file_mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1"; }
+if command -v md5sum >/dev/null; then MD5_CMD=(md5sum); else MD5_CMD=(md5 -r); fi
+
+ssh_cmd() {
+ # shellcheck disable=SC2086
+ ssh $DEPLOY_SSH_OPTS "$DEPLOY_SSH" "$@"
+}
+
+check_ssh_env() {
+ [ -n "$DEPLOY_SSH" ] || die "в .env.deploy нет DEPLOY_SSH (user@host или алиас из ~/.ssh/config)"
+ [ -n "$DEPLOY_PATH" ] || die "в .env.deploy нет DEPLOY_PATH (корень сайта на сервере)"
+}
+
+check_ftp_env() {
+ command -v lftp >/dev/null || die "нет lftp: установите его (brew install lftp, apt install lftp)"
+ [ -n "$FTP_HOST" ] && [ -n "$FTP_USER" ] && [ -n "$FTP_PASSWORD" ] || die "в .env.deploy нет FTP_HOST, FTP_USER или FTP_PASSWORD"
+ [ -n "$FTP_PATH" ] || die "в .env.deploy нет FTP_PATH (корень сайта на FTP)"
+}
+
+ftp_run() {
+ LFTP_PASSWORD="$FTP_PASSWORD" lftp -c "set ssl:verify-certificate $FTP_SSL_VERIFY; set net:max-retries 3; set net:timeout 30; set cmd:verbose no; open --env-password -u '$FTP_USER' 'ftp://$FTP_HOST'; $1"
+}
+
+ftp_exclude_args() {
+ local p rx
+ for p in "$@"; do
+ rx="$(printf '%s' "$p" | sed 's/[.[\*^$+?(){}|]/\\&/g')"
+ case "$p" in
+ /*) printf -- '--exclude=^%s\n' "${rx#/}" ;;
+ */) printf -- '--exclude=(^|/)%s\n' "$rx" ;;
+ *) printf -- '--exclude=(^|/)%s$\n' "$rx" ;;
+ esac
+ done
+}
+
+md5_filter() {
+ awk -v ex="$1" 'BEGIN { n = split(ex, e, " ") }
+ { p = $0; sub(/^[0-9a-f]+ /, "", p); b = p; sub(/.*\//, "", b)
+ for (i = 1; i <= n; i++) {
+ x = e[i]
+ if (substr(x, 1, 1) == "/") { x = substr(x, 2); if (index(p, x) == 1) next }
+ else if (x ~ /\/$/) { if (index(p, x) == 1 || index(p, "/" x) > 0) next }
+ else if (b == x) next
+ }
+ print }'
+}
+
+ftp_sync_dir() {
+ local src="$1" dst="$2"; shift 2
+ [ -d "$src" ] || die "нет папки $src"
+ local ex="" l
+ while IFS= read -r l; do ex="$ex '$l'"; done < <(ftp_exclude_args "$@")
+ ftp_run "mkdir -p -f '$dst'; mirror --reverse --delete --no-perms --parallel=4 $ex '$src/' '$dst/'"
+}
+
+ftp_verify_dir() {
+ local src="$1" dst="$2"; shift 2
+ local ex="$*"
+ local tmp; tmp="$(mktemp -d)"
+ (cd "$src" && find . -type f | while IFS= read -r f; do printf '%s %s\n' "$(file_size "$f")" "${f#./}"; done | LC_ALL=C sort -k2) | md5_filter "$ex" > "$tmp/local"
+ ftp_run "cd '$dst' && find -l ." | awk '/^-/ { s = $3; p = $0; sub(/^[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +[^ ]+ +/, "", p); sub(/^\.\//, "", p); print s " " p }' | LC_ALL=C sort -k2 | md5_filter "$ex" > "$tmp/remote"
+ local n; n=$(wc -l < "$tmp/local" | tr -d ' ')
+ if diff -u "$tmp/local" "$tmp/remote" > "$tmp/diff"; then
+ echo "размеры: совпадают ($n файлов; исключены: $ex)"
+ rm -rf "$tmp"
+ else
+ echo "размеры: РАСХОЖДЕНИЕ" >&2
+ cat "$tmp/diff" >&2
+ rm -rf "$tmp"
+ return 1
+ fi
+}
+
+lock_acquire() {
+ local waited=0 pid
+ while ! mkdir "$LOCK_DIR" 2>/dev/null; do
+ pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
+ if [ -n "$pid" ] && ! kill -0 "$pid" 2>/dev/null; then
+ echo "замок: процесс $pid мёртв — снимаю замок" >&2
+ rm -rf "$LOCK_DIR"; continue
+ fi
+ if [ -z "$pid" ] && [ -d "$LOCK_DIR" ] && [ $(( $(date +%s) - $(file_mtime "$LOCK_DIR" 2>/dev/null || date +%s) )) -gt 60 ]; then
+ echo "замок: без PID дольше минуты — снимаю" >&2
+ rm -rf "$LOCK_DIR"; continue
+ fi
+ if [ "$waited" -ge "$LOCK_WAIT" ]; then
+ echo "замок: жду уже ${LOCK_WAIT}с, держит PID ${pid:-?} — выхожу" >&2
+ exit 75
+ fi
+ [ $((waited % 30)) -eq 0 ] && echo "замок: занят (PID ${pid:-?}), жду…" >&2
+ sleep 2; waited=$((waited + 2))
+ done
+ echo $$ > "$LOCK_DIR/pid"
+ trap 'lock_release' EXIT
+ trap 'exit 130' INT TERM
+}
+
+lock_release() {
+ [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR"
+ return 0
+}
+
+sync_dir() {
+ local src="$1" dst="$2"; shift 2
+ [ -d "$src" ] || die "нет папки $src"
+ local args=() p
+ for p in "$@"; do args+=("--exclude=$p"); done
+ ssh_cmd "mkdir -p '$dst'"
+ rsync -rlptz --delete --no-perms --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \
+ -e "ssh $DEPLOY_SSH_OPTS" "${args[@]}" "$src/" "$DEPLOY_SSH:$dst/"
+}
+
+verify_dir() {
+ local src="$1" dst="$2"; shift 2
+ local ex="$*"
+ local tmp; tmp="$(mktemp -d)"
+ (cd "$src" && find . -type f -print0 | xargs -0 "${MD5_CMD[@]}" | sed -E 's#^([0-9a-f]+) +\./#\1 #' | LC_ALL=C sort -k2) | md5_filter "$ex" > "$tmp/local"
+ ssh_cmd "cd '$dst' && find . -type f -print0 | xargs -0 -r md5sum | sed 's# \./# #' | LC_ALL=C sort -k2" | md5_filter "$ex" > "$tmp/remote"
+ local n; n=$(wc -l < "$tmp/local" | tr -d ' ')
+ if diff -u "$tmp/local" "$tmp/remote" > "$tmp/diff"; then
+ echo "md5: совпадает ($n файлов; исключены: $ex)"
+ rm -rf "$tmp"
+ else
+ echo "md5: РАСХОЖДЕНИЕ" >&2
+ cat "$tmp/diff" >&2
+ rm -rf "$tmp"
+ return 1
+ fi
+}
diff --git a/scripts/_plan-lib.sh b/scripts/_plan-lib.sh
new file mode 100755
index 0000000..df0a968
--- /dev/null
+++ b/scripts/_plan-lib.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+ENV_FILE="${DEPLOY_ENV:-$ROOT/.env.deploy}"
+[ -f "$ENV_FILE" ] && set -a && . "$ENV_FILE" && set +a
+
+HOUSE_URL="${HOUSE_URL:-${DEPLOY_URL:-}}"
+HOUSE_URL="${HOUSE_URL%/}"
+HOUSE_PASSWORD="${HOUSE_PASSWORD:-}"
+CLIENT_VERSION="${HOUSE_CLIENT_VERSION:-$(sed -n 's/^export const CLIENT_VERSION = \([0-9]*\).*/\1/p' "$ROOT/src/model/schema.ts")}"
+API="$HOUSE_URL/api"
+
+die() { echo "$*" >&2; exit 1; }
+
+[ -n "$HOUSE_URL" ] || die "нет HOUSE_URL (адрес сайта, напр. https://plan.example.com) — в env или .env.deploy"
+[ -n "$HOUSE_PASSWORD" ] || die "нет HOUSE_PASSWORD — в env или .env.deploy"
+command -v curl >/dev/null || die "нет curl"
+command -v python3 >/dev/null || die "нет python3"
+
+JAR="$(mktemp)"
+cleanup_jar() { rm -f "$JAR"; }
+
+house_login() {
+ local body code
+ body="$(python3 -c 'import json,sys; print(json.dumps({"password": sys.argv[1]}))' "$HOUSE_PASSWORD")"
+ code="$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR" -X POST \
+ -H 'Content-Type: application/json' -H 'X-Requested-With: plan-cli' \
+ --data-binary "$body" "$API/login.php")"
+ case "$code" in
+ 200) ;;
+ 401) die "неверный пароль (HOUSE_PASSWORD)" ;;
+ 503) die "планировщик не установлен: откройте $API/setup.php" ;;
+ *) die "вход не удался: HTTP $code от $API/login.php" ;;
+ esac
+}
diff --git a/scripts/demo-reset.php b/scripts/demo-reset.php
new file mode 100644
index 0000000..ce1aa7b
--- /dev/null
+++ b/scripts/demo-reset.php
@@ -0,0 +1,47 @@
+<?php
+
+// Hourly reset of the public demo: current.json back to plans/demo.json,
+// versions and snapshots older than an hour removed, data/ and plans/ opened.
+// Cron, as the web server user:
+// 0 * * * * php /path/to/scripts/demo-reset.php --webroot=/path/to/site
+// --webroot defaults to ../public next to this script (dev checkout).
+
+if (PHP_SAPI !== 'cli') {
+ http_response_code(404);
+ exit;
+}
+
+$webroot = dirname(__DIR__) . '/public';
+foreach (array_slice($argv, 1) as $arg) {
+ if (strncmp($arg, '--webroot=', 10) === 0) {
+ $webroot = rtrim(substr($arg, 10), '/');
+ } else {
+ fwrite(STDERR, "использование: php scripts/demo-reset.php [--webroot=<корень сайта>]\n");
+ exit(2);
+ }
+}
+
+$lib = $webroot . '/api/_lib.php';
+if (!is_file($lib)) {
+ fwrite(STDERR, "нет $lib — укажите --webroot\n");
+ exit(2);
+}
+require $lib;
+
+if (find_storage() === null) {
+ fwrite(STDERR, "хранилище не найдено: планировщик не установлен\n");
+ exit(1);
+}
+if (!is_demo()) {
+ fwrite(STDERR, "демо-режим выключен ('demo' => true в config.php или HOUSE_DEMO=1), сброс не выполняется\n");
+ exit(1);
+}
+
+$r = demo_reset(false);
+printf(
+ "сброшено: rev %d, %s, удалено версий %d, снимков %d\n",
+ $r['rev'],
+ $r['updatedAt'],
+ $r['versionsDropped'],
+ $r['snapshotsDropped']
+);
diff --git a/scripts/demo/build-demo.mts b/scripts/demo/build-demo.mts
new file mode 100644
index 0000000..ad206ff
--- /dev/null
+++ b/scripts/demo/build-demo.mts
@@ -0,0 +1,711 @@
+import { writeFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import proj4 from 'proj4'
+import { close, load } from './vite-load.mts'
+
+type Pt = { x: number; y: number }
+type Rect = { x0: number; y0: number; x1: number; y1: number }
+type Side = 'N' | 'S' | 'E' | 'W'
+type Any = Record<string, unknown>
+
+const root = fileURLToPath(new URL('../..', import.meta.url))
+const out = (p: string) => `${root}/${p}`
+
+const ROAD = { lat: 59.300621, lng: 24.857898, bearingDeg: -27.92 }
+const ROTATION = ROAD.bearingDeg + 180
+const LOT = { w: 30000, d: 45000, roadOffsetM: 4 }
+
+const rad = (d: number) => (d * Math.PI) / 180
+const aeqd = (lat: number, lng: number) => proj4('WGS84', `+proj=aeqd +lat_0=${lat} +lon_0=${lng} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs`)
+const xAxis = { e: Math.cos(rad(ROTATION)), n: Math.sin(rad(ROTATION)) }
+const yAxis = { e: Math.sin(rad(ROTATION)), n: -Math.cos(rad(ROTATION)) }
+
+const streetMid = { e: -LOT.roadOffsetM * yAxis.e, n: -LOT.roadOffsetM * yAxis.n }
+const v0 = {
+ e: streetMid.e - (LOT.w / 2000) * xAxis.e - (LOT.d / 1000) * yAxis.e,
+ n: streetMid.n - (LOT.w / 2000) * xAxis.n - (LOT.d / 1000) * yAxis.n,
+}
+const [originLng, originLat] = aeqd(ROAD.lat, ROAD.lng).inverse([v0.e, v0.n])
+const geo = { lat: Math.round(originLat * 1e8) / 1e8, lng: Math.round(originLng * 1e8) / 1e8, rotationDeg: Math.round(ROTATION * 1000) / 1000 }
+
+const toLngLat = (p: Pt): [number, number] => {
+ const c = Math.cos(rad(geo.rotationDeg))
+ const s = Math.sin(rad(geo.rotationDeg))
+ const e = (p.x * c + p.y * s) / 1000
+ const n = (p.x * s - p.y * c) / 1000
+ const [lng, lat] = aeqd(geo.lat, geo.lng).inverse([e, n])
+ return [Math.round(lng * 1e8) / 1e8, Math.round(lat * 1e8) / 1e8]
+}
+const ring = (pts: Pt[]) => {
+ const r = pts.map(toLngLat)
+ return [[...r, r[0]]]
+}
+const rectPts = (x0: number, y0: number, x1: number, y1: number): Pt[] => [
+ { x: x0, y: y0 },
+ { x: x1, y: y0 },
+ { x: x1, y: y1 },
+ { x: x0, y: y1 },
+]
+
+const walls: Any[] = []
+const openings: Any[] = []
+const furniture: Any[] = []
+const rooms: Any[] = []
+const wallById = new Map<string, Any>()
+
+function wall(id: string, a: Pt, b: Pt, thickness: number, materialId: string, note?: string) {
+ const w = { id, a, b, thickness, height: 2800, materialId, ...(note ? { note } : {}) }
+ walls.push(w)
+ wallById.set(id, w)
+}
+
+const unit = (w: Any) => {
+ const a = w.a as Pt
+ const b = w.b as Pt
+ const len = Math.hypot(b.x - a.x, b.y - a.y)
+ return { ux: (b.x - a.x) / len, uy: (b.y - a.y) / len, len, a }
+}
+
+const along = (w: Any, p: Pt) => {
+ const { ux, uy, a } = unit(w)
+ return (p.x - a.x) * ux + (p.y - a.y) * uy
+}
+
+function opening(id: string, wallId: string, type: 'door' | 'window' | 'gate', from: number, to: number, height: number, sill: number, extra: Any = {}) {
+ const w = wallById.get(wallId)!
+ const horizontal = (w.a as Pt).y === (w.b as Pt).y
+ const pa = horizontal ? { x: from, y: (w.a as Pt).y } : { x: (w.a as Pt).x, y: from }
+ const pb = horizontal ? { x: to, y: (w.a as Pt).y } : { x: (w.a as Pt).x, y: to }
+ const t0 = along(w, pa)
+ const t1 = along(w, pb)
+ const offset = Math.round(Math.min(t0, t1))
+ const width = Math.round(Math.abs(t1 - t0))
+ openings.push({ id, wallId, type, offset, width, height, sill, ...extra })
+ return { offset, width }
+}
+
+function door(id: string, wallId: string, from: number, to: number, opensToward: Pt, hingeAt: number, height = 2000, note?: string) {
+ const w = wallById.get(wallId)!
+ const { ux, uy } = unit(w)
+ const nRight = { x: -uy, y: ux }
+ const mid = horizontalPoint(w, (from + to) / 2)
+ const side = (opensToward.x - mid.x) * nRight.x + (opensToward.y - mid.y) * nRight.y > 0 ? 'right' : 'left'
+ const tHinge = along(w, horizontalPoint(w, hingeAt))
+ const tFrom = along(w, horizontalPoint(w, from))
+ const tTo = along(w, horizontalPoint(w, to))
+ const hinge = Math.abs(tHinge - Math.min(tFrom, tTo)) < 1 ? 'start' : 'end'
+ opening(id, wallId, 'door', from, to, height, 0, { hinge, side, ...(note ? { note } : {}) })
+}
+
+function horizontalPoint(w: Any, v: number): Pt {
+ const horizontal = (w.a as Pt).y === (w.b as Pt).y
+ return horizontal ? { x: v, y: (w.a as Pt).y } : { x: (w.a as Pt).x, y: v }
+}
+
+const CATALOG_DIMS: Record<string, [w: number, d: number]> = {
+ 'bed-1600': [1700, 2100],
+ nightstand: [450, 400],
+ wardrobe: [1200, 600],
+ dresser: [1000, 450],
+ sofa: [2200, 950],
+ armchair: [850, 850],
+ 'coffee-table': [1100, 600],
+ 'tv-stand': [1600, 420],
+ bookcase: [800, 350],
+ plant: [450, 450],
+ 'kitchen-base': [600, 600],
+ 'kitchen-drawers': [600, 600],
+ 'kitchen-upper': [600, 330],
+ 'kitchen-sink': [800, 600],
+ stove: [600, 600],
+ dishwasher: [600, 600],
+ fridge: [600, 650],
+ 'dining-6': [1800, 1700],
+ toilet: [380, 680],
+ washbasin: [600, 460],
+ vanity: [800, 480],
+ bathtub: [1700, 750],
+ shower: [900, 900],
+ washer: [600, 600],
+ 'water-heater': [450, 470],
+ 'shoe-cabinet': [800, 320],
+ 'hall-wardrobe': [1600, 600],
+ desk: [1200, 600],
+ 'office-chair': [650, 650],
+ 'floor-boiler': [500, 650],
+}
+
+const ROT: Record<Side, number> = { N: 0, E: 90, S: 180, W: 270 }
+
+function put(id: string, type: string, room: Rect, side: Side, pos: number, opts: { w?: number; d?: number; h?: number; color?: string; note?: string; gap?: number } = {}) {
+ const d = opts.d ?? CATALOG_DIMS[type]?.[1] ?? 600
+ const gap = opts.gap ?? 0
+ const x = side === 'E' ? room.x1 - d / 2 - gap : side === 'W' ? room.x0 + d / 2 + gap : pos
+ const y = side === 'N' ? room.y0 + d / 2 + gap : side === 'S' ? room.y1 - d / 2 - gap : pos
+ const item: Any = { id, type, x: Math.round(x), y: Math.round(y), rotationDeg: ROT[side] }
+ if (opts.w !== undefined) item.w = opts.w
+ if (opts.d !== undefined) item.d = opts.d
+ if (opts.h !== undefined) item.h = opts.h
+ if (opts.color) item.color = opts.color
+ if (opts.note) item.note = opts.note
+ furniture.push(item)
+ return item
+}
+
+function free(id: string, type: string, x: number, y: number, rotationDeg = 0, opts: { w?: number; d?: number; color?: string; note?: string } = {}) {
+ const item: Any = { id, type, x, y, rotationDeg, ...opts }
+ furniture.push(item)
+ return item
+}
+
+const room = (id: string, name: string, kind: string, r: Rect, at?: Pt) =>
+ rooms.push({ id, name, kind, x: Math.round(at?.x ?? (r.x0 + r.x1) / 2), y: Math.round(at?.y ?? (r.y0 + r.y1) / 2) })
+
+const EXT = 400
+const PART = 120
+const H = { x0: 4200, y0: 17200, x1: 19000, y1: 26400 }
+const P = {
+ p1: 8000,
+ p2: 9800,
+ p3: 19700,
+ p4: 21800,
+ p5: 23000,
+ p6: 8000,
+ p7: 11400,
+ p8: 13800,
+ p9: 16400,
+ p10: 24000,
+}
+const h = PART / 2
+const e = EXT / 2
+
+wall('ext-back', { x: H.x0, y: H.y0 }, { x: H.x1, y: H.y0 }, EXT, 'teploblok-400', 'Garden facade (south-west)')
+wall('ext-right', { x: H.x1, y: H.y0 }, { x: H.x1, y: H.y1 }, EXT, 'teploblok-400', 'Kitchen / utility gable')
+wall('ext-front', { x: H.x1, y: H.y1 }, { x: H.x0, y: H.y1 }, EXT, 'teploblok-400', 'Street facade (north-east)')
+wall('ext-left', { x: H.x0, y: H.y1 }, { x: H.x0, y: H.y0 }, EXT, 'teploblok-400', 'Bedroom gable')
+wall('p1', { x: P.p1, y: H.y0 }, { x: P.p1, y: P.p4 }, PART, 'partition-120')
+wall('p2', { x: P.p2, y: H.y0 }, { x: P.p2, y: P.p4 }, PART, 'partition-120')
+wall('p3', { x: P.p1, y: P.p3 }, { x: P.p2, y: P.p3 }, PART, 'partition-120')
+wall('p4', { x: H.x0, y: P.p4 }, { x: H.x1, y: P.p4 }, PART, 'partition-120')
+wall('p5', { x: H.x0, y: P.p5 }, { x: P.p8, y: P.p5 }, PART, 'partition-120')
+wall('p6', { x: P.p6, y: P.p5 }, { x: P.p6, y: H.y1 }, PART, 'partition-120')
+wall('p7', { x: P.p7, y: P.p5 }, { x: P.p7, y: H.y1 }, PART, 'partition-120')
+wall('p8', { x: P.p8, y: P.p5 }, { x: P.p8, y: H.y1 }, PART, 'partition-120')
+wall('p9', { x: P.p9, y: P.p4 }, { x: P.p9, y: H.y1 }, PART, 'partition-120')
+wall('p11', { x: P.p8, y: P.p4 }, { x: P.p8, y: P.p5 }, PART, 'partition-120')
+wall('p10', { x: P.p9, y: P.p10 }, { x: H.x1, y: P.p10 }, PART, 'partition-120')
+
+const G = { x0: 22100, y0: 32100, x1: 28900, y1: 38500 }
+const GT = 200
+wall('g-back', { x: G.x0, y: G.y0 }, { x: G.x1, y: G.y0 }, GT, 'smartblock-200')
+wall('g-right', { x: G.x1, y: G.y0 }, { x: G.x1, y: G.y1 }, GT, 'smartblock-200')
+wall('g-front', { x: G.x1, y: G.y1 }, { x: G.x0, y: G.y1 }, GT, 'smartblock-200', 'Gate wall, faces the street')
+wall('g-left', { x: G.x0, y: G.y1 }, { x: G.x0, y: G.y0 }, GT, 'smartblock-200')
+
+const R = {
+ master: { x0: H.x0 + e, y0: H.y0 + e, x1: P.p1 - h, y1: P.p4 - h },
+ ensuite: { x0: P.p1 + h, y0: H.y0 + e, x1: P.p2 - h, y1: P.p3 - h },
+ wic: { x0: P.p1 + h, y0: P.p3 + h, x1: P.p2 - h, y1: P.p4 - h },
+ living: { x0: P.p2 + h, y0: H.y0 + e, x1: H.x1 - e, y1: P.p4 - h },
+ corridor: { x0: H.x0 + e, y0: P.p4 + h, x1: P.p8 - h, y1: P.p5 - h },
+ entry: { x0: P.p8 + h, y0: P.p4 + h, x1: P.p9 - h, y1: H.y1 - e },
+ bed2: { x0: H.x0 + e, y0: P.p5 + h, x1: P.p6 - h, y1: H.y1 - e },
+ bed3: { x0: P.p6 + h, y0: P.p5 + h, x1: P.p7 - h, y1: H.y1 - e },
+ bath: { x0: P.p7 + h, y0: P.p5 + h, x1: P.p8 - h, y1: H.y1 - e },
+ pantry: { x0: P.p9 + h, y0: P.p4 + h, x1: H.x1 - e, y1: P.p10 - h },
+ utility: { x0: P.p9 + h, y0: P.p10 + h, x1: H.x1 - e, y1: H.y1 - e },
+ garage: { x0: G.x0 + GT / 2, y0: G.y0 + GT / 2, x1: G.x1 - GT / 2, y1: G.y1 - GT / 2 },
+}
+const center = (r: Rect): Pt => ({ x: (r.x0 + r.x1) / 2, y: (r.y0 + r.y1) / 2 })
+
+room('r-living', 'Living / Kitchen', 'living', R.living, { x: 11800, y: 21000 })
+room('r-master', 'Master bedroom', 'bedroom', R.master, { x: 6100, y: 17950 })
+room('r-ensuite', 'En-suite', 'bath', R.ensuite, { x: 8600, y: 19250 })
+room('r-wic', 'Walk-in closet', 'storage', R.wic, { x: 8600, y: 21350 })
+room('r-hall', 'Hall', 'hall', R.entry, { x: 15100, y: 22500 })
+room('r-corridor', 'Corridor', 'hall', R.corridor, { x: 10800, y: 22400 })
+room('r-bed2', 'Bedroom 2', 'bedroom', R.bed2, { x: 6150, y: 25750 })
+room('r-bed3', 'Bedroom 3', 'bedroom', R.bed3, { x: 9500, y: 25750 })
+room('r-bath', 'Bathroom', 'bath', R.bath, { x: 12600, y: 23300 })
+room('r-pantry', 'Pantry', 'storage', R.pantry, { x: 17200, y: 22300 })
+room('r-utility', 'Utility / Boiler', 'tech', R.utility, { x: 17300, y: 25200 })
+room('r-garage', 'Garage', 'garage', R.garage, { x: 25500, y: 35300 })
+
+door('d-front', 'ext-front', 14700, 15660, center(R.entry), 15660, 2100, 'Entrance door with thermal break, 960 × 2100')
+door('d-terrace', 'ext-back', 14000, 15000, { x: 14500, y: 16000 }, 15000, 2200, 'Glazed terrace door, opens outward')
+door('d-lk', 'p4', 14800, 15700, center(R.living), 14800, 2000, 'Glazed door hall → living')
+door('d-corr', 'p11', 21950, 22850, { x: 13000, y: 22400 }, 21950, 2000, 'Glazed door hall → bedroom corridor')
+door('d-living2', 'p4', 12300, 13200, center(R.living), 13200, 2000, 'Glazed door corridor → living')
+door('d-master', 'p4', 7000, 7800, center(R.master), 7800)
+door('d-ensuite', 'p1', 18300, 19000, center(R.ensuite), 18300)
+door('d-wic', 'p1', 20300, 21000, center(R.wic), 21000)
+door('d-bed2', 'p5', 7000, 7800, center(R.bed2), 7800)
+door('d-bed3', 'p5', 8200, 9000, center(R.bed3), 8200)
+door('d-bath', 'p5', 11800, 12500, center(R.bath), 11800)
+door('d-pantry', 'p9', 22300, 23100, center(R.pantry), 22300)
+door('d-utility', 'p9', 24300, 25100, center(R.utility), 24300)
+door('d-garage', 'g-left', 34000, 34900, center(R.garage), 34900, 2100, 'Side door towards the house')
+
+opening('win-master', 'ext-back', 'window', 5300, 7100, 1500, 800)
+opening('win-ensuite', 'ext-back', 'window', 8750, 9350, 600, 1500)
+opening('win-living', 'ext-back', 'window', 10400, 12800, 1500, 700)
+opening('win-dining', 'ext-back', 'window', 15500, 17500, 1500, 800)
+opening('win-kitchen', 'ext-right', 'window', 18500, 19500, 1000, 1100)
+opening('win-utility', 'ext-right', 'window', 24900, 25500, 600, 1500)
+opening('win-bath', 'ext-front', 'window', 12400, 13300, 600, 1500)
+opening('win-bed3', 'ext-front', 'window', 9200, 10700, 1400, 800)
+opening('win-bed2', 'ext-front', 'window', 5200, 6700, 1400, 800)
+opening('win-bed2-side', 'ext-left', 'window', 24200, 25200, 1400, 800)
+opening('win-hall', 'ext-front', 'window', 15900, 16200, 1500, 600)
+opening('gate-1', 'g-front', 'gate', 25800, 28300, 2250, 0, { side: 'right', note: 'Sectional door 2500 × 2250' })
+opening('gate-2', 'g-front', 'gate', 22700, 25200, 2250, 0, { side: 'right', note: 'Sectional door 2500 × 2250' })
+opening('win-garage', 'g-back', 'window', 25000, 26000, 600, 1500)
+
+const OAK = '#c9a27a'
+const LINEN = '#e8e2d6'
+const GRAPHITE = '#4b4f54'
+
+put('f-m-bed', 'bed-1600', R.master, 'W', 19500, { color: LINEN })
+put('f-m-ns1', 'nightstand', R.master, 'W', 18400, { color: OAK })
+put('f-m-ns2', 'nightstand', R.master, 'W', 20600, { color: OAK })
+put('f-m-dresser', 'dresser', R.master, 'S', 5300, { color: OAK })
+free('f-m-chair', 'armchair', 7460, 17860, 0, { color: GRAPHITE })
+
+put('f-es-shower', 'shower', R.ensuite, 'N', R.ensuite.x1 - 450)
+put('f-es-wc', 'toilet', R.ensuite, 'E', 19000)
+put('f-es-basin', 'washbasin', R.ensuite, 'N', R.ensuite.x0 + 300)
+
+put('f-wic-wardrobe', 'wardrobe', R.wic, 'E', 20750, { w: 1800, color: OAK })
+
+put('f-k-fridge', 'fridge', R.living, 'E', 17700)
+put('f-k-base1', 'kitchen-base', R.living, 'E', 18300, { color: LINEN })
+put('f-k-sink', 'kitchen-sink', R.living, 'E', 19000, { color: LINEN })
+put('f-k-dw', 'dishwasher', R.living, 'E', 19700)
+put('f-k-stove', 'stove', R.living, 'E', 20300)
+put('f-k-drawers', 'kitchen-drawers', R.living, 'E', 20900, { color: LINEN })
+put('f-k-base2', 'kitchen-base', R.living, 'E', 21470, { w: 540, color: LINEN })
+put('f-k-upper', 'kitchen-upper', R.living, 'E', 20600, { w: 1200, color: LINEN })
+free('f-dining', 'dining-6', 16200, 19400, 0, { color: OAK })
+put('f-tv', 'tv-stand', R.living, 'W', 19500, { color: OAK })
+free('f-sofa', 'sofa', 13100, 19500, 90, { color: '#8a9099' })
+free('f-coffee', 'coffee-table', 11450, 19500, 90, { color: OAK })
+put('f-books', 'bookcase', R.living, 'S', 11000, { color: OAK })
+free('f-plant1', 'plant', 10200, 17750)
+
+put('f-h-wardrobe', 'hall-wardrobe', R.entry, 'W', 24400, { color: OAK })
+put('f-h-shoes', 'shoe-cabinet', R.entry, 'E', 25700, { color: OAK })
+
+put('f-b2-bed', 'bed-1600', R.bed2, 'N', 5750, { color: LINEN })
+put('f-b2-ns', 'nightstand', R.bed2, 'N', R.bed2.x0 + 225, { color: OAK })
+put('f-b2-wardrobe', 'wardrobe', R.bed2, 'E', 25650, { w: 1000, color: OAK })
+free('f-b2-plant', 'plant', R.bed2.x0 + 250, R.bed2.y1 - 250)
+
+put('f-b3-bed', 'bed-1600', R.bed3, 'N', 10000, { color: LINEN })
+put('f-b3-ns', 'nightstand', R.bed3, 'N', R.bed3.x1 - 225, { color: OAK })
+put('f-b3-wardrobe', 'wardrobe', R.bed3, 'W', 25650, { w: 1000, color: OAK })
+
+put('f-ba-tub', 'bathtub', R.bath, 'S', R.bath.x0 + 850)
+put('f-ba-wc', 'toilet', R.bath, 'E', 24300)
+put('f-ba-vanity', 'vanity', R.bath, 'W', 24300, { color: OAK })
+
+put('f-p-shelf', 'bookcase', R.pantry, 'E', 22900, { w: 1800, color: LINEN, note: 'Pantry shelving' })
+
+put('f-u-hp', 'floor-boiler', R.utility, 'E', 24500, { note: 'Air-to-water heat pump, indoor unit' })
+put('f-u-washer', 'washer', R.utility, 'S', 18350)
+put('f-u-heater', 'water-heater', R.utility, 'N', 17200, { note: 'Electric water heater, 80 L' })
+
+put('f-g-bench', 'desk', R.garage, 'N', 24200, { w: 1600, color: OAK, note: 'Workbench' })
+
+const site = {
+ convention: 'y-down-clockwise',
+ width: LOT.w,
+ depth: LOT.d,
+ geo,
+ boundary: rectPts(0, 0, LOT.w, LOT.d),
+ zones: [
+ { id: 'zone-lawn', name: 'Lawn', kind: 'lawn', polygon: rectPts(500, 500, 29500, 44500) },
+ { id: 'zone-terrace', name: 'Terrace', kind: 'paving', polygon: rectPts(9600, 13800, 17600, 17000) },
+ { id: 'zone-drive', name: 'Driveway', kind: 'paving', polygon: rectPts(22000, 38600, 29000, 45000) },
+ { id: 'zone-path', name: 'Front path', kind: 'paving', polygon: rectPts(14500, 26600, 15900, 45000) },
+ { id: 'zone-gravel', name: 'Gravel parking', kind: 'fill', polygon: rectPts(17000, 40000, 21500, 45000) },
+ ],
+ street: { side: [2, 3], note: 'Demo Lane' },
+ imagery: { offsetE: 0, offsetN: 0, rotationDeg: 0 },
+ note: 'Demo plot 30 × 45 m in an open field near Kiili, Harju County, Estonia. Fictional lot; street side 2–3 (bottom of the plan) faces the gravel road.',
+}
+
+const sn: Any[] = []
+const sp: Any[] = []
+const snode = (id: string, x: number, y: number, kind: string, extra: Any = {}) => sn.push({ id, x, y, kind, ...extra })
+const spipe = (id: string, from: string, to: string, diameter: number, location: 'inside' | 'outside', extra: Any = {}) =>
+ sp.push({ id, from, to, diameter, slope: diameter === 50 ? 3 : 2, location, ...extra })
+
+snode('s-es-shower', 9290, 17850, 'fixture', { fixture: 'shower', furnitureId: 'f-es-shower', label: 'En-suite shower' })
+snode('s-es-basin', 8360, 17550, 'fixture', { fixture: 'sink', furnitureId: 'f-es-basin', label: 'En-suite basin' })
+snode('s-es-wc', 9590, 19000, 'fixture', { fixture: 'toilet', furnitureId: 'f-es-wc', label: 'En-suite WC' })
+snode('s-t1', 9600, 19300, 'junction', { label: 'Tee 45°' })
+snode('s-c1', 9600, 21900, 'junction', { label: 'Bend 45°' })
+snode('s-c2', 10100, 22400, 'junction', { label: 'Bend 45°' })
+snode('s-c3', 12900, 22400, 'junction', { label: 'Bend 45°' })
+snode('s-c4', 13600, 23100, 'junction', { label: 'Bend 45°' })
+snode('s-ba-wc', 13400, 24300, 'fixture', { fixture: 'toilet', furnitureId: 'f-ba-wc', label: 'Bathroom WC' })
+snode('s-ba-basin', 11600, 24300, 'fixture', { fixture: 'sink', furnitureId: 'f-ba-vanity', label: 'Bathroom basin' })
+snode('s-ba-tub', 12310, 25825, 'fixture', { fixture: 'bath', furnitureId: 'f-ba-tub', label: 'Bathtub' })
+snode('s-riser', 13600, 26000, 'riser', { height: 4000, label: 'Soil stack Ø110, vented through the roof' })
+snode('s-k-sink', 18600, 19000, 'fixture', { fixture: 'kitchen', furnitureId: 'f-k-sink', label: 'Kitchen sink' })
+snode('s-k-dw', 18300, 19700, 'fixture', { fixture: 'kitchen', furnitureId: 'f-k-dw', label: 'Dishwasher' })
+snode('s-k1', 18600, 19700, 'junction', { label: 'Tee 45°' })
+snode('s-u-hp', 18300, 24900, 'fixture', { fixture: 'boiler', furnitureId: 'f-u-hp', label: 'Heat pump safety valve drain' })
+snode('s-u-washer', 18350, 25700, 'fixture', { fixture: 'washer', furnitureId: 'f-u-washer', label: 'Washing machine' })
+snode('s-u1', 18600, 25300, 'junction', { label: 'Tee 45°' })
+snode('s-u2', 17900, 26000, 'junction', { label: 'Bend 45°' })
+snode('s-out', 13600, 26600, 'outlet', { label: 'Outlet through the foundation in a sleeve' })
+snode('s-o1', 13600, 27600, 'cleanout', { label: 'Inspection chamber' })
+snode('s-septic', 2200, 43300, 'septic', { model: 'Compact treatment plant, 5 PE', w: 1200, d: 1200, rotationDeg: 0, label: 'Treatment plant' })
+
+spipe('sp1', 's-es-shower', 's-t1', 50, 'inside')
+spipe('sp2', 's-es-basin', 's-t1', 50, 'inside')
+spipe('sp3', 's-es-wc', 's-t1', 110, 'inside')
+spipe('sp4', 's-t1', 's-c1', 110, 'inside')
+spipe('sp5', 's-c1', 's-c2', 110, 'inside')
+spipe('sp6', 's-c2', 's-c3', 110, 'inside')
+spipe('sp7', 's-c3', 's-c4', 110, 'inside')
+spipe('sp8', 's-c4', 's-riser', 110, 'inside')
+spipe('sp9', 's-ba-wc', 's-riser', 110, 'inside')
+spipe('sp10', 's-ba-basin', 's-riser', 50, 'inside')
+spipe('sp11', 's-ba-tub', 's-riser', 50, 'inside')
+spipe('sp12', 's-k-sink', 's-k1', 50, 'inside')
+spipe('sp13', 's-k-dw', 's-k1', 50, 'inside')
+spipe('sp14', 's-k1', 's-u1', 50, 'inside')
+spipe('sp15', 's-u-hp', 's-u1', 50, 'inside')
+spipe('sp16', 's-u-washer', 's-u1', 50, 'inside')
+spipe('sp17', 's-u1', 's-u2', 50, 'inside')
+spipe('sp18', 's-u2', 's-riser', 50, 'inside')
+spipe('sp19', 's-riser', 's-out', 110, 'inside')
+spipe('sp20', 's-out', 's-o1', 110, 'outside', { depth: 1200 })
+spipe('sp21', 's-o1', 's-septic', 110, 'outside')
+
+const wn: Any[] = []
+const wp: Any[] = []
+const wnode = (id: string, x: number, y: number, kind: string, extra: Any = {}) => wn.push({ id, x, y, kind, ...extra })
+const wpipe = (id: string, from: string, to: string, line: string, diameter: number, location: 'inside' | 'outside', extra: Any = {}) =>
+ wp.push({ id, from, to, line, diameter, material: location === 'outside' ? 'PE' : 'PEX', location, ...extra })
+
+wnode('w-src', 29200, 800, 'source', { source: 'borehole', label: 'Borehole, 50 m from the treatment plant' })
+wnode('w-j1', 21000, 25000, 'junction', { label: 'Turn to the house' })
+wnode('w-entry', 19000, 25000, 'entry', { label: 'Entry in a Ø50 sleeve below frost depth' })
+wnode('w-pump', 18500, 25000, 'pump', { model: 'Pressure tank 50 L + pressure switch', label: 'Hydrophore' })
+wnode('w-filter', 18050, 25000, 'filter', { label: 'Sediment + 20" cartridge filter' })
+wnode('w-cold', 17600, 25000, 'collector', { line: 'cold', outputs: 11, label: 'Cold manifold' })
+wnode('w-heater', 17200, 24300, 'boiler', { furnitureId: 'f-u-heater', model: '80 L', label: 'Water heater' })
+wnode('w-hot', 16900, 24700, 'collector', { line: 'hot', outputs: 5, label: 'Hot manifold' })
+wnode('w-tap', 15200, 17000, 'tap_outdoor', { label: 'Frost-free garden tap on the terrace' })
+
+wpipe('wp-src', 'w-src', 'w-j1', 'cold', 32, 'outside', { depth: 1800 })
+wpipe('wp-in', 'w-j1', 'w-entry', 'cold', 32, 'outside', { depth: 1800 })
+wpipe('wp-pump', 'w-entry', 'w-pump', 'cold', 25, 'inside')
+wpipe('wp-filter', 'w-pump', 'w-filter', 'cold', 25, 'inside')
+wpipe('wp-cold', 'w-filter', 'w-cold', 'cold', 25, 'inside')
+wpipe('wp-heater', 'w-cold', 'w-heater', 'cold', 20, 'inside')
+wpipe('wp-hot', 'w-heater', 'w-hot', 'hot', 20, 'inside')
+
+const fixturesWater: { id: string; fixture: string; furnitureId: string; at: Pt; hot: boolean; label: string }[] = [
+ { id: 'w-k-sink', fixture: 'kitchen', furnitureId: 'f-k-sink', at: { x: 18500, y: 19000 }, hot: true, label: 'Kitchen sink' },
+ { id: 'w-k-dw', fixture: 'kitchen', furnitureId: 'f-k-dw', at: { x: 18500, y: 19700 }, hot: false, label: 'Dishwasher' },
+ { id: 'w-u-washer', fixture: 'washer', furnitureId: 'f-u-washer', at: { x: 18350, y: 25800 }, hot: false, label: 'Washing machine' },
+ { id: 'w-ba-wc', fixture: 'toilet', furnitureId: 'f-ba-wc', at: { x: 13500, y: 24300 }, hot: false, label: 'Bathroom WC' },
+ { id: 'w-ba-basin', fixture: 'sink', furnitureId: 'f-ba-vanity', at: { x: 11600, y: 24300 }, hot: true, label: 'Bathroom basin' },
+ { id: 'w-ba-tub', fixture: 'bath', furnitureId: 'f-ba-tub', at: { x: 12310, y: 25700 }, hot: true, label: 'Bathtub' },
+ { id: 'w-es-wc', fixture: 'toilet', furnitureId: 'f-es-wc', at: { x: 9500, y: 19000 }, hot: false, label: 'En-suite WC' },
+ { id: 'w-es-basin', fixture: 'sink', furnitureId: 'f-es-basin', at: { x: 8360, y: 17600 }, hot: true, label: 'En-suite basin' },
+ { id: 'w-es-shower', fixture: 'shower', furnitureId: 'f-es-shower', at: { x: 9290, y: 17850 }, hot: true, label: 'En-suite shower' },
+]
+for (const f of fixturesWater) wnode(f.id, f.at.x, f.at.y, 'fixture', { fixture: f.fixture, furnitureId: f.furnitureId, label: f.label })
+
+const coldNode = { x: 17600, y: 25000 }
+const hotNode = { x: 16900, y: 24700 }
+let lane = 0
+function radial(prefix: string, from: string, fromAt: Pt, to: string, toAt: Pt, line: 'cold' | 'hot') {
+ const k = lane++
+ const laneY = 22300 + (k % 14) * 45
+ const sx = fromAt.x - 40 - (k % 14) * 30
+ const j1 = `${prefix}-a`
+ const j2 = `${prefix}-b`
+ const nearLane = Math.abs(toAt.y - laneY) < 400
+ if (nearLane) {
+ wnode(j1, sx, toAt.y, 'junction')
+ wpipe(`${prefix}-1`, from, j1, line, 16, 'inside')
+ wpipe(`${prefix}-2`, j1, to, line, 16, 'inside')
+ return
+ }
+ wnode(j1, sx, laneY, 'junction')
+ wnode(j2, toAt.x + (toAt.x > sx ? -150 : 150), laneY, 'junction')
+ wpipe(`${prefix}-1`, from, j1, line, 16, 'inside')
+ wpipe(`${prefix}-2`, j1, j2, line, 16, 'inside')
+ wpipe(`${prefix}-3`, j2, to, line, 16, 'inside')
+}
+for (const f of fixturesWater) {
+ if (f.id === 'w-u-washer') {
+ wpipe('wl-washer', 'w-cold', f.id, 'cold', 16, 'inside')
+ continue
+ }
+ radial(`wc-${f.id.slice(2)}`, 'w-cold', coldNode, f.id, f.at, 'cold')
+ if (f.hot) radial(`wh-${f.id.slice(2)}`, 'w-hot', hotNode, f.id, f.at, 'hot')
+}
+wnode('w-tap-a', 15200, 23600, 'junction')
+wpipe('wl-tap-1', 'w-cold', 'w-tap-a', 'cold', 16, 'inside')
+wpipe('wl-tap-2', 'w-tap-a', 'w-tap', 'cold', 16, 'inside')
+
+const ep: Any[] = []
+const faceOf = (wallId: string, v: number, toward: Pt) => {
+ const w = wallById.get(wallId)!
+ const p = horizontalPoint(w, v)
+ const half = (w.thickness as number) / 2
+ const horizontal = (w.a as Pt).y === (w.b as Pt).y
+ if (horizontal) return { x: p.x, y: p.y + (toward.y > p.y ? half : -half) }
+ return { x: p.x + (toward.x > p.x ? half : -half), y: p.y }
+}
+let epN = 0
+function pt(kind: string, wallId: string | null, v: number | Pt, toward: Pt | null, circuitId: string, height: number, extra: Any = {}) {
+ const at = wallId ? faceOf(wallId, v as number, toward!) : (v as Pt)
+ ep.push({ id: `ep${++epN}`, kind, x: Math.round(at.x), y: Math.round(at.y), height, ...(wallId ? { wallId } : {}), circuitId, ...extra })
+}
+const OUT_BACK = { x: 0, y: 0 }
+const OUT_FRONT = { x: 0, y: 50000 }
+const switchBy = (doorId: string, toward: Pt, circuitId: string, kind = 'switch', label?: string) => {
+ const o = openings.find((x) => x.id === doorId)!
+ const w = wallById.get(o.wallId as string)!
+ const { ux, uy, a } = unit(w)
+ const hingeStart = o.hinge === 'start'
+ const t = hingeStart ? (o.offset as number) + (o.width as number) + 150 : (o.offset as number) - 150
+ const p = { x: a.x + ux * t, y: a.y + uy * t }
+ const horizontal = (w.a as Pt).y === (w.b as Pt).y
+ pt(kind, o.wallId as string, horizontal ? p.x : p.y, toward, circuitId, 900, label ? { label } : {})
+}
+
+const circuits = [
+ { id: 'c-l1', name: 'Lighting — bedrooms wing', kind: 'light', breaker: { type: 'MCB', rating: 10, curve: 'C' }, cable: '3x1.5', phase: 'L1' },
+ { id: 'c-l2', name: 'Lighting — living, hall, utility', kind: 'light', breaker: { type: 'MCB', rating: 10, curve: 'C' }, cable: '3x1.5', phase: 'L2' },
+ { id: 'c-s1', name: 'Sockets — living & dining', kind: 'socket', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L3' },
+ { id: 'c-s2', name: 'Sockets — kitchen worktop', kind: 'socket', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L1' },
+ { id: 'c-s3', name: 'Sockets — master suite', kind: 'socket', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L2' },
+ { id: 'c-s4', name: 'Sockets — bedrooms 2–3, hall', kind: 'socket', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L3' },
+ { id: 'c-w1', name: 'Bathrooms (IP44)', kind: 'wet', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L1' },
+ { id: 'c-w2', name: 'Washing machine', kind: 'wet', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L2' },
+ { id: 'c-w3', name: 'Water heater 80 L', kind: 'wet', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L3' },
+ { id: 'c-p1', name: 'Induction hob & oven', kind: 'power', breaker: { type: 'RCBO', rating: 32, curve: 'C' }, cable: '3x6', phase: 'L1' },
+ { id: 'c-p2', name: 'Dishwasher', kind: 'power', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L2' },
+ { id: 'c-p3', name: 'Heat pump', kind: 'power', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L3' },
+ { id: 'c-p4', name: 'Borehole pump', kind: 'power', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L1' },
+ { id: 'c-o1', name: 'Outdoor & terrace', kind: 'outdoor', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L2' },
+ { id: 'c-g1', name: 'Garage (buried cable)', kind: 'garage', breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5', phase: 'L3' },
+]
+
+const C = (r: Rect) => center(r)
+pt('light', null, C(R.master), null, 'c-l1', 2800, { label: 'Master bedroom' })
+pt('light', null, C(R.ensuite), null, 'c-l1', 2800, { label: 'En-suite' })
+pt('light', null, C(R.wic), null, 'c-l1', 2800, { label: 'Walk-in closet' })
+pt('light', null, { x: 6200, y: 22400 }, null, 'c-l1', 2800, { label: 'Corridor' })
+pt('light', null, { x: 10600, y: 22400 }, null, 'c-l1', 2800, { label: 'Corridor' })
+pt('light', null, C(R.bed2), null, 'c-l1', 2800, { label: 'Bedroom 2' })
+pt('light', null, C(R.bed3), null, 'c-l1', 2800, { label: 'Bedroom 3' })
+pt('light', null, C(R.bath), null, 'c-l1', 2800, { label: 'Bathroom' })
+switchBy('d-master', C(R.master), 'c-l1')
+switchBy('d-ensuite', C(R.master), 'c-l1', 'switch', 'En-suite (outside the door)')
+switchBy('d-wic', C(R.master), 'c-l1', 'switch', 'Walk-in closet')
+switchBy('d-bed2', C(R.bed2), 'c-l1')
+switchBy('d-bed3', C(R.bed3), 'c-l1')
+switchBy('d-bath', C(R.corridor), 'c-l1', 'switch', 'Bathroom (outside the door)')
+pt('switch2', 'p4', 6200, C(R.corridor), 'c-l1', 900, { label: 'Corridor' })
+
+pt('light', null, { x: 11700, y: 19500 }, null, 'c-l2', 2800, { label: 'Living' })
+pt('light', null, { x: 16200, y: 19400 }, null, 'c-l2', 2800, { label: 'Dining' })
+pt('light', null, { x: 17700, y: 19400 }, null, 'c-l2', 2800, { label: 'Kitchen' })
+pt('light', null, { x: 15100, y: 22800 }, null, 'c-l2', 2800, { label: 'Hall' })
+pt('light', null, { x: 15100, y: 25000 }, null, 'c-l2', 2800, { label: 'Entrance' })
+pt('light', null, C(R.pantry), null, 'c-l2', 2800, { label: 'Pantry' })
+pt('light', null, C(R.utility), null, 'c-l2', 2800, { label: 'Utility' })
+switchBy('d-lk', C(R.living), 'c-l2', 'switch2', 'Living / dining')
+pt('switch', 'p4', 16000, C(R.living), 'c-l2', 900, { label: 'Kitchen' })
+switchBy('d-front', C(R.entry), 'c-l2', 'switch2', 'Hall / entrance')
+switchBy('d-pantry', C(R.entry), 'c-l2', 'switch', 'Pantry (outside the door)')
+switchBy('d-utility', C(R.entry), 'c-l2', 'switch', 'Utility (outside the door)')
+
+pt('socket2', 'p2', 19000, C(R.living), 'c-s1', 300, { label: 'TV' })
+pt('socket2', 'p2', 20000, C(R.living), 'c-s1', 300, { label: 'TV' })
+pt('socket', 'ext-back', 10500, C(R.living), 'c-s1', 300)
+pt('socket', 'ext-back', 13300, C(R.living), 'c-s1', 300, { label: 'Sofa' })
+pt('socket', 'p4', 12000, C(R.living), 'c-s1', 300)
+pt('socket', 'p4', 13800, C(R.living), 'c-s1', 300)
+pt('socket', 'ext-back', 17800, C(R.living), 'c-s1', 300, { label: 'Dining' })
+
+pt('socket2', 'ext-right', 18300, C(R.living), 'c-s2', 1100, { label: 'Worktop' })
+pt('socket2', 'ext-right', 20900, C(R.living), 'c-s2', 1100, { label: 'Worktop' })
+pt('socket2', 'ext-right', 21450, C(R.living), 'c-s2', 1100, { label: 'Worktop' })
+pt('socket', 'ext-right', 17700, C(R.living), 'c-s2', 300, { label: 'Fridge', powerW: 300 })
+pt('socket', 'ext-right', 20300, C(R.living), 'c-s2', 2000, { label: 'Cooker hood', powerW: 200 })
+
+pt('socket', 'ext-left', 18300, C(R.master), 'c-s3', 700, { label: 'Bedside' })
+pt('socket', 'ext-left', 20700, C(R.master), 'c-s3', 700, { label: 'Bedside' })
+pt('socket', 'p4', 5900, C(R.master), 'c-s3', 900, { label: 'Dresser' })
+pt('socket', 'ext-back', 7700, C(R.master), 'c-s3', 300, { label: 'Reading chair' })
+pt('socket', 'p2', 20100, C(R.wic), 'c-s3', 300, { label: 'Walk-in closet' })
+
+pt('socket', 'p5', 4700, C(R.bed2), 'c-s4', 700, { label: 'Bedside' })
+pt('socket', 'ext-left', 25600, C(R.bed2), 'c-s4', 300)
+pt('socket', 'p6', 24400, C(R.bed2), 'c-s4', 300)
+pt('socket', 'p5', 11150, C(R.bed3), 'c-s4', 700, { label: 'Bedside' })
+pt('socket', 'p7', 24000, C(R.bed3), 'c-s4', 300)
+pt('socket', 'ext-front', 9000, C(R.bed3), 'c-s4', 300)
+pt('socket', 'p5', 5800, C(R.corridor), 'c-s4', 300, { label: 'Corridor' })
+pt('socket', 'p8', 23300, C(R.entry), 'c-s4', 300, { label: 'Hall' })
+
+pt('socket_ip44', 'p1', 17700, C(R.ensuite), 'c-w1', 1100, { label: 'En-suite basin' })
+pt('socket_ip44', 'p7', 23500, C(R.bath), 'c-w1', 1100, { label: 'Bathroom basin' })
+pt('socket_ip44', 'ext-right', 25800, C(R.utility), 'c-w2', 1100, { label: 'Washing machine', powerW: 2200 })
+pt('power', 'p10', 17700, C(R.utility), 'c-w3', 1900, { label: 'Water heater', powerW: 2000 })
+pt('power', 'ext-right', 20300, C(R.living), 'c-p1', 600, { label: 'Induction hob + oven', powerW: 7000 })
+pt('power', 'ext-right', 19700, C(R.living), 'c-p2', 300, { label: 'Dishwasher', powerW: 2000 })
+pt('power', 'p10', 18450, C(R.utility), 'c-p3', 600, { label: 'Heat pump indoor unit', powerW: 3500 })
+pt('power', 'p9', 25700, C(R.utility), 'c-p4', 600, { label: 'Borehole pump controller', powerW: 1100 })
+
+pt('outdoor', 'ext-back', 16200, OUT_BACK, 'c-o1', 600, { label: 'Terrace' })
+pt('light_wall', 'ext-back', 13700, OUT_BACK, 'c-o1', 2200, { label: 'Terrace' })
+pt('light_wall', 'ext-back', 15300, OUT_BACK, 'c-o1', 2200, { label: 'Terrace' })
+pt('light_wall', 'ext-front', 14450, OUT_FRONT, 'c-o1', 2200, { label: 'Front door' })
+pt('switch', 'ext-back', 15200, C(R.living), 'c-o1', 900, { label: 'Terrace lights' })
+
+pt('socket', 'g-back', 23000, C(R.garage), 'c-g1', 900, { label: 'Workbench' })
+pt('socket', 'g-back', 27900, C(R.garage), 'c-g1', 300)
+pt('socket', 'g-right', 37000, C(R.garage), 'c-g1', 2500, { label: 'Door operators' })
+pt('light', null, { x: 24000, y: 35300 }, null, 'c-g1', 2800, { label: 'Garage' })
+pt('light', null, { x: 27000, y: 35300 }, null, 'c-g1', 2800, { label: 'Garage' })
+switchBy('d-garage', C(R.garage), 'c-g1', 'switch', 'Garage lights')
+
+const panel = { id: 'panel', ...faceOf('p9', 23600, C(R.entry)), wallId: 'p9', modules: 36 }
+
+const plan: Any = {
+ version: 1,
+ name: 'Demo: Nordic single-storey house with garage',
+ resetEpoch: 2,
+ site,
+ materials: [
+ {
+ id: 'teploblok-400',
+ name: 'Teploblok 400 × 200 × 400, three-layer block (200 structural + 150 EPS + 50 facade)',
+ kind: 'block',
+ thickness: 400,
+ unitLength: 400,
+ unitHeight: 200,
+ jointMm: 10,
+ price: 580,
+ pricePer: 'pcs',
+ url: 'https://teplobloki-sz.ru/teplobloki',
+ source: 'teplobloki-sz.ru, price list',
+ checkedAt: '2026-09-30',
+ finish: 'plaster',
+ note: 'External walls, painted facade layer',
+ },
+ {
+ id: 'partition-120',
+ name: 'Smart-Block partition block 390 × 120 × 200',
+ kind: 'block',
+ thickness: 120,
+ unitLength: 390,
+ unitHeight: 200,
+ jointMm: 3,
+ price: 158,
+ pricePer: 'pcs',
+ url: 'https://xn----7sbe2ajfduoho.xn--p1ai/',
+ source: 'Smart-Block, manufacturer retail price',
+ checkedAt: '2026-09-30',
+ note: 'Interior partitions, plastered both sides',
+ },
+ {
+ id: 'smartblock-200',
+ name: 'Smart-Block 390 × 200 × 200, concrete-filled (garage)',
+ kind: 'block',
+ thickness: 200,
+ unitLength: 390,
+ unitHeight: 200,
+ jointMm: 3,
+ price: 192,
+ pricePer: 'pcs',
+ url: 'https://gssmarket.ru/ryadovoj-blok-390h200h200mm',
+ source: 'GSSMarket, dealer price',
+ checkedAt: '2026-09-30',
+ finish: 'plaster',
+ note: 'Unheated detached garage',
+ },
+ ],
+ walls,
+ openings,
+ furniture,
+ rooms,
+ palette: { name: 'Nordic white', walls: 'RAL 9010', accent: 'RAL 7016', roof: 'RAL 7016', windows: 'RAL 7016', gates: 'RAL 7016', plinth: 'RAL 7016' },
+ estimate: {
+ lines: [
+ { id: 'l-slab', name: 'Insulated slab foundation, house 15.2 × 9.6 m, turnkey', category: 'фундамент', qty: 146, unit: 'm²', price: 5500, url: 'https://top-fundament.ru/fundamenty/fundament-ushp', note: 'Starting price per m² of slab' },
+ { id: 'l-garage-slab', name: 'Garage slab on grade 7.0 × 6.6 m', category: 'фундамент', qty: 46, unit: 'm²', price: 3000, url: 'https://sankt-peterburg.svaifund.ru/fundament-ushp/' },
+ { id: 'l-terrace', name: 'Terrace paving on gravel base, 8.0 × 3.2 m', category: 'прочее', qty: 25.6, unit: 'm²' },
+ { id: 'l-drive', name: 'Driveway and front path, concrete pavers', category: 'прочее', qty: 70, unit: 'm²' },
+ { id: 'l-roof', name: 'Standing-seam steel roof, RAL 7016', category: 'кровля', qty: 210, unit: 'm²', note: 'House and garage incl. overhangs' },
+ { id: 'l-paint', name: 'Facade paint, RAL 9010, two coats', category: 'прочее', qty: 190, unit: 'm²' },
+ { id: 'l-masonry', name: 'Masonry labour: external walls and partitions', category: 'работы', qty: 1, unit: 'lot', note: 'Ask local contractors for a quote' },
+ ],
+ purchases: {},
+ wasteSipPct: 5,
+ notes: [
+ 'All quantities are generated from the plan; prices are examples, check them before ordering.',
+ 'Foundation: insulated slab with underfloor heating pipes in the screed.',
+ 'Garage is unheated; the power cable runs underground in a duct.',
+ 'Septic and borehole positions follow the 50 m separation rule.',
+ ],
+ },
+ networks: {
+ sewer: { floorLevel: 450, nodes: sn, pipes: sp },
+ water: { nodes: wn, pipes: wp },
+ electric: { panel, points: ep, circuits },
+ heating: { collector: { id: 'collector', x: 12000, y: 22880, outputs: 12, label: 'Manifold cabinet in the corridor wall' }, loops: [], params: { supplyT: 50, returnT: 40, screedMm: 60, insulation: 'XPS 150', screedMix: 'cps', fixing: 'staples' } },
+ },
+}
+
+const { autoLayout } = await load<{ autoLayout: (p: Any) => { heating: Any; notes: string[] } }>('/src/networks/heating/layout.ts')
+const heat = autoLayout(plan)
+const UNHEATED = new Set(['r-wic', 'r-pantry', 'r-utility'])
+const loops = (heat.heating.loops as Any[])
+ .filter((l) => !UNHEATED.has(l.roomId as string))
+ .map((l) => {
+ const parts = ((l.parts as Any[] | undefined) ?? []).filter((x) => !UNHEATED.has(x.roomId as string))
+ if (parts.length) return { ...l, parts }
+ const { parts: _p, linkPath: _l, ...rest } = l
+ return { ...rest, roomName: String(l.roomName).replace(/ \+ (Pantry|Walk-in closet)$/, '') }
+ })
+loops.forEach((l, i) => (l.id = `hl${i + 1}`))
+;(plan.networks as Any).heating = { ...heat.heating, collector: { ...(heat.heating.collector as Any), outputs: loops.length }, loops, params: ((plan.networks as Any).heating as Any).params }
+console.log('heating notes:', heat.notes)
+
+const { autoRoute } = await load<{ autoRoute: (p: Any, id: string) => Any[] }>('/src/networks/electric/route.ts')
+const routes = circuits.flatMap((c) => autoRoute(plan, c.id))
+;((plan.networks as Any).electric as Any).routes = routes
+
+const { computeElectric } = await load<{ computeElectric: (p: Any) => { modules: number; panelSize: number } }>('/src/networks/electric/calc.ts')
+const ec = computeElectric(plan)
+panel.modules = ec.panelSize
+await close()
+
+writeFileSync(out('public/plans/demo.json'), JSON.stringify(plan, null, 1) + '\n')
+
+const lot = (x0: number) => ring(rectPts(x0, 0, x0 + LOT.w, LOT.d))
+const roadLine = [-45000, 75000].map((x) => toLngLat({ x, y: LOT.d + LOT.roadOffsetM * 1000 }))
+const parcel = {
+ type: 'FeatureCollection',
+ features: [
+ { type: 'Feature', properties: { role: 'parcel', label: 'Lot 12', note: '30 × 45 m, 1350 m²' }, geometry: { type: 'Polygon', coordinates: lot(0) } },
+ { type: 'Feature', properties: { role: 'neighbor', label: 'Lot 11' }, geometry: { type: 'Polygon', coordinates: lot(-LOT.w) } },
+ { type: 'Feature', properties: { role: 'neighbor', label: 'Lot 13' }, geometry: { type: 'Polygon', coordinates: lot(LOT.w) } },
+ { type: 'Feature', properties: { role: 'street', label: 'Demo Lane' }, geometry: { type: 'LineString', coordinates: roadLine } },
+ ],
+}
+writeFileSync(out('public/data/parcel.geojson'), JSON.stringify(parcel, null, 1) + '\n')
+console.log('geo', geo, 'walls', walls.length, 'openings', openings.length, 'furniture', furniture.length, 'points', ep.length, 'routes', routes.length, 'panel', ec.modules, ec.panelSize)
diff --git a/scripts/demo/check-demo.mts b/scripts/demo/check-demo.mts
new file mode 100644
index 0000000..d9e9bfd
--- /dev/null
+++ b/scripts/demo/check-demo.mts
@@ -0,0 +1,124 @@
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { close, load } from './vite-load.mts'
+
+type Pt = { x: number; y: number }
+type Any = Record<string, any>
+
+const file = process.argv[2] ?? fileURLToPath(new URL('../../public/plans/demo.json', import.meta.url))
+const raw = JSON.parse(readFileSync(file, 'utf8'))
+const { parsePlan } = await load<Any>('/src/model/schema.ts')
+const parsed = parsePlan(raw)
+if (!parsed.ok) {
+ console.error(parsed.error)
+ process.exit(1)
+}
+const plan = parsed.plan
+const { computeSewer } = await load<Any>('/src/networks/sewerCalc.ts')
+const { computeWater } = await load<Any>('/src/networks/waterCalc.ts')
+const { computeElectric } = await load<Any>('/src/networks/electric/calc.ts')
+const { computeHeating } = await load<Any>('/src/networks/heating/calc.ts')
+const { computePlanSummary } = await load<Any>('/src/stats/summary.ts')
+const { resolveFurniture } = await load<Any>('/src/furniture/catalog.ts')
+const { pointInPolygon } = await load<Any>('/src/stats/rooms.ts')
+
+const report = (name: string, ws: { text: string; level?: string }[]) => {
+ console.log(`\n${name}: ${ws.length} warning(s)`)
+ for (const w of ws) console.log(` [${w.level ?? 'warn'}] ${w.text}`)
+}
+const sewer = computeSewer(plan)
+report('Sewer', sewer.warnings)
+console.log(' outlets', sewer.outlets.map((o: Any) => `${o.nodeId} ${(o.depth / 1000).toFixed(2)} m`).join(', '))
+console.log(' septic', sewer.septics.map((s: Any) => `depth ${(s.depth / 1000).toFixed(2)} m, to house ${(s.toHouse / 1000).toFixed(1)} m, to boundary ${(s.toBoundary / 1000).toFixed(1)} m`).join('; '))
+const water = computeWater(plan)
+report('Water', water.warnings)
+const el = computeElectric(plan)
+report('Electric', el.warnings)
+console.log(` modules ${el.modules}, panel ${el.panelSize}, load ${(el.totalLoadW / 1000).toFixed(1)} kW`)
+for (const c of el.circuits) console.log(` ${c.circuit.id.padEnd(5)} ${c.circuit.name.padEnd(36)} pts ${String(c.points).padStart(2)} ${String(Math.round(c.loadW)).padStart(5)} W ${c.currentA.toFixed(1).padStart(5)} A cable ${String(c.cableM).padStart(3)} m drop ${c.dropPct?.toFixed(2)}%`)
+const heat = computeHeating(plan)
+report('Heating', heat.warnings)
+console.log(` loops ${plan.networks.heating.loops.length}, collector outputs ${plan.networks.heating.collector?.outputs}`)
+for (const l of heat.loops) console.log(` ${l.loop.id.padEnd(5)} ${(l.loop.roomName ?? '').padEnd(40)} step ${l.loop.stepMm} ${Math.round(l.lengthM)} m ${Math.round(l.powerW ?? 0)} W`)
+for (const k of Object.keys(heat)) if (!['loops', 'warnings', 'rooms', 'items'].includes(k)) console.log(` ${k}:`, JSON.stringify(heat[k]).slice(0, 200))
+
+const sum = computePlanSummary(plan)
+console.log('\nSummary totals', sum.totals, 'site', { area: sum.site.areaM2, built: sum.site.builtM2.toFixed(1), pct: sum.site.builtPct.toFixed(1), violations: sum.site.violations })
+for (const b of sum.buildings) {
+ console.log(` ${b.name}: footprint ${b.footprintM2.toFixed(1)} m², rooms ${b.totalAreaM2.toFixed(1)} m², living ${b.livingAreaM2.toFixed(1)} m²`)
+ for (const r of b.rooms) console.log(` ${r.name.padEnd(20)} ${r.areaM2.toFixed(1).padStart(5)} m² win ${r.windows} light ${r.lightRatio === null ? '-' : r.lightRatio.toFixed(3)} ${r.lightOk === false ? 'LOW' : ''}`)
+ for (const c of b.clearances) if (!c.ok) console.log(` clearance FAIL ${c.label} ${c.distanceM.toFixed(2)} < ${c.normM}`)
+ console.log(` clearances: ${b.clearances.map((c: Any) => `${c.label} ${c.distanceM.toFixed(1)}`).join(', ')}`)
+}
+for (const g of sum.site.gaps) console.log(` gap ${g.label} ${g.distanceM.toFixed(2)} m ${g.ok ? 'ok' : 'FAIL'}`)
+if (sum.unmatchedLabels.length) console.log(' unmatched labels', sum.unmatchedLabels)
+
+const rect = (f: Any) => {
+ const r = resolveFurniture(f)
+ const a = (f.rotationDeg * Math.PI) / 180
+ const c = Math.cos(a)
+ const s = Math.sin(a)
+ return [
+ [-r.w / 2, -r.d / 2],
+ [r.w / 2, -r.d / 2],
+ [r.w / 2, r.d / 2],
+ [-r.w / 2, r.d / 2],
+ ].map(([x, y]) => ({ x: f.x + x * c - y * s, y: f.y + x * s + y * c }))
+}
+const elevated = new Set(['kitchen-upper', 'water-heater', 'gas-boiler'])
+const polys = plan.furniture.map((f: Any) => ({ f, p: rect(f) }))
+const sepAxis = (a: Pt[], b: Pt[]) => {
+ for (const poly of [a, b])
+ for (let i = 0; i < poly.length; i++) {
+ const p = poly[i]
+ const q = poly[(i + 1) % poly.length]
+ const n = { x: q.y - p.y, y: p.x - q.x }
+ const pa = a.map((v) => v.x * n.x + v.y * n.y)
+ const pb = b.map((v) => v.x * n.x + v.y * n.y)
+ if (Math.max(...pa) <= Math.min(...pb) + 1 || Math.max(...pb) <= Math.min(...pa) + 1) return true
+ }
+ return false
+}
+let clashes = 0
+for (let i = 0; i < polys.length; i++)
+ for (let j = i + 1; j < polys.length; j++) {
+ const A = polys[i]
+ const B = polys[j]
+ if (elevated.has(A.f.type) !== elevated.has(B.f.type)) continue
+ if (!sepAxis(A.p, B.p)) {
+ clashes++
+ console.log(` furniture clash ${A.f.id} × ${B.f.id}`)
+ }
+ }
+const roomPolys = sum.buildings.flatMap((b: Any) => b.rooms.map((r: Any) => r.polygon))
+for (const { f, p } of polys) {
+ const ok = roomPolys.some((poly: Pt[]) => p.every((v) => pointInPolygon({ x: v.x + Math.sign(f.x - v.x) * 2, y: v.y + Math.sign(f.y - v.y) * 2 }, poly)))
+ if (!ok) {
+ clashes++
+ console.log(` furniture outside its room or into a wall: ${f.id}`)
+ }
+}
+const walls = new Map(plan.walls.map((w: Any) => [w.id, w]))
+for (const o of plan.openings) {
+ if (o.type !== 'door') continue
+ const w: Any = walls.get(o.wallId)
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y)
+ const ux = (w.b.x - w.a.x) / len
+ const uy = (w.b.y - w.a.y) / len
+ const sign = o.side === 'left' ? -1 : 1
+ const n = { x: -uy * sign, y: ux * sign }
+ const t0 = o.hinge === 'end' ? o.offset + o.width : o.offset
+ const t1 = o.hinge === 'end' ? o.offset : o.offset + o.width
+ const half = w.thickness / 2
+ const at = (t: number, k: number) => ({ x: w.a.x + ux * t + n.x * (half + k), y: w.a.y + uy * t + n.y * (half + k) })
+ const sweep = [at(t0, 0), at(t1, 0), at(t1, o.width), at(t0, o.width)]
+ for (const { f, p } of polys) {
+ if (elevated.has(f.type)) continue
+ if (!sepAxis(sweep, p)) {
+ clashes++
+ console.log(` door swing ${o.id} hits ${f.id}`)
+ }
+ }
+}
+console.log(`\nFurniture/door checks: ${clashes} issue(s)`)
+await close()
diff --git a/scripts/demo/vite-load.mts b/scripts/demo/vite-load.mts
new file mode 100644
index 0000000..7dab262
--- /dev/null
+++ b/scripts/demo/vite-load.mts
@@ -0,0 +1,22 @@
+import { createServer, type ViteDevServer } from 'vite'
+
+const g = globalThis as Record<string, unknown>
+g.document ??= { documentElement: {}, title: '', cookie: '' }
+
+let server: ViteDevServer | null = null
+
+export async function load<T = Record<string, unknown>>(path: string): Promise<T> {
+ server ??= await createServer({
+ root: new URL('../..', import.meta.url).pathname,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: 'custom',
+ logLevel: 'error',
+ optimizeDeps: { noDiscovery: true },
+ })
+ return (await server.ssrLoadModule(path)) as T
+}
+
+export async function close() {
+ await server?.close()
+ server = null
+}
diff --git a/scripts/deploy.sh b/scripts/deploy.sh
new file mode 100755
index 0000000..dd39d2e
--- /dev/null
+++ b/scripts/deploy.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+set -euo pipefail
+. "$(dirname "${BASH_SOURCE[0]}")/_deploy-lib.sh"
+
+EXCLUDES=(.DS_Store cgi-bin/ /storage/ /data/.htaccess /plans/.htaccess)
+BUILD=1
+
+for a in "$@"; do
+ case "$a" in
+ --no-build) BUILD=0 ;;
+ -h|--help)
+ cat <<USAGE
+usage: scripts/deploy.sh [--no-build]
+ npm run build → заливка dist/ в корень сайта → сверка с сервером.
+ Настройки берутся из .env.deploy (пример: .env.deploy.example):
+ DEPLOY_METHOD=ssh — rsync по SSH (DEPLOY_SSH, DEPLOY_PATH, DEPLOY_SSH_OPTS);
+ DEPLOY_METHOD=ftp — lftp mirror (FTP_HOST, FTP_USER, FTP_PASSWORD, FTP_PATH).
+ Не трогаются на сервере: ${EXCLUDES[*]}
+USAGE
+ exit 0 ;;
+ *) die "неизвестный аргумент: $a" ;;
+ esac
+done
+
+case "$DEPLOY_METHOD" in
+ ssh) check_ssh_env ;;
+ ftp) check_ftp_env ;;
+ *) die "DEPLOY_METHOD: ssh или ftp, а не '$DEPLOY_METHOD'" ;;
+esac
+
+cd "$ROOT"
+lock_acquire
+
+if [ "$BUILD" = 1 ] && ! npm run build; then
+ echo "СБОРКА УПАЛА — заливка отменена" >&2
+ exit 2
+fi
+[ -f dist/index.html ] || die "нет dist/index.html — заливка отменена"
+
+if [ "$DEPLOY_METHOD" = ftp ]; then
+ ftp_sync_dir "$ROOT/dist" "$FTP_PATH" "${EXCLUDES[@]}"
+ ftp_verify_dir "$ROOT/dist" "$FTP_PATH" "${EXCLUDES[@]}"
+else
+ sync_dir "$ROOT/dist" "$DEPLOY_PATH" "${EXCLUDES[@]}"
+ verify_dir "$ROOT/dist" "$DEPLOY_PATH" "${EXCLUDES[@]}"
+fi
+[ -n "$DEPLOY_URL" ] && echo "URL: $DEPLOY_URL/"
+[ -n "$DEPLOY_URL" ] && echo "первый запуск: $DEPLOY_URL/api/setup.php"
+exit 0
diff --git a/scripts/dev-router.php b/scripts/dev-router.php
new file mode 100644
index 0000000..9b370d3
--- /dev/null
+++ b/scripts/dev-router.php
@@ -0,0 +1,36 @@
+<?php
+
+// Router for the PHP built-in server in development: npm run dev:api.
+// php -S ignores .htaccess, so this repeats its rules: no direct access to
+// api/_*.php, storage/ and dotfiles; data/ and plans/ need the login cookie
+// (except in demo mode, where they are open).
+
+$path = rawurldecode((string)parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH));
+
+function dev_deny(int $code): bool
+{
+ http_response_code($code);
+ header('Content-Type: application/json');
+ header('Cache-Control: no-store');
+ echo json_encode(['error' => $code === 401 ? 'unauthorized' : 'forbidden']), "\n";
+ return true;
+}
+
+if (preg_match('#(^|/)\.#', $path) || preg_match('#^/api/_#', $path) || preg_match('#^/storage(/|$)#', $path)) {
+ return dev_deny(403);
+}
+
+if (preg_match('#^/(data|plans)/#', $path)) {
+ require __DIR__ . '/../public/api/_lib.php';
+ $dir = find_storage();
+ if ($dir === null) {
+ return dev_deny(403);
+ }
+ $config = require $dir . '/config.php';
+ $token = is_array($config) ? (string)($config['hauth'] ?? '') : '';
+ if (!is_demo() && ($token === '' || !hash_equals($token, (string)($_COOKIE[AUTH_COOKIE] ?? '')))) {
+ return dev_deny(401);
+ }
+}
+
+return false;
diff --git a/scripts/plan-pull.sh b/scripts/plan-pull.sh
new file mode 100755
index 0000000..81aee74
--- /dev/null
+++ b/scripts/plan-pull.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+set -euo pipefail
+. "$(dirname "${BASH_SOURCE[0]}")/_plan-lib.sh"
+
+OUT="$ROOT/plans/server.json"
+REV=""
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ -o|--out) OUT="$2"; shift 2 ;;
+ -r|--rev) REV="$2"; shift 2 ;;
+ -h|--help) echo "usage: scripts/plan-pull.sh [--rev N] [--out файл] план с сервера → plans/server.json (HOUSE_URL, HOUSE_PASSWORD)"; exit 0 ;;
+ *) die "неизвестный аргумент: $1" ;;
+ esac
+done
+
+mkdir -p "$(dirname "$OUT")"
+tmp="$(mktemp)"
+trap 'rm -f "$tmp"; cleanup_jar' EXIT
+
+house_login
+url="$API/plan.php"
+[ -n "$REV" ] && url="$url?rev=$REV"
+code="$(curl -s -o "$tmp" -w '%{http_code}' -b "$JAR" "$url")"
+[ "$code" = 200 ] || { echo "ошибка $code:" >&2; cat "$tmp" >&2; exit 1; }
+
+python3 - "$tmp" <<'PY'
+import json, sys
+d = json.load(open(sys.argv[1]))
+print(f"rev {d.get('rev')} {d.get('updatedAt')} автор {d.get('author')} стен {len(d['walls'])} проёмов {len(d['openings'])}")
+PY
+mv "$tmp" "$OUT"
+echo "→ $OUT"
diff --git a/scripts/plan-push.sh b/scripts/plan-push.sh
new file mode 100755
index 0000000..056757f
--- /dev/null
+++ b/scripts/plan-push.sh
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+set -euo pipefail
+. "$(dirname "${BASH_SOURCE[0]}")/_plan-lib.sh"
+
+FILE="$ROOT/plans/server.json"
+REV=""
+AUTHOR="cli"
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ -r|--rev) REV="$2"; shift 2 ;;
+ -a|--author) AUTHOR="$2"; shift 2 ;;
+ -h|--help) echo "usage: scripts/plan-push.sh [файл] [--rev N] [--author метка] файл (по умолчанию plans/server.json) → новая версия на сервере (HOUSE_URL, HOUSE_PASSWORD)"; exit 0 ;;
+ -*) die "неизвестный аргумент: $1" ;;
+ *) FILE="$1"; shift ;;
+ esac
+done
+
+[ -f "$FILE" ] || die "нет файла $FILE"
+if [ -z "$REV" ]; then
+ REV="$(python3 -c 'import json,sys; r=json.load(open(sys.argv[1])).get("rev"); print(r if isinstance(r,int) else "")' "$FILE")"
+ [ -n "$REV" ] || die "в $FILE нет поля rev — укажите --rev N (базовая версия, от которой правили)"
+fi
+
+resp="$(mktemp)"
+trap 'rm -f "$resp"; cleanup_jar' EXIT
+
+house_login
+code="$(curl -s -o "$resp" -w '%{http_code}' -b "$JAR" -X PUT \
+ -H 'X-Requested-With: plan-cli' -H "X-Client-Version: $CLIENT_VERSION" -H "X-Plan-Author: $AUTHOR" \
+ -H "If-Match: $REV" -H 'Content-Type: application/json' --data-binary @"$FILE" "$API/plan.php")"
+
+case "$code" in
+ 200)
+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print("ок: rev %s %s" % (d["rev"], d["updatedAt"]))' "$resp"
+ if [ "$FILE" -ef "$ROOT/plans/server.json" ]; then
+ "$ROOT/scripts/plan-pull.sh" >/dev/null && echo "plans/server.json обновлён до серверной версии"
+ fi
+ ;;
+ 409)
+ conflict="${FILE%.json}.conflict.json"
+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); json.dump(d["plan"], open(sys.argv[2],"w"), ensure_ascii=False, indent=2); print("конфликт: на сервере rev %s (%s), а правки от rev %s" % (d["rev"], d["plan"].get("author"), sys.argv[3]))' "$resp" "$conflict" "$REV"
+ echo "серверный план сохранён в $conflict — перенесите правки на него и отправьте снова" >&2
+ exit 2
+ ;;
+ *)
+ echo "ошибка $code:" >&2; cat "$resp" >&2; exit 1 ;;
+esac
diff --git a/scripts/plan-validate.mts b/scripts/plan-validate.mts
new file mode 100644
index 0000000..1a04309
--- /dev/null
+++ b/scripts/plan-validate.mts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { parsePlan } from '../src/model/schema.ts'
+
+const files = process.argv.slice(2)
+if (!files.length) {
+ console.error('usage: node scripts/plan-validate.mts <plan.json> [...]')
+ process.exit(1)
+}
+let bad = 0
+for (const f of files) {
+ const r = parsePlan(JSON.parse(readFileSync(resolve(f), 'utf8')))
+ if (r.ok) console.log(`${f}: ok`)
+ else {
+ bad++
+ console.error(`${f}:\n${r.error}`)
+ }
+}
+process.exit(bad ? 1 : 0)
diff --git a/src/App.tsx b/src/App.tsx
new file mode 100644
index 0000000..dd60ac3
--- /dev/null
+++ b/src/App.tsx
@@ -0,0 +1,113 @@
+import { lazy, Suspense, useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { PlanCanvas } from './canvas/PlanCanvas'
+import { formatMeters, type Plan, type Point } from './model'
+import { startSync, useSyncStore } from './storage'
+import { usePlanStore } from './store/planStore'
+import { LoginScreen } from './ui/LoginScreen'
+import { GridLegend } from './ui/GridLegend'
+import { FurniturePanel } from './ui/FurniturePanel'
+import { Header } from './ui/Header'
+import { Toast } from './ui/Toast'
+import { PreviewBar } from './ui/PreviewBar'
+import { Inspector } from './ui/Inspector'
+import { Toolbar } from './ui/Toolbar'
+import { useSection, type SectionId } from './ui/useSection'
+
+const View3D = lazy(() => import('./view3d'))
+const MapView = lazy(() => import('./map'))
+const EstimatePage = lazy(() => import('./estimate'))
+const InfoPage = lazy(() => import('./info/InfoPage'))
+
+const loadingKey: Record<Exclude<SectionId, 'plan'>, string> = {
+ '3d': 'loading.3d',
+ map: 'loading.map',
+ estimate: 'loading.estimate',
+ info: 'loading.generic',
+}
+
+function SectionPage({ section }: { section: Exclude<SectionId, 'plan'> }) {
+ const { t } = useTranslation('common')
+ const plan = usePlanStore((s) => s.plan)
+ const commit = usePlanStore((s) => s.commit)
+ const onChange = useCallback((next: Plan) => commit(next), [commit])
+ const full = section === '3d' || section === 'map'
+ return (
+ <main className={`page ${full ? 'page--full' : ''}`}>
+ <Suspense fallback={<div className="page__loading">{t(loadingKey[section])}</div>}>
+ {section === 'info' && <InfoPage />}
+ {section !== 'info' && !plan && <div className="page__loading">{t('loading.plan')}</div>}
+ {section === '3d' && plan && <View3D plan={plan} onChange={onChange} />}
+ {section === 'map' && plan && <MapView plan={plan} onChange={onChange} />}
+ {section === 'estimate' && plan && <EstimatePage plan={plan} onChange={onChange} />}
+ </Suspense>
+ </main>
+ )
+}
+
+export default function App() {
+ const { t } = useTranslation('common')
+ const tool = usePlanStore((s) => s.tool)
+ const hasPlan = usePlanStore((s) => !!s.plan)
+ const status = useSyncStore((s) => s.status)
+ const camScale = usePlanStore((s) => s.cam?.scale ?? 0)
+ const section = useSection()
+ const [cursor, setCursor] = useState<{ p: Point | null; scale: number }>({ p: null, scale: 0 })
+
+ useEffect(() => {
+ startSync()
+ }, [])
+
+ const onCursor = useCallback((p: Point | null, scale: number) => setCursor({ p, scale }), [])
+
+ if (status === 'login' || !hasPlan) {
+ return (
+ <>
+ <LoginScreen />
+ <Toast />
+ </>
+ )
+ }
+
+ if (section !== 'plan') {
+ return (
+ <div className={`app app--page app--${section}`}>
+ <SectionPage section={section} />
+ <div className="overlay">
+ <Header section={section} />
+ <Toast />
+ <PreviewBar />
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="app app--plan">
+ <PlanCanvas onCursor={onCursor} />
+ <div className="overlay">
+ <Header section={section} />
+ <Toast />
+ <PreviewBar />
+ <Toolbar />
+ <FurniturePanel />
+ <Inspector />
+ <footer className="status card">
+ <span>
+ {cursor.p ? t('status.cursor', { x: formatMeters(cursor.p.x), y: formatMeters(cursor.p.y) }) : t('status.cursorEmpty')}
+ </span>
+ {camScale > 0 && <GridLegend scale={camScale} />}
+ <span className="muted">
+ {tool === 'wall'
+ ? t('status.hintWall')
+ : tool === 'door'
+ ? t('status.hintDoor')
+ : tool === 'window'
+ ? t('status.hintWindow')
+ : t('status.hintSelect')}
+ </span>
+ </footer>
+ </div>
+ </div>
+ )
+}
diff --git a/src/canvas/Dimensions.tsx b/src/canvas/Dimensions.tsx
new file mode 100644
index 0000000..595a462
--- /dev/null
+++ b/src/canvas/Dimensions.tsx
@@ -0,0 +1,69 @@
+import { Group, Line, Rect, Text } from 'react-konva'
+import { wallAngle, type Point, type Wall } from '../model'
+import { readableAngle } from './camera'
+import { canvasTheme } from './theme'
+
+type Props = {
+ wall: Wall
+ spans: [number, number][]
+ scale: number
+ toward?: Point
+ viewRot?: number
+}
+
+const LABEL_H = 16
+
+export function Dimensions({ wall, spans, scale, toward, viewRot = 0 }: Props) {
+ const px = 1 / scale
+ const angle = wallAngle(wall)
+ const nx = -Math.sin(angle)
+ const ny = Math.cos(angle)
+ const mid = { x: (wall.a.x + wall.b.x) / 2, y: (wall.a.y + wall.b.y) / 2 }
+ const sign = toward && (toward.x - mid.x) * nx + (toward.y - mid.y) * ny < 0 ? -1 : 1
+ const off = sign * (wall.thickness / 2 + 16 * px)
+ const deg = (angle * 180) / Math.PI
+ const readable = readableAngle(deg, viewRot) - deg
+
+ return (
+ <Group x={wall.a.x} y={wall.a.y} rotation={(angle * 180) / Math.PI} listening={false}>
+ {spans
+ .filter(([s, e]) => e - s > 1)
+ .map(([s, e]) => {
+ const text = `${Math.round(e - s)}`
+ const w = text.length * 6.4 + 8
+ const fits = (e - s) * scale > w + 6
+ return (
+ <Group key={`${s}-${e}`}>
+ <Line points={[s, off, e, off]} stroke={canvasTheme.accent} strokeWidth={1 * px} />
+ <Line points={[s, off - 5 * px, s, off + 5 * px]} stroke={canvasTheme.accent} strokeWidth={1 * px} />
+ <Line points={[e, off - 5 * px, e, off + 5 * px]} stroke={canvasTheme.accent} strokeWidth={1 * px} />
+ {fits && (
+ <Group
+ x={(s + e) / 2}
+ y={off}
+ rotation={readable}
+ scaleX={px}
+ scaleY={px}
+ >
+ <Rect x={-w / 2} y={-LABEL_H / 2} width={w} height={LABEL_H} cornerRadius={4} fill="#ffffff" stroke={canvasTheme.accent} strokeWidth={1} />
+ <Text
+ x={-w / 2}
+ y={-LABEL_H / 2}
+ width={w}
+ height={LABEL_H}
+ align="center"
+ verticalAlign="middle"
+ text={text}
+ fontSize={10.5}
+ fontStyle="600"
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.accent}
+ />
+ </Group>
+ )}
+ </Group>
+ )
+ })}
+ </Group>
+ )
+}
diff --git a/src/canvas/Grid.tsx b/src/canvas/Grid.tsx
new file mode 100644
index 0000000..4d4d4f4
--- /dev/null
+++ b/src/canvas/Grid.tsx
@@ -0,0 +1,41 @@
+import { Shape } from 'react-konva'
+import type { Context } from 'konva/lib/Context'
+import { gridSteps, visibleRect, type Camera } from './camera'
+import { canvasTheme } from './theme'
+
+type Props = { cam: Camera; width: number; height: number; opacity?: number }
+
+export function Grid({ cam, width, height, opacity = 1 }: Props) {
+ const rect = visibleRect(cam, width, height)
+ const { minor, major } = gridSteps(cam.scale)
+
+ const draw = (ctx: Context, step: number, color: string) => {
+ const x0 = Math.floor(rect.minX / step) * step
+ const y0 = Math.floor(rect.minY / step) * step
+ const c = ctx._context
+ c.beginPath()
+ for (let x = x0; x <= rect.maxX; x += step) {
+ c.moveTo(x, rect.minY)
+ c.lineTo(x, rect.maxY)
+ }
+ for (let y = y0; y <= rect.maxY; y += step) {
+ c.moveTo(rect.minX, y)
+ c.lineTo(rect.maxX, y)
+ }
+ c.strokeStyle = color
+ c.lineWidth = 1 / cam.scale
+ c.stroke()
+ }
+
+ return (
+ <Shape
+ listening={false}
+ opacity={opacity}
+ perfectDrawEnabled={false}
+ sceneFunc={(ctx) => {
+ draw(ctx, minor, canvasTheme.gridMinor)
+ draw(ctx, major, canvasTheme.gridMajor)
+ }}
+ />
+ )
+}
diff --git a/src/canvas/Handles.tsx b/src/canvas/Handles.tsx
new file mode 100644
index 0000000..465c9ff
--- /dev/null
+++ b/src/canvas/Handles.tsx
@@ -0,0 +1,202 @@
+import { Circle, Group, Line, Rect, Text } from 'react-konva'
+import { t } from '../i18n'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import type { Opening, Wall } from '../model'
+import { readableAngle } from './camera'
+import { canvasTheme } from './theme'
+
+export type HandleKind = 'a' | 'b' | 'move'
+
+type Props = {
+ wall: Wall
+ scale: number
+ onStart: (kind: HandleKind, e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+ onAdd?: (type: 'door' | 'window') => void
+ viewRot?: number
+ buttonsAt?: number
+}
+
+const R = 6.5
+
+export function Handles({ wall, scale, onStart, onAdd, viewRot = 0, buttonsAt }: Props) {
+ const px = 1 / scale
+ const start = (kind: HandleKind) => (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if ('button' in e.evt && e.evt.button !== 0) return
+ e.cancelBubble = true
+ onStart(kind, e)
+ }
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+ const mid = { x: (wall.a.x + wall.b.x) / 2, y: (wall.a.y + wall.b.y) / 2 }
+ const angle = (Math.atan2(wall.b.y - wall.a.y, wall.b.x - wall.a.x) * 180) / Math.PI
+ const arm = 4
+
+ return (
+ <>
+ {(['a', 'b'] as const).map((end) => (
+ <Circle
+ key={end}
+ x={wall[end].x}
+ y={wall[end].y}
+ radius={R * px}
+ hitStrokeWidth={10 * px}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2.5 * px}
+ shadowColor="rgba(0,0,0,0.25)"
+ shadowBlur={4 * px}
+ shadowOffsetY={1 * px}
+ onMouseDown={start(end)}
+ onTouchStart={start(end)}
+ onMouseEnter={cursor('crosshair')}
+ onMouseLeave={cursor('')}
+ />
+ ))}
+ <Group
+ x={mid.x}
+ y={mid.y}
+ rotation={angle}
+ scaleX={px}
+ scaleY={px}
+ onMouseDown={start('move')}
+ onTouchStart={start('move')}
+ onMouseEnter={cursor('move')}
+ onMouseLeave={cursor('')}
+ >
+ <Circle radius={R + 2} fill={canvasTheme.accent} stroke="#ffffff" strokeWidth={2} hitStrokeWidth={8} />
+ <Line points={[-arm, 0, arm, 0]} stroke="#ffffff" strokeWidth={1.6} lineCap="round" listening={false} />
+ <Line points={[0, -arm, 0, arm]} stroke="#ffffff" strokeWidth={1.6} lineCap="round" listening={false} />
+ </Group>
+ {onAdd && (
+ <Group
+ x={buttonsAt === undefined ? mid.x : wall.a.x + ((wall.b.x - wall.a.x) / (Math.hypot(wall.b.x - wall.a.x, wall.b.y - wall.a.y) || 1)) * buttonsAt}
+ y={buttonsAt === undefined ? mid.y : wall.a.y + ((wall.b.y - wall.a.y) / (Math.hypot(wall.b.x - wall.a.x, wall.b.y - wall.a.y) || 1)) * buttonsAt}
+ rotation={readableAngle(angle, viewRot)}
+ scaleX={px}
+ scaleY={px}
+ >
+ {(
+ [
+ ['door', t('common:canvas.addDoor'), -62],
+ ['window', t('common:canvas.addWindow'), 8],
+ ] as const
+ ).map(([type, text, x]) => (
+ <Group
+ key={type}
+ x={x}
+ y={-(wall.thickness * scale) / 2 - 30}
+ onMouseDown={(e) => {
+ e.cancelBubble = true
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ onAdd(type)
+ }}
+ onTap={(e) => {
+ e.cancelBubble = true
+ onAdd(type)
+ }}
+ onMouseEnter={cursor('pointer')}
+ onMouseLeave={cursor('')}
+ >
+ <Rect width={56} height={22} cornerRadius={11} fill="#ffffff" stroke={canvasTheme.accent} strokeWidth={1.2} shadowColor="rgba(0,0,0,0.15)" shadowBlur={4} shadowOffsetY={1} />
+ <Text width={56} height={22} align="center" verticalAlign="middle" text={text} fontSize={11} fontStyle="600" fontFamily={canvasTheme.font} fill={canvasTheme.accent} />
+ </Group>
+ ))}
+ </Group>
+ )}
+ </>
+ )
+}
+
+type OpeningHandlesProps = {
+ wall: Wall
+ opening: Opening
+ scale: number
+ onStart: (edge: 'op-start' | 'op-end', e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+}
+
+export function OpeningHandles({ wall, opening, scale, onStart }: OpeningHandlesProps) {
+ const px = 1 / scale
+ const angle = (Math.atan2(wall.b.y - wall.a.y, wall.b.x - wall.a.x) * 180) / Math.PI
+ const start = (edge: 'op-start' | 'op-end') => (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if ('button' in e.evt && e.evt.button !== 0) return
+ e.cancelBubble = true
+ onStart(edge, e)
+ }
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+ return (
+ <Group x={wall.a.x} y={wall.a.y} rotation={angle}>
+ {(
+ [
+ ['op-start', opening.offset],
+ ['op-end', opening.offset + opening.width],
+ ] as const
+ ).map(([edge, x]) => (
+ <Rect
+ key={edge}
+ x={x - 4 * px}
+ y={-9 * px}
+ width={8 * px}
+ height={18 * px}
+ cornerRadius={3 * px}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2 * px}
+ hitStrokeWidth={10 * px}
+ onMouseDown={start(edge)}
+ onTouchStart={start(edge)}
+ onMouseEnter={cursor('ew-resize')}
+ onMouseLeave={cursor('')}
+ />
+ ))}
+ </Group>
+ )
+}
+
+type RotateProps = {
+ x: number
+ y: number
+ rotationDeg: number
+ depth: number
+ scale: number
+ onStart: () => void
+}
+
+export function FurnitureRotateHandle({ x, y, rotationDeg, depth, scale, onStart }: RotateProps) {
+ const px = 1 / scale
+ const dist = depth / 2 + 22 * px
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+ return (
+ <Group x={x} y={y} rotation={rotationDeg}>
+ <Line points={[0, -depth / 2, 0, -dist]} stroke={canvasTheme.accent} strokeWidth={1.2 * px} listening={false} />
+ <Circle
+ y={-dist}
+ radius={6 * px}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2 * px}
+ hitStrokeWidth={10 * px}
+ onMouseDown={(e) => {
+ if (e.evt.button !== 0) return
+ e.cancelBubble = true
+ onStart()
+ }}
+ onTouchStart={(e) => {
+ e.cancelBubble = true
+ onStart()
+ }}
+ onMouseEnter={cursor('grab')}
+ onMouseLeave={cursor('')}
+ />
+ </Group>
+ )
+}
diff --git a/src/canvas/LengthLabel.tsx b/src/canvas/LengthLabel.tsx
new file mode 100644
index 0000000..2d50225
--- /dev/null
+++ b/src/canvas/LengthLabel.tsx
@@ -0,0 +1,92 @@
+import { Group, Rect, Text } from 'react-konva'
+import { formatLength, type Point } from '../model'
+import { readableAngle } from './camera'
+import { canvasTheme } from './theme'
+
+type Props = {
+ a: Point
+ b: Point
+ scale: number
+ gap: number
+ accent?: boolean
+ away?: Point
+ onDblClick?: () => void
+ onClick?: () => void
+ viewRot?: number
+}
+
+const FONT = 11
+const HEIGHT = 18
+
+export function labelAnchor(a: Point, b: Point, scale: number, gap: number, away?: Point, viewRot = 0) {
+ const angle = readableAngle((Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI, viewRot)
+ const rad = (angle * Math.PI) / 180
+ const mx = (a.x + b.x) / 2
+ const my = (a.y + b.y) / 2
+ const nx = Math.sin(rad)
+ const ny = -Math.cos(rad)
+ const flip = away && (mx - away.x) * nx + (my - away.y) * ny < 0 ? -1 : 1
+ const offset = flip * (gap + (HEIGHT / 2 + 3) / scale)
+ return { x: mx + nx * offset, y: my + ny * offset, angle }
+}
+
+export function LengthLabel({ a, b, scale, gap, accent, away, onDblClick, onClick, viewRot = 0 }: Props) {
+ const len = Math.hypot(b.x - a.x, b.y - a.y)
+ if (len * scale < 36 && !accent) return null
+ const { x, y, angle } = labelAnchor(a, b, scale, gap, away, viewRot)
+ const text = formatLength(len)
+ const width = text.length * 6.6 + 10
+ return (
+ <Group
+ x={x}
+ y={y}
+ rotation={angle}
+ scaleX={1 / scale}
+ scaleY={1 / scale}
+ listening={!!onDblClick}
+ onDblClick={(e) => {
+ e.cancelBubble = true
+ onDblClick?.()
+ }}
+ onDblTap={(e) => {
+ e.cancelBubble = true
+ onDblClick?.()
+ }}
+ onMouseDown={(e) => {
+ e.cancelBubble = true
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ onClick?.()
+ }}
+ onTap={(e) => {
+ e.cancelBubble = true
+ onClick?.()
+ }}
+ >
+ <Rect
+ x={-width / 2}
+ y={-HEIGHT / 2}
+ width={width}
+ height={HEIGHT}
+ cornerRadius={5}
+ fill={accent ? canvasTheme.accent : 'rgba(255,255,255,0.92)'}
+ stroke={accent ? undefined : canvasTheme.rulerLine}
+ strokeWidth={1}
+ />
+ <Text
+ x={-width / 2}
+ y={-HEIGHT / 2}
+ width={width}
+ height={HEIGHT}
+ align="center"
+ verticalAlign="middle"
+ text={text}
+ fontSize={FONT}
+ fontFamily={canvasTheme.font}
+ fontStyle="600"
+ fill={accent ? '#ffffff' : canvasTheme.ink}
+ />
+ </Group>
+ )
+}
diff --git a/src/canvas/MeasureLayer.tsx b/src/canvas/MeasureLayer.tsx
new file mode 100644
index 0000000..d2b3fa2
--- /dev/null
+++ b/src/canvas/MeasureLayer.tsx
@@ -0,0 +1,72 @@
+import { Circle, Group, Line, Rect, Text } from 'react-konva'
+import { formatNumber, type Point } from '../model'
+import { t } from '../i18n'
+import { readableAngle } from './camera'
+import type { Measure } from './measure'
+import { canvasTheme } from './theme'
+
+type Props = {
+ measures: Measure[]
+ active: Measure | null
+ cursor: Point | null
+ scale: number
+ viewRot: number
+}
+
+const INK = '#1f6feb'
+
+function Segment({ a, b, scale, viewRot, live }: { a: Point; b: Point; scale: number; viewRot: number; live?: boolean }) {
+ const px = 1 / scale
+ const len = Math.hypot(b.x - a.x, b.y - a.y)
+ if (len < 1) return null
+ const deg = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI
+ const shown = readableAngle(deg, viewRot)
+ const nx = -(b.y - a.y) / len
+ const ny = (b.x - a.x) / len
+ const tick = 6 * px
+ const angleText = `${formatNumber(((-deg % 360) + 360) % 360, 0)}°`
+ const m = `${formatNumber(len / 1000, 2)} ${t('common:units.m')}`
+ const text = live ? `${m} · ${angleText}` : m
+ const w = text.length * 6.6 + 12
+ return (
+ <Group listening={false}>
+ <Line points={[a.x, a.y, b.x, b.y]} stroke={INK} strokeWidth={1.6 * px} dash={live ? [6 * px, 4 * px] : undefined} />
+ <Line points={[a.x - nx * tick, a.y - ny * tick, a.x + nx * tick, a.y + ny * tick]} stroke={INK} strokeWidth={1.6 * px} />
+ <Line points={[b.x - nx * tick, b.y - ny * tick, b.x + nx * tick, b.y + ny * tick]} stroke={INK} strokeWidth={1.6 * px} />
+ <Group x={(a.x + b.x) / 2} y={(a.y + b.y) / 2} rotation={shown} scaleX={px} scaleY={px}>
+ <Rect x={-w / 2} y={-22} width={w} height={18} cornerRadius={5} fill={INK} />
+ <Text
+ x={-w / 2}
+ y={-22}
+ width={w}
+ height={18}
+ align="center"
+ verticalAlign="middle"
+ text={text}
+ fontSize={11}
+ fontStyle="600"
+ fontFamily={canvasTheme.font}
+ fill="#ffffff"
+ />
+ </Group>
+ </Group>
+ )
+}
+
+export function MeasureLayer({ measures, active, cursor, scale, viewRot }: Props) {
+ const px = 1 / scale
+ const all = active ? [...measures, active] : measures
+ const last = active?.points.at(-1)
+ return (
+ <>
+ {all.map((m, i) =>
+ m.points.slice(1).map((p, j) => <Segment key={`${i}-${j}`} a={m.points[j]} b={p} scale={scale} viewRot={viewRot} />),
+ )}
+ {all.flatMap((m, i) =>
+ m.points.map((p, j) => <Circle key={`p${i}-${j}`} x={p.x} y={p.y} radius={3 * px} fill={INK} listening={false} />),
+ )}
+ {last && cursor && <Segment a={last} b={cursor} scale={scale} viewRot={viewRot} live />}
+ {cursor && <Circle x={cursor.x} y={cursor.y} radius={4 * px} stroke={INK} strokeWidth={1.5 * px} listening={false} />}
+ </>
+ )
+}
diff --git a/src/canvas/OpeningShape.tsx b/src/canvas/OpeningShape.tsx
new file mode 100644
index 0000000..3578cee
--- /dev/null
+++ b/src/canvas/OpeningShape.tsx
@@ -0,0 +1,145 @@
+import { Group, Line, Rect, Shape } from 'react-konva'
+import { wallAngle, type Opening, type Wall } from '../model'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { canvasTheme } from './theme'
+
+type Props = {
+ wall: Wall
+ opening: Opening
+ scale: number
+ selected?: boolean
+ ghost?: boolean
+ listening?: boolean
+ onPointerDown?: (id: string, e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+}
+
+export function OpeningShape({ wall, opening: o, scale, selected, ghost, listening, onPointerDown }: Props) {
+ const t = wall.thickness
+ const px = 1 / scale
+ const x0 = o.offset
+ const x1 = o.offset + o.width
+ const stroke = selected ? canvasTheme.accent : canvasTheme.ink
+ const down = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if ('button' in e.evt && e.evt.button !== 0) return
+ e.cancelBubble = true
+ onPointerDown?.(o.id, e)
+ }
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+
+ return (
+ <Group
+ x={wall.a.x}
+ y={wall.a.y}
+ rotation={(wallAngle(wall) * 180) / Math.PI}
+ listening={!!listening}
+ opacity={ghost ? 0.75 : 1}
+ onMouseDown={down}
+ onTouchStart={down}
+ onClick={(e) => {
+ e.cancelBubble = true
+ }}
+ onMouseEnter={cursor(selected ? 'ew-resize' : 'pointer')}
+ onMouseLeave={cursor('')}
+ >
+ <Rect
+ x={x0}
+ y={-t / 2 - 2 * px}
+ width={o.width}
+ height={t + 4 * px}
+ fill={ghost ? canvasTheme.accentSoft : canvasTheme.opening}
+ hitStrokeWidth={0}
+ />
+ {selected && (
+ <Rect
+ x={x0}
+ y={-t / 2 - 4 * px}
+ width={o.width}
+ height={t + 8 * px}
+ stroke={canvasTheme.accent}
+ strokeWidth={2 * px}
+ cornerRadius={2 * px}
+ listening={false}
+ />
+ )}
+ <Line points={[x0, -t / 2, x0, t / 2]} stroke={stroke} strokeWidth={1.5 * px} listening={false} />
+ <Line points={[x1, -t / 2, x1, t / 2]} stroke={stroke} strokeWidth={1.5 * px} listening={false} />
+ {o.type === 'window' ? (
+ <WindowSymbol x0={x0} x1={x1} t={t} px={px} />
+ ) : o.type === 'gate' ? (
+ <GateSymbol o={o} t={t} px={px} />
+ ) : (
+ <DoorSymbol o={o} t={t} px={px} />
+ )}
+ <Rect x={x0} y={-Math.max(t / 2, 8 * px)} width={o.width} height={Math.max(t, 16 * px)} fill="transparent" />
+ </Group>
+ )
+}
+
+function GateSymbol({ o, t, px }: { o: Opening; t: number; px: number }) {
+ const sign = o.side === 'left' ? -1 : 1
+ const y0 = (sign * t) / 2
+ const y1 = y0 + sign * 600
+ const x0 = o.offset
+ const x1 = o.offset + o.width
+ return (
+ <>
+ <Line points={[x0, y0, x1, y0]} stroke={canvasTheme.ink} strokeWidth={1.2 * px} listening={false} />
+ <Line
+ points={[x0, y1, x1, y1]}
+ stroke={canvasTheme.ink}
+ strokeWidth={1.5 * px}
+ dash={[8 * px, 5 * px]}
+ listening={false}
+ />
+ <Line points={[x0, y0, x0, y1]} stroke={canvasTheme.inkMuted} strokeWidth={1 * px} dash={[4 * px, 4 * px]} listening={false} />
+ <Line points={[x1, y0, x1, y1]} stroke={canvasTheme.inkMuted} strokeWidth={1 * px} dash={[4 * px, 4 * px]} listening={false} />
+ </>
+ )
+}
+
+function WindowSymbol({ x0, x1, t, px }: { x0: number; x1: number; t: number; px: number }) {
+ const stroke = canvasTheme.ink
+ return (
+ <>
+ <Rect x={x0} y={-t / 2} width={x1 - x0} height={t} stroke={stroke} strokeWidth={1.2 * px} fill="#eef7fb" />
+ <Line points={[x0, -t / 6, x1, -t / 6]} stroke={stroke} strokeWidth={1 * px} />
+ <Line points={[x0, t / 6, x1, t / 6]} stroke={stroke} strokeWidth={1 * px} />
+ </>
+ )
+}
+
+function DoorSymbol({ o, t, px }: { o: Opening; t: number; px: number }) {
+ const hingeAtEnd = o.hinge === 'end'
+ const sign = o.side === 'left' ? -1 : 1
+ const hx = hingeAtEnd ? o.offset + o.width : o.offset
+ const hy = (sign * t) / 2
+ const r = o.width
+ const leafAngle = sign > 0 ? Math.PI / 2 : -Math.PI / 2
+ const closedAngle = hingeAtEnd ? Math.PI : 0
+ const sweep = (((closedAngle - leafAngle) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)
+ const anticlockwise = Math.abs(sweep - Math.PI / 2) > 1e-6
+
+ return (
+ <>
+ <Line
+ points={[hx, hy, hx, hy + sign * r]}
+ stroke={canvasTheme.ink}
+ strokeWidth={2 * px}
+ lineCap="round"
+ />
+ <Shape
+ stroke={canvasTheme.inkMuted}
+ strokeWidth={1 * px}
+ dash={[6 * px, 4 * px]}
+ sceneFunc={(ctx, shape) => {
+ ctx.beginPath()
+ ctx.arc(hx, hy, r, leafAngle, closedAngle, anticlockwise)
+ ctx.strokeShape(shape)
+ }}
+ />
+ </>
+ )
+}
diff --git a/src/canvas/PlanCanvas.tsx b/src/canvas/PlanCanvas.tsx
new file mode 100644
index 0000000..354aa58
--- /dev/null
+++ b/src/canvas/PlanCanvas.tsx
@@ -0,0 +1,1508 @@
+import { useCallback, useEffect, useMemo, useRef, useState, type ComponentType } from 'react'
+import { Circle, Layer, Line, Stage } from 'react-konva'
+import type Konva from 'konva'
+import { useTranslation } from 'react-i18next'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { FurnitureSymbol2D } from '../furniture/Symbol2D'
+import { resolveFurniture } from '../furniture/catalog'
+import {
+ addFurniture,
+ addZone,
+ deleteZone,
+ updateZone,
+ deleteFurniture,
+ normalizeDeg,
+ updateFurniture,
+ OPENING_PRESETS,
+ addOpening,
+ deleteOpening,
+ distanceToSegment,
+ formatMeters,
+ fitOffset,
+ fitOffsetClear,
+ moveOpening,
+ openingGaps,
+ resizeOpening,
+ snapOffset,
+ updateOpening,
+ wallDirection,
+ type Opening,
+ type Wall,
+ endpointGroup,
+ findMaterial,
+ materialColor,
+ moveEndpoint,
+ moveWall,
+ setWallLength,
+ sitePolygon,
+ wallColor,
+ wallLength,
+ wallMoveGroup,
+ type EndRef,
+ type Plan,
+ type Point,
+} from '../model'
+import { redo, undo, usePlanStore } from '../store/planStore'
+import { setBusy } from '../storage/busy'
+import { isViewOnly, useViewOnly } from '../store/viewOnly'
+import { anchorAt, clampScale, fitCamera, northAngle, normRot, toScreen, toWorld, type Camera } from './camera'
+import { ViewControls } from './ViewControls'
+import { MeasureLayer } from './MeasureLayer'
+import { snapZonePoint, ZoneShape } from './ZoneShape'
+import { measureTargets, polylineLength, snapMeasure, type Measure } from './measure'
+import { RoomHover } from './RoomLabels'
+import { detectRooms, pointInPolygon, type RoomFace } from '../stats/rooms'
+import { showToast } from '../ui/Toast'
+import { useUnderlayAlign, type UnderlayAlign } from '../map/useUnderlayAlign'
+import { Grid } from './Grid'
+import { FurnitureRotateHandle, Handles, OpeningHandles, type HandleKind } from './Handles'
+import { labelAnchor, LengthLabel } from './LengthLabel'
+import { Dimensions } from './Dimensions'
+import { OpeningShape } from './OpeningShape'
+import { Rulers } from './Rulers'
+import { GRID_SNAP, snapAngle, snapPoint, type Snap } from './snap'
+import { canvasTheme, RULER_SIZE } from './theme'
+import { useElementSize } from './useElementSize'
+import { SewerLayer, WaterLayer, layerLocks, lockedToast, stopEdit, useBaseOpacity, useLayerLocks, useLayers, useNetworkEdit } from '../networks'
+import { ElectricLayer } from '../networks/electric'
+import { HeatingLayer } from '../networks/heating'
+import { WallFill, WallOutline } from './WallShape'
+import { buildingSel, CornerHint, formatDeg, groupRotateDeg, wrapDeg, emptySel, groupGuides, groupPolys, GroupOverlay, GuideLines, mergeSel, MoveHandle, movePlan, polysCenter, rectSel, ROTATE_CURSOR, rotatePlan, selBounds, selCenter, selHas, selectAll, toggleSel, withoutLocked, type ScreenRect, type SelKind, type Selection } from './selection'
+
+const narrowView = () => window.innerWidth <= 760
+const rulerTop = () => 0
+const headerBottom = () => (narrowView() ? 24 + 6 + 52 : 24 + 8 + 52)
+const chromeRect = (selector: string) => {
+ const r = document.querySelector(selector)?.getBoundingClientRect()
+ return r && r.width > 0 && r.height > 0 ? r : null
+}
+const fitPadding = (el?: HTMLElement | null) => {
+ if (narrowView()) return { left: RULER_SIZE + 12, top: headerBottom() + 12, right: 12, bottom: 86 }
+ const c = el?.getBoundingClientRect()
+ const header = chromeRect('.header')
+ const toolbar = chromeRect('.toolbar')
+ const panel = chromeRect('.inspector')
+ const left = c && toolbar && toolbar.right < c.left + c.width / 2 ? toolbar.right - c.left : RULER_SIZE
+ const right = c && panel && panel.left > c.left + c.width / 2 ? c.right - panel.left : 0
+ const top = c && header ? header.bottom - c.top : headerBottom()
+ return { left: Math.max(RULER_SIZE, left) + 24, top: Math.max(0, top) + 24, right: Math.max(0, right) + 24, bottom: 24 }
+}
+const DEFAULT_CAM: Camera = { x: 0, y: 0, scale: 0.05 }
+const DRAG_THRESHOLD_PX = 3
+
+type DragKind = HandleKind | 'op-move' | 'op-start' | 'op-end' | 'fur-move' | 'fur-rot' | 'room-move' | 'group-move' | 'group-rot' | 'zone-vertex'
+
+type Ghost = { wallId: string; opening: Opening }
+
+type Drag = {
+ kind: DragKind
+ wallId: string
+ openingId?: string
+ furnitureId?: string
+ roomId?: string
+ zoneId?: string
+ vertex?: number
+ origin: Point
+ originScreen: Point
+ base: Plan
+ moved: boolean
+ pick?: [SelKind, string]
+ pivot?: Point
+ altPivot?: Point
+}
+
+type LengthEdit = { wallId: string; value: string }
+
+type ViewBox = { x: number; y: number; scale: number; width: number; height: number; rotationDeg?: number }
+
+type UnderlayModules = {
+ Underlay: ComponentType<{ plan: Plan; view: ViewBox; opacity?: number; geo?: UnderlayAlign['shown']; imagery?: UnderlayAlign['imagery'] }>
+ Overlay: ComponentType<{ align: UnderlayAlign; view: ViewBox }>
+ Controls: ComponentType<{ align: UnderlayAlign }>
+}
+
+function useUnderlay(enabled: boolean) {
+ const [mods, setMods] = useState<UnderlayModules | null>(null)
+ useEffect(() => {
+ if (!enabled || mods) return
+ let alive = true
+ Promise.all([import('../map/SatelliteUnderlay'), import('../map/UnderlayAlign')])
+ .then(([u, a]) => {
+ if (alive) setMods({ Underlay: u.default as UnderlayModules['Underlay'], Overlay: a.default, Controls: a.UnderlayAlignControls })
+ })
+ .catch(() => undefined)
+ return () => {
+ alive = false
+ }
+ }, [enabled, mods])
+ return enabled ? mods : null
+}
+
+const NO_PLAN = { site: {} } as Plan
+
+type Props = { onCursor?: (p: Point | null, scale: number) => void }
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+export function PlanCanvas({ onCursor }: Props) {
+ const { t } = useTranslation('common')
+ const [containerRef, size] = useElementSize<HTMLDivElement>()
+ const plan = usePlanStore((s) => s.plan)
+ const tool = usePlanStore((s) => s.tool)
+ const selectedWallId = usePlanStore((s) => s.selectedWallId)
+ const selectedOpeningId = usePlanStore((s) => s.selectedOpeningId)
+ const selectOpening = usePlanStore((s) => s.selectOpening)
+ const doorPreset = usePlanStore((s) => s.doorPreset)
+ const selectedFurnitureId = usePlanStore((s) => s.selectedFurnitureId)
+ const selectFurniture = usePlanStore((s) => s.selectFurniture)
+ const activeMaterialId = usePlanStore((s) => s.activeMaterialId)
+ const fitNonce = usePlanStore((s) => s.fitNonce)
+ const storedCam = usePlanStore((s) => s.cam)
+ const setStoredCam = usePlanStore((s) => s.setCam)
+ const selectWall = usePlanStore((s) => s.selectWall)
+ const addWall = usePlanStore((s) => s.addWall)
+ const deleteWall = usePlanStore((s) => s.deleteWall)
+ const setTool = usePlanStore((s) => s.setTool)
+ const commit = usePlanStore((s) => s.commit)
+ const underlay = usePlanStore((s) => s.underlay)
+ const underlayMods = useUnderlay(underlay.on)
+ const Underlay = underlayMods?.Underlay ?? null
+ const aligning = usePlanStore((s) => s.aligning) && underlay.on && !isViewOnly()
+ const setAligning = usePlanStore((s) => s.setAligning)
+ const align = useUnderlayAlign(
+ plan ?? NO_PLAN,
+ (geo) => {
+ const current = usePlanStore.getState().plan
+ if (current) commit({ ...current, site: { ...current.site, geo } })
+ },
+ (imagery) => {
+ const current = usePlanStore.getState().plan
+ if (current) commit({ ...current, site: { ...current.site, imagery } })
+ },
+ )
+
+ const cam = storedCam ?? DEFAULT_CAM
+ const layers = useLayers()
+ const locks = useLayerLocks()
+ const baseOpacity = useBaseOpacity()
+ const viewOnly = useViewOnly()
+ const rot = cam.rotation ?? 0
+ const [cursor, setCursor] = useState<Snap | null>(null)
+ const [draftStart, setDraftStart] = useState<Point | null>(null)
+ const [shiftDown, setShiftDown] = useState(false)
+ const [drag, setDrag] = useState<Drag | null>(null)
+ const [preview, setPreview] = useState<Plan | null>(null)
+ const [lengthEdit, setLengthEdit] = useState<LengthEdit | null>(null)
+ const [ghost, setGhost] = useState<Ghost | null>(null)
+ const [measures, setMeasures] = useState<Measure[]>([])
+ const [activeMeasure, setActiveMeasure] = useState<Measure | null>(null)
+ const [measureCursor, setMeasureCursor] = useState<Point | null>(null)
+ const [roomEdit, setRoomEdit] = useState<{ id: string; value: string } | null>(null)
+ const [ctxMenu, setCtxMenu] = useState<{ left: number; top: number; at: Point } | null>(null)
+ const [hoverRoom, setHoverRoom] = useState<RoomFace | null>(null)
+ const group = usePlanStore((s) => s.group)
+ const [marquee, setMarquee] = useState<(ScreenRect & { add: boolean }) | null>(null)
+ const [groupInfo, setGroupInfo] = useState<{ text: string; at: Point } | null>(null)
+ const [hoverCorner, setHoverCorner] = useState<Point | null>(null)
+ const [hoverWall, setHoverWall] = useState<string | null>(null)
+ const [hoverZone, setHoverZone] = useState<string | null>(null)
+ const [zoneDraft, setZoneDraft] = useState<Point[]>([])
+ const [zoneCursor, setZoneCursor] = useState<Point | null>(null)
+ const selectedZoneId = usePlanStore((s) => s.selectedZoneId)
+ const selectZone = usePlanStore((s) => s.selectZone)
+ const finishZone = (pts: Point[]) => {
+ const current = usePlanStore.getState().plan
+ setZoneDraft([])
+ if (!current || pts.length < 3) return
+ const res = addZone(current, pts)
+ commit(res.plan)
+ setTool('select')
+ selectZone(res.id)
+ }
+ const showDims = usePlanStore((s) => s.showDims)
+ const panRef = useRef(false)
+ const suppressClickUntil = useRef(0)
+
+ useEffect(() => {
+ setBusy(!!drag || !!lengthEdit)
+ }, [drag, lengthEdit])
+ const stageRef = useRef<Konva.Stage>(null)
+ const fittedRef = useRef(-1)
+ const siteKeyRef = useRef<string | null>(null)
+
+ const shown = preview ?? plan
+ const hasPlan = !!plan
+ const ready = size.width > 0 && size.height > 0
+
+ useEffect(() => {
+ if (!hasPlan || !ready || fittedRef.current === fitNonce) return
+ const ps = usePlanStore.getState().plan?.site
+ siteKeyRef.current = ps ? JSON.stringify([ps.boundary, ps.width, ps.depth]) : null
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ fittedRef.current = fitNonce
+ setStoredCam(
+ fitCamera(sitePolygon(current.site), size.width, size.height, fitPadding(containerRef.current), usePlanStore.getState().cam?.rotation ?? 0),
+ )
+ }, [hasPlan, ready, fitNonce, size.width, size.height, setStoredCam])
+
+ const narrowNow = size.width > 0 && size.width <= 760
+ const narrowRef = useRef<boolean | null>(null)
+ useEffect(() => {
+ if (size.width === 0) return
+ if (narrowRef.current !== null && narrowRef.current !== narrowNow) usePlanStore.getState().requestFit()
+ narrowRef.current = narrowNow
+ }, [narrowNow, size.width])
+
+ const siteKey = plan ? JSON.stringify([plan.site.boundary, plan.site.width, plan.site.depth]) : null
+ useEffect(() => {
+ if (!siteKey || siteKeyRef.current === null || siteKeyRef.current === siteKey) return
+ siteKeyRef.current = siteKey
+ usePlanStore.getState().requestFit()
+ }, [siteKey])
+
+ useEffect(() => {
+ if (!viewOnly) return
+ const st = usePlanStore.getState()
+ if (st.tool !== 'select' && st.tool !== 'measure') st.setTool('select')
+ if (st.aligning) st.setAligning(false)
+ st.selectWall(null)
+ }, [viewOnly])
+
+ useEffect(() => {
+ const st = usePlanStore.getState()
+ if (locks.walls && (st.tool === 'wall' || st.tool === 'door' || st.tool === 'window')) st.setTool('select')
+ if (locks.zones && st.tool === 'zone') st.setTool('select')
+ if ((locks.walls && (st.selectedWallId || st.selectedOpeningId)) || (locks.furniture && st.selectedFurnitureId) || (locks.zones && st.selectedZoneId)) st.selectWall(null)
+ if (st.group && st.tool !== 'building') st.setGroup(withoutLocked(st.group, locks))
+ }, [locks.walls, locks.furniture, locks.zones, tool])
+
+ useEffect(() => {
+ if (tool !== 'wall') setDraftStart(null)
+ if (tool !== 'door' && tool !== 'window') setGhost(null)
+ }, [tool])
+
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (e.key === 'Shift') setShiftDown(true)
+ if (isTyping(e)) return
+ const mod = e.metaKey || e.ctrlKey
+ if (mod && (e.key === 'z' || e.key === 'Z' || e.key === 'я' || e.key === 'Я')) {
+ e.preventDefault()
+ if (e.shiftKey) redo()
+ else undo()
+ return
+ }
+ if (mod && (e.key === 'y' || e.key === 'н')) {
+ e.preventDefault()
+ redo()
+ return
+ }
+ if (mod && (e.key === 'a' || e.key === 'ф' || e.key === 'A' || e.key === 'Ф') && !isViewOnly()) {
+ const st = usePlanStore.getState()
+ if (!st.plan) return
+ e.preventDefault()
+ st.setTool('select')
+ st.setGroup(withoutLocked(selectAll(st.plan), layerLocks()))
+ return
+ }
+ if (mod) return
+ const state = usePlanStore.getState()
+ if (isViewOnly()) {
+ if (e.key === 'm' || e.key === 'ь') setTool(state.tool === 'measure' ? 'select' : 'measure')
+ if (e.key === 'Escape') {
+ setMeasures([])
+ setActiveMeasure(null)
+ }
+ return
+ }
+ if (e.key === 'Escape' && state.aligning) {
+ setAligning(false)
+ return
+ }
+ if (e.key === 'b' || e.key === 'и' || e.key === 'B' || e.key === 'И') {
+ if (useNetworkEdit.getState().editing) stopEdit()
+ setTool('building')
+ return
+ }
+ if (e.key === 'Escape' && state.tool === 'building') {
+ state.setGroup(null)
+ setTool('select')
+ return
+ }
+ if (state.group && (state.tool === 'select' || state.tool === 'building')) {
+ const arrows: Record<string, Point> = { ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 }, ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 } }
+ const dir = arrows[e.key]
+ if (dir) {
+ e.preventDefault()
+ const r = (-(state.cam?.rotation ?? 0) * Math.PI) / 180
+ const wx = dir.x * Math.cos(r) - dir.y * Math.sin(r)
+ const wy = dir.x * Math.sin(r) + dir.y * Math.cos(r)
+ const step = e.shiftKey ? 1000 : 100
+ if (Math.abs(wx) >= Math.abs(wy)) state.moveGroup(Math.sign(wx) * step, 0)
+ else state.moveGroup(0, Math.sign(wy) * step)
+ return
+ }
+ if (e.code === 'BracketLeft' || e.code === 'BracketRight') {
+ e.preventDefault()
+ state.rotateGroup((e.code === 'BracketLeft' ? -1 : 1) * (e.shiftKey ? 15 : 1))
+ return
+ }
+ if (e.key === 'Delete' || e.key === 'Backspace') {
+ e.preventDefault()
+ state.deleteGroup()
+ return
+ }
+ if (e.key === 'Escape') {
+ state.setGroup(null)
+ return
+ }
+ }
+ const op = state.plan?.openings.find((o) => o.id === state.selectedOpeningId)
+ const fur = state.plan?.furniture.find((f) => f.id === state.selectedFurnitureId)
+ const lk = layerLocks()
+ if (fur && state.plan && lk.furniture) return
+ if (fur && state.plan && (e.key === 'Delete' || e.key === 'Backspace')) {
+ e.preventDefault()
+ state.commit(deleteFurniture(state.plan, fur.id))
+ return
+ }
+ if (fur && state.plan && (e.key === 'r' || e.key === 'к' || e.key === 'R' || e.key === 'К')) {
+ state.commit(updateFurniture(state.plan, fur.id, { rotationDeg: normalizeDeg(fur.rotationDeg + (e.shiftKey ? -90 : 90)) }))
+ return
+ }
+ if (e.key === 'm' || e.key === 'ь' || e.key === 'M' || e.key === 'Ь') {
+ if (state.tool === 'measure') {
+ setMeasures([])
+ setActiveMeasure(null)
+ } else setTool('measure')
+ return
+ }
+ if (state.tool === 'zone' && (e.key === 'Enter' || e.key === 'Escape')) {
+ if (e.key === 'Enter') finishZone(zoneDraft)
+ else if (zoneDraft.length) setZoneDraft([])
+ else setTool('select')
+ return
+ }
+ if (state.selectedZoneId && state.plan && (e.key === 'Delete' || e.key === 'Backspace') && !lk.zones) {
+ e.preventDefault()
+ if (!state.plan.site.zones?.find((z) => z.id === state.selectedZoneId)?.locked)
+ state.commit(deleteZone(state.plan, state.selectedZoneId))
+ return
+ }
+ if (e.key === 'Escape' && state.tool === 'measure') {
+ setMeasures([])
+ setActiveMeasure(null)
+ return
+ }
+ if (e.key === 'Escape') {
+ setCtxMenu(null)
+ if (draftStart) setDraftStart(null)
+ else if (state.tool !== 'select') setTool('select')
+ else selectWall(null)
+ } else if (lk.walls && (e.key === 'd' || e.key === 'в' || e.key === 'o' || e.key === 'щ' || e.key === 'w' || e.key === 'ц')) {
+ lockedToast('walls')
+ } else if (lk.walls && (op || state.selectedWallId)) {
+ return
+ } else if ((e.key === 'Delete' || e.key === 'Backspace') && op && state.plan) {
+ e.preventDefault()
+ state.commit(deleteOpening(state.plan, op.id))
+ } else if ((e.key === 'Delete' || e.key === 'Backspace') && state.selectedWallId) {
+ e.preventDefault()
+ deleteWall(state.selectedWallId)
+ } else if ((e.key === 'f' || e.key === 'а') && (op?.type === 'door' || op?.type === 'gate') && state.plan) {
+ state.commit(updateOpening(state.plan, op.id, { side: op.side === 'left' ? 'right' : 'left' }))
+ } else if ((e.key === 'h' || e.key === 'р') && op?.type === 'door' && state.plan) {
+ state.commit(updateOpening(state.plan, op.id, { hinge: op.hinge === 'end' ? 'start' : 'end' }))
+ } else if (e.key === 'v' || e.key === 'м') {
+ setTool('select')
+ } else if (e.key === 'd' || e.key === 'в') {
+ setTool('door')
+ } else if (e.key === 'o' || e.key === 'щ') {
+ setTool('window')
+ } else if (e.key === 'w' || e.key === 'ц') {
+ setTool('wall')
+ } else if (e.key === 'Enter') {
+ setDraftStart(null)
+ }
+ }
+ const up = (e: KeyboardEvent) => {
+ if (e.key === 'Shift') setShiftDown(false)
+ }
+ window.addEventListener('keydown', down)
+ window.addEventListener('keyup', up)
+ return () => {
+ window.removeEventListener('keydown', down)
+ window.removeEventListener('keyup', up)
+ }
+ }, [draftStart, deleteWall, selectWall, setTool, setAligning, zoneDraft])
+
+ const worldPointer = useCallback((): Point | null => {
+ const p = stageRef.current?.getRelativePointerPosition()
+ return p ? { x: p.x, y: p.y } : null
+ }, [])
+
+ const screenPointer = useCallback((): Point | null => {
+ const p = stageRef.current?.getPointerPosition()
+ return p ? { x: p.x, y: p.y } : null
+ }, [])
+
+ const startDrag = useCallback(
+ (kind: DragKind, wallId: string, openingId?: string, furnitureId?: string, roomId?: string, zoneId?: string, vertex?: number) => {
+ const origin = worldPointer()
+ const originScreen = screenPointer()
+ const base = usePlanStore.getState().plan
+ if (!origin || !originScreen || !base) return
+ stageRef.current?.stopDrag()
+ setDrag({ kind, wallId, openingId, furnitureId, roomId, zoneId, vertex, origin, originScreen, base, moved: false })
+ },
+ [screenPointer, worldPointer],
+ )
+
+ const dragPlan = (d: Drag, raw: Point, shift: boolean, alt: boolean): Plan => {
+ if (d.kind === 'group-move' || d.kind === 'group-rot') {
+ const g = usePlanStore.getState().group
+ if (!g) return d.base
+ const sp = screenPointer()
+ if (d.kind === 'group-move') {
+ const delta = { x: raw.x - d.origin.x, y: raw.y - d.origin.y }
+ const snapped = shift
+ ? snapAngle({ x: 0, y: 0 }, delta)
+ : { x: Math.round(delta.x / GRID_SNAP) * GRID_SNAP, y: Math.round(delta.y / GRID_SNAP) * GRID_SNAP }
+ if (sp) setGroupInfo({ text: t('canvas.groupMove', { x: formatMeters(snapped.x), y: formatMeters(snapped.y) }), at: sp })
+ return movePlan(d.base, g, snapped)
+ }
+ const c = (alt && d.altPivot) || d.pivot || selCenter(d.base, g)
+ if (!c) return d.base
+ const deg = ((Math.atan2(raw.y - c.y, raw.x - c.x) - Math.atan2(d.origin.y - c.y, d.origin.x - c.x)) * 180) / Math.PI
+ const snappedDeg = groupRotateDeg(d.base, g, wrapDeg(deg), shift)
+ if (sp) setGroupInfo({ text: formatDeg(snappedDeg), at: sp })
+ return rotatePlan(d.base, g, snappedDeg, c)
+ }
+ if (d.kind === 'zone-vertex') {
+ const z = d.base.site.zones?.find((x) => x.id === d.zoneId)
+ if (!z || z.locked || d.vertex === undefined) return d.base
+ const prev = z.polygon[(d.vertex - 1 + z.polygon.length) % z.polygon.length]
+ const p = snapZonePoint(raw, d.base, cam.scale, prev, shift, z.polygon[d.vertex])
+ return updateZone(d.base, z.id, { polygon: z.polygon.map((q, i) => (i === d.vertex ? p : q)) })
+ }
+ if (d.kind === 'room-move') {
+ const rooms = d.base.rooms ?? []
+ const r = rooms.find((x) => x.id === d.roomId)
+ if (!r) return d.base
+ const nx = snapOffset(r.x + raw.x - d.origin.x)
+ const ny = snapOffset(r.y + raw.y - d.origin.y)
+ return { ...d.base, rooms: rooms.map((x) => (x.id === r.id ? { ...x, x: nx, y: ny } : x)) }
+ }
+ if (d.kind === 'fur-move' || d.kind === 'fur-rot') {
+ const f = d.base.furniture.find((x) => x.id === d.furnitureId)
+ if (!f) return d.base
+ if (d.kind === 'fur-move') {
+ return updateFurniture(d.base, f.id, {
+ x: snapOffset(f.x + raw.x - d.origin.x),
+ y: snapOffset(f.y + raw.y - d.origin.y),
+ })
+ }
+ const deg = (Math.atan2(raw.y - f.y, raw.x - f.x) * 180) / Math.PI + 90
+ const step = shift ? 5 : 15
+ return updateFurniture(d.base, f.id, { rotationDeg: normalizeDeg(Math.round(deg / step) * step) })
+ }
+ const wall = d.base.walls.find((w) => w.id === d.wallId)
+ if (!wall) return d.base
+ if (d.kind === 'op-move' || d.kind === 'op-start' || d.kind === 'op-end') {
+ const o = d.base.openings.find((x) => x.id === d.openingId)
+ if (!o) return d.base
+ const dir = wallDirection(wall)
+ const along = (raw.x - wall.a.x) * dir.x + (raw.y - wall.a.y) * dir.y
+ if (d.kind === 'op-move') {
+ const start = (d.origin.x - wall.a.x) * dir.x + (d.origin.y - wall.a.y) * dir.y
+ return moveOpening(d.base, o.id, snapOffset(o.offset + along - start))
+ }
+ return resizeOpening(d.base, o.id, d.kind === 'op-start' ? 'start' : 'end', snapOffset(along))
+ }
+ if (d.kind === 'move') {
+ const delta = { x: raw.x - d.origin.x, y: raw.y - d.origin.y }
+ const snapped = shift
+ ? snapAngle({ x: 0, y: 0 }, delta)
+ : { x: Math.round(delta.x / GRID_SNAP) * GRID_SNAP, y: Math.round(delta.y / GRID_SNAP) * GRID_SNAP }
+ return moveWall(d.base, d.wallId, snapped, alt)
+ }
+ const ref: EndRef = { wallId: d.wallId, end: d.kind }
+ const moving = endpointGroup(d.base, ref, alt)
+ const fixed = wall[d.kind === 'a' ? 'b' : 'a']
+ const skip = (wallId: string, end: 'a' | 'b') =>
+ moving.some((r) => r.wallId === wallId && r.end === end) || (wallId === d.wallId && end !== d.kind)
+ const snap = snapPoint(raw, d.base.walls, cam.scale, fixed, shift, skip)
+ setCursor(snap)
+ return moveEndpoint(d.base, ref, snap.point, alt)
+ }
+
+ const pinchRef = useRef<{ dist: number; center: Point } | null>(null)
+
+ const onTouchMove = (e: KonvaEventObject<TouchEvent>) => {
+ const touches = e.evt.touches
+ if (touches.length < 2) {
+ if (!pinchRef.current) onMouseMove(e)
+ return
+ }
+ e.evt.preventDefault()
+ const stage = stageRef.current
+ if (!stage) return
+ if (stage.isDragging()) stage.stopDrag()
+ if (drag) {
+ setDrag(null)
+ setPreview(null)
+ }
+ const rect = stage.container().getBoundingClientRect()
+ const p1 = { x: touches[0].clientX - rect.left, y: touches[0].clientY - rect.top }
+ const p2 = { x: touches[1].clientX - rect.left, y: touches[1].clientY - rect.top }
+ const center = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }
+ const dist = Math.hypot(p1.x - p2.x, p1.y - p2.y)
+ suppressClickUntil.current = Date.now() + 500
+ const prev = pinchRef.current
+ pinchRef.current = { dist, center }
+ if (!prev) return
+ const current = usePlanStore.getState().cam ?? cam
+ const world = toWorld(current, prev.center)
+ const scale = clampScale(current.scale * (dist / prev.dist))
+ setCam(anchorAt({ ...current, scale }, world, center))
+ }
+
+ const onTouchEnd = (e: KonvaEventObject<TouchEvent>) => {
+ if (e.evt.touches.length < 2 && pinchRef.current) {
+ pinchRef.current = null
+ suppressClickUntil.current = Date.now() + 500
+ panRef.current = true
+ }
+ }
+
+ const onMouseMove = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ const shift = e.evt.shiftKey || shiftDown
+ const raw = worldPointer()
+ if (!raw) return
+ if (marquee) {
+ const sp = screenPointer()
+ if (sp) setMarquee({ ...marquee, x1: sp.x, y1: sp.y })
+ return
+ }
+ if (drag) {
+ const sp = screenPointer()
+ const far =
+ drag.moved ||
+ (sp && Math.hypot(sp.x - drag.originScreen.x, sp.y - drag.originScreen.y) > DRAG_THRESHOLD_PX)
+ if (!far) return
+ if (!drag.moved) setDrag({ ...drag, moved: true })
+ setPreview(dragPlan(drag, raw, shift, e.evt.altKey))
+ onCursor?.(raw, cam.scale)
+ return
+ }
+ const walls = usePlanStore.getState().plan?.walls ?? []
+ if (tool === 'zone') {
+ const current = usePlanStore.getState().plan
+ if (current) setZoneCursor(snapZonePoint(raw, current, cam.scale, zoneDraft.at(-1) ?? null, shift))
+ onCursor?.(raw, cam.scale)
+ return
+ }
+ if (tool === 'measure') {
+ const from = activeMeasure?.points.at(-1) ?? null
+ const snap = e.evt.altKey ? { point: raw } : snapMeasure(raw, targets, cam.scale, from, shift)
+ setMeasureCursor(snap.point)
+ onCursor?.(snap.point, cam.scale)
+ return
+ }
+ if (tool === 'door' || tool === 'window') {
+ setGhost(ghostAt(raw))
+ setCursor(null)
+ onCursor?.(raw, cam.scale)
+ return
+ }
+ const snap = snapPoint(raw, walls, cam.scale, draftStart, shift)
+ setCursor(snap)
+ onCursor?.(snap.point, cam.scale)
+ if (tool === 'select' && !viewOnly) {
+ const face = findRoomAt(raw)
+ if ((face?.id ?? null) !== (hoverRoom?.id ?? null)) setHoverRoom(face)
+ } else if (hoverRoom) setHoverRoom(null)
+ const sp = screenPointer()
+ const corner =
+ (tool === 'select' || tool === 'building') && !viewOnly && group && sp && e.target === stageRef.current && !groupPolygons.some((poly) => pointInPolygon(raw, poly))
+ ? (groupCorners.find((c) => {
+ const q = toScreen(cam, c)
+ const dd = Math.hypot(q.x - sp.x, q.y - sp.y)
+ return dd >= 6 && dd <= 24
+ }) ?? null)
+ : null
+ if (corner !== hoverCorner) {
+ setHoverCorner(corner)
+ const st = stageRef.current
+ if (st && (corner || hoverCorner)) st.container().style.cursor = corner ? ROTATE_CURSOR : ''
+ }
+ }
+
+ function ghostAt(raw: Point): Ghost | null {
+ const current = usePlanStore.getState().plan
+ if (!current) return null
+ let best: Wall | null = null
+ let bestD = Infinity
+ for (const w of current.walls) {
+ const d = distanceToSegment(raw, w.a, w.b)
+ if (d <= Math.max(w.thickness / 2, 14 / cam.scale) && d < bestD) {
+ best = w
+ bestD = d
+ }
+ }
+ if (!best) return null
+ const spec = OPENING_PRESETS[tool === 'window' ? 'window' : doorPreset]
+ const dir = wallDirection(best)
+ const along = (raw.x - best.a.x) * dir.x + (raw.y - best.a.y) * dir.y
+ const offset = fitOffset(current, best.id, spec.width, snapOffset(along - spec.width / 2))
+ if (offset === null) return null
+ const { label: _label, ...rest } = spec
+ void _label
+ return { wallId: best.id, opening: { ...rest, id: '__ghost', wallId: best.id, offset } }
+ }
+
+ const groupPick = (kind: SelKind, id: string, shift: boolean) => {
+ const st = usePlanStore.getState()
+ if (shift) {
+ const cur: Selection = st.group ?? {
+ ...emptySel(),
+ walls: st.selectedWallId ? [st.selectedWallId] : [],
+ openings: st.selectedOpeningId ? [st.selectedOpeningId] : [],
+ furniture: st.selectedFurnitureId ? [st.selectedFurnitureId] : [],
+ }
+ st.setGroup(toggleSel(cur, kind, id))
+ stageRef.current?.stopDrag()
+ suppressClickUntil.current = Date.now() + 350
+ return true
+ }
+ if (!selHas(st.group, kind, id)) return false
+ startDrag('group-move', '')
+ setDrag((d) => (d ? { ...d, pick: [kind, id] } : d))
+ return true
+ }
+
+ const finishMarquee = () => {
+ if (!marquee) return
+ setMarquee(null)
+ suppressClickUntil.current = Date.now() + 350
+ const current = usePlanStore.getState().plan
+ if (!current || Math.hypot(marquee.x1 - marquee.x0, marquee.y1 - marquee.y0) < DRAG_THRESHOLD_PX) return
+ const st = usePlanStore.getState()
+ const hit = withoutLocked(rectSel(current, cam, marquee), layerLocks())
+ st.setGroup(marquee.add && st.group ? mergeSel(st.group, hit) : hit)
+ }
+
+ useEffect(() => {
+ if (!marquee) return
+ const up = () => finishMarquee()
+ window.addEventListener('mouseup', up)
+ return () => window.removeEventListener('mouseup', up)
+ })
+
+ const finishDrag = useCallback(() => {
+ if (!drag) return
+ if (drag.moved && preview) commit(preview)
+ if (!drag.moved && drag.pick) {
+ const st = usePlanStore.getState()
+ const [kind, id] = drag.pick
+ if (kind === 'walls') st.selectWall(id)
+ else if (kind === 'openings') st.selectOpening(id)
+ else if (kind === 'furniture') st.selectFurniture(id)
+ }
+ setGroupInfo(null)
+ suppressClickUntil.current = Date.now() + 350
+ setDrag(null)
+ setPreview(null)
+ setCursor(null)
+ }, [commit, drag, preview])
+
+ useEffect(() => {
+ if (!drag) return
+ const up = () => finishDrag()
+ window.addEventListener('mouseup', up)
+ window.addEventListener('touchend', up)
+ return () => {
+ window.removeEventListener('mouseup', up)
+ window.removeEventListener('touchend', up)
+ }
+ }, [drag, finishDrag])
+
+ const setCam = (next: Camera) => setStoredCam(next)
+
+ useEffect(() => {
+ const el = containerRef.current
+ if (!el) return
+ let start = 0
+ const onStart = (e: Event) => {
+ e.preventDefault()
+ start = usePlanStore.getState().cam?.rotation ?? 0
+ }
+ const onChange = (e: Event) => {
+ e.preventDefault()
+ const g = e as Event & { rotation?: number; clientX?: number; clientY?: number }
+ const current = usePlanStore.getState().cam
+ if (!current || g.rotation === undefined) return
+ const rect = el.getBoundingClientRect()
+ const at = { x: (g.clientX ?? rect.width / 2 + rect.left) - rect.left, y: (g.clientY ?? rect.height / 2 + rect.top) - rect.top }
+ setStoredCam(anchorAt({ ...current, rotation: normRot(start + g.rotation) }, toWorld(current, at), at))
+ }
+ el.addEventListener('gesturestart', onStart)
+ el.addEventListener('gesturechange', onChange)
+ return () => {
+ el.removeEventListener('gesturestart', onStart)
+ el.removeEventListener('gesturechange', onChange)
+ }
+ }, [containerRef, setStoredCam])
+
+ const onWheel = (e: KonvaEventObject<WheelEvent>) => {
+ e.evt.preventDefault()
+ const pointer = stageRef.current?.getPointerPosition()
+ if (!pointer) return
+ const world = toWorld(cam, pointer)
+ if (e.evt.altKey) {
+ const d = Math.abs(e.evt.deltaY) > Math.abs(e.evt.deltaX) ? e.evt.deltaY : e.evt.deltaX
+ const rotation = normRot(rot + d * 0.15)
+ setCam(anchorAt({ ...cam, rotation }, world, pointer))
+ return
+ }
+ const intensity = e.evt.ctrlKey ? 0.01 : 0.0015
+ const scale = clampScale(cam.scale * Math.exp(-e.evt.deltaY * intensity))
+ setCam(anchorAt({ ...cam, scale }, world, pointer))
+ }
+
+ const onStageClick = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if (panRef.current) {
+ panRef.current = false
+ return
+ }
+ if (Date.now() < suppressClickUntil.current) return
+ if ('button' in e.evt && e.evt.button !== 0) return
+ setCtxMenu(null)
+ if (tool === 'zone') {
+ const raw = worldPointer()
+ const current = usePlanStore.getState().plan
+ if (!raw || !current) return
+ const pt = snapZonePoint(raw, current, cam.scale, zoneDraft.at(-1) ?? null, e.evt.shiftKey || shiftDown)
+ const first = zoneDraft[0]
+ if (first && zoneDraft.length >= 3 && Math.hypot(first.x - pt.x, first.y - pt.y) * cam.scale < 12) {
+ finishZone(zoneDraft)
+ return
+ }
+ setZoneDraft([...zoneDraft, pt])
+ return
+ }
+ if (tool === 'measure') {
+ const raw = worldPointer()
+ if (!raw) return
+ const from = activeMeasure?.points.at(-1) ?? null
+ const pt = e.evt.altKey ? raw : snapMeasure(raw, targets, cam.scale, from, e.evt.shiftKey || shiftDown).point
+ const chain = e.evt.metaKey || e.evt.ctrlKey
+ if (!activeMeasure) setActiveMeasure({ points: [pt] })
+ else if (chain) setActiveMeasure({ points: [...activeMeasure.points, pt] })
+ else {
+ setMeasures((m) => [...m, { points: [...activeMeasure.points, pt] }])
+ setActiveMeasure(null)
+ }
+ return
+ }
+ if (tool === 'select') {
+ if (e.target === stageRef.current) selectWall(null)
+ return
+ }
+ if (tool === 'building') {
+ const at = worldPointer()
+ if (!at || !buildingWallAt(at)) {
+ usePlanStore.getState().setGroup(null)
+ setTool('select')
+ }
+ return
+ }
+ if (tool === 'door' || tool === 'window') {
+ const raw = worldPointer()
+ const g = raw ? ghostAt(raw) : null
+ if (!g || !plan) return
+ const { id: _id, wallId: _w, offset, ...spec } = g.opening
+ void _id
+ void _w
+ const res = addOpening(plan, g.wallId, spec, offset)
+ if (res) {
+ commit(res.plan)
+ selectOpening(res.id)
+ }
+ return
+ }
+ const raw = worldPointer()
+ if (!raw || !plan) return
+ const snap = snapPoint(raw, plan.walls, cam.scale, draftStart, e.evt.shiftKey || shiftDown)
+ if (!draftStart) {
+ setDraftStart(snap.point)
+ return
+ }
+ if (snap.point.x === draftStart.x && snap.point.y === draftStart.y) {
+ setDraftStart(null)
+ return
+ }
+ addWall(draftStart, snap.point)
+ setDraftStart(snap.kind === 'endpoint' ? null : snap.point)
+ }
+
+ const applyLength = () => {
+ if (!lengthEdit || !plan) return
+ const meters = Number(lengthEdit.value.replace(',', '.').replace(/[^\d.]/g, ''))
+ setLengthEdit(null)
+ if (!(meters > 0)) return
+ commit(setWallLength(plan, lengthEdit.wallId, Math.round(meters * 1000)))
+ }
+
+ const activeMaterial = plan ? findMaterial(plan, activeMaterialId ?? undefined) : undefined
+ const draftThickness = activeMaterial?.thickness ?? 200
+ const site = plan ? sitePolygon(plan.site) : []
+ const cursorPoint = cursor?.point ?? null
+ const wallsCenter = useMemo(() => {
+ const walls = plan?.walls ?? []
+ if (walls.length === 0) return undefined
+ const sum = walls.reduce((acc, w) => ({ x: acc.x + w.a.x + w.b.x, y: acc.y + w.a.y + w.b.y }), { x: 0, y: 0 })
+ return { x: sum.x / (walls.length * 2), y: sum.y / (walls.length * 2) }
+ }, [plan?.walls])
+
+ const selectedWall = shown?.walls.find((w) => w.id === selectedWallId)
+ const movingIds = useMemo(() => {
+ if (!drag || !plan) return new Set<string>()
+ if (drag.kind !== 'move' && drag.kind !== 'a' && drag.kind !== 'b') return new Set<string>()
+ const refs = drag.kind === 'move' ? wallMoveGroup(plan, drag.wallId, false) : endpointGroup(plan, { wallId: drag.wallId, end: drag.kind }, false)
+ return new Set(refs.map((r) => r.wallId))
+ }, [drag, plan])
+
+ const buttonsAlong = (w: Wall) => {
+ const len = wallLength(w)
+ const half = 70 / cam.scale
+ const spans = (shown?.openings ?? []).filter((o) => o.wallId === w.id).map((o) => [o.offset - half, o.offset + o.width + half])
+ const free = (p: number) => spans.every(([s0, e0]) => p < s0 || p > e0)
+ const step = 10 / cam.scale
+ for (let d = 0; d <= len / 2; d += step) {
+ if (free(len / 2 + d)) return len / 2 + d
+ if (free(len / 2 - d)) return len / 2 - d
+ }
+ return len / 2
+ }
+ const targets = useMemo(() => (plan ? measureTargets(plan) : { points: [], segments: [] }), [plan])
+ const detection = useMemo(() => detectRooms(shown ?? NO_PLAN), [shown])
+ const findRoomAt = (p: Point): RoomFace | null => {
+ for (const b of detection.buildings) for (const r of b.rooms) if (pointInPolygon(p, r.clearPolygon)) return r
+ return null
+ }
+ const chainSum = activeMeasure && activeMeasure.points.length > 1 ? polylineLength(activeMeasure.points) : null
+ const roomEditItem = roomEdit && shown?.rooms?.find((r) => r.id === roomEdit.id)
+ const roomEditPos = roomEditItem ? toScreen(cam, roomEditItem) : null
+ const commitRoomName = () => {
+ if (!roomEdit || !plan) return
+ const name = roomEdit.value.trim()
+ const rooms = plan.rooms ?? []
+ setRoomEdit(null)
+ commit({
+ ...plan,
+ rooms: name ? rooms.map((r) => (r.id === roomEdit.id ? { ...r, name } : r)) : rooms.filter((r) => r.id !== roomEdit.id),
+ })
+ }
+ const addRoomLabel = (at: Point) => {
+ if (!plan) return
+ const rooms = plan.rooms ?? []
+ const used = new Set(rooms.map((r) => r.id))
+ let n = rooms.length + 1
+ while (used.has(`r${n}`)) n += 1
+ const id = `r${n}`
+ const name = t('canvas.defaultRoomName')
+ commit({ ...plan, rooms: [...rooms, { id, name, x: snapOffset(at.x), y: snapOffset(at.y) }] })
+ setRoomEdit({ id, value: name })
+ setCtxMenu(null)
+ }
+
+ const groupBounds = group && shown ? selBounds(shown, group) : null
+ const buildingWallAt = (at: Point): string | null => {
+ const b = detection.buildings.find((x) => pointInPolygon(at, x.footprint))
+ if (b?.walls[0]) return b.walls[0].id
+ return plan?.walls.find((w) => distanceToSegment(at, w.a, w.b) <= Math.max(w.thickness / 2, 6 / cam.scale))?.id ?? null
+ }
+ const groupPolygons = group && shown ? groupPolys(shown, detection.buildings, group) : []
+ const groupCorners = groupPolygons.flat()
+ const groupCenter = polysCenter(groupPolygons)
+ const guides = group && shown && drag?.moved && drag.kind === 'group-move' ? groupGuides(shown, detection.buildings, group) : []
+ const moveHandleAt = (() => {
+ if (!groupCorners.length) return null
+ const pts = groupCorners.map((c) => toScreen(cam, c))
+ const xs = pts.map((p) => p.x)
+ const maxY = Math.max(...pts.map((p) => p.y))
+ return toWorld(cam, { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: maxY + 30 })
+ })()
+ const selFurniture = shown?.furniture.find((f) => f.id === selectedFurnitureId)
+ const selOpening = shown?.openings.find((o) => o.id === selectedOpeningId)
+ const selOpeningWall = selOpening && shown?.walls.find((w) => w.id === selOpening.wallId)
+ const ghostWall = ghost && shown?.walls.find((w) => w.id === ghost.wallId)
+ const dimOpening = ghost?.opening ?? selOpening
+ const dimWall = ghost ? ghostWall : selOpeningWall
+
+ const editWall = lengthEdit && shown?.walls.find((w) => w.id === lengthEdit.wallId)
+ const editPos = editWall
+ ? (() => {
+ const p = labelAnchor(editWall.a, editWall.b, cam.scale, editWall.thickness / 2, wallsCenter)
+ const sp = toScreen(cam, p)
+ return { left: sp.x, top: sp.y }
+ })()
+ : null
+
+ return (
+ <div
+ ref={containerRef}
+ onDoubleClick={(e) => {
+ const stage = stageRef.current
+ if (tool !== 'select' || viewOnly || !locks.walls || !stage || !plan) return
+ stage.setPointersPositions(e.nativeEvent)
+ const at = stage.getRelativePointerPosition()
+ if (at && plan.walls.some((w) => distanceToSegment(at, w.a, w.b) <= Math.max(w.thickness / 2, 6 / cam.scale)))
+ showToast(t('canvas.moveHouseHint'))
+ }}
+ onDragOver={(e) => {
+ if (e.dataTransfer.types.includes('text/x-furniture')) {
+ e.preventDefault()
+ e.dataTransfer.dropEffect = 'copy'
+ }
+ }}
+ onDrop={(e) => {
+ const type = e.dataTransfer.getData('text/x-furniture')
+ const stage = stageRef.current
+ const current = usePlanStore.getState().plan
+ if (!type || !stage || !current) return
+ e.preventDefault()
+ if (layerLocks().furniture) {
+ lockedToast('furniture')
+ return
+ }
+ stage.setPointersPositions(e.nativeEvent)
+ const p = stage.getRelativePointerPosition()
+ if (!p) return
+ const res = addFurniture(current, { type, x: snapOffset(p.x), y: snapOffset(p.y), rotationDeg: 0 })
+ commit(res.plan)
+ setTool('select')
+ selectFurniture(res.id)
+ }}
+ className={`plan-canvas plan-canvas--${tool} ${drag?.moved ? 'plan-canvas--dragging' : ''}`}>
+ {ready && (
+ <Stage
+ ref={stageRef}
+ width={size.width}
+ height={size.height}
+ x={cam.x}
+ y={cam.y}
+ scaleX={cam.scale}
+ scaleY={cam.scale}
+ rotation={rot}
+ draggable={!drag && !pinchRef.current && !marquee}
+ dragDistance={4}
+ onDragStart={(e) => {
+ if (e.target === stageRef.current) panRef.current = true
+ }}
+ onDragMove={(e) => {
+ if (e.target === stageRef.current) setCam({ ...cam, x: e.target.x(), y: e.target.y() })
+ }}
+ onDragEnd={(e) => {
+ if (e.target === stageRef.current) setCam({ ...cam, x: e.target.x(), y: e.target.y() })
+ }}
+ onWheel={onWheel}
+ onMouseMove={onMouseMove}
+ onTouchMove={onTouchMove}
+ onTouchEnd={onTouchEnd}
+ onMouseDown={(e) => {
+ if (hoverCorner && (tool === 'select' || tool === 'building') && !viewOnly && e.target === stageRef.current && e.evt.button === 0) {
+ const corner = hoverCorner
+ const altPivot = groupCorners.reduce((m, c) =>
+ Math.hypot(c.x - corner.x, c.y - corner.y) > Math.hypot(m.x - corner.x, m.y - corner.y) ? c : m,
+ )
+ stageRef.current?.stopDrag()
+ startDrag('group-rot', '')
+ setDrag((d) => (d ? { ...d, pivot: groupCenter ?? undefined, altPivot } : d))
+ setHoverCorner(null)
+ return
+ }
+ if (tool === 'building' && !viewOnly && !aligning && e.evt.button === 0 && plan) {
+ const at = worldPointer()
+ const wallId = at ? buildingWallAt(at) : null
+ if (!wallId) return
+ const st = usePlanStore.getState()
+ if (!selHas(st.group, 'walls', wallId)) st.setGroup(buildingSel(plan, wallId))
+ stageRef.current?.stopDrag()
+ startDrag('group-move', '')
+ return
+ }
+ if (tool === 'select' && !viewOnly && !aligning && e.target === stageRef.current && e.evt.button === 0 && layers.walls && locks.walls) {
+ const at = worldPointer()
+ if (at && plan?.walls.some((w) => distanceToSegment(at, w.a, w.b) <= Math.max(w.thickness / 2, 6 / cam.scale))) lockedToast('walls')
+ }
+ if (tool !== 'select' || viewOnly || aligning || e.target !== stageRef.current || e.evt.button !== 0 || !e.evt.shiftKey) return
+ const sp = screenPointer()
+ if (!sp) return
+ stageRef.current?.stopDrag()
+ setMarquee({ x0: sp.x, y0: sp.y, x1: sp.x, y1: sp.y, add: true })
+ }}
+ onMouseUp={() => {
+ finishMarquee()
+ finishDrag()
+ }}
+ onMouseLeave={() => {
+ setHoverRoom(null)
+ if (!drag) setCursor(null)
+ onCursor?.(null, cam.scale)
+ }}
+ onClick={onStageClick}
+ onTap={onStageClick}
+ onDblClick={() => {
+ setDraftStart(null)
+ if (tool !== 'select' || viewOnly) return
+ const at = worldPointer()
+ const hitWall = at && plan?.walls.find((w) => distanceToSegment(at, w.a, w.b) <= Math.max(w.thickness / 2, 6 / cam.scale))
+ if (hitWall && plan && locks.walls) return
+ if (hitWall && plan) {
+ usePlanStore.getState().setGroup(buildingSel(plan, hitWall.id))
+ return
+ }
+ const face = at ? findRoomAt(at) : null
+ const id = face?.labelIds[0]
+ const r = id ? plan?.rooms?.find((x) => x.id === id) : null
+ if (r) setRoomEdit({ id: r.id, value: r.name })
+ else if (face && at) addRoomLabel(at)
+ }}
+ onContextMenu={(e) => {
+ e.evt.preventDefault()
+ setDraftStart(null)
+ if (tool !== 'select' || viewOnly) return
+ const at = worldPointer()
+ const sp = screenPointer()
+ if (!at || !sp) return
+ const inside = detection.buildings.some((b) => b.rooms.some((r) => pointInPolygon(at, r.clearPolygon)))
+ setCtxMenu(inside ? { left: sp.x, top: sp.y, at } : null)
+ }}
+ >
+ <Layer listening={false}>
+ {!underlay.on && (
+ <Line
+ points={site.flatMap((p) => [p.x, p.y])}
+ closed
+ fill={canvasTheme.site}
+ shadowColor="rgba(40,30,20,0.12)"
+ shadowBlur={24}
+ shadowOffsetY={4}
+ shadowForStrokeEnabled={false}
+ />
+ )}
+ {Underlay && plan && (
+ <Underlay
+ plan={plan}
+ view={{ x: cam.x, y: cam.y, scale: cam.scale, width: size.width, height: size.height, rotationDeg: rot }}
+ opacity={underlay.opacity}
+ geo={align.shown}
+ imagery={align.imagery}
+ />
+ )}
+ <Grid cam={cam} width={size.width} height={size.height} opacity={underlay.on ? 0.45 : 1} />
+ <Line
+ points={site.flatMap((p) => [p.x, p.y])}
+ closed
+ stroke={underlay.on ? '#ffffff' : canvasTheme.siteStroke}
+ strokeWidth={(underlay.on ? 2.5 : 1.5) / cam.scale}
+ dash={[10 / cam.scale, 6 / cam.scale]}
+ />
+ </Layer>
+ {shown && (
+ <Layer opacity={baseOpacity}>
+ {layers.zones && (shown.site.zones ?? []).map((z) => (
+ <ZoneShape
+ key={z.id}
+ zone={z}
+ scale={cam.scale}
+ viewRot={rot}
+ listening={tool === 'select' && !drag && !aligning && !viewOnly && !locks.zones}
+ showDims={z.id === hoverZone || z.id === selectedZoneId}
+ selected={z.id === selectedZoneId && !viewOnly}
+ onSelect={selectZone}
+ onHover={setHoverZone}
+ onVertexDown={(i) => startDrag('zone-vertex', '', undefined, undefined, undefined, z.id, i)}
+ onSideDblClick={(i, at) => {
+ const current = usePlanStore.getState().plan
+ const zz = current?.site.zones?.find((x) => x.id === z.id)
+ if (!current || !zz) return
+ const p = snapZonePoint(at, current, cam.scale, null, false)
+ const polygon = [...zz.polygon.slice(0, i + 1), p, ...zz.polygon.slice(i + 1)]
+ commit(updateZone(current, z.id, { polygon }))
+ }}
+ worldPointer={worldPointer}
+ />
+ ))}
+ {layers.furniture && shown.furniture.map((f) => (
+ <FurnitureSymbol2D
+ key={f.id}
+ item={f}
+ selected={f.id === selectedFurnitureId || selHas(group, 'furniture', f.id)}
+ listening={tool === 'select' && !drag && !aligning && !viewOnly && !locks.furniture}
+ onMouseDown={(e: KonvaEventObject<MouseEvent>) => {
+ if (e.evt.button !== 0) return
+ e.cancelBubble = true
+ if (groupPick('furniture', f.id, e.evt.shiftKey)) return
+ selectFurniture(f.id)
+ startDrag('fur-move', '', undefined, f.id)
+ }}
+ onClick={(e: KonvaEventObject<MouseEvent>) => {
+ e.cancelBubble = true
+ }}
+ onMouseEnter={(e: KonvaEventObject<MouseEvent>) => {
+ const st = e.target.getStage()
+ if (st) st.container().style.cursor = 'move'
+ }}
+ onMouseLeave={(e: KonvaEventObject<MouseEvent>) => {
+ const st = e.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ />
+ ))}
+ {layers.walls && shown.walls.map((w) => (
+ <WallOutline key={`o-${w.id}`} wall={w} scale={cam.scale} selected={w.id === selectedWallId || selHas(group, 'walls', w.id)} />
+ ))}
+ {layers.walls && shown.walls.map((w) => (
+ <WallFill
+ key={`f-${w.id}`}
+ wall={w}
+ color={wallColor(shown, w)}
+ scale={cam.scale}
+ listening={tool === 'select' && !drag && !aligning && !viewOnly && !locks.walls}
+ selected={w.id === selectedWallId || selHas(group, 'walls', w.id)}
+ onSelect={() => undefined}
+ onDragStart={(id, e) => {
+ if (groupPick('walls', id, e.evt.shiftKey)) return
+ selectWall(id)
+ startDrag('move', id)
+ }}
+ onHover={setHoverWall}
+ />
+ ))}
+ {layers.walls && shown.openings.map((o) => {
+ const wall = shown.walls.find((w) => w.id === o.wallId)
+ return wall ? (
+ <OpeningShape
+ key={o.id}
+ wall={wall}
+ opening={o}
+ scale={cam.scale}
+ selected={o.id === selectedOpeningId || selHas(group, 'openings', o.id)}
+ listening={tool === 'select' && !drag && !aligning && !viewOnly && !locks.walls}
+ onPointerDown={(id, e) => {
+ if (groupPick('openings', id, e.evt.shiftKey)) return
+ selectOpening(id)
+ startDrag('op-move', wall.id, id)
+ }}
+ />
+ ) : null
+ })}
+ {ghostWall && ghost && (
+ <OpeningShape wall={ghostWall} opening={ghost.opening} scale={cam.scale} ghost selected />
+ )}
+ {shown.walls.map((w) =>
+ lengthEdit?.wallId === w.id ||
+ !(showDims || w.id === selectedWallId || w.id === hoverWall || (!!drag && movingIds.has(w.id))) ? null : (
+ <LengthLabel
+ key={`l-${w.id}`}
+ a={w.a}
+ b={w.b}
+ scale={cam.scale}
+ gap={w.thickness / 2}
+ accent={w.id === selectedWallId || (!!drag && movingIds.has(w.id))}
+ away={wallsCenter}
+ viewRot={rot}
+ onClick={tool === 'select' && !drag && !viewOnly && !locks.walls ? () => selectWall(w.id) : undefined}
+ onDblClick={
+ tool === 'select' && !drag && !viewOnly && !locks.walls
+ ? () => {
+ selectWall(w.id)
+ setLengthEdit({ wallId: w.id, value: formatMeters(wallLength(w), 3) })
+ }
+ : undefined
+ }
+ />
+ ),
+ )}
+ {hoverRoom && !drag && !viewOnly && tool === 'select' && (
+ <RoomHover room={hoverRoom} scale={cam.scale} viewRot={rot} />
+ )}
+ {tool === 'select' && !viewOnly && !locks.walls && selectedWall && (
+ <Handles
+ wall={selectedWall}
+ scale={cam.scale}
+ viewRot={rot}
+ buttonsAt={buttonsAlong(selectedWall)}
+ onStart={(kind) => startDrag(kind, selectedWall.id)}
+ onAdd={(type) => {
+ if (!plan || drag) return
+ const spec = OPENING_PRESETS[type === 'window' ? 'window' : doorPreset]
+ const { label: _l, ...rest } = spec
+ void _l
+ const at = fitOffsetClear(plan, selectedWall.id, spec.width, Math.round((wallLength(selectedWall) - spec.width) / 2))
+ const res = at === null ? null : addOpening(plan, selectedWall.id, rest, at)
+ if (res) {
+ commit(res.plan)
+ selectOpening(res.id)
+ } else showToast(t('canvas.noRoomOnWall'))
+ }}
+ />
+ )}
+ {dimWall && dimOpening && shown && (
+ <Dimensions
+ wall={dimWall}
+ scale={cam.scale}
+ toward={wallsCenter}
+ viewRot={rot}
+ spans={(() => {
+ const g = openingGaps(shown, dimWall.id, dimOpening.offset, dimOpening.width, dimOpening.id)
+ return g ? [g.before, [dimOpening.offset, dimOpening.offset + dimOpening.width], g.after] : []
+ })()}
+ />
+ )}
+ {tool === 'select' && !viewOnly && !locks.furniture && selFurniture && (
+ <FurnitureRotateHandle
+ x={selFurniture.x}
+ y={selFurniture.y}
+ rotationDeg={selFurniture.rotationDeg}
+ depth={resolveFurniture(selFurniture).d}
+ scale={cam.scale}
+ onStart={() => startDrag('fur-rot', '', undefined, selFurniture.id)}
+ />
+ )}
+ {tool === 'select' && !viewOnly && !locks.walls && selOpening && selOpeningWall && (
+ <OpeningHandles
+ wall={selOpeningWall}
+ opening={selOpening}
+ scale={cam.scale}
+ onStart={(edge) => startDrag(edge, selOpeningWall.id, selOpening.id)}
+ />
+ )}
+ {(tool === 'select' || tool === 'building') && !viewOnly && groupBounds && (
+ <GroupOverlay
+ bounds={groupBounds}
+ scale={cam.scale}
+ onRotateStart={drag ? undefined : () => startDrag('group-rot', '')}
+ />
+ )}
+ {(tool === 'select' || tool === 'building') && !viewOnly && group && hoverCorner && groupCenter && !drag && (
+ <CornerHint corner={hoverCorner} center={groupCenter} scale={cam.scale} />
+ )}
+ {(tool === 'select' || tool === 'building') && !viewOnly && group && moveHandleAt && (!drag || drag.kind === 'group-move') && (
+ <MoveHandle at={moveHandleAt} scale={cam.scale} viewRot={rot} onStart={() => startDrag('group-move', '')} />
+ )}
+ {guides.length > 0 && <GuideLines guides={guides} scale={cam.scale} />}
+ </Layer>
+ )}
+ {shown && (
+ <HeatingLayer plan={shown} scale={cam.scale} viewRot={rot} worldPointer={worldPointer} interactive={!viewOnly && !aligning && !drag && !locks.heating} />
+ )}
+ {shown && (
+ <SewerLayer plan={shown} scale={cam.scale} viewRot={rot} worldPointer={worldPointer} interactive={!viewOnly && !aligning && !drag && !locks.sewer} />
+ )}
+ {shown && (
+ <WaterLayer plan={shown} scale={cam.scale} viewRot={rot} worldPointer={worldPointer} interactive={!viewOnly && !aligning && !drag && !locks.water} />
+ )}
+ {shown && (
+ <ElectricLayer plan={shown} scale={cam.scale} viewRot={rot} worldPointer={worldPointer} interactive={!viewOnly && !aligning && !drag && !locks.electric} />
+ )}
+ <Layer listening={false}>
+ {tool === 'zone' && zoneDraft.length > 0 && (
+ <>
+ <Line
+ points={[...zoneDraft, ...(zoneCursor ? [zoneCursor] : [])].flatMap((p) => [p.x, p.y])}
+ stroke={canvasTheme.accent}
+ strokeWidth={1.8 / cam.scale}
+ fill="rgba(242, 107, 29, 0.06)"
+ closed={zoneDraft.length >= 2}
+ dash={[6 / cam.scale, 4 / cam.scale]}
+ />
+ {zoneDraft.map((p, i) => (
+ <Circle key={i} x={p.x} y={p.y} radius={(i === 0 ? 6 : 3.5) / cam.scale} fill={i === 0 ? '#ffffff' : canvasTheme.accent} stroke={canvasTheme.accent} strokeWidth={1.5 / cam.scale} />
+ ))}
+ {zoneCursor && (
+ <LengthLabel a={zoneDraft[zoneDraft.length - 1]} b={zoneCursor} scale={cam.scale} gap={0} accent viewRot={rot} />
+ )}
+ </>
+ )}
+ {tool === 'zone' && zoneCursor && (
+ <Circle x={zoneCursor.x} y={zoneCursor.y} radius={4 / cam.scale} fill={canvasTheme.accent} />
+ )}
+ {tool === 'measure' && (
+ <MeasureLayer measures={measures} active={activeMeasure} cursor={measureCursor} scale={cam.scale} viewRot={rot} />
+ )}
+ {tool !== 'measure' && measures.length > 0 && (
+ <MeasureLayer measures={measures} active={null} cursor={null} scale={cam.scale} viewRot={rot} />
+ )}
+ {tool === 'wall' && draftStart && cursorPoint && (
+ <>
+ <Line
+ points={[draftStart.x, draftStart.y, cursorPoint.x, cursorPoint.y]}
+ stroke={materialColor(activeMaterial)}
+ opacity={0.6}
+ strokeWidth={draftThickness}
+ lineCap="square"
+ />
+ <Line
+ points={[draftStart.x, draftStart.y, cursorPoint.x, cursorPoint.y]}
+ stroke={canvasTheme.accent}
+ strokeWidth={1.5 / cam.scale}
+ dash={[6 / cam.scale, 4 / cam.scale]}
+ />
+ <LengthLabel a={draftStart} b={cursorPoint} scale={cam.scale} gap={draftThickness / 2} accent viewRot={rot} />
+ </>
+ )}
+ {(tool === 'wall' || (drag?.moved && drag.kind !== 'move' && drag.kind !== 'group-move' && drag.kind !== 'group-rot')) && cursorPoint && (
+ <Circle
+ x={cursorPoint.x}
+ y={cursorPoint.y}
+ radius={(cursor?.kind === 'endpoint' ? 9 : 4) / cam.scale}
+ fill={cursor?.kind === 'endpoint' ? canvasTheme.accentSoft : canvasTheme.accent}
+ stroke={canvasTheme.accent}
+ strokeWidth={1.5 / cam.scale}
+ />
+ )}
+ </Layer>
+ {aligning && underlayMods && (
+ <Layer>
+ <underlayMods.Overlay
+ align={align}
+ view={{ x: cam.x, y: cam.y, scale: cam.scale, width: size.width, height: size.height, rotationDeg: rot }}
+ />
+ </Layer>
+ )}
+ {rot === 0 && (
+ <Layer
+ listening={false}
+ x={-cam.x / cam.scale}
+ y={-cam.y / cam.scale}
+ scaleX={1 / cam.scale}
+ scaleY={1 / cam.scale}
+ >
+ <Rulers cam={cam} width={size.width} height={size.height} cursor={cursorPoint} top={rulerTop()} />
+ </Layer>
+ )}
+ </Stage>
+ )}
+ {aligning && underlayMods && (
+ <div className="align-controls card">
+ <div className="align-controls__head">
+ <strong>{t('canvas.alignTitle')}</strong>
+ <span className="muted">{t('canvas.alignHint')}</span>
+ </div>
+ <underlayMods.Controls align={align} />
+ </div>
+ )}
+ {ready && plan && (
+ <ViewControls
+ rotation={rot}
+ northUp={plan.site.geo ? normRot(-90 - northAngle(plan.site.geo.rotationDeg)) : null}
+ onRotate={(rotation, fit) => {
+ if (fit) {
+ setCam(fitCamera(sitePolygon(plan.site), size.width, size.height, fitPadding(containerRef.current), normRot(rotation)))
+ return
+ }
+ const center = { x: size.width / 2, y: size.height / 2 }
+ setCam(anchorAt({ ...cam, rotation: normRot(rotation) }, toWorld(cam, center), center))
+ }}
+ />
+ )}
+ {marquee && (
+ <div
+ className="marquee"
+ style={{
+ left: Math.min(marquee.x0, marquee.x1),
+ top: Math.min(marquee.y0, marquee.y1),
+ width: Math.abs(marquee.x1 - marquee.x0),
+ height: Math.abs(marquee.y1 - marquee.y0),
+ }}
+ />
+ )}
+ {guides.map((g, i) => {
+ const at = toScreen(cam, { x: (g.a.x + g.b.x) / 2, y: (g.a.y + g.b.y) / 2 })
+ return (
+ <div key={i} className="group-delta group-delta--guide" style={{ left: at.x, top: at.y }}>
+ {formatMeters(g.d)} {t('units.m')}
+ </div>
+ )
+ })}
+ {groupInfo && drag?.moved && (
+ <div className="group-delta" style={{ left: groupInfo.at.x, top: groupInfo.at.y - 14 }}>
+ {groupInfo.text}
+ </div>
+ )}
+ {ctxMenu && (
+ <div className="ctx-menu card" style={{ left: ctxMenu.left, top: ctxMenu.top }}>
+ <button className="menu__item" onClick={() => addRoomLabel(ctxMenu.at)}>
+ {t('canvas.labelRoom')}
+ </button>
+ </div>
+ )}
+ {roomEdit && roomEditPos && (
+ <form
+ className="length-edit"
+ style={{ left: roomEditPos.x, top: roomEditPos.y }}
+ onSubmit={(e) => {
+ e.preventDefault()
+ commitRoomName()
+ }}
+ >
+ <input
+ autoFocus
+ className="length-edit__input room-edit__input"
+ value={roomEdit.value}
+ onChange={(e) => setRoomEdit({ ...roomEdit, value: e.target.value })}
+ onFocus={(e) => e.target.select()}
+ onBlur={commitRoomName}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation()
+ setRoomEdit(null)
+ }
+ }}
+ />
+ </form>
+ )}
+ {tool === 'measure' && (
+ <div className="measure-hint card">
+ {chainSum !== null
+ ? t('canvas.measureSum', { sum: formatMeters(chainSum) })
+ : t('canvas.measureHint')}
+ </div>
+ )}
+ {lengthEdit && editPos && (
+ <form
+ className="length-edit"
+ style={{ left: editPos.left, top: editPos.top }}
+ onSubmit={(e) => {
+ e.preventDefault()
+ applyLength()
+ }}
+ >
+ <input
+ autoFocus
+ className="length-edit__input"
+ value={lengthEdit.value}
+ onChange={(e) => setLengthEdit({ ...lengthEdit, value: e.target.value })}
+ onFocus={(e) => e.target.select()}
+ onBlur={applyLength}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation()
+ setLengthEdit(null)
+ }
+ }}
+ />
+ <span className="length-edit__unit">{t('units.m')}</span>
+ </form>
+ )}
+ </div>
+ )
+}
diff --git a/src/canvas/RoomLabels.tsx b/src/canvas/RoomLabels.tsx
new file mode 100644
index 0000000..ddcc395
--- /dev/null
+++ b/src/canvas/RoomLabels.tsx
@@ -0,0 +1,58 @@
+import { Group, Line, Rect, Text } from 'react-konva'
+import { formatNumber, type Point } from '../model'
+import { t } from '../i18n'
+import type { RoomFace } from '../stats/rooms'
+import { canvasTheme } from './theme'
+
+function centroid(poly: Point[]): Point {
+ let a = 0
+ let cx = 0
+ let cy = 0
+ for (let i = 0; i < poly.length; i += 1) {
+ const p = poly[i]
+ const q = poly[(i + 1) % poly.length]
+ const k = p.x * q.y - q.x * p.y
+ a += k
+ cx += (p.x + q.x) * k
+ cy += (p.y + q.y) * k
+ }
+ if (Math.abs(a) < 1e-9) {
+ const n = poly.length || 1
+ return { x: poly.reduce((s, p) => s + p.x, 0) / n, y: poly.reduce((s, p) => s + p.y, 0) / n }
+ }
+ return { x: cx / (3 * a), y: cy / (3 * a) }
+}
+
+export function RoomHover({ room, scale, viewRot }: { room: RoomFace; scale: number; viewRot: number }) {
+ const px = 1 / scale
+ const c = centroid(room.clearPolygon)
+ const text = `${room.name} · ${formatNumber(room.areaM2, 1)} ${t('common:units.m2')}`
+ const w = text.length * 7 + 16
+ return (
+ <Group listening={false}>
+ <Line
+ points={room.clearPolygon.flatMap((p) => [p.x, p.y])}
+ closed
+ fill="rgba(242, 107, 29, 0.08)"
+ stroke="rgba(242, 107, 29, 0.35)"
+ strokeWidth={1 * px}
+ />
+ <Group x={c.x} y={c.y} rotation={-viewRot} scaleX={px} scaleY={px}>
+ <Rect x={-w / 2} y={-11} width={w} height={22} cornerRadius={6} fill="rgba(255,255,255,0.95)" shadowColor="rgba(0,0,0,0.12)" shadowBlur={4} />
+ <Text
+ x={-w / 2}
+ y={-11}
+ width={w}
+ height={22}
+ align="center"
+ verticalAlign="middle"
+ text={text}
+ fontSize={12}
+ fontStyle="600"
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.ink}
+ />
+ </Group>
+ </Group>
+ )
+}
diff --git a/src/canvas/Rulers.tsx b/src/canvas/Rulers.tsx
new file mode 100644
index 0000000..9da1fce
--- /dev/null
+++ b/src/canvas/Rulers.tsx
@@ -0,0 +1,101 @@
+import { Group, Rect, Shape, Text } from 'react-konva'
+import { formatMeters } from '../model'
+import { t } from '../i18n'
+import { labelStep, visibleRect, type Camera } from './camera'
+import { canvasTheme, RULER_SIZE } from './theme'
+
+type Props = { cam: Camera; width: number; height: number; cursor: { x: number; y: number } | null; top?: number }
+
+const meters = (mm: number) => formatMeters(mm, 1)
+
+export function Rulers({ cam, width, height, cursor, top = 0 }: Props) {
+ const T = top
+ const rect = visibleRect(cam, width, height)
+ const step = labelStep(cam.scale)
+ const sub = step / 5
+ const toX = (mm: number) => mm * cam.scale + cam.x
+ const toY = (mm: number) => mm * cam.scale + cam.y
+
+ const xs: number[] = []
+ for (let v = Math.floor(rect.minX / step) * step; v <= rect.maxX; v += step) xs.push(v)
+ const ys: number[] = []
+ for (let v = Math.floor(rect.minY / step) * step; v <= rect.maxY; v += step) ys.push(v)
+
+ return (
+ <Group listening={false}>
+ <Rect x={0} y={T} width={width} height={RULER_SIZE} fill={canvasTheme.ruler} />
+ <Rect x={0} y={T} width={RULER_SIZE} height={height - T} fill={canvasTheme.ruler} />
+ <Shape
+ sceneFunc={(ctx) => {
+ const c = ctx._context
+ c.beginPath()
+ for (let v = Math.floor(rect.minX / sub) * sub; v <= rect.maxX; v += sub) {
+ const x = Math.round(toX(v)) + 0.5
+ const len = Math.abs(v % step) < 1e-6 ? RULER_SIZE * 0.55 : RULER_SIZE * 0.22
+ c.moveTo(x, T + RULER_SIZE)
+ c.lineTo(x, T + RULER_SIZE - len)
+ }
+ for (let v = Math.floor(rect.minY / sub) * sub; v <= rect.maxY; v += sub) {
+ const y = Math.round(toY(v)) + 0.5
+ if (y < T + RULER_SIZE) continue
+ const len = Math.abs(v % step) < 1e-6 ? RULER_SIZE * 0.55 : RULER_SIZE * 0.22
+ c.moveTo(RULER_SIZE, y)
+ c.lineTo(RULER_SIZE - len, y)
+ }
+ c.moveTo(0, T + RULER_SIZE + 0.5)
+ c.lineTo(width, T + RULER_SIZE + 0.5)
+ c.moveTo(RULER_SIZE + 0.5, T)
+ c.lineTo(RULER_SIZE + 0.5, height)
+ c.strokeStyle = canvasTheme.inkMuted
+ c.lineWidth = 1
+ c.stroke()
+ if (cursor) {
+ c.beginPath()
+ c.moveTo(toX(cursor.x), T)
+ c.lineTo(toX(cursor.x), T + RULER_SIZE)
+ c.moveTo(0, toY(cursor.y))
+ c.lineTo(RULER_SIZE, toY(cursor.y))
+ c.strokeStyle = canvasTheme.accent
+ c.stroke()
+ }
+ }}
+ />
+ {xs.map((v) => (
+ <Text
+ key={`x${v}`}
+ x={toX(v) + 3}
+ y={T + 3}
+ text={meters(v)}
+ fontSize={10}
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.ink}
+ />
+ ))}
+ {ys.filter((v) => toY(v) - 3 > T + RULER_SIZE + 20).map((v) => (
+ <Text
+ key={`y${v}`}
+ x={3}
+ y={toY(v) - 3}
+ rotation={-90}
+ text={meters(v)}
+ fontSize={10}
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.ink}
+ />
+ ))}
+ <Rect x={0} y={T} width={RULER_SIZE} height={RULER_SIZE} fill={canvasTheme.ruler} />
+ <Text
+ x={0}
+ y={T}
+ width={RULER_SIZE}
+ height={RULER_SIZE}
+ align="center"
+ verticalAlign="middle"
+ text={t('common:units.m')}
+ fontSize={10}
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.inkMuted}
+ />
+ </Group>
+ )
+}
diff --git a/src/canvas/ViewControls.tsx b/src/canvas/ViewControls.tsx
new file mode 100644
index 0000000..6ab7fb6
--- /dev/null
+++ b/src/canvas/ViewControls.tsx
@@ -0,0 +1,54 @@
+import { useTranslation } from 'react-i18next'
+import { CanvasToolbar, ToolbarSeparator } from '../ui/CanvasToolbar'
+import { IconButton } from '../ui/IconButton'
+import { Segmented } from '../ui/Segmented'
+
+type Props = {
+ rotation: number
+ northUp: number | null
+ onRotate: (deg: number, fit?: boolean) => void
+}
+
+const near = (a: number, b: number) => Math.abs(((a - b + 540) % 360) - 180) < 0.5
+
+export function ViewControls({ rotation, northUp, onRotate }: Props) {
+ const { t } = useTranslation('common')
+ const mode = near(rotation, 0) ? 'plan' : northUp !== null && near(rotation, northUp) ? 'north' : 'free'
+ const north = northUp !== null ? -90 - northUp + rotation : null
+ return (
+ <CanvasToolbar placement="bottom-right" className="view-controls">
+ <Segmented
+ size="sm"
+ value={mode}
+ options={[
+ { value: 'plan', label: t('canvas.planUp') },
+ ...(northUp !== null ? [{ value: 'north', label: t('canvas.northUp') }] : []),
+ ...(mode === 'free' ? [{ value: 'free', label: `${Math.round(rotation)}°` }] : []),
+ ]}
+ onChange={(v) => {
+ if (v === 'plan') onRotate(0, true)
+ else if (v === 'north' && northUp !== null) onRotate(northUp, true)
+ }}
+ />
+ <ToolbarSeparator />
+ <IconButton label={t('canvas.rotateCcw')} size="sm" onClick={() => onRotate(rotation - 15)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <path d="M4 9a8 8 0 1 1 1 7M4 4v5h5" />
+ </svg>
+ </IconButton>
+ <IconButton label={t('canvas.rotateCw')} size="sm" onClick={() => onRotate(rotation + 15)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <path d="M20 9a8 8 0 1 0-1 7M20 4v5h-5" />
+ </svg>
+ </IconButton>
+ {north !== null && (
+ <IconButton label={t('canvas.compass')} size="sm" className="compass" onClick={() => onRotate(0, true)}>
+ <svg viewBox="0 0 24 24" aria-hidden style={{ transform: `rotate(${north + 90}deg)` }}>
+ <path d="M12 3l4 9h-8z" fill="var(--accent)" />
+ <path d="M12 21l-4-9h8z" fill="var(--line-strong)" />
+ </svg>
+ </IconButton>
+ )}
+ </CanvasToolbar>
+ )
+}
diff --git a/src/canvas/WallShape.tsx b/src/canvas/WallShape.tsx
new file mode 100644
index 0000000..aaecaf9
--- /dev/null
+++ b/src/canvas/WallShape.tsx
@@ -0,0 +1,72 @@
+import { Line } from 'react-konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import type { Wall } from '../model'
+import { canvasTheme } from './theme'
+
+const points = (w: Wall) => [w.a.x, w.a.y, w.b.x, w.b.y]
+
+export function WallOutline({ wall, scale, selected }: { wall: Wall; scale: number; selected: boolean }) {
+ return (
+ <Line
+ points={points(wall)}
+ stroke={selected ? canvasTheme.accent : canvasTheme.ink}
+ strokeWidth={wall.thickness + (selected ? 6 : 2.5) / scale}
+ lineCap="square"
+ listening={false}
+ />
+ )
+}
+
+type FillProps = {
+ wall: Wall
+ color: string
+ scale: number
+ listening: boolean
+ selected: boolean
+ onSelect: (id: string) => void
+ onDragStart: (id: string, e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+ onHover?: (id: string | null) => void
+}
+
+const setCursor = (e: KonvaEventObject<MouseEvent>, value: string) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+}
+
+export function WallFill({ wall, color, scale, listening, selected, onSelect, onDragStart, onHover }: FillProps) {
+ return (
+ <Line
+ points={points(wall)}
+ stroke={color}
+ strokeWidth={wall.thickness}
+ lineCap="square"
+ hitStrokeWidth={Math.max(wall.thickness, 12 / scale)}
+ listening={listening}
+ onMouseDown={(e) => {
+ if (e.evt.button !== 0) return
+ e.cancelBubble = true
+ onSelect(wall.id)
+ onDragStart(wall.id, e)
+ }}
+ onTouchStart={(e) => {
+ e.cancelBubble = true
+ onSelect(wall.id)
+ onDragStart(wall.id, e)
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ }}
+ onTap={(e) => {
+ e.cancelBubble = true
+ }}
+ onMouseEnter={(e) => {
+ setCursor(e, selected ? 'move' : 'pointer')
+ onHover?.(wall.id)
+ }}
+ onMouseLeave={(e) => {
+ setCursor(e, '')
+ onHover?.(null)
+ }}
+ />
+ )
+}
diff --git a/src/canvas/ZoneShape.tsx b/src/canvas/ZoneShape.tsx
new file mode 100644
index 0000000..d1dbcb7
--- /dev/null
+++ b/src/canvas/ZoneShape.tsx
@@ -0,0 +1,199 @@
+import { Circle, Group, Line, Rect, Text } from 'react-konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { distance, formatNumber, polygonAreaMm2, polygonCentroid, sitePolygon, snapToGrid, type Plan, type Point, type Zone } from '../model'
+import { t } from '../i18n'
+import { LengthLabel } from './LengthLabel'
+import { GRID_SNAP, snapAngle } from './snap'
+import { canvasTheme } from './theme'
+
+let gravel: HTMLCanvasElement | null = null
+function gravelPattern() {
+ if (gravel || typeof document === 'undefined') return gravel
+ const c = document.createElement('canvas')
+ c.width = 12
+ c.height = 12
+ const ctx = c.getContext('2d')
+ if (ctx) {
+ ctx.fillStyle = '#ece9e3'
+ ctx.fillRect(0, 0, 12, 12)
+ ctx.fillStyle = '#b9b3a8'
+ for (const [x, y] of [
+ [2, 2],
+ [8, 4],
+ [5, 9],
+ [10, 10],
+ ]) {
+ ctx.beginPath()
+ ctx.arc(x, y, 0.9, 0, Math.PI * 2)
+ ctx.fill()
+ }
+ }
+ gravel = c
+ return c
+}
+
+const FILLS: Record<Zone['kind'], string> = {
+ fill: '#ece9e3',
+ lawn: '#e2efd9',
+ paving: '#e8e2d8',
+ other: '#eceef1',
+}
+
+type Props = {
+ zone: Zone
+ scale: number
+ viewRot: number
+ listening: boolean
+ showDims: boolean
+ selected: boolean
+ onSelect: (id: string) => void
+ onHover: (id: string | null) => void
+ onVertexDown: (index: number) => void
+ onSideDblClick: (index: number, at: Point) => void
+ worldPointer: () => Point | null
+}
+
+export function ZoneShape({ zone, scale, viewRot, listening, showDims, selected, onSelect, onHover, onVertexDown, onSideDblClick, worldPointer }: Props) {
+ const px = 1 / scale
+ const pts = zone.polygon
+ const flat = pts.flatMap((p) => [p.x, p.y])
+ const pattern = zone.kind === 'fill' ? gravelPattern() : null
+ const c = polygonCentroid(pts)
+ const area = polygonAreaMm2(pts) / 1e6
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const st = e.target.getStage()
+ if (st) st.container().style.cursor = value
+ }
+ return (
+ <Group>
+ <Line
+ points={flat}
+ closed
+ fill={pattern ? undefined : FILLS[zone.kind]}
+ fillPatternImage={(pattern ?? undefined) as HTMLImageElement | undefined}
+ fillPatternScale={pattern ? { x: px, y: px } : undefined}
+ stroke={selected ? canvasTheme.accent : zone.locked ? '#6f6a60' : '#8f8a80'}
+ strokeWidth={(selected ? 2 : zone.locked ? 1.4 : 1) * px}
+ dash={selected || zone.locked ? undefined : [6 * px, 3 * px]}
+ listening={listening}
+ onMouseEnter={(e) => {
+ cursor('pointer')(e)
+ onHover(zone.id)
+ }}
+ onMouseLeave={(e) => {
+ cursor('')(e)
+ onHover(null)
+ }}
+ onMouseDown={(e) => {
+ if (e.evt.button !== 0) return
+ e.cancelBubble = true
+ onSelect(zone.id)
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ }}
+ onDblClick={(e) => {
+ e.cancelBubble = true
+ if (zone.locked) return
+ const p = worldPointer()
+ if (!p) return
+ let best = -1
+ let bestD = Infinity
+ pts.forEach((a, i) => {
+ const b = pts[(i + 1) % pts.length]
+ const d = distToSeg(p, a, b)
+ if (d < bestD) {
+ bestD = d
+ best = i
+ }
+ })
+ if (best >= 0 && bestD < 14 / scale) onSideDblClick(best, p)
+ }}
+ />
+ {showDims && (
+ <>
+ {pts.map((a, i) => (
+ <LengthLabel key={i} a={a} b={pts[(i + 1) % pts.length]} scale={scale} gap={0} away={c} viewRot={viewRot} />
+ ))}
+ <Group x={c.x} y={c.y} rotation={-viewRot} scaleX={px} scaleY={px} listening={false}>
+ <Rect x={-70} y={-11} width={140} height={22} cornerRadius={6} fill="rgba(255,255,255,0.92)" />
+ <Text
+ x={-70}
+ y={-11}
+ width={140}
+ height={22}
+ align="center"
+ verticalAlign="middle"
+ text={`${zone.name} · ${formatNumber(area, 1)} ${t('common:units.m2')}`}
+ fontSize={11.5}
+ fontStyle="600"
+ fontFamily={canvasTheme.font}
+ fill={canvasTheme.ink}
+ />
+ </Group>
+ </>
+ )}
+ {selected &&
+ listening &&
+ !zone.locked &&
+ pts.map((p, i) => (
+ <Circle
+ key={`v${i}`}
+ x={p.x}
+ y={p.y}
+ radius={6 * px}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2 * px}
+ hitStrokeWidth={10 * px}
+ onMouseDown={(e) => {
+ if (e.evt.button !== 0) return
+ e.cancelBubble = true
+ onVertexDown(i)
+ }}
+ onMouseEnter={cursor('crosshair')}
+ onMouseLeave={cursor('')}
+ />
+ ))}
+ </Group>
+ )
+}
+
+function distToSeg(p: Point, a: Point, b: Point) {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy
+ const t = l2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2)) : 0
+ return distance(p, { x: a.x + t * dx, y: a.y + t * dy })
+}
+
+export function snapZonePoint(raw: Point, plan: Plan, scale: number, from: Point | null, angle: boolean, skip?: Point): Point {
+ if (from && angle) return snapAngle(from, raw)
+ const r = 12 / scale
+ const site = sitePolygon(plan.site)
+ const cands: Point[] = [...site, ...plan.walls.flatMap((w) => [w.a, w.b])]
+ for (const z of plan.site.zones ?? []) cands.push(...z.polygon)
+ let best: Point | null = null
+ let bestD = r
+ for (const p of cands) {
+ if (skip && p === skip) continue
+ const d = distance(raw, p)
+ if (d < bestD) {
+ best = p
+ bestD = d
+ }
+ }
+ if (best) return { x: best.x, y: best.y }
+ const er = 8 / scale
+ for (let i = 0; i < site.length; i += 1) {
+ const a = site[i]
+ const b = site[(i + 1) % site.length]
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy
+ const t = l2 ? Math.max(0, Math.min(1, ((raw.x - a.x) * dx + (raw.y - a.y) * dy) / l2)) : 0
+ const q = { x: a.x + t * dx, y: a.y + t * dy }
+ if (distance(raw, q) < er) return { x: Math.round(q.x), y: Math.round(q.y) }
+ }
+ return snapToGrid(raw, GRID_SNAP)
+}
diff --git a/src/canvas/camera.ts b/src/canvas/camera.ts
new file mode 100644
index 0000000..7c07bf2
--- /dev/null
+++ b/src/canvas/camera.ts
@@ -0,0 +1,100 @@
+export type Camera = { x: number; y: number; scale: number; rotation?: number }
+
+export const MIN_SCALE = 0.004
+export const MAX_SCALE = 2
+
+export const clampScale = (s: number) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, s))
+
+export const normRot = (deg: number) => {
+ const r = ((deg % 360) + 360) % 360
+ return r > 180 ? r - 360 : r
+}
+
+type P = { x: number; y: number }
+
+export function toScreen(cam: Camera, p: P): P {
+ const r = ((cam.rotation ?? 0) * Math.PI) / 180
+ const c = Math.cos(r)
+ const s = Math.sin(r)
+ const x = p.x * cam.scale
+ const y = p.y * cam.scale
+ return { x: cam.x + x * c - y * s, y: cam.y + x * s + y * c }
+}
+
+export function toWorld(cam: Camera, p: P): P {
+ const r = ((cam.rotation ?? 0) * Math.PI) / 180
+ const c = Math.cos(r)
+ const s = Math.sin(r)
+ const dx = p.x - cam.x
+ const dy = p.y - cam.y
+ return { x: (dx * c + dy * s) / cam.scale, y: (-dx * s + dy * c) / cam.scale }
+}
+
+export function anchorAt(cam: Camera, world: P, screen: P): Camera {
+ const z = toScreen({ ...cam, x: 0, y: 0 }, world)
+ return { ...cam, x: screen.x - z.x, y: screen.y - z.y }
+}
+
+export function visibleRect(cam: Camera, width: number, height: number) {
+ const pts = [
+ toWorld(cam, { x: 0, y: 0 }),
+ toWorld(cam, { x: width, y: 0 }),
+ toWorld(cam, { x: 0, y: height }),
+ toWorld(cam, { x: width, y: height }),
+ ]
+ const xs = pts.map((p) => p.x)
+ const ys = pts.map((p) => p.y)
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) }
+}
+
+const GRID_STEPS = [100, 500, 1000, 5000, 10000, 50000]
+
+export function gridSteps(scale: number) {
+ const minor = GRID_STEPS.find((s) => s * scale >= 8) ?? GRID_STEPS[GRID_STEPS.length - 1]
+ const major = GRID_STEPS.find((s) => s > minor && s >= 1000 && s * scale >= 50) ?? minor * 10
+ return { minor, major }
+}
+
+const LABEL_STEPS = [500, 1000, 2000, 5000, 10000, 20000, 50000, 100000]
+
+export const labelStep = (scale: number) =>
+ LABEL_STEPS.find((s) => s * scale >= 56) ?? LABEL_STEPS[LABEL_STEPS.length - 1]
+
+export function fitCamera(
+ points: P[],
+ width: number,
+ height: number,
+ padding: { left: number; top: number; right: number; bottom: number },
+ rotation = 0,
+): Camera {
+ const unit = { x: 0, y: 0, scale: 1, rotation }
+ const rp = points.map((p) => toScreen(unit, p))
+ const xs = rp.map((p) => p.x)
+ const ys = rp.map((p) => p.y)
+ const minX = Math.min(...xs)
+ const minY = Math.min(...ys)
+ const w = Math.max(1, Math.max(...xs) - minX)
+ const h = Math.max(1, Math.max(...ys) - minY)
+ const availW = Math.max(50, width - padding.left - padding.right)
+ const availH = Math.max(50, height - padding.top - padding.bottom)
+ const scale = clampScale(Math.min(availW / w, availH / h))
+ return {
+ scale,
+ rotation,
+ x: padding.left + (availW - w * scale) / 2 - minX * scale,
+ y: padding.top + (availH - h * scale) / 2 - minY * scale,
+ }
+}
+
+export const readableAngle = (deg: number, viewRot = 0) => {
+ let a = deg + viewRot
+ a = ((a % 360) + 360) % 360
+ if (a > 90 && a <= 270) a -= 180
+ if (a > 270) a -= 360
+ return a - viewRot
+}
+
+export function northAngle(rotationDeg: number) {
+ const t = (rotationDeg * Math.PI) / 180
+ return (Math.atan2(-Math.cos(t), Math.sin(t)) * 180) / Math.PI
+}
diff --git a/src/canvas/measure.ts b/src/canvas/measure.ts
new file mode 100644
index 0000000..53e0ca2
--- /dev/null
+++ b/src/canvas/measure.ts
@@ -0,0 +1,98 @@
+import { resolveFurniture } from '../furniture/catalog'
+import { distance, sitePolygon, wallDirection, wallLength, type Plan, type Point } from '../model'
+
+export type Measure = { points: Point[] }
+
+function segmentClosest(p: Point, a: Point, b: Point): Point {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const len2 = dx * dx + dy * dy
+ if (len2 === 0) return a
+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))
+ return { x: a.x + t * dx, y: a.y + t * dy }
+}
+
+export function measureTargets(plan: Plan) {
+ const points: Point[] = []
+ const segments: [Point, Point][] = []
+ for (const w of plan.walls) {
+ const d = wallDirection(w)
+ const n = { x: -d.y, y: d.x }
+ const h = w.thickness / 2
+ points.push(w.a, w.b)
+ for (const s of [1, -1]) {
+ const a = { x: w.a.x + n.x * h * s, y: w.a.y + n.y * h * s }
+ const b = { x: w.b.x + n.x * h * s, y: w.b.y + n.y * h * s }
+ points.push(a, b)
+ segments.push([a, b])
+ }
+ const len = wallLength(w)
+ for (const o of plan.openings.filter((x) => x.wallId === w.id)) {
+ for (const off of [o.offset, o.offset + o.width]) {
+ if (off < 0 || off > len) continue
+ const c = { x: w.a.x + d.x * off, y: w.a.y + d.y * off }
+ points.push(c, { x: c.x + n.x * h, y: c.y + n.y * h }, { x: c.x - n.x * h, y: c.y - n.y * h })
+ }
+ }
+ }
+ for (const p of sitePolygon(plan.site)) points.push(p)
+ for (const f of plan.furniture) {
+ const r = resolveFurniture(f)
+ const t = (f.rotationDeg * Math.PI) / 180
+ const c = Math.cos(t)
+ const s = Math.sin(t)
+ points.push({ x: f.x, y: f.y })
+ for (const [u, v] of [
+ [-1, -1],
+ [1, -1],
+ [1, 1],
+ [-1, 1],
+ ]) {
+ const lx = (u * r.w) / 2
+ const ly = (v * r.d) / 2
+ points.push({ x: f.x + lx * c - ly * s, y: f.y + lx * s + ly * c })
+ }
+ }
+ return { points, segments }
+}
+
+export function snapMeasure(
+ raw: Point,
+ targets: ReturnType<typeof measureTargets>,
+ scale: number,
+ from: Point | null,
+ angle: boolean,
+): { point: Point; snapped: boolean } {
+ if (from && angle) {
+ const dx = raw.x - from.x
+ const dy = raw.y - from.y
+ const a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4)
+ const len = dx * Math.cos(a) + dy * Math.sin(a)
+ return { point: { x: from.x + Math.cos(a) * len, y: from.y + Math.sin(a) * len }, snapped: true }
+ }
+ const r = 12 / scale
+ let best: Point | null = null
+ let bestD = r
+ for (const p of targets.points) {
+ const d = distance(raw, p)
+ if (d < bestD) {
+ best = p
+ bestD = d
+ }
+ }
+ if (best) return { point: best, snapped: true }
+ const edgeR = 8 / scale
+ let bestE: Point | null = null
+ let bestED = edgeR
+ for (const [a, b] of targets.segments) {
+ const c = segmentClosest(raw, a, b)
+ const d = distance(raw, c)
+ if (d < bestED) {
+ bestE = c
+ bestED = d
+ }
+ }
+ return bestE ? { point: bestE, snapped: true } : { point: raw, snapped: false }
+}
+
+export const polylineLength = (pts: Point[]) => pts.slice(1).reduce((s, p, i) => s + distance(pts[i], p), 0)
diff --git a/src/canvas/selection/GroupOverlay.tsx b/src/canvas/selection/GroupOverlay.tsx
new file mode 100644
index 0000000..d9d9cb5
--- /dev/null
+++ b/src/canvas/selection/GroupOverlay.tsx
@@ -0,0 +1,148 @@
+import { Arc, Circle, Group, Line, Path, Rect } from 'react-konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { canvasTheme } from '../theme'
+
+export const ROTATE_GAP_PX = 28
+
+type Bounds = { minX: number; minY: number; maxX: number; maxY: number }
+
+type Props = {
+ bounds: Bounds
+ scale: number
+ onRotateStart?: (e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+}
+
+export function GroupOverlay({ bounds: b, scale, onRotateStart }: Props) {
+ const px = 1 / scale
+ const cx = (b.minX + b.maxX) / 2
+ const hy = b.minY - ROTATE_GAP_PX * px
+ const down = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if ('button' in e.evt && e.evt.button !== 0) return
+ e.cancelBubble = true
+ onRotateStart?.(e)
+ }
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+ return (
+ <>
+ <Rect
+ x={b.minX - 6 * px}
+ y={b.minY - 6 * px}
+ width={b.maxX - b.minX + 12 * px}
+ height={b.maxY - b.minY + 12 * px}
+ stroke={canvasTheme.accent}
+ strokeWidth={1.5 * px}
+ dash={[6 * px, 4 * px]}
+ listening={false}
+ />
+ {onRotateStart && (
+ <>
+ <Line points={[cx, b.minY - 6 * px, cx, hy]} stroke={canvasTheme.accent} strokeWidth={1.5 * px} listening={false} />
+ <Circle
+ x={cx}
+ y={hy}
+ radius={7 * px}
+ hitStrokeWidth={12 * px}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2.5 * px}
+ shadowColor="rgba(0,0,0,0.25)"
+ shadowBlur={4 * px}
+ shadowOffsetY={1 * px}
+ onMouseDown={down}
+ onTouchStart={down}
+ onMouseEnter={cursor('grab')}
+ onMouseLeave={cursor('')}
+ />
+ </>
+ )}
+ </>
+ )
+}
+
+export function CornerHint({ corner, center, scale }: { corner: { x: number; y: number }; center: { x: number; y: number }; scale: number }) {
+ const px = 1 / scale
+ const out = (Math.atan2(corner.y - center.y, corner.x - center.x) * 180) / Math.PI
+ return (
+ <Arc
+ x={corner.x}
+ y={corner.y}
+ innerRadius={15 * px}
+ outerRadius={17 * px}
+ angle={70}
+ rotation={out - 35}
+ fill={canvasTheme.accent}
+ listening={false}
+ />
+ )
+}
+
+const MOVE_ICON =
+ 'M0 -7 L-2.6 -4.2 M0 -7 L2.6 -4.2 M0 -7 L0 7 M0 7 L-2.6 4.2 M0 7 L2.6 4.2 M-7 0 L-4.2 -2.6 M-7 0 L-4.2 2.6 M-7 0 L7 0 M7 0 L4.2 -2.6 M7 0 L4.2 2.6'
+
+export function MoveHandle({
+ at,
+ scale,
+ viewRot,
+ onStart,
+}: {
+ at: { x: number; y: number }
+ scale: number
+ viewRot: number
+ onStart: (e: KonvaEventObject<MouseEvent | TouchEvent>) => void
+}) {
+ const down = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if ('button' in e.evt && e.evt.button !== 0) return
+ e.cancelBubble = true
+ onStart(e)
+ }
+ const cursor = (value: string) => (e: KonvaEventObject<MouseEvent>) => {
+ const stage = e.target.getStage()
+ if (stage) stage.container().style.cursor = value
+ }
+ return (
+ <Group
+ x={at.x}
+ y={at.y}
+ scaleX={1 / scale}
+ scaleY={1 / scale}
+ rotation={-viewRot}
+ onMouseDown={down}
+ onTouchStart={down}
+ onMouseEnter={cursor('move')}
+ onMouseLeave={cursor('')}
+ >
+ <Circle
+ radius={13}
+ fill="#ffffff"
+ stroke={canvasTheme.accent}
+ strokeWidth={2}
+ shadowColor="rgba(0,0,0,0.25)"
+ shadowBlur={4}
+ shadowOffsetY={1}
+ hitStrokeWidth={8}
+ />
+ <Path data={MOVE_ICON} stroke={canvasTheme.accent} strokeWidth={1.8} lineCap="round" lineJoin="round" listening={false} />
+ </Group>
+ )
+}
+
+export function GuideLines({ guides, scale }: { guides: { a: { x: number; y: number }; b: { x: number; y: number } }[]; scale: number }) {
+ const px = 1 / scale
+ return (
+ <>
+ {guides.map((g, i) => (
+ <Line
+ key={i}
+ points={[g.a.x, g.a.y, g.b.x, g.b.y]}
+ stroke={canvasTheme.accent}
+ strokeWidth={1.2 * px}
+ dash={[5 * px, 4 * px]}
+ listening={false}
+ />
+ ))}
+ </>
+ )
+}
diff --git a/src/canvas/selection/index.ts b/src/canvas/selection/index.ts
new file mode 100644
index 0000000..f834947
--- /dev/null
+++ b/src/canvas/selection/index.ts
@@ -0,0 +1,4 @@
+import './selection.css'
+
+export * from './model'
+export { CornerHint, GroupOverlay, GuideLines, MoveHandle, ROTATE_GAP_PX } from './GroupOverlay'
diff --git a/src/canvas/selection/model.ts b/src/canvas/selection/model.ts
new file mode 100644
index 0000000..8d86260
--- /dev/null
+++ b/src/canvas/selection/model.ts
@@ -0,0 +1,564 @@
+import { normalizeDeg, sitePolygon, type Plan, type Point } from '../../model'
+import { fmtNum, t } from '../../i18n'
+import { detectRooms, pointInPolygon } from '../../stats/rooms'
+import { toScreen, type Camera } from '../camera'
+
+export type SelKind = 'walls' | 'openings' | 'furniture' | 'rooms'
+export type Selection = Record<SelKind, string[]>
+
+export const SEL_KINDS: SelKind[] = ['walls', 'openings', 'furniture', 'rooms']
+
+export const emptySel = (): Selection => ({ walls: [], openings: [], furniture: [], rooms: [] })
+
+export const withoutLocked = (s: Selection, locked: { walls: boolean; furniture: boolean }): Selection => ({
+ ...s,
+ walls: locked.walls ? [] : s.walls,
+ openings: locked.walls ? [] : s.openings,
+ furniture: locked.furniture ? [] : s.furniture,
+})
+
+export const selSize = (s: Selection | null) => (s ? SEL_KINDS.reduce((n, k) => n + s[k].length, 0) : 0)
+
+export const selHas = (s: Selection | null, kind: SelKind, id: string) => !!s && s[kind].includes(id)
+
+export function pruneSel(plan: Plan, s: Selection): Selection {
+ const ids = {
+ walls: new Set(plan.walls.map((w) => w.id)),
+ openings: new Set(plan.openings.map((o) => o.id)),
+ furniture: new Set(plan.furniture.map((f) => f.id)),
+ rooms: new Set((plan.rooms ?? []).map((r) => r.id)),
+ }
+ return {
+ walls: s.walls.filter((id) => ids.walls.has(id)),
+ openings: s.openings.filter((id) => ids.openings.has(id)),
+ furniture: s.furniture.filter((id) => ids.furniture.has(id)),
+ rooms: s.rooms.filter((id) => ids.rooms.has(id)),
+ }
+}
+
+export function toggleSel(s: Selection, kind: SelKind, id: string): Selection {
+ const list = s[kind]
+ return { ...s, [kind]: list.includes(id) ? list.filter((x) => x !== id) : [...list, id] }
+}
+
+export function selectAll(plan: Plan): Selection {
+ return {
+ walls: plan.walls.map((w) => w.id),
+ openings: plan.openings.map((o) => o.id),
+ furniture: plan.furniture.map((f) => f.id),
+ rooms: (plan.rooms ?? []).map((r) => r.id),
+ }
+}
+
+function connectedWalls(plan: Plan, wallId: string, tol = 20): Set<string> {
+ const seen = new Set([wallId])
+ const queue = [wallId]
+ const near = (p: Point, q: Point) => Math.hypot(p.x - q.x, p.y - q.y) <= tol
+ while (queue.length) {
+ const w = plan.walls.find((x) => x.id === queue.pop())
+ if (!w) continue
+ for (const o of plan.walls) {
+ if (seen.has(o.id)) continue
+ if ([o.a, o.b].some((p) => near(p, w.a) || near(p, w.b)) || [w.a, w.b].some((p) => near(p, o.a) || near(p, o.b))) {
+ seen.add(o.id)
+ queue.push(o.id)
+ }
+ }
+ }
+ return seen
+}
+
+export function buildingSel(plan: Plan, wallId: string): Selection {
+ const b = detectRooms(plan).buildings.find((x) => x.walls.some((w) => w.id === wallId))
+ const walls = b ? new Set(b.walls.map((w) => w.id)) : connectedWalls(plan, wallId)
+ const outline = b?.outline ?? []
+ const inside = (p: Point) => outline.length >= 3 && pointInPolygon(p, outline)
+ return {
+ walls: [...walls],
+ openings: plan.openings.filter((o) => walls.has(o.wallId)).map((o) => o.id),
+ furniture: plan.furniture.filter(inside).map((f) => f.id),
+ rooms: (plan.rooms ?? []).filter(inside).map((r) => r.id),
+ }
+}
+
+export type ScreenRect = { x0: number; y0: number; x1: number; y1: number }
+
+export function rectSel(plan: Plan, cam: Camera, r: ScreenRect): Selection {
+ const minX = Math.min(r.x0, r.x1)
+ const maxX = Math.max(r.x0, r.x1)
+ const minY = Math.min(r.y0, r.y1)
+ const maxY = Math.max(r.y0, r.y1)
+ const hit = (p: Point) => {
+ const s = toScreen(cam, p)
+ return s.x >= minX && s.x <= maxX && s.y >= minY && s.y <= maxY
+ }
+ const walls = plan.walls.filter((w) => hit(w.a) && hit(w.b)).map((w) => w.id)
+ const ws = new Set(walls)
+ return {
+ walls,
+ openings: plan.openings.filter((o) => ws.has(o.wallId)).map((o) => o.id),
+ furniture: plan.furniture.filter(hit).map((f) => f.id),
+ rooms: (plan.rooms ?? []).filter(hit).map((r) => r.id),
+ }
+}
+
+export function mergeSel(a: Selection, b: Selection): Selection {
+ const out = emptySel()
+ for (const k of SEL_KINDS) out[k] = [...new Set([...a[k], ...b[k]])]
+ return out
+}
+
+export function selPoints(plan: Plan, s: Selection): Point[] {
+ const w = new Set(s.walls)
+ const f = new Set(s.furniture)
+ const r = new Set(s.rooms)
+ return [
+ ...plan.walls.filter((x) => w.has(x.id)).flatMap((x) => [x.a, x.b]),
+ ...plan.furniture.filter((x) => f.has(x.id)),
+ ...(plan.rooms ?? []).filter((x) => r.has(x.id)),
+ ]
+}
+
+export function selBounds(plan: Plan, s: Selection) {
+ const w = new Set(s.walls)
+ const pts = selPoints(plan, s)
+ if (pts.length === 0) return null
+ const pad = Math.max(0, ...plan.walls.filter((x) => w.has(x.id)).map((x) => x.thickness / 2))
+ const xs = pts.map((p) => p.x)
+ const ys = pts.map((p) => p.y)
+ return { minX: Math.min(...xs) - pad, minY: Math.min(...ys) - pad, maxX: Math.max(...xs) + pad, maxY: Math.max(...ys) + pad }
+}
+
+export function selCenter(plan: Plan, s: Selection): Point | null {
+ const b = selBounds(plan, s)
+ return b ? { x: Math.round((b.minX + b.maxX) / 2), y: Math.round((b.minY + b.maxY) / 2) } : null
+}
+
+export function movePlan(plan: Plan, s: Selection, d: Point): Plan {
+ const dx = Math.round(d.x)
+ const dy = Math.round(d.y)
+ if (!dx && !dy) return plan
+ const w = new Set(s.walls)
+ const f = new Set(s.furniture)
+ const r = new Set(s.rooms)
+ const sh = (p: Point) => ({ x: p.x + dx, y: p.y + dy })
+ return {
+ ...plan,
+ walls: plan.walls.map((x) => (w.has(x.id) ? { ...x, a: sh(x.a), b: sh(x.b) } : x)),
+ furniture: plan.furniture.map((x) => (f.has(x.id) ? { ...x, ...sh(x) } : x)),
+ ...(plan.rooms ? { rooms: plan.rooms.map((x) => (r.has(x.id) ? { ...x, ...sh(x) } : x)) } : {}),
+ ...(plan.networks ? { networks: netsTransform(plan, s, sh, 0) } : {}),
+ }
+}
+
+export function rotatePlan(plan: Plan, s: Selection, deg: number, center: Point): Plan {
+ if (!deg) return plan
+ const rad = (deg * Math.PI) / 180
+ const c = Math.cos(rad)
+ const sn = Math.sin(rad)
+ const rt = (p: Point) => {
+ const x = p.x - center.x
+ const y = p.y - center.y
+ return { x: Math.round(center.x + x * c - y * sn), y: Math.round(center.y + x * sn + y * c) }
+ }
+ const w = new Set(s.walls)
+ const f = new Set(s.furniture)
+ const r = new Set(s.rooms)
+ return {
+ ...plan,
+ walls: plan.walls.map((x) => (w.has(x.id) ? { ...x, a: rt(x.a), b: rt(x.b) } : x)),
+ furniture: plan.furniture.map((x) => (f.has(x.id) ? { ...x, ...rt(x), rotationDeg: rotDeg(x.rotationDeg + deg) } : x)),
+ ...(plan.rooms ? { rooms: plan.rooms.map((x) => (r.has(x.id) ? { ...x, ...rt(x) } : x)) } : {}),
+ ...(plan.networks ? { networks: netsTransform(plan, s, rt, deg) } : {}),
+ }
+}
+
+const rotDeg = (d: number) => (Number.isInteger(d) ? normalizeDeg(d) : Math.round(((((d % 360) + 360) % 360) * 10)) / 10)
+
+export const wrapDeg = (d: number) => ((((d + 180) % 360) + 360) % 360) - 180
+
+export const formatDeg = (d: number) => `${d > 0 ? '+' : ''}${fmtNum(Math.round(d * 10) / 10, 1, 1)}°`
+
+export function groupRotateDeg(plan: Plan, s: Selection, raw: number, shift: boolean): number {
+ if (shift) return wrapDeg(Math.round(raw / 15) * 15)
+ const fine = wrapDeg(Math.round(raw * 2) / 2)
+ const axis = groupAxisDeg(plan, s)
+ if (axis === null) return fine
+ const targets = [0]
+ const st = streetDeg(plan)
+ if (st !== null) targets.push(st)
+ let best: number | null = null
+ for (const t of targets) {
+ const m = ((((t - axis - raw) % 90) + 135) % 90) - 45
+ if (Math.abs(m) <= 1 && (best === null || Math.abs(m) < Math.abs(best - raw))) best = raw + m
+ }
+ return best === null ? fine : wrapDeg(best)
+}
+
+export function groupAxisDeg(plan: Plan, s: Selection): number | null {
+ const w = new Set(s.walls)
+ let sx = 0
+ let sy = 0
+ for (const x of plan.walls) {
+ if (!w.has(x.id)) continue
+ const len = Math.hypot(x.b.x - x.a.x, x.b.y - x.a.y)
+ const a = 4 * Math.atan2(x.b.y - x.a.y, x.b.x - x.a.x)
+ sx += len * Math.cos(a)
+ sy += len * Math.sin(a)
+ }
+ if (!sx && !sy) return null
+ return ((Math.atan2(sy, sx) / 4) * 180) / Math.PI
+}
+
+export function streetDeg(plan: Plan): number | null {
+ const side = plan.site.street?.side
+ if (!side) return null
+ const poly = sitePolygon(plan.site)
+ const p = poly[side[0]]
+ const q = poly[side[1]]
+ if (!p || !q) return null
+ return (Math.atan2(q.y - p.y, q.x - p.x) * 180) / Math.PI
+}
+
+export function deletePlan(plan: Plan, s: Selection): Plan {
+ const w = new Set(s.walls)
+ const o = new Set(s.openings)
+ const f = new Set(s.furniture)
+ const r = new Set(s.rooms)
+ return {
+ ...plan,
+ walls: plan.walls.filter((x) => !w.has(x.id)),
+ openings: plan.openings.filter((x) => !o.has(x.id) && !w.has(x.wallId)),
+ furniture: plan.furniture.filter((x) => !f.has(x.id)),
+ ...(plan.rooms ? { rooms: plan.rooms.filter((x) => !r.has(x.id)) } : {}),
+ ...(plan.networks ? { networks: netsDelete(plan, s) } : {}),
+ }
+}
+
+const contourCache = new WeakMap<Plan, WeakMap<Selection, Point[][]>>()
+
+function netContours(plan: Plan, s: Selection): Point[][] {
+ let bySel = contourCache.get(plan)
+ if (!bySel) contourCache.set(plan, (bySel = new WeakMap()))
+ let polys = bySel.get(s)
+ if (!polys) {
+ polys = fullBuildings(detectRooms(plan).buildings, s).map((b) => b.footprint)
+ bySel.set(s, polys)
+ }
+ return polys
+}
+
+const NET_TOL = 60
+
+function netTest(plan: Plan, s: Selection) {
+ const walls = new Set(s.walls)
+ const polys = netContours(plan, s)
+ const inside = (p: Point) =>
+ polys.some(
+ (poly) =>
+ pointInPolygon(p, poly) ||
+ poly.some((a, i) => {
+ const q = segPoint(p, a, poly[(i + 1) % poly.length])
+ return Math.hypot(p.x - q.x, p.y - q.y) <= NET_TOL
+ }),
+ )
+ return (p: Point & { wallId?: string }) => (p.wallId ? walls.has(p.wallId) : false) || inside(p)
+}
+
+type Hit = (p: Point & { wallId?: string }) => boolean
+
+function walkTransform(v: unknown, hit: Hit, f: (p: Point) => Point, deg: number): unknown {
+ if (Array.isArray(v)) return v.map((x) => walkTransform(x, hit, f, deg))
+ if (!v || typeof v !== 'object') return v
+ const o = v as Record<string, unknown>
+ const out: Record<string, unknown> = {}
+ for (const [k, x] of Object.entries(o)) out[k] = walkTransform(x, hit, f, deg)
+ if (typeof o.x === 'number' && typeof o.y === 'number' && hit(o as Point & { wallId?: string })) {
+ Object.assign(out, f(o as Point))
+ if (deg && typeof o.rotationDeg === 'number') out.rotationDeg = rotDeg(o.rotationDeg + deg)
+ }
+ return out
+}
+
+function walkDelete(v: unknown, hit: Hit): unknown {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return v
+ const o = v as Record<string, unknown>
+ const gone = new Set<string>()
+ const out: Record<string, unknown> = { ...o }
+ for (const [k, x] of Object.entries(o)) {
+ if (!Array.isArray(x)) continue
+ out[k] = x.filter((it) => {
+ const r = it as Record<string, unknown>
+ const del = !!r && typeof r.x === 'number' && typeof r.y === 'number' && hit(r as Point & { wallId?: string })
+ if (del && typeof r.id === 'string') gone.add(r.id)
+ return !del
+ })
+ }
+ for (const [k, x] of Object.entries(out)) {
+ if (!Array.isArray(x)) continue
+ out[k] = x.filter((it) => {
+ const r = it as Record<string, unknown>
+ return !(r && (gone.has(r.from as string) || gone.has(r.to as string)))
+ })
+ }
+ return out
+}
+
+const KNOWN_NETS = new Set(['electric', 'sewer', 'heating'])
+
+type Heating = NonNullable<NonNullable<Plan['networks']>['heating']>
+type Loop = Heating['loops'][number]
+
+const loopCenter = (l: Loop): Point => {
+ const n = l.polygon.length || 1
+ return { x: l.polygon.reduce((a, p) => a + p.x, 0) / n, y: l.polygon.reduce((a, p) => a + p.y, 0) / n }
+}
+
+function heatingTransform(h: Heating, hit: Hit, f: (p: Point) => Point): Heating {
+ const path = <T extends Point>(ps: T[] | undefined) => ps && ps.map((p) => ({ ...p, ...f(p) }))
+ return {
+ ...h,
+ ...(h.collector && hit(h.collector) ? { collector: { ...h.collector, ...f(h.collector) } } : {}),
+ loops: h.loops.map((l) =>
+ hit(loopCenter(l))
+ ? {
+ ...l,
+ polygon: path(l.polygon) ?? l.polygon,
+ ...(l.supplyPath ? { supplyPath: path(l.supplyPath) } : {}),
+ ...(l.linkPath ? { linkPath: path(l.linkPath) } : {}),
+ ...(l.excluded ? { excluded: l.excluded.map((e) => path(e) ?? e) } : {}),
+ ...(l.parts
+ ? {
+ parts: l.parts.map((pt) => ({
+ ...pt,
+ polygon: path(pt.polygon) ?? pt.polygon,
+ ...(pt.excluded ? { excluded: pt.excluded.map((e) => path(e) ?? e) } : {}),
+ })),
+ }
+ : {}),
+ }
+ : l,
+ ),
+ }
+}
+
+function heatingDelete(h: Heating, hit: Hit): Heating {
+ return {
+ ...h,
+ collector: h.collector && !hit(h.collector) ? h.collector : undefined,
+ loops: h.loops.filter((l) => !hit(loopCenter(l))),
+ }
+}
+
+function otherNets(net: NonNullable<Plan['networks']>, fn: (v: unknown) => unknown) {
+ const out: Record<string, unknown> = {}
+ for (const [k, v] of Object.entries(net)) if (!KNOWN_NETS.has(k) && v && typeof v === 'object') out[k] = fn(v)
+ return out
+}
+
+function netsTransform(plan: Plan, s: Selection, f: (p: Point) => Point, deg: number): Plan['networks'] {
+ const net = plan.networks
+ if (!net) return net
+ const hit = netTest(plan, s)
+ const el = net.electric
+ const sw = net.sewer
+ return {
+ ...net,
+ ...otherNets(net, (v) => walkTransform(v, hit, f, deg)),
+ ...(net.heating ? { heating: heatingTransform(net.heating, hit, f) } : {}),
+ ...(el
+ ? {
+ electric: {
+ ...el,
+ ...(el.panel && hit(el.panel) ? { panel: { ...el.panel, ...f(el.panel) } } : {}),
+ points: el.points.map((p) => (hit(p) ? { ...p, ...f(p) } : p)),
+ ...(el.routes
+ ? {
+ routes: el.routes.map((r) => {
+ const a = hit(r.path[0])
+ const b = hit(r.path[r.path.length - 1])
+ if (!a && !b) return r
+ return { ...r, path: r.path.map((p) => (a && b) || hit(p) ? f(p) : p) }
+ }),
+ }
+ : {}),
+ },
+ }
+ : {}),
+ ...(sw
+ ? {
+ sewer: {
+ ...sw,
+ nodes: sw.nodes.map((n) =>
+ hit(n)
+ ? { ...n, ...f(n), ...(deg && n.rotationDeg !== undefined ? { rotationDeg: rotDeg(n.rotationDeg + deg) } : {}) }
+ : n,
+ ),
+ },
+ }
+ : {}),
+ }
+}
+
+function netsDelete(plan: Plan, s: Selection): Plan['networks'] {
+ const net = plan.networks
+ if (!net) return net
+ const hit = netTest(plan, s)
+ const el = net.electric
+ const sw = net.sewer
+ const gone = new Set(sw ? sw.nodes.filter(hit).map((n) => n.id) : [])
+ const panel = el?.panel && !hit(el.panel) ? el.panel : undefined
+ return {
+ ...net,
+ ...otherNets(net, (v) => walkDelete(v, hit)),
+ ...(net.heating ? { heating: heatingDelete(net.heating, hit) } : {}),
+ ...(el
+ ? {
+ electric: {
+ ...el,
+ panel,
+ points: el.points.filter((p) => !hit(p)),
+ ...(el.routes ? { routes: el.routes.filter((r) => !hit(r.path[0]) && !hit(r.path[r.path.length - 1])) } : {}),
+ },
+ }
+ : {}),
+ ...(sw
+ ? { sewer: { ...sw, nodes: sw.nodes.filter((n) => !gone.has(n.id)), pipes: sw.pipes.filter((p) => !gone.has(p.from) && !gone.has(p.to)) } }
+ : {}),
+ }
+}
+
+export function streetAlignDeg(plan: Plan, s: Selection): number | null {
+ const side = plan.site.street?.side
+ if (!side) return null
+ const poly = sitePolygon(plan.site)
+ const p = poly[side[0]]
+ const q = poly[side[1]]
+ if (!p || !q) return null
+ const street = Math.atan2(q.y - p.y, q.x - p.x)
+ const w = new Set(s.walls)
+ let sx = 0
+ let sy = 0
+ for (const x of plan.walls) {
+ if (!w.has(x.id)) continue
+ const len = Math.hypot(x.b.x - x.a.x, x.b.y - x.a.y)
+ const a = 4 * Math.atan2(x.b.y - x.a.y, x.b.x - x.a.x)
+ sx += len * Math.cos(a)
+ sy += len * Math.sin(a)
+ }
+ if (!sx && !sy) return null
+ const axis = Math.atan2(sy, sx) / 4
+ let d = ((street - axis) * 180) / Math.PI
+ d = ((d % 90) + 90) % 90
+ if (d > 45) d -= 90
+ const deg = Math.round(d * 10) / 10
+ return Math.abs(deg) < 0.05 ? 0 : deg
+}
+
+export function selSummary(s: Selection) {
+ return t('common:canvas.selSummary', {
+ walls: t('common:canvas.walls', { count: s.walls.length }),
+ openings: t('common:canvas.openings', { count: s.openings.length }),
+ items: t('common:canvas.items', { count: s.furniture.length }),
+ })
+}
+
+export function plural(n: number, one: string, few: string, many: string) {
+ const m10 = n % 10
+ const m100 = n % 100
+ if (m10 === 1 && m100 !== 11) return one
+ if (m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14)) return few
+ return many
+}
+
+type Building = { walls: { id: string }[]; footprint: Point[] }
+
+function dropCollinear(poly: Point[]): Point[] {
+ const n = poly.length
+ const out = poly.filter((p, i) => {
+ const a = poly[(i - 1 + n) % n]
+ const b = poly[(i + 1) % n]
+ const ux = p.x - a.x
+ const uy = p.y - a.y
+ const vx = b.x - p.x
+ const vy = b.y - p.y
+ const lu = Math.hypot(ux, uy)
+ const lv = Math.hypot(vx, vy)
+ if (lu < 1 || lv < 1) return false
+ return Math.abs(ux * vy - uy * vx) / (lu * lv) > 0.05
+ })
+ return out.length >= 3 ? out : poly
+}
+
+export function fullBuildings<B extends Building>(buildings: B[], s: Selection): B[] {
+ const w = new Set(s.walls)
+ return buildings.filter((b) => b.walls.length > 0 && b.walls.every((x) => w.has(x.id)))
+}
+
+export function groupPolys(plan: Plan, buildings: Building[], s: Selection): Point[][] {
+ const full = fullBuildings(buildings, s)
+ if (full.length) return full.map((b) => dropCollinear(b.footprint))
+ const b = selBounds(plan, s)
+ return b
+ ? [[{ x: b.minX, y: b.minY }, { x: b.maxX, y: b.minY }, { x: b.maxX, y: b.maxY }, { x: b.minX, y: b.maxY }]]
+ : []
+}
+
+export function polysCenter(polys: Point[][]): Point | null {
+ const pts = polys.flat()
+ if (!pts.length) return null
+ const xs = pts.map((p) => p.x)
+ const ys = pts.map((p) => p.y)
+ return { x: Math.round((Math.min(...xs) + Math.max(...xs)) / 2), y: Math.round((Math.min(...ys) + Math.max(...ys)) / 2) }
+}
+
+export function segPoint(p: Point, a: Point, b: Point): Point {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy
+ const t = l2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2)) : 0
+ return { x: a.x + dx * t, y: a.y + dy * t }
+}
+
+export type Guide = { a: Point; b: Point; d: number; kind: 'site' | 'building' }
+
+function nearestToEdges(pts: Point[], poly: Point[]) {
+ let best: { a: Point; b: Point; d: number } | null = null
+ for (const p of pts) {
+ for (let i = 0; i < poly.length; i++) {
+ const q = segPoint(p, poly[i], poly[(i + 1) % poly.length])
+ const d = Math.hypot(p.x - q.x, p.y - q.y)
+ if (!best || d < best.d) best = { a: p, b: q, d }
+ }
+ }
+ return best
+}
+
+export function groupGuides(plan: Plan, buildings: Building[], s: Selection): Guide[] {
+ const polys = groupPolys(plan, buildings, s)
+ const pts = polys.flat()
+ if (!pts.length) return []
+ const site = sitePolygon(plan.site)
+ const edges: Guide[] = []
+ for (let i = 0; i < site.length; i++) {
+ const hit = nearestToEdges(pts, [site[i], site[(i + 1) % site.length]])
+ if (hit) edges.push({ ...hit, kind: 'site' })
+ }
+ const out = edges.sort((x, y) => x.d - y.d).slice(0, 2)
+ const w = new Set(s.walls)
+ let near: Guide | null = null
+ for (const b of buildings) {
+ if (b.walls.some((x) => w.has(x.id))) continue
+ for (const poly of polys) {
+ const h1 = nearestToEdges(poly, b.footprint)
+ const h2 = nearestToEdges(b.footprint, poly)
+ const h = h1 && (!h2 || h1.d <= h2.d) ? h1 : h2 && { a: h2.b, b: h2.a, d: h2.d }
+ if (h && (!near || h.d < near.d)) near = { ...h, kind: 'building' }
+ }
+ }
+ return near ? [...out, near] : out
+}
+
+export const ROTATE_CURSOR = `url("data:image/svg+xml,${encodeURIComponent(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><g fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M5 15a8 8 0 0 1 11-9.5" stroke="#fff" stroke-width="4.5"/><path d="M14 2.5l3.5 3.2-4.3 1.9" stroke="#fff" stroke-width="4.5"/><path d="M5 15a8 8 0 0 1 11-9.5" stroke="#2b2d33" stroke-width="1.8"/><path d="M14 2.5l3.5 3.2-4.3 1.9" stroke="#2b2d33" stroke-width="1.8"/></g></svg>',
+)}") 12 12, alias`
diff --git a/src/canvas/selection/selection.css b/src/canvas/selection/selection.css
new file mode 100644
index 0000000..ce06c3c
--- /dev/null
+++ b/src/canvas/selection/selection.css
@@ -0,0 +1,30 @@
+.marquee {
+ position: absolute;
+ border: 1px dashed var(--accent);
+ background: rgba(242, 107, 29, 0.08);
+ pointer-events: none;
+ z-index: 2;
+}
+
+.group-delta {
+ position: absolute;
+ padding: 3px 8px;
+ border-radius: var(--radius-sm);
+ background: var(--card);
+ box-shadow: 0 0 0 1.5px var(--accent), var(--shadow);
+ color: var(--ink);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ transform: translate(-50%, -100%);
+ pointer-events: none;
+ z-index: 3;
+}
+
+.group-delta--guide {
+ padding: 1px 6px;
+ font-size: 11px;
+ color: var(--accent-ink);
+ box-shadow: 0 0 0 1px var(--accent);
+ transform: translate(-50%, -50%);
+}
diff --git a/src/canvas/snap.ts b/src/canvas/snap.ts
new file mode 100644
index 0000000..6be10d7
--- /dev/null
+++ b/src/canvas/snap.ts
@@ -0,0 +1,48 @@
+import { distance, snapToGrid, type Point, type Wall } from '../model'
+
+export const GRID_SNAP = 100
+const ENDPOINT_SNAP_PX = 12
+
+export type Snap = { point: Point; kind: 'endpoint' | 'grid' | 'angle' }
+
+export function snapAngle(from: Point, raw: Point, step = GRID_SNAP): Point {
+ const dx = raw.x - from.x
+ const dy = raw.y - from.y
+ const angle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4)
+ const ux = Math.round(Math.cos(angle) * 1e9) / 1e9
+ const uy = Math.round(Math.sin(angle) * 1e9) / 1e9
+ const proj = dx * ux + dy * uy
+ const diagonal = ux !== 0 && uy !== 0
+ if (!diagonal) {
+ const len = Math.round(proj / step) * step
+ return { x: Math.round(from.x + ux * len), y: Math.round(from.y + uy * len) }
+ }
+ const leg = Math.round((proj * Math.SQRT1_2) / step) * step
+ return { x: from.x + Math.sign(ux) * leg, y: from.y + Math.sign(uy) * leg }
+}
+
+export function snapPoint(
+ raw: Point,
+ walls: Wall[],
+ scale: number,
+ from: Point | null,
+ angle: boolean,
+ skip?: (wallId: string, end: 'a' | 'b') => boolean,
+): Snap {
+ if (from && angle) return { point: snapAngle(from, raw), kind: 'angle' }
+ const radius = ENDPOINT_SNAP_PX / scale
+ let best: Point | null = null
+ let bestDist = radius
+ for (const w of walls) {
+ for (const end of ['a', 'b'] as const) {
+ if (skip?.(w.id, end)) continue
+ const d = distance(raw, w[end])
+ if (d <= bestDist) {
+ best = w[end]
+ bestDist = d
+ }
+ }
+ }
+ if (best) return { point: { x: best.x, y: best.y }, kind: 'endpoint' }
+ return { point: snapToGrid(raw, GRID_SNAP), kind: 'grid' }
+}
diff --git a/src/canvas/theme.ts b/src/canvas/theme.ts
new file mode 100644
index 0000000..eeb02c3
--- /dev/null
+++ b/src/canvas/theme.ts
@@ -0,0 +1,17 @@
+export const canvasTheme = {
+ background: '#f3f1ec',
+ site: '#ffffff',
+ siteStroke: '#9a948a',
+ gridMinor: '#ece8e1',
+ gridMajor: '#d9d3c9',
+ accent: '#f26b1d',
+ accentSoft: 'rgba(242, 107, 29, 0.18)',
+ ink: '#2b2d33',
+ inkMuted: '#8a8f98',
+ ruler: 'rgba(255, 255, 255, 0.94)',
+ rulerLine: '#e3ded6',
+ opening: '#ffffff',
+ font: 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif',
+}
+
+export const RULER_SIZE = 24
diff --git a/src/canvas/useElementSize.ts b/src/canvas/useElementSize.ts
new file mode 100644
index 0000000..1f0bb00
--- /dev/null
+++ b/src/canvas/useElementSize.ts
@@ -0,0 +1,19 @@
+import { useLayoutEffect, useRef, useState } from 'react'
+
+export function useElementSize<T extends HTMLElement>() {
+ const ref = useRef<T>(null)
+ const [size, setSize] = useState({ width: 0, height: 0 })
+
+ useLayoutEffect(() => {
+ const el = ref.current
+ if (!el) return
+ const observer = new ResizeObserver(([entry]) => {
+ const { width, height } = entry.contentRect
+ setSize({ width: Math.round(width), height: Math.round(height) })
+ })
+ observer.observe(el)
+ return () => observer.disconnect()
+ }, [])
+
+ return [ref, size] as const
+}
diff --git a/src/estimate/PetrovichCart.tsx b/src/estimate/PetrovichCart.tsx
new file mode 100644
index 0000000..32853a7
--- /dev/null
+++ b/src/estimate/PetrovichCart.tsx
@@ -0,0 +1,143 @@
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useSyncStore } from '../storage'
+import { Button, Checkbox, Segmented } from '../ui'
+import { fmtDate } from './format'
+import {
+ buildCart,
+ CART_SECTIONS,
+ cartItems,
+ cartSection,
+ cartSectionLabel,
+ type CartResult,
+ type CartSection,
+ type City,
+ type PetrovichLink,
+} from './petrovich'
+import type { Row } from './rows'
+
+type Props = {
+ rows: Row[]
+ saved: PetrovichLink[]
+ onSave: (links: PetrovichLink[]) => void
+}
+
+const CITY_IDS = ['spb', 'vbg'] as const
+
+export function PetrovichCart({ rows, saved, onSave }: Props) {
+ const { t } = useTranslation('estimate')
+ const cities = CITY_IDS.map((value) => ({ value, label: t(`cart.cities.${value}`) }))
+ const ref = useRef<HTMLDialogElement>(null)
+ const [city, setCity] = useState<City>('spb')
+ const [sections, setSections] = useState<Set<CartSection>>(() => new Set(CART_SECTIONS))
+ const [onlyLeft, setOnlyLeft] = useState(true)
+ const [busy, setBusy] = useState<number | null>(null)
+ const [results, setResults] = useState<CartResult[] | null>(null)
+ const [copied, setCopied] = useState<string | null>(null)
+ const demo = useSyncStore((s) => s.demo)
+
+ const picked = rows.filter((r) => sections.has(cartSection(r)) && (!onlyLeft || !r.bought))
+ const total = cartItems(picked).length
+
+ const run = async (split: boolean) => {
+ const groups = split
+ ? CART_SECTIONS.filter((s) => sections.has(s)).map((s) => ({ section: cartSectionLabel(s), items: cartItems(picked.filter((r) => cartSection(r) === s)) }))
+ : [{ section: t('cart.all'), items: cartItems(picked) }]
+ const jobs = groups.filter((g) => g.items.length)
+ setBusy(jobs.reduce((s, g) => s + g.items.length, 0))
+ setResults(null)
+ const out = await Promise.all(jobs.map((g) => buildCart(g.section, city, g.items)))
+ setBusy(null)
+ setResults(out)
+ const createdAt = new Date().toISOString()
+ const links = out.filter((r) => r.url).map((r) => ({ section: r.section, url: r.url!, createdAt, count: r.added ?? r.count }))
+ if (links.length) onSave(links)
+ }
+
+ const copy = (url: string) => void navigator.clipboard.writeText(url).then(() => setCopied(url))
+
+ const links: { section: string; url: string; count: number; note?: string }[] = results
+ ? results.filter((r) => r.url).map((r) => ({ section: r.section, url: r.url!, count: r.added ?? r.count }))
+ : saved.map((l) => ({ ...l, note: fmtDate(l.createdAt.slice(0, 10)) }))
+
+ return (
+ <>
+ <button
+ type="button"
+ className="est-tool"
+ disabled={demo}
+ title={demo ? t('cart.demoDisabled') : undefined}
+ onClick={() => ref.current?.showModal()}
+ >
+ {t('cart.open')}
+ </button>
+ <dialog ref={ref} className="est-dialog card card--padded" onClose={() => setCopied(null)}>
+ <div className="est-dialog__head">
+ <h2 className="est-dialog__title">{t('cart.title')}</h2>
+ <button type="button" className="est-tool" onClick={() => ref.current?.close()}>
+ {t('cart.close')}
+ </button>
+ </div>
+
+ <Segmented options={cities} value={city} onChange={setCity} size="sm" />
+
+ <div className="est-dialog__sections">
+ {CART_SECTIONS.map((s) => (
+ <Checkbox
+ key={s}
+ label={cartSectionLabel(s)}
+ checked={sections.has(s)}
+ onChange={(on) => {
+ const next = new Set(sections)
+ if (on) next.add(s)
+ else next.delete(s)
+ setSections(next)
+ }}
+ />
+ ))}
+ </div>
+ <Checkbox label={t('cart.onlyLeft')} checked={onlyLeft} onChange={setOnlyLeft} />
+
+ <div className="est-dialog__actions">
+ <Button variant="primary" size="sm" disabled={!total || busy !== null} onClick={() => void run(false)}>
+ {t('cart.oneLink')}
+ </Button>
+ <Button size="sm" disabled={!total || busy !== null} onClick={() => void run(true)}>
+ {t('cart.perSection')}
+ </Button>
+ <span className="est-dialog__hint">
+ {busy !== null ? t('cart.building', { count: busy }) : t('cart.withCode', { count: total })}
+ </span>
+ </div>
+
+ {links.length > 0 && (
+ <ul className="est-dialog__links">
+ {links.map((l) => (
+ <li key={l.section + l.url}>
+ <span className="est-dialog__section">
+ {l.section} · {t('cart.linkCount', { count: l.count })}{l.note ? ` · ${l.note}` : ''}
+ </span>
+ <a className="est-link" href={l.url} target="_blank" rel="noreferrer">
+ {t('cart.openLink')}
+ </a>
+ <button type="button" className="est-tool" onClick={() => copy(l.url)}>
+ {copied === l.url ? t('cart.copied') : t('cart.copy')}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {results?.map(
+ (r) =>
+ (r.error || r.missing.length > 0) && (
+ <div key={r.section} className="est-dialog__missing">
+ <b>{r.section}:</b> {r.error ? t('cart.error', { error: r.error }) : ''}
+ {r.missing.length > 0 && <>{t('cart.missing', { list: r.missing.join(', ') })}</>}
+ </div>
+ ),
+ )}
+ </dialog>
+ </>
+ )
+}
diff --git a/src/estimate/catalog.ts b/src/estimate/catalog.ts
new file mode 100644
index 0000000..be427e6
--- /dev/null
+++ b/src/estimate/catalog.ts
@@ -0,0 +1,95 @@
+import { useEffect, useState } from 'react'
+
+export type CatalogItem = {
+ id: string
+ name: string
+ kind: string
+ vendor?: string
+ url?: string
+ price: number
+ unit: string
+ thickness?: number
+ length?: number
+ height?: number
+ opening?: { width: number; height: number }
+ subtype?: string
+ sku?: string
+ preferred?: boolean
+}
+
+const CATALOG_URL = `${import.meta.env.BASE_URL}data/catalog.json`
+
+const isItem = (v: unknown): v is CatalogItem => {
+ const o = v as Partial<CatalogItem> | null
+ return (
+ !!o && typeof o.name === 'string' && typeof o.price === 'number' && typeof o.unit === 'string' && o.subtype !== 'house-kit'
+ )
+}
+
+let cache: Promise<CatalogItem[]> | null = null
+
+const loadCatalog = () =>
+ (cache ??= fetch(CATALOG_URL, { cache: 'no-cache' })
+ .then((r) => (r.ok ? r.json() : []))
+ .then((d: unknown) => (Array.isArray(d) ? d.filter(isItem) : []))
+ .catch(() => []))
+
+export function useCatalog() {
+ const [items, setItems] = useState<CatalogItem[]>([])
+ useEffect(() => {
+ let alive = true
+ void loadCatalog().then((list) => alive && setItems(list))
+ return () => {
+ alive = false
+ }
+ }, [])
+ return items
+}
+
+const isPcs = (u: string) => u === 'шт' || u === 'pcs'
+const isM2 = (u: string) => u === 'м²' || u === 'm²'
+
+const VENDOR_RANK = ['Петрович', 'ПроСИП']
+const vendorRank = (v?: string) => {
+ const i = VENDOR_RANK.findIndex((x) => v?.startsWith(x))
+ return i === -1 ? VENDOR_RANK.length : i
+}
+const byVendor = (a: CatalogItem, b: CatalogItem) => vendorRank(a.vendor) - vendorRank(b.vendor) || a.price - b.price
+
+export function findPanel(catalog: CatalogItem[], kind: string, thickness: number, w?: number, h?: number) {
+ const sameSize = (c: CatalogItem) => !w || !h || (c.length === Math.max(w, h) && c.height === Math.min(w, h))
+ const usable = (c: CatalogItem) =>
+ c.kind === kind && c.thickness === thickness && (isM2(c.unit) || (isPcs(c.unit) && !!c.length && !!c.height))
+ const roof = (c: CatalogItem) => Number(!!c.subtype?.includes('roof'))
+ const rank = (a: CatalogItem, b: CatalogItem) =>
+ roof(a) - roof(b) ||
+ Number(!!b.preferred) - Number(!!a.preferred) || Number(sameSize(b)) - Number(sameSize(a)) || byVendor(a, b)
+ const c = catalog.filter(usable).sort(rank)[0]
+ if (!c) return undefined
+ const itemM2 = isPcs(c.unit) ? (c.length! * c.height!) / 1e6 : 1
+ const perM2 = c.price / itemM2
+ const panelM2 = w && h ? (w * h) / 1e6 : undefined
+ const perPiece = isPcs(c.unit) && sameSize(c) ? c.price : panelM2 ? perM2 * panelM2 : undefined
+ return { item: c, perM2, perPiece }
+}
+
+export function findOpening(catalog: CatalogItem[], type: 'door' | 'window' | 'gate', width: number, height: number) {
+ const all = catalog.filter((c) => c.kind === type && isPcs(c.unit) && c.length && c.height)
+ const preferred = all.filter((c) => !c.vendor?.includes('DoorHan'))
+ const list = preferred.length ? preferred : all
+ const near = (a: number, b: number) => Math.abs(a - b) <= 10
+ const exact = list
+ .filter(
+ (c) =>
+ (c.opening && c.opening.width === width && c.opening.height === height) ||
+ (near(c.length!, width) && near(c.height!, height)),
+ )
+ .sort(byVendor)[0]
+ if (exact) return { item: exact, price: exact.price, exact: true }
+ const area = width * height
+ const diff = (c: CatalogItem) => Math.abs(c.length! * c.height! - area)
+ const item = [...list].sort((a, b) => diff(a) - diff(b) || byVendor(a, b))[0]
+ if (!item) return undefined
+ const price = Math.round((item.price * area) / (item.length! * item.height!) / 10) * 10
+ return { item, price, exact: false }
+}
diff --git a/src/estimate/csv.ts b/src/estimate/csv.ts
new file mode 100644
index 0000000..112b1e2
--- /dev/null
+++ b/src/estimate/csv.ts
@@ -0,0 +1,72 @@
+import { t } from '../i18n'
+import { unitLabel } from '../i18n/units'
+import { decimalSep } from './format'
+import { rowSum, type Row } from './rows'
+
+type Value = string | number | undefined
+
+export type CsvColumn = { title: string; value: (r: Row, n: number) => Value; total?: boolean }
+
+export type CsvFilter = (r: Row) => boolean
+
+const petrovichSku = (url?: string) => url?.match(/petrovich\.ru\/(?:product|catalog\/\d+)\/(\d+)/)?.[1]
+
+export const rowSku = (r: Row) => r.sku ?? petrovichSku(r.url)
+
+export const isPetrovich = (r: Row) => !!r.vendor?.includes('Петрович') || !!r.url?.includes('petrovich.ru')
+
+export const sectionOf = (r: Row) => r.group ?? (r.line ? t('estimate:sections.manual') : t('estimate:sections.auto'))
+
+export const COLUMNS = {
+ section: { get title() { return t('estimate:csv.columns.section') }, value: (r) => sectionOf(r) },
+ n: { get title() { return t('estimate:csv.columns.n') }, value: (_, n) => n },
+ name: { get title() { return t('estimate:csv.columns.name') }, value: (r) => r.name },
+ sku: { get title() { return t('estimate:csv.columns.sku') }, value: rowSku },
+ qty: { get title() { return t('estimate:csv.columns.qty') }, value: (r) => r.qty },
+ unit: { get title() { return t('estimate:csv.columns.unit') }, value: (r) => unitLabel(r.unit) },
+ price: { get title() { return t('estimate:csv.columns.price') }, value: (r) => r.price },
+ sum: { get title() { return t('estimate:csv.columns.sum') }, value: (r) => (r.price !== undefined ? rowSum(r) : undefined), total: true },
+ bought: { get title() { return t('estimate:csv.columns.bought') }, value: (r) => (r.bought ? t('estimate:csv.yes') : t('estimate:csv.no')) },
+ url: { get title() { return t('estimate:csv.columns.url') }, value: (r) => r.url },
+ note: { get title() { return t('estimate:csv.columns.note') }, value: (r) => [r.note, r.priceFrom].filter(Boolean).join(' · ') || undefined },
+} satisfies Record<string, CsvColumn>
+
+export const FULL_COLUMNS: CsvColumn[] = Object.values(COLUMNS)
+
+export const FILTERS = {
+ all: () => true,
+ petrovichLeft: (r) => isPetrovich(r) && !r.bought,
+} satisfies Record<string, CsvFilter>
+
+const csvSep = () => (decimalSep() === ',' ? ';' : ',')
+
+const cell = (v: Value) => {
+ if (v === undefined) return ''
+ const s = typeof v === 'number' ? String(Math.round(v * 100) / 100).replace('.', decimalSep()) : v
+ return /[;,"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
+}
+
+export function toCsv(rows: Row[], columns: CsvColumn[] = FULL_COLUMNS, filter: CsvFilter = FILTERS.all, totals = true) {
+ const lines: Value[][] = [columns.map((c) => c.title)]
+ const picked = rows.filter(filter)
+ const sections = [...new Set(picked.map(sectionOf))]
+ const totalRow = (label: string, list: Row[]) =>
+ columns.map((c, i) => (c.total ? list.reduce((s, r) => s + rowSum(r), 0) : i === 0 ? label : undefined))
+ let n = 0
+ for (const sec of sections) {
+ const list = picked.filter((r) => sectionOf(r) === sec)
+ for (const r of list) lines.push(columns.map((c) => c.value(r, ++n)))
+ if (totals) lines.push(totalRow(t('estimate:csv.sectionTotal', { section: sec }), list))
+ }
+ if (totals) lines.push(totalRow(t('estimate:csv.total'), picked))
+ return '' + lines.map((l) => l.map(cell).join(csvSep())).join('\r\n')
+}
+
+export function downloadCsv(name: string, text: string) {
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/csv;charset=utf-8' }))
+ const a = document.createElement('a')
+ a.href = url
+ a.download = name
+ a.click()
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
+}
diff --git a/src/estimate/estimate.css b/src/estimate/estimate.css
new file mode 100644
index 0000000..2e5687a
--- /dev/null
+++ b/src/estimate/estimate.css
@@ -0,0 +1,490 @@
+.est {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: var(--space-2) 0 var(--space-6);
+}
+
+.est-tools {
+ display: flex;
+ justify-content: flex-end;
+ gap: var(--space-4);
+ width: 100%;
+ max-width: 800px;
+ margin-bottom: var(--space-2);
+}
+
+.est-tool {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--muted);
+ font: inherit;
+ font-size: var(--text-sm);
+ text-decoration: underline;
+ text-decoration-color: var(--line-strong);
+ text-underline-offset: 3px;
+ cursor: pointer;
+}
+
+.est-tool:hover {
+ color: var(--accent);
+ text-decoration-color: var(--accent);
+}
+
+.est-sheet {
+ width: 100%;
+ max-width: 800px;
+ min-height: 1131px;
+ padding: 56px 64px;
+ background: var(--surface);
+ box-shadow: var(--shadow);
+ color: var(--ink);
+}
+
+.est-head {
+ margin-bottom: var(--space-5);
+}
+
+.est-head__title {
+ margin: 0;
+ font-size: var(--text-xl);
+ font-weight: 700;
+}
+
+.est-head__sub {
+ margin-top: var(--space-1);
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.est-table {
+ table-layout: fixed;
+}
+
+.est-col--n {
+ width: 32px;
+}
+
+.est-col--check {
+ width: 32px;
+}
+
+.est-col--qty {
+ width: 72px;
+}
+
+.est-col--unit {
+ width: 56px;
+}
+
+.est-col--price {
+ width: 96px;
+}
+
+.est-col--sum {
+ width: 108px;
+}
+
+.est-col--del {
+ width: 32px;
+}
+
+.est-table th {
+ position: static;
+ padding: var(--space-2) 6px;
+ border-bottom: 1px solid var(--ink-2);
+ background: none;
+}
+
+.est-table td {
+ padding: 7px 6px;
+ vertical-align: top;
+}
+
+.est-table tbody tr:hover td {
+ background: none;
+}
+
+.est-table .checkbox {
+ margin-top: 1px;
+}
+
+.est-link {
+ color: inherit;
+ text-decoration: underline;
+ text-decoration-color: var(--line-strong);
+ text-underline-offset: 3px;
+}
+
+.est-link:hover {
+ color: var(--accent);
+ text-decoration-color: var(--accent);
+}
+
+.est-from {
+ margin-top: 2px;
+ overflow: hidden;
+ color: var(--muted);
+ font-size: var(--text-xs);
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.est-name {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+}
+
+.est-name__go {
+ flex: none;
+ color: var(--muted);
+}
+
+.est-name__go:hover {
+ color: var(--accent);
+ text-decoration: none;
+}
+
+.est-cell {
+ width: 100%;
+ min-width: 0;
+ margin: -2px 0;
+ padding: 1px 0;
+ border: 0;
+ border-bottom: 1px dashed var(--line-strong);
+ background: none;
+ color: inherit;
+ font: inherit;
+ outline: 0;
+}
+
+.est-cell:focus {
+ border-bottom: 1px solid var(--accent);
+}
+
+.est-cell--num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+.est-cell::placeholder {
+ color: var(--muted);
+}
+
+.est-del {
+ text-align: center;
+}
+
+.est-table td.est-del {
+ padding: 2px 0;
+}
+
+.est-total td {
+ padding: 10px 6px;
+ vertical-align: baseline;
+ border-top: 1px solid var(--ink-2);
+ border-bottom: 0;
+ font-weight: 700;
+}
+
+.est-group td {
+ padding: 14px 6px 6px;
+ border-bottom: 1px solid var(--line-strong);
+ font-weight: 700;
+ font-size: var(--text-md);
+}
+
+.est-add {
+ margin-top: var(--space-2);
+ color: var(--muted);
+}
+
+.est-print {
+ display: none;
+}
+
+@media screen and (max-width: 720px) {
+ .est {
+ padding: 0;
+ }
+
+ .est-tools {
+ padding: var(--space-2) var(--space-3) 0;
+ }
+
+ .est-sheet {
+ min-height: 0;
+ padding: var(--space-5) var(--space-3);
+ }
+
+ .est-head {
+ margin-bottom: var(--space-3);
+ }
+
+ .est-table {
+ font-size: var(--text-xs);
+ }
+
+ .est-table th {
+ padding: 6px 3px;
+ font-size: 9px;
+ letter-spacing: 0;
+ white-space: normal;
+ }
+
+ .est-table td {
+ padding: 6px 3px;
+ }
+
+ .est-col--n {
+ width: 0;
+ }
+
+ .est-table tr > :first-child {
+ padding: 0;
+ font-size: 0;
+ }
+
+ .est-col--check {
+ width: 22px;
+ }
+
+ .est-col--qty {
+ width: 34px;
+ }
+
+ .est-col--unit {
+ width: 30px;
+ }
+
+ .est-col--price {
+ width: 58px;
+ }
+
+ .est-col--sum {
+ width: 68px;
+ }
+
+ .est-col--del {
+ width: 20px;
+ }
+
+ .est-table .num {
+ white-space: normal;
+ }
+
+ .est-total td {
+ padding: 8px 3px;
+ }
+
+ .est-total td:first-child {
+ font-size: var(--text-xs);
+ padding-left: 3px;
+ }
+}
+
+@media print {
+ @page {
+ size: A4;
+ margin: 15mm 14mm;
+ }
+
+ html:has(.est-sheet),
+ html:has(.est-sheet) body,
+ html:has(.est-sheet) #root {
+ height: auto;
+ overflow: visible;
+ background: var(--surface);
+ }
+
+ body:has(.est-sheet) .overlay,
+ .est-tools,
+ .est-add,
+ .est-del > * {
+ display: none;
+ }
+
+ .est-col--del {
+ width: 0;
+ }
+
+ .est-table .est-del {
+ padding: 0;
+ }
+
+ body:has(.est-sheet) .app,
+ body:has(.est-sheet) .page {
+ position: static;
+ height: auto;
+ overflow: visible;
+ padding: 0;
+ }
+
+ .est {
+ display: block;
+ padding: 0;
+ }
+
+ .est-sheet {
+ max-width: none;
+ min-height: 0;
+ padding: 0;
+ box-shadow: none;
+ }
+
+ .est-cell {
+ display: none;
+ }
+
+ .est-print {
+ display: inline;
+ }
+
+ .est .checkbox__box {
+ print-color-adjust: exact;
+ }
+
+ .est-table tr {
+ break-inside: avoid;
+ }
+}
+
+.est-note {
+ margin-top: 2px;
+ color: var(--muted);
+ font-size: var(--text-xs);
+}
+
+.est-block {
+ margin-top: var(--space-5);
+}
+
+.est-block__title {
+ margin: 0 0 var(--space-2);
+ padding-bottom: var(--space-1);
+ border-bottom: 1px solid var(--ink-2);
+ font-size: var(--text-md);
+ font-weight: 700;
+}
+
+.est-colors {
+ border-collapse: collapse;
+ font-size: 13px;
+}
+
+.est-colors td {
+ padding: 5px var(--space-3) 5px 0;
+ border-bottom: 1px solid var(--line);
+ vertical-align: middle;
+}
+
+.est-colors__what {
+ min-width: 160px;
+}
+
+.est-colors__code {
+ white-space: nowrap;
+ font-variant-numeric: tabular-nums;
+}
+
+.est-colors__name {
+ color: var(--muted);
+}
+
+.est-swatch {
+ display: inline-block;
+ width: 14px;
+ height: 14px;
+ margin-right: var(--space-2);
+ border: 1px solid var(--line-strong);
+ border-radius: 3px;
+ vertical-align: -2px;
+ print-color-adjust: exact;
+}
+
+.est-notes {
+ margin: 0;
+ padding-left: 22px;
+ font-size: 13px;
+}
+
+.est-notes li {
+ padding: 4px 0;
+}
+
+.est-empty-note {
+ margin: 0;
+ color: var(--muted);
+ font-size: 13px;
+}
+
+.est-dialog {
+ width: min(520px, calc(100vw - 32px));
+ border: 0;
+ color: var(--ink);
+ box-shadow: var(--shadow-lg);
+}
+
+.est-dialog::backdrop {
+ background: color-mix(in srgb, var(--ink) 35%, transparent);
+}
+
+.est-dialog__head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ margin-bottom: var(--space-3);
+}
+
+.est-dialog__title {
+ margin: 0;
+ font-size: var(--text-lg);
+ font-weight: 700;
+}
+
+.est-dialog__sections {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: var(--space-2) var(--space-4);
+ margin: var(--space-4) 0 var(--space-3);
+}
+
+.est-dialog__actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin-top: var(--space-4);
+}
+
+.est-dialog__hint {
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.est-dialog__links {
+ margin: var(--space-4) 0 0;
+ padding: 0;
+ list-style: none;
+}
+
+.est-dialog__links li {
+ display: flex;
+ align-items: baseline;
+ gap: var(--space-3);
+ padding: 6px 0;
+ border-bottom: 1px solid var(--line);
+ font-size: 13px;
+}
+
+.est-dialog__section {
+ flex: 1;
+}
+
+.est-dialog__missing {
+ margin-top: var(--space-3);
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
diff --git a/src/estimate/format.ts b/src/estimate/format.ts
new file mode 100644
index 0000000..505eede
--- /dev/null
+++ b/src/estimate/format.ts
@@ -0,0 +1,27 @@
+import { fmtDateTime, fmtNum as fmtNumber, fmtRub as fmtRubles, lang } from '../i18n'
+
+export const fmtRub = (v: number) => fmtRubles(v)
+export const fmtNum = (v: number) => fmtNumber(v, 2)
+
+export const today = () => {
+ const d = new Date()
+ const p = (n: number) => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
+}
+
+export const fmtDate = (iso: string) => {
+ const [y, m, d] = iso.split('-').map(Number)
+ if (!y || !m || !d) return iso
+ return fmtDateTime(new Date(y, m - 1, d), { year: 'numeric', month: '2-digit', day: '2-digit' })
+}
+
+export const parseNum = (s: string): number | undefined => {
+ const t = s.replace(/\s/g, '').replace(',', '.')
+ if (t === '') return undefined
+ const v = Number(t)
+ return Number.isFinite(v) && v >= 0 ? v : undefined
+}
+
+export const decimalSep = () => (lang() === 'ru' ? ',' : '.')
+
+export const numText = (v: number | undefined) => (v === undefined ? '' : String(v).replace('.', decimalSep()))
diff --git a/src/estimate/index.tsx b/src/estimate/index.tsx
new file mode 100644
index 0000000..c0f5857
--- /dev/null
+++ b/src/estimate/index.tsx
@@ -0,0 +1,328 @@
+import { Fragment, useMemo, useState, type InputHTMLAttributes } from 'react'
+import { useTranslation } from 'react-i18next'
+import { t as tr } from '../i18n'
+import { unitLabel } from '../i18n/units'
+import type { Plan } from '../model'
+import { useViewOnly } from '../store/viewOnly'
+import { RAL_CLASSIC, ralCode, ralLabel } from '../view3d/ral'
+import { Button, Checkbox, IconButton, Table, Td, Th, Tr } from '../ui'
+import { downloadCsv, toCsv } from './csv'
+import type { PetrovichLink } from './petrovich'
+import { PetrovichCart } from './PetrovichCart'
+import { useCatalog, type CatalogItem } from './catalog'
+import { fmtDate, fmtNum, fmtRub, numText, parseNum, today } from './format'
+import { buildRows, estimateOf, newLineId, removeLine, rowSum, setPurchase, upsertLine, withEstimate, type Row } from './rows'
+import './estimate.css'
+
+type Props = {
+ plan: Plan
+ onChange: (next: Plan) => void
+}
+
+type CellProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> & {
+ value: string
+ onCommit: (value: string) => void
+}
+
+function Cell({ value, onCommit, className, ...rest }: CellProps) {
+ const [draft, setDraft] = useState(value)
+ const [synced, setSynced] = useState(value)
+ if (synced !== value) {
+ setSynced(value)
+ setDraft(value)
+ }
+ return (
+ <>
+ <span className={`est-print ${className ?? ''}`}>{value}</span>
+ <input
+ className={`est-cell ${className ?? ''}`}
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={() => draft !== value && onCommit(draft)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.currentTarget.blur()
+ if (e.key === 'Escape') setDraft(value)
+ }}
+ {...rest}
+ />
+ </>
+ )
+}
+
+const newLineName = () => tr('estimate:page.newLine')
+
+const PALETTE_SLOTS = ['walls', 'gates', 'roof', 'windows', 'accent', 'plinth'] as const
+
+function Colors({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('estimate')
+ const palette = plan.palette ?? {}
+ const items: { label: string; code: string }[] = []
+ for (const key of PALETTE_SLOTS) {
+ const label = t(`colors.slots.${key}`)
+ const code = ralCode(palette[key])
+ if (!code) continue
+ const prev = items.at(-1)
+ if (prev && prev.code === code && (key === 'gates' || key === 'plinth')) prev.label = t('colors.joined', { a: prev.label, b: label.toLowerCase() })
+ else items.push({ label, code })
+ }
+ return (
+ <section className="est-block">
+ <h2 className="est-block__title">{t('colors.title')}{palette.name ? ` · ${palette.name}` : ''}</h2>
+ {items.length ? (
+ <table className="est-colors">
+ <tbody>
+ {items.map((c) => (
+ <tr key={c.label}>
+ <td className="est-colors__what">{c.label}</td>
+ <td className="est-colors__code">
+ <span className="est-swatch" style={{ background: RAL_CLASSIC[c.code][0] }} aria-hidden />
+ {ralLabel(c.code)}
+ </td>
+ <td className="est-colors__name">{RAL_CLASSIC[c.code][1]}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ ) : (
+ <p className="est-empty-note">{t('colors.empty')}</p>
+ )}
+ </section>
+ )
+}
+
+export default function EstimatePage({ plan, onChange }: Props) {
+ const { t } = useTranslation('estimate')
+ const catalog = useCatalog()
+ const viewOnly = useViewOnly()
+ const [focusId, setFocusId] = useState<string | null>(null)
+ const rows = useMemo(() => buildRows(plan, catalog), [plan, catalog])
+ const total = rows.reduce((s, r) => s + rowSum(r), 0)
+ const purchases = estimateOf(plan).purchases
+
+ const commit = (fn: Parameters<typeof withEstimate>[1]) => onChange(withEstimate(plan, fn))
+
+ const toggle = (r: Row, done: boolean) =>
+ commit((e) => setPurchase(e, r.id, done ? { done: true, date: today() } : undefined))
+
+ const patch = (r: Row, p: Partial<NonNullable<Row['line']>>) => {
+ const line = r.line
+ if (line) commit((e) => upsertLine(e, { ...line, ...p }))
+ }
+
+ const pickName = (r: Row, name: string) => {
+ const c: CatalogItem | undefined = catalog.find((x) => x.name === name)
+ if (c) patch(r, { name: c.name, unit: c.unit, price: c.price, url: c.url })
+ else if (name.trim()) patch(r, { name: name.trim() })
+ }
+
+ const notes = estimateOf(plan).notes ?? []
+ const [noteFocus, setNoteFocus] = useState<number | null>(null)
+
+ const setNote = (i: number, v: string) =>
+ commit((e) => {
+ const next = [...(e.notes ?? [])]
+ if (v.trim()) next[i] = v.trim()
+ else next.splice(i, 1)
+ return { ...e, notes: next }
+ })
+
+ const addNote = () => {
+ commit((e) => ({ ...e, notes: [...(e.notes ?? []), t('page.newNote')] }))
+ setNoteFocus(notes.length)
+ }
+
+ const add = () => {
+ const id = newLineId(estimateOf(plan))
+ commit((e) => upsertLine(e, { id, category: 'прочее', name: newLineName(), qty: 1, unit: tr('common:units.pcs') }))
+ setFocusId(id)
+ }
+
+ return (
+ <div className="est">
+ <div className="est-tools">
+ <button type="button" className="est-tool" onClick={() => downloadCsv(t('csv.fileName', { date: today() }), toCsv(rows))}>
+ {t('page.downloadCsv')}
+ </button>
+ <PetrovichCart
+ rows={rows}
+ saved={(estimateOf(plan).petrovichLinks as PetrovichLink[] | undefined) ?? []}
+ onSave={(links) => commit((e) => ({ ...e, petrovichLinks: links }))}
+ />
+ </div>
+ <article className="est-sheet">
+ <header className="est-head">
+ <h1 className="est-head__title">{t('page.title')}</h1>
+ <div className="est-head__sub">{plan.name}</div>
+ </header>
+
+ <Table className="est-table">
+ <colgroup>
+ <col className="est-col--n" />
+ <col className="est-col--check" />
+ <col />
+ <col className="est-col--qty" />
+ <col className="est-col--unit" />
+ <col className="est-col--price" />
+ <col className="est-col--sum" />
+ <col className="est-col--del" />
+ </colgroup>
+ <thead>
+ <tr>
+ <Th num>{t('columns.n')}</Th>
+ <Th aria-label={t('page.bought')} />
+ <Th>{t('columns.name')}</Th>
+ <Th num>{t('columns.qty')}</Th>
+ <Th>{t('columns.unit')}</Th>
+ <Th num>{t('columns.price')}</Th>
+ <Th num>{t('columns.sum')}</Th>
+ <Th className="est-del" aria-label={t('page.delete')} />
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r, i) => {
+ const date = purchases[r.id]?.date
+ const heading = r.group && r.group !== rows[i - 1]?.group
+ return (
+ <Fragment key={r.id}>
+ {heading && (
+ <tr className="est-group">
+ <td colSpan={8}>{r.group}</td>
+ </tr>
+ )}
+ <Tr muted={r.bought}>
+ <Td num>{i + 1}</Td>
+ <Td>
+ <Checkbox
+ checked={r.bought}
+ disabled={viewOnly}
+ onChange={(done) => toggle(r, done)}
+ aria-label={r.bought ? t('page.bought') : t('page.markBought')}
+ title={r.bought && date ? t('page.boughtOn', { date: fmtDate(date) }) : undefined}
+ />
+ </Td>
+ <Td>
+ {!viewOnly && r.line ? (
+ <div className="est-name">
+ <Cell
+ value={r.name}
+ list="est-catalog"
+ autoFocus={focusId === r.id}
+ onFocus={(e) => e.target.value === newLineName() && e.target.select()}
+ onCommit={(v) => pickName(r, v)}
+ />
+ {r.url && (
+ <a className="est-name__go" href={r.url} target="_blank" rel="noreferrer" aria-label={t('page.openInStore')}>
+ ↗
+ </a>
+ )}
+ </div>
+ ) : (
+ <>
+ {r.url ? (
+ <a href={r.url} target="_blank" rel="noreferrer" className="est-link">
+ {r.name}
+ </a>
+ ) : (
+ r.name
+ )}
+ {r.priceFrom && (
+ <div className="est-from" title={r.priceFrom}>
+ {r.priceFrom}
+ </div>
+ )}
+ </>
+ )}
+ {r.note && <div className="est-note">{r.note}</div>}
+ </Td>
+ <Td num>
+ {!viewOnly && r.line ? (
+ <Cell
+ className="est-cell--num"
+ inputMode="decimal"
+ value={numText(r.qty)}
+ onCommit={(v) => patch(r, { qty: parseNum(v) ?? 0 })}
+ />
+ ) : (
+ fmtNum(r.qty)
+ )}
+ </Td>
+ <Td>{!viewOnly && r.line ? <Cell value={unitLabel(r.unit)} onCommit={(v) => patch(r, { unit: v.trim() || tr('common:units.pcs') })} /> : unitLabel(r.unit)}</Td>
+ <Td num>
+ {!viewOnly && r.line ? (
+ <Cell
+ className="est-cell--num"
+ inputMode="decimal"
+ placeholder="—"
+ value={numText(r.price)}
+ onCommit={(v) => patch(r, { price: parseNum(v) })}
+ />
+ ) : r.price !== undefined ? (
+ fmtRub(r.price)
+ ) : (
+ '—'
+ )}
+ </Td>
+ <Td num>{r.price !== undefined ? fmtRub(rowSum(r)) : '—'}</Td>
+ <Td className="est-del">
+ {!viewOnly && r.line && (
+ <IconButton
+ size="sm"
+ label={t('page.deleteLine')}
+ onClick={() => {
+ if (window.confirm(t('page.confirmDelete', { name: r.name }))) commit((e) => removeLine(e, r.id))
+ }}
+ >
+ ×
+ </IconButton>
+ )}
+ </Td>
+ </Tr>
+ </Fragment>
+ )
+ })}
+ </tbody>
+ <tfoot>
+ <tr className="est-total">
+ <td colSpan={6}>{t('page.total')}</td>
+ <td className="num">{fmtRub(total)}</td>
+ <td className="est-del" />
+ </tr>
+ </tfoot>
+ </Table>
+
+ {!viewOnly && (
+ <Button variant="ghost" size="sm" className="est-add" onClick={add}>
+ {t('page.addLine')}
+ </Button>
+ )}
+
+ <Colors plan={plan} />
+
+ <section className="est-block">
+ <h2 className="est-block__title">{t('page.notesTitle')}</h2>
+ {notes.length > 0 && (
+ <ol className="est-notes">
+ {notes.map((n, i) => (
+ <li key={i}>
+ {viewOnly ? n : <Cell value={n} onCommit={(v) => setNote(i, v)} autoFocus={noteFocus === i} />}
+ </li>
+ ))}
+ </ol>
+ )}
+ {!notes.length && viewOnly && <p className="est-empty-note">{t('page.noNotes')}</p>}
+ {!viewOnly && (
+ <Button variant="ghost" size="sm" className="est-add" onClick={addNote}>
+ {t('page.addNote')}
+ </Button>
+ )}
+ </section>
+ </article>
+
+ <datalist id="est-catalog">
+ {catalog.map((c) => (
+ <option key={c.id} value={c.name} label={`${c.vendor ?? ''} · ${fmtRub(c.price)}/${unitLabel(c.unit)}`} />
+ ))}
+ </datalist>
+ </div>
+ )
+}
diff --git a/src/estimate/petrovich.ts b/src/estimate/petrovich.ts
new file mode 100644
index 0000000..99dc04b
--- /dev/null
+++ b/src/estimate/petrovich.ts
@@ -0,0 +1,96 @@
+import { t } from '../i18n'
+import { CLIENT_VERSION } from '../model'
+import { showToast } from '../ui/Toast'
+import { rowSku, isPetrovich } from './csv'
+import type { Row } from './rows'
+
+export const CART_SECTIONS = ['house', 'garage', 'electric', 'sewer', 'water', 'heating', 'other'] as const
+export type CartSection = (typeof CART_SECTIONS)[number]
+
+export const cartSectionLabel = (s: CartSection) => t(`estimate:cart.sections.${s}`)
+
+const NETWORK_SECTIONS = ['electric', 'sewer', 'water', 'heating'] as const
+
+export type City = 'vbg' | 'spb'
+
+export type CartItem = { code: string; qty: number; name: string }
+
+export type CartResult = {
+ section: string
+ url?: string
+ count: number
+ added?: number
+ missing: string[]
+ error?: string
+}
+
+export type PetrovichLink = { section: string; url: string; createdAt: string; count: number }
+
+export function cartSection(r: Row): CartSection {
+ const net = NETWORK_SECTIONS.find((s) => r.id.startsWith(`auto:${s}:`))
+ if (net) return net
+ const g = CART_SECTIONS.find((s) => r.group === cartSectionLabel(s))
+ if (g) return g
+ if (r.id.startsWith('auto:gate')) return 'garage'
+ if (r.id.startsWith('auto:')) return 'house'
+ return 'other'
+}
+
+export function cartItems(rows: Row[]): CartItem[] {
+ const byCode = new Map<string, CartItem>()
+ for (const r of rows) {
+ const code = rowSku(r)
+ if (!code || !isPetrovich(r) || r.qty <= 0) continue
+ const it = byCode.get(code)
+ if (it) it.qty += r.qty
+ else byCode.set(code, { code, qty: r.qty, name: r.name })
+ }
+ return [...byCode.values()].map((i) => ({ ...i, qty: Math.ceil(i.qty - 1e-9) }))
+}
+
+const missingNames = (v: unknown, items: CartItem[]) => {
+ if (!Array.isArray(v)) return []
+ return v.map((m) => {
+ if (typeof m === 'string') return items.find((i) => i.code === m)?.name ?? m
+ const o = (m ?? {}) as { code?: string; name?: string; reason?: string }
+ const name = o.name ?? items.find((i) => i.code === o.code)?.name ?? o.code ?? '?'
+ return o.reason ? `${name} — ${o.reason}` : name
+ })
+}
+
+let reloading = false
+function reloadOutdated() {
+ if (reloading) return
+ reloading = true
+ showToast(t('estimate:cart.outdated'))
+ setTimeout(() => location.reload(), 1000)
+}
+
+export async function buildCart(section: string, city: City, items: CartItem[]): Promise<CartResult> {
+ try {
+ const res = await fetch(`${import.meta.env.BASE_URL}api/petrovich-cart.php`, {
+ method: 'POST',
+ credentials: 'same-origin',
+ cache: 'no-store',
+ headers: {
+ 'X-Requested-With': 'fetch',
+ 'X-Client-Version': String(CLIENT_VERSION),
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ city, items }),
+ })
+ if (res.status === 426) {
+ reloadOutdated()
+ return { section, count: items.length, missing: [], error: t('estimate:cart.outdated') }
+ }
+ const data = (await res.json().catch(() => ({}))) as { url?: string; added?: unknown; missing?: unknown; error?: string }
+ if (!res.ok || !data.url) {
+ return { section, count: items.length, missing: missingNames(data.missing, items), error: data.error ?? `HTTP ${res.status}` }
+ }
+ const added = typeof data.added === 'number' ? data.added : Array.isArray(data.added) ? data.added.length : undefined
+ return { section, url: data.url, count: items.length, added, missing: missingNames(data.missing, items) }
+ } catch (e) {
+ return { section, count: items.length, missing: [], error: (e as Error).message }
+ }
+}
diff --git a/src/estimate/rows.ts b/src/estimate/rows.ts
new file mode 100644
index 0000000..889dfa7
--- /dev/null
+++ b/src/estimate/rows.ts
@@ -0,0 +1,124 @@
+import { computeWallEstimate, unitLabels, type Estimate, type EstimateLine, type Plan, type Purchase } from '../model'
+import { t } from '../i18n'
+import { findOpening, findPanel, type CatalogItem } from './catalog'
+import { sewerEstimateRows, waterEstimateRows } from '../networks/estimate'
+import { electricEstimateRows } from '../networks/electric/estimate'
+import { heatingEstimateRows } from '../networks/heating/estimate'
+
+export type Row = {
+ id: string
+ name: string
+ url?: string
+ qty: number
+ unit: string
+ price?: number
+ priceFrom?: string
+ note?: string
+ line?: EstimateLine
+ group?: string
+ sku?: string
+ vendor?: string
+ bought: boolean
+}
+
+export const estimateOf = (plan: Plan): Estimate => ({
+ ...plan.estimate,
+ lines: plan.estimate?.lines ?? [],
+ purchases: plan.estimate?.purchases ?? {},
+ ...(plan.estimate?.wasteSipPct !== undefined ? { wasteSipPct: plan.estimate.wasteSipPct } : {}),
+})
+
+const isAutoId = (id: string) => id.startsWith('auto:')
+
+const fromCatalog = (c: CatalogItem) => `${c.name}${c.vendor ? `, ${c.vendor}` : ''}`
+
+function wallRows(plan: Plan, catalog: CatalogItem[]): Omit<Row, 'bought'>[] {
+ return computeWallEstimate(plan).lines.map((l) => {
+ const m = l.material
+ const usePanels = l.qty === null && l.panelsWithWaste !== undefined
+ const qty = usePanels ? l.panelsWithWaste! : (l.qty ?? 0)
+ const unit = usePanels ? 'pcs' : l.unit
+ const row: Omit<Row, 'bought'> = {
+ id: l.id,
+ name: l.name,
+ url: l.url,
+ qty,
+ unit: unit ? unitLabels[unit] : t('common:units.pcs'),
+ price: l.price,
+ }
+ if (row.price !== undefined || !m || (m.kind !== 'sip' && m.kind !== 'pir')) return row
+ const found = findPanel(catalog, m.kind, m.thickness, m.panelWidth ?? m.length, m.panelHeight ?? m.height)
+ if (!found) return row
+ const price = unit === 'pcs' ? found.perPiece : unit === 'm2' ? found.perM2 : undefined
+ if (price === undefined) return row
+ const c = found.item
+ return { ...row, price: Math.round(price), url: row.url ?? c.url, sku: c.sku, vendor: c.vendor, priceFrom: t('estimate:rows.priceBy', { item: fromCatalog(c) }) }
+ })
+}
+
+function openingRows(plan: Plan, catalog: CatalogItem[]): Omit<Row, 'bought'>[] {
+ const groups = new Map<string, { type: 'door' | 'window' | 'gate'; width: number; height: number; count: number }>()
+ for (const o of plan.openings) {
+ const key = `${o.type}:${o.width}x${o.height}`
+ const g = groups.get(key) ?? { type: o.type, width: o.width, height: o.height, count: 0 }
+ g.count += 1
+ groups.set(key, g)
+ }
+ return [...groups.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([key, g]) => {
+ const m = findOpening(catalog, g.type, g.width, g.height)
+ const c = m?.item
+ return {
+ id: `auto:${key}`,
+ name: t(`estimate:rows.${g.type}`, { w: g.width, h: g.height }),
+ url: c?.url,
+ qty: g.count,
+ unit: t('common:units.pcs'),
+ price: m?.price,
+ sku: c?.sku,
+ vendor: c?.vendor,
+ priceFrom: m && (m.exact ? t('estimate:rows.priceBy', { item: fromCatalog(m.item) }) : t('estimate:rows.areaEstimate', { w: c!.length, h: c!.height, item: fromCatalog(m.item) })),
+ }
+ })
+}
+
+export function buildRows(plan: Plan, catalog: CatalogItem[]): Row[] {
+ const est = estimateOf(plan)
+ const manual = est.lines
+ .filter((l) => !isAutoId(l.id))
+ .map((l) => ({ id: l.id, name: l.name, url: l.url, qty: l.qty, unit: l.unit, price: l.price, note: l.note, line: l }))
+ return [...wallRows(plan, catalog), ...openingRows(plan, catalog), ...manual, ...sewerEstimateRows(plan, catalog), ...waterEstimateRows(plan, catalog), ...electricEstimateRows(plan, catalog), ...heatingEstimateRows(plan, catalog)].map((r) => ({
+ ...r,
+ bought: !!est.purchases[r.id]?.done,
+ }))
+}
+
+export const rowSum = (r: Row) => (r.price ?? 0) * r.qty
+
+export const withEstimate = (plan: Plan, patch: (e: Estimate) => Estimate): Plan => ({
+ ...plan,
+ estimate: patch(estimateOf(plan)),
+})
+
+export const setPurchase = (e: Estimate, id: string, p: Purchase | undefined): Estimate => {
+ const purchases = { ...e.purchases }
+ if (p) purchases[id] = p
+ else delete purchases[id]
+ return { ...e, purchases }
+}
+
+export const upsertLine = (e: Estimate, line: EstimateLine): Estimate => ({
+ ...e,
+ lines: e.lines.some((l) => l.id === line.id) ? e.lines.map((l) => (l.id === line.id ? line : l)) : [...e.lines, line],
+})
+
+export const removeLine = (e: Estimate, id: string): Estimate =>
+ setPurchase({ ...e, lines: e.lines.filter((l) => l.id !== id) }, id, undefined)
+
+export function newLineId(e: Estimate) {
+ const used = new Set(e.lines.map((l) => l.id))
+ let n = e.lines.length + 1
+ while (used.has(`l${n}`)) n += 1
+ return `l${n}`
+}
diff --git a/src/furniture/Model3D.tsx b/src/furniture/Model3D.tsx
new file mode 100644
index 0000000..17609c0
--- /dev/null
+++ b/src/furniture/Model3D.tsx
@@ -0,0 +1,143 @@
+import { Suspense, memo, useMemo } from 'react'
+import { useGLTF } from '@react-three/drei'
+import * as THREE from 'three'
+import { resolveFurniture, type FurnitureItem } from './catalog'
+import { CHAIR, diningLayout, isDining } from './layout'
+import { finishMaterial, kenneyFinish, type Finish, type FurnitureLook } from './materials3d'
+import { ProceduralFurniture, hasProcedural } from './procedural'
+import { KENNEY_MODELS, type KenneySpec } from './models'
+
+const M = 0.001
+
+export const FURNITURE_MODELS_BASE = `${import.meta.env.BASE_URL}models/furniture/`
+
+export type FurnitureModelProps = {
+ item: FurnitureItem
+ look?: FurnitureLook
+ baseY?: number
+ placed?: boolean
+ modelsBase?: string
+ castShadow?: boolean
+}
+
+
+export const FurnitureModel = memo(function FurnitureModel({
+ item,
+ look = 'real',
+ baseY = 0,
+ placed = true,
+ modelsBase = FURNITURE_MODELS_BASE,
+ castShadow = true,
+}: FurnitureModelProps) {
+ const { w, d, h, elevation } = resolveFurniture(item)
+ const body = <FurnitureBody type={item.type} w={w} d={d} h={h} look={look} color={item.color} base={modelsBase} shadow={castShadow} />
+ if (!placed) return elevation ? <group position={[0, baseY + elevation * M, 0]}>{body}</group> : body
+ return (
+ <group position={[item.x * M, baseY + elevation * M, item.y * M]} rotation={[0, (-item.rotationDeg * Math.PI) / 180, 0]}>
+ {body}
+ </group>
+ )
+})
+
+type BodyProps = { type: string; w: number; d: number; h: number; look: FurnitureLook; color?: string; base: string; shadow: boolean }
+
+function FurnitureBody({ type, w, d, h, look, color, base, shadow }: BodyProps) {
+ if (isDining(type)) return <Dining type={type} w={w} d={d} h={h} look={look} color={color} base={base} shadow={shadow} />
+ if (type === 'tv-stand') {
+ const standH = Math.min(520, h * 0.4)
+ const tvW = Math.min(w * 0.85, 1450)
+ return (
+ <>
+ <Fitted spec={KENNEY_MODELS['tv-stand']} w={w} d={d} h={standH} look={look} color={color} base={base} shadow={shadow} />
+ <group position={[0, standH * M, (-d / 2 + 140) * M]}>
+ <Fitted spec={KENNEY_MODELS.tv} w={tvW} d={220} h={Math.min(h - standH, tvW * 0.6)} look={look} base={base} shadow={shadow} />
+ </group>
+ </>
+ )
+ }
+ const spec = KENNEY_MODELS[type]
+ if (spec) return <Fitted spec={spec} w={w} d={d} h={h} look={look} color={color} base={base} shadow={shadow} />
+ if (hasProcedural(type)) {
+ return <ProceduralFurniture type={type} w={w} d={d} h={h} paint={{ look, color, primary: ['wood', 'textile', 'plaster', 'brick'] }} />
+ }
+ return <ProceduralFurniture type="generic" w={w} d={d} h={h} paint={{ look, color, primary: ['white'] }} />
+}
+
+function Dining({ type, w, d, h, look, color, base, shadow }: BodyProps) {
+ const lay = diningLayout(type, w, d)
+ return (
+ <>
+ {lay.round ? (
+ <ProceduralFurniture type="table-round" w={lay.table.w} d={lay.table.d} h={h} paint={{ look, color, primary: ['wood'] }} />
+ ) : (
+ <Fitted spec={KENNEY_MODELS.table} w={lay.table.w} d={lay.table.d} h={h} look={look} color={color} base={base} shadow={shadow} />
+ )}
+ {lay.seats.map((s, i) => (
+ <group key={i} position={[s.x * M, 0, s.y * M]} rotation={[0, (-s.rot * Math.PI) / 180, 0]}>
+ <Fitted spec={KENNEY_MODELS.chair} w={CHAIR.w} d={CHAIR.d} h={900} look={look} color={color} base={base} shadow={shadow} />
+ </group>
+ ))}
+ </>
+ )
+}
+
+type FittedProps = { spec: KenneySpec; w: number; d: number; h: number; look: FurnitureLook; color?: string; base: string; shadow: boolean }
+
+function Fitted(props: FittedProps) {
+ return (
+ <Suspense fallback={<Placeholder w={props.w} d={props.d} h={props.h} look={props.look} />}>
+ <FittedGLTF {...props} />
+ </Suspense>
+ )
+}
+
+function Placeholder({ w, d, h, look }: { w: number; d: number; h: number; look: FurnitureLook }) {
+ return (
+ <mesh position={[0, (h * M) / 2, 0]} material={finishMaterial('white', look)}>
+ <boxGeometry args={[w * M, h * M, d * M]} />
+ </mesh>
+ )
+}
+
+function FittedGLTF({ spec, w, d, h, look, color, base, shadow }: FittedProps) {
+ const gltf = useGLTF(base + spec.file)
+ const fitted = useMemo(() => {
+ const root = new THREE.Group()
+ const inner = gltf.scene.clone(true)
+ inner.rotation.y = ((spec.rotY ?? 0) * Math.PI) / 180
+ root.add(inner)
+ const primary = new Set<Finish>(spec.primary ?? ['textile'])
+ root.traverse((o) => {
+ const mesh = o as THREE.Mesh
+ if (!mesh.isMesh) return
+ const swap = (m: THREE.Material) => {
+ const f = spec.remap?.[m.name] ?? kenneyFinish(m.name)
+ return finishMaterial(f, look, primary.has(f) ? color : undefined)
+ }
+ mesh.material = Array.isArray(mesh.material) ? mesh.material.map(swap) : swap(mesh.material)
+ mesh.castShadow = shadow
+ mesh.receiveShadow = true
+ })
+ root.updateMatrixWorld(true)
+ const box = new THREE.Box3().setFromObject(root)
+ const size = box.getSize(new THREE.Vector3())
+ const center = box.getCenter(new THREE.Vector3())
+ return { root, size, center }
+ }, [gltf, spec, look, color, shadow])
+
+ const sx = (w * M) / (fitted.size.x || 1)
+ const sy = (h * M) / (fitted.size.y || 1)
+ const sz = (d * M) / (fitted.size.z || 1)
+ return (
+ <group scale={[sx, sy, sz]}>
+ <group position={[-fitted.center.x, -fitted.center.y + fitted.size.y / 2, -fitted.center.z]}>
+ <primitive object={fitted.root} />
+ </group>
+ </group>
+ )
+}
+
+export function preloadFurnitureModels(base = FURNITURE_MODELS_BASE) {
+ for (const spec of Object.values(KENNEY_MODELS)) useGLTF.preload(base + spec.file)
+}
+
diff --git a/src/furniture/README.md b/src/furniture/README.md
new file mode 100644
index 0000000..431f93a
--- /dev/null
+++ b/src/furniture/README.md
@@ -0,0 +1,25 @@
+# Библиотека мебели
+
+Типовые предметы интерьера для плана: каталог с реальными размерами, архитектурные символы для 2D (react-konva), иконки для панели (SVG) и 3D-модели (r3f). Единицы — мм, `x/y` — центр предмета, ось Y вниз, `rotationDeg` по часовой на плане. Локальная система предмета: ширина `w` по X, глубина `d` по Y, **задняя сторона (к стене) — `-d/2`, фронт — `+d/2`**. В 3D фронт смотрит в `+z`, поворот `rotation.y = -rotationDeg`.
+
+## API
+
+`FURNITURE_CATALOG`, `FURNITURE_CATEGORIES`, `furnitureDef(type)`, `resolveFurniture(item)` → `{ def, w, d, h, elevation }` (размеры item перекрывают каталожные). `createFurniture(type, x, y, id, rotationDeg?)`.
+
+`<FurnitureSymbol2D item selected? showClearance? ghost? {...groupProps} />` — Konva `Group` в мм-координатах плана, линии не масштабируются (`strokeScaleEnabled=false`). При `selected` рисуется рамка и зона подхода `clearance`. Остальные пропсы (`onMouseDown`, `draggable`, `listening`, `name`…) уходят в `Group`.
+
+`<FurnitureIcon type size? />` — SVG-иконка из того же символа.
+
+`<FurnitureModel item look?="real|model" baseY? placed? modelsBase? castShadow? />` — сама ставит себя в `x/y/rotation` (метры, `M = 0.001`). Если позиционирует вызывающий — `placed={false}`, тогда применяется только подъём `elevation` (навесные шкафы, бойлер, настенный котёл). Внутри `Suspense` не нужен: GLB грузятся со своим заглушечным боксом. `preloadFurnitureModels()` — предзагрузка всех GLB.
+
+## Как добавить предмет
+
+Строка в `FURNITURE_CATALOG` (`catalog.ts`): `type`, русское имя, категория, `[w, d, h]`, опции `resizable`, `clearance { front, side }`, `elevation`.
+
+2D-символ — функция в `symbols.ts`, возвращающая массив примитивов (`rect`, `circle`, `ellipse`, `line`, `path` в SVG-синтаксисе, `group` с поворотом) в локальных мм с центром в нуле, и ветка в `furnitureSymbol`. Стили: `s: 'main' | 'thin'`, `f: 'paper' | 'tone' | 'dark' | 'water' | 'none'`, `dash` — для того, что выше секущей плоскости. Один символ сразу работает и в Konva, и в иконке.
+
+3D — либо GLB: положить файл в `public/models/furniture/`, строка в `KENNEY_MODELS` (`models.ts`) с `rotY`, если фронт модели не в `+z`, и `primary` — какие отделки перекрашивает `item.color`. Модель автоматически вписывается в `w×h×d` по габаритному боксу, материалы по имени меняются на палитру проекта (`materials3d.ts`, режимы «Макет»/«Материалы»). Либо процедурно: компонент в `procedural.tsx` из `Box`/`Cyl` (скругления через drei `RoundedBox`), имя в `PROCEDURAL` и ветка в `ProceduralFurniture`. Лицензию нового GLB дописать в `public/models/furniture/LICENSES.md`.
+
+## Стенд
+
+`npx vite --config prototypes/furniture/vite.config.ts` → http://localhost:5188. Параметры: `?view=2d|icons|3d`, `look=model`, `cat=kitchen`, `only=bed-1600,toilet`, `cols`, `zoom`, `scale`, `sel=<type>` (выделение с зоной подхода), `top=1` (3D сверху), `walls=1`. Снимки — `prototypes/furniture/shots/`.
diff --git a/src/furniture/Symbol2D.tsx b/src/furniture/Symbol2D.tsx
new file mode 100644
index 0000000..1f27a25
--- /dev/null
+++ b/src/furniture/Symbol2D.tsx
@@ -0,0 +1,130 @@
+import { memo, useMemo, type ComponentProps, type ReactNode } from 'react'
+import { Circle, Ellipse, Group, Line, Path, Rect } from 'react-konva'
+import { resolveFurniture, type FurnitureItem } from './catalog'
+import { furnitureSymbol, SYMBOL_STYLE, type FillKind, type Prim, type StrokeKind } from './symbols'
+
+export const FURNITURE_ACCENT = '#f26b1d'
+
+type GroupProps = Omit<ComponentProps<typeof Group>, 'x' | 'y' | 'rotation' | 'children'>
+
+export type FurnitureSymbol2DProps = GroupProps & {
+ item: FurnitureItem
+ selected?: boolean
+ showClearance?: boolean
+ ghost?: boolean
+}
+
+const fillColor = (f: FillKind | undefined, def: FillKind, custom?: string) => {
+ const k = f ?? def
+ if (k === 'none') return undefined
+ if (k === 'paper') return custom ?? SYMBOL_STYLE.paper
+ return SYMBOL_STYLE[k]
+}
+
+const strokeOf = (s: StrokeKind | undefined, def: StrokeKind) => {
+ const k = s ?? def
+ if (k === 'none') return { stroke: undefined, strokeWidth: 0 }
+ return k === 'main'
+ ? { stroke: SYMBOL_STYLE.ink, strokeWidth: SYMBOL_STYLE.main }
+ : { stroke: SYMBOL_STYLE.thin, strokeWidth: SYMBOL_STYLE.thinWidth }
+}
+
+function renderPrim(p: Prim, key: number, paper?: string): ReactNode {
+ if (p.k === 'group') {
+ return (
+ <Group key={key} x={p.x} y={p.y} rotation={p.rot} listening={false}>
+ {p.items.map((c, i) => renderPrim(c, i, paper))}
+ </Group>
+ )
+ }
+ const common = {
+ listening: false,
+ strokeScaleEnabled: false,
+ perfectDrawEnabled: false,
+ dash: p.dash ? SYMBOL_STYLE.dash : undefined,
+ lineJoin: 'round' as const,
+ lineCap: 'round' as const,
+ }
+ switch (p.k) {
+ case 'rect':
+ return <Rect key={key} {...common} x={p.x} y={p.y} width={p.w} height={p.h} cornerRadius={p.r ?? 0} fill={fillColor(p.f, 'paper', paper)} {...strokeOf(p.s, 'main')} />
+ case 'circle':
+ return <Circle key={key} {...common} x={p.cx} y={p.cy} radius={p.r} fill={fillColor(p.f, 'paper', paper)} {...strokeOf(p.s, 'main')} />
+ case 'ellipse':
+ return <Ellipse key={key} {...common} x={p.cx} y={p.cy} radiusX={p.rx} radiusY={p.ry} fill={fillColor(p.f, 'paper', paper)} {...strokeOf(p.s, 'main')} />
+ case 'line':
+ return <Line key={key} {...common} points={p.p} closed={p.closed} fill={fillColor(p.f, 'none', paper)} {...strokeOf(p.s, 'thin')} />
+ case 'path':
+ return <Path key={key} {...common} data={p.d} fill={fillColor(p.f, 'paper', paper)} {...strokeOf(p.s, 'main')} />
+ }
+}
+
+export const FurnitureSymbol2D = memo(function FurnitureSymbol2D({ item, selected, showClearance, ghost, ...rest }: FurnitureSymbol2DProps) {
+ const { def, w, d } = resolveFurniture(item)
+ const prims = useMemo(() => furnitureSymbol(item.type, w, d), [item.type, w, d])
+ const clearance = (showClearance ?? selected) ? def?.clearance : undefined
+ const paper = item.color && /^#[0-9a-f]{3,8}$/i.test(item.color) ? tint(item.color) : undefined
+
+ return (
+ <Group x={item.x} y={item.y} rotation={item.rotationDeg} opacity={ghost ? 0.6 : 1} {...rest}>
+ {clearance?.front ? (
+ <Rect
+ x={-w / 2}
+ y={d / 2}
+ width={w}
+ height={clearance.front}
+ fill="rgba(242, 107, 29, 0.07)"
+ stroke={FURNITURE_ACCENT}
+ strokeWidth={1}
+ strokeScaleEnabled={false}
+ dash={[4, 4]}
+ opacity={0.7}
+ listening={false}
+ />
+ ) : null}
+ {clearance?.side
+ ? [-1, 1].map((s) => (
+ <Rect
+ key={s}
+ x={s < 0 ? -w / 2 - clearance.side! : w / 2}
+ y={-d / 2}
+ width={clearance.side}
+ height={d}
+ fill="rgba(242, 107, 29, 0.05)"
+ stroke={FURNITURE_ACCENT}
+ strokeWidth={1}
+ strokeScaleEnabled={false}
+ dash={[4, 4]}
+ opacity={0.5}
+ listening={false}
+ />
+ ))
+ : null}
+ <Rect x={-w / 2} y={-d / 2} width={w} height={d} fill="rgba(255,255,255,0.001)" />
+ {prims.map((p, i) => renderPrim(p, i, paper))}
+ {selected && (
+ <Rect
+ x={-w / 2}
+ y={-d / 2}
+ width={w}
+ height={d}
+ stroke={FURNITURE_ACCENT}
+ strokeWidth={1.6}
+ strokeScaleEnabled={false}
+ fill="rgba(242, 107, 29, 0.06)"
+ listening={false}
+ />
+ )}
+ </Group>
+ )
+})
+
+function tint(hex: string) {
+ const h = hex.length === 4 ? '#' + [...hex.slice(1)].map((c) => c + c).join('') : hex.slice(0, 7)
+ const v = parseInt(h.slice(1), 16)
+ const mix = (c: number) => Math.round(c * 0.28 + 255 * 0.72)
+ const r = mix((v >> 16) & 255)
+ const g = mix((v >> 8) & 255)
+ const b = mix(v & 255)
+ return `rgb(${r}, ${g}, ${b})`
+}
diff --git a/src/furniture/catalog.ts b/src/furniture/catalog.ts
new file mode 100644
index 0000000..aaa95dd
--- /dev/null
+++ b/src/furniture/catalog.ts
@@ -0,0 +1,131 @@
+import { t } from '../i18n'
+
+export type FurnitureCategory = 'bedroom' | 'living' | 'kitchen' | 'bathroom' | 'hall' | 'other'
+
+export const FURNITURE_CATEGORIES: { id: FurnitureCategory; name: string }[] = (
+ ['bedroom', 'living', 'kitchen', 'bathroom', 'hall', 'other'] as const
+).map((id) => ({
+ id,
+ get name() {
+ return t(`plan:furniture.categories.${id}`)
+ },
+}))
+
+export type FurnitureItem = {
+ id: string
+ type: string
+ x: number
+ y: number
+ rotationDeg: number
+ w?: number
+ d?: number
+ h?: number
+ color?: string
+}
+
+export type Clearance = { front?: number; side?: number }
+
+export type FurnitureDef = {
+ type: string
+ name: string
+ category: FurnitureCategory
+ w: number
+ d: number
+ h: number
+ elevation?: number
+ resizable: boolean
+ clearance?: Clearance
+ note?: string
+}
+
+const def = (
+ type: string,
+ category: FurnitureCategory,
+ [w, d, h]: [number, number, number],
+ extra: Partial<Pick<FurnitureDef, 'resizable' | 'clearance' | 'elevation' | 'note'>> = {},
+): FurnitureDef => ({
+ type,
+ get name() {
+ return t(`plan:furniture.items.${type}`)
+ },
+ category,
+ w,
+ d,
+ h,
+ resizable: false,
+ ...extra,
+})
+
+export const FURNITURE_CATALOG: FurnitureDef[] = [
+ def('bed-1600', 'bedroom', [1700, 2100, 1000], { clearance: { front: 600, side: 600 } }),
+ def('bed-1800', 'bedroom', [1900, 2100, 1000], { clearance: { front: 600, side: 600 } }),
+ def('bed-900', 'bedroom', [1000, 2100, 900], { clearance: { side: 600 } }),
+ def('nightstand', 'bedroom', [450, 400, 550]),
+ def('wardrobe', 'bedroom', [1200, 600, 2200], { resizable: true, clearance: { front: 800 } }),
+ def('dresser', 'bedroom', [1000, 450, 850], { resizable: true, clearance: { front: 700 } }),
+
+ def('sofa', 'living', [2200, 950, 850], { resizable: true, clearance: { front: 600 } }),
+ def('sofa-corner', 'living', [2700, 1650, 850], { resizable: true, clearance: { front: 600 } }),
+ def('armchair', 'living', [850, 850, 850], { clearance: { front: 450 } }),
+ def('coffee-table', 'living', [1100, 600, 450], { resizable: true }),
+ def('tv-stand', 'living', [1600, 420, 1300], { resizable: true }),
+ def('bookcase', 'living', [800, 350, 2000], { resizable: true, clearance: { front: 600 } }),
+ def('plant', 'living', [450, 450, 1200]),
+
+ def('kitchen-base', 'kitchen', [600, 600, 900], { resizable: true, clearance: { front: 1000 } }),
+ def('kitchen-drawers', 'kitchen', [600, 600, 900], { resizable: true, clearance: { front: 1000 } }),
+ def('kitchen-corner', 'kitchen', [900, 900, 900], { clearance: { front: 1000 } }),
+ def('kitchen-upper', 'kitchen', [600, 330, 720], { resizable: true, elevation: 1450 }),
+ def('kitchen-sink', 'kitchen', [800, 600, 900], { resizable: true, clearance: { front: 1000 } }),
+ def('stove', 'kitchen', [600, 600, 900], { clearance: { front: 1000 } }),
+ def('dishwasher', 'kitchen', [600, 600, 900], { clearance: { front: 1000 } }),
+ def('fridge', 'kitchen', [600, 650, 2000], { clearance: { front: 1000 } }),
+ def('dining-4', 'kitchen', [1200, 1600, 750], { clearance: { side: 300 } }),
+ def('dining-6', 'kitchen', [1800, 1700, 750], { clearance: { side: 300 } }),
+ def('dining-round', 'kitchen', [1800, 1800, 750]),
+ def('chair', 'kitchen', [450, 520, 900]),
+
+ def('toilet', 'bathroom', [380, 680, 780], { clearance: { front: 600, side: 200 } }),
+ def('washbasin', 'bathroom', [600, 460, 850], { clearance: { front: 700 } }),
+ def('vanity', 'bathroom', [800, 480, 850], { resizable: true, clearance: { front: 700 } }),
+ def('bathtub', 'bathroom', [1700, 750, 600], { resizable: true, clearance: { front: 700 } }),
+ def('shower', 'bathroom', [900, 900, 2000], { resizable: true, clearance: { front: 700 } }),
+ def('washer', 'bathroom', [600, 600, 850], { clearance: { front: 800 } }),
+ def('water-heater', 'bathroom', [450, 470, 800], { elevation: 1100 }),
+
+ def('coat-rack', 'hall', [1000, 350, 1800], { resizable: true, clearance: { front: 600 } }),
+ def('shoe-cabinet', 'hall', [800, 320, 1000], { resizable: true, clearance: { front: 600 } }),
+ def('hall-wardrobe', 'hall', [1600, 600, 2400], { resizable: true, clearance: { front: 700 } }),
+
+ def('desk', 'other', [1200, 600, 750], { resizable: true, clearance: { front: 800 } }),
+ def('office-chair', 'other', [650, 650, 1050]),
+ def('fireplace', 'other', [1000, 550, 1100], { clearance: { front: 1000 } }),
+ def('masonry-stove', 'other', [1150, 900, 2000], { resizable: true, clearance: { front: 1250, side: 380 } }),
+ def('gas-boiler', 'other', [440, 340, 740], { elevation: 1000, clearance: { front: 700 } }),
+ def('floor-boiler', 'other', [500, 650, 900], { clearance: { front: 1000, side: 400 } }),
+]
+
+export const FURNITURE_BY_TYPE: Record<string, FurnitureDef> = Object.fromEntries(
+ FURNITURE_CATALOG.map((d) => [d.type, d]),
+)
+
+export function furnitureDef(type: string): FurnitureDef | undefined {
+ return FURNITURE_BY_TYPE[type]
+}
+
+export type ResolvedFurniture = { def: FurnitureDef | undefined; w: number; d: number; h: number; elevation: number }
+
+export function resolveFurniture(item: Pick<FurnitureItem, 'type' | 'w' | 'd' | 'h'>): ResolvedFurniture {
+ const d = furnitureDef(item.type)
+ return {
+ def: d,
+ w: item.w ?? d?.w ?? 600,
+ d: item.d ?? d?.d ?? 600,
+ h: item.h ?? d?.h ?? 900,
+ elevation: d?.elevation ?? 0,
+ }
+}
+
+export function createFurniture(type: string, x: number, y: number, id: string, rotationDeg = 0): FurnitureItem {
+ return { id, type, x, y, rotationDeg }
+}
diff --git a/src/furniture/icons.tsx b/src/furniture/icons.tsx
new file mode 100644
index 0000000..b992cfa
--- /dev/null
+++ b/src/furniture/icons.tsx
@@ -0,0 +1,72 @@
+import { memo, useMemo, type ReactNode, type SVGProps } from 'react'
+import { resolveFurniture } from './catalog'
+import { furnitureSymbol, SYMBOL_STYLE, type FillKind, type Prim, type StrokeKind } from './symbols'
+
+export type FurnitureIconProps = Omit<SVGProps<SVGSVGElement>, 'type'> & {
+ type: string
+ size?: number
+ pad?: number
+}
+
+const fill = (f: FillKind | undefined, def: FillKind) => {
+ const k = f ?? def
+ return k === 'none' ? 'none' : SYMBOL_STYLE[k]
+}
+
+function prim(p: Prim, key: number): ReactNode {
+ if (p.k === 'group') {
+ return (
+ <g key={key} transform={`translate(${p.x} ${p.y}) rotate(${p.rot})`}>
+ {p.items.map((c, i) => prim(c, i))}
+ </g>
+ )
+ }
+ const strokeKind: StrokeKind = p.s ?? (p.k === 'line' ? 'thin' : 'main')
+ const st =
+ strokeKind === 'none'
+ ? { stroke: 'none' }
+ : {
+ stroke: strokeKind === 'main' ? SYMBOL_STYLE.ink : SYMBOL_STYLE.thin,
+ strokeWidth: strokeKind === 'main' ? 1 : 0.6,
+ vectorEffect: 'non-scaling-stroke' as const,
+ strokeDasharray: p.dash ? '3 2' : undefined,
+ strokeLinejoin: 'round' as const,
+ strokeLinecap: 'round' as const,
+ }
+ switch (p.k) {
+ case 'rect':
+ return <rect key={key} x={p.x} y={p.y} width={p.w} height={p.h} rx={p.r ?? 0} fill={fill(p.f, 'paper')} {...st} />
+ case 'circle':
+ return <circle key={key} cx={p.cx} cy={p.cy} r={p.r} fill={fill(p.f, 'paper')} {...st} />
+ case 'ellipse':
+ return <ellipse key={key} cx={p.cx} cy={p.cy} rx={p.rx} ry={p.ry} fill={fill(p.f, 'paper')} {...st} />
+ case 'line': {
+ const pts = p.p.join(' ')
+ return p.closed ? (
+ <polygon key={key} points={pts} fill={fill(p.f, 'none')} {...st} />
+ ) : (
+ <polyline key={key} points={pts} fill="none" {...st} />
+ )
+ }
+ case 'path':
+ return <path key={key} d={p.d} fill={fill(p.f, 'paper')} {...st} />
+ }
+}
+
+export const FurnitureIcon = memo(function FurnitureIcon({ type, size = 40, pad = 0.08, ...rest }: FurnitureIconProps) {
+ const { w, d } = resolveFurniture({ type })
+ const prims = useMemo(() => furnitureSymbol(type, w, d), [type, w, d])
+ const side = Math.max(w, d) * (1 + pad * 2)
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox={`${-side / 2} ${-side / 2} ${side} ${side}`}
+ role="img"
+ aria-hidden={rest['aria-label'] ? undefined : true}
+ {...rest}
+ >
+ {prims.map((p, i) => prim(p, i))}
+ </svg>
+ )
+})
diff --git a/src/furniture/index.ts b/src/furniture/index.ts
new file mode 100644
index 0000000..c24d8b5
--- /dev/null
+++ b/src/furniture/index.ts
@@ -0,0 +1,18 @@
+export {
+ FURNITURE_CATALOG,
+ FURNITURE_CATEGORIES,
+ FURNITURE_BY_TYPE,
+ furnitureDef,
+ resolveFurniture,
+ createFurniture,
+ type FurnitureItem,
+ type FurnitureDef,
+ type FurnitureCategory,
+ type Clearance,
+ type ResolvedFurniture,
+} from './catalog'
+export { FurnitureSymbol2D, FURNITURE_ACCENT, type FurnitureSymbol2DProps } from './Symbol2D'
+export { FurnitureIcon, type FurnitureIconProps } from './icons'
+export { FurnitureModel, preloadFurnitureModels, FURNITURE_MODELS_BASE, type FurnitureModelProps } from './Model3D'
+export { furnitureSymbol, SYMBOL_STYLE, type Prim } from './symbols'
+export type { FurnitureLook } from './materials3d'
diff --git a/src/furniture/layout.ts b/src/furniture/layout.ts
new file mode 100644
index 0000000..0d60ae7
--- /dev/null
+++ b/src/furniture/layout.ts
@@ -0,0 +1,37 @@
+export const CHAIR = { w: 450, d: 520, tuck: 120 }
+
+export type Seat = { x: number; y: number; rot: number }
+
+export type DiningLayout = {
+ round: boolean
+ table: { w: number; d: number }
+ seats: Seat[]
+}
+
+export function diningLayout(type: string, w: number, d: number): DiningLayout {
+ const reach = CHAIR.d - CHAIR.tuck
+ if (type === 'dining-round') {
+ const dia = Math.max(600, Math.min(w, d) - 2 * reach)
+ const r = dia / 2 + reach - CHAIR.d / 2
+ const seats = [0, 90, 180, 270].map((deg) => {
+ const a = (deg * Math.PI) / 180
+ return { x: Math.sin(a) * r, y: -Math.cos(a) * r, rot: deg }
+ })
+ return { round: true, table: { w: dia, d: dia }, seats }
+ }
+ const perSide = type === 'dining-6' ? 3 : 2
+ const tw = w
+ const td = Math.max(600, d - 2 * reach)
+ const seats: Seat[] = []
+ const yTop = -td / 2 - reach + CHAIR.d / 2
+ for (let i = 0; i < perSide; i++) {
+ const x = -tw / 2 + (tw / perSide) * (i + 0.5)
+ seats.push({ x, y: yTop, rot: 0 })
+ seats.push({ x, y: -yTop, rot: 180 })
+ }
+ return { round: false, table: { w: tw, d: td }, seats }
+}
+
+export function isDining(type: string) {
+ return type === 'dining-4' || type === 'dining-6' || type === 'dining-round'
+}
diff --git a/src/furniture/materials3d.ts b/src/furniture/materials3d.ts
new file mode 100644
index 0000000..a355778
--- /dev/null
+++ b/src/furniture/materials3d.ts
@@ -0,0 +1,106 @@
+import * as THREE from 'three'
+
+export type FurnitureLook = 'model' | 'real'
+
+export type Finish =
+ | 'wood'
+ | 'woodDark'
+ | 'textile'
+ | 'textileDark'
+ | 'textileBlue'
+ | 'linen'
+ | 'white'
+ | 'porcelain'
+ | 'metal'
+ | 'metalLight'
+ | 'metalMedium'
+ | 'metalDark'
+ | 'glass'
+ | 'water'
+ | 'plant'
+ | 'lamp'
+ | 'brick'
+ | 'plaster'
+ | 'stone'
+ | 'soot'
+ | 'screen'
+
+type Spec = { color: string; roughness: number; metalness?: number; opacity?: number }
+
+const REAL: Record<Finish, Spec> = {
+ wood: { color: '#c7a582', roughness: 0.78 },
+ woodDark: { color: '#7d6150', roughness: 0.8 },
+ textile: { color: '#b3aea5', roughness: 0.95 },
+ textileDark: { color: '#8e8a83', roughness: 0.95 },
+ textileBlue: { color: '#8f9aa1', roughness: 0.95 },
+ linen: { color: '#f2f0eb', roughness: 0.95 },
+ white: { color: '#eeede9', roughness: 0.7 },
+ porcelain: { color: '#f6f6f3', roughness: 0.35 },
+ metal: { color: '#c3c6c7', roughness: 0.45, metalness: 0.35 },
+ metalLight: { color: '#ecedea', roughness: 0.5, metalness: 0.1 },
+ metalMedium: { color: '#8f9497', roughness: 0.5, metalness: 0.3 },
+ metalDark: { color: '#4f5458', roughness: 0.6, metalness: 0.2 },
+ glass: { color: '#d9e4e6', roughness: 0.1, opacity: 0.35 },
+ water: { color: '#c9dbe0', roughness: 0.15 },
+ plant: { color: '#7c9667', roughness: 0.9 },
+ lamp: { color: '#f4efe2', roughness: 0.8 },
+ brick: { color: '#c4927c', roughness: 0.95 },
+ plaster: { color: '#ece9e3', roughness: 0.95 },
+ stone: { color: '#b9b6b0', roughness: 0.9 },
+ soot: { color: '#2f3033', roughness: 1 },
+ screen: { color: '#26282c', roughness: 0.3 },
+}
+
+const MODEL: Record<Finish, Spec> = Object.fromEntries(
+ (Object.keys(REAL) as Finish[]).map((k) => {
+ const dark = k === 'soot' || k === 'screen' || k === 'metalDark'
+ const mid = k === 'woodDark' || k === 'textileDark' || k === 'metalMedium' || k === 'brick'
+ const tone = k === 'wood' || k === 'textile' || k === 'textileBlue' || k === 'stone' || k === 'plant'
+ const color = dark ? '#8d8b87' : mid ? '#cfccc6' : tone ? '#dfddd7' : '#f0efeb'
+ const glass = k === 'glass'
+ return [k, { color: glass ? '#dde4e6' : color, roughness: glass ? 0.2 : 1, opacity: glass ? 0.35 : undefined }]
+ }),
+) as Record<Finish, Spec>
+
+const KENNEY: Record<string, Finish> = {
+ wood: 'wood',
+ woodDark: 'woodDark',
+ carpet: 'textile',
+ carpetDarker: 'textileDark',
+ carpetBlue: 'textileBlue',
+ carpetWhite: 'linen',
+ metal: 'metal',
+ metalLight: 'metalLight',
+ metalMedium: 'metalMedium',
+ metalDark: 'metalDark',
+ glass: 'glass',
+ _defaultMat: 'porcelain',
+ plant: 'plant',
+ lamp: 'lamp',
+ fur: 'textile',
+}
+
+export function kenneyFinish(name: string): Finish {
+ return KENNEY[name] ?? 'white'
+}
+
+const cache = new Map<string, THREE.MeshStandardMaterial>()
+
+export function finishMaterial(finish: Finish, look: FurnitureLook, color?: string) {
+ const key = `${look}|${finish}|${color ?? ''}`
+ let m = cache.get(key)
+ if (!m) {
+ const spec = (look === 'model' ? MODEL : REAL)[finish]
+ m = new THREE.MeshStandardMaterial({
+ color: color && look === 'real' ? color : spec.color,
+ roughness: spec.roughness,
+ metalness: spec.metalness ?? 0,
+ transparent: spec.opacity !== undefined,
+ opacity: spec.opacity ?? 1,
+ depthWrite: spec.opacity === undefined,
+ })
+ m.name = `furniture-${finish}`
+ cache.set(key, m)
+ }
+ return m
+}
diff --git a/src/furniture/models.ts b/src/furniture/models.ts
new file mode 100644
index 0000000..511c29d
--- /dev/null
+++ b/src/furniture/models.ts
@@ -0,0 +1,42 @@
+import type { Finish } from './materials3d'
+
+export type KenneySpec = {
+ file: string
+ rotY?: number
+ primary?: Finish[]
+ remap?: Record<string, Finish>
+}
+
+const k = (file: string, extra: Omit<KenneySpec, 'file'> = {}): KenneySpec => ({ file: `${file}.glb`, ...extra })
+
+export const KENNEY_MODELS: Record<string, KenneySpec> = {
+ 'bed-1600': k('bedDouble'),
+ 'bed-1800': k('bedDouble'),
+ 'bed-900': k('bedSingle'),
+ nightstand: k('cabinetBedDrawer', { primary: ['wood'] }),
+ sofa: k('loungeSofa'),
+ 'sofa-corner': k('loungeSofaCorner'),
+ armchair: k('loungeChair'),
+ 'coffee-table': k('tableCoffee', { primary: ['wood'] }),
+ 'tv-stand': k('cabinetTelevision', { primary: ['wood'] }),
+ tv: k('televisionModern', { remap: { metalDark: 'screen' } }),
+ plant: k('pottedPlant'),
+ 'kitchen-base': k('kitchenCabinet', { primary: ['wood'] }),
+ 'kitchen-drawers': k('kitchenCabinetDrawer', { primary: ['wood'] }),
+ 'kitchen-corner': k('kitchenCabinetCornerInner', { rotY: 90, primary: ['wood'] }),
+ 'kitchen-upper': k('kitchenCabinetUpper', { primary: ['wood'] }),
+ 'kitchen-sink': k('kitchenSink', { primary: ['wood'] }),
+ stove: k('kitchenStove', { primary: ['wood'] }),
+ fridge: k('kitchenFridgeLarge'),
+ table: k('table', { primary: ['wood'] }),
+ chair: k('chair', { primary: ['wood'] }),
+ toilet: k('toilet'),
+ washbasin: k('bathroomSink'),
+ vanity: k('bathroomSinkSquare', { primary: ['wood'] }),
+ bathtub: k('bathtub'),
+ shower: k('shower'),
+ washer: k('washer'),
+ desk: k('desk', { primary: ['wood'] }),
+ 'office-chair': k('chairDesk'),
+ 'coat-rack': k('coatRack', { primary: ['wood'] }),
+}
diff --git a/src/furniture/procedural.tsx b/src/furniture/procedural.tsx
new file mode 100644
index 0000000..bdb9898
--- /dev/null
+++ b/src/furniture/procedural.tsx
@@ -0,0 +1,306 @@
+import { RoundedBox } from '@react-three/drei'
+import type { ReactNode } from 'react'
+import { finishMaterial, type Finish, type FurnitureLook } from './materials3d'
+
+const M = 0.001
+
+type Paint = { look: FurnitureLook; color?: string; primary: Finish[] }
+type V3 = [number, number, number]
+
+const PROCEDURAL = new Set([
+ 'wardrobe',
+ 'hall-wardrobe',
+ 'dresser',
+ 'dishwasher',
+ 'water-heater',
+ 'shoe-cabinet',
+ 'fireplace',
+ 'masonry-stove',
+ 'gas-boiler',
+ 'floor-boiler',
+ 'bookcase',
+ 'table-round',
+ 'generic',
+])
+
+export function hasProcedural(type: string) {
+ return PROCEDURAL.has(type)
+}
+
+function mat(paint: Paint, f: Finish) {
+ return finishMaterial(f, paint.look, paint.primary.includes(f) ? paint.color : undefined)
+}
+
+function Box({ p, s, f, r = 0, paint }: { p: V3; s: V3; f: Finish; r?: number; paint: Paint }) {
+ const size = s.map((v) => Math.max(v, 0.5) * M) as V3
+ const pos = p.map((v) => v * M) as V3
+ const radius = Math.min(r, ...s.map((v) => v / 2 - 0.5)) * M
+ if (radius <= 0.0005) {
+ return (
+ <mesh position={pos} material={mat(paint, f)} castShadow receiveShadow>
+ <boxGeometry args={size} />
+ </mesh>
+ )
+ }
+ return <RoundedBox args={size} radius={radius} smoothness={3} position={pos} material={mat(paint, f)} castShadow receiveShadow />
+}
+
+function Cyl({ p, r, h, f, paint, rot, seg = 32 }: { p: V3; r: number; h: number; f: Finish; paint: Paint; rot?: V3; seg?: number }) {
+ return (
+ <mesh position={p.map((v) => v * M) as V3} rotation={rot} material={mat(paint, f)} castShadow receiveShadow>
+ <cylinderGeometry args={[r * M, r * M, h * M, seg]} />
+ </mesh>
+ )
+}
+
+function Handle({ x, y, z, len, vertical, paint }: { x: number; y: number; z: number; len: number; vertical?: boolean; paint: Paint }) {
+ return <Box p={[x, y, z + 12]} s={vertical ? [12, len, 14] : [len, 12, 14]} r={5} f="metalMedium" paint={paint} />
+}
+
+type P = { w: number; d: number; h: number; paint: Paint }
+
+function Wardrobe({ w, d, h, paint }: P) {
+ const plinth = 80
+ const doors = Math.max(1, Math.round(w / 500))
+ const dw = w / doors
+ const items: ReactNode[] = [
+ <Box key="c" p={[0, h / 2, -10]} s={[w, h, d - 20]} r={6} f="wood" paint={paint} />,
+ <Box key="p" p={[0, plinth / 2, d / 2 - 60]} s={[w - 40, plinth, 20]} f="woodDark" paint={paint} />,
+ ]
+ for (let i = 0; i < doors; i++) {
+ const x = -w / 2 + dw * (i + 0.5)
+ items.push(<Box key={`d${i}`} p={[x, plinth + (h - plinth) / 2, d / 2 - 10]} s={[dw - 4, h - plinth - 6, 20]} r={4} f="wood" paint={paint} />)
+ const hx = x + (i % 2 ? -1 : 1) * (dw / 2 - 45)
+ items.push(<Handle key={`h${i}`} x={hx} y={h * 0.5} z={d / 2} len={260} vertical paint={paint} />)
+ }
+ return <>{items}</>
+}
+
+function HallWardrobe({ w, d, h, paint }: P) {
+ const pw = w / 2 + 40
+ return (
+ <>
+ <Box p={[0, h / 2, -20]} s={[w, h, d - 40]} r={6} f="wood" paint={paint} />
+ <Box p={[0, 40, d / 2 - 50]} s={[w - 20, 80, 20]} f="woodDark" paint={paint} />
+ <Box p={[0, h - 25, d / 2 - 20]} s={[w, 50, 40]} f="metalMedium" paint={paint} />
+ <Box p={[-w / 2 + pw / 2, h / 2 + 20, d / 2 - 38]} s={[pw, h - 90, 18]} r={3} f="wood" paint={paint} />
+ <Box p={[w / 2 - pw / 2, h / 2 + 20, d / 2 - 14]} s={[pw, h - 90, 18]} r={3} f="glass" paint={paint} />
+ <Box p={[w / 2 - pw / 2, h / 2 + 20, d / 2 - 22]} s={[pw - 60, h - 150, 4]} f="metalLight" paint={paint} />
+ </>
+ )
+}
+
+function Drawers({ w, d, h, paint, rows, legs }: P & { rows: number; legs: number }) {
+ const cols = Math.max(1, Math.round(w / 500))
+ const top = 25
+ const bodyH = h - legs
+ const fh = (bodyH - top - 30) / rows
+ const cw = (w - 30) / cols
+ const items: ReactNode[] = [
+ <Box key="c" p={[0, legs + bodyH / 2, -10]} s={[w, bodyH, d - 20]} r={8} f="wood" paint={paint} />,
+ <Box key="t" p={[0, h - top / 2, 0]} s={[w + 10, top, d + 10]} r={6} f="wood" paint={paint} />,
+ ]
+ if (legs > 0) {
+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) items.push(<Box key={`l${sx}${sz}`} p={[sx * (w / 2 - 50), legs / 2, sz * (d / 2 - 50)]} s={[30, legs, 30]} r={6} f="woodDark" paint={paint} />)
+ }
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ const x = -w / 2 + 15 + cw * (c + 0.5)
+ const y = legs + 15 + fh * (r + 0.5)
+ items.push(<Box key={`f${r}${c}`} p={[x, y, d / 2 - 8]} s={[cw - 6, fh - 6, 18]} r={4} f="wood" paint={paint} />)
+ items.push(<Handle key={`h${r}${c}`} x={x} y={y + fh * 0.2} z={d / 2} len={Math.min(160, cw * 0.4)} paint={paint} />)
+ }
+ }
+ return <>{items}</>
+}
+
+function ShoeCabinet({ w, d, h, paint }: P) {
+ const cols = Math.max(1, Math.round(w / 450))
+ const cw = w / cols
+ const fh = (h - 80) / 2
+ const items: ReactNode[] = [
+ <Box key="c" p={[0, h / 2, -10]} s={[w, h, d - 20]} r={6} f="plaster" paint={paint} />,
+ <Box key="t" p={[0, h - 12, 0]} s={[w + 10, 24, d + 10]} r={5} f="wood" paint={paint} />,
+ ]
+ for (let r = 0; r < 2; r++) {
+ for (let c = 0; c < cols; c++) {
+ const x = -w / 2 + cw * (c + 0.5)
+ const y = 60 + fh * (r + 0.5)
+ items.push(<Box key={`f${r}${c}`} p={[x, y, d / 2 - 6]} s={[cw - 6, fh - 6, 16]} r={4} f="plaster" paint={paint} />)
+ items.push(<Handle key={`h${r}${c}`} x={x} y={y + fh / 2 - 40} z={d / 2} len={Math.min(140, cw * 0.4)} paint={paint} />)
+ }
+ }
+ return <>{items}</>
+}
+
+function Dishwasher({ w, d, h, paint }: P) {
+ const top = 38
+ return (
+ <>
+ <Box p={[0, (h - top) / 2, -10]} s={[w - 4, h - top, d - 20]} r={4} f="metalLight" paint={paint} />
+ <Box p={[0, h - top / 2, 10]} s={[w, top, d + 20]} r={4} f="stone" paint={paint} />
+ <Box p={[0, 50, d / 2 - 40]} s={[w - 10, 100, 20]} f="woodDark" paint={paint} />
+ <Box p={[0, (h - top + 100) / 2, d / 2 - 8]} s={[w - 8, h - top - 110, 16]} r={4} f="metalLight" paint={paint} />
+ <Box p={[0, h - top - 45, d / 2 + 2]} s={[w - 8, 70, 6]} r={3} f="metalDark" paint={paint} />
+ <Handle x={0} y={h - top - 120} z={d / 2} len={w * 0.6} paint={paint} />
+ </>
+ )
+}
+
+function WaterHeater({ w, d, h, paint }: P) {
+ const r = Math.min(w, d) / 2
+ const cz = d / 2 - r
+ return (
+ <>
+ <Cyl p={[0, h / 2, cz]} r={r} h={h - r * 0.5} f="metalLight" paint={paint} />
+ <mesh position={[0, (h - r * 0.25) * M, cz * M]} scale={[1, 0.25, 1]} material={mat(paint, 'metalLight')} castShadow>
+ <sphereGeometry args={[r * M, 32, 16, 0, Math.PI * 2, 0, Math.PI / 2]} />
+ </mesh>
+ <mesh position={[0, r * 0.25 * M, cz * M]} scale={[1, 0.25, 1]} rotation={[Math.PI, 0, 0]} material={mat(paint, 'metalLight')} castShadow>
+ <sphereGeometry args={[r * M, 32, 16, 0, Math.PI * 2, 0, Math.PI / 2]} />
+ </mesh>
+ <Box p={[0, h * 0.35, cz + r - 5]} s={[r * 0.6, r * 0.35, 16]} r={6} f="metalDark" paint={paint} />
+ <Cyl p={[-r * 0.3, -60, cz]} r={12} h={140} f="metal" paint={paint} />
+ <Cyl p={[r * 0.3, -60, cz]} r={12} h={140} f="metal" paint={paint} />
+ <Box p={[0, h * 0.75, -d / 2 + 10]} s={[r * 1.1, 60, 20]} f="metalMedium" paint={paint} />
+ </>
+ )
+}
+
+function GasBoiler({ w, d, h, paint }: P) {
+ return (
+ <>
+ <Box p={[0, h / 2, 0]} s={[w, h, d]} r={30} f="white" paint={paint} />
+ <Box p={[0, 70, d / 2 - 4]} s={[w - 40, 90, 14]} r={10} f="metalDark" paint={paint} />
+ <Box p={[-w * 0.2, 70, d / 2 + 4]} s={[w * 0.25, 40, 4]} r={2} f="screen" paint={paint} />
+ <Cyl p={[0, h + 90, -d / 2 + 120]} r={50} h={180} f="metal" paint={paint} />
+ {[-0.3, -0.1, 0.1, 0.3].map((x) => (
+ <Cyl key={x} p={[w * x, -70, 0]} r={11} h={140} f="metal" paint={paint} />
+ ))}
+ </>
+ )
+}
+
+function FloorBoiler({ w, d, h, paint }: P) {
+ return (
+ <>
+ <Box p={[0, h / 2, 0]} s={[w, h, d]} r={25} f="white" paint={paint} />
+ <Box p={[0, h - 60, d / 2 - 4]} s={[w - 30, 90, 14]} r={10} f="metalDark" paint={paint} />
+ <Box p={[0, h * 0.42, d / 2 - 2]} s={[w - 60, h * 0.55, 8]} r={8} f="white" paint={paint} />
+ <Cyl p={[0, h + 150, -d / 2 + 150]} r={75} h={300} f="metal" paint={paint} />
+ <Box p={[0, 25, 0]} s={[w + 10, 50, d + 10]} r={6} f="metalMedium" paint={paint} />
+ </>
+ )
+}
+
+function Fireplace({ w, d, h, paint }: P) {
+ const fw = w * 0.56
+ const fh = h * 0.5
+ return (
+ <>
+ <Box p={[0, 40, 90]} s={[w + 300, 80, d + 180]} r={10} f="stone" paint={paint} />
+ <Box p={[0, h / 2, 0]} s={[w, h, d]} r={10} f="plaster" paint={paint} />
+ <Box p={[0, h - 30, 30]} s={[w + 120, 60, d + 60]} r={10} f="wood" paint={paint} />
+ <Box p={[0, 80 + fh / 2, d / 2 - 90]} s={[fw, fh, 200]} r={20} f="soot" paint={paint} />
+ <Box p={[0, 80 + fh + 30, d / 2 - 5]} s={[fw + 40, 50, 20]} r={6} f="stone" paint={paint} />
+ <Box p={[0, 80 + 25, d / 2 - 60]} s={[fw * 0.6, 50, 120]} r={20} f="woodDark" paint={paint} />
+ </>
+ )
+}
+
+function MasonryStove({ w, d, h, paint }: P) {
+ const doorW = Math.min(360, w * 0.35)
+ return (
+ <>
+ <Box p={[0, h / 2, 0]} s={[w, h, d]} r={15} f="brick" paint={paint} />
+ <Box p={[0, h - 40, 0]} s={[w + 40, 80, d + 40]} r={15} f="brick" paint={paint} />
+ <Box p={[0, 130, 0]} s={[w + 40, 260, d + 40]} r={15} f="brick" paint={paint} />
+ <Box p={[0, 420, d / 2 + 4]} s={[doorW, doorW * 0.8, 16]} r={8} f="metalDark" paint={paint} />
+ <Box p={[0, 180, d / 2 + 22]} s={[doorW * 0.8, 110, 12]} r={6} f="metalDark" paint={paint} />
+ <Box p={[0, h * 0.65, d / 2 + 2]} s={[w * 0.6, 12, 10]} f="metalMedium" paint={paint} />
+ </>
+ )
+}
+
+function Bookcase({ w, d, h, paint }: P) {
+ const t = 22
+ const shelves = Math.max(2, Math.round(h / 380))
+ const step = (h - 2 * t - 60) / shelves
+ const sections = Math.max(1, Math.round(w / 420))
+ const sw = (w - 2 * t) / sections
+ const tones: Finish[] = ['linen', 'textileDark', 'woodDark', 'textileBlue', 'linen', 'textile']
+ const items: ReactNode[] = [
+ <Box key="l" p={[-w / 2 + t / 2, h / 2, 0]} s={[t, h, d]} f="wood" paint={paint} />,
+ <Box key="r" p={[w / 2 - t / 2, h / 2, 0]} s={[t, h, d]} f="wood" paint={paint} />,
+ <Box key="b" p={[0, h / 2, -d / 2 + 5]} s={[w - 2 * t, h, 10]} f="wood" paint={paint} />,
+ <Box key="k" p={[0, 30, d / 2 - 30]} s={[w - 2 * t, 60, 20]} f="woodDark" paint={paint} />,
+ ]
+ for (let i = 1; i < sections; i++) items.push(<Box key={`v${i}`} p={[-w / 2 + t + sw * i, h / 2, 0]} s={[t, h - 2 * t, d - 20]} f="wood" paint={paint} />)
+ for (let i = 0; i <= shelves; i++) {
+ const y = 60 + t / 2 + step * i
+ items.push(<Box key={`s${i}`} p={[0, i === shelves ? h - t / 2 : y, 0]} s={[w, t, d]} f="wood" paint={paint} />)
+ if (i === shelves) continue
+ for (let c = 0; c < sections; c++) {
+ if ((i + c) % 3 === 2) continue
+ const seed = i * 7 + c * 3
+ const fill = 0.45 + ((seed * 37) % 40) / 100
+ const bw = (sw - 40) * fill
+ const bh = step * (0.62 + ((seed * 13) % 20) / 100)
+ const x0 = -w / 2 + t + sw * c + 20 + (seed % 2 ? sw - 40 - bw : 0)
+ const parts = Math.max(2, Math.round(bw / 70))
+ for (let k = 0; k < parts; k++) {
+ const pw = bw / parts
+ const ph = bh * (0.85 + ((seed + k * 5) % 4) * 0.05)
+ items.push(<Box key={`bk${i}-${c}-${k}`} p={[x0 + pw * (k + 0.5), y + t / 2 + ph / 2, 10]} s={[pw - 4, ph, d * 0.7]} r={3} f={tones[(seed + k) % tones.length]} paint={paint} />)
+ }
+ }
+ }
+ return <>{items}</>
+}
+
+function RoundTable({ w, h, paint }: P) {
+ const r = w / 2
+ return (
+ <>
+ <Cyl p={[0, h - 18, 0]} r={r} h={36} f="wood" paint={paint} seg={64} />
+ <Cyl p={[0, (h - 36) / 2, 0]} r={45} h={h - 36} f="wood" paint={paint} />
+ <Cyl p={[0, 12, 0]} r={r * 0.45} h={24} f="woodDark" paint={paint} seg={48} />
+ </>
+ )
+}
+
+function Generic({ w, d, h, paint }: P) {
+ return <Box p={[0, h / 2, 0]} s={[w, h, d]} r={20} f="white" paint={paint} />
+}
+
+export function ProceduralFurniture({ type, w, d, h, paint }: { type: string } & P) {
+ const p = { w, d, h, paint }
+ switch (type) {
+ case 'wardrobe':
+ return <Wardrobe {...p} />
+ case 'hall-wardrobe':
+ return <HallWardrobe {...p} />
+ case 'dresser':
+ return <Drawers {...p} rows={3} legs={0} />
+ case 'shoe-cabinet':
+ return <ShoeCabinet {...p} />
+ case 'dishwasher':
+ return <Dishwasher {...p} />
+ case 'water-heater':
+ return <WaterHeater {...p} />
+ case 'gas-boiler':
+ return <GasBoiler {...p} />
+ case 'floor-boiler':
+ return <FloorBoiler {...p} />
+ case 'fireplace':
+ return <Fireplace {...p} />
+ case 'masonry-stove':
+ return <MasonryStove {...p} />
+ case 'bookcase':
+ return <Bookcase {...p} />
+ case 'table-round':
+ return <RoundTable {...p} />
+ default:
+ return <Generic {...p} />
+ }
+}
diff --git a/src/furniture/symbols.ts b/src/furniture/symbols.ts
new file mode 100644
index 0000000..4dfe1b2
--- /dev/null
+++ b/src/furniture/symbols.ts
@@ -0,0 +1,668 @@
+import { CHAIR, diningLayout } from './layout'
+
+export type StrokeKind = 'main' | 'thin' | 'none'
+export type FillKind = 'paper' | 'tone' | 'dark' | 'water' | 'none'
+
+type Style = { s?: StrokeKind; f?: FillKind; dash?: boolean }
+
+export type Prim =
+ | ({ k: 'rect'; x: number; y: number; w: number; h: number; r?: number } & Style)
+ | ({ k: 'circle'; cx: number; cy: number; r: number } & Style)
+ | ({ k: 'ellipse'; cx: number; cy: number; rx: number; ry: number } & Style)
+ | ({ k: 'line'; p: number[]; closed?: boolean } & Style)
+ | ({ k: 'path'; d: string } & Style)
+ | { k: 'group'; x: number; y: number; rot: number; items: Prim[] }
+
+export const SYMBOL_STYLE = {
+ ink: '#2b2d33',
+ thin: '#6f737b',
+ paper: '#ffffff',
+ tone: '#ecebe6',
+ dark: '#474a52',
+ water: '#eef4f7',
+ main: 1.1,
+ thinWidth: 0.7,
+ dash: [5, 3],
+}
+
+const rect = (x: number, y: number, w: number, h: number, o: Style & { r?: number } = {}): Prim => ({ k: 'rect', x, y, w, h, ...o })
+const circle = (cx: number, cy: number, r: number, o: Style = {}): Prim => ({ k: 'circle', cx, cy, r, ...o })
+const ellipse = (cx: number, cy: number, rx: number, ry: number, o: Style = {}): Prim => ({ k: 'ellipse', cx, cy, rx, ry, ...o })
+const line = (p: number[], o: Style & { closed?: boolean } = {}): Prim => ({ k: 'line', p, s: 'thin', f: 'none', ...o })
+const path = (d: string, o: Style = {}): Prim => ({ k: 'path', d, ...o })
+const group = (x: number, y: number, rot: number, items: Prim[]): Prim => ({ k: 'group', x, y, rot, items })
+
+const n = (v: number) => Math.round(v * 10) / 10
+
+function hatch(x0: number, y0: number, w: number, h: number, step: number): Prim[] {
+ const out: Prim[] = []
+ const start = x0 + y0 + step
+ const end = x0 + w + y0 + h
+ for (let k = start; k < end; k += step) {
+ const xa = Math.max(x0, k - (y0 + h))
+ const xb = Math.min(x0 + w, k - y0)
+ if (xb - xa < 1) continue
+ out.push(line([xa, k - xa, xb, k - xb]))
+ }
+ return out
+}
+
+function bed(w: number, d: number, pillows: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const head = 70
+ const m = 45
+ const mx0 = x0 + m
+ const mw = w - 2 * m
+ const gap = 70
+ const pw = (mw - gap * (pillows + 1)) / pillows
+ const ph = Math.min(380, d * 0.19)
+ const py = y0 + head + 70
+ const by = py + ph + 90
+ const bx0 = mx0 - 12
+ const bx1 = x0 + w - m + 12
+ const by1 = y1 - m + 12
+ const fold = Math.min(360, mw * 0.36)
+ const items: Prim[] = [
+ rect(x0, y0, w, d, { r: 30 }),
+ rect(x0, y0, w, head, { r: 20, f: 'tone' }),
+ rect(mx0, y0 + head, mw, d - head - m, { r: 40, s: 'thin' }),
+ ]
+ for (let i = 0; i < pillows; i++) {
+ items.push(rect(mx0 + gap + i * (pw + gap), py, pw, ph, { r: 90, s: 'thin' }))
+ }
+ items.push(
+ path(`M${n(bx0)} ${n(by)} L${n(bx1)} ${n(by)} L${n(bx1)} ${n(by1 - fold)} L${n(bx1 - fold)} ${n(by1)} L${n(bx0)} ${n(by1)} Z`),
+ line([bx0, by + 230, bx1, by + 230]),
+ path(`M${n(bx1)} ${n(by1 - fold)} L${n(bx1 - fold)} ${n(by1)} L${n(bx1 - fold)} ${n(by1 - fold)} Z`, { s: 'thin', f: 'tone' }),
+ )
+ return items
+}
+
+function cabinetDoors(w: number, d: number, sliding: boolean): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const items: Prim[] = [rect(x0, y0, w, d, { r: 10 })]
+ const rodY = y0 + (d - 60) / 2
+ items.push(line([x0 + 40, rodY, x0 + w - 40, rodY]))
+ const step = 110
+ for (let x = x0 + 90; x < x0 + w - 60; x += step) {
+ const half = (d - 150) / 2
+ items.push(line([x - half * 0.3, rodY - half, x + half * 0.3, rodY + half]))
+ }
+ if (sliding) {
+ const half = w / 2
+ items.push(line([x0 + 20, y1 - 55, x0 + half + 40, y1 - 55], { s: 'main' }))
+ items.push(line([x0 + half - 40, y1 - 28, x0 + w - 20, y1 - 28], { s: 'main' }))
+ } else {
+ const doors = Math.max(1, Math.round(w / 500))
+ items.push(line([x0, y1 - 30, x0 + w, y1 - 30]))
+ for (let i = 1; i < doors; i++) items.push(line([x0 + (w / doors) * i, y1 - 30, x0 + (w / doors) * i, y1]))
+ }
+ return items
+}
+
+function sofaPieces(x0: number, y0: number, w: number, d: number, back: number, arm: number): Prim[] {
+ const items: Prim[] = [
+ rect(x0, y0, w, back, { r: 50 }),
+ rect(x0, y0, arm, d, { r: 50 }),
+ rect(x0 + w - arm, y0, arm, d, { r: 50 }),
+ ]
+ const seatW = w - 2 * arm
+ const count = Math.max(1, Math.round(seatW / 700))
+ const cw = seatW / count
+ for (let i = 0; i < count; i++) {
+ items.push(rect(x0 + arm + i * cw + 8, y0 + back + 8, cw - 16, d - back - 16, { r: 45, s: 'thin' }))
+ }
+ return items
+}
+
+function sofa(w: number, d: number): Prim[] {
+ const back = Math.min(230, d * 0.26)
+ const arm = Math.min(220, w * 0.12)
+ return sofaPieces(-w / 2, -d / 2, w, d, back, arm)
+}
+
+function sofaCorner(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const x1 = w / 2
+ const y1 = d / 2
+ const back = 230
+ const arm = 200
+ const seat = Math.min(980, d * 0.6, w * 0.4)
+ const items: Prim[] = [
+ rect(x0, y0, w, back, { r: 50 }),
+ rect(x1 - back, y0, back, d, { r: 50 }),
+ rect(x0, y0, arm, seat, { r: 50 }),
+ rect(x1 - seat, y1 - arm, seat, arm, { r: 50 }),
+ ]
+ const mainW = x1 - seat - (x0 + arm)
+ const count = Math.max(1, Math.round(mainW / 700))
+ const cw = mainW / count
+ for (let i = 0; i < count; i++) {
+ items.push(rect(x0 + arm + i * cw + 8, y0 + back + 8, cw - 16, seat - back - 16, { r: 45, s: 'thin' }))
+ }
+ items.push(rect(x1 - seat + 8, y0 + back + 8, seat - back - 16, seat - back - 16, { r: 45, s: 'thin' }))
+ items.push(rect(x1 - seat + 8, y0 + seat + 8, seat - back - 16, y1 - arm - (y0 + seat) - 16, { r: 45, s: 'thin' }))
+ return items
+}
+
+function chair(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ return [
+ rect(x0 + 15, y0 + 60, w - 30, d - 60, { r: 50 }),
+ rect(x0, y0, w, 100, { r: 40, f: 'tone' }),
+ ]
+}
+
+function dining(type: string, w: number, d: number): Prim[] {
+ const lay = diningLayout(type, w, d)
+ const items: Prim[] = lay.seats.map((s) => group(s.x, s.y, s.rot, chair(CHAIR.w, CHAIR.d)))
+ if (lay.round) {
+ items.push(circle(0, 0, lay.table.w / 2))
+ items.push(circle(0, 0, lay.table.w / 2 - 40, { s: 'thin', f: 'none' }))
+ } else {
+ items.push(rect(-lay.table.w / 2, -lay.table.d / 2, lay.table.w, lay.table.d, { r: 25 }))
+ items.push(rect(-lay.table.w / 2 + 40, -lay.table.d / 2 + 40, lay.table.w - 80, lay.table.d - 80, { r: 10, s: 'thin', f: 'none' }))
+ }
+ return items
+}
+
+function kitchenBase(w: number, d: number, handle: 'door' | 'drawer'): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const items: Prim[] = [rect(x0, y0, w, d), line([x0, y1 - 40, x0 + w, y1 - 40], { dash: true })]
+ if (handle === 'door') items.push(line([x0 + w - 70, y1 - 20, x0 + w - 70, y1 - 60], { s: 'main' }))
+ else items.push(line([-Math.min(120, w * 0.2), y1 - 20, Math.min(120, w * 0.2), y1 - 20], { s: 'main' }))
+ return items
+}
+
+function kitchenCorner(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const x1 = w / 2
+ const y1 = d / 2
+ const cd = Math.min(600, w - 200, d - 200)
+ return [
+ rect(x0, y0, w, d),
+ line([x1, y0 + cd - 40, x0 + cd - 40, y0 + cd - 40, x0 + cd - 40, y1], { dash: true }),
+ ]
+}
+
+function stove(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const qx = w / 4
+ const qy = (d - 90) / 4
+ const cy = y0 + (d - 90) / 2
+ const big = Math.min(qx, qy) * 0.78
+ const small = big * 0.72
+ const items: Prim[] = [rect(x0, y0, w, d), line([x0, y1 - 90, x0 + w, y1 - 90])]
+ const burners: [number, number, number][] = [
+ [-qx, cy - qy, small],
+ [qx, cy - qy, big],
+ [-qx, cy + qy, big],
+ [qx, cy + qy, small],
+ ]
+ for (const [bx, by, r] of burners) {
+ items.push(circle(bx, by, r, { s: 'main', f: 'none' }))
+ items.push(circle(bx, by, r * 0.55, { s: 'thin', f: 'none' }))
+ }
+ for (let i = 0; i < 4; i++) items.push(circle(x0 + (w / 5) * (i + 1), y1 - 45, 16, { s: 'thin', f: 'paper' }))
+ return items
+}
+
+function kitchenSink(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const items: Prim[] = [rect(x0, y0, w, d), line([x0, d / 2 - 40, x0 + w, d / 2 - 40], { dash: true })]
+ const drainer = w >= 750
+ const bw = drainer ? Math.min(450, w * 0.55) : w - 140
+ const bx = drainer ? x0 + 70 : x0 + 70
+ const by = y0 + 110
+ const bh = d - 230
+ items.push(rect(bx, by, bw, bh, { r: 60, f: 'water' }))
+ items.push(circle(bx + bw / 2, by + bh / 2 + 20, 28, { s: 'thin', f: 'none' }))
+ items.push(circle(bx + bw / 2, y0 + 55, 22, { s: 'thin', f: 'paper' }))
+ items.push(line([bx + bw / 2, y0 + 55, bx + bw / 2, by + 60], { s: 'main' }))
+ if (drainer) {
+ const dx0 = bx + bw + 50
+ const dx1 = x0 + w - 60
+ items.push(rect(dx0, by, dx1 - dx0, bh, { r: 30, s: 'thin', f: 'none' }))
+ for (let y = by + 60; y < by + bh - 30; y += 60) items.push(line([dx0 + 40, y, dx1 - 40, y]))
+ }
+ return items
+}
+
+function toilet(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const tank = Math.min(190, d * 0.28)
+ const top = y0 + tank - 20
+ const rx = w * 0.46
+ const len = y1 - top
+ const bowl = (s: number, dy: number) => {
+ const r = rx * s
+ const t = top + dy
+ const b = y1 - (1 - s) * len * 0.35
+ const l = b - t
+ return `M${n(-r)} ${n(t)} L${n(r)} ${n(t)} C${n(r)} ${n(t + l * 0.6)} ${n(r * 0.7)} ${n(b)} 0 ${n(b)} C${n(-r * 0.7)} ${n(b)} ${n(-r)} ${n(t + l * 0.6)} ${n(-r)} ${n(t)} Z`
+ }
+ return [
+ path(bowl(1, 0)),
+ path(bowl(0.66, len * 0.22), { s: 'thin', f: 'water' }),
+ rect(x0, y0, w, tank, { r: 30 }),
+ rect(-w * 0.12, y0 + tank * 0.35, w * 0.24, tank * 0.3, { r: 12, s: 'thin', f: 'none' }),
+ ]
+}
+
+function washbasin(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const x1 = w / 2
+ const shoulder = y0 + d * 0.3
+ const outer = `M${n(x0)} ${n(y0)} L${n(x1)} ${n(y0)} L${n(x1)} ${n(shoulder)} C${n(x1)} ${n(y1)} ${n(x1 * 0.55)} ${n(y1)} 0 ${n(y1)} C${n(x0 * 0.55)} ${n(y1)} ${n(x0)} ${n(y1)} ${n(x0)} ${n(shoulder)} Z`
+ return [
+ path(outer),
+ ellipse(0, y0 + d * 0.56, w * 0.36, d * 0.3, { s: 'thin', f: 'water' }),
+ circle(0, y0 + d * 0.6, 22, { s: 'thin', f: 'none' }),
+ circle(0, y0 + 55, 20, { s: 'thin', f: 'paper' }),
+ line([0, y0 + 55, 0, y0 + d * 0.3], { s: 'main' }),
+ ]
+}
+
+function vanity(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const bw = Math.min(w - 160, 520)
+ const bh = d - 170
+ return [
+ rect(x0, y0, w, d, { r: 12 }),
+ line([x0, d / 2 - 30, x0 + w, d / 2 - 30], { dash: true }),
+ rect(-bw / 2, y0 + 110, bw, bh, { r: Math.min(bw, bh) * 0.4, s: 'thin', f: 'water' }),
+ circle(0, y0 + 110 + bh / 2 + 15, 22, { s: 'thin', f: 'none' }),
+ circle(0, y0 + 55, 20, { s: 'thin', f: 'paper' }),
+ line([0, y0 + 55, 0, y0 + 120], { s: 'main' }),
+ ]
+}
+
+function bathtub(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const m = 70
+ return [
+ rect(x0, y0, w, d, { r: 40 }),
+ rect(x0 + m, y0 + m, w - 2 * m, d - 2 * m, { r: Math.min(220, (d - 2 * m) / 2), s: 'thin', f: 'water' }),
+ circle(x0 + m + 150, 0, 25, { s: 'thin', f: 'none' }),
+ rect(x0 + 18, -60, 40, 120, { r: 12, s: 'thin', f: 'paper' }),
+ ]
+}
+
+function shower(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const m = 45
+ const ix0 = x0 + m
+ const iy0 = y0 + m
+ const iw = w - 2 * m
+ const ih = d - 2 * m
+ return [
+ rect(x0, y0, w, d, { r: 10 }),
+ rect(ix0, iy0, iw, ih, { r: 30, s: 'thin', f: 'water' }),
+ line([ix0 + 20, iy0 + 20, ix0 + iw - 20, iy0 + ih - 20]),
+ line([ix0 + iw - 20, iy0 + 20, ix0 + 20, iy0 + ih - 20]),
+ circle(0, 0, 45, { s: 'thin', f: 'paper' }),
+ circle(0, 0, 20, { s: 'thin', f: 'none' }),
+ ]
+}
+
+function washer(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const r = Math.min(w, d - 110) * 0.36
+ const cy = y0 + 110 + (d - 110) / 2
+ return [
+ rect(x0, y0, w, d, { r: 25 }),
+ line([x0, y0 + 110, x0 + w, y0 + 110]),
+ rect(x0 + 40, y0 + 30, w * 0.3, 55, { r: 8, s: 'thin', f: 'none' }),
+ circle(x0 + w - 90, y0 + 57, 22, { s: 'thin', f: 'none' }),
+ circle(0, cy, r, { s: 'main', f: 'none' }),
+ circle(0, cy, r * 0.72, { s: 'thin', f: 'water' }),
+ ]
+}
+
+function waterHeater(w: number, d: number): Prim[] {
+ const r = Math.min(w, d) / 2
+ const cy = d / 2 - r
+ return [
+ line([-r * 0.35, -d / 2, -r * 0.35, cy], { s: 'main' }),
+ line([r * 0.35, -d / 2, r * 0.35, cy], { s: 'main' }),
+ circle(0, cy, r),
+ circle(0, cy, r * 0.8, { s: 'thin', f: 'none' }),
+ rect(-r * 0.3, cy + r * 0.25, r * 0.6, r * 0.28, { r: 10, s: 'thin', f: 'none' }),
+ ]
+}
+
+function coatRack(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const items: Prim[] = [rect(x0, y0, w, d, { f: 'none', dash: true }), rect(x0, y0, w, 40, { f: 'tone' })]
+ const coats = Math.max(1, Math.floor((w - 40) / 330))
+ const step = (w - 40) / coats
+ for (let i = 0; i < coats; i++) {
+ const x = x0 + 20 + step * (i + 0.5)
+ const cw = Math.min(300, step - 30)
+ items.push(rect(x - cw / 2, y0 + 70, cw, d - 110, { r: 70, s: 'thin', f: 'paper' }))
+ items.push(line([x - cw * 0.32, y0 + 95, x + cw * 0.32, y0 + 95], { s: 'main' }))
+ items.push(circle(x, y0 + 60, 14, { s: 'thin', f: 'tone' }))
+ }
+ return items
+}
+
+function shoeCabinet(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const items: Prim[] = [rect(x0, y0, w, d, { r: 8 }), line([x0, y1 - 30, x0 + w, y1 - 30])]
+ const pairs = Math.max(1, Math.floor((w - 60) / 260))
+ const pw = (w - 60) / pairs
+ for (let i = 0; i < pairs; i++) {
+ const cx = x0 + 30 + pw * (i + 0.5)
+ const sy = y0 + 40
+ const sh = d - 110
+ items.push(ellipse(cx - 55, sy + sh / 2, 42, sh / 2, { s: 'thin', f: 'none' }))
+ items.push(ellipse(cx + 55, sy + sh / 2, 42, sh / 2, { s: 'thin', f: 'none' }))
+ }
+ return items
+}
+
+function desk(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const mw = Math.min(600, w * 0.45)
+ const kw = Math.min(440, w * 0.36)
+ return [
+ rect(x0, y0, w, d, { r: 10 }),
+ rect(-mw / 2, y0 + 90, mw, 36, { r: 8, s: 'thin', f: 'dark' }),
+ rect(-70, y0 + 126, 140, 60, { r: 10, s: 'thin', f: 'none' }),
+ rect(-kw / 2, y1 - 230, kw, 140, { r: 12, s: 'thin', f: 'none' }),
+ ellipse(kw / 2 + 110, y1 - 160, 34, 52, { s: 'thin', f: 'none' }),
+ ]
+}
+
+function officeChair(w: number, d: number): Prim[] {
+ const r = Math.min(w, d) / 2 - 25
+ const items: Prim[] = []
+ for (let i = 0; i < 5; i++) {
+ const a = (i / 5) * Math.PI * 2 + Math.PI / 2
+ const x = Math.cos(a) * r
+ const y = Math.sin(a) * r
+ items.push(line([0, 0, x, y], { s: 'main' }))
+ items.push(circle(x, y, 24, { s: 'thin', f: 'paper' }))
+ }
+ const sw = w * 0.74
+ const sd = d * 0.64
+ items.push(rect(-sw / 2, -sd / 2 + 30, sw, sd, { r: 90 }))
+ items.push(path(`M${n(-sw / 2 - 10)} ${n(-sd / 2 + 60)} Q0 ${n(-d / 2 - 40)} ${n(sw / 2 + 10)} ${n(-sd / 2 + 60)} L${n(sw / 2 - 20)} ${n(-sd / 2 + 100)} Q0 ${n(-d / 2 + 20)} ${n(-sw / 2 + 20)} ${n(-sd / 2 + 100)} Z`, { f: 'tone' }))
+ return items
+}
+
+function fireplace(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const fw = w * 0.56
+ const fd = d * 0.55
+ return [
+ rect(x0, y0, w, d),
+ ...hatch(x0, y0, w, d, 70),
+ path(`M${n(-fw / 2)} ${n(y1)} L${n(-fw * 0.34)} ${n(y1 - fd)} L${n(fw * 0.34)} ${n(y1 - fd)} L${n(fw / 2)} ${n(y1)} Z`, { f: 'tone' }),
+ rect(x0, y0, w, d, { f: 'none' }),
+ ]
+}
+
+function masonryStove(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ const fw = Math.min(420, w * 0.4)
+ const cw = Math.min(270, w * 0.25)
+ return [
+ rect(x0, y0, w, d),
+ ...hatch(x0, y0, w, d, 90),
+ rect(-fw / 2, y1 - 120 - d * 0.35, fw, d * 0.35 + 120, { f: 'tone' }),
+ line([-fw / 2 - 40, y1, fw / 2 + 40, y1], { s: 'main' }),
+ rect(x0 + w - cw - 90, y0 + 90, cw, cw, { f: 'paper' }),
+ line([x0 + w - cw - 90, y0 + 90, x0 + w - 90, y0 + 90 + cw]),
+ line([x0 + w - 90, y0 + 90, x0 + w - cw - 90, y0 + 90 + cw]),
+ rect(x0, y0, w, d, { f: 'none' }),
+ ]
+}
+
+function gasBoiler(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const r = Math.min(w, d) * 0.22
+ return [
+ rect(x0, y0, w, d, { r: 25 }),
+ rect(x0 + 35, y0 + 35, w - 70, d - 70, { r: 18, s: 'thin', f: 'none' }),
+ circle(0, 0, r, { s: 'thin', f: 'none' }),
+ circle(0, 0, r * 0.45, { s: 'thin', f: 'tone' }),
+ ]
+}
+
+function floorBoiler(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ return [
+ rect(x0, y0, w, d, { r: 20 }),
+ line([x0, y1 - 40, x0 + w, y1 - 40]),
+ circle(0, y0 + 150, 75, { s: 'main', f: 'tone' }),
+ circle(0, y0 + 150, 45, { s: 'thin', f: 'none' }),
+ rect(-w * 0.3, y1 - 200, w * 0.6, 110, { r: 10, s: 'thin', f: 'none' }),
+ ]
+}
+
+function nightstand(w: number, d: number): Prim[] {
+ return [
+ rect(-w / 2, -d / 2, w, d, { r: 12 }),
+ line([-w / 2, d / 2 - 25, w / 2, d / 2 - 25]),
+ circle(0, -15, Math.min(w, d) * 0.24, { s: 'thin', f: 'none' }),
+ circle(0, -15, Math.min(w, d) * 0.07, { s: 'thin', f: 'tone' }),
+ ]
+}
+
+function dresser(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y1 = d / 2
+ const items: Prim[] = [rect(x0, -d / 2, w, d, { r: 10 }), line([x0, y1 - 30, x0 + w, y1 - 30])]
+ const cols = Math.max(1, Math.round(w / 500))
+ for (let i = 1; i < cols; i++) items.push(line([x0 + (w / cols) * i, y1 - 30, x0 + (w / cols) * i, y1]))
+ return items
+}
+
+function coffeeTable(w: number, d: number): Prim[] {
+ return [
+ rect(-w / 2, -d / 2, w, d, { r: 60 }),
+ rect(-w / 2 + 50, -d / 2 + 50, w - 100, d - 100, { r: 30, s: 'thin', f: 'none' }),
+ ]
+}
+
+function tvStand(w: number, d: number): Prim[] {
+ const tw = Math.min(w * 0.85, 1450)
+ const y0 = -d / 2
+ return [
+ rect(-w / 2, y0, w, d, { r: 10 }),
+ line([-w / 2, d / 2 - 30, w / 2, d / 2 - 30]),
+ rect(-150, y0 + 70, 300, 160, { r: 20, s: 'thin', f: 'none' }),
+ rect(-tw / 2, y0 + 110, tw, 45, { r: 10, s: 'main', f: 'dark' }),
+ ]
+}
+
+function bookcase(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const items: Prim[] = [rect(x0, y0, w, d), rect(x0 + 25, y0 + 25, w - 50, d - 50, { s: 'thin', f: 'none' })]
+ const sections = Math.max(1, Math.round(w / 400))
+ for (let i = 1; i < sections; i++) items.push(line([x0 + (w / sections) * i, y0 + 25, x0 + (w / sections) * i, y0 + d - 25]))
+ items.push(line([x0, y0, x0 + w, y0 + d]))
+ return items
+}
+
+function upper(w: number, d: number): Prim[] {
+ return [
+ rect(-w / 2, -d / 2, w, d, { f: 'none', dash: true }),
+ line([-w / 2, -d / 2, w / 2, d / 2], { dash: true }),
+ ]
+}
+
+function dishwasher(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const items: Prim[] = [rect(x0, y0, w, d), rect(x0 + 50, y0 + 50, w - 100, d - 130, { r: 20, s: 'thin', f: 'none' })]
+ for (let i = 1; i <= 4; i++) {
+ const x = x0 + 50 + ((w - 100) / 5) * i
+ items.push(line([x, y0 + 80, x, y0 + d - 110]))
+ }
+ items.push(line([x0, d / 2 - 40, x0 + w, d / 2 - 40], { dash: true }))
+ return items
+}
+
+function fridge(w: number, d: number): Prim[] {
+ const x0 = -w / 2
+ const y0 = -d / 2
+ const y1 = d / 2
+ return [
+ rect(x0, y0, w, d, { r: 20 }),
+ line([x0, y1 - 60, x0 + w, y1 - 60], { s: 'main' }),
+ line([x0 + 30, y0 + 30, x0 + w - 30, y1 - 90]),
+ line([x0 + w - 30, y0 + 30, x0 + 30, y1 - 90]),
+ line([x0 + w - 70, y1 - 60, x0 + w - 70, y1 - 10], { s: 'main' }),
+ ]
+}
+
+function plant(w: number, d: number): Prim[] {
+ const r = Math.min(w, d) / 2
+ const pot = r * 0.62
+ const items: Prim[] = [circle(0, 0, pot, { s: 'thin', f: 'tone' })]
+ const leaves = 9
+ for (let i = 0; i < leaves; i++) {
+ const a = (i / leaves) * Math.PI * 2 + (i % 2) * 0.25
+ const len = r * (i % 2 ? 0.86 : 1)
+ const tx = Math.cos(a) * len
+ const ty = Math.sin(a) * len
+ const mx = Math.cos(a) * len * 0.5
+ const my = Math.sin(a) * len * 0.5
+ const wx = -Math.sin(a) * len * 0.24
+ const wy = Math.cos(a) * len * 0.24
+ items.push(path(`M0 0 Q${n(mx + wx)} ${n(my + wy)} ${n(tx)} ${n(ty)} Q${n(mx - wx)} ${n(my - wy)} 0 0 Z`, { s: 'thin', f: 'paper' }))
+ items.push(line([Math.cos(a) * len * 0.15, Math.sin(a) * len * 0.15, tx * 0.85, ty * 0.85]))
+ }
+ return items
+}
+
+function armchair(w: number, d: number): Prim[] {
+ const back = Math.min(200, d * 0.24)
+ const arm = Math.min(170, w * 0.2)
+ return sofaPieces(-w / 2, -d / 2, w, d, back, arm)
+}
+
+function generic(w: number, d: number): Prim[] {
+ return [rect(-w / 2, -d / 2, w, d, { r: 10 }), line([-w / 2, -d / 2, w / 2, d / 2]), line([w / 2, -d / 2, -w / 2, d / 2])]
+}
+
+export function furnitureSymbol(type: string, w: number, d: number): Prim[] {
+ switch (type) {
+ case 'bed-1600':
+ case 'bed-1800':
+ return bed(w, d, 2)
+ case 'bed-900':
+ return bed(w, d, 1)
+ case 'nightstand':
+ return nightstand(w, d)
+ case 'wardrobe':
+ return cabinetDoors(w, d, false)
+ case 'hall-wardrobe':
+ return cabinetDoors(w, d, true)
+ case 'dresser':
+ return dresser(w, d)
+ case 'sofa':
+ return sofa(w, d)
+ case 'sofa-corner':
+ return sofaCorner(w, d)
+ case 'armchair':
+ return armchair(w, d)
+ case 'coffee-table':
+ return coffeeTable(w, d)
+ case 'tv-stand':
+ return tvStand(w, d)
+ case 'bookcase':
+ return bookcase(w, d)
+ case 'plant':
+ return plant(w, d)
+ case 'kitchen-base':
+ return kitchenBase(w, d, 'door')
+ case 'kitchen-drawers':
+ return kitchenBase(w, d, 'drawer')
+ case 'kitchen-corner':
+ return kitchenCorner(w, d)
+ case 'kitchen-upper':
+ return upper(w, d)
+ case 'kitchen-sink':
+ return kitchenSink(w, d)
+ case 'stove':
+ return stove(w, d)
+ case 'dishwasher':
+ return dishwasher(w, d)
+ case 'fridge':
+ return fridge(w, d)
+ case 'dining-4':
+ case 'dining-6':
+ case 'dining-round':
+ return dining(type, w, d)
+ case 'chair':
+ return chair(w, d)
+ case 'toilet':
+ return toilet(w, d)
+ case 'washbasin':
+ return washbasin(w, d)
+ case 'vanity':
+ return vanity(w, d)
+ case 'bathtub':
+ return bathtub(w, d)
+ case 'shower':
+ return shower(w, d)
+ case 'washer':
+ return washer(w, d)
+ case 'water-heater':
+ return waterHeater(w, d)
+ case 'coat-rack':
+ return coatRack(w, d)
+ case 'shoe-cabinet':
+ return shoeCabinet(w, d)
+ case 'desk':
+ return desk(w, d)
+ case 'office-chair':
+ return officeChair(w, d)
+ case 'fireplace':
+ return fireplace(w, d)
+ case 'masonry-stove':
+ return masonryStove(w, d)
+ case 'gas-boiler':
+ return gasBoiler(w, d)
+ case 'floor-boiler':
+ return floorBoiler(w, d)
+ default:
+ return generic(w, d)
+ }
+}
diff --git a/src/i18n/index.ts b/src/i18n/index.ts
new file mode 100644
index 0000000..b36b42d
--- /dev/null
+++ b/src/i18n/index.ts
@@ -0,0 +1,87 @@
+import i18n from 'i18next'
+import LanguageDetector from 'i18next-browser-languagedetector'
+import { initReactI18next } from 'react-i18next'
+
+export const LANGUAGES = ['en', 'ru'] as const
+export type Lang = (typeof LANGUAGES)[number]
+
+type Tree = { [k: string]: string | Tree }
+
+const isTree = (v: unknown): v is Tree => typeof v === 'object' && v !== null && !Array.isArray(v)
+
+const merge = (into: Tree, from: Tree) => {
+ for (const [k, v] of Object.entries(from)) {
+ const cur = into[k]
+ if (isTree(v) && isTree(cur)) merge(cur, v)
+ else into[k] = v
+ }
+ return into
+}
+
+// Files are locales/<lng>/<ns>.json; extra parts like <ns>.<part>.json are deep-merged into <ns>.
+const files = import.meta.glob<Tree>('./locales/*/*.json', { eager: true, import: 'default' })
+const resources: Record<string, Record<string, Tree>> = {}
+for (const [path, data] of Object.entries(files)) {
+ const m = /\.\/locales\/([^/]+)\/([^/.]+)(?:\.[^/]+)?\.json$/.exec(path)
+ if (!m) continue
+ const [, lng, ns] = m
+ const byNs = (resources[lng] ??= {})
+ byNs[ns] = merge(byNs[ns] ?? {}, data)
+}
+
+void i18n
+ .use(LanguageDetector)
+ .use(initReactI18next)
+ .init({
+ resources,
+ fallbackLng: 'en',
+ supportedLngs: [...LANGUAGES],
+ nonExplicitSupportedLngs: true,
+ load: 'languageOnly',
+ ns: ['common', 'plan', 'networks', 'estimate', 'info', 'map', 'view3d'],
+ defaultNS: 'common',
+ interpolation: { escapeValue: false },
+ returnNull: false,
+ initAsync: false,
+ saveMissing: import.meta.env.DEV,
+ missingKeyHandler: (_lngs, ns, key) => console.warn(`[i18n] missing key ${ns}:${key}`),
+ detection: {
+ order: ['localStorage', 'cookie', 'navigator'],
+ lookupLocalStorage: 'lang',
+ lookupCookie: 'lang',
+ caches: ['localStorage', 'cookie'],
+ },
+ })
+
+const syncDocument = (lng: string) => {
+ document.documentElement.lang = lng
+ document.title = i18n.t('common:app.title')
+}
+syncDocument(i18n.resolvedLanguage ?? 'en')
+i18n.on('languageChanged', syncDocument)
+
+export const lang = (): Lang => (i18n.resolvedLanguage === 'ru' ? 'ru' : 'en')
+export const locale = () => (lang() === 'ru' ? 'ru-RU' : 'en-US')
+export const setLang = (lng: Lang) => i18n.changeLanguage(lng)
+
+const formats = new Map<string, Intl.NumberFormat>()
+export const numberFormat = (opts: Intl.NumberFormatOptions = {}) => {
+ const key = locale() + JSON.stringify(opts)
+ let f = formats.get(key)
+ if (!f) {
+ f = new Intl.NumberFormat(locale(), opts)
+ formats.set(key, f)
+ }
+ return f
+}
+
+// Locale-aware number: fmtNum(1234.5, 1) → "1,234.5" (en) / "1 234,5" (ru).
+export const fmtNum = (v: number, maxDigits = 2, minDigits = 0) =>
+ numberFormat({ maximumFractionDigits: maxDigits, minimumFractionDigits: minDigits }).format(v)
+
+export const fmtRub = (v: number) => `${fmtNum(Math.round(v), 0)} ₽`
+
+export const fmtDateTime = (d: Date, opts: Intl.DateTimeFormatOptions) => d.toLocaleString(locale(), opts)
+
+export const t = i18n.t.bind(i18n)
+export default i18n
diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json
new file mode 100644
index 0000000..72bcfb2
--- /dev/null
+++ b/src/i18n/locales/en/common.json
@@ -0,0 +1,161 @@
+{
+ "app": {
+ "title": "House Planner"
+ },
+ "units": {
+ "mm": "mm",
+ "cm": "cm",
+ "m": "m",
+ "m2": "m²",
+ "m3": "m³",
+ "pcs": "pcs",
+ "rub": "₽",
+ "kw": "kW",
+ "w": "W",
+ "deg": "°",
+ "roll": "roll",
+ "coil": "coil",
+ "pack": "pack",
+ "kg": "kg",
+ "l": "L",
+ "set": "set",
+ "sheet": "sheet",
+ "kit": "kit"
+ },
+ "language": {
+ "label": "Language",
+ "en": "English",
+ "ru": "Русский"
+ },
+ "sections": {
+ "plan": "Plan",
+ "3d": "3D",
+ "map": "Map",
+ "estimate": "Estimate",
+ "info": "Plot & house",
+ "infoShort": "Plot"
+ },
+ "loading": {
+ "3d": "Loading 3D…",
+ "map": "Loading map…",
+ "estimate": "Loading estimate…",
+ "generic": "Loading…",
+ "plan": "Loading plan…"
+ },
+ "status": {
+ "cursor": "x {{x}} m · y {{y}} m",
+ "cursorEmpty": "x — · y —",
+ "hintWall": "Click — point, Shift — 45° angle, Esc/right click — finish",
+ "hintDoor": "Hover a wall and click to place a door · Esc — exit",
+ "hintWindow": "Hover a wall and click to place a window · Esc — exit",
+ "hintSelect": "Drag wall ends and middle · Alt — detach · Shift — 45° · ⌘Z — undo"
+ },
+ "header": {
+ "subtitle": "plot {{width}} × {{depth}} m · {{walls}} · {{openings}}",
+ "walls_one": "{{count}} wall",
+ "walls_other": "{{count}} walls",
+ "openings_one": "{{count}} opening",
+ "openings_other": "{{count}} openings",
+ "loadingPlan": "Loading plan…",
+ "viewOnly": "View only"
+ },
+ "grid": {
+ "title": "Grid cell size at the current zoom",
+ "legend": "Cell {{minor}} · major {{major}}"
+ },
+ "preview": {
+ "label": "Viewing version <strong>{{label}}</strong> — read only",
+ "back": "Back",
+ "restore": "Restore this one",
+ "confirm": "Restore version {{label}}? It will be saved as a new revision, history is kept."
+ },
+ "save": {
+ "saving": "Saving…",
+ "offline": "No connection to server · retry",
+ "saved": "Saved",
+ "savedAt": "Saved · {{time}}"
+ },
+ "login": {
+ "loading": "Loading plan from server…",
+ "offlineTitle": "No connection to server",
+ "offlineText": "The plan is stored only on the server; the editor can't open without a connection.",
+ "retry": "Retry",
+ "password": "Password",
+ "checking": "Checking…",
+ "signIn": "Sign in"
+ },
+ "menu": {
+ "more": "More",
+ "plan": "Plan",
+ "exportJson": "Export JSON",
+ "importJson": "Import JSON",
+ "versions": "Versions",
+ "importInvalid": "The plan failed validation:\n\n{{error}}"
+ },
+ "versions": {
+ "saved": "Saved",
+ "all": "All changes",
+ "defaultName": "Version {{date}}",
+ "snapshot": "snapshot",
+ "saveVersion": "Save version…",
+ "save": "Save",
+ "loading": "Loading…",
+ "empty": "No saved versions yet",
+ "open": "Open",
+ "restore": "Restore",
+ "current": "current",
+ "walls_one": "{{count}} wall",
+ "walls_other": "{{count}} walls",
+ "confirmSnapshot": "Restore “{{name}}”? It will be saved as a new revision, history is kept.",
+ "confirmRevision": "Restore revision #{{rev}}? It will be saved as a new revision, history is kept.",
+ "quoted": "“{{name}}”"
+ },
+ "planFile": {
+ "notJson": "File is not JSON: {{message}}"
+ },
+ "lengthField": {
+ "title": "mm or m: 2800, 2.8 m, 280 cm"
+ },
+ "sync": {
+ "wrongPassword": "Wrong password",
+ "loginHttp": "Sign-in error: HTTP {{status}}",
+ "offline": "No connection to server",
+ "cookieNotSaved": "Sign-in cookie was not saved",
+ "planChanged": "The plan was updated, please repeat the action",
+ "saveFailedReason": "Not saved: {{reason}}",
+ "saveFailed": "Not saved on the server — change reverted",
+ "siteUpdated": "The site was updated — reloading",
+ "invalidServerPlan": "Server plan failed validation: {{error}}",
+ "noSnapshot": "No snapshot {{id}}",
+ "noVersion": "No version {{rev}}"
+ },
+ "canvas": {
+ "addDoor": "+ door",
+ "addWindow": "+ window",
+ "defaultRoomName": "Room",
+ "moveHouseHint": "To move the whole house, use the “Building” tool (B)",
+ "noRoomOnWall": "No room on the wall",
+ "alignTitle": "Aligning the image",
+ "alignHint": "drag center — move, handle — rotate · Esc — done",
+ "labelRoom": "Label room",
+ "measureSum": "Total: {{sum}} m",
+ "measureHint": "Click — point A, click — point B · ⌘ — chain · Shift — 45° · Alt — no snapping · M/Esc — clear",
+ "groupMove": "Δx {{x}} m · Δy {{y}} m",
+ "planUp": "Plan up",
+ "northUp": "North up",
+ "rotateCcw": "Rotate 15° counterclockwise",
+ "rotateCw": "Rotate 15° clockwise",
+ "compass": "North · click — plan up",
+ "walls_one": "{{count}} wall",
+ "walls_other": "{{count}} walls",
+ "openings_one": "{{count}} opening",
+ "openings_other": "{{count}} openings",
+ "items_one": "{{count}} item",
+ "items_other": "{{count}} items",
+ "selSummary": "{{walls}}, {{openings}}, {{items}}"
+ },
+ "demo": {
+ "long": "Demo: changes are visible to everyone and reset every hour — get your own copy on",
+ "short": "Demo: shared plan, resets hourly"
+ }
+}
diff --git a/src/i18n/locales/en/estimate.json b/src/i18n/locales/en/estimate.json
new file mode 100644
index 0000000..5003970
--- /dev/null
+++ b/src/i18n/locales/en/estimate.json
@@ -0,0 +1,109 @@
+{
+ "page": {
+ "title": "Estimate",
+ "downloadCsv": "Download CSV",
+ "newLine": "New item",
+ "newNote": "New note",
+ "addLine": "+ item",
+ "addNote": "+ note",
+ "total": "Total",
+ "notesTitle": "Order notes",
+ "noNotes": "No notes",
+ "openInStore": "Open in store",
+ "deleteLine": "Delete item",
+ "confirmDelete": "Delete “{{name}}”?",
+ "bought": "Purchased",
+ "boughtOn": "Purchased {{date}}",
+ "markBought": "Mark as purchased",
+ "delete": "Delete"
+ },
+ "columns": {
+ "n": "No.",
+ "name": "Item",
+ "qty": "Qty",
+ "unit": "Unit",
+ "price": "Price",
+ "sum": "Amount"
+ },
+ "colors": {
+ "title": "Colors (RAL)",
+ "empty": "No colors selected — set them in the 3D tab",
+ "joined": "{{a}} and {{b}}",
+ "slots": {
+ "walls": "Walls",
+ "gates": "Gates",
+ "roof": "Roof and gutters",
+ "windows": "Windows",
+ "accent": "Accent",
+ "plinth": "Plinth"
+ }
+ },
+ "csv": {
+ "fileName": "estimate-{{date}}.csv",
+ "yes": "yes",
+ "no": "no",
+ "total": "Total",
+ "sectionTotal": "Section total “{{section}}”",
+ "columns": {
+ "section": "Section",
+ "n": "No.",
+ "name": "Item",
+ "sku": "SKU",
+ "qty": "Qty",
+ "unit": "Unit",
+ "price": "Price",
+ "sum": "Amount",
+ "bought": "Purchased",
+ "url": "Link",
+ "note": "Note"
+ }
+ },
+ "sections": {
+ "manual": "Manual items",
+ "auto": "Walls, windows and doors"
+ },
+ "rows": {
+ "door": "Door {{w}}×{{h}} mm",
+ "gate": "Gate {{w}}×{{h}} mm",
+ "window": "Window {{w}}×{{h}} mm",
+ "priceBy": "price per: {{item}}",
+ "areaEstimate": "estimate by area from {{w}}×{{h}} mm: {{item}}"
+ },
+ "wallLine": {
+ "noMaterial": "Walls without material"
+ },
+ "cart": {
+ "open": "Build Petrovich cart",
+ "title": "Petrovich cart",
+ "close": "Close",
+ "demoDisabled": "The Petrovich cart is disabled in the demo — run your own copy",
+ "onlyLeft": "Only not purchased",
+ "oneLink": "One link for everything",
+ "perSection": "One link per section",
+ "building_one": "Building… {{count}} item",
+ "building_other": "Building… {{count}} items",
+ "withCode_one": "{{count}} item with a Petrovich code",
+ "withCode_other": "{{count}} items with a Petrovich code",
+ "linkCount": "{{count}} items",
+ "openLink": "Open",
+ "copy": "Copy",
+ "copied": "Copied",
+ "error": "error — {{error}}. ",
+ "missing": "not found or out of stock: {{list}}",
+ "all": "Everything",
+ "outdated": "The site has been updated — reloading",
+ "cities": {
+ "spb": "Saint Petersburg",
+ "vbg": "Vyborg"
+ },
+ "sections": {
+ "house": "House",
+ "garage": "Garage",
+ "electric": "Electrical",
+ "sewer": "Sewer",
+ "water": "Water supply",
+ "heating": "Underfloor heating",
+ "other": "Other"
+ }
+ }
+}
diff --git a/src/i18n/locales/en/info.json b/src/i18n/locales/en/info.json
new file mode 100644
index 0000000..a5bcd63
--- /dev/null
+++ b/src/i18n/locales/en/info.json
@@ -0,0 +1,19 @@
+{
+ "loadError": "Failed to load data: {{error}}",
+ "loading": "Loading…",
+ "updated": "updated {{date}}",
+ "sectionsNav": "Sections",
+ "collecting": "being collected",
+ "unverified": "not verified",
+ "source": "Source:",
+ "dated": "dated {{date}}",
+ "more": "More",
+ "map": {
+ "title": "Site diagram",
+ "north": "N",
+ "parcel": "site",
+ "zone": "buildable area",
+ "neighbors": "neighbors",
+ "street": "street"
+ }
+}
diff --git a/src/i18n/locales/en/map.json b/src/i18n/locales/en/map.json
new file mode 100644
index 0000000..2cb2f34
--- /dev/null
+++ b/src/i18n/locales/en/map.json
@@ -0,0 +1,46 @@
+{
+ "attribution": "Imagery © Esri, Vantor, Earthstar Geographics",
+ "orientation": { "plan": "Plan up", "north": "North up" },
+ "legend": {
+ "title": "Legend",
+ "site": "Site (plan boundary)",
+ "neighbor": "Adjacent plots from data/parcel.geojson",
+ "street": "Street side",
+ "walls": "House walls"
+ },
+ "panel": {
+ "eyebrow": "Map",
+ "titleAlign": "Imagery alignment",
+ "titlePlan": "Plan on imagery",
+ "expand": "Expand",
+ "collapse": "Collapse",
+ "opacity": "Plan opacity",
+ "done": "Done",
+ "align": "Align imagery",
+ "toSite": "Go to site",
+ "notBound": "The plan isn't georeferenced: set geo via “Boundary from GeoJSON”.",
+ "alignHint": "The cadastre and the plan stay in place, the imagery moves. “0” — match the plan origin with its place on the imagery, “X” — rotate along the X axis.",
+ "reset": "Reset",
+ "imagery": "imagery: E {{e}} m · N {{n}} m · {{rot}}°",
+ "copied": "Copied",
+ "copy": "Copy"
+ },
+ "geojson": {
+ "summary": "Boundary from GeoJSON",
+ "autoGeo": "Compute geo from polygon",
+ "startVertex": "Origin at vertex No.",
+ "convert": "Recalculate",
+ "apply": "Apply to plan",
+ "result_one": "{{count}} vertex · {{w}} × {{d}} m · {{area}} m² · rotation {{rot}}°",
+ "result_other": "{{count}} vertices · {{w}} × {{d}} m · {{area}} m² · rotation {{rot}}°",
+ "notBound": "The plan isn't georeferenced: enable “Compute geo from polygon”",
+ "noPolygon": "No polygon in the GeoJSON",
+ "tooFewVertices": "The polygon has fewer than three vertices"
+ },
+ "underlay": {
+ "ccw1": "Rotate imagery counterclockwise by 1°",
+ "ccw01": "Rotate imagery counterclockwise by 0.1°",
+ "cw01": "Rotate imagery clockwise by 0.1°",
+ "cw1": "Rotate imagery clockwise by 1°"
+ }
+}
diff --git a/src/i18n/locales/en/networks.json b/src/i18n/locales/en/networks.json
new file mode 100644
index 0000000..48ef05c
--- /dev/null
+++ b/src/i18n/locales/en/networks.json
@@ -0,0 +1,635 @@
+{
+ "shared": {
+ "layers": {
+ "walls": "Walls",
+ "furniture": "Furniture",
+ "zones": "Zones",
+ "sewer": "Sewer",
+ "water": "Water supply",
+ "electric": "Electrical",
+ "heating": "Underfloor heating"
+ },
+ "locks": {
+ "walls": "Walls are locked — unlock them in Layers",
+ "editing": "Network editing is on — exit it (Esc) to edit everything else",
+ "layer": "Layer is locked — unlock it in Layers"
+ },
+ "tools": {
+ "buttonTitle": "Plan layers and utility networks",
+ "buttonLabel": "Layers · {{count}}",
+ "heading": "Layers",
+ "unlock": "Unlock: {{layer}}",
+ "lock": "Lock: {{layer}}",
+ "lockedTitle": "Layer is locked — click to unlock",
+ "lockTitle": "Lock the layer against accidental edits",
+ "edit": "Edit: {{layer}}",
+ "note": "Lock — the layer stays visible but can't be edited. An enabled network dims everything else to 40%",
+ "editing": "Editing: {{layer}}",
+ "exitLabel": "Exit editing (Esc)",
+ "exitTitle": "Exit (Esc)"
+ },
+ "ui": {
+ "close": "Close",
+ "delete": "Delete",
+ "where": "Location",
+ "inside": "Inside",
+ "outside": "Outside",
+ "insideLower": "inside",
+ "outsideLower": "outside",
+ "diameter": "Diameter",
+ "length": "Length",
+ "type": "Type",
+ "fixture": "Fixture",
+ "model": "Model",
+ "center": "Center",
+ "materials": "Materials",
+ "networks": "Utility networks",
+ "noPrice": "no price set",
+ "warnings": "Warnings · {{count}}",
+ "modeSelect": "Select",
+ "modeSelectTitle": "Select: click a pipe or node, drag nodes, Delete removes",
+ "hintSelect": "drag nodes · Delete removes",
+ "missing_one": "no price: {{count}} item",
+ "missing_other": "no price: {{count}} items"
+ },
+ "units": {
+ "pct": "{{v}}%",
+ "pack": "pack"
+ },
+ "pricing": {
+ "fromMaterials": "price from network materials: {{name}}",
+ "fromCatalog": "price based on: {{name}}",
+ "includedInBorehole": "included in the borehole setup — not counted separately"
+ },
+ "warn": {
+ "notConnected": "{{name}}: fixture not connected"
+ }
+ },
+ "sewer": {
+ "fixture": {
+ "toilet": "Toilet",
+ "sink": "Washbasin",
+ "bath": "Bathtub",
+ "shower": "Shower",
+ "washer": "Washing machine",
+ "kitchen": "Kitchen sink",
+ "boiler": "Boiler, water heater"
+ },
+ "kind": {
+ "fixture": "Fixture",
+ "riser": "Riser",
+ "cleanout": "Cleanout",
+ "outlet": "Outlet",
+ "septic": "Septic tank",
+ "junction": "Joint"
+ },
+ "item": {
+ "pipeOutside": "Outdoor PVC sewer pipe Ø{{d}} (orange)",
+ "pipeInside": "Indoor sewer pipe Ø{{d}}",
+ "elbow": "Elbow {{angle}}° Ø{{d}}",
+ "elbowOut": "Outdoor elbow {{angle}}° Ø{{d}}",
+ "clamp": "Pipe clamp Ø{{d}}",
+ "corrugation": "Corrugated toilet connector Ø110",
+ "cleanout": "Cleanout Ø{{d}}",
+ "cleanoutOut": "Outdoor cleanout Ø{{d}}",
+ "vent": "Vent cap / air admittance valve Ø110",
+ "tee87": "Tee 87° Ø110",
+ "tee87Reduced": "Tee 87° 110/{{branch}}",
+ "tee45": "Tee 45° Ø{{d}}",
+ "tee45Out": "Outdoor tee 45° Ø{{d}}",
+ "tee45Reduced": "Tee 45° {{main}}/{{branch}}",
+ "tee45ReducedOut": "Outdoor tee 45° {{main}}/{{branch}}",
+ "sleeve": "Foundation sleeve for outlet Ø{{d}}",
+ "septic": "Septic tank",
+ "septicModel": "Septic tank {{model}}",
+ "reducer": "Reducer {{big}}/{{small}}"
+ },
+ "warn": {
+ "loop": "The network has a loop: flow must go one way — reverse a pipe",
+ "slopeLow": "{{id}}: slope {{slope}} is below the {{min}} minimum for Ø{{d}} (SP 30.13330)",
+ "shallow": "{{id}}: outdoor pipe at {{depth}} depth — less than {{min}}, insulate it",
+ "thinner": "{{id}}: Ø{{d}} is smaller than the inflow (Ø{{up}})",
+ "toiletPipe": "{{id}}: a toilet needs a Ø110 pipe",
+ "riserPipe": "{{id}}: a riser needs a Ø110 pipe",
+ "septicHouse": "Septic tank {{name}}: {{dist}} to the foundation — at least {{min}} required",
+ "septicBoundary": "Septic tank {{name}}: {{dist}} to the property line — at least {{min}} required",
+ "sharpTurn": "{{id}}: {{deg}}° horizontal turn with an 87° elbow — better two 45° elbows or a cleanout",
+ "deadEnd": "{{id}}: the run ends here — extend it to the outlet and septic tank"
+ },
+ "panel": {
+ "eyebrowPipe": "Sewer · pipe",
+ "eyebrowNode": "Sewer · {{kind}}",
+ "slope": "Slope",
+ "depthStart": "Depth at start",
+ "drop": "Drop",
+ "invert": "Invert, start → end",
+ "slopeNorm": "Minimum slope",
+ "min": "min {{v}}",
+ "flow": "Flow",
+ "reverse": "Reverse flow",
+ "pipeHint": "Slope in percent: 2% = 20 mm per metre. Invert levels are relative to ground, floor at {{floor}}. Delete removes.",
+ "riserHeight": "Riser height",
+ "modelPlaceholder": "Tver 0.75",
+ "width": "Width",
+ "rotation": "Rotation",
+ "invertLevel": "Invert level",
+ "outletDepth": "Outlet depth at wall",
+ "inletDepth": "Inlet depth",
+ "toFoundation": "To foundation",
+ "toBoundary": "To property line",
+ "septicNorms": "Rules: at least {{house}} from the foundation, at least {{boundary}} from the property line.",
+ "nodeHint": "Drag the node on the plan. Delete removes it; an intermediate node is removed and the pipe is joined."
+ },
+ "summary": {
+ "empty": "No runs yet. Use the Sewer tool in the left panel: click a toilet or washbasin, then click along the run to the outlet and septic tank.",
+ "outletRow": "Outlet {{id}}, depth at wall",
+ "septicRow": "Septic tank, inlet depth",
+ "septicRowModel": "Septic tank {{model}}, inlet depth",
+ "total": "Sewer total",
+ "floorAbove": "Floor above ground",
+ "hint": "Prices come from the network materials in the plan, otherwise from the catalog. Slopes per SP 30.13330: Ø50 — from 2.5%, Ø110 — from 1.2%, outdoors — from 1%."
+ },
+ "edit": {
+ "trace": "Run",
+ "traceTitle": "Run: click a fixture or node, then clicks add nodes and pipes",
+ "cleanout": "Cleanout",
+ "cleanoutTitle": "Next node of the run is a cleanout",
+ "riser": "Riser",
+ "riserTitle": "Next node of the run is a riser",
+ "outlet": "Outlet",
+ "outletTitle": "Next node of the run is an outlet through the foundation",
+ "septic": "Septic",
+ "septicTitle": "Click places a septic tank, the run ends there",
+ "hintTrace": "click a fixture → click along the run · double-click or Enter to finish"
+ },
+ "layer": {
+ "connectFixture": "connect fixture"
+ }
+ },
+ "water": {
+ "lineShort": {
+ "cold": "CW",
+ "hot": "HW",
+ "recirc": "Recirc."
+ },
+ "line": {
+ "cold": "Cold",
+ "hot": "Hot",
+ "recirc": "Recirculation"
+ },
+ "kind": {
+ "source": "Source",
+ "entry": "House entry",
+ "pump": "Pump station",
+ "filter": "Filter",
+ "boiler": "Water heater",
+ "collector": "Manifold",
+ "fixture": "Fixture",
+ "junction": "Junction",
+ "tap_outdoor": "Outdoor tap"
+ },
+ "source": {
+ "borehole": "Borehole",
+ "well": "Well"
+ },
+ "caption": {
+ "depth": "depth {{depth}}"
+ },
+ "item": {
+ "insulation": "Pipe insulation Ø{{d}}",
+ "heatCable": "Pipe heating cable",
+ "sleeve": "Wall sleeve for pipe Ø{{d}}",
+ "pipe": "{{material}} pipe Ø{{d}}",
+ "pipeOut": "Outdoor {{material}} pipe Ø{{d}}",
+ "head": "Borehole cap",
+ "tap": "Frost-free outdoor tap",
+ "socket": "Wall-plate elbow Ø{{d}}",
+ "collector_one": "Manifold, {{count}} outlet",
+ "collector_other": "Manifold, {{count}} outlets",
+ "collectorOut": "Manifold outlet fitting Ø{{d}}",
+ "pump": "Pump / pump station",
+ "pumpModel": "Pump {{model}}",
+ "adapter": "Threaded adapter Ø{{d}}",
+ "tee": "Press tee Ø{{d}}",
+ "reducer": "Press reducer {{big}}/{{small}}",
+ "elbow": "Press elbow Ø{{d}}"
+ },
+ "warn": {
+ "frostNoDepth": "{{id}}: outdoor pipe without depth — must be below frost depth {{frost}} or have a heating cable",
+ "frostShallow": "{{id}}: outdoor pipe at {{depth}} depth — must be below frost depth {{frost}} or have a heating cable",
+ "toSewer": "{{id}}: {{dist}} to the sewer — at least {{min}} required (or a sleeved crossing)",
+ "sourcePassport": "{{what}}: {{dist}} to the septic tank — less than {{min}} even per the septic tank's datasheet",
+ "sourceSanpin": "{{what}}: {{dist}} to the septic tank — SanPiN requires {{min}} if the septic tank is upstream in groundwater flow; less is allowed only per the unit's datasheet (no closer than {{passport}})",
+ "noCold": "{{name}}: no cold water",
+ "viaTee": "{{name}}: {{line}} goes through a tee — with manifold (home-run) layout each fixture needs its own manifold outlet",
+ "notFromCollector": "{{name}}: {{line}} is not fed from a manifold",
+ "collectorFull": "Manifold {{line}}: {{used}} of {{outputs}} outlets used"
+ },
+ "panel": {
+ "eyebrowPipe": "Water supply · pipe",
+ "eyebrowNode": "Water supply · {{kind}}",
+ "line": "Line",
+ "material": "Material",
+ "depth": "Depth",
+ "heatCable": "Heating cable",
+ "no": "No",
+ "yes": "Yes",
+ "feed": "Feed",
+ "reverse": "Reverse",
+ "pipeHint": "Outdoor pipe — below the 1.5 m frost depth or with a heating cable. Delete removes.",
+ "source": "Source",
+ "water": "Water",
+ "outputs": "Outlets",
+ "usedOutputs": "Outlets used"
+ },
+ "summary": {
+ "empty": "No runs yet. Layers → pencil next to Water supply: place the source, entry, pump, filter and manifolds as a run, then click a fixture — a separate line from the manifold.",
+ "total": "Water supply total",
+ "hint": "Prices come from the network materials in the plan, otherwise from the catalog (kind water). Rules: frost depth 1.5 m, to sewer ≥ 1.5 m, source to septic tank ≥ 50 m (per datasheet ≥ 15 m)."
+ },
+ "edit": {
+ "cold": "Cold",
+ "coldTitle": "Cold water run; click a fixture for a separate line from the CW manifold",
+ "hot": "Hot",
+ "hotTitle": "Hot water run from the water heater; click a fixture for a line from the HW manifold",
+ "recirc": "Recirc.",
+ "recircTitle": "Hot water recirculation",
+ "nextTitle": "Which node a click on empty space places",
+ "hintTrace": "click a fixture — line from the manifold · clicks — run · double-click — finish"
+ },
+ "layer": {
+ "outputs": "outlets {{value}}",
+ "fromCollector": "run from manifold"
+ },
+ "trace": {
+ "alreadyHot": "Fixture is already connected to hot water",
+ "alreadyCold": "Fixture is already connected to cold water",
+ "needHotCollector": "Place a hot water manifold first",
+ "needColdCollector": "Place a cold water manifold first"
+ }
+ },
+ "electric": {
+ "layer": "Electrical",
+ "amps": "{{value}} A",
+ "pointKind": {
+ "socket": "Socket",
+ "socket2": "Double socket",
+ "socket_ip44": "IP44 socket",
+ "power": "Power outlet",
+ "switch": "Switch",
+ "switch2": "2-gang switch",
+ "light": "Light fixture",
+ "light_wall": "Wall light",
+ "junction": "Junction box",
+ "outdoor": "Outdoor socket"
+ },
+ "circuitKind": {
+ "light": "Lighting",
+ "socket": "Sockets",
+ "power": "Power",
+ "wet": "Wet area",
+ "outdoor": "Outdoor",
+ "garage": "Garage"
+ },
+ "circuitName": "{{kind}} {{n}}",
+ "tools": {
+ "mode": {
+ "select": {
+ "label": "Select",
+ "title": "Select: click a point, Shift to add, drag along the wall, Delete to remove"
+ },
+ "socket": {
+ "label": "Socket",
+ "title": "Socket: click near a wall, snaps to the wall face"
+ },
+ "switch": {
+ "label": "Switch",
+ "title": "Switch: click near a wall"
+ },
+ "light": {
+ "label": "Light",
+ "title": "Light: click on the ceiling; wall lights and boxes go near a wall"
+ },
+ "panel": {
+ "label": "Panel",
+ "title": "Panel: click near a wall"
+ }
+ },
+ "kind": {
+ "socket": "Single",
+ "socket2": "Double",
+ "socket_ip44": "IP44",
+ "power": "Power",
+ "outdoor": "Outdoor",
+ "switch": "1-gang",
+ "switch2": "2-gang",
+ "light": "Ceiling",
+ "light_wall": "Wall light",
+ "junction": "Box"
+ },
+ "groupTitle": "Circuit for new points; assign a circuit to selected points in the right panel",
+ "noGroup": "No circuit",
+ "hintSelect": "drag along the wall · Shift to add to selection · Delete to remove",
+ "hintCeiling": "click on the ceiling",
+ "hintWall": "click near a wall"
+ },
+ "layerTag": {
+ "noGroup": "no circuit",
+ "height": "{{height}} mm above floor",
+ "panel": "Panel"
+ },
+ "device": {
+ "socket": "Grounded socket",
+ "socket2": "Grounded double socket",
+ "socket_ip44": "IP44 socket with cover",
+ "power": "Power socket / 32 A terminal block",
+ "switch": "1-gang switch",
+ "switch2": "2-gang switch",
+ "light": "Ceiling light point (terminal block, hook)",
+ "light_wall": "Wall light outlet",
+ "junction": "Junction box with terminals",
+ "outdoor": "Outdoor socket IP54, surface-mounted"
+ },
+ "item": {
+ "rcbo": "RCBO {{curve}}{{rating}} 30 mA",
+ "rcbo4p": "RCBO {{curve}}{{rating}} 30 mA 4P",
+ "breaker": "Circuit breaker {{curve}}{{rating}} {{poles}}P",
+ "rcd": "RCD {{rating}} A 30 mA {{poles}}",
+ "frameIp44": "Single frame IP44",
+ "frame": "Single frame",
+ "box": "Hollow-wall back box Ø68",
+ "cable": "VVGng(A)-LS cable {{cable}}",
+ "conduit": "Metal conduit / corrugated tube Ø{{d}}",
+ "main3p": "Main breaker 3P C32",
+ "main2p": "Main breaker 2P C40",
+ "relay": "Voltage monitoring relay",
+ "panel": "Flush-mounted panel, {{modules}} modules"
+ },
+ "warn": {
+ "cableUnknown": "{{label}}: can't parse cable type “{{cable}}” — write it like 3x2.5",
+ "breakerOverCable": "{{label}}: {{rating}} A breaker on {{cable}} cable — max {{max}} A, the cable will overheat",
+ "overload": "{{label}}: load {{load}} W ≈ {{current}} A exceeds the {{rating}} A breaker",
+ "wetNoRcd": "{{label}}: {{kind}} without RCD — needs an RCBO or a 30 mA RCD (PUE 7.1.79)",
+ "socketRcd": "{{label}}: better protect the socket circuit with a 30 mA RCD (PUE 7.1.79)",
+ "voltageDrop": "{{label}}: voltage drop {{pct}} % at full load — over 5 %, increase the cross-section",
+ "tooManySockets": "{{label}}: {{sockets}} sockets on one circuit — keep it to 8–10",
+ "powerSeparate": "{{label}}: a power outlet (stove, oven, boiler) needs its own circuit",
+ "lightWithSockets": "{{label}}: sockets on a lighting circuit — lighting and sockets go on separate circuits",
+ "emptyCircuit": "{{label}}: circuit has no points",
+ "noCircuit": "{{name}}: no circuit assigned",
+ "unknownCircuit": "{{name}}: circuit “{{id}}” does not exist",
+ "zone01Bath": "{{name}} above the bathtub — zone 0/1, sockets and switches are prohibited (GOST R 50571.7.701)",
+ "zone01Shower": "{{name}} above the shower — zone 0/1, sockets and switches are prohibited (GOST R 50571.7.701)",
+ "zone2Bath": "{{name}}: {{d}} mm from the bathtub — zone 2, must be at least 600 mm away",
+ "zone2Shower": "{{name}}: {{d}} mm from the shower — zone 2, must be at least 600 mm away",
+ "bathSocket": "{{name}} in a bathroom — needs IP44 and a 30 mA RCD",
+ "bathNoRcd": "{{name}} in a bathroom, but circuit {{circuit}} has no RCD",
+ "noPanel": "No panel placed — cable lengths are approximate",
+ "panelTooSmall": "Panel holds {{modules}} modules, but devices need {{need}} — use at least {{size}}"
+ },
+ "priceFromOwn": "price from network materials: {{name}}",
+ "panel": {
+ "rcboPrefix": "RCBO ",
+ "rcdPrefix": "RCD+",
+ "clearSelection": "Clear selection",
+ "panelTitle": "Panel",
+ "devices": "Devices",
+ "modules": "{{n}} mod.",
+ "panelNeeded": "Panel needed",
+ "panelFor": "{{n}} mod.",
+ "modulesInPanel": "Modules in panel",
+ "removePanel": "Remove panel",
+ "pointsCount": "Points: {{n}}",
+ "group": "Circuit",
+ "mixed": "mixed",
+ "noGroup": "No circuit",
+ "newGroup": "+ new circuit",
+ "type": "Type",
+ "height": "Height above floor",
+ "heightMixed": "mixed",
+ "power": "Power",
+ "label": "Label",
+ "labelPlaceholder": "stove, TV…",
+ "pointHint": "Drag the symbol along the wall · Shift+click to add to selection · Delete to remove",
+ "deletePoint": "Delete point",
+ "deletePoints_one": "Delete {{count}} point",
+ "deletePoints_other": "Delete {{count}} points",
+ "noWarnings": "No issues",
+ "layerEyebrow": "Layer",
+ "points": "Points",
+ "circuits": "Circuits",
+ "load": "Load",
+ "panelRow": "Panel",
+ "panelState": "{{modules}} mod. → {{size}}-module",
+ "notPlaced": "not placed",
+ "groups": "Circuits",
+ "autoRouteTitle": "Route all circuits from the panel along the walls",
+ "placePanelFirst": "Place the panel first",
+ "autoRoute": "Auto-route",
+ "noGroups": "No circuits yet",
+ "colGroup": "Circuit",
+ "colProtection": "Protection",
+ "colPoints": "Pts",
+ "routed": "along the route",
+ "estimated": "estimate without a route",
+ "addGroup": "+ circuit",
+ "materials": "Materials",
+ "noMaterials": "Place points and build circuits",
+ "total": "Electrical total",
+ "noPrice": "no price: {{n}} items",
+ "warnings": "Issues",
+ "howto": "How to do it",
+ "howtoNote": "Default heights: sockets 300 mm, above the countertop 1100, switches 900, wall lights 2000, route 150 mm below the ceiling. Cable: lighting 3×1.5 on 10 A, sockets 3×2.5 on 16 A, stove 3×6 on 32 A. Circuit length = route + drops + 1.5 m for termination in the panel + 15 % reserve.",
+ "protection": "Protection",
+ "cable": "Cable",
+ "phase": "Phase",
+ "collapse": "Collapse",
+ "name": "Name",
+ "device": "Device",
+ "mcb": "Circuit breaker",
+ "rcbo": "RCBO",
+ "rcd": "Breaker + RCD",
+ "rating": "Rating",
+ "selectPoints": "Select points",
+ "route": "Route",
+ "delete": "Delete"
+ },
+ "steps": [
+ "Agree the power allowance and service connection with the utility, choose single or three phase.",
+ "Mark all points on the walls according to this plan: heights are from the finished floor.",
+ "In a SIP house — only in metal conduit or steel pipe, VVGng(A)-LS cable; no chasing in panels — run wiring in panel channels or behind a service batten.",
+ "Lay the routes: horizontal runs 150 mm below the ceiling, strictly vertical drops to points, 90° corners.",
+ "Each circuit is a separate cable from the panel, no twisted joints; branches go in boxes on Wago terminals.",
+ "Use hollow-wall back boxes; junction boxes must stay accessible for service.",
+ "Assemble the panel: main breaker, voltage relay, RCDs/RCBOs for sockets and wet areas, breakers for lighting and power lines.",
+ "Test continuity, measure insulation resistance with a megohmmeter, test RCD tripping, label circuits in the panel.",
+ "Photograph the walls with routes before closing them up — useful for future repairs."
+ ]
+ },
+ "heating": {
+ "layer": "Underfloor heating",
+ "units": {
+ "pcs": "pcs",
+ "m": "m",
+ "m2": "m²",
+ "m3": "m³",
+ "kg": "kg",
+ "pack": "pack"
+ },
+ "cover": {
+ "tile": "tile",
+ "laminate": "laminate"
+ },
+ "tools": {
+ "autoLayout": "Lay out by rooms",
+ "hintSelected": "Delete to remove the loop · spacing and pattern in the right panel",
+ "hintIdle": "click a loop to select · drag the manifold with the mouse"
+ },
+ "actions": {
+ "confirmReplace_one": "Replace {{count}} loop with a new layout? Manual loop edits will be lost, the manifold stays in place.",
+ "confirmReplace_other": "Replace {{count}} loops with a new layout? Manual loop edits will be lost, the manifold stays in place.",
+ "done": "Loops laid out: {{count}}. {{notes}}"
+ },
+ "layout": {
+ "collectorInRoom": "Manifold — in “{{room}}”",
+ "noBoilerRoom": "No boiler room — manifold placed at the center of the house",
+ "collectorKept": "Manifold kept in place",
+ "edgeSuffix": " · along exterior wall",
+ "noHeating": "“{{room}}” — no underfloor heating",
+ "fixedEdge": "“{{room}}”: floor output was short — 100 mm spacing in a 1 m strip along exterior walls",
+ "fixedFull": "“{{room}}”: floor output was short — 100 mm spacing across the whole room",
+ "needRadiator": "“{{room}}”: floor output is short even at 100 mm spacing — a radiator is needed",
+ "loopsInRoom_one": "“{{room}}”: {{count}} loop",
+ "loopsInRoom_other": "“{{room}}”: {{count}} loops",
+ "cantMerge": "{{count}} loops — couldn't merge small ones, a second manifold is needed",
+ "merged": "“{{a}}” and “{{b}}” — one loop, {{len}} m"
+ },
+ "warn": {
+ "loopTooLong": "“{{room}}”: loop {{len}} m — over {{max}} m, split it in two",
+ "loopLong": "“{{room}}”: loop {{len}} m — longer than {{max}} m, hard on the pump",
+ "dpHigh": "“{{room}}”: pressure drop {{dp}} kPa — over 20",
+ "noFeed": "“{{room}}”: no supply line from the manifold",
+ "roomShortCapped": "“{{room}}”: floor gives {{power}} W, but heat loss is ≈{{loss}} W ({{lossWm2}} W/m²) — floor surface temperature limit reached, a radiator is needed",
+ "roomShort": "“{{room}}”: floor gives {{power}} W, but heat loss is ≈{{loss}} W ({{lossWm2}} W/m²) — reduce spacing, raise supply temperature or add a radiator",
+ "returnNotBelow": "Return temperature is not below supply — check the parameters",
+ "supplyHigh": "Supply {{t}} °C — underfloor heating should not exceed 55 °C",
+ "insulationThin": "Insulation {{mm}} mm — for a slab on grade in the North-West at least 100 mm XPS, 150 is right",
+ "noCollector": "Manifold not placed",
+ "collectorOutputs": "Manifold has {{outputs}} outlets, but there are {{loops}} loops",
+ "tooManyLoops": "{{count}} loops — more than 12 per manifold, use two or merge small loops"
+ },
+ "item": {
+ "pipe500": "Pipe {{pipe}}, 500 m coil (total across loops {{total}} m)",
+ "pipe200": "Pipe {{pipe}}, 200 m coil",
+ "pipe200Total": "Pipe {{pipe}}, 200 m coil (total across loops {{total}} m)",
+ "collector": "Manifold with flow meters, {{n}} outlets",
+ "mixing": "Pump and mixing unit for underfloor heating",
+ "pump": "Circulation pump 25/60 for the unit, head ≥ {{head}} m needed",
+ "cabinet": "Manifold cabinet for {{n}} outlets and mixing unit",
+ "eurocone": "Eurocone fitting 16×2 — 3/4\"",
+ "damper": "Edge insulation strip 10 mm",
+ "insulation": "Insulation {{insulation}}",
+ "film": "PE film 200 µm (with overlap)",
+ "staples": "Tacker staples for 16 mm pipe (every 0.4 m)",
+ "mesh": "Reinforcing mesh 100×100, 4 mm wire",
+ "ties": "Cable ties for fixing pipe to mesh",
+ "cps": "Sand-cement mix M300 (screed {{mm}} mm, {{m3}} m³)",
+ "cement": "Cement M500 (screed {{mm}} mm, {{m3}} m³, 1:3)",
+ "sand": "Building sand",
+ "fiber": "Polypropylene fiber"
+ },
+ "price": {
+ "none": "no price set",
+ "own": "price from network materials: {{name}}",
+ "pack": "{{from}} · {{qty}} {{unit}} per {{pack}}",
+ "twoHalves": "2 pcs for {{n}} outlets — {{name}}",
+ "twoOf": "{{name}} (two of {{n}})"
+ },
+ "tag": {
+ "length": "{{len}} m of pipe · spacing {{step}} mm",
+ "snake": " · serpentine",
+ "area": "{{area}} m² · {{power}} W ({{q}} W/m²)",
+ "excluded": "{{room}} — loop excluded"
+ },
+ "panel": {
+ "spiral": "Spiral",
+ "snake": "Serpentine",
+ "clearSelection": "Clear selection",
+ "collector": "Manifold",
+ "loops": "Loops",
+ "flow": "Flow",
+ "flowM3h": "{{v}} m³/h",
+ "pump": "Pump",
+ "head": "head ≥ {{v}} m",
+ "outputs": "Outlets",
+ "label": "Label",
+ "reroute": "Re-route supply lines",
+ "loopEyebrow": "Underfloor heating · loop {{id}}",
+ "area": "Area",
+ "pipe": "Pipe",
+ "feed": "(supply {{v}} m ×2)",
+ "power": "Output",
+ "wm2": "W/m²",
+ "floor": "Floor",
+ "lmin": "L/min",
+ "kpa": "kPa",
+ "excludedFromCalc": "Loop excluded from calculation",
+ "step": "Spacing, mm",
+ "pattern": "Pattern",
+ "include": "Include in calculation",
+ "exclude": "Exclude",
+ "deleteLoop": "Delete loop",
+ "noWarnings": "No issues",
+ "layerEyebrow": "Layer",
+ "excludedCount": " (+{{n}} excl.)",
+ "floorGives": "Floor output",
+ "heatLoss": "Heat loss",
+ "boiler": "Boiler",
+ "boilerFrom": "from {{v}} kW",
+ "unit": "Mixing unit",
+ "unitValue": "{{flow}} m³/h, head ≥ {{head}} m",
+ "collectorOutputs": "{{n}} outlets",
+ "notPlaced": "not placed",
+ "loopsTitle": "Loops",
+ "noLoops": "No loops — press “Lay out by rooms” in edit mode",
+ "room": "Room",
+ "colStep": "Spacing",
+ "total": "Total",
+ "roomsTitle": "Rooms: floor output vs heat loss",
+ "colLoss": "Loss",
+ "colFloor": "Floor",
+ "params": "Parameters",
+ "supply": "Supply",
+ "return": "Return",
+ "floorLimit": "Floor limit",
+ "norm": "default",
+ "screed": "Screed",
+ "insulation": "Insulation",
+ "screedMix": "Screed mix",
+ "cementSand": "cement + sand",
+ "cps": "ready sand-cement mix",
+ "fixing": "Pipe fixing",
+ "mesh": "reinforcing mesh",
+ "staples": "tacker staples",
+ "materials": "Materials",
+ "noMaterials": "Lay out loops to see materials",
+ "materialsTotal": "Underfloor heating total",
+ "noPriceCount": "{{label}}: {{n}} items",
+ "warnings": "Issues",
+ "howto": "How it's calculated and how to build it",
+ "howtoNote": "Loop length = area without furniture / spacing + supply line there and back, plus 5 %. Heat output — from the log-mean temperature difference of supply, return and air (20 °C, bathroom 24 °C), spacing and floor covering: tile in bathrooms, kitchen, corridor and hall, laminate elsewhere. Floor limit 29 °C, bathroom 33 °C, along exterior walls 35 °C. Heat loss by the rough norm for the North-West: 50 W/m² with no exterior walls, 60 — one exterior wall, 70 — corner room. Boiler — heat loss × 1.2. Loop flow = 0.86 × output × 1.1 / Δt; pressure drop — Darcy with a 30 % allowance for local resistances; pump — the hardest loop + 5 kPa for the unit."
+ },
+ "steps": [
+ "Level the base, no more than 5 mm deviation over 2 m.",
+ "Around room perimeters — 10 mm edge insulation strip, full screed height.",
+ "Insulation boards tight with no gaps, film on top overlapping 100 mm onto the strip.",
+ "Reinforcing mesh on spacers, or fix the pipe to the insulation with tacker staples every 0.3–0.5 m, more often at bends.",
+ "Each loop is one continuous pipe from the coil, no joints in the screed. Start a spiral with the supply along the perimeter.",
+ "Supply lines in corridors — in corrugated sleeve or insulation so the passage doesn't overheat.",
+ "Pressure test at 6 bar for 24 hours before pouring; pour under 3 bar pressure.",
+ "Screed at least 45 mm above the pipe, with fiber; expansion joints at thresholds and on areas over 30 m².",
+ "First start-up no sooner than 28 days, raise the temperature by 5 °C per day.",
+ "Set the manifold flow meters according to the balancing table."
+ ]
+ }
+}
diff --git a/src/i18n/locales/en/plan.json b/src/i18n/locales/en/plan.json
new file mode 100644
index 0000000..3819bff
--- /dev/null
+++ b/src/i18n/locales/en/plan.json
@@ -0,0 +1,259 @@
+{
+ "close": "Close",
+ "delete": "Delete",
+ "height": "Height",
+ "width": "Width",
+ "area": "Area",
+ "type": "Type",
+ "openingTypes": {
+ "door": "Door",
+ "window": "Window",
+ "gate": "Gate"
+ },
+ "openingPresets": {
+ "entry": "Entrance door 960×2070",
+ "interior": "Interior door 800×2000",
+ "gate": "Gate 2500×2200",
+ "window": "Window 1200×1400, sill 800"
+ },
+ "materialKinds": {
+ "sip": "SIP panel",
+ "pir": "PIR panel",
+ "brick": "Brick",
+ "block": "Block",
+ "timber": "Timber/log",
+ "frame": "Timber frame",
+ "concrete": "Concrete",
+ "glass": "Glass",
+ "other": "Other"
+ },
+ "zoneKinds": {
+ "fill": "Gravel fill",
+ "lawn": "Lawn",
+ "paving": "Paving",
+ "other": "Other"
+ },
+ "wall": {
+ "eyebrow": "Wall",
+ "length": "Length",
+ "thickness": "Thickness",
+ "material": "Material",
+ "noMaterial": "— no material —",
+ "panels": "Panels",
+ "panelsFrac": "{{n}} panels",
+ "panelsDative_one": "{{count}} panel",
+ "panelsDative_other": "{{count}} panels",
+ "multipleOf": "fits {{panels}}",
+ "panelWidth": "of {{width}} mm",
+ "extraPanels": "+{{n}} panel",
+ "notAligned": "length is not a multiple of {{half}} mm, panels will be cut. Better: {{down}} or {{up}}.",
+ "openings": "Openings",
+ "fromA": "from a {{offset}}",
+ "selectBuilding": "Select building",
+ "delete": "Delete wall",
+ "hint": "Enter mm or m (2800, 2.8 m). Double-click a length on the plan to edit it too. ⌘Z — undo."
+ },
+ "group": {
+ "deselect": "Clear selection",
+ "eyebrow": "Group",
+ "selected": "Selected: {{summary}}",
+ "moveX": "Move X",
+ "moveY": "Move Y",
+ "rotateDeg": "Rotate, °",
+ "alignStreet": "Align parallel to street",
+ "hint": "Drag any selected object or the arrow handle below the frame to move the whole group (100 mm step). Arrow keys — 100 mm, Shift — 1 m. Drag a building corner from outside or the circle above the frame to rotate in 0.5° steps, snapping to axes and the street; Shift — 15°, Alt — around the opposite corner. [ and ] — 1°, Shift — 15°. Shift+click — add or remove, Shift+drag on empty space — select, ⌘A — all, Esc — clear."
+ },
+ "opening": {
+ "sill": "Sill height",
+ "offset": "From start a",
+ "hinges": "Hinges",
+ "hingeStart": "at a",
+ "hingeEnd": "at b",
+ "swing": "Swing",
+ "left": "left",
+ "right": "right",
+ "toEnd": "To end b",
+ "wall": "Wall {{id}}",
+ "hint": "Drag the opening along the wall, drag edges to resize (50 mm step). F — side, H — hinges, Delete — remove."
+ },
+ "zone": {
+ "defaultName": "Zone {{n}}",
+ "lockedEyebrow": "Site data",
+ "lockedHint": "This zone comes from the site data on the server and can't be edited here.",
+ "eyebrow": "Site zone",
+ "name": "Name",
+ "perimeter": "Perimeter",
+ "vertices": "Vertices",
+ "hint": "Drag vertices, double-click an edge to add a vertex. Delete — remove zone."
+ },
+ "furniture": {
+ "eyebrow": "Furniture",
+ "depth": "Depth",
+ "rotation": "Rotation",
+ "color": "Color",
+ "center": "Center",
+ "rotate90": "Rotate 90°",
+ "hint": "Drag furniture on the plan (50 mm step), the circle on top rotates it (Shift — 5° step). R — 90°, Delete — remove.",
+ "categories": {
+ "bedroom": "Bedroom",
+ "living": "Living room",
+ "kitchen": "Kitchen",
+ "bathroom": "Bathroom",
+ "hall": "Hallway",
+ "other": "Other"
+ },
+ "items": {
+ "bed-1600": "Double bed 1600",
+ "bed-1800": "Double bed 1800",
+ "bed-900": "Single bed 900",
+ "nightstand": "Nightstand",
+ "wardrobe": "Wardrobe",
+ "dresser": "Chest of drawers",
+ "sofa": "Three-seat sofa",
+ "sofa-corner": "Corner sofa",
+ "armchair": "Armchair",
+ "coffee-table": "Coffee table",
+ "tv-stand": "TV stand with TV",
+ "bookcase": "Bookcase",
+ "plant": "Potted plant",
+ "kitchen-base": "Kitchen base unit 600",
+ "kitchen-drawers": "Drawer unit 600",
+ "kitchen-corner": "Corner unit 900",
+ "kitchen-upper": "Wall cabinet 600",
+ "kitchen-sink": "Sink unit 800",
+ "stove": "Cooker 600",
+ "dishwasher": "Dishwasher 600",
+ "fridge": "Fridge",
+ "dining-4": "Dining table for 4",
+ "dining-6": "Dining table for 6",
+ "dining-round": "Round table for 4",
+ "chair": "Chair",
+ "toilet": "Toilet",
+ "washbasin": "Washbasin",
+ "vanity": "Vanity unit 800",
+ "bathtub": "Bathtub 1700",
+ "shower": "Shower 900×900",
+ "washer": "Washing machine",
+ "water-heater": "Water heater 80 L",
+ "coat-rack": "Wall coat rack",
+ "shoe-cabinet": "Shoe cabinet",
+ "hall-wardrobe": "Sliding wardrobe",
+ "desk": "Desk",
+ "office-chair": "Office chair",
+ "fireplace": "Fireplace",
+ "masonry-stove": "Masonry stove",
+ "gas-boiler": "Wall-hung boiler",
+ "floor-boiler": "Floor-standing boiler"
+ }
+ },
+ "furniturePanel": {
+ "eyebrow": "Catalog",
+ "title": "Furniture",
+ "hint": "Drag onto the plan or click to place it at the screen center. R — rotate 90°."
+ },
+ "estimate": {
+ "walls_one": "{{count}} wall, {{length}}",
+ "walls_other": "{{count}} walls, {{length}}",
+ "panels_one": "{{count}} panel",
+ "panels_other": "{{count}} panels",
+ "wholeWall": " — whole wall",
+ "noMaterial": "no material set",
+ "panelSize": " · panel {{w}}×{{h}}",
+ "withWaste": "with {{pct}}% waste: {{n}} pcs",
+ "areaWithWaste": " · {{area}} m² incl. waste",
+ "noPrice": "no price set",
+ "piecesPerM2": "{{n}} pcs/m² (block {{l}}×{{h}} + {{joint}} mm joint)",
+ "pieces": " · {{n}} pcs",
+ "source": "source",
+ "checked": " · checked {{date}}"
+ },
+ "tabs": {
+ "general": "General",
+ "materials": "Materials",
+ "sewer": "Sewer",
+ "water": "Water",
+ "electric": "Electrical",
+ "heating": "Underfloor heating"
+ },
+ "materials": {
+ "eyebrow": "Plan",
+ "title": "Wall materials",
+ "noWalls": "No walls yet",
+ "unused": "not used in walls",
+ "waste": "Cutting allowance",
+ "total": "Walls total",
+ "noPrice_one": "no price: {{count}} item",
+ "noPrice_other": "no price: {{count}} items",
+ "hint": "Click a wall for handles and properties. W — draw a wall."
+ },
+ "toolbar": {
+ "tools": {
+ "select": "Select",
+ "wall": "Wall",
+ "door": "Door",
+ "window": "Window",
+ "zone": "Zone",
+ "building": "Building"
+ },
+ "undo": "Undo",
+ "undoTitle": "Undo (⌘Z)",
+ "redo": "Redo",
+ "redoTitle": "Redo (⌘⇧Z)",
+ "buildingTitle": "Building (B): click a house to select it with walls, furniture and utilities; drag to move, corners to rotate. Esc or click outside to exit",
+ "zonesLocked": "Zones are locked — unlock them in Layers",
+ "zoneTitle": "Site zone: click vertices; close by clicking the first point or pressing Enter",
+ "view": "View",
+ "furniture": "Furniture",
+ "furnitureTitle": "Furniture: catalog, drag onto the plan",
+ "measure": "Ruler",
+ "measureTitle": "Ruler (M): click A → click B, ⌘ — chain",
+ "summary": "Summary",
+ "summaryTitle": "House summary",
+ "dims": "Dimensions",
+ "dimsTitle": "Always show wall lengths",
+ "fit": "Fit",
+ "fitTitle": "Show the whole site",
+ "map": "Map",
+ "mapTitle": "Satellite image under the plan",
+ "align": "Align image",
+ "alignTitle": "Align the image to the site: move and rotate · Esc — exit",
+ "opacityTitle": "Image opacity: {{pct}}%",
+ "clickWall": "click a wall",
+ "noMaterial": "No material, 200 mm"
+ },
+ "summary": {
+ "buildingKinds": {
+ "house": "House",
+ "garage": "Garage",
+ "outbuilding": "Outbuilding"
+ },
+ "side": "Side {{from}}–{{to}}",
+ "sideStreet": "{{side}}, street",
+ "street": "Street",
+ "defaultRoom": "Room {{n}}",
+ "lessThan": "less than {{norm}}",
+ "empty": "No closed wall outlines — no rooms found.",
+ "totalArea": "Total area",
+ "livingArea": "Living area",
+ "rooms": "Rooms",
+ "bedrooms": "Bedrooms",
+ "baths": "Bathrooms",
+ "footprint": "Footprint",
+ "height": "Height",
+ "allHouses": "All houses",
+ "roomsSection": "Rooms",
+ "lowLight": "not enough daylight",
+ "area": "Area",
+ "site": "Site",
+ "siteArea": "{{area}} · {{ares}} ares",
+ "built": "Built-up",
+ "toStreet": "To street",
+ "toBorders": "To boundaries, min.",
+ "toNeighbour": "To neighbour {{name}}",
+ "unmatchedLabels": "Labels outside rooms",
+ "wallCost": "Wall cost",
+ "withWaste": "With {{pct}} % waste",
+ "noPrice_one": "no price: {{count}}",
+ "noPrice_other": "no price: {{count}}"
+ }
+}
diff --git a/src/i18n/locales/en/view3d.json b/src/i18n/locales/en/view3d.json
new file mode 100644
index 0000000..d33cebd
--- /dev/null
+++ b/src/i18n/locales/en/view3d.json
@@ -0,0 +1,25 @@
+{
+ "views": { "top": "Top", "front": "Front" },
+ "looks": { "model": "Mock-up", "real": "Materials" },
+ "cuts": { "full": "Full", "low": "1 m", "floor": "Floor" },
+ "finishes": { "plaster": "Plaster", "timber": "Log imitation", "planken": "Planken" },
+ "presets": {
+ "granite": "Grey granite",
+ "scandinavia": "Scandinavian",
+ "graphite": "Graphite",
+ "warm": "Warm",
+ "forest": "Forest"
+ },
+ "toolbar": {
+ "grid": "Grid",
+ "facade": "Facade",
+ "wallColor": "Wall color",
+ "accent": "Accent",
+ "presets": "Ready-made combinations"
+ },
+ "error": {
+ "eyebrow": "3D view",
+ "text": "Couldn't build 3D for this plan. The plan is unharmed, everything is still in the editor. Fix the walls or openings and come back to this tab.",
+ "retry": "Try again"
+ }
+}
diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json
new file mode 100644
index 0000000..36ebff1
--- /dev/null
+++ b/src/i18n/locales/ru/common.json
@@ -0,0 +1,173 @@
+{
+ "app": {
+ "title": "Планировщик дома"
+ },
+ "units": {
+ "mm": "мм",
+ "cm": "см",
+ "m": "м",
+ "m2": "м²",
+ "m3": "м³",
+ "pcs": "шт",
+ "rub": "₽",
+ "kw": "кВт",
+ "w": "Вт",
+ "deg": "°",
+ "roll": "рул",
+ "coil": "бухта",
+ "pack": "упак",
+ "kg": "кг",
+ "l": "л",
+ "set": "компл.",
+ "sheet": "лист",
+ "kit": "домокомплект"
+ },
+ "language": {
+ "label": "Язык",
+ "en": "English",
+ "ru": "Русский"
+ },
+ "sections": {
+ "plan": "План",
+ "3d": "3D",
+ "map": "Карта",
+ "estimate": "Смета",
+ "info": "Участок и дом",
+ "infoShort": "Участок"
+ },
+ "loading": {
+ "3d": "Загружаю 3D…",
+ "map": "Загружаю карту…",
+ "estimate": "Загружаю смету…",
+ "generic": "Загружаю…",
+ "plan": "Загружаю план…"
+ },
+ "status": {
+ "cursor": "x {{x}} м · y {{y}} м",
+ "cursorEmpty": "x — · y —",
+ "hintWall": "Клик — точка, Shift — угол 45°, Esc/правый клик — закончить",
+ "hintDoor": "Наведи на стену и кликни, чтобы поставить дверь · Esc — выйти",
+ "hintWindow": "Наведи на стену и кликни, чтобы поставить окно · Esc — выйти",
+ "hintSelect": "Тяни концы и середину стены · Alt — оторвать · Shift — 45° · ⌘Z — отмена"
+ },
+ "header": {
+ "subtitle": "участок {{width}} × {{depth}} м · {{walls}} · {{openings}}",
+ "walls_one": "{{count}} стена",
+ "walls_few": "{{count}} стены",
+ "walls_many": "{{count}} стен",
+ "walls_other": "{{count}} стен",
+ "openings_one": "{{count}} проём",
+ "openings_few": "{{count}} проёма",
+ "openings_many": "{{count}} проёмов",
+ "openings_other": "{{count}} проёмов",
+ "loadingPlan": "Загрузка плана…",
+ "viewOnly": "Просмотр"
+ },
+ "grid": {
+ "title": "Размер клеток сетки при текущем масштабе",
+ "legend": "Клетка {{minor}} · крупная {{major}}"
+ },
+ "preview": {
+ "label": "Просмотр версии <strong>{{label}}</strong> — только чтение",
+ "back": "Вернуться",
+ "restore": "Восстановить эту",
+ "confirm": "Восстановить версию {{label}}? Она запишется новой ревизией, история не теряется."
+ },
+ "save": {
+ "saving": "Сохраняю…",
+ "offline": "Нет связи с сервером · повторить",
+ "saved": "Сохранено",
+ "savedAt": "Сохранено · {{time}}"
+ },
+ "login": {
+ "loading": "Загружаю план с сервера…",
+ "offlineTitle": "Нет связи с сервером",
+ "offlineText": "План хранится только на сервере, без связи редактор не открывается.",
+ "retry": "Повторить",
+ "password": "Пароль",
+ "checking": "Проверяю…",
+ "signIn": "Войти"
+ },
+ "menu": {
+ "more": "Ещё",
+ "plan": "План",
+ "exportJson": "Экспорт JSON",
+ "importJson": "Импорт JSON",
+ "versions": "Версии",
+ "importInvalid": "План не прошёл проверку:\n\n{{error}}"
+ },
+ "versions": {
+ "saved": "Сохранённые",
+ "all": "Все изменения",
+ "defaultName": "Версия {{date}}",
+ "snapshot": "снимок",
+ "saveVersion": "Сохранить версию…",
+ "save": "Сохранить",
+ "loading": "Загружаю…",
+ "empty": "Сохранённых версий пока нет",
+ "open": "Открыть",
+ "restore": "Восстановить",
+ "current": "текущая",
+ "walls_one": "{{count}} стена",
+ "walls_few": "{{count}} стены",
+ "walls_many": "{{count}} стен",
+ "walls_other": "{{count}} стен",
+ "confirmSnapshot": "Восстановить «{{name}}»? Она запишется новой ревизией, история не теряется.",
+ "confirmRevision": "Восстановить ревизию #{{rev}}? Она запишется новой ревизией, история не теряется.",
+ "quoted": "«{{name}}»"
+ },
+ "planFile": {
+ "notJson": "Файл не JSON: {{message}}"
+ },
+ "lengthField": {
+ "title": "мм или м: 2800, 2,8 м, 280 см"
+ },
+ "sync": {
+ "wrongPassword": "Неверный пароль",
+ "loginHttp": "Ошибка входа: HTTP {{status}}",
+ "offline": "Нет связи с сервером",
+ "cookieNotSaved": "Кука входа не сохранилась",
+ "planChanged": "План обновился, повторите действие",
+ "saveFailedReason": "Не сохранилось: {{reason}}",
+ "saveFailed": "Не сохранилось на сервере — изменение отменено",
+ "siteUpdated": "Сайт обновился — перезагружаю",
+ "invalidServerPlan": "Серверный план не прошёл проверку: {{error}}",
+ "noSnapshot": "Нет снимка {{id}}",
+ "noVersion": "Нет версии {{rev}}"
+ },
+ "canvas": {
+ "addDoor": "+ дверь",
+ "addWindow": "+ окно",
+ "defaultRoomName": "Комната",
+ "moveHouseHint": "Чтобы двигать весь дом — инструмент «Здание» (B)",
+ "noRoomOnWall": "На стене нет места",
+ "alignTitle": "Выравнивание снимка",
+ "alignHint": "тяни центр — сдвиг, ручку — поворот · Esc — готово",
+ "labelRoom": "Подписать комнату",
+ "measureSum": "Сумма: {{sum}} м",
+ "measureHint": "Клик — точка A, клик — точка B · ⌘ — цепочка · Shift — 45° · Alt — без привязки · M/Esc — очистить",
+ "groupMove": "Δx {{x}} м · Δy {{y}} м",
+ "planUp": "План вверх",
+ "northUp": "Север вверх",
+ "rotateCcw": "Повернуть на 15° против часовой",
+ "rotateCw": "Повернуть на 15° по часовой",
+ "compass": "Север · клик — план вверх",
+ "walls_one": "{{count}} стена",
+ "walls_few": "{{count}} стены",
+ "walls_many": "{{count}} стен",
+ "walls_other": "{{count}} стен",
+ "openings_one": "{{count}} проём",
+ "openings_few": "{{count}} проёма",
+ "openings_many": "{{count}} проёмов",
+ "openings_other": "{{count}} проёмов",
+ "items_one": "{{count}} предмет",
+ "items_few": "{{count}} предмета",
+ "items_many": "{{count}} предметов",
+ "items_other": "{{count}} предметов",
+ "selSummary": "{{walls}}, {{openings}}, {{items}}"
+ },
+ "demo": {
+ "long": "Демо: изменения видят все и сбрасываются каждый час — поставьте себе свою копию",
+ "short": "Демо: общий план, сброс каждый час"
+ }
+}
diff --git a/src/i18n/locales/ru/estimate.json b/src/i18n/locales/ru/estimate.json
new file mode 100644
index 0000000..8660775
--- /dev/null
+++ b/src/i18n/locales/ru/estimate.json
@@ -0,0 +1,113 @@
+{
+ "page": {
+ "title": "Смета",
+ "downloadCsv": "Скачать CSV",
+ "newLine": "Новая позиция",
+ "newNote": "Новое примечание",
+ "addLine": "+ позиция",
+ "addNote": "+ примечание",
+ "total": "Итого",
+ "notesTitle": "Примечания к заказу",
+ "noNotes": "Нет примечаний",
+ "openInStore": "Открыть в магазине",
+ "deleteLine": "Удалить позицию",
+ "confirmDelete": "Удалить «{{name}}»?",
+ "bought": "Куплено",
+ "boughtOn": "Куплено {{date}}",
+ "markBought": "Отметить купленным",
+ "delete": "Удалить"
+ },
+ "columns": {
+ "n": "№",
+ "name": "Наименование",
+ "qty": "Кол-во",
+ "unit": "Ед.",
+ "price": "Цена",
+ "sum": "Сумма"
+ },
+ "colors": {
+ "title": "Цвета (RAL)",
+ "empty": "Цвета не выбраны — задаются во вкладке 3D",
+ "joined": "{{a}} и {{b}}",
+ "slots": {
+ "walls": "Стены",
+ "gates": "Ворота",
+ "roof": "Кровля и водостоки",
+ "windows": "Окна",
+ "accent": "Акцент",
+ "plinth": "Цоколь"
+ }
+ },
+ "csv": {
+ "fileName": "smeta-{{date}}.csv",
+ "yes": "да",
+ "no": "нет",
+ "total": "Итого",
+ "sectionTotal": "Итого по разделу «{{section}}»",
+ "columns": {
+ "section": "Раздел",
+ "n": "№",
+ "name": "Наименование",
+ "sku": "Артикул",
+ "qty": "Кол-во",
+ "unit": "Ед.",
+ "price": "Цена",
+ "sum": "Сумма",
+ "bought": "Куплено",
+ "url": "Ссылка",
+ "note": "Примечание"
+ }
+ },
+ "sections": {
+ "manual": "Ручные позиции",
+ "auto": "Стены, окна и двери"
+ },
+ "rows": {
+ "door": "Дверь {{w}}×{{h}} мм",
+ "gate": "Ворота {{w}}×{{h}} мм",
+ "window": "Окно {{w}}×{{h}} мм",
+ "priceBy": "цена по: {{item}}",
+ "areaEstimate": "оценка по площади от {{w}}×{{h}} мм: {{item}}"
+ },
+ "wallLine": {
+ "noMaterial": "Стены без материала"
+ },
+ "cart": {
+ "open": "Собрать корзину в Петровиче",
+ "title": "Корзина в Петровиче",
+ "close": "Закрыть",
+ "demoDisabled": "В демо корзина Петровича отключена — поставьте свою копию",
+ "onlyLeft": "Только некупленные",
+ "oneLink": "Одна ссылка на всё",
+ "perSection": "По ссылке на раздел",
+ "building_one": "Собираю… {{count}} позицию",
+ "building_few": "Собираю… {{count}} позиции",
+ "building_many": "Собираю… {{count}} позиций",
+ "building_other": "Собираю… {{count}} позиций",
+ "withCode_one": "{{count}} позиция с кодом Петровича",
+ "withCode_few": "{{count}} позиции с кодом Петровича",
+ "withCode_many": "{{count}} позиций с кодом Петровича",
+ "withCode_other": "{{count}} позиций с кодом Петровича",
+ "linkCount": "{{count}} поз.",
+ "openLink": "Открыть",
+ "copy": "Копировать",
+ "copied": "Скопировано",
+ "error": "ошибка — {{error}}. ",
+ "missing": "не нашлось или нет в наличии: {{list}}",
+ "all": "Всё",
+ "outdated": "Сайт обновился — перезагружаю",
+ "cities": {
+ "spb": "Санкт-Петербург",
+ "vbg": "Выборг"
+ },
+ "sections": {
+ "house": "Дом",
+ "garage": "Гараж",
+ "electric": "Электрика",
+ "sewer": "Канализация",
+ "water": "Водопровод",
+ "heating": "Тёплый пол",
+ "other": "Прочее"
+ }
+ }
+}
diff --git a/src/i18n/locales/ru/info.json b/src/i18n/locales/ru/info.json
new file mode 100644
index 0000000..7bdf665
--- /dev/null
+++ b/src/i18n/locales/ru/info.json
@@ -0,0 +1,19 @@
+{
+ "loadError": "Не удалось загрузить данные: {{error}}",
+ "loading": "Загрузка…",
+ "updated": "обновлено {{date}}",
+ "sectionsNav": "Разделы",
+ "collecting": "собирается",
+ "unverified": "не сверено",
+ "source": "Источник:",
+ "dated": "от {{date}}",
+ "more": "Подробнее",
+ "map": {
+ "title": "Схема участка",
+ "north": "С",
+ "parcel": "участок",
+ "zone": "где можно ставить дом",
+ "neighbors": "соседи",
+ "street": "улица"
+ }
+}
diff --git a/src/i18n/locales/ru/map.json b/src/i18n/locales/ru/map.json
new file mode 100644
index 0000000..3ba9ed8
--- /dev/null
+++ b/src/i18n/locales/ru/map.json
@@ -0,0 +1,48 @@
+{
+ "attribution": "Снимки © Esri, Vantor, Earthstar Geographics",
+ "orientation": { "plan": "План вверх", "north": "Север вверх" },
+ "legend": {
+ "title": "Легенда",
+ "site": "Участок (граница плана)",
+ "neighbor": "Смежные участки из data/parcel.geojson",
+ "street": "Сторона к улице",
+ "walls": "Стены дома"
+ },
+ "panel": {
+ "eyebrow": "Карта",
+ "titleAlign": "Выравнивание снимка",
+ "titlePlan": "План на снимке",
+ "expand": "Развернуть",
+ "collapse": "Свернуть",
+ "opacity": "Прозрачность плана",
+ "done": "Готово",
+ "align": "Выровнять снимок",
+ "toSite": "К участку",
+ "notBound": "План не привязан к местности: задайте geo через «Граница из GeoJSON».",
+ "alignHint": "Кадастр и план остаются на месте, двигается снимок. «0» — совместите начало плана с его местом на снимке, «X» — поверните по оси X.",
+ "reset": "Сбросить",
+ "imagery": "снимок: E {{e}} м · N {{n}} м · {{rot}}°",
+ "copied": "Скопировано",
+ "copy": "Копировать"
+ },
+ "geojson": {
+ "summary": "Граница из GeoJSON",
+ "autoGeo": "Вычислить geo по полигону",
+ "startVertex": "Начало в вершине №",
+ "convert": "Пересчитать",
+ "apply": "Применить к плану",
+ "result_one": "{{count}} вершина · {{w}} × {{d}} м · {{area}} м² · поворот {{rot}}°",
+ "result_few": "{{count}} вершины · {{w}} × {{d}} м · {{area}} м² · поворот {{rot}}°",
+ "result_many": "{{count}} вершин · {{w}} × {{d}} м · {{area}} м² · поворот {{rot}}°",
+ "result_other": "{{count}} вершин · {{w}} × {{d}} м · {{area}} м² · поворот {{rot}}°",
+ "notBound": "План не привязан: включите «Вычислить geo по полигону»",
+ "noPolygon": "В GeoJSON нет полигона",
+ "tooFewVertices": "В полигоне меньше трёх вершин"
+ },
+ "underlay": {
+ "ccw1": "Повернуть снимок против часовой на 1°",
+ "ccw01": "Повернуть снимок против часовой на 0,1°",
+ "cw01": "Повернуть снимок по часовой на 0,1°",
+ "cw1": "Повернуть снимок по часовой на 1°"
+ }
+}
diff --git a/src/i18n/locales/ru/networks.json b/src/i18n/locales/ru/networks.json
new file mode 100644
index 0000000..a2f30b9
--- /dev/null
+++ b/src/i18n/locales/ru/networks.json
@@ -0,0 +1,645 @@
+{
+ "shared": {
+ "layers": {
+ "walls": "Стены",
+ "furniture": "Мебель",
+ "zones": "Зоны",
+ "sewer": "Канализация",
+ "water": "Водопровод",
+ "electric": "Электрика",
+ "heating": "Тёплый пол"
+ },
+ "locks": {
+ "walls": "Стены заблокированы — сними замок в «Слоях»",
+ "editing": "Идёт редактирование сети — выйди из него (Esc), чтобы править остальное",
+ "layer": "Слой заблокирован — сними замок в «Слоях»"
+ },
+ "tools": {
+ "buttonTitle": "Слои плана и инженерные сети",
+ "buttonLabel": "Слои · {{count}}",
+ "heading": "Слои",
+ "unlock": "Снять замок: {{layer}}",
+ "lock": "Заблокировать: {{layer}}",
+ "lockedTitle": "Слой заблокирован — клик снимает замок",
+ "lockTitle": "Заблокировать слой от случайных правок",
+ "edit": "Редактировать: {{layer}}",
+ "note": "Замок — слой виден, но не правится. Включённая сеть приглушает остальное до 40 %",
+ "editing": "Редактирование: {{layer}}",
+ "exitLabel": "Выйти из редактирования (Esc)",
+ "exitTitle": "Выйти (Esc)"
+ },
+ "ui": {
+ "close": "Закрыть",
+ "delete": "Удалить",
+ "where": "Где",
+ "inside": "Внутри",
+ "outside": "Снаружи",
+ "insideLower": "внутри",
+ "outsideLower": "снаружи",
+ "diameter": "Диаметр",
+ "length": "Длина",
+ "type": "Тип",
+ "fixture": "Прибор",
+ "model": "Модель",
+ "center": "Центр",
+ "materials": "Материалы",
+ "networks": "Инженерные сети",
+ "noPrice": "цена не задана",
+ "warnings": "Предупреждения · {{count}}",
+ "modeSelect": "Выбор",
+ "modeSelectTitle": "Выбор: клик по трубе или узлу, узлы тянутся, Delete — удалить",
+ "hintSelect": "тяни узлы · Delete — удалить",
+ "missing_one": "без цены: {{count}} поз.",
+ "missing_few": "без цены: {{count}} поз.",
+ "missing_many": "без цены: {{count}} поз.",
+ "missing_other": "без цены: {{count}} поз."
+ },
+ "units": {
+ "pct": "{{v}} %",
+ "pack": "упак"
+ },
+ "pricing": {
+ "fromMaterials": "цена из материалов сети: {{name}}",
+ "fromCatalog": "цена по: {{name}}",
+ "includedInBorehole": "входит в обустройство скважины — отдельно не считается"
+ },
+ "warn": {
+ "notConnected": "{{name}}: прибор не подключён"
+ }
+ },
+ "sewer": {
+ "fixture": {
+ "toilet": "Унитаз",
+ "sink": "Раковина",
+ "bath": "Ванна",
+ "shower": "Душ",
+ "washer": "Стиральная машина",
+ "kitchen": "Кухонная мойка",
+ "boiler": "Котёл, бойлер"
+ },
+ "kind": {
+ "fixture": "Прибор",
+ "riser": "Стояк",
+ "cleanout": "Ревизия",
+ "outlet": "Выпуск",
+ "septic": "Септик",
+ "junction": "Стык"
+ },
+ "item": {
+ "pipeOutside": "Труба ПВХ наружная Ø{{d}} (рыжая)",
+ "pipeInside": "Труба канализационная Ø{{d}} внутренняя",
+ "elbow": "Отвод {{angle}}° Ø{{d}}",
+ "elbowOut": "Отвод наружный {{angle}}° Ø{{d}}",
+ "clamp": "Хомут Ø{{d}}",
+ "corrugation": "Гофра для унитаза Ø110",
+ "cleanout": "Ревизия Ø{{d}}",
+ "cleanoutOut": "Ревизия наружная Ø{{d}}",
+ "vent": "Выход фановый / аэратор Ø110",
+ "tee87": "Тройник 87° Ø110",
+ "tee87Reduced": "Тройник 87° 110/{{branch}}",
+ "tee45": "Тройник 45° Ø{{d}}",
+ "tee45Out": "Тройник наружный 45° Ø{{d}}",
+ "tee45Reduced": "Тройник 45° {{main}}/{{branch}}",
+ "tee45ReducedOut": "Тройник наружный 45° {{main}}/{{branch}}",
+ "sleeve": "Гильза для выпуска через фундамент Ø{{d}}",
+ "septic": "Септик",
+ "septicModel": "Септик {{model}}",
+ "reducer": "Переход {{big}}/{{small}}"
+ },
+ "warn": {
+ "loop": "В сети есть кольцо: сток должен идти в одну сторону — разверни трубу",
+ "slopeLow": "{{id}}: уклон {{slope}} меньше нормы {{min}} для Ø{{d}} (СП 30.13330)",
+ "shallow": "{{id}}: наружная труба на глубине {{depth}} — меньше {{min}}, утеплить",
+ "thinner": "{{id}}: Ø{{d}} тоньше, чем сток в неё (Ø{{up}})",
+ "toiletPipe": "{{id}}: от унитаза нужна труба Ø110",
+ "riserPipe": "{{id}}: из стояка нужна труба Ø110",
+ "septicHouse": "Септик {{name}}: до фундамента {{dist}} — нужно не меньше {{min}}",
+ "septicBoundary": "Септик {{name}}: до границы участка {{dist}} — нужно не меньше {{min}}",
+ "sharpTurn": "{{id}}: поворот {{deg}}° на горизонтали отводом 87° — лучше два по 45° или ревизия",
+ "deadEnd": "{{id}}: трасса обрывается — доведи до выпуска и септика"
+ },
+ "panel": {
+ "eyebrowPipe": "Канализация · труба",
+ "eyebrowNode": "Канализация · {{kind}}",
+ "slope": "Уклон",
+ "depthStart": "Глубина в начале",
+ "drop": "Перепад",
+ "invert": "Лоток, начало → конец",
+ "slopeNorm": "Норма уклона",
+ "min": "мин. {{v}}",
+ "flow": "Сток",
+ "reverse": "Развернуть сток",
+ "pipeHint": "Уклон в процентах: 2 % — 20 мм на метр. Лоток — от уровня земли, пол на {{floor}}. Delete — удалить.",
+ "riserHeight": "Высота стояка",
+ "modelPlaceholder": "Тверь 0,75",
+ "width": "Ширина",
+ "rotation": "Поворот",
+ "invertLevel": "Отметка лотка",
+ "outletDepth": "Глубина выпуска у стены",
+ "inletDepth": "Глубина входа",
+ "toFoundation": "До фундамента",
+ "toBoundary": "До границы участка",
+ "septicNorms": "Нормы: до фундамента не ближе {{house}}, до границы участка не ближе {{boundary}}.",
+ "nodeHint": "Тяни узел по плану. Delete — удалить; промежуточный узел удаляется со сращиванием трубы."
+ },
+ "summary": {
+ "empty": "Трасс пока нет. Инструмент «Канализация» в панели слева: клик по унитазу или раковине, дальше клики по трассе к выпуску и септику.",
+ "outletRow": "Выпуск {{id}}, глубина у стены",
+ "septicRow": "Септик, глубина входа",
+ "septicRowModel": "Септик {{model}}, глубина входа",
+ "total": "Итого по канализации",
+ "floorAbove": "Пол над землёй",
+ "hint": "Цены — из материалов сети в плане, иначе из каталога. Уклоны по СП 30.13330: Ø50 — от 2,5 %, Ø110 — от 1,2 %, снаружи — от 1 %."
+ },
+ "edit": {
+ "trace": "Трасса",
+ "traceTitle": "Трасса: клик по прибору или узлу, дальше клики — узлы и трубы",
+ "cleanout": "Ревизия",
+ "cleanoutTitle": "Следующий узел трассы — ревизия",
+ "riser": "Стояк",
+ "riserTitle": "Следующий узел трассы — стояк",
+ "outlet": "Выпуск",
+ "outletTitle": "Следующий узел трассы — выпуск через фундамент",
+ "septic": "Септик",
+ "septicTitle": "Клик — септик, трасса заканчивается в нём",
+ "hintTrace": "клик по прибору → клики по трассе · двойной клик или Enter — конец"
+ },
+ "layer": {
+ "connectFixture": "подключить прибор"
+ }
+ },
+ "water": {
+ "lineShort": {
+ "cold": "ХВС",
+ "hot": "ГВС",
+ "recirc": "Рециркуляция"
+ },
+ "line": {
+ "cold": "Холодная",
+ "hot": "Горячая",
+ "recirc": "Рециркуляция"
+ },
+ "kind": {
+ "source": "Источник",
+ "entry": "Ввод в дом",
+ "pump": "Насосная станция",
+ "filter": "Фильтр",
+ "boiler": "Бойлер",
+ "collector": "Коллектор",
+ "fixture": "Прибор",
+ "junction": "Узел",
+ "tap_outdoor": "Кран уличный"
+ },
+ "source": {
+ "borehole": "Скважина",
+ "well": "Колодец"
+ },
+ "caption": {
+ "depth": "глубина {{depth}}"
+ },
+ "item": {
+ "insulation": "Теплоизоляция для трубы Ø{{d}}",
+ "heatCable": "Греющий кабель для трубы",
+ "sleeve": "Гильза через стену для трубы Ø{{d}}",
+ "pipe": "Труба {{material}} Ø{{d}}",
+ "pipeOut": "Труба {{material}} Ø{{d}} наружная",
+ "head": "Оголовок скважины",
+ "tap": "Кран уличный незамерзающий",
+ "socket": "Водорозетка Ø{{d}}",
+ "collector_one": "Коллектор на {{count}} выход",
+ "collector_few": "Коллектор на {{count}} выхода",
+ "collector_many": "Коллектор на {{count}} выходов",
+ "collector_other": "Коллектор на {{count}} выхода",
+ "collectorOut": "Фитинг на выход коллектора Ø{{d}}",
+ "pump": "Насос / насосная станция",
+ "pumpModel": "Насос {{model}}",
+ "adapter": "Переходник на резьбу Ø{{d}}",
+ "tee": "Тройник пресс Ø{{d}}",
+ "reducer": "Переход пресс {{big}}/{{small}}",
+ "elbow": "Угольник пресс Ø{{d}}"
+ },
+ "warn": {
+ "frostNoDepth": "{{id}}: наружная труба без глубины — нужно глубже промерзания {{frost}} или греющий кабель",
+ "frostShallow": "{{id}}: наружная труба на глубине {{depth}} — нужно глубже промерзания {{frost}} или греющий кабель",
+ "toSewer": "{{id}}: до канализации {{dist}} — нужно не меньше {{min}} (или пересечение в футляре)",
+ "sourcePassport": "{{what}}: до септика {{dist}} — меньше {{min}} даже по паспорту септика",
+ "sourceSanpin": "{{what}}: до септика {{dist}} — по СанПиН нужно {{min}}, если септик выше по потоку грунтовых вод; меньше допустимо только по паспорту станции (не ближе {{passport}})",
+ "noCold": "{{name}}: нет холодной воды",
+ "viaTee": "{{name}}: {{line}} идёт через тройник — при лучевой разводке каждому прибору нужен свой выход коллектора",
+ "notFromCollector": "{{name}}: {{line}} подключена не от коллектора",
+ "collectorFull": "Коллектор {{line}}: занято {{used}} выходов из {{outputs}}"
+ },
+ "panel": {
+ "eyebrowPipe": "Водопровод · труба",
+ "eyebrowNode": "Водопровод · {{kind}}",
+ "line": "Линия",
+ "material": "Материал",
+ "depth": "Глубина",
+ "heatCable": "Греющий кабель",
+ "no": "Нет",
+ "yes": "Есть",
+ "feed": "Подача",
+ "reverse": "Развернуть",
+ "pipeHint": "Наружная труба — глубже промерзания 1,5 м или с греющим кабелем. Delete — удалить.",
+ "source": "Источник",
+ "water": "Вода",
+ "outputs": "Выходов",
+ "usedOutputs": "Занято выходов"
+ },
+ "summary": {
+ "empty": "Трасс пока нет. «Слои» → карандаш у «Водопровода»: поставь источник, ввод, насос, фильтр и коллекторы трассой, потом клик по прибору — отдельная линия от коллектора.",
+ "total": "Итого по водопроводу",
+ "hint": "Цены — из материалов сети в плане, иначе из каталога (kind water). Нормы: промерзание 1,5 м, до канализации ≥ 1,5 м, источник от септика ≥ 50 м (по паспорту ≥ 15 м)."
+ },
+ "edit": {
+ "cold": "Холодная",
+ "coldTitle": "Трасса холодной воды; клик по прибору — отдельная линия от коллектора ХВС",
+ "hot": "Горячая",
+ "hotTitle": "Трасса горячей воды от бойлера; клик по прибору — линия от коллектора ГВС",
+ "recirc": "Рецирк.",
+ "recircTitle": "Рециркуляция горячей воды",
+ "nextTitle": "Какой узел ставит клик по пустому месту",
+ "hintTrace": "клик по прибору — линия от коллектора · клики — трасса · двойной клик — конец"
+ },
+ "layer": {
+ "outputs": "выходов {{value}}",
+ "fromCollector": "провести от коллектора"
+ },
+ "trace": {
+ "alreadyHot": "Прибор уже подключён к горячей воде",
+ "alreadyCold": "Прибор уже подключён к холодной воде",
+ "needHotCollector": "Сначала поставь коллектор горячей воды",
+ "needColdCollector": "Сначала поставь коллектор холодной воды"
+ }
+ },
+ "electric": {
+ "layer": "Электрика",
+ "amps": "{{value}} А",
+ "pointKind": {
+ "socket": "Розетка",
+ "socket2": "Розетка двойная",
+ "socket_ip44": "Розетка IP44",
+ "power": "Силовая точка",
+ "switch": "Выключатель",
+ "switch2": "Выключатель 2-кл.",
+ "light": "Светильник",
+ "light_wall": "Бра",
+ "junction": "Распаечная коробка",
+ "outdoor": "Уличная розетка"
+ },
+ "circuitKind": {
+ "light": "Свет",
+ "socket": "Розетки",
+ "power": "Силовая",
+ "wet": "Мокрая зона",
+ "outdoor": "Улица",
+ "garage": "Гараж"
+ },
+ "circuitName": "{{kind}} {{n}}",
+ "tools": {
+ "mode": {
+ "select": {
+ "label": "Выбор",
+ "title": "Выбор: клик по точке, Shift — добавить, тяни вдоль стены, Delete — удалить"
+ },
+ "socket": {
+ "label": "Розетка",
+ "title": "Розетка: клик у стены, встаёт на грань стены"
+ },
+ "switch": {
+ "label": "Выключатель",
+ "title": "Выключатель: клик у стены"
+ },
+ "light": {
+ "label": "Свет",
+ "title": "Светильник: клик по потолку; бра и коробка — у стены"
+ },
+ "panel": {
+ "label": "Щит",
+ "title": "Щит: клик у стены"
+ }
+ },
+ "kind": {
+ "socket": "Одинарная",
+ "socket2": "Двойная",
+ "socket_ip44": "IP44",
+ "power": "Силовая",
+ "outdoor": "Уличная",
+ "switch": "1 клавиша",
+ "switch2": "2 клавиши",
+ "light": "Потолок",
+ "light_wall": "Бра",
+ "junction": "Коробка"
+ },
+ "groupTitle": "Группа для новых точек; выделенным точкам группа назначается в правой панели",
+ "noGroup": "Без группы",
+ "hintSelect": "тяни вдоль стены · Shift — добавить к выделению · Delete — удалить",
+ "hintCeiling": "клик по потолку",
+ "hintWall": "клик у стены"
+ },
+ "layerTag": {
+ "noGroup": "без группы",
+ "height": "{{height}} мм от пола",
+ "panel": "Щит"
+ },
+ "device": {
+ "socket": "Розетка с заземлением",
+ "socket2": "Розетка двойная с заземлением",
+ "socket_ip44": "Розетка IP44 с крышкой",
+ "power": "Силовая розетка / клеммник 32 А",
+ "switch": "Выключатель одноклавишный",
+ "switch2": "Выключатель двухклавишный",
+ "light": "Точка света потолочная (клеммник, крюк)",
+ "light_wall": "Бра, настенный вывод",
+ "junction": "Коробка распаечная с клеммами",
+ "outdoor": "Розетка уличная IP54, накладная"
+ },
+ "item": {
+ "rcbo": "Дифавтомат {{curve}}{{rating}} 30 мА",
+ "rcbo4p": "Дифавтомат {{curve}}{{rating}} 30 мА 4P",
+ "breaker": "Автомат {{curve}}{{rating}} {{poles}}P",
+ "rcd": "УЗО {{rating}} А 30 мА {{poles}}",
+ "frameIp44": "Рамка одноместная IP44",
+ "frame": "Рамка одноместная",
+ "box": "Подрозетник для полых стен Ø68",
+ "cable": "Кабель ВВГнг(А)-LS {{cable}}",
+ "conduit": "Металлорукав / гофра Ø{{d}}",
+ "main3p": "Вводной автомат 3P C32",
+ "main2p": "Вводной автомат 2P C40",
+ "relay": "Реле напряжения",
+ "panel": "Щит встраиваемый на {{modules}} модулей"
+ },
+ "warn": {
+ "cableUnknown": "{{label}}: не понял марку кабеля «{{cable}}» — пиши как 3x2.5",
+ "breakerOverCable": "{{label}}: автомат {{rating}} А на кабель {{cable}} — максимум {{max}} А, кабель перегреется",
+ "overload": "{{label}}: нагрузка {{load}} Вт ≈ {{current}} А больше автомата {{rating}} А",
+ "wetNoRcd": "{{label}}: {{kind}} без УЗО — нужен дифавтомат или УЗО 30 мА (ПУЭ 7.1.79)",
+ "socketRcd": "{{label}}: розеточную группу лучше защитить УЗО 30 мА (ПУЭ 7.1.79)",
+ "voltageDrop": "{{label}}: падение напряжения {{pct}} % при полной нагрузке — больше 5 %, увеличь сечение",
+ "tooManySockets": "{{label}}: {{sockets}} розеток на одну группу — лучше не больше 8–10",
+ "powerSeparate": "{{label}}: силовую точку (плита, духовка, котёл) ставят отдельной группой",
+ "lightWithSockets": "{{label}}: розетки в группе света — свет и розетки разводят разными группами",
+ "emptyCircuit": "{{label}}: в группе нет точек",
+ "noCircuit": "{{name}}: не назначена группа",
+ "unknownCircuit": "{{name}}: нет группы «{{id}}»",
+ "zone01Bath": "{{name}} над ванной — зона 0/1, розетки и выключатели запрещены (ГОСТ Р 50571.7.701)",
+ "zone01Shower": "{{name}} над душем — зона 0/1, розетки и выключатели запрещены (ГОСТ Р 50571.7.701)",
+ "zone2Bath": "{{name}}: {{d}} мм от ванны — зона 2, нужно не ближе 600 мм",
+ "zone2Shower": "{{name}}: {{d}} мм от душа — зона 2, нужно не ближе 600 мм",
+ "bathSocket": "{{name}} в санузле — нужна IP44 и УЗО 30 мА",
+ "bathNoRcd": "{{name}} в санузле, а группа {{circuit}} без УЗО",
+ "noPanel": "Не поставлен щит — длины кабеля считаются приблизительно",
+ "panelTooSmall": "Щит на {{modules}} модулей, а аппаратов на {{need}} — нужен от {{size}}"
+ },
+ "priceFromOwn": "цена из материалов сети: {{name}}",
+ "panel": {
+ "rcboPrefix": "Диф ",
+ "rcdPrefix": "УЗО+",
+ "clearSelection": "Снять выделение",
+ "panelTitle": "Щит",
+ "devices": "Аппаратов",
+ "modules": "{{n}} мод.",
+ "panelNeeded": "Нужен щит",
+ "panelFor": "на {{n}} мод.",
+ "modulesInPanel": "Модулей в щите",
+ "removePanel": "Убрать щит",
+ "pointsCount": "Точек: {{n}}",
+ "group": "Группа",
+ "mixed": "разные",
+ "noGroup": "Без группы",
+ "newGroup": "+ новая группа",
+ "type": "Тип",
+ "height": "Высота от пола",
+ "heightMixed": "разная",
+ "power": "Мощность",
+ "label": "Подпись",
+ "labelPlaceholder": "плита, ТВ…",
+ "pointHint": "Тяни символ вдоль стены · Shift+клик — добавить к выделению · Delete — удалить",
+ "deletePoint": "Удалить точку",
+ "deletePoints_one": "Удалить {{count}} точку",
+ "deletePoints_few": "Удалить {{count}} точки",
+ "deletePoints_many": "Удалить {{count}} точек",
+ "deletePoints_other": "Удалить {{count}} точек",
+ "noWarnings": "Замечаний нет",
+ "layerEyebrow": "Слой",
+ "points": "Точек",
+ "circuits": "Групп",
+ "load": "Нагрузка",
+ "panelRow": "Щит",
+ "panelState": "{{modules}} мод. → на {{size}}",
+ "notPlaced": "не поставлен",
+ "groups": "Группы",
+ "autoRouteTitle": "Проложить все группы от щита по стенам",
+ "placePanelFirst": "Сначала поставь щит",
+ "autoRoute": "Автотрасса",
+ "noGroups": "Групп пока нет",
+ "colGroup": "Группа",
+ "colProtection": "Защита",
+ "colPoints": "Тч",
+ "routed": "по трассе",
+ "estimated": "оценка без трассы",
+ "addGroup": "+ группа",
+ "materials": "Материалы",
+ "noMaterials": "Поставь точки и собери группы",
+ "total": "Итого по электрике",
+ "noPrice": "без цены: {{n}} поз.",
+ "warnings": "Замечания",
+ "howto": "Как делать",
+ "howtoNote": "Высоты по умолчанию: розетки 300 мм, над столешницей 1100, выключатели 900, бра 2000, трасса — на 150 мм ниже потолка. Кабель: свет 3×1,5 на 10 А, розетки 3×2,5 на 16 А, плита 3×6 на 32 А. Длина группы = трасса + опуски + 1,5 м на разделку в щите + 15 % запаса.",
+ "protection": "Защита",
+ "cable": "Кабель",
+ "phase": "Фаза",
+ "collapse": "Свернуть",
+ "name": "Название",
+ "device": "Аппарат",
+ "mcb": "Автомат",
+ "rcbo": "Дифавтомат",
+ "rcd": "Автомат + УЗО",
+ "rating": "Номинал",
+ "selectPoints": "Выделить точки",
+ "route": "Трасса",
+ "delete": "Удалить"
+ },
+ "steps": [
+ "Согласовать мощность и ввод с сетевой компанией (ТУ), выбрать 1 или 3 фазы.",
+ "Разметить на стенах все точки по этому плану: высоты — от чистого пола.",
+ "В СИП-доме — только в металлорукаве или стальной трубе, кабель ВВГнг(А)-LS; штроб в панелях нет — разводка в каналах панелей или за инсталляционной обрешёткой.",
+ "Проложить трассы: горизонталь под потолком на 150 мм, к точкам — строго вертикальные опуски, углы 90°.",
+ "Каждая группа — отдельным кабелем от щита, без скруток; ответвления — в коробках на клеммах Wago.",
+ "Подрозетники для полых стен, коробки — доступны для обслуживания.",
+ "Собрать щит: вводной автомат, реле напряжения, УЗО/дифы на розетки и мокрые зоны, автоматы на свет и силовые линии.",
+ "Прозвонить линии, замерить сопротивление изоляции мегаомметром, проверить срабатывание УЗО, подписать группы в щите.",
+ "Сфотографировать стены с трассами до зашивки — пригодится при ремонте."
+ ]
+ },
+ "heating": {
+ "layer": "Тёплый пол",
+ "units": {
+ "pcs": "шт",
+ "m": "м",
+ "m2": "м²",
+ "m3": "м³",
+ "kg": "кг",
+ "pack": "уп."
+ },
+ "cover": {
+ "tile": "плитка",
+ "laminate": "ламинат"
+ },
+ "tools": {
+ "autoLayout": "Разложить по комнатам",
+ "hintSelected": "Delete — удалить петлю · шаг и паттерн — в правой панели",
+ "hintIdle": "клик по петле — выбрать · коллектор тяни мышью"
+ },
+ "actions": {
+ "confirmReplace_one": "Заменить {{count}} петлю новой раскладкой? Ручные правки петель пропадут, коллектор останется на месте.",
+ "confirmReplace_few": "Заменить {{count}} петли новой раскладкой? Ручные правки петель пропадут, коллектор останется на месте.",
+ "confirmReplace_many": "Заменить {{count}} петель новой раскладкой? Ручные правки петель пропадут, коллектор останется на месте.",
+ "confirmReplace_other": "Заменить {{count}} петель новой раскладкой? Ручные правки петель пропадут, коллектор останется на месте.",
+ "done": "Разложено петель: {{count}}. {{notes}}"
+ },
+ "layout": {
+ "collectorInRoom": "Коллектор — в комнате «{{room}}»",
+ "noBoilerRoom": "Котельной нет — коллектор в центре дома",
+ "collectorKept": "Коллектор оставлен на месте",
+ "edgeSuffix": " · у наружной стены",
+ "noHeating": "«{{room}}» — без тёплого пола",
+ "fixedEdge": "«{{room}}»: пола не хватало — шаг 100 в полосе 1 м у наружных стен",
+ "fixedFull": "«{{room}}»: пола не хватало — шаг 100 на всю комнату",
+ "needRadiator": "«{{room}}»: пола не хватает и при шаге 100 — нужен радиатор",
+ "loopsInRoom_one": "«{{room}}»: {{count}} петля",
+ "loopsInRoom_few": "«{{room}}»: {{count}} петли",
+ "loopsInRoom_many": "«{{room}}»: {{count}} петель",
+ "loopsInRoom_other": "«{{room}}»: {{count}} петли",
+ "cantMerge": "Петель {{count}} — объединить мелкие не вышло, нужен второй коллектор",
+ "merged": "«{{a}}» и «{{b}}» — одна петля, {{len}} м"
+ },
+ "warn": {
+ "loopTooLong": "«{{room}}»: петля {{len}} м — больше {{max}} м, раздели на две",
+ "loopLong": "«{{room}}»: петля {{len}} м — длиннее {{max}} м, насосу тяжело",
+ "dpHigh": "«{{room}}»: потери давления {{dp}} кПа — больше 20",
+ "noFeed": "«{{room}}»: нет подводки от коллектора",
+ "roomShortCapped": "«{{room}}»: пол даёт {{power}} Вт, а теплопотери ≈{{loss}} Вт ({{lossWm2}} Вт/м²) — упёрлись в предельную температуру пола, нужен радиатор",
+ "roomShort": "«{{room}}»: пол даёт {{power}} Вт, а теплопотери ≈{{loss}} Вт ({{lossWm2}} Вт/м²) — уменьши шаг, подними температуру подачи или добавь радиатор",
+ "returnNotBelow": "Температура обратки не ниже подачи — проверь параметры",
+ "supplyHigh": "Подача {{t}} °C — для тёплого пола не выше 55 °C",
+ "insulationThin": "Утеплитель {{mm}} мм — для пола по грунту на Северо-Западе минимум ЭППС 100 мм, правильно 150",
+ "noCollector": "Коллектор не поставлен",
+ "collectorOutputs": "На коллекторе {{outputs}} выходов, а петель {{loops}}",
+ "tooManyLoops": "Петель {{count}} — больше 12 на один коллектор, ставь два или объединяй мелкие петли"
+ },
+ "item": {
+ "pipe500": "Труба {{pipe}}, бухта 500 м (всего по петлям {{total}} м)",
+ "pipe200": "Труба {{pipe}}, бухта 200 м",
+ "pipe200Total": "Труба {{pipe}}, бухта 200 м (всего по петлям {{total}} м)",
+ "collector": "Коллектор с расходомерами на {{n}} выход.",
+ "mixing": "Насосно-смесительный узел для тёплого пола",
+ "pump": "Циркуляционный насос 25/60 для узла, нужен напор ≥ {{head}} м",
+ "cabinet": "Шкаф коллекторный под {{n}} выход. и смесительный узел",
+ "eurocone": "Евроконус 16×2 — 3/4\"",
+ "damper": "Демпферная лента 10 мм",
+ "insulation": "Утеплитель {{insulation}}",
+ "film": "Плёнка ПЭ 200 мкм (с нахлёстом)",
+ "staples": "Скобы-гарпуны для трубы 16 мм (шаг 0,4 м)",
+ "mesh": "Армосетка 100×100, пруток 4 мм",
+ "ties": "Хомуты-стяжки для трубы к сетке",
+ "cps": "ЦПС М300 (стяжка {{mm}} мм, {{m3}} м³)",
+ "cement": "Цемент М500 (стяжка {{mm}} мм, {{m3}} м³, 1:3)",
+ "sand": "Песок строительный",
+ "fiber": "Фиброволокно полипропиленовое"
+ },
+ "price": {
+ "none": "цена не задана",
+ "own": "цена из материалов сети: {{name}}",
+ "pack": "{{from}} · {{qty}} {{unit}} в {{pack}}",
+ "twoHalves": "2 шт. на {{n}} вых. — {{name}}",
+ "twoOf": "{{name}} (два по {{n}})"
+ },
+ "tag": {
+ "length": "{{len}} м трубы · шаг {{step}} мм",
+ "snake": " · змейка",
+ "area": "{{area}} м² · {{power}} Вт ({{q}} Вт/м²)",
+ "excluded": "{{room}} — петля исключена"
+ },
+ "panel": {
+ "spiral": "Улитка",
+ "snake": "Змейка",
+ "clearSelection": "Снять выделение",
+ "collector": "Коллектор",
+ "loops": "Петель",
+ "flow": "Расход",
+ "flowM3h": "{{v}} м³/ч",
+ "pump": "Насос",
+ "head": "напор ≥ {{v}} м",
+ "outputs": "Выходов",
+ "label": "Подпись",
+ "reroute": "Перепроложить подводки",
+ "loopEyebrow": "Тёплый пол · петля {{id}}",
+ "area": "Площадь",
+ "pipe": "Труба",
+ "feed": "(подводка {{v}} м ×2)",
+ "power": "Мощность",
+ "wm2": "Вт/м²",
+ "floor": "Пол",
+ "lmin": "л/мин",
+ "kpa": "кПа",
+ "excludedFromCalc": "Петля исключена из расчёта",
+ "step": "Шаг, мм",
+ "pattern": "Укладка",
+ "include": "Вернуть в расчёт",
+ "exclude": "Исключить",
+ "deleteLoop": "Удалить петлю",
+ "noWarnings": "Замечаний нет",
+ "layerEyebrow": "Слой",
+ "excludedCount": " (+{{n}} искл.)",
+ "floorGives": "Пол отдаёт",
+ "heatLoss": "Теплопотери",
+ "boiler": "Котёл",
+ "boilerFrom": "от {{v}} кВт",
+ "unit": "Узел",
+ "unitValue": "{{flow}} м³/ч, напор ≥ {{head}} м",
+ "collectorOutputs": "{{n}} вых.",
+ "notPlaced": "не поставлен",
+ "loopsTitle": "Петли",
+ "noLoops": "Петель нет — нажми «Разложить по комнатам» в режиме редактирования",
+ "room": "Комната",
+ "colStep": "Шаг",
+ "total": "Итого",
+ "roomsTitle": "Комнаты: пол против теплопотерь",
+ "colLoss": "Потери",
+ "colFloor": "Пол",
+ "params": "Параметры",
+ "supply": "Подача",
+ "return": "Обратка",
+ "floorLimit": "Предел пола",
+ "norm": "норма",
+ "screed": "Стяжка",
+ "insulation": "Утеплитель",
+ "screedMix": "Стяжка из",
+ "cementSand": "цемент + песок",
+ "cps": "ЦПС",
+ "fixing": "Крепёж трубы",
+ "mesh": "армосетка",
+ "staples": "скобы-гарпуны",
+ "materials": "Материалы",
+ "noMaterials": "Разложи петли — появятся материалы",
+ "materialsTotal": "Итого по тёплому полу",
+ "noPriceCount": "{{label}}: {{n}} поз.",
+ "warnings": "Замечания",
+ "howto": "Как считается и как делать",
+ "howtoNote": "Длина петли = площадь без мебели / шаг + подводка туда и обратно, плюс 5 %. Теплоотдача — по логарифмическому перепаду подачи, обратки и воздуха (20 °C, санузел 24 °C), шагу и покрытию: плитка в санузлах, кухне, коридоре и прихожей, ламинат в остальных. Предел пола 29 °C, санузел 33 °C, у наружных стен 35 °C. Теплопотери по укрупнённой норме для Северо-Запада: 50 Вт/м² без наружных стен, 60 — одна наружная, 70 — угловая. Котёл — теплопотери × 1,2. Расход петли = 0,86 × мощность × 1,1 / Δt; потери давления — по Дарси с запасом 30 % на местные сопротивления; насос — самая тяжёлая петля + 5 кПа на узел."
+ },
+ "steps": [
+ "Выровнять основание, перепад не больше 5 мм на 2 м.",
+ "По периметру комнат — демпферная лента 10 мм, на всю высоту стяжки.",
+ "Утеплитель внахлёст без щелей, сверху плёнка с нахлёстом 100 мм на ленту.",
+ "Армосетка на подкладках или трубу крепить гарпунами к утеплителю через 0,3–0,5 м, на поворотах чаще.",
+ "Каждая петля — цельная труба из бухты, без соединений в стяжке. Улитку начинать с подачи по периметру.",
+ "Подводки в коридорах — в гофре или теплоизоляции, чтобы не перегревать проход.",
+ "Опрессовка 6 бар на 24 часа до заливки; заливать под давлением 3 бара.",
+ "Стяжка минимум 45 мм над трубой, с фиброволокном; деформационные швы у порогов и на площадях больше 30 м².",
+ "Первый запуск — не раньше 28 суток, температуру поднимать по 5 °C в сутки.",
+ "Расходомеры на коллекторе выставить по таблице балансировки."
+ ]
+ }
+}
diff --git a/src/i18n/locales/ru/plan.json b/src/i18n/locales/ru/plan.json
new file mode 100644
index 0000000..88d81df
--- /dev/null
+++ b/src/i18n/locales/ru/plan.json
@@ -0,0 +1,269 @@
+{
+ "close": "Закрыть",
+ "delete": "Удалить",
+ "height": "Высота",
+ "width": "Ширина",
+ "area": "Площадь",
+ "type": "Тип",
+ "openingTypes": {
+ "door": "Дверь",
+ "window": "Окно",
+ "gate": "Ворота"
+ },
+ "openingPresets": {
+ "entry": "Входная дверь 960×2070",
+ "interior": "Межкомнатная 800×2000",
+ "gate": "Ворота 2500×2200",
+ "window": "Окно 1200×1400, подоконник 800"
+ },
+ "materialKinds": {
+ "sip": "СИП-панель",
+ "pir": "ПИР-панель",
+ "brick": "Кирпич",
+ "block": "Блок",
+ "timber": "Брус/бревно",
+ "frame": "Каркас",
+ "concrete": "Бетон",
+ "glass": "Стекло",
+ "other": "Другое"
+ },
+ "zoneKinds": {
+ "fill": "Отсыпка",
+ "lawn": "Газон",
+ "paving": "Мощение",
+ "other": "Другое"
+ },
+ "wall": {
+ "eyebrow": "Стена",
+ "length": "Длина",
+ "thickness": "Толщина",
+ "material": "Материал",
+ "noMaterial": "— без материала —",
+ "panels": "Панелей",
+ "panelsFrac": "{{n}} панели",
+ "panelsDative_one": "{{count}} панели",
+ "panelsDative_few": "{{count}} панелям",
+ "panelsDative_many": "{{count}} панелям",
+ "panelsDative_other": "{{count}} панелям",
+ "multipleOf": "кратно {{panels}}",
+ "panelWidth": "по {{width}} мм",
+ "extraPanels": "+{{n}} панели",
+ "notAligned": "длина некратна {{half}} мм, будет подрезка. Выгоднее {{down}} или {{up}}.",
+ "openings": "Проёмы",
+ "fromA": "от a {{offset}}",
+ "selectBuilding": "Выделить здание",
+ "delete": "Удалить стену",
+ "hint": "Ввод в мм или м (2800, 2,8 м). Двойной клик по длине на плане — тоже ввод. ⌘Z — отмена."
+ },
+ "group": {
+ "deselect": "Снять выделение",
+ "eyebrow": "Группа",
+ "selected": "Выделено: {{summary}}",
+ "moveX": "Сдвиг X",
+ "moveY": "Сдвиг Y",
+ "rotateDeg": "Поворот, °",
+ "alignStreet": "Повернуть параллельно улице",
+ "hint": "Тяни любой выделенный объект или ручку со стрелками под рамкой — едет вся группа (шаг 100 мм). Стрелки — 100 мм, Shift — 1 м. Угол здания снаружи или кружок над рамкой — поворот шагом 0,5° с магнитом к осям и улице, Shift — 15°, Alt — вокруг противоположного угла. [ и ] — 1°, Shift — 15°. Shift+клик — добавить или убрать, Shift+рамка по пустому месту — выделить, ⌘A — всё, Esc — снять."
+ },
+ "opening": {
+ "sill": "Подоконник",
+ "offset": "От начала a",
+ "hinges": "Петли",
+ "hingeStart": "у a",
+ "hingeEnd": "у b",
+ "swing": "Открывание",
+ "left": "влево",
+ "right": "вправо",
+ "toEnd": "До конца b",
+ "wall": "Стена {{id}}",
+ "hint": "Тяни проём вдоль стены, края — ширина (шаг 50 мм). F — сторона, H — петли, Delete — удалить."
+ },
+ "zone": {
+ "defaultName": "Зона {{n}}",
+ "lockedEyebrow": "Данные участка",
+ "lockedHint": "Зона заведена сервером по данным участка, в редакторе не меняется.",
+ "eyebrow": "Зона участка",
+ "name": "Название",
+ "perimeter": "Периметр",
+ "vertices": "Вершин",
+ "hint": "Тяни вершины, двойной клик по стороне — новая вершина. Delete — удалить зону."
+ },
+ "furniture": {
+ "eyebrow": "Мебель",
+ "depth": "Глубина",
+ "rotation": "Поворот",
+ "color": "Цвет",
+ "center": "Центр",
+ "rotate90": "Повернуть на 90°",
+ "hint": "Тяни мебель по плану (шаг 50 мм), кружок сверху — поворот (Shift — шаг 5°). R — 90°, Delete — удалить.",
+ "categories": {
+ "bedroom": "Спальня",
+ "living": "Гостиная",
+ "kitchen": "Кухня",
+ "bathroom": "Санузел",
+ "hall": "Прихожая",
+ "other": "Прочее"
+ },
+ "items": {
+ "bed-1600": "Кровать двуспальная 1600",
+ "bed-1800": "Кровать двуспальная 1800",
+ "bed-900": "Кровать односпальная 900",
+ "nightstand": "Прикроватная тумба",
+ "wardrobe": "Шкаф распашной",
+ "dresser": "Комод",
+ "sofa": "Диван трёхместный",
+ "sofa-corner": "Диван угловой",
+ "armchair": "Кресло",
+ "coffee-table": "Журнальный стол",
+ "tv-stand": "ТВ-тумба с телевизором",
+ "bookcase": "Стеллаж",
+ "plant": "Растение в кашпо",
+ "kitchen-base": "Кухонный модуль 600",
+ "kitchen-drawers": "Модуль с ящиками 600",
+ "kitchen-corner": "Угловой модуль 900",
+ "kitchen-upper": "Навесной шкаф 600",
+ "kitchen-sink": "Мойка в модуле 800",
+ "stove": "Плита 600",
+ "dishwasher": "Посудомоечная машина 600",
+ "fridge": "Холодильник",
+ "dining-4": "Обеденный стол на 4",
+ "dining-6": "Обеденный стол на 6",
+ "dining-round": "Круглый стол на 4",
+ "chair": "Стул",
+ "toilet": "Унитаз",
+ "washbasin": "Раковина",
+ "vanity": "Тумба с раковиной 800",
+ "bathtub": "Ванна 1700",
+ "shower": "Душевая 900×900",
+ "washer": "Стиральная машина",
+ "water-heater": "Бойлер 80 л",
+ "coat-rack": "Вешалка настенная",
+ "shoe-cabinet": "Обувница",
+ "hall-wardrobe": "Шкаф-купе",
+ "desk": "Рабочий стол",
+ "office-chair": "Офисное кресло",
+ "fireplace": "Камин",
+ "masonry-stove": "Печь кирпичная",
+ "gas-boiler": "Котёл настенный",
+ "floor-boiler": "Котёл напольный"
+ }
+ },
+ "furniturePanel": {
+ "eyebrow": "Каталог",
+ "title": "Мебель",
+ "hint": "Перетащи на план или кликни — встанет в центр экрана. R — поворот на 90°."
+ },
+ "estimate": {
+ "walls_one": "{{count}} стена, {{length}}",
+ "walls_few": "{{count}} стены, {{length}}",
+ "walls_many": "{{count}} стен, {{length}}",
+ "walls_other": "{{count}} стен, {{length}}",
+ "panels_one": "{{count}} панель",
+ "panels_few": "{{count}} панели",
+ "panels_many": "{{count}} панелей",
+ "panels_other": "{{count}} панелей",
+ "wholeWall": " — стена целиком",
+ "noMaterial": "материал не задан",
+ "panelSize": " · панель {{w}}×{{h}}",
+ "withWaste": "с запасом {{pct}}%: {{n}} шт",
+ "areaWithWaste": " · {{area}} м² с запасом",
+ "noPrice": "цена не задана",
+ "piecesPerM2": "{{n}} шт/м² (блок {{l}}×{{h}} + шов {{joint}} мм)",
+ "pieces": " · {{n}} шт",
+ "source": "источник",
+ "checked": " · проверено {{date}}"
+ },
+ "tabs": {
+ "general": "Общее",
+ "materials": "Материалы",
+ "sewer": "Канализация",
+ "water": "Водопровод",
+ "electric": "Электрика",
+ "heating": "Тёплый пол"
+ },
+ "materials": {
+ "eyebrow": "План",
+ "title": "Материалы стен",
+ "noWalls": "Стен пока нет",
+ "unused": "не используется в стенах",
+ "waste": "Запас на подрезку",
+ "total": "Итого по стенам",
+ "noPrice_one": "без цены: {{count}} поз.",
+ "noPrice_few": "без цены: {{count}} поз.",
+ "noPrice_many": "без цены: {{count}} поз.",
+ "noPrice_other": "без цены: {{count}} поз.",
+ "hint": "Клик по стене — ручки и свойства. W — рисовать стену."
+ },
+ "toolbar": {
+ "tools": {
+ "select": "Выбор",
+ "wall": "Стена",
+ "door": "Дверь",
+ "window": "Окно",
+ "zone": "Зона",
+ "building": "Здание"
+ },
+ "undo": "Отменить",
+ "undoTitle": "Отменить (⌘Z)",
+ "redo": "Повторить",
+ "redoTitle": "Повторить (⌘⇧Z)",
+ "buildingTitle": "Здание (B): клик по дому — выделить целиком со стенами, мебелью и сетями; тяни — перенос, углы — поворот. Esc или клик мимо — выход",
+ "zonesLocked": "Зоны заблокированы — сними замок в «Слоях»",
+ "zoneTitle": "Зона участка: клики по вершинам, замкнуть — клик по первой точке или Enter",
+ "view": "Обзор",
+ "furniture": "Мебель",
+ "furnitureTitle": "Мебель: каталог, перетащи на план",
+ "measure": "Линейка",
+ "measureTitle": "Линейка (M): клик A → клик B, ⌘ — цепочка",
+ "summary": "Сводка",
+ "summaryTitle": "Сводка по дому",
+ "dims": "Размеры",
+ "dimsTitle": "Всегда показывать длины стен",
+ "fit": "Вписать",
+ "fitTitle": "Показать весь участок",
+ "map": "Карта",
+ "mapTitle": "Спутниковый снимок под планом",
+ "align": "Выровнять снимок",
+ "alignTitle": "Выровнять снимок по участку: сдвиг и поворот · Esc — выйти",
+ "opacityTitle": "Непрозрачность снимка: {{pct}}%",
+ "clickWall": "клик по стене",
+ "noMaterial": "Без материала, 200 мм"
+ },
+ "summary": {
+ "buildingKinds": {
+ "house": "Дом",
+ "garage": "Гараж",
+ "outbuilding": "Постройка"
+ },
+ "side": "Сторона {{from}}–{{to}}",
+ "sideStreet": "{{side}}, улица",
+ "street": "Улица",
+ "defaultRoom": "Помещение {{n}}",
+ "lessThan": "меньше {{norm}}",
+ "empty": "Нет замкнутых контуров стен — помещения не найдены.",
+ "totalArea": "Общая площадь",
+ "livingArea": "Жилая площадь",
+ "rooms": "Комнат",
+ "bedrooms": "Спален",
+ "baths": "Санузлов",
+ "footprint": "Пятно застройки",
+ "height": "Высота",
+ "allHouses": "Все дома",
+ "roomsSection": "Помещения",
+ "lowLight": "мало света",
+ "area": "Площадь",
+ "site": "Участок",
+ "siteArea": "{{area}} · {{ares}} сот.",
+ "built": "Застройка",
+ "toStreet": "До улицы",
+ "toBorders": "До границ, мин.",
+ "toNeighbour": "До соседа {{name}}",
+ "unmatchedLabels": "Подписи вне помещений",
+ "wallCost": "Стоимость стен",
+ "withWaste": "С запасом {{pct}} %",
+ "noPrice_one": "без цены: {{count}}",
+ "noPrice_few": "без цены: {{count}}",
+ "noPrice_many": "без цены: {{count}}",
+ "noPrice_other": "без цены: {{count}}"
+ }
+}
diff --git a/src/i18n/locales/ru/view3d.json b/src/i18n/locales/ru/view3d.json
new file mode 100644
index 0000000..db89db1
--- /dev/null
+++ b/src/i18n/locales/ru/view3d.json
@@ -0,0 +1,25 @@
+{
+ "views": { "top": "Сверху", "front": "Спереди" },
+ "looks": { "model": "Макет", "real": "Материалы" },
+ "cuts": { "full": "Полные", "low": "1 м", "floor": "Пол" },
+ "finishes": { "plaster": "Штукатурка", "timber": "Имитация бруса", "planken": "Планкен" },
+ "presets": {
+ "granite": "Серый гранит",
+ "scandinavia": "Скандинавия",
+ "graphite": "Графит",
+ "warm": "Тёплый",
+ "forest": "Лес"
+ },
+ "toolbar": {
+ "grid": "Сетка",
+ "facade": "Фасад",
+ "wallColor": "Цвет стен",
+ "accent": "Акцент",
+ "presets": "Готовые сочетания"
+ },
+ "error": {
+ "eyebrow": "3D-вид",
+ "text": "Не получилось построить 3D по этому плану. План не пострадал, в редакторе всё на месте. Поправьте стены или проёмы и вернитесь на вкладку.",
+ "retry": "Попробовать снова"
+ }
+}
diff --git a/src/i18n/units.ts b/src/i18n/units.ts
new file mode 100644
index 0000000..379455e
--- /dev/null
+++ b/src/i18n/units.ts
@@ -0,0 +1,40 @@
+import { lang, t } from '.'
+
+const SYNONYMS: Record<string, string> = {
+ pcs: 'pcs', pc: 'pcs', шт: 'pcs', штука: 'pcs', штук: 'pcs',
+ m: 'm', м: 'm', 'пог. м': 'm', 'пог.м': 'm', 'пог м': 'm', 'пог. м.': 'm', 'м.п.': 'm', 'мп': 'm', 'п.м.': 'm',
+ m2: 'm2', 'm²': 'm2', м2: 'm2', 'м²': 'm2', 'кв. м': 'm2', 'кв.м': 'm2',
+ m3: 'm3', 'm³': 'm3', м3: 'm3', 'м³': 'm3', 'куб. м': 'm3', 'куб.м': 'm3',
+ mm: 'mm', мм: 'mm', cm: 'cm', см: 'cm',
+ roll: 'roll', рул: 'roll', рулон: 'roll',
+ coil: 'coil', бухта: 'coil', бухт: 'coil',
+ pack: 'pack', упак: 'pack', уп: 'pack', упаковка: 'pack',
+ kg: 'kg', кг: 'kg',
+ l: 'l', л: 'l',
+ set: 'set', компл: 'set', комплект: 'set',
+ sheet: 'sheet', лист: 'sheet',
+ kit: 'kit', домокомплект: 'kit',
+}
+
+const keyOf = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace(/\.$/, '')
+
+const code = (raw: string) => SYNONYMS[keyOf(raw)] ?? SYNONYMS[raw.trim().toLowerCase().replace(/\s+/g, ' ')]
+
+const TOKENS = Object.keys(SYNONYMS)
+ .filter((k) => /[а-яё]/i.test(k))
+ .sort((a, b) => b.length - a.length)
+ .map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+
+const TOKEN_RE = new RegExp(`(?<![а-яёa-z])(${TOKENS.join('|')})\\.?(?![а-яёa-z0-9²³])`, 'gi')
+
+// Display label for a unit from plan or catalog data ("шт", "пог. м", "упак (5 шт, 3.51 м²)"); data stays untouched.
+export function unitLabel(raw: string | undefined): string {
+ if (!raw) return ''
+ const c = code(raw)
+ if (c) return lang() === 'ru' && /[а-яё]/i.test(raw) ? raw : t(`common:units.${c}`)
+ if (lang() === 'ru') return raw
+ return raw.replace(TOKEN_RE, (m) => {
+ const k = code(m)
+ return k ? t(`common:units.${k}`) : m
+ })
+}
diff --git a/src/index.css b/src/index.css
new file mode 100644
index 0000000..2f962ff
--- /dev/null
+++ b/src/index.css
@@ -0,0 +1,1067 @@
+* {
+ box-sizing: border-box;
+}
+
+html,
+body {
+ overscroll-behavior: none;
+}
+
+html,
+body,
+#root {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ background: var(--bg);
+}
+
+button,
+select,
+input {
+ font: inherit;
+ color: inherit;
+}
+
+a {
+ color: var(--accent);
+ text-decoration: none;
+}
+
+a:hover {
+ text-decoration: underline;
+}
+
+.app {
+ position: relative;
+ width: 100%;
+ height: 100%;
+}
+
+.plan-canvas {
+ position: absolute;
+ inset: 0;
+ touch-action: none;
+ cursor: grab;
+}
+
+.plan-canvas:active {
+ cursor: grabbing;
+}
+
+.plan-canvas--zone,
+.plan-canvas--zone:active,
+.plan-canvas--measure,
+.plan-canvas--measure:active,
+.plan-canvas--wall,
+.plan-canvas--wall:active,
+.plan-canvas--door,
+.plan-canvas--door:active,
+.plan-canvas--window,
+.plan-canvas--window:active {
+ cursor: crosshair;
+}
+
+.plan-canvas--dragging,
+.plan-canvas--dragging:active {
+ cursor: move;
+}
+
+.overlay {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+
+.overlay > * {
+ pointer-events: auto;
+}
+
+.header {
+ position: absolute;
+ top: var(--header-top);
+ left: 10px;
+ right: 10px;
+ height: var(--header-h);
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 0 8px 0 12px;
+ border-radius: 14px;
+ z-index: 5;
+}
+
+.app--plan {
+ --header-top: calc(var(--ruler) + 8px);
+ --chrome-left: calc(var(--ruler) + 8px);
+ --chrome-top: calc(var(--header-top) + var(--header-h) + 8px);
+}
+
+.app--plan .header {
+ left: var(--chrome-left);
+}
+
+.header__logo {
+ width: 22px;
+ height: 22px;
+ flex: none;
+ border-radius: 7px;
+ background: var(--accent);
+ box-shadow: inset 0 -5px 0 rgba(0, 0, 0, 0.12);
+}
+
+.header__text {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.header__title {
+ font-size: 14px;
+ font-weight: 650;
+}
+
+.header__meta {
+ margin-left: 10px;
+ color: var(--muted);
+ font-size: 12.5px;
+}
+
+.header__actions {
+ display: flex;
+ flex: none;
+ gap: 4px;
+}
+
+.save {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ gap: 6px;
+ max-width: 260px;
+ height: 26px;
+ padding: 0 10px;
+ border-radius: 999px;
+ background: #f6f4f0;
+ color: var(--muted);
+ font-size: 12px;
+ white-space: nowrap;
+}
+
+a.save:hover {
+ text-decoration: none;
+ background: var(--accent-soft);
+}
+
+.save__text {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.save__dot {
+ width: 7px;
+ height: 7px;
+ flex: none;
+ border-radius: 50%;
+ background: var(--ok);
+}
+
+.save--warn {
+ background: var(--accent-soft);
+ color: #b4581a;
+}
+
+.save--warn .save__dot {
+ background: var(--warn);
+}
+
+.save--err {
+ background: #fdf0ee;
+ color: var(--danger);
+}
+
+.save--err .save__dot {
+ background: var(--danger);
+}
+
+.save--busy .save__dot {
+ background: var(--warn);
+ animation: pulse 1s ease-in-out infinite;
+}
+
+@keyframes pulse {
+ 50% {
+ opacity: 0.3;
+ }
+}
+
+.page {
+ position: absolute;
+ inset: 0;
+ overflow: auto;
+ padding: calc(var(--header-h) + 22px) 16px 24px;
+}
+
+.page--full {
+ touch-action: none;
+ overflow: hidden;
+ padding: 0;
+}
+
+.page__loading {
+ display: grid;
+ place-items: center;
+ height: 100%;
+ min-height: 200px;
+ color: var(--muted);
+}
+
+.toolbar.canvas-toolbar {
+ width: 80px;
+ max-height: calc(100% - var(--chrome-top) - 56px);
+ align-items: stretch;
+ padding: 6px;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-width: thin;
+ scrollbar-color: var(--line-strong) transparent;
+}
+
+.toolbar.canvas-toolbar > * {
+ flex: none;
+}
+
+.toolbar.canvas-toolbar::-webkit-scrollbar {
+ width: 4px;
+}
+
+.toolbar.canvas-toolbar::-webkit-scrollbar-thumb {
+ border-radius: 2px;
+ background: var(--line-strong);
+}
+
+.toolbar .tool {
+ width: 100%;
+}
+
+.toolbar.canvas-toolbar--column .canvas-toolbar__sep {
+ margin: 2px 0;
+}
+
+.toolbar__history {
+ position: sticky;
+ top: -6px;
+ z-index: 1;
+ margin: -6px -6px 0;
+ padding: 6px 6px 2px;
+ background: var(--surface);
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 2px;
+}
+
+.toolbar .tool--mini {
+ width: auto;
+ padding: 6px 0;
+}
+
+.tool:disabled {
+ opacity: 0.35;
+ cursor: default;
+ background: transparent;
+}
+
+.tool--on {
+ color: var(--accent);
+ background: var(--accent-soft);
+}
+
+.toolbar__opacity {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+ width: 100%;
+ color: var(--muted);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+}
+
+.toolbar__opacity input {
+ width: 56px;
+ accent-color: var(--accent);
+}
+
+.tool {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 2px;
+ width: 66px;
+ padding: 7px 2px 5px;
+ border: 0;
+ border-radius: 11px;
+ background: transparent;
+ cursor: pointer;
+ color: var(--ink);
+}
+
+.tool:hover {
+ background: #f7f4f0;
+}
+
+.tool--active,
+.tool--active:hover {
+ background: var(--accent);
+ color: #fff;
+}
+
+.tool__icon {
+ width: 20px;
+ height: 20px;
+ fill: currentColor;
+}
+
+.tool__icon--line {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 2;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.tool__label {
+ font-size: 11px;
+ font-weight: 600;
+}
+
+.toolbar__material {
+ position: absolute;
+ top: 6px;
+ left: calc(100% + 10px);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ border-radius: 12px;
+ background: var(--card);
+ box-shadow: var(--shadow);
+ white-space: nowrap;
+}
+
+.select {
+ height: 30px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ padding: 0 8px;
+ background: var(--card);
+}
+
+.swatch {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ flex: none;
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.12);
+}
+
+.swatch--lg {
+ width: 28px;
+ height: 28px;
+ border-radius: 8px;
+}
+
+.inspector {
+ position: absolute;
+ top: var(--chrome-top);
+ right: 12px;
+ width: 310px;
+ max-height: calc(100% - var(--chrome-top) - 60px);
+ overflow: auto;
+ padding: 16px;
+}
+
+.inspector__head {
+ position: relative;
+ margin-bottom: 12px;
+}
+
+.eyebrow--lock {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+}
+
+.inspector__tabs {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-width: 0;
+ margin-bottom: 12px;
+}
+
+.inspector__sheet-close,
+.tool--narrow {
+ display: none;
+}
+
+.inspector__close {
+ position: absolute;
+ top: -4px;
+ right: -6px;
+}
+
+.inspector__title {
+ font-size: 17px;
+ font-weight: 650;
+}
+
+.inspector__section {
+ margin-top: 14px;
+ padding-top: 12px;
+ border-top: 1px solid var(--line);
+}
+
+.props {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 6px 12px;
+ margin: 0;
+}
+
+.props dt {
+ color: var(--muted);
+}
+
+.props dd {
+ margin: 0;
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+.chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.row {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 4px 0;
+}
+
+.row--center {
+ align-items: center;
+}
+
+.total {
+ margin-top: 4px;
+ font-size: 15px;
+}
+
+.furniture-panel {
+ position: absolute;
+ top: var(--chrome-top);
+ left: calc(var(--chrome-left, 12px) + 88px);
+ width: 300px;
+ max-height: calc(100% - var(--chrome-top) - 60px);
+}
+
+.furniture-panel__group + .furniture-panel__group {
+ margin-top: 14px;
+}
+
+.furniture-panel__grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 4px;
+ margin-top: 6px;
+}
+
+.furniture-panel__item {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ padding: 8px 4px 6px;
+ border: 1px solid transparent;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--ink-2);
+ cursor: grab;
+}
+
+.furniture-panel__item:hover {
+ border-color: var(--line);
+ background: var(--surface-2);
+}
+
+.furniture-panel__name {
+ font-size: 11px;
+ line-height: 1.2;
+ text-align: center;
+}
+
+.gate {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ padding: 16px;
+ background: var(--bg);
+}
+
+.gate__card {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: min(340px, 100%);
+ padding: 24px;
+}
+
+.gate__card .input {
+ width: 100%;
+ height: var(--control-h-lg);
+}
+
+.gate__title {
+ font-size: var(--text-lg);
+ font-weight: 650;
+}
+
+.gate__error {
+ color: var(--danger);
+ font-size: 13px;
+}
+
+button.save {
+ border: 0;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.preview-bar {
+ position: absolute;
+ top: calc(var(--chrome-top) + 4px);
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ max-width: calc(100% - 24px);
+ padding: 8px 10px 8px 16px;
+ border-left: 3px solid var(--accent);
+ z-index: var(--z-popover);
+}
+
+.preview-bar__actions {
+ display: flex;
+ flex: none;
+ gap: 6px;
+}
+
+.versions__head {
+ padding: 4px 4px 8px;
+}
+
+.versions__save {
+ display: flex;
+ gap: 6px;
+ padding: 4px;
+}
+
+.versions__save .input {
+ flex: 1;
+}
+
+.versions__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 6px 4px;
+ border-radius: 8px;
+}
+
+.versions__row:hover {
+ background: var(--surface-2);
+}
+
+.versions__info {
+ min-width: 0;
+}
+
+.versions__name {
+ overflow: hidden;
+ font-size: 13px;
+ font-weight: 600;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.versions__actions {
+ display: flex;
+ flex: none;
+ gap: 4px;
+}
+
+.toast {
+ position: absolute;
+ top: calc(var(--chrome-top) + 4px);
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 10px 16px;
+ border-left: 3px solid var(--ok);
+ font-weight: 600;
+ z-index: var(--z-popover);
+ animation: toast-in 0.2s ease-out;
+}
+
+@keyframes toast-in {
+ from {
+ opacity: 0;
+ transform: translate(-50%, -6px);
+ }
+}
+
+.align-controls {
+ position: absolute;
+ top: var(--chrome-top);
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 10px 14px;
+ z-index: var(--z-chrome);
+}
+
+.align-controls__head {
+ display: flex;
+ gap: 10px;
+ align-items: baseline;
+}
+
+.ctx-menu {
+ position: absolute;
+ min-width: 190px;
+ padding: 4px;
+ box-shadow: var(--shadow-lg);
+ z-index: var(--z-popover);
+}
+
+.measure-hint {
+ position: absolute;
+ bottom: 60px;
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 8px 14px;
+ color: var(--ink-2);
+ font-size: 12.5px;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ z-index: var(--z-chrome);
+}
+
+.room-edit__input {
+ width: 140px;
+ text-align: center;
+}
+
+.view-controls {
+ bottom: 12px;
+}
+
+.compass svg {
+ width: 20px;
+ height: 20px;
+ transition: transform 0.2s;
+}
+
+.form {
+ display: grid;
+ gap: 8px;
+ margin-bottom: 12px;
+}
+
+.form__row {
+ display: grid;
+ grid-template-columns: 96px 1fr;
+ align-items: center;
+ gap: 8px;
+ color: var(--muted);
+ font-size: 13px;
+}
+
+.form__row .input,
+.form__select {
+ width: 100%;
+ color: var(--ink);
+}
+
+.form__color {
+ width: 44px;
+ height: 28px;
+ padding: 0;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-xs);
+ background: none;
+}
+
+.props--compact {
+ font-size: 13px;
+}
+
+.layout-hint {
+ margin-top: 12px;
+ padding: 10px 12px;
+ border-radius: var(--radius-sm);
+ background: var(--surface-2);
+ font-size: 12.5px;
+ line-height: 1.5;
+}
+
+.layout-hint--warn {
+ background: var(--warn-soft);
+}
+
+.layout-hint__actions {
+ display: flex;
+ gap: 4px;
+ margin-top: 6px;
+}
+
+.row--link {
+ width: 100%;
+ border: 0;
+ border-radius: var(--radius-xs);
+ background: transparent;
+ text-align: left;
+ cursor: pointer;
+}
+
+.row--link:hover {
+ background: var(--surface-2);
+}
+
+.inspector__actions {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 16px;
+}
+
+.waste {
+ width: 72px;
+}
+
+.inspector__delete {
+ width: 100%;
+ margin-top: 16px;
+}
+
+.material {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 10px 0;
+}
+
+.material + .material {
+ border-top: 1px solid var(--line);
+}
+
+.material--unused {
+ opacity: 0.6;
+}
+
+.material__body {
+ flex: 1;
+ min-width: 0;
+}
+
+.material__name {
+ font-weight: 600;
+}
+
+.material__calc {
+ margin-top: 4px;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.5;
+}
+
+.material__price {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ margin-top: 4px;
+ font-variant-numeric: tabular-nums;
+}
+
+.material__source {
+ margin-top: 2px;
+ font-size: 12px;
+}
+
+.hint {
+ margin: 12px 0 0;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.grid-legend {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.grid-legend__cell {
+ width: 10px;
+ height: 10px;
+ border: 1px solid #d9d3c9;
+ background: #ffffff;
+ box-shadow: inset 0 0 0 0.5px #ece8e1;
+}
+
+.status {
+ position: absolute;
+ left: var(--chrome-left, 12px);
+ bottom: 12px;
+ display: flex;
+ gap: 16px;
+ padding: 8px 14px;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
+
+.alert {
+ position: absolute;
+ top: var(--chrome-top);
+ left: 50%;
+ transform: translateX(-50%);
+ max-width: 520px;
+ padding: 12px 16px;
+ color: var(--danger);
+ white-space: pre-wrap;
+}
+
+.notice {
+ position: absolute;
+ bottom: 60px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ max-width: calc(100% - 24px);
+ padding: 12px 14px 12px 16px;
+ border-left: 3px solid var(--accent);
+ z-index: 6;
+}
+
+.notice__title {
+ font-weight: 650;
+}
+
+.notice__actions {
+ display: flex;
+ flex: none;
+ gap: 6px;
+}
+
+.length-edit {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 8px 3px 3px;
+ border-radius: 9px;
+ background: var(--card);
+ box-shadow: 0 0 0 2px var(--accent), var(--shadow);
+ transform: translate(-50%, -50%);
+}
+
+.length-edit__input {
+ width: 72px;
+ height: 26px;
+ padding: 0 6px;
+ border: 0;
+ outline: 0;
+ font-weight: 600;
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+.length-edit__unit {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+@media (max-width: 1100px) {
+ .header__meta {
+ display: none;
+ }
+}
+
+@media (max-width: 760px) {
+ :root {
+ --header-top: 6px;
+ }
+
+ .app--plan {
+ --header-top: calc(var(--ruler) + 6px);
+ --chrome-left: 8px;
+ --chrome-top: calc(var(--header-top) + var(--header-h) + 8px);
+ }
+
+ .app--plan .header {
+ left: 6px;
+ }
+
+ .header {
+ left: 6px;
+ right: 6px;
+ gap: 6px;
+ padding: 0 4px 0 8px;
+ }
+
+ .header .segmented {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+
+ .header__text,
+ .save__text {
+ display: none;
+ }
+
+ .header .segmented__item {
+ padding: 0 8px;
+ }
+
+ .toolbar.canvas-toolbar {
+ top: auto;
+ right: 8px;
+ bottom: 8px;
+ left: 8px;
+ width: auto;
+ flex-direction: row;
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+
+ .toolbar .tool {
+ flex: none;
+ width: 64px;
+ }
+
+ .toolbar__history {
+ flex: none;
+ width: 72px;
+ }
+
+ .toolbar .tool--mini {
+ width: auto;
+ }
+
+ .toolbar__opacity {
+ width: 64px;
+ }
+
+ .toolbar .canvas-toolbar__sep {
+ width: 1px;
+ height: auto;
+ margin: 4px 2px;
+ }
+
+ .toolbar__material {
+ position: fixed;
+ top: auto;
+ bottom: 86px;
+ left: 8px;
+ }
+
+ .toolbar__opacity {
+ flex: none;
+ }
+
+ .inspector {
+ position: fixed;
+ top: auto;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ width: auto;
+ max-height: 55vh;
+ border-radius: 16px 16px 0 0;
+ box-shadow: var(--shadow-lg);
+ z-index: 15;
+ }
+
+ .inspector--summary {
+ display: none;
+ }
+
+ .inspector--summary.inspector--open {
+ display: block;
+ }
+
+ .inspector__sheet-close,
+ .toolbar .tool--narrow {
+ display: flex;
+ }
+
+ .furniture-panel {
+ position: fixed;
+ top: auto;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ width: auto;
+ max-height: 60vh;
+ border-radius: 16px 16px 0 0;
+ z-index: 15;
+ }
+
+ .status {
+ display: none;
+ }
+
+ .view-controls.canvas-toolbar {
+ top: var(--chrome-top);
+ right: 8px;
+ bottom: auto;
+ }
+
+ .align-controls {
+ left: 8px;
+ right: 8px;
+ transform: none;
+ }
+
+ .align-controls__head .muted {
+ display: none;
+ }
+
+ .measure-hint {
+ bottom: 84px;
+ max-width: calc(100% - 16px);
+ white-space: normal;
+ text-align: center;
+ }
+
+ .notice {
+ flex-direction: column;
+ align-items: stretch;
+ bottom: 120px;
+ }
+}
diff --git a/src/info/Blocks.tsx b/src/info/Blocks.tsx
new file mode 100644
index 0000000..cd1853f
--- /dev/null
+++ b/src/info/Blocks.tsx
@@ -0,0 +1,202 @@
+import { t } from '../i18n'
+import { Badge, type BadgeTone, Table, Td, Th } from '../ui'
+import { Cell, Md, Rich } from './format'
+import { fmtDate } from './util'
+import { ParcelMap } from './ParcelMap'
+import type { Block } from './types'
+
+const STATUS_TONE: Record<string, BadgeTone> = {
+ решено: 'ok',
+ есть: 'ok',
+ готово: 'ok',
+ рассматривается: 'accent',
+ 'в работе': 'accent',
+ нужно: 'danger',
+ позже: 'neutral',
+ отменено: 'neutral',
+ decided: 'ok',
+ done: 'ok',
+ ready: 'ok',
+ have: 'ok',
+ available: 'ok',
+ 'in place': 'ok',
+ considering: 'accent',
+ 'under review': 'accent',
+ 'in progress': 'accent',
+ needed: 'danger',
+ required: 'danger',
+ todo: 'danger',
+ later: 'neutral',
+ cancelled: 'neutral',
+ canceled: 'neutral',
+}
+
+function Status({ value }: { value?: string }) {
+ if (!value) return null
+ return <Badge tone={STATUS_TONE[value.toLowerCase()] ?? 'accent'}>{value}</Badge>
+}
+
+function Unverified({ on }: { on?: boolean }) {
+ return on ? (
+ <Badge tone="warn" className="info-unverified">
+ {t('info:unverified')}
+ </Badge>
+ ) : null
+}
+
+function Source({ value }: { value?: string }) {
+ return value ? <div className="info-source">{t('info:source')} <Rich text={value} /></div> : null
+}
+
+export function BlockView({ block }: { block: Block }) {
+ const title =
+ block.title && block.type !== 'group' && block.type !== 'map' ? (
+ <h3 className="info-block__title">
+ {block.title}
+ <Unverified on={block.unverified} />
+ </h3>
+ ) : null
+ switch (block.type) {
+ case 'facts':
+ return (
+ <div className="info-block">
+ {title}
+ <dl className="info-facts">
+ {block.items.map((f) => (
+ <div key={f.label} className="info-fact">
+ <dt>{f.label}</dt>
+ <dd>
+ <Rich text={/^\d{4}-\d{2}-\d{2}$/.test(f.value) ? fmtDate(f.value) : f.value} />
+ <Unverified on={f.unverified ?? block.unverified} />
+ {f.hint && (
+ <span className="info-fact__hint">
+ <Rich text={f.hint} />
+ </span>
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <Source value={block.source} />
+ </div>
+ )
+ case 'text':
+ return (
+ <div className="info-block info-text">
+ {title}
+ {block.paragraphs.map((p, i) => (
+ <p key={i}>
+ <Rich text={p} />
+ {block.unverified && /\d/.test(p) && <Unverified on />}
+ </p>
+ ))}
+ </div>
+ )
+ case 'markdown':
+ return (
+ <div className="info-block">
+ {title}
+ <Md text={block.text} />
+ </div>
+ )
+ case 'heading':
+ return <h3 className="info-block__title info-block__title--sub">{block.text}</h3>
+ case 'table':
+ return (
+ <div className="info-block">
+ {title}
+ <div className="info-frame">
+ <Table>
+ <thead>
+ <tr>
+ {block.columns.map((c, i) => (
+ <Th key={i}>
+ <Rich text={c} />
+ </Th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {block.rows.map((r, i) => (
+ <tr key={i}>
+ {r.map((c, j) => (
+ <Td key={j}>
+ <Cell value={c} />
+ {block.unverified && j > 0 && /\d/.test(c) && <Unverified on />}
+ </Td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ </div>
+ <Source value={block.source} />
+ </div>
+ )
+ case 'links':
+ return (
+ <div className="info-block">
+ {title}
+ <ul className="info-links">
+ {block.items.map((l) => (
+ <li key={l.url + l.title}>
+ <a href={l.url} target="_blank" rel="noreferrer">
+ {l.title}
+ </a>
+ {l.note && <span className="info-links__note">{l.note}</span>}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+ case 'list':
+ return (
+ <div className="info-block">
+ {title}
+ <ul className="info-list">
+ {block.items.map((d, i) => (
+ <li key={i} className="info-list__item">
+ <div className="info-list__main">
+ <strong>{d.url ? <a href={d.url} target="_blank" rel="noreferrer">{d.title}</a> : d.title}</strong>
+ {d.date && <span className="info-list__date">{t('info:dated', { date: fmtDate(d.date) })}</span>}
+ {d.note && (
+ <span className="info-list__note">
+ <Rich text={d.note} />
+ </span>
+ )}
+ </div>
+ <Status value={d.status} />
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+ case 'note':
+ return (
+ <div className={`info-note info-note--${block.tone ?? 'info'}`}>
+ <Rich text={block.text} />
+ </div>
+ )
+ case 'group':
+ return (
+ <details className="info-group" open={block.open}>
+ <summary>{block.title ?? t('info:more')}</summary>
+ <div className="info-group__body">
+ {block.blocks.map((b, i) => (
+ <BlockView key={i} block={b} />
+ ))}
+ </div>
+ <Source value={block.source} />
+ </details>
+ )
+ case 'map':
+ return (
+ <div className="info-block">
+ {block.title && <h3 className="info-block__title">{block.title}</h3>}
+ <ParcelMap block={block} />
+ </div>
+ )
+ default:
+ return null
+ }
+}
diff --git a/src/info/InfoPage.tsx b/src/info/InfoPage.tsx
new file mode 100644
index 0000000..e7ace89
--- /dev/null
+++ b/src/info/InfoPage.tsx
@@ -0,0 +1,83 @@
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Badge, Button, Card } from '../ui'
+import { BlockView } from './Blocks'
+import { fmtDate } from './util'
+import type { Block, HouseData } from './types'
+import './info.css'
+
+const DATA_URL = `${import.meta.env.BASE_URL}data/house.json`
+
+const pairs = (blocks: Block[]) =>
+ blocks.map((b, i) => {
+ const next = blocks[i + 1]
+ const prev = blocks[i - 1]
+ return (b.type === 'facts' && next?.type === 'map') || (b.type === 'map' && prev?.type === 'facts')
+ })
+
+export default function InfoPage() {
+ const { t } = useTranslation('info')
+ const [data, setData] = useState<HouseData | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const refs = useRef<Record<string, HTMLElement | null>>({})
+
+ useEffect(() => {
+ let alive = true
+ fetch(DATA_URL, { cache: 'no-cache' })
+ .then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`)
+ return r.json() as Promise<HouseData>
+ })
+ .then((d) => alive && setData(d))
+ .catch((e: unknown) => alive && setError(t('loadError', { error: e instanceof Error ? e.message : String(e) })))
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ if (error) return <div className="info"><div className="info-note info-note--warn">{error}</div></div>
+ if (!data) return <div className="info"><div className="info-loading">{t('loading')}</div></div>
+
+ return (
+ <div className="info">
+ <header className="info-hero">
+ <div>
+ <h1 className="info-hero__title">{data.title}</h1>
+ {data.subtitle && <div className="info-hero__sub">{data.subtitle}</div>}
+ </div>
+ {data.updated && <div className="info-hero__updated">{t('updated', { date: fmtDate(data.updated) })}</div>}
+ </header>
+
+ <nav className="info-nav" aria-label={t('sectionsNav')}>
+ {data.sections.map((s) => (
+ <Button key={s.id} size="sm" onClick={() => refs.current[s.id]?.scrollIntoView({ behavior: 'smooth', block: 'start' })}>
+ {s.title}
+ {s.status === 'collecting' && <span className="info-nav__dot" title={t('collecting')} />}
+ </Button>
+ ))}
+ </nav>
+
+ {data.sections.map((s) => {
+ const half = pairs(s.blocks)
+ return (
+ <section key={s.id} className="info-anchor" ref={(el) => void (refs.current[s.id] = el)}>
+ <Card className="info-section">
+ <div className="info-section__head">
+ <h2 className="info-section__title">{s.title}</h2>
+ {s.status === 'collecting' && <Badge tone="accent">{t('collecting')}</Badge>}
+ </div>
+ {s.lead && <p className="info-section__lead">{s.lead}</p>}
+ <div className="info-section__body">
+ {s.blocks.map((b, i) => (
+ <div key={b.auto ?? i} className={half[i] ? 'info-cell info-cell--half' : 'info-cell'}>
+ <BlockView block={b} />
+ </div>
+ ))}
+ </div>
+ </Card>
+ </section>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/src/info/ParcelMap.tsx b/src/info/ParcelMap.tsx
new file mode 100644
index 0000000..2c859d5
--- /dev/null
+++ b/src/info/ParcelMap.tsx
@@ -0,0 +1,125 @@
+import { useTranslation } from 'react-i18next'
+import { fmtNum } from '../i18n'
+import type { MapBlock, Pt } from './types'
+
+const MARGIN = 16
+const path = (pts: Pt[]) => `M${pts.map((p) => p.join(' ')).join('L')}Z`
+const center = (pts: Pt[]): Pt => [pts.reduce((a, p) => a + p[0], 0) / pts.length, pts.reduce((a, p) => a + p[1], 0) / pts.length]
+const num = (v: number) => fmtNum(v, 2, 2)
+
+export function ParcelMap({ block }: { block: MapBlock }) {
+ const { t } = useTranslation('info')
+ const own = block.parcel.points
+ const xs = own.map((p) => p[0])
+ const ys = own.map((p) => p[1])
+ const x0 = Math.min(...xs) - MARGIN
+ const y0 = Math.min(...ys) - MARGIN
+ const w = Math.max(...xs) - Math.min(...xs) + MARGIN * 2
+ const h = Math.max(...ys) - Math.min(...ys) + MARGIN * 2
+ const c = center(own)
+
+ return (
+ <figure className="info-map">
+ <svg className="info-map__svg" viewBox={`${x0} ${y0} ${w} ${h}`} role="img" aria-label={block.title ?? t('map.title')}>
+ <defs>
+ <pattern id="info-hatch" width="1.2" height="1.2" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
+ <line x1="0" y1="0" x2="0" y2="1.2" className="info-map__hatch" />
+ </pattern>
+ </defs>
+ <rect x={x0} y={y0} width={w} height={h} className="info-map__ground" />
+ {block.neighbors?.map((n) => (
+ <g key={n.label}>
+ <path d={path(n.points)} className="info-map__neighbor" />
+ {(() => {
+ const at = labelAt(n.points, own, x0, y0, w, h)
+ return (
+ <text x={at[0]} y={at[1]} className="info-map__nlabel">
+ {n.label}
+ {n.note && (
+ <tspan x={at[0]} dy="2.2" className="info-map__nnote">
+ {n.note}
+ </tspan>
+ )}
+ </text>
+ )
+ })()}
+ </g>
+ ))}
+ {block.street?.band && <path d={path(block.street.band)} className="info-map__street" />}
+ {block.street && (
+ <text
+ x={block.street.at[0]}
+ y={block.street.at[1]}
+ transform={`rotate(${block.street.angle ?? 0} ${block.street.at[0]} ${block.street.at[1]})`}
+ className="info-map__slabel"
+ >
+ {block.street.label}
+ </text>
+ )}
+ {block.strip && (
+ <text
+ x={block.strip.at[0]}
+ y={block.strip.at[1]}
+ transform={`rotate(${block.strip.angle ?? 0} ${block.strip.at[0]} ${block.strip.at[1]})`}
+ className="info-map__road"
+ >
+ {block.strip.label}
+ </text>
+ )}
+ <path d={path(own)} className="info-map__parcel" />
+ {block.zone && <path d={path(block.zone.points)} className="info-map__zone" />}
+ {block.zone?.label && (
+ <text x={center(block.zone.points)[0]} y={center(block.zone.points)[1] + 2.2} className="info-map__zlabel">
+ {block.zone.label}
+ </text>
+ )}
+ <text x={c[0]} y={c[1] - 1} className="info-map__plabel">
+ {block.parcel.label}
+ {block.parcel.note && <tspan className="info-map__pnote"> {block.parcel.note}</tspan>}
+ </text>
+ {block.sides?.map((s, i) => (
+ <SideLabel key={i} at={s.at} c={c} angle={s.angle ?? 0} text={`${num(s.len)} ${t('common:units.m')}`} />
+ ))}
+ {block.north != null && (
+ <g transform={`translate(${x0 + w - 4.5} ${y0 + 5}) rotate(${block.north})`} className="info-map__north">
+ <circle r="3.4" />
+ <path d="M0 -2.6L1.3 1.4L0 0.6L-1.3 1.4Z" />
+ <text y="-4.2" transform={`rotate(${-block.north} 0 -4.2)`}>
+ {t('map.north')}
+ </text>
+ </g>
+ )}
+ </svg>
+ <figcaption className="info-map__legend">
+ <span className="info-map__key info-map__key--parcel">{t('map.parcel')}</span>
+ {block.zone && <span className="info-map__key info-map__key--zone">{t('map.zone')}</span>}
+ {block.neighbors?.length ? <span className="info-map__key info-map__key--neighbor">{t('map.neighbors')}</span> : null}
+ {block.street && <span className="info-map__key info-map__key--street">{t('map.street')}</span>}
+ {block.caption && <span className="info-map__caption">{block.caption}</span>}
+ </figcaption>
+ </figure>
+ )
+}
+
+function SideLabel({ at, c, angle, text }: { at: Pt; c: Pt; angle: number; text: string }) {
+ const dx = at[0] - c[0]
+ const dy = at[1] - c[1]
+ const len = Math.hypot(dx, dy) || 1
+ const x = at[0] + (dx / len) * 1.6
+ const y = at[1] + (dy / len) * 1.6
+ return (
+ <text x={x} y={y} dy="0.5" transform={`rotate(${angle} ${x} ${y})`} className="info-map__side">
+ {text}
+ </text>
+ )
+}
+
+function labelAt(pts: Pt[], own: Pt[], x0: number, y0: number, w: number, h: number): Pt {
+ const inside = pts.map(([x, y]): Pt => [Math.min(Math.max(x, x0 + 1), x0 + w - 1), Math.min(Math.max(y, y0 + 1), y0 + h - 1)])
+ const nc = center(inside)
+ const oc = center(own)
+ const dx = nc[0] - oc[0]
+ const dy = nc[1] - oc[1]
+ const len = Math.hypot(dx, dy) || 1
+ return [nc[0] + (dx / len) * 2.5, nc[1] + (dy / len) * 2.5 - 0.4]
+}
diff --git a/src/info/README.md b/src/info/README.md
new file mode 100644
index 0000000..0a08d83
--- /dev/null
+++ b/src/info/README.md
@@ -0,0 +1,35 @@
+# Раздел «Участок и дом»
+
+Страница `#/info` строится целиком из `public/data/house.json`. Компонент `InfoPage.tsx` загружает файл при открытии и рисует секции по порядку; пересборка сайта нужна только при правке кода, для правки данных достаточно залить новый JSON.
+
+## Формат house.json
+
+```json
+{
+ "title": "Участок и дом",
+ "subtitle": "…",
+ "updated": "2026-09-30",
+ "sections": [
+ { "id": "docs", "title": "Документы", "lead": "…", "status": "ready|collecting", "blocks": [ … ] }
+ ]
+}
+```
+
+Блоки (`type`), у любого можно указать `title` и `source`:
+
+- `facts` — `items: [{ label, value, hint? }]`, таблица «параметр — значение».
+- `text` — `paragraphs: ["…"]`. Внутри строк понимаются `**жирный**`, `[текст](https://…)`, голые ссылки и `` `код` ``.
+- `table` — `columns: [..]`, `rows: [[..], ..]`; ячейка-ссылка показывается доменом, дата `YYYY-MM-DD` — как `ДД.ММ.ГГГГ`.
+- `links` — `items: [{ title, url, note? }]`.
+- `list` — `items: [{ title, status?, note?, date?, url? }]`, используется для документов.
+- `note` — `text`, `tone: info|pending|warn`.
+- `group` — сворачиваемый блок, `blocks: [...]`.
+- `map` — схема участка в метрах: `parcel.points`, необязательные `sides`, `neighbors`, `zone`, `street`, `strip`, `north` — угол на север.
+
+Статусы с цветом: `решено`, `есть`, `готово` — зелёный; `рассматривается`, `в работе` — оранжевый; `нужно` — красный; `позже`, `отменено` — серый.
+
+## Правка данных
+
+`house.json` правится вручную и заливается на хостинг вместе со сборкой; пересборка нужна только при правке кода. Поле `auto` у блока и пометка `status: "collecting"` у секции поддерживаются отображением, но заполнять их не обязательно. В репозитории лежит демо-файл с вымышленным участком — замените его своими данными.
+
+Страница публичная: не кладите сюда ФИО, реквизиты и сканы документов.
diff --git a/src/info/format.tsx b/src/info/format.tsx
new file mode 100644
index 0000000..878cbab
--- /dev/null
+++ b/src/info/format.tsx
@@ -0,0 +1,61 @@
+import type { ComponentProps } from 'react'
+import Markdown, { type Components } from 'react-markdown'
+import remarkGfm from 'remark-gfm'
+import { Table } from '../ui'
+import { fmtDate, isUrl } from './util'
+
+const plugins = [remarkGfm]
+
+const ExtLink = ({ node: _node, ...props }: ComponentProps<'a'> & { node?: unknown }) => <a {...props} target="_blank" rel="noreferrer" />
+
+const blockComponents: Components = {
+ a: ExtLink,
+ table: ({ node: _node, ...props }) => (
+ <div className="info-frame">
+ <Table {...props} />
+ </div>
+ ),
+ h1: ({ node: _node, ...props }) => <h3 className="info-block__title info-block__title--sub" {...props} />,
+ h2: ({ node: _node, ...props }) => <h3 className="info-block__title info-block__title--sub" {...props} />,
+ h3: ({ node: _node, ...props }) => <h4 className="info-md__h4" {...props} />,
+}
+
+const inlineComponents: Components = {
+ a: ExtLink,
+ p: ({ children }) => <>{children}</>,
+}
+
+export function Md({ text }: { text: string }) {
+ return (
+ <div className="info-md">
+ <Markdown remarkPlugins={plugins} components={blockComponents}>
+ {text}
+ </Markdown>
+ </div>
+ )
+}
+
+export function Rich({ text }: { text: string }) {
+ return (
+ <Markdown remarkPlugins={plugins} components={inlineComponents}>
+ {text}
+ </Markdown>
+ )
+}
+
+export function Cell({ value }: { value: string }) {
+ if (isUrl(value)) {
+ let host = value
+ try {
+ host = new URL(value).hostname.replace(/^www\./, '')
+ } catch {
+ host = value
+ }
+ return (
+ <a href={value} target="_blank" rel="noreferrer">
+ {host}
+ </a>
+ )
+ }
+ return <Rich text={/^\d{4}-\d{2}-\d{2}$/.test(value) ? fmtDate(value) : value} />
+}
diff --git a/src/info/info.css b/src/info/info.css
new file mode 100644
index 0000000..5634ca0
--- /dev/null
+++ b/src/info/info.css
@@ -0,0 +1,556 @@
+.info {
+ max-width: 1120px;
+ margin: 0 auto;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+ color: var(--ink);
+}
+
+.info-loading {
+ padding: 48px 0;
+ text-align: center;
+ color: var(--muted);
+}
+
+.info-hero {
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: var(--space-4);
+ flex-wrap: wrap;
+ padding: var(--space-2) var(--space-1) 0;
+}
+
+.info-hero__title {
+ margin: 0;
+ font-size: var(--text-xl);
+ line-height: 1.15;
+ font-weight: 700;
+}
+
+.info-hero__sub {
+ margin-top: var(--space-1);
+ color: var(--muted);
+}
+
+.info-hero__updated {
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.info-nav {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+
+.info-nav__dot {
+ width: 6px;
+ height: 6px;
+ border-radius: var(--radius-pill);
+ background: var(--accent);
+}
+
+.info-anchor {
+ scroll-margin-top: calc(var(--chrome-top) + var(--space-2));
+}
+
+.info-section.card--padded {
+ padding: var(--space-5);
+}
+
+.info-section__head {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+}
+
+.info-section__title {
+ margin: 0;
+ padding-left: var(--space-3);
+ border-left: 4px solid var(--accent);
+ font-size: var(--text-lg);
+ font-weight: 700;
+ line-height: 1.2;
+}
+
+.info-section__lead {
+ margin: var(--space-2) 0 0;
+ color: var(--muted);
+}
+
+.info-section__body {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: var(--space-5);
+ margin-top: var(--space-4);
+}
+
+.info-cell {
+ grid-column: 1 / -1;
+ min-width: 0;
+}
+
+.info-cell--half {
+ grid-column: auto;
+}
+
+.info-block__title {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin: 0 0 var(--space-3);
+ color: var(--muted);
+ font-size: var(--text-xs);
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+.info-block__title--sub {
+ margin: var(--space-2) 0 0;
+ color: var(--ink);
+ font-size: var(--text-md);
+ letter-spacing: 0;
+ text-transform: none;
+}
+
+.info-source {
+ margin-top: var(--space-2);
+ color: var(--muted);
+ font-size: var(--text-sm);
+ word-break: break-word;
+}
+
+.info-frame {
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.info-frame .table tbody tr:last-child td {
+ border-bottom: 0;
+}
+
+.info-frame .table td {
+ vertical-align: top;
+}
+
+.info-facts {
+ margin: 0;
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.info-fact {
+ display: grid;
+ grid-template-columns: minmax(140px, 38%) 1fr;
+ gap: var(--space-3);
+ padding: 10px 14px;
+}
+
+.info-fact + .info-fact {
+ border-top: 1px solid var(--line);
+}
+
+.info-fact dt {
+ color: var(--muted);
+}
+
+.info-fact dd {
+ margin: 0;
+ font-weight: 600;
+}
+
+.info-fact__hint {
+ display: block;
+ margin-top: 2px;
+ color: var(--muted);
+ font-size: var(--text-sm);
+ font-weight: 400;
+}
+
+.info-unverified {
+ margin-left: var(--space-2);
+ vertical-align: 1px;
+ letter-spacing: 0;
+ text-transform: none;
+}
+
+.info-text p {
+ max-width: 78ch;
+ margin: 0 0 10px;
+ line-height: 1.55;
+}
+
+.info-text p:last-child {
+ margin-bottom: 0;
+}
+
+.info code {
+ padding: 1px 5px;
+ border-radius: var(--radius-xs);
+ background: var(--surface-3);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+}
+
+.info-md {
+ line-height: 1.55;
+}
+
+.info-md p,
+.info-md ul,
+.info-md ol {
+ max-width: 78ch;
+ margin: 0 0 10px;
+}
+
+.info-md ul,
+.info-md ol {
+ padding-left: 20px;
+}
+
+.info-md li + li {
+ margin-top: var(--space-1);
+}
+
+.info-md .info-frame {
+ margin: var(--space-1) 0 var(--space-3);
+}
+
+.info-md pre {
+ overflow-x: auto;
+ padding: var(--space-3);
+ border-radius: var(--radius-sm);
+ background: var(--surface-3);
+}
+
+.info-md pre code {
+ padding: 0;
+ background: none;
+}
+
+.info-md__h4 {
+ margin: var(--space-3) 0 var(--space-2);
+ font-size: var(--text-md);
+}
+
+.info-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.info-links li {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 10px 14px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ background: var(--surface-2);
+}
+
+.info-links a {
+ font-weight: 600;
+}
+
+.info-links__note {
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.info-list {
+ display: grid;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.info-list__item {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: var(--space-3);
+ padding: var(--space-3) 14px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+}
+
+.info-list__main {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.info-list__date {
+ font-size: var(--text-sm);
+}
+
+.info-list__note {
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.info-note {
+ padding: var(--space-3) 14px;
+ border-radius: var(--radius);
+ line-height: 1.5;
+}
+
+.info-note--info {
+ background: var(--surface-3);
+}
+
+.info-note--pending {
+ border: 1px dashed var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent-ink);
+}
+
+.info-note--warn {
+ background: var(--danger-soft);
+ color: var(--danger);
+}
+
+.info-group {
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ background: var(--surface-2);
+}
+
+.info-group > summary {
+ padding: var(--space-3) 14px;
+ cursor: pointer;
+ font-weight: 600;
+ list-style: none;
+}
+
+.info-group > summary::-webkit-details-marker {
+ display: none;
+}
+
+.info-group > summary::before {
+ content: '▸';
+ display: inline-block;
+ width: var(--space-4);
+ color: var(--accent);
+ transition: transform 0.15s;
+}
+
+.info-group[open] > summary::before {
+ transform: rotate(90deg);
+}
+
+.info-group__body {
+ display: grid;
+ gap: var(--space-4);
+ padding: var(--space-1) 14px 14px;
+}
+
+.info-group__body .info-frame {
+ background: var(--surface);
+}
+
+.info-group > .info-source {
+ margin: 0;
+ padding: 0 14px var(--space-3);
+}
+
+.info-map {
+ margin: 0;
+}
+
+.info-map__svg {
+ display: block;
+ width: 100%;
+ height: auto;
+ max-height: 460px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ background: var(--surface-2);
+}
+
+.info-map__ground {
+ fill: var(--surface-2);
+}
+
+.info-map__hatch {
+ stroke: var(--line-strong);
+ stroke-width: 0.25;
+}
+
+.info-map__neighbor {
+ fill: url(#info-hatch);
+ stroke: var(--line-strong);
+ stroke-width: 0.25;
+}
+
+.info-map__street {
+ fill: var(--warn-soft);
+ stroke: var(--line-strong);
+ stroke-width: 0.2;
+}
+
+.info-map__parcel {
+ fill: var(--surface);
+ stroke: var(--accent);
+ stroke-width: 0.45;
+ stroke-linejoin: round;
+}
+
+.info-map__zone {
+ fill: var(--accent-soft);
+ stroke: var(--accent);
+ stroke-width: 0.2;
+ stroke-dasharray: 0.9 0.6;
+}
+
+.info-map__plabel {
+ fill: var(--ink);
+ font-size: 2.6px;
+ font-weight: 700;
+ text-anchor: middle;
+}
+
+.info-map__pnote,
+.info-map__nnote {
+ fill: var(--muted);
+ font-weight: 400;
+}
+
+.info-map__zlabel {
+ fill: var(--accent-ink);
+ font-size: 1.5px;
+ text-anchor: middle;
+}
+
+.info-map__nlabel {
+ fill: var(--ink-2);
+ font-size: 1.9px;
+ font-weight: 600;
+ text-anchor: middle;
+ paint-order: stroke;
+ stroke: var(--surface-2);
+ stroke-width: 0.6px;
+}
+
+.info-map__road {
+ fill: var(--muted);
+ font-size: 1.6px;
+ font-style: italic;
+ text-anchor: middle;
+}
+
+.info-map__slabel {
+ fill: var(--ink-2);
+ font-size: 1.6px;
+ font-weight: 600;
+ text-anchor: middle;
+}
+
+.info-map__side {
+ fill: var(--accent);
+ font-size: 1.5px;
+ font-weight: 600;
+ text-anchor: middle;
+ paint-order: stroke;
+ stroke: var(--surface-2);
+ stroke-width: 0.5px;
+}
+
+.info-map__north circle {
+ fill: var(--surface);
+ stroke: var(--line);
+ stroke-width: 0.2;
+}
+
+.info-map__north path {
+ fill: var(--accent);
+}
+
+.info-map__north text {
+ fill: var(--ink);
+ font-size: 1.7px;
+ font-weight: 700;
+ text-anchor: middle;
+}
+
+.info-map__legend {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px 14px;
+ margin-top: var(--space-2);
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.info-map__key {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.info-map__key::before {
+ content: '';
+ width: 14px;
+ height: 10px;
+ border-radius: 3px;
+}
+
+.info-map__key--parcel::before {
+ border: 2px solid var(--accent);
+ background: var(--surface);
+}
+
+.info-map__key--zone::before {
+ border: 1px dashed var(--accent);
+ background: var(--accent-soft);
+}
+
+.info-map__key--neighbor::before {
+ border: 1px solid var(--line-strong);
+ background: repeating-linear-gradient(45deg, var(--surface-2) 0 2px, var(--line-strong) 2px 3px);
+}
+
+.info-map__key--street::before {
+ border: 1px solid var(--line-strong);
+ background: var(--warn-soft);
+}
+
+.info-map__caption {
+ flex-basis: 100%;
+}
+
+@media (max-width: 900px) {
+ .info-section__body {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .info-cell--half {
+ grid-column: 1 / -1;
+ }
+}
+
+@media (max-width: 600px) {
+ .info-section.card--padded {
+ padding: 18px var(--space-4);
+ }
+
+ .info-fact {
+ grid-template-columns: 1fr;
+ gap: 2px;
+ }
+
+ .info-list__item {
+ flex-direction: column;
+ }
+}
diff --git a/src/info/types.ts b/src/info/types.ts
new file mode 100644
index 0000000..923dd60
--- /dev/null
+++ b/src/info/types.ts
@@ -0,0 +1,48 @@
+export type Pt = [number, number]
+
+export type Fact = { label: string; value: string; hint?: string; unverified?: boolean }
+export type Link = { title: string; url: string; note?: string }
+export type ListItem = { title: string; status?: string; note?: string; date?: string; url?: string }
+
+export type Base = { auto?: string; title?: string; source?: string; unverified?: boolean }
+
+export type Block = Base &
+ (
+ | { type: 'facts'; items: Fact[] }
+ | { type: 'text'; paragraphs: string[] }
+ | { type: 'markdown'; text: string }
+ | { type: 'heading'; text: string }
+ | { type: 'table'; columns: string[]; rows: string[][] }
+ | { type: 'links'; items: Link[] }
+ | { type: 'list'; items: ListItem[] }
+ | { type: 'note'; text: string; tone?: 'pending' | 'info' | 'warn' }
+ | { type: 'group'; blocks: Block[]; open?: boolean }
+ | MapBlock
+ )
+
+export type MapBlock = Base & {
+ type: 'map'
+ caption?: string
+ north?: number
+ parcel: { label: string; note?: string; points: Pt[] }
+ sides?: { at: Pt; len: number; angle?: number }[]
+ neighbors?: { label: string; note?: string; points: Pt[] }[]
+ zone?: { label?: string; points: Pt[] }
+ street?: { label: string; at: Pt; angle?: number; band?: Pt[] } | null
+ strip?: { label: string; at: Pt; angle?: number } | null
+}
+
+export type Section = {
+ id: string
+ title: string
+ lead?: string
+ status?: 'ready' | 'collecting'
+ blocks: Block[]
+}
+
+export type HouseData = {
+ title: string
+ subtitle?: string
+ updated?: string
+ sections: Section[]
+}
diff --git a/src/info/util.ts b/src/info/util.ts
new file mode 100644
index 0000000..e697d46
--- /dev/null
+++ b/src/info/util.ts
@@ -0,0 +1,11 @@
+import { fmtDateTime } from '../i18n'
+
+const ISO = /^(\d{4})-(\d{2})-(\d{2})$/
+
+export const fmtDate = (s?: string) => {
+ if (!s) return ''
+ const m = s.match(ISO)
+ return m ? fmtDateTime(new Date(+m[1], +m[2] - 1, +m[3]), { year: 'numeric', month: '2-digit', day: '2-digit' }) : s
+}
+
+export const isUrl = (s: string) => /^https?:\/\/\S+$/.test(s.trim())
diff --git a/src/main.tsx b/src/main.tsx
new file mode 100644
index 0000000..130c4e2
--- /dev/null
+++ b/src/main.tsx
@@ -0,0 +1,20 @@
+import './i18n'
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import { useTranslation } from 'react-i18next'
+import './styles/tokens.css'
+import './styles/ui.css'
+import './index.css'
+import App from './App.tsx'
+
+// Remount on language change so memoized calc texts and warnings are rebuilt in the new language.
+function Root() {
+ const { i18n } = useTranslation()
+ return <App key={i18n.resolvedLanguage} />
+}
+
+createRoot(document.getElementById('root')!).render(
+ <StrictMode>
+ <Root />
+ </StrictMode>,
+)
diff --git a/src/map/SatelliteUnderlay.tsx b/src/map/SatelliteUnderlay.tsx
new file mode 100644
index 0000000..e0d957f
--- /dev/null
+++ b/src/map/SatelliteUnderlay.tsx
@@ -0,0 +1,194 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import type Konva from 'konva'
+import { Group, Image as KonvaImage } from 'react-konva'
+import type { Plan } from '../model'
+import { imageryOf, roundGeo, type Geo, type Imagery } from './geo'
+import {
+ parentTile,
+ tileKey,
+ tileMatrix,
+ tilesForView,
+ tileUrl,
+ zoomForScale,
+ screenToPlan,
+ viewCorners,
+ type ScreenView,
+ TILE_SIZE,
+ type TileId,
+} from './tiles'
+
+export type UnderlayView = ScreenView
+
+type Props = {
+ plan: Plan
+ view: UnderlayView
+ opacity?: number
+ geo?: Geo | null
+ imagery?: Imagery | null
+}
+
+type Entry = { img: HTMLImageElement; ready: boolean; failed: boolean; waiters: Set<() => void> }
+
+const cache = new Map<string, Entry>()
+const CACHE_LIMIT = 600
+const ANCESTOR_LEVELS = 6
+const MARGIN_PX = 128
+const SEAM_PX = 0.5
+
+function loadTile(t: TileId, onReady: () => void): Entry {
+ const key = tileKey(t)
+ let e = cache.get(key)
+ if (e) {
+ cache.delete(key)
+ cache.set(key, e)
+ if (!e.ready && !e.failed) e.waiters.add(onReady)
+ return e
+ }
+ const img = new window.Image()
+ img.crossOrigin = 'anonymous'
+ const entry: Entry = { img, ready: false, failed: false, waiters: new Set([onReady]) }
+ img.onload = () => {
+ entry.ready = true
+ entry.waiters.forEach((w) => w())
+ entry.waiters.clear()
+ }
+ img.onerror = () => {
+ entry.failed = true
+ entry.waiters.clear()
+ }
+ img.src = tileUrl(t)
+ cache.set(key, entry)
+ while (cache.size > CACHE_LIMIT) {
+ const oldest = cache.keys().next().value
+ if (oldest === undefined) break
+ cache.delete(oldest)
+ }
+ e = entry
+ return e
+}
+
+const isReady = (t: TileId) => cache.get(tileKey(t))?.ready === true
+
+function paint(canvas: HTMLCanvasElement, geo: Geo, im: Imagery, orderKey: string, view: UnderlayView, dpr: number) {
+ const w = Math.max(1, Math.round(view.width * dpr))
+ const h = Math.max(1, Math.round(view.height * dpr))
+ if (canvas.width !== w) canvas.width = w
+ if (canvas.height !== h) canvas.height = h
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return
+ ctx.setTransform(1, 0, 0, 1, 0, 0)
+ ctx.clearRect(0, 0, w, h)
+ ctx.imageSmoothingEnabled = true
+ ctx.imageSmoothingQuality = 'high'
+ for (const key of orderKey ? orderKey.split('|') : []) {
+ const e = cache.get(key)
+ if (!e?.ready) continue
+ const [z, x, y] = key.split('/').map(Number)
+ const m = tileMatrix(geo, { z, x, y }, TILE_SIZE, im)
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ ctx.translate(view.x, view.y)
+ ctx.rotate(((view.rotationDeg ?? 0) * Math.PI) / 180)
+ ctx.scale(view.scale, view.scale)
+ ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5])
+ ctx.drawImage(e.img, 0, 0, TILE_SIZE + SEAM_PX, TILE_SIZE + SEAM_PX)
+ }
+}
+
+export default function SatelliteUnderlay({ plan, view, opacity = 1, geo: override, imagery }: Props) {
+ const src = override ?? plan.site.geo
+ const lat = src?.lat
+ const lng = src?.lng
+ const rot = src?.rotationDeg
+ const geo = useMemo(
+ () => (lat !== undefined && lng !== undefined ? roundGeo({ lat, lng, rotationDeg: rot ?? 0 }) : null),
+ [lat, lng, rot],
+ )
+ const imSrc = imagery ?? imageryOf(plan.site as { imagery?: Partial<Imagery> })
+ const { offsetE: ie, offsetN: iN, rotationDeg: ir } = imSrc
+ const im = useMemo<Imagery>(() => ({ offsetE: ie, offsetN: iN, rotationDeg: ir }), [ie, iN, ir])
+ const [, setTick] = useState(0)
+ const [complete, setComplete] = useState<{ geo: typeof geo; tiles: TileId[] }>({ geo: null, tiles: [] })
+
+ const { x: vx, y: vy, scale: vs, width: vw, height: vh, rotationDeg: vr = 0 } = view
+ const wanted = useMemo(() => {
+ const v = { x: vx, y: vy, scale: vs, width: vw, height: vh, rotationDeg: vr }
+ if (!geo || vs <= 0 || vw <= 0 || vh <= 0) return []
+ const area = viewCorners(v, MARGIN_PX)
+ const dpr = typeof window === 'undefined' ? 1 : Math.min(2, window.devicePixelRatio || 1)
+ return tilesForView(geo, area, zoomForScale(vs, geo.lat, dpr), undefined, im)
+ }, [geo, im, vx, vy, vs, vw, vh, vr])
+
+ useEffect(() => {
+ let alive = true
+ const bump = () => {
+ if (!alive) return
+ if (wanted.every(isReady)) setComplete({ geo, tiles: wanted })
+ else setTick((n) => n + 1)
+ }
+ for (const t of wanted) loadTile(t, bump)
+ if (wanted.length > 0 && wanted.every(isReady)) queueMicrotask(bump)
+ return () => {
+ alive = false
+ }
+ }, [wanted, geo])
+
+ const allReady = wanted.length > 0 && wanted.every(isReady)
+
+ const order = (() => {
+ if (!geo) return []
+ const seen = new Set<string>()
+ const back: TileId[] = []
+ const fallback: TileId[] = []
+ const front: TileId[] = []
+ const push = (list: TileId[], t: TileId) => {
+ const k = tileKey(t)
+ if (seen.has(k)) return
+ seen.add(k)
+ list.push(t)
+ }
+ if (!allReady && complete.geo === geo) for (const t of complete.tiles) if (isReady(t)) push(back, t)
+ for (const t of wanted) {
+ if (isReady(t)) continue
+ for (let l = 1; l <= ANCESTOR_LEVELS && t.z - l >= 0; l++) {
+ const p = parentTile(t, l)
+ if (isReady(p)) {
+ push(fallback, p)
+ break
+ }
+ }
+ }
+ for (const t of wanted) if (isReady(t)) push(front, t)
+ fallback.sort((a, b) => a.z - b.z)
+ return [...back, ...fallback, ...front]
+ })()
+
+ const [canvas] = useState(() => document.createElement('canvas'))
+ const imageRef = useRef<Konva.Image>(null)
+ const dpr = typeof window === 'undefined' ? 1 : Math.min(2, window.devicePixelRatio || 1)
+ const orderKey = order.map(tileKey).join('|')
+
+ useLayoutEffect(() => {
+ if (!geo) return
+ paint(canvas, geo, im, orderKey, view, dpr)
+ imageRef.current?.getLayer()?.batchDraw()
+ }, [canvas, geo, im, orderKey, view, dpr])
+
+ if (!geo) return null
+ const topLeft = screenToPlan(view, 0, 0)
+
+ return (
+ <Group opacity={opacity} listening={false}>
+ <KonvaImage
+ ref={imageRef}
+ image={canvas}
+ x={topLeft.x}
+ y={topLeft.y}
+ rotation={-(view.rotationDeg ?? 0)}
+ width={view.width / view.scale}
+ height={view.height / view.scale}
+ perfectDrawEnabled={false}
+ listening={false}
+ />
+ </Group>
+ )
+}
diff --git a/src/map/UnderlayAlign.tsx b/src/map/UnderlayAlign.tsx
new file mode 100644
index 0000000..d0fa6bb
--- /dev/null
+++ b/src/map/UnderlayAlign.tsx
@@ -0,0 +1,112 @@
+import type Konva from 'konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { Circle, Group, Line, Text } from 'react-konva'
+import { useTranslation } from 'react-i18next'
+import { fmtNum } from '../i18n'
+import { Button } from '../ui'
+import type { UnderlayAlign } from './useUnderlayAlign'
+import type { ScreenView } from './tiles'
+import './underlay-align.css'
+
+const HANDLE_R = 13
+const ARM_PX = 110
+const PIVOT_COLOR = '#f26b1d'
+const ROTATE_COLOR = '#2b2d33'
+
+type Props = { align: UnderlayAlign; view: ScreenView }
+
+export default function UnderlayAlignOverlay({ align, view }: Props) {
+ if (!align.geo) return null
+ const k = 1 / view.scale
+ const a = (align.handleAngle * Math.PI) / 180
+ const arm = ARM_PX * k
+ const p = align.pivot
+ const h = { x: p.x + Math.cos(a) * arm, y: p.y + Math.sin(a) * arm }
+ const counter = -(view.rotationDeg ?? 0)
+
+ const pos = (e: KonvaEventObject<DragEvent>) => ({ x: e.target.x(), y: e.target.y() })
+ const angleOf = (node: Konva.Node) => (Math.atan2(node.y() - p.y, node.x() - p.x) * 180) / Math.PI
+ const snapToArm = (node: Konva.Node) => {
+ const t = (angleOf(node) * Math.PI) / 180
+ node.position({ x: p.x + Math.cos(t) * arm, y: p.y + Math.sin(t) * arm })
+ }
+
+ const handle = (label: string, fill: string) => (
+ <Group rotation={counter}>
+ <Circle radius={HANDLE_R * k} fill={fill} stroke="#ffffff" strokeWidth={2 * k} shadowColor="#000" shadowBlur={4 * k} shadowOpacity={0.4} />
+ <Text
+ text={label}
+ fontSize={12 * k}
+ fontStyle="bold"
+ fill="#ffffff"
+ width={HANDLE_R * 2 * k}
+ height={HANDLE_R * 2 * k}
+ offsetX={HANDLE_R * k}
+ offsetY={HANDLE_R * k}
+ align="center"
+ verticalAlign="middle"
+ listening={false}
+ />
+ </Group>
+ )
+
+ return (
+ <Group>
+ <Line points={[p.x, p.y, h.x, h.y]} stroke={ROTATE_COLOR} strokeWidth={2 * k} dash={[6 * k, 4 * k]} listening={false} />
+ <Group
+ x={h.x}
+ y={h.y}
+ draggable
+ onDragStart={align.startRotate}
+ onDragMove={(e) => {
+ snapToArm(e.target)
+ align.rotate(angleOf(e.target))
+ }}
+ onDragEnd={(e) => {
+ snapToArm(e.target)
+ align.endRotate(angleOf(e.target))
+ }}
+ onMouseEnter={(e) => setCursor(e, 'grab')}
+ onMouseLeave={(e) => setCursor(e, '')}
+ >
+ {handle('X', ROTATE_COLOR)}
+ </Group>
+ <Group
+ x={p.x}
+ y={p.y}
+ draggable
+ onDragStart={align.startMove}
+ onDragMove={(e) => align.move(pos(e))}
+ onDragEnd={(e) => align.endMove(pos(e))}
+ onMouseEnter={(e) => setCursor(e, 'move')}
+ onMouseLeave={(e) => setCursor(e, '')}
+ >
+ {handle('0', PIVOT_COLOR)}
+ </Group>
+ </Group>
+ )
+}
+
+function setCursor(e: KonvaEventObject<MouseEvent>, cursor: string) {
+ const c = e.target.getStage()?.container()
+ if (c) c.style.cursor = cursor
+}
+
+export function UnderlayAlignControls({ align }: { align: UnderlayAlign }) {
+ const { t } = useTranslation('map')
+ if (!align.geo) return null
+ const im = align.imagery
+ return (
+ <div className="underlay-align">
+ <div className="underlay-align__buttons">
+ <Button size="sm" title={t('underlay.ccw1')} onClick={() => align.nudge(-1)}>↺ 1°</Button>
+ <Button size="sm" title={t('underlay.ccw01')} onClick={() => align.nudge(-0.1)}>↺ 0.1°</Button>
+ <Button size="sm" title={t('underlay.cw01')} onClick={() => align.nudge(0.1)}>↻ 0.1°</Button>
+ <Button size="sm" title={t('underlay.cw1')} onClick={() => align.nudge(1)}>↻ 1°</Button>
+ </div>
+ <div className="underlay-align__geo muted">
+ {t('panel.imagery', { e: fmtNum(im.offsetE, 2, 2), n: fmtNum(im.offsetN, 2, 2), rot: fmtNum(im.rotationDeg, 3, 3) })}
+ </div>
+ </div>
+ )
+}
diff --git a/src/map/geo.ts b/src/map/geo.ts
new file mode 100644
index 0000000..c014060
--- /dev/null
+++ b/src/map/geo.ts
@@ -0,0 +1,301 @@
+import proj4 from 'proj4'
+import { t } from '../i18n'
+import type { Feature, FeatureCollection, Polygon, Position } from 'geojson'
+import type { Opening, Plan, Point, Wall } from '../model'
+
+export type Geo = { lat: number; lng: number; rotationDeg: number }
+export type LngLat = [number, number]
+
+const converters = new Map<string, proj4.Converter>()
+
+function localProjection(lat: number, lng: number): proj4.Converter {
+ const key = `${lat.toFixed(9)},${lng.toFixed(9)}`
+ let c = converters.get(key)
+ if (!c) {
+ c = proj4('WGS84', `+proj=aeqd +lat_0=${lat} +lon_0=${lng} +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs`)
+ converters.set(key, c)
+ }
+ return c
+}
+
+const rad = (d: number) => (d * Math.PI) / 180
+
+export function normalizeDeg(d: number): number {
+ const r = ((d % 360) + 360) % 360
+ return Math.round(r * 1000) / 1000
+}
+
+export function roundGeo(g: Geo): Geo {
+ return {
+ lat: Math.round(g.lat * 1e8) / 1e8,
+ lng: Math.round(g.lng * 1e8) / 1e8,
+ rotationDeg: normalizeDeg(g.rotationDeg),
+ }
+}
+
+export function planToEN(p: Point, rotationDeg: number): [number, number] {
+ const c = Math.cos(rad(rotationDeg))
+ const s = Math.sin(rad(rotationDeg))
+ return [(p.x * c + p.y * s) / 1000, (p.x * s - p.y * c) / 1000]
+}
+
+export function enToPlan(e: number, n: number, rotationDeg: number): Point {
+ const c = Math.cos(rad(rotationDeg))
+ const s = Math.sin(rad(rotationDeg))
+ return { x: (e * c + n * s) * 1000, y: (e * s - n * c) * 1000 }
+}
+
+export function planToLngLat(p: Point, geo: Geo): LngLat {
+ const [e, n] = planToEN(p, geo.rotationDeg)
+ const [lng, lat] = localProjection(geo.lat, geo.lng).inverse([e, n])
+ return [lng, lat]
+}
+
+export function lngLatToPlan(ll: LngLat | Position, geo: Geo): Point {
+ const [e, n] = localProjection(geo.lat, geo.lng).forward([ll[0], ll[1]])
+ return enToPlan(e, n, geo.rotationDeg)
+}
+
+export function rotationFromHandle(origin: LngLat, handle: LngLat): number {
+ const [e, n] = localProjection(origin[1], origin[0]).forward([handle[0], handle[1]])
+ return normalizeDeg((Math.atan2(n, e) * 180) / Math.PI)
+}
+
+export function bearingForPlanUp(rotationDeg: number): number {
+ return normalizeDeg(-rotationDeg)
+}
+
+export function siteRing(plan: Plan): Point[] {
+ const { width, depth, boundary } = plan.site
+ return boundary && boundary.length >= 3
+ ? boundary
+ : [
+ { x: 0, y: 0 },
+ { x: width, y: 0 },
+ { x: width, y: depth },
+ { x: 0, y: depth },
+ ]
+}
+
+export function ringToFeature(points: Point[], geo: Geo, properties: Record<string, unknown> = {}): Feature<Polygon> {
+ const ring = points.map((p) => planToLngLat(p, geo))
+ return { type: 'Feature', properties, geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] } }
+}
+
+function unit(w: Wall) {
+ const dx = w.b.x - w.a.x
+ const dy = w.b.y - w.a.y
+ const len = Math.hypot(dx, dy) || 1
+ return { ux: dx / len, uy: dy / len }
+}
+
+export function wallOutline(w: Wall): Point[] {
+ const { ux, uy } = unit(w)
+ const h = w.thickness / 2
+ const nx = -uy * h
+ const ny = ux * h
+ const a = { x: w.a.x - ux * h, y: w.a.y - uy * h }
+ const b = { x: w.b.x + ux * h, y: w.b.y + uy * h }
+ return [
+ { x: a.x + nx, y: a.y + ny },
+ { x: b.x + nx, y: b.y + ny },
+ { x: b.x - nx, y: b.y - ny },
+ { x: a.x - nx, y: a.y - ny },
+ ]
+}
+
+export function openingOutline(o: Opening, w: Wall): Point[] {
+ const { ux, uy } = unit(w)
+ const h = w.thickness / 2 + 20
+ const nx = -uy * h
+ const ny = ux * h
+ const a = { x: w.a.x + ux * o.offset, y: w.a.y + uy * o.offset }
+ const b = { x: a.x + ux * o.width, y: a.y + uy * o.width }
+ return [
+ { x: a.x + nx, y: a.y + ny },
+ { x: b.x + nx, y: b.y + ny },
+ { x: b.x - nx, y: b.y - ny },
+ { x: a.x - nx, y: a.y - ny },
+ ]
+}
+
+export function boundsOf(points: Point[]) {
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const p of points) {
+ minX = Math.min(minX, p.x)
+ minY = Math.min(minY, p.y)
+ maxX = Math.max(maxX, p.x)
+ maxY = Math.max(maxY, p.y)
+ }
+ return { minX, minY, maxX, maxY }
+}
+
+export function lngLatBounds(points: LngLat[]): [number, number, number, number] {
+ const b = boundsOf(points.map(([x, y]) => ({ x, y })))
+ return [b.minX, b.minY, b.maxX, b.maxY]
+}
+
+export function outerRing(input: unknown): Position[] {
+ const gj = input as { type?: string } | null
+ let ring: Position[] | undefined
+ const fromGeometry = (g: { type?: string; coordinates?: unknown } | null | undefined) => {
+ if (g?.type === 'Polygon') return (g.coordinates as Position[][])[0]
+ if (g?.type === 'MultiPolygon') return (g.coordinates as Position[][][])[0][0]
+ return undefined
+ }
+ if (Array.isArray(input)) ring = input as Position[]
+ else if (gj?.type === 'FeatureCollection') {
+ for (const f of (input as FeatureCollection).features) {
+ ring = fromGeometry(f.geometry as { type?: string; coordinates?: unknown })
+ if (ring) break
+ }
+ } else if (gj?.type === 'Feature') ring = fromGeometry((input as Feature).geometry as { type?: string; coordinates?: unknown })
+ else ring = fromGeometry(gj as { type?: string; coordinates?: unknown })
+ if (!ring) throw new Error(t('map:geojson.noPolygon'))
+ const first = ring[0]
+ const last = ring[ring.length - 1]
+ const open = ring.length > 1 && first[0] === last[0] && first[1] === last[1] ? ring.slice(0, -1) : ring
+ if (open.length < 3) throw new Error(t('map:geojson.tooFewVertices'))
+ return open
+}
+
+function signedArea(points: { x: number; y: number }[]): number {
+ let s = 0
+ for (let i = 0; i < points.length; i++) {
+ const a = points[i]
+ const b = points[(i + 1) % points.length]
+ s += a.x * b.y - b.x * a.y
+ }
+ return s / 2
+}
+
+export function ringAreaM2(points: Point[]): number {
+ return Math.abs(signedArea(points)) / 1e6
+}
+
+export function geoJSONToBoundary(input: unknown, geo: Geo): Point[] {
+ return outerRing(input).map((ll) => {
+ const p = lngLatToPlan(ll, geo)
+ return { x: Math.round(p.x), y: Math.round(p.y) }
+ })
+}
+
+export function geoFromPolygon(input: unknown, startIndex = 0): Geo {
+ const ring = outerRing(input)
+ const n = ring.length
+ const origin0 = { lat: ring[0][1], lng: ring[0][0] }
+ const en = ring.map((ll) => localProjection(origin0.lat, origin0.lng).forward([ll[0], ll[1]]))
+ const cw = signedArea(en.map(([x, y]) => ({ x, y }))) < 0 ? ring : [...ring].reverse()
+ const i = ((startIndex % n) + n) % n
+ const o = cw[i]
+ const next = cw[(i + 1) % n]
+ const [e, nn] = localProjection(o[1], o[0]).forward([next[0], next[1]])
+ return roundGeo({ lat: o[1], lng: o[0], rotationDeg: (Math.atan2(nn, e) * 180) / Math.PI })
+}
+
+export function siteFromGeoJSON(input: unknown, startIndex = 0) {
+ const geo = geoFromPolygon(input, startIndex)
+ const raw = geoJSONToBoundary(input, geo)
+ const ordered = signedArea(raw) < 0 ? [...raw].reverse() : raw
+ const o = ordered.reduce((best, p, i) => (Math.hypot(p.x, p.y) < Math.hypot(ordered[best].x, ordered[best].y) ? i : best), 0)
+ const boundary = [...ordered.slice(o), ...ordered.slice(0, o)]
+ const b = boundsOf(boundary)
+ return { geo, boundary, width: b.maxX - b.minX, depth: b.maxY - b.minY }
+}
+
+export function rotatePlan(p: Point, deg: number): Point {
+ const c = Math.cos(rad(deg))
+ const s = Math.sin(rad(deg))
+ return { x: p.x * c - p.y * s, y: p.x * s + p.y * c }
+}
+
+export function moveImagery(geo: Geo, rotationDeg: number, pivot: Point, shift: Point = { x: 0, y: 0 }): Geo {
+ const r = rotatePlan(pivot, rotationDeg)
+ const t = { x: pivot.x - r.x + shift.x, y: pivot.y - r.y + shift.y }
+ const back = rotatePlan({ x: -t.x, y: -t.y }, -rotationDeg)
+ const [lng, lat] = planToLngLat(back, geo)
+ return roundGeo({ lat, lng, rotationDeg: geo.rotationDeg + rotationDeg })
+}
+
+export type Imagery = { offsetE: number; offsetN: number; rotationDeg: number }
+
+export const NO_IMAGERY: Imagery = { offsetE: 0, offsetN: 0, rotationDeg: 0 }
+
+export function imageryOf(site: { imagery?: Partial<Imagery> | null }): Imagery {
+ const im = site.imagery
+ return {
+ offsetE: im?.offsetE ?? 0,
+ offsetN: im?.offsetN ?? 0,
+ rotationDeg: im?.rotationDeg ?? 0,
+ }
+}
+
+export const isIdentityImagery = (im: Imagery) => im.offsetE === 0 && im.offsetN === 0 && im.rotationDeg === 0
+
+function rotEN(e: number, n: number, deg: number): [number, number] {
+ const c = Math.cos(rad(deg))
+ const s = Math.sin(rad(deg))
+ return [e * c - n * s, e * s + n * c]
+}
+
+export function imageryToTrueEN(e: number, n: number, im: Imagery): [number, number] {
+ const [re, rn] = rotEN(e, n, im.rotationDeg)
+ return [re + im.offsetE, rn + im.offsetN]
+}
+
+export function trueToImageryEN(e: number, n: number, im: Imagery): [number, number] {
+ return rotEN(e - im.offsetE, n - im.offsetN, -im.rotationDeg)
+}
+
+export function imageryLngLatToPlan(ll: LngLat | Position, geo: Geo, im: Imagery): Point {
+ const proj = localProjection(geo.lat, geo.lng)
+ const [e, n] = proj.forward([ll[0], ll[1]])
+ const [te, tn] = imageryToTrueEN(e, n, im)
+ return enToPlan(te, tn, geo.rotationDeg)
+}
+
+export function planToImageryLngLat(p: Point, geo: Geo, im: Imagery): LngLat {
+ const [e, n] = planToEN(p, geo.rotationDeg)
+ const [ie, iN] = trueToImageryEN(e, n, im)
+ const [lng, lat] = localProjection(geo.lat, geo.lng).inverse([ie, iN])
+ return [lng, lat]
+}
+
+export function trueLngLatToImagery(ll: LngLat | Position, geo: Geo, im: Imagery): LngLat {
+ if (isIdentityImagery(im)) return [ll[0], ll[1]]
+ const proj = localProjection(geo.lat, geo.lng)
+ const [e, n] = proj.forward([ll[0], ll[1]])
+ const [ie, iN] = trueToImageryEN(e, n, im)
+ const [lng, lat] = proj.inverse([ie, iN])
+ return [lng, lat]
+}
+
+export function roundImagery(im: Imagery): Imagery {
+ return {
+ offsetE: Math.round(im.offsetE * 100) / 100,
+ offsetN: Math.round(im.offsetN * 100) / 100,
+ rotationDeg: Math.round(im.rotationDeg * 1000) / 1000,
+ }
+}
+
+export function moveImageryInPlan(im: Imagery, geo: Geo, rotationDeg: number, pivot: Point, shift: Point = { x: 0, y: 0 }): Imagery {
+ const [pe, pn] = planToEN(pivot, geo.rotationDeg)
+ const [de, dn] = planToEN(shift, geo.rotationDeg)
+ const phi = -rotationDeg
+ const [oe, on] = rotEN(im.offsetE - pe, im.offsetN - pn, phi)
+ return roundImagery({ offsetE: oe + pe + de, offsetN: on + pn + dn, rotationDeg: im.rotationDeg + phi })
+}
+
+export function imageryFromDisplayedOrigin(geo: Geo, im: Imagery, originEN: [number, number], displayedAxisDeg?: number): Imagery {
+ const r = displayedAxisDeg === undefined ? im.rotationDeg : geo.rotationDeg - displayedAxisDeg
+ const [qe, qn] = rotEN(originEN[0], originEN[1], r)
+ return roundImagery({ offsetE: -qe, offsetN: -qn, rotationDeg: r })
+}
+
+export function enOf(ll: LngLat | Position, geo: Geo): [number, number] {
+ const [e, n] = localProjection(geo.lat, geo.lng).forward([ll[0], ll[1]])
+ return [e, n]
+}
diff --git a/src/map/index.tsx b/src/map/index.tsx
new file mode 100644
index 0000000..2b644aa
--- /dev/null
+++ b/src/map/index.tsx
@@ -0,0 +1,636 @@
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import * as maplibregl from 'maplibre-gl'
+import type { GeoJSONSource, ImageSource, StyleSpecification } from 'maplibre-gl'
+import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url'
+import 'maplibre-gl/dist/maplibre-gl.css'
+import type { Feature, FeatureCollection, Geometry, Polygon, Position } from 'geojson'
+import type { Plan, Point } from '../model'
+import {
+ bearingForPlanUp,
+ boundsOf,
+ enOf,
+ geoJSONToBoundary,
+ imageryFromDisplayedOrigin,
+ imageryOf,
+ isIdentityImagery,
+ lngLatBounds,
+ openingOutline,
+ planToImageryLngLat,
+ ringAreaM2,
+ roundGeo,
+ roundImagery,
+ siteFromGeoJSON,
+ siteRing,
+ trueLngLatToImagery,
+ trueToImageryEN,
+ wallOutline,
+ type Geo,
+ type Imagery,
+ type LngLat,
+} from './geo'
+import { useTranslation } from 'react-i18next'
+import { fmtNum, t as tr } from '../i18n'
+import { useViewOnly } from '../store/viewOnly'
+import { Button, Checkbox, Input, Panel, Segmented, type SegmentedOption } from '../ui'
+import './map.css'
+
+type ConvertedSite = { geo: Geo; boundary: Point[]; width: number; depth: number }
+
+const orientation = (): readonly SegmentedOption<'plan' | 'north'>[] => [
+ { value: 'plan', label: tr('map:orientation.plan') },
+ { value: 'north', label: tr('map:orientation.north') },
+]
+
+maplibregl.setWorkerUrl(workerUrl)
+
+type Props = {
+ plan: Plan
+ onChange: (next: Plan) => void
+}
+
+const IMAGERY_URL = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
+const IMAGERY_MAXZOOM = 18
+const EMPTY: FeatureCollection = { type: 'FeatureCollection', features: [] }
+const WALL_COLOR = '#f26b1d'
+const SITE_COLOR = '#3fd0ff'
+const STREET_COLOR = '#ff3b6b'
+const NEIGHBOR_COLOR = '#c084fc'
+const NEIGHBOR_FALLBACK = '#e5e7eb'
+const AXIS_X = '#ff4d6d'
+const AXIS_Y = '#4dff88'
+
+const LEGEND = [
+ { key: 'site', color: SITE_COLOR, kind: 'solid' },
+ { key: 'neighbor', color: NEIGHBOR_COLOR, kind: 'dash' },
+ { key: 'street', color: STREET_COLOR, kind: 'thick' },
+ { key: 'walls', color: WALL_COLOR, kind: 'fill' },
+] as const
+const DOOR_COLOR = '#ffd84a'
+const WINDOW_COLOR = '#9be7ff'
+const MAX_CANVAS = 4096
+const MM_PER_PX = 10
+
+const style: StyleSpecification = {
+ version: 8,
+ sources: {
+ imagery: {
+ type: 'raster',
+ tiles: [IMAGERY_URL],
+ tileSize: 256,
+ maxzoom: IMAGERY_MAXZOOM,
+ get attribution() {
+ return tr('map:attribution')
+ },
+ },
+ reference: { type: 'geojson', data: EMPTY },
+ boundary: { type: 'geojson', data: EMPTY },
+ axes: { type: 'geojson', data: EMPTY },
+ },
+ layers: [
+ { id: 'imagery', type: 'raster', source: 'imagery' },
+ {
+ id: 'reference-line',
+ type: 'line',
+ source: 'reference',
+ paint: {
+ 'line-color': ['match', ['get', 'role'], 'neighbor', NEIGHBOR_COLOR, 'parcel', SITE_COLOR, NEIGHBOR_FALLBACK],
+ 'line-width': 2,
+ 'line-dasharray': [3, 2],
+ },
+ filter: ['!=', ['get', 'role'], 'street'],
+ },
+ { id: 'boundary-fill', type: 'fill', source: 'boundary', paint: { 'fill-color': SITE_COLOR, 'fill-opacity': 0.1 } },
+ { id: 'boundary-line', type: 'line', source: 'boundary', paint: { 'line-color': SITE_COLOR, 'line-width': 2.5 } },
+ {
+ id: 'street-line',
+ type: 'line',
+ source: 'reference',
+ filter: ['==', ['get', 'role'], 'street'],
+ layout: { 'line-cap': 'round' },
+ paint: { 'line-color': STREET_COLOR, 'line-width': 6, 'line-opacity': 0.9 },
+ },
+ {
+ id: 'axes-line',
+ type: 'line',
+ source: 'axes',
+ paint: { 'line-color': ['match', ['get', 'axis'], 'x', AXIS_X, AXIS_Y], 'line-width': 2 },
+ },
+ ],
+}
+
+type PlanImage = { url: string; coordinates: [LngLat, LngLat, LngLat, LngLat] } | null
+
+function planCanvas(plan: Plan) {
+ const walls = new Map(plan.walls.map((w) => [w.id, w]))
+ const wallShapes = plan.walls.map(wallOutline)
+ const openingShapes = plan.openings.flatMap((o) => {
+ const w = walls.get(o.wallId)
+ return w ? [{ type: o.type, pts: openingOutline(o, w) }] : []
+ })
+ if (wallShapes.length === 0) return null
+ const b = boundsOf([...wallShapes.flat(), ...openingShapes.flatMap((s) => s.pts)])
+ const pad = 100
+ const box = { minX: b.minX - pad, minY: b.minY - pad, maxX: b.maxX + pad, maxY: b.maxY + pad }
+ const spanX = box.maxX - box.minX
+ const spanY = box.maxY - box.minY
+ const k = Math.min(1 / MM_PER_PX, MAX_CANVAS / Math.max(spanX, spanY))
+ const canvas = document.createElement('canvas')
+ canvas.width = Math.max(1, Math.ceil(spanX * k))
+ canvas.height = Math.max(1, Math.ceil(spanY * k))
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return null
+ const path = (pts: Point[]) => {
+ ctx.beginPath()
+ pts.forEach((p, i) => {
+ const x = (p.x - box.minX) * k
+ const y = (p.y - box.minY) * k
+ if (i === 0) ctx.moveTo(x, y)
+ else ctx.lineTo(x, y)
+ })
+ ctx.closePath()
+ }
+ ctx.fillStyle = WALL_COLOR
+ for (const s of wallShapes) {
+ path(s)
+ ctx.fill()
+ }
+ for (const s of openingShapes) {
+ ctx.fillStyle = s.type === 'door' ? DOOR_COLOR : WINDOW_COLOR
+ path(s.pts)
+ ctx.fill()
+ }
+ return { url: canvas.toDataURL('image/png'), box }
+}
+
+function markerEl(className: string, text?: string) {
+ const el = document.createElement('div')
+ el.className = className
+ if (text) el.textContent = text
+ return el
+}
+
+function ringCenter(f: Feature): LngLat | null {
+ if (f.geometry?.type === 'LineString') {
+ const c = f.geometry.coordinates
+ return [(c[0][0] + c[c.length - 1][0]) / 2, (c[0][1] + c[c.length - 1][1]) / 2]
+ }
+ if (f.geometry?.type !== 'Polygon') return null
+ const ring = (f.geometry as Polygon).coordinates[0].slice(0, -1)
+ const s = ring.reduce((acc, p) => [acc[0] + p[0], acc[1] + p[1]], [0, 0])
+ return [s[0] / ring.length, s[1] / ring.length]
+}
+
+function fitPadding(container: HTMLElement | null, panel: HTMLElement | null) {
+ const pad = { top: 80, right: 60, bottom: 40, left: 60 }
+ if (!container || !panel) return pad
+ const c = container.getBoundingClientRect()
+ const r = panel.getBoundingClientRect()
+ if (r.width === 0 || r.height === 0) return pad
+ if (r.top > c.top + c.height / 2) pad.bottom = Math.min(c.height * 0.6, c.bottom - r.top + 24)
+ else pad.left = Math.min(c.width * 0.6, r.right - c.left + 24)
+ return pad
+}
+
+function mapCoords(g: Geometry, f: (p: Position) => Position): Geometry {
+ switch (g.type) {
+ case 'Point':
+ return { ...g, coordinates: f(g.coordinates) }
+ case 'LineString':
+ case 'MultiPoint':
+ return { ...g, coordinates: g.coordinates.map(f) }
+ case 'Polygon':
+ case 'MultiLineString':
+ return { ...g, coordinates: g.coordinates.map((r) => r.map(f)) }
+ case 'MultiPolygon':
+ return { ...g, coordinates: g.coordinates.map((pl) => pl.map((r) => r.map(f))) }
+ default:
+ return g
+ }
+}
+
+function displayCollection(fc: FeatureCollection, geo: Geo, im: Imagery): FeatureCollection {
+ if (isIdentityImagery(im)) return fc
+ const f = (p: Position) => trueLngLatToImagery(p, geo, im)
+ return { ...fc, features: fc.features.map((ft) => (ft.geometry ? { ...ft, geometry: mapCoords(ft.geometry, f) } : ft)) }
+}
+
+export default function MapView({ plan, onChange }: Props) {
+ const { t } = useTranslation('map')
+ const containerRef = useRef<HTMLDivElement>(null)
+ const mapRef = useRef<maplibregl.Map | null>(null)
+ const originMarker = useRef<maplibregl.Marker | null>(null)
+ const handleMarker = useRef<maplibregl.Marker | null>(null)
+ const [ready, setReady] = useState(false)
+ const [reference, setReference] = useState<FeatureCollection | null>(null)
+ const [draft, setDraft] = useState<Imagery | null>(null)
+ const viewOnly = useViewOnly()
+ const [collapsed, setCollapsed] = useState(() => typeof window !== 'undefined' && window.innerWidth < 560)
+ const panelRef = useRef<HTMLElement>(null)
+ const [opacity, setOpacity] = useState(0.85)
+ const [binding, setBinding] = useState(false)
+ const [planUp, setPlanUp] = useState(true)
+ const [copied, setCopied] = useState('')
+ const [geojsonText, setGeojsonText] = useState('')
+ const [autoGeo, setAutoGeo] = useState(true)
+ const [startIndex, setStartIndex] = useState(0)
+ const [convertError, setConvertError] = useState('')
+ const [converted, setConverted] = useState<ConvertedSite | null>(null)
+ const didFit = useRef(false)
+
+ const savedGeo = plan.site.geo ? roundGeo(plan.site.geo) : null
+ const geo = savedGeo
+ const savedIm = imageryOf(plan.site as { imagery?: Partial<Imagery> })
+ const { offsetE: iE, offsetN: iN, rotationDeg: iR } = draft ?? savedIm
+ const im = useMemo<Imagery>(() => ({ offsetE: iE, offsetN: iN, rotationDeg: iR }), [iE, iN, iR])
+ const imRef = useRef(im)
+ const geoRef = useRef(geo)
+ const planRef = useRef(plan)
+ const onChangeRef = useRef(onChange)
+ const opacityRef = useRef(opacity)
+ useLayoutEffect(() => {
+ geoRef.current = geo
+ imRef.current = im
+ planRef.current = plan
+ onChangeRef.current = onChange
+ opacityRef.current = opacity
+ })
+
+ const handleLength = Math.max(plan.site.width, plan.site.depth, 10000) * 0.6
+ const image = useMemo(() => planCanvas(plan), [plan])
+
+ const commit = useCallback((next: Imagery) => {
+ const p = planRef.current
+ setDraft(null)
+ onChangeRef.current({ ...p, site: { ...p.site, imagery: roundImagery(next) } })
+ }, [])
+
+ useEffect(() => {
+ let alive = true
+ fetch(`${import.meta.env.BASE_URL}data/parcel.geojson`)
+ .then((r) => (r.ok ? r.json() : null))
+ .then((d) => alive && d && setReference(d as FeatureCollection))
+ .catch(() => undefined)
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ useEffect(() => {
+ if (!containerRef.current) return
+ const map = new maplibregl.Map({
+ container: containerRef.current,
+ style,
+ center: [24.8577, 59.3002],
+ zoom: 17,
+ maxZoom: 22,
+ attributionControl: { compact: true },
+ })
+ map.addControl(new maplibregl.NavigationControl({ visualizePitch: false }), 'top-right')
+ map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-left')
+ map.on('load', () => setReady(true))
+ mapRef.current = map
+ return () => {
+ map.remove()
+ mapRef.current = null
+ }
+ }, [])
+
+ const fit = useCallback(
+ (animate: boolean) => {
+ const map = mapRef.current
+ if (!map) return
+ const g = geoRef.current
+ const cur = imRef.current
+ const pts: LngLat[] = g
+ ? siteRing(planRef.current).map((p) => planToImageryLngLat(p, g, cur))
+ : (reference?.features ?? []).flatMap((f) =>
+ f.geometry?.type === 'Polygon' ? (f.geometry.coordinates[0] as LngLat[]) : [],
+ )
+ if (pts.length === 0) return
+ const bearing = planUp && g ? bearingForPlanUp(g.rotationDeg - cur.rotationDeg) : 0
+ map.fitBounds(lngLatBounds(pts), { padding: fitPadding(containerRef.current, panelRef.current), maxZoom: 19.5, bearing, animate })
+ },
+ [planUp, reference],
+ )
+
+ useEffect(() => {
+ if (!ready || didFit.current) return
+ if (!geo && !reference) return
+ didFit.current = true
+ fit(false)
+ }, [ready, geo, reference, fit])
+
+ useEffect(() => {
+ const map = mapRef.current
+ if (!map || !ready) return
+ const g = geoRef.current
+ const shown = reference && g ? displayCollection(reference, g, imRef.current) : reference
+ ;(map.getSource('reference') as GeoJSONSource).setData(shown ?? EMPTY)
+ const markers = (shown?.features ?? []).flatMap((f) => {
+ const c = ringCenter(f)
+ const label = f.properties?.label as string | undefined
+ if (!c || !label) return []
+ return [new maplibregl.Marker({ element: markerEl('map-view__tag', label) }).setLngLat(c).addTo(map)]
+ })
+ return () => markers.forEach((m) => m.remove())
+ }, [reference, ready, geo, im])
+
+ useEffect(() => {
+ const map = mapRef.current
+ if (!map || !ready) return
+ const boundary = map.getSource('boundary') as GeoJSONSource
+ const axes = map.getSource('axes') as GeoJSONSource
+ if (!geo) {
+ boundary.setData(EMPTY)
+ axes.setData(EMPTY)
+ if (map.getLayer('plan-walls')) map.removeLayer('plan-walls')
+ if (map.getSource('plan-image')) map.removeSource('plan-image')
+ return
+ }
+ const at = (p: Point) => planToImageryLngLat(p, geo, im)
+ const ring = siteRing(plan).map(at)
+ boundary.setData({ type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [[...ring, ring[0]]] } })
+ const o = at({ x: 0, y: 0 })
+ axes.setData({
+ type: 'FeatureCollection',
+ features: binding && !viewOnly
+ ? [
+ { type: 'Feature', properties: { axis: 'x' }, geometry: { type: 'LineString', coordinates: [o, at({ x: handleLength, y: 0 })] } },
+ { type: 'Feature', properties: { axis: 'y' }, geometry: { type: 'LineString', coordinates: [o, at({ x: 0, y: handleLength * 0.5 })] } },
+ ]
+ : [],
+ })
+ const next: PlanImage = image
+ ? {
+ url: image.url,
+ coordinates: [
+ at({ x: image.box.minX, y: image.box.minY }),
+ at({ x: image.box.maxX, y: image.box.minY }),
+ at({ x: image.box.maxX, y: image.box.maxY }),
+ at({ x: image.box.minX, y: image.box.maxY }),
+ ],
+ }
+ : null
+ const src = map.getSource('plan-image') as ImageSource | undefined
+ if (!next) {
+ if (map.getLayer('plan-walls')) map.removeLayer('plan-walls')
+ if (src) map.removeSource('plan-image')
+ } else if (!src) {
+ map.addSource('plan-image', { type: 'image', url: next.url, coordinates: next.coordinates })
+ map.addLayer(
+ { id: 'plan-walls', type: 'raster', source: 'plan-image', paint: { 'raster-opacity': opacityRef.current, 'raster-fade-duration': 0 } },
+ 'axes-line',
+ )
+ } else if (src.url !== next.url) {
+ src.updateImage({ url: next.url, coordinates: next.coordinates })
+ } else {
+ src.setCoordinates(next.coordinates)
+ }
+ originMarker.current?.setLngLat(o)
+ handleMarker.current?.setLngLat(at({ x: handleLength, y: 0 }))
+ }, [plan, geo, im, image, ready, binding, handleLength, viewOnly])
+
+ useEffect(() => {
+ const map = mapRef.current
+ if (!map || !ready) return
+ if (map.getLayer('plan-walls')) map.setPaintProperty('plan-walls', 'raster-opacity', opacity)
+ map.setPaintProperty('boundary-line', 'line-opacity', Math.max(0.25, opacity))
+ map.setPaintProperty('boundary-fill', 'fill-opacity', 0.12 * opacity)
+ }, [opacity, ready])
+
+ useEffect(() => {
+ const map = mapRef.current
+ const g = geoRef.current
+ if (!map || !ready || !binding || !g || viewOnly) return
+ const start = imRef.current
+ const origin = new maplibregl.Marker({ element: markerEl('map-view__handle map-view__handle--origin', '0'), draggable: true })
+ .setLngLat(planToImageryLngLat({ x: 0, y: 0 }, g, start))
+ .addTo(map)
+ const handle = new maplibregl.Marker({ element: markerEl('map-view__handle map-view__handle--rotate', 'X'), draggable: true })
+ .setLngLat(planToImageryLngLat({ x: handleLength, y: 0 }, g, start))
+ .addTo(map)
+ const originEN = () => {
+ const ll = origin.getLngLat()
+ return enOf([ll.lng, ll.lat], g)
+ }
+ origin.on('drag', () => {
+ setDraft(imageryFromDisplayedOrigin(g, imRef.current, originEN()))
+ })
+ handle.on('drag', () => {
+ const q = originEN()
+ const h = handle.getLngLat()
+ const [he, hn] = enOf([h.lng, h.lat], g)
+ const axis = (Math.atan2(hn - q[1], he - q[0]) * 180) / Math.PI
+ setDraft(imageryFromDisplayedOrigin(g, imRef.current, q, axis))
+ })
+ const done = () => commit(imRef.current)
+ origin.on('dragend', done)
+ handle.on('dragend', done)
+ originMarker.current = origin
+ handleMarker.current = handle
+ return () => {
+ origin.remove()
+ handle.remove()
+ originMarker.current = null
+ handleMarker.current = null
+ }
+ }, [binding, ready, handleLength, commit, geo, viewOnly])
+
+ useEffect(() => {
+ const map = mapRef.current
+ if (!map || !ready) return
+ const g = geoRef.current
+ map.easeTo({ bearing: planUp && g ? bearingForPlanUp(g.rotationDeg - imRef.current.rotationDeg) : 0, duration: 400 })
+ }, [planUp, ready])
+
+ const nudge = (delta: number) => {
+ if (!geo) return
+ const q = trueToImageryEN(0, 0, im)
+ commit(imageryFromDisplayedOrigin(geo, im, q, geo.rotationDeg - im.rotationDeg + delta))
+ }
+
+ const imageryText = JSON.stringify({ imagery: roundImagery(im) }, null, 2)
+
+ const copy = async (text: string, what: string) => {
+ try {
+ await navigator.clipboard.writeText(text)
+ setCopied(what)
+ window.setTimeout(() => setCopied(''), 1500)
+ } catch {
+ setCopied('')
+ }
+ }
+
+ const convert = () => {
+ setConvertError('')
+ setConverted(null)
+ try {
+ const parsed: unknown = JSON.parse(geojsonText)
+ if (autoGeo) {
+ setConverted(siteFromGeoJSON(parsed, startIndex))
+ } else {
+ if (!geo) throw new Error(t('geojson.notBound'))
+ const boundary = geoJSONToBoundary(parsed, geo)
+ const b = boundsOf(boundary)
+ setConverted({ geo, boundary, width: b.maxX - b.minX, depth: b.maxY - b.minY })
+ }
+ } catch (e) {
+ setConvertError(e instanceof Error ? e.message : String(e))
+ }
+ }
+
+ const apply = () => {
+ if (!converted) return
+ const p = planRef.current
+ setDraft(null)
+ onChangeRef.current({
+ ...p,
+ site: { ...p.site, geo: converted.geo, boundary: converted.boundary, width: converted.width, depth: converted.depth },
+ })
+ didFit.current = false
+ }
+
+ return (
+ <div className="map-view">
+ <div className="map-view__map" ref={containerRef} />
+ <Panel
+ ref={panelRef}
+ className="map-view__panel"
+ eyebrow={t('panel.eyebrow')}
+ title={binding ? t('panel.titleAlign') : t('panel.titlePlan')}
+ actions={
+ <Button size="sm" variant="ghost" onClick={() => setCollapsed((c) => !c)} aria-expanded={!collapsed}>
+ {collapsed ? t('panel.expand') : t('panel.collapse')}
+ </Button>
+ }
+ >
+ {!collapsed && (
+ <div className="map-view__stack">
+ <label className="map-view__row">
+ <span className="muted">{t('panel.opacity')}</span>
+ <input
+ className="map-view__range"
+ type="range"
+ min={0}
+ max={1}
+ step={0.05}
+ value={opacity}
+ onChange={(e) => setOpacity(Number(e.target.value))}
+ />
+ <span className="num">{Math.round(opacity * 100)}%</span>
+ </label>
+ <Segmented
+ size="sm"
+ options={orientation()}
+ value={planUp ? 'plan' : 'north'}
+ onChange={(v) => setPlanUp(v === 'plan')}
+ />
+ <div className="map-view__buttons">
+ {!viewOnly && (
+ <Button
+ size="sm"
+ variant={binding ? 'primary' : 'default'}
+ pressed={binding}
+ disabled={!geo}
+ onClick={() => setBinding((b) => !b)}
+ >
+ {binding ? t('panel.done') : t('panel.align')}
+ </Button>
+ )}
+ <Button size="sm" onClick={() => fit(true)}>
+ {t('panel.toSite')}
+ </Button>
+ </div>
+ {!geo && <p className="map-view__hint muted">{t('panel.notBound')}</p>}
+ {!viewOnly && binding && geo && (
+ <>
+ <p className="map-view__hint muted">
+ {t('panel.alignHint')}
+ </p>
+ <div className="map-view__buttons">
+ <Button size="sm" onClick={() => nudge(1)}>↺ 1°</Button>
+ <Button size="sm" onClick={() => nudge(0.1)}>↺ 0.1°</Button>
+ <Button size="sm" onClick={() => nudge(-0.1)}>↻ 0.1°</Button>
+ <Button size="sm" onClick={() => nudge(-1)}>↻ 1°</Button>
+ <Button size="sm" variant="ghost" onClick={() => commit({ offsetE: 0, offsetN: 0, rotationDeg: 0 })}>
+ {t('panel.reset')}
+ </Button>
+ </div>
+ </>
+ )}
+ {geo && (
+ <div className="map-view__geo">
+ <code className="map-view__code">
+ {t('panel.imagery', { e: fmtNum(im.offsetE, 2, 2), n: fmtNum(im.offsetN, 2, 2), rot: fmtNum(im.rotationDeg, 3, 3) })}
+ </code>
+ <Button size="sm" variant="ghost" onClick={() => copy(imageryText, 'imagery')}>
+ {copied === 'imagery' ? t('panel.copied') : 'JSON'}
+ </Button>
+ </div>
+ )}
+ <section className="map-view__section">
+ <div className="eyebrow">{t('legend.title')}</div>
+ <ul className="map-view__legend">
+ {LEGEND.map((l) => (
+ <li key={l.key} className="map-view__legend-item">
+ <span className={`map-view__swatch map-view__swatch--${l.kind}`} style={{ color: l.color }} aria-hidden />
+ <span>{t(`legend.${l.key}`)}</span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ {!viewOnly && (
+ <details className="map-view__section">
+ <summary className="map-view__summary">{t('geojson.summary')}</summary>
+ <div className="map-view__stack">
+ <textarea
+ className="map-view__textarea"
+ placeholder='{"type":"Polygon","coordinates":[[[lng,lat],…]]}'
+ value={geojsonText}
+ onChange={(e) => setGeojsonText(e.target.value)}
+ />
+ <Checkbox label={t('geojson.autoGeo')} checked={autoGeo} onChange={setAutoGeo} />
+ {autoGeo && (
+ <Input
+ size="sm"
+ label={t('geojson.startVertex')}
+ type="number"
+ min={0}
+ value={startIndex}
+ onChange={(e) => setStartIndex(Number(e.target.value))}
+ />
+ )}
+ <div className="map-view__buttons">
+ <Button size="sm" onClick={convert}>{t('geojson.convert')}</Button>
+ {converted && (
+ <Button size="sm" variant="primary" onClick={apply}>
+ {t('geojson.apply')}
+ </Button>
+ )}
+ {converted && (
+ <Button size="sm" variant="ghost" onClick={() => copy(JSON.stringify(converted, null, 2), 'site')}>
+ {copied === 'site' ? t('panel.copied') : t('panel.copy')}
+ </Button>
+ )}
+ </div>
+ {convertError && <p className="map-view__hint map-view__error">{convertError}</p>}
+ {converted && (
+ <p className="map-view__hint muted">
+ {t('geojson.result', {
+ count: converted.boundary.length,
+ w: fmtNum(converted.width / 1000, 2, 2),
+ d: fmtNum(converted.depth / 1000, 2, 2),
+ area: fmtNum(ringAreaM2(converted.boundary), 1, 1),
+ rot: fmtNum(converted.geo.rotationDeg, 3, 3),
+ })}
+ </p>
+ )}
+ </div>
+ </details>
+ )}
+ </div>
+ )}
+ </Panel>
+ </div>
+ )
+}
diff --git a/src/map/map.css b/src/map/map.css
new file mode 100644
index 0000000..9fe2df0
--- /dev/null
+++ b/src/map/map.css
@@ -0,0 +1,183 @@
+.map-view {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 320px;
+ overflow: hidden;
+ background: var(--ink);
+}
+
+.map-view__map {
+ position: absolute;
+ inset: 0;
+}
+
+.map-view .maplibregl-ctrl-top-right {
+ top: calc(var(--chrome-top) - 10px);
+}
+
+.map-view__panel {
+ position: absolute;
+ top: var(--chrome-top);
+ left: var(--chrome-left, 12px);
+ z-index: var(--z-chrome);
+ width: 300px;
+ max-width: calc(100% - 80px);
+ max-height: calc(100% - var(--chrome-top) - 40px);
+}
+
+.map-view__stack {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+}
+
+.map-view__row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ font-size: var(--text-sm);
+}
+
+.map-view__range {
+ flex: 1;
+ min-width: 0;
+ accent-color: var(--accent);
+}
+
+.map-view__buttons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+}
+
+.map-view__hint {
+ margin: 0;
+ font-size: var(--text-sm);
+}
+
+.map-view__error {
+ color: var(--danger);
+}
+
+.map-view__geo {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+}
+
+.map-view__code {
+ font: var(--text-xs) / 1.35 var(--font-mono);
+ color: var(--ink-2);
+ overflow-wrap: anywhere;
+}
+
+.map-view__section {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ padding-top: var(--space-3);
+ border-top: 1px solid var(--line);
+}
+
+.map-view__summary {
+ font-size: var(--text-sm);
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.map-view__legend {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ font-size: var(--text-sm);
+}
+
+.map-view__legend-item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.map-view__swatch {
+ flex: 0 0 22px;
+ height: 0;
+ border-top: 2px solid currentColor;
+}
+
+.map-view__swatch--dash {
+ border-top-style: dashed;
+}
+
+.map-view__swatch--thick {
+ border-top-width: 5px;
+ border-radius: var(--radius-pill);
+}
+
+.map-view__swatch--fill {
+ height: 10px;
+ border: 0;
+ border-radius: 2px;
+ background: currentColor;
+}
+
+.map-view__textarea {
+ min-height: 96px;
+ padding: var(--space-2);
+ font: var(--text-xs) / 1.4 var(--font-mono);
+ color: var(--ink);
+ background: var(--surface);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ resize: vertical;
+}
+
+.map-view__textarea:focus {
+ outline: none;
+ border-color: var(--accent);
+}
+
+.map-view__handle {
+ display: grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ font: 700 var(--text-sm) / 1 var(--font);
+ color: var(--surface);
+ background: var(--accent);
+ border: 2px solid var(--surface);
+ border-radius: var(--radius-pill);
+ box-shadow: var(--shadow-sm);
+ cursor: grab;
+}
+
+.map-view__handle--rotate {
+ background: var(--ink);
+}
+
+.map-view__tag {
+ padding: 2px var(--space-2);
+ font: 600 var(--text-xs) / 1.3 var(--font);
+ color: var(--ink);
+ background: var(--surface);
+ border-radius: var(--radius-xs);
+ box-shadow: var(--shadow-sm);
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+@media (max-width: 560px) {
+ .map-view__panel {
+ top: auto;
+ bottom: 28px;
+ left: var(--space-2);
+ right: var(--space-2);
+ width: auto;
+ max-width: none;
+ max-height: 45%;
+ }
+}
diff --git a/src/map/tiles.ts b/src/map/tiles.ts
new file mode 100644
index 0000000..5a41b07
--- /dev/null
+++ b/src/map/tiles.ts
@@ -0,0 +1,148 @@
+import { t } from '../i18n'
+import type { Point } from '../model'
+import { imageryLngLatToPlan, NO_IMAGERY, planToImageryLngLat, type Geo, type Imagery } from './geo'
+
+export type TileId = { z: number; x: number; y: number }
+export type ViewRect = { minX: number; minY: number; maxX: number; maxY: number }
+export type TilePlacement = { x: number; y: number; rotation: number; scaleX: number; scaleY: number; skewX: number }
+
+export const TILE_SIZE = 256
+export const IMAGERY_MAX_ZOOM = 18
+export const IMAGERY_URL = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
+export const imageryAttribution = () => t('map:attribution')
+
+const EARTH_CIRCUMFERENCE = 40075016.686
+const MAX_TILES = 160
+
+export const tileKey = (t: TileId) => `${t.z}/${t.x}/${t.y}`
+
+export const tileUrl = (t: TileId) =>
+ IMAGERY_URL.replace('{z}', String(t.z)).replace('{y}', String(t.y)).replace('{x}', String(t.x))
+
+export function lngLatToTile(lng: number, lat: number, z: number): { x: number; y: number } {
+ const n = 2 ** z
+ const r = (lat * Math.PI) / 180
+ return {
+ x: ((lng + 180) / 360) * n,
+ y: ((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2) * n,
+ }
+}
+
+export function tileToLngLat(x: number, y: number, z: number): [number, number] {
+ const n = 2 ** z
+ const lng = (x / n) * 360 - 180
+ const lat = (Math.atan(Math.sinh(Math.PI * (1 - (2 * y) / n))) * 180) / Math.PI
+ return [lng, lat]
+}
+
+export function metersPerTilePixel(lat: number, z: number): number {
+ return (EARTH_CIRCUMFERENCE * Math.cos((lat * Math.PI) / 180)) / (TILE_SIZE * 2 ** z)
+}
+
+export function zoomForScale(scale: number, lat: number, pixelRatio = 1): number {
+ const screenMetersPerPx = 1 / (1000 * scale * pixelRatio)
+ const z = Math.ceil(Math.log2((EARTH_CIRCUMFERENCE * Math.cos((lat * Math.PI) / 180)) / (TILE_SIZE * screenMetersPerPx)) + 0.5)
+ return Math.max(0, Math.min(IMAGERY_MAX_ZOOM, z))
+}
+
+export function rectCornersLngLat(geo: Geo, rect: ViewRect, im: Imagery = NO_IMAGERY): [number, number][] {
+ return [
+ planToImageryLngLat({ x: rect.minX, y: rect.minY }, geo, im),
+ planToImageryLngLat({ x: rect.maxX, y: rect.minY }, geo, im),
+ planToImageryLngLat({ x: rect.maxX, y: rect.maxY }, geo, im),
+ planToImageryLngLat({ x: rect.minX, y: rect.maxY }, geo, im),
+ ]
+}
+
+export type ViewArea = ViewRect | Point[]
+
+const areaCornersLngLat = (geo: Geo, area: ViewArea, im: Imagery) =>
+ Array.isArray(area) ? area.map((p) => planToImageryLngLat(p, geo, im)) : rectCornersLngLat(geo, area, im)
+
+export function tileRange(geo: Geo, area: ViewArea, z: number, im: Imagery = NO_IMAGERY) {
+ const pts = areaCornersLngLat(geo, area, im).map(([lng, lat]) => lngLatToTile(lng, lat, z))
+ const n = 2 ** z
+ const clamp = (v: number) => Math.max(0, Math.min(n - 1, v))
+ return {
+ minX: clamp(Math.floor(Math.min(...pts.map((p) => p.x)))),
+ maxX: clamp(Math.floor(Math.max(...pts.map((p) => p.x)))),
+ minY: clamp(Math.floor(Math.min(...pts.map((p) => p.y)))),
+ maxY: clamp(Math.floor(Math.max(...pts.map((p) => p.y)))),
+ }
+}
+
+export type ScreenView = { x: number; y: number; scale: number; width: number; height: number; rotationDeg?: number }
+
+export function screenToPlan(view: ScreenView, sx: number, sy: number): Point {
+ const a = ((view.rotationDeg ?? 0) * Math.PI) / 180
+ const dx = sx - view.x
+ const dy = sy - view.y
+ const c = Math.cos(a)
+ const s = Math.sin(a)
+ return { x: (dx * c + dy * s) / view.scale, y: (-dx * s + dy * c) / view.scale }
+}
+
+export function viewCorners(view: ScreenView, marginPx = 0): Point[] {
+ const m = marginPx
+ return [
+ screenToPlan(view, -m, -m),
+ screenToPlan(view, view.width + m, -m),
+ screenToPlan(view, view.width + m, view.height + m),
+ screenToPlan(view, -m, view.height + m),
+ ]
+}
+
+export function tilesForView(geo: Geo, area: ViewArea, zoom: number, maxTiles = MAX_TILES, im: Imagery = NO_IMAGERY): TileId[] {
+ let z = Math.max(0, Math.min(IMAGERY_MAX_ZOOM, Math.round(zoom)))
+ let r = tileRange(geo, area, z, im)
+ while (z > 0 && (r.maxX - r.minX + 1) * (r.maxY - r.minY + 1) > maxTiles) {
+ z -= 1
+ r = tileRange(geo, area, z, im)
+ }
+ const out: TileId[] = []
+ for (let y = r.minY; y <= r.maxY; y++) for (let x = r.minX; x <= r.maxX; x++) out.push({ z, x, y })
+ return out
+}
+
+export function parentTile(t: TileId, levels = 1): TileId {
+ const k = 2 ** levels
+ return { z: t.z - levels, x: Math.floor(t.x / k), y: Math.floor(t.y / k) }
+}
+
+export function tileCornersPlan(geo: Geo, t: TileId, im: Imagery = NO_IMAGERY): { nw: Point; ne: Point; sw: Point } {
+ return {
+ nw: imageryLngLatToPlan(tileToLngLat(t.x, t.y, t.z), geo, im),
+ ne: imageryLngLatToPlan(tileToLngLat(t.x + 1, t.y, t.z), geo, im),
+ sw: imageryLngLatToPlan(tileToLngLat(t.x, t.y + 1, t.z), geo, im),
+ }
+}
+
+export function affineFromCorners(nw: Point, ne: Point, sw: Point, size = TILE_SIZE): TilePlacement {
+ const ux = (ne.x - nw.x) / size
+ const uy = (ne.y - nw.y) / size
+ const vx = (sw.x - nw.x) / size
+ const vy = (sw.y - nw.y) / size
+ const rot = Math.atan2(uy, ux)
+ const c = Math.cos(rot)
+ const s = Math.sin(rot)
+ const rvx = c * vx + s * vy
+ const rvy = -s * vx + c * vy
+ return {
+ x: nw.x,
+ y: nw.y,
+ rotation: (rot * 180) / Math.PI,
+ scaleX: Math.hypot(ux, uy),
+ scaleY: rvy,
+ skewX: rvx / rvy,
+ }
+}
+
+export function tilePlacement(geo: Geo, t: TileId, im: Imagery = NO_IMAGERY): TilePlacement {
+ const { nw, ne, sw } = tileCornersPlan(geo, t, im)
+ return affineFromCorners(nw, ne, sw)
+}
+
+export function tileMatrix(geo: Geo, t: TileId, size = TILE_SIZE, im: Imagery = NO_IMAGERY): [number, number, number, number, number, number] {
+ const { nw, ne, sw } = tileCornersPlan(geo, t, im)
+ return [(ne.x - nw.x) / size, (ne.y - nw.y) / size, (sw.x - nw.x) / size, (sw.y - nw.y) / size, nw.x, nw.y]
+}
diff --git a/src/map/underlay-align.css b/src/map/underlay-align.css
new file mode 100644
index 0000000..d3403f6
--- /dev/null
+++ b/src/map/underlay-align.css
@@ -0,0 +1,15 @@
+.underlay-align {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.underlay-align__buttons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+}
+
+.underlay-align__geo {
+ font: var(--text-xs) / 1.3 var(--font-mono);
+}
diff --git a/src/map/useUnderlayAlign.ts b/src/map/useUnderlayAlign.ts
new file mode 100644
index 0000000..d7525f3
--- /dev/null
+++ b/src/map/useUnderlayAlign.ts
@@ -0,0 +1,132 @@
+import { useCallback, useMemo, useRef, useState } from 'react'
+import type { Plan, Point } from '../model'
+import { imageryOf, moveImagery, moveImageryInPlan, roundGeo, type Geo, type Imagery } from './geo'
+
+export type UnderlayAlign = {
+ geo: Geo | null
+ preview: Geo | null
+ shown: Geo | null
+ imagery: Imagery
+ pivot: Point
+ handleAngle: number
+ nudge: (deltaDeg: number) => void
+ startMove: () => void
+ move: (pos: Point) => void
+ endMove: (pos: Point) => void
+ startRotate: () => void
+ rotate: (angleDeg: number) => void
+ endRotate: (angleDeg: number) => void
+}
+
+type Start = { geo: Geo; imagery: Imagery; pivot: Point; angle: number }
+
+export function useUnderlayAlign(
+ plan: Plan,
+ onGeoChange: (geo: Geo) => void,
+ onImageryChange?: (imagery: Imagery) => void,
+): UnderlayAlign {
+ const src = plan.site.geo
+ const lat = src?.lat
+ const lng = src?.lng
+ const rot = src?.rotationDeg
+ const geo = useMemo(
+ () => (lat !== undefined && lng !== undefined ? roundGeo({ lat, lng, rotationDeg: rot ?? 0 }) : null),
+ [lat, lng, rot],
+ )
+ const saved = imageryOf(plan.site as { imagery?: Partial<Imagery> })
+ const { offsetE, offsetN, rotationDeg: imRot } = saved
+ const imagery = useMemo<Imagery>(() => ({ offsetE, offsetN, rotationDeg: imRot }), [offsetE, offsetN, imRot])
+ const [preview, setPreview] = useState<{ geo: Geo; imagery: Imagery } | null>(null)
+ const [pivot, setPivot] = useState<Point>({ x: 0, y: 0 })
+ const [handleAngle, setHandleAngle] = useState(0)
+ const start = useRef<Start | null>(null)
+
+ const apply = useCallback(
+ (s: Start, rotationDeg: number, shift?: Point) => {
+ if (onImageryChange) return { geo: s.geo, imagery: moveImageryInPlan(s.imagery, s.geo, rotationDeg, s.pivot, shift) }
+ return { geo: moveImagery(s.geo, rotationDeg, s.pivot, shift), imagery: s.imagery }
+ },
+ [onImageryChange],
+ )
+
+ const commit = useCallback(
+ (next: { geo: Geo; imagery: Imagery }) => {
+ if (onImageryChange) onImageryChange(next.imagery)
+ else onGeoChange(next.geo)
+ },
+ [onGeoChange, onImageryChange],
+ )
+
+ const begin = useCallback(() => {
+ if (geo) start.current = { geo, imagery, pivot, angle: handleAngle }
+ }, [geo, imagery, pivot, handleAngle])
+
+ const shiftOf = (s: Start, pos: Point) => ({ x: pos.x - s.pivot.x, y: pos.y - s.pivot.y })
+
+ const move = useCallback(
+ (pos: Point) => {
+ const s = start.current
+ if (s) setPreview(apply(s, 0, shiftOf(s, pos)))
+ },
+ [apply],
+ )
+
+ const endMove = useCallback(
+ (pos: Point) => {
+ const s = start.current
+ start.current = null
+ if (!s) return
+ setPreview(null)
+ setPivot(pos)
+ commit(apply(s, 0, shiftOf(s, pos)))
+ },
+ [apply, commit],
+ )
+
+ const rotate = useCallback(
+ (angleDeg: number) => {
+ const s = start.current
+ if (!s) return
+ setHandleAngle(angleDeg)
+ setPreview(apply(s, angleDeg - s.angle))
+ },
+ [apply],
+ )
+
+ const endRotate = useCallback(
+ (angleDeg: number) => {
+ const s = start.current
+ start.current = null
+ if (!s) return
+ setPreview(null)
+ setHandleAngle(angleDeg)
+ commit(apply(s, angleDeg - s.angle))
+ },
+ [apply, commit],
+ )
+
+ const nudge = useCallback(
+ (deltaDeg: number) => {
+ if (!geo) return
+ setHandleAngle((a) => a + deltaDeg)
+ commit(apply({ geo, imagery, pivot, angle: 0 }, deltaDeg))
+ },
+ [geo, imagery, pivot, apply, commit],
+ )
+
+ return {
+ geo,
+ preview: preview?.geo ?? null,
+ shown: preview?.geo ?? geo,
+ imagery: preview?.imagery ?? imagery,
+ pivot,
+ handleAngle,
+ nudge,
+ startMove: begin,
+ move,
+ endMove,
+ startRotate: begin,
+ rotate,
+ endRotate,
+ }
+}
diff --git a/src/model/edit.ts b/src/model/edit.ts
new file mode 100644
index 0000000..50a4f60
--- /dev/null
+++ b/src/model/edit.ts
@@ -0,0 +1,300 @@
+import { wallLength } from './geometry'
+import type { Furniture, Opening, Plan, Point, Wall, Zone } from './schema'
+import { t } from '../i18n'
+
+export type WallEnd = 'a' | 'b'
+export type EndRef = { wallId: string; end: WallEnd }
+
+const EPS = 0.5
+
+export const samePoint = (p: Point, q: Point) => Math.abs(p.x - q.x) < EPS && Math.abs(p.y - q.y) < EPS
+
+export function connectedEnds(plan: Plan, point: Point, exclude?: EndRef): EndRef[] {
+ const out: EndRef[] = []
+ for (const w of plan.walls) {
+ for (const end of ['a', 'b'] as const) {
+ if (exclude && exclude.wallId === w.id && exclude.end === end) continue
+ if (samePoint(w[end], point)) out.push({ wallId: w.id, end })
+ }
+ }
+ return out
+}
+
+function setEnds(plan: Plan, ends: EndRef[], map: (p: Point) => Point): Plan {
+ if (ends.length === 0) return plan
+ const byWall = new Map<string, Set<WallEnd>>()
+ for (const r of ends) byWall.set(r.wallId, (byWall.get(r.wallId) ?? new Set()).add(r.end))
+ const walls = plan.walls.map((w) => {
+ const set = byWall.get(w.id)
+ if (!set) return w
+ return {
+ ...w,
+ a: set.has('a') ? map(w.a) : w.a,
+ b: set.has('b') ? map(w.b) : w.b,
+ }
+ })
+ return clampOpenings({ ...plan, walls })
+}
+
+export function endpointGroup(plan: Plan, ref: EndRef, detach: boolean): EndRef[] {
+ const wall = plan.walls.find((w) => w.id === ref.wallId)
+ if (!wall) return []
+ return detach ? [ref] : [ref, ...connectedEnds(plan, wall[ref.end], ref)]
+}
+
+export function moveEndpoint(plan: Plan, ref: EndRef, to: Point, detach = false): Plan {
+ const group = endpointGroup(plan, ref, detach)
+ const clean = group.filter((r) => {
+ const w = plan.walls.find((x) => x.id === r.wallId)
+ if (!w) return false
+ const other = w[r.end === 'a' ? 'b' : 'a']
+ return !samePoint(other, to)
+ })
+ if (!clean.some((r) => r.wallId === ref.wallId && r.end === ref.end)) return plan
+ return setEnds(plan, clean, () => ({ x: to.x, y: to.y }))
+}
+
+export function wallMoveGroup(plan: Plan, wallId: string, detach: boolean): EndRef[] {
+ const wall = plan.walls.find((w) => w.id === wallId)
+ if (!wall) return []
+ const own: EndRef[] = [
+ { wallId, end: 'a' },
+ { wallId, end: 'b' },
+ ]
+ if (detach) return own
+ return [
+ ...own,
+ ...connectedEnds(plan, wall.a).filter((r) => r.wallId !== wallId),
+ ...connectedEnds(plan, wall.b).filter((r) => r.wallId !== wallId),
+ ]
+}
+
+export function moveWall(plan: Plan, wallId: string, delta: Point, detach = false): Plan {
+ if (delta.x === 0 && delta.y === 0) return plan
+ const group = wallMoveGroup(plan, wallId, detach)
+ const unique = group.filter((r, i) => group.findIndex((q) => q.wallId === r.wallId && q.end === r.end) === i)
+ const moved = setEnds(plan, unique, (p) => ({ x: p.x + delta.x, y: p.y + delta.y }))
+ return {
+ ...moved,
+ walls: moved.walls.filter((w) => !samePoint(w.a, w.b)),
+ }
+}
+
+export function setWallLength(plan: Plan, wallId: string, lengthMm: number, detach = false): Plan {
+ const wall = plan.walls.find((w) => w.id === wallId)
+ if (!wall || !(lengthMm > 0)) return plan
+ const len = wallLength(wall) || 1
+ const to = {
+ x: Math.round(wall.a.x + ((wall.b.x - wall.a.x) / len) * lengthMm),
+ y: Math.round(wall.a.y + ((wall.b.y - wall.a.y) / len) * lengthMm),
+ }
+ return moveEndpoint(plan, { wallId, end: 'b' }, to, detach)
+}
+
+export function clampOpenings(plan: Plan): Plan {
+ const walls = new Map<string, Wall>(plan.walls.map((w) => [w.id, w]))
+ let changed = false
+ const openings = plan.openings.map((o) => {
+ const w = walls.get(o.wallId)
+ if (!w) return o
+ const len = wallLength(w)
+ if (o.offset + o.width <= len + EPS) return o
+ const offset = Math.max(0, Math.round(len - o.width))
+ if (offset === o.offset) return o
+ changed = true
+ return { ...o, offset }
+ })
+ return changed ? { ...plan, openings } : plan
+}
+
+export function openingFits(plan: Plan, openingId: string) {
+ const o = plan.openings.find((x) => x.id === openingId)
+ const w = o && plan.walls.find((x) => x.id === o.wallId)
+ return !!o && !!w && o.offset + o.width <= wallLength(w) + EPS
+}
+
+export const OPENING_SNAP = 50
+export const MIN_OPENING_WIDTH = 300
+
+export type OpeningSpec = Pick<Opening, 'type' | 'width' | 'height' | 'sill' | 'hinge' | 'side'>
+export type OpeningPreset = 'entry' | 'interior' | 'gate' | 'window'
+
+export const OPENING_PRESETS: Record<OpeningPreset, OpeningSpec & { label: string }> = {
+ entry: { get label() { return t('plan:openingPresets.entry') }, type: 'door', width: 960, height: 2070, sill: 0, hinge: 'start', side: 'right' },
+ interior: { get label() { return t('plan:openingPresets.interior') }, type: 'door', width: 800, height: 2000, sill: 0, hinge: 'start', side: 'right' },
+ gate: { get label() { return t('plan:openingPresets.gate') }, type: 'gate', width: 2500, height: 2200, sill: 0, side: 'right' },
+ window: { get label() { return t('plan:openingPresets.window') }, type: 'window', width: 1200, height: 1400, sill: 800 },
+}
+
+export const snapOffset = (v: number, step = OPENING_SNAP) => Math.round(v / step) * step
+
+export function freeIntervals(plan: Plan, wallId: string, excludeId?: string): [number, number][] {
+ const wall = plan.walls.find((w) => w.id === wallId)
+ if (!wall) return []
+ const len = wallLength(wall)
+ const taken = plan.openings
+ .filter((o) => o.wallId === wallId && o.id !== excludeId)
+ .map((o) => [o.offset, o.offset + o.width] as [number, number])
+ .sort((p, q) => p[0] - q[0])
+ const out: [number, number][] = []
+ let cursor = 0
+ for (const [s, e] of taken) {
+ if (s > cursor) out.push([cursor, s])
+ cursor = Math.max(cursor, e)
+ }
+ if (len > cursor) out.push([cursor, len])
+ return out
+}
+
+export function fitOffset(plan: Plan, wallId: string, width: number, desired: number, excludeId?: string): number | null {
+ let best: number | null = null
+ let bestDist = Infinity
+ for (const [s, e] of freeIntervals(plan, wallId, excludeId)) {
+ if (e - s < width - EPS) continue
+ const lo = Math.ceil(s)
+ const hi = Math.floor(e - width)
+ const v = Math.min(hi, Math.max(lo, desired))
+ const d = Math.abs(v - desired)
+ if (d < bestDist) {
+ best = v
+ bestDist = d
+ }
+ }
+ return best
+}
+
+export function addOpening(plan: Plan, wallId: string, spec: OpeningSpec, offset: number): { plan: Plan; id: string } | null {
+ const at = fitOffset(plan, wallId, spec.width, offset)
+ if (at === null) return null
+ const used = new Set(plan.openings.map((o) => o.id))
+ const prefix = spec.type === 'door' ? 'd' : spec.type === 'gate' ? 'g' : 'win'
+ let n = plan.openings.filter((o) => o.type === spec.type).length + 1
+ while (used.has(`${prefix}${n}`)) n += 1
+ const id = `${prefix}${n}`
+ const opening: Opening = {
+ id,
+ wallId,
+ type: spec.type,
+ offset: at,
+ width: spec.width,
+ height: spec.height,
+ sill: spec.sill,
+ ...(spec.type === 'door' ? { hinge: spec.hinge ?? 'start', side: spec.side ?? 'right' } : {}),
+ ...(spec.type === 'gate' ? { side: spec.side ?? 'right' } : {}),
+ }
+ return { plan: { ...plan, openings: [...plan.openings, opening] }, id }
+}
+
+export function updateOpening(plan: Plan, id: string, patch: Partial<Omit<Opening, 'id'>>): Plan {
+ return { ...plan, openings: plan.openings.map((o) => (o.id === id ? { ...o, ...patch } : o)) }
+}
+
+export function moveOpening(plan: Plan, id: string, offset: number): Plan {
+ const o = plan.openings.find((x) => x.id === id)
+ if (!o) return plan
+ const at = fitOffset(plan, o.wallId, o.width, offset, id)
+ return at === null || at === o.offset ? plan : updateOpening(plan, id, { offset: at })
+}
+
+export function resizeOpening(plan: Plan, id: string, edge: 'start' | 'end', pos: number): Plan {
+ const o = plan.openings.find((x) => x.id === id)
+ if (!o) return plan
+ const room = freeIntervals(plan, o.wallId, id).find(([s, e]) => s <= o.offset + EPS && e >= o.offset + o.width - EPS)
+ if (!room) return plan
+ if (edge === 'start') {
+ const end = o.offset + o.width
+ const start = Math.min(end - MIN_OPENING_WIDTH, Math.max(room[0], pos))
+ return updateOpening(plan, id, { offset: Math.round(start), width: Math.round(end - start) })
+ }
+ const end = Math.max(o.offset + MIN_OPENING_WIDTH, Math.min(room[1], pos))
+ return updateOpening(plan, id, { width: Math.round(end - o.offset) })
+}
+
+export function deleteOpening(plan: Plan, id: string): Plan {
+ return { ...plan, openings: plan.openings.filter((o) => o.id !== id) }
+}
+
+export function updateWall(plan: Plan, id: string, patch: Partial<Omit<Wall, 'id' | 'a' | 'b'>>): Plan {
+ return { ...plan, walls: plan.walls.map((w) => (w.id === id ? { ...w, ...patch } : w)) }
+}
+
+export function openingGaps(plan: Plan, wallId: string, offset: number, width: number, excludeId?: string) {
+ const wall = plan.walls.find((w) => w.id === wallId)
+ if (!wall) return null
+ const len = wallLength(wall)
+ const others = plan.openings.filter((o) => o.wallId === wallId && o.id !== excludeId)
+ const before = Math.max(0, ...others.filter((o) => o.offset + o.width <= offset + EPS).map((o) => o.offset + o.width))
+ const after = Math.min(len, ...others.filter((o) => o.offset >= offset + width - EPS).map((o) => o.offset))
+ return { before: [before, offset] as [number, number], after: [offset + width, after] as [number, number] }
+}
+
+export function addFurniture(
+ plan: Plan,
+ item: Pick<Furniture, 'type' | 'x' | 'y' | 'rotationDeg'> & Partial<Pick<Furniture, 'w' | 'd' | 'h' | 'color'>>,
+): { plan: Plan; id: string } {
+ const used = new Set(plan.furniture.map((f) => f.id))
+ let n = plan.furniture.length + 1
+ while (used.has(`f${n}`)) n += 1
+ const id = `f${n}`
+ const f: Furniture = { ...item, id }
+ return { plan: { ...plan, furniture: [...plan.furniture, f] }, id }
+}
+
+export function updateFurniture(plan: Plan, id: string, patch: Partial<Omit<Furniture, 'id'>>): Plan {
+ return { ...plan, furniture: plan.furniture.map((f) => (f.id === id ? { ...f, ...patch } : f)) }
+}
+
+export function deleteFurniture(plan: Plan, id: string): Plan {
+ return { ...plan, furniture: plan.furniture.filter((f) => f.id !== id) }
+}
+
+export const normalizeDeg = (deg: number) => ((Math.round(deg) % 360) + 360) % 360
+
+export const PIER_MIN = 300
+export const CORNER_MIN = 250
+
+export function fitOffsetClear(plan: Plan, wallId: string, width: number, desired: number, excludeId?: string): number | null {
+ const wall = plan.walls.find((w) => w.id === wallId)
+ if (!wall) return null
+ const len = wallLength(wall)
+ let best: number | null = null
+ let bestDist = Infinity
+ for (const [s, e] of freeIntervals(plan, wallId, excludeId)) {
+ const lo = s + (s <= EPS ? CORNER_MIN : PIER_MIN)
+ const hi = e - (e >= len - EPS ? CORNER_MIN : PIER_MIN) - width
+ if (hi < lo) continue
+ const v = snapOffset(Math.min(hi, Math.max(lo, desired)))
+ const clamped = Math.min(Math.floor(hi), Math.max(Math.ceil(lo), v))
+ const d = Math.abs(clamped - desired)
+ if (d < bestDist) {
+ best = clamped
+ bestDist = d
+ }
+ }
+ return best
+}
+
+export const zoneKindLabels = Object.defineProperties(
+ {},
+ Object.fromEntries((['fill', 'lawn', 'paving', 'other'] as const).map((k) => [k, { enumerable: true, get: () => t(`plan:zoneKinds.${k}`) }])),
+) as Record<Zone['kind'], string>
+
+export function addZone(plan: Plan, polygon: Point[], kind: Zone['kind'] = 'fill'): { plan: Plan; id: string } {
+ const zones = plan.site.zones ?? []
+ const used = new Set(zones.map((z) => z.id))
+ let n = zones.length + 1
+ while (used.has(`z${n}`)) n += 1
+ const id = `z${n}`
+ const zone: Zone = { id, name: t('plan:zone.defaultName', { n }), kind, polygon: polygon.map((p) => ({ x: Math.round(p.x), y: Math.round(p.y) })) }
+ return { plan: { ...plan, site: { ...plan.site, zones: [...zones, zone] } }, id }
+}
+
+export function updateZone(plan: Plan, id: string, patch: Partial<Omit<Zone, 'id'>>): Plan {
+ const zones = (plan.site.zones ?? []).map((z) => (z.id === id ? { ...z, ...patch } : z))
+ return { ...plan, site: { ...plan.site, zones } }
+}
+
+export function deleteZone(plan: Plan, id: string): Plan {
+ const zones = (plan.site.zones ?? []).filter((z) => z.id !== id)
+ return { ...plan, site: { ...plan.site, zones } }
+}
diff --git a/src/model/estimate.ts b/src/model/estimate.ts
new file mode 100644
index 0000000..43071da
--- /dev/null
+++ b/src/model/estimate.ts
@@ -0,0 +1,139 @@
+import { fmtRub, t } from '../i18n'
+import { wallLength } from './geometry'
+import type { Material, Plan, PricePer, Wall } from './schema'
+
+export const DEFAULT_WASTE_PCT = 7
+export const NO_MATERIAL_ID = 'none'
+
+export type WallEstimateLine = {
+ id: string
+ materialId: string
+ material?: Material
+ name: string
+ category: 'стены'
+ wallCount: number
+ lengthMm: number
+ grossAreaM2: number
+ openingsAreaM2: number
+ netAreaM2: number
+ volumeM3: number
+ panels?: number
+ panelsWithWaste?: number
+ pieces?: number
+ piecesPerM2?: number
+ areaWithWasteM2: number
+ wastePct: number
+ qty: number | null
+ unit: PricePer | null
+ price?: number
+ cost: number | null
+ url?: string
+ source?: string
+ checkedAt?: string
+}
+
+export type WallEstimate = {
+ lines: WallEstimateLine[]
+ total: number
+ missingPrices: number
+ wastePct: number
+}
+
+export const wallEstimateId = (materialId: string) => `auto:wall:${materialId}`
+
+const round = (v: number, digits = 2) => Math.round(v * 10 ** digits) / 10 ** digits
+
+export function wallPanelCount(wall: Wall, material: Material): number | undefined {
+ if (!material.panelWidth || !material.panelHeight) return undefined
+ return Math.ceil(wallLength(wall) / material.panelWidth - 1e-9) * Math.ceil(wall.height / material.panelHeight - 1e-9)
+}
+
+export function computeWallEstimate(plan: Plan): WallEstimate {
+ const wastePct = plan.estimate?.wasteSipPct ?? DEFAULT_WASTE_PCT
+ const k = 1 + wastePct / 100
+ const materials = new Map(plan.materials.map((m) => [m.id, m]))
+ const groups = new Map<string, Wall[]>()
+ for (const w of plan.walls) {
+ const key = w.materialId && materials.has(w.materialId) ? w.materialId : NO_MATERIAL_ID
+ groups.set(key, [...(groups.get(key) ?? []), w])
+ }
+
+ const lines: WallEstimateLine[] = []
+ for (const [materialId, walls] of groups) {
+ const material = materials.get(materialId)
+ const ids = new Set(walls.map((w) => w.id))
+ const lengthMm = walls.reduce((s, w) => s + wallLength(w), 0)
+ const grossAreaM2 = walls.reduce((s, w) => s + (wallLength(w) * w.height) / 1e6, 0)
+ const openingsAreaM2 = plan.openings
+ .filter((o) => ids.has(o.wallId))
+ .reduce((s, o) => s + (o.width * o.height) / 1e6, 0)
+ const netAreaM2 = Math.max(0, grossAreaM2 - openingsAreaM2)
+ const thickness = material?.thickness ?? 0
+ const volumeM3 = (netAreaM2 * thickness) / 1000
+
+ const panelCounts = material ? walls.map((w) => wallPanelCount(w, material)) : []
+ const panels = material && panelCounts.every((n) => n !== undefined)
+ ? panelCounts.reduce<number>((s, n) => s + (n ?? 0), 0)
+ : undefined
+ const panelsWithWaste = panels !== undefined ? Math.ceil(panels * k - 1e-9) : undefined
+
+ const joint = material?.jointMm ?? 10
+ const piecesPerM2 =
+ material?.unitLength && material.unitHeight ? 1e6 / ((material.unitLength + joint) * (material.unitHeight + joint)) : undefined
+ const pieces = piecesPerM2 !== undefined ? Math.ceil(netAreaM2 * k * piecesPerM2 - 1e-9) : undefined
+
+ const unit: PricePer | null =
+ material?.pricePer ?? (panels !== undefined || pieces !== undefined ? 'pcs' : material ? 'm2' : null)
+ let qty: number | null = null
+ if (unit === 'pcs') qty = panelsWithWaste ?? pieces ?? null
+ else if (unit === 'm2') qty = round(netAreaM2 * k)
+ else if (unit === 'm3') qty = round(volumeM3 * k, 3)
+ else if (unit === 'm') qty = round((lengthMm / 1000) * k)
+
+ const price = material?.price
+ const cost = price !== undefined && qty !== null ? Math.round(price * qty) : null
+
+ lines.push({
+ id: wallEstimateId(materialId),
+ materialId,
+ material,
+ name: material?.name ?? t('estimate:wallLine.noMaterial'),
+ category: 'стены',
+ wallCount: walls.length,
+ lengthMm,
+ grossAreaM2: round(grossAreaM2),
+ openingsAreaM2: round(openingsAreaM2),
+ netAreaM2: round(netAreaM2),
+ volumeM3: round(volumeM3, 3),
+ panels,
+ panelsWithWaste,
+ pieces,
+ piecesPerM2: piecesPerM2 !== undefined ? round(piecesPerM2, 2) : undefined,
+ areaWithWasteM2: round(netAreaM2 * k),
+ wastePct,
+ qty,
+ unit,
+ price,
+ cost,
+ url: material?.url,
+ source: material?.source,
+ checkedAt: material?.checkedAt,
+ })
+ }
+
+ return {
+ lines,
+ total: lines.reduce((s, l) => s + (l.cost ?? 0), 0),
+ missingPrices: lines.filter((l) => l.cost === null).length,
+ wastePct,
+ }
+}
+
+export const unitLabels: Record<PricePer, string> = {
+ get pcs() { return t('common:units.pcs') },
+ get m2() { return t('common:units.m2') },
+ get m3() { return t('common:units.m3') },
+ get m() { return t('common:units.m') },
+}
+
+export const formatMoney = (rub: number) => fmtRub(rub)
diff --git a/src/model/geometry.ts b/src/model/geometry.ts
new file mode 100644
index 0000000..d736996
--- /dev/null
+++ b/src/model/geometry.ts
@@ -0,0 +1,104 @@
+import type { Opening, Point, Site, Wall } from './schema'
+import { numberFormat, t } from '../i18n'
+
+export const distance = (p: Point, q: Point) => Math.hypot(q.x - p.x, q.y - p.y)
+
+export const wallLength = (w: Wall) => distance(w.a, w.b)
+
+export const wallAngle = (w: Wall) => Math.atan2(w.b.y - w.a.y, w.b.x - w.a.x)
+
+export function wallDirection(w: Wall): Point {
+ const len = wallLength(w) || 1
+ return { x: (w.b.x - w.a.x) / len, y: (w.b.y - w.a.y) / len }
+}
+
+export function pointOnWall(w: Wall, offset: number): Point {
+ const d = wallDirection(w)
+ return { x: w.a.x + d.x * offset, y: w.a.y + d.y * offset }
+}
+
+export const openingCenter = (w: Wall, o: Opening) => pointOnWall(w, o.offset + o.width / 2)
+
+export function distanceToSegment(p: Point, a: Point, b: Point) {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const len2 = dx * dx + dy * dy
+ if (len2 === 0) return distance(p, a)
+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2))
+ return distance(p, { x: a.x + t * dx, y: a.y + t * dy })
+}
+
+export const snapToGrid = (p: Point, step: number): Point => ({
+ x: Math.round(p.x / step) * step,
+ y: Math.round(p.y / step) * step,
+})
+
+export function snapOrthogonal(from: Point, to: Point): Point {
+ return Math.abs(to.x - from.x) >= Math.abs(to.y - from.y) ? { x: to.x, y: from.y } : { x: from.x, y: to.y }
+}
+
+export function formatNumber(v: number, maxDigits = 2) {
+ return numberFormat({ maximumFractionDigits: maxDigits }).format(v)
+}
+
+export const formatMeters = (mm: number, maxDigits = 2) => formatNumber(mm / 1000, maxDigits)
+
+export function formatLength(mm: number) {
+ if (Math.abs(mm) >= 1000) return `${formatNumber(mm / 1000, 2)} ${t('common:units.m')}`
+ return `${Math.round(mm)} ${t('common:units.mm')}`
+}
+
+export function nextId(prefix: string, items: { id: string }[]) {
+ const used = new Set(items.map((i) => i.id))
+ let n = items.length + 1
+ while (used.has(`${prefix}${n}`)) n += 1
+ return `${prefix}${n}`
+}
+
+export function sitePolygon(site: Site): Point[] {
+ if (site.boundary && site.boundary.length >= 3) return site.boundary
+ return [
+ { x: 0, y: 0 },
+ { x: site.width, y: 0 },
+ { x: site.width, y: site.depth },
+ { x: 0, y: site.depth },
+ ]
+}
+
+export function polygonBounds(points: Point[]) {
+ const xs = points.map((p) => p.x)
+ const ys = points.map((p) => p.y)
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) }
+}
+
+export function polygonAreaMm2(points: Point[]) {
+ let a = 0
+ for (let i = 0; i < points.length; i += 1) {
+ const p = points[i]
+ const q = points[(i + 1) % points.length]
+ a += p.x * q.y - q.x * p.y
+ }
+ return Math.abs(a) / 2
+}
+
+export function polygonCentroid(points: Point[]): Point {
+ let a = 0
+ let cx = 0
+ let cy = 0
+ for (let i = 0; i < points.length; i += 1) {
+ const p = points[i]
+ const q = points[(i + 1) % points.length]
+ const k = p.x * q.y - q.x * p.y
+ a += k
+ cx += (p.x + q.x) * k
+ cy += (p.y + q.y) * k
+ }
+ if (Math.abs(a) < 1e-9) {
+ const n = points.length || 1
+ return { x: points.reduce((s, p) => s + p.x, 0) / n, y: points.reduce((s, p) => s + p.y, 0) / n }
+ }
+ return { x: cx / (3 * a), y: cy / (3 * a) }
+}
+
+export const polygonPerimeter = (points: Point[]) =>
+ points.reduce((s, p, i) => s + distance(p, points[(i + 1) % points.length]), 0)
diff --git a/src/model/index.ts b/src/model/index.ts
new file mode 100644
index 0000000..41d44df
--- /dev/null
+++ b/src/model/index.ts
@@ -0,0 +1,5 @@
+export * from './schema'
+export * from './geometry'
+export * from './materials'
+export * from './estimate'
+export * from './edit'
diff --git a/src/model/materials.ts b/src/model/materials.ts
new file mode 100644
index 0000000..a3b04bb
--- /dev/null
+++ b/src/model/materials.ts
@@ -0,0 +1,31 @@
+import type { Material, MaterialKind, Plan, Wall } from './schema'
+import { t } from '../i18n'
+
+export const kindColors: Record<MaterialKind, string> = {
+ sip: '#e8b86a',
+ pir: '#e3c27a',
+ brick: '#c9624a',
+ block: '#b9b4a8',
+ timber: '#b0824f',
+ frame: '#d9c29a',
+ concrete: '#9aa0a6',
+ glass: '#8cc6e0',
+ other: '#8a8f98',
+}
+
+export const kindLabels = Object.defineProperties(
+ {},
+ Object.fromEntries(
+ (Object.keys(kindColors) as MaterialKind[]).map((k) => [k, { enumerable: true, get: () => t(`plan:materialKinds.${k}`) }]),
+ ),
+) as Record<MaterialKind, string>
+
+export const DEFAULT_WALL_COLOR = '#5b6270'
+export const DEFAULT_WALL_THICKNESS = 200
+export const DEFAULT_WALL_HEIGHT = 2800
+
+export const materialColor = (m?: Material) => (m ? m.color ?? kindColors[m.kind] : DEFAULT_WALL_COLOR)
+
+export const findMaterial = (plan: Plan, id?: string) => (id ? plan.materials.find((m) => m.id === id) : undefined)
+
+export const wallColor = (plan: Plan, w: Wall) => materialColor(findMaterial(plan, w.materialId))
diff --git a/src/model/schema.ts b/src/model/schema.ts
new file mode 100644
index 0000000..6b65d13
--- /dev/null
+++ b/src/model/schema.ts
@@ -0,0 +1,515 @@
+import { z } from 'zod'
+
+export const CLIENT_VERSION = 6
+
+const mm = z.number().finite()
+const positiveMm = mm.positive()
+const id = z.string().min(1)
+
+export const pointSchema = z.looseObject({ x: mm, y: mm })
+
+export const materialKindSchema = z.enum([
+ 'sip',
+ 'pir',
+ 'brick',
+ 'block',
+ 'timber',
+ 'frame',
+ 'concrete',
+ 'glass',
+ 'other',
+])
+
+export const pricePerSchema = z.enum(['pcs', 'm2', 'm3', 'm'])
+
+export const materialSchema = z.looseObject({
+ id,
+ name: z.string().min(1),
+ kind: materialKindSchema,
+ url: z.string().optional(),
+ thickness: positiveMm,
+ length: positiveMm.optional(),
+ height: positiveMm.optional(),
+ panelWidth: positiveMm.optional(),
+ panelHeight: positiveMm.optional(),
+ unitLength: positiveMm.optional(),
+ unitHeight: positiveMm.optional(),
+ jointMm: mm.nonnegative().optional(),
+ price: z.number().nonnegative().optional(),
+ pricePer: pricePerSchema.optional(),
+ source: z.string().optional(),
+ checkedAt: z.string().optional(),
+ color: z.string().optional(),
+ finish: z.enum(['osb', 'plaster', 'timber', 'planken']).optional(),
+ note: z.string().optional(),
+})
+
+export const wallSchema = z.looseObject({
+ id,
+ a: pointSchema,
+ b: pointSchema,
+ thickness: positiveMm,
+ height: positiveMm,
+ materialId: id.optional(),
+ note: z.string().optional(),
+})
+
+export const openingSchema = z.looseObject({
+ id,
+ wallId: id,
+ type: z.enum(['door', 'window', 'gate']),
+ offset: mm.nonnegative(),
+ width: positiveMm,
+ height: positiveMm,
+ sill: mm.nonnegative().default(0),
+ hinge: z.enum(['start', 'end']).optional(),
+ side: z.enum(['left', 'right']).optional(),
+ note: z.string().optional(),
+})
+
+export const furnitureSchema = z.looseObject({
+ id,
+ type: z.string().min(1),
+ x: mm,
+ y: mm,
+ rotationDeg: z.number().finite().default(0),
+ w: positiveMm.optional(),
+ d: positiveMm.optional(),
+ h: positiveMm.optional(),
+ color: z.string().optional(),
+ note: z.string().optional(),
+})
+
+export const roomLabelSchema = z.looseObject({
+ id,
+ name: z.string().min(1),
+ x: mm,
+ y: mm,
+ kind: z.enum(['living', 'bedroom', 'kitchen', 'bath', 'tech', 'hall', 'storage', 'garage']).optional(),
+})
+
+export const zoneSchema = z.looseObject({
+ id,
+ name: z.string().min(1),
+ kind: z.enum(['fill', 'lawn', 'paving', 'other']),
+ polygon: z.array(pointSchema).min(3),
+ locked: z.boolean().optional(),
+})
+
+export const siteSchema = z.looseObject({
+ convention: z.string().optional(),
+ width: positiveMm,
+ depth: positiveMm,
+ geo: z
+ .looseObject({
+ lat: z.number().min(-90).max(90),
+ lng: z.number().min(-180).max(180),
+ rotationDeg: z.number().finite().default(0),
+ })
+ .optional(),
+ boundary: z.array(pointSchema).min(3).optional(),
+ zones: z.array(zoneSchema).optional(),
+ street: z.looseObject({ side: z.tuple([z.number().int(), z.number().int()]), note: z.string().optional() }).optional(),
+ imagery: z
+ .looseObject({ offsetE: z.number().finite(), offsetN: z.number().finite(), rotationDeg: z.number().finite() })
+ .optional(),
+ note: z.string().optional(),
+})
+
+export const estimateCategorySchema = z.enum([
+ 'фундамент',
+ 'стены',
+ 'перекрытия',
+ 'кровля',
+ 'окна-двери',
+ 'утепление',
+ 'крепёж',
+ 'инженерия',
+ 'работы',
+ 'прочее',
+])
+
+export const estimateLineSchema = z.looseObject({
+ id,
+ name: z.string().min(1),
+ category: estimateCategorySchema,
+ materialId: id.optional(),
+ qty: z.number().nonnegative(),
+ unit: z.string().min(1),
+ price: z.number().nonnegative().optional(),
+ url: z.string().optional(),
+ note: z.string().optional(),
+})
+
+export const purchaseSchema = z.looseObject({
+ done: z.boolean(),
+ date: z.string().optional(),
+ actualPrice: z.number().nonnegative().optional(),
+ qty: z.number().nonnegative().optional(),
+ shop: z.string().optional(),
+ note: z.string().optional(),
+})
+
+export const estimateSchema = z.looseObject({
+ lines: z.array(estimateLineSchema).default([]),
+ purchases: z.record(z.string(), purchaseSchema).default({}),
+ wasteSipPct: z.number().min(0).max(100).optional(),
+ notes: z.array(z.string()).optional(),
+})
+
+export const sewerNodeKindSchema = z.enum(['fixture', 'riser', 'cleanout', 'outlet', 'septic', 'junction'])
+export const sewerFixtureSchema = z.enum(['toilet', 'sink', 'bath', 'shower', 'washer', 'kitchen', 'boiler'])
+export const sewerDiameterSchema = z.union([z.literal(50), z.literal(110), z.literal(160)])
+
+export const sewerNodeSchema = z.looseObject({
+ id,
+ x: mm,
+ y: mm,
+ kind: sewerNodeKindSchema,
+ fixture: sewerFixtureSchema.optional(),
+ label: z.string().optional(),
+ furnitureId: z.string().optional(),
+ height: positiveMm.optional(),
+ w: positiveMm.optional(),
+ d: positiveMm.optional(),
+ rotationDeg: z.number().finite().optional(),
+ model: z.string().optional(),
+ depth: mm.nonnegative().optional(),
+})
+
+export const sewerPipeSchema = z.looseObject({
+ id,
+ from: id,
+ to: id,
+ diameter: sewerDiameterSchema,
+ slope: z.number().positive().max(100).optional(),
+ depth: mm.nonnegative().optional(),
+ location: z.enum(['inside', 'outside']),
+ material: z.string().optional(),
+})
+
+export const networkMaterialSchema = z.looseObject({
+ id,
+ name: z.string().min(1),
+ kind: z.string().optional(),
+ diameter: positiveMm.optional(),
+ angle: z.number().finite().optional(),
+ length: positiveMm.optional(),
+ price: z.number().nonnegative().optional(),
+ pricePer: pricePerSchema.optional(),
+ url: z.string().optional(),
+ source: z.string().optional(),
+ checkedAt: z.string().optional(),
+ note: z.string().optional(),
+})
+
+export const sewerSchema = z.looseObject({
+ nodes: z.array(sewerNodeSchema).default([]),
+ pipes: z.array(sewerPipeSchema).default([]),
+ materials: z.array(networkMaterialSchema).optional(),
+ floorLevel: mm.optional(),
+})
+
+export const electricPointKindSchema = z.enum([
+ 'socket',
+ 'socket2',
+ 'socket_ip44',
+ 'power',
+ 'switch',
+ 'switch2',
+ 'light',
+ 'light_wall',
+ 'junction',
+ 'outdoor',
+])
+
+export const electricPointSchema = z.looseObject({
+ id,
+ kind: electricPointKindSchema,
+ x: mm,
+ y: mm,
+ height: mm.nonnegative(),
+ wallId: id.optional(),
+ circuitId: id.optional(),
+ label: z.string().optional(),
+ powerW: z.number().nonnegative().optional(),
+})
+
+export const electricCircuitSchema = z.looseObject({
+ id,
+ name: z.string(),
+ kind: z.enum(['light', 'socket', 'power', 'wet', 'outdoor', 'garage']),
+ breaker: z.looseObject({
+ type: z.enum(['MCB', 'RCBO', 'RCD']),
+ rating: z.number().positive(),
+ curve: z.string().optional(),
+ }),
+ cable: z.string().min(1),
+ phase: z.enum(['L1', 'L2', 'L3']).optional(),
+})
+
+export const electricPanelSchema = z.looseObject({
+ id,
+ x: mm,
+ y: mm,
+ wallId: id.optional(),
+ modules: z.number().int().positive().optional(),
+})
+
+export const electricRouteSchema = z.looseObject({
+ circuitId: id,
+ path: z.array(pointSchema).min(2),
+})
+
+export const electricSchema = z.looseObject({
+ panel: electricPanelSchema.optional(),
+ points: z.array(electricPointSchema).default([]),
+ circuits: z.array(electricCircuitSchema).default([]),
+ routes: z.array(electricRouteSchema).optional(),
+ materials: z.array(networkMaterialSchema).optional(),
+})
+
+export const waterNodeSchema = z.looseObject({
+ id,
+ x: mm,
+ y: mm,
+ kind: z.enum(['source', 'entry', 'pump', 'filter', 'boiler', 'collector', 'fixture', 'junction', 'tap_outdoor']),
+ fixture: sewerFixtureSchema.optional(),
+ furnitureId: z.string().optional(),
+ label: z.string().optional(),
+ model: z.string().optional(),
+ source: z.enum(['well', 'borehole']).optional(),
+ line: z.enum(['cold', 'hot']).optional(),
+ outputs: z.number().int().positive().optional(),
+ rotationDeg: z.number().finite().optional(),
+})
+
+export const waterPipeSchema = z.looseObject({
+ id,
+ from: id,
+ to: id,
+ line: z.enum(['cold', 'hot', 'recirc']),
+ diameter: z.union([z.literal(16), z.literal(20), z.literal(25), z.literal(32)]),
+ material: z.enum(['PEX', 'PPR', 'PE']).optional(),
+ location: z.enum(['inside', 'outside']),
+ depth: mm.nonnegative().optional(),
+ heated: z.boolean().optional(),
+})
+
+export const waterSchema = z.looseObject({
+ nodes: z.array(waterNodeSchema).default([]),
+ pipes: z.array(waterPipeSchema).default([]),
+ materials: z.array(networkMaterialSchema).optional(),
+})
+
+export const heatingStepSchema = z.union([z.literal(100), z.literal(150), z.literal(200)])
+
+export const heatingLoopSchema = z.looseObject({
+ id,
+ roomId: z.string().optional(),
+ roomName: z.string().optional(),
+ polygon: z.array(pointSchema).min(3),
+ stepMm: heatingStepSchema,
+ pattern: z.enum(['spiral', 'snake']),
+ pipe: z.string().min(1),
+ supplyPath: z.array(pointSchema).optional(),
+ excluded: z.array(z.array(pointSchema).min(3)).optional(),
+ parts: z
+ .array(
+ z.looseObject({
+ polygon: z.array(pointSchema).min(3),
+ roomId: z.string().optional(),
+ roomName: z.string().optional(),
+ excluded: z.array(z.array(pointSchema).min(3)).optional(),
+ }),
+ )
+ .optional(),
+ linkPath: z.array(pointSchema).optional(),
+ edge: z.boolean().optional(),
+ off: z.boolean().optional(),
+})
+
+export const heatingCollectorSchema = z.looseObject({
+ id,
+ x: mm,
+ y: mm,
+ outputs: z.number().int().positive(),
+ label: z.string().optional(),
+})
+
+export const heatingParamsSchema = z.looseObject({
+ supplyT: z.number().finite().optional(),
+ returnT: z.number().finite().optional(),
+ floorT: z.number().finite().optional(),
+ screedMm: positiveMm.optional(),
+ insulation: z.string().optional(),
+ screedMix: z.enum(['cement-sand', 'cps']).optional(),
+ fixing: z.enum(['mesh', 'staples']).optional(),
+})
+
+export const heatingSchema = z.looseObject({
+ collector: heatingCollectorSchema.optional(),
+ loops: z.array(heatingLoopSchema).default([]),
+ params: heatingParamsSchema.optional(),
+ materials: z.array(networkMaterialSchema).optional(),
+})
+
+export const networksSchema = z.looseObject({
+ sewer: sewerSchema.optional(),
+ water: waterSchema.optional(),
+ electric: electricSchema.optional(),
+ heating: heatingSchema.optional(),
+})
+
+const ralSchema = z.string().regex(/^RAL \d{4}$/)
+
+export const paletteSchema = z.looseObject({
+ name: z.string().optional(),
+ walls: ralSchema.optional(),
+ accent: ralSchema.optional(),
+ roof: ralSchema.optional(),
+ windows: ralSchema.optional(),
+ gates: ralSchema.optional(),
+ plinth: ralSchema.optional(),
+})
+
+export const planSchema = z
+ .looseObject({
+ version: z.literal(1),
+ name: z.string().min(1),
+ rev: z.number().int().nonnegative().optional(),
+ updatedAt: z.string().optional(),
+ author: z.string().optional(),
+ resetEpoch: z.number().int().nonnegative().optional(),
+ site: siteSchema,
+ materials: z.array(materialSchema).default([]),
+ walls: z.array(wallSchema).default([]),
+ openings: z.array(openingSchema).default([]),
+ furniture: z.array(furnitureSchema).default([]),
+ rooms: z.array(roomLabelSchema).optional(),
+ estimate: estimateSchema.optional(),
+ networks: networksSchema.optional(),
+ palette: paletteSchema.optional(),
+ })
+ .superRefine((plan, ctx) => {
+ const unique = (items: { id: string }[], path: string) => {
+ const seen = new Set<string>()
+ items.forEach((item, i) => {
+ if (seen.has(item.id)) {
+ ctx.addIssue({ code: 'custom', path: [path, i, 'id'], message: `Duplicate id "${item.id}"` })
+ }
+ seen.add(item.id)
+ })
+ }
+ unique(plan.materials, 'materials')
+ unique(plan.walls, 'walls')
+ unique(plan.openings, 'openings')
+ unique(plan.furniture, 'furniture')
+
+ const water = plan.networks?.water
+ if (water) {
+ unique(water.nodes, 'networks.water.nodes')
+ unique(water.pipes, 'networks.water.pipes')
+ const ids = new Set(water.nodes.map((n) => n.id))
+ water.pipes.forEach((p, i) => {
+ for (const end of ['from', 'to'] as const) {
+ if (!ids.has(p[end])) ctx.addIssue({ code: 'custom', path: ['networks', 'water', 'pipes', i, end], message: `Missing node "${p[end]}"` })
+ }
+ })
+ }
+ const sewer = plan.networks?.sewer
+ if (sewer) {
+ unique(sewer.nodes, 'networks.sewer.nodes')
+ unique(sewer.pipes, 'networks.sewer.pipes')
+ const nodeIds = new Set(sewer.nodes.map((n) => n.id))
+ sewer.pipes.forEach((p, i) => {
+ for (const end of ['from', 'to'] as const) {
+ if (!nodeIds.has(p[end])) {
+ ctx.addIssue({ code: 'custom', path: ['networks', 'sewer', 'pipes', i, end], message: `Missing node "${p[end]}"` })
+ }
+ }
+ if (p.from === p.to) ctx.addIssue({ code: 'custom', path: ['networks', 'sewer', 'pipes', i], message: 'Pipe connects a node to itself' })
+ })
+ }
+
+ const electric = plan.networks?.electric
+ if (electric) {
+ unique(electric.points, 'networks.electric.points')
+ unique(electric.circuits, 'networks.electric.circuits')
+ }
+
+ const heating = plan.networks?.heating
+ if (heating) unique(heating.loops, 'networks.heating.loops')
+
+ const materialIds = new Set(plan.materials.map((m) => m.id))
+ const walls = new Map(plan.walls.map((w) => [w.id, w]))
+
+ plan.walls.forEach((w, i) => {
+ if (w.materialId && !materialIds.has(w.materialId)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['walls', i, 'materialId'],
+ message: `Missing material "${w.materialId}"`,
+ })
+ }
+ if (w.a.x === w.b.x && w.a.y === w.b.y) {
+ ctx.addIssue({ code: 'custom', path: ['walls', i], message: 'Zero-length wall' })
+ }
+ })
+
+ plan.openings.forEach((o, i) => {
+ const wall = walls.get(o.wallId)
+ if (!wall) {
+ ctx.addIssue({ code: 'custom', path: ['openings', i, 'wallId'], message: `Missing wall "${o.wallId}"` })
+ }
+ })
+ })
+
+export type Point = z.infer<typeof pointSchema>
+export type MaterialKind = z.infer<typeof materialKindSchema>
+export type Material = z.infer<typeof materialSchema>
+export type Wall = z.infer<typeof wallSchema>
+export type Opening = z.infer<typeof openingSchema>
+export type Site = z.infer<typeof siteSchema>
+export type Plan = z.infer<typeof planSchema>
+export type Palette = z.infer<typeof paletteSchema>
+export type Furniture = z.infer<typeof furnitureSchema>
+export type Zone = z.infer<typeof zoneSchema>
+export type RoomLabelItem = z.infer<typeof roomLabelSchema>
+export type PricePer = z.infer<typeof pricePerSchema>
+export type EstimateCategory = z.infer<typeof estimateCategorySchema>
+export type EstimateLine = z.infer<typeof estimateLineSchema>
+export type Purchase = z.infer<typeof purchaseSchema>
+export type Estimate = z.infer<typeof estimateSchema>
+export type SewerNode = z.infer<typeof sewerNodeSchema>
+export type SewerPipe = z.infer<typeof sewerPipeSchema>
+export type SewerNetwork = z.infer<typeof sewerSchema>
+export type SewerDiameter = z.infer<typeof sewerDiameterSchema>
+export type SewerFixture = z.infer<typeof sewerFixtureSchema>
+export type SewerNodeKind = z.infer<typeof sewerNodeKindSchema>
+export type NetworkMaterial = z.infer<typeof networkMaterialSchema>
+export type Networks = z.infer<typeof networksSchema>
+export type WaterNode = z.infer<typeof waterNodeSchema>
+export type WaterPipe = z.infer<typeof waterPipeSchema>
+export type WaterNetwork = z.infer<typeof waterSchema>
+export type WaterLine = WaterPipe['line']
+export type WaterDiameter = WaterPipe['diameter']
+export type ElectricPointKind = z.infer<typeof electricPointKindSchema>
+export type ElectricPoint = z.infer<typeof electricPointSchema>
+export type ElectricCircuit = z.infer<typeof electricCircuitSchema>
+export type ElectricPanel = z.infer<typeof electricPanelSchema>
+export type ElectricRoute = z.infer<typeof electricRouteSchema>
+export type ElectricNetwork = z.infer<typeof electricSchema>
+export type HeatingLoop = z.infer<typeof heatingLoopSchema>
+export type HeatingCollector = z.infer<typeof heatingCollectorSchema>
+export type HeatingParams = z.infer<typeof heatingParamsSchema>
+export type HeatingNetwork = z.infer<typeof heatingSchema>
+export type HeatingStep = z.infer<typeof heatingStepSchema>
+
+export type ParseResult = { ok: true; plan: Plan } | { ok: false; error: string }
+
+export function parsePlan(data: unknown): ParseResult {
+ const result = planSchema.safeParse(data)
+ if (result.success) return { ok: true, plan: result.data }
+ return { ok: false, error: z.prettifyError(result.error) }
+}
diff --git a/src/networks/NetworkTools.tsx b/src/networks/NetworkTools.tsx
new file mode 100644
index 0000000..edffb2a
--- /dev/null
+++ b/src/networks/NetworkTools.tsx
@@ -0,0 +1,210 @@
+import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'
+import { createPortal } from 'react-dom'
+import { useTranslation } from 'react-i18next'
+import { useViewOnly } from '../store/viewOnly'
+import { Checkbox, IconButton } from '../ui'
+import { LAYER_LABELS, useLayers, type LayerKey } from './layers'
+import { startEdit, stopEdit, useNetworkEdit } from './registry'
+import { useSewerUi } from './sewerStore'
+import { useWaterUi } from './waterStore'
+import './networks.css'
+
+const GAP = 10
+const MARGIN = 8
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+function usePopoverPosition(open: boolean, anchor: RefObject<HTMLElement | null>, panel: RefObject<HTMLElement | null>) {
+ const [pos, setPos] = useState<{ left: number; top: number } | null>(null)
+ useLayoutEffect(() => {
+ if (!open) {
+ setPos(null)
+ return
+ }
+ const place = () => {
+ const a = anchor.current?.getBoundingClientRect()
+ const p = panel.current?.getBoundingClientRect()
+ if (!a || !p) return
+ const vw = window.innerWidth
+ const vh = window.innerHeight
+ let left = a.right + GAP
+ if (left + p.width > vw - MARGIN) left = a.left - GAP - p.width
+ left = Math.max(MARGIN, Math.min(left, vw - MARGIN - p.width))
+ let top = a.top
+ if (top + p.height > vh - MARGIN) top = vh - MARGIN - p.height
+ if (left < a.right && left + p.width > a.left && top + p.height > a.top) top = a.top - GAP - p.height
+ top = Math.max(MARGIN, top)
+ setPos({ left, top })
+ }
+ place()
+ window.addEventListener('resize', place)
+ window.addEventListener('scroll', place, true)
+ return () => {
+ window.removeEventListener('resize', place)
+ window.removeEventListener('scroll', place, true)
+ }
+ }, [open, anchor, panel])
+ return pos
+}
+
+const PencilIcon = () => (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <path d="M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4" />
+ </svg>
+)
+
+const LockIcon = ({ locked }: { locked: boolean }) => (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
+ <path d={locked ? 'M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3' : 'M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 6.8-1.2'} />
+ </svg>
+)
+
+export function LayersButton() {
+ const { t } = useTranslation('networks')
+ const [open, setOpen] = useState(false)
+ const layers = useLayers()
+ const viewOnly = useViewOnly()
+ const editing = useNetworkEdit((s) => s.editing)
+ const defs = useNetworkEdit((s) => s.defs)
+ const btnRef = useRef<HTMLButtonElement>(null)
+ const panelRef = useRef<HTMLDivElement>(null)
+ const pos = usePopoverPosition(open, btnRef, panelRef)
+ const keys = (Object.keys(LAYER_LABELS) as LayerKey[]).filter((k) => typeof layers[k] === 'boolean')
+ const count = keys.filter((k) => layers[k]).length
+
+ useEffect(() => {
+ if (!open) return
+ const onDown = (e: MouseEvent) => {
+ const target = e.target as Node
+ if (!btnRef.current?.contains(target) && !panelRef.current?.contains(target)) setOpen(false)
+ }
+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false)
+ window.addEventListener('mousedown', onDown)
+ window.addEventListener('keydown', onKey)
+ return () => {
+ window.removeEventListener('mousedown', onDown)
+ window.removeEventListener('keydown', onKey)
+ }
+ }, [open])
+
+ return (
+ <>
+ <button
+ ref={btnRef}
+ className={`tool ${open || editing ? 'tool--on' : ''}`}
+ onClick={() => setOpen(!open)}
+ title={t('shared.tools.buttonTitle')}
+ aria-expanded={open}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M12 3l9 5-9 5-9-5zM3 13l9 5 9-5M3 17.5l9 5 9-5" />
+ </svg>
+ <span className="tool__label">{t('shared.tools.buttonLabel', { count })}</span>
+ </button>
+ {open &&
+ createPortal(
+ <div
+ ref={panelRef}
+ className="net-layers card"
+ role="menu"
+ style={pos ? { left: pos.left, top: pos.top } : { left: -9999, top: 0, visibility: 'hidden' }}
+ >
+ <div className="eyebrow">{t('shared.tools.heading')}</div>
+ {keys.map((k) => {
+ const def = defs[k]
+ return (
+ <div key={k} className="net-layers__row">
+ <Checkbox
+ checked={layers[k]}
+ label={LAYER_LABELS[k]}
+ onChange={(on) => {
+ layers.setLayer(k, on)
+ if (k === 'sewer') useSewerUi.getState().setPanel(on)
+ if (k === 'water') useWaterUi.getState().setPanel(on)
+ }}
+ />
+ {!viewOnly && (
+ <span className="net-layers__actions">
+ <IconButton
+ size="sm"
+ label={t(layers.locks[k] ? 'shared.tools.unlock' : 'shared.tools.lock', { layer: LAYER_LABELS[k] })}
+ title={layers.locks[k] ? t('shared.tools.lockedTitle') : t('shared.tools.lockTitle')}
+ className={layers.locks[k] ? 'net-layers__lock net-layers__lock--on' : 'net-layers__lock'}
+ aria-pressed={layers.locks[k]}
+ onClick={() => layers.setLock(k, !layers.locks[k])}
+ >
+ <LockIcon locked={layers.locks[k]} />
+ </IconButton>
+ {def && (
+ <IconButton
+ size="sm"
+ label={t('shared.tools.edit', { layer: LAYER_LABELS[k] })}
+ title={t('shared.tools.edit', { layer: LAYER_LABELS[k] })}
+ className={editing === k ? 'net-layers__edit net-layers__edit--on' : 'net-layers__edit'}
+ onClick={() => {
+ if (editing === k) stopEdit()
+ else {
+ if (layers.locks[k]) layers.setLock(k, false)
+ startEdit(k)
+ }
+ setOpen(false)
+ }}
+ >
+ <PencilIcon />
+ </IconButton>
+ )}
+ </span>
+ )}
+ </div>
+ )
+ })}
+ <span className="muted net-layers__note">{t('shared.tools.note')}</span>
+ </div>,
+ document.body,
+ )}
+ <NetworkEditBar />
+ </>
+ )
+}
+
+export function NetworkEditBar() {
+ const { t } = useTranslation('networks')
+ const editing = useNetworkEdit((s) => s.editing)
+ const def = useNetworkEdit((s) => (s.editing ? s.defs[s.editing] : undefined))
+ const viewOnly = useViewOnly()
+
+ useEffect(() => {
+ if (viewOnly && editing) stopEdit()
+ }, [viewOnly, editing])
+
+ useEffect(() => {
+ if (!editing) return
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape' || isTyping(e)) return
+ const st = useNetworkEdit.getState()
+ const h = st.editing ? st.defs[st.editing] : undefined
+ if (h?.onEscape?.()) return
+ stopEdit()
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [editing])
+
+ if (!editing || !def || viewOnly) return null
+ const Tools = def.Tools
+ return createPortal(
+ <div className="net-editbar card" role="toolbar" aria-label={t('shared.tools.editing', { layer: LAYER_LABELS[editing] })}>
+ <span className="net-editbar__title">{LAYER_LABELS[editing]}</span>
+ <Tools />
+ <IconButton size="sm" label={t('shared.tools.exitLabel')} title={t('shared.tools.exitTitle')} onClick={stopEdit}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ </div>,
+ document.body,
+ )
+}
diff --git a/src/networks/SewerLayer.tsx b/src/networks/SewerLayer.tsx
new file mode 100644
index 0000000..7baa9da
--- /dev/null
+++ b/src/networks/SewerLayer.tsx
@@ -0,0 +1,448 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useNetworkEdit } from './registry'
+import { t } from '../i18n'
+import { fmtPct } from './labels'
+import { Arrow, Circle, Group, Layer, Line, Rect, Text } from 'react-konva'
+import type Konva from 'konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { formatLength, type Plan, type Point, type SewerNode, type SewerPipe } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { detectRooms } from '../stats/rooms'
+import { useLayers } from './layers'
+import { useSewerUi } from './sewerStore'
+import { findTarget, type SewerTarget } from './sewerSnap'
+import { traceClick } from './sewerTrace'
+import { DEFAULT_SEPTIC, deleteNode, deletePipe, fixtureLabels, moveNode, nodeById, nodeKindLabels, pipeSlope, sewerOf } from './sewerModel'
+import { septicCorners } from './sewerCalc'
+
+export const PIPE_COLOR = '#cf5f1f'
+const PIPE_DARK = '#7a3210'
+const HALO = 'rgba(242, 107, 29, 0.28)'
+const INK = '#2b2d33'
+const FONT = 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif'
+
+type Props = {
+ plan: Plan
+ scale: number
+ viewRot: number
+ worldPointer: () => Point | null
+ interactive: boolean
+}
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+const pipeWidth = (p: SewerPipe, scale: number) => Math.max(p.diameter, (p.diameter >= 110 ? 3 : 1.6) / scale)
+
+export const pipeCaption = (p: SewerPipe) =>
+ `Ø${p.diameter} · ${fmtPct(pipeSlope(p))}${p.location === 'outside' ? ` · ${t('networks:shared.ui.outsideLower')}` : ''}`
+
+function Tag({ at, text, scale, viewRot, strong }: { at: Point; text: string; scale: number; viewRot: number; strong?: boolean }) {
+ const w = text.length * 6.4 + 12
+ return (
+ <Group x={at.x} y={at.y} scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <Rect x={-w / 2} y={-22} width={w} height={18} cornerRadius={4} fill={strong ? PIPE_DARK : '#ffffff'} stroke={PIPE_COLOR} strokeWidth={1} />
+ <Text x={-w / 2} y={-19} width={w} align="center" text={text} fontSize={11} fontFamily={FONT} fill={strong ? '#ffffff' : INK} />
+ </Group>
+ )
+}
+
+function NodeIcon({ node, selected }: { node: SewerNode; selected: boolean }) {
+ const halo = selected ? <Circle radius={12} fill={HALO} /> : null
+ switch (node.kind) {
+ case 'fixture':
+ return (
+ <>
+ {halo}
+ <Circle radius={6.5} fill="#ffffff" stroke={PIPE_COLOR} strokeWidth={2} />
+ <Circle radius={2.6} fill={PIPE_COLOR} />
+ </>
+ )
+ case 'riser':
+ return (
+ <>
+ {halo}
+ <Circle radius={8.5} fill="#ffffff" stroke={PIPE_DARK} strokeWidth={2} />
+ <Circle radius={4.5} fill={PIPE_COLOR} />
+ </>
+ )
+ case 'cleanout':
+ return (
+ <>
+ {halo}
+ <Rect x={-6} y={-6} width={12} height={12} fill="#ffffff" stroke={PIPE_DARK} strokeWidth={1.8} />
+ <Line points={[-6, -6, 6, 6]} stroke={PIPE_DARK} strokeWidth={1.4} />
+ <Line points={[-6, 6, 6, -6]} stroke={PIPE_DARK} strokeWidth={1.4} />
+ </>
+ )
+ case 'outlet':
+ return (
+ <>
+ {halo}
+ <Rect x={-6} y={-6} width={12} height={12} rotation={45} fill={PIPE_DARK} stroke="#ffffff" strokeWidth={1.5} />
+ </>
+ )
+ case 'septic':
+ return halo
+ default:
+ return (
+ <>
+ {halo}
+ <Circle radius={3.8} fill={PIPE_COLOR} stroke="#ffffff" strokeWidth={1} />
+ </>
+ )
+ }
+}
+
+function Septic({ node, scale, viewRot, selected }: { node: SewerNode; scale: number; viewRot: number; selected: boolean }) {
+ const w = node.w ?? DEFAULT_SEPTIC.w
+ const d = node.d ?? DEFAULT_SEPTIC.d
+ const hatch = Math.min(w, d) * 0.22
+ return (
+ <>
+ <Group x={node.x} y={node.y} rotation={node.rotationDeg ?? 0} listening={false}>
+ <Rect
+ x={-w / 2}
+ y={-d / 2}
+ width={w}
+ height={d}
+ cornerRadius={Math.min(w, d) / 2}
+ fill="rgba(207, 95, 31, 0.12)"
+ stroke={selected ? PIPE_DARK : PIPE_COLOR}
+ strokeWidth={(selected ? 2.5 : 1.6) / scale}
+ />
+ <Circle x={-w / 4} radius={hatch} fill="#ffffff" stroke={PIPE_COLOR} strokeWidth={1.2 / scale} />
+ <Circle x={w / 4} radius={hatch} fill="#ffffff" stroke={PIPE_COLOR} strokeWidth={1.2 / scale} />
+ </Group>
+ <Group x={node.x} y={node.y} scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <Text x={-80} y={(Math.abs(Math.sin((((node.rotationDeg ?? 0) + viewRot) * Math.PI) / 180)) * w / 2 + Math.abs(Math.cos((((node.rotationDeg ?? 0) + viewRot) * Math.PI) / 180)) * d / 2) * scale + 4} width={160} align="center" text={node.model || node.label || nodeKindLabels.septic} fontSize={11} fontStyle="600" fontFamily={FONT} fill={PIPE_DARK} />
+ </Group>
+ </>
+ )
+}
+
+export function SewerLayer(props: Props) {
+ const on = useLayers((s) => s.sewer)
+ return on ? <SewerLayerInner {...props} /> : null
+}
+
+function SewerLayerInner({ plan, scale, viewRot, worldPointer, interactive }: Props) {
+ const editing = useNetworkEdit((st) => st.editing === 'sewer') && interactive
+ const toolOn = useSewerUi((s) => s.tool)
+ const tool = toolOn && editing
+ const selected = useSewerUi((s) => s.selected)
+ const hover = useSewerUi((s) => s.hover)
+ const select = useSewerUi((s) => s.select)
+ const setHover = useSewerUi((s) => s.setHover)
+ const nextKind = useSewerUi((s) => s.nextKind)
+ const planTool = usePlanStore((s) => s.tool)
+ const commit = usePlanStore((s) => s.commit)
+ const draft = useSewerUi((s) => s.draft)
+ const setDraft = useSewerUi((s) => s.setDraft)
+ const [cursor, setCursor] = useState<SewerTarget | null>(null)
+ const [preview, setPreview] = useState<Plan | null>(null)
+ const layerRef = useRef<Konva.Layer>(null)
+
+ const shown = preview ?? plan
+ const s = sewerOf(shown)
+ const walls = plan.walls
+ const footprints = useMemo(() => detectRooms({ ...plan, walls } as Plan).buildings.map((b) => b.footprint), [walls])
+ const editable = editing && !tool && planTool === 'select'
+
+ useEffect(() => {
+ if (!tool) {
+ setDraft(null)
+ setCursor(null)
+ }
+ }, [tool, setDraft])
+
+ useEffect(() => {
+ if (draft && !nodeById(sewerOf(plan), draft)) setDraft(null)
+ }, [plan, draft, setDraft])
+
+ useEffect(
+ () =>
+ usePlanStore.subscribe((st, prev) => {
+ const picked = st.selectedWallId || st.selectedOpeningId || st.selectedFurnitureId || st.selectedZoneId || st.group
+ const was = prev.selectedWallId || prev.selectedOpeningId || prev.selectedFurnitureId || prev.selectedZoneId || prev.group
+ if (picked && picked !== was) useSewerUi.getState().select(null)
+ }),
+ [],
+ )
+
+ useEffect(() => {
+ const stage = layerRef.current?.getStage()
+ if (!stage) return
+ const onClick = (e: KonvaEventObject<MouseEvent>) => {
+ if (e.target === stage) useSewerUi.getState().select(null)
+ }
+ stage.on('click.sewer tap.sewer', onClick)
+ return () => {
+ stage.off('click.sewer tap.sewer')
+ }
+ }, [])
+
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (isTyping(e) || e.metaKey || e.ctrlKey) return
+ const ui = useSewerUi.getState()
+ if (e.key === 'Enter' && draft) {
+ setDraft(null)
+ return
+ }
+ if ((e.key === 'Delete' || e.key === 'Backspace') && ui.selected && editing) {
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ e.preventDefault()
+ const ref = ui.selected
+ commit(ref.kind === 'node' ? deleteNode(current, ref.id) : deletePipe(current, ref.id))
+ ui.select(null)
+ }
+ }
+ window.addEventListener('keydown', down)
+ return () => window.removeEventListener('keydown', down)
+ }, [draft, editing, commit, setDraft])
+
+ const draftNode = draft ? nodeById(s, draft) : undefined
+
+ const targetAt = (shift: boolean) => {
+ const raw = worldPointer()
+ const current = usePlanStore.getState().plan
+ if (!raw || !current) return null
+ return findTarget(current, raw, scale, draftNode ? { x: draftNode.x, y: draftNode.y } : null, shift)
+ }
+
+ const onToolMove = (e: KonvaEventObject<MouseEvent>) => {
+ e.cancelBubble = true
+ const t = targetAt(e.evt.shiftKey)
+ setCursor(t)
+ const h = t?.kind === 'pipe' ? ({ kind: 'pipe', id: t.id } as const) : t?.kind === 'node' ? ({ kind: 'node', id: t.id } as const) : null
+ if (h?.id !== hover?.id) setHover(h)
+ }
+
+ const onToolClick = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ e.cancelBubble = true
+ if ('button' in e.evt && e.evt.button !== 0) return
+ const current = usePlanStore.getState().plan
+ const t = targetAt(e.evt.shiftKey)
+ if (!current || !t) return
+ const step = traceClick(current, draft, t, nextKind, footprints)
+ if (step.plan !== current) commit(step.plan)
+ setDraft(step.draft)
+ }
+
+ const nodeDrag = (n: SewerNode) => (e: KonvaEventObject<DragEvent>) => {
+ const raw = { x: e.target.x(), y: e.target.y() }
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ const t = findTarget({ ...current, networks: { ...current.networks, sewer: { ...sewerOf(current), pipes: [] } } }, raw, scale, null, false, n.id)
+ const pt = t.kind === 'node' ? raw : t.point
+ e.target.position(pt)
+ setPreview(moveNode(current, n.id, pt))
+ }
+
+ const nodeDragEnd = (n: SewerNode) => (e: KonvaEventObject<DragEvent>) => {
+ const current = usePlanStore.getState().plan
+ setPreview(null)
+ if (!current) return
+ commit(moveNode(current, n.id, { x: e.target.x(), y: e.target.y() }))
+ }
+
+ const pickPipe = (p: SewerPipe) => (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ e.cancelBubble = true
+ if (!editing) {
+ setHover({ kind: 'pipe', id: p.id })
+ return
+ }
+ usePlanStore.getState().selectWall(null)
+ select({ kind: 'pipe', id: p.id })
+ }
+
+ const cursorPoint = cursor?.point ?? null
+ const hoverPipe = hover?.kind === 'pipe' ? s.pipes.find((p) => p.id === hover.id) : undefined
+ const selPipe = selected?.kind === 'pipe' ? s.pipes.find((p) => p.id === selected.id) : undefined
+ const labelPipes = [hoverPipe, selPipe !== hoverPipe ? selPipe : undefined].filter(Boolean) as SewerPipe[]
+
+ return (
+ <Layer ref={layerRef}>
+ {tool && (
+ <Rect
+ x={-1e7}
+ y={-1e7}
+ width={2e7}
+ height={2e7}
+ fill="rgba(0,0,0,0.001)"
+ onMouseMove={onToolMove}
+ onMouseDown={(e) => {
+ if (e.evt.button === 0 && !e.evt.shiftKey) return
+ e.cancelBubble = true
+ }}
+ onClick={onToolClick}
+ onTap={onToolClick}
+ onDblClick={(e) => {
+ e.cancelBubble = true
+ setDraft(null)
+ }}
+ onContextMenu={(e) => {
+ e.evt.preventDefault()
+ e.cancelBubble = true
+ setDraft(null)
+ }}
+ onMouseLeave={() => setCursor(null)}
+ />
+ )}
+ {s.nodes.filter((n) => n.kind === 'septic').map((n) => (
+ <Septic key={`sep-${n.id}`} node={n} scale={scale} viewRot={viewRot} selected={selected?.id === n.id} />
+ ))}
+ {s.pipes.map((p) => {
+ const a = nodeById(s, p.from)
+ const b = nodeById(s, p.to)
+ if (!a || !b) return null
+ const len = Math.hypot(b.x - a.x, b.y - a.y)
+ const ux = (b.x - a.x) / (len || 1)
+ const uy = (b.y - a.y) / (len || 1)
+ const mx = (a.x + b.x) / 2
+ const my = (a.y + b.y) / 2
+ const arrow = 7 / scale
+ const w = pipeWidth(p, scale)
+ const on = selected?.id === p.id || hover?.id === p.id
+ return (
+ <Group key={p.id}>
+ {on && <Line points={[a.x, a.y, b.x, b.y]} stroke={HALO} strokeWidth={w + 10 / scale} lineCap="round" listening={false} />}
+ <Line
+ points={[a.x, a.y, b.x, b.y]}
+ stroke={PIPE_COLOR}
+ strokeWidth={w}
+ lineCap={p.location === 'outside' ? 'butt' : 'round'}
+ dash={p.location === 'outside' ? [Math.max(w * 2.4, 10 / scale), Math.max(w * 1.3, 6 / scale)] : undefined}
+ hitStrokeWidth={Math.max(w, 12 / scale)}
+ listening={!tool}
+ onClick={pickPipe(p)}
+ onTap={pickPipe(p)}
+ onMouseEnter={() => setHover({ kind: 'pipe', id: p.id })}
+ onMouseLeave={() => useSewerUi.getState().hover?.id === p.id && setHover(null)}
+ />
+ {len * scale > 26 && (
+ <Arrow
+ points={[mx - ux * arrow, my - uy * arrow, mx + ux * arrow, my + uy * arrow]}
+ stroke={PIPE_DARK}
+ fill={PIPE_DARK}
+ strokeWidth={1.4 / scale}
+ pointerLength={5 / scale}
+ pointerWidth={5 / scale}
+ listening={false}
+ />
+ )}
+ </Group>
+ )
+ })}
+ {s.nodes.map((n) => {
+ const isSel = selected?.id === n.id
+ const size = n.kind === 'septic' ? { w: n.w ?? DEFAULT_SEPTIC.w, d: n.d ?? DEFAULT_SEPTIC.d } : null
+ return (
+ <Group
+ key={n.id}
+ x={n.x}
+ y={n.y}
+ listening={editable || (!editing && n.kind !== 'junction')}
+ draggable={editable}
+ onMouseDown={(e) => {
+ if (!editable || e.evt.button !== 0) return
+ e.cancelBubble = true
+ usePlanStore.getState().selectWall(null)
+ select({ kind: 'node', id: n.id })
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ }}
+ onTap={(e) => {
+ e.cancelBubble = true
+ if (!editing) setHover({ kind: 'node', id: n.id })
+ }}
+ onDragMove={nodeDrag(n)}
+ onDragEnd={nodeDragEnd(n)}
+ onMouseEnter={(e) => {
+ setHover({ kind: 'node', id: n.id })
+ const st = e.target.getStage()
+ if (st && editable) st.container().style.cursor = 'move'
+ }}
+ onMouseLeave={(e) => {
+ if (useSewerUi.getState().hover?.id === n.id) setHover(null)
+ const st = e.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ >
+ {size ? (
+ <Rect offsetX={size.w / 2} offsetY={size.d / 2} width={size.w} height={size.d} rotation={n.rotationDeg ?? 0} fill="rgba(0,0,0,0.001)" />
+ ) : (
+ <Circle radius={12 / scale} fill="rgba(0,0,0,0.001)" />
+ )}
+ <Group scaleX={1 / scale} scaleY={1 / scale} listening={false}>
+ <NodeIcon node={n} selected={isSel} />
+ </Group>
+ </Group>
+ )
+ })}
+ {s.nodes
+ .filter((n) => n.kind === 'septic' && selected?.id === n.id)
+ .map((n) => (
+ <Line key={`sc-${n.id}`} points={septicCorners(n).flatMap((p) => [p.x, p.y])} closed stroke={HALO} strokeWidth={8 / scale} listening={false} />
+ ))}
+ {labelPipes.map((p) => {
+ const a = nodeById(s, p.from)
+ const b = nodeById(s, p.to)
+ if (!a || !b) return null
+ return (
+ <Tag
+ key={`t-${p.id}`}
+ at={{ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }}
+ text={`${pipeCaption(p)} · ${formatLength(Math.hypot(b.x - a.x, b.y - a.y))}`}
+ scale={scale}
+ viewRot={viewRot}
+ strong={selected?.id === p.id}
+ />
+ )
+ })}
+ {hover?.kind === 'node' &&
+ (() => {
+ const n = nodeById(s, hover.id)
+ if (!n || n.kind === 'septic') return null
+ const text = n.label || (n.kind === 'fixture' && n.fixture ? fixtureLabels[n.fixture] : nodeKindLabels[n.kind])
+ return <Tag at={{ x: n.x, y: n.y - 8 / scale }} text={text} scale={scale} viewRot={viewRot} />
+ })()}
+ {tool && draftNode && cursorPoint && (
+ <>
+ <Line
+ points={[draftNode.x, draftNode.y, cursorPoint.x, cursorPoint.y]}
+ stroke={PIPE_COLOR}
+ strokeWidth={2 / scale}
+ dash={[6 / scale, 4 / scale]}
+ listening={false}
+ />
+ <Tag
+ at={{ x: (draftNode.x + cursorPoint.x) / 2, y: (draftNode.y + cursorPoint.y) / 2 }}
+ text={formatLength(Math.hypot(cursorPoint.x - draftNode.x, cursorPoint.y - draftNode.y))}
+ scale={scale}
+ viewRot={viewRot}
+ />
+ </>
+ )}
+ {tool && cursorPoint && (
+ <Circle
+ x={cursorPoint.x}
+ y={cursorPoint.y}
+ radius={(cursor?.kind === 'point' ? 4 : 8) / scale}
+ fill={cursor?.kind === 'point' ? PIPE_COLOR : HALO}
+ stroke={PIPE_COLOR}
+ strokeWidth={1.5 / scale}
+ listening={false}
+ />
+ )}
+ {tool && cursor?.kind === 'fixture' && (
+ <Tag at={{ x: cursor.point.x, y: cursor.point.y - 10 / scale }} text={t('networks:sewer.layer.connectFixture')} scale={scale} viewRot={viewRot} />
+ )}
+ </Layer>
+ )
+}
diff --git a/src/networks/SewerPanel.tsx b/src/networks/SewerPanel.tsx
new file mode 100644
index 0000000..ea6a6cb
--- /dev/null
+++ b/src/networks/SewerPanel.tsx
@@ -0,0 +1,456 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { fmtNum, lang, t as tr } from '../i18n'
+import { fmtPct, unitLabel } from './labels'
+import { formatLength, formatMoney, type Plan, type SewerDiameter, type SewerFixture, type SewerNode, type SewerPipe } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { useCatalog } from '../estimate/catalog'
+import { LengthField } from '../ui/LengthField'
+import { Badge, Button, IconButton, Input, Segmented } from '../ui'
+import { computeSewer, type SewerCalc, type SewerRef } from './sewerCalc'
+import { itemSum, priceAll } from './pricing'
+import {
+ DEFAULT_FLOOR_LEVEL,
+ DEFAULT_RISER_HEIGHT,
+ DEFAULT_SEPTIC,
+ SEPTIC_TO_BOUNDARY_MIN,
+ SEPTIC_TO_HOUSE_MIN,
+ defaultSlope,
+ deleteNode,
+ deletePipe,
+ fixtureLabels,
+ minSlope,
+ nodeById,
+ nodeKindLabels,
+ pipeLength,
+ pipeSlope,
+ reversePipe,
+ sewerOf,
+ updateNode,
+ updatePipe,
+ withSewer,
+} from './sewerModel'
+import { useSewerUi } from './sewerStore'
+import './networks.css'
+
+const fmt = (v: number, d = 2) => fmtNum(v, d)
+const fmtM = (mm: number) => `${fmt(mm / 1000)} ${tr('common:units.m')}`
+const level = (mm: number) => `${mm > 0 ? '+' : mm < 0 ? '−' : ''}${fmt(Math.abs(mm) / 1000)} ${tr('common:units.m')}`
+
+function NumField({ value, suffix, onCommit, min = 0 }: { value: number; suffix: string; onCommit: (v: number) => void; min?: number }) {
+ const [draft, setDraft] = useState<string | null>(null)
+ const commit = () => {
+ if (draft === null) return
+ const v = Number(draft.replace(',', '.').replace(/[^\d.-]/g, ''))
+ setDraft(null)
+ if (Number.isFinite(v) && v > min && v !== value) onCommit(v)
+ }
+ return (
+ <Input
+ size="sm"
+ suffix={suffix}
+ value={draft ?? (lang() === 'ru' ? String(value).replace('.', ',') : String(value))}
+ onChange={(e) => setDraft(e.target.value)}
+ onFocus={(e) => e.target.select()}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur()
+ if (e.key === 'Escape') setDraft(null)
+ }}
+ />
+ )
+}
+
+export function useSewerSelection(plan: Plan | null): SewerRef | null {
+ const selected = useSewerUi((s) => s.selected)
+ if (!plan || !selected) return null
+ const s = sewerOf(plan)
+ const exists = selected.kind === 'node' ? s.nodes.some((n) => n.id === selected.id) : s.pipes.some((p) => p.id === selected.id)
+ return exists ? selected : null
+}
+
+function Close() {
+ const { t } = useTranslation('networks')
+ const select = useSewerUi((s) => s.select)
+ return (
+ <IconButton label={t('shared.ui.close')} size="sm" className="inspector__close" onClick={() => select(null)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ )
+}
+
+export function SewerInspector({ plan, sel }: { plan: Plan; sel: SewerRef }) {
+ const calc = useMemo(() => computeSewer(plan), [plan])
+ const s = sewerOf(plan)
+ if (sel.kind === 'pipe') {
+ const p = s.pipes.find((x) => x.id === sel.id)
+ return p ? <PipeInspector plan={plan} pipe={p} calc={calc} /> : null
+ }
+ const n = s.nodes.find((x) => x.id === sel.id)
+ return n ? <NodeInspector plan={plan} node={n} calc={calc} /> : null
+}
+
+function Warnings({ calc, refId }: { calc: SewerCalc; refId?: string }) {
+ const list = refId ? calc.warnings.filter((w) => w.ref?.id === refId) : calc.warnings
+ if (!list.length) return null
+ return (
+ <div className="net-warnings">
+ {list.map((w, i) => (
+ <div key={i} className="layout-hint layout-hint--warn">
+ {w.text}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function PipeInspector({ plan, pipe, calc }: { plan: Plan; pipe: SewerPipe; calc: SewerCalc }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((st) => st.commit)
+ const s = sewerOf(plan)
+ const len = pipeLength(s, pipe)
+ const slope = pipeSlope(pipe)
+ const min = minSlope(pipe.diameter, pipe.location)
+ const lv = calc.pipeLevel[pipe.id]
+ const set = (patch: Partial<SewerPipe>) => commit(updatePipe(plan, pipe.id, patch))
+ const from = nodeById(s, pipe.from)
+ const to = nodeById(s, pipe.to)
+ const name = (n?: SewerNode) => (n ? `${n.kind === 'fixture' && n.fixture ? fixtureLabels[n.fixture] : nodeKindLabels[n.kind]} ${n.id}` : '—')
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <Close />
+ <div className="eyebrow">{t('sewer.panel.eyebrowPipe')}</div>
+ <div className="inspector__title">
+ Ø{pipe.diameter} · {fmtPct(slope)}
+ </div>
+ </div>
+ <div className="form">
+ <div className="form__row">
+ <span>{t('shared.ui.diameter')}</span>
+ <Segmented
+ size="sm"
+ value={String(pipe.diameter)}
+ options={[50, 110, 160].map((d) => ({ value: String(d), label: `Ø${d}` }))}
+ onChange={(v) => {
+ const d = Number(v) as SewerDiameter
+ set({ diameter: d, slope: pipe.slope === undefined || pipe.slope === defaultSlope(pipe.diameter, pipe.location) ? defaultSlope(d, pipe.location) : pipe.slope })
+ }}
+ />
+ </div>
+ <label className="form__row">
+ <span>{t('sewer.panel.slope')}</span>
+ <NumField value={slope} suffix="%" onCommit={(v) => set({ slope: Math.min(100, v) })} />
+ </label>
+ <div className="form__row">
+ <span>{t('shared.ui.where')}</span>
+ <Segmented
+ size="sm"
+ value={pipe.location}
+ options={[
+ { value: 'inside', label: t('shared.ui.inside') },
+ { value: 'outside', label: t('shared.ui.outside') },
+ ]}
+ onChange={(location) => set({ location, slope: pipe.slope === defaultSlope(pipe.diameter, pipe.location) ? defaultSlope(pipe.diameter, location) : pipe.slope })}
+ />
+ </div>
+ {pipe.location === 'outside' && (
+ <label className="form__row">
+ <span>{t('sewer.panel.depthStart')}</span>
+ <LengthField value={lv ? Math.round(-lv.start) : (pipe.depth ?? 0)} min={0} onCommit={(depth) => set({ depth })} />
+ </label>
+ )}
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('shared.ui.length')}</dt>
+ <dd>{formatLength(len)}</dd>
+ <dt>{t('sewer.panel.drop')}</dt>
+ <dd>{lv ? `${Math.round(lv.drop)} ${t('common:units.mm')}` : '—'}</dd>
+ {lv && (
+ <>
+ <dt>{t('sewer.panel.invert')}</dt>
+ <dd>
+ {level(lv.start)} → {level(lv.end)}
+ </dd>
+ </>
+ )}
+ <dt>{t('sewer.panel.slopeNorm')}</dt>
+ <dd>
+ {slope + 1e-9 < min ? <Badge tone="warn">{t('sewer.panel.min', { v: fmtPct(min) })}</Badge> : <Badge tone="ok">≥ {fmtPct(min)}</Badge>}
+ </dd>
+ <dt>{t('sewer.panel.flow')}</dt>
+ <dd>
+ {name(from)} → {name(to)}
+ </dd>
+ </dl>
+ <Warnings calc={calc} refId={pipe.id} />
+ <div className="inspector__actions">
+ <Button size="sm" onClick={() => commit(reversePipe(plan, pipe.id))}>
+ {t('sewer.panel.reverse')}
+ </Button>
+ <Button size="sm" variant="danger" onClick={() => commit(deletePipe(plan, pipe.id))}>
+ {t('shared.ui.delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('sewer.panel.pipeHint', { floor: level(calc.floorLevel) })}</p>
+ </aside>
+ )
+}
+
+const KIND_OPTIONS: SewerNode['kind'][] = ['fixture', 'junction', 'cleanout', 'riser', 'outlet', 'septic']
+
+function NodeInspector({ plan, node, calc }: { plan: Plan; node: SewerNode; calc: SewerCalc }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((st) => st.commit)
+ const set = (patch: Partial<SewerNode>) => commit(updateNode(plan, node.id, patch))
+ const lvl = calc.nodeLevel[node.id]
+ const septic = calc.septics.find((x) => x.nodeId === node.id)
+ const outlet = calc.outlets.find((x) => x.nodeId === node.id)
+ const [model, setModel] = useState<string | null>(null)
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <Close />
+ <div className="eyebrow">{t('sewer.panel.eyebrowNode', { kind: nodeKindLabels[node.kind].toLowerCase() })}</div>
+ <div className="inspector__title">
+ {node.kind === 'septic' ? node.model || nodeKindLabels.septic : node.kind === 'fixture' && node.fixture ? fixtureLabels[node.fixture] : node.id}
+ </div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('shared.ui.type')}</span>
+ <select
+ className="select form__select"
+ value={node.kind}
+ onChange={(e) => {
+ const kind = e.target.value as SewerNode['kind']
+ const extra: Partial<SewerNode> =
+ kind === 'septic' ? { w: node.w ?? DEFAULT_SEPTIC.w, d: node.d ?? DEFAULT_SEPTIC.d, rotationDeg: node.rotationDeg ?? 0 } : {}
+ set({ kind, ...extra, ...(kind === 'fixture' && !node.fixture ? { fixture: 'sink' as SewerFixture } : {}) })
+ }}
+ >
+ {KIND_OPTIONS.map((k) => (
+ <option key={k} value={k}>
+ {nodeKindLabels[k]}
+ </option>
+ ))}
+ </select>
+ </label>
+ {node.kind === 'fixture' && (
+ <label className="form__row">
+ <span>{t('shared.ui.fixture')}</span>
+ <select className="select form__select" value={node.fixture ?? ''} onChange={(e) => set({ fixture: e.target.value as SewerFixture })}>
+ {(Object.keys(fixtureLabels) as SewerFixture[]).map((f) => (
+ <option key={f} value={f}>
+ {fixtureLabels[f]}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {node.kind === 'riser' && (
+ <label className="form__row">
+ <span>{t('sewer.panel.riserHeight')}</span>
+ <LengthField value={node.height ?? DEFAULT_RISER_HEIGHT} min={100} onCommit={(height) => set({ height })} />
+ </label>
+ )}
+ {node.kind === 'septic' && (
+ <>
+ <label className="form__row">
+ <span>{t('shared.ui.model')}</span>
+ <Input
+ size="sm"
+ value={model ?? node.model ?? ''}
+ placeholder={t('sewer.panel.modelPlaceholder')}
+ onChange={(e) => setModel(e.target.value)}
+ onBlur={() => {
+ if (model === null) return
+ const v = model.trim()
+ setModel(null)
+ if (v !== (node.model ?? '')) set({ model: v || undefined })
+ }}
+ onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
+ />
+ </label>
+ <label className="form__row">
+ <span>{t('shared.ui.length')}</span>
+ <LengthField value={node.w ?? DEFAULT_SEPTIC.w} min={300} onCommit={(w) => set({ w })} />
+ </label>
+ <label className="form__row">
+ <span>{t('sewer.panel.width')}</span>
+ <LengthField value={node.d ?? DEFAULT_SEPTIC.d} min={300} onCommit={(d) => set({ d })} />
+ </label>
+ <div className="form__row">
+ <span>{t('sewer.panel.rotation')}</span>
+ <Segmented
+ size="sm"
+ value={String(((Math.round(node.rotationDeg ?? 0) % 360) + 360) % 360)}
+ options={['0', '90', '180', '270'].map((v) => ({ value: v, label: `${v}°` }))}
+ onChange={(v) => set({ rotationDeg: Number(v) })}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ <dl className="props props--compact">
+ {lvl !== undefined && (
+ <>
+ <dt>{t('sewer.panel.invertLevel')}</dt>
+ <dd>{level(lvl)}</dd>
+ </>
+ )}
+ {outlet && (
+ <>
+ <dt>{t('sewer.panel.outletDepth')}</dt>
+ <dd>{fmtM(outlet.depth)}</dd>
+ </>
+ )}
+ {septic && (
+ <>
+ <dt>{t('sewer.panel.inletDepth')}</dt>
+ <dd>{septic.depth !== null ? fmtM(septic.depth) : '—'}</dd>
+ <dt>{t('sewer.panel.toFoundation')}</dt>
+ <dd>
+ {septic.toHouse === null ? '—' : <Badge tone={septic.toHouse < SEPTIC_TO_HOUSE_MIN ? 'warn' : 'ok'}>{fmtM(septic.toHouse)}</Badge>}
+ </dd>
+ <dt>{t('sewer.panel.toBoundary')}</dt>
+ <dd>
+ {septic.toBoundary === null ? '—' : <Badge tone={septic.toBoundary < SEPTIC_TO_BOUNDARY_MIN ? 'warn' : 'ok'}>{fmtM(septic.toBoundary)}</Badge>}
+ </dd>
+ </>
+ )}
+ <dt>{t('shared.ui.center')}</dt>
+ <dd>
+ {Math.round(node.x)}, {Math.round(node.y)}
+ </dd>
+ </dl>
+ {septic && (
+ <p className="hint">
+ {t('sewer.panel.septicNorms', { house: fmtM(SEPTIC_TO_HOUSE_MIN), boundary: fmtM(SEPTIC_TO_BOUNDARY_MIN) })}
+ </p>
+ )}
+ <Warnings calc={calc} refId={node.id} />
+ <div className="inspector__actions">
+ <span />
+ <Button size="sm" variant="danger" onClick={() => commit(deleteNode(plan, node.id))}>
+ {t('shared.ui.delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('sewer.panel.nodeHint')}</p>
+ </aside>
+ )
+}
+
+export function SewerSummary({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('networks')
+ const catalog = useCatalog()
+ const viewOnly = useViewOnly()
+ const commit = usePlanStore((st) => st.commit)
+ const select = useSewerUi((st) => st.select)
+ const calc = useMemo(() => computeSewer(plan), [plan])
+ const s = sewerOf(plan)
+ const items = useMemo(() => priceAll(calc.items, s.materials, catalog), [calc, s.materials, catalog])
+ const total = items.reduce((acc, i) => acc + itemSum(i), 0)
+ const missing = items.filter((i) => i.price === undefined).length
+
+ return (
+ <div className="inspector__materials net-summary">
+ <div className="inspector__head">
+ <div className="eyebrow">{t('shared.ui.networks')}</div>
+ <div className="inspector__title">{t('shared.layers.sewer')}</div>
+ </div>
+ {s.pipes.length === 0 && (
+ <p className="muted">{t('sewer.summary.empty')}</p>
+ )}
+ {calc.lengths.length > 0 && (
+ <dl className="props props--compact">
+ {calc.lengths.map((l) => (
+ <div key={`${l.diameter}-${l.location}`} className="net-props__pair">
+ <dt>
+ Ø{l.diameter} {l.location === 'outside' ? t('shared.ui.outsideLower') : t('shared.ui.insideLower')}
+ </dt>
+ <dd>{fmtM(l.lengthMm)}</dd>
+ </div>
+ ))}
+ {calc.outlets.map((o) => (
+ <div key={o.nodeId} className="net-props__pair">
+ <dt>{t('sewer.summary.outletRow', { id: o.nodeId })}</dt>
+ <dd>{fmtM(o.depth)}</dd>
+ </div>
+ ))}
+ {calc.septics.map((x) => (
+ <div key={x.nodeId} className="net-props__pair">
+ <dt>{x.model ? t('sewer.summary.septicRowModel', { model: x.model }) : t('sewer.summary.septicRow')}</dt>
+ <dd>{x.depth !== null ? fmtM(x.depth) : '—'}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ {items.length > 0 && (
+ <div className="inspector__section net-items">
+ <div className="eyebrow">{t('shared.ui.materials')}</div>
+ {items.map((i) => (
+ <div key={i.key} className="net-item">
+ <div className="net-item__name">
+ {i.url ? (
+ <a href={i.url} target="_blank" rel="noreferrer">
+ {i.name}
+ </a>
+ ) : (
+ i.name
+ )}
+ {i.priceFrom && <div className="muted net-item__from">{i.priceFrom}</div>}
+ </div>
+ <div className="net-item__qty">
+ {fmt(i.buyQty)} {unitLabel(i.buyUnit)}
+ {unitLabel(i.buyUnit) !== unitLabel(i.unit) && <div className="muted">{fmt(i.qty)} {unitLabel(i.unit)}</div>}
+ </div>
+ <div className="net-item__sum">{i.price !== undefined ? formatMoney(itemSum(i)) : <span className="muted">{t('shared.ui.noPrice')}</span>}</div>
+ </div>
+ ))}
+ <div className="row total">
+ <span>{t('sewer.summary.total')}</span>
+ <strong>{formatMoney(total)}</strong>
+ </div>
+ {missing > 0 && <div className="muted">{t('shared.ui.missing', { count: missing })}</div>}
+ </div>
+ )}
+ {calc.warnings.length > 0 && (
+ <div className="inspector__section">
+ <div className="eyebrow">{t('shared.ui.warnings', { count: calc.warnings.length })}</div>
+ <div className="net-warnings">
+ {calc.warnings.map((w, i) =>
+ w.ref && !viewOnly ? (
+ <button key={i} className="layout-hint layout-hint--warn net-warning" onClick={() => select(w.ref!)}>
+ {w.text}
+ </button>
+ ) : (
+ <div key={i} className="layout-hint layout-hint--warn">
+ {w.text}
+ </div>
+ ),
+ )}
+ </div>
+ </div>
+ )}
+ {!viewOnly && (
+ <div className="inspector__section">
+ <label className="row row--center">
+ <span>{t('sewer.summary.floorAbove')}</span>
+ <LengthField
+ value={s.floorLevel ?? DEFAULT_FLOOR_LEVEL}
+ min={0}
+ onCommit={(floorLevel) => commit(withSewer(plan, (x) => ({ ...x, floorLevel })))}
+ />
+ </label>
+ </div>
+ )}
+ <p className="hint">
+ {t('sewer.summary.hint')}
+ </p>
+ </div>
+ )
+}
diff --git a/src/networks/WaterLayer.tsx b/src/networks/WaterLayer.tsx
new file mode 100644
index 0000000..1fabd46
--- /dev/null
+++ b/src/networks/WaterLayer.tsx
@@ -0,0 +1,474 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Arrow, Circle, Group, Layer, Line, Rect, Text } from 'react-konva'
+import type Konva from 'konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import { formatLength, type Plan, type Point, type WaterNode, type WaterPipe } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { detectRooms } from '../stats/rooms'
+import { showToast } from '../ui/Toast'
+import { t } from '../i18n'
+import { useLayers } from './layers'
+import { useNetworkEdit } from './registry'
+import { findTarget, type SewerTarget } from './sewerSnap'
+import { fixtureLabels } from './sewerModel'
+import { useWaterUi } from './waterStore'
+import { waterClick } from './waterTrace'
+import {
+ LINE_COLORS,
+ LINE_DARK,
+ LINE_SHORT,
+ collectorLine,
+ deleteWaterNode,
+ deleteWaterPipe,
+ moveWaterNode,
+ waterCaption,
+ waterKindLabels,
+ waterOf,
+ wNode,
+} from './waterModel'
+
+const BLUE = LINE_COLORS.cold
+const INK = '#2b2d33'
+const HALO = 'rgba(47, 111, 214, 0.25)'
+const FONT = 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif'
+
+type Props = {
+ plan: Plan
+ scale: number
+ viewRot: number
+ worldPointer: () => Point | null
+ interactive: boolean
+}
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+const pipeWidth = (p: WaterPipe, scale: number) => Math.max(p.diameter, (1 + p.diameter / 16) / scale)
+
+function Tag({ at, text, scale, viewRot, color = BLUE }: { at: Point; text: string; scale: number; viewRot: number; color?: string }) {
+ const w = text.length * 6.4 + 12
+ return (
+ <Group x={at.x} y={at.y} scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <Rect x={-w / 2} y={-24} width={w} height={18} cornerRadius={4} fill="#ffffff" stroke={color} strokeWidth={1} />
+ <Text x={-w / 2} y={-21} width={w} align="center" text={text} fontSize={11} fontFamily={FONT} fill={INK} />
+ </Group>
+ )
+}
+
+function NodeIcon({ node, selected }: { node: WaterNode; selected: boolean }) {
+ const halo = selected ? <Circle radius={13} fill={HALO} /> : null
+ const hot = node.line === 'hot' || node.kind === 'boiler'
+ const c = hot ? LINE_COLORS.hot : BLUE
+ const dark = hot ? LINE_DARK.hot : LINE_DARK.cold
+ switch (node.kind) {
+ case 'source':
+ return (
+ <>
+ {halo}
+ <Circle radius={10} fill="#ffffff" stroke={dark} strokeWidth={2.2} />
+ <Circle radius={5} fill={BLUE} />
+ </>
+ )
+ case 'entry':
+ return (
+ <>
+ {halo}
+ <Rect x={-6} y={-6} width={12} height={12} rotation={45} fill={dark} stroke="#ffffff" strokeWidth={1.5} />
+ </>
+ )
+ case 'pump':
+ return (
+ <>
+ {halo}
+ <Circle radius={9} fill="#ffffff" stroke={dark} strokeWidth={2} />
+ <Line points={[-4, -5, 6, 0, -4, 5]} closed fill={dark} />
+ </>
+ )
+ case 'filter':
+ return (
+ <>
+ {halo}
+ <Rect x={-7} y={-9} width={14} height={18} cornerRadius={3} fill="#ffffff" stroke={dark} strokeWidth={2} />
+ <Line points={[-7, 9, 7, -9]} stroke={dark} strokeWidth={1.4} />
+ </>
+ )
+ case 'boiler':
+ return (
+ <>
+ {halo}
+ <Circle radius={10} fill="#ffffff" stroke={LINE_DARK.hot} strokeWidth={2} />
+ <Line points={[-9, 0, 9, 0]} stroke={LINE_DARK.hot} strokeWidth={1.4} />
+ <Circle radius={3.5} y={4} fill={LINE_COLORS.hot} />
+ <Circle radius={3.5} y={-4} fill={BLUE} />
+ </>
+ )
+ case 'collector': {
+ const n = Math.max(2, Math.min(8, node.outputs ?? 4))
+ const w = 8 + n * 6
+ return (
+ <>
+ {halo}
+ <Rect x={-w / 2} y={-5} width={w} height={10} cornerRadius={2} fill={c} stroke="#ffffff" strokeWidth={1.2} />
+ {Array.from({ length: n }, (_, i) => (
+ <Line key={i} points={[-w / 2 + 7 + i * 6, 5, -w / 2 + 7 + i * 6, 10]} stroke={dark} strokeWidth={1.6} />
+ ))}
+ </>
+ )
+ }
+ case 'fixture':
+ return (
+ <>
+ {halo}
+ <Circle radius={6} fill="#ffffff" stroke={c} strokeWidth={2} />
+ <Circle radius={2.4} fill={c} />
+ </>
+ )
+ case 'tap_outdoor':
+ return (
+ <>
+ {halo}
+ <Line points={[-7, -6, 7, -6, 0, -6, 0, 7]} stroke={dark} strokeWidth={2.4} lineCap="round" />
+ <Circle radius={2.5} y={7} fill={BLUE} />
+ </>
+ )
+ default:
+ return (
+ <>
+ {halo}
+ <Circle radius={3.4} fill={c} stroke="#ffffff" strokeWidth={1} />
+ </>
+ )
+ }
+}
+
+export function WaterLayer(props: Props) {
+ const on = useLayers((s) => s.water)
+ return on ? <WaterLayerInner {...props} /> : null
+}
+
+function WaterLayerInner({ plan, scale, viewRot, worldPointer, interactive }: Props) {
+ const editing = useNetworkEdit((st) => st.editing === 'water') && interactive
+ const mode = useWaterUi((s) => s.mode)
+ const tool = editing && mode !== 'select'
+ const selected = useWaterUi((s) => s.selected)
+ const hover = useWaterUi((s) => s.hover)
+ const select = useWaterUi((s) => s.select)
+ const setHover = useWaterUi((s) => s.setHover)
+ const nextKind = useWaterUi((s) => s.nextKind)
+ const draft = useWaterUi((s) => s.draft)
+ const setDraft = useWaterUi((s) => s.setDraft)
+ const planTool = usePlanStore((s) => s.tool)
+ const commit = usePlanStore((s) => s.commit)
+ const [cursor, setCursor] = useState<SewerTarget | null>(null)
+ const [preview, setPreview] = useState<Plan | null>(null)
+ const layerRef = useRef<Konva.Layer>(null)
+
+ const shown = preview ?? plan
+ const w = waterOf(shown)
+ const walls = plan.walls
+ const footprints = useMemo(() => detectRooms({ ...plan, walls } as Plan).buildings.map((b) => b.footprint), [walls])
+ const editable = editing && !tool && planTool === 'select'
+
+ useEffect(() => {
+ if (!tool) {
+ setDraft(null)
+ setCursor(null)
+ }
+ }, [tool, setDraft])
+
+ useEffect(() => {
+ if (draft && !wNode(waterOf(plan), draft)) setDraft(null)
+ }, [plan, draft, setDraft])
+
+ useEffect(
+ () =>
+ usePlanStore.subscribe((st, prev) => {
+ const picked = st.selectedWallId || st.selectedOpeningId || st.selectedFurnitureId || st.selectedZoneId || st.group
+ const was = prev.selectedWallId || prev.selectedOpeningId || prev.selectedFurnitureId || prev.selectedZoneId || prev.group
+ if (picked && picked !== was) useWaterUi.getState().select(null)
+ }),
+ [],
+ )
+
+ useEffect(() => {
+ const stage = layerRef.current?.getStage()
+ if (!stage) return
+ const onClick = (e: KonvaEventObject<MouseEvent>) => {
+ if (e.target === stage) useWaterUi.getState().select(null)
+ }
+ stage.on('click.water tap.water', onClick)
+ return () => {
+ stage.off('click.water tap.water')
+ }
+ }, [])
+
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (isTyping(e) || e.metaKey || e.ctrlKey) return
+ const ui = useWaterUi.getState()
+ if (e.key === 'Enter' && ui.draft) {
+ ui.setDraft(null)
+ return
+ }
+ if ((e.key === 'Delete' || e.key === 'Backspace') && ui.selected && editing) {
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ e.preventDefault()
+ const ref = ui.selected
+ commit(ref.kind === 'node' ? deleteWaterNode(current, ref.id) : deleteWaterPipe(current, ref.id))
+ ui.select(null)
+ }
+ }
+ window.addEventListener('keydown', down)
+ return () => window.removeEventListener('keydown', down)
+ }, [editing, commit])
+
+ const draftNode = draft ? wNode(w, draft) : undefined
+
+ const targetAt = (shift: boolean) => {
+ const raw = worldPointer()
+ const current = usePlanStore.getState().plan
+ if (!raw || !current) return null
+ return findTarget(current, raw, scale, draftNode ? { x: draftNode.x, y: draftNode.y } : null, shift, undefined, waterOf(current))
+ }
+
+ const onToolMove = (e: KonvaEventObject<MouseEvent>) => {
+ e.cancelBubble = true
+ const t = targetAt(e.evt.shiftKey)
+ setCursor(t)
+ const h = t?.kind === 'pipe' ? ({ kind: 'pipe', id: t.id } as const) : t?.kind === 'node' ? ({ kind: 'node', id: t.id } as const) : null
+ if (h?.id !== hover?.id) setHover(h)
+ }
+
+ const onToolClick = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ e.cancelBubble = true
+ if ('button' in e.evt && e.evt.button !== 0) return
+ const current = usePlanStore.getState().plan
+ const t = targetAt(e.evt.shiftKey)
+ if (!current || !t || mode === 'select') return
+ const step = waterClick(current, draft, t, nextKind, mode, footprints)
+ if (step.message) showToast(step.message)
+ if (step.plan !== current) commit(step.plan)
+ setDraft(step.draft)
+ }
+
+ const nodeDrag = (n: WaterNode) => (e: KonvaEventObject<DragEvent>) => {
+ const raw = { x: e.target.x(), y: e.target.y() }
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ const t = findTarget(current, raw, scale, null, false, n.id, { nodes: [], pipes: [] })
+ const pt = t.point
+ e.target.position(pt)
+ setPreview(moveWaterNode(current, n.id, pt))
+ }
+
+ const nodeDragEnd = (n: WaterNode) => (e: KonvaEventObject<DragEvent>) => {
+ const current = usePlanStore.getState().plan
+ setPreview(null)
+ if (current) commit(moveWaterNode(current, n.id, { x: e.target.x(), y: e.target.y() }))
+ }
+
+ const pickPipe = (p: WaterPipe) => (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ e.cancelBubble = true
+ if (!editing) {
+ setHover({ kind: 'pipe', id: p.id })
+ return
+ }
+ usePlanStore.getState().selectWall(null)
+ select({ kind: 'pipe', id: p.id })
+ }
+
+ const cursorPoint = cursor?.point ?? null
+ const labelPipes = [hover, selected]
+ .filter((r, i, a) => r?.kind === 'pipe' && a.findIndex((x) => x?.id === r.id) === i)
+ .map((r) => w.pipes.find((p) => p.id === r!.id))
+ .filter(Boolean) as WaterPipe[]
+ const lineColor = mode === 'select' ? BLUE : LINE_COLORS[mode]
+ const order = (p: WaterPipe) => (p.line === 'cold' ? 0 : p.line === 'hot' ? 1 : 2)
+
+ return (
+ <Layer ref={layerRef}>
+ {tool && (
+ <Rect
+ x={-1e7}
+ y={-1e7}
+ width={2e7}
+ height={2e7}
+ fill="rgba(0,0,0,0.001)"
+ onMouseMove={onToolMove}
+ onMouseDown={(e) => {
+ if (e.evt.button === 0 && !e.evt.shiftKey) return
+ e.cancelBubble = true
+ }}
+ onClick={onToolClick}
+ onTap={onToolClick}
+ onDblClick={(e) => {
+ e.cancelBubble = true
+ setDraft(null)
+ }}
+ onContextMenu={(e) => {
+ e.evt.preventDefault()
+ e.cancelBubble = true
+ setDraft(null)
+ }}
+ onMouseLeave={() => setCursor(null)}
+ />
+ )}
+ {[...w.pipes].sort((a, b) => order(a) - order(b)).map((p) => {
+ const a = wNode(w, p.from)
+ const b = wNode(w, p.to)
+ if (!a || !b) return null
+ const len = Math.hypot(b.x - a.x, b.y - a.y)
+ const ux = (b.x - a.x) / (len || 1)
+ const uy = (b.y - a.y) / (len || 1)
+ const shift = p.line === 'hot' ? 1 : p.line === 'recirc' ? 2 : 0
+ const off = (shift * 4) / scale
+ const ax = a.x - uy * off
+ const ay = a.y + ux * off
+ const bx = b.x - uy * off
+ const by = b.y + ux * off
+ const mx = (ax + bx) / 2
+ const my = (ay + by) / 2
+ const wd = pipeWidth(p, scale)
+ const on = selected?.id === p.id || hover?.id === p.id
+ const dash =
+ p.line === 'recirc'
+ ? [4 / scale, 3 / scale]
+ : p.location === 'outside'
+ ? [Math.max(wd * 2.4, 10 / scale), Math.max(wd * 1.3, 6 / scale)]
+ : undefined
+ const arrow = 6 / scale
+ return (
+ <Group key={p.id}>
+ {on && <Line points={[ax, ay, bx, by]} stroke={HALO} strokeWidth={wd + 10 / scale} lineCap="round" listening={false} />}
+ <Line
+ points={[ax, ay, bx, by]}
+ stroke={LINE_COLORS[p.line]}
+ strokeWidth={wd}
+ lineCap={dash ? 'butt' : 'round'}
+ dash={dash}
+ hitStrokeWidth={Math.max(wd, 12 / scale)}
+ listening={!tool}
+ onClick={pickPipe(p)}
+ onTap={pickPipe(p)}
+ onMouseEnter={() => setHover({ kind: 'pipe', id: p.id })}
+ onMouseLeave={() => useWaterUi.getState().hover?.id === p.id && setHover(null)}
+ />
+ {len * scale > 40 && (
+ <Arrow
+ points={[mx - ux * arrow, my - uy * arrow, mx + ux * arrow, my + uy * arrow]}
+ stroke={LINE_DARK[p.line]}
+ fill={LINE_DARK[p.line]}
+ strokeWidth={1.2 / scale}
+ pointerLength={4 / scale}
+ pointerWidth={4 / scale}
+ listening={false}
+ />
+ )}
+ </Group>
+ )
+ })}
+ {w.nodes.map((n) => (
+ <Group
+ key={n.id}
+ x={n.x}
+ y={n.y}
+ listening={editable || (!editing && n.kind !== 'junction')}
+ draggable={editable}
+ onMouseDown={(e) => {
+ if (!editable || e.evt.button !== 0) return
+ e.cancelBubble = true
+ usePlanStore.getState().selectWall(null)
+ select({ kind: 'node', id: n.id })
+ }}
+ onClick={(e) => {
+ e.cancelBubble = true
+ }}
+ onTap={(e) => {
+ e.cancelBubble = true
+ if (!editing) setHover({ kind: 'node', id: n.id })
+ }}
+ onDragMove={nodeDrag(n)}
+ onDragEnd={nodeDragEnd(n)}
+ onMouseEnter={(e) => {
+ setHover({ kind: 'node', id: n.id })
+ const st = e.target.getStage()
+ if (st && editable) st.container().style.cursor = 'move'
+ }}
+ onMouseLeave={(e) => {
+ if (useWaterUi.getState().hover?.id === n.id) setHover(null)
+ const st = e.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ >
+ <Circle radius={13 / scale} fill="rgba(0,0,0,0.001)" />
+ <Group scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <NodeIcon node={n} selected={selected?.id === n.id} />
+ </Group>
+ </Group>
+ ))}
+ {labelPipes.map((p) => {
+ const a = wNode(w, p.from)
+ const b = wNode(w, p.to)
+ if (!a || !b) return null
+ return (
+ <Tag
+ key={`t-${p.id}`}
+ at={{ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }}
+ text={`${waterCaption(p)} · ${formatLength(Math.hypot(b.x - a.x, b.y - a.y))}`}
+ scale={scale}
+ viewRot={viewRot}
+ color={LINE_COLORS[p.line]}
+ />
+ )
+ })}
+ {hover?.kind === 'node' &&
+ (() => {
+ const n = wNode(w, hover.id)
+ if (!n) return null
+ const base = n.kind === 'fixture' && n.fixture ? fixtureLabels[n.fixture] : waterKindLabels[n.kind]
+ const extra =
+ n.kind === 'collector'
+ ? ` ${LINE_SHORT[collectorLine(n) === 'hot' ? 'hot' : 'cold']} · ${t('networks:water.layer.outputs', { value: `${w.pipes.filter((p) => p.from === n.id).length}${n.outputs ? `/${n.outputs}` : ''}` })}`
+ : n.kind === 'source'
+ ? ` · ${t(n.source === 'well' ? 'networks:water.source.well' : 'networks:water.source.borehole').toLowerCase()}`
+ : ''
+ return <Tag at={{ x: n.x, y: n.y - 10 / scale }} text={`${n.label || base}${extra}${n.model ? ` · ${n.model}` : ''}`} scale={scale} viewRot={viewRot} />
+ })()}
+ {tool && draftNode && cursorPoint && (
+ <>
+ <Line
+ points={[draftNode.x, draftNode.y, cursorPoint.x, cursorPoint.y]}
+ stroke={lineColor}
+ strokeWidth={2 / scale}
+ dash={[6 / scale, 4 / scale]}
+ listening={false}
+ />
+ <Tag
+ at={{ x: (draftNode.x + cursorPoint.x) / 2, y: (draftNode.y + cursorPoint.y) / 2 }}
+ text={formatLength(Math.hypot(cursorPoint.x - draftNode.x, cursorPoint.y - draftNode.y))}
+ scale={scale}
+ viewRot={viewRot}
+ color={lineColor}
+ />
+ </>
+ )}
+ {tool && cursorPoint && (
+ <Circle
+ x={cursorPoint.x}
+ y={cursorPoint.y}
+ radius={(cursor?.kind === 'point' ? 4 : 8) / scale}
+ fill={cursor?.kind === 'point' ? lineColor : HALO}
+ stroke={lineColor}
+ strokeWidth={1.5 / scale}
+ listening={false}
+ />
+ )}
+ {tool && cursor?.kind === 'fixture' && !draft && (
+ <Tag at={{ x: cursor.point.x, y: cursor.point.y - 10 / scale }} text={t('networks:water.layer.fromCollector')} scale={scale} viewRot={viewRot} color={lineColor} />
+ )}
+ </Layer>
+ )
+}
diff --git a/src/networks/WaterPanel.tsx b/src/networks/WaterPanel.tsx
new file mode 100644
index 0000000..e874d1a
--- /dev/null
+++ b/src/networks/WaterPanel.tsx
@@ -0,0 +1,375 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { fmtNum } from '../i18n'
+import { fmtM, unitLabel } from './labels'
+import { formatLength, formatMoney, type Plan, type SewerFixture, type WaterDiameter, type WaterNode, type WaterPipe } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { useCatalog } from '../estimate/catalog'
+import { LengthField } from '../ui/LengthField'
+import { Button, IconButton, Input, Segmented } from '../ui'
+import type { SewerRef } from './sewerCalc'
+import { fixtureLabels } from './sewerModel'
+import { computeWater, type WaterCalc } from './waterCalc'
+import { priceWater, waterSum } from './waterPricing'
+import {
+ DIAMETERS,
+ LINE_LABELS,
+ LINE_SHORT,
+ deleteWaterNode,
+ deleteWaterPipe,
+ pipeMaterial,
+ updateWaterNode,
+ updateWaterPipe,
+ waterKindLabels,
+ waterOf,
+ waterPipeLength,
+ wNode,
+} from './waterModel'
+import { useWaterUi } from './waterStore'
+import './networks.css'
+
+const fmt = (v: number, d = 2) => fmtNum(v, d)
+
+export function useWaterSelection(plan: Plan | null): SewerRef | null {
+ const selected = useWaterUi((s) => s.selected)
+ if (!plan || !selected) return null
+ const w = waterOf(plan)
+ const ok = selected.kind === 'node' ? w.nodes.some((n) => n.id === selected.id) : w.pipes.some((p) => p.id === selected.id)
+ return ok ? selected : null
+}
+
+function Close() {
+ const { t } = useTranslation('networks')
+ const select = useWaterUi((s) => s.select)
+ return (
+ <IconButton label={t('shared.ui.close')} size="sm" className="inspector__close" onClick={() => select(null)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ )
+}
+
+function Warnings({ calc, refId }: { calc: WaterCalc; refId?: string }) {
+ const list = refId ? calc.warnings.filter((w) => w.ref?.id === refId) : calc.warnings
+ if (!list.length) return null
+ return (
+ <div className="net-warnings">
+ {list.map((w, i) => (
+ <div key={i} className="layout-hint layout-hint--warn">
+ {w.text}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export function WaterInspector({ plan, sel }: { plan: Plan; sel: SewerRef }) {
+ const calc = useMemo(() => computeWater(plan), [plan])
+ const w = waterOf(plan)
+ if (sel.kind === 'pipe') {
+ const p = w.pipes.find((x) => x.id === sel.id)
+ return p ? <PipeInspector plan={plan} pipe={p} calc={calc} /> : null
+ }
+ const n = w.nodes.find((x) => x.id === sel.id)
+ return n ? <NodeInspector plan={plan} node={n} calc={calc} /> : null
+}
+
+function PipeInspector({ plan, pipe, calc }: { plan: Plan; pipe: WaterPipe; calc: WaterCalc }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const w = waterOf(plan)
+ const set = (patch: Partial<WaterPipe>) => commit(updateWaterPipe(plan, pipe.id, patch))
+ const name = (n?: WaterNode) => (n ? `${n.kind === 'fixture' && n.fixture ? fixtureLabels[n.fixture] : waterKindLabels[n.kind]} ${n.id}` : '—')
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <Close />
+ <div className="eyebrow">{t('water.panel.eyebrowPipe')}</div>
+ <div className="inspector__title">
+ {LINE_SHORT[pipe.line]} Ø{pipe.diameter} {pipeMaterial(pipe)}
+ </div>
+ </div>
+ <div className="form">
+ <div className="form__row">
+ <span>{t('water.panel.line')}</span>
+ <Segmented
+ size="sm"
+ value={pipe.line}
+ options={(['cold', 'hot', 'recirc'] as const).map((l) => ({ value: l, label: LINE_LABELS[l] }))}
+ onChange={(line) => set({ line })}
+ />
+ </div>
+ <div className="form__row">
+ <span>{t('shared.ui.diameter')}</span>
+ <Segmented size="sm" value={String(pipe.diameter)} options={DIAMETERS.map((d) => ({ value: String(d), label: `Ø${d}` }))} onChange={(v) => set({ diameter: Number(v) as WaterDiameter })} />
+ </div>
+ <div className="form__row">
+ <span>{t('water.panel.material')}</span>
+ <Segmented size="sm" value={pipeMaterial(pipe)} options={(['PEX', 'PPR', 'PE'] as const).map((m) => ({ value: m, label: m }))} onChange={(material) => set({ material })} />
+ </div>
+ <div className="form__row">
+ <span>{t('shared.ui.where')}</span>
+ <Segmented
+ size="sm"
+ value={pipe.location}
+ options={[
+ { value: 'inside', label: t('shared.ui.inside') },
+ { value: 'outside', label: t('shared.ui.outside') },
+ ]}
+ onChange={(location) => set({ location })}
+ />
+ </div>
+ {pipe.location === 'outside' && (
+ <>
+ <label className="form__row">
+ <span>{t('water.panel.depth')}</span>
+ <LengthField value={pipe.depth ?? 0} min={0} onCommit={(depth) => set({ depth })} />
+ </label>
+ <div className="form__row">
+ <span>{t('water.panel.heatCable')}</span>
+ <Segmented
+ size="sm"
+ value={pipe.heated ? 'yes' : 'no'}
+ options={[
+ { value: 'no', label: t('water.panel.no') },
+ { value: 'yes', label: t('water.panel.yes') },
+ ]}
+ onChange={(v) => set({ heated: v === 'yes' })}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('shared.ui.length')}</dt>
+ <dd>{formatLength(waterPipeLength(w, pipe))}</dd>
+ <dt>{t('water.panel.feed')}</dt>
+ <dd>
+ {name(wNode(w, pipe.from))} → {name(wNode(w, pipe.to))}
+ </dd>
+ </dl>
+ <Warnings calc={calc} refId={pipe.id} />
+ <div className="inspector__actions">
+ <Button size="sm" onClick={() => set({ from: pipe.to, to: pipe.from })}>
+ {t('water.panel.reverse')}
+ </Button>
+ <Button size="sm" variant="danger" onClick={() => commit(deleteWaterPipe(plan, pipe.id))}>
+ {t('shared.ui.delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('water.panel.pipeHint')}</p>
+ </aside>
+ )
+}
+
+const KINDS: WaterNode['kind'][] = ['source', 'entry', 'pump', 'filter', 'boiler', 'collector', 'fixture', 'junction', 'tap_outdoor']
+
+function NodeInspector({ plan, node, calc }: { plan: Plan; node: WaterNode; calc: WaterCalc }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const set = (patch: Partial<WaterNode>) => commit(updateWaterNode(plan, node.id, patch))
+ const [model, setModel] = useState<string | null>(null)
+ const used = waterOf(plan).pipes.filter((p) => p.from === node.id).length
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <Close />
+ <div className="eyebrow">{t('water.panel.eyebrowNode', { kind: waterKindLabels[node.kind].toLowerCase() })}</div>
+ <div className="inspector__title">{node.kind === 'fixture' && node.fixture ? fixtureLabels[node.fixture] : node.model || waterKindLabels[node.kind]}</div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('shared.ui.type')}</span>
+ <select className="select form__select" value={node.kind} onChange={(e) => set({ kind: e.target.value as WaterNode['kind'] })}>
+ {KINDS.map((k) => (
+ <option key={k} value={k}>
+ {waterKindLabels[k]}
+ </option>
+ ))}
+ </select>
+ </label>
+ {node.kind === 'fixture' && (
+ <label className="form__row">
+ <span>{t('shared.ui.fixture')}</span>
+ <select className="select form__select" value={node.fixture ?? ''} onChange={(e) => set({ fixture: e.target.value as SewerFixture })}>
+ {(Object.keys(fixtureLabels) as SewerFixture[]).map((f) => (
+ <option key={f} value={f}>
+ {fixtureLabels[f]}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {node.kind === 'source' && (
+ <div className="form__row">
+ <span>{t('water.panel.source')}</span>
+ <Segmented
+ size="sm"
+ value={node.source ?? 'borehole'}
+ options={[
+ { value: 'borehole', label: t('water.source.borehole') },
+ { value: 'well', label: t('water.source.well') },
+ ]}
+ onChange={(source) => set({ source })}
+ />
+ </div>
+ )}
+ {node.kind === 'collector' && (
+ <>
+ <div className="form__row">
+ <span>{t('water.panel.water')}</span>
+ <Segmented
+ size="sm"
+ value={node.line ?? 'cold'}
+ options={[
+ { value: 'cold', label: LINE_LABELS.cold },
+ { value: 'hot', label: LINE_LABELS.hot },
+ ]}
+ onChange={(line) => set({ line })}
+ />
+ </div>
+ <label className="form__row">
+ <span>{t('water.panel.outputs')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={2}
+ max={12}
+ value={node.outputs ?? Math.max(used, 2)}
+ onChange={(e) => {
+ const v = Math.round(Number(e.target.value))
+ if (v >= 2 && v <= 12) set({ outputs: v })
+ }}
+ />
+ </label>
+ </>
+ )}
+ {(node.kind === 'pump' || node.kind === 'filter' || node.kind === 'boiler' || node.kind === 'source' || node.kind === 'collector') && (
+ <label className="form__row">
+ <span>{t('shared.ui.model')}</span>
+ <Input
+ size="sm"
+ value={model ?? node.model ?? ''}
+ onChange={(e) => setModel(e.target.value)}
+ onBlur={() => {
+ if (model === null) return
+ const v = model.trim()
+ setModel(null)
+ if (v !== (node.model ?? '')) set({ model: v || undefined })
+ }}
+ onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()}
+ />
+ </label>
+ )}
+ </div>
+ <dl className="props props--compact">
+ {node.kind === 'collector' && (
+ <>
+ <dt>{t('water.panel.usedOutputs')}</dt>
+ <dd>{used}</dd>
+ </>
+ )}
+ <dt>{t('shared.ui.center')}</dt>
+ <dd>
+ {Math.round(node.x)}, {Math.round(node.y)}
+ </dd>
+ </dl>
+ <Warnings calc={calc} refId={node.id} />
+ <div className="inspector__actions">
+ <span />
+ <Button size="sm" variant="danger" onClick={() => commit(deleteWaterNode(plan, node.id))}>
+ {t('shared.ui.delete')}
+ </Button>
+ </div>
+ </aside>
+ )
+}
+
+export function WaterSummary({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('networks')
+ const catalog = useCatalog()
+ const viewOnly = useViewOnly()
+ const select = useWaterUi((s) => s.select)
+ const calc = useMemo(() => computeWater(plan), [plan])
+ const w = waterOf(plan)
+ const items = useMemo(() => priceWater(calc.items, w.materials, catalog), [calc, w.materials, catalog])
+ const total = items.reduce((a, i) => a + waterSum(i), 0)
+ const missing = items.filter((i) => i.price === undefined).length
+ return (
+ <div className="inspector__materials net-summary">
+ <div className="inspector__head">
+ <div className="eyebrow">{t('shared.ui.networks')}</div>
+ <div className="inspector__title">{t('shared.layers.water')}</div>
+ </div>
+ {w.pipes.length === 0 && (
+ <p className="muted">{t('water.summary.empty')}</p>
+ )}
+ {calc.lengths.length > 0 && (
+ <dl className="props props--compact">
+ {calc.lengths.map((l) => (
+ <div key={`${l.line}-${l.diameter}-${l.material}-${l.location}`} className="net-props__pair">
+ <dt>
+ {LINE_SHORT[l.line]} Ø{l.diameter} {l.material} {l.location === 'outside' ? t('shared.ui.outsideLower') : t('shared.ui.insideLower')}
+ </dt>
+ <dd>{fmtM(l.lengthMm)}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ {items.length > 0 && (
+ <div className="inspector__section net-items">
+ <div className="eyebrow">{t('shared.ui.materials')}</div>
+ {items.map((i) => (
+ <div key={i.key} className="net-item">
+ <div className="net-item__name">
+ {i.url ? (
+ <a href={i.url} target="_blank" rel="noreferrer">
+ {i.name}
+ </a>
+ ) : (
+ i.name
+ )}
+ {i.priceFrom && <div className="muted net-item__from">{i.priceFrom}</div>}
+ </div>
+ <div className="net-item__qty">
+ {fmt(i.buyQty)} {unitLabel(i.buyUnit)}
+ {unitLabel(i.buyUnit) !== unitLabel(i.unit) && (
+ <div className="muted">
+ {fmt(i.qty)} {unitLabel(i.unit)}
+ </div>
+ )}
+ </div>
+ <div className="net-item__sum">{i.price !== undefined ? formatMoney(waterSum(i)) : <span className="muted">{t('shared.ui.noPrice')}</span>}</div>
+ </div>
+ ))}
+ <div className="row total">
+ <span>{t('water.summary.total')}</span>
+ <strong>{formatMoney(total)}</strong>
+ </div>
+ {missing > 0 && <div className="muted">{t('shared.ui.missing', { count: missing })}</div>}
+ </div>
+ )}
+ {calc.warnings.length > 0 && (
+ <div className="inspector__section">
+ <div className="eyebrow">{t('shared.ui.warnings', { count: calc.warnings.length })}</div>
+ <div className="net-warnings">
+ {calc.warnings.map((wr, i) =>
+ wr.ref && !viewOnly ? (
+ <button key={i} className="layout-hint layout-hint--warn net-warning" onClick={() => select(wr.ref!)}>
+ {wr.text}
+ </button>
+ ) : (
+ <div key={i} className="layout-hint layout-hint--warn">
+ {wr.text}
+ </div>
+ ),
+ )}
+ </div>
+ </div>
+ )}
+ <p className="hint">{t('water.summary.hint')}</p>
+ </div>
+ )
+}
diff --git a/src/networks/electric/ElectricLayer.tsx b/src/networks/electric/ElectricLayer.tsx
new file mode 100644
index 0000000..e344390
--- /dev/null
+++ b/src/networks/electric/ElectricLayer.tsx
@@ -0,0 +1,506 @@
+import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { Circle, Group, Layer, Line, Rect, Text } from 'react-konva'
+import type Konva from 'konva'
+import { useTranslation } from 'react-i18next'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import type { ElectricPoint, ElectricPointKind, Plan, Point } from '../../model'
+import { usePlanStore } from '../../store/planStore'
+import { useLayers } from '../layers'
+import { useNetworkEdit } from '../registry'
+import { useSewerUi } from '../sewerStore'
+import { useElectricUi } from './store'
+import {
+ addPoint,
+ ceilingOf,
+ circuitColor,
+ defaultHeight,
+ deletePoints,
+ electricOf,
+ kindLabel,
+ pointNormal,
+ setPanel,
+ snapToWallFace,
+ updatePoints,
+ withElectric,
+} from './model'
+
+type Props = {
+ plan: Plan
+ scale: number
+ viewRot: number
+ worldPointer: () => Point | null
+ interactive: boolean
+}
+
+const INK = '#2b2d33'
+const HALO = 'rgba(242, 107, 29, 0.28)'
+const FONT = 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif'
+const REACH_PX = 40
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+const semi = (r: number, y0: number, n = 14) => {
+ const pts: number[] = []
+ for (let i = 0; i <= n; i++) {
+ const a = (Math.PI * i) / n
+ pts.push(Math.cos(a) * r, y0 + Math.sin(a) * r)
+ }
+ return pts
+}
+
+function Symbol({ kind, color, r }: { kind: ElectricPointKind | 'panel'; color: string; r: number }) {
+ const sw = Math.max(1.4, r / 6)
+ const common = { stroke: color, strokeWidth: sw, lineCap: 'round' as const, lineJoin: 'round' as const }
+ const h = r * 0.35
+ const socket = (fill: boolean, dx = 0, rr = r) => (
+ <>
+ <Line points={[dx, 0, dx, h]} {...common} />
+ <Line points={semi(rr, h).map((v, i) => (i % 2 ? v : v + dx))} closed fill={fill ? color : '#ffffff'} {...common} />
+ <Line points={[dx - rr * 0.7, h + rr + sw * 1.6, dx + rr * 0.7, h + rr + sw * 1.6]} {...common} />
+ </>
+ )
+ switch (kind) {
+ case 'socket':
+ return socket(false)
+ case 'socket_ip44':
+ return socket(true)
+ case 'socket2':
+ return (
+ <>
+ {socket(false, -r * 0.62, r * 0.6)}
+ {socket(false, r * 0.62, r * 0.6)}
+ </>
+ )
+ case 'outdoor':
+ return (
+ <>
+ {socket(true)}
+ <Rect x={-r * 1.15} y={h - sw} width={r * 2.3} height={r * 1.25 + sw * 3} stroke={color} strokeWidth={sw * 0.7} dash={[sw * 2, sw * 1.5]} />
+ </>
+ )
+ case 'power':
+ return (
+ <>
+ {socket(false)}
+ <Line points={[-r * 0.45, h + r * 0.15, -r * 0.45, h + r * 0.75]} {...common} />
+ <Line points={[0, h + r * 0.15, 0, h + r * 0.9]} {...common} />
+ <Line points={[r * 0.45, h + r * 0.15, r * 0.45, h + r * 0.75]} {...common} />
+ </>
+ )
+ case 'switch':
+ case 'switch2': {
+ const c = r * 0.45
+ const cy = h + c
+ const flag = (ang: number) => {
+ const a = (ang * Math.PI) / 180
+ const ex = Math.cos(a) * r * 1.3
+ const ey = cy + Math.sin(a) * r * 1.3
+ const tx = Math.cos(a + Math.PI / 2) * r * 0.45
+ const ty = Math.sin(a + Math.PI / 2) * r * 0.45
+ return (
+ <>
+ <Line points={[Math.cos(a) * c, cy + Math.sin(a) * c, ex, ey]} {...common} />
+ <Line points={[ex, ey, ex + tx, ey + ty]} {...common} />
+ </>
+ )
+ }
+ return (
+ <>
+ <Line points={[0, 0, 0, h]} {...common} />
+ <Circle x={0} y={cy} radius={c} fill="#ffffff" {...common} />
+ {flag(45)}
+ {kind === 'switch2' && flag(80)}
+ </>
+ )
+ }
+ case 'light':
+ case 'light_wall': {
+ const cy = kind === 'light_wall' ? h + r * 0.8 : 0
+ const k = r * 0.8 * Math.SQRT1_2
+ return (
+ <>
+ {kind === 'light_wall' && <Line points={[0, 0, 0, h]} {...common} />}
+ <Circle x={0} y={cy} radius={r * 0.8} fill="#ffffff" {...common} />
+ <Line points={[-k, cy - k, k, cy + k]} {...common} />
+ <Line points={[-k, cy + k, k, cy - k]} {...common} />
+ </>
+ )
+ }
+ case 'junction':
+ return (
+ <>
+ <Circle x={0} y={r * 0.5} radius={r * 0.45} fill="#ffffff" {...common} />
+ <Circle x={0} y={r * 0.5} radius={sw} fill={color} />
+ </>
+ )
+ case 'panel':
+ return (
+ <>
+ <Rect x={-r * 1.4} y={0} width={r * 2.8} height={r * 1.2} fill="#ffffff" {...common} />
+ <Line points={[-r * 1.4, 0, r * 1.4, 0, r * 1.4, r * 1.2]} closed fill={color} strokeEnabled={false} />
+ </>
+ )
+ }
+}
+
+function Tag({ at, text, scale, viewRot }: { at: Point; text: string; scale: number; viewRot: number }) {
+ const w = text.length * 6.3 + 12
+ return (
+ <Group x={at.x} y={at.y} scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <Rect x={-w / 2} y={-34} width={w} height={18} cornerRadius={4} fill="#ffffff" stroke={INK} strokeWidth={0.6} opacity={0.96} />
+ <Text x={-w / 2} y={-31} width={w} align="center" text={text} fontSize={11} fontFamily={FONT} fill={INK} />
+ </Group>
+ )
+}
+
+function Mounted({
+ at,
+ normal,
+ zoom,
+ children,
+ selected,
+ r,
+ ...rest
+}: {
+ at: Point
+ normal: Point | null
+ zoom: number
+ children: ReactNode
+ selected: boolean
+ r: number
+} & Record<string, unknown>) {
+ const rotation = normal ? (Math.atan2(normal.y, normal.x) * 180) / Math.PI - 90 : 0
+ return (
+ <Group x={at.x} y={at.y} {...rest}>
+ <Group scaleX={1 / zoom} scaleY={1 / zoom} rotation={rotation}>
+ {selected && <Circle x={0} y={r * 0.6} radius={r * 1.9} fill={HALO} />}
+ <Circle x={0} y={r * 0.6} radius={r * 1.5} fill="rgba(0,0,0,0.001)" />
+ {children}
+ </Group>
+ </Group>
+ )
+}
+
+export function ElectricLayer(props: Props) {
+ const on = useLayers((s) => s.electric)
+ return on ? <ElectricLayerInner {...props} /> : null
+}
+
+type Ghost = { point: Point; wallId?: string; normal: Point | null; ok: boolean }
+
+function ElectricLayerInner({ plan, scale, viewRot, worldPointer, interactive }: Props) {
+ const { t } = useTranslation('networks')
+ const toolOn = useElectricUi((s) => s.tool)
+ const editing = useNetworkEdit((st) => st.editing === 'electric') && interactive
+ const tool = editing ? toolOn : null
+ const selected = useElectricUi((s) => s.selected)
+ const panelSelected = useElectricUi((s) => s.panelSelected)
+ const planTool = usePlanStore((s) => s.tool)
+ const commit = usePlanStore((s) => s.commit)
+ const [ghost, setGhost] = useState<Ghost | null>(null)
+ const [hover, setHover] = useState<string | null>(null)
+ const [preview, setPreview] = useState<Plan | null>(null)
+ const layerRef = useRef<Konva.Layer>(null)
+ const e = electricOf(preview ?? plan)
+ const editable = editing && !tool && planTool === 'select'
+ const r = Math.max(7, Math.min(16, 150 * scale))
+
+ useEffect(() => {
+ if (!tool) setGhost(null)
+ }, [tool])
+
+ useEffect(
+ () =>
+ usePlanStore.subscribe((st, prev) => {
+ const picked = st.selectedWallId || st.selectedOpeningId || st.selectedFurnitureId || st.selectedZoneId || st.group
+ const was = prev.selectedWallId || prev.selectedOpeningId || prev.selectedFurnitureId || prev.selectedZoneId || prev.group
+ if (picked && picked !== was) useElectricUi.getState().select([])
+ if (st.tool !== prev.tool && st.tool !== 'select') useElectricUi.getState().setTool(null)
+ }),
+ [],
+ )
+
+ useEffect(
+ () =>
+ useSewerUi.subscribe((st, prev) => {
+ if (st.tool && !prev.tool) useElectricUi.getState().setTool(null)
+ if (st.selected && !prev.selected) useElectricUi.getState().select([])
+ }),
+ [],
+ )
+
+ useEffect(() => {
+ const stage = layerRef.current?.getStage()
+ if (!stage) return
+ const onClick = (ev: KonvaEventObject<MouseEvent>) => {
+ if (ev.target === stage) useElectricUi.getState().select([])
+ }
+ stage.on('click.electric tap.electric', onClick)
+ return () => {
+ stage.off('click.electric tap.electric')
+ }
+ }, [])
+
+ useEffect(() => {
+ const down = (ev: KeyboardEvent) => {
+ if (isTyping(ev) || ev.metaKey || ev.ctrlKey) return
+ const ui = useElectricUi.getState()
+ if ((ev.key === 'Delete' || ev.key === 'Backspace') && editing && (ui.selected.length || ui.panelSelected)) {
+ const current = usePlanStore.getState().plan
+ if (!current) return
+ ev.preventDefault()
+ commit(ui.panelSelected ? setPanel(current, undefined) : deletePoints(current, ui.selected))
+ ui.select([])
+ }
+ }
+ window.addEventListener('keydown', down)
+ return () => window.removeEventListener('keydown', down)
+ }, [editing, commit])
+
+ const ghostAt = (): Ghost | null => {
+ const raw = worldPointer()
+ const current = usePlanStore.getState().plan
+ if (!raw || !current || !tool) return null
+ const ui = useElectricUi.getState()
+ const kind = tool === 'light' ? ui.lightKind : null
+ if (kind === 'light') return { point: { x: Math.round(raw.x / 50) * 50, y: Math.round(raw.y / 50) * 50 }, normal: null, ok: true }
+ const snap = snapToWallFace(current, raw, REACH_PX / scale + 300)
+ if (!snap) return { point: raw, normal: null, ok: false }
+ return { point: snap.point, wallId: snap.wallId, normal: snap.normal, ok: true }
+ }
+
+ const onToolMove = (ev: KonvaEventObject<MouseEvent>) => {
+ ev.cancelBubble = true
+ setGhost(ghostAt())
+ }
+
+ const onToolClick = (ev: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ ev.cancelBubble = true
+ if ('button' in ev.evt && ev.evt.button !== 0) return
+ const current = usePlanStore.getState().plan
+ const g = ghostAt()
+ if (!current || !g?.ok || !tool) return
+ const ui = useElectricUi.getState()
+ if (tool === 'panel') {
+ const prev = electricOf(current).panel
+ commit(setPanel(current, { ...(prev ?? {}), id: prev?.id ?? 'panel', x: g.point.x, y: g.point.y, ...(g.wallId ? { wallId: g.wallId } : {}) }))
+ ui.setTool(null)
+ ui.selectPanel(true)
+ return
+ }
+ const kind = tool === 'socket' ? ui.socketKind : tool === 'switch' ? ui.switchKind : ui.lightKind
+ const circuit = ui.activeCircuit && electricOf(current).circuits.some((c) => c.id === ui.activeCircuit) ? ui.activeCircuit : undefined
+ const height = kind === 'light' ? ceilingOf(current) : kind === 'junction' ? ceilingOf(current, g.wallId) - 150 : defaultHeight[kind]
+ const res = addPoint(current, {
+ kind,
+ x: g.point.x,
+ y: g.point.y,
+ height,
+ ...(g.wallId ? { wallId: g.wallId } : {}),
+ ...(circuit ? { circuitId: circuit } : {}),
+ })
+ commit(res.plan)
+ ui.select([res.id])
+ }
+
+ const snapDrag = (raw: Point, wallOnly: boolean) => {
+ const current = usePlanStore.getState().plan
+ if (!current) return null
+ if (!wallOnly) return { point: { x: Math.round(raw.x / 50) * 50, y: Math.round(raw.y / 50) * 50 }, wallId: undefined as string | undefined }
+ const s = snapToWallFace(current, raw, REACH_PX / scale + 300)
+ return s ? { point: s.point, wallId: s.wallId as string | undefined } : null
+ }
+
+ const pointDrag = (p: ElectricPoint) => (ev: KonvaEventObject<DragEvent>) => {
+ const s = snapDrag({ x: ev.target.x(), y: ev.target.y() }, p.kind !== 'light')
+ const current = usePlanStore.getState().plan
+ if (!s || !current) return
+ ev.target.position(s.point)
+ setPreview(updatePoints(current, [p.id], { x: s.point.x, y: s.point.y, wallId: s.wallId }))
+ }
+
+ const pointDragEnd = (p: ElectricPoint) => (ev: KonvaEventObject<DragEvent>) => {
+ const current = usePlanStore.getState().plan
+ setPreview(null)
+ if (!current) return
+ const s = snapDrag({ x: ev.target.x(), y: ev.target.y() }, p.kind !== 'light')
+ if (!s) return
+ const moved = updatePoints(current, [p.id], { x: s.point.x, y: s.point.y })
+ commit(
+ withElectric(moved, (x) => ({
+ ...x,
+ points: x.points.map((q) => {
+ if (q.id !== p.id) return q
+ const next = { ...q }
+ if (s.wallId) next.wallId = s.wallId
+ else delete next.wallId
+ return next
+ }),
+ })),
+ )
+ }
+
+ const panelDrag = (ev: KonvaEventObject<DragEvent>, end: boolean) => {
+ const current = usePlanStore.getState().plan
+ const panel = current && electricOf(current).panel
+ const s = snapDrag({ x: ev.target.x(), y: ev.target.y() }, true)
+ if (!current || !panel || !s) return
+ ev.target.position(s.point)
+ const next = setPanel(current, { ...panel, x: s.point.x, y: s.point.y, ...(s.wallId ? { wallId: s.wallId } : {}) })
+ if (end) {
+ setPreview(null)
+ commit(next)
+ } else setPreview(next)
+ }
+
+ const pick = (id: string) => (ev: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ ev.cancelBubble = true
+ if (!editing) {
+ setHover(id)
+ return
+ }
+ const ui = useElectricUi.getState()
+ const shift = 'shiftKey' in ev.evt && ev.evt.shiftKey
+ usePlanStore.getState().selectWall(null)
+ useSewerUi.getState().select(null)
+ ui.select(shift ? (ui.selected.includes(id) ? ui.selected.filter((x) => x !== id) : [...ui.selected, id]) : [id])
+ }
+
+ const hoverPoint = e.points.find((p) => p.id === hover)
+ const circuitName = (id?: string) => (id ? (e.circuits.find((c) => c.id === id)?.name ?? id) : t('electric.layerTag.noGroup'))
+
+ return (
+ <Layer ref={layerRef}>
+ {tool && (
+ <Rect
+ x={-1e7}
+ y={-1e7}
+ width={2e7}
+ height={2e7}
+ fill="rgba(0,0,0,0.001)"
+ onMouseMove={onToolMove}
+ onMouseDown={(ev) => {
+ if (ev.evt.button === 0 && !ev.evt.shiftKey) return
+ ev.cancelBubble = true
+ }}
+ onClick={onToolClick}
+ onTap={onToolClick}
+ onDblClick={(ev) => {
+ ev.cancelBubble = true
+ }}
+ onContextMenu={(ev) => {
+ ev.evt.preventDefault()
+ ev.cancelBubble = true
+ useElectricUi.getState().setTool(null)
+ }}
+ onMouseLeave={() => setGhost(null)}
+ />
+ )}
+ {(e.routes ?? []).map((rt, i) => (
+ <Line
+ key={`rt-${i}`}
+ points={rt.path.flatMap((p) => [p.x, p.y])}
+ stroke={circuitColor(e, rt.circuitId)}
+ strokeWidth={1.6 / scale}
+ dash={[7 / scale, 4 / scale]}
+ lineJoin="round"
+ opacity={0.9}
+ listening={false}
+ />
+ ))}
+ {(e.routes ?? []).flatMap((rt, i) =>
+ [rt.path[rt.path.length - 1]].map((p) => (
+ <Circle key={`drop-${i}`} x={p.x} y={p.y} radius={2.2 / scale} fill={circuitColor(e, rt.circuitId)} listening={false} />
+ )),
+ )}
+ {e.panel && (
+ <Mounted
+ at={e.panel}
+ normal={pointNormal(plan, e.panel)}
+ zoom={scale}
+ r={r}
+ selected={panelSelected}
+ draggable={editable}
+ onDragMove={(ev: KonvaEventObject<DragEvent>) => panelDrag(ev, false)}
+ onDragEnd={(ev: KonvaEventObject<DragEvent>) => panelDrag(ev, true)}
+ onMouseDown={(ev: KonvaEventObject<MouseEvent>) => {
+ ev.cancelBubble = true
+ }}
+ onClick={(ev: KonvaEventObject<MouseEvent>) => {
+ ev.cancelBubble = true
+ if (!editing) return
+ usePlanStore.getState().selectWall(null)
+ useElectricUi.getState().selectPanel(true)
+ }}
+ onMouseEnter={() => setHover('panel')}
+ onMouseLeave={() => setHover(null)}
+ listening={!tool}
+ >
+ <Symbol kind="panel" color={INK} r={r} />
+ </Mounted>
+ )}
+ {e.points.map((p) => (
+ <Mounted
+ key={p.id}
+ at={p}
+ normal={pointNormal(plan, p)}
+ zoom={scale}
+ r={r}
+ selected={selected.includes(p.id)}
+ draggable={editable}
+ listening={!tool}
+ onDragMove={pointDrag(p)}
+ onDragEnd={pointDragEnd(p)}
+ onMouseDown={(ev: KonvaEventObject<MouseEvent>) => {
+ ev.cancelBubble = true
+ }}
+ onClick={pick(p.id)}
+ onTap={pick(p.id)}
+ onMouseEnter={(ev: KonvaEventObject<MouseEvent>) => {
+ setHover(p.id)
+ const st = ev.target.getStage()
+ if (st && editable) st.container().style.cursor = 'move'
+ }}
+ onMouseLeave={(ev: KonvaEventObject<MouseEvent>) => {
+ setHover((h) => (h === p.id ? null : h))
+ const st = ev.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ >
+ <Symbol kind={p.kind} color={circuitColor(e, p.circuitId)} r={r} />
+ </Mounted>
+ ))}
+ {ghost && tool && (
+ <Group opacity={ghost.ok ? 0.75 : 0.35} listening={false}>
+ <Mounted at={ghost.point} normal={ghost.normal} zoom={scale} r={r} selected={false} listening={false}>
+ <Symbol
+ kind={
+ tool === 'panel'
+ ? 'panel'
+ : tool === 'socket'
+ ? useElectricUi.getState().socketKind
+ : tool === 'switch'
+ ? useElectricUi.getState().switchKind
+ : useElectricUi.getState().lightKind
+ }
+ color={ghost.ok ? circuitColor(e, useElectricUi.getState().activeCircuit ?? undefined) : '#d9412b'}
+ r={r}
+ />
+ </Mounted>
+ </Group>
+ )}
+ {hoverPoint && (
+ <Tag
+ at={hoverPoint}
+ scale={scale}
+ viewRot={viewRot}
+ text={`${hoverPoint.label ? `${hoverPoint.label} · ` : ''}${kindLabel(hoverPoint.kind)} · ${t('electric.layerTag.height', { height: hoverPoint.height })} · ${circuitName(hoverPoint.circuitId)}`}
+ />
+ )}
+ {hover === 'panel' && e.panel && <Tag at={e.panel} scale={scale} viewRot={viewRot} text={t('electric.layerTag.panel')} />}
+ </Layer>
+ )
+}
diff --git a/src/networks/electric/ElectricPanel.tsx b/src/networks/electric/ElectricPanel.tsx
new file mode 100644
index 0000000..155dc4b
--- /dev/null
+++ b/src/networks/electric/ElectricPanel.tsx
@@ -0,0 +1,494 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { ElectricCircuit, ElectricPoint, ElectricPointKind, Plan } from '../../model'
+import { formatMoney } from '../../model'
+import { fmtNum, t as tt } from '../../i18n'
+import { unitLabel } from '../../i18n/units'
+import { usePlanStore } from '../../store/planStore'
+import { useViewOnly } from '../../store/viewOnly'
+import { useCatalog } from '../../estimate/catalog'
+import { Badge, Button, IconButton, Input, Table, Td, Th, Tr } from '../../ui'
+import { computeElectric, pointPower, type ElectricWarning } from './calc'
+import {
+ CABLES,
+ RATINGS,
+ addCircuit,
+ cableLabel,
+ circuitColor,
+ CIRCUIT_KINDS,
+ POINT_KINDS,
+ circuitKindLabel,
+ circuitPresets,
+ deleteCircuit,
+ deletePoints,
+ electricOf,
+ kindLabel,
+ setPanel,
+ setRoutes,
+ updateCircuit,
+ updatePoints,
+} from './model'
+import { autoRoute } from './route'
+import { electricSum, priceElectric } from './pricing'
+import { useElectricUi } from './store'
+import './electric.css'
+
+const fmt = (v: number, d = 1) => fmtNum(v, d)
+const breakerLabel = (c: ElectricCircuit) =>
+ `${c.breaker.type === 'RCBO' ? tt('networks:electric.panel.rcboPrefix') : c.breaker.type === 'RCD' ? tt('networks:electric.panel.rcdPrefix') : ''}${c.breaker.curve ?? 'C'}${c.breaker.rating}`
+
+const CLOSE_ICON = (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+)
+
+export function useElectricSelection(plan: Plan | null) {
+ const selected = useElectricUi((s) => s.selected)
+ const panelSelected = useElectricUi((s) => s.panelSelected)
+ if (!plan) return null
+ const e = electricOf(plan)
+ const points = e.points.filter((p) => selected.includes(p.id))
+ if (panelSelected && e.panel) return { points: [] as ElectricPoint[], panel: true }
+ return points.length ? { points, panel: false } : null
+}
+
+export function ElectricInspector({ plan, sel }: { plan: Plan; sel: { points: ElectricPoint[]; panel: boolean } }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const select = useElectricUi((s) => s.select)
+ const e = electricOf(plan)
+ const ids = sel.points.map((p) => p.id)
+ const one = sel.points.length === 1 ? sel.points[0] : null
+ const same = <K extends keyof ElectricPoint>(k: K) => (sel.points.every((p) => p[k] === sel.points[0][k]) ? sel.points[0][k] : undefined)
+ const patch = (p: Partial<ElectricPoint>) => commit(updatePoints(plan, ids, p))
+
+ if (sel.panel && e.panel) {
+ const panel = e.panel
+ const calc = computeElectric(plan)
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <IconButton label={t('electric.panel.clearSelection')} size="sm" className="inspector__close" onClick={() => select([])}>
+ {CLOSE_ICON}
+ </IconButton>
+ <div className="eyebrow">{t('electric.layer')}</div>
+ <div className="inspector__title">{t('electric.panel.panelTitle')}</div>
+ </div>
+ <dl className="props">
+ <dt>{t('electric.panel.devices')}</dt>
+ <dd>{t('electric.panel.modules', { n: calc.modules })}</dd>
+ <dt>{t('electric.panel.panelNeeded')}</dt>
+ <dd>{calc.panelSize ? t('electric.panel.panelFor', { n: calc.panelSize }) : '—'}</dd>
+ </dl>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.modulesInPanel')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={4}
+ step={1}
+ className="el-num"
+ value={panel.modules ?? ''}
+ placeholder={String(calc.panelSize || '')}
+ onChange={(ev) => {
+ const v = Math.round(Number(ev.target.value))
+ const next = { ...panel }
+ if (v > 0) next.modules = v
+ else delete next.modules
+ commit(setPanel(plan, next))
+ }}
+ />
+ </label>
+ <Button variant="danger" className="inspector__delete" onClick={() => {
+ commit(setPanel(plan, undefined))
+ select([])
+ }}>
+ {t('electric.panel.removePanel')}
+ </Button>
+ </aside>
+ )
+ }
+
+ const kind = same('kind')
+ const height = same('height')
+ const circuit = same('circuitId')
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <IconButton label={t('electric.panel.clearSelection')} size="sm" className="inspector__close" onClick={() => select([])}>
+ {CLOSE_ICON}
+ </IconButton>
+ <div className="eyebrow">{t('electric.layer')}</div>
+ <div className="inspector__title">{one ? `${kindLabel(one.kind)} ${one.label ?? one.id}` : t('electric.panel.pointsCount', { n: sel.points.length })}</div>
+ </div>
+ <div className="el-form">
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.group')}</span>
+ <select className="select" value={circuit ?? ''} onChange={(ev) => {
+ const v = ev.target.value
+ if (v === '__new') {
+ const res = addCircuit(plan, kind === 'light' || kind === 'switch' || kind === 'switch2' || kind === 'light_wall' ? 'light' : kind === 'power' ? 'power' : kind === 'socket_ip44' ? 'wet' : kind === 'outdoor' ? 'outdoor' : 'socket')
+ commit(updatePoints(res.plan, ids, { circuitId: res.id }))
+ return
+ }
+ commit(v ? updatePoints(plan, ids, { circuitId: v }) : updatePoints(plan, ids, { circuitId: undefined }))
+ }}>
+ {circuit === undefined && sel.points.length > 1 && !sel.points.every((p) => !p.circuitId) && <option value="">{t('electric.panel.mixed')}</option>}
+ <option value="">{t('electric.panel.noGroup')}</option>
+ {e.circuits.map((c) => (
+ <option key={c.id} value={c.id}>
+ {c.name}
+ </option>
+ ))}
+ <option value="__new">{t('electric.panel.newGroup')}</option>
+ </select>
+ </label>
+ {one && (
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.type')}</span>
+ <select className="select" value={one.kind} onChange={(ev) => patch({ kind: ev.target.value as ElectricPointKind })}>
+ {POINT_KINDS.map((k) => (
+ <option key={k} value={k}>
+ {kindLabel(k)}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.height')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={0}
+ step={50}
+ suffix={t('common:units.mm')}
+ className="el-num"
+ value={height ?? ''}
+ placeholder={t('electric.panel.heightMixed')}
+ onChange={(ev) => {
+ const v = Number(ev.target.value)
+ if (Number.isFinite(v) && v >= 0 && ev.target.value !== '') patch({ height: Math.round(v) })
+ }}
+ />
+ </label>
+ {one && (
+ <>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.power')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={0}
+ step={50}
+ suffix={t('common:units.w')}
+ className="el-num"
+ value={one.powerW ?? ''}
+ placeholder={String(pointPower({ ...one, powerW: undefined }))}
+ onChange={(ev) => patch({ powerW: ev.target.value === '' ? undefined : Math.max(0, Math.round(Number(ev.target.value))) })}
+ />
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.label')}</span>
+ <Input size="sm" className="el-text" value={one.label ?? ''} placeholder={t('electric.panel.labelPlaceholder')} onChange={(ev) => patch({ label: ev.target.value || undefined })} />
+ </label>
+ </>
+ )}
+ </div>
+ <p className="hint">{t('electric.panel.pointHint')}</p>
+ <Button variant="danger" className="inspector__delete" onClick={() => {
+ commit(deletePoints(plan, ids))
+ select([])
+ }}>
+ {sel.points.length > 1 ? t('electric.panel.deletePoints', { count: sel.points.length }) : t('electric.panel.deletePoint')}
+ </Button>
+ </aside>
+ )
+}
+
+function Warnings({ list, onPick }: { list: ElectricWarning[]; onPick: (w: ElectricWarning) => void }) {
+ const { t } = useTranslation('networks')
+ if (!list.length) return <p className="muted">{t('electric.panel.noWarnings')}</p>
+ return (
+ <div className="el-warnings">
+ {list.map((w, i) => (
+ <button key={i} type="button" className={`el-warning el-warning--${w.level}`} onClick={() => onPick(w)}>
+ {w.text}
+ </button>
+ ))}
+ </div>
+ )
+}
+
+export function ElectricSummary({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const viewOnly = useViewOnly()
+ const catalog = useCatalog()
+ const select = useElectricUi((s) => s.select)
+ const selectPanel = useElectricUi((s) => s.selectPanel)
+ const [editId, setEditId] = useState<string | null>(null)
+ const [newKind, setNewKind] = useState<ElectricCircuit['kind']>('socket')
+ const e = electricOf(plan)
+ const calc = useMemo(() => computeElectric(plan), [plan])
+ const priced = useMemo(() => priceElectric(calc.items, e.materials, catalog), [calc, e.materials, catalog])
+ const total = priced.reduce((s, i) => s + electricSum(i), 0)
+ const missing = priced.filter((i) => i.price === undefined).length
+ const edit = e.circuits.find((c) => c.id === editId)
+
+ const routeAll = (ids: string[]) => {
+ let routes = ids.flatMap((id) => autoRoute(plan, id))
+ if (!e.panel) routes = []
+ commit(setRoutes(plan, ids, routes))
+ }
+
+ const pickWarning = (w: ElectricWarning) => {
+ if (!w.ref) return
+ if (w.ref.kind === 'point') select([w.ref.id])
+ else if (w.ref.kind === 'panel') selectPanel(true)
+ else setEditId(w.ref.id)
+ }
+
+ return (
+ <div className="el-summary">
+ <div className="inspector__head">
+ <div className="eyebrow">{t('electric.panel.layerEyebrow')}</div>
+ <div className="inspector__title">{t('electric.layer')}</div>
+ </div>
+ <dl className="props">
+ <dt>{t('electric.panel.points')}</dt>
+ <dd>{e.points.length}</dd>
+ <dt>{t('electric.panel.circuits')}</dt>
+ <dd>{e.circuits.length}</dd>
+ <dt>{t('electric.panel.load')}</dt>
+ <dd>{fmt(calc.totalLoadW / 1000)} {t('common:units.kw')}</dd>
+ <dt>{t('electric.panel.panelRow')}</dt>
+ <dd>{e.panel ? t('electric.panel.panelState', { modules: calc.modules, size: calc.panelSize || '—' }) : t('electric.panel.notPlaced')}</dd>
+ </dl>
+
+ <div className="inspector__section">
+ <div className="el-head">
+ <strong>{t('electric.panel.groups')}</strong>
+ {!viewOnly && e.circuits.length > 0 && (
+ <Button size="sm" variant="ghost" onClick={() => routeAll(e.circuits.map((c) => c.id))} disabled={!e.panel} title={e.panel ? t('electric.panel.autoRouteTitle') : t('electric.panel.placePanelFirst')}>
+ {t('electric.panel.autoRoute')}
+ </Button>
+ )}
+ </div>
+ {e.circuits.length === 0 ? (
+ <p className="muted">{t('electric.panel.noGroups')}</p>
+ ) : (
+ <Table dense className="el-table">
+ <thead>
+ <tr>
+ <Th>{t('electric.panel.colGroup')}</Th>
+ <Th>{t('electric.panel.colProtection')}</Th>
+ <Th num>{t('common:units.m')}</Th>
+ <Th num>{t('electric.panel.colPoints')}</Th>
+ <Th num>{t('common:units.kw')}</Th>
+ </tr>
+ </thead>
+ <tbody>
+ {calc.circuits.map((c) => (
+ <Tr key={c.circuit.id} className={`el-row ${editId === c.circuit.id ? 'el-row--active' : ''}`} onClick={() => setEditId(editId === c.circuit.id ? null : c.circuit.id)}>
+ <Td>
+ <span className="el-dot" style={{ background: circuitColor(e, c.circuit.id) }} />
+ {c.circuit.name}
+ <div className="muted el-sub">{cableLabel(c.circuit.cable)}</div>
+ </Td>
+ <Td>{breakerLabel(c.circuit)}</Td>
+ <Td num title={c.routed ? t('electric.panel.routed') : t('electric.panel.estimated')}>
+ {c.routed ? '' : '≈'}
+ {c.cableM}
+ </Td>
+ <Td num>{c.points}</Td>
+ <Td num>{fmt(c.loadW / 1000)}</Td>
+ </Tr>
+ ))}
+ </tbody>
+ </Table>
+ )}
+ {edit && <CircuitEditor plan={plan} circuit={edit} readOnly={viewOnly} onClose={() => setEditId(null)} onRoute={() => routeAll([edit.id])} />}
+ {!viewOnly && (
+ <div className="el-add">
+ <select className="select" value={newKind} onChange={(ev) => setNewKind(ev.target.value as ElectricCircuit['kind'])}>
+ {CIRCUIT_KINDS.map((k) => (
+ <option key={k} value={k}>
+ {circuitKindLabel(k)}
+ </option>
+ ))}
+ </select>
+ <Button size="sm" onClick={() => {
+ const res = addCircuit(plan, newKind)
+ commit(res.plan)
+ setEditId(res.id)
+ useElectricUi.getState().setActiveCircuit(res.id)
+ }}>
+ {t('electric.panel.addGroup')}
+ </Button>
+ </div>
+ )}
+ </div>
+
+ <div className="inspector__section">
+ <strong>{t('electric.panel.materials')}</strong>
+ <div className="el-items">
+ {priced.map((i) => (
+ <div key={i.key} className="el-item">
+ <div className="el-item__name">
+ {i.url ? (
+ <a href={i.url} target="_blank" rel="noreferrer">
+ {i.name}
+ </a>
+ ) : (
+ i.name
+ )}
+ {i.priceFrom && <div className="muted el-sub">{i.priceFrom}</div>}
+ </div>
+ <div className="el-item__qty">
+ {fmt(i.buyQty)} {unitLabel(i.buyUnit)}
+ </div>
+ <div className="el-item__sum">{i.price !== undefined ? formatMoney(electricSum(i)) : '—'}</div>
+ </div>
+ ))}
+ {!priced.length && <p className="muted">{t('electric.panel.noMaterials')}</p>}
+ </div>
+ <div className="row total">
+ <span>{t('electric.panel.total')}</span>
+ <strong>{formatMoney(total)}</strong>
+ </div>
+ {missing > 0 && <div className="muted">{t('electric.panel.noPrice', { n: missing })}</div>}
+ </div>
+
+ <div className="inspector__section">
+ <strong>{t('electric.panel.warnings')}</strong>
+ <Warnings list={calc.warnings} onPick={pickWarning} />
+ </div>
+
+ <details className="inspector__section el-howto">
+ <summary>{t('electric.panel.howto')}</summary>
+ <ol>
+ {(t('electric.steps', { returnObjects: true }) as string[]).map((s, i) => (
+ <li key={i}>{s}</li>
+ ))}
+ </ol>
+ <p className="muted">
+ {t('electric.panel.howtoNote')}
+ </p>
+ </details>
+ </div>
+ )
+}
+
+function CircuitEditor({ plan, circuit: c, readOnly, onClose, onRoute }: { plan: Plan; circuit: ElectricCircuit; readOnly: boolean; onClose: () => void; onRoute: () => void }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const e = electricOf(plan)
+ const patch = (p: Partial<ElectricCircuit>) => commit(updateCircuit(plan, c.id, p))
+ const pts = e.points.filter((p) => p.circuitId === c.id)
+ if (readOnly)
+ return (
+ <div className="el-edit">
+ <dl className="props">
+ <dt>{t('electric.panel.type')}</dt>
+ <dd>{circuitKindLabel(c.kind)}</dd>
+ <dt>{t('electric.panel.protection')}</dt>
+ <dd>{breakerLabel(c)}</dd>
+ <dt>{t('electric.panel.cable')}</dt>
+ <dd>{cableLabel(c.cable)}</dd>
+ {c.phase && (
+ <>
+ <dt>{t('electric.panel.phase')}</dt>
+ <dd>{c.phase}</dd>
+ </>
+ )}
+ </dl>
+ </div>
+ )
+ return (
+ <div className="el-edit">
+ <div className="el-head">
+ <Badge tone="accent">{c.id}</Badge>
+ <IconButton label={t('electric.panel.collapse')} size="sm" onClick={onClose}>
+ {CLOSE_ICON}
+ </IconButton>
+ </div>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.name')}</span>
+ <Input size="sm" className="el-text" value={c.name} onChange={(ev) => patch({ name: ev.target.value })} />
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.type')}</span>
+ <select className="select" value={c.kind} onChange={(ev) => {
+ const kind = ev.target.value as ElectricCircuit['kind']
+ patch({ kind, ...structuredClone(circuitPresets[kind]) })
+ }}>
+ {CIRCUIT_KINDS.map((k) => (
+ <option key={k} value={k}>
+ {circuitKindLabel(k)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.device')}</span>
+ <select className="select" value={c.breaker.type} onChange={(ev) => patch({ breaker: { ...c.breaker, type: ev.target.value as ElectricCircuit['breaker']['type'] } })}>
+ <option value="MCB">{t('electric.panel.mcb')}</option>
+ <option value="RCBO">{t('electric.panel.rcbo')}</option>
+ <option value="RCD">{t('electric.panel.rcd')}</option>
+ </select>
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.rating')}</span>
+ <span className="el-pair">
+ <select className="select" value={c.breaker.curve ?? 'C'} onChange={(ev) => patch({ breaker: { ...c.breaker, curve: ev.target.value } })}>
+ <option value="B">B</option>
+ <option value="C">C</option>
+ <option value="D">D</option>
+ </select>
+ <select className="select" value={c.breaker.rating} onChange={(ev) => patch({ breaker: { ...c.breaker, rating: Number(ev.target.value) } })}>
+ {[...new Set([...RATINGS, c.breaker.rating])].sort((a, b) => a - b).map((r) => (
+ <option key={r} value={r}>
+ {t('electric.amps', { value: r })}
+ </option>
+ ))}
+ </select>
+ </span>
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.cable')}</span>
+ <select className="select" value={c.cable} onChange={(ev) => patch({ cable: ev.target.value })}>
+ {[...new Set([...CABLES, c.cable])].map((k) => (
+ <option key={k} value={k}>
+ {cableLabel(k)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="row row--center el-field">
+ <span>{t('electric.panel.phase')}</span>
+ <select className="select" value={c.phase ?? ''} onChange={(ev) => patch({ phase: (ev.target.value || undefined) as ElectricCircuit['phase'] })}>
+ <option value="">—</option>
+ <option value="L1">L1</option>
+ <option value="L2">L2</option>
+ <option value="L3">L3</option>
+ </select>
+ </label>
+ <div className="inspector__actions">
+ <Button size="sm" variant="ghost" onClick={() => useElectricUi.getState().select(pts.map((p) => p.id))} disabled={!pts.length}>
+ {t('electric.panel.selectPoints')}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onRoute} disabled={!e.panel || !pts.length}>
+ {t('electric.panel.route')}
+ </Button>
+ <Button size="sm" variant="danger" onClick={() => {
+ commit(deleteCircuit(plan, c.id))
+ onClose()
+ }}>
+ {t('electric.panel.delete')}
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/src/networks/electric/ElectricTools.tsx b/src/networks/electric/ElectricTools.tsx
new file mode 100644
index 0000000..df12514
--- /dev/null
+++ b/src/networks/electric/ElectricTools.tsx
@@ -0,0 +1,84 @@
+import { useTranslation } from 'react-i18next'
+import type { ElectricPointKind } from '../../model'
+import { t as tt } from '../../i18n'
+import { usePlanStore } from '../../store/planStore'
+import { Segmented } from '../../ui'
+import { registerNetworkLayer } from '../registry'
+import { EMPTY_ELECTRIC, electricOf } from './model'
+import { useElectricUi, type ElectricTool } from './store'
+import './electric.css'
+
+type Mode = 'select' | Exclude<ElectricTool, null>
+
+const MODES: Mode[] = ['select', 'socket', 'switch', 'light', 'panel']
+
+const KINDS: Record<'socket' | 'switch' | 'light', ElectricPointKind[]> = {
+ socket: ['socket', 'socket2', 'socket_ip44', 'power', 'outdoor'],
+ switch: ['switch', 'switch2'],
+ light: ['light', 'light_wall', 'junction'],
+}
+
+function ElectricEditTools() {
+ const { t } = useTranslation('networks')
+ const ui = useElectricUi()
+ const circuits = usePlanStore((s) => (s.plan ? electricOf(s.plan).circuits : EMPTY_ELECTRIC.circuits))
+ const mode: Mode = ui.tool ?? 'select'
+ const sub = mode === 'socket' || mode === 'switch' || mode === 'light' ? mode : null
+ const kind = sub === 'socket' ? ui.socketKind : sub === 'switch' ? ui.switchKind : ui.lightKind
+
+ return (
+ <>
+ <Segmented size="sm" value={mode} options={MODES.map((m) => ({ value: m, label: t(`electric.tools.mode.${m}.label`), title: t(`electric.tools.mode.${m}.title`) }))} onChange={(m) => ui.setTool(m === 'select' ? null : m)} />
+ {sub && <Segmented size="sm" value={kind} options={KINDS[sub].map((k) => ({ value: k, label: t(`electric.tools.kind.${k}`) }))} onChange={(k) => ui.setKind(sub, k)} />}
+ {mode !== 'panel' && (
+ <select
+ className="select el-group-select"
+ value={ui.activeCircuit ?? ''}
+ onChange={(ev) => ui.setActiveCircuit(ev.target.value || null)}
+ title={t('electric.tools.groupTitle')}
+ >
+ <option value="">{t('electric.tools.noGroup')}</option>
+ {circuits.map((c) => (
+ <option key={c.id} value={c.id}>
+ {c.name}
+ </option>
+ ))}
+ </select>
+ )}
+ <span className="muted net-editbar__hint">
+ {mode === 'select' ? t('electric.tools.hintSelect') : mode === 'light' && kind === 'light' ? t('electric.tools.hintCeiling') : t('electric.tools.hintWall')}
+ </span>
+ </>
+ )
+}
+
+registerNetworkLayer({
+ key: 'electric',
+ get label() {
+ return tt('networks:electric.layer')
+ },
+ Tools: ElectricEditTools,
+ enter: () => {
+ const ui = useElectricUi.getState()
+ ui.select([])
+ ui.setTab(true)
+ ui.setTool('socket')
+ },
+ exit: () => {
+ const ui = useElectricUi.getState()
+ ui.setTool(null)
+ ui.select([])
+ },
+ onEscape: () => {
+ const ui = useElectricUi.getState()
+ if (ui.tool) {
+ ui.setTool(null)
+ return true
+ }
+ if (ui.selected.length || ui.panelSelected) {
+ ui.select([])
+ return true
+ }
+ return false
+ },
+})
diff --git a/src/networks/electric/calc.ts b/src/networks/electric/calc.ts
new file mode 100644
index 0000000..134b12a
--- /dev/null
+++ b/src/networks/electric/calc.ts
@@ -0,0 +1,285 @@
+import type { ElectricCircuit, ElectricPoint, ElectricPointKind, Plan, Point } from '../../model'
+import { resolveFurniture } from '../../furniture/catalog'
+import { detectRooms, pointInPolygon } from '../../stats/rooms'
+import { fmtNum, t } from '../../i18n'
+import {
+ CABLE_RESERVE,
+ PANEL_HEIGHT,
+ PANEL_TAIL,
+ ROUTE_BELOW_CEILING,
+ cableLabel,
+ ceilingOf,
+ circuitKindLabel,
+ defaultPower,
+ electricOf,
+ isSocket,
+ kindLabel,
+ parseCable,
+ pathLength,
+} from './model'
+
+export type ElectricItemKind = 'cable' | 'device' | 'frame' | 'box' | 'breaker' | 'rcbo' | 'rcd' | 'main' | 'panel' | 'conduit'
+
+export type ElectricSpec = {
+ cores?: number
+ section?: number
+ rating?: number
+ curve?: string
+ poles?: number
+ leakage?: number
+ modules?: number
+ diameter?: number
+ device?: ElectricPointKind | 'relay'
+}
+
+export type ElectricItem = { key: string; kind: ElectricItemKind; name: string; qty: number; unit: 'm' | 'pcs'; spec?: ElectricSpec }
+
+export type ElectricRef = { kind: 'point' | 'circuit' | 'panel'; id: string }
+
+export type ElectricWarning = { text: string; level: 'error' | 'warn' | 'info'; ref?: ElectricRef }
+
+export type CircuitCalc = {
+ circuit: ElectricCircuit
+ points: number
+ loadW: number
+ currentA: number
+ horizontalMm: number
+ dropsMm: number
+ cableM: number
+ routed: boolean
+ maxBreaker: number | null
+ dropPct: number | null
+}
+
+export type ElectricCalc = {
+ circuits: CircuitCalc[]
+ items: ElectricItem[]
+ warnings: ElectricWarning[]
+ modules: number
+ panelSize: number
+ totalLoadW: number
+ cableByMark: { cable: string; m: number }[]
+}
+
+const MAX_BREAKER: Record<string, number> = { '1.5': 10, '2.5': 16, '4': 25, '6': 32, '10': 40, '16': 63 }
+const RHO_CU = 0.0175
+const PANEL_SIZES = [12, 18, 24, 36, 48, 54, 72, 96]
+const DEVICE_BOXES: Record<ElectricPointKind, number> = {
+ socket: 1,
+ socket2: 2,
+ socket_ip44: 1,
+ power: 1,
+ switch: 1,
+ switch2: 1,
+ light: 0,
+ light_wall: 1,
+ junction: 0,
+ outdoor: 0,
+}
+const FRAMED = new Set<ElectricPointKind>(['socket', 'socket2', 'socket_ip44', 'switch', 'switch2'])
+const DEVICE_NAMES = new Set<ElectricPointKind>(['socket', 'socket2', 'socket_ip44', 'power', 'switch', 'switch2', 'light', 'light_wall', 'junction', 'outdoor'])
+
+export const pointPower = (p: ElectricPoint) => p.powerW ?? defaultPower[p.kind]
+
+export function maxBreakerFor(cable: string) {
+ const c = parseCable(cable)
+ return c ? (MAX_BREAKER[String(c.section)] ?? null) : null
+}
+
+function mstManhattan(nodes: Point[]) {
+ if (nodes.length < 2) return 0
+ const inTree = [true, ...nodes.slice(1).map(() => false)]
+ const best = nodes.map((p) => Math.abs(p.x - nodes[0].x) + Math.abs(p.y - nodes[0].y))
+ let total = 0
+ for (let k = 1; k < nodes.length; k++) {
+ let u = -1
+ for (let i = 0; i < nodes.length; i++) if (!inTree[i] && (u < 0 || best[i] < best[u])) u = i
+ inTree[u] = true
+ total += best[u]
+ for (let i = 0; i < nodes.length; i++)
+ if (!inTree[i]) best[i] = Math.min(best[i], Math.abs(nodes[i].x - nodes[u].x) + Math.abs(nodes[i].y - nodes[u].y))
+ }
+ return total
+}
+
+function distToRect(p: Point, f: { x: number; y: number; rotationDeg: number }, w: number, d: number) {
+ const a = (-f.rotationDeg * Math.PI) / 180
+ const lx = (p.x - f.x) * Math.cos(a) - (p.y - f.y) * Math.sin(a)
+ const ly = (p.x - f.x) * Math.sin(a) + (p.y - f.y) * Math.cos(a)
+ const dx = Math.max(0, Math.abs(lx) - w / 2)
+ const dy = Math.max(0, Math.abs(ly) - d / 2)
+ return Math.hypot(dx, dy)
+}
+
+export function computeElectric(plan: Plan): ElectricCalc {
+ const e = electricOf(plan)
+ const warnings: ElectricWarning[] = []
+ const items = new Map<string, ElectricItem>()
+ const add = (it: Omit<ElectricItem, 'qty'>, qty: number) => {
+ if (qty <= 0) return
+ const cur = items.get(it.key)
+ items.set(it.key, { ...it, qty: (cur?.qty ?? 0) + qty })
+ }
+ const panel = e.panel
+ const ceilingAt = (wallId?: string) => ceilingOf(plan, wallId)
+ const routeLevel = (wallId?: string) => ceilingAt(wallId) - ROUTE_BELOW_CEILING
+
+ const cableMm = new Map<string, number>()
+ let modules = 0
+ let threePhase = false
+
+ const circuits: CircuitCalc[] = e.circuits.map((c) => {
+ const pts = e.points.filter((p) => p.circuitId === c.id)
+ const routes = (e.routes ?? []).filter((r) => r.circuitId === c.id)
+ const routed = routes.length > 0
+ const horizontalMm = routed
+ ? routes.reduce((s, r) => s + pathLength(r.path), 0)
+ : mstManhattan([...(panel ? [{ x: panel.x, y: panel.y }] : []), ...pts.map((p) => ({ x: p.x, y: p.y }))])
+ const dropsMm =
+ pts.reduce((s, p) => s + Math.abs(routeLevel(p.wallId) - Math.min(p.height, ceilingAt(p.wallId))), 0) +
+ (panel ? Math.abs(routeLevel(panel.wallId) - PANEL_HEIGHT) : 0)
+ const raw = horizontalMm + dropsMm + (pts.length ? PANEL_TAIL : 0)
+ const cableM = pts.length ? Math.ceil((raw * (1 + CABLE_RESERVE)) / 1000) : 0
+ const loadW = pts.reduce((s, p) => s + pointPower(p), 0)
+ const cab = parseCable(c.cable)
+ const three = !!cab && cab.cores >= 5
+ if (three) threePhase = true
+ const currentA = three ? loadW / (Math.sqrt(3) * 400 * 0.95) : loadW / 230
+ const maxBreaker = maxBreakerFor(c.cable)
+ const lengthM = raw / 1000
+ const dropPct = cab ? (((three ? 1 : 2) * lengthM * currentA * RHO_CU) / cab.section / (three ? 400 : 230)) * 100 : null
+ const ref: ElectricRef = { kind: 'circuit', id: c.id }
+
+ cableMm.set(c.cable, (cableMm.get(c.cable) ?? 0) + (pts.length ? raw * (1 + CABLE_RESERVE) : 0))
+
+ const poles = three ? 3 : 1
+ const curve = c.breaker.curve ?? 'C'
+ if (c.breaker.type === 'RCBO') {
+ add({ key: `rcbo-${curve}${c.breaker.rating}-${poles}p`, kind: 'rcbo', name: t(three ? 'networks:electric.item.rcbo4p' : 'networks:electric.item.rcbo', { curve, rating: c.breaker.rating }), unit: 'pcs', spec: { rating: c.breaker.rating, curve, poles: three ? 4 : 2, leakage: 30 } }, 1)
+ modules += three ? 4 : 2
+ } else {
+ add({ key: `mcb-${curve}${c.breaker.rating}-${poles}p`, kind: 'breaker', name: t('networks:electric.item.breaker', { curve, rating: c.breaker.rating, poles }), unit: 'pcs', spec: { rating: c.breaker.rating, curve, poles } }, 1)
+ modules += poles
+ if (c.breaker.type === 'RCD') {
+ const r = c.breaker.rating <= 25 ? 25 : c.breaker.rating <= 40 ? 40 : 63
+ add({ key: `rcd-${r}-${three ? 4 : 2}p`, kind: 'rcd', name: t('networks:electric.item.rcd', { rating: r, poles: three ? '4P' : '2P' }), unit: 'pcs', spec: { rating: r, poles: three ? 4 : 2, leakage: 30 } }, 1)
+ modules += three ? 4 : 2
+ }
+ }
+
+ const label = c.name || c.id
+ if (!cab) warnings.push({ text: t('networks:electric.warn.cableUnknown', { label, cable: c.cable }), level: 'warn', ref })
+ if (maxBreaker !== null && c.breaker.rating > maxBreaker)
+ warnings.push({ text: t('networks:electric.warn.breakerOverCable', { label, rating: c.breaker.rating, cable: cableLabel(c.cable), max: maxBreaker }), level: 'error', ref })
+ if (currentA > c.breaker.rating)
+ warnings.push({ text: t('networks:electric.warn.overload', { label, load: fmtNum(Math.round(loadW), 0), current: fmtNum(currentA, 1, 1), rating: c.breaker.rating }), level: 'warn', ref })
+ const wet = c.kind === 'wet' || c.kind === 'outdoor' || c.kind === 'garage' || pts.some((p) => p.kind === 'socket_ip44' || p.kind === 'outdoor')
+ if (wet && c.breaker.type === 'MCB')
+ warnings.push({ text: t('networks:electric.warn.wetNoRcd', { label, kind: circuitKindLabel(c.kind).toLowerCase() }), level: 'error', ref })
+ else if (c.kind === 'socket' && c.breaker.type === 'MCB')
+ warnings.push({ text: t('networks:electric.warn.socketRcd', { label }), level: 'info', ref })
+ if (dropPct !== null && dropPct > 5)
+ warnings.push({ text: t('networks:electric.warn.voltageDrop', { label, pct: fmtNum(dropPct, 1, 1) }), level: 'warn', ref })
+ const sockets = pts.filter((p) => isSocket(p.kind) && p.kind !== 'power').reduce((s, p) => s + (p.kind === 'socket2' ? 2 : 1), 0)
+ if (sockets > 10) warnings.push({ text: t('networks:electric.warn.tooManySockets', { label, sockets }), level: 'info', ref })
+ if (pts.some((p) => p.kind === 'power') && pts.length > 1)
+ warnings.push({ text: t('networks:electric.warn.powerSeparate', { label }), level: 'warn', ref })
+ if (c.kind === 'light' && pts.some((p) => isSocket(p.kind)))
+ warnings.push({ text: t('networks:electric.warn.lightWithSockets', { label }), level: 'warn', ref })
+ if (!pts.length) warnings.push({ text: t('networks:electric.warn.emptyCircuit', { label }), level: 'info', ref })
+
+ return { circuit: c, points: pts.length, loadW, currentA, horizontalMm, dropsMm, cableM, routed, maxBreaker, dropPct }
+ })
+
+ const rooms = detectRooms(plan).buildings.flatMap((b) => b.rooms)
+ const wet = plan.furniture.filter((f) => f.type === 'bathtub' || f.type === 'shower')
+ const known = new Set(e.circuits.map((c) => c.id))
+ for (const p of e.points) {
+ const ref: ElectricRef = { kind: 'point', id: p.id }
+ const name = `${kindLabel(p.kind)} ${p.label ?? p.id}`
+ add({ key: `dev-${p.kind}`, kind: 'device', name: DEVICE_NAMES.has(p.kind) ? t(`networks:electric.device.${p.kind}`) : kindLabel(p.kind), unit: 'pcs', spec: { device: p.kind } }, 1)
+ if (FRAMED.has(p.kind))
+ add(
+ p.kind === 'socket_ip44'
+ ? { key: 'frame-1-ip44', kind: 'frame', name: t('networks:electric.item.frameIp44'), unit: 'pcs', spec: { device: 'socket_ip44' } }
+ : { key: 'frame-1', kind: 'frame', name: t('networks:electric.item.frame'), unit: 'pcs', spec: { device: 'socket' } },
+ 1,
+ )
+ add({ key: 'box-flush', kind: 'box', name: t('networks:electric.item.box'), unit: 'pcs' }, DEVICE_BOXES[p.kind])
+ if (!p.circuitId) warnings.push({ text: t('networks:electric.warn.noCircuit', { name }), level: 'warn', ref })
+ else if (!known.has(p.circuitId)) warnings.push({ text: t('networks:electric.warn.unknownCircuit', { name, id: p.circuitId }), level: 'error', ref })
+ if (isSocket(p.kind) || p.kind === 'switch' || p.kind === 'switch2') {
+ for (const f of wet) {
+ const r = resolveFurniture(f)
+ const d = distToRect(p, f, r.w, r.d)
+ if (d <= 1)
+ warnings.push({ text: t(f.type === 'bathtub' ? 'networks:electric.warn.zone01Bath' : 'networks:electric.warn.zone01Shower', { name }), level: 'error', ref })
+ else if (d < 600 && isSocket(p.kind))
+ warnings.push({ text: t(f.type === 'bathtub' ? 'networks:electric.warn.zone2Bath' : 'networks:electric.warn.zone2Shower', { name, d: fmtNum(Math.round(d), 0) }), level: 'error', ref })
+ }
+ const inBath = rooms.some((r) => r.kind === 'bath' && (pointInPolygon(p, r.clearPolygon) || nearPoly(p, r.clearPolygon, 30)))
+ if (inBath && isSocket(p.kind) && p.kind !== 'socket_ip44' && p.kind !== 'outdoor')
+ warnings.push({ text: t('networks:electric.warn.bathSocket', { name }), level: 'warn', ref })
+ if (inBath && isSocket(p.kind) && p.circuitId) {
+ const c = e.circuits.find((x) => x.id === p.circuitId)
+ if (c && c.breaker.type === 'MCB') warnings.push({ text: t('networks:electric.warn.bathNoRcd', { name, circuit: c.name }), level: 'error', ref })
+ }
+ }
+ }
+
+ if (e.points.length && !panel) warnings.push({ text: t('networks:electric.warn.noPanel'), level: 'warn' })
+
+ for (const [cable, mm] of cableMm) {
+ if (mm <= 0) continue
+ add({ key: `cable-${cable}`, kind: 'cable', name: t('networks:electric.item.cable', { cable: cableLabel(cable) }), unit: 'm', spec: { cores: parseCable(cable)?.cores, section: parseCable(cable)?.section } }, Math.ceil(mm / 1000))
+ }
+ const conduit = new Map<number, number>()
+ for (const [cable, mm] of cableMm) {
+ const c = parseCable(cable)
+ const d = c && c.section >= 6 ? 25 : c && (c.section >= 4 || c.cores >= 5) ? 20 : 16
+ conduit.set(d, (conduit.get(d) ?? 0) + mm)
+ }
+ for (const [d, mm] of conduit) {
+ if (mm <= 0) continue
+ add({ key: `conduit-${d}`, kind: 'conduit', name: t('networks:electric.item.conduit', { d }), unit: 'm', spec: { diameter: d } }, Math.ceil((mm - PANEL_TAIL * circuits.filter((c) => c.points).length) / 1000))
+ }
+
+ if (e.circuits.length) {
+ add({ key: threePhase ? 'main-3p' : 'main-2p', kind: 'main', name: t(threePhase ? 'networks:electric.item.main3p' : 'networks:electric.item.main2p'), unit: 'pcs', spec: threePhase ? { rating: 32, curve: 'C', poles: 3 } : { rating: 40, curve: 'C', poles: 2 } }, 1)
+ add({ key: 'relay-voltage', kind: 'main', name: t('networks:electric.item.relay'), unit: 'pcs', spec: { device: 'relay' } }, threePhase ? 0 : 1)
+ modules += threePhase ? 3 : 4
+ }
+ const needed = Math.ceil(modules * 1.2)
+ const panelSize = modules ? (PANEL_SIZES.find((s) => s >= needed) ?? PANEL_SIZES.at(-1)!) : 0
+ if (panelSize) add({ key: `panel-${panelSize}`, kind: 'panel', name: t('networks:electric.item.panel', { modules: panelSize }), unit: 'pcs', spec: { modules: panelSize } }, 1)
+ if (panel?.modules && panel.modules < modules)
+ warnings.push({ text: t('networks:electric.warn.panelTooSmall', { modules: panel.modules, need: modules, size: panelSize }), level: 'error', ref: { kind: 'panel', id: panel.id } })
+
+ const order: ElectricItemKind[] = ['cable', 'conduit', 'device', 'frame', 'box', 'panel', 'main', 'rcd', 'rcbo', 'breaker']
+ const list = [...items.values()].sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind) || a.key.localeCompare(b.key))
+ const rank = { error: 0, warn: 1, info: 2 }
+ warnings.sort((a, b) => rank[a.level] - rank[b.level])
+
+ return {
+ circuits,
+ items: list,
+ warnings,
+ modules,
+ panelSize,
+ totalLoadW: circuits.reduce((s, c) => s + c.loadW, 0),
+ cableByMark: [...cableMm].filter(([, mm]) => mm > 0).map(([cable, mm]) => ({ cable, m: Math.ceil(mm / 1000) })),
+ }
+}
+
+function nearPoly(p: Point, poly: Point[], tol: number) {
+ for (let i = 0; i < poly.length; i++) {
+ const a = poly[i]
+ const b = poly[(i + 1) % poly.length]
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy || 1
+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2))
+ if (Math.hypot(p.x - a.x - dx * t, p.y - a.y - dy * t) <= tol) return true
+ }
+ return false
+}
diff --git a/src/networks/electric/electric.css b/src/networks/electric/electric.css
new file mode 100644
index 0000000..c3dd8ce
--- /dev/null
+++ b/src/networks/electric/electric.css
@@ -0,0 +1,178 @@
+.el-tool {
+ z-index: var(--z-popover);
+ flex-wrap: wrap;
+ max-width: 460px;
+}
+
+.el-form {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.el-field > span:first-child {
+ color: var(--muted);
+ white-space: nowrap;
+}
+
+.el-field .select {
+ max-width: 170px;
+}
+
+.el-num {
+ width: 110px;
+}
+
+.el-text {
+ width: 170px;
+}
+
+.el-pair {
+ display: inline-flex;
+ gap: var(--space-1);
+}
+
+.el-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ margin-bottom: var(--space-2);
+}
+
+.el-table td {
+ vertical-align: top;
+}
+
+.el-row {
+ cursor: pointer;
+}
+
+.el-row:hover,
+.el-row--active {
+ background: var(--surface-2);
+}
+
+.el-dot {
+ display: inline-block;
+ width: 9px;
+ height: 9px;
+ margin-right: 6px;
+ border-radius: var(--radius-pill);
+ vertical-align: 1px;
+}
+
+.el-sub {
+ font-size: var(--text-xs);
+}
+
+.el-edit {
+ margin-top: var(--space-2);
+ padding: var(--space-3);
+ border-radius: var(--radius-sm);
+ background: var(--surface-2);
+}
+
+.el-edit .inspector__actions {
+ margin-top: var(--space-2);
+}
+
+.el-add {
+ display: flex;
+ gap: var(--space-2);
+ margin-top: var(--space-2);
+}
+
+.el-items {
+ display: flex;
+ flex-direction: column;
+ margin-top: var(--space-2);
+}
+
+.el-item {
+ display: grid;
+ grid-template-columns: 1fr auto auto;
+ gap: var(--space-2);
+ align-items: baseline;
+ padding: 6px 0;
+ font-size: var(--text-sm);
+ border-bottom: 1px solid var(--line);
+}
+
+.el-item__name a {
+ color: inherit;
+}
+
+.el-item__qty,
+.el-item__sum {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.el-item__sum {
+ min-width: 72px;
+}
+
+.el-warnings {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: var(--space-2);
+}
+
+.el-warning {
+ width: 100%;
+ padding: 8px 10px;
+ border: 0;
+ border-radius: var(--radius-xs);
+ color: var(--ink);
+ font: inherit;
+ font-size: var(--text-sm);
+ text-align: left;
+ cursor: pointer;
+}
+
+.el-warning--error {
+ background: var(--danger-soft);
+}
+
+.el-warning--warn {
+ background: var(--warn-soft);
+}
+
+.el-warning--info {
+ background: var(--surface-2);
+ color: var(--ink-2);
+}
+
+.el-howto summary {
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.el-howto ol {
+ margin: var(--space-2) 0;
+ padding-left: 18px;
+ font-size: var(--text-sm);
+ line-height: 1.45;
+}
+
+.el-howto li + li {
+ margin-top: 4px;
+}
+
+.el-howto .muted {
+ font-size: var(--text-xs);
+ line-height: 1.45;
+}
+
+@media (max-width: 760px) {
+ .el-tool {
+ max-width: calc(100vw - 16px);
+ }
+}
+
+.el-group-select {
+ max-width: 160px;
+}
diff --git a/src/networks/electric/estimate.ts b/src/networks/electric/estimate.ts
new file mode 100644
index 0000000..3bbcb43
--- /dev/null
+++ b/src/networks/electric/estimate.ts
@@ -0,0 +1,23 @@
+import type { Plan } from '../../model'
+import type { CatalogItem } from '../../estimate/catalog'
+import { computeElectric } from './calc'
+import { electricOf } from './model'
+import { t } from '../../i18n'
+import { priceElectric } from './pricing'
+
+export const electricGroup = () => t('networks:shared.layers.electric')
+
+export function electricEstimateRows(plan: Plan, catalog: CatalogItem[]) {
+ const e = electricOf(plan)
+ if (!e.points.length && !e.circuits.length) return []
+ return priceElectric(computeElectric(plan).items, e.materials, catalog).map((i) => ({
+ id: `auto:electric:${i.key}`,
+ name: i.name,
+ url: i.url,
+ qty: i.buyQty,
+ unit: i.buyUnit,
+ price: i.price,
+ priceFrom: i.priceFrom,
+ group: electricGroup(),
+ }))
+}
diff --git a/src/networks/electric/index.ts b/src/networks/electric/index.ts
new file mode 100644
index 0000000..1fe5877
--- /dev/null
+++ b/src/networks/electric/index.ts
@@ -0,0 +1,6 @@
+export { ElectricLayer } from './ElectricLayer'
+import './ElectricTools'
+export { ElectricInspector, ElectricSummary, useElectricSelection } from './ElectricPanel'
+export { useElectricUi } from './store'
+export { computeElectric, type ElectricCalc } from './calc'
+export { electricEstimateRows, electricGroup } from './estimate'
diff --git a/src/networks/electric/model.ts b/src/networks/electric/model.ts
new file mode 100644
index 0000000..3debb7b
--- /dev/null
+++ b/src/networks/electric/model.ts
@@ -0,0 +1,186 @@
+import {
+ nextId,
+ type ElectricCircuit,
+ type ElectricNetwork,
+ type ElectricPanel,
+ type ElectricPoint,
+ type ElectricPointKind,
+ type ElectricRoute,
+ type Plan,
+ type Point,
+ type Wall,
+} from '../../model'
+import { fmtNum, t } from '../../i18n'
+
+export const EMPTY_ELECTRIC: ElectricNetwork = { points: [], circuits: [] }
+
+export const DEFAULT_CEILING = 2700
+export const ROUTE_BELOW_CEILING = 150
+export const PANEL_HEIGHT = 1700
+export const PANEL_TAIL = 1500
+export const CABLE_RESERVE = 0.15
+
+export const POINT_KINDS: ElectricPointKind[] = ['socket', 'socket2', 'socket_ip44', 'power', 'switch', 'switch2', 'light', 'light_wall', 'junction', 'outdoor']
+
+export const kindLabel = (k: ElectricPointKind) => t(`networks:electric.pointKind.${k}`)
+
+export const defaultHeight: Record<ElectricPointKind, number> = {
+ socket: 300,
+ socket2: 300,
+ socket_ip44: 1100,
+ power: 600,
+ switch: 900,
+ switch2: 900,
+ light: DEFAULT_CEILING,
+ light_wall: 2000,
+ junction: DEFAULT_CEILING - ROUTE_BELOW_CEILING,
+ outdoor: 1000,
+}
+
+export const defaultPower: Record<ElectricPointKind, number> = {
+ socket: 300,
+ socket2: 500,
+ socket_ip44: 500,
+ power: 3500,
+ switch: 0,
+ switch2: 0,
+ light: 50,
+ light_wall: 30,
+ junction: 0,
+ outdoor: 1000,
+}
+
+export const CIRCUIT_KINDS: ElectricCircuit['kind'][] = ['light', 'socket', 'power', 'wet', 'outdoor', 'garage']
+
+export const circuitKindLabel = (k: ElectricCircuit['kind']) => t(`networks:electric.circuitKind.${k}`)
+
+export const circuitPresets: Record<ElectricCircuit['kind'], Pick<ElectricCircuit, 'breaker' | 'cable'>> = {
+ light: { breaker: { type: 'MCB', rating: 10, curve: 'C' }, cable: '3x1.5' },
+ socket: { breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5' },
+ power: { breaker: { type: 'MCB', rating: 32, curve: 'C' }, cable: '3x6' },
+ wet: { breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5' },
+ outdoor: { breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5' },
+ garage: { breaker: { type: 'RCBO', rating: 16, curve: 'C' }, cable: '3x2.5' },
+}
+
+export const CABLES = ['3x1.5', '3x2.5', '3x4', '3x6', '5x2.5', '5x4', '5x6']
+export const RATINGS = [6, 10, 13, 16, 20, 25, 32, 40, 50, 63]
+
+export const CIRCUIT_COLORS = ['#e0452b', '#2a7de1', '#2f9e5b', '#9b4dca', '#d98a1d', '#0f9aa8', '#c2408f', '#6b7a1f', '#7a5230', '#4a55c9']
+export const NO_CIRCUIT_COLOR = '#8a8f98'
+
+export const isSocket = (k: ElectricPointKind) => k === 'socket' || k === 'socket2' || k === 'socket_ip44' || k === 'power' || k === 'outdoor'
+export const isSwitch = (k: ElectricPointKind) => k === 'switch' || k === 'switch2'
+export const isWallMounted = (k: ElectricPointKind) => k !== 'light'
+
+export const electricOf = (plan: Plan): ElectricNetwork => plan.networks?.electric ?? EMPTY_ELECTRIC
+
+export const withElectric = (plan: Plan, fn: (e: ElectricNetwork) => ElectricNetwork): Plan => ({
+ ...plan,
+ networks: { ...plan.networks, electric: fn(electricOf(plan)) },
+})
+
+export function circuitColor(e: ElectricNetwork, circuitId?: string) {
+ const i = circuitId ? e.circuits.findIndex((c) => c.id === circuitId) : -1
+ return i < 0 ? NO_CIRCUIT_COLOR : CIRCUIT_COLORS[i % CIRCUIT_COLORS.length]
+}
+
+export function parseCable(cable: string) {
+ const m = /^(\d+)\s*[xх×*]\s*(\d+(?:[.,]\d+)?)$/i.exec(cable.trim())
+ if (!m) return null
+ return { cores: Number(m[1]), section: Number(m[2].replace(',', '.')) }
+}
+
+export const cableLabel = (cable: string) => {
+ const c = parseCable(cable)
+ return c ? `${c.cores}×${fmtNum(c.section)}` : cable
+}
+
+export function ceilingOf(plan: Plan, wallId?: string) {
+ const w = wallId ? plan.walls.find((x) => x.id === wallId) : undefined
+ if (w) return w.height
+ const hs = plan.walls.map((x) => x.height)
+ return hs.length ? Math.max(...hs) : DEFAULT_CEILING
+}
+
+export function projectOnWall(p: Point, w: Wall) {
+ const dx = w.b.x - w.a.x
+ const dy = w.b.y - w.a.y
+ const l2 = dx * dx + dy * dy || 1
+ const t = Math.max(0, Math.min(1, ((p.x - w.a.x) * dx + (p.y - w.a.y) * dy) / l2))
+ const q = { x: w.a.x + dx * t, y: w.a.y + dy * t }
+ return { point: q, t, dist: Math.hypot(p.x - q.x, p.y - q.y) }
+}
+
+export function snapToWallFace(plan: Plan, p: Point, reach: number): { point: Point; wallId: string; normal: Point } | null {
+ let best: { point: Point; wallId: string; normal: Point; d: number } | null = null
+ for (const w of plan.walls) {
+ const pr = projectOnWall(p, w)
+ if (pr.dist > w.thickness / 2 + reach) continue
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) || 1
+ const n = { x: -(w.b.y - w.a.y) / len, y: (w.b.x - w.a.x) / len }
+ const side = (p.x - pr.point.x) * n.x + (p.y - pr.point.y) * n.y >= 0 ? 1 : -1
+ const face = { x: pr.point.x + n.x * side * (w.thickness / 2), y: pr.point.y + n.y * side * (w.thickness / 2) }
+ const d = pr.dist - w.thickness / 2
+ if (!best || d < best.d) best = { point: { x: Math.round(face.x), y: Math.round(face.y) }, wallId: w.id, normal: { x: n.x * side, y: n.y * side }, d }
+ }
+ return best && { point: best.point, wallId: best.wallId, normal: best.normal }
+}
+
+export function pointNormal(plan: Plan, p: { x: number; y: number; wallId?: string }): Point | null {
+ const w = p.wallId ? plan.walls.find((x) => x.id === p.wallId) : undefined
+ if (!w) return null
+ const pr = projectOnWall(p, w)
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) || 1
+ const n = { x: -(w.b.y - w.a.y) / len, y: (w.b.x - w.a.x) / len }
+ const side = (p.x - pr.point.x) * n.x + (p.y - pr.point.y) * n.y >= 0 ? 1 : -1
+ return { x: n.x * side, y: n.y * side }
+}
+
+export function addPoint(plan: Plan, pt: Omit<ElectricPoint, 'id'>): { plan: Plan; id: string } {
+ const id = nextId('ep', electricOf(plan).points)
+ return { plan: withElectric(plan, (e) => ({ ...e, points: [...e.points, { ...pt, id } as ElectricPoint] })), id }
+}
+
+export const updatePoints = (plan: Plan, ids: string[], patch: Partial<ElectricPoint>): Plan =>
+ withElectric(plan, (e) => ({ ...e, points: e.points.map((p) => (ids.includes(p.id) ? ({ ...p, ...patch } as ElectricPoint) : p)) }))
+
+export const deletePoints = (plan: Plan, ids: string[]): Plan =>
+ withElectric(plan, (e) => ({ ...e, points: e.points.filter((p) => !ids.includes(p.id)) }))
+
+export const setPanel = (plan: Plan, panel: ElectricPanel | undefined): Plan =>
+ withElectric(plan, (e) => {
+ const next = { ...e }
+ if (panel) next.panel = panel
+ else delete next.panel
+ return next
+ })
+
+export function addCircuit(plan: Plan, kind: ElectricCircuit['kind']): { plan: Plan; id: string } {
+ const e = electricOf(plan)
+ const id = nextId('c', e.circuits)
+ const n = e.circuits.filter((c) => c.kind === kind).length + 1
+ const circuit: ElectricCircuit = { id, name: t('networks:electric.circuitName', { kind: circuitKindLabel(kind), n }), kind, ...structuredClone(circuitPresets[kind]) }
+ return { plan: withElectric(plan, (x) => ({ ...x, circuits: [...x.circuits, circuit] })), id }
+}
+
+export const updateCircuit = (plan: Plan, id: string, patch: Partial<ElectricCircuit>): Plan =>
+ withElectric(plan, (e) => ({ ...e, circuits: e.circuits.map((c) => (c.id === id ? ({ ...c, ...patch } as ElectricCircuit) : c)) }))
+
+export const deleteCircuit = (plan: Plan, id: string): Plan =>
+ withElectric(plan, (e) => ({
+ ...e,
+ circuits: e.circuits.filter((c) => c.id !== id),
+ points: e.points.map((p) => {
+ if (p.circuitId !== id) return p
+ const rest = { ...p }
+ delete rest.circuitId
+ return rest
+ }),
+ ...(e.routes ? { routes: e.routes.filter((r) => r.circuitId !== id) } : {}),
+ }))
+
+export const setRoutes = (plan: Plan, circuitIds: string[], routes: ElectricRoute[]): Plan =>
+ withElectric(plan, (e) => ({ ...e, routes: [...(e.routes ?? []).filter((r) => !circuitIds.includes(r.circuitId)), ...routes] }))
+
+export const pathLength = (path: Point[]) => path.reduce((s, p, i) => (i ? s + Math.hypot(p.x - path[i - 1].x, p.y - path[i - 1].y) : 0), 0)
diff --git a/src/networks/electric/pricing.ts b/src/networks/electric/pricing.ts
new file mode 100644
index 0000000..b095682
--- /dev/null
+++ b/src/networks/electric/pricing.ts
@@ -0,0 +1,184 @@
+import type { NetworkMaterial } from '../../model'
+import type { CatalogItem } from '../../estimate/catalog'
+import type { ElectricItem } from './calc'
+import { t } from '../../i18n'
+
+export type PricedElectricItem = ElectricItem & { buyQty: number; buyUnit: string; price?: number; url?: string; priceFrom?: string }
+
+type Loose = Record<string, unknown> & {
+ id: string
+ name: string
+ kind?: string
+ subtype?: string
+ price?: number
+ unit?: string
+ pricePer?: string
+ length?: number
+ url?: string
+ vendor?: string
+ source?: string
+ preferred?: boolean
+}
+
+const num = (v: unknown) => {
+ const n = typeof v === 'string' ? Number(v.replace(',', '.')) : v
+ return typeof n === 'number' && Number.isFinite(n) ? n : undefined
+}
+const field = (x: Loose, ...keys: string[]) => {
+ for (const k of keys) {
+ const v = num(x[k])
+ if (v !== undefined) return v
+ }
+ return undefined
+}
+const text = (x: Loose) => `${x.name} ${typeof x.subtype === 'string' ? x.subtype : ''} ${typeof x.note === 'string' ? x.note : ''}`.toLowerCase()
+
+function cableOf(x: Loose) {
+ const cores = field(x, 'cores')
+ const section = field(x, 'section', 'crossSection')
+ if (cores && section) return { cores, section }
+ const s = typeof x.cable === 'string' ? x.cable : x.name
+ const m = /(\d)\s*[xх×*]\s*(\d+(?:[.,]\d+)?)/i.exec(s)
+ return m ? { cores: Number(m[1]), section: Number(m[2].replace(',', '.')) } : null
+}
+
+function breakerOf(x: Loose) {
+ const t = x.name
+ const cm = /(?:^|[\s(])([BCD])-?(\d{1,2})(?![\d,.])/.exec(t)
+ const rating = field(x, 'rating', 'current', 'amps') ?? num(/(\d{1,3})\s?[АA](?![а-яА-Яa-zA-Z])/.exec(t)?.[1]) ?? (cm ? Number(cm[2]) : undefined)
+ const curve = (typeof x.curve === 'string' ? x.curve : undefined) ?? cm?.[1]
+ const pm = /(\d)\s*[PР]\b|(\d)[- ]?полюс|(\d)п\b/i.exec(t)
+ const poles = field(x, 'poles') ?? (pm ? Number(pm[1] ?? pm[2] ?? pm[3]) : /1P\+N|1\+N/i.test(t) ? 2 : undefined)
+ const leakage = field(x, 'leakage', 'leakageMa', 'ma') ?? num(/(\d{2,3})\s*мА/i.exec(t)?.[1])
+ return { rating, curve, poles, leakage }
+}
+
+const lengthMm = (x: Loose) => {
+ const l = field(x, 'length', 'lengthM', 'coil')
+ if (l === undefined) return undefined
+ return l <= 1000 ? l * 1000 : l
+}
+const perMeter = (x: Loose) => /^(м|пог\.? ?м|м\.п\.|m)$/i.test((x.unit ?? '').trim()) || x.pricePer === 'm'
+
+function unitPrice(item: ElectricItem, x: Loose) {
+ if (x.price === undefined) return Infinity
+ if (item.unit !== 'm') return x.price
+ if (perMeter(x)) return x.price * item.qty
+ const l = lengthMm(x)
+ return l ? Math.ceil((item.qty * 1000) / l) * x.price : Infinity
+}
+
+const has = (t: string, ...words: string[]) => words.some((w) => t.includes(w))
+
+function fits(item: ElectricItem, x: Loose): boolean {
+ const sub = String(x.subtype ?? '').toLowerCase()
+ const t = text(x)
+ const sp = item.spec ?? {}
+ switch (item.kind) {
+ case 'cable': {
+ if (sub && sub !== 'cable') return false
+ const c = cableOf(x)
+ return !!c && c.cores === sp.cores && c.section === sp.section && !has(t, 'ппгнг-hf')
+ }
+ case 'conduit': {
+ if (sub && sub !== 'conduit') return false
+ const d = field(x, 'diameter') ?? num(/(?:d|ø|ф|диаметр)\s?(\d{2})|(\d{2})\s*мм/i.exec(x.name)?.slice(1).find(Boolean))
+ return d === sp.diameter
+ }
+ case 'box':
+ return (sub === 'box' || (!sub && has(t, 'подрозетник'))) && has(t, 'подрозетник', 'установочн', 'полых') && !has(t, 'распаеч', 'распред', 'соединител', 'клемм')
+ case 'frame': {
+ if (sub !== 'frame') return false
+ const posts = field(x, 'posts') ?? (has(t, 'одномест') ? 1 : undefined)
+ const aqua = (field(x, 'ip') ?? 0) >= 44 || has(t, 'aqua', 'ip44')
+ return posts === 1 && aqua === (sp.device === 'socket_ip44')
+ }
+ case 'panel': {
+ if (sub && sub !== 'panel') return false
+ const mods = field(x, 'modules') ?? num(/(\d{1,3})\s*мод/i.exec(x.name)?.[1]) ?? 0
+ return mods > 0 && mods >= (sp.modules ?? 0)
+ }
+ case 'breaker':
+ case 'main': {
+ if (sp.device === 'relay') return sub === 'relay' || has(t, 'реле напряж')
+ if (sub && sub !== 'breaker') return false
+ const b = breakerOf(x)
+ return b.rating === sp.rating && (!b.curve || !sp.curve || b.curve === sp.curve) && (!b.poles || b.poles === sp.poles)
+ }
+ case 'rcbo': {
+ if (sub && sub !== 'rcbo') return false
+ const b = breakerOf(x)
+ return b.rating === sp.rating && (!b.curve || b.curve === sp.curve) && (b.leakage ?? 30) === (sp.leakage ?? 30) && (!b.poles || b.poles === sp.poles || (sp.poles === 2 && b.poles === 1))
+ }
+ case 'rcd': {
+ if (sub && sub !== 'rcd') return false
+ const b = breakerOf(x)
+ return b.rating === sp.rating && (b.leakage ?? 30) === (sp.leakage ?? 30) && (!b.poles || b.poles === sp.poles)
+ }
+ case 'device': {
+ const d = sp.device
+ const double = has(t, 'двойн', 'двухмест', '2-мест', '2 мест', 'x2', '×2')
+ const wet = (field(x, 'ip') ?? 0) >= 44 || has(t, 'ip44', 'ip54', 'ip55', 'влагозащ')
+ if (d === 'light' || d === 'light_wall') {
+ if (sub ? sub !== 'light' : !has(t, 'светильник')) return false
+ const facade = has(t, 'фасадн', 'настен', 'бра', 'wall')
+ return d === 'light_wall' ? facade : !facade && !has(t, 'саун', 'бан')
+ }
+ if (d === 'switch' || d === 'switch2') {
+ if (sub ? sub !== 'switch' : !has(t, 'выключател') || has(t, 'автомат', 'дифф')) return false
+ const two = field(x, 'gangs') === 2 || has(t, 'двухклав', '2-клав', '2 клав', 'двухкноп')
+ if (wet || has(t, 'переключ', 'проходн', 'подсветк', 'трехклав', 'трёхклав')) return false
+ return d === 'switch2' ? two : !two
+ }
+ if (d === 'junction') return (sub === 'box' || sub === 'junction') && has(t, 'распаеч', 'распред', 'ответвит')
+ if (!d || !['socket', 'socket2', 'socket_ip44', 'outdoor', 'power'].includes(d)) return false
+ if (sub ? sub !== 'socket' : !has(t, 'розетк')) return false
+ if (d === 'power') return has(t, 'силов', '32 а', '32а', 'для плит', 'электроплит')
+ if (has(t, 'силов', 'для плит', 'компьютер', 'rj45', 'вывод кабел', 'телефон', 'tv', 'антенн')) return false
+ if (d === 'socket2') return double && !wet
+ if (d === 'socket_ip44') return wet && !double
+ if (d === 'outdoor') return wet && !double && has(t, 'накладн', 'наружн', 'уличн', 'ip54', 'ip55')
+ return !double && !wet
+ }
+ }
+ return false
+}
+
+const matches = (item: ElectricItem, x: Loose) => x.id === item.key || x.subtype === item.key || fits(item, x)
+
+function pick(item: ElectricItem, list: Loose[]) {
+ const all = list.filter((x) => matches(item, x) && x.price !== undefined)
+ if (!all.length) return undefined
+ const exact = all.filter((x) => x.id === item.key || x.subtype === item.key)
+ const pool0 = exact.length ? exact : all
+ const pref = pool0.filter((x) => x.preferred || (x.vendor ?? '').startsWith('Петрович'))
+ const pool = pref.length ? pref : pool0
+ const mods = (x: Loose) => (item.kind === 'panel' ? (field(x, 'modules') ?? 0) : 0)
+ return [...pool].sort((a, b) => mods(a) - mods(b) || Number(!!b.preferred) - Number(!!a.preferred) || unitPrice(item, a) - unitPrice(item, b))[0]
+}
+
+const unitLabel = (u: ElectricItem['unit']) => t(`common:units.${u}`)
+
+function priceFrom(item: ElectricItem, src: Loose, from: string): PricedElectricItem {
+ const base: PricedElectricItem = { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit), url: src.url, priceFrom: from }
+ if (src.price === undefined) return base
+ if (item.unit === 'm' && !perMeter(src)) {
+ const l = lengthMm(src)
+ if (l) return { ...base, buyQty: Math.ceil((item.qty * 1000) / l), buyUnit: unitLabel('pcs'), price: src.price }
+ }
+ return { ...base, price: src.price }
+}
+
+export function priceElectric(items: ElectricItem[], materials: NetworkMaterial[] | undefined, catalog: CatalogItem[]): PricedElectricItem[] {
+ const own = (materials ?? []) as unknown as Loose[]
+ const shop = catalog.filter((c) => c.kind === 'electric' || c.kind.startsWith('electric')) as unknown as Loose[]
+ return items.map((item) => {
+ const m = own.find((x) => matches(item, x))
+ if (m) return priceFrom(item, m, t('networks:electric.priceFromOwn', { name: `${m.name}${m.source ? `, ${m.source}` : ''}` }))
+ const c = pick(item, shop) ?? (item.spec?.device === 'light_wall' ? pick({ ...item, spec: { device: 'light' } }, shop) : undefined)
+ if (c) return priceFrom(item, c, `${c.name}${c.vendor ? `, ${c.vendor}` : ''}`)
+ return { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit) }
+ })
+}
+
+export const electricSum = (i: PricedElectricItem) => (i.price ?? 0) * i.buyQty
diff --git a/src/networks/electric/route.ts b/src/networks/electric/route.ts
new file mode 100644
index 0000000..4bfbec5
--- /dev/null
+++ b/src/networks/electric/route.ts
@@ -0,0 +1,166 @@
+import type { ElectricRoute, Plan, Point, Wall } from '../../model'
+import { electricOf, isWallMounted, projectOnWall } from './model'
+
+const MERGE = 30
+
+type Graph = { nodes: Point[]; adj: Map<number, { to: number; w: number }[]> }
+
+function makeGraph(): Graph & { node: (p: Point) => number; link: (a: number, b: number) => void } {
+ const nodes: Point[] = []
+ const adj = new Map<number, { to: number; w: number }[]>()
+ const node = (p: Point) => {
+ const i = nodes.findIndex((q) => Math.abs(q.x - p.x) <= MERGE && Math.abs(q.y - p.y) <= MERGE)
+ if (i >= 0) return i
+ nodes.push({ x: Math.round(p.x), y: Math.round(p.y) })
+ adj.set(nodes.length - 1, [])
+ return nodes.length - 1
+ }
+ const link = (a: number, b: number) => {
+ if (a === b) return
+ const w = Math.hypot(nodes[a].x - nodes[b].x, nodes[a].y - nodes[b].y)
+ adj.get(a)!.push({ to: b, w })
+ adj.get(b)!.push({ to: a, w })
+ }
+ return { nodes, adj, node, link }
+}
+
+function axisCross(p: Wall, q: Wall): Point | null {
+ const r = { x: p.b.x - p.a.x, y: p.b.y - p.a.y }
+ const s = { x: q.b.x - q.a.x, y: q.b.y - q.a.y }
+ const den = r.x * s.y - r.y * s.x
+ if (Math.abs(den) < 1e-9) return null
+ const t = ((q.a.x - p.a.x) * s.y - (q.a.y - p.a.y) * s.x) / den
+ const u = ((q.a.x - p.a.x) * r.y - (q.a.y - p.a.y) * r.x) / den
+ if (t < 0 || t > 1 || u < 0 || u > 1) return null
+ return { x: p.a.x + r.x * t, y: p.a.y + r.y * t }
+}
+
+function nearestWall(plan: Plan, p: Point, wallId?: string) {
+ const own = wallId ? plan.walls.find((w) => w.id === wallId) : undefined
+ if (own) return own
+ let best: Wall | null = null
+ let d = Infinity
+ for (const w of plan.walls) {
+ const pr = projectOnWall(p, w)
+ if (pr.dist < d) {
+ d = pr.dist
+ best = w
+ }
+ }
+ return best
+}
+
+function simplify(path: Point[]) {
+ const out: Point[] = []
+ for (const p of path) {
+ const last = out.at(-1)
+ if (last && Math.abs(last.x - p.x) < 1 && Math.abs(last.y - p.y) < 1) continue
+ if (out.length >= 2) {
+ const a = out[out.length - 2]
+ const b = out[out.length - 1]
+ const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
+ if (Math.abs(cross) < 1e-3 * Math.hypot(b.x - a.x, b.y - a.y) * Math.hypot(p.x - a.x, p.y - a.y) + 1) out.pop()
+ }
+ out.push(p)
+ }
+ return out
+}
+
+export function autoRoute(plan: Plan, circuitId: string): ElectricRoute[] {
+ const e = electricOf(plan)
+ const panel = e.panel
+ const terms = e.points.filter((p) => p.circuitId === circuitId)
+ if (!panel || !terms.length) return []
+
+ const g = makeGraph()
+ const onWall = new Map<string, Point[]>(plan.walls.map((w) => [w.id, [w.a, w.b]]))
+ for (const w of plan.walls) {
+ for (const q of plan.walls) {
+ if (q.id === w.id) continue
+ for (const end of [q.a, q.b]) {
+ const pr = projectOnWall(end, w)
+ if (pr.dist <= w.thickness / 2 + q.thickness / 2 + 20) onWall.get(w.id)!.push(pr.point)
+ }
+ const x = axisCross(w, q)
+ if (x) onWall.get(w.id)!.push(x)
+ }
+ }
+
+ const attach = (p: Point & { wallId?: string }, mounted: boolean) => {
+ const t = g.node(p)
+ const w = nearestWall(plan, p, mounted ? p.wallId : undefined)
+ if (!w) return t
+ const pr = projectOnWall(p, w)
+ onWall.get(w.id)!.push(pr.point)
+ return { t, proj: pr.point }
+ }
+
+ const links: { t: number; proj: Point }[] = []
+ const panelAt = attach({ x: panel.x, y: panel.y, wallId: panel.wallId }, true)
+ const termAt = terms.map((p) => attach(p, isWallMounted(p.kind)))
+ for (const a of [panelAt, ...termAt]) if (typeof a !== 'number') links.push(a)
+
+ for (const w of plan.walls) {
+ const pts = onWall.get(w.id)!
+ const sorted = pts
+ .map((p) => ({ p, t: projectOnWall(p, w).t }))
+ .sort((a, b) => a.t - b.t)
+ .map((x) => g.node(x.p))
+ for (let i = 1; i < sorted.length; i++) g.link(sorted[i - 1], sorted[i])
+ }
+ for (const l of links) g.link(l.t, g.node(l.proj))
+
+ const idx = (a: number | { t: number }) => (typeof a === 'number' ? a : a.t)
+ const root = idx(panelAt)
+ const tree = new Set<number>([root])
+ const left = new Set(termAt.map(idx))
+ left.delete(root)
+ const routes: ElectricRoute[] = []
+
+ while (left.size) {
+ const n = g.nodes.length
+ const dist = new Array<number>(n).fill(Infinity)
+ const prev = new Array<number>(n).fill(-1)
+ const done = new Array<boolean>(n).fill(false)
+ for (const t of tree) dist[t] = 0
+ for (;;) {
+ let u = -1
+ for (let i = 0; i < n; i++) if (!done[i] && dist[i] < Infinity && (u < 0 || dist[i] < dist[u])) u = i
+ if (u < 0) break
+ done[u] = true
+ if (left.has(u)) break
+ for (const { to, w } of g.adj.get(u)!) {
+ if (dist[u] + w < dist[to]) {
+ dist[to] = dist[u] + w
+ prev[to] = u
+ }
+ }
+ }
+ let target = -1
+ for (const t of left) if (dist[t] < Infinity && (target < 0 || dist[t] < dist[target])) target = t
+ if (target < 0) {
+ const t = [...left][0]
+ const from = [...tree].reduce((m, x) =>
+ Math.abs(g.nodes[x].x - g.nodes[t].x) + Math.abs(g.nodes[x].y - g.nodes[t].y) <
+ Math.abs(g.nodes[m].x - g.nodes[t].x) + Math.abs(g.nodes[m].y - g.nodes[t].y)
+ ? x
+ : m,
+ )
+ const a = g.nodes[from]
+ const b = g.nodes[t]
+ routes.push({ circuitId, path: simplify([a, { x: b.x, y: a.y }, b]) })
+ tree.add(t)
+ left.delete(t)
+ continue
+ }
+ const chain: number[] = []
+ for (let c = target; c >= 0; c = tree.has(c) ? -1 : prev[c]) chain.unshift(c)
+ chain.forEach((c) => {
+ tree.add(c)
+ left.delete(c)
+ })
+ const path = simplify(chain.map((c) => g.nodes[c]))
+ if (path.length >= 2) routes.push({ circuitId, path })
+ }
+ return routes
+}
diff --git a/src/networks/electric/store.ts b/src/networks/electric/store.ts
new file mode 100644
index 0000000..b394c33
--- /dev/null
+++ b/src/networks/electric/store.ts
@@ -0,0 +1,38 @@
+import { create } from 'zustand'
+import type { ElectricPointKind } from '../../model'
+
+export type ElectricTool = null | 'socket' | 'switch' | 'light' | 'panel'
+
+type ElectricUiState = {
+ tool: ElectricTool
+ socketKind: ElectricPointKind
+ switchKind: ElectricPointKind
+ lightKind: ElectricPointKind
+ activeCircuit: string | null
+ selected: string[]
+ panelSelected: boolean
+ tab: boolean
+ setTool: (tool: ElectricTool) => void
+ setKind: (tool: 'socket' | 'switch' | 'light', kind: ElectricPointKind) => void
+ setActiveCircuit: (id: string | null) => void
+ select: (ids: string[]) => void
+ selectPanel: (on: boolean) => void
+ setTab: (on: boolean) => void
+}
+
+export const useElectricUi = create<ElectricUiState>()((set) => ({
+ tool: null,
+ socketKind: 'socket',
+ switchKind: 'switch',
+ lightKind: 'light',
+ activeCircuit: null,
+ selected: [],
+ panelSelected: false,
+ tab: false,
+ setTool: (tool) => set({ tool }),
+ setKind: (tool, kind) => set(tool === 'socket' ? { socketKind: kind } : tool === 'switch' ? { switchKind: kind } : { lightKind: kind }),
+ setActiveCircuit: (activeCircuit) => set({ activeCircuit }),
+ select: (selected) => set({ selected, panelSelected: false }),
+ selectPanel: (panelSelected) => set({ panelSelected, selected: [] }),
+ setTab: (tab) => set({ tab }),
+}))
diff --git a/src/networks/estimate.ts b/src/networks/estimate.ts
new file mode 100644
index 0000000..c89fedc
--- /dev/null
+++ b/src/networks/estimate.ts
@@ -0,0 +1,54 @@
+import type { Plan } from '../model'
+import type { CatalogItem } from '../estimate/catalog'
+import { computeSewer } from './sewerCalc'
+import { priceAll } from './pricing'
+import { sewerOf } from './sewerModel'
+import { computeWater } from './waterCalc'
+import { priceWater } from './waterPricing'
+import { waterOf } from './waterModel'
+import { t } from '../i18n'
+
+export const sewerGroup = () => t('networks:shared.layers.sewer')
+
+export type SewerEstimateRow = {
+ id: string
+ name: string
+ url?: string
+ qty: number
+ unit: string
+ price?: number
+ priceFrom?: string
+ group: string
+}
+
+export function sewerEstimateRows(plan: Plan, catalog: CatalogItem[]): SewerEstimateRow[] {
+ const s = sewerOf(plan)
+ if (!s.pipes.length && !s.nodes.length) return []
+ return priceAll(computeSewer(plan).items, s.materials, catalog).map((i) => ({
+ id: `auto:sewer:${i.key}`,
+ name: i.name,
+ url: i.url,
+ qty: i.buyQty,
+ unit: i.buyUnit,
+ price: i.price,
+ priceFrom: i.priceFrom,
+ group: sewerGroup(),
+ }))
+}
+
+export const waterGroup = () => t('networks:shared.layers.water')
+
+export function waterEstimateRows(plan: Plan, catalog: CatalogItem[]): SewerEstimateRow[] {
+ const w = waterOf(plan)
+ if (!w.pipes.length && !w.nodes.length) return []
+ return priceWater(computeWater(plan).items, w.materials, catalog).map((i) => ({
+ id: `auto:water:${i.key}`,
+ name: i.name,
+ url: i.url,
+ qty: i.buyQty,
+ unit: i.buyUnit,
+ price: i.price,
+ priceFrom: i.priceFrom,
+ group: waterGroup(),
+ }))
+}
diff --git a/src/networks/heating/HeatingLayer.tsx b/src/networks/heating/HeatingLayer.tsx
new file mode 100644
index 0000000..3fb3544
--- /dev/null
+++ b/src/networks/heating/HeatingLayer.tsx
@@ -0,0 +1,291 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Group, Layer, Line, Rect, Text } from 'react-konva'
+import type Konva from 'konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import type { HeatingLoop, Plan, Point } from '../../model'
+import { fmtNum, t } from '../../i18n'
+import { usePlanStore } from '../../store/planStore'
+import { pointInPolygon } from '../../stats/rooms'
+import { useLayers } from '../layers'
+import { useNetworkEdit } from '../registry'
+import { useSewerUi } from '../sewerStore'
+import { computeHeating, type LoopCalc } from './calc'
+import { snakeLines, spiralRings } from './geometry'
+import { rerouteAll } from './layout'
+import { allPolygons, deleteLoop, heatingOf, setCollector, withHeating } from './model'
+import { useHeatingUi } from './store'
+
+type Props = {
+ plan: Plan
+ scale: number
+ viewRot: number
+ worldPointer: () => Point | null
+ interactive: boolean
+}
+
+const INK = '#2b2d33'
+const SELECT = '#f26b1d'
+const FONT = 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif'
+const HOT = [198, 40, 40]
+const WARM = [239, 154, 154]
+const COOL = [144, 202, 249]
+const COLD = [21, 101, 192]
+
+const mix = (a: number[], b: number[], t: number) => `rgb(${a.map((v, i) => Math.round(v + (b[i] - v) * Math.max(0, Math.min(1, t)))).join(',')})`
+
+const isTyping = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable
+}
+
+type Stroke = { points: number[]; color: string }
+
+function loopStrokes(loop: HeatingLoop): Stroke[] {
+ const link = loop.linkPath
+ const partEntry = link?.length ? link[link.length - 1] : undefined
+ return [
+ ...zoneStrokes(loop, loop.supplyPath?.length ? loop.supplyPath[loop.supplyPath.length - 1] : undefined),
+ ...(loop.parts ?? []).flatMap((p) => zoneStrokes({ ...loop, polygon: p.polygon, excluded: p.excluded }, partEntry)),
+ ]
+}
+
+function zoneStrokes(loop: HeatingLoop, entry: Point | undefined): Stroke[] {
+ if (loop.pattern === 'snake') {
+ const path = snakeLines(loop)
+ const n = path.length
+ if (n < 2) return []
+ const out: Stroke[] = []
+ const chunk = Math.max(2, Math.ceil(n / 24))
+ for (let i = 0; i < n - 1; i += chunk) {
+ const seg = path.slice(i, Math.min(n, i + chunk + 1))
+ const t = i / (n - 1)
+ out.push({ points: seg.flatMap((p) => [p.x, p.y]), color: t < 0.5 ? mix(HOT, WARM, t * 2) : mix(COOL, COLD, (t - 0.5) * 2) })
+ }
+ return out
+ }
+ const rings = spiralRings(loop, entry)
+ const k = rings.reduce((m, r) => Math.max(m, r.order), 0) + 1
+ const nS = Math.ceil(k / 2)
+ const nR = Math.floor(k / 2)
+ return rings.map((r) => {
+ const idx = r.supply ? r.order / 2 : (r.order - 1) / 2
+ const t = idx / Math.max(1, (r.supply ? nS : nR) - 1)
+ return { points: r.path.flatMap((p) => [p.x, p.y]), color: r.supply ? mix(HOT, WARM, t) : mix(COLD, COOL, t) }
+ })
+}
+
+function Tag({ at, lines, scale, viewRot }: { at: Point; lines: string[]; scale: number; viewRot: number }) {
+ const w = Math.max(...lines.map((l) => l.length)) * 6.3 + 14
+ const h = lines.length * 15 + 8
+ return (
+ <Group x={at.x} y={at.y} scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot} listening={false}>
+ <Rect x={-w / 2} y={-h - 14} width={w} height={h} cornerRadius={4} fill="#ffffff" stroke={INK} strokeWidth={0.6} opacity={0.96} />
+ <Text x={-w / 2} y={-h - 9} width={w} align="center" text={lines.join('\n')} lineHeight={1.3} fontSize={11} fontFamily={FONT} fill={INK} />
+ </Group>
+ )
+}
+
+function loopTagLines(c: LoopCalc) {
+ return [
+ c.roomName,
+ `${t('networks:heating.tag.length', { len: Math.round(c.lengthM), step: c.loop.stepMm })}${c.loop.pattern === 'snake' ? t('networks:heating.tag.snake') : ''}`,
+ t('networks:heating.tag.area', { area: fmtNum(c.areaM2, 1, 1), power: Math.round(c.powerW), q: Math.round(c.qWm2) }),
+ ]
+}
+
+export function HeatingLayer(props: Props) {
+ const on = useLayers((s) => s.heating)
+ return on ? <HeatingLayerInner {...props} /> : null
+}
+
+function HeatingLayerInner({ plan, scale, viewRot, worldPointer, interactive }: Props) {
+ const editing = useNetworkEdit((st) => st.editing === 'heating') && interactive
+ const selected = useHeatingUi((s) => s.selected)
+ const collectorSelected = useHeatingUi((s) => s.collectorSelected)
+ const commit = usePlanStore((s) => s.commit)
+ const planTool = usePlanStore((s) => s.tool)
+ const [hover, setHover] = useState<{ id: string; at: Point } | null>(null)
+ const [preview, setPreview] = useState<Plan | null>(null)
+ const layerRef = useRef<Konva.Layer>(null)
+ const shownPlan = preview ?? plan
+ const h = heatingOf(shownPlan)
+ const calc = useMemo(() => computeHeating(plan), [plan])
+ const strokes = useMemo(() => new Map(h.loops.map((l) => [l.id, loopStrokes(l)])), [h.loops])
+ const editable = editing && planTool === 'select'
+
+ useEffect(
+ () =>
+ usePlanStore.subscribe((st, prev) => {
+ const picked = st.selectedWallId || st.selectedOpeningId || st.selectedFurnitureId || st.selectedZoneId || st.group
+ const was = prev.selectedWallId || prev.selectedOpeningId || prev.selectedFurnitureId || prev.selectedZoneId || prev.group
+ if (picked && picked !== was) useHeatingUi.getState().select(null)
+ }),
+ [],
+ )
+
+ useEffect(
+ () =>
+ useSewerUi.subscribe((st, prev) => {
+ if (st.selected && !prev.selected) useHeatingUi.getState().select(null)
+ }),
+ [],
+ )
+
+ useEffect(() => {
+ const stage = layerRef.current?.getStage()
+ if (!stage) return
+ const find = () => {
+ const p = worldPointer()
+ if (!p) return null
+ const loops = heatingOf(usePlanStore.getState().plan ?? plan).loops
+ const hit = [...loops].reverse().find((l) => allPolygons(l).some((poly) => pointInPolygon(p, poly)))
+ return hit ? { id: hit.id, at: p } : null
+ }
+ const onMove = () => {
+ if (useNetworkEdit.getState().editing === 'heating') return
+ const f = find()
+ setHover((cur) => (f?.id === cur?.id ? cur : f))
+ }
+ const onClick = (ev: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if (ev.target === stage) useHeatingUi.getState().select(null)
+ if (ev.type === 'tap') setHover(find())
+ }
+ stage.on('mousemove.heating', onMove)
+ stage.on('mouseleave.heating', () => setHover(null))
+ stage.on('click.heating tap.heating', onClick)
+ return () => {
+ stage.off('mousemove.heating mouseleave.heating click.heating tap.heating')
+ }
+ }, [worldPointer, plan])
+
+ useEffect(() => {
+ const down = (ev: KeyboardEvent) => {
+ if (isTyping(ev) || ev.metaKey || ev.ctrlKey || !editing) return
+ if (ev.key !== 'Delete' && ev.key !== 'Backspace') return
+ const ui = useHeatingUi.getState()
+ const current = usePlanStore.getState().plan
+ if (!current || !ui.selected) return
+ ev.preventDefault()
+ commit(deleteLoop(current, ui.selected))
+ ui.select(null)
+ }
+ window.addEventListener('keydown', down)
+ return () => window.removeEventListener('keydown', down)
+ }, [editing, commit])
+
+ const collectorDrag = (ev: KonvaEventObject<DragEvent>, end: boolean) => {
+ const current = usePlanStore.getState().plan
+ const col = current && heatingOf(current).collector
+ if (!current || !col) return
+ const at = { x: Math.round(ev.target.x() / 10) * 10, y: Math.round(ev.target.y() / 10) * 10 }
+ ev.target.position(at)
+ const moved = setCollector(current, { ...col, ...at })
+ if (end) {
+ setPreview(null)
+ commit(withHeating(moved, () => rerouteAll(moved)))
+ } else setPreview(moved)
+ }
+
+ const pickLoop = (id: string) => (ev: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ ev.cancelBubble = true
+ if (!editing) return
+ usePlanStore.getState().selectWall(null)
+ useSewerUi.getState().select(null)
+ useHeatingUi.getState().select(id)
+ }
+
+ const thin = 1 / scale
+ const hoverCalc = hover ? calc.loops.find((c) => c.loop.id === hover.id) : undefined
+ const col = h.collector
+ const colW = col ? 16 + col.outputs * 3 : 0
+
+ return (
+ <Layer ref={layerRef}>
+ {h.loops.map((l) => (
+ <Group key={l.id} opacity={l.off ? 0.25 : 1} listening={false}>
+ {(strokes.get(l.id) ?? []).map((s, i) => (
+ <Line key={i} points={s.points} stroke={s.color} strokeWidth={Math.max(thin * 1.1, Math.min(16, 0.12 * l.stepMm))} lineJoin="round" lineCap="round" perfectDrawEnabled={false} />
+ ))}
+ {[...(l.excluded ?? []), ...(l.parts ?? []).flatMap((q) => q.excluded ?? [])].map((e, i) => (
+ <Line key={`x${i}`} points={e.flatMap((p) => [p.x, p.y])} closed stroke="#8a8f98" strokeWidth={thin} dash={[4 * thin, 3 * thin]} fill="rgba(138,143,152,0.12)" />
+ ))}
+ </Group>
+ ))}
+ {h.loops.flatMap((l) =>
+ [l.supplyPath, l.linkPath].map((path, pi) =>
+ path && path.length > 1 ? (
+ <Group key={`sp-${l.id}-${pi}`} opacity={l.off ? 0.25 : 0.95} listening={false}>
+ <Line points={path.flatMap((p) => [p.x, p.y])} stroke="rgb(198,40,40)" strokeWidth={1.4 * thin} dash={[6 * thin, 6 * thin]} lineJoin="round" />
+ <Line points={path.flatMap((p) => [p.x, p.y])} stroke="rgb(21,101,192)" strokeWidth={1.4 * thin} dash={[6 * thin, 6 * thin]} dashOffset={6 * thin} lineJoin="round" />
+ </Group>
+ ) : null,
+ ),
+ )}
+ {h.loops.flatMap((l) => allPolygons(l).map((poly, pi) => (
+ <Line
+ key={`hit-${l.id}-${pi}`}
+ points={poly.flatMap((p) => [p.x, p.y])}
+ closed
+ fill={editing ? 'rgba(0,0,0,0.001)' : undefined}
+ stroke={selected === l.id ? SELECT : hover?.id === l.id ? INK : undefined}
+ strokeWidth={(selected === l.id ? 2.2 : 1) * thin}
+ dash={l.off ? [5 * thin, 4 * thin] : undefined}
+ listening={editing}
+ onMouseDown={(ev) => {
+ if (ev.evt.button === 0) ev.cancelBubble = true
+ }}
+ onClick={pickLoop(l.id)}
+ onTap={pickLoop(l.id)}
+ onMouseEnter={(ev) => {
+ const p = worldPointer()
+ if (p) setHover({ id: l.id, at: p })
+ const st = ev.target.getStage()
+ if (st) st.container().style.cursor = 'pointer'
+ }}
+ onMouseLeave={(ev) => {
+ setHover((cur) => (cur?.id === l.id ? null : cur))
+ const st = ev.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ />
+ )))}
+ {col && (
+ <Group
+ x={col.x}
+ y={col.y}
+ draggable={editable}
+ listening={editing}
+ onDragMove={(ev) => collectorDrag(ev, false)}
+ onDragEnd={(ev) => collectorDrag(ev, true)}
+ onMouseDown={(ev) => {
+ ev.cancelBubble = true
+ }}
+ onClick={(ev) => {
+ ev.cancelBubble = true
+ if (!editing) return
+ usePlanStore.getState().selectWall(null)
+ useHeatingUi.getState().selectCollector(true)
+ }}
+ onMouseEnter={(ev) => {
+ const st = ev.target.getStage()
+ if (st && editable) st.container().style.cursor = 'move'
+ }}
+ onMouseLeave={(ev) => {
+ const st = ev.target.getStage()
+ if (st) st.container().style.cursor = ''
+ }}
+ >
+ <Group scaleX={1 / scale} scaleY={1 / scale} rotation={-viewRot}>
+ {collectorSelected && <Rect x={-colW / 2 - 5} y={-14} width={colW + 10} height={28} cornerRadius={6} fill="rgba(242, 107, 29, 0.28)" />}
+ <Rect x={-colW / 2} y={-9} width={colW} height={18} cornerRadius={2} fill="#ffffff" stroke={INK} strokeWidth={1.4} />
+ <Rect x={-colW / 2} y={-9} width={colW} height={4} fill="rgb(198,40,40)" />
+ <Rect x={-colW / 2} y={5} width={colW} height={4} fill="rgb(21,101,192)" />
+ <Text x={-colW / 2} y={-5} width={colW} align="center" text={String(col.outputs)} fontSize={10} fontStyle="bold" fontFamily={FONT} fill={INK} />
+ </Group>
+ </Group>
+ )}
+ {hover && hoverCalc && <Tag at={hover.at} lines={loopTagLines(hoverCalc)} scale={scale} viewRot={viewRot} />}
+ {hover && !hoverCalc && h.loops.find((l) => l.id === hover.id)?.off && <Tag at={hover.at} lines={[t('networks:heating.tag.excluded', { room: h.loops.find((l) => l.id === hover.id)?.roomName ?? '' })]} scale={scale} viewRot={viewRot} />}
+ </Layer>
+ )
+}
diff --git a/src/networks/heating/HeatingPanel.tsx b/src/networks/heating/HeatingPanel.tsx
new file mode 100644
index 0000000..0a802a3
--- /dev/null
+++ b/src/networks/heating/HeatingPanel.tsx
@@ -0,0 +1,441 @@
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { HeatingLoop, HeatingStep, Plan } from '../../model'
+import { formatMoney } from '../../model'
+import { fmtNum } from '../../i18n'
+import { unitLabel } from '../../i18n/units'
+import { usePlanStore } from '../../store/planStore'
+import { useViewOnly } from '../../store/viewOnly'
+import { useCatalog } from '../../estimate/catalog'
+import { Button, IconButton, Input, Segmented, Table, Td, Th, Tr } from '../../ui'
+import { computeHeating, coverLabel, type HeatingWarning } from './calc'
+import { rerouteAll } from './layout'
+import { PIPES, STEPS, deleteLoop, heatingOf, paramsOf, setCollector, setParams, updateLoop, withHeating } from './model'
+import { heatingSum, noPrice, priceHeating } from './pricing'
+import { useHeatingUi } from './store'
+import { useLayerLocks } from '../locks'
+import { useNetworkEdit } from '../registry'
+import { runAutoLayout } from './actions'
+import './heating.css'
+
+const fmt = (v: number, d = 1) => fmtNum(v, d)
+
+const CLOSE_ICON = (
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+)
+
+const STEP_OPTIONS = STEPS.map((s) => ({ value: String(s), label: `${s}` }))
+const PATTERNS = ['spiral', 'snake'] as const
+
+export type HeatingSelection = { loop: HeatingLoop | null; collector: boolean }
+
+export function useHeatingSelection(plan: Plan | null): HeatingSelection | null {
+ const selected = useHeatingUi((s) => s.selected)
+ const collectorSelected = useHeatingUi((s) => s.collectorSelected)
+ if (!plan) return null
+ const h = heatingOf(plan)
+ if (collectorSelected && h.collector) return { loop: null, collector: true }
+ const loop = selected ? h.loops.find((l) => l.id === selected) : undefined
+ return loop ? { loop, collector: false } : null
+}
+
+export function HeatingInspector({ plan, sel }: { plan: Plan; sel: HeatingSelection }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const select = useHeatingUi((s) => s.select)
+ const calc = useMemo(() => computeHeating(plan), [plan])
+ const h = heatingOf(plan)
+
+ if (sel.collector && h.collector) {
+ const col = h.collector
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <IconButton label={t('heating.panel.clearSelection')} size="sm" className="inspector__close" onClick={() => select(null)}>
+ {CLOSE_ICON}
+ </IconButton>
+ <div className="eyebrow">{t('heating.layer')}</div>
+ <div className="inspector__title">{t('heating.panel.collector')}</div>
+ </div>
+ <dl className="props">
+ <dt>{t('heating.panel.loops')}</dt>
+ <dd>{calc.loops.length}</dd>
+ <dt>{t('heating.panel.flow')}</dt>
+ <dd>{t('heating.panel.flowM3h', { v: fmt(calc.totals.flowLh / 1000, 2) })}</dd>
+ <dt>{t('heating.panel.pump')}</dt>
+ <dd>{t('heating.panel.head', { v: fmt(calc.totals.pumpKPa / 9.81) })}</dd>
+ </dl>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.outputs')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={1}
+ max={24}
+ step={1}
+ className="hp-num"
+ value={col.outputs}
+ onChange={(ev) => {
+ const v = Math.round(Number(ev.target.value))
+ if (v > 0) commit(setCollector(plan, { ...col, outputs: v }))
+ }}
+ />
+ </label>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.label')}</span>
+ <Input
+ size="sm"
+ className="hp-text"
+ value={col.label ?? ''}
+ onChange={(ev) => {
+ const next = { ...col }
+ if (ev.target.value) next.label = ev.target.value
+ else delete next.label
+ commit(setCollector(plan, next))
+ }}
+ />
+ </label>
+ <div className="inspector__actions">
+ <Button size="sm" variant="ghost" onClick={() => commit(withHeating(plan, () => rerouteAll(plan)))}>
+ {t('heating.panel.reroute')}
+ </Button>
+ </div>
+ </aside>
+ )
+ }
+
+ const loop = sel.loop
+ if (!loop) return null
+ const c = calc.loops.find((x) => x.loop.id === loop.id)
+ const patch = (p: Partial<HeatingLoop>) => commit(updateLoop(plan, loop.id, p))
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <IconButton label={t('heating.panel.clearSelection')} size="sm" className="inspector__close" onClick={() => select(null)}>
+ {CLOSE_ICON}
+ </IconButton>
+ <div className="eyebrow">{t('heating.panel.loopEyebrow', { id: loop.id })}</div>
+ <div className="inspector__title">{loop.roomName ?? loop.id}</div>
+ </div>
+ {c ? (
+ <dl className="props">
+ <dt>{t('heating.panel.area')}</dt>
+ <dd>{fmt(c.areaM2)} {t('common:units.m2')}</dd>
+ <dt>{t('heating.panel.pipe')}</dt>
+ <dd>
+ {Math.round(c.lengthM)} {t('common:units.m')} <span className="muted">{t('heating.panel.feed', { v: fmt(c.feedM) })}</span>
+ </dd>
+ <dt>{t('heating.panel.power')}</dt>
+ <dd>
+ {Math.round(c.powerW)} {t('common:units.w')} · {Math.round(c.qWm2)} {t('heating.panel.wm2')}
+ </dd>
+ <dt>{t('heating.panel.floor')}</dt>
+ <dd>
+ {coverLabel(c.cover)}, ≈{fmt(c.floorT)} °C
+ </dd>
+ <dt>{t('heating.panel.flow')}</dt>
+ <dd>
+ {fmt(c.flowLmin, 2)} {t('heating.panel.lmin')} · {fmt(c.dpKPa)} {t('heating.panel.kpa')}
+ </dd>
+ </dl>
+ ) : (
+ <p className="muted">{t('heating.panel.excludedFromCalc')}</p>
+ )}
+ <div className="hp-form">
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.step')}</span>
+ <Segmented size="sm" value={String(loop.stepMm)} options={STEP_OPTIONS} onChange={(v) => patch({ stepMm: Number(v) as HeatingStep })} />
+ </label>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.pattern')}</span>
+ <Segmented size="sm" value={loop.pattern} options={PATTERNS.map((v) => ({ value: v, label: t(`heating.panel.${v}`) }))} onChange={(v) => patch({ pattern: v as HeatingLoop['pattern'] })} />
+ </label>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.pipe')}</span>
+ <select className="select" value={loop.pipe} onChange={(ev) => patch({ pipe: ev.target.value })}>
+ {[...new Set([...PIPES, loop.pipe])].map((p) => (
+ <option key={p} value={p}>
+ {p}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <div className="inspector__actions">
+ <Button size="sm" variant="ghost" onClick={() => patch({ off: loop.off ? undefined : true })}>
+ {loop.off ? t('heating.panel.include') : t('heating.panel.exclude')}
+ </Button>
+ <Button
+ size="sm"
+ variant="danger"
+ onClick={() => {
+ commit(deleteLoop(plan, loop.id))
+ select(null)
+ }}
+ >
+ {t('heating.panel.deleteLoop')}
+ </Button>
+ </div>
+ </aside>
+ )
+}
+
+function Warnings({ list }: { list: HeatingWarning[] }) {
+ const { t } = useTranslation('networks')
+ const select = useHeatingUi((s) => s.select)
+ if (!list.length) return <p className="muted">{t('heating.panel.noWarnings')}</p>
+ return (
+ <div className="hp-warnings">
+ {list.map((w, i) => (
+ <button key={i} type="button" className={`hp-warning hp-warning--${w.level}`} onClick={() => w.loopId && select(w.loopId)}>
+ {w.text}
+ </button>
+ ))}
+ </div>
+ )
+}
+
+export function HeatingSummary({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('networks')
+ const commit = usePlanStore((s) => s.commit)
+ const locked = useLayerLocks().heating
+ const viewOnly = useViewOnly() || locked
+ const editing = useNetworkEdit((s) => s.editing === 'heating')
+ const catalog = useCatalog()
+ const selected = useHeatingUi((s) => s.selected)
+ const select = useHeatingUi((s) => s.select)
+ const h = heatingOf(plan)
+ const p = paramsOf(h)
+ const calc = useMemo(() => computeHeating(plan), [plan])
+ const priced = useMemo(() => priceHeating(calc.items, h.materials, catalog), [calc, h.materials, catalog])
+ const total = priced.reduce((s, i) => s + heatingSum(i), 0)
+ const missing = priced.filter((i) => i.price === undefined).length
+ const tot = calc.totals
+ const num = (key: 'supplyT' | 'returnT' | 'screedMm' | 'floorT', label: string, unit: string, placeholder?: string) => (
+ <label className="row row--center hp-field">
+ <span>{label}</span>
+ <span className="hp-pair">
+ <Input
+ size="sm"
+ type="number"
+ className="hp-num"
+ disabled={viewOnly}
+ value={h.params?.[key] ?? (placeholder ? '' : p[key] ?? '')}
+ placeholder={placeholder}
+ onChange={(ev) => {
+ const v = ev.target.value === '' ? undefined : Number(ev.target.value)
+ if (v === undefined || Number.isFinite(v)) commit(setParams(plan, { [key]: v }))
+ }}
+ />
+ <span className="muted">{unit}</span>
+ </span>
+ </label>
+ )
+
+ return (
+ <div className="hp-summary">
+ <div className="inspector__head">
+ <div className="eyebrow">{t('heating.panel.layerEyebrow')}</div>
+ <div className="inspector__title">{t('heating.layer')}</div>
+ </div>
+ {!viewOnly && (
+ <div className="hp-actions">
+ <Button size="sm" onClick={runAutoLayout}>
+ {t('heating.tools.autoLayout')}
+ </Button>
+ {h.collector && h.loops.length > 0 && (
+ <Button size="sm" variant="ghost" onClick={() => commit(withHeating(plan, () => rerouteAll(plan)))}>
+ {t('heating.panel.reroute')}
+ </Button>
+ )}
+ </div>
+ )}
+ <dl className="props">
+ <dt>{t('heating.panel.loops')}</dt>
+ <dd>
+ {calc.loops.length}
+ {h.loops.length > calc.loops.length ? t('heating.panel.excludedCount', { n: h.loops.length - calc.loops.length }) : ''}
+ </dd>
+ <dt>{t('heating.panel.area')}</dt>
+ <dd>{fmt(tot.areaM2)} {t('common:units.m2')}</dd>
+ <dt>{t('heating.panel.pipe')}</dt>
+ <dd>{Math.round(tot.pipeM)} {t('common:units.m')}</dd>
+ <dt>{t('heating.panel.floorGives')}</dt>
+ <dd>{fmt(tot.powerW / 1000, 2)} {t('common:units.kw')}</dd>
+ <dt>{t('heating.panel.heatLoss')}</dt>
+ <dd>≈{fmt(tot.lossW / 1000, 2)} {t('common:units.kw')}</dd>
+ <dt>{t('heating.panel.boiler')}</dt>
+ <dd>{t('heating.panel.boilerFrom', { v: tot.boilerKW })}</dd>
+ <dt>{t('heating.panel.unit')}</dt>
+ <dd>
+ {t('heating.panel.unitValue', { flow: fmt(tot.flowLh / 1000, 2), head: fmt(tot.pumpKPa / 9.81) })}
+ </dd>
+ <dt>{t('heating.panel.collector')}</dt>
+ <dd>{h.collector ? t('heating.panel.collectorOutputs', { n: h.collector.outputs }) : t('heating.panel.notPlaced')}</dd>
+ </dl>
+
+ <div className="inspector__section">
+ <strong>{t('heating.panel.loopsTitle')}</strong>
+ {h.loops.length === 0 ? (
+ <p className="muted">{t('heating.panel.noLoops')}</p>
+ ) : (
+ <Table dense className="hp-table">
+ <thead>
+ <tr>
+ <Th>{t('heating.panel.room')}</Th>
+ <Th num>{t('common:units.m2')}</Th>
+ <Th num>{t('heating.panel.colStep')}</Th>
+ <Th num>{t('common:units.m')}</Th>
+ <Th num>{t('common:units.w')}</Th>
+ </tr>
+ </thead>
+ <tbody>
+ {h.loops.map((l) => {
+ const c = calc.loops.find((x) => x.loop.id === l.id)
+ return (
+ <Tr key={l.id} className={`hp-row ${selected === l.id ? 'hp-row--active' : ''} ${l.off ? 'hp-row--off' : ''}`} onClick={() => editing && select(selected === l.id ? null : l.id)}>
+ <Td>
+ {l.roomName ?? l.id}
+ {c && (
+ <div className="muted hp-sub">
+ {coverLabel(c.cover)} · {fmt(c.flowLmin, 2)} {t('heating.panel.lmin')} · {fmt(c.dpKPa)} {t('heating.panel.kpa')}
+ </div>
+ )}
+ </Td>
+ <Td num>{c ? fmt(c.areaM2) : '—'}</Td>
+ <Td num>{l.stepMm}</Td>
+ <Td num className={c && c.lengthM > 80 ? 'hp-bad' : undefined}>
+ {c ? Math.round(c.lengthM) : '—'}
+ </Td>
+ <Td num>{c ? Math.round(c.powerW) : '—'}</Td>
+ </Tr>
+ )
+ })}
+ </tbody>
+ <tfoot>
+ <tr className="hp-total">
+ <Td>{t('heating.panel.total')}</Td>
+ <Td num>{fmt(tot.areaM2)}</Td>
+ <Td num />
+ <Td num>{Math.round(tot.pipeM)}</Td>
+ <Td num>{Math.round(tot.powerW)}</Td>
+ </tr>
+ </tfoot>
+ </Table>
+ )}
+ </div>
+
+ {calc.rooms.length > 0 && (
+ <div className="inspector__section">
+ <strong>{t('heating.panel.roomsTitle')}</strong>
+ <Table dense className="hp-table">
+ <thead>
+ <tr>
+ <Th>{t('heating.panel.room')}</Th>
+ <Th num>{t('heating.panel.colLoss')}</Th>
+ <Th num>{t('heating.panel.colFloor')}</Th>
+ </tr>
+ </thead>
+ <tbody>
+ {calc.rooms.map((b) => (
+ <tr key={b.key}>
+ <Td>
+ {b.name}
+ <div className="muted hp-sub">
+ {fmt(b.areaM2)} {t('common:units.m2')} × {b.lossWm2} {t('heating.panel.wm2')}
+ </div>
+ </Td>
+ <Td num>{Math.round(b.lossW)}</Td>
+ <Td num className={b.ok ? 'hp-ok' : 'hp-bad'}>
+ {Math.round(b.powerW)}
+ </Td>
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ </div>
+ )}
+
+ <div className="inspector__section">
+ <strong>{t('heating.panel.params')}</strong>
+ <div className="hp-form">
+ {num('supplyT', t('heating.panel.supply'), '°C')}
+ {num('returnT', t('heating.panel.return'), '°C')}
+ {num('floorT', t('heating.panel.floorLimit'), '°C', t('heating.panel.norm'))}
+ {num('screedMm', t('heating.panel.screed'), t('common:units.mm'))}
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.insulation')}</span>
+ <Input size="sm" className="hp-text" disabled={viewOnly} value={p.insulation} onChange={(ev) => commit(setParams(plan, { insulation: ev.target.value || undefined }))} />
+ </label>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.screedMix')}</span>
+ <select className="select" disabled={viewOnly} value={p.screedMix} onChange={(ev) => commit(setParams(plan, { screedMix: ev.target.value as 'cps' | 'cement-sand' }))}>
+ <option value="cement-sand">{t('heating.panel.cementSand')}</option>
+ <option value="cps">{t('heating.panel.cps')}</option>
+ </select>
+ </label>
+ <label className="row row--center hp-field">
+ <span>{t('heating.panel.fixing')}</span>
+ <select className="select" disabled={viewOnly} value={p.fixing} onChange={(ev) => commit(setParams(plan, { fixing: ev.target.value as 'mesh' | 'staples' }))}>
+ <option value="mesh">{t('heating.panel.mesh')}</option>
+ <option value="staples">{t('heating.panel.staples')}</option>
+ </select>
+ </label>
+ </div>
+ </div>
+
+ <div className="inspector__section">
+ <strong>{t('heating.panel.materials')}</strong>
+ <div className="hp-items">
+ {priced.map((i) => (
+ <div key={i.key} className="hp-item">
+ <div className="hp-item__name">
+ {i.url ? (
+ <a href={i.url} target="_blank" rel="noreferrer">
+ {i.name}
+ </a>
+ ) : (
+ i.name
+ )}
+ <div className="muted hp-sub">{i.priceFrom}</div>
+ </div>
+ <div className="hp-item__qty">
+ {fmt(i.buyQty)} {unitLabel(i.buyUnit)}
+ </div>
+ <div className="hp-item__sum">{i.price !== undefined ? formatMoney(heatingSum(i)) : '—'}</div>
+ </div>
+ ))}
+ {!priced.length && <p className="muted">{t('heating.panel.noMaterials')}</p>}
+ </div>
+ <div className="row total">
+ <span>{t('heating.panel.materialsTotal')}</span>
+ <strong>{formatMoney(total)}</strong>
+ </div>
+ {missing > 0 && (
+ <div className="muted">
+ {t('heating.panel.noPriceCount', { label: noPrice(), n: missing })}
+ </div>
+ )}
+ </div>
+
+ <div className="inspector__section">
+ <strong>{t('heating.panel.warnings')}</strong>
+ <Warnings list={calc.warnings} />
+ </div>
+
+ <details className="inspector__section hp-howto">
+ <summary>{t('heating.panel.howto')}</summary>
+ <ol>
+ {(t('heating.steps', { returnObjects: true }) as string[]).map((s, i) => (
+ <li key={i}>{s}</li>
+ ))}
+ </ol>
+ <p className="muted">
+ {t('heating.panel.howtoNote')}
+ </p>
+ </details>
+ </div>
+ )
+}
diff --git a/src/networks/heating/HeatingTools.tsx b/src/networks/heating/HeatingTools.tsx
new file mode 100644
index 0000000..2d3d1a6
--- /dev/null
+++ b/src/networks/heating/HeatingTools.tsx
@@ -0,0 +1,44 @@
+import { useTranslation } from 'react-i18next'
+import { t as tt } from '../../i18n'
+import { Button } from '../../ui'
+import { registerNetworkLayer } from '../registry'
+import { runAutoLayout } from './actions'
+import { useHeatingUi } from './store'
+import './heating.css'
+
+function HeatingEditTools() {
+ const { t } = useTranslation('networks')
+ const selected = useHeatingUi((s) => s.selected)
+ return (
+ <>
+ <Button size="sm" onClick={runAutoLayout}>
+ {t('heating.tools.autoLayout')}
+ </Button>
+ <span className="muted net-editbar__hint">
+ {selected ? t('heating.tools.hintSelected') : t('heating.tools.hintIdle')}
+ </span>
+ </>
+ )
+}
+
+registerNetworkLayer({
+ key: 'heating',
+ get label() {
+ return tt('networks:heating.layer')
+ },
+ Tools: HeatingEditTools,
+ enter: () => {
+ const ui = useHeatingUi.getState()
+ ui.select(null)
+ ui.setTab(true)
+ },
+ exit: () => useHeatingUi.getState().select(null),
+ onEscape: () => {
+ const ui = useHeatingUi.getState()
+ if (ui.selected || ui.collectorSelected) {
+ ui.select(null)
+ return true
+ }
+ return false
+ },
+})
diff --git a/src/networks/heating/actions.ts b/src/networks/heating/actions.ts
new file mode 100644
index 0000000..c0d04bd
--- /dev/null
+++ b/src/networks/heating/actions.ts
@@ -0,0 +1,18 @@
+import { usePlanStore } from '../../store/planStore'
+import { showToast } from '../../ui/Toast'
+import { t } from '../../i18n'
+import { autoLayout } from './layout'
+import { heatingOf, withHeating } from './model'
+import { useHeatingUi } from './store'
+
+export function runAutoLayout() {
+ const plan = usePlanStore.getState().plan
+ if (!plan) return
+ const have = heatingOf(plan).loops.length
+ if (have && !window.confirm(t('networks:heating.actions.confirmReplace', { count: have }))) return
+ const res = autoLayout(plan)
+ usePlanStore.getState().commit(withHeating(plan, () => res.heating))
+ useHeatingUi.getState().select(null)
+ useHeatingUi.getState().setTab(true)
+ showToast(t('networks:heating.actions.done', { count: res.heating.loops.length, notes: res.notes.slice(0, 2).join('. ') }))
+}
diff --git a/src/networks/heating/calc.ts b/src/networks/heating/calc.ts
new file mode 100644
index 0000000..2c2ed02
--- /dev/null
+++ b/src/networks/heating/calc.ts
@@ -0,0 +1,293 @@
+import type { HeatingLoop, Plan } from '../../model'
+import { detectRooms } from '../../stats/rooms'
+import { fmtNum, t } from '../../i18n'
+import { zoneAreaM2 } from './geometry'
+import { LOOP_HARD_MAX_M, LOOP_MAX_M, PIPE_RESERVE, centroid, heatingOf, paramsOf, pathLength, zonesOf, type LoopZone } from './model'
+import { classify, coverLabel, coverOf, heatRooms, lossNorm, roomOfPoint, type HeatRoom } from './rooms'
+
+export type WarnLevel = 'error' | 'warn' | 'info'
+export type HeatingWarning = { level: WarnLevel; text: string; loopId?: string }
+
+export type LoopCalc = {
+ loop: HeatingLoop
+ roomName: string
+ roomKey: string
+ roomKeys: string[]
+ cover: 'tile' | 'laminate'
+ tInside: number
+ areaM2: number
+ coilM: number
+ feedM: number
+ lengthM: number
+ qWm2: number
+ powerW: number
+ floorT: number
+ capped: boolean
+ flowLh: number
+ flowLmin: number
+ velocity: number
+ dpKPa: number
+ throttleKPa: number
+}
+
+export type RoomBalance = { key: string; name: string; areaM2: number; heatedM2: number; lossWm2: number; lossW: number; powerW: number; ok: boolean }
+
+export type HeatingUnit = 'pcs' | 'm' | 'm2' | 'm3' | 'kg'
+
+export type HeatingItem = { key: string; sub: string; name: string; qty: number; unit: HeatingUnit; spec?: Record<string, number | string> }
+
+export type HeatingCalc = {
+ loops: LoopCalc[]
+ rooms: RoomBalance[]
+ totals: {
+ areaM2: number
+ pipeM: number
+ powerW: number
+ lossW: number
+ carrierW: number
+ boilerKW: number
+ flowLh: number
+ maxDpKPa: number
+ pumpKPa: number
+ outputs: number
+ screedM3: number
+ }
+ deltaT: number
+ items: HeatingItem[]
+ warnings: HeatingWarning[]
+}
+
+const K_H: Record<'tile' | 'laminate', Record<number, number>> = {
+ tile: { 100: 6.7, 150: 5.9, 200: 5.2 },
+ laminate: { 100: 4.2, 150: 3.8, 200: 3.4 },
+}
+
+const BOILERS = [9, 12, 14, 18, 24, 28, 32, 35, 40, 45, 50, 60]
+const COLLECTORS = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+const DOWNWARD = 0.1
+const WATER_NU = 0.66e-6
+const WATER_RHO = 992
+const LOCAL_LOSS = 1.3
+const UNIT_KPA = 5
+
+export const logMeanDT = (supply: number, ret: number, ti: number) => {
+ if (ret <= ti || supply <= ret) return Math.max(0, (supply + ret) / 2 - ti)
+ return (supply - ret) / Math.log((supply - ti) / (ret - ti))
+}
+
+export const maxFlux = (floorMax: number, ti: number) => 8.92 * Math.pow(Math.max(0, floorMax - ti), 1.1)
+
+export function innerDiameterMm(pipe: string) {
+ const m = /(\d{2})\s*[xх×*]\s*(\d(?:[.,]\d)?)/i.exec(pipe)
+ if (!m) return 12
+ return Number(m[1]) - 2 * Number(m[2].replace(',', '.'))
+}
+
+export function pressureDrop(lengthM: number, flowLh: number, dInnerMm: number) {
+ const d = dInnerMm / 1000
+ const v = flowLh / 3.6e6 / (Math.PI * (d / 2) ** 2)
+ const re = (v * d) / WATER_NU
+ const lambda = re < 1 ? 0 : re < 2300 ? 64 / re : 0.3164 / Math.pow(re, 0.25)
+ const dp = ((lambda * lengthM) / d) * ((WATER_RHO * v * v) / 2) * LOCAL_LOSS
+ return { v, dpKPa: dp / 1000 }
+}
+
+function ffd(lengths: number[], cap: number) {
+ const bins: number[][] = []
+ for (const l of [...lengths].sort((a, b) => b - a)) {
+ const b = bins.find((x) => x.reduce((s, v) => s + v, 0) + l <= cap)
+ if (b) b.push(l)
+ else bins.push([l])
+ }
+ return bins
+}
+
+export function packCoils(lengths: number[]) {
+ let c500 = 0
+ let c200 = 0
+ for (const bin of ffd(lengths, 500)) {
+ const small = bin.every((l) => l <= 200) ? ffd(bin, 200).length : Infinity
+ if (small * 200 < 500) c200 += small
+ else c500 += 1
+ }
+ return { c500, c200 }
+}
+
+const r1 = (v: number) => Math.round(v * 10) / 10
+const up = (v: number, d = 1) => Math.ceil(v * d) / d
+
+function roomFor(rooms: HeatRoom[], zone: LoopZone) {
+ return (zone.roomId ? rooms.find((r) => r.labelId === zone.roomId) : undefined) ?? roomOfPoint(rooms, centroid(zone.polygon))
+}
+
+export function computeHeating(plan: Plan): HeatingCalc {
+ const h = heatingOf(plan)
+ const p = paramsOf(h)
+ const rooms = heatRooms(plan, detectRooms(plan))
+ const warnings: HeatingWarning[] = []
+ const deltaT = p.supplyT - p.returnT
+ const screedCover = p.screedMm - 20
+ const screedF = Math.max(0.8, Math.min(1.1, 1 - 0.004 * (screedCover - 45)))
+ const dIn = (pipe: string) => innerDiameterMm(pipe)
+ const active = h.loops.filter((l) => !l.off)
+ const byRoom = new Map<string, RoomBalance>()
+
+ const loops: LoopCalc[] = active.map((loop) => {
+ const zones = zonesOf(loop).map((z, zi) => {
+ const room = roomFor(rooms, z)
+ const cls = room?.cls ?? classify(z.roomName ?? '')
+ const cover = room?.cover ?? coverOf(cls)
+ const ti = room?.tInside ?? (cls === 'wet' ? 24 : 20)
+ const areaM2 = zoneAreaM2(z)
+ const floorMax = p.floorT ?? (loop.edge ? 35 : cls === 'wet' ? 33 : 29)
+ const raw = K_H[cover][loop.stepMm] * logMeanDT(p.supplyT, p.returnT, ti) * screedF
+ const lim = maxFlux(floorMax, ti)
+ const q = Math.min(raw, lim)
+ const key = room?.labelId ?? room?.face.id ?? `loop:${loop.id}:${zi}`
+ return { room, cover, ti, areaM2, q, capped: raw > lim, key, name: room?.name ?? z.roomName ?? loop.id }
+ })
+ const main = zones[0]
+ const areaM2 = zones.reduce((s, z) => s + z.areaM2, 0)
+ const powerW = zones.reduce((s, z) => s + z.q * z.areaM2, 0)
+ const qWm2 = areaM2 ? powerW / areaM2 : 0
+ const coilM = areaM2 / (loop.stepMm / 1000)
+ const feedM = pathLength(loop.supplyPath) / 1000 + pathLength(loop.linkPath) / 1000
+ const lengthM = (coilM + 2 * feedM) * (1 + PIPE_RESERVE)
+ const flowLh = deltaT > 0 ? (0.86 * powerW * (1 + DOWNWARD)) / deltaT : 0
+ const hyd = pressureDrop(lengthM, flowLh, dIn(loop.pipe))
+ for (const z of zones) {
+ const cur = byRoom.get(z.key)
+ const w = z.q * z.areaM2
+ if (cur) {
+ cur.powerW += w
+ cur.heatedM2 += z.areaM2
+ } else {
+ const lossWm2 = z.room?.lossWm2 ?? lossNorm(1)
+ const roomArea = z.room?.face.areaM2 ?? z.areaM2
+ byRoom.set(z.key, { key: z.key, name: z.name, areaM2: roomArea, heatedM2: z.areaM2, lossWm2, lossW: lossWm2 * roomArea, powerW: w, ok: true })
+ }
+ }
+ return {
+ loop,
+ roomName: loop.roomName ?? main.name,
+ roomKey: main.key,
+ roomKeys: zones.map((z) => z.key),
+ cover: main.cover,
+ tInside: main.ti,
+ areaM2,
+ coilM,
+ feedM,
+ lengthM,
+ qWm2,
+ powerW,
+ floorT: main.ti + Math.pow(main.q / 8.92, 1 / 1.1),
+ capped: zones.some((z) => z.capped),
+ flowLh,
+ flowLmin: flowLh / 60,
+ velocity: hyd.v,
+ dpKPa: hyd.dpKPa,
+ throttleKPa: 0,
+ }
+ })
+ const maxDp = loops.reduce((m, l) => Math.max(m, l.dpKPa), 0)
+ loops.forEach((l) => (l.throttleKPa = maxDp - l.dpKPa))
+
+ const balance = [...byRoom.values()]
+ balance.forEach((b) => (b.ok = b.powerW >= b.lossW * 0.95))
+
+ for (const l of loops) {
+ const room = l.roomName
+ if (l.lengthM > LOOP_HARD_MAX_M) warnings.push({ level: 'error', text: t('networks:heating.warn.loopTooLong', { room, len: Math.round(l.lengthM), max: LOOP_HARD_MAX_M }), loopId: l.loop.id })
+ else if (l.lengthM > LOOP_MAX_M) warnings.push({ level: 'warn', text: t('networks:heating.warn.loopLong', { room, len: Math.round(l.lengthM), max: LOOP_MAX_M }), loopId: l.loop.id })
+ if (l.dpKPa > 20) warnings.push({ level: 'warn', text: t('networks:heating.warn.dpHigh', { room, dp: fmtNum(r1(l.dpKPa), 1) }), loopId: l.loop.id })
+ if (!l.loop.supplyPath?.length) warnings.push({ level: 'info', text: t('networks:heating.warn.noFeed', { room }), loopId: l.loop.id })
+ }
+ for (const b of balance)
+ if (!b.ok)
+ warnings.push({
+ level: 'warn',
+ text: t(loops.some((l) => l.roomKeys.includes(b.key) && l.capped) ? 'networks:heating.warn.roomShortCapped' : 'networks:heating.warn.roomShort', { room: b.name, power: Math.round(b.powerW), loss: Math.round(b.lossW), lossWm2: b.lossWm2 }),
+ loopId: loops.find((l) => l.roomKeys.includes(b.key))?.loop.id,
+ })
+
+ const heatedRooms = rooms.filter((r) => r.cls !== 'skip' && balance.some((b) => b.key === (r.labelId ?? r.face.id)))
+ const lossW = balance.reduce((s, b) => s + b.lossW, 0)
+ const powerW = loops.reduce((s, l) => s + l.powerW, 0)
+ const carrierW = powerW * (1 + DOWNWARD)
+ const boilerNeed = (Math.max(lossW, 0) * 1.2) / 1000
+ const boilerKW = BOILERS.find((b) => b >= boilerNeed) ?? Math.ceil(boilerNeed)
+ const flowLh = loops.reduce((s, l) => s + l.flowLh, 0)
+ const outputs = Math.max(h.collector?.outputs ?? 0, loops.length)
+ if (deltaT <= 0) warnings.push({ level: 'error', text: t('networks:heating.warn.returnNotBelow') })
+ if (p.supplyT > 55) warnings.push({ level: 'warn', text: t('networks:heating.warn.supplyHigh', { t: p.supplyT }) })
+ const insMm = Number(/(\d{2,3})/.exec(p.insulation)?.[1] ?? 0)
+ if (loops.length && insMm && insMm < 100) warnings.push({ level: 'error', text: t('networks:heating.warn.insulationThin', { mm: insMm }) })
+ if (loops.length && !h.collector) warnings.push({ level: 'warn', text: t('networks:heating.warn.noCollector') })
+ if (h.collector && h.collector.outputs < loops.length) warnings.push({ level: 'error', text: t('networks:heating.warn.collectorOutputs', { outputs: h.collector.outputs, loops: loops.length }) })
+ if (loops.length > 12) warnings.push({ level: 'warn', text: t('networks:heating.warn.tooManyLoops', { count: loops.length }) })
+
+ const heatedM2 = heatedRooms.reduce((s, r) => s + r.face.areaM2, 0) || loops.reduce((s, l) => s + l.areaM2, 0)
+ const perimeterM = heatedRooms.reduce((s, r) => s + r.face.clearPolygon.reduce((a, q, i, arr) => a + Math.hypot(arr[(i + 1) % arr.length].x - q.x, arr[(i + 1) % arr.length].y - q.y), 0), 0) / 1000
+ const screedM3 = (heatedM2 * p.screedMm) / 1000
+
+ const items: HeatingItem[] = []
+ if (loops.length) {
+ const pipes = new Map<string, number[]>()
+ for (const l of loops) pipes.set(l.loop.pipe, [...(pipes.get(l.loop.pipe) ?? []), l.lengthM])
+ for (const [pipe, lens] of pipes) {
+ const k = pipe.replace(/\s+/g, '-').replace(/[×х]/g, 'x').toLowerCase()
+ const { c500, c200 } = packCoils(lens)
+ const total = Math.round(lens.reduce((s, v) => s + v, 0))
+ if (c500) items.push({ key: `pipe-${k}-500`, sub: 'pipe', name: t('networks:heating.item.pipe500', { pipe, total }), qty: c500, unit: 'pcs', spec: { coil: 500, pipe } })
+ if (c200) items.push({ key: `pipe-${k}-200`, sub: 'pipe', name: t(c500 ? 'networks:heating.item.pipe200' : 'networks:heating.item.pipe200Total', { pipe, total }), qty: c200, unit: 'pcs', spec: { coil: 200, pipe } })
+ }
+ const collectors = outputs > 12 ? [Math.ceil(outputs / 2), Math.floor(outputs / 2)] : [outputs]
+ for (const n0 of collectors) {
+ const n = COLLECTORS.find((c) => c >= n0) ?? n0
+ items.push({ key: `collector-${n}`, sub: 'collector', name: t('networks:heating.item.collector', { n }), qty: 1, unit: 'pcs', spec: { outputs: n } })
+ }
+ items.push({ key: 'mixing-unit', sub: 'mixing', name: t('networks:heating.item.mixing'), qty: 1, unit: 'pcs' })
+ items.push({ key: 'pump-25-60', sub: 'pump', name: t('networks:heating.item.pump', { head: fmtNum(r1((maxDp + UNIT_KPA) / 9.81), 1) }), qty: 1, unit: 'pcs', spec: { headM: r1((maxDp + UNIT_KPA) / 9.81) } })
+ for (const n0 of collectors) {
+ const n = COLLECTORS.find((c) => c >= n0) ?? n0
+ items.push({ key: `cabinet-${n}`, sub: 'cabinet', name: t('networks:heating.item.cabinet', { n }), qty: 1, unit: 'pcs', spec: { outputs: n } })
+ }
+ items.push({ key: 'eurocone-16', sub: 'eurocone', name: t('networks:heating.item.eurocone'), qty: loops.length * 2, unit: 'pcs' })
+ items.push({ key: 'damper-tape', sub: 'damper', name: t('networks:heating.item.damper'), qty: Math.ceil(perimeterM * 1.1), unit: 'm' })
+ items.push({ key: `insulation-${p.insulation.replace(/\s+/g, '-').toLowerCase()}`, sub: 'insulation', name: t('networks:heating.item.insulation', { insulation: p.insulation }), qty: up(heatedM2 * 1.05), unit: 'm2', spec: { insulation: p.insulation } })
+ items.push({ key: 'film', sub: 'film', name: t('networks:heating.item.film'), qty: up(heatedM2 * 1.15), unit: 'm2', spec: { thickness: 0.2 } })
+ const pipeM = loops.reduce((s, l) => s + l.lengthM, 0)
+ if (p.fixing === 'staples') items.push({ key: 'staples', sub: 'staples', name: t('networks:heating.item.staples'), qty: Math.ceil(pipeM / 0.4 / 100) * 100, unit: 'pcs' })
+ else items.push({ key: 'mesh', sub: 'mesh', name: t('networks:heating.item.mesh'), qty: up(heatedM2 * 1.1), unit: 'm2' })
+ if (p.fixing !== 'staples') items.push({ key: 'ties', sub: 'ties', name: t('networks:heating.item.ties'), qty: Math.ceil(pipeM / 0.4 / 100) * 100, unit: 'pcs' })
+ if (p.screedMix === 'cps') items.push({ key: 'cps', sub: 'cps', name: t('networks:heating.item.cps', { mm: p.screedMm, m3: fmtNum(r1(screedM3), 1) }), qty: Math.ceil(screedM3 * 2000), unit: 'kg' })
+ else {
+ items.push({ key: 'cement-m500', sub: 'cement', name: t('networks:heating.item.cement', { mm: p.screedMm, m3: fmtNum(r1(screedM3), 1) }), qty: Math.ceil(screedM3 * 400), unit: 'kg' })
+ items.push({ key: 'sand', sub: 'sand', name: t('networks:heating.item.sand'), qty: Math.ceil(screedM3 * 1200 * 1.05), unit: 'kg' })
+ }
+ items.push({ key: 'fiber', sub: 'fiber', name: t('networks:heating.item.fiber'), qty: up(screedM3 * 0.9, 10), unit: 'kg' })
+ }
+
+ return {
+ loops,
+ rooms: balance,
+ totals: {
+ areaM2: loops.reduce((s, l) => s + l.areaM2, 0),
+ pipeM: loops.reduce((s, l) => s + l.lengthM, 0),
+ powerW,
+ lossW,
+ carrierW,
+ boilerKW,
+ flowLh,
+ maxDpKPa: maxDp,
+ pumpKPa: maxDp + UNIT_KPA,
+ outputs,
+ screedM3,
+ },
+ deltaT,
+ items,
+ warnings,
+ }
+}
+
+export { coverLabel }
diff --git a/src/networks/heating/estimate.ts b/src/networks/heating/estimate.ts
new file mode 100644
index 0000000..1749a97
--- /dev/null
+++ b/src/networks/heating/estimate.ts
@@ -0,0 +1,23 @@
+import type { Plan } from '../../model'
+import type { CatalogItem } from '../../estimate/catalog'
+import { computeHeating } from './calc'
+import { heatingOf } from './model'
+import { t } from '../../i18n'
+import { priceHeating } from './pricing'
+
+export const heatingGroup = () => t('networks:shared.layers.heating')
+
+export function heatingEstimateRows(plan: Plan, catalog: CatalogItem[]) {
+ const h = heatingOf(plan)
+ if (!h.loops.some((l) => !l.off)) return []
+ return priceHeating(computeHeating(plan).items, h.materials, catalog).map((i) => ({
+ id: `auto:heating:${i.key}`,
+ name: i.name,
+ url: i.url,
+ qty: i.buyQty,
+ unit: i.buyUnit,
+ price: i.price,
+ priceFrom: i.priceFrom,
+ group: heatingGroup(),
+ }))
+}
diff --git a/src/networks/heating/geometry.ts b/src/networks/heating/geometry.ts
new file mode 100644
index 0000000..02be7cb
--- /dev/null
+++ b/src/networks/heating/geometry.ts
@@ -0,0 +1,232 @@
+import { ClipType, ClipperD, EndType, FillRule, JoinType, areaD, differenceD, inflatePathsD, intersectD, simplifyPathsD, unionD, type PathD, type PathsD } from 'clipper2-ts'
+import type { HeatingLoop, Point } from '../../model'
+
+const PREC = 1
+
+const clean = (paths: PathsD): Point[][] =>
+ simplifyPathsD(paths, 2, true)
+ .filter((p) => p.length >= 3 && Math.abs(areaD(p)) > 1)
+ .map((p) => p.map((q) => ({ x: Math.round(q.x), y: Math.round(q.y) })))
+
+export const areaOf = (paths: Point[][]) => paths.reduce((s, p) => s + areaD(p as PathD), 0)
+
+export const inset = (paths: Point[][], d: number): Point[][] => clean(inflatePathsD(paths as PathsD, -d, JoinType.Miter, EndType.Polygon, 4, PREC))
+
+export const grow = (paths: Point[][], d: number): Point[][] => clean(inflatePathsD(paths as PathsD, d, JoinType.Miter, EndType.Polygon, 4, PREC))
+
+export const minus = (a: Point[][], b: Point[][]): Point[][] => (b.length ? clean(differenceD(a as PathsD, b as PathsD, FillRule.NonZero, PREC)) : a)
+
+export const intersect = (a: Point[][], b: Point[][]): Point[][] => clean(intersectD(a as PathsD, b as PathsD, FillRule.NonZero, PREC))
+
+export const union = (a: Point[][]): Point[][] => clean(unionD(a as PathsD, FillRule.NonZero))
+
+export function strokeBuffer(segments: [Point, Point][], half: number): Point[][] {
+ if (!segments.length) return []
+ return clean(inflatePathsD(segments.map(([a, b]) => [a, b]) as PathsD, half, JoinType.Miter, EndType.Butt, 2, PREC))
+}
+
+export function outerAreaM2(paths: Point[][]) {
+ return Math.max(0, areaOf(paths)) / 1e6
+}
+
+export const loopRegion = (loop: { polygon: Point[]; excluded?: Point[][] }): Point[][] => minus([loop.polygon], loop.excluded ?? [])
+
+export const zoneAreaM2 = (z: { polygon: Point[]; excluded?: Point[][] }) => Math.abs(areaOf(loopRegion(z))) / 1e6
+
+export const netAreaM2 = (loop: HeatingLoop) => zoneAreaM2(loop) + (loop.parts ?? []).reduce((s, p) => s + zoneAreaM2(p), 0)
+
+export function rect(cx: number, cy: number, w: number, d: number, deg: number): Point[] {
+ const a = (deg * Math.PI) / 180
+ const c = Math.cos(a)
+ const s = Math.sin(a)
+ return [
+ [-w / 2, -d / 2],
+ [w / 2, -d / 2],
+ [w / 2, d / 2],
+ [-w / 2, d / 2],
+ ].map(([x, y]) => ({ x: Math.round(cx + x * c - y * s), y: Math.round(cy + x * s + y * c) }))
+}
+
+export function bbox(paths: Point[][]) {
+ let x0 = Infinity
+ let y0 = Infinity
+ let x1 = -Infinity
+ let y1 = -Infinity
+ for (const p of paths) for (const q of p) {
+ x0 = Math.min(x0, q.x)
+ y0 = Math.min(y0, q.y)
+ x1 = Math.max(x1, q.x)
+ y1 = Math.max(y1, q.y)
+ }
+ return { x0, y0, x1, y1 }
+}
+
+export function splitStrips(poly: Point[][], n: number): Point[][][] {
+ if (n <= 1) return [poly]
+ const b = bbox(poly)
+ const alongX = b.x1 - b.x0 >= b.y1 - b.y0
+ const lo = alongX ? b.x0 : b.y0
+ const hi = alongX ? b.x1 : b.y1
+ const total = Math.abs(areaOf(poly))
+ const slab = (a: number, z: number): Point[] =>
+ alongX
+ ? [{ x: a, y: b.y0 - 10 }, { x: z, y: b.y0 - 10 }, { x: z, y: b.y1 + 10 }, { x: a, y: b.y1 + 10 }]
+ : [{ x: b.x0 - 10, y: a }, { x: b.x1 + 10, y: a }, { x: b.x1 + 10, y: z }, { x: b.x0 - 10, y: z }]
+ const cuts = [lo]
+ for (let k = 1; k < n; k++) {
+ const target = (total * k) / n
+ let a = cuts[cuts.length - 1]
+ let z = hi
+ for (let i = 0; i < 40; i++) {
+ const m = (a + z) / 2
+ if (Math.abs(areaOf(intersect(poly, [slab(lo, m)]))) < target) a = m
+ else z = m
+ }
+ cuts.push(Math.round((a + z) / 2))
+ }
+ cuts.push(hi)
+ return cuts.slice(1).map((z, i) => intersect(poly, [slab(cuts[i], z)])).filter((p) => p.length)
+}
+
+export type Ring = { path: Point[]; supply: boolean; order: number }
+
+function rotateTo(path: Point[], at: Point) {
+ let best = 0
+ let bd = Infinity
+ path.forEach((p, i) => {
+ const d = Math.hypot(p.x - at.x, p.y - at.y)
+ if (d < bd) {
+ bd = d
+ best = i
+ }
+ })
+ return [...path.slice(best), ...path.slice(0, best)]
+}
+
+function trimEnd(path: Point[], gap: number) {
+ const out = [...path]
+ let left = gap
+ while (out.length > 2 && left > 0) {
+ const a = out[out.length - 2]
+ const b = out[out.length - 1]
+ const l = Math.hypot(b.x - a.x, b.y - a.y)
+ if (l > left) {
+ const t = (l - left) / l
+ out[out.length - 1] = { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }
+ return out
+ }
+ out.pop()
+ left -= l
+ }
+ return out
+}
+
+export function spiralRings(loop: HeatingLoop, entry: Point | undefined): Ring[] {
+ const region = loopRegion(loop)
+ const step = loop.stepMm
+ const raw: Point[][][] = []
+ for (let k = 0; k < 400; k++) {
+ const r = inset(region, step / 2 + k * step)
+ if (!r.length) break
+ raw.push(r)
+ }
+ const at = entry ?? loop.polygon[0]
+ const rings: Ring[] = []
+ raw.forEach((paths, k) => {
+ for (const p of paths) {
+ const closed = rotateTo(p, at)
+ rings.push({ path: trimEnd([...closed, closed[0]], step * 1.5), supply: k % 2 === 0, order: k })
+ }
+ })
+ return rings
+}
+
+export function snakeLines(loop: HeatingLoop): Point[] {
+ const region = inset(loopRegion(loop), loop.stepMm / 2)
+ if (!region.length) return []
+ const b = bbox(region)
+ const alongX = b.x1 - b.x0 >= b.y1 - b.y0
+ const lines: PathsD = []
+ const step = loop.stepMm
+ if (alongX) for (let y = b.y0; y <= b.y1 + 1; y += step) lines.push([{ x: b.x0 - 10, y }, { x: b.x1 + 10, y }])
+ else for (let x = b.x0; x <= b.x1 + 1; x += step) lines.push([{ x, y: b.y0 - 10 }, { x, y: b.y1 + 10 }])
+ const c = new ClipperD(PREC)
+ c.addOpenSubjectPaths(lines)
+ c.addClipPaths(region as PathsD)
+ const closed: PathsD = []
+ const open: PathsD = []
+ c.execute(ClipType.Intersection, FillRule.NonZero, closed, open)
+ const key = (p: PathD) => (alongX ? p[0].y : p[0].x)
+ const segs = open
+ .filter((p) => p.length >= 2)
+ .map((p) => {
+ const s = [p[0], p[p.length - 1]]
+ return (alongX ? s[0].x > s[1].x : s[0].y > s[1].y) ? [s[1], s[0]] : s
+ })
+ .sort((a, b) => key(a) - key(b) || (alongX ? a[0].x - b[0].x : a[0].y - b[0].y))
+ const out: Point[] = []
+ segs.forEach((s, i) => {
+ const seg = i % 2 ? [s[1], s[0]] : s
+ out.push(...seg.map((p) => ({ x: p.x, y: p.y })))
+ })
+ return out
+}
+
+export function closestOnPolygon(poly: Point[], p: Point) {
+ let best = { point: poly[0], s: 0, d: Infinity }
+ let acc = 0
+ for (let i = 0; i < poly.length; i++) {
+ const a = poly[i]
+ const b = poly[(i + 1) % poly.length]
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy
+ const l = Math.sqrt(l2)
+ const t = l2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2)) : 0
+ const q = { x: a.x + dx * t, y: a.y + dy * t }
+ const d = Math.hypot(p.x - q.x, p.y - q.y)
+ if (d < best.d) best = { point: q, s: acc + l * t, d }
+ acc += l
+ }
+ return { ...best, perimeter: acc }
+}
+
+export function walkBoundary(poly: Point[], from: Point, to: Point): Point[] {
+ const a = closestOnPolygon(poly, from)
+ const b = closestOnPolygon(poly, to)
+ const per = a.perimeter
+ const cum: number[] = []
+ let acc = 0
+ for (let i = 0; i < poly.length; i++) {
+ cum.push(acc)
+ const q = poly[(i + 1) % poly.length]
+ acc += Math.hypot(q.x - poly[i].x, q.y - poly[i].y)
+ }
+ const fwd = (b.s - a.s + per) % per
+ const forward = fwd <= per - fwd
+ const span = forward ? fwd : per - fwd
+ const pts: Point[] = [a.point]
+ poly
+ .map((p, i) => ({ p, d: forward ? (cum[i] - a.s + per) % per : (a.s - cum[i] + per) % per }))
+ .filter((x) => x.d > 1e-6 && x.d < span)
+ .sort((x, y) => x.d - y.d)
+ .forEach((x) => pts.push(x.p))
+ pts.push(b.point)
+ return pts
+}
+
+export function simplifyPath(path: Point[]): Point[] {
+ const out: Point[] = []
+ for (const p of path) {
+ const q = { x: Math.round(p.x), y: Math.round(p.y) }
+ const last = out[out.length - 1]
+ if (last && Math.hypot(last.x - q.x, last.y - q.y) < 5) continue
+ if (out.length >= 2) {
+ const a = out[out.length - 2]
+ const cross = (last.x - a.x) * (q.y - a.y) - (last.y - a.y) * (q.x - a.x)
+ if (Math.abs(cross) < 1e-3 * Math.hypot(last.x - a.x, last.y - a.y) * Math.hypot(q.x - a.x, q.y - a.y) + 1) out.pop()
+ }
+ out.push(q)
+ }
+ return out
+}
diff --git a/src/networks/heating/heating.css b/src/networks/heating/heating.css
new file mode 100644
index 0000000..151cd4a
--- /dev/null
+++ b/src/networks/heating/heating.css
@@ -0,0 +1,168 @@
+.hp-summary .props {
+ margin-bottom: var(--space-2);
+}
+
+.hp-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin-bottom: var(--space-3);
+}
+
+.hp-form {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin-top: var(--space-2);
+}
+
+.hp-field {
+ justify-content: space-between;
+ gap: var(--space-2);
+}
+
+.hp-field > span:first-child {
+ color: var(--muted);
+ white-space: nowrap;
+}
+
+.hp-field .select {
+ max-width: 170px;
+}
+
+.hp-pair {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+}
+
+.hp-num {
+ width: 80px;
+}
+
+.hp-text {
+ width: 150px;
+}
+
+.hp-table {
+ margin-top: var(--space-2);
+}
+
+.hp-table td {
+ vertical-align: top;
+}
+
+.hp-row {
+ cursor: pointer;
+}
+
+.hp-row:hover,
+.hp-row--active {
+ background: var(--surface-2);
+}
+
+.hp-row--off {
+ opacity: 0.5;
+}
+
+.hp-total td {
+ font-weight: 600;
+ border-top: 1px solid var(--line);
+}
+
+.hp-sub {
+ font-size: var(--text-xs);
+}
+
+.hp-bad {
+ color: var(--danger);
+ font-weight: 600;
+}
+
+.hp-ok {
+ color: var(--ink);
+}
+
+.hp-items {
+ display: flex;
+ flex-direction: column;
+ margin-top: var(--space-2);
+}
+
+.hp-item {
+ display: grid;
+ grid-template-columns: 1fr auto auto;
+ gap: var(--space-2);
+ align-items: baseline;
+ padding: 6px 0;
+ font-size: var(--text-sm);
+ border-bottom: 1px solid var(--line);
+}
+
+.hp-item__name a {
+ color: inherit;
+}
+
+.hp-item__qty,
+.hp-item__sum {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.hp-item__sum {
+ min-width: 72px;
+}
+
+.hp-warnings {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: var(--space-2);
+}
+
+.hp-warning {
+ width: 100%;
+ padding: 8px 10px;
+ border: 0;
+ border-radius: var(--radius-xs);
+ color: var(--ink);
+ font: inherit;
+ font-size: var(--text-sm);
+ text-align: left;
+ cursor: pointer;
+}
+
+.hp-warning--error {
+ background: var(--danger-soft);
+}
+
+.hp-warning--warn {
+ background: var(--warn-soft);
+}
+
+.hp-warning--info {
+ background: var(--surface-2);
+ color: var(--ink-2);
+}
+
+.hp-howto summary {
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.hp-howto ol {
+ margin: var(--space-2) 0;
+ padding-left: 18px;
+ font-size: var(--text-sm);
+ line-height: 1.45;
+}
+
+.hp-howto li + li {
+ margin-top: 4px;
+}
+
+.hp-howto .muted {
+ font-size: var(--text-xs);
+ line-height: 1.45;
+}
diff --git a/src/networks/heating/index.ts b/src/networks/heating/index.ts
new file mode 100644
index 0000000..2a2606f
--- /dev/null
+++ b/src/networks/heating/index.ts
@@ -0,0 +1,6 @@
+export { HeatingLayer } from './HeatingLayer'
+import './HeatingTools'
+export { HeatingInspector, HeatingSummary, useHeatingSelection } from './HeatingPanel'
+export { useHeatingUi } from './store'
+export { computeHeating, type HeatingCalc } from './calc'
+export { heatingEstimateRows, heatingGroup } from './estimate'
diff --git a/src/networks/heating/layout.ts b/src/networks/heating/layout.ts
new file mode 100644
index 0000000..526847a
--- /dev/null
+++ b/src/networks/heating/layout.ts
@@ -0,0 +1,289 @@
+import type { HeatingCollector, HeatingLoop, HeatingNetwork, HeatingStep, Plan, Point } from '../../model'
+import { resolveFurniture } from '../../furniture/catalog'
+import { detectRooms, type RoomDetection } from '../../stats/rooms'
+import { edgeContains, openingPoint } from '../../stats/rooms'
+import { closestOnPolygon, inset, intersect, minus, areaOf, rect, simplifyPath, splitStrips, strokeBuffer, walkBoundary, bbox } from './geometry'
+import { DEFAULT_PIPE, LOOP_MAX_M, PIPE_RESERVE, WALL_GAP, centroid, heatingOf, pathLength } from './model'
+import { heatRooms, roomOfPoint, type HeatRoom } from './rooms'
+import { computeHeating } from './calc'
+import { t } from '../../i18n'
+
+export const FIXED_FURNITURE = new Set([
+ 'kitchen-base',
+ 'kitchen-drawers',
+ 'kitchen-corner',
+ 'kitchen-sink',
+ 'stove',
+ 'dishwasher',
+ 'fridge',
+ 'wardrobe',
+ 'hall-wardrobe',
+ 'bathtub',
+ 'shower',
+ 'gas-boiler',
+ 'floor-boiler',
+ 'masonry-stove',
+ 'fireplace',
+])
+
+const EDGE_STRIP = 1000
+const EDGE_MIN_M2 = 3
+const EDGE_ROOM_M2 = 12
+const ALONG_WALL = 60
+const MAX_OUTPUTS = 12
+const MAX_LINK_M = 6
+
+type Door = { at: Point; rooms: [HeatRoom, HeatRoom] }
+
+function doorsOf(plan: Plan, det: RoomDetection, rooms: HeatRoom[]): Door[] {
+ const out: Door[] = []
+ for (const o of plan.openings) {
+ if (o.type !== 'door') continue
+ const wall = plan.walls.find((w) => w.id === o.wallId)
+ if (!wall) continue
+ const at = openingPoint(wall, o)
+ const hit = rooms.filter((r) => r.face.edges.some((e) => e.wall.id === wall.id && edgeContains(det.nodes, e, at, wall.thickness)))
+ if (hit.length === 2) out.push({ at, rooms: [hit[0], hit[1]] })
+ }
+ return out
+}
+
+function route(start: Point, from: HeatRoom | undefined, to: HeatRoom, doors: Door[]): { doors: Point[]; rooms: HeatRoom[] } | null {
+ if (!from) return null
+ if (from === to) return { doors: [], rooms: [from] }
+ type Node = { at: Point; room: HeatRoom; cost: number; prev: Node | null; door: Door | null }
+ const best = new Map<Door, number>()
+ const queue: Node[] = [{ at: start, room: from, cost: 0, prev: null, door: null }]
+ let done: Node | null = null
+ while (queue.length) {
+ queue.sort((a, b) => a.cost - b.cost)
+ const n = queue.shift()!
+ if (n.room === to) {
+ done = n
+ break
+ }
+ for (const d of doors) {
+ if (!d.rooms.includes(n.room) || d === n.door) continue
+ const cost = n.cost + Math.hypot(d.at.x - n.at.x, d.at.y - n.at.y) + 1
+ if ((best.get(d) ?? Infinity) <= cost) continue
+ best.set(d, cost)
+ queue.push({ at: d.at, room: d.rooms[0] === n.room ? d.rooms[1] : d.rooms[0], cost, prev: n, door: d })
+ }
+ }
+ if (!done) return null
+ const pts: Point[] = []
+ const rs: HeatRoom[] = []
+ for (let n: Node | null = done; n; n = n.prev) {
+ rs.unshift(n.room)
+ if (n.door) pts.unshift(n.door.at)
+ }
+ return { doors: pts, rooms: rs }
+}
+
+function hug(room: HeatRoom) {
+ const r = inset([room.face.clearPolygon], ALONG_WALL)
+ return r.sort((a, b) => Math.abs(areaOf([b])) - Math.abs(areaOf([a])))[0] ?? room.face.clearPolygon
+}
+
+export function supplyPath(collector: Point, polygon: Point[], room: HeatRoom | undefined, rooms: HeatRoom[], doors: Door[]): Point[] {
+ const from = roomOfPoint(rooms, collector)
+ const r = room ? route(collector, from, room, doors) : null
+ if (!r) {
+ const entry = closestOnPolygon(polygon, collector).point
+ return simplifyPath([collector, { x: entry.x, y: collector.y }, entry])
+ }
+ const last = r.doors.length ? r.doors[r.doors.length - 1] : collector
+ const entry = closestOnPolygon(polygon, last).point
+ const way = [collector, ...r.doors, entry]
+ const path: Point[] = [collector]
+ for (let i = 0; i < way.length - 1; i++) {
+ const ring = hug(r.rooms[i])
+ path.push(...walkBoundary(ring, way[i], way[i + 1]), way[i + 1])
+ }
+ return simplifyPath(path)
+}
+
+function fixedRects(plan: Plan): Point[][] {
+ return plan.furniture
+ .filter((f) => FIXED_FURNITURE.has(f.type))
+ .map((f) => {
+ const r = resolveFurniture(f)
+ return rect(f.x, f.y, r.w, r.d, f.rotationDeg ?? 0)
+ })
+}
+
+function placeCollector(det: RoomDetection, rooms: HeatRoom[]): Point {
+ const main = [...det.buildings].sort((a, b) => b.rooms.filter((r) => r.name).length - a.rooms.filter((r) => r.name).length || b.footprintM2 - a.footprintM2)[0]
+ const center = main ? centroid(main.footprint) : { x: 0, y: 0 }
+ const boiler = rooms.find((r) => r.cls === 'boiler')
+ if (!boiler) return { x: Math.round(center.x), y: Math.round(center.y) }
+ const ring = inset([boiler.face.clearPolygon], 150)[0] ?? boiler.face.clearPolygon
+ const p = closestOnPolygon(ring, center).point
+ return { x: Math.round(p.x), y: Math.round(p.y) }
+}
+
+export type LayoutResult = { heating: HeatingNetwork; notes: string[] }
+
+export function autoLayout(plan: Plan): LayoutResult {
+ const det = detectRooms(plan)
+ const rooms = heatRooms(plan, det)
+ const doors = doorsOf(plan, det, rooms)
+ const prev = heatingOf(plan)
+ const notes: string[] = []
+ const at = prev.collector ? { x: prev.collector.x, y: prev.collector.y } : placeCollector(det, rooms)
+ if (!prev.collector) {
+ const b = rooms.find((r) => r.cls === 'boiler')
+ notes.push(b ? t('networks:heating.layout.collectorInRoom', { room: b.name }) : t('networks:heating.layout.noBoilerRoom'))
+ } else notes.push(t('networks:heating.layout.collectorKept'))
+ const fixed = fixedRects(plan)
+ const pipe = prev.loops[0]?.pipe ?? DEFAULT_PIPE
+ const make = (room: HeatRoom, poly: Point[], step: HeatingStep, edge: boolean, suffix: string): HeatingLoop => {
+ const excluded = intersect([poly], fixed)
+ return {
+ id: 'hl',
+ ...(room.labelId ? { roomId: room.labelId } : {}),
+ roomName: `${room.name}${edge ? t('networks:heating.layout.edgeSuffix') : ''}${suffix}`,
+ polygon: poly,
+ stepMm: step,
+ pattern: 'spiral',
+ pipe,
+ supplyPath: supplyPath(at, poly, room, rooms, doors),
+ ...(excluded.length ? { excluded } : {}),
+ ...(edge ? { edge: true } : {}),
+ }
+ }
+ const coilOf = (l: { polygon: Point[]; excluded?: Point[][] }, step: number) => (Math.abs(areaOf(minus([l.polygon], l.excluded ?? []))) / 1e6 / (step / 1000)) * (1 + PIPE_RESERVE)
+ const measure = (room: HeatRoom, poly: Point[], step: HeatingStep) => {
+ const feed = pathLength(supplyPath(at, poly, room, rooms, doors)) / 1000
+ const coil = coilOf({ polygon: poly, excluded: intersect([poly], fixed) }, step)
+ return { feed, coil, total: coil + 2 * feed * (1 + PIPE_RESERVE) }
+ }
+ const piece = (out: HeatingLoop[], room: HeatRoom, poly: Point[], step: HeatingStep, edge: boolean) => {
+ const { feed, coil, total } = measure(room, poly, step)
+ if (total <= LOOP_MAX_M) {
+ out.push(make(room, poly, step, edge, ''))
+ return 1
+ }
+ const room4coil = LOOP_MAX_M - 2 * feed * (1 + PIPE_RESERVE)
+ const n = room4coil > 15 ? Math.ceil(coil / room4coil) : Math.ceil(total / LOOP_MAX_M)
+ const parts = splitStrips([poly], n).flat().filter((p) => Math.abs(areaOf([p])) > 5e5)
+ parts.forEach((p, i) => out.push(make(room, p, step, edge, ` · ${i + 1}/${parts.length}`)))
+ return parts.length
+ }
+ type Mode = 'auto' | 'full100' | 'edge' | 'split100'
+ const genRoom = (room: HeatRoom, mode: Mode): HeatingLoop[] | null => {
+ const base = inset([room.face.clearPolygon], WALL_GAP).filter((p) => Math.abs(areaOf([p])) > 3e5)
+ if (!base.length) return []
+ const out: HeatingLoop[] = []
+ const wet = room.cls === 'wet'
+ if (mode === 'full100' || mode === 'split100') {
+ for (const p of base) if (piece(out, room, p, 100, false) > 1 && mode === 'full100') return null
+ return out
+ }
+ const bigEnough = mode === 'edge' || room.face.areaM2 > EDGE_ROOM_M2
+ const buf = !wet && bigEnough && room.exteriorWalls.length ? strokeBuffer(room.exteriorWalls.map((w) => [w.a, w.b]), room.exteriorWalls[0].thickness / 2 + EDGE_STRIP) : []
+ const edge = buf.length ? intersect(base, buf).filter((p) => Math.abs(areaOf([p])) > 5e5) : []
+ const core = buf.length ? minus(base, buf).filter((p) => Math.abs(areaOf([p])) > 5e5) : []
+ const minEdge = mode === 'edge' ? 1 : EDGE_MIN_M2
+ const edgeFits = edge.length === 1 && measure(room, edge[0], 100).total <= LOOP_MAX_M
+ if (edgeFits && core.length && Math.abs(areaOf(edge)) / 1e6 >= minEdge && Math.abs(areaOf(core)) / 1e6 >= minEdge) {
+ edge.forEach((p) => piece(out, room, p, 100, true))
+ core.forEach((p) => piece(out, room, p, 150, false))
+ } else if (mode === 'edge') return null
+ else base.forEach((p) => piece(out, room, p, wet ? 100 : 150, false))
+ return out
+ }
+
+ const byRoom = new Map<HeatRoom, HeatingLoop[]>()
+ for (const room of rooms) {
+ if (room.cls === 'skip') {
+ notes.push(t('networks:heating.layout.noHeating', { room: room.name }))
+ continue
+ }
+ if (room.face.areaM2 < 1) continue
+ byRoom.set(room, genRoom(room, 'auto') ?? [])
+ }
+ const keyOf = (r: HeatRoom) => r.labelId ?? r.face.id
+ const collectorAt: HeatingCollector = { ...(prev.collector ?? {}), id: prev.collector?.id ?? 'collector', x: at.x, y: at.y, outputs: 1 }
+ const evaluate = (loops: HeatingLoop[]) => computeHeating({ ...plan, networks: { ...plan.networks, heating: { ...prev, collector: collectorAt, loops } } })
+ const flat = () => [...byRoom.values()].flat()
+ const short = evaluate(flat()).rooms.filter((b) => !b.ok).map((b) => b.key)
+ for (const room of byRoom.keys()) {
+ if (!short.includes(keyOf(room)) || room.cls === 'wet') continue
+ const was = byRoom.get(room)!
+ let fixedIt = false
+ for (const mode of ['full100', 'edge', 'split100'] as Mode[]) {
+ const alt = genRoom(room, mode)
+ if (!alt || !alt.length) continue
+ byRoom.set(room, alt)
+ if (evaluate(flat()).rooms.find((b) => b.key === keyOf(room))?.ok) {
+ notes.push(t(mode === 'edge' ? 'networks:heating.layout.fixedEdge' : 'networks:heating.layout.fixedFull', { room: room.name }))
+ fixedIt = true
+ break
+ }
+ byRoom.set(room, was)
+ }
+ if (!fixedIt) notes.push(t('networks:heating.layout.needRadiator', { room: room.name }))
+ }
+ const roomOf = new Map<HeatingLoop, HeatRoom>()
+ for (const [room, ls] of byRoom) for (const l of ls) roomOf.set(l, room)
+ let loops = flat()
+ for (const [room, ls] of byRoom) if (ls.length > 1 && ls.some((l) => / · \d+\/\d+$/.test(l.roomName ?? ''))) notes.push(t('networks:heating.layout.loopsInRoom', { room: room.name, count: ls.length }))
+
+ while (loops.length > MAX_OUTPUTS) {
+ let best: { a: HeatingLoop; b: HeatingLoop; link: Point[]; len: number } | null = null
+ for (const a of loops)
+ for (const b of loops) {
+ if (a === b || a.stepMm !== b.stepMm || a.parts || b.parts || roomOf.get(a) === roomOf.get(b)) continue
+ if (pathLength(a.supplyPath) > pathLength(b.supplyPath)) continue
+ const entry = a.supplyPath?.[a.supplyPath.length - 1] ?? a.polygon[0]
+ const link = supplyPath(entry, b.polygon, roomOf.get(b), rooms, doors)
+ const linkM = pathLength(link) / 1000
+ if (linkM > MAX_LINK_M) continue
+ const len = coilOf(a, a.stepMm) + coilOf(b, b.stepMm) + 2 * (pathLength(a.supplyPath) / 1000 + linkM) * (1 + PIPE_RESERVE)
+ if (len > LOOP_MAX_M) continue
+ if (!best || len < best.len) best = { a, b, link, len }
+ }
+ if (!best) {
+ notes.push(t('networks:heating.layout.cantMerge', { count: loops.length }))
+ break
+ }
+ const { a, b, link } = best
+ const merged: HeatingLoop = {
+ ...a,
+ roomName: `${a.roomName} + ${b.roomName}`,
+ parts: [{ polygon: b.polygon, ...(b.roomId ? { roomId: b.roomId } : {}), ...(b.roomName ? { roomName: b.roomName } : {}), ...(b.excluded ? { excluded: b.excluded } : {}) }],
+ linkPath: link,
+ }
+ roomOf.set(merged, roomOf.get(a)!)
+ loops = loops.filter((l) => l !== b).map((l) => (l === a ? merged : l))
+ notes.push(t('networks:heating.layout.merged', { a: a.roomName, b: b.roomName, len: Math.round(best.len) }))
+ }
+
+ loops.sort((a, b) => pathLength(a.supplyPath) - pathLength(b.supplyPath))
+ loops.forEach((l, i) => (l.id = `hl${i + 1}`))
+ const collector: HeatingCollector = { ...collectorAt, outputs: Math.max(loops.length, 1) }
+ return { heating: { ...prev, collector, loops }, notes }
+}
+
+export function rerouteAll(plan: Plan): HeatingNetwork {
+ const h = heatingOf(plan)
+ if (!h.collector) return h
+ const det = detectRooms(plan)
+ const rooms = heatRooms(plan, det)
+ const doors = doorsOf(plan, det, rooms)
+ const at = { x: h.collector.x, y: h.collector.y }
+ return {
+ ...h,
+ loops: h.loops.map((l) => {
+ const room = rooms.find((r) => r.labelId && r.labelId === l.roomId) ?? roomOfPoint(rooms, centroid(l.polygon))
+ const sp = supplyPath(at, l.polygon, room, rooms, doors)
+ const part = l.parts?.[0]
+ if (!part) return { ...l, supplyPath: sp }
+ const partRoom = rooms.find((r) => r.labelId && r.labelId === part.roomId) ?? roomOfPoint(rooms, centroid(part.polygon))
+ return { ...l, supplyPath: sp, linkPath: supplyPath(sp[sp.length - 1], part.polygon, partRoom, rooms, doors) }
+ }),
+ }
+}
+
+export const loopBox = (l: HeatingLoop) => bbox([l.polygon])
diff --git a/src/networks/heating/model.ts b/src/networks/heating/model.ts
new file mode 100644
index 0000000..2f8cdb3
--- /dev/null
+++ b/src/networks/heating/model.ts
@@ -0,0 +1,114 @@
+import { nextId, type HeatingCollector, type HeatingLoop, type HeatingNetwork, type HeatingParams, type HeatingStep, type Plan, type Point } from '../../model'
+import { t } from '../../i18n'
+
+export const EMPTY_HEATING: HeatingNetwork = { loops: [] }
+
+export const DEFAULT_PIPE = '16x2 PEX-a'
+export const PIPES = ['16x2 PEX-a', '16x2 PE-RT']
+export const STEPS: HeatingStep[] = [100, 150, 200]
+export const LOOP_MAX_M = 80
+export const LOOP_HARD_MAX_M = 100
+export const WALL_GAP = 100
+export const PIPE_RESERVE = 0.05
+
+export const DEFAULT_PARAMS: ResolvedParams = {
+ supplyT: 45,
+ returnT: 35,
+ screedMm: 60,
+ insulation: 'XPS 100',
+ screedMix: 'cement-sand',
+ fixing: 'staples',
+}
+
+export const heatingOf = (plan: Plan): HeatingNetwork => plan.networks?.heating ?? EMPTY_HEATING
+
+export type ResolvedParams = { supplyT: number; returnT: number; floorT?: number; screedMm: number; insulation: string; screedMix: 'cement-sand' | 'cps'; fixing: 'mesh' | 'staples' }
+
+export const paramsOf = (h: HeatingNetwork): ResolvedParams => {
+ const p: HeatingParams = h.params ?? {}
+ const d = DEFAULT_PARAMS
+ return {
+ supplyT: p.supplyT ?? d.supplyT,
+ returnT: p.returnT ?? d.returnT,
+ floorT: p.floorT,
+ screedMm: p.screedMm ?? d.screedMm,
+ insulation: p.insulation || d.insulation,
+ screedMix: p.screedMix ?? d.screedMix,
+ fixing: p.fixing ?? d.fixing,
+ }
+}
+
+export const withHeating = (plan: Plan, fn: (h: HeatingNetwork) => HeatingNetwork): Plan => ({
+ ...plan,
+ networks: { ...plan.networks, heating: fn(heatingOf(plan)) },
+})
+
+export const updateLoop = (plan: Plan, id: string, patch: Partial<HeatingLoop>): Plan =>
+ withHeating(plan, (h) => ({
+ ...h,
+ loops: h.loops.map((l) => {
+ if (l.id !== id) return l
+ const next = { ...l, ...patch } as HeatingLoop
+ for (const k of Object.keys(patch) as (keyof HeatingLoop)[]) if (patch[k] === undefined) delete next[k]
+ return next
+ }),
+ }))
+
+export const deleteLoop = (plan: Plan, id: string): Plan => withHeating(plan, (h) => ({ ...h, loops: h.loops.filter((l) => l.id !== id) }))
+
+export const setCollector = (plan: Plan, collector: HeatingCollector | undefined): Plan =>
+ withHeating(plan, (h) => {
+ const next = { ...h }
+ if (collector) next.collector = collector
+ else delete next.collector
+ return next
+ })
+
+export const setParams = (plan: Plan, patch: Partial<HeatingParams>): Plan =>
+ withHeating(plan, (h) => {
+ const params = { ...h.params, ...patch }
+ for (const k of Object.keys(patch) as (keyof HeatingParams)[]) if (patch[k] === undefined) delete params[k]
+ return { ...h, params }
+ })
+
+export const loopId = (loops: HeatingLoop[]) => nextId('hl', loops)
+
+export const pathLength = (path: Point[] | undefined) =>
+ (path ?? []).reduce((s, p, i, a) => (i ? s + Math.hypot(p.x - a[i - 1].x, p.y - a[i - 1].y) : 0), 0)
+
+export function polygonArea(poly: Point[]) {
+ let s = 0
+ for (let i = 0; i < poly.length; i++) {
+ const p = poly[i]
+ const q = poly[(i + 1) % poly.length]
+ s += p.x * q.y - q.x * p.y
+ }
+ return Math.abs(s) / 2
+}
+
+export function centroid(poly: Point[]): Point {
+ let a = 0
+ let cx = 0
+ let cy = 0
+ for (let i = 0; i < poly.length; i++) {
+ const p = poly[i]
+ const q = poly[(i + 1) % poly.length]
+ const f = p.x * q.y - q.x * p.y
+ a += f
+ cx += (p.x + q.x) * f
+ cy += (p.y + q.y) * f
+ }
+ if (Math.abs(a) < 1e-6) return { x: poly.reduce((s, p) => s + p.x, 0) / poly.length, y: poly.reduce((s, p) => s + p.y, 0) / poly.length }
+ return { x: cx / (3 * a), y: cy / (3 * a) }
+}
+
+export const stepLabel = (s: number) => `${s} ${t('common:units.mm')}`
+
+export type LoopZone = { polygon: Point[]; excluded?: Point[][]; roomId?: string; roomName?: string }
+
+export const zonesOf = (l: HeatingLoop): LoopZone[] => [
+ { polygon: l.polygon, excluded: l.excluded, roomId: l.roomId, roomName: l.roomName },
+ ...(l.parts ?? []).map((p) => ({ polygon: p.polygon, excluded: p.excluded, roomId: p.roomId, roomName: p.roomName })),
+]
+
+export const allPolygons = (l: HeatingLoop) => zonesOf(l).map((z) => z.polygon)
diff --git a/src/networks/heating/pricing.ts b/src/networks/heating/pricing.ts
new file mode 100644
index 0000000..501fe23
--- /dev/null
+++ b/src/networks/heating/pricing.ts
@@ -0,0 +1,185 @@
+import type { NetworkMaterial } from '../../model'
+import type { CatalogItem } from '../../estimate/catalog'
+import type { HeatingItem, HeatingUnit } from './calc'
+import { fmtNum, t } from '../../i18n'
+import { unitLabel as rawUnitLabel } from '../../i18n/units'
+
+export const noPrice = () => t('networks:heating.price.none')
+
+export const unitLabel = (u: HeatingUnit | 'pack') => t(`networks:heating.units.${u}`)
+
+const SHOP_UNIT: Record<HeatingUnit, string> = { pcs: 'шт', m: 'м', m2: 'м²', m3: 'м³', kg: 'кг' }
+
+export type PricedHeatingItem = HeatingItem & { buyQty: number; buyUnit: string; price?: number; url?: string; priceFrom: string }
+
+type Loose = Record<string, unknown> & {
+ id: string
+ name: string
+ kind?: string
+ subtype?: string
+ price?: number
+ unit?: string
+ pricePer?: string
+ url?: string
+ vendor?: string
+ source?: string
+ preferred?: boolean
+}
+
+const num = (v: unknown) => {
+ const n = typeof v === 'string' ? Number(v.replace(',', '.')) : v
+ return typeof n === 'number' && Number.isFinite(n) ? n : undefined
+}
+const field = (x: Loose, ...keys: string[]) => {
+ for (const k of keys) {
+ const v = num(x[k])
+ if (v !== undefined) return v
+ }
+ return undefined
+}
+const text = (x: Loose) => `${x.name} ${x.subtype ?? ''} ${typeof x.note === 'string' ? x.note : ''}`.toLowerCase()
+const has = (t: string, ...w: string[]) => w.some((s) => t.includes(s))
+
+const SUBS: Record<string, { subs: string[]; words: string[]; not?: string[] }> = {
+ pipe: { subs: ['pipe'], words: ['труба'] },
+ collector: { subs: ['collector'], words: ['коллектор'], not: ['шкаф'] },
+ mixing: { subs: ['mixing'], words: ['смесительн'] },
+ pump: { subs: ['pump', 'mixing'], words: ['циркуляц'], not: ['смесительн'] },
+ cabinet: { subs: ['cabinet'], words: ['шкаф'] },
+ eurocone: { subs: ['eurocone', 'fitting'], words: ['евроконус'] },
+ damper: { subs: ['damper'], words: ['демпфер'] },
+ insulation: { subs: ['insulation'], words: ['xps', 'эппс', 'экструд', 'пенополистирол'] },
+ film: { subs: ['film'], words: ['плёнк', 'пленк'] },
+ mesh: { subs: ['mesh'], words: ['сетка'] },
+ staples: { subs: ['staples', 'mesh'], words: ['скоба', 'гарпун'] },
+ ties: { subs: ['ties', 'mesh'], words: ['хомут', 'стяжк'] },
+ cement: { subs: ['cement', 'screed'], words: ['цемент'], not: ['цементно-песчан', 'смесь'] },
+ sand: { subs: ['sand', 'screed'], words: ['песок'] },
+ cps: { subs: ['cps', 'screed'], words: ['цпс', 'цементно-песчан'] },
+ fiber: { subs: ['fiber', 'screed'], words: ['фибр'] },
+}
+
+const maxNum = (v: unknown) => {
+ if (typeof v === 'number') return v
+ if (typeof v !== 'string') return undefined
+ const ns = v.match(/\d+/g)?.map(Number)
+ return ns?.length ? Math.max(...ns) : undefined
+}
+const outputsOf = (x: Loose) => maxNum(x.outputs ?? x.outlets ?? x.ways) ?? num(/(\d{1,2})\s*(?:вых|конт|отвод|петл)/i.exec(x.name)?.[1])
+const coilOf = (x: Loose) => {
+ const l = field(x, 'coil', 'lengthM')
+ if (l !== undefined) return l > 1000 ? l / 1000 : l
+ return num(/\((\d{3})\s*м\)/i.exec(x.name)?.[1])
+}
+const flat = (t: string) => t.replace(/[-\s]/g, '')
+
+function fits(item: HeatingItem, x: Loose) {
+ const rule = SUBS[item.sub]
+ if (!rule) return false
+ const sub = String(x.subtype ?? '').toLowerCase()
+ const t = text(x)
+ if (sub && !rule.subs.includes(sub)) return false
+ if (!has(t, ...rule.words) || (rule.not && has(t, ...rule.not))) return false
+ const sp = item.spec ?? {}
+ switch (item.sub) {
+ case 'pipe': {
+ const want = flat(String(sp.pipe ?? '').toLowerCase())
+ const kind = want.includes('pert') ? 'pert' : want.includes('pexa') ? 'pexa' : want.includes('pex') ? 'pex' : ''
+ const got = flat(`${x.material ?? ''} ${x.name}`.toLowerCase())
+ if (kind && !got.includes(kind)) return false
+ const d = field(x, 'diameter') ?? num(/(\d{2})\s*[xх×]/i.exec(x.name)?.[1])
+ return d === 16 && coilOf(x) === sp.coil
+ }
+ case 'collector':
+ case 'cabinet':
+ return (outputsOf(x) ?? 0) >= Number(sp.outputs ?? 0)
+ case 'insulation': {
+ const want = String(sp.insulation ?? '').toLowerCase()
+ const th = num(/(\d{2,3})/.exec(want)?.[1])
+ const got = field(x, 'thickness') ?? num(/(\d{2,3})\s*[xх×]/i.exec(x.name)?.[1])
+ return !th || !got || got === th
+ }
+ case 'film': {
+ const th = field(x, 'thickness')
+ return th === undefined || sp.thickness === undefined || th === sp.thickness
+ }
+ default:
+ return true
+ }
+}
+
+const matches = (item: HeatingItem, x: Loose) => x.id === item.key || fits(item, x)
+
+const perUnit = (item: HeatingItem, x: Loose): number | undefined => {
+ const u = (x.unit ?? '').trim().toLowerCase().replace(/\s+/g, ' ')
+ const lenMm = field(x, 'length')
+ const hMm = field(x, 'height')
+ const sheet = lenMm && hMm && lenMm > 100 && hMm > 100 ? (lenMm * hMm) / 1e6 : undefined
+ switch (item.unit) {
+ case 'm2':
+ if (u === 'м²' || u === 'м2' || x.pricePer === 'm2') return 1
+ if (field(x, 'area', 'areaM2')) return field(x, 'area', 'areaM2')
+ if (sheet) return sheet
+ if (field(x, 'width')) return (field(x, 'width')! / 1000) * (u.startsWith('пог') ? 1 : (field(x, 'roll') ?? 1))
+ return undefined
+ case 'm': {
+ if (u === 'м' || u.startsWith('пог') || x.pricePer === 'm') return 1
+ const l = field(x, 'roll', 'lengthM')
+ return l === undefined ? undefined : l > 1000 ? l / 1000 : l
+ }
+ case 'kg':
+ if (u === 'кг' || x.pricePer === 'kg') return 1
+ return field(x, 'weight', 'weightKg')
+ case 'm3':
+ if (u === 'м³' || u === 'м3' || x.pricePer === 'm3') return 1
+ return field(x, 'volume', 'volumeM3')
+ case 'pcs':
+ return field(x, 'pack') ?? 1
+ default:
+ return undefined
+ }
+}
+
+function pick(item: HeatingItem, list: Loose[]) {
+ const all = list.filter((x) => x.price !== undefined && matches(item, x) && perUnit(item, x))
+ if (!all.length) return undefined
+ const exact = all.filter((x) => x.id === item.key)
+ const pool0 = exact.length ? exact : all
+ const pref = pool0.filter((x) => x.preferred)
+ const pool = pref.length ? pref : pool0
+ const cost = (x: Loose) => (x.price ?? 0) / (perUnit(item, x) ?? 1) + (item.sub === 'collector' || item.sub === 'cabinet' ? (outputsOf(x) ?? 0) : 0)
+ return [...pool].sort((a, b) => cost(a) - cost(b))[0]
+}
+
+function priceFrom(item: HeatingItem, src: Loose, from: string): PricedHeatingItem {
+ const pack = perUnit(item, src) ?? 1
+ const own = SHOP_UNIT[item.unit]
+ if (src.price === undefined) return { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit), url: src.url, priceFrom: noPrice() }
+ if (pack === 1 && src.unit && src.unit !== own && item.unit !== 'pcs') return { ...item, buyQty: Math.ceil(item.qty), buyUnit: src.unit, price: src.price, url: src.url, priceFrom: from }
+ if (pack === 1) return { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit), price: src.price, url: src.url, priceFrom: from }
+ const packUnit = src.unit && src.unit !== own ? src.unit : unitLabel('pack')
+ return { ...item, buyQty: Math.ceil(item.qty / pack), buyUnit: packUnit, price: src.price, url: src.url, priceFrom: t('networks:heating.price.pack', { from, qty: fmtNum(Math.round(pack * 100) / 100), unit: unitLabel(item.unit), pack: rawUnitLabel(packUnit) }) }
+}
+
+export function priceHeating(items: HeatingItem[], materials: NetworkMaterial[] | undefined, catalog: CatalogItem[]): PricedHeatingItem[] {
+ const own = (materials ?? []) as unknown as Loose[]
+ const shop = catalog.filter((c) => c.kind === 'heating' || c.kind.startsWith('heating')) as unknown as Loose[]
+ return items.map((item) => {
+ const m = own.find((x) => matches(item, x))
+ if (m) return priceFrom(item, m, t('networks:heating.price.own', { name: `${m.name}${m.source ? `, ${m.source}` : ''}` }))
+ const c = pick(item, shop)
+ if (c) return priceFrom(item, c, `${c.name}${c.vendor ? `, ${c.vendor}` : ''}`)
+ const n = Number(item.spec?.outputs ?? 0)
+ if ((item.sub === 'collector' || item.sub === 'cabinet') && n > 2) {
+ const half = { ...item, spec: { ...item.spec, outputs: Math.ceil(n / 2) } }
+ const c2 = pick(half, shop)
+ if (c2) {
+ const r = priceFrom(half, c2, t('networks:heating.price.twoHalves', { n: Math.ceil(n / 2), name: `${c2.name}${c2.vendor ? `, ${c2.vendor}` : ''}` }))
+ return { ...r, spec: item.spec, name: t('networks:heating.price.twoOf', { name: item.name, n: Math.ceil(n / 2) }), buyQty: r.buyQty * 2 }
+ }
+ }
+ return { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit), priceFrom: noPrice() }
+ })
+}
+
+export const heatingSum = (i: PricedHeatingItem) => (i.price ?? 0) * i.buyQty
diff --git a/src/networks/heating/rooms.ts b/src/networks/heating/rooms.ts
new file mode 100644
index 0000000..cda5694
--- /dev/null
+++ b/src/networks/heating/rooms.ts
@@ -0,0 +1,88 @@
+import type { Plan, Point } from '../../model'
+import { t } from '../../i18n'
+import { detectRooms, pointInPolygon, type DetectedBuilding, type RoomDetection, type RoomFace } from '../../stats/rooms'
+
+export type RoomClass = 'wet' | 'tile' | 'dry' | 'boiler' | 'skip'
+
+export type HeatRoom = {
+ face: RoomFace
+ building: DetectedBuilding
+ labelId?: string
+ name: string
+ cls: RoomClass
+ cover: 'tile' | 'laminate'
+ exteriorWalls: { a: Point; b: Point; thickness: number }[]
+ exteriorSides: number
+ lossWm2: number
+ tInside: number
+}
+
+const WET = /сан\.?\s?узел|санузел|с\/у|душ|ванн|туалет|уборн|постир|прачеч|bath|shower|toilet|\bwc\b|restroom|laundry|utility/i
+const TILE = /кухн|прихож|коридор|холл|тамбур|крыльц|веранд|столов|kitchen|hall|corridor|entry|entrance|vestibule|porch|veranda|dining/i
+const DRY = /спальн|зал\b|^зал|гостин|гардероб|кабинет|детск|комнат|bedroom|living|lounge|wardrobe|closet|office|study|nursery|kids|guest room|playroom/i
+const BOILER = /кот[её]л|котельн|тепловой узел|топочн|boiler|furnace|mechanical/i
+const SKIP = /саун|парилк|парн|гараж|баня|чердак|мансард.*холод|sauna|steam|garage|attic/i
+
+export function classify(name: string, kind?: string): RoomClass {
+ if (SKIP.test(name)) return 'skip'
+ if (BOILER.test(name)) return 'boiler'
+ if (WET.test(name)) return 'wet'
+ if (TILE.test(name)) return 'tile'
+ if (DRY.test(name)) return 'dry'
+ if (/^(Помещение|Room) \d+$/.test(name)) return 'skip'
+ if (kind === 'garage') return 'skip'
+ if (kind === 'tech') return 'boiler'
+ if (kind === 'bath') return 'wet'
+ if (kind === 'kitchen' || kind === 'hall') return 'tile'
+ return 'dry'
+}
+
+export const coverOf = (cls: RoomClass): 'tile' | 'laminate' => (cls === 'dry' ? 'laminate' : 'tile')
+
+export const coverLabel = (c: 'tile' | 'laminate') => t(`networks:heating.cover.${c}`)
+
+export function lossNorm(exteriorSides: number) {
+ return exteriorSides >= 2 ? 70 : exteriorSides === 1 ? 60 : 50
+}
+
+function sides(walls: { a: Point; b: Point }[]) {
+ const dirs: number[] = []
+ for (const w of walls) {
+ const ang = ((Math.atan2(w.b.y - w.a.y, w.b.x - w.a.x) * 180) / Math.PI + 180) % 180
+ if (!dirs.some((d) => Math.min(Math.abs(d - ang), 180 - Math.abs(d - ang)) < 20)) dirs.push(ang)
+ }
+ return walls.length ? Math.max(1, dirs.length) : 0
+}
+
+export function heatRooms(plan: Plan, det: RoomDetection = detectRooms(plan)): HeatRoom[] {
+ const out: HeatRoom[] = []
+ for (const b of det.buildings) {
+ const outer = new Set(b.outlineEdges)
+ for (const face of b.rooms) {
+ const label = plan.rooms?.find((r) => face.labelIds.includes(r.id))
+ const cls = classify(face.name, face.kind ?? label?.kind)
+ const ext = face.edges
+ .filter((e) => outer.has(e))
+ .map((e) => ({ a: det.nodes[e.u], b: det.nodes[e.v], thickness: e.wall.thickness }))
+ .filter((w) => Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) > 300)
+ const exteriorSides = sides(ext)
+ out.push({
+ face,
+ building: b,
+ labelId: face.labelIds[0],
+ name: face.name,
+ cls,
+ cover: coverOf(cls),
+ exteriorWalls: ext,
+ exteriorSides,
+ lossWm2: lossNorm(exteriorSides),
+ tInside: cls === 'wet' ? 24 : 20,
+ })
+ }
+ }
+ return out
+}
+
+export function roomOfPoint(rooms: HeatRoom[], p: Point) {
+ return rooms.find((r) => pointInPolygon(p, r.face.axisPolygon))
+}
diff --git a/src/networks/heating/store.ts b/src/networks/heating/store.ts
new file mode 100644
index 0000000..45f5000
--- /dev/null
+++ b/src/networks/heating/store.ts
@@ -0,0 +1,19 @@
+import { create } from 'zustand'
+
+type HeatingUiState = {
+ selected: string | null
+ collectorSelected: boolean
+ tab: boolean
+ select: (id: string | null) => void
+ selectCollector: (on: boolean) => void
+ setTab: (on: boolean) => void
+}
+
+export const useHeatingUi = create<HeatingUiState>()((set) => ({
+ selected: null,
+ collectorSelected: false,
+ tab: false,
+ select: (selected) => set({ selected, collectorSelected: false }),
+ selectCollector: (collectorSelected) => set({ collectorSelected, selected: null }),
+ setTab: (tab) => set({ tab }),
+}))
diff --git a/src/networks/index.ts b/src/networks/index.ts
new file mode 100644
index 0000000..b4c9747
--- /dev/null
+++ b/src/networks/index.ts
@@ -0,0 +1,18 @@
+import './sewerEdit'
+import './waterEdit'
+
+export { SewerLayer, PIPE_COLOR } from './SewerLayer'
+export { LayersButton, NetworkEditBar } from './NetworkTools'
+export { SewerInspector, SewerSummary, useSewerSelection } from './SewerPanel'
+export { useLayers, useBaseOpacity, DIM_OPACITY, LAYER_LABELS, type LayerKey } from './layers'
+export { registerNetworkLayer, startEdit, stopEdit, isEditing, useNetworkEdit, type NetworkLayerDef } from './registry'
+export { useSewerUi } from './sewerStore'
+export { computeSewer, type SewerCalc } from './sewerCalc'
+export { sewerEstimateRows, sewerGroup } from './estimate'
+export { useLayerLocks, layerLocks, isLayerLocked, lockedToast, wallsLockedText } from './locks'
+export { DEFAULT_LOCKS, type LayerLocks } from './layers'
+export { WaterLayer } from './WaterLayer'
+export { useWaterUi } from './waterStore'
+export { WaterInspector, WaterSummary, useWaterSelection } from './WaterPanel'
+export { computeWater, type WaterCalc } from './waterCalc'
+export { waterEstimateRows, waterGroup } from './estimate'
diff --git a/src/networks/labels.ts b/src/networks/labels.ts
new file mode 100644
index 0000000..553a166
--- /dev/null
+++ b/src/networks/labels.ts
@@ -0,0 +1,15 @@
+import { fmtNum, t } from '../i18n'
+
+export function labelMap<K extends string>(keys: readonly K[], prefix: string): Record<K, string> {
+ const map = {} as Record<K, string>
+ for (const k of keys) Object.defineProperty(map, k, { get: () => t(`${prefix}.${k}`), enumerable: true })
+ return map
+}
+
+export type ItemUnit = 'm' | 'pcs'
+
+export { unitLabel } from '../i18n/units'
+
+export const fmtPct = (v: number, d = 2) => t('networks:shared.units.pct', { v: fmtNum(v, d) })
+
+export const fmtM = (mm: number) => `${fmtNum(mm / 1000)} ${t('common:units.m')}`
diff --git a/src/networks/layers.ts b/src/networks/layers.ts
new file mode 100644
index 0000000..e0688c9
--- /dev/null
+++ b/src/networks/layers.ts
@@ -0,0 +1,49 @@
+import { create } from 'zustand'
+import { createJSONStorage, persist } from 'zustand/middleware'
+import { labelMap } from './labels'
+
+export type LayerKey = 'walls' | 'furniture' | 'zones' | 'sewer' | 'water' | 'electric' | 'heating'
+
+export const LAYER_LABELS: Record<LayerKey, string> = labelMap<LayerKey>(['walls', 'furniture', 'zones', 'sewer', 'water', 'electric', 'heating'], 'networks:shared.layers')
+
+export const DIM_OPACITY = 0.4
+
+export type LayerLocks = Record<LayerKey, boolean>
+
+export const DEFAULT_LOCKS: LayerLocks = { walls: true, furniture: false, zones: false, sewer: false, water: false, electric: false, heating: false }
+
+type LayersState = Record<LayerKey, boolean> & {
+ locks: LayerLocks
+ setLayer: (key: LayerKey, on: boolean) => void
+ setLock: (key: LayerKey, locked: boolean) => void
+}
+
+export const useLayers = create<LayersState>()(
+ persist(
+ (set) => ({
+ walls: true,
+ furniture: true,
+ zones: true,
+ sewer: false,
+ water: false,
+ electric: false,
+ heating: false,
+ locks: DEFAULT_LOCKS,
+ setLayer: (key, on) => set({ [key]: on } as Partial<LayersState>),
+ setLock: (key, locked) => set((st) => ({ locks: { ...st.locks, [key]: locked } })),
+ }),
+ {
+ name: 'house-planner:layers',
+ version: 3,
+ migrate: () => ({ walls: true, furniture: true, zones: true, sewer: false, water: false, electric: false, heating: false, locks: DEFAULT_LOCKS }) as LayersState,
+ storage: createJSONStorage(() => localStorage),
+ partialize: (s) => ({ walls: s.walls, furniture: s.furniture, zones: s.zones, sewer: s.sewer, water: s.water, electric: s.electric, heating: s.heating, locks: s.locks }),
+ merge: (persisted, current) => {
+ const p = (persisted ?? {}) as Partial<LayersState>
+ return { ...current, ...p, locks: { ...DEFAULT_LOCKS, ...p.locks } }
+ },
+ },
+ ),
+)
+
+export const useBaseOpacity = () => useLayers((s) => (s.sewer || s.water || s.electric || s.heating ? DIM_OPACITY : 1))
diff --git a/src/networks/locks.ts b/src/networks/locks.ts
new file mode 100644
index 0000000..54ca871
--- /dev/null
+++ b/src/networks/locks.ts
@@ -0,0 +1,39 @@
+import { useLayers, type LayerKey, type LayerLocks } from './layers'
+import { stopEdit, useNetworkEdit } from './registry'
+import { showToast } from '../ui/Toast'
+import { t } from '../i18n'
+
+const KEYS: LayerKey[] = ['walls', 'furniture', 'zones', 'sewer', 'water', 'electric', 'heating']
+
+const effective = (locks: LayerLocks, editing: LayerKey | null): LayerLocks =>
+ Object.fromEntries(KEYS.map((k) => [k, !!locks[k] || (!!editing && editing !== k)])) as LayerLocks
+
+export function layerLocks(): LayerLocks {
+ return effective(useLayers.getState().locks, useNetworkEdit.getState().editing)
+}
+
+export const isLayerLocked = (key: LayerKey) => layerLocks()[key]
+
+export function useLayerLocks(): LayerLocks {
+ const locks = useLayers((s) => s.locks)
+ const editing = useNetworkEdit((s) => s.editing)
+ return effective(locks, editing)
+}
+
+export const wallsLockedText = () => t('networks:shared.locks.walls')
+
+let lastToast = 0
+export function lockedToast(key: LayerKey) {
+ const now = Date.now()
+ if (now - lastToast < 1500) return
+ lastToast = now
+ const editing = useNetworkEdit.getState().editing
+ if (editing && editing !== key) showToast(t('networks:shared.locks.editing'))
+ else if (key === 'walls') showToast(wallsLockedText())
+ else showToast(t('networks:shared.locks.layer'))
+}
+
+useLayers.subscribe((st) => {
+ const { editing } = useNetworkEdit.getState()
+ if (editing && st.locks[editing]) stopEdit()
+})
diff --git a/src/networks/networks.css b/src/networks/networks.css
new file mode 100644
index 0000000..92fbfd1
--- /dev/null
+++ b/src/networks/networks.css
@@ -0,0 +1,147 @@
+.net-layers {
+ position: fixed;
+ z-index: var(--z-popover);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ min-width: 220px;
+ max-width: 280px;
+ max-height: calc(100vh - 16px);
+ overflow: auto;
+ padding: 10px 12px;
+ border-radius: var(--radius);
+ box-shadow: var(--shadow-lg);
+}
+
+.net-layers__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ min-height: var(--control-h-sm);
+}
+
+.net-layers__actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.net-layers__lock {
+ color: var(--muted);
+}
+
+.net-layers__lock--on,
+.net-layers__edit--on {
+ color: var(--accent);
+ background: var(--accent-soft);
+}
+
+.net-layers__note {
+ font-size: var(--text-xs);
+}
+
+.net-editbar {
+ position: fixed;
+ top: calc(var(--chrome-top) + var(--ruler));
+ left: 124px;
+ z-index: var(--z-popover);
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ max-width: calc(100vw - 124px - 340px);
+ padding: 6px 8px 6px 14px;
+ border-radius: var(--radius);
+ box-shadow: var(--shadow-lg);
+ white-space: nowrap;
+}
+
+.net-editbar__title {
+ font-weight: 650;
+}
+
+.net-editbar__hint {
+ font-size: var(--text-xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.net-props__pair {
+ display: contents;
+}
+
+.net-items {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.net-item {
+ display: grid;
+ grid-template-columns: 1fr auto auto;
+ gap: var(--space-2);
+ align-items: baseline;
+ padding: 6px 0;
+ font-size: var(--text-sm);
+ border-bottom: 1px solid var(--line);
+}
+
+.net-item__name a {
+ color: inherit;
+}
+
+.net-item__from {
+ font-size: var(--text-xs);
+}
+
+.net-item__qty,
+.net-item__sum {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.net-item__sum {
+ min-width: 76px;
+}
+
+.net-warnings {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: var(--space-2);
+}
+
+.net-warnings .layout-hint {
+ margin-top: 0;
+}
+
+.net-warning {
+ width: 100%;
+ border: 0;
+ color: inherit;
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+}
+
+.tool[aria-disabled='true'] {
+ opacity: 0.35;
+ cursor: not-allowed;
+}
+
+.tool[aria-disabled='true']:hover {
+ background: transparent;
+}
+
+.inspector__tabs .segmented {
+ flex: 0 1 auto;
+ flex-wrap: wrap;
+ height: auto;
+ min-width: 0;
+}
+
+.inspector__tabs .segmented__item {
+ min-height: 24px;
+ white-space: nowrap;
+}
diff --git a/src/networks/pricing.ts b/src/networks/pricing.ts
new file mode 100644
index 0000000..4e9a2b4
--- /dev/null
+++ b/src/networks/pricing.ts
@@ -0,0 +1,113 @@
+import type { NetworkMaterial } from '../model'
+import type { CatalogItem } from '../estimate/catalog'
+import type { SewerItem } from './sewerCalc'
+import { t } from '../i18n'
+import { unitLabel } from './labels'
+
+export type PricedItem = SewerItem & {
+ buyQty: number
+ buyUnit: string
+ price?: number
+ url?: string
+ priceFrom?: string
+}
+
+type Source = { name: string; price?: number; per?: 'pcs' | 'm'; length?: number; pack?: number; unit?: string; url?: string; from: string }
+
+const fits = (item: SewerItem, kind?: string, diameter?: number, angle?: number) =>
+ kind === item.kind && (item.diameter === undefined || diameter === item.diameter) && (item.angle === undefined || angle === undefined || angle === item.angle)
+
+function fromMaterials(item: SewerItem, list: NetworkMaterial[]): Source | undefined {
+ const m = list.find((x) => x.id === item.key) ?? list.find((x) => fits(item, x.kind, x.diameter, x.angle))
+ if (!m) return undefined
+ return {
+ name: m.name,
+ price: m.price,
+ per: m.pricePer === 'm' ? 'm' : 'pcs',
+ length: m.length,
+ url: m.url,
+ from: t('networks:shared.pricing.fromMaterials', { name: `${m.name}${m.source ? `, ${m.source}` : ''}` }),
+ }
+}
+
+function catalogIds(item: SewerItem): string[] {
+ const loc = item.location === 'outside' ? 'out' : 'in'
+ const d = item.diameter
+ switch (item.kind) {
+ case 'pipe':
+ return [`sewer-pipe-${loc}-${d}-`]
+ case 'elbow':
+ return [`sewer-elbow-${loc}-${d}-${item.angle}`]
+ case 'tee': {
+ const m = item.key.match(/^tee-(\d+)(?:x(\d+))?-(\d+)/)
+ if (!m) return []
+ return [`sewer-tee-${loc}-${m[1]}${m[2] ? `x${m[2]}` : ''}-${m[3]}`]
+ }
+ case 'reducer': {
+ const m = item.key.match(/^reducer-(\d+x\d+)/)
+ return m ? [`sewer-reducer-${loc}-${m[1]}`, `sewer-reducer-in-${m[1]}`] : []
+ }
+ case 'cleanout':
+ return [`sewer-cleanout-${loc}-${d}`]
+ case 'clamp':
+ return [`sewer-clamp-${d}-plastic`, `sewer-clamp-${d}-`]
+ case 'corrugation':
+ return [`sewer-wc-corrugated-${d}`]
+ case 'vent':
+ return [`sewer-vent-cap-${d}`]
+ default:
+ return []
+ }
+}
+
+const perMeter = (c: CatalogItem) => (c.length ? c.price / (c.length / 1000) : c.price)
+
+function fromCatalog(item: SewerItem, catalog: CatalogItem[]): Source | undefined {
+ let c: CatalogItem | undefined = catalog.find((x) => x.id === item.key || x.id === `sewer-${item.key}`)
+ if (!c && item.kind === 'septic') {
+ const model = item.model?.toLowerCase().split(/[\s,]+/).filter((w) => w.length > 2) ?? []
+ const septics = catalog.filter((x) => x.subtype === 'septic' || x.kind === 'septic')
+ c = model.length ? septics.find((x) => model.every((w) => x.name.toLowerCase().includes(w))) ?? septics.find((x) => x.name.toLowerCase().includes(model[0])) : undefined
+ }
+ if (!c) {
+ for (const id of catalogIds(item)) {
+ const found = catalog.filter((x) => (id.endsWith('-') ? x.id.startsWith(id) : x.id === id || x.id.startsWith(`${id}-`)))
+ if (found.length) {
+ c = item.kind === 'pipe' ? found.sort((a, b) => perMeter(a) - perMeter(b))[0] : found.sort((a, b) => a.price - b.price)[0]
+ break
+ }
+ }
+ }
+ if (!c) c = catalog.find((x) => x.name === item.name)
+ if (!c) return undefined
+ const perM = /^(м|пог\. ?м|м\.п\.)$/.test(c.unit.trim())
+ const pack = Number(c.name.match(/\((\d+)\s*шт\.?\)/)?.[1] ?? 0) || undefined
+ return {
+ name: c.name,
+ price: c.price,
+ per: perM ? 'm' : 'pcs',
+ length: c.length,
+ pack: pack && pack > 1 ? pack : undefined,
+ unit: c.unit,
+ url: c.url,
+ from: t('networks:shared.pricing.fromCatalog', { name: `${c.name}${c.vendor ? `, ${c.vendor}` : ''}` }),
+ }
+}
+
+export function priceItem(item: SewerItem, materials: NetworkMaterial[], catalog: CatalogItem[]): PricedItem {
+ const src = fromMaterials(item, materials) ?? fromCatalog(item, catalog)
+ const base: PricedItem = { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit) }
+ if (!src) return base
+ const res: PricedItem = { ...base, url: src.url, priceFrom: src.from }
+ if (src.price === undefined) return res
+ if (item.kind === 'pipe' && src.per === 'pcs' && src.length && item.lengthMm !== undefined) {
+ return { ...res, buyQty: Math.ceil(item.lengthMm / src.length), buyUnit: unitLabel('pcs'), price: src.price }
+ }
+ if (src.pack) return { ...res, buyQty: Math.ceil(item.qty / src.pack), buyUnit: src.unit ?? t('networks:shared.units.pack'), price: src.price }
+ return { ...res, price: src.price }
+}
+
+export const priceAll = (items: SewerItem[], materials: NetworkMaterial[] | undefined, catalog: CatalogItem[]) =>
+ items.map((i) => priceItem(i, materials ?? [], catalog))
+
+export const itemSum = (i: PricedItem) => (i.price ?? 0) * i.buyQty
diff --git a/src/networks/registry.ts b/src/networks/registry.ts
new file mode 100644
index 0000000..fd4a90a
--- /dev/null
+++ b/src/networks/registry.ts
@@ -0,0 +1,51 @@
+import type { ComponentType } from 'react'
+import { create } from 'zustand'
+import { usePlanStore } from '../store/planStore'
+import { useLayers, type LayerKey } from './layers'
+
+export type NetworkLayerDef = {
+ key: LayerKey
+ label?: string
+ Tools: ComponentType
+ enter?: () => void
+ exit?: () => void
+ onEscape?: () => boolean
+}
+
+type EditState = { editing: LayerKey | null; defs: Partial<Record<LayerKey, NetworkLayerDef>> }
+
+export const useNetworkEdit = create<EditState>()(() => ({ editing: null, defs: {} }))
+
+export function registerNetworkLayer(def: NetworkLayerDef) {
+ useNetworkEdit.setState((s) => ({ defs: { ...s.defs, [def.key]: def } }))
+}
+
+export function stopEdit() {
+ const { editing, defs } = useNetworkEdit.getState()
+ if (!editing) return
+ useNetworkEdit.setState({ editing: null })
+ defs[editing]?.exit?.()
+}
+
+export function startEdit(key: LayerKey) {
+ const { editing, defs } = useNetworkEdit.getState()
+ if (editing === key) return
+ stopEdit()
+ useLayers.getState().setLayer(key, true)
+ const st = usePlanStore.getState()
+ st.setTool('select')
+ st.selectWall(null)
+ useNetworkEdit.setState({ editing: key })
+ defs[key]?.enter?.()
+}
+
+export const isEditing = (key: LayerKey) => useNetworkEdit.getState().editing === key
+
+usePlanStore.subscribe((st, prev) => {
+ if (st.tool !== prev.tool && st.tool !== 'select') stopEdit()
+})
+
+useLayers.subscribe((st) => {
+ const { editing } = useNetworkEdit.getState()
+ if (editing && !st[editing]) stopEdit()
+})
diff --git a/src/networks/sewerCalc.ts b/src/networks/sewerCalc.ts
new file mode 100644
index 0000000..9c6435d
--- /dev/null
+++ b/src/networks/sewerCalc.ts
@@ -0,0 +1,304 @@
+import { sitePolygon, type Plan, type Point, type SewerNetwork, type SewerNode, type SewerPipe } from '../model'
+import { detectRooms } from '../stats/rooms'
+import {
+ DEFAULT_FLOOR_LEVEL,
+ DEFAULT_RISER_HEIGHT,
+ DEFAULT_SEPTIC,
+ MIN_OUTSIDE_DEPTH,
+ SEPTIC_TO_BOUNDARY_MIN,
+ SEPTIC_TO_HOUSE_MIN,
+ fixtureLabels,
+ minSlope,
+ pipeLength,
+ pipeSlope,
+ projectOnSegment,
+ sewerOf,
+} from './sewerModel'
+import { t } from '../i18n'
+import { fmtM, fmtPct, type ItemUnit } from './labels'
+
+export type SewerItemKind = 'pipe' | 'elbow' | 'tee' | 'reducer' | 'cleanout' | 'clamp' | 'sleeve' | 'corrugation' | 'vent' | 'septic'
+
+export type SewerItem = {
+ key: string
+ kind: SewerItemKind
+ name: string
+ qty: number
+ unit: ItemUnit
+ diameter?: number
+ angle?: number
+ lengthMm?: number
+ location?: SewerPipe['location']
+ model?: string
+}
+
+export type SewerRef = { kind: 'node' | 'pipe'; id: string }
+
+export type SewerWarning = { text: string; ref?: SewerRef }
+
+export type PipeLevel = { start: number; end: number; drop: number; length: number; slope: number; vertical: number }
+
+export type SepticInfo = { nodeId: string; model: string; depth: number | null; toHouse: number | null; toBoundary: number | null }
+
+export type SewerCalc = {
+ lengths: { diameter: number; location: SewerPipe['location']; lengthMm: number }[]
+ items: SewerItem[]
+ nodeLevel: Record<string, number>
+ pipeLevel: Record<string, PipeLevel>
+ outlets: { nodeId: string; depth: number }[]
+ septics: SepticInfo[]
+ warnings: SewerWarning[]
+ floorLevel: number
+}
+
+const pipeName = (d: number, location: SewerPipe['location']) =>
+ t(location === 'outside' ? 'networks:sewer.item.pipeOutside' : 'networks:sewer.item.pipeInside', { d })
+
+function dir(a: Point, b: Point) {
+ const l = Math.hypot(b.x - a.x, b.y - a.y) || 1
+ return { x: (b.x - a.x) / l, y: (b.y - a.y) / l }
+}
+
+function turnDeg(s: SewerNetwork, inPipe: SewerPipe, outPipe: SewerPipe) {
+ const n = (id: string) => s.nodes.find((x) => x.id === id)
+ const a = n(inPipe.from)
+ const m = n(inPipe.to)
+ const b = n(outPipe.to)
+ if (!a || !m || !b) return 0
+ const u = dir(a, m)
+ const v = dir(m, b)
+ const cos = Math.max(-1, Math.min(1, u.x * v.x + u.y * v.y))
+ return (Math.acos(cos) * 180) / Math.PI
+}
+
+export function septicCorners(n: SewerNode): Point[] {
+ const w = n.w ?? DEFAULT_SEPTIC.w
+ const d = n.d ?? DEFAULT_SEPTIC.d
+ const a = ((n.rotationDeg ?? 0) * Math.PI) / 180
+ return [
+ [-w / 2, -d / 2],
+ [w / 2, -d / 2],
+ [w / 2, d / 2],
+ [-w / 2, d / 2],
+ ].map(([x, y]) => ({ x: n.x + x * Math.cos(a) - y * Math.sin(a), y: n.y + x * Math.sin(a) + y * Math.cos(a) }))
+}
+
+function segSegDist(a: Point, b: Point, c: Point, d: Point) {
+ return Math.min(
+ projectOnSegment(a, c, d).dist,
+ projectOnSegment(b, c, d).dist,
+ projectOnSegment(c, a, b).dist,
+ projectOnSegment(d, a, b).dist,
+ )
+}
+
+function polyDist(p: Point[], q: Point[]) {
+ let best = Infinity
+ for (let i = 0; i < p.length; i++)
+ for (let j = 0; j < q.length; j++) best = Math.min(best, segSegDist(p[i], p[(i + 1) % p.length], q[j], q[(j + 1) % q.length]))
+ return best
+}
+
+export function computeSewer(plan: Plan): SewerCalc {
+ const s = sewerOf(plan)
+ const floorLevel = s.floorLevel ?? DEFAULT_FLOOR_LEVEL
+ const warnings: SewerWarning[] = []
+ const items = new Map<string, SewerItem>()
+ const add = (it: Omit<SewerItem, 'qty'>, qty: number) => {
+ if (qty <= 0) return
+ const cur = items.get(it.key)
+ items.set(it.key, { ...it, qty: (cur?.qty ?? 0) + qty })
+ }
+ const outSuffix = (loc: SewerPipe['location']) => (loc === 'outside' ? { key: '-out', out: true, location: loc } : { key: '', out: false, location: loc })
+ const elbow = (d: number, angle: 45 | 87, qty = 1, loc: SewerPipe['location'] = 'inside') => {
+ const o = outSuffix(loc)
+ add({ key: `elbow-${d}-${angle}${o.key}`, kind: 'elbow', name: t(o.out ? 'networks:sewer.item.elbowOut' : 'networks:sewer.item.elbow', { angle, d }), unit: 'pcs', diameter: d, angle, location: o.location }, qty)
+ }
+
+ const inc = new Map<string, SewerPipe[]>()
+ const out = new Map<string, SewerPipe[]>()
+ for (const n of s.nodes) {
+ inc.set(n.id, [])
+ out.set(n.id, [])
+ }
+ for (const p of s.pipes) {
+ inc.get(p.to)?.push(p)
+ out.get(p.from)?.push(p)
+ }
+
+ const nodeLevel: Record<string, number> = {}
+ const pipeLevel: Record<string, PipeLevel> = {}
+ const indeg = new Map(s.nodes.map((n) => [n.id, inc.get(n.id)!.length]))
+ const queue = s.nodes.filter((n) => indeg.get(n.id) === 0).map((n) => n.id)
+ const done = new Set<string>()
+ while (queue.length) {
+ const id = queue.shift()!
+ done.add(id)
+ const incoming = inc.get(id)!
+ nodeLevel[id] = incoming.length ? Math.min(...incoming.map((p) => pipeLevel[p.id]?.end ?? floorLevel)) : floorLevel
+ const node = s.nodes.find((n) => n.id === id)
+ if (node?.kind === 'septic' && node.depth !== undefined && !incoming.length) nodeLevel[id] = -node.depth
+ for (const p of out.get(id)!) {
+ const length = pipeLength(s, p)
+ const slope = pipeSlope(p)
+ let start = nodeLevel[id]
+ if (p.depth !== undefined) start = -p.depth
+ else if (p.location === 'outside') start = Math.min(start, -MIN_OUTSIDE_DEPTH)
+ const vertical = Math.max(0, nodeLevel[id] - start)
+ const drop = (length * slope) / 100
+ pipeLevel[p.id] = { start, end: start - drop, drop, length, slope, vertical }
+ const k = (indeg.get(p.to) ?? 1) - 1
+ indeg.set(p.to, k)
+ if (k === 0) queue.push(p.to)
+ }
+ }
+ if (done.size < s.nodes.length) warnings.push({ text: t('networks:sewer.warn.loop') })
+
+ const lengthMap = new Map<string, { diameter: number; location: SewerPipe['location']; lengthMm: number }>()
+ const addLength = (d: number, location: SewerPipe['location'], mm: number) => {
+ const key = `${d}-${location}`
+ const cur = lengthMap.get(key) ?? { diameter: d, location, lengthMm: 0 }
+ cur.lengthMm += mm
+ lengthMap.set(key, cur)
+ }
+
+ for (const p of s.pipes) {
+ const lv = pipeLevel[p.id]
+ const length = lv?.length ?? pipeLength(s, p)
+ addLength(p.diameter, p.location, length)
+ if (lv?.vertical && lv.vertical > 50) {
+ addLength(p.diameter, 'inside', lv.vertical)
+ elbow(p.diameter, 87)
+ elbow(p.diameter, 45, 2)
+ add({ key: `clamp-${p.diameter}`, kind: 'clamp', name: t('networks:sewer.item.clamp', { d: p.diameter }), unit: 'pcs', diameter: p.diameter }, Math.ceil(lv.vertical / 2000))
+ }
+ const min = minSlope(p.diameter, p.location)
+ const slope = pipeSlope(p)
+ if (slope + 1e-9 < min) {
+ warnings.push({ text: t('networks:sewer.warn.slopeLow', { id: p.id, slope: fmtPct(slope), min: fmtPct(min), d: p.diameter }), ref: { kind: 'pipe', id: p.id } })
+ }
+ if (p.location === 'inside') {
+ const step = p.diameter * 10
+ add({ key: `clamp-${p.diameter}`, kind: 'clamp', name: t('networks:sewer.item.clamp', { d: p.diameter }), unit: 'pcs', diameter: p.diameter }, Math.max(1, Math.ceil(length / step)))
+ }
+ if (p.location === 'outside' && lv && -lv.start < MIN_OUTSIDE_DEPTH - 1) {
+ warnings.push({ text: t('networks:sewer.warn.shallow', { id: p.id, depth: fmtM(-lv.start), min: fmtM(MIN_OUTSIDE_DEPTH) }), ref: { kind: 'pipe', id: p.id } })
+ }
+ const upstream = inc.get(p.from) ?? []
+ const bigger = upstream.find((u) => u.diameter > p.diameter)
+ if (bigger) warnings.push({ text: t('networks:sewer.warn.thinner', { id: p.id, d: p.diameter, up: bigger.diameter }), ref: { kind: 'pipe', id: p.id } })
+ }
+
+ const buildings = detectRooms(plan).buildings
+ const boundary = sitePolygon(plan.site)
+ const outlets: SewerCalc['outlets'] = []
+ const septics: SepticInfo[] = []
+
+ for (const n of s.nodes) {
+ const ins = inc.get(n.id)!
+ const outs = out.get(n.id)!
+ const main = outs.reduce<number>((m, p) => Math.max(m, p.diameter), 0) || ins.reduce<number>((m, p) => Math.max(m, p.diameter), 0)
+ const ref: SewerRef = { kind: 'node', id: n.id }
+ const loc: SewerPipe['location'] = (outs[0] ?? ins[0])?.location ?? 'inside'
+ const o = outSuffix(loc)
+ if (!main && n.kind !== 'septic') continue
+
+ if (n.kind === 'fixture') {
+ if (n.fixture === 'toilet') add({ key: 'corrugation-110', kind: 'corrugation', name: t('networks:sewer.item.corrugation'), unit: 'pcs', diameter: 110 }, 1)
+ else elbow(main, 87)
+ if (n.fixture === 'toilet' && outs.some((p) => p.diameter < 110)) {
+ warnings.push({ text: t('networks:sewer.warn.toiletPipe', { id: n.id }), ref })
+ }
+ }
+
+ if (n.kind === 'riser') {
+ const h = n.height ?? DEFAULT_RISER_HEIGHT
+ addLength(110, 'inside', h)
+ add({ key: 'cleanout-110', kind: 'cleanout', name: t('networks:sewer.item.cleanout', { d: 110 }), unit: 'pcs', diameter: 110 }, 1)
+ add({ key: 'vent-110', kind: 'vent', name: t('networks:sewer.item.vent'), unit: 'pcs', diameter: 110 }, 1)
+ add({ key: 'clamp-110', kind: 'clamp', name: t('networks:sewer.item.clamp', { d: 110 }), unit: 'pcs', diameter: 110 }, Math.ceil(h / 2000))
+ for (const p of ins) {
+ const key = p.diameter < 110 ? `tee-110x${p.diameter}-87` : 'tee-110-87'
+ add({ key, kind: 'tee', name: p.diameter < 110 ? t('networks:sewer.item.tee87Reduced', { branch: p.diameter }) : t('networks:sewer.item.tee87'), unit: 'pcs', diameter: 110, angle: 87 }, 1)
+ }
+ elbow(110, 45, 2)
+ if (outs.some((p) => p.diameter < 110)) warnings.push({ text: t('networks:sewer.warn.riserPipe', { id: n.id }), ref })
+ continue
+ }
+
+ if (n.kind === 'cleanout') add({ key: `cleanout-${main}${o.key}`, kind: 'cleanout', name: t(o.out ? 'networks:sewer.item.cleanoutOut' : 'networks:sewer.item.cleanout', { d: main }), unit: 'pcs', diameter: main, location: loc }, 1)
+ if (n.kind === 'outlet') {
+ add({ key: `sleeve-${main}`, kind: 'sleeve', name: t('networks:sewer.item.sleeve', { d: main }), unit: 'pcs', diameter: main }, 1)
+ const o = outs[0] && pipeLevel[outs[0].id]
+ if (o) outlets.push({ nodeId: n.id, depth: -o.start })
+ }
+
+ if (n.kind === 'septic') {
+ add({ key: 'septic', kind: 'septic', name: n.model ? t('networks:sewer.item.septicModel', { model: n.model }) : t('networks:sewer.item.septic'), unit: 'pcs', model: n.model }, 1)
+ const corners = septicCorners(n)
+ const toHouse = buildings.length ? Math.min(...buildings.map((b) => polyDist(corners, b.footprint))) : null
+ const toBoundary = boundary.length >= 3 ? polyDist(corners, boundary) : null
+ const level = ins.length ? nodeLevel[n.id] : n.depth !== undefined ? -n.depth : null
+ septics.push({ nodeId: n.id, model: n.model ?? '', depth: level === null || level === undefined ? null : -level, toHouse, toBoundary })
+ if (toHouse !== null && toHouse < SEPTIC_TO_HOUSE_MIN)
+ warnings.push({ text: t('networks:sewer.warn.septicHouse', { name: n.model ?? n.id, dist: fmtM(toHouse), min: fmtM(SEPTIC_TO_HOUSE_MIN) }), ref })
+ if (toBoundary !== null && toBoundary < SEPTIC_TO_BOUNDARY_MIN)
+ warnings.push({ text: t('networks:sewer.warn.septicBoundary', { name: n.model ?? n.id, dist: fmtM(toBoundary), min: fmtM(SEPTIC_TO_BOUNDARY_MIN) }), ref })
+ continue
+ }
+
+ const deg = ins.length + outs.length
+ if (deg >= 3) {
+ const branch = Math.min(...ins.map((p) => p.diameter), main)
+ const tees = deg - 2
+ const key = (branch < main ? `tee-${main}x${branch}-45` : `tee-${main}-45`) + o.key
+ add({ key, kind: 'tee', name: branch < main ? t(o.out ? 'networks:sewer.item.tee45ReducedOut' : 'networks:sewer.item.tee45Reduced', { main, branch }) : t(o.out ? 'networks:sewer.item.tee45Out' : 'networks:sewer.item.tee45', { d: main }), unit: 'pcs', diameter: main, angle: 45, location: loc }, tees)
+ continue
+ }
+ if (ins.length === 1 && outs.length === 1) {
+ const a = ins[0]
+ const b = outs[0]
+ if (a.diameter !== b.diameter) {
+ const big = Math.max(a.diameter, b.diameter)
+ const small = Math.min(a.diameter, b.diameter)
+ add({ key: `reducer-${big}x${small}`, kind: 'reducer', name: t('networks:sewer.item.reducer', { big, small }), unit: 'pcs', diameter: big }, 1)
+ }
+ const turn = turnDeg(s, a, b)
+ if (turn > 15 && turn <= 60) elbow(b.diameter, 45, 1, loc)
+ else if (turn > 60) {
+ elbow(b.diameter, 87, 1, loc)
+ if (turn > 100) elbow(b.diameter, 45, 1, loc)
+ if (n.kind !== 'cleanout')
+ warnings.push({ text: t('networks:sewer.warn.sharpTurn', { id: n.id, deg: Math.round(turn) }), ref })
+ }
+ }
+ if (ins.length && !outs.length && n.kind !== 'outlet') {
+ warnings.push({ text: t('networks:sewer.warn.deadEnd', { id: n.id }), ref })
+ }
+ }
+
+ const fixtures = s.nodes.filter((n) => n.kind === 'fixture' && !(out.get(n.id) ?? []).length)
+ for (const f of fixtures) warnings.push({ text: t('networks:shared.warn.notConnected', { name: f.fixture ? fixtureLabels[f.fixture] : f.id }), ref: { kind: 'node', id: f.id } })
+
+ for (const l of lengthMap.values()) {
+ const m = Math.ceil(l.lengthMm / 100) / 10
+ add({ key: `pipe-${l.diameter}-${l.location}`, kind: 'pipe', name: pipeName(l.diameter, l.location), unit: 'm', diameter: l.diameter, lengthMm: l.lengthMm, location: l.location }, m)
+ }
+
+ const order: SewerItemKind[] = ['septic', 'pipe', 'elbow', 'tee', 'reducer', 'cleanout', 'sleeve', 'corrugation', 'vent', 'clamp']
+ const list = [...items.values()].sort(
+ (a, b) => order.indexOf(a.kind) - order.indexOf(b.kind) || (b.diameter ?? 0) - (a.diameter ?? 0) || a.key.localeCompare(b.key),
+ )
+
+ return {
+ lengths: [...lengthMap.values()].sort((a, b) => b.diameter - a.diameter || a.location.localeCompare(b.location)),
+ items: list,
+ nodeLevel,
+ pipeLevel,
+ outlets,
+ septics,
+ warnings,
+ floorLevel,
+ }
+}
+
diff --git a/src/networks/sewerEdit.tsx b/src/networks/sewerEdit.tsx
new file mode 100644
index 0000000..be90838
--- /dev/null
+++ b/src/networks/sewerEdit.tsx
@@ -0,0 +1,71 @@
+import { useTranslation } from 'react-i18next'
+import { Segmented } from '../ui'
+import { registerNetworkLayer } from './registry'
+import { useSewerUi, type NextKind } from './sewerStore'
+
+type Mode = 'select' | NextKind
+
+const MODE_KEYS: Exclude<Mode, 'select'>[] = ['junction', 'cleanout', 'riser', 'outlet', 'septic']
+const EDIT_KEY: Record<Exclude<Mode, 'select'>, string> = { junction: 'trace', cleanout: 'cleanout', riser: 'riser', outlet: 'outlet', septic: 'septic' }
+
+function SewerEditTools() {
+ const { t } = useTranslation('networks')
+ const modes: { value: Mode; label: string; title: string }[] = [
+ { value: 'select', label: t('shared.ui.modeSelect'), title: t('shared.ui.modeSelectTitle') },
+ ...MODE_KEYS.map((m) => ({ value: m, label: t(`sewer.edit.${EDIT_KEY[m]}`), title: t(`sewer.edit.${EDIT_KEY[m]}Title`) })),
+ ]
+ const tool = useSewerUi((s) => s.tool)
+ const nextKind = useSewerUi((s) => s.nextKind)
+ const mode: Mode = tool ? nextKind : 'select'
+ return (
+ <>
+ <Segmented
+ size="sm"
+ value={mode}
+ options={modes}
+ onChange={(m) => {
+ const ui = useSewerUi.getState()
+ if (m === 'select') ui.setTool(false)
+ else {
+ ui.setNextKind(m)
+ ui.setTool(true)
+ }
+ }}
+ />
+ <span className="muted net-editbar__hint">
+ {tool ? t('sewer.edit.hintTrace') : t('shared.ui.hintSelect')}
+ </span>
+ </>
+ )
+}
+
+registerNetworkLayer({
+ key: 'sewer',
+ Tools: SewerEditTools,
+ enter: () => {
+ const ui = useSewerUi.getState()
+ ui.select(null)
+ ui.setNextKind('junction')
+ ui.setTool(true)
+ ui.setPanel(true)
+ },
+ exit: () => {
+ const ui = useSewerUi.getState()
+ ui.setTool(false)
+ ui.setDraft(null)
+ ui.select(null)
+ ui.setHover(null)
+ },
+ onEscape: () => {
+ const ui = useSewerUi.getState()
+ if (ui.draft) {
+ ui.setDraft(null)
+ return true
+ }
+ if (ui.selected) {
+ ui.select(null)
+ return true
+ }
+ return false
+ },
+})
diff --git a/src/networks/sewerModel.ts b/src/networks/sewerModel.ts
new file mode 100644
index 0000000..1d54cfc
--- /dev/null
+++ b/src/networks/sewerModel.ts
@@ -0,0 +1,194 @@
+import { nextId, type Furniture, type Plan, type Point, type SewerDiameter, type SewerFixture, type SewerNetwork, type SewerNode, type SewerPipe } from '../model'
+import { resolveFurniture } from '../furniture/catalog'
+import { labelMap } from './labels'
+
+export type NewSewerNode = Pick<SewerNode, 'x' | 'y' | 'kind'> &
+ Partial<Pick<SewerNode, 'fixture' | 'label' | 'furnitureId' | 'height' | 'w' | 'd' | 'rotationDeg' | 'model' | 'depth'>>
+export type NewSewerPipe = Pick<SewerPipe, 'from' | 'to' | 'diameter' | 'location'> & Partial<Pick<SewerPipe, 'slope' | 'depth' | 'material'>>
+
+export const EMPTY_SEWER: SewerNetwork = { nodes: [], pipes: [] }
+
+export const DEFAULT_FLOOR_LEVEL = 600
+export const DEFAULT_RISER_HEIGHT = 3000
+export const MIN_OUTSIDE_DEPTH = 1000
+export const SEPTIC_TO_HOUSE_MIN = 5000
+export const SEPTIC_TO_BOUNDARY_MIN = 1000
+export const DEFAULT_SEPTIC = { w: 2500, d: 1100 }
+
+export const fixtureLabels: Record<SewerFixture, string> = labelMap<SewerFixture>(['toilet', 'sink', 'bath', 'shower', 'washer', 'kitchen', 'boiler'], 'networks:sewer.fixture')
+
+export const nodeKindLabels: Record<SewerNode['kind'], string> = labelMap<SewerNode['kind']>(['fixture', 'riser', 'cleanout', 'outlet', 'septic', 'junction'], 'networks:sewer.kind')
+
+export const FURNITURE_FIXTURE: Record<string, SewerFixture> = {
+ toilet: 'toilet',
+ washbasin: 'sink',
+ vanity: 'sink',
+ bathtub: 'bath',
+ shower: 'shower',
+ washer: 'washer',
+ 'kitchen-sink': 'kitchen',
+ dishwasher: 'kitchen',
+ 'water-heater': 'boiler',
+ 'gas-boiler': 'boiler',
+ 'floor-boiler': 'boiler',
+}
+
+export function minSlope(diameter: SewerDiameter, location: SewerPipe['location']) {
+ if (diameter === 50) return 2.5
+ if (diameter === 160) return 0.8
+ return location === 'outside' ? 1 : 1.2
+}
+
+export function defaultSlope(diameter: SewerDiameter, location: SewerPipe['location']) {
+ if (diameter === 50) return 3
+ if (location === 'outside') return diameter === 160 ? 0.8 : 1
+ return 2
+}
+
+export const pipeSlope = (p: SewerPipe) => p.slope ?? defaultSlope(p.diameter, p.location)
+
+export const sewerOf = (plan: Plan): SewerNetwork => plan.networks?.sewer ?? EMPTY_SEWER
+
+export const withSewer = (plan: Plan, fn: (s: SewerNetwork) => SewerNetwork): Plan => ({
+ ...plan,
+ networks: { ...plan.networks, sewer: fn(sewerOf(plan)) },
+})
+
+export const nodeById = (s: SewerNetwork, id: string) => s.nodes.find((n) => n.id === id)
+
+export const pipeEnds = (s: SewerNetwork, p: SewerPipe) => {
+ const a = nodeById(s, p.from)
+ const b = nodeById(s, p.to)
+ return a && b ? { a, b } : null
+}
+
+export const pipeLength = (s: SewerNetwork, p: SewerPipe) => {
+ const e = pipeEnds(s, p)
+ return e ? Math.hypot(e.b.x - e.a.x, e.b.y - e.a.y) : 0
+}
+
+export function fixtureOutlet(f: Furniture): Point {
+ const r = resolveFurniture(f)
+ const fixture = FURNITURE_FIXTURE[f.type]
+ const local = fixture === 'shower' ? { x: 0, y: 0 } : { x: 0, y: -r.d / 2 + Math.min(150, r.d / 4) }
+ const a = (f.rotationDeg * Math.PI) / 180
+ return {
+ x: Math.round(f.x + local.x * Math.cos(a) - local.y * Math.sin(a)),
+ y: Math.round(f.y + local.x * Math.sin(a) + local.y * Math.cos(a)),
+ }
+}
+
+export function addNode(plan: Plan, node: NewSewerNode): { plan: Plan; id: string } {
+ const s = sewerOf(plan)
+ const id = nextId('sn', s.nodes)
+ return { plan: withSewer(plan, (x) => ({ ...x, nodes: [...x.nodes, { ...node, id } as SewerNode] })), id }
+}
+
+export function addPipe(plan: Plan, pipe: NewSewerPipe): { plan: Plan; id: string } {
+ const s = sewerOf(plan)
+ const id = nextId('sp', s.pipes)
+ const next = withSewer(plan, (x) => ({ ...x, pipes: [...x.pipes, { ...pipe, id } as SewerPipe] }))
+ return { plan: upsizeDownstream(next, pipe.to, pipe.diameter), id }
+}
+
+export function upsizeDownstream(plan: Plan, fromNode: string, diameter: SewerDiameter): Plan {
+ let s = sewerOf(plan)
+ const seen = new Set<string>()
+ const queue = [fromNode]
+ while (queue.length) {
+ const n = queue.shift()!
+ if (seen.has(n)) continue
+ seen.add(n)
+ for (const p of s.pipes) {
+ if (p.from !== n) continue
+ if (p.diameter < diameter) {
+ const slope = p.slope === defaultSlope(p.diameter, p.location) ? defaultSlope(diameter, p.location) : p.slope
+ s = { ...s, pipes: s.pipes.map((q) => (q.id === p.id ? { ...q, diameter, slope } : q)) }
+ }
+ queue.push(p.to)
+ }
+ }
+ return withSewer(plan, () => s)
+}
+
+export function upstreamDiameter(s: SewerNetwork, nodeId: string): SewerDiameter | null {
+ const node = nodeById(s, nodeId)
+ if (node?.kind === 'fixture' && node.fixture === 'toilet') return 110
+ const incoming = s.pipes.filter((p) => p.to === nodeId)
+ if (!incoming.length) return null
+ return incoming.reduce<SewerDiameter>((m, p) => (p.diameter > m ? p.diameter : m), 50)
+}
+
+export const updateNode = (plan: Plan, id: string, patch: Partial<SewerNode>): Plan =>
+ withSewer(plan, (s) => ({ ...s, nodes: s.nodes.map((n) => (n.id === id ? ({ ...n, ...patch } as SewerNode) : n)) }))
+
+export const updatePipe = (plan: Plan, id: string, patch: Partial<SewerPipe>): Plan => {
+ const next = withSewer(plan, (s) => ({ ...s, pipes: s.pipes.map((p) => (p.id === id ? ({ ...p, ...patch } as SewerPipe) : p)) }))
+ const pipe = sewerOf(next).pipes.find((p) => p.id === id)
+ return pipe && patch.diameter ? upsizeDownstream(next, pipe.to, pipe.diameter) : next
+}
+
+export const reversePipe = (plan: Plan, id: string): Plan =>
+ withSewer(plan, (s) => ({ ...s, pipes: s.pipes.map((p) => (p.id === id ? { ...p, from: p.to, to: p.from } : p)) }))
+
+export const deletePipe = (plan: Plan, id: string): Plan =>
+ withSewer(plan, (s) => ({ ...s, pipes: s.pipes.filter((p) => p.id !== id) }))
+
+export function deleteNode(plan: Plan, id: string): Plan {
+ const s = sewerOf(plan)
+ const inc = s.pipes.filter((p) => p.to === id)
+ const out = s.pipes.filter((p) => p.from === id)
+ const node = nodeById(s, id)
+ if (node && node.kind !== 'fixture' && node.kind !== 'septic' && inc.length === 1 && out.length === 1 && inc[0].from !== out[0].to) {
+ const merged: SewerPipe = { ...out[0], from: inc[0].from, diameter: Math.max(inc[0].diameter, out[0].diameter) as SewerDiameter }
+ return withSewer(plan, (x) => ({
+ ...x,
+ nodes: x.nodes.filter((n) => n.id !== id),
+ pipes: x.pipes.filter((p) => p.id !== inc[0].id).map((p) => (p.id === out[0].id ? merged : p)),
+ }))
+ }
+ return withSewer(plan, (x) => ({
+ ...x,
+ nodes: x.nodes.filter((n) => n.id !== id),
+ pipes: x.pipes.filter((p) => p.from !== id && p.to !== id),
+ }))
+}
+
+export function splitPipe(plan: Plan, pipeId: string, at: Point): { plan: Plan; id: string } | null {
+ const s = sewerOf(plan)
+ const pipe = s.pipes.find((p) => p.id === pipeId)
+ if (!pipe) return null
+ const added = addNode(plan, { x: at.x, y: at.y, kind: 'junction' })
+ const s2 = sewerOf(added.plan)
+ const secondId = nextId('sp', s2.pipes)
+ const next = withSewer(added.plan, (x) => ({
+ ...x,
+ pipes: [
+ ...x.pipes.map((p) => (p.id === pipeId ? { ...p, to: added.id } : p)),
+ { ...pipe, id: secondId, from: added.id },
+ ],
+ }))
+ return { plan: next, id: added.id }
+}
+
+export const moveNode = (plan: Plan, id: string, to: Point): Plan => updateNode(plan, id, { x: Math.round(to.x), y: Math.round(to.y) })
+
+export function projectOnSegment(p: Point, a: Point, b: Point) {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const l2 = dx * dx + dy * dy
+ const t = l2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2)) : 0
+ const q = { x: a.x + dx * t, y: a.y + dy * t }
+ return { point: q, t, dist: Math.hypot(p.x - q.x, p.y - q.y) }
+}
+
+export function segmentIntersection(p1: Point, p2: Point, q1: Point, q2: Point): { point: Point; t: number } | null {
+ const r = { x: p2.x - p1.x, y: p2.y - p1.y }
+ const s = { x: q2.x - q1.x, y: q2.y - q1.y }
+ const den = r.x * s.y - r.y * s.x
+ if (Math.abs(den) < 1e-9) return null
+ const t = ((q1.x - p1.x) * s.y - (q1.y - p1.y) * s.x) / den
+ const u = ((q1.x - p1.x) * r.y - (q1.y - p1.y) * r.x) / den
+ if (t <= 1e-6 || t >= 1 - 1e-6 || u < 0 || u > 1) return null
+ return { point: { x: p1.x + r.x * t, y: p1.y + r.y * t }, t }
+}
diff --git a/src/networks/sewerSnap.ts b/src/networks/sewerSnap.ts
new file mode 100644
index 0000000..9bc8bcb
--- /dev/null
+++ b/src/networks/sewerSnap.ts
@@ -0,0 +1,114 @@
+import type { Furniture, Plan, Point, Wall } from '../model'
+import { resolveFurniture } from '../furniture/catalog'
+import { pointInPolygon } from '../stats/rooms'
+import { snapAngle } from '../canvas/snap'
+import { FURNITURE_FIXTURE, fixtureOutlet, projectOnSegment, segmentIntersection, sewerOf } from './sewerModel'
+
+export type SewerTarget =
+ | { kind: 'node'; id: string; point: Point }
+ | { kind: 'fixture'; furniture: Furniture; point: Point }
+ | { kind: 'pipe'; id: string; point: Point }
+ | { kind: 'point'; point: Point; wall?: boolean }
+
+const NODE_PX = 12
+const PIPE_PX = 8
+const AXIS_PX = 10
+const WALL_GAP = 80
+const GRID = 50
+
+function insideFurniture(f: Furniture, p: Point) {
+ const r = resolveFurniture(f)
+ const a = (-f.rotationDeg * Math.PI) / 180
+ const dx = p.x - f.x
+ const dy = p.y - f.y
+ const lx = dx * Math.cos(a) - dy * Math.sin(a)
+ const ly = dx * Math.sin(a) + dy * Math.cos(a)
+ return Math.abs(lx) <= r.w / 2 && Math.abs(ly) <= r.d / 2
+}
+
+function wallSnap(p: Point, walls: Wall[], scale: number): Point | null {
+ let best: { q: Point; d: number } | null = null
+ for (const w of walls) {
+ const pr = projectOnSegment(p, w.a, w.b)
+ const reach = w.thickness / 2 + Math.max(250, 14 / scale)
+ if (pr.dist > reach || pr.t <= 0 || pr.t >= 1) continue
+ if (best && pr.dist >= best.d) continue
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) || 1
+ const nx = -(w.b.y - w.a.y) / len
+ const ny = (w.b.x - w.a.x) / len
+ const side = (p.x - pr.point.x) * nx + (p.y - pr.point.y) * ny >= 0 ? 1 : -1
+ const off = w.thickness / 2 + WALL_GAP
+ best = { q: { x: Math.round(pr.point.x + nx * off * side), y: Math.round(pr.point.y + ny * off * side) }, d: pr.dist }
+ }
+ return best?.q ?? null
+}
+
+export type SnapNet = {
+ nodes: { id: string; x: number; y: number; kind: string; furnitureId?: string; w?: number; d?: number }[]
+ pipes: { id: string; from: string; to: string; diameter: number }[]
+}
+
+export function findTarget(plan: Plan, raw: Point, scale: number, from: Point | null, shift: boolean, skipNode?: string, net?: SnapNet): SewerTarget {
+ const s: SnapNet = net ?? sewerOf(plan)
+ const nodeR = NODE_PX / scale
+ let node: { id: string; point: Point; d: number } | null = null
+ for (const n of s.nodes) {
+ if (n.id === skipNode) continue
+ const d = Math.hypot(n.x - raw.x, n.y - raw.y)
+ const hit = n.kind === 'septic' ? d <= Math.max(nodeR, Math.min(n.w ?? 2500, n.d ?? 1100) / 2) : d <= nodeR
+ if (hit && (!node || d < node.d)) node = { id: n.id, point: { x: n.x, y: n.y }, d }
+ }
+ if (node) return { kind: 'node', id: node.id, point: node.point }
+
+ const fixtureAt = (near: boolean): SewerTarget | null => {
+ for (const f of plan.furniture) {
+ if (!FURNITURE_FIXTURE[f.type]) continue
+ const out = fixtureOutlet(f)
+ if (near ? Math.hypot(out.x - raw.x, out.y - raw.y) <= nodeR * 1.5 : insideFurniture(f, raw)) {
+ const existing = s.nodes.find((n) => n.furnitureId === f.id && n.id !== skipNode)
+ if (existing) return { kind: 'node', id: existing.id, point: { x: existing.x, y: existing.y } }
+ return { kind: 'fixture', furniture: f, point: out }
+ }
+ }
+ return null
+ }
+ const inFixture = fixtureAt(false)
+ if (inFixture) return inFixture
+
+ const pipeR = PIPE_PX / scale
+ for (const p of s.pipes) {
+ const a = s.nodes.find((n) => n.id === p.from)
+ const b = s.nodes.find((n) => n.id === p.to)
+ if (!a || !b || a.id === skipNode || b.id === skipNode) continue
+ const pr = projectOnSegment(raw, a, b)
+ if (pr.dist <= Math.max(pipeR, p.diameter / 2) && pr.t > 0.02 && pr.t < 0.98) {
+ return { kind: 'pipe', id: p.id, point: { x: Math.round(pr.point.x), y: Math.round(pr.point.y) } }
+ }
+ }
+
+ const nearFixture = fixtureAt(true)
+ if (nearFixture) return nearFixture
+
+ if (from && shift) return { kind: 'point', point: snapAngle(from, raw, GRID) }
+ const wall = wallSnap(raw, plan.walls, scale)
+ let pt = wall ?? { x: Math.round(raw.x / GRID) * GRID, y: Math.round(raw.y / GRID) * GRID }
+ if (from) {
+ const axis = AXIS_PX / scale
+ if (Math.abs(pt.x - from.x) <= axis) pt = { ...pt, x: from.x }
+ if (Math.abs(pt.y - from.y) <= axis) pt = { ...pt, y: from.y }
+ }
+ return { kind: 'point', point: pt, wall: !!wall }
+}
+
+export const insideAny = (p: Point, footprints: Point[][]) => footprints.some((poly) => pointInPolygon(p, poly))
+
+export function firstCrossing(a: Point, b: Point, footprints: Point[][]): Point | null {
+ let best: { point: Point; t: number } | null = null
+ for (const poly of footprints) {
+ for (let i = 0; i < poly.length; i++) {
+ const hit = segmentIntersection(a, b, poly[i], poly[(i + 1) % poly.length])
+ if (hit && (!best || hit.t < best.t)) best = hit
+ }
+ }
+ return best ? { x: Math.round(best.point.x), y: Math.round(best.point.y) } : null
+}
diff --git a/src/networks/sewerStore.ts b/src/networks/sewerStore.ts
new file mode 100644
index 0000000..457233f
--- /dev/null
+++ b/src/networks/sewerStore.ts
@@ -0,0 +1,35 @@
+import { create } from 'zustand'
+import type { SewerNode } from '../model'
+import type { SewerRef } from './sewerCalc'
+
+export type NextKind = Exclude<SewerNode['kind'], 'fixture'>
+
+type SewerUiState = {
+ tool: boolean
+ selected: SewerRef | null
+ hover: SewerRef | null
+ panel: boolean
+ draft: string | null
+ setDraft: (id: string | null) => void
+ nextKind: NextKind
+ setNextKind: (k: NextKind) => void
+ setTool: (on: boolean) => void
+ select: (ref: SewerRef | null) => void
+ setHover: (ref: SewerRef | null) => void
+ setPanel: (on: boolean) => void
+}
+
+export const useSewerUi = create<SewerUiState>()((set) => ({
+ tool: false,
+ selected: null,
+ hover: null,
+ panel: false,
+ draft: null,
+ setDraft: (draft) => set({ draft }),
+ nextKind: 'junction',
+ setNextKind: (nextKind) => set({ nextKind }),
+ setTool: (tool) => set({ tool }),
+ select: (selected) => set({ selected }),
+ setHover: (hover) => set({ hover }),
+ setPanel: (panel) => set({ panel }),
+}))
diff --git a/src/networks/sewerTrace.ts b/src/networks/sewerTrace.ts
new file mode 100644
index 0000000..0deaa6e
--- /dev/null
+++ b/src/networks/sewerTrace.ts
@@ -0,0 +1,60 @@
+import type { Plan, Point, SewerDiameter, SewerNode, SewerPipe } from '../model'
+import { firstCrossing, insideAny, type SewerTarget } from './sewerSnap'
+import { type NewSewerPipe, DEFAULT_SEPTIC, FURNITURE_FIXTURE, addNode, addPipe, defaultSlope, nodeById, sewerOf, splitPipe, upstreamDiameter } from './sewerModel'
+import type { NextKind } from './sewerStore'
+
+export type TraceStep = { plan: Plan; draft: string | null; last: string | null }
+
+function nodeFromTarget(plan: Plan, t: SewerTarget, nextKind: NextKind): { plan: Plan; id: string; end: boolean } {
+ if (t.kind === 'node') return { plan, id: t.id, end: true }
+ if (t.kind === 'pipe') {
+ const r = splitPipe(plan, t.id, t.point)
+ if (r) return { ...r, end: true }
+ }
+ if (t.kind === 'fixture') {
+ const r = addNode(plan, { x: t.point.x, y: t.point.y, kind: 'fixture', fixture: FURNITURE_FIXTURE[t.furniture.type], furnitureId: t.furniture.id })
+ return { ...r, end: true }
+ }
+ const extra: Partial<SewerNode> = nextKind === 'septic' ? { w: DEFAULT_SEPTIC.w, d: DEFAULT_SEPTIC.d, rotationDeg: 0 } : {}
+ const r = addNode(plan, { x: t.point.x, y: t.point.y, kind: nextKind, ...extra })
+ return { ...r, end: nextKind === 'septic' }
+}
+
+function pipeSpec(plan: Plan, fromId: string, toId: string, location: SewerPipe['location']): NewSewerPipe {
+ const s = sewerOf(plan)
+ const from = nodeById(s, fromId)
+ const to = nodeById(s, toId)
+ let d: SewerDiameter = upstreamDiameter(s, fromId) ?? 50
+ if (from?.kind === 'riser') d = 110
+ if ((location === 'outside' || to?.kind === 'septic' || to?.kind === 'riser') && d < 110) d = 110
+ return { from: fromId, to: toId, diameter: d, slope: defaultSlope(d, location), location }
+}
+
+export function connect(plan: Plan, fromId: string, toId: string, footprints: Point[][]): Plan {
+ const s = sewerOf(plan)
+ const a = nodeById(s, fromId)
+ const b = nodeById(s, toId)
+ if (!a || !b || a.id === b.id) return plan
+ const aIn = a.kind !== 'outlet' && insideAny(a, footprints)
+ const bIn = insideAny(b, footprints)
+ const downstreamOut = a.kind === 'outlet' || s.pipes.some((p) => p.to === a.id && p.location === 'outside')
+ if (aIn && !bIn) {
+ const c = firstCrossing(a, b, footprints)
+ if (c && Math.hypot(c.x - a.x, c.y - a.y) > 50 && Math.hypot(c.x - b.x, c.y - b.y) > 50) {
+ const o = addNode(plan, { x: c.x, y: c.y, kind: 'outlet' })
+ const p1 = addPipe(o.plan, pipeSpec(o.plan, fromId, o.id, 'inside'))
+ return addPipe(p1.plan, pipeSpec(p1.plan, o.id, toId, 'outside')).plan
+ }
+ }
+ const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
+ const location: SewerPipe['location'] = downstreamOut || (!insideAny(mid, footprints) && footprints.length > 0) ? 'outside' : 'inside'
+ return addPipe(plan, pipeSpec(plan, fromId, toId, location)).plan
+}
+
+export function traceClick(plan: Plan, draft: string | null, t: SewerTarget, nextKind: NextKind, footprints: Point[][]): TraceStep {
+ if (draft && t.kind === 'node' && t.id === draft) return { plan, draft: null, last: draft }
+ const r = nodeFromTarget(plan, t, draft ? nextKind : t.kind === 'point' ? nextKind : 'junction')
+ if (!draft) return { plan: r.plan, draft: r.id, last: r.id }
+ const next = connect(r.plan, draft, r.id, footprints)
+ return { plan: next, draft: r.end ? null : r.id, last: r.id }
+}
diff --git a/src/networks/waterCalc.ts b/src/networks/waterCalc.ts
new file mode 100644
index 0000000..a0def54
--- /dev/null
+++ b/src/networks/waterCalc.ts
@@ -0,0 +1,224 @@
+import type { Plan, Point, WaterPipe } from '../model'
+import { projectOnSegment, segmentIntersection, sewerOf } from './sewerModel'
+import { fixtureLabels } from './sewerModel'
+import {
+ FROST_DEPTH,
+ LINE_SHORT,
+ SOURCE_TO_SEPTIC_MIN,
+ SOURCE_TO_SEPTIC_PASSPORT_MIN,
+ WATER_TO_SEWER_MIN,
+ collectorLine,
+ pipeMaterial,
+ waterOf,
+ waterPipeLength,
+ wNode,
+} from './waterModel'
+import type { SewerRef, SewerWarning } from './sewerCalc'
+import { t } from '../i18n'
+import { fmtM, type ItemUnit } from './labels'
+
+export type WaterItemKind = 'pipe' | 'elbow' | 'tee' | 'socket' | 'reducer' | 'collector' | 'collector-out' | 'sleeve' | 'insulation' | 'heat-cable' | 'head' | 'tap' | 'adapter' | 'pump'
+
+export type WaterItem = {
+ key: string
+ kind: WaterItemKind
+ name: string
+ qty: number
+ unit: ItemUnit
+ diameter?: number
+ material?: string
+ model?: string
+ location?: WaterPipe['location']
+ lengthMm?: number
+}
+
+export type WaterCalc = {
+ lengths: { line: WaterPipe['line']; diameter: number; material: string; location: WaterPipe['location']; lengthMm: number }[]
+ items: WaterItem[]
+ warnings: SewerWarning[]
+}
+
+function segDist(a: Point, b: Point, c: Point, d: Point) {
+ if (segmentIntersection(a, b, c, d)) return 0
+ return Math.min(projectOnSegment(a, c, d).dist, projectOnSegment(b, c, d).dist, projectOnSegment(c, a, b).dist, projectOnSegment(d, a, b).dist)
+}
+
+export function computeWater(plan: Plan): WaterCalc {
+ const w = waterOf(plan)
+ const warnings: SewerWarning[] = []
+ const items = new Map<string, WaterItem>()
+ const add = (it: Omit<WaterItem, 'qty'>, qty: number) => {
+ if (qty <= 0) return
+ const cur = items.get(it.key)
+ items.set(it.key, { ...it, qty: (cur?.qty ?? 0) + qty })
+ }
+ const inc = new Map<string, WaterPipe[]>(w.nodes.map((n) => [n.id, []]))
+ const out = new Map<string, WaterPipe[]>(w.nodes.map((n) => [n.id, []]))
+ for (const p of w.pipes) {
+ inc.get(p.to)?.push(p)
+ out.get(p.from)?.push(p)
+ }
+ const ends = (p: WaterPipe) => {
+ const a = wNode(w, p.from)
+ const b = wNode(w, p.to)
+ return a && b ? { a, b } : null
+ }
+
+ const lengths = new Map<string, WaterCalc['lengths'][number]>()
+ for (const p of w.pipes) {
+ const len = waterPipeLength(w, p)
+ const mat = pipeMaterial(p)
+ const key = `${p.line}-${p.diameter}-${mat}-${p.location}`
+ const cur = lengths.get(key) ?? { line: p.line, diameter: p.diameter, material: mat, location: p.location, lengthMm: 0 }
+ cur.lengthMm += len
+ lengths.set(key, cur)
+ const ref: SewerRef = { kind: 'pipe', id: p.id }
+ if (p.line === 'hot' || p.line === 'recirc' || p.location === 'outside') {
+ const it = items.get(`insul-${p.diameter}`) ?? { key: `insul-${p.diameter}`, kind: 'insulation' as const, name: t('networks:water.item.insulation', { d: p.diameter }), unit: 'm' as const, diameter: p.diameter, qty: 0, lengthMm: 0 }
+ items.set(it.key, { ...it, lengthMm: (it.lengthMm ?? 0) + len })
+ }
+ if (p.location === 'outside') {
+ if (p.heated) add({ key: 'heat-cable', kind: 'heat-cable', name: t('networks:water.item.heatCable'), unit: 'm' }, Math.ceil(len / 100) / 10)
+ if (!p.heated && (p.depth === undefined || p.depth < FROST_DEPTH))
+ warnings.push({
+ text:
+ p.depth === undefined
+ ? t('networks:water.warn.frostNoDepth', { id: p.id, frost: fmtM(FROST_DEPTH) })
+ : t('networks:water.warn.frostShallow', { id: p.id, depth: fmtM(p.depth), frost: fmtM(FROST_DEPTH) }),
+ ref,
+ })
+ }
+ const e = ends(p)
+ if (e && p.location === 'inside') {
+ const crossings = plan.walls.filter((wl) => segmentIntersection(e.a, e.b, wl.a, wl.b)).length
+ add({ key: `sleeve-${p.diameter}`, kind: 'sleeve', name: t('networks:water.item.sleeve', { d: p.diameter }), unit: 'pcs', diameter: p.diameter }, crossings)
+ }
+ }
+ for (const it of items.values()) if (it.kind === 'insulation') items.set(it.key, { ...it, qty: Math.ceil((it.lengthMm ?? 0) / 100) / 10 })
+ for (const l of lengths.values()) {
+ const key = `pipe-${l.diameter}-${l.material}-${l.location}`
+ const name = t(l.location === 'outside' ? 'networks:water.item.pipeOut' : 'networks:water.item.pipe', { material: l.material, d: l.diameter })
+ const cur = items.get(key)
+ items.set(key, {
+ key,
+ kind: 'pipe',
+ name,
+ unit: 'm',
+ diameter: l.diameter,
+ material: l.material,
+ location: l.location,
+ lengthMm: (cur?.lengthMm ?? 0) + l.lengthMm,
+ qty: Math.ceil(((cur?.lengthMm ?? 0) + l.lengthMm) / 100) / 10,
+ })
+ }
+
+ const sewer = sewerOf(plan)
+ const sewerSegs = sewer.pipes
+ .map((p) => {
+ const a = sewer.nodes.find((n) => n.id === p.from)
+ const b = sewer.nodes.find((n) => n.id === p.to)
+ return a && b ? { a, b, outside: p.location === 'outside' } : null
+ })
+ .filter(Boolean) as { a: Point; b: Point; outside: boolean }[]
+ for (const p of w.pipes) {
+ if (p.location !== 'outside') continue
+ const e = ends(p)
+ if (!e) continue
+ const d = Math.min(Infinity, ...sewerSegs.filter((s) => s.outside).map((s) => segDist(e.a, e.b, s.a, s.b)))
+ if (d < WATER_TO_SEWER_MIN)
+ warnings.push({ text: t('networks:water.warn.toSewer', { id: p.id, dist: fmtM(d), min: fmtM(WATER_TO_SEWER_MIN) }), ref: { kind: 'pipe', id: p.id } })
+ }
+
+ const septics = sewer.nodes.filter((n) => n.kind === 'septic')
+ for (const n of w.nodes) {
+ const ins = inc.get(n.id)!
+ const outs = out.get(n.id)!
+ const all = [...ins, ...outs]
+ const d = all.reduce((m, p) => Math.max(m, p.diameter), 0)
+ const ref: SewerRef = { kind: 'node', id: n.id }
+ if (n.kind === 'source') {
+ if (n.source !== 'well') add({ key: 'head', kind: 'head', name: t('networks:water.item.head'), unit: 'pcs' }, 1)
+ for (const s of septics) {
+ const dist = Math.hypot(s.x - n.x, s.y - n.y)
+ const what = t(n.source === 'well' ? 'networks:water.source.well' : 'networks:water.source.borehole')
+ if (dist < SOURCE_TO_SEPTIC_PASSPORT_MIN)
+ warnings.push({ text: t('networks:water.warn.sourcePassport', { what, dist: fmtM(dist), min: fmtM(SOURCE_TO_SEPTIC_PASSPORT_MIN) }), ref })
+ else if (dist < SOURCE_TO_SEPTIC_MIN)
+ warnings.push({ text: t('networks:water.warn.sourceSanpin', { what, dist: fmtM(dist), min: fmtM(SOURCE_TO_SEPTIC_MIN), passport: fmtM(SOURCE_TO_SEPTIC_PASSPORT_MIN) }), ref })
+ }
+ continue
+ }
+ if (n.kind === 'tap_outdoor') {
+ add({ key: 'tap-outdoor', kind: 'tap', name: t('networks:water.item.tap'), unit: 'pcs' }, 1)
+ continue
+ }
+ if (n.kind === 'fixture') {
+ for (const p of ins) add({ key: `socket-${p.diameter}`, kind: 'socket', name: t('networks:water.item.socket', { d: p.diameter }), unit: 'pcs', diameter: p.diameter }, 1)
+ const name = n.fixture ? fixtureLabels[n.fixture] : n.id
+ if (!ins.some((p) => p.line === 'cold')) warnings.push({ text: t('networks:water.warn.noCold', { name }), ref })
+ for (const p of ins) {
+ let cur = wNode(w, p.from)
+ let guard = 0
+ while (cur && cur.kind === 'junction' && guard++ < 50) {
+ if ((out.get(cur.id) ?? []).length > 1) {
+ warnings.push({ text: t('networks:water.warn.viaTee', { name, line: LINE_SHORT[p.line] }), ref })
+ break
+ }
+ cur = wNode(w, (inc.get(cur.id) ?? [])[0]?.from ?? '')
+ }
+ if (cur && cur.kind !== 'collector' && cur.kind !== 'junction' && p.line !== 'recirc')
+ warnings.push({ text: t('networks:water.warn.notFromCollector', { name, line: LINE_SHORT[p.line] }), ref })
+ }
+ continue
+ }
+ if (n.kind === 'collector') {
+ const used = outs.length
+ const size = Math.max(n.outputs ?? used, used, 2)
+ add({ key: `collector-${size}`, kind: 'collector', name: t('networks:water.item.collector', { count: size }), unit: 'pcs' }, 1)
+ for (const p of outs) add({ key: `collector-out-${p.diameter}`, kind: 'collector-out', name: t('networks:water.item.collectorOut', { d: p.diameter }), unit: 'pcs', diameter: p.diameter }, 1)
+ if (n.outputs && used > n.outputs) warnings.push({ text: t('networks:water.warn.collectorFull', { line: LINE_SHORT[collectorLine(n) === 'hot' ? 'hot' : 'cold'], used, outputs: n.outputs }), ref })
+ continue
+ }
+ if (n.kind === 'pump') add({ key: 'pump', kind: 'pump', name: n.model ? t('networks:water.item.pumpModel', { model: n.model }) : t('networks:water.item.pump'), unit: 'pcs', model: n.model }, 1)
+ if (n.kind === 'pump' || n.kind === 'filter' || n.kind === 'boiler') {
+ add({ key: `adapter-${d || 20}`, kind: 'adapter', name: t('networks:water.item.adapter', { d: d || 20 }), unit: 'pcs', diameter: d || 20 }, all.length)
+ continue
+ }
+ if (n.kind === 'entry') add({ key: `sleeve-${d || 32}`, kind: 'sleeve', name: t('networks:water.item.sleeve', { d: d || 32 }), unit: 'pcs', diameter: d || 32 }, 1)
+ const byLine = new Map<string, WaterPipe[]>()
+ for (const p of all) byLine.set(p.line, [...(byLine.get(p.line) ?? []), p])
+ for (const group of byLine.values()) {
+ if (group.length >= 3) {
+ add({ key: `tee-${d}`, kind: 'tee', name: t('networks:water.item.tee', { d }), unit: 'pcs', diameter: d }, group.length - 2)
+ continue
+ }
+ if (group.length !== 2) continue
+ const [a, b] = [group.find((p) => p.to === n.id), group.find((p) => p.from === n.id)]
+ if (!a || !b) continue
+ if (a.diameter !== b.diameter) {
+ const big = Math.max(a.diameter, b.diameter)
+ const small = Math.min(a.diameter, b.diameter)
+ add({ key: `reducer-${big}x${small}`, kind: 'reducer', name: t('networks:water.item.reducer', { big, small }), unit: 'pcs', diameter: big }, 1)
+ }
+ const pa = wNode(w, a.from)
+ const pb = wNode(w, b.to)
+ if (!pa || !pb) continue
+ const u = { x: n.x - pa.x, y: n.y - pa.y }
+ const v = { x: pb.x - n.x, y: pb.y - n.y }
+ const cos = (u.x * v.x + u.y * v.y) / ((Math.hypot(u.x, u.y) || 1) * (Math.hypot(v.x, v.y) || 1))
+ if (Math.acos(Math.max(-1, Math.min(1, cos))) > (15 * Math.PI) / 180)
+ add({ key: `elbow-${b.diameter}`, kind: 'elbow', name: t('networks:water.item.elbow', { d: b.diameter }), unit: 'pcs', diameter: b.diameter }, 1)
+ }
+ }
+
+ const unconnected = w.nodes.filter((n) => n.kind === 'fixture' && !(inc.get(n.id) ?? []).length)
+ for (const n of unconnected) warnings.push({ text: t('networks:shared.warn.notConnected', { name: n.fixture ? fixtureLabels[n.fixture] : n.id }), ref: { kind: 'node', id: n.id } })
+
+ const order: WaterItemKind[] = ['head', 'pump', 'pipe', 'collector', 'collector-out', 'socket', 'elbow', 'tee', 'reducer', 'adapter', 'sleeve', 'insulation', 'heat-cable', 'tap']
+ return {
+ lengths: [...lengths.values()].sort((a, b) => a.line.localeCompare(b.line) || b.diameter - a.diameter),
+ items: [...items.values()].filter((i) => i.qty > 0).sort((a, b) => order.indexOf(a.kind) - order.indexOf(b.kind) || (b.diameter ?? 0) - (a.diameter ?? 0)),
+ warnings,
+ }
+}
+
diff --git a/src/networks/waterEdit.tsx b/src/networks/waterEdit.tsx
new file mode 100644
index 0000000..a8eaf53
--- /dev/null
+++ b/src/networks/waterEdit.tsx
@@ -0,0 +1,66 @@
+import { useTranslation } from 'react-i18next'
+import { Segmented } from '../ui'
+import { registerNetworkLayer } from './registry'
+import { useWaterUi, type WaterMode, type WaterNextKind } from './waterStore'
+import { waterKindLabels } from './waterModel'
+
+const LINE_MODES = ['cold', 'hot', 'recirc'] as const
+
+const NEXT: WaterNextKind[] = ['junction', 'source', 'entry', 'pump', 'filter', 'boiler', 'collector', 'tap_outdoor']
+
+function WaterEditTools() {
+ const { t } = useTranslation('networks')
+ const modes: { value: WaterMode; label: string; title: string }[] = [
+ { value: 'select', label: t('shared.ui.modeSelect'), title: t('shared.ui.modeSelectTitle') },
+ ...LINE_MODES.map((m) => ({ value: m, label: t(`water.edit.${m}`), title: t(`water.edit.${m}Title`) })),
+ ]
+ const mode = useWaterUi((s) => s.mode)
+ const nextKind = useWaterUi((s) => s.nextKind)
+ return (
+ <>
+ <Segmented size="sm" value={mode} options={modes} onChange={(m) => useWaterUi.getState().setMode(m)} />
+ {mode !== 'select' && (
+ <select className="select" value={nextKind} onChange={(e) => useWaterUi.getState().setNextKind(e.target.value as WaterNextKind)} title={t('water.edit.nextTitle')}>
+ {NEXT.map((k) => (
+ <option key={k} value={k}>
+ {waterKindLabels[k]}
+ </option>
+ ))}
+ </select>
+ )}
+ <span className="muted net-editbar__hint">
+ {mode === 'select' ? t('shared.ui.hintSelect') : t('water.edit.hintTrace')}
+ </span>
+ </>
+ )
+}
+
+registerNetworkLayer({
+ key: 'water',
+ Tools: WaterEditTools,
+ enter: () => {
+ const ui = useWaterUi.getState()
+ ui.select(null)
+ ui.setMode('cold')
+ ui.setPanel(true)
+ },
+ exit: () => {
+ const ui = useWaterUi.getState()
+ ui.setMode('select')
+ ui.setDraft(null)
+ ui.select(null)
+ ui.setHover(null)
+ },
+ onEscape: () => {
+ const ui = useWaterUi.getState()
+ if (ui.draft) {
+ ui.setDraft(null)
+ return true
+ }
+ if (ui.selected) {
+ ui.select(null)
+ return true
+ }
+ return false
+ },
+})
diff --git a/src/networks/waterModel.ts b/src/networks/waterModel.ts
new file mode 100644
index 0000000..d53b5e7
--- /dev/null
+++ b/src/networks/waterModel.ts
@@ -0,0 +1,98 @@
+import { nextId, type Plan, type Point, type WaterDiameter, type WaterLine, type WaterNetwork, type WaterNode, type WaterPipe } from '../model'
+import { t } from '../i18n'
+import { fmtM, labelMap } from './labels'
+
+export type NewWaterNode = Pick<WaterNode, 'x' | 'y' | 'kind'> &
+ Partial<Pick<WaterNode, 'fixture' | 'furnitureId' | 'label' | 'model' | 'source' | 'line' | 'outputs' | 'rotationDeg'>>
+export type NewWaterPipe = Pick<WaterPipe, 'from' | 'to' | 'line' | 'diameter' | 'location'> & Partial<Pick<WaterPipe, 'material' | 'depth' | 'heated'>>
+
+export const EMPTY_WATER: WaterNetwork = { nodes: [], pipes: [] }
+
+export const FROST_DEPTH = 1500
+export const WATER_TO_SEWER_MIN = 1500
+export const SOURCE_TO_SEPTIC_MIN = 50000
+export const SOURCE_TO_SEPTIC_PASSPORT_MIN = 15000
+
+export const LINE_COLORS: Record<WaterLine, string> = { cold: '#2f6fd6', hot: '#d64545', recirc: '#d64545' }
+export const LINE_DARK: Record<WaterLine, string> = { cold: '#173f85', hot: '#8a2020', recirc: '#8a2020' }
+const LINES: WaterLine[] = ['cold', 'hot', 'recirc']
+export const LINE_SHORT: Record<WaterLine, string> = labelMap(LINES, 'networks:water.lineShort')
+export const LINE_LABELS: Record<WaterLine, string> = labelMap(LINES, 'networks:water.line')
+
+export const waterKindLabels: Record<WaterNode['kind'], string> = labelMap<WaterNode['kind']>(
+ ['source', 'entry', 'pump', 'filter', 'boiler', 'collector', 'fixture', 'junction', 'tap_outdoor'],
+ 'networks:water.kind',
+)
+
+export const DIAMETERS: WaterDiameter[] = [16, 20, 25, 32]
+
+export const waterOf = (plan: Plan): WaterNetwork => plan.networks?.water ?? EMPTY_WATER
+
+export const withWater = (plan: Plan, fn: (w: WaterNetwork) => WaterNetwork): Plan => ({
+ ...plan,
+ networks: { ...plan.networks, water: fn(waterOf(plan)) },
+})
+
+export const wNode = (w: WaterNetwork, id: string) => w.nodes.find((n) => n.id === id)
+
+export const waterPipeLength = (w: WaterNetwork, p: WaterPipe) => {
+ const a = wNode(w, p.from)
+ const b = wNode(w, p.to)
+ return a && b ? Math.hypot(b.x - a.x, b.y - a.y) : 0
+}
+
+export const pipeMaterial = (p: WaterPipe) => p.material ?? (p.location === 'outside' ? 'PE' : 'PEX')
+
+export const waterCaption = (p: WaterPipe) =>
+ `${LINE_SHORT[p.line]} Ø${p.diameter} ${pipeMaterial(p)}${p.location === 'outside' ? ` · ${t('networks:shared.ui.outsideLower')}${p.depth !== undefined ? ` · ${t('networks:water.caption.depth', { depth: fmtM(p.depth) })}` : ''}` : ''}`
+
+export function addWaterNode(plan: Plan, node: NewWaterNode): { plan: Plan; id: string } {
+ const id = nextId('wn', waterOf(plan).nodes)
+ return { plan: withWater(plan, (w) => ({ ...w, nodes: [...w.nodes, { ...node, id } as WaterNode] })), id }
+}
+
+export function addWaterPipe(plan: Plan, pipe: NewWaterPipe): { plan: Plan; id: string } {
+ const id = nextId('wp', waterOf(plan).pipes)
+ return { plan: withWater(plan, (w) => ({ ...w, pipes: [...w.pipes, { ...pipe, id } as WaterPipe] })), id }
+}
+
+export const updateWaterNode = (plan: Plan, id: string, patch: Partial<WaterNode>): Plan =>
+ withWater(plan, (w) => ({ ...w, nodes: w.nodes.map((n) => (n.id === id ? ({ ...n, ...patch } as WaterNode) : n)) }))
+
+export const updateWaterPipe = (plan: Plan, id: string, patch: Partial<WaterPipe>): Plan =>
+ withWater(plan, (w) => ({ ...w, pipes: w.pipes.map((p) => (p.id === id ? ({ ...p, ...patch } as WaterPipe) : p)) }))
+
+export const deleteWaterPipe = (plan: Plan, id: string): Plan => withWater(plan, (w) => ({ ...w, pipes: w.pipes.filter((p) => p.id !== id) }))
+
+export function deleteWaterNode(plan: Plan, id: string): Plan {
+ const w = waterOf(plan)
+ const inc = w.pipes.filter((p) => p.to === id)
+ const out = w.pipes.filter((p) => p.from === id)
+ const node = wNode(w, id)
+ if (node?.kind === 'junction' && inc.length === 1 && out.length === 1 && inc[0].from !== out[0].to) {
+ return withWater(plan, (x) => ({
+ ...x,
+ nodes: x.nodes.filter((n) => n.id !== id),
+ pipes: x.pipes.filter((p) => p.id !== inc[0].id).map((p) => (p.id === out[0].id ? { ...p, from: inc[0].from } : p)),
+ }))
+ }
+ return withWater(plan, (x) => ({ ...x, nodes: x.nodes.filter((n) => n.id !== id), pipes: x.pipes.filter((p) => p.from !== id && p.to !== id) }))
+}
+
+export function splitWaterPipe(plan: Plan, pipeId: string, at: Point): { plan: Plan; id: string } | null {
+ const pipe = waterOf(plan).pipes.find((p) => p.id === pipeId)
+ if (!pipe) return null
+ const added = addWaterNode(plan, { x: at.x, y: at.y, kind: 'junction' })
+ const secondId = nextId('wp', waterOf(added.plan).pipes)
+ return {
+ plan: withWater(added.plan, (x) => ({
+ ...x,
+ pipes: [...x.pipes.map((p) => (p.id === pipeId ? { ...p, to: added.id } : p)), { ...pipe, id: secondId, from: added.id }],
+ })),
+ id: added.id,
+ }
+}
+
+export const moveWaterNode = (plan: Plan, id: string, to: Point): Plan => updateWaterNode(plan, id, { x: Math.round(to.x), y: Math.round(to.y) })
+
+export const collectorLine = (n: WaterNode): WaterLine => n.line ?? 'cold'
diff --git a/src/networks/waterPricing.ts b/src/networks/waterPricing.ts
new file mode 100644
index 0000000..ce2328a
--- /dev/null
+++ b/src/networks/waterPricing.ts
@@ -0,0 +1,69 @@
+import type { NetworkMaterial } from '../model'
+import type { CatalogItem } from '../estimate/catalog'
+import type { WaterItem } from './waterCalc'
+import { t } from '../i18n'
+import { unitLabel } from './labels'
+
+export type PricedWaterItem = WaterItem & { buyQty: number; buyUnit: string; price?: number; url?: string; priceFrom?: string }
+
+type Loose = CatalogItem & { diameter?: number; material?: string }
+
+const perMeter = (c: CatalogItem) => (c.length ? c.price / (c.length / 1000) : c.price)
+
+const outputsOf = (c: CatalogItem) => Number(c.id.match(/^water-collector-(\d+)(?:-|$)/)?.[1] ?? 0)
+
+function findCatalog(item: WaterItem, catalog: CatalogItem[]): CatalogItem | undefined {
+ const water = catalog.filter((c) => c.kind === 'water') as Loose[]
+ const sameKind = (c: Loose) => (c.subtype ? c.subtype === item.kind : c.id.startsWith(`water-${item.kind}-`))
+ if (item.kind === 'collector') {
+ const need = Number(item.key.match(/^collector-(\d+)/)?.[1] ?? 0)
+ const list = water.filter((c) => c.subtype === 'collector' && outputsOf(c) >= need)
+ const plain = (c: CatalogItem) => Number(c.id !== `water-collector-${outputsOf(c)}`)
+ return list.sort((a, b) => outputsOf(a) - outputsOf(b) || plain(a) - plain(b) || a.price - b.price)[0]
+ }
+ if (item.kind === 'pump' && item.model) {
+ const words = item.model.toLowerCase().split(/[\s/,]+/).filter((w) => w.length > 2)
+ const byModel = water.find((c) => c.subtype === 'pump' && words.length > 0 && words.every((w) => c.name.toLowerCase().includes(w)))
+ if (byModel) return byModel
+ }
+ const exact = water.find((c) => (c.id === `water-${item.key}` || c.id === item.key) && (item.kind === 'head' || sameKind(c)))
+ if (exact) return exact
+ const fit = (c: Loose) =>
+ sameKind(c) &&
+ (item.diameter === undefined || c.diameter === undefined || c.diameter === null || c.diameter === item.diameter) &&
+ (!item.material || !c.material || c.material.toUpperCase() === item.material.toUpperCase()) &&
+ (item.kind !== 'pipe' || !item.location || !c.id.includes(item.location === 'outside' ? '-in-' : '-out-'))
+ const list = water.filter(fit)
+ if (!list.length) return water.find((c) => c.name === item.name)
+ return item.kind === 'pipe' ? [...list].sort((a, b) => perMeter(a) - perMeter(b))[0] : [...list].sort((a, b) => a.price - b.price)[0]
+}
+
+export function priceWaterItem(item: WaterItem, materials: NetworkMaterial[], catalog: CatalogItem[]): PricedWaterItem {
+ const base: PricedWaterItem = { ...item, buyQty: item.qty, buyUnit: unitLabel(item.unit) }
+ const m = materials.find((x) => x.id === item.key) ?? materials.find((x) => x.kind === item.kind && (item.diameter === undefined || x.diameter === item.diameter))
+ if (m) {
+ const res = { ...base, url: m.url, priceFrom: t('networks:shared.pricing.fromMaterials', { name: m.name }) }
+ if (m.price === undefined) return res
+ if (item.lengthMm !== undefined && m.pricePer !== 'm' && m.length) return { ...res, buyQty: Math.ceil(item.lengthMm / m.length), buyUnit: unitLabel('pcs'), price: m.price }
+ return { ...res, price: m.price }
+ }
+ const c = findCatalog(item, catalog)
+ if (!c) return base
+ const res = { ...base, url: c.url, priceFrom: t('networks:shared.pricing.fromCatalog', { name: `${c.name}${c.vendor ? `, ${c.vendor}` : ''}` }), price: c.price }
+ const perM = /^(м|пог\. ?м|м\.п\.)$/.test(c.unit.trim())
+ if (item.lengthMm !== undefined && !perM && c.length) return { ...res, buyQty: Math.ceil(item.lengthMm / c.length), buyUnit: c.unit }
+ if (item.lengthMm !== undefined && !perM && /бухт|рулон/i.test(c.unit)) return { ...res, buyQty: 1, buyUnit: c.unit }
+ return res
+}
+
+export function priceWater(items: WaterItem[], materials: NetworkMaterial[] | undefined, catalog: CatalogItem[]): PricedWaterItem[] {
+ const priced = items.map((i) => priceWaterItem(i, materials ?? [], catalog))
+ const head = priced.find((i) => i.kind === 'head' && i.price !== undefined)
+ const packaged = head && /насос/i.test(head.priceFrom ?? '')
+ if (!packaged) return priced
+ return priced.map((i) =>
+ i.kind === 'pump' ? { ...i, price: 0, url: undefined, priceFrom: t('networks:shared.pricing.includedInBorehole') } : i,
+ )
+}
+
+export const waterSum = (i: PricedWaterItem) => (i.price ?? 0) * i.buyQty
diff --git a/src/networks/waterStore.ts b/src/networks/waterStore.ts
new file mode 100644
index 0000000..eab7d4b
--- /dev/null
+++ b/src/networks/waterStore.ts
@@ -0,0 +1,36 @@
+import { create } from 'zustand'
+import type { WaterLine, WaterNode } from '../model'
+import type { SewerRef } from './sewerCalc'
+
+export type WaterMode = 'select' | WaterLine
+export type WaterNextKind = Exclude<WaterNode['kind'], 'fixture'>
+
+type WaterUiState = {
+ mode: WaterMode
+ nextKind: WaterNextKind
+ draft: string | null
+ selected: SewerRef | null
+ hover: SewerRef | null
+ panel: boolean
+ setMode: (m: WaterMode) => void
+ setNextKind: (k: WaterNextKind) => void
+ setDraft: (id: string | null) => void
+ select: (r: SewerRef | null) => void
+ setHover: (r: SewerRef | null) => void
+ setPanel: (on: boolean) => void
+}
+
+export const useWaterUi = create<WaterUiState>()((set) => ({
+ mode: 'select',
+ nextKind: 'junction',
+ draft: null,
+ selected: null,
+ hover: null,
+ panel: false,
+ setMode: (mode) => set({ mode, draft: null }),
+ setNextKind: (nextKind) => set({ nextKind }),
+ setDraft: (draft) => set({ draft }),
+ select: (selected) => set({ selected }),
+ setHover: (hover) => set({ hover }),
+ setPanel: (panel) => set({ panel }),
+}))
diff --git a/src/networks/waterTrace.ts b/src/networks/waterTrace.ts
new file mode 100644
index 0000000..30f44d9
--- /dev/null
+++ b/src/networks/waterTrace.ts
@@ -0,0 +1,93 @@
+import { distanceToSegment, type Plan, type Point, type WaterLine, type WaterPipe } from '../model'
+import { firstCrossing, insideAny, type SewerTarget } from './sewerSnap'
+import { FURNITURE_FIXTURE } from './sewerModel'
+import { addWaterNode, addWaterPipe, collectorLine, splitWaterPipe, waterOf, wNode, type NewWaterPipe } from './waterModel'
+import type { WaterNextKind } from './waterStore'
+import { t } from '../i18n'
+
+export type WaterStep = { plan: Plan; draft: string | null; message?: string }
+
+function nodeFromTarget(plan: Plan, t: SewerTarget, nextKind: WaterNextKind, line: WaterLine) {
+ if (t.kind === 'node') return { plan, id: t.id, end: true }
+ if (t.kind === 'pipe') {
+ const r = splitWaterPipe(plan, t.id, t.point)
+ if (r) return { ...r, end: true }
+ }
+ if (t.kind === 'fixture') {
+ const r = addWaterNode(plan, { x: t.point.x, y: t.point.y, kind: 'fixture', fixture: FURNITURE_FIXTURE[t.furniture.type], furnitureId: t.furniture.id })
+ return { ...r, end: true }
+ }
+ const extra = nextKind === 'collector' || nextKind === 'boiler' ? { line: nextKind === 'boiler' ? ('hot' as const) : line === 'recirc' ? ('hot' as const) : line } : {}
+ const r = addWaterNode(plan, { x: t.point.x, y: t.point.y, kind: nextKind, ...extra })
+ return { ...r, end: nextKind === 'tap_outdoor' }
+}
+
+function spec(plan: Plan, fromId: string, toId: string, line: WaterLine, location: WaterPipe['location']): NewWaterPipe {
+ const to = wNode(waterOf(plan), toId)
+ if (location === 'outside') return { from: fromId, to: toId, line, diameter: 32, material: 'PE', location }
+ const leaf = to?.kind === 'fixture' || to?.kind === 'tap_outdoor' || line === 'recirc'
+ return { from: fromId, to: toId, line, diameter: leaf ? 16 : 20, material: 'PEX', location }
+}
+
+export function connectWater(plan: Plan, fromId: string, toId: string, line: WaterLine, footprints: Point[][]): Plan {
+ const w = waterOf(plan)
+ const a = wNode(w, fromId)
+ const b = wNode(w, toId)
+ if (!a || !b || a.id === b.id) return plan
+ const aIn = insideAny(a, footprints)
+ const bIn = insideAny(b, footprints)
+ if (!aIn && bIn && a.kind !== 'entry') {
+ const c = firstCrossing(a, b, footprints)
+ if (c && Math.hypot(c.x - a.x, c.y - a.y) > 50 && Math.hypot(c.x - b.x, c.y - b.y) > 50) {
+ const e = addWaterNode(plan, { x: c.x, y: c.y, kind: 'entry' })
+ const p1 = addWaterPipe(e.plan, spec(e.plan, fromId, e.id, line, 'outside'))
+ return addWaterPipe(p1.plan, spec(p1.plan, e.id, toId, line, 'inside')).plan
+ }
+ }
+ const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
+ const location: WaterPipe['location'] = footprints.length > 0 && !insideAny(mid, footprints) ? 'outside' : 'inside'
+ return addWaterPipe(plan, spec(plan, fromId, toId, line, location)).plan
+}
+
+export function radialToFixture(plan: Plan, fixtureId: string, line: WaterLine): WaterStep {
+ const w = waterOf(plan)
+ const f = wNode(w, fixtureId)
+ if (!f) return { plan, draft: null }
+ const feedLine: WaterLine = line === 'recirc' ? 'hot' : line
+ if (w.pipes.some((p) => p.to === fixtureId && p.line === feedLine)) return { plan, draft: null, message: t(feedLine === 'hot' ? 'networks:water.trace.alreadyHot' : 'networks:water.trace.alreadyCold') }
+ const collectors = w.nodes.filter((n) => n.kind === 'collector' && collectorLine(n) === feedLine)
+ if (!collectors.length) return { plan, draft: null, message: t(feedLine === 'hot' ? 'networks:water.trace.needHotCollector' : 'networks:water.trace.needColdCollector') }
+ const c = collectors.reduce((m, n) => (Math.hypot(n.x - f.x, n.y - f.y) < Math.hypot(m.x - f.x, m.y - f.y) ? n : m))
+ const corners = [
+ { x: f.x, y: c.y },
+ { x: c.x, y: f.y },
+ ]
+ const wallDist = (p: Point) => Math.min(Infinity, ...plan.walls.map((wl) => distanceToSegment(p, wl.a, wl.b) - wl.thickness / 2))
+ const corner = corners.sort((p, q) => wallDist(p) - wallDist(q))[0]
+ const straight = Math.abs(f.x - c.x) < 30 || Math.abs(f.y - c.y) < 30
+ let next = plan
+ let from = c.id
+ if (!straight) {
+ const j = addWaterNode(next, { x: Math.round(corner.x), y: Math.round(corner.y), kind: 'junction' })
+ next = addWaterPipe(j.plan, { from, to: j.id, line: feedLine, diameter: 16, material: 'PEX', location: 'inside' }).plan
+ from = j.id
+ }
+ next = addWaterPipe(next, { from, to: fixtureId, line: feedLine, diameter: 16, material: 'PEX', location: 'inside' }).plan
+ return { plan: next, draft: null }
+}
+
+export function waterClick(plan: Plan, draft: string | null, t: SewerTarget, nextKind: WaterNextKind, line: WaterLine, footprints: Point[][]): WaterStep {
+ const w = waterOf(plan)
+ if (draft && t.kind === 'node' && t.id === draft) return { plan, draft: null }
+ if (!draft) {
+ const fixtureNode = t.kind === 'node' ? wNode(w, t.id) : undefined
+ if (t.kind === 'fixture' || fixtureNode?.kind === 'fixture') {
+ const r = nodeFromTarget(plan, t, nextKind, line)
+ return radialToFixture(r.plan, r.id, line)
+ }
+ const r = nodeFromTarget(plan, t, nextKind, line)
+ return { plan: r.plan, draft: r.id }
+ }
+ const r = nodeFromTarget(plan, t, nextKind, line)
+ return { plan: connectWater(r.plan, draft, r.id, line, footprints), draft: r.end ? null : r.id }
+}
diff --git a/src/stats/PlanSummary.tsx b/src/stats/PlanSummary.tsx
new file mode 100644
index 0000000..915d309
--- /dev/null
+++ b/src/stats/PlanSummary.tsx
@@ -0,0 +1,148 @@
+import { useMemo, type ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { t, numberFormat } from '../i18n'
+import { formatMoney, formatNumber } from '../model'
+import type { PlanWithRooms } from './rooms'
+import { computePlanSummary, type BuildingSummary, type Clearance } from './summary'
+import './stats.css'
+
+const m2 = (v: number) => `${numberFormat({ minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(v)} ${t('common:units.m2')}`
+const m = (v: number) => `${formatNumber(v, 1)} ${t('common:units.m')}`
+
+function Row({ label, children, bad }: { label: ReactNode; children: ReactNode; bad?: ReactNode }) {
+ return (
+ <div className="plan-stats__row">
+ <dt>{label}</dt>
+ <dd>
+ {children}
+ {bad && <span className="plan-stats__bad">{bad}</span>}
+ </dd>
+ </div>
+ )
+}
+
+function Section({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section className="plan-stats__section">
+ <h3 className="plan-stats__title">{title}</h3>
+ <dl className="plan-stats__list">{children}</dl>
+ </section>
+ )
+}
+
+function ClearanceRow({ label, c }: { label: string; c: Clearance | undefined }) {
+ if (!c) return null
+ return (
+ <Row label={label} bad={c.ok ? undefined : t('plan:summary.lessThan', { norm: m(c.normM) })}>
+ {m(c.distanceM)}
+ </Row>
+ )
+}
+
+function neighbourSides(note: string | undefined, n: number) {
+ const out: { side: number; name: string }[] = []
+ for (const x of (note ?? '').matchAll(/сторона\s+(\d+)\s*[–-]\s*(\d+)\s*—\s*граница с\s+(:?\d+)/giu)) {
+ const i = Number(x[1]) % n
+ const j = Number(x[2]) % n
+ const side = j === (i + 1) % n ? i : i === (j + 1) % n ? j : -1
+ if (side >= 0) out.push({ side, name: x[3] })
+ }
+ return out
+}
+
+const minBy = (items: Clearance[]) =>
+ items.reduce<Clearance | undefined>((best, c) => (!best || c.distanceM < best.distanceM ? c : best), undefined)
+
+function lowerName(b: BuildingSummary) {
+ return b.name.toLowerCase()
+}
+
+export function PlanSummary({ plan }: { plan: PlanWithRooms }) {
+ const { t } = useTranslation('plan')
+ const s = useMemo(() => computePlanSummary(plan), [plan])
+ const { totals, site } = s
+ const homes = s.buildings.filter((b) => b.kind === 'house')
+ const others = s.buildings.filter((b) => b.kind !== 'house')
+ const rooms = homes.flatMap((b) => b.rooms)
+ const sideCount = s.buildings[0]?.clearances.filter((c) => c.side !== undefined).length ?? 0
+ const neighbours = neighbourSides(plan.site.note, sideCount || 1)
+ const many = s.buildings.length > 1
+ const suffix = (b: BuildingSummary) => (many ? ` · ${lowerName(b)}` : '')
+ const badGaps = site.gaps.filter((g) => !g.ok)
+
+ if (s.buildings.length === 0) {
+ return <p className="plan-stats__empty">{t('summary.empty')}</p>
+ }
+
+ return (
+ <div className="plan-stats">
+ {homes.map((b) => (
+ <Section key={b.id} title={b.name}>
+ <Row label={t('summary.totalArea')}>{m2(b.totalAreaM2)}</Row>
+ <Row label={t('summary.livingArea')}>{m2(b.livingAreaM2)}</Row>
+ <Row label={t('summary.rooms')}>{b.livingRooms}</Row>
+ <Row label={t('summary.bedrooms')}>{b.bedrooms}</Row>
+ <Row label={t('summary.baths')}>{b.baths}</Row>
+ <Row label={t('summary.footprint')}>{m2(b.footprintM2)}</Row>
+ <Row label={t('summary.height')}>{`${formatNumber(b.heightM, 2)} ${t('common:units.m')}`}</Row>
+ </Section>
+ ))}
+ {homes.length > 1 && (
+ <Section title={t('summary.allHouses')}>
+ <Row label={t('summary.totalArea')}>{m2(totals.totalAreaM2)}</Row>
+ <Row label={t('summary.livingArea')}>{m2(totals.livingAreaM2)}</Row>
+ </Section>
+ )}
+
+ {rooms.length > 0 && (
+ <Section title={t('summary.roomsSection')}>
+ {rooms.map((r) => (
+ <Row key={r.id} label={r.name} bad={r.lightOk === false ? t('summary.lowLight') : undefined}>
+ {m2(r.areaM2)}
+ </Row>
+ ))}
+ </Section>
+ )}
+
+ {others.map((b) => (
+ <Section key={b.id} title={b.name}>
+ <Row label={t('summary.area')}>{m2(b.totalAreaM2)}</Row>
+ </Section>
+ ))}
+
+ <Section title={t('summary.site')}>
+ <Row label={t('summary.area')}>{t('summary.siteArea', { area: m2(site.areaM2), ares: formatNumber(site.areaM2 / 100, 1) })}</Row>
+ <Row label={t('summary.built')}>{`${m2(site.builtM2)} · ${formatNumber(site.builtPct, 1)} %`}</Row>
+ {s.buildings.map((b) => (
+ <ClearanceRow key={`st-${b.id}`} label={`${t('summary.toStreet')}${suffix(b)}`} c={minBy(b.clearances.filter((c) => c.target === 'street'))} />
+ ))}
+ {s.buildings.map((b) => (
+ <ClearanceRow key={`bd-${b.id}`} label={`${t('summary.toBorders')}${suffix(b)}`} c={minBy(b.clearances.filter((c) => c.target === 'side'))} />
+ ))}
+ {neighbours.flatMap((nb) =>
+ s.buildings.map((b) => (
+ <ClearanceRow
+ key={`nb-${nb.side}-${b.id}`}
+ label={`${t('summary.toNeighbour', { name: nb.name })}${suffix(b)}`}
+ c={b.clearances.find((c) => c.side === nb.side)}
+ />
+ )),
+ )}
+ {badGaps.map((g) => (
+ <ClearanceRow key={g.label} label={g.label} c={g} />
+ ))}
+ {s.unmatchedLabels.length > 0 && (
+ <Row label={t('summary.unmatchedLabels')} bad={s.unmatchedLabels.join(', ')}>
+ {''}
+ </Row>
+ )}
+ </Section>
+
+ <Section title={t('summary.wallCost')}>
+ <Row label={t('summary.withWaste', { pct: formatNumber(s.estimate.wastePct, 1) })} bad={s.estimate.missingPrices > 0 ? t('summary.noPrice', { count: s.estimate.missingPrices }) : undefined}>
+ {formatMoney(s.estimate.total)}
+ </Row>
+ </Section>
+ </div>
+ )
+}
diff --git a/src/stats/index.ts b/src/stats/index.ts
new file mode 100644
index 0000000..9c6fb42
--- /dev/null
+++ b/src/stats/index.ts
@@ -0,0 +1,3 @@
+export { detectRooms, roomKinds, type RoomKind, type RoomLabel, type RoomDetection, type RoomFace, type DetectedBuilding } from './rooms'
+export { computePlanSummary, NORMS, type PlanSummary as PlanSummaryData, type BuildingSummary, type RoomSummary, type Clearance } from './summary'
+export { PlanSummary } from './PlanSummary'
diff --git a/src/stats/rooms.ts b/src/stats/rooms.ts
new file mode 100644
index 0000000..71bcaab
--- /dev/null
+++ b/src/stats/rooms.ts
@@ -0,0 +1,366 @@
+import type { Opening, Plan, Point, Wall } from '../model'
+import { t } from '../i18n'
+
+export const NODE_TOLERANCE_MM = 20
+
+export const roomKinds = ['living', 'bedroom', 'kitchen', 'bath', 'tech', 'hall', 'storage', 'garage'] as const
+export type RoomKind = (typeof roomKinds)[number]
+
+export type RoomLabel = { id: string; name: string; x: number; y: number; kind?: RoomKind }
+
+export type PlanWithRooms = Plan & { rooms?: RoomLabel[] }
+
+export type GraphEdge = { id: number; u: number; v: number; wall: Wall }
+
+export type RoomFace = {
+ id: string
+ buildingId: string
+ name: string
+ kind?: RoomKind
+ labelIds: string[]
+ axisPolygon: Point[]
+ clearPolygon: Point[]
+ axisAreaM2: number
+ areaM2: number
+ edges: GraphEdge[]
+}
+
+export type DetectedBuilding = {
+ id: string
+ walls: Wall[]
+ outline: Point[]
+ outlineEdges: GraphEdge[]
+ footprint: Point[]
+ footprintM2: number
+ interiorEdges: GraphEdge[]
+ rooms: RoomFace[]
+}
+
+export type RoomDetection = {
+ nodes: Point[]
+ edges: GraphEdge[]
+ buildings: DetectedBuilding[]
+ unmatchedLabels: RoomLabel[]
+}
+
+const EPS = 1e-9
+
+export function signedArea(poly: Point[]): number {
+ let s = 0
+ for (let i = 0; i < poly.length; i++) {
+ const p = poly[i]
+ const q = poly[(i + 1) % poly.length]
+ s += p.x * q.y - q.x * p.y
+ }
+ return s / 2
+}
+
+export const polygonAreaM2 = (poly: Point[]) => Math.abs(signedArea(poly)) / 1e6
+
+export function pointInPolygon(p: Point, poly: Point[]): boolean {
+ let inside = false
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
+ const a = poly[i]
+ const b = poly[j]
+ if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) inside = !inside
+ }
+ return inside
+}
+
+function projectParam(p: Point, a: Point, b: Point) {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const len2 = dx * dx + dy * dy
+ return len2 === 0 ? 0 : ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
+}
+
+function distToLine(p: Point, a: Point, b: Point, t: number) {
+ return Math.hypot(p.x - (a.x + (b.x - a.x) * t), p.y - (a.y + (b.y - a.y) * t))
+}
+
+function segmentIntersection(a: Point, b: Point, c: Point, d: Point): Point | null {
+ const rx = b.x - a.x
+ const ry = b.y - a.y
+ const sx = d.x - c.x
+ const sy = d.y - c.y
+ const den = rx * sy - ry * sx
+ if (Math.abs(den) < EPS) return null
+ const t = ((c.x - a.x) * sy - (c.y - a.y) * sx) / den
+ const u = ((c.x - a.x) * ry - (c.y - a.y) * rx) / den
+ if (t < -EPS || t > 1 + EPS || u < -EPS || u > 1 + EPS) return null
+ return { x: a.x + rx * t, y: a.y + ry * t }
+}
+
+function buildGraph(walls: Wall[], tol: number) {
+ const raw: { p: Point; endpoint: boolean }[] = []
+ for (const w of walls) {
+ raw.push({ p: w.a, endpoint: true }, { p: w.b, endpoint: true })
+ }
+ for (let i = 0; i < walls.length; i++) {
+ for (let j = i + 1; j < walls.length; j++) {
+ const x = segmentIntersection(walls[i].a, walls[i].b, walls[j].a, walls[j].b)
+ if (x) raw.push({ p: x, endpoint: false })
+ }
+ }
+ for (const w of walls) {
+ for (const other of walls) {
+ if (other === w) continue
+ for (const e of [other.a, other.b]) {
+ const t = projectParam(e, w.a, w.b)
+ if (t > 0 && t < 1 && distToLine(e, w.a, w.b, t) <= tol) {
+ raw.push({ p: { x: w.a.x + (w.b.x - w.a.x) * t, y: w.a.y + (w.b.y - w.a.y) * t }, endpoint: false })
+ }
+ }
+ }
+ }
+
+ const nodes: Point[] = []
+ const members: { p: Point; endpoint: boolean }[][] = []
+ const nodeOf = (p: Point) => {
+ for (let i = 0; i < nodes.length; i++) if (Math.hypot(nodes[i].x - p.x, nodes[i].y - p.y) <= tol) return i
+ return -1
+ }
+ const sorted = [...raw].sort((a, b) => Number(b.endpoint) - Number(a.endpoint))
+ for (const r of sorted) {
+ const i = nodeOf(r.p)
+ if (i >= 0) members[i].push(r)
+ else {
+ nodes.push(r.p)
+ members.push([r])
+ }
+ }
+ for (let i = 0; i < nodes.length; i++) {
+ const ends = members[i].filter((m) => m.endpoint)
+ const src = ends.length ? ends : members[i]
+ nodes[i] = {
+ x: src.reduce((s, m) => s + m.p.x, 0) / src.length,
+ y: src.reduce((s, m) => s + m.p.y, 0) / src.length,
+ }
+ }
+
+ const edges: GraphEdge[] = []
+ const seen = new Map<string, GraphEdge>()
+ for (const w of walls) {
+ const on: { t: number; n: number }[] = []
+ for (let n = 0; n < nodes.length; n++) {
+ const t = projectParam(nodes[n], w.a, w.b)
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y)
+ if (t * len < -tol || (t - 1) * len > tol) continue
+ if (distToLine(nodes[n], w.a, w.b, Math.max(0, Math.min(1, t))) <= tol) on.push({ t, n })
+ }
+ on.sort((a, b) => a.t - b.t)
+ for (let k = 0; k + 1 < on.length; k++) {
+ const u = on[k].n
+ const v = on[k + 1].n
+ if (u === v) continue
+ const key = u < v ? `${u}:${v}` : `${v}:${u}`
+ const prev = seen.get(key)
+ if (prev) {
+ if (w.thickness > prev.wall.thickness) prev.wall = w
+ continue
+ }
+ const e: GraphEdge = { id: edges.length, u, v, wall: w }
+ seen.set(key, e)
+ edges.push(e)
+ }
+ }
+ return { nodes, edges }
+}
+
+function pruneDangling(nodeCount: number, edges: GraphEdge[]) {
+ let alive = edges
+ for (;;) {
+ const deg = new Array<number>(nodeCount).fill(0)
+ for (const e of alive) {
+ deg[e.u]++
+ deg[e.v]++
+ }
+ const next = alive.filter((e) => deg[e.u] > 1 && deg[e.v] > 1)
+ if (next.length === alive.length) return alive
+ alive = next
+ }
+}
+
+type HalfEdge = { from: number; to: number; edge: GraphEdge }
+
+function traceFaces(nodes: Point[], edges: GraphEdge[]) {
+ const out = new Map<number, HalfEdge[]>()
+ for (const e of edges) {
+ for (const [from, to] of [
+ [e.u, e.v],
+ [e.v, e.u],
+ ]) {
+ const list = out.get(from) ?? []
+ list.push({ from, to, edge: e })
+ out.set(from, list)
+ }
+ }
+ const angle = (h: HalfEdge) => Math.atan2(nodes[h.to].y - nodes[h.from].y, nodes[h.to].x - nodes[h.from].x)
+ for (const list of out.values()) list.sort((a, b) => angle(a) - angle(b))
+
+ const used = new Set<HalfEdge>()
+ const faces: HalfEdge[][] = []
+ for (const list of out.values()) {
+ for (const start of list) {
+ if (used.has(start)) continue
+ const face: HalfEdge[] = []
+ let h = start
+ while (!used.has(h)) {
+ used.add(h)
+ face.push(h)
+ const around = out.get(h.to)!
+ const twin = around.findIndex((x) => x.to === h.from && x.edge === h.edge)
+ h = around[(twin - 1 + around.length) % around.length]
+ }
+ faces.push(face)
+ }
+ }
+ return faces
+}
+
+function mergeCollinear(poly: Point[], dist: number[]) {
+ const pts = [...poly]
+ const d = [...dist]
+ let changed = true
+ while (changed && pts.length > 3) {
+ changed = false
+ for (let i = 0; i < pts.length; i++) {
+ const prev = (i - 1 + pts.length) % pts.length
+ const next = (i + 1) % pts.length
+ const ax = pts[i].x - pts[prev].x
+ const ay = pts[i].y - pts[prev].y
+ const bx = pts[next].x - pts[i].x
+ const by = pts[next].y - pts[i].y
+ const cross = (ax * by - ay * bx) / (Math.hypot(ax, ay) * Math.hypot(bx, by) || 1)
+ if (Math.abs(cross) < 1e-6 && ax * bx + ay * by > 0 && Math.abs(d[prev] - d[i]) < 1e-6) {
+ pts.splice(i, 1)
+ d.splice(i, 1)
+ changed = true
+ break
+ }
+ }
+ }
+ return { pts, d }
+}
+
+export function offsetPolygon(poly: Point[], dist: number[]): Point[] {
+ const ccw = signedArea(poly) > 0
+ const src = ccw ? poly : [...poly].reverse()
+ const srcDist = ccw ? dist : [...dist.slice(0, -1)].reverse().concat(dist.slice(-1))
+ const { pts, d } = mergeCollinear(src, srcDist)
+ const n = pts.length
+ const lines = pts.map((p, i) => {
+ const q = pts[(i + 1) % n]
+ const len = Math.hypot(q.x - p.x, q.y - p.y) || 1
+ const dir = { x: (q.x - p.x) / len, y: (q.y - p.y) / len }
+ const nx = -dir.y
+ const ny = dir.x
+ return { p: { x: p.x + nx * d[i], y: p.y + ny * d[i] }, q: { x: q.x + nx * d[i], y: q.y + ny * d[i] }, dir }
+ })
+ const res: Point[] = []
+ for (let i = 0; i < n; i++) {
+ const a = lines[(i - 1 + n) % n]
+ const b = lines[i]
+ const den = a.dir.x * b.dir.y - a.dir.y * b.dir.x
+ if (Math.abs(den) < 1e-9) {
+ res.push(a.q, b.p)
+ continue
+ }
+ const t = ((b.p.x - a.p.x) * b.dir.y - (b.p.y - a.p.y) * b.dir.x) / den
+ res.push({ x: a.p.x + a.dir.x * t, y: a.p.y + a.dir.y * t })
+ }
+ return res
+}
+
+function faceGeometry(nodes: Point[], face: HalfEdge[], sign: 1 | -1) {
+ const poly = face.map((h) => nodes[h.from])
+ const dist = face.map((h) => (sign * h.edge.wall.thickness) / 2)
+ return offsetPolygon(poly, dist)
+}
+
+export function detectRooms(plan: PlanWithRooms, tol = NODE_TOLERANCE_MM): RoomDetection {
+ const walls = plan.walls.filter((w) => Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) > tol)
+ const { nodes, edges: allEdges } = buildGraph(walls, tol)
+ const edges = pruneDangling(nodes.length, allEdges)
+
+ const parent = nodes.map((_, i) => i)
+ const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])))
+ for (const e of edges) parent[find(e.u)] = find(e.v)
+ for (const e of allEdges) parent[find(e.u)] = find(e.v)
+
+ const faces = traceFaces(nodes, edges)
+ const byComponent = new Map<number, HalfEdge[][]>()
+ for (const f of faces) {
+ const c = find(f[0].from)
+ byComponent.set(c, [...(byComponent.get(c) ?? []), f])
+ }
+
+ const labels = plan.rooms ?? []
+ const usedLabels = new Set<string>()
+ const buildings: DetectedBuilding[] = []
+ const components = [...byComponent.entries()]
+ .map(([c, fs]) => ({ c, fs, outer: fs.reduce((m, f) => (areaOf(nodes, f) < areaOf(nodes, m) ? f : m)) }))
+ .filter((x) => areaOf(nodes, x.outer) < 0)
+ .sort((a, b) => areaOf(nodes, a.outer) - areaOf(nodes, b.outer))
+
+ let roomNo = 0
+ components.forEach(({ c, fs, outer }, bi) => {
+ const buildingId = `b${bi + 1}`
+ const outerEdges = new Set(outer.map((h) => h.edge))
+ const compWalls = new Set<Wall>()
+ for (const e of allEdges) if (find(e.u) === c) compWalls.add(e.wall)
+ const outline = outer.map((h) => nodes[h.from]).reverse()
+ const footprint = faceGeometry(nodes, outer, -1)
+ const rooms: RoomFace[] = fs
+ .filter((f) => f !== outer && areaOf(nodes, f) > 0)
+ .map((f, fi) => {
+ const axisPolygon = f.map((h) => nodes[h.from])
+ const clearPolygon = faceGeometry(nodes, f, 1)
+ const inside = labels.filter((l) => !usedLabels.has(l.id) && pointInPolygon(l, axisPolygon))
+ inside.forEach((l) => usedLabels.add(l.id))
+ return {
+ id: `${buildingId}-r${fi + 1}`,
+ buildingId,
+ name: inside.length ? inside.map((l) => l.name).join(' + ') : '',
+ kind: inside.find((l) => l.kind)?.kind,
+ labelIds: inside.map((l) => l.id),
+ axisPolygon,
+ clearPolygon,
+ axisAreaM2: polygonAreaM2(axisPolygon),
+ areaM2: Math.max(0, signedArea(clearPolygon)) / 1e6,
+ edges: f.map((h) => h.edge),
+ }
+ })
+ .sort((a, b) => b.areaM2 - a.areaM2)
+ for (const r of rooms) if (!r.name) r.name = t('plan:summary.defaultRoom', { n: ++roomNo })
+ buildings.push({
+ id: buildingId,
+ walls: [...compWalls],
+ outline,
+ outlineEdges: [...outerEdges],
+ footprint,
+ footprintM2: polygonAreaM2(footprint),
+ interiorEdges: edges.filter((e) => find(e.u) === c && !outerEdges.has(e)),
+ rooms,
+ })
+ })
+
+ return { nodes, edges, buildings, unmatchedLabels: labels.filter((l) => !usedLabels.has(l.id)) }
+}
+
+function areaOf(nodes: Point[], face: HalfEdge[]) {
+ return signedArea(face.map((h) => nodes[h.from]))
+}
+
+export function openingPoint(wall: Wall, o: Opening): Point {
+ const len = Math.hypot(wall.b.x - wall.a.x, wall.b.y - wall.a.y) || 1
+ const t = (o.offset + o.width / 2) / len
+ return { x: wall.a.x + (wall.b.x - wall.a.x) * t, y: wall.a.y + (wall.b.y - wall.a.y) * t }
+}
+
+export function edgeContains(nodes: Point[], e: GraphEdge, p: Point, tol = NODE_TOLERANCE_MM) {
+ const a = nodes[e.u]
+ const b = nodes[e.v]
+ const t = projectParam(p, a, b)
+ return t >= 0 && t <= 1 && distToLine(p, a, b, t) <= tol
+}
diff --git a/src/stats/stats.css b/src/stats/stats.css
new file mode 100644
index 0000000..cb1b8b5
--- /dev/null
+++ b/src/stats/stats.css
@@ -0,0 +1,56 @@
+.plan-stats {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+ min-width: 0;
+ font-size: var(--text-md);
+}
+
+.plan-stats__title {
+ margin: 0 0 var(--space-1);
+ color: var(--muted);
+ font-size: var(--text-xs);
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+.plan-stats__list {
+ margin: 0;
+}
+
+.plan-stats__row {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-3);
+ padding: 7px 0;
+ border-bottom: 1px solid var(--line);
+}
+
+.plan-stats__row:last-child {
+ border-bottom: 0;
+}
+
+.plan-stats__row dt {
+ min-width: 0;
+ color: var(--ink-2);
+}
+
+.plan-stats__row dd {
+ margin: 0;
+ color: var(--ink);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+
+.plan-stats__bad {
+ display: block;
+ color: var(--danger);
+ font-size: var(--text-xs);
+}
+
+.plan-stats__empty {
+ margin: 0;
+ color: var(--muted);
+}
diff --git a/src/stats/summary.ts b/src/stats/summary.ts
new file mode 100644
index 0000000..fcf731b
--- /dev/null
+++ b/src/stats/summary.ts
@@ -0,0 +1,296 @@
+import { computeWallEstimate, sitePolygon, type Opening, type Point } from '../model'
+import { t } from '../i18n'
+import {
+ detectRooms,
+ edgeContains,
+ openingPoint,
+ polygonAreaM2,
+ type DetectedBuilding,
+ type PlanWithRooms,
+ type RoomKind,
+} from './rooms'
+
+export const NORMS = {
+ houseToBorderMm: 3000,
+ houseToStreetMm: 5000,
+ outbuildingToBorderMm: 1000,
+ outbuildingToStreetMm: 5000,
+ betweenBuildingsMm: 6000,
+ minLightRatio: 1 / 8,
+} as const
+
+export const LIVING_KINDS: readonly RoomKind[] = ['living', 'bedroom']
+
+export type StreetRef = number | [number, number] | { side: number | [number, number] } | Point[] | { a: Point; b: Point }
+
+export type BuildingKind = 'house' | 'garage' | 'outbuilding'
+
+export type RoomSummary = {
+ id: string
+ name: string
+ kind?: RoomKind
+ areaM2: number
+ living: boolean
+ windows: number
+ glazingM2: number
+ lightRatio: number | null
+ lightOk: boolean | null
+ polygon: Point[]
+}
+
+export type Clearance = {
+ target: 'side' | 'street' | 'building'
+ label: string
+ side?: number
+ otherBuildingId?: string
+ distanceM: number
+ normM: number
+ ok: boolean
+}
+
+export type BuildingSummary = {
+ id: string
+ name: string
+ kind: BuildingKind
+ footprintM2: number
+ footprint: Point[]
+ totalAreaM2: number
+ livingAreaM2: number
+ livingRooms: number
+ bedrooms: number
+ baths: number
+ exteriorPerimeterM: number
+ partitionsLengthM: number
+ heightM: number
+ volumeM3: number
+ doors: number
+ windows: number
+ gates: number
+ glazingM2: number
+ rooms: RoomSummary[]
+ clearances: Clearance[]
+}
+
+export type PlanSummary = {
+ totals: {
+ totalAreaM2: number
+ livingAreaM2: number
+ livingRooms: number
+ bedrooms: number
+ baths: number
+ }
+ buildings: BuildingSummary[]
+ site: {
+ areaM2: number
+ builtM2: number
+ builtPct: number
+ gaps: Clearance[]
+ violations: number
+ }
+ estimate: { total: number; missingPrices: number; wastePct: number }
+ unmatchedLabels: string[]
+}
+
+function segDist(p: Point, a: Point, b: Point) {
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const len2 = dx * dx + dy * dy
+ const t = len2 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2)) : 0
+ return Math.hypot(p.x - a.x - dx * t, p.y - a.y - dy * t)
+}
+
+function segmentsCross(a: Point, b: Point, c: Point, d: Point) {
+ const o = (p: Point, q: Point, r: Point) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x))
+ return o(a, b, c) * o(a, b, d) < 0 && o(c, d, a) * o(c, d, b) < 0
+}
+
+function polylineDistance(p: Point[], q: Point[], closedP: boolean, closedQ: boolean) {
+ const segs = (pts: Point[], closed: boolean) => {
+ const out: [Point, Point][] = []
+ for (let i = 0; i + 1 < pts.length; i++) out.push([pts[i], pts[i + 1]])
+ if (closed && pts.length > 2) out.push([pts[pts.length - 1], pts[0]])
+ return out
+ }
+ const sp = segs(p, closedP)
+ const sq = segs(q, closedQ)
+ let best = Infinity
+ for (const [a, b] of sp) {
+ for (const [c, d] of sq) {
+ if (segmentsCross(a, b, c, d)) return 0
+ best = Math.min(best, segDist(a, c, d), segDist(b, c, d), segDist(c, a, b), segDist(d, a, b))
+ }
+ }
+ return best
+}
+
+const isPoint = (v: unknown): v is Point =>
+ !!v && typeof (v as Point).x === 'number' && typeof (v as Point).y === 'number'
+
+function streetLine(street: unknown, boundary: Point[]): { side?: number; line?: Point[] } {
+ if (typeof street === 'number' && Number.isInteger(street)) {
+ return { side: ((street % boundary.length) + boundary.length) % boundary.length }
+ }
+ if (Array.isArray(street) && street.length === 2 && street.every((v) => Number.isInteger(v))) {
+ const n = boundary.length
+ const [i, j] = street.map((v: number) => ((v % n) + n) % n)
+ if (j === (i + 1) % n) return { side: i }
+ if (i === (j + 1) % n) return { side: j }
+ return {}
+ }
+ if (Array.isArray(street)) return street.length >= 2 && street.every(isPoint) ? { line: street } : {}
+ if (street && typeof street === 'object') {
+ const s = street as { a?: unknown; b?: unknown; side?: unknown }
+ if (isPoint(s.a) && isPoint(s.b)) return { line: [s.a, s.b] }
+ if (s.side !== undefined) return streetLine(s.side, boundary)
+ }
+ return {}
+}
+
+function classify(b: DetectedBuilding, gates: number, largestId: string): BuildingKind {
+ const kinds = b.rooms.map((r) => r.kind).filter(Boolean)
+ if (kinds.includes('garage')) return kinds.some((k) => LIVING_KINDS.includes(k!)) ? 'house' : 'garage'
+ if (kinds.some((k) => k && k !== 'storage' && k !== 'tech')) return 'house'
+ if (b.id === largestId) return 'house'
+ return gates > 0 ? 'garage' : 'outbuilding'
+}
+
+const kindName = (kind: BuildingKind) => t(`plan:summary.buildingKinds.${kind}`)
+
+const sideLabel = (i: number, n: number) => t('plan:summary.side', { from: i, to: (i + 1) % n })
+
+export function computePlanSummary(plan: PlanWithRooms): PlanSummary {
+ const detection = detectRooms(plan)
+ const { nodes } = detection
+ const wallById = new Map(plan.walls.map((w) => [w.id, w]))
+ const boundary = sitePolygon(plan.site)
+ const street = streetLine((plan.site as { street?: unknown }).street, boundary)
+ const largestId = detection.buildings.reduce<DetectedBuilding | null>(
+ (m, b) => (!m || b.footprintM2 > m.footprintM2 ? b : m),
+ null,
+ )?.id ?? ''
+
+ const kindCount = new Map<BuildingKind, number>()
+ const buildings: BuildingSummary[] = detection.buildings.map((b) => {
+ const wallIds = new Set(b.walls.map((w) => w.id))
+ const openings = plan.openings.filter((o) => wallIds.has(o.wallId))
+ const count = (t: Opening['type']) => openings.filter((o) => o.type === t).length
+ const windows = openings.filter((o) => o.type === 'window')
+
+ const rooms: RoomSummary[] = b.rooms.map((r) => {
+ const own = windows.filter((o) => {
+ const w = wallById.get(o.wallId)!
+ const p = openingPoint(w, o)
+ return r.edges.some((e) => e.wall.id === w.id && edgeContains(nodes, e, p))
+ })
+ const glazingM2 = own.reduce((s, o) => s + (o.width * o.height) / 1e6, 0)
+ const living = !!r.kind && LIVING_KINDS.includes(r.kind)
+ const lightRatio = r.areaM2 > 0 ? glazingM2 / r.areaM2 : null
+ return {
+ id: r.id,
+ name: r.name,
+ kind: r.kind,
+ areaM2: r.areaM2,
+ living,
+ windows: own.length,
+ glazingM2,
+ lightRatio: living ? lightRatio : null,
+ lightOk: living && lightRatio !== null ? lightRatio >= NORMS.minLightRatio - 1e-9 : null,
+ polygon: r.clearPolygon,
+ }
+ })
+
+ const kind = classify(b, count('gate'), largestId)
+ const n = (kindCount.get(kind) ?? 0) + 1
+ kindCount.set(kind, n)
+ const heightMm = Math.max(0, ...b.walls.map((w) => w.height))
+ const axisLen = (edges: typeof b.interiorEdges) =>
+ edges.reduce((s, e) => s + Math.hypot(nodes[e.v].x - nodes[e.u].x, nodes[e.v].y - nodes[e.u].y), 0) / 1000
+ const livingRooms = rooms.filter((r) => r.living)
+
+ const borderNorm = kind === 'house' ? NORMS.houseToBorderMm : NORMS.outbuildingToBorderMm
+ const streetNorm = kind === 'house' ? NORMS.houseToStreetMm : NORMS.outbuildingToStreetMm
+ const clearances: Clearance[] = boundary.map((p, i) => {
+ const q = boundary[(i + 1) % boundary.length]
+ const isStreet = street.side === i
+ const d = polylineDistance(b.footprint, [p, q], true, false)
+ const norm = isStreet ? streetNorm : borderNorm
+ return {
+ target: isStreet ? 'street' : 'side',
+ label: isStreet ? t('plan:summary.sideStreet', { side: sideLabel(i, boundary.length) }) : sideLabel(i, boundary.length),
+ side: i,
+ distanceM: d / 1000,
+ normM: norm / 1000,
+ ok: d >= norm - 1,
+ }
+ })
+ if (street.line) {
+ const d = polylineDistance(b.footprint, street.line, true, false)
+ clearances.push({ target: 'street', label: t('plan:summary.street'), distanceM: d / 1000, normM: streetNorm / 1000, ok: d >= streetNorm - 1 })
+ }
+
+ return {
+ id: b.id,
+ name: n > 1 ? `${kindName(kind)} ${n}` : kindName(kind),
+ kind,
+ footprintM2: b.footprintM2,
+ footprint: b.footprint,
+ totalAreaM2: rooms.reduce((s, r) => s + r.areaM2, 0),
+ livingAreaM2: livingRooms.reduce((s, r) => s + r.areaM2, 0),
+ livingRooms: livingRooms.length,
+ bedrooms: rooms.filter((r) => r.kind === 'bedroom').length,
+ baths: rooms.filter((r) => r.kind === 'bath').length,
+ exteriorPerimeterM: axisLen(b.outlineEdges),
+ partitionsLengthM: axisLen(b.interiorEdges),
+ heightM: heightMm / 1000,
+ volumeM3: (b.footprintM2 * heightMm) / 1000,
+ doors: count('door'),
+ windows: windows.length,
+ gates: count('gate'),
+ glazingM2: windows.reduce((s, o) => s + (o.width * o.height) / 1e6, 0),
+ rooms,
+ clearances,
+ }
+ })
+
+ const gaps: Clearance[] = []
+ for (let i = 0; i < buildings.length; i++) {
+ for (let j = i + 1; j < buildings.length; j++) {
+ const d = polylineDistance(buildings[i].footprint, buildings[j].footprint, true, true)
+ const gap: Clearance = {
+ target: 'building',
+ label: `${buildings[i].name} — ${buildings[j].name}`,
+ otherBuildingId: buildings[j].id,
+ distanceM: d / 1000,
+ normM: NORMS.betweenBuildingsMm / 1000,
+ ok: d >= NORMS.betweenBuildingsMm - 1,
+ }
+ gaps.push(gap)
+ }
+ }
+
+ const siteArea = polygonAreaM2(boundary)
+ const builtM2 = buildings.reduce((s, b) => s + b.footprintM2, 0)
+ const sum = (f: (b: BuildingSummary) => number, list = buildings) => list.reduce((s, b) => s + f(b), 0)
+ const homes = buildings.filter((b) => b.kind === 'house')
+ const estimate = computeWallEstimate(plan)
+
+ return {
+ totals: {
+ totalAreaM2: sum((b) => b.totalAreaM2, homes),
+ livingAreaM2: sum((b) => b.livingAreaM2, homes),
+ livingRooms: sum((b) => b.livingRooms, homes),
+ bedrooms: sum((b) => b.bedrooms, homes),
+ baths: sum((b) => b.baths, homes),
+ },
+ buildings,
+ site: {
+ areaM2: siteArea,
+ builtM2,
+ builtPct: siteArea > 0 ? (builtM2 / siteArea) * 100 : 0,
+ gaps,
+ violations: gaps.filter((g) => !g.ok).length + sum((b) => b.clearances.filter((c) => !c.ok).length),
+ },
+ estimate: { total: estimate.total, missingPrices: estimate.missingPrices, wastePct: estimate.wastePct },
+ unmatchedLabels: detection.unmatchedLabels.map((l) => l.name),
+ }
+}
diff --git a/src/storage/busy.ts b/src/storage/busy.ts
new file mode 100644
index 0000000..73f9fed
--- /dev/null
+++ b/src/storage/busy.ts
@@ -0,0 +1,7 @@
+let busy = false
+
+export const setBusy = (value: boolean) => {
+ busy = value
+}
+
+export const isBusy = () => busy
diff --git a/src/storage/index.ts b/src/storage/index.ts
new file mode 100644
index 0000000..907374a
--- /dev/null
+++ b/src/storage/index.ts
@@ -0,0 +1,17 @@
+export * from './types'
+export { ServerStorage, apiHeaders, type SnapshotInfo } from './server'
+export {
+ useSyncStore,
+ startSync,
+ loadFromServer,
+ login,
+ listVersions,
+ restoreVersion,
+ listSnapshots,
+ saveSnapshot,
+ previewSnapshot,
+ previewRevision,
+ restorePreview,
+ type SyncStatus,
+} from './sync'
+export { setBusy, isBusy } from './busy'
diff --git a/src/storage/server.ts b/src/storage/server.ts
new file mode 100644
index 0000000..58f87e7
--- /dev/null
+++ b/src/storage/server.ts
@@ -0,0 +1,129 @@
+import { CLIENT_VERSION, parsePlan, type Plan } from '../model'
+import { t } from '../i18n'
+import {
+ AuthError,
+ ConflictError,
+ OfflineError,
+ OutdatedError,
+ UnavailableError,
+ type Loaded,
+ type PlanStorage,
+ type Saved,
+ type VersionInfo,
+} from './types'
+
+const API = `${import.meta.env.BASE_URL}api/plan.php`
+
+const revOf = (res: Response, body?: { rev?: unknown }) => {
+ const header = res.headers.get('X-Plan-Rev') ?? res.headers.get('ETag')?.replace(/\D/g, '')
+ const n = Number(header ?? body?.rev)
+ return Number.isFinite(n) ? n : 0
+}
+
+export const apiHeaders = (extra: Record<string, string> = {}): Record<string, string> => ({
+ 'X-Requested-With': 'fetch',
+ 'X-Client-Version': String(CLIENT_VERSION),
+ Accept: 'application/json',
+ ...extra,
+})
+
+export type SnapshotInfo = { id: string; name: string; rev?: number; createdAt?: string; author?: string }
+
+async function request(url: string, init: RequestInit = {}) {
+ let res: Response
+ try {
+ res = await fetch(url, {
+ credentials: 'same-origin',
+ cache: 'no-store',
+ ...init,
+ headers: { ...apiHeaders(), ...(init.headers as Record<string, string> | undefined) },
+ })
+ } catch (e) {
+ throw new OfflineError((e as Error).message)
+ }
+ if (res.status === 401) throw new AuthError('unauthorized')
+ if (res.status === 426) throw new OutdatedError('client_outdated')
+ if (res.status === 404 && !url.includes('rev=')) throw new UnavailableError('api not found')
+ const type = res.headers.get('Content-Type') ?? ''
+ if (!type.includes('json')) {
+ if (res.redirected || type.includes('html')) throw new AuthError('redirected')
+ throw new UnavailableError(`HTTP ${res.status}`)
+ }
+ return res
+}
+
+function toPlan(data: unknown): Plan {
+ const parsed = parsePlan(data)
+ if (!parsed.ok) throw new Error(t('common:sync.invalidServerPlan', { error: parsed.error }))
+ return parsed.plan
+}
+
+export class ServerStorage implements PlanStorage {
+ readonly kind = 'server' as const
+
+ async load(): Promise<Loaded> {
+ const res = await request(API)
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
+ const data = await res.json()
+ const plan = toPlan(data)
+ return { plan, rev: revOf(res, data), updatedAt: plan.updatedAt, author: plan.author, demo: res.headers.get('X-House-Demo') === '1' }
+ }
+
+ async save(plan: Plan, baseRev: number, author = 'web'): Promise<Saved> {
+ const res = await request(API, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', 'If-Match': String(baseRev), 'X-Plan-Author': author },
+ body: JSON.stringify(plan),
+ })
+ const data = await res.json()
+ if (res.status === 409) throw new ConflictError(toPlan(data.plan), revOf(res, data))
+ if (!res.ok) throw new Error(data?.message ?? `HTTP ${res.status}`)
+ return { rev: Number(data.rev), updatedAt: String(data.updatedAt) }
+ }
+
+ async list(): Promise<VersionInfo[]> {
+ const res = await request(`${API}?versions`)
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
+ const data = await res.json()
+ const list: VersionInfo[] = Array.isArray(data) ? data : (data.versions ?? [])
+ return list.map((v) => ({ rev: Number(v.rev), updatedAt: v.updatedAt, author: v.author, walls: v.walls, openings: v.openings }))
+ }
+
+ async snapshots(): Promise<SnapshotInfo[]> {
+ const res = await request(`${API}?snapshots`)
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
+ const data = await res.json()
+ const list: Record<string, unknown>[] = Array.isArray(data) ? data : (data.snapshots ?? [])
+ return list.map((x) => ({
+ id: String(x.id),
+ name: String(x.name ?? x.id),
+ rev: x.rev === undefined ? undefined : Number(x.rev),
+ createdAt: (x.createdAt ?? x.updatedAt ?? x.date) as string | undefined,
+ author: x.author as string | undefined,
+ }))
+ }
+
+ async saveSnapshot(name: string): Promise<SnapshotInfo> {
+ const res = await request(`${API}?snapshot`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name }),
+ })
+ const data = await res.json()
+ if (!res.ok) throw new Error(data?.message ?? `HTTP ${res.status}`)
+ return { id: String(data.id), name: String(data.name ?? name), rev: data.rev, createdAt: data.createdAt }
+ }
+
+ async snapshot(id: string): Promise<Plan> {
+ const res = await request(`${API}?snapshot=${encodeURIComponent(id)}`)
+ if (!res.ok) throw new Error(t('common:sync.noSnapshot', { id }))
+ const data = await res.json()
+ return toPlan(data.plan ?? data)
+ }
+
+ async get(rev: number): Promise<Plan> {
+ const res = await request(`${API}?rev=${rev}`)
+ if (!res.ok) throw new Error(t('common:sync.noVersion', { rev }))
+ return toPlan(await res.json())
+ }
+}
diff --git a/src/storage/sync.ts b/src/storage/sync.ts
new file mode 100644
index 0000000..68072a3
--- /dev/null
+++ b/src/storage/sync.ts
@@ -0,0 +1,287 @@
+import { create } from 'zustand'
+import { parsePlan, type Plan } from '../model'
+import { t } from '../i18n'
+import { usePlanStore } from '../store/planStore'
+import { showToast } from '../ui/Toast'
+import { isViewOnly } from '../store/viewOnly'
+import { ServerStorage } from './server'
+import { AuthError, ConflictError, OfflineError, OutdatedError, type VersionInfo } from './types'
+import { isBusy } from './busy'
+
+export type SyncStatus = 'loading' | 'login' | 'offline' | 'saving' | 'saved' | 'error'
+
+type SyncState = {
+ status: SyncStatus
+ savedAt: string | null
+ rev: number | null
+ error: string | null
+ demo: boolean
+}
+
+export const useSyncStore = create<SyncState>()(() => ({
+ status: 'loading',
+ savedAt: null,
+ rev: null,
+ error: null,
+ demo: false,
+}))
+
+export const serverStorage = new ServerStorage()
+
+const API_LOGIN = `${import.meta.env.BASE_URL}api/login.php`
+const LEGACY_KEYS = ['house-planner', 'house-planner:working', 'house-planner:versions']
+const MERGE_KEYS = ['walls', 'openings', 'furniture', 'materials'] as const
+
+const sync = useSyncStore.setState
+
+let confirmed: Plan | null = null
+let loading = false
+let inFlight = false
+let started = false
+let nextAuthor: string | null = null
+
+function purgeLocalPlans() {
+ try {
+ for (const k of LEGACY_KEYS) localStorage.removeItem(k)
+ } catch {
+ return
+ }
+}
+
+function applyServer(plan: Plan, rev: number, fit: boolean) {
+ confirmed = plan
+ loading = true
+ usePlanStore.getState().loadPlan(plan, { fit })
+ loading = false
+ sync({ rev, status: 'saved', savedAt: plan.updatedAt ?? new Date().toISOString(), error: null })
+}
+
+function fail(e: unknown) {
+ if (e instanceof AuthError) sync({ status: 'login', error: null })
+ else if (e instanceof OfflineError) sync({ status: 'offline', error: (e as Error).message })
+ else sync({ status: 'error', error: (e as Error).message })
+}
+
+export async function loadFromServer(fit = true) {
+ sync({ status: usePlanStore.getState().plan ? useSyncStore.getState().status : 'loading' })
+ try {
+ const { plan, rev, demo } = await serverStorage.load()
+ sync({ demo: !!demo })
+ applyServer(plan, rev, fit)
+ } catch (e) {
+ fail(e)
+ }
+}
+
+export async function login(password: string): Promise<string | null> {
+ try {
+ const res = await fetch(API_LOGIN, {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'fetch' },
+ body: JSON.stringify({ password }),
+ })
+ if (res.status === 401) return t('common:sync.wrongPassword')
+ if (!res.ok) return t('common:sync.loginHttp', { status: res.status })
+ } catch {
+ return t('common:sync.offline')
+ }
+ await loadFromServer(true)
+ return useSyncStore.getState().status === 'login' ? t('common:sync.cookieNotSaved') : null
+}
+
+const byId = <T extends { id: string }>(list: T[] | undefined) => new Map((list ?? []).map((x) => [x.id, x]))
+const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
+
+function mergeOnto(server: Plan, base: Plan, mine: Plan): Plan {
+ const out: Record<string, unknown> = { ...server }
+ for (const key of MERGE_KEYS) {
+ const b = byId(base[key] as { id: string }[])
+ const m = byId(mine[key] as { id: string }[])
+ const s = byId(server[key] as { id: string }[])
+ for (const [id, item] of m) {
+ if (!b.has(id) || !same(b.get(id), item)) s.set(id, item)
+ }
+ for (const id of b.keys()) if (!m.has(id)) s.delete(id)
+ out[key] = [...s.values()]
+ }
+ for (const key of Object.keys(mine) as (keyof Plan)[]) {
+ if ((MERGE_KEYS as readonly string[]).includes(key) || key === 'rev' || key === 'updatedAt' || key === 'author') continue
+ if (!same(mine[key], base[key])) out[key] = mine[key]
+ }
+ const parsed = parsePlan(out)
+ if (!parsed.ok) throw new Error(parsed.error)
+ return parsed.plan
+}
+
+function rollback(message: string) {
+ if (confirmed) {
+ loading = true
+ usePlanStore.getState().loadPlan(confirmed)
+ loading = false
+ }
+ showToast(message)
+}
+
+async function push() {
+ if (inFlight) return
+ const plan = usePlanStore.getState().plan
+ const { rev } = useSyncStore.getState()
+ if (!plan || !confirmed || rev === null || plan === confirmed) return
+ if (isViewOnly()) {
+ loading = true
+ usePlanStore.getState().loadPlan(confirmed)
+ loading = false
+ return
+ }
+ inFlight = true
+ sync({ status: 'saving' })
+ const base = confirmed
+ try {
+ let saved
+ const author = nextAuthor ?? 'web'
+ nextAuthor = null
+ try {
+ saved = await serverStorage.save(plan, rev, author)
+ } catch (e) {
+ if (!(e instanceof ConflictError)) throw e
+ let merged: Plan
+ try {
+ merged = mergeOnto(e.plan, base, plan)
+ } catch {
+ inFlight = false
+ applyServer(e.plan, e.rev, false)
+ showToast(t('common:sync.planChanged'))
+ return
+ }
+ try {
+ saved = await serverStorage.save(merged, e.rev, author)
+ } catch {
+ inFlight = false
+ applyServer(e.plan, e.rev, false)
+ showToast(t('common:sync.planChanged'))
+ return
+ }
+ confirmed = { ...merged, rev: saved.rev, updatedAt: saved.updatedAt }
+ sync({ rev: saved.rev, savedAt: saved.updatedAt, status: 'saved' })
+ inFlight = false
+ if (usePlanStore.getState().plan === plan) {
+ loading = true
+ usePlanStore.getState().commit(merged)
+ loading = false
+ const current = usePlanStore.getState().plan
+ if (current) confirmed = current
+ } else void push()
+ return
+ }
+ const current = usePlanStore.getState().plan
+ confirmed = plan
+ sync({ rev: saved.rev, savedAt: saved.updatedAt, status: 'saved' })
+ inFlight = false
+ if (current !== plan) void push()
+ } catch (e) {
+ inFlight = false
+ if (e instanceof OutdatedError) {
+ reloadOutdated()
+ return
+ }
+ const reason = useSyncStore.getState().demo ? (e as Error).message : ''
+ rollback(reason ? t('common:sync.saveFailedReason', { reason }) : t('common:sync.saveFailed'))
+ if (e instanceof AuthError) sync({ status: 'login' })
+ else sync({ status: 'saved' })
+ }
+}
+
+let reloading = false
+function reloadOutdated() {
+ if (reloading) return
+ reloading = true
+ showToast(t('common:sync.siteUpdated'))
+ setTimeout(() => location.reload(), 1000)
+}
+
+function currentBundle() {
+ const el = document.querySelector<HTMLScriptElement>('script[type="module"][src*="assets/index-"]')
+ return el?.getAttribute('src')?.match(/assets\/index-[^"'?]+\.js/)?.[0] ?? null
+}
+
+async function checkBundle() {
+ const mine = currentBundle()
+ if (!mine || isBusy() || inFlight) return
+ try {
+ const res = await fetch(`${import.meta.env.BASE_URL}index.html`, { cache: 'no-store' })
+ const html = await res.text()
+ const latest = html.match(/assets\/index-[^"'?]+\.js/)?.[0]
+ if (latest && latest !== mine && !isBusy()) reloadOutdated()
+ } catch {
+ return
+ }
+}
+
+async function refreshIfStale() {
+ void checkBundle()
+ if (inFlight || !confirmed || useSyncStore.getState().status === 'login' || usePlanStore.getState().versionPreview) return
+ try {
+ const { plan, rev, demo } = await serverStorage.load()
+ sync({ demo: !!demo })
+ if (rev !== useSyncStore.getState().rev && !inFlight) applyServer(plan, rev, false)
+ } catch (e) {
+ if (e instanceof AuthError) sync({ status: 'login' })
+ }
+}
+
+export function startSync() {
+ if (started) return
+ started = true
+ purgeLocalPlans()
+ usePlanStore.subscribe((s, prev) => {
+ if (s.plan !== prev.plan && !loading && s.plan && !s.versionPreview && !prev.versionPreview) void push()
+ })
+ window.addEventListener('focus', () => void refreshIfStale())
+ document.addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'visible') void refreshIfStale()
+ })
+ window.addEventListener('online', () => {
+ if (useSyncStore.getState().status === 'offline') void loadFromServer(false)
+ })
+ void loadFromServer(true)
+}
+
+export async function listVersions(): Promise<{ source: 'server'; items: VersionInfo[] }> {
+ return { source: 'server', items: await serverStorage.list() }
+}
+
+export async function restoreVersion(rev: number) {
+ const plan = await serverStorage.get(rev)
+ usePlanStore.getState().exitPreview()
+ nextAuthor = `restore:rev${rev}`
+ usePlanStore.getState().commit(plan)
+}
+
+export const listSnapshots = () => serverStorage.snapshots()
+export const saveSnapshot = (name: string) => serverStorage.saveSnapshot(name)
+
+let previewSource: string | null = null
+
+export async function previewSnapshot(id: string, label: string) {
+ const plan = await serverStorage.snapshot(id)
+ previewSource = `restore:${id}`
+ usePlanStore.getState().enterPreview(plan, label)
+}
+
+export async function previewRevision(rev: number) {
+ const plan = await serverStorage.get(rev)
+ previewSource = `restore:rev${rev}`
+ usePlanStore.getState().enterPreview(plan, `#${rev}`)
+}
+
+export function restorePreview() {
+ const st = usePlanStore.getState()
+ const vp = st.versionPreview
+ if (!vp) return
+ const shown = st.plan
+ st.exitPreview()
+ nextAuthor = previewSource
+ previewSource = null
+ if (shown) usePlanStore.getState().commit(shown)
+}
diff --git a/src/storage/types.ts b/src/storage/types.ts
new file mode 100644
index 0000000..03c99b3
--- /dev/null
+++ b/src/storage/types.ts
@@ -0,0 +1,28 @@
+import type { Plan } from '../model'
+
+export type Loaded = { plan: Plan; rev: number; updatedAt?: string; author?: string; demo?: boolean }
+export type Saved = { rev: number; updatedAt: string }
+export type VersionInfo = { rev: number; updatedAt?: string; author?: string; walls?: number; openings?: number }
+
+export interface PlanStorage {
+ readonly kind: 'server' | 'local'
+ load(): Promise<Loaded>
+ save(plan: Plan, baseRev: number, author?: string): Promise<Saved>
+ list(): Promise<VersionInfo[]>
+ get(rev: number): Promise<Plan>
+}
+
+export class ConflictError extends Error {
+ readonly plan: Plan
+ readonly rev: number
+ constructor(plan: Plan, rev: number) {
+ super('conflict')
+ this.plan = plan
+ this.rev = rev
+ }
+}
+
+export class AuthError extends Error {}
+export class UnavailableError extends Error {}
+export class OfflineError extends Error {}
+export class OutdatedError extends Error {}
diff --git a/src/store/planStore.ts b/src/store/planStore.ts
new file mode 100644
index 0000000..05efb01
--- /dev/null
+++ b/src/store/planStore.ts
@@ -0,0 +1,236 @@
+import { create } from 'zustand'
+import { createJSONStorage, persist } from 'zustand/middleware'
+import { temporal } from 'zundo'
+import {
+ DEFAULT_WALL_HEIGHT,
+ DEFAULT_WALL_THICKNESS,
+ clampOpenings,
+ findMaterial,
+ nextId,
+ type Plan,
+ type Point,
+} from '../model'
+import type { Camera } from '../canvas/camera'
+import { isViewOnly } from './viewOnly'
+import { deletePlan, movePlan, pruneSel, rotatePlan, selCenter, selSize, type Selection } from '../canvas/selection/model'
+
+export type Tool = 'select' | 'wall' | 'door' | 'window' | 'measure' | 'zone' | 'building'
+export type DoorPreset = 'entry' | 'interior' | 'gate'
+
+export type PlanState = {
+ plan: Plan | null
+ tool: Tool
+ selectedWallId: string | null
+ selectedOpeningId: string | null
+ selectedFurnitureId: string | null
+ selectedZoneId: string | null
+ selectZone: (id: string | null) => void
+ selectFurniture: (id: string | null) => void
+ furniturePanel: boolean
+ aligning: boolean
+ versionPreview: { label: string; real: Plan } | null
+ enterPreview: (plan: Plan, label: string) => void
+ exitPreview: () => Plan | null
+ showDims: boolean
+ setShowDims: (on: boolean) => void
+ summaryTab: 'general' | 'materials'
+ setSummaryTab: (t: 'general' | 'materials') => void
+ summaryOpen: boolean
+ setSummaryOpen: (open: boolean) => void
+ setAligning: (on: boolean) => void
+ setFurniturePanel: (open: boolean) => void
+ doorPreset: DoorPreset
+ setDoorPreset: (p: DoorPreset) => void
+ selectOpening: (id: string | null) => void
+ activeMaterialId: string | null
+ cam: Camera | null
+ underlay: { on: boolean; opacity: number }
+ setUnderlay: (u: Partial<{ on: boolean; opacity: number }>) => void
+ fitNonce: number
+ requestFit: () => void
+ setCam: (cam: Camera) => void
+ setTool: (tool: Tool) => void
+ setActiveMaterial: (id: string | null) => void
+ selectWall: (id: string | null) => void
+ loadPlan: (plan: Plan, opts?: { fit?: boolean }) => void
+ commit: (plan: Plan) => void
+ addWall: (a: Point, b: Point) => string | null
+ deleteWall: (id: string) => void
+ group: Selection | null
+ setGroup: (s: Selection | null) => void
+ moveGroup: (dx: number, dy: number) => void
+ rotateGroup: (deg: number, center?: Point) => void
+ deleteGroup: () => void
+}
+
+export const usePlanStore = create<PlanState>()(
+ temporal(
+ persist(
+ (set, get) => ({
+ plan: null,
+ tool: 'select',
+ selectedWallId: null,
+ selectedOpeningId: null,
+ selectedFurnitureId: null,
+ selectedZoneId: null,
+ furniturePanel: false,
+ aligning: false,
+ versionPreview: null,
+ showDims: false,
+ summaryTab: 'general',
+ summaryOpen: false,
+ doorPreset: 'entry',
+ activeMaterialId: null,
+ cam: null,
+ underlay: { on: false, opacity: 0.8 },
+ fitNonce: 0,
+ group: null,
+
+ requestFit: () => set({ fitNonce: get().fitNonce + 1 }),
+ setCam: (cam) => set({ cam }),
+ setUnderlay: (u) => set({ underlay: { ...get().underlay, ...u } }),
+ setTool: (tool) => set({ tool }),
+ setActiveMaterial: (activeMaterialId) => set({ activeMaterialId }),
+ selectWall: (selectedWallId) => set({ selectedWallId, selectedOpeningId: null, selectedFurnitureId: null, selectedZoneId: null, group: null }),
+ selectOpening: (selectedOpeningId) => set({ selectedOpeningId, selectedWallId: null, selectedFurnitureId: null, selectedZoneId: null, group: null }),
+ selectFurniture: (selectedFurnitureId) => set({ selectedFurnitureId, selectedWallId: null, selectedOpeningId: null, selectedZoneId: null, group: null }),
+ selectZone: (selectedZoneId) => set({ selectedZoneId, selectedWallId: null, selectedOpeningId: null, selectedFurnitureId: null, group: null }),
+ setFurniturePanel: (furniturePanel) => set({ furniturePanel }),
+ setAligning: (aligning) => set({ aligning }),
+ enterPreview: (preview, label) => {
+ const { plan, versionPreview } = get()
+ const real = versionPreview?.real ?? plan
+ if (!real) return
+ usePlanStore.temporal.getState().pause()
+ set({ versionPreview: { label, real }, plan: preview, selectedWallId: null, selectedOpeningId: null, selectedFurnitureId: null })
+ usePlanStore.temporal.getState().resume()
+ },
+ exitPreview: () => {
+ const vp = get().versionPreview
+ if (!vp) return null
+ usePlanStore.temporal.getState().pause()
+ set({ versionPreview: null, plan: vp.real })
+ usePlanStore.temporal.getState().resume()
+ return vp.real
+ },
+ setShowDims: (showDims) => set({ showDims }),
+ setSummaryTab: (summaryTab) => set({ summaryTab }),
+ setSummaryOpen: (summaryOpen) => set({ summaryOpen }),
+ setDoorPreset: (doorPreset) => set({ doorPreset }),
+
+ loadPlan: (plan, opts) => {
+ const { activeMaterialId, selectedWallId, fitNonce } = get()
+ usePlanStore.temporal.getState().pause()
+ set({
+ plan,
+ selectedWallId: plan.walls.some((w) => w.id === selectedWallId) ? selectedWallId : null,
+ activeMaterialId: plan.materials.some((m) => m.id === activeMaterialId)
+ ? activeMaterialId
+ : (plan.materials[0]?.id ?? null),
+ fitNonce: opts?.fit ? fitNonce + 1 : fitNonce,
+ })
+ usePlanStore.temporal.getState().resume()
+ usePlanStore.temporal.getState().clear()
+ },
+
+ commit: (plan) => {
+ if (isViewOnly() || get().versionPreview) return
+ const next = clampOpenings(plan)
+ const selected = get().selectedWallId
+ const op = get().selectedOpeningId
+ set({
+ plan: next,
+ selectedWallId: selected && next.walls.some((w) => w.id === selected) ? selected : null,
+ selectedOpeningId: op && next.openings.some((o) => o.id === op) ? op : null,
+ selectedFurnitureId:
+ get().selectedFurnitureId && next.furniture.some((f) => f.id === get().selectedFurnitureId)
+ ? get().selectedFurnitureId
+ : null,
+ group: get().group ? pruneSel(next, get().group as Selection) : null,
+ })
+ },
+
+ setGroup: (s) => {
+ const one = s && selSize(s) === 1 && s.rooms.length === 0
+ if (one) {
+ if (s.walls[0]) get().selectWall(s.walls[0])
+ else if (s.openings[0]) get().selectOpening(s.openings[0])
+ else get().selectFurniture(s.furniture[0])
+ return
+ }
+ set({ group: s && selSize(s) > 0 ? s : null, selectedWallId: null, selectedOpeningId: null, selectedFurnitureId: null })
+ },
+
+ moveGroup: (dx, dy) => {
+ const { plan, group } = get()
+ if (!plan || !group || (!dx && !dy)) return
+ get().commit(movePlan(plan, group, { x: dx, y: dy }))
+ },
+
+ rotateGroup: (deg, center) => {
+ const { plan, group } = get()
+ const c = plan && group ? (center ?? selCenter(plan, group)) : null
+ if (!plan || !group || !c || !deg) return
+ get().commit(rotatePlan(plan, group, deg, c))
+ },
+
+ deleteGroup: () => {
+ const { plan, group } = get()
+ if (!plan || !group) return
+ get().commit(deletePlan(plan, group))
+ set({ group: null })
+ },
+
+ addWall: (a, b) => {
+ if (isViewOnly() || get().versionPreview) return null
+ const plan = get().plan
+ if (!plan || (a.x === b.x && a.y === b.y)) return null
+ const material = findMaterial(plan, get().activeMaterialId ?? undefined)
+ const id = nextId('w', plan.walls)
+ const wall = {
+ id,
+ a,
+ b,
+ thickness: material?.thickness ?? DEFAULT_WALL_THICKNESS,
+ height: plan.walls.at(-1)?.height ?? DEFAULT_WALL_HEIGHT,
+ ...(material ? { materialId: material.id } : {}),
+ }
+ set({ plan: { ...plan, walls: [...plan.walls, wall] } })
+ return id
+ },
+
+ deleteWall: (id) => {
+ if (isViewOnly() || get().versionPreview) return
+ const plan = get().plan
+ if (!plan) return
+ set({
+ plan: {
+ ...plan,
+ walls: plan.walls.filter((w) => w.id !== id),
+ openings: plan.openings.filter((o) => o.wallId !== id),
+ },
+ selectedWallId: get().selectedWallId === id ? null : get().selectedWallId,
+ })
+ },
+ }),
+ {
+ name: 'house-planner:ui',
+ version: 2,
+ storage: createJSONStorage(() => localStorage),
+ partialize: (s) => ({ tool: s.tool, activeMaterialId: s.activeMaterialId, cam: s.cam, underlay: s.underlay, doorPreset: s.doorPreset, furniturePanel: s.furniturePanel, summaryTab: s.summaryTab, showDims: s.showDims }),
+ },
+ ),
+ {
+ partialize: (s) => ({ plan: s.plan }),
+ equality: (a, b) => a.plan === b.plan,
+ limit: 200,
+ },
+ ),
+)
+
+export const undo = () => {
+ if (!isViewOnly()) usePlanStore.temporal.getState().undo()
+}
+export const redo = () => {
+ if (!isViewOnly()) usePlanStore.temporal.getState().redo()
+}
diff --git a/src/store/viewOnly.ts b/src/store/viewOnly.ts
new file mode 100644
index 0000000..a3a741f
--- /dev/null
+++ b/src/store/viewOnly.ts
@@ -0,0 +1,18 @@
+import { useSyncExternalStore } from 'react'
+
+const QUERY = '(max-width: 699px), (pointer: coarse) and (not (any-pointer: fine))'
+
+const media = () => (typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(QUERY) : null)
+
+export const isViewOnly = () => !!media()?.matches
+
+export const useViewOnly = () =>
+ useSyncExternalStore(
+ (cb) => {
+ const q = media()
+ q?.addEventListener('change', cb)
+ return () => q?.removeEventListener('change', cb)
+ },
+ isViewOnly,
+ () => false,
+ )
diff --git a/src/styles/tokens.css b/src/styles/tokens.css
new file mode 100644
index 0000000..d4fb3b4
--- /dev/null
+++ b/src/styles/tokens.css
@@ -0,0 +1,53 @@
+:root {
+ --bg: #f3f1ec;
+ --surface: #ffffff;
+ --surface-2: #f7f4f0;
+ --surface-3: #f4f1ec;
+ --card: var(--surface);
+ --ink: #2b2d33;
+ --ink-2: #4a4e57;
+ --muted: #8a8f98;
+ --line: #ece8e1;
+ --line-strong: #d8d2c8;
+ --accent: #f26b1d;
+ --accent-hover: #e05e12;
+ --accent-soft: #fff1e8;
+ --accent-ink: #b4581a;
+ --danger: #d9412b;
+ --danger-soft: #fdf0ee;
+ --ok: #2f9e5b;
+ --ok-soft: #eaf6ef;
+ --warn: #d98a1d;
+ --warn-soft: #fff4e2;
+ --radius-xs: 6px;
+ --radius-sm: 9px;
+ --radius: 12px;
+ --radius-lg: 16px;
+ --radius-pill: 999px;
+ --shadow-sm: 0 1px 3px rgba(40, 30, 20, 0.12);
+ --shadow: 0 1px 2px rgba(40, 30, 20, 0.06), 0 8px 24px rgba(40, 30, 20, 0.08);
+ --shadow-lg: 0 2px 4px rgba(40, 30, 20, 0.06), 0 16px 40px rgba(40, 30, 20, 0.14);
+ --space-1: 4px;
+ --space-2: 8px;
+ --space-3: 12px;
+ --space-4: 16px;
+ --space-5: 24px;
+ --space-6: 32px;
+ --font: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+ --font-mono: ui-monospace, 'SF Mono', Menlo, monospace;
+ --text-xs: 11px;
+ --text-sm: 12.5px;
+ --text-md: 14px;
+ --text-lg: 17px;
+ --text-xl: 22px;
+ --control-h-sm: 28px;
+ --control-h: 32px;
+ --control-h-lg: 38px;
+ --header-h: 52px;
+ --header-top: 10px;
+ --chrome-top: calc(var(--header-top) + var(--header-h) + var(--space-3));
+ --ruler: 24px;
+ --z-chrome: 5;
+ --z-popover: 20;
+ color-scheme: light;
+}
diff --git a/src/styles/ui.css b/src/styles/ui.css
new file mode 100644
index 0000000..fd66240
--- /dev/null
+++ b/src/styles/ui.css
@@ -0,0 +1,600 @@
+html {
+ font: var(--text-md) / 1.4 var(--font);
+ color: var(--ink);
+ background: var(--bg);
+ -webkit-font-smoothing: antialiased;
+}
+
+.card {
+ background: var(--surface);
+ border-radius: var(--radius-lg);
+ box-shadow: var(--shadow);
+}
+
+.card--padded {
+ padding: var(--space-4);
+}
+
+.eyebrow {
+ color: var(--muted);
+ font-size: var(--text-xs);
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+.muted {
+ color: var(--muted);
+ font-size: 13px;
+}
+
+.num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.panel {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.panel__head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: var(--space-3);
+ padding: var(--space-4) var(--space-4) var(--space-2);
+}
+
+.panel__title {
+ font-size: var(--text-lg);
+ font-weight: 650;
+}
+
+.panel__actions {
+ display: flex;
+ gap: var(--space-1);
+}
+
+.panel__body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: var(--space-2) var(--space-4) var(--space-4);
+}
+
+.panel__foot {
+ padding: var(--space-3) var(--space-4);
+ border-top: 1px solid var(--line);
+}
+
+.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: var(--control-h);
+ padding: 0 12px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+ color: var(--ink);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 550;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+}
+
+.btn--sm {
+ height: var(--control-h-sm);
+ padding: 0 10px;
+ font-size: 12.5px;
+}
+
+.btn:hover:not(:disabled),
+.btn--pressed {
+ border-color: var(--line-strong);
+ background: #faf8f5;
+}
+
+.btn:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+
+.btn--primary,
+.btn--primary:hover:not(:disabled) {
+ border-color: var(--accent);
+ background: var(--accent);
+ color: #fff;
+}
+
+.btn--primary:hover:not(:disabled) {
+ background: var(--accent-hover);
+}
+
+.btn--ghost {
+ border-color: transparent;
+ background: transparent;
+ color: var(--ink-2);
+}
+
+.btn--ghost:hover:not(:disabled) {
+ border-color: transparent;
+ background: var(--surface-2);
+}
+
+.btn--danger {
+ color: var(--danger);
+}
+
+.btn--danger:hover:not(:disabled) {
+ border-color: #f3c9c2;
+ background: var(--danger-soft);
+}
+
+.btn__icon {
+ display: inline-flex;
+}
+
+.icon-btn {
+ display: inline-grid;
+ place-items: center;
+ width: var(--control-h);
+ height: var(--control-h);
+ padding: 0;
+ border: 0;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--ink-2);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+
+.icon-btn--sm {
+ width: var(--control-h-sm);
+ height: var(--control-h-sm);
+}
+
+.icon-btn:hover:not(:disabled) {
+ background: var(--surface-2);
+ color: var(--ink);
+}
+
+.icon-btn--active,
+.icon-btn--active:hover:not(:disabled) {
+ background: var(--accent);
+ color: #fff;
+}
+
+.icon-btn:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
+.icon-btn svg {
+ width: 18px;
+ height: 18px;
+}
+
+.segmented {
+ display: inline-flex;
+ flex: none;
+ gap: 2px;
+ height: 36px;
+ padding: 3px;
+ border-radius: 10px;
+ background: var(--surface-3);
+}
+
+.segmented--sm {
+ height: 30px;
+}
+
+.segmented__item {
+ display: inline-flex;
+ align-items: center;
+ padding: 0 12px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--muted);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ white-space: nowrap;
+ cursor: pointer;
+}
+
+.segmented--sm .segmented__item {
+ padding: 0 9px;
+ font-size: 12px;
+}
+
+.segmented__item:hover {
+ color: var(--ink);
+ text-decoration: none;
+}
+
+.segmented__item--active,
+.segmented__item--active:hover {
+ background: var(--surface);
+ color: var(--ink);
+ box-shadow: var(--shadow-sm);
+}
+
+.badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 20px;
+ padding: 0 8px;
+ border-radius: var(--radius-pill);
+ background: var(--surface-3);
+ color: var(--ink-2);
+ font-size: var(--text-xs);
+ font-weight: 600;
+ white-space: nowrap;
+}
+
+.badge--accent {
+ background: var(--accent-soft);
+ color: var(--accent);
+}
+
+.badge--ok {
+ background: var(--ok-soft);
+ color: var(--ok);
+}
+
+.badge--warn {
+ background: var(--warn-soft);
+ color: var(--accent-ink);
+}
+
+.badge--danger {
+ background: var(--danger-soft);
+ color: var(--danger);
+}
+
+.field {
+ display: inline-flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.field__label {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.input {
+ display: inline-flex;
+ align-items: center;
+ height: var(--control-h);
+ padding: 0 8px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+ transition: border-color 0.15s, box-shadow 0.15s;
+}
+
+.input--sm {
+ height: var(--control-h-sm);
+ border-radius: var(--radius-xs);
+}
+
+.input:focus-within {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+}
+
+.input--invalid {
+ border-color: var(--danger);
+}
+
+.input__control {
+ width: 100%;
+ min-width: 0;
+ height: 100%;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ font: inherit;
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+}
+
+.input__suffix {
+ flex: none;
+ margin-left: 4px;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.checkbox {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ user-select: none;
+}
+
+.checkbox__control {
+ position: absolute;
+ opacity: 0;
+ pointer-events: none;
+}
+
+.checkbox__box {
+ width: 16px;
+ height: 16px;
+ flex: none;
+ border: 1.5px solid var(--line-strong);
+ border-radius: 5px;
+ background: var(--surface);
+ transition: background 0.15s, border-color 0.15s;
+}
+
+.checkbox__control:checked + .checkbox__box {
+ border-color: var(--accent);
+ background: var(--accent)
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")
+ center / 14px no-repeat;
+}
+
+.checkbox__control:focus-visible + .checkbox__box {
+ box-shadow: 0 0 0 3px var(--accent-soft);
+}
+
+.table-wrap {
+ overflow: auto;
+}
+
+.table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 13px;
+}
+
+.table th {
+ position: sticky;
+ top: 0;
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--line);
+ background: var(--surface);
+ color: var(--muted);
+ font-size: var(--text-xs);
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-align: left;
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+
+.table td {
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--line);
+ vertical-align: middle;
+}
+
+.table--dense th,
+.table--dense td {
+ padding: 5px 8px;
+}
+
+.table tbody tr:hover td {
+ background: #fcfbf9;
+}
+
+.table__row--muted td {
+ color: var(--muted);
+}
+
+.table th.num {
+ text-align: right;
+}
+
+.canvas-toolbar {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 6px;
+ border-radius: 14px;
+ z-index: var(--z-chrome);
+}
+
+.canvas-toolbar--column {
+ flex-direction: column;
+}
+
+.canvas-toolbar--top-left {
+ top: var(--chrome-top);
+ left: var(--chrome-left, 12px);
+}
+
+.canvas-toolbar--top-right {
+ top: var(--chrome-top);
+ right: 12px;
+}
+
+.canvas-toolbar--top-center {
+ top: var(--chrome-top);
+ left: 50%;
+ transform: translateX(-50%);
+}
+
+.canvas-toolbar--bottom-left {
+ bottom: 12px;
+ left: var(--chrome-left, 12px);
+}
+
+.canvas-toolbar--bottom-right {
+ right: 12px;
+ bottom: 12px;
+}
+
+.canvas-toolbar--bottom-center {
+ bottom: 12px;
+ left: 50%;
+ transform: translateX(-50%);
+}
+
+.canvas-toolbar__sep {
+ align-self: stretch;
+ width: 1px;
+ margin: 4px 2px;
+ background: var(--line);
+}
+
+.canvas-toolbar--column .canvas-toolbar__sep {
+ width: auto;
+ height: 1px;
+ margin: 2px 4px;
+}
+
+.menu {
+ position: relative;
+}
+
+.menu__panel {
+ position: absolute;
+ top: calc(100% + 8px);
+ max-height: 70vh;
+ overflow: auto;
+ padding: 6px;
+ box-shadow: var(--shadow-lg);
+ z-index: var(--z-popover);
+}
+
+.menu__panel--right {
+ right: 0;
+}
+
+.menu__panel--left {
+ left: 0;
+}
+
+.menu__section + .menu__section {
+ margin-top: 4px;
+ padding-top: 4px;
+ border-top: 1px solid var(--line);
+}
+
+.menu__title {
+ padding: 6px 8px 4px;
+}
+
+.menu__item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ width: 100%;
+ min-height: 32px;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--ink);
+ font: inherit;
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+}
+
+.menu__item:hover:not(:disabled) {
+ background: var(--surface-2);
+}
+
+.menu__item:disabled {
+ color: var(--muted);
+ cursor: default;
+}
+
+.menu__label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.menu__hint {
+ flex: none;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.menu__scroll {
+ max-height: 320px;
+ overflow: auto;
+}
+
+.menu__note {
+ padding: 6px 8px;
+ color: var(--muted);
+ font-size: 12.5px;
+}
+
+.menu__note--error {
+ color: var(--danger);
+}
+
+.is-demo {
+ --demo-h: 24px;
+}
+
+.is-demo #root {
+ height: calc(100% - var(--demo-h));
+ margin-top: var(--demo-h);
+}
+
+.demo-banner {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ z-index: 100;
+ height: var(--demo-h, 24px);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 0 12px;
+ background: var(--accent-soft);
+ color: var(--accent-ink);
+ border-bottom: 1px solid var(--line);
+ font-size: 12px;
+ white-space: nowrap;
+}
+
+.demo-banner__text {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.demo-banner__text--short {
+ display: none;
+}
+
+@media (max-width: 760px) {
+ .demo-banner__text--long {
+ display: none;
+ }
+
+ .demo-banner__text--short {
+ display: inline;
+ }
+}
+
+.demo-banner__link {
+ flex: none;
+ color: var(--accent-ink);
+ font-weight: 600;
+}
diff --git a/src/ui/Badge.tsx b/src/ui/Badge.tsx
new file mode 100644
index 0000000..517b712
--- /dev/null
+++ b/src/ui/Badge.tsx
@@ -0,0 +1,8 @@
+import type { HTMLAttributes } from 'react'
+import { cx } from './cx'
+
+export type BadgeTone = 'neutral' | 'accent' | 'ok' | 'warn' | 'danger'
+
+export function Badge({ tone = 'neutral', className, ...rest }: HTMLAttributes<HTMLSpanElement> & { tone?: BadgeTone }) {
+ return <span className={cx('badge', `badge--${tone}`, className)} {...rest} />
+}
diff --git a/src/ui/Button.tsx b/src/ui/Button.tsx
new file mode 100644
index 0000000..1c5e7b0
--- /dev/null
+++ b/src/ui/Button.tsx
@@ -0,0 +1,23 @@
+import type { ButtonHTMLAttributes, ReactNode } from 'react'
+import { cx } from './cx'
+
+export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
+ variant?: 'default' | 'primary' | 'ghost' | 'danger'
+ size?: 'sm' | 'md'
+ pressed?: boolean
+ icon?: ReactNode
+}
+
+export function Button({ variant = 'default', size = 'md', pressed, icon, className, children, type = 'button', ...rest }: ButtonProps) {
+ return (
+ <button
+ type={type}
+ className={cx('btn', `btn--${variant}`, size === 'sm' && 'btn--sm', pressed && 'btn--pressed', className)}
+ aria-pressed={pressed}
+ {...rest}
+ >
+ {icon && <span className="btn__icon">{icon}</span>}
+ {children}
+ </button>
+ )
+}
diff --git a/src/ui/CanvasToolbar.tsx b/src/ui/CanvasToolbar.tsx
new file mode 100644
index 0000000..11e2adf
--- /dev/null
+++ b/src/ui/CanvasToolbar.tsx
@@ -0,0 +1,22 @@
+import type { HTMLAttributes } from 'react'
+import { cx } from './cx'
+
+export type ToolbarPlacement = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top-center' | 'bottom-center'
+
+type Props = HTMLAttributes<HTMLDivElement> & {
+ placement?: ToolbarPlacement
+ direction?: 'row' | 'column'
+}
+
+export function CanvasToolbar({ placement = 'top-left', direction = 'row', className, ...rest }: Props) {
+ return (
+ <div
+ className={cx('card', 'canvas-toolbar', `canvas-toolbar--${placement}`, `canvas-toolbar--${direction}`, className)}
+ {...rest}
+ />
+ )
+}
+
+export function ToolbarSeparator() {
+ return <span className="canvas-toolbar__sep" aria-hidden />
+}
diff --git a/src/ui/Card.tsx b/src/ui/Card.tsx
new file mode 100644
index 0000000..b571f30
--- /dev/null
+++ b/src/ui/Card.tsx
@@ -0,0 +1,37 @@
+import type { HTMLAttributes, ReactNode, Ref } from 'react'
+import { cx } from './cx'
+
+export function Card({
+ className,
+ padded = true,
+ ref,
+ ...rest
+}: HTMLAttributes<HTMLDivElement> & { padded?: boolean; ref?: Ref<HTMLDivElement> }) {
+ return <div ref={ref} className={cx('card', padded && 'card--padded', className)} {...rest} />
+}
+
+type PanelProps = Omit<HTMLAttributes<HTMLElement>, 'title'> & {
+ title?: ReactNode
+ eyebrow?: ReactNode
+ actions?: ReactNode
+ footer?: ReactNode
+ ref?: Ref<HTMLElement>
+}
+
+export function Panel({ title, eyebrow, actions, footer, className, children, ref, ...rest }: PanelProps) {
+ return (
+ <section ref={ref} className={cx('card', 'panel', className)} {...rest}>
+ {(title || eyebrow || actions) && (
+ <header className="panel__head">
+ <div className="panel__titles">
+ {eyebrow && <div className="eyebrow">{eyebrow}</div>}
+ {title && <div className="panel__title">{title}</div>}
+ </div>
+ {actions && <div className="panel__actions">{actions}</div>}
+ </header>
+ )}
+ <div className="panel__body">{children}</div>
+ {footer && <footer className="panel__foot">{footer}</footer>}
+ </section>
+ )
+}
diff --git a/src/ui/Checkbox.tsx b/src/ui/Checkbox.tsx
new file mode 100644
index 0000000..7c8bc38
--- /dev/null
+++ b/src/ui/Checkbox.tsx
@@ -0,0 +1,17 @@
+import type { InputHTMLAttributes, ReactNode } from 'react'
+import { cx } from './cx'
+
+export type CheckboxProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'onChange'> & {
+ label?: ReactNode
+ onChange?: (checked: boolean) => void
+}
+
+export function Checkbox({ label, onChange, className, ...rest }: CheckboxProps) {
+ return (
+ <label className={cx('checkbox', className)}>
+ <input type="checkbox" className="checkbox__control" onChange={(e) => onChange?.(e.target.checked)} {...rest} />
+ <span className="checkbox__box" aria-hidden />
+ {label && <span className="checkbox__label">{label}</span>}
+ </label>
+ )
+}
diff --git a/src/ui/DemoBanner.tsx b/src/ui/DemoBanner.tsx
new file mode 100644
index 0000000..aa0a200
--- /dev/null
+++ b/src/ui/DemoBanner.tsx
@@ -0,0 +1,31 @@
+import { useEffect } from 'react'
+import { createPortal } from 'react-dom'
+import { useTranslation } from 'react-i18next'
+import { useSyncStore } from '../storage'
+
+const REPO = 'https://github.com/egmalt/house-planner'
+
+export function DemoBanner() {
+ const { t } = useTranslation()
+ const demo = useSyncStore((s) => s.demo)
+
+ useEffect(() => {
+ if (!demo) return
+ document.documentElement.classList.add('is-demo')
+ return () => document.documentElement.classList.remove('is-demo')
+ }, [demo])
+
+ if (!demo) return null
+ return createPortal(
+ <div className="demo-banner" role="note">
+ <span className="demo-banner__text demo-banner__text--long">
+ {t('demo.long')}
+ </span>
+ <span className="demo-banner__text demo-banner__text--short">{t('demo.short')}</span>
+ <a className="demo-banner__link" href={REPO} target="_blank" rel="noreferrer">
+ GitHub
+ </a>
+ </div>,
+ document.body,
+ )
+}
diff --git a/src/ui/FurniturePanel.tsx b/src/ui/FurniturePanel.tsx
new file mode 100644
index 0000000..8bcd0f8
--- /dev/null
+++ b/src/ui/FurniturePanel.tsx
@@ -0,0 +1,94 @@
+import { useTranslation } from 'react-i18next'
+import { FURNITURE_CATALOG, FURNITURE_CATEGORIES, resolveFurniture } from '../furniture/catalog'
+import { FurnitureIcon } from '../furniture/icons'
+import { toWorld } from '../canvas/camera'
+import { addFurniture, distanceToSegment, snapOffset, type Plan, type Point } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { IconButton } from './IconButton'
+import { Panel } from './Card'
+
+function freeSpot(plan: Plan, center: Point, w: number, d: number): Point {
+ const r = Math.hypot(w, d) / 2
+ const fits = (p: Point) =>
+ plan.furniture.every((f) => {
+ const o = resolveFurniture(f)
+ return Math.hypot(f.x - p.x, f.y - p.y) > (r + Math.hypot(o.w, o.d) / 2) * 0.85
+ }) && plan.walls.every((wall) => distanceToSegment(p, wall.a, wall.b) > Math.max(w, d) / 2 + wall.thickness / 2 + 50)
+ const step = Math.max(300, Math.min(w, d) / 2)
+ for (let ring = 0; ring <= 20; ring += 1) {
+ for (let i = -ring; i <= ring; i += 1) {
+ for (const [dx, dy] of [[i, -ring], [i, ring], [-ring, i], [ring, i]]) {
+ const p = { x: center.x + dx * step, y: center.y + dy * step }
+ if (fits(p)) return p
+ }
+ }
+ }
+ return center
+}
+
+export function FurniturePanel() {
+ const { t } = useTranslation('plan')
+ const open = usePlanStore((s) => s.furniturePanel)
+ const setOpen = usePlanStore((s) => s.setFurniturePanel)
+ const viewOnly = useViewOnly()
+ if (!open || viewOnly) return null
+
+ const place = (type: string) => {
+ const { plan, cam, commit, selectFurniture, setTool } = usePlanStore.getState()
+ if (!plan) return
+ const center = cam
+ ? toWorld(cam, { x: window.innerWidth / 2, y: window.innerHeight / 2 })
+ : { x: plan.site.width / 2, y: plan.site.depth / 2 }
+ const size = resolveFurniture({ type })
+ const at = freeSpot(plan, center, size.w, size.d)
+ const res = addFurniture(plan, { type, x: snapOffset(at.x), y: snapOffset(at.y), rotationDeg: 0 })
+ commit(res.plan)
+ setTool('select')
+ selectFurniture(res.id)
+ }
+
+ return (
+ <Panel
+ className="furniture-panel"
+ eyebrow={t('furniturePanel.eyebrow')}
+ title={t('furniturePanel.title')}
+ actions={
+ <IconButton label={t('close')} size="sm" onClick={() => setOpen(false)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ }
+ footer={<span className="muted">{t('furniturePanel.hint')}</span>}
+ >
+ {FURNITURE_CATEGORIES.map((c) => {
+ const items = FURNITURE_CATALOG.filter((d) => d.category === c.id)
+ if (items.length === 0) return null
+ return (
+ <section key={c.id} className="furniture-panel__group">
+ <div className="eyebrow">{c.name}</div>
+ <div className="furniture-panel__grid">
+ {items.map((d) => (
+ <button
+ key={d.type}
+ className="furniture-panel__item"
+ draggable
+ title={`${d.name}, ${d.w}×${d.d} ${t('common:units.mm')}`}
+ onDragStart={(e) => {
+ e.dataTransfer.setData('text/x-furniture', d.type)
+ e.dataTransfer.effectAllowed = 'copy'
+ }}
+ onClick={() => place(d.type)}
+ >
+ <FurnitureIcon type={d.type} size={40} />
+ <span className="furniture-panel__name">{d.name}</span>
+ </button>
+ ))}
+ </div>
+ </section>
+ )
+ })}
+ </Panel>
+ )
+}
diff --git a/src/ui/GridLegend.tsx b/src/ui/GridLegend.tsx
new file mode 100644
index 0000000..2a751f9
--- /dev/null
+++ b/src/ui/GridLegend.tsx
@@ -0,0 +1,17 @@
+import { gridSteps } from '../canvas/camera'
+import { useTranslation } from 'react-i18next'
+import { formatNumber } from '../model'
+import { t as tr } from '../i18n'
+
+const size = (mm: number) => (mm >= 1000 ? `${formatNumber(mm / 1000, 2)} ${tr('common:units.m')}` : `${formatNumber(mm / 10, 1)} ${tr('common:units.cm')}`)
+
+export function GridLegend({ scale }: { scale: number }) {
+ const { t } = useTranslation('common')
+ const { minor, major } = gridSteps(scale)
+ return (
+ <span className="grid-legend muted" title={t('grid.title')}>
+ <span className="grid-legend__cell" aria-hidden />
+ {t('grid.legend', { minor: size(minor), major: size(major) })}
+ </span>
+ )
+}
diff --git a/src/ui/Header.tsx b/src/ui/Header.tsx
new file mode 100644
index 0000000..09f353e
--- /dev/null
+++ b/src/ui/Header.tsx
@@ -0,0 +1,52 @@
+import { useTranslation } from 'react-i18next'
+import { formatMeters } from '../model'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { Badge } from './Badge'
+import { DemoBanner } from './DemoBanner'
+import { HeaderMenu } from './HeaderMenu'
+import { SaveIndicator } from './SaveIndicator'
+import { Segmented } from './Segmented'
+import { sectionHref, sections, useNarrow, type SectionId } from './useSection'
+
+const meters = (mm: number) => formatMeters(mm)
+
+
+export function Header({ section }: { section: SectionId }) {
+ const { t } = useTranslation('common')
+ const plan = usePlanStore((s) => s.plan)
+ const narrow = useNarrow()
+ const viewOnly = useViewOnly()
+ const tabs = sections.map((s) => ({
+ value: s.id,
+ label: t(narrow && 'short' in s ? s.short : s.label),
+ href: sectionHref(s.id),
+ }))
+ const subtitle = plan
+ ? t('header.subtitle', {
+ width: meters(plan.site.width),
+ depth: meters(plan.site.depth),
+ walls: t('header.walls', { count: plan.walls.length }),
+ openings: t('header.openings', { count: plan.openings.length }),
+ })
+ : ''
+
+ return (
+ <header className={`header card header--${section}`}>
+ <span className="header__logo" aria-hidden />
+ <div className="header__text" title={plan ? `${plan.name} — ${subtitle}` : undefined}>
+ <span className="header__title">{plan?.name ?? t('header.loadingPlan')}</span>
+ {plan && <span className="header__meta">{subtitle}</span>}
+ </div>
+ {viewOnly && (
+ <Badge tone="neutral" className="header__view">
+ {t('header.viewOnly')}
+ </Badge>
+ )}
+ <SaveIndicator />
+ <Segmented options={tabs} value={section} className="header__tabs" />
+ <HeaderMenu />
+ <DemoBanner />
+ </header>
+ )
+}
diff --git a/src/ui/HeaderMenu.tsx b/src/ui/HeaderMenu.tsx
new file mode 100644
index 0000000..d98175f
--- /dev/null
+++ b/src/ui/HeaderMenu.tsx
@@ -0,0 +1,266 @@
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { fmtDateTime, lang, setLang, type Lang } from '../i18n'
+import {
+ listSnapshots,
+ listVersions,
+ previewRevision,
+ previewSnapshot,
+ restorePreview,
+ restoreVersion,
+ saveSnapshot,
+ type SnapshotInfo,
+ type VersionInfo,
+} from '../storage'
+import { useViewOnly } from '../store/viewOnly'
+import { Button } from './Button'
+import { Input } from './Input'
+import { Segmented } from './Segmented'
+import { usePlanStore } from '../store/planStore'
+import { IconButton } from './IconButton'
+import { Menu, MenuItem, MenuSection } from './Menu'
+import { downloadPlan, readPlanFile } from './planFile'
+
+const when = (iso?: string) => {
+ if (!iso) return ''
+ const d = new Date(iso)
+ return Number.isNaN(d.getTime())
+ ? iso
+ : fmtDateTime(d, { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
+}
+
+type Tab = 'saved' | 'all'
+
+function Versions({ close }: { close: () => void }) {
+ const { t } = useTranslation('common')
+ const viewOnly = useViewOnly()
+ const [tab, setTab] = useState<Tab>('saved')
+ const [revs, setRevs] = useState<VersionInfo[] | null>(null)
+ const [snaps, setSnaps] = useState<SnapshotInfo[] | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [naming, setNaming] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ const load = () => {
+ setError(null)
+ listSnapshots()
+ .then(setSnaps)
+ .catch((e) => {
+ setSnaps([])
+ setError((e as Error).message)
+ })
+ listVersions()
+ .then((r) => setRevs(r.items))
+ .catch((e) => setError((e as Error).message))
+ }
+
+ useEffect(load, [])
+
+ const run = async (fn: () => Promise<unknown>, done = true) => {
+ try {
+ await fn()
+ if (done) close()
+ } catch (e) {
+ setError((e as Error).message)
+ }
+ }
+
+ const today = fmtDateTime(new Date(), { day: '2-digit', month: '2-digit', year: 'numeric' })
+
+ return (
+ <MenuSection>
+ <div className="versions__head">
+ <Segmented
+ size="sm"
+ value={tab}
+ options={[
+ { value: 'saved', label: t('versions.saved') },
+ { value: 'all', label: t('versions.all') },
+ ]}
+ onChange={setTab}
+ />
+ </div>
+ {!viewOnly &&
+ (naming === null ? (
+ <MenuItem onClick={() => setNaming(t('versions.defaultName', { date: today }))} hint={t('versions.snapshot')}>
+ {t('versions.saveVersion')}
+ </MenuItem>
+ ) : (
+ <form
+ className="versions__save"
+ onSubmit={async (e) => {
+ e.preventDefault()
+ if (!naming.trim() || busy) return
+ setBusy(true)
+ await run(() => saveSnapshot(naming.trim()), false)
+ setBusy(false)
+ setNaming(null)
+ setTab('saved')
+ load()
+ }}
+ >
+ <Input size="sm" autoFocus value={naming} onChange={(e) => setNaming(e.target.value)} onFocus={(e) => e.target.select()} />
+ <Button size="sm" variant="primary" type="submit" disabled={busy}>
+ {t('versions.save')}
+ </Button>
+ </form>
+ ))}
+ {error && <div className="menu__note menu__note--error">{error}</div>}
+ <div className="menu__scroll">
+ {tab === 'saved' && (
+ <>
+ {!snaps && <div className="menu__note">{t('versions.loading')}</div>}
+ {snaps && snaps.length === 0 && !error && <div className="menu__note">{t('versions.empty')}</div>}
+ {snaps?.map((v) => (
+ <div key={v.id} className="versions__row">
+ <div className="versions__info">
+ <div className="versions__name">{v.name}</div>
+ <div className="muted">
+ {when(v.createdAt)}
+ {v.rev !== undefined ? ` · rev ${v.rev}` : ''}
+ </div>
+ </div>
+ <div className="versions__actions">
+ <Button size="sm" variant="ghost" onClick={() => void run(() => previewSnapshot(v.id, t('versions.quoted', { name: v.name })))}>
+ {t('versions.open')}
+ </Button>
+ {!viewOnly && (
+ <Button
+ size="sm"
+ onClick={() => {
+ if (window.confirm(t('versions.confirmSnapshot', { name: v.name })))
+ void run(async () => {
+ await previewSnapshot(v.id, v.name)
+ restorePreview()
+ })
+ }}
+ >
+ {t('versions.restore')}
+ </Button>
+ )}
+ </div>
+ </div>
+ ))}
+ </>
+ )}
+ {tab === 'all' && (
+ <>
+ {!revs && !error && <div className="menu__note">{t('versions.loading')}</div>}
+ {revs?.slice(0, 80).map((v, i) => (
+ <div key={v.rev} className="versions__row">
+ <div className="versions__info">
+ <div className="versions__name">
+ #{v.rev} · {when(v.updatedAt)}
+ </div>
+ <div className="muted">
+ {i === 0 ? t('versions.current') : [v.author, v.walls !== undefined ? t('versions.walls', { count: v.walls }) : ''].filter(Boolean).join(' · ')}
+ </div>
+ </div>
+ {i > 0 && (
+ <div className="versions__actions">
+ <Button size="sm" variant="ghost" onClick={() => void run(() => previewRevision(v.rev))}>
+ {t('versions.open')}
+ </Button>
+ {!viewOnly && (
+ <Button
+ size="sm"
+ onClick={() => {
+ if (window.confirm(t('versions.confirmRevision', { rev: v.rev })))
+ void run(() => restoreVersion(v.rev))
+ }}
+ >
+ {t('versions.restore')}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ ))}
+ </>
+ )}
+ </div>
+ </MenuSection>
+ )
+}
+
+export function HeaderMenu() {
+ const { t } = useTranslation('common')
+ const plan = usePlanStore((s) => s.plan)
+ const commit = usePlanStore((s) => s.commit)
+ const fileRef = useRef<HTMLInputElement>(null)
+ const [showVersions, setShowVersions] = useState(false)
+
+ const onImport = async (file: File | undefined) => {
+ if (!file) return
+ const result = await readPlanFile(file)
+ if (result.ok) commit(result.plan)
+ else window.alert(t('menu.importInvalid', { error: result.error }))
+ }
+
+ return (
+ <>
+ <Menu
+ width={400}
+ trigger={({ open, toggle }) => (
+ <IconButton
+ label={t('menu.more')}
+ active={open}
+ onClick={() => {
+ if (!open) setShowVersions(false)
+ toggle()
+ }}
+ >
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
+ <circle cx="5" cy="12" r="1.8" />
+ <circle cx="12" cy="12" r="1.8" />
+ <circle cx="19" cy="12" r="1.8" />
+ </svg>
+ </IconButton>
+ )}
+ >
+ {(close) => (
+ <>
+ <MenuSection title={t('menu.plan')}>
+ <MenuItem disabled={!plan} onClick={() => { if (plan) downloadPlan(plan); close() }} hint=".json">
+ {t('menu.exportJson')}
+ </MenuItem>
+ <MenuItem onClick={() => { fileRef.current?.click(); close() }} hint=".json">
+ {t('menu.importJson')}
+ </MenuItem>
+ <MenuItem onClick={() => setShowVersions((v) => !v)} hint={showVersions ? '▴' : '▾'}>
+ {t('menu.versions')}
+ </MenuItem>
+ </MenuSection>
+ {showVersions && <Versions close={close} />}
+ <MenuSection title={t('language.label')}>
+ <div className="versions__head">
+ <Segmented<Lang>
+ size="sm"
+ value={lang()}
+ options={[
+ { value: 'en', label: t('language.en') },
+ { value: 'ru', label: t('language.ru') },
+ ]}
+ onChange={(l) => {
+ close()
+ void setLang(l)
+ }}
+ />
+ </div>
+ </MenuSection>
+ </>
+ )}
+ </Menu>
+ <input
+ ref={fileRef}
+ type="file"
+ accept="application/json,.json"
+ hidden
+ onChange={(e) => {
+ void onImport(e.target.files?.[0])
+ e.target.value = ''
+ }}
+ />
+ </>
+ )
+}
diff --git a/src/ui/IconButton.tsx b/src/ui/IconButton.tsx
new file mode 100644
index 0000000..9bafe94
--- /dev/null
+++ b/src/ui/IconButton.tsx
@@ -0,0 +1,23 @@
+import type { ButtonHTMLAttributes, ReactNode } from 'react'
+import { cx } from './cx'
+
+export type IconButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children'> & {
+ label: string
+ children: ReactNode
+ active?: boolean
+ size?: 'sm' | 'md'
+}
+
+export function IconButton({ label, children, active, size = 'md', className, type = 'button', ...rest }: IconButtonProps) {
+ return (
+ <button
+ type={type}
+ aria-label={label}
+ title={label}
+ className={cx('icon-btn', size === 'sm' && 'icon-btn--sm', active && 'icon-btn--active', className)}
+ {...rest}
+ >
+ {children}
+ </button>
+ )
+}
diff --git a/src/ui/Input.tsx b/src/ui/Input.tsx
new file mode 100644
index 0000000..b217683
--- /dev/null
+++ b/src/ui/Input.tsx
@@ -0,0 +1,26 @@
+import type { InputHTMLAttributes, ReactNode, Ref } from 'react'
+import { cx } from './cx'
+
+export type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
+ label?: ReactNode
+ suffix?: ReactNode
+ size?: 'sm' | 'md'
+ invalid?: boolean
+ ref?: Ref<HTMLInputElement>
+}
+
+export function Input({ label, suffix, size = 'md', invalid, className, ref, ...rest }: InputProps) {
+ const field = (
+ <span className={cx('input', size === 'sm' && 'input--sm', invalid && 'input--invalid', !label && className)}>
+ <input ref={ref} className="input__control" {...rest} />
+ {suffix && <span className="input__suffix">{suffix}</span>}
+ </span>
+ )
+ if (!label) return field
+ return (
+ <label className={cx('field', className)}>
+ <span className="field__label">{label}</span>
+ {field}
+ </label>
+ )
+}
diff --git a/src/ui/Inspector.tsx b/src/ui/Inspector.tsx
new file mode 100644
index 0000000..98431a6
--- /dev/null
+++ b/src/ui/Inspector.tsx
@@ -0,0 +1,795 @@
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import i18n, { fmtNum, fmtDateTime } from '../i18n'
+import {
+ DEFAULT_WASTE_PCT,
+ computeWallEstimate,
+ findMaterial,
+ fitOffset,
+ formatLength,
+ formatMoney,
+ kindLabels,
+ materialColor,
+ setWallLength,
+ unitLabels,
+ updateOpening,
+ updateFurniture,
+ updateZone,
+ deleteZone,
+ zoneKindLabels,
+ polygonAreaMm2,
+ polygonPerimeter,
+ type Zone,
+ deleteFurniture,
+ normalizeDeg,
+ type Furniture,
+ updateWall,
+ wallLength,
+ wallPanelCount,
+ type Material,
+ type Opening,
+ type Plan,
+ type Wall,
+ type WallEstimateLine,
+} from '../model'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { resolveFurniture } from '../furniture/catalog'
+import { buildingSel, selSummary, streetAlignDeg, type Selection } from '../canvas/selection/model'
+import { PlanSummary as StatsSummary } from '../stats'
+import { Badge } from './Badge'
+import { Button } from './Button'
+import { IconButton } from './IconButton'
+import { Input } from './Input'
+import { LengthField } from './LengthField'
+import { Segmented } from './Segmented'
+import { SewerInspector, SewerSummary, WaterInspector, WaterSummary, useLayers, useSewerSelection, useSewerUi, useWaterSelection, useWaterUi } from '../networks'
+import { ElectricInspector, ElectricSummary, useElectricSelection, useElectricUi } from '../networks/electric'
+import { HeatingInspector, HeatingSummary, useHeatingSelection, useHeatingUi } from '../networks/heating'
+
+export function Inspector() {
+ const plan = usePlanStore((s) => s.plan)
+ const selectedWallId = usePlanStore((s) => s.selectedWallId)
+ const selectedOpeningId = usePlanStore((s) => s.selectedOpeningId)
+ const selectedFurnitureId = usePlanStore((s) => s.selectedFurnitureId)
+ const selectedZoneId = usePlanStore((s) => s.selectedZoneId)
+ const group = usePlanStore((s) => s.group)
+ const viewOnly = useViewOnly()
+ const sewerOn = useLayers((s) => s.sewer)
+ const sewerSel = useSewerSelection(plan)
+ const electricOn = useLayers((s) => s.electric)
+ const electricSel = useElectricSelection(plan)
+ const heatingOn = useLayers((s) => s.heating)
+ const heatingSel = useHeatingSelection(plan)
+ const waterOn = useLayers((s) => s.water)
+ const waterSel = useWaterSelection(plan)
+ if (!plan) return null
+ if (viewOnly) return <SummaryPanel plan={plan} />
+ if (sewerOn && sewerSel) return <SewerInspector plan={plan} sel={sewerSel} />
+ if (waterOn && waterSel) return <WaterInspector plan={plan} sel={waterSel} />
+ if (electricOn && electricSel) return <ElectricInspector plan={plan} sel={electricSel} />
+ if (heatingOn && heatingSel) return <HeatingInspector plan={plan} sel={heatingSel} />
+ if (group) return <GroupInspector plan={plan} group={group} />
+ const item = plan.furniture.find((f) => f.id === selectedFurnitureId)
+ const zone = plan.site.zones?.find((z) => z.id === selectedZoneId)
+ if (zone) return zone.locked ? <LockedZoneInspector zone={zone} /> : <ZoneInspector plan={plan} zone={zone} />
+ if (item) return <FurnitureInspector plan={plan} item={item} />
+ const opening = plan.openings.find((o) => o.id === selectedOpeningId)
+ if (opening) return <OpeningInspector plan={plan} opening={opening} />
+ const wall = plan.walls.find((w) => w.id === selectedWallId)
+ if (wall) return <WallInspector plan={plan} wall={wall} />
+ return <SummaryPanel plan={plan} />
+}
+
+function InspectorClose() {
+ const { t } = useTranslation('plan')
+ const selectWall = usePlanStore((st) => st.selectWall)
+ return (
+ <IconButton label={t('close')} size="sm" className="inspector__close" onClick={() => selectWall(null)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ )
+}
+
+const typeLabel = (type: Opening['type']) => i18n.t(`plan:openingTypes.${type}`)
+
+const panelsDative = (n: number) => {
+ if (!Number.isInteger(Math.round(n * 1000) / 1000)) return i18n.t('plan:wall.panelsFrac', { n: fmt(n) })
+ return i18n.t('plan:wall.panelsDative', { count: Math.round(n) })
+}
+
+const fmt = (v: number, d = 2) => fmtNum(v, d)
+
+export function panelFit(len: number, m?: Material) {
+ if (!m?.panelWidth) return null
+ const n = len / m.panelWidth
+ const half = m.panelWidth / 2
+ const rest = len % half
+ const aligned = rest < 1 || half - rest < 1
+ const down = Math.floor(len / half) * half
+ const up = Math.ceil(len / half) * half
+ return { n, aligned, down, up, frac: n - Math.floor(n), half }
+}
+
+function WallInspector({ plan, wall }: { plan: Plan; wall: Wall }) {
+ const { t } = useTranslation('plan')
+ const commit = usePlanStore((s) => s.commit)
+ const deleteWall = usePlanStore((s) => s.deleteWall)
+ const material = findMaterial(plan, wall.materialId)
+ const openings = plan.openings.filter((o) => o.wallId === wall.id)
+ const len = wallLength(wall)
+ const panels = material ? wallPanelCount(wall, material) : undefined
+ const fit = panelFit(len, material)
+ const selectOpening = usePlanStore((s) => s.selectOpening)
+
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <InspectorClose />
+ <div className="eyebrow">{t('wall.eyebrow')}</div>
+ <div className="inspector__title">{wall.id}</div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('wall.length')}</span>
+ <LengthField value={len} min={100} onCommit={(mm) => commit(setWallLength(plan, wall.id, mm))} />
+ </label>
+ <label className="form__row">
+ <span>{t('wall.thickness')}</span>
+ <LengthField value={wall.thickness} min={10} onCommit={(mm) => commit(updateWall(plan, wall.id, { thickness: mm }))} />
+ </label>
+ <label className="form__row">
+ <span>{t('height')}</span>
+ <LengthField value={wall.height} min={100} onCommit={(mm) => commit(updateWall(plan, wall.id, { height: mm }))} />
+ </label>
+ <label className="form__row">
+ <span>{t('wall.material')}</span>
+ <select
+ className="select form__select"
+ value={wall.materialId ?? ''}
+ onChange={(e) => {
+ const m = findMaterial(plan, e.target.value || undefined)
+ const next = { ...wall, thickness: m?.thickness ?? wall.thickness }
+ delete (next as { materialId?: string }).materialId
+ commit({
+ ...plan,
+ walls: plan.walls.map((w) => (w.id === wall.id ? (m ? { ...next, materialId: m.id } : next) : w)),
+ })
+ }}
+ >
+ <option value="">{t('wall.noMaterial')}</option>
+ {plan.materials.map((m) => (
+ <option key={m.id} value={m.id}>
+ {m.name}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('area')}</dt>
+ <dd>{fmt((len * wall.height) / 1e6)} {t('common:units.m2')}</dd>
+ {panels !== undefined && (
+ <>
+ <dt>{t('wall.panels')}</dt>
+ <dd>{panels} {t('common:units.pcs')}</dd>
+ </>
+ )}
+ <dt>a → b</dt>
+ <dd>
+ {Math.round(wall.a.x)}, {Math.round(wall.a.y)} → {Math.round(wall.b.x)}, {Math.round(wall.b.y)}
+ </dd>
+ </dl>
+ {fit && material && (
+ <div className={`layout-hint ${fit.aligned ? '' : 'layout-hint--warn'}`}>
+ {fit.aligned ? (
+ <>
+ <Badge tone="ok">{t('wall.multipleOf', { panels: panelsDative(fit.n) })}</Badge> {t('wall.panelWidth', { width: material.panelWidth })}
+ </>
+ ) : (
+ <>
+ <Badge tone="warn">{t('wall.extraPanels', { n: fmt(fit.frac) })}</Badge>{' '}
+ {t('wall.notAligned', { half: (material.panelWidth ?? 0) / 2, down: formatLength(fit.down), up: formatLength(fit.up) })}
+ <div className="layout-hint__actions">
+ <Button size="sm" variant="ghost" onClick={() => commit(setWallLength(plan, wall.id, fit.down))}>
+ {formatLength(fit.down)}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => commit(setWallLength(plan, wall.id, fit.up))}>
+ {formatLength(fit.up)}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ {openings.length > 0 && (
+ <div className="inspector__section">
+ <div className="eyebrow">{t('wall.openings')}</div>
+ {openings.map((o) => (
+ <button key={o.id} className="row row--link" onClick={() => selectOpening(o.id)}>
+ <span>
+ {typeLabel(o.type)} {o.id}
+ </span>
+ <span className="muted">
+ {o.width}×{o.height}, {t('wall.fromA', { offset: o.offset })}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ <Button size="sm" onClick={() => usePlanStore.getState().setGroup(buildingSel(plan, wall.id))}>
+ {t('wall.selectBuilding')}
+ </Button>
+ <Button variant="danger" className="inspector__delete" onClick={() => deleteWall(wall.id)}>
+ {t('wall.delete')}
+ </Button>
+ <p className="hint">{t('wall.hint')}</p>
+ </aside>
+ )
+}
+
+function DegField({ onCommit }: { onCommit: (deg: number) => void }) {
+ const [draft, setDraft] = useState('0')
+ const [invalid, setInvalid] = useState(false)
+ const commit = () => {
+ const v = Number(draft.trim().replace(',', '.').replace('−', '-'))
+ if (!Number.isFinite(v)) {
+ setInvalid(true)
+ return
+ }
+ setDraft('0')
+ setInvalid(false)
+ if (v) onCommit(v)
+ }
+ return (
+ <Input
+ size="sm"
+ suffix="°"
+ invalid={invalid}
+ value={draft}
+ onChange={(e) => {
+ setDraft(e.target.value)
+ setInvalid(false)
+ }}
+ onFocus={(e) => e.target.select()}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur()
+ else if (e.key === 'Escape') {
+ setDraft('0')
+ ;(e.target as HTMLInputElement).blur()
+ }
+ }}
+ />
+ )
+}
+
+function GroupInspector({ plan, group }: { plan: Plan; group: Selection }) {
+ const { t } = useTranslation('plan')
+ const moveGroup = usePlanStore((s) => s.moveGroup)
+ const rotateGroup = usePlanStore((s) => s.rotateGroup)
+ const deleteGroup = usePlanStore((s) => s.deleteGroup)
+ const setGroup = usePlanStore((s) => s.setGroup)
+ const street = streetAlignDeg(plan, group)
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <IconButton label={t('group.deselect')} size="sm" className="inspector__close" onClick={() => setGroup(null)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ <div className="eyebrow">{t('group.eyebrow')}</div>
+ <div className="inspector__title">{t('group.selected', { summary: selSummary(group) })}</div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('group.moveX')}</span>
+ <LengthField value={0} min={-1e7} onCommit={(mm) => moveGroup(mm, 0)} />
+ </label>
+ <label className="form__row">
+ <span>{t('group.moveY')}</span>
+ <LengthField value={0} min={-1e7} onCommit={(mm) => moveGroup(0, mm)} />
+ </label>
+ <label className="form__row">
+ <span>{t('group.rotateDeg')}</span>
+ <DegField onCommit={rotateGroup} />
+ </label>
+ </div>
+ <div className="inspector__actions">
+ {[-15, -1, 1, 15].map((d) => (
+ <Button key={d} size="sm" onClick={() => rotateGroup(d)}>
+ {d > 0 ? `+${d}` : `−${-d}`}°
+ </Button>
+ ))}
+ </div>
+ {street !== null && street !== 0 && (
+ <Button size="sm" onClick={() => rotateGroup(street)}>
+ {t('group.alignStreet')}
+ </Button>
+ )}
+ <Button variant="danger" className="inspector__delete" onClick={deleteGroup}>
+ {t('delete')}
+ </Button>
+ <p className="hint">
+ {t('group.hint')}
+ </p>
+ </aside>
+ )
+}
+
+function OpeningInspector({ plan, opening: o }: { plan: Plan; opening: Opening }) {
+ const { t } = useTranslation('plan')
+ const commit = usePlanStore((s) => s.commit)
+ const selectWall = usePlanStore((s) => s.selectWall)
+ const wall = plan.walls.find((w) => w.id === o.wallId)
+ const len = wall ? wallLength(wall) : 0
+ const set = (patch: Partial<Opening>) => {
+ const next = { ...o, ...patch }
+ if (patch.width !== undefined || patch.offset !== undefined) {
+ const at = fitOffset(plan, o.wallId, next.width, next.offset, o.id)
+ if (at === null) return
+ next.offset = at
+ }
+ commit(updateOpening(plan, o.id, next))
+ }
+
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <InspectorClose />
+ <div className="eyebrow">{typeLabel(o.type)}</div>
+ <div className="inspector__title">{o.id}</div>
+ </div>
+ <div className="form">
+ <div className="form__row">
+ <span>{t('type')}</span>
+ <Segmented
+ size="sm"
+ value={o.type}
+ options={[
+ { value: 'door', label: typeLabel('door') },
+ { value: 'window', label: typeLabel('window') },
+ { value: 'gate', label: typeLabel('gate') },
+ ]}
+ onChange={(type) =>
+ set(
+ type === 'door'
+ ? { type, sill: 0, hinge: o.hinge ?? 'start', side: o.side ?? 'right' }
+ : type === 'gate'
+ ? { type, sill: 0, hinge: undefined, side: o.side ?? 'right' }
+ : { type, sill: o.sill || 800, hinge: undefined, side: undefined },
+ )
+ }
+ />
+ </div>
+ <label className="form__row">
+ <span>{t('width')}</span>
+ <LengthField value={o.width} min={300} onCommit={(width) => set({ width })} />
+ </label>
+ <label className="form__row">
+ <span>{t('height')}</span>
+ <LengthField value={o.height} min={300} onCommit={(height) => set({ height })} />
+ </label>
+ <label className="form__row">
+ <span>{t('opening.sill')}</span>
+ <LengthField value={o.sill} onCommit={(sill) => set({ sill })} />
+ </label>
+ <label className="form__row">
+ <span>{t('opening.offset')}</span>
+ <LengthField value={o.offset} onCommit={(offset) => set({ offset })} />
+ </label>
+ {o.type === 'door' && (
+ <>
+ <div className="form__row">
+ <span>{t('opening.hinges')}</span>
+ <Segmented
+ size="sm"
+ value={o.hinge ?? 'start'}
+ options={[
+ { value: 'start', label: t('opening.hingeStart') },
+ { value: 'end', label: t('opening.hingeEnd') },
+ ]}
+ onChange={(hinge) => set({ hinge })}
+ />
+ </div>
+ </>
+ )}
+ {(o.type === 'door' || o.type === 'gate') && (
+ <>
+ <div className="form__row">
+ <span>{t('opening.swing')}</span>
+ <Segmented
+ size="sm"
+ value={o.side ?? 'right'}
+ options={[
+ { value: 'left', label: t('opening.left') },
+ { value: 'right', label: t('opening.right') },
+ ]}
+ onChange={(side) => set({ side })}
+ />
+ </div>
+ </>
+ )}
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('opening.toEnd')}</dt>
+ <dd>{Math.round(len - o.offset - o.width)} {t('common:units.mm')}</dd>
+ <dt>{t('area')}</dt>
+ <dd>{fmt((o.width * o.height) / 1e6)} {t('common:units.m2')}</dd>
+ </dl>
+ <div className="inspector__actions">
+ {wall && (
+ <Button size="sm" onClick={() => selectWall(wall.id)}>
+ {t('opening.wall', { id: wall.id })}
+ </Button>
+ )}
+ <Button
+ size="sm"
+ variant="danger"
+ onClick={() => commit({ ...plan, openings: plan.openings.filter((x) => x.id !== o.id) })}
+ >
+ {t('delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('opening.hint')}</p>
+ </aside>
+ )
+}
+
+function LockedZoneInspector({ zone }: { zone: Zone }) {
+ const { t } = useTranslation('plan')
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <InspectorClose />
+ <div className="eyebrow eyebrow--lock">
+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2.2" aria-hidden>
+ <rect x="5" y="11" width="14" height="10" rx="2" />
+ <path d="M8 11V8a4 4 0 0 1 8 0v3" />
+ </svg>
+ {t('zone.lockedEyebrow')}
+ </div>
+ <div className="inspector__title">{zone.name}</div>
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('area')}</dt>
+ <dd>{fmt(polygonAreaMm2(zone.polygon) / 1e6, 1)} {t('common:units.m2')}</dd>
+ </dl>
+ <p className="hint">{t('zone.lockedHint')}</p>
+ </aside>
+ )
+}
+
+function ZoneInspector({ plan, zone }: { plan: Plan; zone: Zone }) {
+ const { t } = useTranslation('plan')
+ const commit = usePlanStore((s) => s.commit)
+ const [name, setName] = useState<string | null>(null)
+ const area = polygonAreaMm2(zone.polygon) / 1e6
+ const saveName = () => {
+ if (name === null) return
+ const v = name.trim()
+ setName(null)
+ if (v && v !== zone.name) commit(updateZone(plan, zone.id, { name: v }))
+ }
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <InspectorClose />
+ <div className="eyebrow">{t('zone.eyebrow')}</div>
+ <div className="inspector__title">{zone.name}</div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('zone.name')}</span>
+ <Input
+ size="sm"
+ value={name ?? zone.name}
+ onChange={(e) => setName(e.target.value)}
+ onBlur={saveName}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur()
+ }}
+ />
+ </label>
+ <div className="form__row">
+ <span>{t('type')}</span>
+ <select
+ className="select form__select"
+ value={zone.kind}
+ onChange={(e) => commit(updateZone(plan, zone.id, { kind: e.target.value as Zone['kind'] }))}
+ >
+ {(Object.keys(zoneKindLabels) as Zone['kind'][]).map((k) => (
+ <option key={k} value={k}>
+ {zoneKindLabels[k]}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('area')}</dt>
+ <dd>{fmt(area, 1)} {t('common:units.m2')}</dd>
+ <dt>{t('zone.perimeter')}</dt>
+ <dd>{formatLength(polygonPerimeter(zone.polygon))}</dd>
+ <dt>{t('zone.vertices')}</dt>
+ <dd>{zone.polygon.length}</dd>
+ </dl>
+ <div className="inspector__actions">
+ <span />
+ <Button size="sm" variant="danger" onClick={() => commit(deleteZone(plan, zone.id))}>
+ {t('delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('zone.hint')}</p>
+ </aside>
+ )
+}
+
+function FurnitureInspector({ plan, item }: { plan: Plan; item: Furniture }) {
+ const { t } = useTranslation('plan')
+ const commit = usePlanStore((s) => s.commit)
+ const r = resolveFurniture(item)
+ const set = (patch: Partial<Furniture>) => commit(updateFurniture(plan, item.id, patch))
+ return (
+ <aside className="inspector card">
+ <div className="inspector__head">
+ <InspectorClose />
+ <div className="eyebrow">{t('furniture.eyebrow')}</div>
+ <div className="inspector__title">{r.def?.name ?? item.type}</div>
+ </div>
+ <div className="form">
+ <label className="form__row">
+ <span>{t('width')}</span>
+ <LengthField value={r.w} min={100} onCommit={(w) => set({ w })} />
+ </label>
+ <label className="form__row">
+ <span>{t('furniture.depth')}</span>
+ <LengthField value={r.d} min={100} onCommit={(d) => set({ d })} />
+ </label>
+ <label className="form__row">
+ <span>{t('height')}</span>
+ <LengthField value={r.h} min={50} onCommit={(h) => set({ h })} />
+ </label>
+ <div className="form__row">
+ <span>{t('furniture.rotation')}</span>
+ <Segmented
+ size="sm"
+ value={String(normalizeDeg(item.rotationDeg))}
+ options={['0', '90', '180', '270'].map((v) => ({ value: v, label: `${v}°` }))}
+ onChange={(v) => set({ rotationDeg: Number(v) })}
+ />
+ </div>
+ <label className="form__row">
+ <span>{t('furniture.color')}</span>
+ <input
+ type="color"
+ className="form__color"
+ value={item.color && /^#[0-9a-f]{6}$/i.test(item.color) ? item.color : '#ffffff'}
+ onChange={(e) => set({ color: e.target.value })}
+ />
+ </label>
+ </div>
+ <dl className="props props--compact">
+ <dt>{t('furniture.center')}</dt>
+ <dd>
+ {Math.round(item.x)}, {Math.round(item.y)}
+ </dd>
+ </dl>
+ <div className="inspector__actions">
+ <Button size="sm" onClick={() => set({ rotationDeg: normalizeDeg(item.rotationDeg + 90) })}>
+ {t('furniture.rotate90')}
+ </Button>
+ <Button size="sm" variant="danger" onClick={() => commit(deleteFurniture(plan, item.id))}>
+ {t('delete')}
+ </Button>
+ </div>
+ <p className="hint">{t('furniture.hint')}</p>
+ </aside>
+ )
+}
+
+const checked = (iso?: string) => {
+ if (!iso) return ''
+ const d = new Date(iso)
+ return Number.isNaN(d.getTime()) ? iso : fmtDateTime(d, { year: 'numeric', month: '2-digit', day: '2-digit' })
+}
+
+function EstimateRow({ line }: { line: WallEstimateLine }) {
+ const { t } = useTranslation('plan')
+ const m = line.material
+ const unit = line.unit ? unitLabels[line.unit] : ''
+ const facts = [
+ t('estimate.walls', { count: line.wallCount, length: formatLength(line.lengthMm) }),
+ `${fmt(line.netAreaM2)} ${t('common:units.m2')}`,
+ line.panels !== undefined ? t('estimate.panels', { count: line.panels }) : null,
+ ].filter(Boolean)
+
+ return (
+ <div className="material">
+ <span className="swatch swatch--lg" style={{ background: materialColor(m) }} />
+ <div className="material__body">
+ <div className="material__name">{line.name}</div>
+ <div className="muted">
+ {m ? `${kindLabels[m.kind]} · ${fmt(m.thickness, 0)} ${t('common:units.mm')}${m.name.includes('+') ? t('estimate.wholeWall') : ''}` : t('estimate.noMaterial')}
+ {m?.panelWidth && m.panelHeight ? t('estimate.panelSize', { w: m.panelWidth, h: m.panelHeight }) : ''}
+ </div>
+ <div className="muted">{facts.join(' · ')}</div>
+ {line.panelsWithWaste !== undefined && (
+ <div className="muted">
+ {t('estimate.withWaste', { pct: line.wastePct, n: line.panelsWithWaste })}
+ </div>
+ )}
+ <div className="material__calc">
+ {line.qty !== null ? `${fmt(line.qty)} ${unit}` : '—'}
+ {line.price !== undefined ? ` × ${formatMoney(line.price)}` : ''}
+ {line.cost !== null ? ' = ' : ''}
+ {line.cost !== null && <strong>{formatMoney(line.cost)}</strong>}
+ <span className="muted">{t('estimate.areaWithWaste', { area: fmt(line.areaWithWasteM2) })}</span>
+ {line.price === undefined && <div className="muted">{t('estimate.noPrice')}</div>}
+ </div>
+ {line.piecesPerM2 !== undefined && (
+ <div className="muted">
+ {t('estimate.piecesPerM2', { n: fmt(line.piecesPerM2, 1), l: m?.unitLength, h: m?.unitHeight, joint: m?.jointMm ?? 10 })}
+ {line.unit !== 'pcs' && line.pieces !== undefined ? t('estimate.pieces', { n: fmt(line.pieces, 0) }) : ''}
+ </div>
+ )}
+ {(line.url || line.source || line.checkedAt) && (
+ <div className="material__source muted">
+ {line.url ? (
+ <a href={line.url} target="_blank" rel="noreferrer">
+ {line.source || t('estimate.source')}
+ </a>
+ ) : (
+ line.source
+ )}
+ {line.checkedAt && t('estimate.checked', { date: checked(line.checkedAt) })}
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+const NET_TAB_KEY = 'house-planner:panel-tab'
+const NET_TABS = ['sewer', 'water', 'electric', 'heating'] as const
+type NetTab = (typeof NET_TABS)[number]
+const readNetTab = (): NetTab | null => {
+ try {
+ const v = localStorage.getItem(NET_TAB_KEY)
+ return (NET_TABS as readonly string[]).includes(v ?? '') ? (v as NetTab) : null
+ } catch {
+ return null
+ }
+}
+const writeNetTab = (v: NetTab | null) => {
+ try {
+ if (v) localStorage.setItem(NET_TAB_KEY, v)
+ else localStorage.removeItem(NET_TAB_KEY)
+ } catch {
+ return
+ }
+}
+
+function SummaryPanel({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('plan')
+ const rawTab = usePlanStore((s) => s.summaryTab)
+ const tab = rawTab === 'materials' ? 'materials' : 'general'
+ const setTab = usePlanStore((s) => s.setSummaryTab)
+ const open = usePlanStore((s) => s.summaryOpen)
+ const setOpen = usePlanStore((s) => s.setSummaryOpen)
+ const sewerOn = useLayers((s) => s.sewer)
+ const sewerTab = useSewerUi((s) => s.panel) && sewerOn
+ const setSewerTab = useSewerUi((s) => s.setPanel)
+ const waterOn = useLayers((s) => s.water)
+ const waterTab = useWaterUi((s) => s.panel) && waterOn
+ const setWaterTab = useWaterUi((s) => s.setPanel)
+ const electricOn = useLayers((s) => s.electric)
+ const electricTab = useElectricUi((s) => s.tab) && electricOn
+ const setElectricTab = useElectricUi((s) => s.setTab)
+ const heatingOn = useLayers((s) => s.heating)
+ const heatingTab = useHeatingUi((s) => s.tab) && heatingOn
+ const setHeatingTab = useHeatingUi((s) => s.setTab)
+ const setNetTab = (v: string) => {
+ setSewerTab(v === 'sewer')
+ setWaterTab(v === 'water')
+ setElectricTab(v === 'electric')
+ setHeatingTab(v === 'heating')
+ }
+ useEffect(() => {
+ const saved = readNetTab()
+ if (saved) setNetTab(saved)
+ }, [])
+ return (
+ <aside className={`inspector inspector--summary card ${open ? 'inspector--open' : ''}`}>
+ <div className="inspector__tabs">
+ <Segmented
+ size="sm"
+ value={heatingTab ? 'heating' : electricTab ? 'electric' : waterTab ? 'water' : sewerTab ? 'sewer' : tab}
+ options={[
+ { value: 'general', label: t('tabs.general') },
+ { value: 'materials', label: t('tabs.materials') },
+ ...(sewerOn ? [{ value: 'sewer', label: t('tabs.sewer') }] : []),
+ ...(waterOn ? [{ value: 'water', label: t('tabs.water') }] : []),
+ ...(electricOn ? [{ value: 'electric', label: t('tabs.electric') }] : []),
+ ...(heatingOn ? [{ value: 'heating', label: t('tabs.heating') }] : []),
+ ]}
+ onChange={(v) => {
+ setNetTab(v)
+ const net = (NET_TABS as readonly string[]).includes(v) ? (v as NetTab) : null
+ writeNetTab(net)
+ if (!net) setTab(v as 'general' | 'materials')
+ }}
+ />
+ <IconButton label={t('close')} size="sm" className="inspector__sheet-close" onClick={() => setOpen(false)}>
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ </IconButton>
+ </div>
+ {heatingTab ? <HeatingSummary plan={plan} /> : electricTab ? <ElectricSummary plan={plan} /> : waterTab ? <WaterSummary plan={plan} /> : sewerTab ? <SewerSummary plan={plan} /> : tab === 'general' ? <StatsSummary plan={plan} /> : <PlanSummary plan={plan} />}
+ </aside>
+ )
+}
+
+function PlanSummary({ plan }: { plan: Plan }) {
+ const { t } = useTranslation('plan')
+ const commit = usePlanStore((s) => s.commit)
+ const estimate = computeWallEstimate(plan)
+ const unused = plan.materials.filter((m) => !estimate.lines.some((l) => l.materialId === m.id))
+
+ const setWaste = (value: number) => {
+ if (!Number.isFinite(value)) return
+ const pct = Math.min(30, Math.max(0, Math.round(value)))
+ commit({
+ ...plan,
+ estimate: { lines: [], purchases: {}, ...plan.estimate, wasteSipPct: pct },
+ })
+ }
+
+ return (
+ <div className="inspector__materials">
+ <div className="inspector__head">
+ <div className="eyebrow">{t('materials.eyebrow')}</div>
+ <div className="inspector__title">{t('materials.title')}</div>
+ </div>
+ {estimate.lines.length === 0 && <p className="muted">{t('materials.noWalls')}</p>}
+ {estimate.lines.map((l) => (
+ <EstimateRow key={l.id} line={l} />
+ ))}
+ {unused.map((m) => (
+ <div key={m.id} className="material material--unused">
+ <span className="swatch swatch--lg" style={{ background: materialColor(m) }} />
+ <div className="material__body">
+ <div className="material__name">{m.name}</div>
+ <div className="muted">{t('materials.unused')}</div>
+ </div>
+ </div>
+ ))}
+ <div className="inspector__section">
+ <label className="row row--center">
+ <span>{t('materials.waste')}</span>
+ <Input
+ size="sm"
+ type="number"
+ min={0}
+ max={30}
+ step={1}
+ suffix="%"
+ className="waste"
+ value={plan.estimate?.wasteSipPct ?? DEFAULT_WASTE_PCT}
+ onChange={(e) => setWaste(Number(e.target.value))}
+ />
+ </label>
+ <div className="row total">
+ <span>{t('materials.total')}</span>
+ <strong>{formatMoney(estimate.total)}</strong>
+ </div>
+ {estimate.missingPrices > 0 && <div className="muted">{t('materials.noPrice', { count: estimate.missingPrices })}</div>}
+ </div>
+ <p className="hint">{t('materials.hint')}</p>
+ </div>
+ )
+}
diff --git a/src/ui/LengthField.tsx b/src/ui/LengthField.tsx
new file mode 100644
index 0000000..3113d9d
--- /dev/null
+++ b/src/ui/LengthField.tsx
@@ -0,0 +1,67 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Input } from './Input'
+
+export function parseLength(raw: string): number | null {
+ const s = raw.trim().toLowerCase().replace(/\s+/g, '').replace(',', '.')
+ const m = s.match(/^(-?\d*\.?\d+)(мм|mm|см|cm|м|m)?$/)
+ if (!m) return null
+ const v = Number(m[1])
+ if (!Number.isFinite(v)) return null
+ const unit = m[2]
+ if (unit === 'мм' || unit === 'mm') return Math.round(v)
+ if (unit === 'см' || unit === 'cm') return Math.round(v * 10)
+ if (unit === 'м' || unit === 'm') return Math.round(v * 1000)
+ return m[1].includes('.') || Math.abs(v) < 30 ? Math.round(v * 1000) : Math.round(v)
+}
+
+type Props = {
+ value: number
+ onCommit: (mm: number) => void
+ min?: number
+ label?: string
+ title?: string
+}
+
+export function LengthField({ value, onCommit, min = 0, label, title }: Props) {
+ const { t } = useTranslation('common')
+ const [draft, setDraft] = useState<string | null>(null)
+ const [invalid, setInvalid] = useState(false)
+ const commit = () => {
+ if (draft === null) return
+ const mm = parseLength(draft)
+ if (mm === null || mm < min) {
+ setInvalid(true)
+ return
+ }
+ setDraft(null)
+ setInvalid(false)
+ if (mm !== Math.round(value)) onCommit(mm)
+ }
+ return (
+ <Input
+ size="sm"
+ label={label}
+ title={title ?? t('lengthField.title')}
+ suffix={t('units.mm')}
+ invalid={invalid}
+ value={draft ?? String(Math.round(value))}
+ onChange={(e) => {
+ setDraft(e.target.value)
+ setInvalid(false)
+ }}
+ onFocus={(e) => e.target.select()}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ commit()
+ ;(e.target as HTMLInputElement).blur()
+ } else if (e.key === 'Escape') {
+ setDraft(null)
+ setInvalid(false)
+ ;(e.target as HTMLInputElement).blur()
+ }
+ }}
+ />
+ )
+}
diff --git a/src/ui/LoginScreen.tsx b/src/ui/LoginScreen.tsx
new file mode 100644
index 0000000..8644529
--- /dev/null
+++ b/src/ui/LoginScreen.tsx
@@ -0,0 +1,69 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { loadFromServer, login, useSyncStore } from '../storage'
+import { Button } from './Button'
+import { Input } from './Input'
+
+export function LoginScreen() {
+ const { t } = useTranslation('common')
+ const status = useSyncStore((s) => s.status)
+ const error = useSyncStore((s) => s.error)
+ const [password, setPassword] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [message, setMessage] = useState<string | null>(null)
+
+ if (status === 'loading') {
+ return (
+ <div className="gate">
+ <div className="gate__card card muted">{t('login.loading')}</div>
+ </div>
+ )
+ }
+
+ if (status !== 'login') {
+ return (
+ <div className="gate">
+ <div className="gate__card card">
+ <div className="gate__title">{t('login.offlineTitle')}</div>
+ <p className="muted">{t('login.offlineText')}{error ? ` ${error}` : ''}</p>
+ <Button variant="primary" onClick={() => void loadFromServer(true)}>
+ {t('login.retry')}
+ </Button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="gate">
+ <form
+ className="gate__card card"
+ onSubmit={async (e) => {
+ e.preventDefault()
+ if (!password || busy) return
+ setBusy(true)
+ setMessage(await login(password))
+ setBusy(false)
+ }}
+ >
+ <span className="header__logo" aria-hidden />
+ <div className="gate__title">{t('login.password')}</div>
+ <Input
+ type="password"
+ autoFocus
+ autoComplete="current-password"
+ value={password}
+ invalid={!!message}
+ onChange={(e) => {
+ setPassword(e.target.value)
+ setMessage(null)
+ }}
+ />
+ {message && <div className="gate__error">{message}</div>}
+ <Button type="submit" variant="primary" disabled={busy || !password}>
+ {busy ? t('login.checking') : t('login.signIn')}
+ </Button>
+ </form>
+ </div>
+ )
+}
diff --git a/src/ui/Menu.tsx b/src/ui/Menu.tsx
new file mode 100644
index 0000000..95357df
--- /dev/null
+++ b/src/ui/Menu.tsx
@@ -0,0 +1,60 @@
+import { useEffect, useRef, useState, type ButtonHTMLAttributes, type ReactNode } from 'react'
+import { cx } from './cx'
+
+type MenuProps = {
+ trigger: (props: { open: boolean; toggle: () => void }) => ReactNode
+ children: ReactNode | ((close: () => void) => ReactNode)
+ align?: 'left' | 'right'
+ width?: number
+}
+
+export function Menu({ trigger, children, align = 'right', width = 280 }: MenuProps) {
+ const [open, setOpen] = useState(false)
+ const ref = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open) return
+ const onDown = (e: MouseEvent) => {
+ if (!ref.current?.contains(e.target as Node)) setOpen(false)
+ }
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') setOpen(false)
+ }
+ window.addEventListener('mousedown', onDown)
+ window.addEventListener('keydown', onKey)
+ return () => {
+ window.removeEventListener('mousedown', onDown)
+ window.removeEventListener('keydown', onKey)
+ }
+ }, [open])
+
+ const close = () => setOpen(false)
+ return (
+ <div className="menu" ref={ref}>
+ {trigger({ open, toggle: () => setOpen((v) => !v) })}
+ {open && (
+ <div className={cx('card', 'menu__panel', `menu__panel--${align}`)} style={{ width }} role="menu">
+ {typeof children === 'function' ? children(close) : children}
+ </div>
+ )}
+ </div>
+ )
+}
+
+export function MenuItem({ className, hint, children, type = 'button', ...rest }: ButtonHTMLAttributes<HTMLButtonElement> & { hint?: ReactNode }) {
+ return (
+ <button type={type} role="menuitem" className={cx('menu__item', className)} {...rest}>
+ <span className="menu__label">{children}</span>
+ {hint && <span className="menu__hint">{hint}</span>}
+ </button>
+ )
+}
+
+export function MenuSection({ title, children }: { title?: ReactNode; children: ReactNode }) {
+ return (
+ <div className="menu__section">
+ {title && <div className="menu__title eyebrow">{title}</div>}
+ {children}
+ </div>
+ )
+}
diff --git a/src/ui/PreviewBar.tsx b/src/ui/PreviewBar.tsx
new file mode 100644
index 0000000..13c1e3e
--- /dev/null
+++ b/src/ui/PreviewBar.tsx
@@ -0,0 +1,36 @@
+import { Trans, useTranslation } from 'react-i18next'
+import { restorePreview } from '../storage'
+import { usePlanStore } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { Button } from './Button'
+
+export function PreviewBar() {
+ const { t } = useTranslation('common')
+ const vp = usePlanStore((s) => s.versionPreview)
+ const exitPreview = usePlanStore((s) => s.exitPreview)
+ const viewOnly = useViewOnly()
+ if (!vp) return null
+ return (
+ <div className="preview-bar card">
+ <span>
+ <Trans t={t} i18nKey="preview.label" values={{ label: vp.label }} components={{ strong: <strong /> }} />
+ </span>
+ <div className="preview-bar__actions">
+ <Button size="sm" onClick={() => exitPreview()}>
+ {t('preview.back')}
+ </Button>
+ {!viewOnly && (
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={() => {
+ if (window.confirm(t('preview.confirm', { label: vp.label }))) restorePreview()
+ }}
+ >
+ {t('preview.restore')}
+ </Button>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/src/ui/SaveIndicator.tsx b/src/ui/SaveIndicator.tsx
new file mode 100644
index 0000000..5d63e7d
--- /dev/null
+++ b/src/ui/SaveIndicator.tsx
@@ -0,0 +1,39 @@
+import { useTranslation } from 'react-i18next'
+import { fmtDateTime } from '../i18n'
+import { loadFromServer, useSyncStore } from '../storage'
+
+const time = (iso: string | null) => {
+ if (!iso) return ''
+ const d = new Date(iso)
+ return Number.isNaN(d.getTime()) ? '' : fmtDateTime(d, { hour: '2-digit', minute: '2-digit' })
+}
+
+export function SaveIndicator() {
+ const { t } = useTranslation('common')
+ const status = useSyncStore((s) => s.status)
+ const savedAt = useSyncStore((s) => s.savedAt)
+ const error = useSyncStore((s) => s.error)
+ if (status === 'saving') {
+ return (
+ <span className="save save--busy">
+ <span className="save__dot" />
+ <span className="save__text">{t('save.saving')}</span>
+ </span>
+ )
+ }
+ if (status === 'offline' || status === 'error') {
+ return (
+ <button className="save save--err" title={error ?? ''} onClick={() => void loadFromServer(false)}>
+ <span className="save__dot" />
+ <span className="save__text">{t('save.offline')}</span>
+ </button>
+ )
+ }
+ const at = time(savedAt)
+ return (
+ <span className="save">
+ <span className="save__dot" />
+ <span className="save__text">{at ? t('save.savedAt', { time: at }) : t('save.saved')}</span>
+ </span>
+ )
+}
diff --git a/src/ui/Segmented.tsx b/src/ui/Segmented.tsx
new file mode 100644
index 0000000..902325b
--- /dev/null
+++ b/src/ui/Segmented.tsx
@@ -0,0 +1,38 @@
+import { cx } from './cx'
+
+export type SegmentedOption<T extends string> = { value: T; label: string; href?: string; title?: string }
+
+type Props<T extends string> = {
+ options: readonly SegmentedOption<T>[]
+ value: T
+ onChange?: (value: T) => void
+ size?: 'sm' | 'md'
+ className?: string
+}
+
+export function Segmented<T extends string>({ options, value, onChange, size = 'md', className }: Props<T>) {
+ return (
+ <div className={cx('segmented', size === 'sm' && 'segmented--sm', className)} role="tablist">
+ {options.map((o) => {
+ const cls = cx('segmented__item', o.value === value && 'segmented__item--active')
+ return o.href ? (
+ <a key={o.value} href={o.href} className={cls} role="tab" aria-selected={o.value === value} title={o.title}>
+ {o.label}
+ </a>
+ ) : (
+ <button
+ key={o.value}
+ type="button"
+ className={cls}
+ role="tab"
+ aria-selected={o.value === value}
+ title={o.title}
+ onClick={() => onChange?.(o.value)}
+ >
+ {o.label}
+ </button>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/src/ui/Table.tsx b/src/ui/Table.tsx
new file mode 100644
index 0000000..e643c7d
--- /dev/null
+++ b/src/ui/Table.tsx
@@ -0,0 +1,22 @@
+import type { HTMLAttributes, TableHTMLAttributes, TdHTMLAttributes, ThHTMLAttributes } from 'react'
+import { cx } from './cx'
+
+export function Table({ className, dense, ...rest }: TableHTMLAttributes<HTMLTableElement> & { dense?: boolean }) {
+ return (
+ <div className="table-wrap">
+ <table className={cx('table', dense && 'table--dense', className)} {...rest} />
+ </div>
+ )
+}
+
+export function Th({ className, num, ...rest }: ThHTMLAttributes<HTMLTableCellElement> & { num?: boolean }) {
+ return <th className={cx(num && 'num', className)} {...rest} />
+}
+
+export function Td({ className, num, ...rest }: TdHTMLAttributes<HTMLTableCellElement> & { num?: boolean }) {
+ return <td className={cx(num && 'num', className)} {...rest} />
+}
+
+export function Tr({ className, muted, ...rest }: HTMLAttributes<HTMLTableRowElement> & { muted?: boolean }) {
+ return <tr className={cx(muted && 'table__row--muted', className)} {...rest} />
+}
diff --git a/src/ui/Toast.tsx b/src/ui/Toast.tsx
new file mode 100644
index 0000000..ab5979f
--- /dev/null
+++ b/src/ui/Toast.tsx
@@ -0,0 +1,25 @@
+import { useEffect } from 'react'
+import { create } from 'zustand'
+
+type ToastState = { text: string | null; id: number }
+
+const useToastStore = create<ToastState>()(() => ({ text: null, id: 0 }))
+
+export function showToast(text: string) {
+ useToastStore.setState((s) => ({ text, id: s.id + 1 }))
+}
+
+export function Toast() {
+ const { text, id } = useToastStore()
+ useEffect(() => {
+ if (!text) return
+ const t = setTimeout(() => useToastStore.setState({ text: null }), 4500)
+ return () => clearTimeout(t)
+ }, [text, id])
+ if (!text) return null
+ return (
+ <div className="toast card" role="status" key={id}>
+ {text}
+ </div>
+ )
+}
diff --git a/src/ui/Toolbar.tsx b/src/ui/Toolbar.tsx
new file mode 100644
index 0000000..f222b69
--- /dev/null
+++ b/src/ui/Toolbar.tsx
@@ -0,0 +1,210 @@
+import { useStore } from 'zustand'
+import { useTranslation } from 'react-i18next'
+import { redo, undo, usePlanStore, type Tool } from '../store/planStore'
+import { useViewOnly } from '../store/viewOnly'
+import { OPENING_PRESETS, materialColor } from '../model'
+import { CanvasToolbar, ToolbarSeparator } from './CanvasToolbar'
+import { LayersButton, lockedToast, stopEdit, useLayers, useNetworkEdit, wallsLockedText } from '../networks'
+
+const tools: { id: Tool; key: string; icon: string }[] = [
+ { id: 'select', key: 'V', icon: 'M5 3l14 8-6 1.5L10 19z' },
+ { id: 'wall', key: 'W', icon: 'M3 9h18v6H3z' },
+ { id: 'door', key: 'D', icon: 'M6 3h12v18H6zM8 5v16h8V5zM13 11h2v2h-2z' },
+ { id: 'window', key: 'O', icon: 'M4 4h16v16H4zM6 6h5v5H6zM13 6h5v5h-5zM6 13h5v5H6zM13 13h5v5h-5z' },
+ { id: 'zone', key: '', icon: 'M4 6l7-3 9 4-2 12-12 2zM6.5 7.5l.5 10.2 9.5-1.6L18 8.3 11 5.3z' },
+ { id: 'building', key: 'B', icon: 'M12 2.5l9 7.5v11.5H3V10zM5 11v8.5h14V11l-7-5.8zM12 8.3l2.6 2.6h-1.8v2.3h2.3v-1.8l2.6 2.6-2.6 2.6v-1.8h-2.3v2.3h1.8L12 20.7l-2.6-2.6h1.8v-2.3H8.9v1.8l-2.6-2.6 2.6-2.6v1.8h2.3v-2.3H9.4z' },
+]
+
+export function Toolbar() {
+ const { t: tr } = useTranslation('plan')
+ const toolLabel = (id: Tool) => tr(`toolbar.tools.${id}`)
+ const tool = usePlanStore((s) => s.tool)
+ const setTool = usePlanStore((s) => s.setTool)
+ const plan = usePlanStore((s) => s.plan)
+ const materials = plan?.materials ?? []
+ const activeMaterialId = usePlanStore((s) => s.activeMaterialId)
+ const setActiveMaterial = usePlanStore((s) => s.setActiveMaterial)
+ const requestFit = usePlanStore((s) => s.requestFit)
+ const underlay = usePlanStore((s) => s.underlay)
+ const aligning = usePlanStore((s) => s.aligning)
+ const setAligning = usePlanStore((s) => s.setAligning)
+ const setUnderlay = usePlanStore((s) => s.setUnderlay)
+ const furniturePanel = usePlanStore((s) => s.furniturePanel)
+ const setFurniturePanel = usePlanStore((s) => s.setFurniturePanel)
+ const doorPreset = usePlanStore((s) => s.doorPreset)
+ const summaryOpen = usePlanStore((s) => s.summaryOpen)
+ const setSummaryOpen = usePlanStore((s) => s.setSummaryOpen)
+ const setDoorPreset = usePlanStore((s) => s.setDoorPreset)
+ const active = materials.find((m) => m.id === activeMaterialId)
+ const pct = Math.round(underlay.opacity * 100)
+ const viewOnly = useViewOnly()
+ const netEditing = useNetworkEdit((s) => !!s.editing)
+ const wallsLocked = useLayers((s) => s.locks.walls)
+ const zonesLocked = useLayers((s) => s.locks.zones)
+ const toolLocked = (id: Tool) => (wallsLocked && (id === 'wall' || id === 'door' || id === 'window')) || (zonesLocked && id === 'zone')
+ const showDims = usePlanStore((s) => s.showDims)
+ const setShowDims = usePlanStore((s) => s.setShowDims)
+ const canUndo = useStore(usePlanStore.temporal, (t) => t.pastStates.length > 0)
+ const canRedo = useStore(usePlanStore.temporal, (t) => t.futureStates.length > 0)
+
+ return (
+ <CanvasToolbar placement="top-left" direction="column" className="toolbar">
+ {!viewOnly && (
+ <div className="toolbar__history">
+ <button className="tool tool--mini" onClick={undo} disabled={!canUndo} title={tr('toolbar.undoTitle')} aria-label={tr('toolbar.undo')}>
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3" />
+ </svg>
+ </button>
+ <button className="tool tool--mini" onClick={redo} disabled={!canRedo} title={tr('toolbar.redoTitle')} aria-label={tr('toolbar.redo')}>
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M15 14l5-5-5-5M20 9H10a6 6 0 0 0 0 12h3" />
+ </svg>
+ </button>
+ </div>
+ )}
+ {!viewOnly && <ToolbarSeparator />}
+ {tools.filter((t) => !viewOnly || t.id === 'select').map((t) => (
+ <button
+ key={t.id}
+ className={`tool ${tool === t.id && !(netEditing && t.id === 'select') ? 'tool--active' : ''}`}
+ aria-disabled={toolLocked(t.id) || undefined}
+ onClick={() => {
+ if (toolLocked(t.id)) {
+ lockedToast(t.id === 'zone' ? 'zones' : 'walls')
+ return
+ }
+ setTool(t.id)
+ if (netEditing) stopEdit()
+ }}
+ title={t.id === 'building' ? tr('toolbar.buildingTitle') : toolLocked(t.id) ? (t.id === 'zone' ? tr('toolbar.zonesLocked') : wallsLockedText()) : t.key ? `${toolLabel(t.id)} (${t.key})` : t.id === 'zone' ? tr('toolbar.zoneTitle') : toolLabel(t.id)}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon" aria-hidden>
+ <path d={t.icon} fillRule="evenodd" />
+ </svg>
+ <span className="tool__label">{viewOnly && t.id === 'select' ? tr('toolbar.view') : toolLabel(t.id)}</span>
+ </button>
+ ))}
+{!viewOnly && (
+ <button
+ className={`tool ${furniturePanel ? 'tool--on' : ''}`}
+ onClick={() => setFurniturePanel(!furniturePanel)}
+ title={tr('toolbar.furnitureTitle')}
+ aria-pressed={furniturePanel}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M4 11V7a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4M3 11h18v6H3zM5 17v2M19 17v2" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.furniture')}</span>
+ </button>
+ )}
+ <button
+ className={`tool ${tool === 'measure' ? 'tool--active' : ''}`}
+ onClick={() => setTool(tool === 'measure' ? 'select' : 'measure')}
+ title={tr('toolbar.measureTitle')}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M3 17L17 3l4 4L7 21zM7 13l2 2M10 10l2 2M13 7l2 2" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.measure')}</span>
+ </button>
+ <button className="tool tool--narrow" onClick={() => setSummaryOpen(!summaryOpen)} title={tr('toolbar.summaryTitle')}>
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M4 20V10M10 20V4M16 20v-7M22 20H2" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.summary')}</span>
+ </button>
+ <ToolbarSeparator />
+ <LayersButton />
+ <button
+ className={`tool ${showDims ? 'tool--on' : ''}`}
+ onClick={() => setShowDims(!showDims)}
+ title={tr('toolbar.dimsTitle')}
+ aria-pressed={showDims}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M3 8v8M21 8v8M3 12h18M7 10l-4 2 4 2M17 10l4 2-4 2" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.dims')}</span>
+ </button>
+ <button className="tool" onClick={requestFit} title={tr('toolbar.fitTitle')}>
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.fit')}</span>
+ </button>
+ <button
+ className={`tool ${underlay.on ? 'tool--on' : ''}`}
+ onClick={() => {
+ if (underlay.on) setAligning(false)
+ setUnderlay({ on: !underlay.on })
+ }}
+ title={tr('toolbar.mapTitle')}
+ aria-pressed={underlay.on}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M3 6l6-2 6 2 6-2v14l-6 2-6-2-6 2zM9 4v14M15 6v14" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.map')}</span>
+ </button>
+ {underlay.on && !viewOnly && (
+ <button
+ className={`tool ${aligning ? 'tool--active' : ''}`}
+ onClick={() => setAligning(!aligning)}
+ title={tr('toolbar.alignTitle')}
+ aria-pressed={aligning}
+ >
+ <svg viewBox="0 0 24 24" className="tool__icon tool__icon--line" aria-hidden>
+ <path d="M12 3v18M3 12h18M12 3l-3 3M12 3l3 3M12 21l-3-3M12 21l3-3M3 12l3-3M3 12l3 3M21 12l-3-3M21 12l-3 3" />
+ </svg>
+ <span className="tool__label">{tr('toolbar.align')}</span>
+ </button>
+ )}
+ {underlay.on && (
+ <label className="toolbar__opacity" title={tr('toolbar.opacityTitle', { pct })}>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ step={5}
+ value={pct}
+ onChange={(e) => setUnderlay({ opacity: Number(e.target.value) / 100 })}
+ />
+ <span>{pct}%</span>
+ </label>
+ )}
+ {!viewOnly && tool === 'door' && (
+ <div className="toolbar__material card">
+ <select className="select" value={doorPreset} onChange={(e) => setDoorPreset(e.target.value as 'entry' | 'interior' | 'gate')}>
+ <option value="entry">{OPENING_PRESETS.entry.label}</option>
+ <option value="interior">{OPENING_PRESETS.interior.label}</option>
+ <option value="gate">{OPENING_PRESETS.gate.label}</option>
+ </select>
+ <span className="muted">{tr('toolbar.clickWall')}</span>
+ </div>
+ )}
+ {!viewOnly && tool === 'window' && (
+ <div className="toolbar__material card">
+ <span className="muted">{OPENING_PRESETS.window.label} · {tr('toolbar.clickWall')}</span>
+ </div>
+ )}
+ {!viewOnly && tool === 'wall' && (
+ <div className="toolbar__material card">
+ <span className="swatch" style={{ background: materialColor(active) }} />
+ <select
+ className="select"
+ value={activeMaterialId ?? ''}
+ onChange={(e) => setActiveMaterial(e.target.value || null)}
+ >
+ <option value="">{tr('toolbar.noMaterial')}</option>
+ {materials.map((m) => (
+ <option key={m.id} value={m.id}>
+ {m.name.includes(String(m.thickness)) ? m.name : `${m.name}, ${m.thickness} ${tr('common:units.mm')}`}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+ </CanvasToolbar>
+ )
+}
diff --git a/src/ui/cx.ts b/src/ui/cx.ts
new file mode 100644
index 0000000..55010ff
--- /dev/null
+++ b/src/ui/cx.ts
@@ -0,0 +1 @@
+export const cx = (...parts: (string | false | null | undefined)[]) => parts.filter(Boolean).join(' ')
diff --git a/src/ui/index.ts b/src/ui/index.ts
new file mode 100644
index 0000000..9edafb8
--- /dev/null
+++ b/src/ui/index.ts
@@ -0,0 +1,11 @@
+export { Button, type ButtonProps } from './Button'
+export { IconButton, type IconButtonProps } from './IconButton'
+export { Segmented, type SegmentedOption } from './Segmented'
+export { Card, Panel } from './Card'
+export { Badge, type BadgeTone } from './Badge'
+export { Input, type InputProps } from './Input'
+export { Checkbox, type CheckboxProps } from './Checkbox'
+export { Table, Th, Td, Tr } from './Table'
+export { CanvasToolbar, ToolbarSeparator, type ToolbarPlacement } from './CanvasToolbar'
+export { Menu, MenuItem, MenuSection } from './Menu'
+export { cx } from './cx'
diff --git a/src/ui/planFile.ts b/src/ui/planFile.ts
new file mode 100644
index 0000000..ce6034f
--- /dev/null
+++ b/src/ui/planFile.ts
@@ -0,0 +1,20 @@
+import { parsePlan, type Plan, type ParseResult } from '../model'
+import { t } from '../i18n'
+
+export function downloadPlan(plan: Plan) {
+ const blob = new Blob([JSON.stringify(plan, null, 2) + '\n'], { type: 'application/json' })
+ const url = URL.createObjectURL(blob)
+ const link = document.createElement('a')
+ link.href = url
+ link.download = `${plan.name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-|-$/g, '') || 'plan'}.json`
+ link.click()
+ URL.revokeObjectURL(url)
+}
+
+export async function readPlanFile(file: File): Promise<ParseResult> {
+ try {
+ return parsePlan(JSON.parse(await file.text()))
+ } catch (e) {
+ return { ok: false, error: t('common:planFile.notJson', { message: (e as Error).message }) }
+ }
+}
diff --git a/src/ui/useSection.ts b/src/ui/useSection.ts
new file mode 100644
index 0000000..04bfa00
--- /dev/null
+++ b/src/ui/useSection.ts
@@ -0,0 +1,38 @@
+import { useSyncExternalStore } from 'react'
+
+export const sections = [
+ { id: 'plan', label: 'sections.plan' },
+ { id: '3d', label: 'sections.3d' },
+ { id: 'map', label: 'sections.map' },
+ { id: 'estimate', label: 'sections.estimate' },
+ { id: 'info', label: 'sections.info', short: 'sections.infoShort' },
+] as const
+
+export type SectionId = (typeof sections)[number]['id']
+
+const subscribe = (cb: () => void) => {
+ window.addEventListener('hashchange', cb)
+ return () => window.removeEventListener('hashchange', cb)
+}
+
+const read = (): SectionId => {
+ const id = window.location.hash.replace(/^#\/?/, '')
+ return sections.some((s) => s.id === id) ? (id as SectionId) : 'plan'
+}
+
+export const useSection = () => useSyncExternalStore(subscribe, read, () => 'plan' as SectionId)
+
+export const sectionHref = (id: SectionId) => `#/${id}`
+
+const narrowQuery = () => window.matchMedia('(max-width: 760px)')
+
+export const useNarrow = () =>
+ useSyncExternalStore(
+ (cb) => {
+ const q = narrowQuery()
+ q.addEventListener('change', cb)
+ return () => q.removeEventListener('change', cb)
+ },
+ () => narrowQuery().matches,
+ () => false,
+ )
diff --git a/src/view3d/ColorPicker.tsx b/src/view3d/ColorPicker.tsx
new file mode 100644
index 0000000..7af7c09
--- /dev/null
+++ b/src/view3d/ColorPicker.tsx
@@ -0,0 +1,81 @@
+import { useTranslation } from 'react-i18next'
+import type { Palette } from '../model'
+import { Button, Menu, MenuItem, MenuSection } from '../ui'
+import { PANEL_RAL, PRESETS, ralName } from './palette'
+import { ralCode, ralHex } from './ral'
+
+const Swatch = ({ hex, size = 14 }: { hex: string; size?: number }) => (
+ <span className="view3d__swatch" style={{ background: hex, width: size, height: size }} aria-hidden />
+)
+
+type Props = {
+ label: string
+ value: string
+ onPick: (ral: string) => void
+ presets?: (palette: Palette) => void
+ align?: 'left' | 'right'
+}
+
+export function ColorPicker({ label, value, onPick, presets, align = 'right' }: Props) {
+ const { t } = useTranslation('view3d')
+ const code = ralCode(value) ?? ''
+ return (
+ <Menu
+ align={align}
+ width={340}
+ trigger={({ open, toggle }) => (
+ <Button size="sm" variant="ghost" pressed={open} onClick={toggle} title={`${label}: RAL ${code} ${ralName(code)}`}>
+ <span className="view3d__label">{label}</span>
+ <Swatch hex={ralHex(value) ?? '#ccc'} />
+ <span className="num">{code}</span>
+ </Button>
+ )}
+ >
+ {(close) => (
+ <>
+ <MenuSection title={label}>
+ <div className="view3d__swatches">
+ {PANEL_RAL.map((c) => (
+ <MenuItem
+ key={c}
+ className={c === code ? 'view3d__swatch-item view3d__swatch-item--active' : 'view3d__swatch-item'}
+ onClick={() => {
+ onPick(`RAL ${c}`)
+ close()
+ }}
+ title={ralName(c)}
+ >
+ <Swatch hex={ralHex(c)!} size={18} />
+ <span className="num">{c}</span>
+ <span className="view3d__swatch-name muted">{ralName(c)}</span>
+ </MenuItem>
+ ))}
+ </div>
+ </MenuSection>
+ {presets && (
+ <MenuSection title={t('toolbar.presets')}>
+ {PRESETS.map((p) => (
+ <MenuItem
+ key={p.name}
+ onClick={() => {
+ presets(p.palette)
+ close()
+ }}
+ hint={
+ <span className="view3d__preset">
+ {[p.palette.walls, p.palette.accent, p.palette.windows, p.palette.plinth].map((c, i) => (
+ <Swatch key={i} hex={ralHex(c) ?? '#ccc'} />
+ ))}
+ </span>
+ }
+ >
+ {p.name}
+ </MenuItem>
+ ))}
+ </MenuSection>
+ )}
+ </>
+ )}
+ </Menu>
+ )
+}
diff --git a/src/view3d/ErrorBoundary.tsx b/src/view3d/ErrorBoundary.tsx
new file mode 100644
index 0000000..1409850
--- /dev/null
+++ b/src/view3d/ErrorBoundary.tsx
@@ -0,0 +1,34 @@
+import { Component, type ReactNode } from 'react'
+import { t } from '../i18n'
+import { Button, Card } from '../ui'
+
+type Props = { resetKey: unknown; children: ReactNode }
+type State = { error: Error | null }
+
+export class SceneErrorBoundary extends Component<Props, State> {
+ state: State = { error: null }
+
+ static getDerivedStateFromError(error: Error): State {
+ return { error }
+ }
+
+ componentDidUpdate(prev: Props) {
+ if (this.state.error && prev.resetKey !== this.props.resetKey) this.setState({ error: null })
+ }
+
+ render() {
+ if (!this.state.error) return this.props.children
+ return (
+ <div className="view3d__error">
+ <Card className="view3d__error-card">
+ <div className="eyebrow">{t('view3d:error.eyebrow')}</div>
+ <p>{t('view3d:error.text')}</p>
+ <p className="muted">{this.state.error.message}</p>
+ <Button size="sm" onClick={() => this.setState({ error: null })}>
+ {t('view3d:error.retry')}
+ </Button>
+ </Card>
+ </div>
+ )
+ }
+}
diff --git a/src/view3d/Scene.tsx b/src/view3d/Scene.tsx
new file mode 100644
index 0000000..3684516
--- /dev/null
+++ b/src/view3d/Scene.tsx
@@ -0,0 +1,529 @@
+import { Suspense, useEffect, useMemo, useRef, type ReactNode } from 'react'
+import * as THREE from 'three'
+import { Canvas, useFrame } from '@react-three/fiber'
+import { CameraControls, Edges, Environment, Grid, Lightformer, Line, useTexture } from '@react-three/drei'
+import { EffectComposer, N8AO, ToneMapping } from '@react-three/postprocessing'
+import { ToneMappingMode } from 'postprocessing'
+import { t } from '../i18n'
+import type { Palette } from '../model'
+import type { Finish, FurnitureItem, Material, Opening, Plan, Point, Wall } from './types'
+import { resolveColors, type Colors } from './palette'
+import { bounds, exteriorWalls, openingPlacement, sanitizePlan, slabOutline, wallGroups, wallEdges, wallFrame, wallSeams, wallSolid, worldUV } from './geometry'
+import { TEXTURE_SIZE, finishOf, modelColor, seamPattern, shade, textureSet, type Look, type TextureSet } from './looks'
+
+const M = 0.001
+const SLAB = 0.25
+
+export type View3D = 'iso' | 'top' | 'front'
+export type { Look }
+
+export const VIEWS: Record<View3D, { azimuth: number; polar: number; fit: number; label: string }> = {
+ iso: { azimuth: Math.PI / 4, polar: 0.955, fit: 1.15, label: '3/4' },
+ top: { azimuth: 0, polar: 0.0001, fit: 0.9, get label() { return t('view3d:views.top') } },
+ front: { azimuth: 0, polar: Math.PI / 2 - 0.12, fit: 0.8, get label() { return t('view3d:views.front') } },
+}
+
+export const LOOKS: { id: Look; label: string }[] = [
+ { id: 'model', get label() { return t('view3d:looks.model') } },
+ { id: 'real', get label() { return t('view3d:looks.real') } },
+]
+
+const PALETTE = {
+ model: { background: '#f3f3f0', ground: '#e9e8e2', grass: '#d6dfc9', grid: '#b4c4a3', section: '#a6b894', edge: '#7b776f', slab: '#cfcfca', door: '#8b7c6e' },
+ real: { background: '#eef0f1', ground: '#dcd9cf', grass: '#e8ecdc', grid: '#b7c59a', section: '#c2cfa6', edge: '#6b665e', slab: '#bdbdb8', door: '#5d4a3c' },
+}
+
+const REAL_TINT: Partial<Record<TextureSet, string>> = { osb: '#f6f0ea', timber: '#f2ebe2', planken: '#e9ddd0' }
+
+const GRASS_BOOST = new THREE.Color(1.12, 1.08, 1.1)
+
+type Ctx = { look: Look; texturesUrl: string; colors: Colors }
+
+function useSetTextures(set: TextureSet, base: string) {
+ const tex = useTexture({
+ map: `${base}${set}/color.jpg`,
+ normalMap: `${base}${set}/normal.jpg`,
+ roughnessMap: `${base}${set}/roughness.jpg`,
+ })
+ useMemo(() => {
+ const [sx, sy] = TEXTURE_SIZE[set]
+ for (const t of Object.values(tex)) {
+ t.wrapS = t.wrapT = THREE.RepeatWrapping
+ t.repeat.set(1 / sx, 1 / sy)
+ t.anisotropy = 8
+ t.needsUpdate = true
+ }
+ tex.map.colorSpace = THREE.SRGBColorSpace
+ }, [tex, set])
+ return tex
+}
+
+function RealSurface({ set, base, attach, tint = '#ffffff' }: { set: TextureSet; base: string; attach?: string; tint?: THREE.ColorRepresentation }) {
+ const tex = useSetTextures(set, base)
+ return <meshStandardMaterial attach={attach} {...tex} color={tint} normalScale={new THREE.Vector2(0.8, 0.8)} />
+}
+
+function WallMesh({ wall, walls, openings, material, finish, exterior, ctx }: { wall: Wall; walls: Wall[]; openings: Opening[]; material?: Material; finish: Finish | null; exterior: boolean; ctx: Ctx }) {
+ const geometry = useMemo(() => wallSolid(wall, walls, openings), [wall, walls, openings])
+ const raw = seamPattern(material, finish)
+ const pattern = ctx.look === 'real' && raw?.dir === 'horizontal' ? null : raw
+ const seams = useMemo(() => {
+ if (!pattern) return null
+ const g = new THREE.BufferGeometry()
+ g.setAttribute('position', new THREE.BufferAttribute(wallSeams(wall, openings, pattern), 3))
+ return g
+ }, [wall, openings, pattern?.dir, pattern?.step])
+ const edges = useMemo(() => {
+ const g = new THREE.BufferGeometry()
+ g.setAttribute('position', new THREE.BufferAttribute(wallEdges(wall, walls, openings), 3))
+ return g
+ }, [wall, walls, openings])
+ const painted = exterior ? ctx.colors.walls : null
+ const color = painted ?? modelColor(material, finish)
+ const model = ctx.look === 'model'
+ const metal = !model && painted && material?.kind === 'pir'
+ const natural = finish === 'osb' || finish === 'timber' || finish === 'planken'
+ const set = painted && !metal && (ctx.colors.explicitWalls || !natural) ? 'plaster' : textureSet(material, finish)
+ const tint = painted && set === 'plaster' ? painted : REAL_TINT[set]
+ return (
+ <group>
+ <mesh geometry={geometry}>
+ <meshBasicMaterial color="#2c3034" side={THREE.BackSide} />
+ </mesh>
+ <mesh geometry={geometry} castShadow receiveShadow>
+ {model ? (
+ <>
+ <meshStandardMaterial attach="material-0" color={shade(color, 0.66)} roughness={1} />
+ <meshStandardMaterial attach="material-1" color={color} roughness={1} />
+ </>
+ ) : metal ? (
+ <>
+ <meshStandardMaterial attach="material-0" color={shade(color, 0.7)} roughness={0.5} metalness={0.3} />
+ <meshStandardMaterial attach="material-1" color={color} roughness={0.45} metalness={0.3} />
+ </>
+ ) : (
+ <>
+ <RealSurface attach="material-0" set={set} base={ctx.texturesUrl} tint={painted ? shade(painted, 0.7) : '#a39c90'} />
+ <RealSurface attach="material-1" set={set} base={ctx.texturesUrl} tint={tint} />
+ </>
+ )}
+ </mesh>
+ {model && (
+ <lineSegments geometry={edges}>
+ <lineBasicMaterial color={PALETTE.model.edge} />
+ </lineSegments>
+ )}
+ {seams && (
+ <lineSegments geometry={seams}>
+ <lineBasicMaterial color={model ? shade(color, 0.8) : '#3b3024'} transparent opacity={model ? 0.9 : 0.5} />
+ </lineSegments>
+ )}
+ </group>
+ )
+}
+
+function Frame({ w, h, depth, profile, color, bottom = true }: { w: number; h: number; depth: number; profile: number; color: string; bottom?: boolean }) {
+ const d = Math.min(depth, 0.08)
+ const bars: [number, number, number, number][] = [
+ [0, h / 2 - profile / 2, w, profile],
+ [-w / 2 + profile / 2, 0, profile, h],
+ [w / 2 - profile / 2, 0, profile, h],
+ ]
+ if (bottom) bars.push([0, -h / 2 + profile / 2, w, profile])
+ return (
+ <>
+ {bars.map(([x, y, bw, bh], i) => (
+ <mesh key={i} castShadow position={[x, y, 0]}>
+ <boxGeometry args={[bw, bh, d]} />
+ <meshStandardMaterial color={color} roughness={0.6} />
+ </mesh>
+ ))}
+ </>
+ )
+}
+
+function outwardSign(wall: Wall, center: Point) {
+ const f = wallFrame(wall)
+ const mx = (wall.a.x + wall.b.x) / 2 - center.x
+ const my = (wall.a.y + wall.b.y) / 2 - center.y
+ return f.dir.x * my - f.dir.y * mx >= 0 ? -1 : 1
+}
+
+function Gate({ wall, o, look, colors }: { wall: Wall; o: Opening; look: Look; colors: Colors }) {
+ const t = openingPlacement(wall, o)
+ const w = o.width * M
+ const h = o.height * M
+ const frame = 0.035
+ const pw = w - frame * 2
+ const ph = h - frame
+ const count = Math.max(1, Math.round(ph / 0.5))
+ const lh = ph / count
+ const roughness = look === 'model' ? 1 : 0.55
+ return (
+ <group position={t.position} rotation={[0, t.rotationY, 0]}>
+ {Array.from({ length: count }, (_, i) => (
+ <mesh key={i} castShadow receiveShadow position={[0, -h / 2 + lh * (i + 0.5), 0]}>
+ <boxGeometry args={[pw, lh - 0.012, 0.04]} />
+ <meshStandardMaterial color={colors.gates} roughness={roughness} metalness={look === 'model' ? 0 : 0.35} />
+ </mesh>
+ ))}
+ <Frame w={w} h={h} depth={wall.thickness * M} profile={frame} color={colors.gates} bottom={false} />
+ </group>
+ )
+}
+
+function Door({ wall, o, colors }: { wall: Wall; o: Opening; colors: Colors }) {
+ const t = openingPlacement(wall, o)
+ const w = o.width * M
+ const h = o.height * M
+ const jamb = 0.05
+ return (
+ <group position={t.position} rotation={[0, t.rotationY, 0]}>
+ <mesh castShadow position={[0, -jamb / 2, 0]}>
+ <boxGeometry args={[w - jamb * 2, h - jamb, 0.045]} />
+ <meshStandardMaterial color={colors.windows} roughness={0.7} />
+ </mesh>
+ <Frame w={w} h={h} depth={wall.thickness * M} profile={jamb} color={colors.windows} bottom={false} />
+ </group>
+ )
+}
+
+function Window({ wall, o, out, look, colors }: { wall: Wall; o: Opening; out: number; look: Look; colors: Colors }) {
+ const t = openingPlacement(wall, o)
+ const w = o.width * M
+ const h = o.height * M
+ const depth = wall.thickness * M
+ const profile = 0.055
+ return (
+ <group position={t.position} rotation={[0, t.rotationY, 0]}>
+ <Frame w={w} h={h} depth={depth} profile={profile} color={colors.windows} />
+ {w > 1.2 && (
+ <mesh castShadow>
+ <boxGeometry args={[profile, h - profile * 2, Math.min(depth, 0.08)]} />
+ <meshStandardMaterial color={colors.windows} roughness={0.6} />
+ </mesh>
+ )}
+ <mesh>
+ <boxGeometry args={[w - profile * 2, h - profile * 2, 0.01]} />
+ {look === 'model' ? (
+ <meshStandardMaterial color="#c5d9e2" roughness={0.2} transparent opacity={0.55} />
+ ) : (
+ <meshPhysicalMaterial color="#9fc3d6" roughness={0.05} metalness={0.2} transparent opacity={0.4} envMapIntensity={1.5} />
+ )}
+ </mesh>
+ <mesh castShadow position={[0, -h / 2 - 0.015, out * (depth / 2 + 0.025)]}>
+ <boxGeometry args={[w + 0.06, 0.02, 0.07]} />
+ <meshStandardMaterial color={colors.accent} roughness={0.5} />
+ </mesh>
+ </group>
+ )
+}
+
+function siteOutline(plan: Plan): Point[] {
+ const { site } = plan
+ if (site.boundary && site.boundary.length >= 3) return site.boundary
+ return [
+ { x: 0, y: 0 },
+ { x: site.width, y: 0 },
+ { x: site.width, y: site.depth },
+ { x: 0, y: site.depth },
+ ]
+}
+
+function Lawn({ geometry, ctx }: { geometry: THREE.BufferGeometry; ctx: Ctx }) {
+ return (
+ <mesh geometry={geometry} receiveShadow>
+ {ctx.look === 'model' ? (
+ <meshStandardMaterial color={PALETTE.model.grass} roughness={1} />
+ ) : (
+ <Suspense fallback={<meshStandardMaterial color={PALETTE.model.grass} roughness={1} />}>
+ <RealSurface set="grass" base={ctx.texturesUrl} tint={GRASS_BOOST} />
+ </Suspense>
+ )}
+ </mesh>
+ )
+}
+
+function Site({ plan, grid, ctx }: { plan: Plan; grid: boolean; ctx: Ctx }) {
+ const outline = useMemo(() => siteOutline(plan), [plan])
+ const geometry = useMemo(() => {
+ const g = new THREE.ShapeGeometry(new THREE.Shape(outline.map((p) => new THREE.Vector2(p.x * M, -p.y * M))))
+ g.rotateX(-Math.PI / 2)
+ return worldUV(g)
+ }, [outline])
+ const b = bounds(outline)
+ const cx = ((b.minX + b.maxX) / 2) * M
+ const cz = ((b.minY + b.maxY) / 2) * M
+ const line = useMemo(() => [...outline, outline[0]].map((p) => [p.x * M, 0.01, p.y * M] as [number, number, number]), [outline])
+ const pal = PALETTE[ctx.look]
+ return (
+ <group>
+ <mesh position={[cx, -0.01, cz]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow>
+ <planeGeometry args={[600, 600]} />
+ <meshStandardMaterial color={pal.ground} roughness={1} />
+ </mesh>
+ <Lawn geometry={geometry} ctx={ctx} />
+ {grid && (
+ <Grid
+ position={[cx, 0.004, cz]}
+ args={[(b.maxX - b.minX) * M, (b.maxY - b.minY) * M]}
+ cellSize={1}
+ cellThickness={0.5}
+ cellColor={pal.grid}
+ sectionSize={5}
+ sectionThickness={0.9}
+ sectionColor={pal.section}
+ fadeDistance={140}
+ fadeStrength={3}
+ />
+ )}
+ <Line points={line} color="#ffffff" lineWidth={1.5} transparent opacity={0.9} />
+ </group>
+ )
+}
+
+function Slab({ plan, ctx }: { plan: Plan; ctx: Ctx }) {
+ const parts = useMemo(
+ () =>
+ wallGroups(plan.walls)
+ .map((group) => slabOutline(group, 100))
+ .filter((outline) => outline.length >= 3)
+ .map((outline) => {
+ const g = new THREE.ExtrudeGeometry(new THREE.Shape(outline.map((p) => new THREE.Vector2(p.x * M, -p.y * M))), { depth: SLAB, bevelEnabled: false })
+ g.rotateX(-Math.PI / 2)
+ return worldUV(g, SLAB)
+ }),
+ [plan.walls],
+ )
+ return (
+ <>
+ {parts.map((geometry, i) => (
+ <mesh key={i} geometry={geometry} castShadow receiveShadow>
+ {ctx.look === 'model' ? (
+ <>
+ <meshStandardMaterial attach="material-0" color={PALETTE.model.slab} roughness={1} />
+ <meshStandardMaterial attach="material-1" color={ctx.colors.plinth} roughness={1} />
+ </>
+ ) : (
+ <>
+ <RealSurface attach="material-0" set="concrete" base={ctx.texturesUrl} tint={PALETTE.real.slab} />
+ <RealSurface attach="material-1" set="concrete" base={ctx.texturesUrl} tint={ctx.colors.plinth} />
+ </>
+ )}
+ {ctx.look === 'model' && <Edges threshold={25} color={PALETTE.model.edge} />}
+ </mesh>
+ ))}
+ </>
+ )
+}
+
+function Rig({ view, nonce, target, fallback }: { view: View3D; nonce: number; target: React.RefObject<THREE.Object3D | null>; fallback: { x: number; z: number; r: number } }) {
+ const controls = useRef<CameraControls>(null)
+ const first = useRef(true)
+ useEffect(() => {
+ const c = controls.current
+ if (!c) return
+ const animate = !first.current
+ first.current = false
+ const v = VIEWS[view]
+ const id = requestAnimationFrame(() => {
+ c.rotateTo(v.azimuth, v.polar, animate)
+ if (!target.current) return
+ const box = new THREE.Box3().setFromObject(target.current)
+ const sphere = box.isEmpty() ? new THREE.Sphere(new THREE.Vector3(fallback.x, 0, fallback.z), fallback.r / 2 + 2) : box.getBoundingSphere(new THREE.Sphere())
+ sphere.radius *= v.fit
+ c.fitToSphere(sphere, animate)
+ })
+ return () => cancelAnimationFrame(id)
+ }, [view, nonce, target, fallback])
+ return <CameraControls ref={controls} makeDefault dollyToCursor minPolarAngle={0} maxPolarAngle={Math.PI / 2 - 0.02} minZoom={3} maxZoom={600} />
+}
+
+export type WallCut = 'full' | 'low' | 'floor'
+
+export const WALL_CUTS: { value: WallCut; label: string }[] = [
+ { value: 'full', get label() { return t('view3d:cuts.full') } },
+ { value: 'low', get label() { return t('view3d:cuts.low') } },
+ { value: 'floor', get label() { return t('view3d:cuts.floor') } },
+]
+
+const CUT_HEIGHT: Record<Exclude<WallCut, 'full'>, number> = { low: 1.0, floor: 0.1 }
+
+function Cutaway({ target, cut, top }: { target: React.RefObject<THREE.Group | null>; cut: WallCut; top: number }) {
+ const plane = useMemo(() => new THREE.Plane(new THREE.Vector3(0, -1, 0), SLAB + top + 0.1), [])
+ const planes = useMemo(() => [plane], [plane])
+ useFrame((_, dt) => {
+ const goal = SLAB + (cut === 'full' ? top + 0.1 : CUT_HEIGHT[cut])
+ plane.constant = Math.abs(plane.constant - goal) < 0.002 ? goal : THREE.MathUtils.damp(plane.constant, goal, 14, Math.min(dt, 0.1))
+ target.current?.traverse((o) => {
+ const m = (o as THREE.Mesh).material as THREE.Material | THREE.Material[] | undefined
+ if (!m) return
+ for (const mat of Array.isArray(m) ? m : [m]) {
+ if (mat.clippingPlanes === planes) continue
+ mat.clippingPlanes = planes
+ mat.clipShadows = true
+ mat.needsUpdate = true
+ }
+ })
+ })
+ return null
+}
+
+function HouseBody({ plan, ctx, finishOverride, roof, cut }: { plan: Plan; ctx: Ctx; finishOverride: Finish | null; roof?: ReactNode; cut: WallCut }) {
+ const cutRef = useRef<THREE.Group>(null)
+ const materials = useMemo(() => new Map(plan.materials.map((m) => [m.id, m as Material])), [plan.materials])
+ const byWall = useMemo(() => {
+ const map = new Map<string, Opening[]>()
+ for (const o of plan.openings) map.set(o.wallId, [...(map.get(o.wallId) ?? []), o])
+ return map
+ }, [plan.openings])
+ const wallsById = useMemo(() => new Map(plan.walls.map((w) => [w.id, w])), [plan.walls])
+ const center = useMemo<Point>(() => {
+ const b = bounds(plan.walls.flatMap((w) => [w.a, w.b]))
+ return { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 }
+ }, [plan.walls])
+ const wallTop = plan.walls.reduce((h, w) => Math.max(h, w.height * M), 0)
+ const exterior = useMemo(() => exteriorWalls(plan.walls), [plan.walls])
+ const empty: Opening[] = []
+ return (
+ <>
+ <Slab plan={plan} ctx={ctx} />
+ <group position={[0, SLAB, 0]} ref={cutRef}>
+ {plan.walls.map((w) => {
+ const material = w.materialId ? materials.get(w.materialId) : undefined
+ return (
+ <WallMesh
+ key={w.id}
+ wall={w}
+ walls={plan.walls}
+ openings={byWall.get(w.id) ?? empty}
+ material={material}
+ finish={finishOf(material, finishOverride)}
+ exterior={exterior.has(w.id)}
+ ctx={ctx}
+ />
+ )
+ })}
+ {plan.openings.map((o) => {
+ const w = wallsById.get(o.wallId)
+ if (!w) return null
+ const type = o.type as string
+ if (type === 'door') return <Door key={o.id} wall={w} o={o} colors={ctx.colors} />
+ if (type === 'window') return <Window key={o.id} wall={w} o={o} out={outwardSign(w, center)} look={ctx.look} colors={ctx.colors} />
+ if (type === 'gate') return <Gate key={o.id} wall={w} o={o} look={ctx.look} colors={ctx.colors} />
+ return null
+ })}
+ <group name="roof" position={[0, wallTop, 0]} visible={cut === 'full'}>
+ {roof}
+ </group>
+ </group>
+ <Cutaway target={cutRef} cut={cut} top={wallTop} />
+ </>
+ )
+}
+
+
+export const defaultTexturesUrl = () => `${import.meta.env.BASE_URL}textures/`
+
+export const primaryFinish = (plan: Plan): Finish | null => {
+ const m = plan.materials.find((x) => x.kind === 'sip' || x.kind === 'pir' || x.kind === 'frame') as Material | undefined
+ return m ? (m.finish ?? 'osb') : null
+}
+
+export type Scene3DProps = {
+ plan: Plan
+ view: View3D
+ nonce: number
+ look: Look
+ grid: boolean
+ finishOverride: Finish | null
+ roof?: ReactNode
+ texturesUrl?: string
+ renderFurniture?: (item: FurnitureItem) => ReactNode
+ cut?: WallCut
+}
+
+function Furniture({ plan, render }: { plan: Plan; render: (item: FurnitureItem) => ReactNode }) {
+ const items = ((plan as Plan & { furniture?: FurnitureItem[] }).furniture ?? []).filter((i) => i && Number.isFinite(i.x) && Number.isFinite(i.y))
+ return (
+ <group position={[0, SLAB, 0]}>
+ {items.map((item) => (
+ <group key={item.id} position={[item.x * M, 0, item.y * M]} rotation={[0, (-(item.rotationDeg || 0) * Math.PI) / 180, 0]}>
+ <Suspense fallback={null}>{render(item)}</Suspense>
+ </group>
+ ))}
+ </group>
+ )
+}
+
+export function Scene3D({ plan: rawPlan, view, nonce, look, grid, finishOverride, roof, texturesUrl, renderFurniture, cut = 'full' }: Scene3DProps) {
+ const plan = useMemo(() => sanitizePlan(rawPlan), [rawPlan])
+ const house = useRef<THREE.Group>(null)
+ const base = texturesUrl ?? defaultTexturesUrl()
+ const palette = (rawPlan as Plan & { palette?: Palette }).palette
+ const colors = useMemo(() => resolveColors(palette), [palette])
+ const ctx = useMemo<Ctx>(() => ({ look, texturesUrl: base, colors }), [look, base, colors])
+ const modelCtx = useMemo<Ctx>(() => ({ look: 'model', texturesUrl: base, colors }), [base, colors])
+ const focus = useMemo(() => {
+ const pts = plan.walls.length ? plan.walls.flatMap((w) => [w.a, w.b]) : siteOutline(plan)
+ const b = bounds(pts)
+ const r = Math.max(b.maxX - b.minX, b.maxY - b.minY) * M
+ return { x: ((b.minX + b.maxX) / 2) * M, z: ((b.minY + b.maxY) / 2) * M, r: Math.max(r, 6) }
+ }, [plan])
+ const pal = PALETTE[look]
+ const s = focus.r * 1.2 + 4
+
+ return (
+ <Canvas
+ shadows="percentage"
+ orthographic
+ dpr={[1, 2]}
+ gl={{ antialias: false, stencil: false }}
+ onCreated={({ gl }) => {
+ gl.localClippingEnabled = true
+ }}
+ camera={{ position: [focus.x + 30, 30, focus.z + 30], zoom: 40, near: 0.1, far: 2000 }}
+ >
+ <color attach="background" args={[pal.background]} />
+ <hemisphereLight args={['#ffffff', '#c9cdbf', look === 'model' ? 1.1 : 1.3]} />
+ <directionalLight
+ castShadow
+ position={[focus.x + 14, 22, focus.z + 9]}
+ intensity={look === 'model' ? 1.9 : 2.6}
+ shadow-mapSize={[4096, 4096]}
+ shadow-bias={-0.0003}
+ shadow-normalBias={0.02}
+ shadow-radius={6}
+ shadow-camera-left={-s}
+ shadow-camera-right={s}
+ shadow-camera-top={s}
+ shadow-camera-bottom={-s}
+ shadow-camera-near={1}
+ shadow-camera-far={120}
+ >
+ <object3D attach="target" position={[focus.x, 0, focus.z]} />
+ </directionalLight>
+ <Environment resolution={256}>
+ <Lightformer form="rect" intensity={1.4} position={[0, 10, 0]} rotation-x={Math.PI / 2} scale={[30, 30, 1]} />
+ <Lightformer form="rect" intensity={0.7} position={[-12, 4, 6]} rotation-y={Math.PI / 2} scale={[30, 6, 1]} />
+ <Lightformer form="rect" intensity={0.5} position={[12, 4, -6]} rotation-y={-Math.PI / 2} scale={[30, 6, 1]} />
+ </Environment>
+ <Site plan={plan} grid={grid} ctx={ctx} />
+ <group ref={house}>
+ {look === 'model' ? (
+ <HouseBody plan={plan} ctx={ctx} finishOverride={finishOverride} roof={roof} cut={cut} />
+ ) : (
+ <Suspense fallback={<HouseBody plan={plan} ctx={modelCtx} finishOverride={finishOverride} roof={roof} cut={cut} />}>
+ <HouseBody plan={plan} ctx={ctx} finishOverride={finishOverride} roof={roof} cut={cut} />
+ </Suspense>
+ )}
+ </group>
+ {renderFurniture && <Furniture plan={plan} render={renderFurniture} />}
+ <Rig view={view} nonce={nonce} target={house} fallback={focus} />
+ <EffectComposer multisampling={4} enableNormalPass={false}>
+ <N8AO halfRes quality="medium" aoRadius={1.2} distanceFalloff={0.8} intensity={look === 'model' ? 2.4 : 1.8} color="#1e2224" />
+ <ToneMapping mode={ToneMappingMode.NEUTRAL} />
+ </EffectComposer>
+ </Canvas>
+ )
+}
diff --git a/src/view3d/geometry.ts b/src/view3d/geometry.ts
new file mode 100644
index 0000000..478e907
--- /dev/null
+++ b/src/view3d/geometry.ts
@@ -0,0 +1,427 @@
+import * as THREE from 'three'
+import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg'
+import type { Opening, Point, Wall } from './types'
+
+const EPS = 1
+
+type V = { x: number; y: number }
+
+const sub = (a: V, b: V): V => ({ x: a.x - b.x, y: a.y - b.y })
+const add = (a: V, b: V): V => ({ x: a.x + b.x, y: a.y + b.y })
+const mul = (a: V, k: number): V => ({ x: a.x * k, y: a.y * k })
+const len = (a: V) => Math.hypot(a.x, a.y)
+const norm = (a: V): V => mul(a, 1 / (len(a) || 1))
+const cross = (a: V, b: V) => a.x * b.y - a.y * b.x
+const left = (a: V): V => ({ x: -a.y, y: a.x })
+const same = (a: Point, b: Point) => Math.abs(a.x - b.x) < EPS && Math.abs(a.y - b.y) < EPS
+
+function intersect(p1: V, d1: V, p2: V, d2: V): V | null {
+ const den = cross(d1, d2)
+ if (Math.abs(den) < 1e-9) return null
+ const t = cross(sub(p2, p1), d2) / den
+ return add(p1, mul(d1, t))
+}
+
+type Arm = { wall: Wall; dir: V }
+
+function armsAt(p: Point, walls: Wall[], self: Wall): Arm[] {
+ const arms: Arm[] = []
+ for (const w of walls) {
+ if (w === self) continue
+ if (same(w.a, p)) arms.push({ wall: w, dir: norm(sub(w.b, w.a)) })
+ else if (same(w.b, p)) arms.push({ wall: w, dir: norm(sub(w.a, w.b)) })
+ }
+ return arms
+}
+
+const angle = (v: V) => Math.atan2(v.y, v.x)
+
+function cornerSide(p: Point, dir: V, half: number, arms: Arm[], side: 1 | -1): V {
+ const n = mul(left(dir), side)
+ const base = add(p, mul(n, half))
+ if (!arms.length) return base
+ const a0 = angle(dir)
+ let best: Arm | null = null
+ let bestDelta = Infinity
+ for (const arm of arms) {
+ let delta = (angle(arm.dir) - a0) * side
+ while (delta <= 0) delta += Math.PI * 2
+ if (delta < bestDelta) {
+ bestDelta = delta
+ best = arm
+ }
+ }
+ if (!best) return base
+ const on = add(p, mul(left(best.dir), -side * (best.wall.thickness / 2)))
+ const hit = intersect(base, dir, on, best.dir)
+ if (!hit) return base
+ const limit = Math.max(half, best.wall.thickness / 2) * 4
+ return len(sub(hit, p)) > limit ? base : hit
+}
+
+export function wallFootprint(wall: Wall, walls: Wall[]): Point[] {
+ const dir = norm(sub(wall.b, wall.a))
+ const back = mul(dir, -1)
+ const half = wall.thickness / 2
+ const armsA = armsAt(wall.a, walls, wall)
+ const armsB = armsAt(wall.b, walls, wall)
+ const aL = cornerSide(wall.a, dir, half, armsA, 1)
+ const aR = cornerSide(wall.a, dir, half, armsA, -1)
+ const bR = cornerSide(wall.b, back, half, armsB, 1)
+ const bL = cornerSide(wall.b, back, half, armsB, -1)
+ return [aR, bR, bL, aL]
+}
+
+export function wallFrame(wall: Wall) {
+ const d = sub(wall.b, wall.a)
+ return { length: len(d), dir: norm(d), angle: Math.atan2(d.y, d.x) }
+}
+
+export function bounds(points: Point[]) {
+ let minX = Infinity
+ let minY = Infinity
+ let maxX = -Infinity
+ let maxY = -Infinity
+ for (const p of points) {
+ minX = Math.min(minX, p.x)
+ minY = Math.min(minY, p.y)
+ maxX = Math.max(maxX, p.x)
+ maxY = Math.max(maxY, p.y)
+ }
+ return { minX, minY, maxX, maxY }
+}
+
+const M = 0.001
+
+export function worldUV(source: THREE.BufferGeometry, capTop?: number) {
+ const g = source.index ? source.toNonIndexed() : source
+ const pos = g.getAttribute('position')
+ const count = pos.count / 3
+ const a = new THREE.Vector3()
+ const b = new THREE.Vector3()
+ const c = new THREE.Vector3()
+ const n = new THREE.Vector3()
+ const caps: number[][] = []
+ const sides: number[][] = []
+ for (let i = 0; i < count; i++) {
+ a.fromBufferAttribute(pos, i * 3)
+ b.fromBufferAttribute(pos, i * 3 + 1)
+ c.fromBufferAttribute(pos, i * 3 + 2)
+ n.copy(c).sub(b).cross(new THREE.Vector3().copy(a).sub(b)).normalize()
+ const horizontal = Math.abs(n.y) > 0.9
+ const tx = -n.z
+ const tz = n.x
+ const tl = Math.hypot(tx, tz) || 1
+ const tri: number[] = []
+ for (const v of [a, b, c]) {
+ const u = horizontal ? v.x : (v.x * tx + v.z * tz) / tl
+ const w = horizontal ? -v.z : v.y
+ tri.push(v.x, v.y, v.z, n.x, n.y, n.z, u, w)
+ }
+ const cy = (a.y + b.y + c.y) / 3
+ const isCap = capTop !== undefined && horizontal && (cy > capTop - 1e-3 || cy < 1e-3)
+ ;(isCap ? caps : sides).push(tri)
+ }
+ const all = [...caps, ...sides]
+ const position = new Float32Array(all.length * 9)
+ const normal = new Float32Array(all.length * 9)
+ const uv = new Float32Array(all.length * 6)
+ all.forEach((tri, t) => {
+ for (let k = 0; k < 3; k++) {
+ const o = k * 8
+ position.set(tri.slice(o, o + 3), t * 9 + k * 3)
+ normal.set(tri.slice(o + 3, o + 6), t * 9 + k * 3)
+ uv.set(tri.slice(o + 6, o + 8), t * 6 + k * 2)
+ }
+ })
+ const out = new THREE.BufferGeometry()
+ out.setAttribute('position', new THREE.BufferAttribute(position, 3))
+ out.setAttribute('normal', new THREE.BufferAttribute(normal, 3))
+ out.setAttribute('uv', new THREE.BufferAttribute(uv, 2))
+ out.addGroup(0, caps.length * 3, 0)
+ out.addGroup(caps.length * 3, sides.length * 3, 1)
+ out.computeBoundingBox()
+ out.computeBoundingSphere()
+ return out
+}
+
+export function openingPlacement(wall: Wall, o: Opening) {
+ const f = wallFrame(wall)
+ const c = (o.offset + o.width / 2) / f.length
+ const x = (wall.a.x + (wall.b.x - wall.a.x) * c) * M
+ const z = (wall.a.y + (wall.b.y - wall.a.y) * c) * M
+ const y = (o.sill + o.height / 2) * M
+ return { position: [x, y, z] as [number, number, number], rotationY: -f.angle }
+}
+
+const evaluator = new Evaluator()
+evaluator.attributes = ['position', 'normal']
+evaluator.useGroups = false
+
+export function wallSolid(wall: Wall, walls: Wall[], openings: Opening[]) {
+ const shape = new THREE.Shape(wallFootprint(wall, walls).map((p) => new THREE.Vector2(p.x * M, -p.y * M)))
+ const base = new THREE.ExtrudeGeometry(shape, { depth: wall.height * M, bevelEnabled: false })
+ base.rotateX(-Math.PI / 2)
+ base.deleteAttribute('uv')
+ let brush = new Brush(base)
+ brush.updateMatrixWorld()
+ for (const o of openings) {
+ const box = new THREE.BoxGeometry(o.width * M, o.height * M, wall.thickness * M + 0.3)
+ box.deleteAttribute('uv')
+ const cut = new Brush(box)
+ const p = openingPlacement(wall, o)
+ cut.position.set(...p.position)
+ cut.rotation.y = p.rotationY
+ cut.updateMatrixWorld()
+ try {
+ brush = evaluator.evaluate(brush, cut, SUBTRACTION)
+ } catch {
+ continue
+ }
+ }
+ return worldUV(brush.geometry, wall.height * M)
+}
+
+export type SeamPattern = { dir: 'vertical' | 'horizontal'; step: number }
+
+export function wallSeams(wall: Wall, openings: Opening[], pattern: SeamPattern) {
+ const f = wallFrame(wall)
+ const L = f.length
+ const H = wall.height
+ const nx = -f.dir.y
+ const ny = f.dir.x
+ const off = wall.thickness / 2 + 2
+ const out: number[] = []
+ const push = (s: number, y0: number, s2: number, y1: number) => {
+ for (const side of [1, -1]) {
+ const px = (t: number) => (wall.a.x + f.dir.x * t + nx * off * side) * M
+ const pz = (t: number) => (wall.a.y + f.dir.y * t + ny * off * side) * M
+ out.push(px(s), y0 * M, pz(s), px(s2), y1 * M, pz(s2))
+ }
+ }
+ const margin = wall.thickness
+ if (pattern.dir === 'vertical') {
+ for (let s = pattern.step; s < L - margin; s += pattern.step) {
+ if (s < margin) continue
+ let spans: [number, number][] = [[0, H]]
+ for (const o of openings) {
+ if (s <= o.offset || s >= o.offset + o.width) continue
+ spans = spans.flatMap(([y0, y1]) => {
+ const r: [number, number][] = []
+ if (o.sill > y0) r.push([y0, Math.min(y1, o.sill)])
+ if (o.sill + o.height < y1) r.push([Math.max(y0, o.sill + o.height), y1])
+ return r
+ })
+ }
+ for (const [y0, y1] of spans) if (y1 - y0 > 1) push(s, y0, s, y1)
+ }
+ } else {
+ for (let y = pattern.step; y < H - 1; y += pattern.step) {
+ let spans: [number, number][] = [[margin / 2, L - margin / 2]]
+ for (const o of openings) {
+ if (y <= o.sill || y >= o.sill + o.height) continue
+ spans = spans.flatMap(([s0, s1]) => {
+ const r: [number, number][] = []
+ if (o.offset > s0) r.push([s0, Math.min(s1, o.offset)])
+ if (o.offset + o.width < s1) r.push([Math.max(s0, o.offset + o.width), s1])
+ return r
+ })
+ }
+ for (const [s0, s1] of spans) if (s1 - s0 > 1) push(s0, y, s1, y)
+ }
+ }
+ return new Float32Array(out)
+}
+
+export function wallEdges(wall: Wall, walls: Wall[], openings: Opening[]) {
+ const H = wall.height * M
+ const fp = wallFootprint(wall, walls).map((p) => [p.x * M, p.y * M] as const)
+ const out: number[] = []
+ for (let i = 0; i < fp.length; i++) {
+ const [x0, z0] = fp[i]
+ const [x1, z1] = fp[(i + 1) % fp.length]
+ out.push(x0, H, z0, x1, H, z1)
+ out.push(x0, 0, z0, x0, H, z0)
+ }
+ const f = wallFrame(wall)
+ const nx = -f.dir.y
+ const ny = f.dir.x
+ const half = wall.thickness / 2
+ const at = (s: number, side: number, y: number) => [(wall.a.x + f.dir.x * s + nx * half * side) * M, y * M, (wall.a.y + f.dir.y * s + ny * half * side) * M]
+ for (const o of openings) {
+ const s0 = o.offset
+ const s1 = o.offset + o.width
+ const y0 = o.sill
+ const y1 = o.sill + o.height
+ for (const side of [1, -1]) {
+ const c = [at(s0, side, y0), at(s1, side, y0), at(s1, side, y1), at(s0, side, y1)]
+ for (let i = 0; i < 4; i++) {
+ if (y0 === 0 && i === 0) continue
+ out.push(...c[i], ...c[(i + 1) % 4])
+ }
+ }
+ for (const [s, y] of [[s0, y0], [s1, y0], [s1, y1], [s0, y1]]) out.push(...at(s, 1, y), ...at(s, -1, y))
+ }
+ return new Float32Array(out)
+}
+
+type PlanLike = { walls: Wall[]; openings: Opening[] }
+
+export function sanitizePlan<P extends PlanLike>(plan: P): P {
+ const ok = (n: unknown) => typeof n === 'number' && Number.isFinite(n)
+ const walls = (plan.walls ?? []).filter(
+ (w) => w && ok(w.a?.x) && ok(w.a?.y) && ok(w.b?.x) && ok(w.b?.y) && ok(w.thickness) && ok(w.height) && w.thickness > 0 && w.height > 0 && Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) > 1,
+ )
+ const byId = new Map(walls.map((w) => [w.id, w]))
+ const openings: Opening[] = []
+ for (const o of plan.openings ?? []) {
+ const w = o && byId.get(o.wallId)
+ if (!w || !ok(o.offset) || !ok(o.width) || !ok(o.height)) continue
+ const L = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y)
+ const start = Math.min(Math.max(o.offset, 0), L)
+ const width = Math.min(o.width, L - start)
+ const sill = Math.min(Math.max(ok(o.sill) ? o.sill : 0, 0), w.height)
+ const height = Math.min(o.height, w.height - sill)
+ if (width < 10 || height < 10) continue
+ openings.push({ ...o, offset: start, width, sill, height })
+ }
+ return { ...plan, walls, openings }
+}
+
+const key = (p: Point) => `${Math.round(p.x)}:${Math.round(p.y)}`
+
+function wallLoop(walls: Wall[]): Point[] | null {
+ const adj = new Map<string, Set<string>>()
+ const pts = new Map<string, Point>()
+ const link = (a: Point, b: Point) => {
+ const ka = key(a)
+ const kb = key(b)
+ if (ka === kb) return
+ pts.set(ka, a)
+ pts.set(kb, b)
+ if (!adj.has(ka)) adj.set(ka, new Set())
+ if (!adj.has(kb)) adj.set(kb, new Set())
+ adj.get(ka)!.add(kb)
+ adj.get(kb)!.add(ka)
+ }
+ for (const w of walls) link(w.a, w.b)
+ let pruned = true
+ while (pruned) {
+ pruned = false
+ for (const [k, s] of adj) {
+ if (s.size > 1) continue
+ for (const n of s) adj.get(n)?.delete(k)
+ adj.delete(k)
+ pruned = true
+ }
+ }
+ if (adj.size < 3 || [...adj.values()].some((s) => s.size !== 2)) return null
+ const start = adj.keys().next().value as string
+ const loop: Point[] = [pts.get(start)!]
+ let prev = start
+ let cur = [...adj.get(start)!][0]
+ while (cur !== start) {
+ loop.push(pts.get(cur)!)
+ const next = [...adj.get(cur)!].find((n) => n !== prev)
+ if (!next || loop.length > adj.size) return null
+ prev = cur
+ cur = next
+ }
+ return loop.length === adj.size ? loop : null
+}
+
+function hull(points: Point[]): Point[] {
+ const p = [...points].sort((a, b) => a.x - b.x || a.y - b.y)
+ if (p.length < 3) return p
+ const turn = (o: Point, a: Point, b: Point) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
+ const lower: Point[] = []
+ for (const q of p) {
+ while (lower.length >= 2 && turn(lower[lower.length - 2], lower[lower.length - 1], q) <= 0) lower.pop()
+ lower.push(q)
+ }
+ const upper: Point[] = []
+ for (const q of [...p].reverse()) {
+ while (upper.length >= 2 && turn(upper[upper.length - 2], upper[upper.length - 1], q) <= 0) upper.pop()
+ upper.push(q)
+ }
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)]
+}
+
+function offsetPolygon(poly: Point[], d: number): Point[] {
+ const area = poly.reduce((s, p, i) => s + cross(p, poly[(i + 1) % poly.length]), 0)
+ const sign = area > 0 ? -1 : 1
+ const n = poly.length
+ return poly.map((p, i) => {
+ const prev = poly[(i - 1 + n) % n]
+ const next = poly[(i + 1) % n]
+ const d1 = norm(sub(p, prev))
+ const d2 = norm(sub(next, p))
+ const o1 = add(prev, mul(left(d1), sign * d))
+ const o2 = add(p, mul(left(d2), sign * d))
+ const hit = intersect(o1, d1, o2, d2)
+ return hit && len(sub(hit, p)) < d * 4 ? hit : add(p, mul(left(d1), sign * d))
+ })
+}
+
+export function slabOutline(walls: Wall[], margin: number): Point[] {
+ if (!walls.length) return []
+ const loop = wallLoop(walls)
+ if (loop) {
+ const t = Math.max(...walls.map((w) => w.thickness))
+ return offsetPolygon(loop, t / 2 + margin)
+ }
+ return offsetPolygon(hull(walls.flatMap((w) => wallFootprint(w, walls))), margin)
+}
+
+function touches(p: Point, w: Wall) {
+ const d = sub(w.b, w.a)
+ const l2 = d.x * d.x + d.y * d.y || 1
+ const t = Math.max(0, Math.min(1, ((p.x - w.a.x) * d.x + (p.y - w.a.y) * d.y) / l2))
+ return len(sub(p, add(w.a, mul(d, t)))) <= w.thickness
+}
+
+export function wallGroups(walls: Wall[]): Wall[][] {
+ const parent = walls.map((_, i) => i)
+ const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])))
+ for (let i = 0; i < walls.length; i++) {
+ for (let j = i + 1; j < walls.length; j++) {
+ const a = walls[i]
+ const b = walls[j]
+ if (touches(a.a, b) || touches(a.b, b) || touches(b.a, a) || touches(b.b, a)) parent[find(i)] = find(j)
+ }
+ }
+ const groups = new Map<number, Wall[]>()
+ walls.forEach((w, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), w]))
+ return [...groups.values()]
+}
+
+function inside(p: Point, poly: Point[]) {
+ let hit = false
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
+ const a = poly[i]
+ const b = poly[j]
+ if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) hit = !hit
+ }
+ return hit
+}
+
+export function exteriorWalls(walls: Wall[]): Set<string> {
+ const out = new Set<string>()
+ for (const group of wallGroups(walls)) {
+ const outline = slabOutline(group, 0)
+ for (const w of group) {
+ if (outline.length < 3) {
+ out.add(w.id)
+ continue
+ }
+ const f = wallFrame(w)
+ const mid = { x: (w.a.x + w.b.x) / 2, y: (w.a.y + w.b.y) / 2 }
+ const n = { x: -f.dir.y, y: f.dir.x }
+ const d = w.thickness / 2 + 60
+ const p1 = { x: mid.x + n.x * d, y: mid.y + n.y * d }
+ const p2 = { x: mid.x - n.x * d, y: mid.y - n.y * d }
+ if (!inside(p1, outline) || !inside(p2, outline)) out.add(w.id)
+ }
+ }
+ return out
+}
diff --git a/src/view3d/index.tsx b/src/view3d/index.tsx
new file mode 100644
index 0000000..39c5649
--- /dev/null
+++ b/src/view3d/index.tsx
@@ -0,0 +1,108 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { Palette, Plan } from '../model'
+import { FurnitureModel } from '../furniture'
+import { useViewOnly } from '../store/viewOnly'
+import { Button, CanvasToolbar, Segmented, ToolbarSeparator } from '../ui'
+import { ColorPicker } from './ColorPicker'
+import { SceneErrorBoundary } from './ErrorBoundary'
+import { DEFAULT_ACCENT, DEFAULT_WALLS } from './palette'
+import { FINISHES, type Look } from './looks'
+import { LOOKS, Scene3D, VIEWS, WALL_CUTS, primaryFinish, type View3D, type WallCut } from './Scene'
+import type { Finish } from './types'
+import './view3d.css'
+
+const lookOptions = () => LOOKS.map((l) => ({ value: l.id, label: l.label }))
+const viewOptions = () => (Object.keys(VIEWS) as View3D[]).map((v) => ({ value: v, label: VIEWS[v].label }))
+const finishOptions = () => FINISHES.map((f) => ({ value: f.id, label: f.label }))
+const hasFinish = (kind: string) => kind === 'sip' || kind === 'pir' || kind === 'frame'
+
+const CUT_KEY = 'house-planner:view3d-cut'
+
+const readCut = (): WallCut => {
+ try {
+ const v = localStorage.getItem(CUT_KEY)
+ return v === 'low' || v === 'floor' ? v : 'full'
+ } catch {
+ return 'full'
+ }
+}
+
+type Props = { plan: Plan; onChange?: (next: Plan) => void }
+
+export default function View3DSection({ plan, onChange }: Props) {
+ const { t } = useTranslation('view3d')
+ const [view, setView] = useState<View3D>('iso')
+ const [look, setLook] = useState<Look>('model')
+ const viewOnly = useViewOnly()
+ const [grid, setGrid] = useState(true)
+ const [cut, setCutState] = useState<WallCut>(readCut)
+ const setCut = (v: WallCut) => {
+ setCutState(v)
+ try {
+ localStorage.setItem(CUT_KEY, v)
+ } catch {
+ return
+ }
+ }
+ const [nonce, setNonce] = useState(0)
+ const [finishOverride, setFinishOverride] = useState<Finish | null>(null)
+ const currentFinish = finishOverride ?? primaryFinish(plan)
+ const [paletteOverride, setPaletteOverride] = useState<Palette | null>(null)
+ const palette: Palette = paletteOverride ?? plan.palette ?? {}
+ const shown = paletteOverride ? { ...plan, palette: paletteOverride } : plan
+ const writePalette = (next: Palette) => {
+ if (!onChange) return setPaletteOverride(next)
+ setPaletteOverride(null)
+ onChange({ ...plan, palette: next })
+ }
+ const pickWalls = (ral: string) => writePalette({ ...palette, name: undefined, walls: ral })
+ const pickAccent = (ral: string) => writePalette({ ...palette, name: undefined, accent: ral, windows: ral, gates: ral, plinth: ral })
+
+ const pickView = (v: View3D) => (v === view ? setNonce((n) => n + 1) : setView(v))
+ const pickFinish = (finish: Finish) => {
+ if (!onChange) return setFinishOverride(finish)
+ setFinishOverride(null)
+ onChange({ ...plan, materials: plan.materials.map((m) => (hasFinish(m.kind) ? { ...m, finish } : m)) })
+ }
+
+ return (
+ <div className="view3d">
+ <SceneErrorBoundary resetKey={plan}>
+ <Scene3D
+ plan={shown}
+ view={view}
+ nonce={nonce}
+ look={look}
+ grid={grid}
+ finishOverride={finishOverride}
+ cut={cut}
+ renderFurniture={(item) => <FurnitureModel item={item} placed={false} look={look} />}
+ />
+ </SceneErrorBoundary>
+ <CanvasToolbar placement="top-left" className="view3d__bar">
+ <Segmented options={lookOptions()} value={look} onChange={setLook} size="sm" />
+ <ToolbarSeparator />
+ <Segmented options={viewOptions()} value={view} onChange={pickView} size="sm" />
+ <ToolbarSeparator />
+ <Segmented options={WALL_CUTS} value={cut} onChange={setCut} size="sm" />
+ <ToolbarSeparator />
+ <Button size="sm" variant="ghost" pressed={grid} onClick={() => setGrid((g) => !g)}>
+ {t('toolbar.grid')}
+ </Button>
+ </CanvasToolbar>
+ {currentFinish && !viewOnly && (
+ <CanvasToolbar placement="top-right" className="view3d__bar view3d__finish">
+ <span className="view3d__label">{t('toolbar.facade')}</span>
+ <Segmented options={finishOptions()} value={currentFinish} onChange={pickFinish} size="sm" />
+ </CanvasToolbar>
+ )}
+ {!viewOnly && (
+ <CanvasToolbar placement="top-right" className="view3d__colors">
+ <ColorPicker label={t('toolbar.wallColor')} value={palette.walls ?? DEFAULT_WALLS} onPick={pickWalls} presets={writePalette} />
+ <ColorPicker label={t('toolbar.accent')} value={palette.accent ?? DEFAULT_ACCENT} onPick={pickAccent} />
+ </CanvasToolbar>
+ )}
+ </div>
+ )
+}
diff --git a/src/view3d/looks.ts b/src/view3d/looks.ts
new file mode 100644
index 0000000..9a43c20
--- /dev/null
+++ b/src/view3d/looks.ts
@@ -0,0 +1,86 @@
+import { t } from '../i18n'
+import type { Finish, Material, MaterialKind } from './types'
+import type { SeamPattern } from './geometry'
+
+export type Look = 'model' | 'real'
+
+export type TextureSet = 'osb' | 'plaster' | 'timber' | 'planken' | 'brick' | 'concrete' | 'grass'
+
+export const TEXTURE_SIZE: Record<TextureSet, [number, number]> = {
+ osb: [1.25, 1.25],
+ plaster: [2.0, 2.0],
+ timber: [1.4, 1.4],
+ planken: [2.24, 1.12],
+ brick: [2.4, 1.2],
+ concrete: [1.1, 0.55],
+ grass: [1.4, 1.4],
+}
+
+export const FINISHES: { id: Finish; label: string }[] = [
+ { id: 'osb', label: 'OSB' },
+ { id: 'plaster', get label() { return t('view3d:finishes.plaster') } },
+ { id: 'timber', get label() { return t('view3d:finishes.timber') } },
+ { id: 'planken', get label() { return t('view3d:finishes.planken') } },
+]
+
+const hasFinish = (kind: MaterialKind) => kind === 'sip' || kind === 'pir' || kind === 'frame'
+
+export function finishOf(material: Material | undefined, override: Finish | null): Finish | null {
+ if (!material || !hasFinish(material.kind)) return null
+ return override ?? material.finish ?? 'osb'
+}
+
+const MODEL_BY_FINISH: Record<Finish, string> = {
+ osb: '#ebe3d3',
+ plaster: '#f2f0eb',
+ timber: '#e0cfb2',
+ planken: '#c9bba7',
+}
+
+const MODEL_BY_KIND: Record<MaterialKind, string> = {
+ sip: '#ebe3d3',
+ pir: '#ebe3d3',
+ frame: '#ebe3d3',
+ brick: '#d4a592',
+ block: '#e3e1db',
+ timber: '#e0cfb2',
+ concrete: '#dcdcd8',
+ glass: '#dce9ee',
+ other: '#e8e6e1',
+}
+
+export function modelColor(material: Material | undefined, finish: Finish | null) {
+ if (material?.color) return material.color
+ if (finish) return MODEL_BY_FINISH[finish]
+ return MODEL_BY_KIND[material?.kind ?? 'other']
+}
+
+export function textureSet(material: Material | undefined, finish: Finish | null): TextureSet {
+ if (finish) return finish
+ switch (material?.kind) {
+ case 'brick':
+ return 'brick'
+ case 'timber':
+ return 'timber'
+ case 'concrete':
+ return 'concrete'
+ default:
+ return 'plaster'
+ }
+}
+
+export function seamPattern(material: Material | undefined, finish: Finish | null): SeamPattern | null {
+ if (finish === 'osb') {
+ const panel = material ? Math.min(material.length ?? 1250, material.height ?? 1250) : 1250
+ return { dir: 'vertical', step: panel }
+ }
+ if (finish === 'timber' || material?.kind === 'timber') return { dir: 'horizontal', step: 180 }
+ if (finish === 'planken') return { dir: 'horizontal', step: 140 }
+ return null
+}
+
+export function shade(hex: string, k: number) {
+ const n = parseInt(hex.replace('#', ''), 16)
+ const ch = (s: number) => Math.max(0, Math.min(255, Math.round(((n >> s) & 255) * k)))
+ return `#${((ch(16) << 16) | (ch(8) << 8) | ch(0)).toString(16).padStart(6, '0')}`
+}
diff --git a/src/view3d/palette.ts b/src/view3d/palette.ts
new file mode 100644
index 0000000..cf37b45
--- /dev/null
+++ b/src/view3d/palette.ts
@@ -0,0 +1,49 @@
+import { t } from '../i18n'
+import type { Palette } from '../model'
+import { RAL_CLASSIC, ralCode, ralHex } from './ral'
+
+export type PalettePart = 'walls' | 'accent' | 'roof' | 'windows' | 'gates' | 'plinth'
+
+export const PANEL_RAL = [
+ '1014', '1015', '1018', '2004', '3000', '3003', '3005', '3009', '3011', '5002', '5005', '5015', '5021', '6002', '6005', '6018',
+ '6019', '6029', '7004', '7005', '7016', '7024', '7035', '7040', '7047', '8004', '8017', '8019', '9002', '9003', '9006', '9010',
+].filter((c) => RAL_CLASSIC[c])
+
+export const DEFAULT_WALLS = 'RAL 7004'
+export const DEFAULT_ACCENT = 'RAL 7024'
+
+const preset = (key: string, colors: Omit<Palette, 'name'>) => ({
+ get name() {
+ return t(`view3d:presets.${key}`)
+ },
+ get palette(): Palette {
+ return { name: t(`view3d:presets.${key}`), ...colors }
+ },
+})
+
+export const PRESETS: { name: string; palette: Palette }[] = [
+ preset('granite', { walls: 'RAL 7004', gates: 'RAL 7004', roof: 'RAL 7024', accent: 'RAL 7024', plinth: 'RAL 7024', windows: 'RAL 7016' }),
+ preset('scandinavia', { walls: 'RAL 9003', accent: 'RAL 7024', windows: 'RAL 7024', gates: 'RAL 7024', roof: 'RAL 7024', plinth: 'RAL 7024' }),
+ preset('graphite', { walls: 'RAL 7024', accent: 'RAL 9003', windows: 'RAL 9003', gates: 'RAL 7024', roof: 'RAL 7024', plinth: 'RAL 7016' }),
+ preset('warm', { walls: 'RAL 1015', accent: 'RAL 8017', windows: 'RAL 8017', gates: 'RAL 8017', roof: 'RAL 8017', plinth: 'RAL 8017' }),
+ preset('forest', { walls: 'RAL 6005', accent: 'RAL 9003', windows: 'RAL 9003', gates: 'RAL 6005', roof: 'RAL 7024', plinth: 'RAL 7024' }),
+]
+
+export type Colors = Record<PalettePart, string> & { explicitWalls: boolean }
+
+export function resolveColors(palette: Palette | undefined): Colors {
+ const hex = (v: string | undefined, fallback: string) => ralHex(v) ?? ralHex(fallback)!
+ const accent = hex(palette?.accent, DEFAULT_ACCENT)
+ const part = (v: string | undefined) => ralHex(v) ?? accent
+ return {
+ walls: hex(palette?.walls, DEFAULT_WALLS),
+ accent,
+ windows: part(palette?.windows),
+ gates: part(palette?.gates),
+ plinth: part(palette?.plinth),
+ roof: part(palette?.roof),
+ explicitWalls: !!ralCode(palette?.walls),
+ }
+}
+
+export const ralName = (code: string) => RAL_CLASSIC[code]?.[1] ?? ''
diff --git a/src/view3d/ral.ts b/src/view3d/ral.ts
new file mode 100644
index 0000000..8734df6
--- /dev/null
+++ b/src/view3d/ral.ts
@@ -0,0 +1,230 @@
+// RAL Classic, данные из npm-пакета ral-colors 1.0.1 (MIT, ieskudero/ral-colors)
+export const RAL_CLASSIC: Record<string, readonly [hex: string, name: string]> = {
+ '1000': ['#cdba88', "Green beige"],
+ '1001': ['#d0b084', "Beige"],
+ '1002': ['#d2aa6d', "Sand yellow"],
+ '1003': ['#f9a800', "Signal yellow"],
+ '1004': ['#e49e00', "Golden yellow"],
+ '1005': ['#cb8e00', "Honey yellow"],
+ '1006': ['#e29000', "Maize yellow"],
+ '1007': ['#e88c00', "Daffodil yellow"],
+ '1011': ['#af804f', "Brown beige"],
+ '1012': ['#ddaf27', "Lemon yellow"],
+ '1013': ['#e3d9c6', "Oyster white"],
+ '1014': ['#ddc49a', "Ivory"],
+ '1015': ['#e6d2b5', "Light ivory"],
+ '1016': ['#f1dd38', "Sulfur yellow"],
+ '1017': ['#f6a950', "Saffron yellow"],
+ '1018': ['#faca30', "Zinc yellow"],
+ '1019': ['#a48f7a', "Grey beige"],
+ '1020': ['#a08f65', "Olive yellow"],
+ '1021': ['#f6b600', "Colza yellow"],
+ '1023': ['#f7b500', "Traffic yellow"],
+ '1024': ['#ba8f4c', "Ochre yellow"],
+ '1026': ['#ffff00', "Luminous yellow"],
+ '1027': ['#a77f0e', "Curry"],
+ '1028': ['#ff9b00', "Melon yellow"],
+ '1032': ['#e2a300', "Broom yellow"],
+ '1033': ['#f99a1c', "Dahlia yellow"],
+ '1034': ['#eb9c52', "Pastel yellow"],
+ '1035': ['#908370', "Pearl beige"],
+ '1036': ['#80643f', "Pearl gold"],
+ '1037': ['#f09200', "Sun yellow"],
+ '2000': ['#dd7907', "Yellow orange"],
+ '2001': ['#be4e20', "Red orange"],
+ '2002': ['#c63927', "Vermilion"],
+ '2003': ['#fa842b', "Pastel orange"],
+ '2004': ['#e75b12', "Pure orange"],
+ '2005': ['#ff2300', "Luminous orange"],
+ '2007': ['#ffa421', "Luminous bright orange"],
+ '2008': ['#f3752c', "Bright red orange"],
+ '2009': ['#e15501', "Traffic orange"],
+ '2010': ['#d4652f', "Signal orange"],
+ '2011': ['#ec7c25', "Deep orange"],
+ '2012': ['#db6a50', "Salmon orange"],
+ '2013': ['#954527', "Pearl orange"],
+ '2017': ['#fa4402', "RAL orange"],
+ '3000': ['#ab2524', "Flame red"],
+ '3001': ['#a02128', "Signal red"],
+ '3002': ['#a1232b', "Carmine red"],
+ '3003': ['#8d1d2c', "Ruby red"],
+ '3004': ['#701f29', "Purple red"],
+ '3005': ['#5e2028', "Wine red"],
+ '3007': ['#402225', "Black red"],
+ '3009': ['#703731', "Oxide red"],
+ '3011': ['#7e292c', "Brown red"],
+ '3012': ['#cb8d73', "Beige red"],
+ '3013': ['#9c322e', "Tomato red"],
+ '3014': ['#d47479', "Antique pink"],
+ '3015': ['#e1a6ad', "Light pink"],
+ '3016': ['#ac4034', "Coral red"],
+ '3017': ['#d3545f', "Rose"],
+ '3018': ['#d14152', "Strawberry red"],
+ '3020': ['#c1121c', "Traffic red"],
+ '3022': ['#d56d56', "Salmon pink"],
+ '3024': ['#f70000', "Luminous red"],
+ '3026': ['#ff0000', "Luminous bright red"],
+ '3027': ['#b42041', "Raspberry red"],
+ '3028': ['#e72512', "Pure red"],
+ '3031': ['#ac323b', "Orient red"],
+ '3032': ['#711521', "Pearl ruby red"],
+ '3033': ['#b24c43', "Pearl pink"],
+ '4001': ['#8a5a83', "Red lilac"],
+ '4002': ['#933d50', "Red violet"],
+ '4003': ['#d15b8f', "Heather violet"],
+ '4004': ['#691639', "Claret violet"],
+ '4005': ['#83639d', "Blue lilac"],
+ '4006': ['#992572', "Traffic purple"],
+ '4007': ['#4a203b', "Purple violet"],
+ '4008': ['#904684', "Signal violet"],
+ '4009': ['#a38995', "Pastel violet"],
+ '4010': ['#c63678', "Telemagenta"],
+ '4011': ['#8773a1', "Pearl violet"],
+ '4012': ['#6b6880', "Pearl blackberry"],
+ '5000': ['#384c70', "Violet blue"],
+ '5001': ['#1f4764', "Green blue"],
+ '5002': ['#2b2c7c', "Ultramarine blue"],
+ '5003': ['#2a3756', "Sapphire blue"],
+ '5004': ['#1d1f2a', "Black blue"],
+ '5005': ['#154889', "Signal blue"],
+ '5007': ['#41678d', "Brilliant blue"],
+ '5008': ['#313c48', "Grey blue"],
+ '5009': ['#2e5978', "Azure blue"],
+ '5010': ['#13447c', "Gentian blue"],
+ '5011': ['#232c3f', "Steel blue"],
+ '5012': ['#3481b8', "Light blue"],
+ '5013': ['#232d53', "Cobalt blue"],
+ '5014': ['#6c7c98', "Pigeon blue"],
+ '5015': ['#2874b2', "Sky blue"],
+ '5017': ['#0e518d', "Traffic blue"],
+ '5018': ['#21888f', "Turquoise blue"],
+ '5019': ['#1a5784', "Capri blue"],
+ '5020': ['#0b4151', "Ocean blue"],
+ '5021': ['#07737a', "Water blue"],
+ '5022': ['#2f2a5a', "Night blue"],
+ '5023': ['#4d668e', "Distant blue"],
+ '5024': ['#6a93b0', "Pastel blue"],
+ '5025': ['#296478', "Pearl Gentian blue"],
+ '5026': ['#102c54', "Pearl night blue"],
+ '6000': ['#327662', "Patina green"],
+ '6001': ['#28713e', "Emerald green"],
+ '6002': ['#276235', "Leaf green"],
+ '6003': ['#4b573e', "Olive green"],
+ '6004': ['#0e4243', "Blue green"],
+ '6005': ['#0f4336', "Moss green"],
+ '6006': ['#40433b', "Grey olive"],
+ '6007': ['#283424', "Bottle green"],
+ '6008': ['#35382e', "Brown green"],
+ '6009': ['#26392f', "Fir green"],
+ '6010': ['#3e753b', "Grass green"],
+ '6011': ['#68825b', "Reseda green"],
+ '6012': ['#31403d', "Black green"],
+ '6013': ['#797c5a', "Reed green"],
+ '6014': ['#444337', "Yellow olive"],
+ '6015': ['#3d403a', "Black olive"],
+ '6016': ['#026a52', "Turquoise green"],
+ '6017': ['#468641', "May green"],
+ '6018': ['#48a43f', "Yellow green"],
+ '6019': ['#b7d9b1', "Pastel green"],
+ '6020': ['#354733', "Chrome green"],
+ '6021': ['#86a47c', "Pale green"],
+ '6022': ['#3e3c32', "Olive-drab/brown olive"],
+ '6024': ['#008754', "Traffic green"],
+ '6025': ['#53753c', "Fern green"],
+ '6026': ['#005d52', "Opal green"],
+ '6027': ['#81c0bb', "Light green"],
+ '6028': ['#2d5546', "Pine green"],
+ '6029': ['#007243', "Mint green"],
+ '6032': ['#0f8558', "Signal green"],
+ '6033': ['#478a84', "Mint turquoise"],
+ '6034': ['#7fb0b2', "Pastel turquoise"],
+ '6035': ['#1b542c', "Pearl green"],
+ '6036': ['#005d4c', "Pearl opal green"],
+ '6037': ['#25e712', "Pure green"],
+ '6038': ['#00f700', "Luminous green"],
+ '7000': ['#7e8b92', "Squirrel grey"],
+ '7001': ['#8f999f', "Silver grey"],
+ '7002': ['#817f68', "Olive grey"],
+ '7003': ['#7a7b6d', "Moss grey"],
+ '7004': ['#9ea0a1', "Signal grey"],
+ '7005': ['#6b716f', "Mouse grey"],
+ '7006': ['#756f61', "Beige grey"],
+ '7008': ['#746643', "Khaki grey"],
+ '7009': ['#5b6259', "Green grey"],
+ '7010': ['#575d57', "Tarpaulin grey"],
+ '7011': ['#555d61', "Iron grey"],
+ '7012': ['#596163', "Basalt grey"],
+ '7013': ['#555548', "Brown grey"],
+ '7015': ['#51565c', "Slate grey"],
+ '7016': ['#373f43', "Anthracite grey"],
+ '7021': ['#2e3234', "Black grey"],
+ '7022': ['#4b4d46', "Umbra grey"],
+ '7023': ['#818479', "Concrete grey"],
+ '7024': ['#474a50', "Graphite grey"],
+ '7026': ['#374447', "Granite grey"],
+ '7030': ['#939388', "Stone grey"],
+ '7031': ['#5d6970', "Blue grey"],
+ '7032': ['#b9b9a8', "Pebble grey"],
+ '7033': ['#818979', "Cement grey"],
+ '7034': ['#939176', "Yellow grey"],
+ '7035': ['#cbd0cc', "Light grey"],
+ '7036': ['#9a9697', "Platinum grey"],
+ '7037': ['#7c7f7e', "Dusty grey"],
+ '7038': ['#b4b8b0', "Agate grey"],
+ '7039': ['#6b695f', "Quartz grey"],
+ '7040': ['#9da3a6', "Window grey"],
+ '7042': ['#8f9695', "Traffic grey A"],
+ '7043': ['#4e5451', "Traffic grey B"],
+ '7044': ['#bdbdb2', "Silk grey"],
+ '7045': ['#91969a', "Telegrey 1"],
+ '7046': ['#82898e', "Telegrey 2"],
+ '7047': ['#cfd0cf', "Telegrey 4"],
+ '7048': ['#888175', "Pearl mouse grey"],
+ '8000': ['#887142', "Green brown"],
+ '8001': ['#9c6b30', "Ochre brown"],
+ '8002': ['#7b5141', "Signal brown"],
+ '8003': ['#80542f', "Clay brown"],
+ '8004': ['#8f4e35', "Copper brown"],
+ '8007': ['#6f4a2f', "Fawn brown"],
+ '8008': ['#6f4f28', "Olive brown"],
+ '8011': ['#5a3a29', "Nut brown"],
+ '8012': ['#673831', "Red brown"],
+ '8014': ['#49392d', "Sepia brown"],
+ '8015': ['#633a34', "Chestnut brown"],
+ '8016': ['#4c2f26', "Mahogany brown"],
+ '8017': ['#44322d', "Chocolate brown"],
+ '8019': ['#3f3a3a', "Grey brown"],
+ '8022': ['#211f20', "Black brown"],
+ '8023': ['#a65e2f', "Orange brown"],
+ '8024': ['#79553c', "Beige brown"],
+ '8025': ['#755c49', "Pale brown"],
+ '8028': ['#4e3b2b', "Terra brown"],
+ '8029': ['#773c27', "Pearl copper"],
+ '9001': ['#efebdc', "Cream"],
+ '9002': ['#ddded4', "Grey white"],
+ '9003': ['#f4f8f4', "Signal white"],
+ '9004': ['#2e3032', "Signal black"],
+ '9005': ['#0a0a0d', "Jet black"],
+ '9006': ['#a5a8a6', "White aluminium"],
+ '9007': ['#8f8f8c', "Grey aluminium"],
+ '9010': ['#f7f9ef', "Pure white"],
+ '9011': ['#292c2f', "Graphite black"],
+ '9012': ['#fffde6', "Clean room white"],
+ '9016': ['#f7fbf5', "Traffic white"],
+ '9017': ['#2a2d2f', "Traffic black"],
+ '9018': ['#cfd3cd', "Papyrus white"],
+ '9022': ['#9c9c9c', "Pearl light grey"],
+ '9023': ['#7e8182', "Pearl dark grey"],
+}
+
+export const ralCode = (value: string | undefined | null) => {
+ const m = /(\d{4})/.exec(value ?? '')
+ return m && RAL_CLASSIC[m[1]] ? m[1] : null
+}
+
+export const ralHex = (value: string | undefined | null) => {
+ const code = ralCode(value)
+ return code ? RAL_CLASSIC[code][0] : null
+}
+
+export const ralLabel = (code: string) => 'RAL ' + code
diff --git a/src/view3d/types.ts b/src/view3d/types.ts
new file mode 100644
index 0000000..6b1337c
--- /dev/null
+++ b/src/view3d/types.ts
@@ -0,0 +1,19 @@
+import type { Material as ModelMaterial } from '../model'
+
+export type { Opening, Plan, Point, Site, Wall, MaterialKind } from '../model'
+
+export type Finish = 'osb' | 'plaster' | 'timber' | 'planken'
+
+export type Material = ModelMaterial & { finish?: Finish }
+
+export type FurnitureItem = {
+ id: string
+ type: string
+ x: number
+ y: number
+ rotationDeg: number
+ w?: number
+ d?: number
+ h?: number
+ color?: string
+}
diff --git a/src/view3d/view3d.css b/src/view3d/view3d.css
new file mode 100644
index 0000000..d35cc7f
--- /dev/null
+++ b/src/view3d/view3d.css
@@ -0,0 +1,111 @@
+.view3d {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ overflow: hidden;
+ background: var(--bg);
+}
+
+.view3d canvas {
+ display: block;
+ touch-action: none;
+}
+
+.view3d__label {
+ padding: 0 var(--space-1) 0 var(--space-2);
+ color: var(--muted);
+ font-size: var(--text-sm);
+}
+
+.view3d__error {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ padding: var(--space-5);
+ background: var(--bg);
+}
+
+.view3d__error-card {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: var(--space-2);
+ max-width: 420px;
+ font-size: var(--text-md);
+ color: var(--ink);
+}
+
+.view3d__error-card p {
+ margin: 0;
+}
+
+.view3d__bar {
+ max-width: calc(100% - 24px);
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+
+.view3d__bar::-webkit-scrollbar {
+ display: none;
+}
+
+.view3d__bar > * {
+ flex-shrink: 0;
+}
+
+@media (max-width: 900px) {
+ .view3d__finish {
+ top: calc(var(--chrome-top) + 52px);
+ right: auto;
+ left: var(--chrome-left, 12px);
+ }
+}
+
+.view3d__colors {
+ top: calc(var(--chrome-top) + 52px);
+}
+
+.view3d__swatch {
+ display: inline-block;
+ flex-shrink: 0;
+ border-radius: var(--radius-xs);
+ box-shadow: inset 0 0 0 1px var(--line-strong);
+}
+
+.view3d__swatches {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 2px;
+}
+
+.view3d__swatch-item .menu__label {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.view3d__swatch-item--active {
+ background: var(--accent-soft);
+}
+
+.view3d__swatch-name {
+ overflow: hidden;
+ font-size: var(--text-xs);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.view3d__preset {
+ display: inline-flex;
+ gap: 3px;
+}
+
+@media (max-width: 900px) {
+ .view3d__colors {
+ top: calc(var(--chrome-top) + 104px);
+ right: auto;
+ left: var(--chrome-left, 12px);
+ }
+}
diff --git a/storage.example/config.example.php b/storage.example/config.example.php
new file mode 100644
index 0000000..51467e0
--- /dev/null
+++ b/storage.example/config.example.php
@@ -0,0 +1,17 @@
+<?php
+
+// Пример storage/config.php. Обычно его пишет мастер установки api/setup.php.
+// Хранилище ищется по порядку: $HOUSE_STORAGE, <корень сайта>/../storage, <корень сайта>/storage.
+//
+// password_hash — результат password_hash(): php -r 'echo password_hash("пароль", PASSWORD_DEFAULT), "\n";'
+// hauth — случайный токен куки входа, 64 hex-символа: php -r 'echo bin2hex(random_bytes(32)), "\n";'
+// Тот же токен должен стоять в data/.htaccess и plans/.htaccess (их тоже пишет setup.php).
+// seed — план, которым засевается пустое хранилище; путь от корня сайта или абсолютный.
+
+return [
+ 'password_hash' => '$2y$10$replace.with.output.of.password_hash.function.......',
+ 'hauth' => 'replace-with-64-hex-chars',
+ 'seed' => 'plans/demo.json',
+ 'timezone' => 'Europe/Moscow',
+ 'min_client_version' => 2,
+];
diff --git a/storage.example/site-fixed.example.json b/storage.example/site-fixed.example.json
new file mode 100644
index 0000000..14d9750
--- /dev/null
+++ b/storage.example/site-fixed.example.json
@@ -0,0 +1,60 @@
+{
+ "site": {
+ "boundary": [
+ {
+ "x": 0,
+ "y": 0
+ },
+ {
+ "x": 25000,
+ "y": 0
+ },
+ {
+ "x": 25000,
+ "y": 40000
+ },
+ {
+ "x": 0,
+ "y": 40000
+ }
+ ],
+ "street": {
+ "side": [
+ 2,
+ 3
+ ],
+ "note": "Улица"
+ },
+ "geo": {
+ "lat": 59.30016929,
+ "lng": 24.85772793,
+ "rotationDeg": 8
+ },
+ "zones": [
+ {
+ "id": "zone-fill",
+ "name": "Отсыпка",
+ "kind": "fill",
+ "locked": true,
+ "polygon": [
+ {
+ "x": 0,
+ "y": 28000
+ },
+ {
+ "x": 25000,
+ "y": 28000
+ },
+ {
+ "x": 25000,
+ "y": 40000
+ },
+ {
+ "x": 0,
+ "y": 40000
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/tsconfig.app.json b/tsconfig.app.json
new file mode 100644
index 0000000..6830b6f
--- /dev/null
+++ b/tsconfig.app.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "es2023",
+ "lib": ["ES2023", "DOM"],
+ "module": "esnext",
+ "types": ["vite/client"],
+ "allowArbitraryExtensions": true,
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+
+ /* Linting */
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "erasableSyntaxOnly": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["src"]
+}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..1ffef60
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "files": [],
+ "references": [
+ { "path": "./tsconfig.app.json" },
+ { "path": "./tsconfig.node.json" }
+ ]
+}
diff --git a/tsconfig.node.json b/tsconfig.node.json
new file mode 100644
index 0000000..8455dcb
--- /dev/null
+++ b/tsconfig.node.json
@@ -0,0 +1,23 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
+ "target": "es2023",
+ "lib": ["ES2023"],
+ "types": ["node"],
+ "skipLibCheck": true,
+
+ /* Bundler mode */
+ "module": "nodenext",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+
+ /* Linting */
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "erasableSyntaxOnly": true,
+ "noFallthroughCasesInSwitch": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/vite.config.ts b/vite.config.ts
new file mode 100644
index 0000000..306dee9
--- /dev/null
+++ b/vite.config.ts
@@ -0,0 +1,19 @@
+import react from '@vitejs/plugin-react'
+import { defineConfig } from 'vite'
+
+export default defineConfig({
+ base: './',
+ plugins: [react()],
+ server: {
+ proxy: {
+ '/api': 'http://127.0.0.1:8000',
+ '/data': 'http://127.0.0.1:8000',
+ '/plans': 'http://127.0.0.1:8000',
+ },
+ },
+ build: {
+ outDir: 'dist',
+ emptyOutDir: true,
+ chunkSizeWarningLimit: 1000,
+ },
+})