IKEA assembly, step by step: animated, manual-style 3D guides. Scan any paper manual with Together AI.
TypeScript
Build Bygga: animated, manual-style assembly guides
Youssef82c3650afc28
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..56e5157--- /dev/null+++ b/.env.example@@ -0,0 +1,12 @@+# Together AI key: unlocks any product name, photo lookup and live help for everyone.+# Scanning a manual (/scan) always uses the visitor's own key instead.+# Get one at https://api.together.ai+TOGETHER_API_KEY=++# Optional: the GitHub repo shown (with its star count) in the nav.+# NEXT_PUBLIC_GITHUB_REPO=Luffixos/bygga++# Optional: comma separated model lists, tried in order.+# TOGETHER_TEXT_MODEL=openai/gpt-oss-120b,zai-org/GLM-5.2+# TOGETHER_VISION_MODEL=Qwen/Qwen3-VL-32B-Instruct,meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8+# TOGETHER_PLAN_MODEL=openai/gpt-oss-120b,deepseek-ai/DeepSeek-V3.1diff --git a/.gitignore b/.gitignoreindex 5ef6a52..eb96524 100644--- a/.gitignore+++ b/.gitignore@@ -39,3 +39,6 @@ yarn-error.log*# typescript*.tsbuildinfonext-env.d.ts++# keep the example env file+!.env.examplediff --git a/README.md b/README.mdindex e215bc4..3009ad0 100644--- a/README.md+++ b/README.md@@ -1,36 +1,38 @@-This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).+<p align="center">+ <img alt="Bygga" src="docs/img/banner.svg">+</p>-## Getting Started+<h1 align="center">Bygga</h1>-First, run the development server:+<p align="center">Type the name on an IKEA box (or snap the label) and get a moving, manual-style assembly guide: tools check, parts check, then every step drawn in 3D line art. Not from IKEA? Photograph any paper manual and it becomes the same kind of guide. Runs locally, no live site yet.</p>-```bash-npm run dev-# or-yarn dev-# or-pnpm dev-# or-bun dev-```+## Tech stack-Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.+- Next.js 16 (App Router, Cache Components) with React 19 and TypeScript, no CSS framework+- three.js stage with ink outlines, hidden-line removal, fly-in arrows and a magnified callout per fitting+- A parametric generator (`src/lib/plan`) that turns a product spec into panels, hardware, holes and ordered steps+- Together AI: `openai/gpt-oss-120b` reads unknown products and answers "Stuck?" questions (streamed), a vision model reads box photos and identifies loose parts+- 152 products drawn offline with typo-tolerant search; unknown names get a "what does it look like?" picker+- Scan any manual (`/scan`): a vision model reads each page, `gpt-oss-120b` lays the parts out as boxes in millimetres, and `src/lib/plan/custom.ts` works out every joint, dowel, bolt and screw from where parts touch. Runs on the visitor's own Together key+- Workshop (`/builds`): everything you finished, rendered together in one drawing at true scale next to a person-You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.+## Cloning & running-This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.+1. Install: `npm install`+2. Add your key: `cp .env.example .env.local`, then set `TOGETHER_API_KEY`+3. Run it: `npm run dev`, then open http://localhost:3000 and try `BISSA`+4. Deep link to a step: http://localhost:3000/build/malm-3-drawers?step=12, or see your builds at `/builds`+5. Try the manual scanner without spending credits: on `/scan`, paste `bygga-dev-mock-key-000000` as the key (only accepted by `npm run dev`) and add any photo+6. Before shipping: `npm run lint && npm run build`-## Learn More+## Roadmap-To learn more about Next.js, take a look at the following resources:+- [ ] teach the generator a few more shapes: bent-wood chairs like POÄNG, pegboards, kitchen units+- [ ] let people flag a step that doesn't match their box, and feed that back into the spec+- [ ] print view: the whole manual on A4, one step per panel+- [ ] cache AI product reads on the server so the second person to ask gets it instantly+- Real IKEA manuals are not scraped or mirrored on purpose: every guide is generated, and the cover links to the official PDF.-- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.-- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.+## Security-You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!--## Deploy on Vercel--The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.--Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.+The server's Together key never leaves the server; the browser only talks to `/api/*`, which is rate limited per IP. A visitor's own key (needed for `/scan`) lives in their `localStorage`, rides along on their requests in an `x-together-key` header, and is never stored or logged. Scanned guides stay in the browser; sharing one puts the guide itself, compressed, in the link. Build progress lives in `localStorage` on the device and is never uploaded. Bygga is not affiliated with IKEA; product names are trademarks of Inter IKEA Systems B.V. MIT licensed.diff --git a/docs/img/banner.svg b/docs/img/banner.svgnew file mode 100644index 0000000..03006a8--- /dev/null+++ b/docs/img/banner.svg@@ -0,0 +1,14 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630" width="1200" height="630">+<rect width="1200" height="630" fill="#f7f6f2"/>+<rect x="640" y="60" width="500" height="510" rx="40" fill="#ffffff"/>+<ellipse cx="917.4800558101097" cy="516" rx="173.22806139112058" ry="26" fill="#141414" opacity="0.06"/>+<g stroke="#141414" stroke-width="2.4" stroke-linejoin="round"><path d="M855.7 375.3 L855.7 147.0 L772.0 199.1 L772.0 427.3 Z" fill="#eceae5"/><path d="M843.6 371.4 L760.0 423.5 L991.3 496.8 L1075.0 444.8 Z" fill="#ffffff"/><path d="M961.7 408.9 L961.7 297.4 L878.1 349.4 L878.1 460.9 Z" fill="#eceae5"/><path d="M760.0 423.5 L772.0 427.3 L772.0 199.1 L760.0 195.2 Z" fill="#f6f5f2"/><path d="M843.6 143.2 L760.0 195.2 L772.0 199.1 L855.7 147.0 Z" fill="#ffffff"/><path d="M760.0 436.7 L991.3 510.0 L991.3 496.8 L760.0 423.5 Z" fill="#f6f5f2"/><path d="M956.9 295.9 L873.3 347.9 L878.1 349.4 L961.7 297.4 Z" fill="#ffffff"/><path d="M855.7 258.5 L772.0 310.5 L979.3 376.2 L1062.9 324.2 Z" fill="#ffffff"/><path d="M1075.0 458.0 L1075.0 444.8 L991.3 496.8 L991.3 510.0 Z" fill="#eceae5"/><path d="M873.3 459.4 L878.1 460.9 L878.1 349.4 L873.3 347.9 Z" fill="#f6f5f2"/><path d="M961.7 292.1 L961.7 180.6 L878.1 232.7 L878.1 344.1 Z" fill="#eceae5"/><path d="M772.0 315.8 L979.3 381.5 L979.3 376.2 L772.0 310.5 Z" fill="#f6f5f2"/><path d="M956.9 179.1 L873.3 231.1 L878.1 232.7 L961.7 180.6 Z" fill="#ffffff"/><path d="M843.6 130.0 L760.0 182.0 L991.3 255.3 L1075.0 203.3 Z" fill="#ffffff"/><path d="M1062.9 329.5 L1062.9 324.2 L979.3 376.2 L979.3 381.5 Z" fill="#eceae5"/><path d="M1075.0 444.8 L1075.0 216.5 L991.3 268.6 L991.3 496.8 Z" fill="#eceae5"/><path d="M873.3 342.6 L878.1 344.1 L878.1 232.7 L873.3 231.1 Z" fill="#f6f5f2"/><path d="M760.0 195.2 L991.3 268.6 L991.3 255.3 L760.0 182.0 Z" fill="#f6f5f2"/><path d="M979.3 493.0 L991.3 496.8 L991.3 268.6 L979.3 264.7 Z" fill="#f6f5f2"/><path d="M1062.9 212.7 L979.3 264.7 L991.3 268.6 L1075.0 216.5 Z" fill="#ffffff"/><path d="M1075.0 216.5 L1075.0 203.3 L991.3 255.3 L991.3 268.6 Z" fill="#eceae5"/></g>+<path d="M940 96 v34 h-9 l14 16 l14 -16 h-9 v-34 z" fill="#141414"/>+<text x="680" y="120" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="64" font-weight="800" fill="#141414">1</text>+<g transform="translate(80 92) scale(2.25)"><circle cx="16" cy="16" r="15.5" fill="#121212"/><path d="M16 6.2 L24.5 11.1 L24.5 20.9 L16 25.8 L7.5 20.9 L7.5 11.1 Z" fill="#ffd21f" stroke="#ffd21f" stroke-width="2.2" stroke-linejoin="round"/><path d="M16 11.2 L20.2 13.6 L20.2 18.4 L16 20.8 L11.8 18.4 L11.8 13.6 Z" fill="#121212"/></g>+<text x="172" y="148" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="54" font-weight="800" fill="#141414" letter-spacing="-2.4">bygga</text>+<text x="80" y="290" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="62" font-weight="800" fill="#141414" letter-spacing="-1.5">IKEA assembly,</text>+<text x="80" y="362" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="62" font-weight="800" fill="#141414" letter-spacing="-1.5">step by step.</text>+<text x="80" y="430" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="26" fill="#4b4a46">Type the product name. Watch every step in 3D.</text>+<text x="80" y="516" font-family="Noto Sans, Helvetica, Arial, sans-serif" font-size="19" fill="#8a877f">Powered by <tspan fill="#4b4a46" font-weight="600">Together AI</tspan></text>+</svg>\ No newline at end of filediff --git a/package-lock.json b/package-lock.jsonindex a1f9e44..06a2e6c 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,14 +8,19 @@"name": "ikea-masta","version": "0.1.0","dependencies": {+ "motion": "^14.4.0","next": "16.4.2","react": "19.3.0",- "react-dom": "19.3.0"+ "react-dom": "19.3.0",+ "server-only": "^0.0.1",+ "three": "^0.186.1",+ "zod": "^4.6.7"},"devDependencies": {"@types/node": "^20","@types/react": "^19","@types/react-dom": "^19",+ "@types/three": "^0.186.0","eslint": "^9","eslint-config-next": "16.4.2","typescript": "^5"@@ -262,34 +267,17 @@"node": ">=6.9.0"}},- "node_modules/@emnapi/core": {- "version": "1.10.0",- "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",- "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",+ "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==","dev": true,- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "@emnapi/wasi-threads": "1.2.1",- "tslib": "^2.4.0"- }- },- "node_modules/@emnapi/runtime": {- "version": "1.11.3",- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",- "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",- "license": "MIT",- "optional": true,- "peer": true,- "dependencies": {- "tslib": "^2.4.0"- }+ "license": "Apache-2.0"},"node_modules/@emnapi/wasi-threads": {- "version": "1.2.1",- "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",- "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",+ "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==","dev": true,"license": "MIT","optional": true,@@ -1321,6 +1309,13 @@"tslib": "^2.8.0"}},+ "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==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@tybys/wasm-util": {"version": "0.10.4","resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",@@ -1384,6 +1379,35 @@"@types/react": "^19.3.0"}},+ "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==",+ "dev": true,+ "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==",+ "dev": true,+ "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/webxr": {+ "version": "0.5.24",+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@typescript-eslint/eslint-plugin": {"version": "8.72.0","resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.0.tgz",@@ -1951,6 +1975,18 @@"node": ">=14.0.0"}},+ "node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/core": {+ "version": "1.10.0",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",+ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.1",+ "tslib": "^2.4.0"+ }+ },"node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/runtime": {"version": "1.10.0","resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",@@ -1962,6 +1998,17 @@"tslib": "^2.4.0"}},+ "node_modules/@unrs/resolver-binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",+ "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },"node_modules/@unrs/resolver-binding-win32-arm64-msvc": {"version": "1.12.2","resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz",@@ -3117,6 +3164,7 @@"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@rtsao/scc": "^1.1.0","array-includes": "^3.1.9",@@ -3393,6 +3441,13 @@"reusify": "^1.0.4"}},+ "node_modules/fflate": {+ "version": "0.8.3",+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/file-entry-cache": {"version": "8.0.0","resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",@@ -3473,6 +3528,29 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/framer-motion": {+ "version": "14.4.0",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.4.0.tgz",+ "integrity": "sha512-HtO1fxord2rnXYRyr1laG4uY7+OtgwDc9Szcg1wlMq/LF7BO3/S7a+KEo691U7pSi+i0ueRuRqaD1UaLEmZHuQ==",+ "license": "MIT",+ "dependencies": {+ "motion-dom": "14.4.0",+ "motion-utils": "14.1.1",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },"node_modules/function-bind": {"version": "1.1.2","resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",@@ -4492,6 +4570,13 @@"node": ">= 8"}},+ "node_modules/meshoptimizer": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",+ "dev": true,+ "license": "MIT"+ },"node_modules/micromatch": {"version": "4.0.8","resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",@@ -4529,6 +4614,43 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/motion": {+ "version": "14.4.0",+ "resolved": "https://registry.npmjs.org/motion/-/motion-14.4.0.tgz",+ "integrity": "sha512-JJTIdeNjtF2zi/py0ndRKxQF+8z2pcDUgJYXul7zqbhMvyTLRsPFR9ifE/j4cFCpCMlehQVJkTwd7BZFiPKgQg==",+ "license": "MIT",+ "dependencies": {+ "framer-motion": "14.4.0",+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/motion-dom": {+ "version": "14.4.0",+ "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.4.0.tgz",+ "integrity": "sha512-1q8RyHSdr5COpzrv3JgJ9XRjOO88ZN9CwflpkGgyO/SR/SNRP/dD6EU8SEo092kcKY34IzHC5diJPKrQRMA8lQ==",+ "license": "MIT",+ "dependencies": {+ "motion-utils": "14.1.1"+ }+ },+ "node_modules/motion-utils": {+ "version": "14.1.1",+ "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-14.1.1.tgz",+ "integrity": "sha512-3VvN5Uvf8B6qG+OfOui6Nht5EWp+vLuU3IqcAj7ItZGKqtmTjCebl5sGZF7/08gEHRnEl1AP/fIwbcEyVrcQGQ==",+ "license": "MIT"+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",@@ -5225,6 +5347,12 @@"semver": "bin/semver.js"}},+ "node_modules/server-only": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/server-only/-/server-only-0.0.1.tgz",+ "integrity": "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==",+ "license": "MIT"+ },"node_modules/set-function-length": {"version": "1.2.2","resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",@@ -5652,6 +5780,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/three": {+ "version": "0.186.1",+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",+ "license": "MIT"+ },"node_modules/tinyglobby": {"version": "0.2.17","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",@@ -6132,7 +6266,6 @@"version": "4.6.7","resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz","integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",- "dev": true,"license": "MIT","peer": true,"funding": {diff --git a/package.json b/package.jsonindex 6d856fb..fc2aea6 100644--- a/package.json+++ b/package.json@@ -9,14 +9,19 @@"lint": "eslint"},"dependencies": {+ "motion": "^14.4.0","next": "16.4.2","react": "19.3.0",- "react-dom": "19.3.0"+ "react-dom": "19.3.0",+ "server-only": "^0.0.1",+ "three": "^0.186.1",+ "zod": "^4.6.7"},"devDependencies": {"@types/node": "^20","@types/react": "^19","@types/react-dom": "^19",+ "@types/three": "^0.186.0","eslint": "^9","eslint-config-next": "16.4.2","typescript": "^5"diff --git a/src/app/api/guide/route.ts b/src/app/api/guide/route.tsnew file mode 100644index 0000000..d644ad3--- /dev/null+++ b/src/app/api/guide/route.ts@@ -0,0 +1,60 @@+import { PRODUCTS, toSpec } from "@/lib/catalog";+import { categoryOf, fold, guessSpec, matchCatalog, searchCatalog } from "@/lib/search";+import { parseSpec, SPEC_PROMPT } from "@/lib/spec";+import { chatText, extractJson, hasKey, ipOf, MODELS, rateLimited, TogetherError, userKey } from "@/lib/together";+import type { ProductSpec } from "@/lib/types";++const cache = new Map<string, { spec: ProductSpec; model: string }>();++export async function POST(req: Request) {+ const body = (await req.json().catch(() => ({}))) as { q?: string };+ const q = (body.q ?? "").toString().slice(0, 80).trim();+ if (!q) return Response.json({ error: "empty" }, { status: 400 });++ const hit = matchCatalog(q);+ if (hit) return Response.json({ spec: hit, via: "catalog" });++ const key = fold(q);+ const cached = cache.get(key);+ if (cached) return Response.json({ spec: cached.spec, via: "ai", model: cached.model });++ const suggestions = () => [...new Set(searchCatalog(q, 8).filter((h) => h.score >= 40).map((h) => h.entry.name))].slice(0, 4);++ const own = userKey(req);+ if (hasKey() || own) {+ if (rateLimited(ipOf(req), 12)) return Response.json({ error: "slow down" }, { status: 429 });+ try {+ const { text, model } = await chatText({+ key: own,+ models: MODELS.text,+ json: true,+ maxTokens: 1800,+ temperature: 0.2,+ messages: [+ { role: "system", content: SPEC_PROMPT },+ { role: "user", content: q },+ ],+ });+ const raw = extractJson(text) as { found?: boolean; suggestions?: string[] } | null;+ if (raw && raw.found === false) {+ return Response.json({ found: false, suggestions: (raw.suggestions ?? []).slice(0, 3).concat(suggestions()).slice(0, 4), via: "ai" });+ }+ const spec = parseSpec(raw);+ if (spec) {+ // prefer our checked catalog when the model lands on a product we know+ const known = PRODUCTS.find((c) => fold(c.name) === fold(spec.name) && c.archetype === spec.archetype && Math.abs(c.size.w - spec.size.w) < 6 && Math.abs(c.size.h - spec.size.h) < 6);+ if (known) return Response.json({ spec: { ...toSpec(known), slug: known.slug }, via: "catalog" });+ spec.slug = key.replace(/\s+/g, "-");+ cache.set(key, { spec, model });+ return Response.json({ spec, via: "ai", model });+ }+ } catch (e) {+ const err = e as TogetherError;+ console.error("[guide] together error", err.status, err.message);+ }+ }++ const g = guessSpec(q);+ if (g && categoryOf(q)) return Response.json({ spec: g, via: "guess" });+ return Response.json({ found: false, suggestions: suggestions(), via: hasKey() || own ? "ai" : "offline" });+}diff --git a/src/app/api/help/route.ts b/src/app/api/help/route.tsnew file mode 100644index 0000000..f7dfc62--- /dev/null+++ b/src/app/api/help/route.ts@@ -0,0 +1,75 @@+import { chat, hasKey, ipOf, MODELS, rateLimited, userKey, type Msg } from "@/lib/together";++interface Body {+ context?: string;+ question?: string;+ history?: { role: "user" | "assistant"; content: string }[];+ image?: string;+}++const SYSTEM = `You are the helper inside Bygga, an app that walks people through assembling flat pack furniture step by step, mostly from IKEA. The person is mid-build, often on the floor with tools in hand.+Answer in plain, warm English. At most 3 short sentences, or a short numbered list when giving steps. No headings, no markdown tables.+Be practical and specific to the step they are on. If something could hurt them or damage the furniture, say so first.+If a part is missing or broken: tell them to note the number printed on the bag or panel, and that IKEA stores and customer service usually replace small fittings for free.+If they send a photo of a part, say which part from the list it most likely is and why (size, shape, head).+Never use em dashes or en dashes.`;++export async function POST(req: Request) {+ const key = userKey(req);+ if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });+ if (rateLimited(ipOf(req), 20)) return Response.json({ error: "slow down" }, { status: 429 });+ const b = (await req.json().catch(() => ({}))) as Body;+ const question = (b.question ?? "").toString().slice(0, 600);+ const context = (b.context ?? "").toString().slice(0, 3000);+ const history = (b.history ?? []).slice(-6).map((m) => ({ role: m.role, content: String(m.content).slice(0, 800) })) as Msg[];+ const image = b.image && b.image.startsWith("data:image/") && b.image.length < 6_000_000 ? b.image : undefined;+ const user: Msg = image+ ? { role: "user", content: [{ type: "text", text: question || "Which part is this?" }, { type: "image_url", image_url: { url: image } }] }+ : { role: "user", content: question };+ try {+ const { res } = await chat({+ key,+ models: image ? MODELS.vision : MODELS.text,+ stream: true,+ maxTokens: 700,+ temperature: 0.4,+ messages: [{ role: "system", content: SYSTEM + "\n\nWhere they are:\n" + context }, ...history, user],+ });+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ const stream = new ReadableStream({+ async start(ctrl) {+ const reader = res.body!.getReader();+ let buf = "";+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ const lines = buf.split("\n");+ buf = lines.pop() ?? "";+ for (const line of lines) {+ const t = line.trim();+ if (!t.startsWith("data:")) continue;+ const data = t.slice(5).trim();+ if (data === "[DONE]") continue;+ try {+ const j = JSON.parse(data);+ const piece: string = j?.choices?.[0]?.delta?.content ?? "";+ if (piece) ctrl.enqueue(enc.encode(piece.replace(/\s*[\u2013\u2014]\s*/g, ", ")));+ } catch {+ /* partial line */+ }+ }+ }+ } finally {+ ctrl.close();+ }+ },+ });+ return new Response(stream, { headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" } });+ } catch (e) {+ console.error("[help]", (e as Error).message);+ return Response.json({ error: "failed" }, { status: 502 });+ }+}diff --git a/src/app/api/identify/route.ts b/src/app/api/identify/route.tsnew file mode 100644index 0000000..81b518a--- /dev/null+++ b/src/app/api/identify/route.ts@@ -0,0 +1,29 @@+import { chatText, extractJson, hasKey, ipOf, MODELS, rateLimited, userKey } from "@/lib/together";++const PROMPT = `This photo shows an IKEA product, its box, its label or its assembly manual cover. Read the product name.+Reply with JSON only: {"name": "KALLAX", "variant": "2x4 shelving unit", "confidence": 0.0-1.0}.+The name is the word in capitals (it may contain Å, Ä or Ö). If you can't read a name, guess the kind of furniture in "variant" and set name to "".`;++export async function POST(req: Request) {+ const key = userKey(req);+ if (!hasKey() && !key) return Response.json({ error: "ai-off" }, { status: 503 });+ if (rateLimited(ipOf(req), 8)) return Response.json({ error: "slow down" }, { status: 429 });+ const { image } = (await req.json().catch(() => ({}))) as { image?: string };+ if (!image || !image.startsWith("data:image/") || image.length > 6_000_000) return Response.json({ error: "bad image" }, { status: 400 });+ try {+ const { text } = await chatText({+ key,+ models: MODELS.vision,+ maxTokens: 200,+ temperature: 0,+ messages: [{ role: "user", content: [{ type: "text", text: PROMPT }, { type: "image_url", image_url: { url: image } }] }],+ });+ const j = extractJson(text) as { name?: string; variant?: string; confidence?: number } | null;+ const name = (j?.name ?? "").toString().trim();+ const variant = (j?.variant ?? "").toString().trim();+ return Response.json({ name, variant, query: [name, variant].filter(Boolean).join(" ").trim(), confidence: Number(j?.confidence ?? 0) });+ } catch (e) {+ console.error("[identify]", (e as Error).message);+ return Response.json({ error: "failed" }, { status: 502 });+ }+}diff --git a/src/app/api/key/route.ts b/src/app/api/key/route.tsnew file mode 100644index 0000000..f8066d2--- /dev/null+++ b/src/app/api/key/route.ts@@ -0,0 +1,16 @@+import { userKey } from "@/lib/together";++/** Checks that a pasted Together AI key works, without storing it. */+export async function POST(req: Request) {+ const key = userKey(req);+ if (!key) return Response.json({ ok: false, reason: "format" });+ if (key === "bygga-dev-mock-key-000000" && process.env.NODE_ENV !== "production") return Response.json({ ok: true });+ try {+ const r = await fetch("https://api.together.xyz/v1/models", { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(8000) });+ await r.body?.cancel();+ if (r.ok) return Response.json({ ok: true });+ return Response.json({ ok: false, reason: r.status === 401 || r.status === 403 ? "rejected" : "unavailable" });+ } catch {+ return Response.json({ ok: false, reason: "unavailable" });+ }+}diff --git a/src/app/api/scan/route.ts b/src/app/api/scan/route.tsnew file mode 100644index 0000000..0020785--- /dev/null+++ b/src/app/api/scan/route.ts@@ -0,0 +1,159 @@+import { buildPlan } from "@/lib/plan";+import { clean, fallbackSpec, parseScan } from "@/lib/scan/parse";+import { PAGE_PROMPT, PLAN_PROMPT, planInput, repairInput } from "@/lib/scan/prompts";+import { SAMPLE_SCAN } from "@/lib/scan/sample";+import { chatText, extractJson, ipOf, MODELS, rateLimited, TogetherError, userKey, type Msg } from "@/lib/together";+import type { ProductSpec } from "@/lib/types";++export const maxDuration = 300;++/** Only for trying the scan flow locally without spending credits. Never accepted in production. */+const DEV_MOCK_KEY = "bygga-dev-mock-key-000000";++type Note = { kind?: string; product?: { name?: string; brand?: string; type?: string }; parts?: unknown[]; hardware?: unknown[]; steps?: { n?: number }[] };++export async function POST(req: Request) {+ const key = userKey(req);+ if (!key) return Response.json({ error: "key" }, { status: 401 });+ if (rateLimited(ipOf(req) + ":scan", 6, 10 * 60_000)) return Response.json({ error: "busy" }, { status: 429 });+ const body = (await req.json().catch(() => null)) as { pages?: unknown[]; hint?: unknown } | null;+ const pages = (body?.pages ?? []).filter((p): p is string => typeof p === "string" && p.startsWith("data:image/") && p.length < 4_000_000).slice(0, 12);+ if (!pages.length) return Response.json({ error: "pages" }, { status: 400 });+ const hint = clean(String(body?.hint ?? "")).slice(0, 80);+ const mock = key === DEV_MOCK_KEY && process.env.NODE_ENV !== "production";++ const enc = new TextEncoder();+ const stream = new ReadableStream({+ async start(ctrl) {+ let open = true;+ const send = (o: object) => {+ if (open) ctrl.enqueue(enc.encode(JSON.stringify(o) + "\n"));+ };+ try {+ send({ type: "stage", stage: "reading", total: pages.length });+ const spec = mock ? await fake(pages.length, hint, send) : await scan(key, pages, hint, send, req.signal);+ send({ type: "done", spec });+ } catch (e) {+ const err = e as TogetherError;+ const status = err instanceof TogetherError ? err.status : 0;+ console.error("[scan]", status, (err.message ?? "").slice(0, 200));+ const code = status === 401 || status === 403 ? "key" : status === 402 ? "credits" : status === 429 ? "busy" : (err.message ?? "").startsWith("unreadable") ? "unreadable" : "failed";+ send({ type: "error", code });+ } finally {+ open = false;+ ctrl.close();+ }+ },+ });+ return new Response(stream, { headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store" } });+}++async function scan(key: string, pages: string[], hint: string, send: (o: object) => void, signal: AbortSignal): Promise<ProductSpec> {+ // 1. read every page on its own, a few at a time+ const notes: Note[] = new Array(pages.length);+ let next = 0;+ let read = 0;+ const worker = async () => {+ while (next < pages.length) {+ const i = next++;+ try {+ const { text } = await chatText({+ key,+ models: MODELS.vision,+ maxTokens: 2000,+ temperature: 0,+ signal,+ messages: [{ role: "user", content: [{ type: "text", text: PAGE_PROMPT }, { type: "image_url", image_url: { url: pages[i] } }] }],+ });+ notes[i] = (extractJson(text) as Note | null) ?? { kind: "other" };+ } catch (e) {+ if (e instanceof TogetherError && [401, 402, 403, 429].includes(e.status)) throw e;+ notes[i] = { kind: "other" };+ }+ read++;+ send({ type: "page", index: i, read, total: pages.length, label: pageLabel(notes[i]), product: notes[i].product?.name ? clean(String(notes[i].product?.name)).slice(0, 40) : undefined, brand: notes[i].product?.brand ? clean(String(notes[i].product?.brand)).slice(0, 40) : undefined });+ }+ };+ await Promise.all(Array.from({ length: Math.min(4, pages.length) }, worker));+ const useful = notes.filter((n) => n && n.kind !== "other");+ if (!useful.length && !hint) throw new Error("unreadable");++ // 2. plan the build+ send({ type: "stage", stage: "planning" });+ const msgs: Msg[] = [+ { role: "system", content: PLAN_PROMPT },+ { role: "user", content: planInput(notes, hint) },+ ];+ const ask = async () => {+ const { text } = await chatText({ key, models: MODELS.plan, json: true, maxTokens: 16000, temperature: 0.2, reasoning: "medium", signal, messages: msgs });+ return { text, raw: extractJson(text) };+ };+ let { text, raw } = await ask();+ let r = parseScan(raw);+ if (r.spec) send({ type: "drafted", name: r.spec.name, brand: r.spec.brand, parts: r.spec.custom?.parts.length ?? 0, steps: r.spec.custom?.steps.length ?? 0 });++ // 3. check it fits together, ask for one round of fixes if not+ send({ type: "stage", stage: "checking" });+ let ok = !!r.spec && r.check.ok && builds(r.spec);+ if (!ok && raw) {+ send({ type: "stage", stage: "fixing" });+ msgs.push({ role: "assistant", content: text.slice(0, 24000) }, { role: "user", content: repairInput(r.check.issues.length ? r.check.issues : ["The parts list or steps couldn't be read. Make sure every part has id, name, size and pos, and every step has a title."]) });+ ({ text, raw } = await ask());+ const again = parseScan(raw);+ if (again.spec && again.check.ok && builds(again.spec)) {+ r = again;+ ok = true;+ }+ }+ if (ok && r.spec) return r.spec;+ const fb = fallbackSpec(raw);+ if (fb && builds(fb)) return fb;+ throw new Error("unbuildable");+}++function builds(spec: ProductSpec) {+ try {+ const p = buildPlan(spec);+ return p.steps.length > 0 && p.parts.length > 0;+ } catch {+ return false;+ }+}++function pageLabel(n: Note) {+ const steps = (n.steps ?? []).map((s) => Number(s?.n)).filter((x) => Number.isFinite(x) && x > 0);+ if (steps.length) {+ const a = Math.min(...steps), b = Math.max(...steps);+ return a === b ? `Step ${a}` : `Steps ${a} to ${b}`;+ }+ switch (n.kind) {+ case "cover":+ return "Cover";+ case "parts":+ return "Parts list";+ case "hardware":+ return "Fittings";+ case "tools":+ return "Tools";+ case "warnings":+ return "Safety notes";+ default:+ return "Page";+ }+}++async function fake(total: number, hint: string, send: (o: object) => void): Promise<ProductSpec> {+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));+ const labels = ["Cover", "Parts list", "Fittings", "Steps 1 to 3", "Steps 4 to 6", "Steps 7 to 10"];+ for (let i = 0; i < total; i++) {+ await wait(700);+ send({ type: "page", index: i, read: i + 1, total, label: labels[i] ?? `Steps ${i * 2} to ${i * 2 + 1}`, product: i === 0 ? SAMPLE_SCAN.name : undefined, brand: i === 0 ? SAMPLE_SCAN.brand : undefined });+ }+ send({ type: "stage", stage: "planning" });+ await wait(2200);+ const spec: ProductSpec = { ...SAMPLE_SCAN, name: hint ? hint.split(" ")[0].toUpperCase().slice(0, 24) : SAMPLE_SCAN.name };+ send({ type: "drafted", name: spec.name, brand: spec.brand, parts: spec.custom!.parts.length, steps: spec.custom!.steps.length });+ send({ type: "stage", stage: "checking" });+ await wait(900);+ return spec;+}diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsnew file mode 100644index 0000000..62fa906--- /dev/null+++ b/src/app/api/status/route.ts@@ -0,0 +1,7 @@+import { connection } from "next/server";+import { hasKey } from "@/lib/together";++export async function GET() {+ await connection();+ return Response.json({ ai: hasKey() });+}diff --git a/src/app/browse/page.tsx b/src/app/browse/page.tsxnew file mode 100644index 0000000..9c9e1e2--- /dev/null+++ b/src/app/browse/page.tsx@@ -0,0 +1,23 @@+import type { Metadata } from "next";+import SiteHeader from "@/components/SiteHeader";+import SiteFooter from "@/components/SiteFooter";+import { Catalog } from "@/components/home/Sections";+import { PRODUCT_COUNT } from "@/lib/search";++export const metadata: Metadata = { title: "All guides | Bygga" };++export default function Page() {+ return (+ <div className="site">+ <SiteHeader />+ <main className="browse">+ <header className="page-head">+ <h1>All guides</h1>+ <p className="lead">{PRODUCT_COUNT} IKEA products, drawn and ready to build. Not listed? Search for it by name on the home page.</p>+ </header>+ <Catalog search />+ </main>+ <SiteFooter />+ </div>+ );+}diff --git a/src/app/build/[slug]/page.tsx b/src/app/build/[slug]/page.tsxnew file mode 100644index 0000000..4d5afc6--- /dev/null+++ b/src/app/build/[slug]/page.tsx@@ -0,0 +1,31 @@+import { Suspense } from "react";+import type { Metadata } from "next";+import GuideApp from "@/components/guide/GuideApp";+import { catalogSpec } from "@/lib/catalog";++type Props = { params: Promise<{ slug: string }>; searchParams: Promise<Record<string, string | string[] | undefined>> };++export async function generateMetadata({ params }: Props): Promise<Metadata> {+ const { slug } = await params;+ if (slug.startsWith("scan-")) return { title: "Scanned guide | Bygga" };+ const s = catalogSpec(decodeURIComponent(slug));+ const name = s ? `${s.name} ${s.variant.toLowerCase()}` : decodeURIComponent(slug).replace(/-/g, " ").toUpperCase();+ return { title: `${name}: assembly step by step | Bygga` };+}++export default function Page(props: Props) {+ return (+ <Suspense fallback={<div className="guide shell" />}>+ <Inner {...props} />+ </Suspense>+ );+}++async function Inner({ params, searchParams }: Props) {+ const { slug } = await params;+ const sp = await searchParams;+ const q = typeof sp.q === "string" ? sp.q.slice(0, 80) : undefined;+ const step = typeof sp.step === "string" ? Number(sp.step) : undefined;+ const kind = typeof sp.kind === "string" ? sp.kind : undefined;+ return <GuideApp slug={decodeURIComponent(slug)} query={q} kind={kind} step={step && step > 0 ? Math.floor(step) : undefined} />;+}diff --git a/src/app/builds/page.tsx b/src/app/builds/page.tsxnew file mode 100644index 0000000..223f964--- /dev/null+++ b/src/app/builds/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import SiteHeader from "@/components/SiteHeader";+import Workshop from "@/components/workshop/Workshop";+import SiteFooter from "@/components/SiteFooter";++export const metadata: Metadata = { title: "Your workshop | Bygga" };++export default function Page() {+ return (+ <div className="site">+ <SiteHeader />+ <main>+ <Workshop />+ </main>+ <SiteFooter />+ </div>+ );+}diff --git a/src/app/favicon.ico b/src/app/favicon.icodeleted file mode 100644index af98450..0000000Binary files a/src/app/favicon.ico and /dev/null differdiff --git a/src/app/globals.css b/src/app/globals.cssindex 4c18fb3..c021248 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -1,49 +1,268 @@:root {- --background: #ffffff;- --foreground: #171717;+ --paper: #ffffff;+ --page: #f5f4f0;+ --ink: #121212;+ --ink-2: #4a4945;+ --ink-3: #8a877f;+ --line: #e8e6e0;+ --line-2: #d9d6ce;+ --sunk: #f2f0eb;+ --accent: #ffd21f;+ --accent-soft: #fff4c7;+ --accent-ink: #3a2f00;+ --blue: #0a5bd3;+ --ok: #157f45;+ --miss: #c8371d;+ --miss-soft: #fdecea;+ --r-xl: 28px;+ --r-lg: 20px;+ --r: 14px;+ --r-sm: 10px;+ --ring: 0 0 0 1px var(--line);+ --shadow-1: 0 0 0 1px var(--line), 0 1px 2px rgba(18, 18, 18, 0.03);+ --shadow-2: 0 0 0 1px rgba(18, 18, 18, 0.04), 0 2px 6px rgba(18, 18, 18, 0.05), 0 24px 56px -12px rgba(18, 18, 18, 0.16);+ --ease: cubic-bezier(0.22, 1, 0.36, 1);+ --spring: cubic-bezier(0.34, 1.56, 0.64, 1);+ --font: var(--font-noto), "Noto Sans", system-ui, -apple-system, "Segoe UI", sans-serif;+ --display: var(--font-display), var(--font-noto), "Noto Sans", system-ui, sans-serif;+ color-scheme: light;}-@media (prefers-color-scheme: dark) {- :root {- --background: #0a0a0a;- --foreground: #ededed;- }-}--html {- height: 100%;+* {+ box-sizing: border-box;}html,body {- max-width: 100vw;- overflow-x: hidden;-}--body {- min-height: 100%;- display: flex;- flex-direction: column;- color: var(--foreground);- background: var(--background);- font-family: Arial, Helvetica, sans-serif;+ margin: 0;+ padding: 0;+ background: var(--page);+ color: var(--ink);+ font-family: var(--font);+ font-size: 16px;+ line-height: 1.5;+ letter-spacing: -0.011em;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ text-rendering: optimizeLegibility;}-* {- box-sizing: border-box;- padding: 0;- margin: 0;+button,+input,+textarea,+select {+ font: inherit;+ color: inherit;+ letter-spacing: inherit;}a {color: inherit;- text-decoration: none;}-@media (prefers-color-scheme: dark) {- html {- color-scheme: dark;- }+:focus-visible {+ outline: 3px solid var(--blue);+ outline-offset: 2px;+}++::selection {+ background: var(--accent);+ color: var(--ink);+}++/* ---------- stage ---------- */++.stage {+ position: relative;+ width: 100%;+ height: 100%;+ overflow: hidden;+ user-select: none;+ -webkit-user-select: none;+}++.stage-canvas {+ position: absolute;+ inset: 0;+ width: 100% !important;+ height: 100% !important;+ display: block;+ cursor: grab;+}++.stage-canvas:active {+ cursor: grabbing;+}++.stage-overlay {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ overflow: visible;+}++.stage-overlay .arrow,+.stage-callout-svg .arrow {+ fill: var(--ink);+ stroke: #fff;+ stroke-width: 2.5px;+ paint-order: stroke;+ stroke-linejoin: round;+}++.stage-callout-svg .arrow.turn {+ fill: var(--ink);+}++.stage-overlay .leader {+ stroke: var(--ink);+ stroke-width: 1.4px;+ fill: none;+}++.stage-overlay .leader-dot {+ fill: #fff;+ stroke: var(--ink);+ stroke-width: 1.6px;+}++.stage-overlay .diag {+ fill: none;+ stroke: var(--ink);+ stroke-width: 2px;+ stroke-dasharray: 7 6;+ stroke-linecap: round;+ stroke-linejoin: round;+}++.stage-overlay .diag-eq circle {+ fill: #fff;+ stroke: var(--ink);+ stroke-width: 2px;+}++.stage-overlay .diag-eq path {+ stroke: var(--ink);+ stroke-width: 2.4px;+ stroke-linecap: round;+}++.stage-labels {+ position: absolute;+ inset: 0;+ pointer-events: none;+}++.stage-label {+ position: absolute;+ left: 0;+ top: 0;+ display: flex;+ align-items: center;+ gap: 4px;+ height: 30px;+ min-width: 30px;+ padding: 0 9px;+ border-radius: 999px;+ background: #fff;+ border: 1.6px solid var(--ink);+ font-weight: 800;+ font-size: 15px;+ justify-content: center;+ will-change: transform, opacity;+ transition: background 0.25s var(--ease);+}++.stage-label span {+ font-weight: 600;+ font-size: 13px;+ color: var(--ink-2);+}++.stage-label.lit {+ background: var(--accent);+}++.stage-callout {+ position: absolute;+ top: 18px;+ right: 18px;+ border-radius: 50%;+ overflow: hidden;+ background: #fff;+ box-shadow: 0 0 0 1.6px var(--ink), 0 10px 30px rgba(20, 20, 20, 0.12);+ pointer-events: none;+ transform-origin: 70% 30%;+}++.stage-callout canvas {+ width: 100% !important;+ height: 100% !important;+ display: block;+}++.stage-callout-svg {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+}++.stage-tip {+ position: absolute;+ left: 0;+ top: 0;+ pointer-events: none;+ background: var(--ink);+ color: #fff;+ font-size: 13px;+ font-weight: 600;+ padding: 6px 10px 6px 6px;+ border-radius: 999px;+ display: flex;+ gap: 8px;+ align-items: center;+ opacity: 0;+ transition: opacity 0.15s;+ white-space: nowrap;+}++.stage-tip b {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: 50%;+ background: #fff;+ color: var(--ink);+ font-size: 12px;+}++.stage-overlay .dims {+ transition: opacity 0.3s;+}+.stage-overlay .dims .dim {+ fill: none;+ stroke: var(--ink);+ stroke-width: 1.4px;+ stroke-linecap: round;+ stroke-linejoin: round;+}+.stage-overlay .dims .ext {+ fill: none;+ stroke: var(--ink-3);+ stroke-width: 1px;+}+.stage-overlay .dims text {+ font-family: var(--font);+ font-size: 13px;+ font-weight: 700;+ fill: var(--ink);+ text-anchor: middle;+ paint-order: stroke;+ stroke: #fff;+ stroke-width: 4px;+ stroke-linejoin: round;}diff --git a/src/app/guide.css b/src/app/guide.cssnew file mode 100644index 0000000..a78c26a--- /dev/null+++ b/src/app/guide.css@@ -0,0 +1,2238 @@+/* ================= shared bits ================= */++.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}++.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ border: 0;+ background: transparent;+ cursor: pointer;+ font-weight: 600;+ font-size: 16px;+ border-radius: 999px;+ text-decoration: none;+ white-space: nowrap;+ color: var(--ink);+ transition:+ transform 0.16s var(--ease),+ background-color 0.2s,+ box-shadow 0.2s,+ color 0.2s,+ opacity 0.2s;+ -webkit-tap-highlight-color: transparent;+}+.btn:active:not(:disabled) {+ transform: scale(0.965);+}+.btn.primary {+ background: var(--ink);+ color: #fff;+ height: 52px;+ padding: 0 24px;+}+.btn.primary:hover:not(:disabled) {+ background: #2a2a2a;+}+.btn.primary.big {+ height: 58px;+ flex: 1;+ font-size: 17px;+ justify-content: space-between;+ padding: 0 22px 0 26px;+ min-width: 0;+ position: relative;+ overflow: hidden;+}+.btn.primary.big > span {+ overflow: hidden;+ text-overflow: ellipsis;+}+.btn.primary.big::after {+ content: "";+ position: absolute;+ inset: 0;+ background: linear-gradient(100deg, transparent 30%, rgba(255, 255, 255, 0.16) 50%, transparent 70%);+ transform: translateX(-120%);+ transition: transform 0.7s var(--ease);+ pointer-events: none;+}+.btn.primary.big:hover::after {+ transform: translateX(120%);+}+.btn.primary.going {+ background: var(--accent);+ color: var(--ink);+}+.btn.primary:disabled {+ background: var(--sunk);+ color: var(--ink-3);+ cursor: default;+}+.btn.round {+ width: 52px;+ height: 52px;+ flex: 0 0 auto;+ background: var(--sunk);+}+.btn.round:hover:not(:disabled) {+ background: #e8e5de;+}+.btn.round.small {+ width: 40px;+ height: 40px;+}+.btn.round.small.primary {+ padding: 0;+ height: 40px;+}+.btn.round:disabled {+ opacity: 0.4;+ cursor: default;+}+.btn.ghost {+ height: 48px;+ padding: 0 20px;+ background: var(--sunk);+}+.btn.link {+ background: none;+ text-decoration: underline;+ text-decoration-thickness: 1.5px;+ text-underline-offset: 4px;+ color: var(--ink-2);+ font-weight: 600;+ padding: 6px 4px;+ font-size: 15px;+}+.btn.link:hover {+ color: var(--ink);+}+.btn.link.inline {+ padding: 0;+ font-size: inherit;+}++.icon-btn {+ position: relative;+ display: inline-grid;+ place-items: center;+ width: 40px;+ height: 40px;+ border-radius: 12px;+ border: 0;+ background: transparent;+ color: var(--ink);+ cursor: pointer;+ transition:+ background 0.2s,+ transform 0.15s var(--ease);+}+.icon-btn:hover {+ background: rgba(18, 18, 18, 0.06);+}+.icon-btn:active {+ transform: scale(0.94);+}+.icon-btn.live {+ background: var(--accent);+}+.icon-btn.float,+.pill-btn.float {+ background: rgba(255, 255, 255, 0.92);+ box-shadow: 0 0 0 1px var(--line);+ backdrop-filter: blur(6px);+ border-radius: 999px;+}+.icon-btn.float:hover,+.pill-btn.float:hover {+ box-shadow: 0 0 0 1.5px var(--ink);+}+[data-tip]::after {+ content: attr(data-tip);+ position: absolute;+ top: calc(100% + 8px);+ left: 50%;+ transform: translate(-50%, -4px);+ padding: 5px 9px;+ border-radius: 8px;+ background: var(--ink);+ color: #fff;+ font-size: 12.5px;+ font-weight: 600;+ white-space: nowrap;+ opacity: 0;+ pointer-events: none;+ transition:+ opacity 0.15s,+ transform 0.15s var(--ease);+ z-index: 30;+}+[data-tip]:hover::after {+ opacity: 1;+ transform: translate(-50%, 0);+ transition-delay: 0.35s;+}+.stage-ctl [data-tip]::after,+.pane-foot [data-tip]::after {+ top: auto;+ bottom: calc(100% + 8px);+}+@media (hover: none) {+ [data-tip]::after {+ display: none;+ }+}+.pill-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 40px;+ padding: 0 15px;+ border: 0;+ border-radius: 999px;+ font-weight: 600;+ font-size: 14px;+ cursor: pointer;+ color: var(--ink);+ transition:+ background 0.2s,+ box-shadow 0.2s;+}+.pill-btn.on {+ background: var(--accent);+ box-shadow: 0 0 0 1.5px var(--ink);+}++.chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 36px;+ padding: 0 14px;+ border-radius: 999px;+ background: #fff;+ box-shadow: inset 0 0 0 1.5px var(--line-2);+ font-weight: 600;+ font-size: 14.5px;+ text-decoration: none;+ color: var(--ink);+ cursor: pointer;+ border: 0;+ transition:+ box-shadow 0.2s,+ background 0.2s,+ transform 0.15s var(--ease);+}+.chip:hover {+ box-shadow: inset 0 0 0 1.5px var(--ink);+}+.chip:active {+ transform: scale(0.97);+}+.chip.on {+ background: var(--ink);+ color: #fff;+ box-shadow: none;+}+.chip.ghost {+ background: var(--sunk);+ box-shadow: none;+}+.chip.ghost:hover {+ background: #e8e5de;+}+.chips {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.chips.center {+ justify-content: center;+ align-items: center;+}++.muted {+ color: var(--ink-3);+}++.ring {+ position: relative;+ display: inline-grid;+ place-items: center;+ flex: 0 0 auto;+}+.ring svg {+ position: absolute;+ inset: 0;+}+.ring-label {+ font-size: 12px;+ font-weight: 800;+}+.dots {+ display: inline-flex;+ gap: 3px;+ align-items: center;+}+.dots i {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--line-2);+}+.dots i.on {+ background: var(--ink);+}+.checkdot {+ display: inline-block;+ flex: 0 0 auto;+}+.checkdot svg {+ display: block;+}++.letter {+ display: inline-grid;+ place-items: center;+ width: 32px;+ height: 32px;+ border-radius: 50%;+ background: #fff;+ box-shadow: inset 0 0 0 1.8px var(--ink);+ font-weight: 800;+ font-size: 15px;+ flex: 0 0 auto;+ transition: background 0.25s;+}+.letter.sm {+ width: 26px;+ height: 26px;+ font-size: 13px;+}++.thumb {+ display: block;+ position: relative;+ border-radius: 10px;+ background: linear-gradient(90deg, #f6f5f1 0%, #fbfaf8 50%, #f6f5f1 100%);+ background-size: 200% 100%;+ animation: shimmer 1.6s linear infinite;+ overflow: hidden;+}+.thumb.ready {+ background: transparent;+ animation: none;+}+.thumb img {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: contain;+ animation: fadeIn 0.4s var(--ease);+}+@keyframes shimmer {+ to {+ background-position: -200% 0;+ }+}+@keyframes fadeIn {+ from {+ opacity: 0;+ transform: scale(0.97);+ }+}++.ai-badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 28px;+ padding: 0 11px 0 9px;+ border-radius: 999px;+ background: var(--ink);+ color: #fff;+ font-size: 13px;+ font-weight: 600;+}+.ai-badge.quiet {+ background: transparent;+ color: var(--ink-2);+ box-shadow: inset 0 0 0 1.5px var(--line-2);+}++/* ================= layout ================= */++.guide {+ height: 100dvh;+ display: grid;+ grid-template-rows: 68px minmax(0, 1fr);+ overflow: hidden;+}++.topbar {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr) auto auto;+ align-items: center;+ gap: 14px;+ padding: 0 14px 0 16px;+ min-width: 0;+}+.guide .topbar {+ grid-template-columns: auto minmax(120px, 1fr) auto minmax(120px, 1fr);+}+.home-btn {+ display: grid;+ place-items: center;+ border-radius: 50%;+}+.tb-title {+ display: flex;+ flex-direction: column;+ line-height: 1.2;+ min-width: 0;+}+.tb-title b {+ font-family: var(--display);+ font-size: 19px;+ font-weight: 800;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ letter-spacing: -0.01em;+}+.tb-title span {+ font-size: 13.5px;+ color: var(--ink-2);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.tb-actions {+ display: flex;+ gap: 4px;+ justify-content: flex-end;+}++/* stepper */+.stepper {+ display: flex;+ align-items: center;+ justify-self: center;+ padding: 4px;+ border-radius: 999px;+ background: #fff;+ box-shadow: var(--shadow-1);+}+.stp-wrap {+ display: flex;+ align-items: center;+}+.stp-line {+ width: 14px;+ height: 2px;+ border-radius: 2px;+ background: var(--line-2);+ margin: 0 2px;+ transition: background 0.4s;+}+.stp-line.on {+ background: var(--ink);+}+.stp {+ position: relative;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ height: 36px;+ padding: 0 14px 0 11px;+ border: 0;+ border-radius: 999px;+ background: transparent;+ font-weight: 500;+ font-size: 14px;+ color: var(--ink-3);+ cursor: default;+ isolation: isolate;+ transition: color 0.3s;+}+.stp > :not(.stp-bg) {+ position: relative;+ z-index: 1;+}+.stp-bg {+ position: absolute;+ inset: 0;+ border-radius: 999px;+ background: var(--ink);+ z-index: 0;+}+.stp.now {+ color: #fff;+}+.stp.done {+ color: var(--ink);+}+.stp:not(:disabled) {+ cursor: pointer;+}+.stp.done:not(:disabled):hover {+ background: var(--sunk);+}+.stp-ico {+ display: grid;+ place-items: center;+ width: 20px;+ height: 20px;+ border-radius: 50%;+}+.stp.done .stp-ico {+ background: var(--accent);+ color: var(--ink);+}+.stp-count {+ font-size: 12.5px;+ font-weight: 600;+ padding: 1px 7px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.16);+ font-variant-numeric: tabular-nums;+}+.stp-bar {+ position: absolute !important;+ left: 14px;+ right: 14px;+ bottom: 5px;+ height: 2px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.2);+ overflow: hidden;+}+.stp.done .stp-bar {+ background: var(--line);+}+.stp-bar i {+ display: block;+ height: 100%;+ background: var(--accent);+ transform-origin: 0 50%;+}++.guide-main {+ display: grid;+ grid-template-columns: minmax(0, 1fr) clamp(380px, 31vw, 450px);+ gap: 12px;+ padding: 0 12px 12px;+ min-height: 0;+}+.sheet {+ position: relative;+ background: var(--paper);+ border-radius: var(--r-xl);+ box-shadow: var(--shadow-1);+ overflow: hidden;+ min-height: 0;+}+.panel {+ background: var(--paper);+ border-radius: var(--r-xl);+ box-shadow: var(--shadow-1);+ overflow: hidden;+ min-height: 0;+ position: relative;+}+.panel-inner {+ height: 100%;+ min-height: 0;+}+.pane {+ height: 100%;+ min-height: 0;+ display: flex;+ flex-direction: column;+}+.pane-scroll {+ flex: 1 1 auto;+ min-height: 0;+ overflow-y: auto;+ padding: 28px 26px 22px;+ overscroll-behavior: contain;+ scrollbar-width: thin;+ scrollbar-color: var(--line-2) transparent;+}+.pane-foot {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 14px 16px 14px;+ border-top: 1px solid var(--line);+ flex-wrap: wrap;+ background: #fff;+}+.pane-head {+ margin-bottom: 4px;+}+.pane h2 {+ font-family: var(--display);+ font-size: 30px;+ line-height: 1.12;+ font-weight: 800;+ letter-spacing: -0.02em;+ margin: 0;+ text-wrap: balance;+}+.eyebrow {+ display: inline-block;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink-3);+ margin: 0 0 6px;+}+.sub {+ color: var(--ink-2);+ margin: 8px 0 0;+ font-size: 16px;+ line-height: 1.5;+ text-wrap: pretty;+}+.sub.center {+ text-align: center;+}+.note {+ font-size: 14.5px;+ color: var(--ink-2);+ margin: -2px 0 10px;+}+.section-title {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink-2);+ margin: 26px 0 10px;+}+.count-pill {+ font-size: 12.5px;+ color: var(--ink-3);+ font-weight: 600;+ background: var(--sunk);+ padding: 1px 8px;+ border-radius: 999px;+}+.foot-row {+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: -4px 0 -6px;+ padding: 0 4px;+}+.foot-row.center {+ justify-content: center;+}+.foot-row .btn.link {+ font-size: 14.5px;+}+.kbd-hint {+ font-size: 13px;+ color: var(--ink-3);+ font-weight: 600;+}+.kbd-hint kbd {+ display: inline-grid;+ place-items: center;+ min-width: 22px;+ height: 22px;+ padding: 0 5px;+ margin-right: 2px;+ border-radius: 6px;+ background: var(--sunk);+ box-shadow: inset 0 -1.5px 0 var(--line-2);+ font: inherit;+ font-size: 12px;+ color: var(--ink-2);+}++.callout {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ margin-top: 16px;+ padding: 13px 15px;+ border-radius: 16px;+ background: var(--sunk);+ font-size: 15px;+ line-height: 1.45;+}+.callout > svg {+ flex: 0 0 auto;+ margin-top: 1px;+}+.callout > div {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.callout b {+ font-size: 15px;+}+.callout span {+ color: var(--ink-2);+ font-size: 14.5px;+}+.callout.warn {+ align-items: center;+ background: #fff6d5;+ box-shadow: inset 0 0 0 1px #f2e3a0;+}+.callout.repeat {+ align-items: center;+ font-weight: 600;+}+.callout.repeat span {+ color: var(--ink);+}+.repeat-badge {+ display: grid;+ place-items: center;+ min-width: 44px;+ height: 44px;+ padding: 0 8px;+ border-radius: 13px;+ background: var(--ink);+ color: #fff !important;+ font-weight: 800;+ font-size: 18px !important;+}+.callout.note {+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--line);+}++/* ================= stage overlays ================= */++.corner {+ position: absolute;+ top: 16px;+ left: 24px;+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 12px;+ pointer-events: none;+ z-index: 2;+}+.num-wrap {+ position: relative;+ height: clamp(58px, 6.4vw, 100px);+ display: flex;+ align-items: flex-start;+}+.corner .big-n {+ display: block;+ font-family: var(--display);+ font-size: clamp(60px, 6.6vw, 104px);+ line-height: 0.92;+ font-weight: 800;+ letter-spacing: -0.05em;+ font-variant-numeric: tabular-nums;+}+.corner-repeat {+ position: absolute;+ left: calc(100% + 8px);+ top: 6px;+ display: grid;+ place-items: center;+ height: 36px;+ padding: 0 12px;+ border-radius: 999px;+ background: var(--ink);+ color: #fff;+ font-weight: 800;+ font-size: 17px;+}+.hw-box {+ display: flex;+ gap: 4px;+ padding: 8px 10px 6px;+ background: #fff;+ border-radius: 16px;+ box-shadow: inset 0 0 0 1.8px var(--ink);+}+.hw-box-item {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: flex-end;+ gap: 4px;+ min-width: 54px;+ padding: 2px 4px;+ border-radius: 10px;+ transition: background 0.2s;+}+.hw-box-item svg {+ max-height: 40px;+}+.hw-box-item b {+ font-size: 15px;+ font-weight: 800;+}+.hw-box-item.lit {+ background: var(--accent-soft);+}+.stamp {+ position: absolute;+ left: 50%;+ top: 46%;+ margin: -42px 0 0 -42px;+ width: 84px;+ height: 84px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow: 0 0 0 2.4px var(--ink);+ display: grid;+ place-items: center;+ pointer-events: none;+ z-index: 4;+}+.toast {+ position: absolute;+ left: 50%;+ bottom: 22px;+ translate: -50% 0;+ display: inline-flex;+ align-items: center;+ gap: 10px;+ height: 52px;+ padding: 0 20px 0 10px;+ border-radius: 999px;+ background: #fff;+ box-shadow: var(--shadow-2);+ font-weight: 600;+ z-index: 5;+ white-space: nowrap;+}+.stage-ctl {+ position: absolute;+ left: 14px;+ bottom: 14px;+ display: flex;+ gap: 8px;+ z-index: 3;+}+.drag-hint,+.sheet-caption {+ position: absolute;+ bottom: 24px;+ right: 24px;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink-3);+ pointer-events: none;+ animation: fadeIn 0.6s 1.2s var(--ease) both;+ display: inline-flex;+ align-items: center;+ gap: 6px;+}+.sheet-caption {+ left: 50%;+ right: auto;+ transform: translateX(-50%);+ white-space: nowrap;+}+.sheet-caption.ai {+ left: auto;+ right: 24px;+ transform: none;+}+.listening {+ position: absolute;+ top: 18px;+ left: 50%;+ transform: translateX(-50%);+ display: inline-flex;+ align-items: center;+ gap: 10px;+ height: 40px;+ padding: 0 16px 0 14px;+ border-radius: 999px;+ background: var(--ink);+ color: #fff;+ font-size: 14px;+ font-weight: 600;+ z-index: 3;+ animation: fadeIn 0.3s var(--ease);+ max-width: calc(100% - 32px);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.eq {+ display: inline-flex;+ align-items: center;+ gap: 2.5px;+ height: 14px;+ flex: 0 0 auto;+}+.eq i {+ width: 3px;+ height: 100%;+ border-radius: 2px;+ background: currentColor;+ opacity: 0.55;+ transform: scaleY(0.35);+ transition: transform 0.3s var(--ease);+}+.eq.on i {+ opacity: 1;+ animation: eq 0.9s ease-in-out infinite;+}+.eq.on i:nth-child(2) {+ animation-delay: -0.3s;+}+.eq.on i:nth-child(3) {+ animation-delay: -0.6s;+}+@keyframes eq {+ 0%,+ 100% {+ transform: scaleY(0.35);+ }+ 50% {+ transform: scaleY(1);+ }+}++/* ================= cover ================= */++.product-name {+ font-family: var(--display);+ font-size: clamp(46px, 4.4vw, 64px);+ font-weight: 800;+ letter-spacing: -0.035em;+ line-height: 0.95;+ margin: 0;+ word-break: break-word;+}+.product-variant {+ font-size: 18px;+ color: var(--ink-2);+ margin: 10px 0 18px;+}+.stats {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ margin: 22px 0 0;+ border-radius: 18px;+ box-shadow: inset 0 0 0 1px var(--line);+}+.stats > div {+ padding: 14px 16px 13px;+ min-width: 0;+}+.stats > div + div {+ border-left: 1px solid var(--line);+}+.stats dt {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 13px;+ font-weight: 600;+ color: var(--ink-3);+}+.stats dd {+ margin: 4px 0 0;+ font-family: var(--display);+ font-size: 21px;+ font-weight: 800;+ letter-spacing: -0.01em;+ white-space: nowrap;+}+.prep {+ list-style: none;+ padding: 0;+ margin: 0;+ display: grid;+ gap: 12px;+}+.prep li {+ display: flex;+ gap: 12px;+ align-items: flex-start;+ font-size: 15.5px;+ line-height: 1.45;+}+.prep-ico {+ display: grid;+ place-items: center;+ width: 32px;+ height: 32px;+ border-radius: 10px;+ background: var(--sunk);+ flex: 0 0 auto;+ margin-top: -4px;+}+.official {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin-top: 20px;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink-3);+ text-underline-offset: 4px;+}+.official:hover {+ color: var(--ink);+}++/* ================= tools ================= */++.tgrid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 10px;+ margin-top: 20px;+}+.tgrid.three {+ grid-template-columns: repeat(3, minmax(0, 1fr));+ margin-top: 0;+}+.tcard {+ perspective: 900px;+}+.tcard-inner {+ position: relative;+ display: block;+ width: 100%;+ min-height: 168px;+ padding: 0;+ border: 0;+ background: none;+ cursor: pointer;+ transform-style: preserve-3d;+ transition: transform 0.6s var(--spring);+ text-align: left;+ color: var(--ink);+}+.tcard.small .tcard-inner {+ min-height: 118px;+}+.tcard-inner.flipped {+ transform: rotateY(180deg);+}+.tface {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ border-radius: 18px;+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--line);+ backface-visibility: hidden;+ -webkit-backface-visibility: hidden;+ padding: 12px 14px 14px;+ transition:+ box-shadow 0.25s,+ background 0.25s;+}+.tcard-inner:hover .front {+ box-shadow: inset 0 0 0 1.5px var(--line-2);+}+.tcard.on .front {+ background: #fffcf0;+ box-shadow: inset 0 0 0 1.5px var(--ink);+}+.tface.back {+ transform: rotateY(180deg);+ background: var(--ink);+ color: #fff;+ box-shadow: none;+ justify-content: center;+ gap: 6px;+}+.tart {+ display: grid;+ place-items: center;+ flex: 1;+ transition: transform 0.45s var(--spring);+}+.tcard.on .tart {+ transform: translateY(-3px) rotate(-6deg) scale(1.04);+}+.tname {+ font-weight: 800;+ font-size: 15px;+ line-height: 1.25;+}+.tcard.small .tname {+ font-size: 13.5px;+}+.thint {+ font-size: 13px;+ color: var(--ink-2);+ line-height: 1.3;+}+.tcard.small .thint {+ display: none;+}+.tbadge {+ position: absolute;+ top: 10px;+ left: 10px;+ height: 22px;+ padding: 0 8px;+ border-radius: 999px;+ background: var(--accent);+ font-size: 11.5px;+ font-weight: 800;+ display: grid;+ place-items: center;+}+.tcheck {+ position: absolute;+ top: 10px;+ right: 10px;+ width: 26px;+ height: 26px;+ border-radius: 50%;+ background: var(--ink);+ color: #fff;+ display: grid;+ place-items: center;+}+.tback-title {+ font-weight: 800;+ font-size: 15.5px;+}+.tback-text {+ font-size: 13.5px;+ line-height: 1.4;+ color: rgba(255, 255, 255, 0.82);+}+.tback-flip {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ margin-top: 6px;+ font-size: 12px;+ font-weight: 600;+ color: var(--accent);+}++/* ================= parts ================= */++.plist {+ display: grid;+ gap: 4px;+}+.prow {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ min-height: 60px;+ padding: 6px 12px 6px 8px;+ border-radius: 14px;+ border: 0;+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--line);+ cursor: pointer;+ text-align: left;+ color: var(--ink);+ transition:+ box-shadow 0.2s,+ background 0.25s,+ opacity 0.25s;+}+.prow:hover {+ box-shadow: inset 0 0 0 1.5px var(--ink);+}+.prow.ok {+ background: #fffcf0;+}+.prow.miss {+ background: var(--miss-soft);+ box-shadow: inset 0 0 0 1.5px #f3c3b9;+}+.prow.miss .ptext b {+ text-decoration: line-through;+ text-decoration-color: var(--miss);+}+.pthumb {+ width: 64px;+ flex: 0 0 auto;+}+.part-art {+ display: grid;+ place-items: center;+ width: 64px;+ min-height: 44px;+ flex: 0 0 auto;+}+.plist.actual .part-art {+ width: auto;+ min-width: 64px;+ justify-items: start;+ padding: 6px 0;+}+.ptext {+ flex: 1 1 auto;+ min-width: 0;+ display: flex;+ flex-direction: column;+ line-height: 1.3;+}+.ptext b {+ font-size: 15px;+ font-weight: 600;+}+.ptext span {+ font-size: 13px;+ color: var(--ink-3);+}+.pqty {+ font-weight: 800;+ font-size: 16px;+ font-variant-numeric: tabular-nums;+}+.pstate {+ display: grid;+ place-items: center;+ min-width: 26px;+ height: 26px;+}+.pdot {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1.5px var(--line-2);+}+.pok {+ width: 24px;+ height: 24px;+ border-radius: 50%;+ background: var(--ink);+ color: #fff;+ display: grid;+ place-items: center;+}+.pmiss {+ height: 24px;+ padding: 0 9px;+ border-radius: 999px;+ background: var(--miss);+ color: #fff;+ font-size: 12px;+ font-weight: 800;+ display: grid;+ place-items: center;+}+.toggle {+ margin-left: auto;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 30px;+ padding: 0 11px;+ border-radius: 999px;+ border: 0;+ background: var(--sunk);+ font-weight: 600;+ font-size: 13px;+ color: var(--ink);+ cursor: pointer;+ transition: background 0.2s;+}+.toggle.on {+ background: var(--accent);+}+.notbox,+.missbox {+ display: flex;+ gap: 10px;+ margin-top: 16px;+ padding: 12px 14px;+ border-radius: 14px;+ background: var(--sunk);+ font-size: 14px;+ line-height: 1.45;+}+.notbox > div,+.missbox {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.notbox span,+.missbox span {+ color: var(--ink-2);+}+.missbox {+ background: var(--miss-soft);+ align-items: flex-start;+}+.missbox b {+ color: var(--miss);+}++.modal-back,+.overlay-back,+.sheet-back {+ position: fixed;+ inset: 0;+ background: rgba(18, 18, 18, 0.3);+ z-index: 50;+ display: grid;+ place-items: center;+ padding: 16px;+}+.modal {+ position: relative;+ width: min(520px, 100%);+ background: #fff;+ border-radius: 28px;+ padding: 26px;+ box-shadow: var(--shadow-2);+ display: grid;+ gap: 14px;+}+.modal h3 {+ margin: 0;+ font-size: 22px;+}+.modal .close {+ position: absolute;+ top: 14px;+ right: 14px;+}+.calib-stage {+ display: grid;+ place-items: center;+ min-height: 240px;+ overflow: hidden;+}+.calib-card {+ border-radius: 9px;+ box-shadow: inset 0 0 0 2px var(--ink);+ background: repeating-linear-gradient(135deg, #fff 0 8px, var(--accent-soft) 8px 16px);+ position: relative;+}+.calib-card span {+ position: absolute;+ left: 12%;+ top: 30%;+ width: 18%;+ height: 26%;+ border-radius: 4px;+ box-shadow: inset 0 0 0 1.5px var(--ink);+ background: #fff;+}+input[type="range"] {+ width: 100%;+ accent-color: var(--ink);+}++/* ================= steps ================= */++.step-meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ margin-bottom: 4px;+}+.step-meta .eyebrow {+ margin: 0;+}+.time-pill {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ height: 26px;+ padding: 0 10px;+ border-radius: 999px;+ background: var(--sunk);+ font-size: 12.5px;+ font-weight: 600;+ color: var(--ink-2);+ white-space: nowrap;+}+.step-title {+ font-size: clamp(26px, 2.2vw, 31px) !important;+}+.needs {+ list-style: none;+ margin: 0;+ padding: 0;+ border-radius: 16px;+ box-shadow: inset 0 0 0 1px var(--line);+ overflow: hidden;+}+.needs li {+ display: flex;+ align-items: center;+ gap: 10px;+ min-height: 56px;+ padding: 6px 14px 6px 8px;+ transition: background 0.2s;+}+.needs li + li {+ border-top: 1px solid var(--line);+}+.needs li:hover {+ background: #fffcf0;+}+.need-thumb {+ width: 56px;+ flex: 0 0 auto;+}+.need-art {+ display: grid;+ place-items: center;+ width: 56px;+ height: 42px;+ flex: 0 0 auto;+}+.need-name {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ line-height: 1.25;+ font-weight: 600;+ font-size: 15px;+}+.need-name small {+ font-size: 12.5px;+ color: var(--ink-3);+ font-weight: 600;+}+.need-qty {+ font-weight: 800;+ font-size: 16px;+ font-variant-numeric: tabular-nums;+}+.warn-row {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 12px;+}+.warn-chip {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ height: 36px;+ padding: 0 12px 0 6px;+ border-radius: 999px;+ background: var(--sunk);+ font-size: 13.5px;+ font-weight: 600;+}+.heads-up {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 16px 0 0;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink-2);+}+.upnext {+ display: block;+ width: 100%;+ margin-top: 22px;+ padding: 0;+ border: 0;+ background: none;+ text-align: left;+ cursor: pointer;+ color: var(--ink);+}+.upnext-label {+ display: block;+ font-size: 14px;+ font-weight: 500;+ color: var(--ink-2);+ margin-bottom: 8px;+}+.upnext-body {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 8px 14px 8px 8px;+ border-radius: 16px;+ background: var(--sunk);+ transition:+ background 0.2s,+ transform 0.2s var(--ease);+}+.upnext:hover .upnext-body {+ background: #ebe8e1;+}+.upnext:hover .upnext-body > svg {+ transform: translateX(3px);+}+.upnext-body > svg {+ transition: transform 0.2s var(--ease);+ flex: 0 0 auto;+}+.upnext-thumb {+ width: 76px;+ flex: 0 0 auto;+ background-color: #fff;+ border-radius: 10px;+}+.upnext-text {+ flex: 1;+ display: flex;+ gap: 8px;+ align-items: baseline;+ font-size: 14.5px;+ font-weight: 600;+ line-height: 1.35;+ min-width: 0;+}+.upnext-text b {+ font-family: var(--display);+ font-size: 22px;+ font-weight: 800;+}+.upnext.final .upnext-body {+ padding: 14px 16px;+ color: var(--ink-2);+}+.done-btn .done-ico {+ display: grid;+ place-items: center;+ width: 30px;+ height: 30px;+ border-radius: 50%;+ background: var(--accent);+ color: var(--ink);+ margin-left: -10px;+ flex: 0 0 auto;+ transition: transform 0.3s var(--spring);+}+.done-btn:hover .done-ico {+ transform: scale(1.1) rotate(-8deg);+}+.done-btn .done-label {+ flex: 1;+ text-align: left;+ margin-left: 4px;+}++/* ================= done ================= */++.done-hero {+ display: flex;+ justify-content: center;+ margin: 2px 0 8px;+}+.figure.bounce {+ animation: hop 0.9s var(--ease) infinite alternate;+}+@keyframes hop {+ from {+ transform: translateY(0);+ }+ to {+ transform: translateY(-8px);+ }+}+.done-title {+ text-align: center;+ font-size: 34px !important;+}+.workshop-link {+ display: flex;+ align-items: center;+ gap: 12px;+ margin-top: 16px;+ padding: 12px 16px 12px 12px;+ border-radius: 16px;+ background: var(--ink);+ color: #fff;+ text-decoration: none;+ transition: transform 0.2s var(--ease);+}+.workshop-link:hover {+ transform: translateY(-1px);+}+.workshop-link > span:nth-child(2) {+ flex: 1;+ display: flex;+ flex-direction: column;+ line-height: 1.3;+}+.workshop-link > span:nth-child(2) span {+ font-size: 13.5px;+ color: rgba(255, 255, 255, 0.72);+}+.wl-ico {+ display: grid;+ place-items: center;+ width: 38px;+ height: 38px;+ border-radius: 12px;+ background: var(--accent);+ color: var(--ink);+}+.after {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 10px;+ font-size: 15px;+ color: var(--ink-2);+}+.after li {+ display: flex;+ gap: 10px;+ align-items: flex-start;+}+.after svg {+ flex: 0 0 auto;+ margin-top: 3px;+ color: var(--ink);+}+.confetti {+ position: fixed;+ inset: 0;+ pointer-events: none;+ z-index: 40;+ overflow: hidden;+}+.confetti .bit {+ position: absolute;+ top: 0;+}++/* ================= help ================= */++.sheet-back {+ place-items: stretch end;+ padding: 12px;+}+.side-sheet {+ width: min(460px, 100%);+ height: 100%;+ background: #fff;+ border-radius: 28px;+ box-shadow: var(--shadow-2);+ display: flex;+ flex-direction: column;+ overflow: hidden;+}+.sheet-head {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ padding: 22px 18px 16px 20px;+ border-bottom: 1px solid var(--line);+}+.sheet-head > div {+ flex: 1;+ min-width: 0;+}+.sheet-head h2 {+ font-family: var(--display);+ font-size: 23px;+ margin: 4px 0 0;+ letter-spacing: -0.015em;+}+.sheet-head .sub {+ font-size: 14.5px;+ margin-top: 4px;+}+.sheet-body {+ flex: 1;+ overflow-y: auto;+ padding: 16px 18px;+}+.faq {+ display: grid;+ gap: 6px;+}+.faq-item {+ border-radius: 14px;+ background: var(--sunk);+ overflow: hidden;+}+.faq-item button {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ width: 100%;+ padding: 13px 14px;+ border: 0;+ background: none;+ font-weight: 600;+ font-size: 15px;+ text-align: left;+ cursor: pointer;+ color: var(--ink);+}+.faq-item button svg {+ transition: transform 0.25s var(--ease);+ flex: 0 0 auto;+}+.faq-item.open button svg {+ transform: rotate(180deg);+}+.faq-item p {+ margin: 0;+ padding: 0 14px 14px;+ font-size: 15px;+ color: var(--ink-2);+ line-height: 1.5;+}+.ask-head {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 22px 0 10px;+ font-size: 15px;+}+.ask-head .muted {+ margin-left: auto;+ font-size: 13px;+ font-weight: 600;+}+.ask-suggest {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}+.ask-suggest .chip {+ height: auto;+ min-height: 36px;+ padding: 7px 13px;+ font-size: 14px;+ white-space: normal;+ text-align: left;+}+.msgs {+ display: grid;+ gap: 8px;+ margin-top: 10px;+}+.msg {+ max-width: 88%;+ padding: 10px 14px;+ border-radius: 18px;+ font-size: 15px;+ line-height: 1.5;+}+.msg p {+ margin: 0;+ white-space: pre-wrap;+}+.msg img {+ display: block;+ width: 160px;+ border-radius: 12px;+ margin-bottom: 8px;+}+.msg.user {+ justify-self: end;+ background: var(--ink);+ color: #fff;+ border-bottom-right-radius: 6px;+}+.msg.assistant {+ justify-self: start;+ background: var(--sunk);+ border-bottom-left-radius: 6px;+}+.typing {+ font-weight: 500;+ background: linear-gradient(90deg, var(--ink-3) 0%, var(--ink-3) 40%, var(--ink) 50%, var(--ink-3) 60%, var(--ink-3) 100%);+ background-size: 250% 100%;+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ animation: textShine 1.6s linear infinite;+}+@keyframes textShine {+ from {+ background-position: 100% 0;+ }+ to {+ background-position: -150% 0;+ }+}+.ask-bar {+ display: flex;+ gap: 8px;+ padding: 12px 14px 14px;+ border-top: 1px solid var(--line);+}+.ask-bar input:not([type]) {+ flex: 1;+ min-width: 0;+ height: 40px;+ padding: 0 16px;+ border-radius: 999px;+ border: 0;+ background: var(--sunk);+ font: inherit;+ font-size: 15px;+}+.ask-bar input:focus {+ outline: 2px solid var(--ink);+ outline-offset: 0;+}++/* ================= overview ================= */++.overview {+ width: min(1120px, 100%);+ max-height: calc(100dvh - 32px);+ background: #fff;+ border-radius: 28px;+ box-shadow: var(--shadow-2);+ display: flex;+ flex-direction: column;+ overflow: hidden;+}+.overview-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ padding: 24px 24px 12px;+}+.overview-head h2 {+ margin: 0;+ font-family: var(--display);+ font-size: 28px;+ letter-spacing: -0.02em;+}+.overview-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));+ gap: 12px;+ padding: 12px 24px 24px;+ overflow-y: auto;+}+.page {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: stretch;+ gap: 6px;+ padding: 12px;+ border-radius: 18px;+ border: 0;+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--line);+ cursor: pointer;+ text-align: left;+ color: var(--ink);+ transition:+ box-shadow 0.2s,+ transform 0.2s var(--ease);+}+.page:hover {+ box-shadow: inset 0 0 0 1.5px var(--ink);+ transform: translateY(-2px);+}+.page.current {+ box-shadow: inset 0 0 0 2.5px var(--ink);+ background: #fffcf0;+}+.page-n {+ font-family: var(--display);+ font-size: 28px;+ font-weight: 800;+ line-height: 1;+ letter-spacing: -0.03em;+}+.page-done {+ position: absolute;+ top: 12px;+ right: 12px;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ background: var(--ink);+ color: #fff;+ display: grid;+ place-items: center;+}+.page-thumb {+ width: 100%;+}+.page-title {+ font-size: 14px;+ font-weight: 600;+ line-height: 1.35;+ color: var(--ink-2);+}++/* ================= loader & not found ================= */++.shell-main {+ display: grid;+ place-items: center;+ padding: 24px 16px 40px;+ min-height: 0;+ overflow-y: auto;+}+.guide.shell .topbar {+ grid-template-columns: auto 1fr;+}+.loader {+ display: grid;+ justify-items: center;+ gap: 18px;+ text-align: center;+}+.loader-art {+ position: relative;+}+.loader-fig {+ position: absolute;+ right: -46px;+ bottom: -4px;+ animation: hop 1.1s var(--ease) infinite alternate;+}+.ld-panels path {+ transform-box: fill-box;+ transform-origin: 50% 100%;+ animation: rise 2.6s var(--ease) infinite;+}+.ld-panels .p2 {+ animation-delay: 0.18s;+}+.ld-panels .p3 {+ animation-delay: 0.36s;+}+@keyframes rise {+ 0%,+ 100% {+ transform: translateY(70px) rotate(0deg);+ }+ 45%,+ 75% {+ transform: translateY(0) rotate(-3deg);+ }+}+.flap-l,+.flap-r {+ transform-box: fill-box;+ animation: flap 2.6s var(--ease) infinite;+}+.flap-l {+ transform-origin: 100% 0;+}+.flap-r {+ transform-origin: 0 0;+ animation-name: flapR;+}+@keyframes flap {+ 0%,+ 100% {+ transform: rotate(0deg);+ }+ 40%,+ 80% {+ transform: rotate(10deg);+ }+}+@keyframes flapR {+ 0%,+ 100% {+ transform: rotate(0deg);+ }+ 40%,+ 80% {+ transform: rotate(-10deg);+ }+}+.loader-text {+ display: grid;+ justify-items: center;+ gap: 14px;+ min-height: 120px;+}+.loader-text p {+ font-family: var(--display);+ font-size: 23px;+ font-weight: 800;+ margin: 0;+}+.loader-bar {+ width: 220px;+ height: 5px;+ border-radius: 99px;+ background: var(--line);+ overflow: hidden;+}+.loader-bar span {+ display: block;+ height: 100%;+ background: var(--ink);+ border-radius: 99px;+ transition: width 1.4s var(--ease);+}+.notfound {+ display: grid;+ justify-items: center;+ gap: 14px;+ text-align: center;+ max-width: 560px;+}+.notfound h1 {+ font-family: var(--display);+ font-size: clamp(28px, 3.6vw, 40px);+ margin: 10px 0 0;+ letter-spacing: -0.025em;+ line-height: 1.1;+}+.notfound.wide {+ max-width: 1000px;+ width: 100%;+ justify-items: stretch;+ text-align: left;+ gap: 22px;+}+.nf-head {+ display: flex;+ align-items: center;+ gap: 18px;+}+.nf-head h1 {+ margin: 0;+}+.kind-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 10px;+}+.kind-card {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 4px;+ padding: 12px 10px 14px;+ border-radius: 20px;+ background: #fff;+ box-shadow: var(--shadow-1);+ text-decoration: none;+ color: var(--ink);+ font-weight: 600;+ font-size: 14.5px;+ transition:+ transform 0.25s var(--ease),+ box-shadow 0.25s;+}+.kind-card:hover {+ transform: translateY(-3px);+ box-shadow:+ 0 0 0 1.5px var(--ink),+ 0 10px 24px -10px rgba(18, 18, 18, 0.25);+}+.kind-thumb {+ width: 100%;+}++/* ================= small screens ================= */++@media (max-width: 1100px) {+ .guide .topbar {+ grid-template-columns: auto minmax(0, 1fr) auto auto;+ }+ .stp-label {+ display: none;+ }+ .stp.now .stp-label {+ display: inline;+ }+}++@media (max-width: 900px) {+ .guide {+ grid-template-rows: 58px minmax(230px, 44dvh) minmax(0, 1fr);+ transition: grid-template-rows 0.45s var(--ease);+ }+ .guide[data-phase="tools"] {+ grid-template-rows: 58px minmax(140px, 22dvh) minmax(0, 1fr);+ }+ .guide-main {+ display: contents;+ }+ .sheet {+ margin: 0 8px;+ border-radius: 22px;+ }+ .panel {+ margin: 8px 0 0;+ border-radius: 24px 24px 0 0;+ box-shadow:+ 0 -1px 0 var(--line),+ 0 -8px 24px rgba(18, 18, 18, 0.05);+ }+ .guide .topbar {+ gap: 8px;+ padding: 0 8px 0 10px;+ }+ .tb-title span {+ display: none;+ }+ .tb-title b {+ font-size: 17px;+ }+ .stp {+ height: 32px;+ padding: 0 10px 0 8px;+ font-size: 13px;+ }+ .stp-line {+ width: 6px;+ margin: 0;+ }+ .stp-count {+ display: none;+ }+ .tb-actions .icon-btn {+ width: 36px;+ height: 36px;+ }+ .tb-actions .icon-btn:not(:last-child):not(.live) {+ display: none;+ }+ .pane-scroll {+ padding: 22px 18px 18px;+ }+ .pane-foot {+ padding: 10px 12px calc(10px + env(safe-area-inset-bottom));+ }+ .corner {+ top: 12px;+ left: 16px;+ gap: 8px;+ }+ .num-wrap {+ height: 50px;+ }+ .corner .big-n {+ font-size: 54px;+ }+ .hw-box {+ padding: 6px 8px 4px;+ }+ .hw-box-item {+ min-width: 42px;+ }+ .hw-box-item svg {+ max-height: 28px;+ max-width: 42px;+ }+ .stage-ctl {+ left: 10px;+ bottom: 10px;+ gap: 6px;+ }+ .stage-ctl .icon-btn,+ .stage-ctl .pill-btn {+ height: 36px;+ }+ .stage-ctl .icon-btn {+ width: 36px;+ }+ .drag-hint {+ display: none;+ }+ .foot-row {+ justify-content: center;+ }+ .sheet-back {+ place-items: end stretch;+ padding: 0;+ }+ .side-sheet {+ width: 100%;+ height: 88dvh;+ border-radius: 26px 26px 0 0;+ }+ .overview {+ max-height: 92dvh;+ }+ .overview-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ padding: 8px 14px 18px;+ gap: 8px;+ }+ .nf-head {+ flex-direction: column;+ text-align: center;+ }+ .kind-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ .toast {+ bottom: 58px;+ }+}++@media (max-width: 420px) {+ .tgrid {+ gap: 8px;+ }+ .tcard-inner {+ min-height: 150px;+ }+ .btn.primary.big {+ font-size: 16px;+ padding: 0 18px 0 20px;+ }+ .stats dd {+ font-size: 18px;+ }+}++@media (hover: none), (max-width: 900px) {+ .kbd-hint {+ display: none;+ }+}++@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+}++@media (max-width: 640px) {+ .guide:not(.shell) .tb-title {+ display: none;+ }+ .guide:not(.shell) .topbar {+ grid-template-columns: auto 1fr auto;+ }+ .stepper {+ justify-self: center;+ }+}diff --git a/src/app/home.css b/src/app/home.cssnew file mode 100644index 0000000..adc874d--- /dev/null+++ b/src/app/home.css@@ -0,0 +1,1669 @@+/* ================= site frame ================= */++.site {+ max-width: 1280px;+ margin: 0 auto;+ padding: 0 28px;+}++.site-head {+ position: sticky;+ top: 0;+ z-index: 30;+ height: 60px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ margin: 0 -28px;+ padding: 0 28px;+ background: color-mix(in srgb, var(--page) 88%, transparent);+ backdrop-filter: saturate(1.4) blur(14px);+ -webkit-backdrop-filter: saturate(1.4) blur(14px);+}+.head-left {+ display: flex;+ align-items: center;+ gap: 28px;+ min-width: 0;+}+.logo {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ text-decoration: none;+ color: var(--ink);+ border-radius: 8px;+}+.wordmark {+ font-family: var(--display);+ font-weight: 800;+ font-size: 20px;+ letter-spacing: -0.045em;+ line-height: 1;+ padding-bottom: 2px;+}+.site-nav {+ display: flex;+ align-items: center;+ gap: 2px;+}+.nav-link {+ position: relative;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 34px;+ padding: 0 10px;+ border-radius: 8px;+ font-weight: 500;+ font-size: 14.5px;+ color: var(--ink-2);+ text-decoration: none;+ transition: color 0.2s;+}+.nav-link::after {+ content: "";+ position: absolute;+ left: 50%;+ bottom: 2px;+ width: 14px;+ height: 2px;+ margin-left: -7px;+ border-radius: 2px;+ background: var(--line-2);+ transform: scaleX(0);+ transition:+ transform 0.25s var(--ease),+ background 0.2s;+}+.nav-link:hover {+ color: var(--ink);+}+.nav-link:hover::after {+ transform: scaleX(1);+}+.nav-link.on {+ color: var(--ink);+}+.nav-link.on::after {+ transform: scaleX(1);+ background: var(--ink);+}+.nav-count {+ display: inline-grid;+ place-items: center;+ min-width: 18px;+ height: 18px;+ padding: 0 5px;+ border-radius: 5px;+ background: rgba(18, 18, 18, 0.07);+ color: var(--ink-2);+ font-size: 11.5px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+}+.gh {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ height: 32px;+ padding: 0 11px;+ border-radius: 8px;+ box-shadow: inset 0 0 0 1px var(--line-2);+ color: var(--ink);+ font-size: 13.5px;+ font-weight: 500;+ text-decoration: none;+ white-space: nowrap;+ transition:+ background 0.2s,+ box-shadow 0.2s;+}+.gh:hover {+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--ink-3);+}+.gh-stars {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: 2px;+ padding-left: 9px;+ border-left: 1px solid var(--line-2);+ color: var(--ink-2);+ font-variant-numeric: tabular-nums;+}++.lead {+ font-size: clamp(17px, 1.4vw, 19.5px);+ letter-spacing: -0.016em;+ color: var(--ink-2);+ margin: 16px 0 0;+ line-height: 1.5;+ max-width: 34em;+}++.sec-head {+ display: flex;+ align-items: flex-end;+ justify-content: space-between;+ gap: 20px;+ margin-bottom: 22px;+}+.sec-title,+.page-head h1,+.ws-head h1 {+ font-family: var(--display);+ font-size: clamp(30px, 3.1vw, 44px);+ letter-spacing: -0.035em;+ line-height: 1.04;+ margin: 0;+ font-weight: 800;+ text-wrap: balance;+}+.sec-link {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-weight: 500;+ font-size: 14.5px;+ color: var(--ink-2);+ text-decoration: none;+ padding: 6px 0;+ transition: color 0.2s;+}+.sec-link:hover {+ color: var(--ink);+}+.sec-link svg {+ transition: transform 0.25s var(--ease);+}+.sec-link:hover svg {+ transform: translateX(3px);+}++/* chips get a lighter touch on site pages */+.site .chip {+ height: 34px;+ padding: 0 13px;+ font-weight: 500;+ font-size: 14px;+ background: transparent;+ box-shadow: inset 0 0 0 1px var(--line-2);+}+.site .chip:hover {+ background: #fff;+ box-shadow: inset 0 0 0 1px var(--ink-3);+}++/* ================= hero ================= */++.hero {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.04fr);+ gap: 48px;+ align-items: center;+ min-height: min(740px, calc(100dvh - 60px));+ padding: 12px 0 56px;+}+.hero h1 {+ font-family: var(--display);+ font-size: clamp(46px, 4.9vw, 74px);+ line-height: 0.98;+ letter-spacing: -0.045em;+ font-weight: 800;+ margin: 0;+}+.hero .lead {+ margin: 20px 0 28px;+ max-width: 28em;+}++.search {+ position: relative;+ max-width: 560px;+ z-index: 10;+}+.search-box {+ display: flex;+ align-items: center;+ height: 64px;+ padding: 0 7px 0 22px;+ background: #fff;+ border-radius: 999px;+ box-shadow:+ 0 0 0 1px var(--line-2),+ 0 10px 30px -16px rgba(18, 18, 18, 0.22);+ transition: box-shadow 0.25s var(--ease);+}+.search-box:focus-within {+ box-shadow:+ 0 0 0 2px var(--ink),+ 0 16px 40px -16px rgba(18, 18, 18, 0.25);+}+.search-ico {+ flex: 0 0 auto;+ color: var(--ink-3);+}+.search-box input {+ flex: 1;+ min-width: 0;+ border: 0;+ outline: none;+ background: transparent;+ font-size: 18px;+ font-weight: 500;+ letter-spacing: -0.015em;+ padding: 0 12px;+ color: var(--ink);+}+.search-box input::placeholder {+ color: var(--ink-3);+ font-weight: 400;+}+.cam-btn {+ position: relative;+ width: 46px;+ height: 46px;+ border-radius: 50%;+ border: 0;+ background: transparent;+ cursor: pointer;+ display: grid;+ place-items: center;+ color: var(--ink-2);+ transition:+ background 0.2s,+ color 0.2s;+ flex: 0 0 auto;+}+.cam-btn:hover {+ background: var(--sunk);+ color: var(--ink);+}+.cam-btn.busy {+ color: var(--ink-3);+}+.cam-btn.busy::after {+ content: "";+ position: absolute;+ inset: 5px;+ border-radius: 50%;+ border: 2px solid transparent;+ border-top-color: var(--ink);+ animation: spin 0.8s linear infinite;+}+@keyframes spin {+ to {+ transform: rotate(360deg);+ }+}+.go-btn {+ width: 50px;+ height: 50px;+ border-radius: 50%;+ border: 0;+ background: var(--ink);+ color: #fff;+ cursor: pointer;+ display: grid;+ place-items: center;+ flex: 0 0 auto;+ margin-left: 4px;+ transition:+ background 0.2s,+ transform 0.15s var(--ease);+}+.go-btn svg {+ transition: transform 0.25s var(--ease);+}+.go-btn:hover {+ background: #000;+}+.go-btn:hover svg {+ transform: translateX(2px);+}+.go-btn:active {+ transform: scale(0.95);+}+.search-msg {+ margin: 10px 0 0 22px;+ font-size: 14px;+ color: var(--ink-2);+}+.suggest {+ position: absolute;+ left: 0;+ right: 0;+ top: calc(100% + 8px);+ background: #fff;+ border-radius: 22px;+ box-shadow: var(--shadow-2);+ list-style: none;+ margin: 0;+ padding: 6px;+ transform-origin: 50% 0;+ max-height: min(460px, 60dvh);+ overflow-y: auto;+}+.suggest-row {+ display: flex;+ align-items: center;+ gap: 14px;+ padding: 6px 14px 6px 6px;+ border-radius: 16px;+ cursor: pointer;+ transition: background 0.15s;+}+.suggest-row.active {+ background: var(--sunk);+}+.s-thumb {+ width: 72px;+ flex: 0 0 auto;+}+.s-text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ line-height: 1.3;+}+.s-text b {+ font-size: 16px;+ font-weight: 800;+}+.s-text span {+ font-size: 13.5px;+ color: var(--ink-2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.s-min {+ font-size: 13px;+ color: var(--ink-3);+ white-space: nowrap;+}+.s-ai {+ width: 72px;+ height: 54px;+ flex: 0 0 auto;+ display: grid;+ place-items: center;+ border-radius: 12px;+ background: var(--sunk);+}+.quick {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ align-items: center;+ margin-top: 16px;+}+.quick > span {+ font-size: 14px;+ color: var(--ink-3);+ margin-right: 4px;+}+.scan-link {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ margin-top: 26px;+ font-size: 14px;+ color: var(--ink-2);+ text-decoration: none;+}+.scan-link svg {+ color: var(--ink-3);+ transition: color 0.2s;+}+.scan-link u {+ text-decoration: underline;+ text-decoration-color: var(--line-2);+ text-decoration-thickness: 1.5px;+ text-underline-offset: 4px;+ transition: text-decoration-color 0.2s;+}+.scan-link:hover {+ color: var(--ink);+}+.scan-link:hover svg {+ color: var(--ink);+}+.scan-link:hover u {+ text-decoration-color: var(--ink);+}++.hero-visual {+ display: grid;+ gap: 14px;+}+.hero-sheet {+ position: relative;+ aspect-ratio: 1 / 0.94;+ max-height: 640px;+ width: 100%;+ background: #fff;+ border-radius: 32px;+ box-shadow: var(--shadow-2);+ overflow: hidden;+ isolation: isolate;+}+.hero-stage {+ position: absolute !important;+ inset: 0;+}+.hero-stage .stage-canvas {+ cursor: default;+}+.hero-cap {+ position: absolute;+ left: 26px;+ right: 20px;+ bottom: 20px;+ display: flex;+ align-items: flex-end;+ justify-content: space-between;+ gap: 12px;+}+.hero-cap-text b {+ display: block;+ font-family: var(--display);+ font-size: 24px;+ font-weight: 800;+ letter-spacing: -0.02em;+}+.hero-cap-text span {+ color: var(--ink-2);+ font-size: 14px;+}+.hero-go {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 40px;+ padding: 0 16px;+ border-radius: 999px;+ background: var(--ink);+ color: #fff;+ font-weight: 500;+ font-size: 14.5px;+ text-decoration: none;+ transition: background 0.2s;+}+.hero-go svg {+ transition: transform 0.25s var(--ease);+}+.hero-go:hover {+ background: #000;+}+.hero-go:hover svg {+ transform: translateX(2px);+}+.hero-tabs {+ display: flex;+ flex-wrap: wrap;+ gap: 2px;+ justify-content: center;+ justify-self: center;+}+.hero-tab {+ position: relative;+ height: 32px;+ padding: 0 12px;+ border: 0;+ border-radius: 8px;+ background: none;+ font-weight: 500;+ font-size: 13px;+ color: var(--ink-3);+ cursor: pointer;+ isolation: isolate;+ transition: color 0.25s;+}+.hero-tab:hover {+ color: var(--ink);+}+.hero-tab.on {+ color: var(--ink);+}+.hero-tab-bg {+ position: absolute;+ inset: 0;+ border-radius: 8px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ z-index: -1;+}++/* ================= how ================= */++.how {+ padding: 48px 0 40px;+ scroll-margin-top: 80px;+}+.how-steps {+ list-style: none;+ padding: 0;+ margin: 26px 0 0;+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ border-top: 1px solid var(--line-2);+}+.how-steps li {+ position: relative;+ padding: 22px 32px 6px;+}+.how-steps li:first-child {+ padding-left: 0;+}+.how-steps li:last-child {+ padding-right: 0;+}+.how-steps li + li {+ border-left: 1px solid var(--line-2);+}+.how-n {+ display: block;+ font-family: var(--display);+ font-weight: 800;+ font-size: 40px;+ letter-spacing: -0.05em;+ line-height: 1;+}+.how-steps h3 {+ font-family: var(--display);+ font-size: 21px;+ font-weight: 700;+ margin: 0 0 6px;+ letter-spacing: -0.02em;+}+.how-steps p {+ margin: 0;+ color: var(--ink-2);+ font-size: 15.5px;+ max-width: 24em;+}+.how-art {+ position: relative;+ height: 180px;+ display: flex;+ align-items: center;+ justify-content: center;+ margin: 0 0 16px;+}+.how-fig {+ position: absolute;+ left: 4%;+ bottom: 0;+}+.how-art.tools {+ gap: 2px;+ padding-top: 12px;+}+.how-hw {+ position: absolute;+ right: 4%;+ bottom: 8px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ padding: 8px 12px 6px;+ border-radius: 12px;+ background: #fff;+ box-shadow: inset 0 0 0 1.8px var(--ink);+}+.how-hw b {+ font-size: 14px;+}+.how-drop {+ animation: drop 2.8s var(--ease) infinite;+}+@keyframes drop {+ 0%,+ 12% {+ transform: translate(-18px, -34px);+ opacity: 0;+ }+ 50%,+ 82% {+ transform: translate(0, 0);+ opacity: 1;+ }+ 100% {+ transform: translate(0, 0);+ opacity: 0;+ }+}++/* ================= catalog ================= */++.popular {+ padding: 48px 0 40px;+ scroll-margin-top: 80px;+}+.catalog {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ gap: 18px;+}+.cat-bar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+}+.cat-tabs {+ display: flex;+ flex-wrap: wrap;+ gap: 2px;+}+.cat-tab {+ position: relative;+ height: 34px;+ padding: 0 13px;+ border: 0;+ border-radius: 8px;+ background: none;+ font-weight: 500;+ font-size: 14.5px;+ color: var(--ink-2);+ cursor: pointer;+ isolation: isolate;+ transition: color 0.2s;+}+.cat-tab:hover {+ color: var(--ink);+}+.cat-tab.on {+ color: var(--ink);+}+.cat-bg {+ position: absolute;+ inset: 0;+ border-radius: 8px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ z-index: -1;+}+.cat-search {+ display: flex;+ align-items: center;+ gap: 8px;+ height: 40px;+ padding: 0 14px;+ border-radius: 10px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ color: var(--ink-3);+ min-width: 260px;+ transition: box-shadow 0.2s;+}+.cat-search:focus-within {+ box-shadow: 0 0 0 2px var(--ink);+}+.cat-search input {+ border: 0;+ outline: none;+ background: none;+ font-size: 15px;+ flex: 1;+ min-width: 0;+ color: var(--ink);+}+.cat-search input::placeholder {+ color: var(--ink-3);+}+.pgrid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 14px;+}+.pcard {+ display: flex;+ flex-direction: column;+ background: #fff;+ border-radius: 24px;+ overflow: hidden;+ text-decoration: none;+ color: var(--ink);+ box-shadow: var(--shadow-1);+ transition: box-shadow 0.3s var(--ease);+ height: 100%;+}+.pcard:hover {+ box-shadow:+ 0 0 0 1px var(--line-2),+ 0 18px 40px -18px rgba(18, 18, 18, 0.22);+}+.pcard-art {+ display: block;+ padding: 12px 12px 0;+}+.pcard-thumb {+ border-radius: 16px;+ transition: transform 0.6s var(--ease);+}+.pcard:hover .pcard-thumb {+ transform: scale(1.03);+}+.pcard-text {+ display: flex;+ flex-direction: column;+ gap: 1px;+ padding: 4px 20px 20px;+}+.pcard-top {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+}+.pcard-top b {+ font-family: var(--display);+ font-size: 22px;+ font-weight: 800;+ letter-spacing: -0.02em;+}+.pcard-go {+ width: 32px;+ height: 32px;+ border-radius: 50%;+ display: grid;+ place-items: center;+ color: var(--ink-3);+ transition:+ transform 0.3s var(--ease),+ color 0.2s,+ background 0.2s;+}+.pcard:hover .pcard-go {+ color: var(--ink);+ background: var(--sunk);+ transform: translateX(2px);+}+.pcard-variant {+ color: var(--ink-2);+ font-size: 14.5px;+}+.pcard-meta {+ display: flex;+ align-items: center;+ gap: 14px;+ margin-top: 12px;+ font-size: 13px;+ color: var(--ink-3);+}+.pcard-meta > span {+ display: inline-flex;+ align-items: center;+ gap: 5px;+}+.empty {+ color: var(--ink-2);+ text-align: center;+ padding: 40px 0;+}++/* ================= floor ================= */++.floor {+ display: grid;+ grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr);+ gap: 40px;+ align-items: center;+ padding: 56px 0 64px;+}+.floor-sub {+ margin: 12px 0 0;+ color: var(--ink-2);+ font-size: 16.5px;+ letter-spacing: -0.016em;+ max-width: 26em;+}+.floor-list {+ list-style: none;+ padding: 0;+ margin: 26px 0 0;+}+.floor-list li {+ display: flex;+ gap: 16px;+ padding: 16px 0;+ border-top: 1px solid var(--line-2);+ cursor: default;+}+.floor-list li:last-child {+ border-bottom: 1px solid var(--line-2);+}+.fl-n {+ flex: 0 0 auto;+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ margin-top: -1px;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1.6px var(--ink);+ background: #fff;+ font-size: 13.5px;+ font-weight: 600;+ transition: background 0.25s;+}+.floor-list li.on .fl-n {+ background: var(--accent);+}+.fl-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.fl-text b {+ font-size: 16.5px;+ font-weight: 600;+}+.fl-text span {+ color: var(--ink-2);+ font-size: 15px;+}+.floor-art svg {+ display: block;+ width: 100%;+ height: auto;+ overflow: visible;+}+.floor-art .co-line {+ stroke: var(--ink);+ stroke-width: 1.3;+ fill: none;+}+.floor-art .co-dot {+ fill: var(--ink);+}+.floor-art .co-badge {+ fill: #fff;+ stroke: var(--ink);+ stroke-width: 1.8;+ transition: fill 0.25s;+}+.floor-art .co-n {+ font-family: var(--font);+ font-size: 14px;+ font-weight: 600;+ fill: var(--ink);+ pointer-events: none;+}+.floor-art .co {+ transition: opacity 0.25s;+}+.floor-art[data-on] .co {+ opacity: 0.3;+}+.floor-art[data-on="1"] .co-1,+.floor-art[data-on="2"] .co-2,+.floor-art[data-on="3"] .co-3,+.floor-art[data-on="4"] .co-4 {+ opacity: 1;+}+.floor-art[data-on="1"] .co-1 .co-badge,+.floor-art[data-on="2"] .co-2 .co-badge,+.floor-art[data-on="3"] .co-3 .co-badge,+.floor-art[data-on="4"] .co-4 .co-badge {+ fill: var(--accent);+}++/* ================= footer ================= */++.site-foot {+ margin-top: 36px;+ padding-bottom: 34px;+}+.foot-ruler {+ position: relative;+ height: 30px;+ background:+ repeating-linear-gradient(90deg, var(--ink-3) 0 1px, transparent 1px 10%) top left / 100% 12px no-repeat,+ repeating-linear-gradient(90deg, var(--line-2) 0 1px, transparent 1px 5%) top left / 100% 8px no-repeat,+ repeating-linear-gradient(90deg, var(--line-2) 0 1px, transparent 1px 1%) top left / 100% 5px no-repeat;+ border-top: 1px solid var(--line-2);+}+.foot-ruler::after {+ content: "";+ position: absolute;+ right: 0;+ top: 0;+ width: 1px;+ height: 12px;+ background: var(--ink-3);+}+.foot-ruler span {+ position: absolute;+ top: 14px;+ font-size: 10.5px;+ line-height: 1;+ color: var(--ink-3);+ transform: translateX(4px);+ font-variant-numeric: tabular-nums;+}+.foot-ruler span:last-child {+ transform: translateX(calc(-100% - 4px));+}+.foot-main {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ justify-content: space-between;+ gap: 20px 40px;+ padding: 22px 0 26px;+}+.foot-brand p {+ margin: 10px 0 0;+ font-size: 14.5px;+ color: var(--ink-2);+ max-width: 28em;+}+.foot-nav {+ display: flex;+ flex-wrap: wrap;+ gap: 6px 24px;+ padding-top: 2px;+}+.foot-nav a {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-weight: 500;+ font-size: 14.5px;+ color: var(--ink-2);+ text-decoration: none;+ transition: color 0.2s;+}+.foot-nav a:hover {+ color: var(--ink);+}+.foot-base {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ justify-content: space-between;+ gap: 10px 30px;+ padding-top: 16px;+ border-top: 1px solid var(--line);+}+.foot-base p {+ margin: 0;+ max-width: 680px;+ font-size: 12.5px;+ color: var(--ink-3);+ line-height: 1.6;+}+.foot-powered {+ font-size: 12.5px;+ color: var(--ink-3);+ text-decoration: none;+ white-space: nowrap;+}+.foot-powered span {+ color: var(--ink-2);+ font-weight: 500;+ transition: color 0.2s;+}+.foot-powered:hover span {+ color: var(--ink);+ text-decoration: underline;+ text-underline-offset: 3px;+}++/* ================= browse ================= */++.browse {+ padding: 28px 0 40px;+}+.page-head {+ margin-bottom: 26px;+}+.page-head .lead {+ margin-top: 10px;+}++/* ================= workshop ================= */++.ws-loading {+ min-height: 60vh;+}+.workshop {+ padding: 28px 0 24px;+}+.ws-head {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ justify-content: space-between;+ gap: 24px;+ margin-bottom: 22px;+}+.ws-head .lead {+ margin-top: 10px;+}+.ws-stats {+ display: flex;+ margin: 0;+}+.ws-stats > div {+ padding: 2px 22px;+}+.ws-stats > div:last-child {+ padding-right: 0;+}+.ws-stats > div + div {+ border-left: 1px solid var(--line-2);+}+.ws-stats dt {+ font-size: 13px;+ color: var(--ink-3);+}+.ws-stats dd {+ margin: 2px 0 0;+ font-family: var(--display);+ font-size: 26px;+ font-weight: 800;+ letter-spacing: -0.025em;+ line-height: 1.1;+ white-space: nowrap;+}++.showroom {+ border-radius: 28px;+ background: #fff;+ box-shadow: var(--shadow-1);+ overflow: hidden;+}+.sr-stage {+ position: relative;+ width: 100%;+}+.sr-img {+ position: absolute;+ inset: 0;+}+.sr-img img {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ object-fit: contain;+ user-select: none;+}+.sr-person {+ position: absolute;+ display: flex;+ flex-direction: column;+ align-items: center;+ transform: translate(-50%, -100%);+ pointer-events: none;+}+.scale-person {+ height: 100%;+ width: auto;+ fill: #e6e3dc;+}+.sr-person span {+ position: absolute;+ top: 100%;+ margin-top: 8px;+ font-size: 12px;+ color: var(--ink-2);+ white-space: nowrap;+}+.sr-tag {+ position: absolute;+ display: flex;+ flex-direction: column;+ align-items: center;+ transform: translate(-50%, 8px);+ padding: 4px 9px;+ border-radius: 8px;+ text-decoration: none;+ color: var(--ink);+ white-space: nowrap;+ line-height: 1.25;+ transition: background 0.2s;+}+.sr-tag b {+ font-size: 13.5px;+ font-weight: 700;+}+.sr-tag span {+ font-size: 12px;+ color: var(--ink-3);+}+.sr-tag:hover {+ background: var(--sunk);+}++.ws-section {+ margin-top: 40px;+}+.ws-sec-head {+ display: flex;+ align-items: baseline;+ gap: 10px;+ margin: 0 0 14px;+}+.ws-sec-head h2 {+ font-family: var(--display);+ font-size: 24px;+ letter-spacing: -0.025em;+ margin: 0;+}+.ws-sec-head span {+ color: var(--ink-3);+ font-size: 14px;+ font-variant-numeric: tabular-nums;+}++.x-btn {+ position: absolute;+ top: 10px;+ right: 10px;+ width: 28px;+ height: 28px;+ border-radius: 8px;+ border: 0;+ background: #fff;+ color: var(--ink-3);+ display: grid;+ place-items: center;+ cursor: pointer;+ opacity: 0;+ transition:+ opacity 0.2s,+ background 0.2s,+ color 0.2s;+}+.going:hover .x-btn,+.built:hover .x-btn,+.x-btn:focus-visible {+ opacity: 1;+}+.x-btn:hover {+ background: var(--sunk);+ color: var(--ink);+}++.ws-going {+ display: grid;+ gap: 8px;+}+.going {+ position: relative;+ background: #fff;+ border-radius: 18px;+ box-shadow: var(--shadow-1);+ overflow: hidden;+}+.going-link {+ display: grid;+ grid-template-columns: 96px minmax(0, 1.2fr) minmax(0, 1fr) auto;+ align-items: center;+ gap: 18px;+ padding: 8px 20px 8px 8px;+ text-decoration: none;+ color: var(--ink);+}+.going-thumb {+ width: 96px;+ border-radius: 12px;+}+.going-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}+.going-text b {+ font-family: var(--display);+ font-size: 19px;+ font-weight: 800;+ letter-spacing: -0.015em;+}+.going-text span {+ font-size: 14px;+ color: var(--ink-2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.going-progress {+ display: grid;+ gap: 7px;+}+.going-status {+ font-size: 13.5px;+ color: var(--ink-2);+}+.going-bar {+ display: block;+ height: 4px;+ border-radius: 4px;+ background: var(--line);+ overflow: hidden;+}+.going-bar i {+ display: block;+ height: 100%;+ border-radius: 4px;+ background: var(--ink);+}+.going-go {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 36px;+ padding: 0 14px;+ border-radius: 999px;+ background: var(--ink);+ color: #fff;+ font-size: 14px;+ font-weight: 500;+ transition: background 0.2s;+}+.going-go svg {+ transition: transform 0.25s var(--ease);+}+.going-link:hover .going-go {+ background: #000;+}+.going-link:hover .going-go svg {+ transform: translateX(2px);+}+.going .x-btn {+ top: 50%;+ right: auto;+ left: 10px;+ margin-top: -14px;+}++.ws-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));+ gap: 12px;+}+.built {+ position: relative;+ background: #fff;+ border-radius: 20px;+ box-shadow: var(--shadow-1);+ transition: box-shadow 0.3s var(--ease);+}+.built:hover {+ box-shadow:+ 0 0 0 1px var(--line-2),+ 0 16px 36px -18px rgba(18, 18, 18, 0.22);+}+.built-link {+ display: flex;+ flex-direction: column;+ text-decoration: none;+ color: var(--ink);+}+.built-thumb {+ margin: 8px 8px 0;+ border-radius: 14px;+}+.built-text {+ display: flex;+ flex-direction: column;+ padding: 4px 16px 16px;+ min-width: 0;+}+.built-text b {+ font-family: var(--display);+ font-size: 19px;+ font-weight: 800;+ letter-spacing: -0.015em;+}+.built-text > span {+ font-size: 13.5px;+ color: var(--ink-2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.built-text > .built-meta {+ display: flex;+ gap: 12px;+ margin-top: 8px;+ color: var(--ink-3);+ font-size: 12.5px;+}+.built-meta span {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}++.badges {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));+ gap: 0 24px;+}+.badge {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px 0;+ border-top: 1px solid var(--line-2);+}+.badge-ico {+ flex: 0 0 auto;+ display: grid;+ place-items: center;+ width: 40px;+ height: 40px;+ border-radius: 50%;+ color: var(--ink-3);+ box-shadow: inset 0 0 0 1.5px var(--line-2);+ font-weight: 800;+}+.badge.on .badge-ico {+ color: var(--ink);+ background: var(--accent);+ box-shadow: inset 0 0 0 1.8px var(--ink);+}+.badge-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}+.badge-text b {+ font-size: 15px;+ font-weight: 600;+ color: var(--ink-3);+}+.badge.on .badge-text b {+ color: var(--ink);+}+.badge-text span {+ font-size: 13px;+ color: var(--ink-3);+}+.bi {+ font-family: var(--display);+ font-size: 16px;+ font-weight: 800;+}++.ws-floor {+ position: relative;+ display: grid;+ justify-items: center;+ padding: 28px 20px 26px;+ border-radius: 28px;+ background: #fff;+ box-shadow: var(--shadow-1);+}+.ws-floor-row {+ display: flex;+ align-items: flex-end;+ justify-content: center;+ gap: 18px;+ width: 100%;+}+.ws-ghosts {+ width: min(70%, 440px);+ height: auto;+}+.ws-floor-fig .figure {+ display: block;+ height: clamp(96px, 18vw, 150px);+ width: auto;+}+.ws-floor p {+ margin: 10px 0 0;+ color: var(--ink-3);+ font-size: 14px;+}+.ws-empty {+ display: grid;+ gap: 30px;+}+.ws-empty-copy {+ display: grid;+ justify-items: center;+ text-align: center;+}+.ws-empty-copy h2 {+ font-family: var(--display);+ font-size: 28px;+ letter-spacing: -0.025em;+ margin: 0;+}+.ws-empty-copy > p {+ margin: 8px 0 22px;+ color: var(--ink-2);+ max-width: 30em;+}+.ws-starters {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 220px));+ gap: 10px;+}+.starter {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ padding: 14px 40px 14px 16px;+ border-radius: 16px;+ background: #fff;+ box-shadow: var(--shadow-1);+ text-decoration: none;+ color: var(--ink);+ text-align: left;+ transition: box-shadow 0.25s var(--ease);+}+.starter b {+ font-family: var(--display);+ font-size: 18px;+ font-weight: 800;+ letter-spacing: -0.015em;+}+.starter span {+ font-size: 13.5px;+ color: var(--ink-2);+}+.starter svg {+ position: absolute;+ right: 14px;+ top: 50%;+ margin-top: -8px;+ color: var(--ink-3);+ transition:+ transform 0.25s var(--ease),+ color 0.2s;+}+.starter:hover {+ box-shadow:+ 0 0 0 1px var(--line-2),+ 0 14px 30px -16px rgba(18, 18, 18, 0.22);+}+.starter:hover svg {+ color: var(--ink);+ transform: translateX(2px);+}+.ws-browse {+ margin-top: 16px;+ font-size: 14.5px;+ color: var(--ink-2);+ text-decoration: underline;+ text-decoration-color: var(--line-2);+ text-underline-offset: 4px;+}+.ws-browse:hover {+ color: var(--ink);+ text-decoration-color: var(--ink);+}++/* ================= responsive ================= */++@media (max-width: 1080px) {+ .hero {+ grid-template-columns: 1fr;+ gap: 34px;+ min-height: 0;+ padding: 18px 0 36px;+ }+ .hero-sheet {+ aspect-ratio: 4 / 3.3;+ }+ .pgrid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ .floor {+ grid-template-columns: 1fr;+ }+ .floor-art {+ order: -1;+ max-width: 620px;+ }+}++@media (max-width: 820px) {+ .how-steps {+ grid-template-columns: 1fr;+ }+ .how-steps li,+ .how-steps li:first-child,+ .how-steps li:last-child {+ padding: 20px 0 22px;+ }+ .how-steps li + li {+ border-left: 0;+ border-top: 1px solid var(--line-2);+ }+ .going-link {+ grid-template-columns: 72px minmax(0, 1fr) auto;+ }+ .going-thumb {+ width: 72px;+ }+ .going-progress {+ grid-column: 2 / 4;+ grid-row: 2;+ padding-bottom: 6px;+ }+ .ws-starters {+ grid-template-columns: 1fr;+ width: 100%;+ max-width: 360px;+ }+}++@media (max-width: 640px) {+ .site {+ padding: 0 16px;+ }+ .site-head {+ height: 56px;+ margin: 0 -16px;+ padding: 0 16px;+ }+ .head-left {+ gap: 14px;+ }+ .wordmark {+ display: none;+ }+ .gh-label {+ display: none;+ }+ .hero h1 {+ font-size: 48px;+ }+ .hero .lead {+ margin: 14px 0 22px;+ }+ .search-box {+ height: 58px;+ padding-left: 16px;+ padding-right: 5px;+ }+ .search-box input {+ font-size: 16.5px;+ padding: 0 8px;+ }+ .cam-btn {+ width: 42px;+ height: 42px;+ }+ .go-btn {+ width: 46px;+ height: 46px;+ }+ .s-min {+ display: none;+ }+ .hero-sheet {+ aspect-ratio: 1 / 1.06;+ border-radius: 26px;+ }+ .hero-cap {+ left: 18px;+ right: 14px;+ bottom: 14px;+ }+ .hero-cap-text b {+ font-size: 20px;+ }+ .sec-head {+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+ }+ .pgrid {+ grid-template-columns: 1fr;+ }+ .cat-tabs {+ flex: 1 1 100%;+ min-width: 0;+ flex-wrap: nowrap;+ overflow-x: auto;+ max-width: 100%;+ scrollbar-width: none;+ }+ .cat-search {+ width: 100%;+ min-width: 0;+ }+ .foot-ruler span:nth-child(even) {+ display: none;+ }+ .ws-head {+ flex-direction: column;+ align-items: stretch;+ }+ .ws-stats > div {+ padding: 2px 14px;+ }+ .ws-stats > div:first-child {+ padding-left: 0;+ }+ .ws-stats dd {+ font-size: 21px;+ }+ .going-go {+ width: 36px;+ padding: 0;+ justify-content: center;+ font-size: 0;+ gap: 0;+ }+ .x-btn {+ opacity: 1;+ }+}diff --git a/src/app/icon.svg b/src/app/icon.svgnew file mode 100644index 0000000..930fe7a--- /dev/null+++ b/src/app/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="15.5" fill="#121212"/><path d="M16 6.2 L24.5 11.1 L24.5 20.9 L16 25.8 L7.5 20.9 L7.5 11.1 Z" fill="#ffd21f" stroke="#ffd21f" stroke-width="2.2" stroke-linejoin="round"/><path d="M16 11.2 L20.2 13.6 L20.2 18.4 L16 20.8 L11.8 18.4 L11.8 13.6 Z" fill="#121212" stroke="#121212" stroke-width="1.4" stroke-linejoin="round"/></svg>diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex f58d37c..d5f0301 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -1,25 +1,38 @@-import type { Metadata } from "next";-import { Geist, Geist_Mono } from "next/font/google";+import type { Metadata, Viewport } from "next";+import { Noto_Sans, Noto_Sans_Display } from "next/font/google";import "./globals.css";+import "./guide.css";+import "./home.css";+import "./scan.css";-const geistSans = Geist({- variable: "--font-geist-sans",- subsets: ["latin"],+const noto = Noto_Sans({+ subsets: ["latin", "latin-ext"],+ weight: ["400", "500", "600", "700", "800"],+ variable: "--font-noto",+ display: "swap",});-const geistMono = Geist_Mono({- variable: "--font-geist-mono",- subsets: ["latin"],+const display = Noto_Sans_Display({+ subsets: ["latin", "latin-ext"],+ weight: ["600", "700", "800"],+ variable: "--font-display",+ display: "swap",});export const metadata: Metadata = {- title: "Create Next App",- description: "Generated by create next app",+ title: "Bygga: IKEA assembly, step by step",+ description: "Type the product name from the box. Bygga shows every assembly step in 3D, with the exact parts, screws and tools.",};-export default function RootLayout({ children }: LayoutProps<"/">) {+export const viewport: Viewport = {+ themeColor: "#f7f6f2",+ width: "device-width",+ initialScale: 1,+};++export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {return (- <html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>+ <html lang="en" className={`${noto.variable} ${display.variable}`}><body>{children}</body></html>);diff --git a/src/app/page.module.css b/src/app/page.module.cssdeleted file mode 100644index 90fe305..0000000--- a/src/app/page.module.css+++ /dev/null@@ -1,150 +0,0 @@-.page {- --background: #fafafa;- --foreground: #fff;-- --text-primary: #000;- --text-secondary: #666;-- --button-primary-hover: #383838;- --button-secondary-hover: #f2f2f2;- --button-secondary-border: #ebebeb;-- display: flex;- flex: 1;- flex-direction: column;- align-items: center;- justify-content: center;- font-family: var(--font-geist-sans);- background-color: var(--background);-}--.main {- display: flex;- flex: 1;- width: 100%;- max-width: 800px;- flex-direction: column;- align-items: flex-start;- justify-content: space-between;- background-color: var(--foreground);- padding: 120px 60px;-}--.intro {- display: flex;- flex-direction: column;- align-items: flex-start;- text-align: left;- gap: 24px;-}--.intro h1 {- max-width: 320px;- font-size: 40px;- font-weight: 600;- line-height: 48px;- letter-spacing: -2.4px;- text-wrap: balance;- color: var(--text-primary);-}--.intro p {- max-width: 440px;- font-size: 18px;- line-height: 32px;- text-wrap: balance;- color: var(--text-secondary);-}--.intro a {- font-weight: 500;- color: var(--text-primary);-}--.ctas {- display: flex;- flex-direction: row;- width: 100%;- max-width: 440px;- gap: 16px;- font-size: 14px;-}--.ctas a {- display: flex;- justify-content: center;- align-items: center;- height: 40px;- padding: 0 16px;- border-radius: 128px;- border: 1px solid transparent;- transition: 0.2s;- cursor: pointer;- width: fit-content;- font-weight: 500;-}--a.primary {- background: var(--text-primary);- color: var(--background);- gap: 8px;-}--a.secondary {- border-color: var(--button-secondary-border);-}--/* Enable hover only on non-touch devices */-@media (hover: hover) and (pointer: fine) {- a.primary:hover {- background: var(--button-primary-hover);- border-color: transparent;- }-- a.secondary:hover {- background: var(--button-secondary-hover);- border-color: transparent;- }-}--@media (max-width: 600px) {- .main {- padding: 48px 24px;- }-- .intro {- gap: 16px;- }-- .intro h1 {- font-size: 32px;- line-height: 40px;- letter-spacing: -1.92px;- }-}--@media (prefers-color-scheme: dark) {- .logo {- filter: invert();- }-- .page {- --background: #000;- --foreground: #000;-- --text-primary: #ededed;- --text-secondary: #999;-- --button-primary-hover: #ccc;- --button-secondary-hover: #1a1a1a;- --button-secondary-border: #1a1a1a;- }-}--.code {- font-family: var(--font-geist-mono);- font-size: 0.9em;- background: color-mix(in srgb, currentColor 8%, transparent);- padding: 0.1em 0.4em;- border-radius: 6px;-}diff --git a/src/app/page.tsx b/src/app/page.tsxindex 3f611f9..6e7613d 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,69 +1,133 @@-import Image from "next/image";-import styles from "./page.module.css";+import Link from "next/link";+import SiteHeader from "@/components/SiteHeader";+import SiteFooter from "@/components/SiteFooter";+import HeroStage from "@/components/home/HeroStage";+import { HeroSearch } from "@/components/home/HomeClient";+import { Catalog } from "@/components/home/Sections";+import FloorFeatures from "@/components/home/FloorFeatures";+import { Figure } from "@/components/art/Figure";+import { ToolArt } from "@/components/art/Tools";+import { HwArt } from "@/components/art/Hardware";+import { IArrowRight, IScan } from "@/components/art/Icons";+import { PRODUCT_COUNT } from "@/lib/search";++const QUICK = [+ { slug: "kallax-2x2", label: "KALLAX" },+ { slug: "bissa-shoe-cabinet-2-compartments", label: "BISSA" },+ { slug: "malm-3-drawers", label: "MALM" },+ { slug: "poang-armchair", label: "POÄNG" },+ { slug: "billy-80x202", label: "BILLY" },+];export default function Home() {return (- <div className={styles.page}>- <main className={styles.main}>- <Image- className={styles.logo}- src="/next.svg"- alt="Next.js logo"- width={100}- height={20}- priority- />- <div className={styles.intro}>+ <div className="site">+ <SiteHeader />++ <section className="hero">+ <div className="hero-copy"><h1>- To get started, edit the{" "}- <code className={styles.code}>page.tsx</code> file.+ IKEA assembly,+ <br />+ step by step.</h1>- <p>- Looking for a starting point or more instructions? Head over to{" "}- <a- href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- Templates- </a>{" "}- or the{" "}- <a- href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- Learning- </a>{" "}- center.- </p>+ <p className="lead">Type the product name from the box. Each step plays in 3D, with the exact parts, screws and tools.</p>+ <HeroSearch />+ <div className="quick">+ <span>Try</span>+ {QUICK.map((q) => (+ <Link key={q.slug} href={`/build/${q.slug}`} className="chip">+ {q.label}+ </Link>+ ))}+ </div>+ <Link href="/scan" className="scan-link">+ <IScan size={17} />+ <span>+ Not from IKEA? <u>Scan its paper manual</u>+ </span>+ </Link></div>- <div className={styles.ctas}>- <a- className={styles.primary}- href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- <Image- className={styles.logo}- src="/vercel.svg"- alt="Vercel logomark"- width={16}- height={14}- />- Deploy Now- </a>- <a- className={styles.secondary}- href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"- target="_blank"- rel="noopener noreferrer"- >- Documentation- </a>+ <HeroStage />+ </section>++ <section className="how" id="how">+ <h2 className="sec-title">How it works</h2>+ <ol className="how-steps">+ <li>+ <span className="how-n">1</span>+ <div className="how-art">+ <svg viewBox="0 0 220 150" width="220" height="150" aria-hidden="true">+ <path d="M30 60 L110 84 L190 60 L190 128 L110 150 L30 128 Z" fill="#fff" stroke="var(--ink)" strokeWidth="2.4" strokeLinejoin="round" />+ <path d="M110 84 V150" stroke="var(--ink)" strokeWidth="2.2" />+ <path d="M30 60 L110 38 L190 60" fill="#f2f0eb" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <g transform="translate(122 98) skewY(-15)">+ <rect x="0" y="0" width="56" height="26" rx="3" fill="var(--accent)" stroke="var(--ink)" strokeWidth="2" />+ <text x="28" y="18" textAnchor="middle" fontSize="12" fontWeight="800" fill="var(--ink)" fontFamily="var(--font)">+ KALLAX+ </text>+ </g>+ </svg>+ <span className="how-fig">+ <Figure pose="point" size={84} />+ </span>+ </div>+ <h3>Type the name</h3>+ <p>It's the big word on the box label, like KALLAX. You can also snap a photo of it.</p>+ </li>+ <li>+ <span className="how-n">2</span>+ <div className="how-art tools">+ <span style={{ transform: "rotate(-10deg)" }}>+ <ToolArt id="screwdriver" size={82} />+ </span>+ <span style={{ transform: "translateY(-10px)" }}>+ <ToolArt id="hammer" size={88} />+ </span>+ <span style={{ transform: "rotate(8deg)" }}>+ <ToolArt id="allen" size={72} />+ </span>+ <span className="how-hw">+ <HwArt kind="dowel" len={30} dia={8} fit={44} />+ <b>8×</b>+ </span>+ </div>+ <h3>Check tools and parts</h3>+ <p>One tap if everything's there. Missing a piece? We'll tell you what to do.</p>+ </li>+ <li>+ <span className="how-n">3</span>+ <div className="how-art step">+ <svg viewBox="0 0 200 140" width="200" height="140" aria-hidden="true">+ <path d="M30 96 L120 120 L176 96 L86 72 Z" fill="#fff" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path d="M30 96 V104 L120 128 V120 M120 128 L176 104 V96" fill="none" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <g className="how-drop">+ <path d="M92 18 L104 22 L104 82 L92 78 Z" fill="var(--accent-soft)" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path d="M104 22 L150 8 L150 68 L104 82" fill="#fff" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path d="M92 18 L138 4 L150 8" fill="none" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ </g>+ <path d="M70 26 v26 h-7 l11 13 l11 -13 h-7 v-26 z" fill="var(--ink)" stroke="#fff" strokeWidth="2" strokeLinejoin="round" />+ </svg>+ </div>+ <h3>Follow each step</h3>+ <p>Every step plays in 3D, with each screw shown up close. Drag to see any side.</p>+ </li>+ </ol>+ </section>++ <section className="popular" id="popular">+ <div className="sec-head">+ <h2 className="sec-title">Popular builds</h2>+ <Link href="/browse" className="sec-link">+ All {PRODUCT_COUNT} guides <IArrowRight size={15} />+ </Link></div>- </main>+ <Catalog limit={9} />+ </section>++ <FloorFeatures />++ <SiteFooter /></div>);}diff --git a/src/app/scan.css b/src/app/scan.cssnew file mode 100644index 0000000..ce63470--- /dev/null+++ b/src/app/scan.css@@ -0,0 +1,613 @@+/* ================= scan a manual ================= */++.scan {+ max-width: 720px;+ margin: 0 auto;+ padding: 36px 0 20px;+}+.scan-head h1 {+ font-family: var(--display);+ font-size: clamp(32px, 3.4vw, 46px);+ letter-spacing: -0.035em;+ line-height: 1.04;+ margin: 0;+ font-weight: 800;+}+.scan-head .lead {+ margin-top: 10px;+}++.scan-form {+ margin-top: 30px;+ border-top: 1px solid var(--line-2);+}+.sf-row {+ display: grid;+ grid-template-columns: 44px minmax(0, 1fr);+ gap: 8px;+ padding: 24px 0;+ border-bottom: 1px solid var(--line-2);+}+.sf-n {+ font-family: var(--display);+ font-size: 30px;+ font-weight: 800;+ letter-spacing: -0.05em;+ line-height: 1;+}+.sf-body h2 {+ margin: 4px 0 12px;+ font-size: 17px;+ font-weight: 600;+ letter-spacing: -0.015em;+}+.sf-body h2 span {+ margin-left: 6px;+ font-weight: 400;+ font-size: 14px;+ color: var(--ink-3);+}+.sf-help {+ margin: -6px 0 12px;+ font-size: 14px;+ color: var(--ink-2);+}+.key-edit .sf-help {+ margin: 10px 0 0;+}+.sf-help.bad {+ color: var(--miss);+}+.sf-help a {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ color: var(--ink);+ text-decoration: underline;+ text-decoration-color: var(--line-2);+ text-underline-offset: 3px;+}+.sf-help a:hover {+ text-decoration-color: var(--ink);+}+.sf-tip {+ display: flex;+ align-items: center;+ gap: 7px;+ margin: 12px 0 0;+ font-size: 13.5px;+ color: var(--ink-3);+}+.sf-input {+ width: 100%;+ height: 48px;+ padding: 0 16px;+ border: 0;+ border-radius: 12px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ font-size: 16px;+ outline: none;+ transition: box-shadow 0.2s;+}+.sf-input:focus {+ box-shadow: 0 0 0 2px var(--ink);+}+.sf-input::placeholder {+ color: var(--ink-3);+}++/* key */+.key-field {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 52px;+ padding: 0 6px 0 16px;+ border-radius: 14px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ color: var(--ink-3);+ transition: box-shadow 0.2s;+}+.key-field:focus-within {+ box-shadow: 0 0 0 2px var(--ink);+}+.key-field.bad {+ box-shadow: 0 0 0 2px var(--miss);+}+.key-field input {+ flex: 1;+ min-width: 0;+ border: 0;+ outline: none;+ background: none;+ font-size: 16px;+ color: var(--ink);+}+.key-field input::placeholder {+ color: var(--ink-3);+}+.btn.sm {+ height: 40px;+ padding: 0 16px;+ font-size: 14.5px;+}+.btn.ghost:hover:not(:disabled) {+ background: #e8e5de;+}+.link-btn {+ border: 0;+ background: none;+ padding: 6px 8px;+ border-radius: 8px;+ font-size: 14px;+ font-weight: 500;+ color: var(--ink-2);+ cursor: pointer;+ transition:+ background 0.2s,+ color 0.2s;+}+.link-btn:hover {+ background: var(--sunk);+ color: var(--ink);+}+.key-saved {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 10px 8px 10px 10px;+ border-radius: 14px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+}+.key-ico {+ display: grid;+ place-items: center;+ width: 36px;+ height: 36px;+ border-radius: 10px;+ background: var(--accent-soft);+ color: var(--ink);+}+.key-text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ line-height: 1.3;+}+.key-text b {+ font-size: 15px;+ font-weight: 600;+}+.key-text span {+ font-size: 13.5px;+ color: var(--ink-3);+}++/* drop zone */+.drop {+ border-radius: 18px;+ border: 1.5px dashed var(--line-2);+ transition:+ border-color 0.2s,+ background 0.2s;+}+.drop.over {+ border-color: var(--ink);+ background: rgba(255, 255, 255, 0.6);+}+.drop.has {+ border-style: solid;+ border-color: transparent;+ padding: 0;+}+.drop-empty {+ display: grid;+ justify-items: center;+ gap: 8px;+ padding: 26px 20px 24px;+ text-align: center;+}+.drop-empty p {+ margin: 4px 0 0;+ color: var(--ink-2);+ font-size: 15px;+}+.drop-empty p button {+ border: 0;+ background: none;+ padding: 0;+ font-weight: 600;+ color: var(--ink);+ text-decoration: underline;+ text-decoration-color: var(--line-2);+ text-underline-offset: 3px;+ cursor: pointer;+}+.drop-empty p button:hover {+ text-decoration-color: var(--ink);+}+.cam-only {+ display: none !important;+}+@media (hover: none) and (pointer: coarse) {+ .cam-only {+ display: inline-flex !important;+ }+}+.pages {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ gap: 10px;+}+.pages li {+ position: relative;+ aspect-ratio: 3 / 4;+ border-radius: 10px;+ overflow: hidden;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+}+.pages img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.pg-n {+ position: absolute;+ left: 6px;+ bottom: 6px;+ min-width: 22px;+ height: 22px;+ padding: 0 6px;+ display: grid;+ place-items: center;+ border-radius: 6px;+ background: #fff;+ box-shadow: 0 0 0 1px var(--line-2);+ font-size: 12px;+ font-weight: 600;+}+.pg-x {+ position: absolute;+ top: 6px;+ right: 6px;+ width: 26px;+ height: 26px;+ display: grid;+ place-items: center;+ border: 0;+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.92);+ color: var(--ink-2);+ cursor: pointer;+ opacity: 0;+ transition:+ opacity 0.2s,+ color 0.2s;+}+.pages li:hover .pg-x,+.pg-x:focus-visible {+ opacity: 1;+}+.pg-x:hover {+ color: var(--ink);+}+@media (hover: none) {+ .pg-x {+ opacity: 1;+ }+}+.pages .pg-add {+ display: grid;+ background: transparent;+ box-shadow: none;+ border: 1.5px dashed var(--line-2);+ gap: 0;+}+.pg-add button {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 4px;+ border: 0;+ background: none;+ color: var(--ink-2);+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ transition:+ background 0.2s,+ color 0.2s;+}+.pg-add button:hover {+ background: rgba(255, 255, 255, 0.7);+ color: var(--ink);+}+.pg-add button + button {+ border-top: 1.5px dashed var(--line-2);+}++.scan-err {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px 10px;+ margin: 18px 0 0;+ padding: 12px 14px;+ border-radius: 12px;+ background: var(--miss-soft);+ color: #7a1f0f;+ font-size: 14.5px;+}+.scan-err a {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ color: inherit;+ font-weight: 600;+}+.scan-go {+ margin-top: 24px;+}+.scan-go .btn.primary.big {+ width: 100%;+ flex: none;+}+.scan-go p {+ margin: 10px 0 0;+ text-align: center;+ font-size: 13.5px;+ color: var(--ink-3);+}+.scan-privacy {+ display: flex;+ align-items: flex-start;+ gap: 8px;+ margin: 26px 0 0;+ font-size: 13px;+ line-height: 1.5;+ color: var(--ink-3);+}+.scan-privacy svg {+ flex: 0 0 auto;+ margin-top: 2px;+}++/* working */+.scan-work {+ margin-top: 30px;+}+.sw-live {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr);+ gap: 36px;+ align-items: center;+ padding: 30px;+ border-radius: 24px;+ background: #fff;+ box-shadow: var(--shadow-1);+}+.sw-stack {+ position: relative;+ height: 280px;+}+.sw-page {+ position: absolute;+ left: 50%;+ top: 50%;+ width: 138px;+ height: 184px;+ margin: -92px 0 0 -69px;+ border-radius: 8px;+ overflow: hidden;+ background: #fff;+ box-shadow:+ 0 0 0 1px var(--line-2),+ 0 8px 22px -12px rgba(18, 18, 18, 0.3);+ transition: filter 0.4s;+}+.sw-page img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.sw-page.read img {+ filter: grayscale(1) contrast(0.9) brightness(1.05);+}+.sw-scanline {+ position: absolute;+ left: 0;+ right: 0;+ top: 0;+ height: 36%;+ background: linear-gradient(180deg, rgba(18, 18, 18, 0) 0%, rgba(18, 18, 18, 0.07) 90%, rgba(18, 18, 18, 0.16) 100%);+ border-bottom: 2px solid var(--ink);+ animation: scanline 1.6s var(--ease) infinite alternate;+}+@keyframes scanline {+ from {+ transform: translateY(-100%);+ }+ to {+ transform: translateY(190%);+ }+}+.sw-tag {+ position: absolute;+ left: 6px;+ bottom: 6px;+ display: inline-flex;+ align-items: center;+ gap: 4px;+ max-width: calc(100% - 12px);+ height: 22px;+ padding: 0 7px;+ border-radius: 6px;+ background: var(--ink);+ color: #fff;+ font-size: 11.5px;+ font-weight: 500;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.sw-steps {+ list-style: none;+ margin: 0;+ padding: 0;+}+.sw-row {+ display: flex;+ gap: 12px;+ padding: 12px 0;+ color: var(--ink-3);+ transition: color 0.3s;+}+.sw-row + .sw-row {+ border-top: 1px solid var(--line);+}+.sw-row.on,+.sw-row.done {+ color: var(--ink);+}+.sw-ico {+ flex: 0 0 auto;+ display: grid;+ place-items: center;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1.5px var(--line-2);+}+.sw-row.done .sw-ico {+ background: var(--accent);+ box-shadow: inset 0 0 0 1.5px var(--ink);+}+.sw-row.on .sw-ico {+ box-shadow: none;+}+.spin {+ width: 18px;+ height: 18px;+ border-radius: 50%;+ border: 2px solid var(--line);+ border-top-color: var(--ink);+ animation: spin 0.8s linear infinite;+}+.sw-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}+.sw-text b {+ font-size: 15.5px;+ font-weight: 600;+}+.sw-text span {+ font-size: 13.5px;+ color: var(--ink-2);+}+.sw-foot {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding-top: 16px;+ border-top: 1px solid var(--line);+ color: var(--ink-3);+ font-size: 14px;+ font-variant-numeric: tabular-nums;+}+.sw-done {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);+ gap: 30px;+ align-items: center;+ padding: 24px;+ border-radius: 24px;+ background: #fff;+ box-shadow: var(--shadow-1);+}+.sw-thumb {+ border-radius: 16px;+}+.sw-ok {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 28px;+ padding: 0 10px;+ border-radius: 8px;+ background: var(--accent-soft);+ font-size: 13.5px;+ font-weight: 600;+}+.sw-done-text h2 {+ margin: 12px 0 4px;+ font-family: var(--display);+ font-size: 34px;+ font-weight: 800;+ letter-spacing: -0.03em;+}+.sw-done-text p {+ margin: 0;+ color: var(--ink-2);+}+.sw-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 20px;+}+.sw-done-text .sw-note {+ margin-top: 14px;+ font-size: 13px;+ color: var(--ink-3);+}++.callout-link {+ display: inline-block;+ margin-top: 6px;+ font-size: 14px;+ font-weight: 600;+ color: var(--ink);+}++@media (max-width: 720px) {+ .scan {+ padding-top: 22px;+ }+ .sf-row {+ grid-template-columns: 32px minmax(0, 1fr);+ }+ .sf-n {+ font-size: 24px;+ }+ .sw-live,+ .sw-done {+ grid-template-columns: 1fr;+ gap: 18px;+ padding: 20px;+ }+ .sw-stack {+ height: 240px;+ }+ .key-saved {+ flex-wrap: wrap;+ }+}++.nf-scan {+ justify-self: center;+ margin-top: 10px;+}diff --git a/src/app/scan/page.tsx b/src/app/scan/page.tsxnew file mode 100644index 0000000..e51ac6c--- /dev/null+++ b/src/app/scan/page.tsx@@ -0,0 +1,21 @@+import type { Metadata } from "next";+import SiteHeader from "@/components/SiteHeader";+import SiteFooter from "@/components/SiteFooter";+import Scanner from "@/components/scan/Scanner";++export const metadata: Metadata = {+ title: "Scan a manual | Bygga",+ description: "Photograph any assembly manual and Together AI turns it into a step by step guide in 3D.",+};++export default function Page() {+ return (+ <div className="site">+ <SiteHeader />+ <main>+ <Scanner />+ </main>+ <SiteFooter />+ </div>+ );+}diff --git a/src/components/Logo.tsx b/src/components/Logo.tsxnew file mode 100644index 0000000..5240bb7--- /dev/null+++ b/src/components/Logo.tsx@@ -0,0 +1,30 @@+import Link from "next/link";++const HEX = "M16 6.2 L24.5 11.1 L24.5 20.9 L16 25.8 L7.5 20.9 L7.5 11.1 Z";++/** The mark: an Allen bolt head seen from above. */+export function LogoMark({ size = 32, className }: { size?: number; className?: string }) {+ return (+ <svg viewBox="0 0 32 32" width={size} height={size} className={"mark " + (className ?? "")} aria-hidden="true">+ <circle cx="16" cy="16" r="15.5" fill="var(--ink)" />+ <path d="M6.2 11.4 A11 11 0 0 1 13 5.6" fill="none" stroke="rgba(255,255,255,.22)" strokeWidth="1.6" strokeLinecap="round" />+ <g className="mark-socket">+ <path d={HEX} fill="var(--accent)" stroke="var(--accent)" strokeWidth="2.2" strokeLinejoin="round" />+ <path d="M16 11.2 L20.2 13.6 L20.2 18.4 L16 20.8 L11.8 18.4 L11.8 13.6 Z" fill="var(--ink)" stroke="var(--ink)" strokeWidth="1.4" strokeLinejoin="round" />+ </g>+ </svg>+ );+}++export function Wordmark({ className }: { className?: string }) {+ return <span className={"wordmark " + (className ?? "")}>bygga</span>;+}++export default function Logo({ href = "/", compact, size = 26 }: { href?: string; compact?: boolean; size?: number }) {+ return (+ <Link href={href} className="logo" aria-label="Bygga home">+ <LogoMark size={size} />+ {!compact && <Wordmark />}+ </Link>+ );+}diff --git a/src/components/NavLinks.tsx b/src/components/NavLinks.tsxnew file mode 100644index 0000000..0cc6f4a--- /dev/null+++ b/src/components/NavLinks.tsx@@ -0,0 +1,31 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import { useMemo } from "react";+import { listProgress } from "@/lib/store";+import { useMounted } from "@/lib/useMounted";++const LINKS = [+ { href: "/browse", label: "Browse" },+ { href: "/builds", label: "Workshop" },+];++export default function NavLinks() {+ const path = usePathname();+ const mounted = useMounted();+ const builds = useMemo(() => (mounted ? listProgress().filter((p) => p.phase !== "cover").length : 0), [mounted]);+ return (+ <nav className="site-nav" aria-label="Main">+ {LINKS.map((l) => {+ const on = path === l.href;+ return (+ <Link key={l.href} href={l.href} className={"nav-link" + (on ? " on" : "")} aria-current={on ? "page" : undefined}>+ {l.label}+ {l.href === "/builds" && builds > 0 && <span className="nav-count">{builds}</span>}+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/src/components/SiteFooter.tsx b/src/components/SiteFooter.tsxnew file mode 100644index 0000000..c227b9f--- /dev/null+++ b/src/components/SiteFooter.tsx@@ -0,0 +1,38 @@+import Link from "next/link";+import Logo from "./Logo";+import { GITHUB_URL } from "@/lib/site";+import { IArrowUpRight } from "./art/Icons";++export default function SiteFooter() {+ return (+ <footer className="site-foot">+ <div className="foot-ruler" aria-hidden="true">+ {Array.from({ length: 11 }, (_, i) => (+ <span key={i} style={{ left: `${i * 10}%` }}>+ {i * 10}+ </span>+ ))}+ </div>+ <div className="foot-main">+ <div className="foot-brand">+ <Logo size={22} />+ <p>Step by step assembly for IKEA furniture, drawn like the paper manual.</p>+ </div>+ <nav className="foot-nav" aria-label="Footer">+ <Link href="/browse">All guides</Link>+ <Link href="/builds">Workshop</Link>+ <Link href="/scan">Scan a manual</Link>+ <a href={GITHUB_URL} target="_blank" rel="noreferrer">+ GitHub <IArrowUpRight size={13} />+ </a>+ </nav>+ </div>+ <div className="foot-base">+ <p>Not affiliated with or endorsed by IKEA. Product names are trademarks of Inter IKEA Systems B.V. Keep the paper manual nearby.</p>+ <a className="foot-powered" href="https://www.together.ai" target="_blank" rel="noreferrer">+ Powered by <span>Together AI</span>+ </a>+ </div>+ </footer>+ );+}diff --git a/src/components/SiteHeader.tsx b/src/components/SiteHeader.tsxnew file mode 100644index 0000000..102d935--- /dev/null+++ b/src/components/SiteHeader.tsx@@ -0,0 +1,45 @@+import { Suspense } from "react";+import Logo from "./Logo";+import NavLinks from "./NavLinks";+import { IGithub, IStar } from "./art/Icons";+import { getStars } from "@/lib/github";+import { GITHUB_URL } from "@/lib/site";++export default function SiteHeader() {+ return (+ <header className="site-head">+ <div className="head-left">+ <Logo />+ <NavLinks />+ </div>+ <Suspense fallback={<GithubLink stars={null} />}>+ <GithubStars />+ </Suspense>+ </header>+ );+}++async function GithubStars() {+ const stars = await getStars();+ return <GithubLink stars={stars} />;+}++function GithubLink({ stars }: { stars: number | null }) {+ return (+ <a className="gh" href={GITHUB_URL} target="_blank" rel="noreferrer" aria-label={stars === null ? "Bygga on GitHub" : `Bygga on GitHub, ${stars} stars`}>+ <IGithub size={16} />+ <span className="gh-label">GitHub</span>+ {stars !== null && (+ <span className="gh-stars">+ <IStar size={13} strokeWidth={2} />+ {fmtStars(stars)}+ </span>+ )}+ </a>+ );+}++function fmtStars(n: number) {+ if (n < 1000) return String(n);+ return (n / 1000).toFixed(n < 10000 ? 1 : 0).replace(/\.0$/, "") + "k";+}diff --git a/src/components/StageView.tsx b/src/components/StageView.tsxnew file mode 100644index 0000000..849123b--- /dev/null+++ b/src/components/StageView.tsx@@ -0,0 +1,111 @@+"use client";++import { useEffect, useRef } from "react";+import type { Plan } from "@/lib/types";+import type { Stage, StageMode, StageOptions } from "@/engine/stage";++export interface StageHandle {+ replay(): void;+ resetView(): void;+ setSpeed(s: number): void;+ setPaused(p: boolean): void;+}++export default function StageView({+ plan,+ mode,+ highlight,+ options,+ className,+ onReady,+ onIntroDone,+ onHover,+ onUserView,+ paused,+ speed,+}: {+ plan: Plan | null;+ mode: StageMode;+ highlight?: string[] | null;+ options?: Omit<StageOptions, "onIntroDone" | "onHover" | "onUserView">;+ className?: string;+ onReady?: (h: StageHandle) => void;+ onIntroDone?: () => void;+ onHover?: (ref: string | null) => void;+ onUserView?: (changed: boolean) => void;+ paused?: boolean;+ speed?: number;+}) {+ const host = useRef<HTMLDivElement>(null);+ const stage = useRef<Stage | null>(null);+ const cbs = useRef({ onIntroDone, onHover, onUserView, onReady });+ useEffect(() => {+ cbs.current = { onIntroDone, onHover, onUserView, onReady };+ });+ const modeKey = JSON.stringify(mode);+ const latest = useRef({ plan, mode, highlight });+ useEffect(() => {+ latest.current = { plan, mode, highlight };+ });++ useEffect(() => {+ let alive = true;+ let s: Stage | null = null;+ import("@/engine/stage").then(({ Stage }) => {+ if (!alive || !host.current) return;+ s = new Stage(host.current, {+ ...options,+ onIntroDone: () => cbs.current.onIntroDone?.(),+ onHover: (r) => cbs.current.onHover?.(r),+ onUserView: (c) => cbs.current.onUserView?.(c),+ });+ stage.current = s;+ const { plan: p, mode: m, highlight: h } = latest.current;+ if (p) {+ s.setPlan(p);+ s.setMode(m);+ }+ s.setHighlight(h ?? null);+ cbs.current.onReady?.({+ replay: () => s?.replay(),+ resetView: () => s?.resetView(),+ setSpeed: (v) => s?.setSpeed(v),+ setPaused: (v) => s?.setPaused(v),+ });+ });+ return () => {+ alive = false;+ s?.dispose();+ stage.current = null;+ };+ // options are read once on mount+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ const s = stage.current;+ if (!s || !plan) return;+ const fresh = s.plan !== plan;+ s.setPlan(plan);+ if (fresh) s.setMode(latest.current.mode);+ }, [plan]);++ useEffect(() => {+ const s = stage.current;+ if (!s || !s.plan) return;+ s.setMode(latest.current.mode);+ }, [modeKey]);++ useEffect(() => {+ stage.current?.setHighlight(highlight ?? null);+ }, [highlight]);++ useEffect(() => {+ stage.current?.setPaused(!!paused);+ }, [paused]);+ useEffect(() => {+ stage.current?.setSpeed(speed ?? 1);+ }, [speed]);++ return <div ref={host} className={"stage " + (className ?? "")} />;+}diff --git a/src/components/Thumb.tsx b/src/components/Thumb.tsxnew file mode 100644index 0000000..2577529--- /dev/null+++ b/src/components/Thumb.tsx@@ -0,0 +1,68 @@+"use client";++import { useEffect, useRef, useState } from "react";+import type { Plan } from "@/lib/types";+import type { StageMode } from "@/engine/stage";+import { peekThumbnail, thumbnail } from "@/engine/thumbs";+import { useMounted } from "@/lib/useMounted";++/** A static line drawing of a plan, rendered offscreen. With `lazy`, it waits until scrolled into view. */+export default function Thumb({+ id,+ plan,+ mode,+ w = 360,+ h = 270,+ className,+ alt = "",+ lazy,+}: {+ id: string;+ plan: Plan | null | (() => Plan);+ mode: StageMode;+ w?: number;+ h?: number;+ className?: string;+ alt?: string;+ lazy?: boolean;+}) {+ const key = `${id}:${JSON.stringify(mode)}:${w}x${h}`;+ const mounted = useMounted();+ const el = useRef<HTMLSpanElement>(null);+ const [seen, setSeen] = useState(!lazy);+ const [loaded, setLoaded] = useState<{ key: string; url: string } | null>(null);+ const url = (mounted ? peekThumbnail(key) : undefined) ?? (loaded?.key === key ? loaded.url : undefined);++ useEffect(() => {+ if (seen || !el.current) return;+ const io = new IntersectionObserver(+ (e) => {+ if (e.some((x) => x.isIntersecting)) {+ setSeen(true);+ io.disconnect();+ }+ },+ { rootMargin: "300px" },+ );+ io.observe(el.current);+ return () => io.disconnect();+ }, [seen]);++ useEffect(() => {+ if (!seen || !plan || peekThumbnail(key)) return;+ let alive = true;+ const p = typeof plan === "function" ? plan() : plan;+ thumbnail(key, p, mode, w, h).then((u) => alive && setLoaded({ key, url: u }));+ return () => {+ alive = false;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [key, plan, seen]);++ return (+ <span ref={el} className={"thumb " + (className ?? "") + (url ? " ready" : "")} style={{ aspectRatio: `${w} / ${h}` }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {url && <img src={url} alt={alt} draggable={false} />}+ </span>+ );+}diff --git a/src/components/art/Figure.tsx b/src/components/art/Figure.tsxnew file mode 100644index 0000000..fe28835--- /dev/null+++ b/src/components/art/Figure.tsx@@ -0,0 +1,76 @@+export type Pose = "stand" | "cheer" | "think" | "point" | "wave" | "read" | "lift";++const ARMS: Record<Pose, [string, string]> = {+ stand: ["M22 34 Q15 46 16 58", "M38 34 Q45 46 44 58"],+ cheer: ["M22 34 Q13 23 12 9", "M38 34 Q47 23 48 9"],+ think: ["M22 34 Q15 46 16 58", "M38 34 Q49 36 41 21"],+ point: ["M22 34 Q15 46 16 58", "M38 34 Q48 33 58 30"],+ wave: ["M22 34 Q15 46 16 58", "M38 34 Q48 26 49 12"],+ read: ["M22 34 Q19 44 27 46", "M38 34 Q41 44 33 46"],+ lift: ["M22 34 Q15 26 14 15", "M38 34 Q45 26 46 15"],+};++/** The helper character: an original little builder drawn with outlined limbs. viewBox 0 0 60 100. */+export function Figure({ pose = "stand", size = 80, className, bubble }: { pose?: Pose; size?: number; className?: string; bubble?: "?" | "!" | "check" }) {+ const [l, r] = ARMS[pose];+ const limb = (d: string, key: string, cls?: string) => (+ <g key={key} className={cls}>+ <path d={d} fill="none" stroke="var(--ink)" strokeWidth={7.4} strokeLinecap="round" />+ <path d={d} fill="none" stroke="#fff" strokeWidth={3.6} strokeLinecap="round" />+ </g>+ );+ return (+ <svg viewBox="0 0 60 100" width={(size * 60) / 100} height={size} className={"figure " + (className ?? "")} aria-hidden="true" overflow="visible">+ {limb("M26 58 L23 91", "ll")}+ {limb("M34 58 L37 91", "lr")}+ <path d="M20 93 h7 M33 93 h7" stroke="var(--ink)" strokeWidth={4.6} strokeLinecap="round" />+ <rect x={20.5} y={27} width={19} height={34} rx={9} fill="#fff" stroke="var(--ink)" strokeWidth={2.2} />+ {limb(l, "al", "arm-l")}+ {limb(r, "ar", "arm-r")}+ {pose === "read" && <rect x={22} y={38} width={16} height={12} rx={1.5} fill="var(--accent-soft)" stroke="var(--ink)" strokeWidth={1.8} transform="rotate(-6 30 44)" />}+ <circle cx={30} cy={15} r={9.5} fill="#fff" stroke="var(--ink)" strokeWidth={2.2} className="head" />+ {bubble && (+ <g transform="translate(46 -6)" className="bubble">+ <path d="M0 10 a12 11 0 1 1 6 9 l-7 4 l2 -6 a11 11 0 0 1 -1 -7 z" fill={bubble === "check" ? "var(--accent)" : "#fff"} stroke="var(--ink)" strokeWidth={2} strokeLinejoin="round" />+ {bubble === "?" && <text x={12} y={16} textAnchor="middle" fontSize={15} fontWeight={800} fill="var(--ink)" fontFamily="var(--font)">?</text>}+ {bubble === "!" && <text x={12} y={16} textAnchor="middle" fontSize={15} fontWeight={800} fill="var(--ink)" fontFamily="var(--font)">!</text>}+ {bubble === "check" && <path d="M6.5 10.5 l4 4 l7 -8" fill="none" stroke="var(--ink)" strokeWidth={2.6} strokeLinecap="round" strokeLinejoin="round" />}+ </g>+ )}+ </svg>+ );+}++/** Two figures carrying a panel together. */+export function TwoPeople({ size = 64, className }: { size?: number; className?: string }) {+ return (+ <svg viewBox="0 -2 120 100" width={(size * 120) / 100} height={size} className={className} aria-hidden="true">+ <rect x={12} y={2} width={96} height={9} rx={2} fill="var(--accent-soft)" stroke="var(--ink)" strokeWidth={2.2} />+ <g transform="translate(4 4)">+ <Mini />+ </g>+ <g transform="translate(62 4)">+ <Mini />+ </g>+ </svg>+ );+}++function Mini() {+ const limb = (d: string) => (+ <>+ <path d={d} fill="none" stroke="var(--ink)" strokeWidth={7} strokeLinecap="round" />+ <path d={d} fill="none" stroke="#fff" strokeWidth={3.4} strokeLinecap="round" />+ </>+ );+ return (+ <g>+ {limb("M26 58 L23 89")}+ {limb("M34 58 L37 89")}+ <rect x={20.5} y={27} width={19} height={34} rx={9} fill="#fff" stroke="var(--ink)" strokeWidth={2.2} />+ {limb("M22 34 Q15 22 18 4")}+ {limb("M38 34 Q45 22 42 4")}+ <circle cx={30} cy={18} r={8.5} fill="#fff" stroke="var(--ink)" strokeWidth={2.2} />+ </g>+ );+}diff --git a/src/components/art/Hardware.tsx b/src/components/art/Hardware.tsxnew file mode 100644index 0000000..e677024--- /dev/null+++ b/src/components/art/Hardware.tsx@@ -0,0 +1,281 @@+import type { HwKind } from "@/lib/types";++const METAL = "#e3e5e7";+const WOOD = "#f1e2c3";+const PLASTIC = "#f4f4f1";++interface Drawn {+ w: number;+ h: number;+ node: React.ReactNode;+ scalable: boolean;+}++const stroke = { stroke: "var(--ink)", strokeWidth: 1.5, vectorEffect: "non-scaling-stroke", strokeLinejoin: "round", strokeLinecap: "round" } as const;+const fine = { stroke: "var(--ink)", strokeWidth: 0.9, vectorEffect: "non-scaling-stroke", opacity: 0.55, strokeLinecap: "round" } as const;++function thread(x0: number, x1: number, r: number, pitch: number) {+ let d = `M${x0} ${-r}`;+ let up = true;+ for (let x = x0 + pitch / 2; x <= x1 + 0.01; x += pitch / 2) {+ d += ` L${Math.min(x, x1)} ${up ? -r * 0.78 : -r}`;+ up = !up;+ }+ d += ` L${x1} ${r}`;+ up = true;+ for (let x = x1 - pitch / 2; x >= x0 - 0.01; x -= pitch / 2) {+ d += ` L${Math.max(x, x0)} ${up ? r * 0.78 : r}`;+ up = !up;+ }+ return d + " Z";+}++function draw(kind: HwKind, len: number, dia: number): Drawn {+ const r = dia / 2;+ switch (kind) {+ case "dowel": {+ const lines = [-r / 2, 0, r / 2].map((y) => <path key={y} d={`M${dia * 0.45} ${y} H${len - dia * 0.45}`} {...fine} />);+ return { w: len, h: dia, scalable: true, node: <g><rect x={0} y={-r} width={len} height={dia} rx={r * 0.55} fill={WOOD} {...stroke} />{lines}</g> };+ }+ case "camScrew":+ return {+ w: 35,+ h: 8,+ scalable: true,+ node: (+ <g>+ <path d={thread(0, 11, 2.9, 1.4)} fill={METAL} {...stroke} />+ <rect x={11} y={-3.8} width={1.6} height={7.6} rx={0.6} fill={METAL} {...stroke} />+ <rect x={12.6} y={-2.2} width={15.6} height={4.4} fill={METAL} {...stroke} />+ <circle cx={31.4} cy={0} r={3.6} fill={METAL} {...stroke} />+ </g>+ ),+ };+ case "cam":+ return {+ w: 15,+ h: 16,+ scalable: true,+ node: (+ <g transform="translate(0 -4)">+ <path d="M0 0 V9.5 A7.5 3.2 0 0 0 15 9.5 V0" fill={METAL} {...stroke} />+ <ellipse cx={7.5} cy={0} rx={7.5} ry={3.2} fill="#f2f3f4" {...stroke} />+ <path d="M3.4 -1.1 L11.6 1.1" {...stroke} strokeWidth={2.2} />+ <path d="M10.6 -1.9 L13 -0.6 L11.2 0.6" fill="none" {...stroke} strokeWidth={1.1} />+ </g>+ ),+ };+ case "screw": {+ const hr = Math.max(dia * 1.05, 3.4);+ const ticks = [];+ for (let x = 3.4; x < len - 3; x += 1.7) ticks.push(<path key={x} d={`M${x} ${-r * 0.9} L${x + 0.9} ${r * 0.9}`} {...fine} />);+ return {+ w: len + 2,+ h: hr * 2,+ scalable: true,+ node: (+ <g>+ <path d={`M2 ${-r * 0.9} H${len - 1.5} L${len + 1.6} 0 L${len - 1.5} ${r * 0.9} H2 Z`} fill={METAL} {...stroke} />+ {ticks}+ <path d={`M2 ${-hr} C0.4 ${-hr} 0 ${-hr * 0.6} 0 0 C0 ${hr * 0.6} 0.4 ${hr} 2 ${hr} Z`} fill={METAL} {...stroke} />+ </g>+ ),+ };+ }+ case "nail":+ return {+ w: len,+ h: dia * 3.4,+ scalable: true,+ node: (+ <g>+ <path d={`M0.8 ${-r} H${len - 1.8} L${len} 0 L${len - 1.8} ${r} H0.8 Z`} fill={METAL} {...stroke} />+ <rect x={0} y={-dia * 1.7} width={0.9} height={dia * 3.4} fill={METAL} {...stroke} />+ </g>+ ),+ };+ case "pin":+ return {+ w: 17.4,+ h: dia + 2.4,+ scalable: true,+ node: (+ <g>+ <rect x={0} y={-r} width={8.4} height={dia} rx={0.8} fill={METAL} {...stroke} />+ <rect x={9.6} y={-r} width={7.8} height={dia} rx={r * 0.8} fill={METAL} {...stroke} />+ <rect x={8.2} y={-r - 1.2} width={1.6} height={dia + 2.4} rx={0.6} fill={METAL} {...stroke} />+ </g>+ ),+ };+ case "legScrew": {+ const mid = 12;+ const a = (len - mid) / 2;+ return {+ w: len,+ h: dia,+ scalable: true,+ node: (+ <g>+ <path d={thread(0, a, r, 1.6)} fill={METAL} {...stroke} />+ <rect x={a} y={-r * 0.82} width={mid} height={r * 1.64} fill={METAL} {...stroke} />+ <path d={thread(a + mid, len, r, 1.6)} fill={METAL} {...stroke} />+ </g>+ ),+ };+ }+ case "bolt": {+ const hr = dia * 0.85;+ const t0 = 5 + len * 0.45;+ return {+ w: len + 5,+ h: hr * 2,+ scalable: true,+ node: (+ <g>+ <rect x={5} y={-r} width={t0 - 5} height={dia} fill={METAL} {...stroke} />+ <path d={thread(t0, len + 5, r, 1.2)} fill={METAL} {...stroke} />+ <rect x={0} y={-hr} width={5.2} height={hr * 2} rx={1} fill={METAL} {...stroke} />+ <path d={`M1.4 ${-hr * 0.42} H3.6 M1.4 ${hr * 0.42} H3.6`} {...fine} />+ </g>+ ),+ };+ }+ case "plate":+ return {+ w: 70,+ h: 70,+ scalable: true,+ node: (+ <g transform="translate(0 -35)">+ <rect x={0} y={0} width={70} height={70} rx={4} fill={METAL} {...stroke} />+ {[+ [7, 7],+ [63, 7],+ [63, 63],+ [7, 63],+ ].map(([x, y]) => (+ <circle key={x + "-" + y} cx={x} cy={y} r={2.6} fill="#fff" {...stroke} />+ ))}+ <circle cx={35} cy={35} r={10} fill="#eef0f1" {...stroke} />+ <circle cx={35} cy={35} r={4.6} fill="#fff" {...stroke} />+ </g>+ ),+ };+ case "bracket":+ return {+ w: 46,+ h: 46,+ scalable: true,+ node: (+ <g transform="translate(0 -23)">+ <path d="M6 30 L30 44 L46 34 L22 20 Z" fill={METAL} {...stroke} />+ <path d="M22 20 L22 2 L46 16 L46 34 Z" fill="#eef0f1" {...stroke} />+ <ellipse cx={34} cy={18} rx={2.6} ry={3.2} fill="#fff" {...stroke} />+ <ellipse cx={21} cy={31} rx={3} ry={1.8} fill="#fff" {...stroke} />+ <ellipse cx={31} cy={37} rx={3} ry={1.8} fill="#fff" {...stroke} />+ </g>+ ),+ };+ case "runner":+ return {+ w: 120,+ h: 22,+ scalable: false,+ node: (+ <g>+ <path d="M0 -6 H114 L120 0 L114 6 H0 Z" fill={METAL} {...stroke} />+ <path d="M0 -10 H112 V-6 H0 Z" fill="#eef0f1" {...stroke} />+ {[16, 60, 104].map((x) => (+ <circle key={x} cx={x} cy={0} r={2} fill="#fff" {...stroke} />+ ))}+ </g>+ ),+ };+ case "knob":+ return {+ w: 26,+ h: 30,+ scalable: true,+ node: (+ <g>+ <rect x={0} y={-5.5} width={12} height={11} rx={1.5} fill={WOOD} {...stroke} />+ <path d="M12 -14 C22 -14 26 -8 26 0 C26 8 22 14 12 14 C10.5 14 10.5 -14 12 -14 Z" fill={WOOD} {...stroke} />+ </g>+ ),+ };+ case "handle":+ return {+ w: len + 24,+ h: 34,+ scalable: true,+ node: (+ <g transform="translate(0 -6)">+ <rect x={12 - 4} y={-8} width={8} height={26} rx={3} fill={METAL} {...stroke} transform={`translate(0 0)`} />+ <rect x={len + 12 - 4} y={-8} width={8} height={26} rx={3} fill={METAL} {...stroke} />+ <rect x={0} y={-14} width={len + 24} height={12} rx={6} fill={METAL} {...stroke} />+ </g>+ ),+ };+ case "hinge":+ return {+ w: 78,+ h: 40,+ scalable: true,+ node: (+ <g>+ <rect x={28} y={-7} width={42} height={14} rx={3} fill={METAL} {...stroke} />+ <rect x={66} y={-20} width={10} height={40} rx={2} fill="#eef0f1" {...stroke} />+ <circle cx={17.5} cy={0} r={17.5} fill={METAL} {...stroke} />+ <circle cx={17.5} cy={0} r={12} fill="#eef0f1" {...stroke} />+ <circle cx={3} cy={-15} r={2} fill="#fff" {...stroke} />+ </g>+ ),+ };+ case "glide":+ return { w: 20, h: 10, scalable: true, node: <g><path d="M0 -1 V2 A10 3.6 0 0 0 20 2 V-1" fill={PLASTIC} {...stroke} /><ellipse cx={10} cy={-1} rx={10} ry={3.6} fill={PLASTIC} {...stroke} /></g> };+ case "plug": {+ const ribs = [];+ for (let x = 5; x < len - 3; x += 4) ribs.push(<path key={x} d={`M${x} ${-r} L${x + 1.6} 0 L${x} ${r}`} fill="none" {...fine} />);+ return {+ w: len,+ h: dia + 3,+ scalable: true,+ node: (+ <g>+ <path d={`M1.5 ${-r} H${len - 2} L${len} 0 L${len - 2} ${r} H1.5 Z`} fill={PLASTIC} {...stroke} />+ {ribs}+ <rect x={0} y={-r - 1.5} width={1.6} height={dia + 3} rx={0.5} fill={PLASTIC} {...stroke} />+ </g>+ ),+ };+ }+ }+}++/**+ * Hardware drawing. `fit` draws it inside a square box of that many pixels;+ * `pxPerMm` draws it at real size.+ */+export function HwArt({ kind, len, dia, fit = 72, pxPerMm, className }: { kind: HwKind; len: number; dia: number; fit?: number; pxPerMm?: number; className?: string }) {+ const d = draw(kind, len, dia);+ const pad = Math.max(d.w, d.h) * 0.06 + 1;+ const vbW = d.w + pad * 2, vbH = d.h + pad * 2;+ let width: number, height: number;+ if (pxPerMm && d.scalable) {+ width = vbW * pxPerMm;+ height = vbH * pxPerMm;+ } else {+ const k = fit / Math.max(vbW, vbH * 1.15);+ width = vbW * k;+ height = vbH * k;+ }+ return (+ <svg className={className} viewBox={`${-pad} ${-d.h / 2 - pad} ${vbW} ${vbH}`} width={width} height={height} aria-hidden="true" overflow="visible">+ {d.node}+ </svg>+ );+}++export function canActualSize(kind: HwKind) {+ return kind !== "runner";+}diff --git a/src/components/art/Icons.tsx b/src/components/art/Icons.tsxnew file mode 100644index 0000000..248a28e--- /dev/null+++ b/src/components/art/Icons.tsx@@ -0,0 +1,161 @@+import type { WarnId } from "@/lib/types";++type P = { size?: number; className?: string; strokeWidth?: number };++function I({ size = 22, className, strokeWidth = 2, children }: P & { children: React.ReactNode }) {+ return (+ <svg viewBox="0 0 24 24" width={size} height={size} className={className} fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">+ {children}+ </svg>+ );+}++export const IArrowRight = (p: P) => <I {...p}><path d="M5 12h14M13 6l6 6-6 6" /></I>;+export const IArrowLeft = (p: P) => <I {...p}><path d="M19 12H5M11 6l-6 6 6 6" /></I>;+export const ICheck = (p: P) => <I {...p}><path d="M5 12.5l4.5 4.5L19 7.5" /></I>;+export const IClose = (p: P) => <I {...p}><path d="M6 6l12 12M18 6L6 18" /></I>;+export const ISearch = (p: P) => <I {...p}><circle cx="10.5" cy="10.5" r="6.5" /><path d="M15.5 15.5L20 20" /></I>;+export const ICamera = (p: P) => <I {...p}><path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2l1.6-2.2h5.8L16.5 7h2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" /><circle cx="12" cy="12.8" r="3.4" /></I>;+export const IMic = (p: P) => <I {...p}><rect x="9" y="3.5" width="6" height="11" rx="3" /><path d="M5.5 11.5a6.5 6.5 0 0 0 13 0M12 18v2.5" /></I>;+export const IGrid = (p: P) => <I {...p}><rect x="4" y="4" width="6.5" height="6.5" rx="1.5" /><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5" /><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5" /><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5" /></I>;+export const IHelp = (p: P) => <I {...p}><circle cx="12" cy="12" r="8.5" /><path d="M9.6 9.4a2.5 2.5 0 1 1 3.4 2.3c-.7.3-1 .9-1 1.6v.4" /><circle cx="12" cy="16.8" r=".4" fill="currentColor" /></I>;+export const IReplay = (p: P) => <I {...p}><path d="M4.5 12a7.5 7.5 0 1 0 2.2-5.3" /><path d="M4.5 4.5v3.8h3.8" /></I>;+export const IPause = (p: P) => <I {...p}><path d="M9 6v12M15 6v12" /></I>;+export const IPlay = (p: P) => <I {...p}><path d="M8 5.5v13l10-6.5z" /></I>;+export const IClock = (p: P) => <I {...p}><circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" /></I>;+export const IPeople = (p: P) => <I {...p}><circle cx="9" cy="8" r="3" /><path d="M3.5 19a5.5 5.5 0 0 1 11 0" /><circle cx="17" cy="9" r="2.4" /><path d="M15.5 14.2A4.5 4.5 0 0 1 21 18.5" /></I>;+export const IPerson = (p: P) => <I {...p}><circle cx="12" cy="8" r="3.2" /><path d="M6 19.5a6 6 0 0 1 12 0" /></I>;+export const IRuler = (p: P) => <I {...p}><path d="M3.5 15.5l12-12 5 5-12 12z" /><path d="M7 12l2 2M10 9l1.5 1.5M13 6l2 2" /></I>;+export const IBox = (p: P) => <I {...p}><path d="M12 3.5l8 4v9l-8 4-8-4v-9z" /><path d="M4 7.5l8 4 8-4M12 11.5v9" /></I>;+export const ISparkle = (p: P) => <I {...p}><path d="M12 3.5c.6 4.4 2.6 6.4 7 7-4.4.6-6.4 2.6-7 7-.6-4.4-2.6-6.4-7-7 4.4-.6 6.4-2.6 7-7z" /></I>;+export const IVolume = (p: P) => <I {...p}><path d="M5 9.5h3l4-3.5v12l-4-3.5H5z" /><path d="M16 9a4 4 0 0 1 0 6M18.5 6.5a7.5 7.5 0 0 1 0 11" /></I>;+export const IRotate = (p: P) => <I {...p}><path d="M19.5 12A7.5 7.5 0 1 1 17.3 6.7" /><path d="M19.5 4.5v3.8h-3.8" /></I>;+export const IHome = (p: P) => <I {...p}><path d="M4.5 10.5L12 4l7.5 6.5V19a1 1 0 0 1-1 1h-4v-5h-5v5h-4a1 1 0 0 1-1-1z" /></I>;+export const IChevron = (p: P) => <I {...p}><path d="M9 6l6 6-6 6" /></I>;+export const IChevronDown = (p: P) => <I {...p}><path d="M6 9l6 6 6-6" /></I>;+export const IExternal = (p: P) => <I {...p}><path d="M14 4.5h5.5V10M19.5 4.5L11 13M17 14v4.5a1 1 0 0 1-1 1H5.5a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1H10" /></I>;+export const ISend = (p: P) => <I {...p}><path d="M5 12h13M12 5.5l6.5 6.5-6.5 6.5" /></I>;+export const IEye = (p: P) => <I {...p}><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z" /><circle cx="12" cy="12" r="2.8" /></I>;+export const IWand = (p: P) => <I {...p}><path d="M4.5 19.5l10-10M13 6l5 5" /><path d="M18 3.5v3M16.5 5h3M6 4v2M5 5h2M19 15v2M18 16h2" /></I>;+export const ISun = (p: P) => <I {...p}><circle cx="12" cy="12" r="3.6" /><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6L7 7M17 17l1.4 1.4M5.6 18.4L7 17M17 7l1.4-1.4" /></I>;+export const IBolt = (p: P) => <I {...p}><path d="M13 3L6 13.5h5L10 21l7.5-11H12z" /></I>;+export const IMore = (p: P) => <I {...p}><circle cx="6" cy="12" r="1" fill="currentColor" /><circle cx="12" cy="12" r="1" fill="currentColor" /><circle cx="18" cy="12" r="1" fill="currentColor" /></I>;+export const IUpload = (p: P) => <I {...p}><path d="M12 15.5V4.5M7.5 9L12 4.5 16.5 9" /><path d="M4.5 15v3.5a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V15" /></I>;+export const ITrash = (p: P) => <I {...p}><path d="M5 7h14M9.5 7V5h5v2M7 7l.8 12a1 1 0 0 0 1 1h6.4a1 1 0 0 0 1-1L17 7" /></I>;++/* Warning pictograms: chunkier, shown in step cards */+export function WarnIcon({ id, size = 36 }: { id: WarnId; size?: number }) {+ const s = { stroke: "var(--ink)", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" } as const;+ const body: Record<WarnId, React.ReactNode> = {+ two: (+ <g {...s}>+ <rect x="5" y="6" width="30" height="4" rx="1" fill="var(--accent-soft)" />+ <circle cx="12" cy="16" r="3.4" fill="#fff" />+ <path d="M7 31v-6a5 5 0 0 1 10 0v6M9 20l-2-10M15 20l2-10" fill="#fff" />+ <circle cx="28" cy="16" r="3.4" fill="#fff" />+ <path d="M23 31v-6a5 5 0 0 1 10 0v6M25 20l-2-10M31 20l2-10" fill="#fff" />+ </g>+ ),+ loose: (+ <g {...s}>+ <rect x="9" y="22" width="22" height="9" rx="1.5" fill="#f1efe9" />+ <path d="M17 22V10h6v12" fill="#fff" />+ <path d="M14 8h12" />+ <path d="M27.5 13.5a6 6 0 0 0-3-4.6" />+ <path d="M24.5 6.5l0 2.6 2.6.2" />+ </g>+ ),+ hand: (+ <g {...s}>+ <path d="M13 31v-9l-3-3.5a1.8 1.8 0 0 1 2.6-2.4L15 18V8.5a1.8 1.8 0 0 1 3.6 0V15V7a1.8 1.8 0 0 1 3.6 0v8V8.5a1.8 1.8 0 0 1 3.6 0V16v-4.5a1.8 1.8 0 0 1 3.6 0V22c0 5-3 9-8 9z" fill="#fff" />+ </g>+ ),+ wall: (+ <g {...s}>+ <path d="M6 4v32" />+ <path d="M6 8l-3 3M6 15l-3 3M6 22l-3 3M6 29l-3 3" strokeWidth={1.4} />+ <rect x="16" y="10" width="17" height="25" rx="1.5" fill="#fff" />+ <path d="M6 11h7v5" fill="none" />+ <path d="M13 16h3" />+ </g>+ ),+ square: (+ <g {...s}>+ <rect x="6" y="8" width="28" height="24" rx="1.5" fill="#fff" />+ <path d="M9 11l22 18M31 11L9 29" strokeDasharray="3 3" />+ <circle cx="20" cy="20" r="4.5" fill="#fff" />+ <path d="M18 19h4M18 21.2h4" strokeWidth={1.4} />+ </g>+ ),+ floor: (+ <g {...s}>+ <path d="M4 28l10-6h22l-10 6z" fill="var(--accent-soft)" />+ <path d="M10 23V12h14v10" fill="#fff" />+ <path d="M8 34l4-2.5M16 34l4-2.5M24 34l4-2.5" strokeWidth={1.4} />+ </g>+ ),+ face: (+ <g {...s}>+ <rect x="6" y="9" width="28" height="22" rx="1.5" fill="#fff" />+ <circle cx="13" cy="15" r="1.8" />+ <circle cx="13" cy="25" r="1.8" />+ <circle cx="27" cy="15" r="1.8" />+ <circle cx="27" cy="25" r="1.8" />+ <path d="M17 20h6M20.5 17.5L23 20l-2.5 2.5" />+ </g>+ ),+ tip: (+ <g {...s}>+ <path d="M5 35h30" />+ <g transform="rotate(14 24 34)">+ <rect x="15" y="6" width="16" height="28" rx="1.5" fill="#fff" />+ <path d="M15 15h16M15 24h16" />+ </g>+ <path d="M8 10l6 6M14 10l-6 6" strokeWidth={2.4} />+ </g>+ ),+ };+ return (+ <svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">+ {body[id]}+ </svg>+ );+}++export const WARN_TEXT: Record<WarnId, string> = {+ two: "Two people",+ loose: "Don't tighten fully yet",+ hand: "Hand tight only",+ wall: "Wall fixing",+ square: "Keep it square",+ floor: "Protect the surface",+ face: "Holes face inwards",+ tip: "Tip-over risk",+};++export const IWrench = (p: P) => <I {...p}><path d="M14.7 6.3a4 4 0 0 0 5.2 5.2l-8.6 8.6a2.1 2.1 0 0 1-3-3l8.6-8.6a4 4 0 0 1-2.2-2.2z" /><path d="M14.7 6.3L17 4l3 3-2.3 2.3" /></I>;+export const IHammer = (p: P) => <I {...p}><path d="M13.5 9.5L5 18a1.8 1.8 0 0 0 2.5 2.5l8.5-8.5" /><path d="M10.5 6.5l3-3c1.6-.6 3.4-.4 5 .8l1.2 1.2-2 2 1.5 1.5-2.5 2.5-1.5-1.5-2 2-2.7-2.7" /></I>;+export const IFlag = (p: P) => <I {...p}><path d="M5.5 21V4.5" /><path d="M5.5 4.5h11l-2.5 4 2.5 4h-11" /></I>;+export const ISound = (p: P) => <I {...p}><path d="M5 9.5h3l4-3.5v12l-4-3.5H5z" /><path d="M16 9a4 4 0 0 1 0 6" /></I>;+export const ISoundOff = (p: P) => <I {...p}><path d="M5 9.5h3l4-3.5v12l-4-3.5H5z" /><path d="M16.5 9.5l5 5M21.5 9.5l-5 5" /></I>;+export const ILibrary = (p: P) => <I {...p}><rect x="4" y="4" width="4" height="16" rx="1" /><rect x="10" y="4" width="4" height="16" rx="1" /><path d="M16.2 5.2l3.8-1 3.2 14.8-3.8 1z" /></I>;+export const IShare = (p: P) => <I {...p}><path d="M12 15V4M7.5 8.5L12 4l4.5 4.5" /><path d="M5 13v6a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-6" /></I>;+export const IPrint = (p: P) => <I {...p}><path d="M7 9V4h10v5" /><rect x="4" y="9" width="16" height="8" rx="2" /><path d="M7 14h10v6H7z" /></I>;+export const IAlert = (p: P) => <I {...p}><circle cx="12" cy="12" r="8.5" /><path d="M12 7.5v5.5" /><circle cx="12" cy="16.4" r=".5" fill="currentColor" /></I>;+export const IPlus = (p: P) => <I {...p}><path d="M12 5v14M5 12h14" /></I>;+export const IFilter = (p: P) => <I {...p}><path d="M4 6h16M7 12h10M10 18h4" /></I>;+export const IArrowUpRight = (p: P) => <I {...p}><path d="M7 17L17 7M8 7h9v9" /></I>;++export function IGithub({ size = 22, className }: { size?: number; className?: string }) {+ return (+ <svg viewBox="0 0 24 24" width={size} height={size} className={className} fill="currentColor" aria-hidden="true">+ <path d="M12 2.2a9.8 9.8 0 0 0-3.1 19.1c.5.1.7-.2.7-.5v-1.7c-2.7.6-3.3-1.3-3.3-1.3-.5-1.1-1.1-1.4-1.1-1.4-.9-.6.1-.6.1-.6 1 .1 1.5 1 1.5 1 .9 1.5 2.3 1.1 2.9.8.1-.6.3-1.1.6-1.3-2.2-.3-4.5-1.1-4.5-4.9 0-1.1.4-2 1-2.6-.1-.3-.4-1.3.1-2.7 0 0 .8-.3 2.7 1a9.3 9.3 0 0 1 4.9 0c1.9-1.3 2.7-1 2.7-1 .5 1.4.2 2.4.1 2.7.6.7 1 1.5 1 2.6 0 3.8-2.3 4.6-4.5 4.9.4.3.7.9.7 1.8v2.7c0 .3.2.6.7.5A9.8 9.8 0 0 0 12 2.2z" />+ </svg>+ );+}+export const IStar = (p: P) => <I {...p}><path d="M12 4.2l2.4 4.9 5.4.8-3.9 3.8.9 5.4-4.8-2.5-4.8 2.5.9-5.4-3.9-3.8 5.4-.8z" /></I>;+export const IScan = (p: P) => <I {...p}><path d="M4 8V5.5A1.5 1.5 0 0 1 5.5 4H8M16 4h2.5A1.5 1.5 0 0 1 20 5.5V8M20 16v2.5a1.5 1.5 0 0 1-1.5 1.5H16M8 20H5.5A1.5 1.5 0 0 1 4 18.5V16" /><path d="M8 9h8M8 12h8M8 15h5" /></I>;+export const IKey = (p: P) => <I {...p}><circle cx="8" cy="15" r="3.8" /><path d="M10.8 12.3L19 4.2M16 7.2l2.3 2.3M13.8 9.4l1.8 1.8" /></I>;+export const IImage = (p: P) => <I {...p}><rect x="4" y="4.5" width="16" height="15" rx="2" /><circle cx="9" cy="9.5" r="1.6" /><path d="M20 16l-4.5-4.5L7 20" /></I>;+export const IDoc = (p: P) => <I {...p}><path d="M6.5 3.5h7.5l4.5 4.5v11.5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1v-15a1 1 0 0 1 1-1z" /><path d="M13.5 3.5V8.5h5" /></I>;+export const ILock = (p: P) => <I {...p}><rect x="5" y="10.5" width="14" height="10" rx="2" /><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5" /></I>;diff --git a/src/components/art/Tools.tsx b/src/components/art/Tools.tsxnew file mode 100644index 0000000..2da9a38--- /dev/null+++ b/src/components/art/Tools.tsx@@ -0,0 +1,126 @@+import type { ToolId } from "@/lib/types";++const S = { stroke: "var(--ink)", strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round" } as const;+const W = "#fff";+const G = "#ecebe6";+const A = "var(--accent-soft)";++/** Hand drawn tool illustrations in the same line style as the 3D stage. viewBox 0 0 96 96. */+export function ToolArt({ id, size = 96, className }: { id: ToolId; size?: number; className?: string }) {+ return (+ <svg viewBox="0 0 96 96" width={size} height={size} className={className} aria-hidden="true">+ {ART[id]}+ </svg>+ );+}++const ART: Record<ToolId, React.ReactNode> = {+ allen: (+ <g transform="rotate(-28 48 48)" {...S}>+ <path d="M40 10 h10 v58 a4 4 0 0 0 4 4 h24 v10 h-30 a8 8 0 0 1 -8 -8 z" fill={W} />+ <path d="M40 18 h10 M70 72 v10" fill="none" />+ <path d="M45 10 v58" fill="none" strokeWidth={1.2} opacity={0.5} />+ <path d="M50 76 h28" fill="none" strokeWidth={1.2} opacity={0.5} />+ </g>+ ),+ screwdriver: (+ <g transform="rotate(38 48 48)" {...S}>+ <rect x="38" y="6" width="20" height="38" rx="8" fill={W} />+ <path d="M44 13 v24 M48 12 v26 M52 13 v24" fill="none" strokeWidth={1.4} />+ <rect x="42" y="44" width="12" height="6" rx="2" fill={G} />+ <rect x="45.5" y="50" width="5" height="32" fill={W} />+ <path d="M45.5 82 L48 90 L50.5 82 Z" fill={G} />+ <path d="M48 83.5 v4.5 M46.6 85.6 h2.8" fill="none" strokeWidth={1.1} />+ </g>+ ),+ flathead: (+ <g transform="rotate(38 48 48)" {...S}>+ <rect x="38" y="6" width="20" height="38" rx="8" fill={W} />+ <path d="M44 13 v24 M48 12 v26 M52 13 v24" fill="none" strokeWidth={1.4} />+ <rect x="42" y="44" width="12" height="6" rx="2" fill={G} />+ <rect x="45.5" y="50" width="5" height="32" fill={W} />+ <path d="M45.5 82 L44.5 90 h7 L50.5 82 Z" fill={G} />+ </g>+ ),+ hammer: (+ <g transform="rotate(-32 48 48)" {...S}>+ <rect x="43" y="30" width="10" height="58" rx="4" fill={W} />+ <rect x="43" y="62" width="10" height="26" rx="4" fill={G} />+ <path d="M30 16 h36 a3 3 0 0 1 3 3 v12 a3 3 0 0 1 -3 3 h-36 z" fill={W} />+ <rect x="66" y="13" width="9" height="24" rx="2.5" fill={G} />+ <path d="M30 17 C20 16 14 22 11 30 C16 27 21 26 30 27 M30 33 C24 33 19 35 16 40" fill={W} />+ </g>+ ),+ drill: (+ <g {...S}>+ <path d="M36 50 L30 76 h18 L52 50 Z" fill={W} />+ <rect x="26" y="76" width="28" height="12" rx="3" fill={G} />+ <rect x="14" y="26" width="52" height="24" rx="12" fill={W} />+ <path d="M24 30 v16" fill="none" strokeWidth={1.4} />+ <path d="M28 30 v16" fill="none" strokeWidth={1.4} />+ <rect x="66" y="30" width="10" height="16" rx="3" fill={G} />+ <path d="M76 38 h14" fill="none" strokeWidth={2.6} />+ <path d="M79 35.5 l2 5 M83 35.5 l2 5 M87 35.5 l2 5" fill="none" strokeWidth={1.1} />+ <rect x="40" y="50" width="6" height="8" rx="2" fill={A} />+ </g>+ ),+ level: (+ <g transform="rotate(-14 48 48)" {...S}>+ <rect x="6" y="38" width="84" height="20" rx="3" fill={W} />+ <rect x="37" y="42" width="22" height="12" rx="6" fill={A} />+ <circle cx="48" cy="48" r="3.4" fill={W} />+ <path d="M44 42 v12 M52 42 v12" fill="none" strokeWidth={1.2} />+ <path d="M14 38 v6 M22 38 v4 M30 38 v6 M66 38 v6 M74 38 v4 M82 38 v6" fill="none" strokeWidth={1.3} />+ </g>+ ),+ tape: (+ <g {...S}>+ <path d="M54 58 h34 v10 h-34" fill={A} />+ <path d="M60 58 v4 M66 58 v6 M72 58 v4 M78 58 v6 M84 58 v4" fill="none" strokeWidth={1.2} />+ <path d="M88 56 v14" fill="none" strokeWidth={2.6} />+ <rect x="10" y="26" width="48" height="46" rx="14" fill={W} />+ <circle cx="34" cy="49" r="12" fill={G} />+ <circle cx="34" cy="49" r="4" fill={W} />+ <rect x="40" y="20" width="12" height="8" rx="2" fill={G} />+ </g>+ ),+ pencil: (+ <g transform="rotate(-40 48 48)" {...S}>+ <rect x="40" y="10" width="16" height="10" rx="3" fill={G} />+ <rect x="40" y="20" width="16" height="50" fill={W} />+ <path d="M45.3 20 v50 M50.6 20 v50" fill="none" strokeWidth={1.1} />+ <path d="M40 70 L48 88 L56 70 Z" fill={A} />+ <path d="M45.2 82 L48 88 L50.8 82 Z" fill="var(--ink)" />+ </g>+ ),+ wrench: (+ <g transform="rotate(-38 48 48)" {...S}>+ <rect x="34" y="42" width="54" height="12" rx="6" fill={W} />+ <circle cx="24" cy="48" r="16" fill={W} />+ <path d="M8 42 h12 l3 6 l-3 6 h-12" fill="var(--paper)" />+ <path d="M8.6 42.4 v11.2" stroke="var(--paper)" strokeWidth={3} />+ <circle cx="80" cy="48" r="2.6" fill={G} />+ </g>+ ),+ knife: (+ <g transform="rotate(-24 48 48)" {...S}>+ <path d="M14 42 h52 a8 8 0 0 1 8 8 v2 a8 8 0 0 1 -8 8 h-52 z" fill={W} />+ <path d="M74 44 L90 50 L74 56 Z" fill={G} />+ <path d="M24 46 h22" fill="none" strokeWidth={1.3} />+ <rect x="50" y="38" width="10" height="5" rx="2" fill={A} />+ </g>+ ),+};++export const TOOL_INFO: Record<ToolId, { name: string; hint: string; alt?: string }> = {+ allen: { name: "Allen key", hint: "The small L-shaped key", alt: "It comes in the box. Keep it with the hardware bag." },+ screwdriver: { name: "Phillips screwdriver", hint: "Cross-shaped tip", alt: "A drill on its lowest setting works, but hand-tighten the last turn." },+ flathead: { name: "Flat screwdriver", hint: "Straight tip", alt: "A coin can turn cam locks in a pinch." },+ hammer: { name: "Hammer", hint: "For dowels and nails", alt: "For dowels, a rubber mallet or a firm push works. Nails need a hammer." },+ drill: { name: "Drill", hint: "Only for the wall", alt: "Ask your landlord or a neighbour. Never skip anchoring tall furniture." },+ level: { name: "Spirit level", hint: "Handy, not essential", alt: "A level app on your phone does the job." },+ tape: { name: "Tape measure", hint: "To check it is square", alt: "A piece of string works: compare both diagonals." },+ pencil: { name: "Pencil", hint: "For marking the wall", alt: "Any pen will do." },+ wrench: { name: "Spanner", hint: "Comes in the box", alt: "Adjustable pliers work too." },+ knife: { name: "Box cutter", hint: "To open the box", alt: "Scissors work. Cut the tape, not the panels." },+};diff --git a/src/components/guide/CoverPanel.tsx b/src/components/guide/CoverPanel.tsxnew file mode 100644index 0000000..a44c329--- /dev/null+++ b/src/components/guide/CoverPanel.tsx@@ -0,0 +1,200 @@+"use client";++import Link from "next/link";+import type { Plan } from "@/lib/types";+import type { Progress } from "@/lib/store";+import { floorSpace, totals } from "@/lib/plan/contents";+import { IArrowRight, IBox, IClock, IExternal, IPeople, IPerson, IRuler, ISparkle, IWrench } from "../art/Icons";+import { Dots } from "./ui";+import { TOOL_INFO } from "../art/Tools";++export default function CoverPanel({+ plan,+ via,+ resume,+ onStart,+ onResume,+}: {+ plan: Plan;+ via: "catalog" | "ai" | "guess" | "scan";+ resume: Progress | null;+ onStart: () => void;+ onResume: () => void;+}) {+ const s = plan.spec;+ const t = totals(plan);+ const resumable = resume && (resume.phase !== "cover" || resume.step > 0) && resume.phase !== "done";+ const official = `https://www.ikea.com/search/?q=${encodeURIComponent(s.name)}`;+ const tools = plan.tools.filter((x) => !x.optional && !x.included).map((x) => TOOL_INFO[x.id].name.replace("Phillips ", ""));+ return (+ <div className="pane cover">+ <div className="pane-scroll">+ <header className="pane-head">+ <p className="eyebrow">{s.brand ? `${s.brand}, ${s.category.toLowerCase()}` : s.category}</p>+ <h1 className="product-name">{s.name}</h1>+ <p className="product-variant">{s.variant}</p>+ </header>++ {s.variants && s.variants.length > 1 && (+ <div className="chips" role="list" aria-label="Other sizes">+ {s.variants.map((v) => (+ <Link key={v.slug} href={`/build/${v.slug}`} className={"chip" + (v.slug === s.slug ? " on" : "")} role="listitem" replace>+ {shortVariant(v.label)}+ </Link>+ ))}+ </div>+ )}++ <dl className="stats">+ <div>+ <dt>+ <IClock size={16} /> Time+ </dt>+ <dd>{fmtMin(s.minutes)}</dd>+ </div>+ <div>+ <dt>{s.people === 2 ? <IPeople size={16} /> : <IPerson size={16} />} People</dt>+ <dd>{s.people === 2 ? "Two" : "One"}</dd>+ </div>+ <div>+ <dt>+ <Dots value={s.difficulty} /> Level+ </dt>+ <dd>{["", "Easy", "Medium", "Patient"][s.difficulty]}</dd>+ </div>+ </dl>++ <h3 className="section-title">Before you start</h3>+ <ul className="prep">+ <li>+ <span className="prep-ico">+ <IRuler size={18} />+ </span>+ <span>+ Clear <b>{floorSpace(plan)}</b> of floor and lay the flattened box down as a mat.+ </span>+ </li>+ <li>+ <span className="prep-ico">+ <IBox size={18} />+ </span>+ <span>+ <b>{t.panels} panels</b> and <b>{t.fittings} fittings</b> in {plan.steps.length} steps.+ </span>+ </li>+ {tools.length > 0 && (+ <li>+ <span className="prep-ico">+ <IWrench size={18} />+ </span>+ <span>+ You'll want a <b>{tools.join(" and a ").toLowerCase()}</b>.+ </span>+ </li>+ )}+ {t.twoAt.length > 0 && s.people === 1 && (+ <li>+ <span className="prep-ico">+ <IPeople size={18} />+ </span>+ <span>Ask someone to help with step {t.twoAt.slice(0, 2).join(" and ")}.</span>+ </li>+ )}+ {s.watchOut?.slice(0, 2).map((w) => (+ <li key={w}>+ <span className="prep-ico">+ <ISparkle size={18} />+ </span>+ <span>{w}</span>+ </li>+ ))}+ </ul>++ {s.siblings && s.siblings.length > 0 && (+ <>+ <h3 className="section-title">Other {s.name} products</h3>+ <div className="chips">+ {s.siblings.slice(0, 6).map((v) => (+ <Link key={v.slug} href={`/build/${v.slug}`} className="chip ghost">+ {v.label}+ </Link>+ ))}+ </div>+ </>+ )}++ {via === "scan" ? (+ <div className="callout note">+ <ISparkle size={18} />+ <div>+ <b>{s.custom?.fromCover ? "Drawn from the cover" : "Made from your manual"}</b>+ <span>+ {s.custom?.fromCover+ ? "Together AI only saw the cover, so this is a typical build for this product. Scan the inside pages for an exact match."+ : "Together AI read your pages and drew each step. Check every step against the paper manual before you fix anything."}+ </span>+ {s.custom?.fromCover && (+ <Link href="/scan" className="callout-link">+ Scan the pages+ </Link>+ )}+ </div>+ </div>+ ) : (+ via !== "catalog" && (+ <div className="callout note">+ <ISparkle size={18} />+ <div>+ <b>{via === "ai" ? "Drafted with Together AI" : "A typical build"}</b>+ <span>+ {via === "ai"+ ? "Built from what Together AI knows about this product. If your box looks different, trust the paper manual."+ : "We don't know this exact product yet, so this follows a typical build. Keep the paper manual close."}+ </span>+ </div>+ </div>+ )+ )}+ {via !== "scan" && (+ <a className="official" href={official} target="_blank" rel="noreferrer">+ Official manual on ikea.com <IExternal size={15} />+ </a>+ )}+ </div>+ <div className="pane-foot">+ {resumable ? (+ <>+ <button className="btn primary big" onClick={onResume}>+ <span>{resume.phase === "steps" ? `Continue at step ${resume.step + 1}` : "Continue"}</span>+ <IArrowRight />+ </button>+ <div className="foot-row center">+ <button className="btn link" onClick={onStart}>+ Start again from the beginning+ </button>+ </div>+ </>+ ) : (+ <button className="btn primary big" onClick={onStart} autoFocus>+ <span>Start building</span>+ <IArrowRight />+ </button>+ )}+ </div>+ </div>+ );+}++function shortVariant(l: string) {+ return l+ .replace(/^[^,]+,\s*/, "")+ .replace(/^chest of /i, "")+ .replace(/^drawer unit, /i, "")+ .replace(/^shoe cabinet with /i, "");+}++export function fmtMin(m: number) {+ if (m < 60) return `${m} min`;+ const h = Math.floor(m / 60), r = m % 60;+ return r ? `${h} h ${r} min` : `${h} h`;+}diff --git a/src/components/guide/DonePanel.tsx b/src/components/guide/DonePanel.tsxnew file mode 100644index 0000000..4ab3828--- /dev/null+++ b/src/components/guide/DonePanel.tsx@@ -0,0 +1,179 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { motion } from "motion/react";+import type { Plan } from "@/lib/types";+import { totals } from "@/lib/plan/contents";+import { Figure } from "../art/Figure";+import { IArrowLeft, IArrowRight, ICheck, ILibrary, IShare } from "../art/Icons";+import { fmtMin } from "./CoverPanel";+import { encodeSpec } from "@/lib/scan/share";++export default function DonePanel({ plan, slug, startedAt, doneAt, onReview }: { plan: Plan; slug: string; startedAt?: number; doneAt?: number; onReview: () => void }) {+ const t = totals(plan);+ const spent = startedAt && doneAt ? Math.max(1, Math.round((doneAt - startedAt) / 60000)) : null;+ const a = plan.spec.archetype;+ const recheck = a === "table" || a === "bed" || a === "seat" || a === "sofa";+ const tall = plan.steps.some((s) => s.kind === "anchor");+ const faster = spent !== null && spent < plan.spec.minutes;+ const [copied, setCopied] = useState(false);++ const share = async () => {+ // scanned guides only exist in this browser, so the link carries the guide itself+ const url = `${location.origin}/build/${slug}` + (plan.spec.source === "scan" ? `#g=${await encodeSpec(plan.spec)}` : "");+ const text = `I just built ${plan.spec.name} with Bygga.`;+ try {+ if (navigator.share) await navigator.share({ title: "Bygga", text, url });+ else {+ await navigator.clipboard.writeText(`${text} ${url}`);+ setCopied(true);+ setTimeout(() => setCopied(false), 1800);+ }+ } catch {+ /* cancelled */+ }+ };++ return (+ <div className="pane done">+ <div className="pane-scroll">+ <motion.div className="done-hero" initial={{ scale: 0.6, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ type: "spring", stiffness: 260, damping: 16, delay: 0.1 }}>+ <Figure pose="cheer" size={104} bubble="check" className="bounce" />+ </motion.div>+ <motion.h2 className="done-title" initial={{ y: 16, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0.25, duration: 0.5, ease: [0.22, 1, 0.36, 1] }}>+ You built {plan.spec.name}.+ </motion.h2>+ <motion.p className="sub center" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.4 }}>+ {faster ? `${plan.spec.minutes - spent!} minutes faster than most people.` : "Every step done. Nice work."}+ </motion.p>+ <dl className="stats">+ <div>+ <dt>{spent ? "Your time" : "Typical time"}</dt>+ <dd>{fmtMin(spent ?? t.minutes)}</dd>+ </div>+ <div>+ <dt>Steps</dt>+ <dd>{plan.steps.length}</dd>+ </div>+ <div>+ <dt>Fittings</dt>+ <dd>{t.fittings}</dd>+ </div>+ </dl>+ <Link href="/builds" className="workshop-link">+ <span className="wl-ico">+ <ILibrary size={18} />+ </span>+ <span>+ <b>Saved to your workshop</b>+ <span>See everything you've built, side by side.</span>+ </span>+ <IArrowRight size={18} />+ </Link>+ <h3 className="section-title">Before you load it up</h3>+ <ul className="after">+ {tall && (+ <li>+ <ICheck size={16} strokeWidth={2.6} /> Double check it's fixed to the wall.+ </li>+ )}+ {recheck && (+ <li>+ <ICheck size={16} strokeWidth={2.6} /> Tighten every bolt again after a week. Wood settles.+ </li>+ )}+ <li>+ <ICheck size={16} strokeWidth={2.6} /> Spare fittings are normal. Tape the bag inside, with the Allen key.+ </li>+ <li>+ <ICheck size={16} strokeWidth={2.6} /> Flatten the box for recycling.+ </li>+ </ul>+ </div>+ <div className="pane-foot">+ <button className="btn round" onClick={onReview} aria-label="Back to the last step">+ <IArrowLeft />+ </button>+ <button className="btn round" onClick={share} aria-label="Share" data-tip={copied ? "Link copied" : "Share"}>+ {copied ? <ICheck /> : <IShare />}+ </button>+ <Link className="btn primary big" href="/">+ <span>Build something else</span>+ <IArrowRight />+ </Link>+ </div>+ </div>+ );+}++const PIECES = ["dowel", "screw", "cam", "pin", "nail", "dowel", "screw"];++export function Confetti() {+ const bits = Array.from({ length: 36 }, (_, i) => i);+ return (+ <div className="confetti" aria-hidden="true">+ {bits.map((i) => {+ const left = (i * 37) % 100;+ const delay = (i % 9) * 0.09;+ const dur = 1.8 + ((i * 13) % 10) / 10;+ const rot = ((i * 71) % 360) - 180;+ const kind = PIECES[i % PIECES.length];+ const yellow = i % 4 === 0;+ return (+ <motion.span+ key={i}+ className="bit"+ style={{ left: `${left}%` }}+ initial={{ y: -40, rotate: 0, opacity: 0 }}+ animate={{ y: "110vh", rotate: rot * 3, opacity: [0, 1, 1, 0] }}+ transition={{ duration: dur, delay, ease: [0.25, 0.1, 0.4, 1] }}+ >+ <Bit kind={kind} yellow={yellow} />+ </motion.span>+ );+ })}+ </div>+ );+}++function Bit({ kind, yellow }: { kind: string; yellow: boolean }) {+ const f = yellow ? "var(--accent)" : "#fff";+ const s = { stroke: "var(--ink)", strokeWidth: 1.6, strokeLinejoin: "round" as const };+ switch (kind) {+ case "dowel":+ return (+ <svg width="28" height="10" viewBox="0 0 28 10">+ <rect x="1" y="1" width="26" height="8" rx="3" fill={yellow ? f : "#f1e2c3"} {...s} />+ </svg>+ );+ case "screw":+ return (+ <svg width="26" height="12" viewBox="0 0 26 12">+ <path d="M4 3.5h17l4 2.5-4 2.5H4z" fill={f} {...s} />+ <rect x="1" y="1" width="3.4" height="10" rx="1.2" fill={f} {...s} />+ </svg>+ );+ case "cam":+ return (+ <svg width="18" height="18" viewBox="0 0 18 18">+ <circle cx="9" cy="9" r="7.5" fill={f} {...s} />+ <path d="M5 7.5l8 3" {...s} strokeWidth={2} />+ </svg>+ );+ case "pin":+ return (+ <svg width="18" height="10" viewBox="0 0 18 10">+ <rect x="1" y="3" width="16" height="4" rx="2" fill={f} {...s} />+ <rect x="7.6" y="1" width="2" height="8" fill={f} {...s} />+ </svg>+ );+ default:+ return (+ <svg width="22" height="8" viewBox="0 0 22 8">+ <path d="M2 3h16l3 1-3 1H2z" fill={f} {...s} />+ <rect x="1" y="1" width="1.4" height="6" fill={f} {...s} />+ </svg>+ );+ }+}diff --git a/src/components/guide/GuideApp.tsx b/src/components/guide/GuideApp.tsxnew file mode 100644index 0000000..b8d978e--- /dev/null+++ b/src/components/guide/GuideApp.tsx@@ -0,0 +1,682 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { AnimatePresence, motion } from "motion/react";+import type { Plan, ProductSpec, ToolId } from "@/lib/types";+import { catalogSpec } from "@/lib/catalog";+import { buildPlan } from "@/lib/plan";+import { stepContents } from "@/lib/plan/contents";+import { matchCatalog, specForKind } from "@/lib/search";+import { KIND_LABELS, type Kind } from "@/lib/products";+import { cacheSpec, cachedSpec, loadProgress, saveProgress, type Phase, type Progress } from "@/lib/store";+import StageView, { type StageHandle } from "../StageView";+import type { StageMode } from "@/engine/stage";+import { LogoMark } from "../Logo";+import { HwArt } from "../art/Hardware";+import { Figure } from "../art/Figure";+import { IBox, ICheck, IFlag, IGrid, IHammer, IHelp, IMic, IPause, IPlay, IReplay, IRotate, IScan, ISound, ISoundOff, ISparkle, IWrench } from "../art/Icons";+import CoverPanel from "./CoverPanel";+import ToolsPanel from "./ToolsPanel";+import PartsPanel from "./PartsPanel";+import StepPanel from "./StepPanel";+import DonePanel, { Confetti } from "./DonePanel";+import HelpSheet from "./HelpSheet";+import Overview from "./Overview";+import Loader from "./Loader";+import Thumb from "../Thumb";+import { haptic, speak, speechSupported, useHandsFree, useWakeLock } from "./hooks";+import { playDone, playStep, setSound, soundOn } from "./sound";+import { useMounted } from "@/lib/useMounted";+import { getUserKey, keyHeaders } from "@/lib/userKey";+import { decodeSpec } from "@/lib/scan/share";++type Via = "catalog" | "ai" | "guess" | "scan";++export default function GuideApp({ slug, query, step, kind }: { slug: string; query?: string; step?: number; kind?: string }) {+ const router = useRouter();+ const mounted = useMounted();+ const picked = KIND_LABELS.some((k) => k.kind === kind) ? (kind as Kind) : null;+ const isScan = slug.startsWith("scan-");+ const q = query || slug.replace(/-/g, " ");+ const initial = useMemo(() => (isScan ? null : (catalogSpec(slug) ?? (picked ? { ...specForKind(picked, q.split(" ")[0] || q), slug } : null))), [isScan, slug, picked, q]);+ const local = useMemo(() => (initial || isScan ? null : matchCatalog(q)), [initial, isScan, q]);+ const [imported, setImported] = useState<{ slug: string; spec: ProductSpec | null } | null>(null);+ const stored = useMemo(() => (mounted && !initial && !local ? cachedSpec(slug) : null), [mounted, initial, local, slug]);+ const cached = stored ?? (imported?.slug === slug ? imported.spec : null);+ const hash = useMemo(() => (mounted && isScan && location.hash.startsWith("#g=") ? location.hash.slice(3) : ""), [mounted, isScan]);++ // a scanned guide shared as a link carries its own data+ useEffect(() => {+ if (!hash) return;+ let alive = true;+ decodeSpec(hash).then((sp) => {+ if (!alive) return;+ if (sp) cacheSpec(slug, { ...sp, slug });+ setImported({ slug, spec: sp ? { ...sp, slug } : null });+ history.replaceState(null, "", location.pathname + location.search);+ });+ return () => {+ alive = false;+ };+ }, [hash, slug]);+ useEffect(() => {+ if (local?.slug && local.slug !== slug) router.replace(`/build/${local.slug}`);+ }, [local, slug, router]);+ const [fetched, setFetched] = useState<{ slug: string; spec?: ProductSpec; via?: Via; suggestions?: string[]; error?: boolean } | null>(null);+ const [ai, setAi] = useState(false);+ const result = fetched?.slug === slug ? fetched : null;+ const spec = initial ?? cached ?? result?.spec ?? null;+ const via: Via = initial ? (initial.source === "guess" ? "guess" : "catalog") : cached ? cached.source : (result?.via ?? "ai");+ const scanGone = isScan && mounted && !cached && (!hash || (imported?.slug === slug && !imported.spec));+ const status = spec ? "ready" : scanGone ? "scangone" : result ? (result.error ? "error" : "notfound") : "loading";+ const suggestions = result?.suggestions ?? [];++ useEffect(() => {+ fetch("/api/status")+ .then((r) => r.json())+ .then((j) => setAi(!!j.ai || !!getUserKey()))+ .catch(() => {});+ }, []);++ // resolve unknown products through the API+ useEffect(() => {+ if (!mounted || initial || cached || local || isScan) return;+ let alive = true;+ fetch("/api/guide", { method: "POST", headers: { "Content-Type": "application/json", ...keyHeaders() }, body: JSON.stringify({ q }) })+ .then((r) => r.json())+ .then((j) => {+ if (!alive) return;+ if (j.spec) {+ const sp = j.spec as ProductSpec;+ if (j.via === "catalog" && sp.slug && sp.slug !== slug) {+ router.replace(`/build/${sp.slug}`);+ return;+ }+ sp.slug = slug;+ cacheSpec(slug, sp);+ setFetched({ slug, spec: sp, via: j.via });+ } else setFetched({ slug, suggestions: j.suggestions ?? [] });+ })+ .catch(() => alive && setFetched({ slug, error: true }));+ return () => {+ alive = false;+ };+ }, [mounted, initial, cached, local, isScan, slug, q, router]);++ const plan = useMemo(() => {+ if (!spec) return null;+ try {+ return buildPlan(spec);+ } catch (e) {+ console.error(e);+ return null;+ }+ }, [spec]);++ if (status === "scangone")+ return (+ <Shell title="Scanned guide">+ <div className="notfound">+ <Figure pose="think" bubble="?" size={120} />+ <h1>This guide lives on another device</h1>+ <p className="sub">Scanned guides are saved in the browser that made them. Ask for a share link from the done screen, or scan the manual again.</p>+ <Link href="/scan" className="btn primary">+ Scan a manual+ </Link>+ </div>+ </Shell>+ );+ if (status === "loading")+ return (+ <Shell title={isScan ? "Scanned guide" : q.toUpperCase()}>+ <Loader query={isScan ? "your guide" : q} ai={ai} />+ </Shell>+ );+ if (status === "notfound" || status === "error" || !plan)+ return (+ <Shell title={q.toUpperCase()}>+ <NotFound query={q} slug={slug} suggestions={suggestions} error={status === "error"} />+ </Shell>+ );+ return <Guide key={slug + (picked ?? "")} plan={plan} slug={slug} via={via} ai={ai} startStep={step} />;+}++function Shell({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <div className="guide shell">+ <header className="topbar">+ <Link href="/" className="home-btn" aria-label="Bygga home">+ <LogoMark size={34} />+ </Link>+ <div className="tb-title">+ <b>{title}</b>+ </div>+ </header>+ <main className="shell-main">{children}</main>+ </div>+ );+}++function NotFound({ query, slug, suggestions, error }: { query: string; slug: string; suggestions: string[]; error: boolean }) {+ const name = query.split(" ")[0].toUpperCase();+ const kinds = useMemo(() => KIND_LABELS.map((k) => ({ ...k, plan: buildPlan({ ...specForKind(k.kind, "X"), slug: "kind-" + k.kind }) })), []);+ if (error)+ return (+ <div className="notfound">+ <Figure pose="think" bubble="?" size={120} />+ <h1>Something went wrong</h1>+ <p className="sub">Check your connection and try again.</p>+ <Link href="/" className="btn primary">+ Back to search+ </Link>+ </div>+ );+ return (+ <div className="notfound wide">+ <div className="nf-head">+ <Figure pose="think" bubble="?" size={96} />+ <div>+ <h1>What does {name} look like?</h1>+ <p className="sub">We don't have {name} on file yet. Pick the closest shape and we'll walk you through a typical build.</p>+ </div>+ </div>+ <div className="kind-grid">+ {kinds.map((k, i) => (+ <motion.div key={k.kind} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.025 }}>+ <Link className="kind-card" href={`/build/${slug}?q=${encodeURIComponent(query)}&kind=${k.kind}`}>+ <Thumb id={"kind-" + k.kind} plan={k.plan} mode={{ kind: "assembled" }} w={200} h={150} className="kind-thumb" />+ <span>{k.label}</span>+ </Link>+ </motion.div>+ ))}+ </div>+ {suggestions.length > 0 && (+ <div className="chips center">+ <span className="muted">Or did you mean</span>+ {suggestions.map((s) => (+ <Link key={s} className="chip" href={`/build/${encodeURIComponent(s.toLowerCase().replace(/\s+/g, "-"))}?q=${encodeURIComponent(s)}`}>+ {s}+ </Link>+ ))}+ </div>+ )}+ <Link href="/scan" className="scan-link nf-scan">+ <IScan size={17} />+ <span>+ Not from IKEA? <u>Scan its paper manual</u>+ </span>+ </Link>+ </div>+ );+}++/* ------------------------------------------------------------------ */++function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; via: Via; ai: boolean; startStep?: number }) {+ const steps = plan.steps;+ const deep = startStep ? Math.min(startStep, steps.length) - 1 : null;+ const [phase, setPhase] = useState<Phase>(deep !== null ? "steps" : "cover");+ const [step, setStep] = useState(deep ?? 0);+ const [dir, setDir] = useState(1);+ const [tools, setTools] = useState<string[]>([]);+ const [missing, setMissing] = useState<Set<string>>(new Set());+ const [startedAt, setStartedAt] = useState<number | undefined>();+ const [doneAt, setDoneAt] = useState<number | undefined>();+ const [resume, setResume] = useState<Progress | null>(null);+ const [maxStep, setMaxStep] = useState(0);+ const [reached, setReached] = useState(deep !== null ? 3 : 0);+ const [help, setHelp] = useState<null | { missing?: boolean }>(null);+ const [overview, setOverview] = useState(false);+ const [handsFree, setHandsFree] = useState(false);+ const [hl, setHl] = useState<string[] | null>(null);+ const [hover3d, setHover3d] = useState<string | null>(null);+ const [introPlayed, setIntroPlayed] = useState(false);+ const [paused, setPaused] = useState(false);+ const [slow, setSlow] = useState(false);+ const [moved, setMoved] = useState(false);+ const [stamp, setStamp] = useState(0);+ const [toast, setToast] = useState<{ id: number; text: string } | null>(null);+ const [sound, setSoundState] = useState(true);+ const stage = useRef<StageHandle | null>(null);+ const mounted = useMounted();+ const canListen = mounted && speechSupported();++ // restore progress once we are in the browser+ const [restored, setRestored] = useState(false);+ if (mounted && !restored) {+ setRestored(true);+ setSoundState(soundOn());+ const p = loadProgress(slug);+ if (p) {+ setResume(p);+ setTools(p.tools);+ setMissing(new Set(p.missing ?? []));+ setStartedAt(p.startedAt);+ setMaxStep(Math.min(p.step, steps.length - 1));+ setReached(PHASES.indexOf(p.phase));+ if (p.doneAt) setDoneAt(p.doneAt);+ }+ }++ // persist+ useEffect(() => {+ if (!restored || phase === "cover") return;+ saveProgress({+ slug,+ name: plan.spec.name,+ variant: plan.spec.variant,+ category: plan.spec.category,+ minutes: plan.spec.minutes,+ people: plan.spec.people,+ phase,+ step,+ steps: steps.length,+ tools,+ parts: [],+ missing: [...missing],+ startedAt,+ doneAt,+ updatedAt: Date.now(),+ spec: plan.spec.source === "catalog" ? undefined : plan.spec,+ });+ }, [restored, slug, plan, phase, step, tools, missing, startedAt, doneAt, steps.length]);++ useWakeLock(phase === "steps" || phase === "parts");++ const go = useCallback((p: Phase, s?: number, d = 1) => {+ setDir(d);+ setPhase(p);+ setReached((r) => Math.max(r, PHASES.indexOf(p)));+ if (s !== undefined) {+ setStep(s);+ setMaxStep((m) => Math.max(m, s));+ }+ setHl(null);+ setMoved(false);+ if (p === "done") setDoneAt((x) => x ?? Date.now());+ }, []);++ const showToast = useCallback((text: string) => {+ const id = Date.now();+ setToast({ id, text });+ setTimeout(() => setToast((t) => (t?.id === id ? null : t)), 2600);+ }, []);++ const next = useCallback(() => {+ haptic(12);+ if (phase === "cover") {+ setStartedAt((x) => x ?? Date.now());+ go("tools");+ } else if (phase === "tools") go("parts");+ else if (phase === "parts") go("steps", 0);+ else if (phase === "steps") {+ setStamp((x) => x + 1);+ if (step < steps.length - 1) {+ playStep();+ const n = step + 1;+ const half = Math.floor(steps.length / 2);+ if (steps.length >= 6 && n === half) showToast("Halfway there. Nice work.");+ else if (n === steps.length - 1 && steps.length >= 4) showToast("Last step coming up.");+ go("steps", n);+ } else {+ playDone();+ go("done");+ }+ }+ }, [phase, step, steps.length, go, showToast]);++ const back = useCallback(() => {+ if (phase === "tools") go("cover", undefined, -1);+ else if (phase === "parts") go("tools", undefined, -1);+ else if (phase === "steps") {+ if (step > 0) go("steps", step - 1, -1);+ else go("parts", undefined, -1);+ } else if (phase === "done") go("steps", steps.length - 1, -1);+ }, [phase, step, steps.length, go]);++ // keyboard+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (help || overview) return;+ const t = e.target as HTMLElement;+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA")) return;+ if (phase !== "steps") return;+ if (e.key === "ArrowRight" || e.key === " " || e.key === "Enter") {+ if (t?.tagName === "BUTTON" && (e.key === " " || e.key === "Enter")) return;+ e.preventDefault();+ next();+ } else if (e.key === "ArrowLeft") {+ e.preventDefault();+ back();+ } else if (e.key.toLowerCase() === "r") stage.current?.replay();+ else if (e.key === "?") setHelp({});+ else if (e.key.toLowerCase() === "o") setOverview(true);+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [phase, next, back, help, overview]);++ // hands free+ const { listening, heard } = useHandsFree(handsFree && phase === "steps", (c) => {+ if (c === "next") next();+ else if (c === "back") back();+ else if (c === "repeat") {+ stage.current?.replay();+ const s = steps[step];+ speak(`${s.title}. ${s.detail ?? ""}`);+ } else if (c === "help") setHelp({});+ else if (c === "stop") setHandsFree(false);+ });+ useEffect(() => {+ if (!handsFree || phase !== "steps") return;+ const s = steps[step];+ const t = setTimeout(() => speak(`Step ${step + 1}. ${s.title}. ${s.detail ?? ""}`), 250);+ return () => clearTimeout(t);+ }, [handsFree, phase, step, steps]);+ useEffect(() => {+ if (!handsFree) window.speechSynthesis?.cancel();+ }, [handsFree]);++ useEffect(() => {+ const base = `${plan.spec.name} | Bygga`;+ document.title = phase === "steps" ? `Step ${step + 1} of ${steps.length}, ${base}` : phase === "done" ? `Built: ${base}` : base;+ }, [phase, step, steps.length, plan.spec.name]);++ const mode: StageMode = useMemo(() => {+ if (phase === "cover") return introPlayed || resume ? { kind: "assembled", turntable: true, dims: true } : { kind: "intro", dims: true };+ if (phase === "tools" || phase === "done") return { kind: "assembled", turntable: true };+ if (phase === "parts") return { kind: "layout" };+ return { kind: "step", index: step };+ }, [phase, step, introPlayed, resume]);++ const highlight = hl ?? (hover3d ? [hover3d] : null);+ const cur = steps[step];+ const contents = phase === "steps" ? stepContents(plan, step) : null;++ const jump = (p: Phase) => {+ if (p === "steps") go("steps", Math.min(maxStep, steps.length - 1), PHASES.indexOf(p) >= PHASES.indexOf(phase) ? 1 : -1);+ else go(p, undefined, PHASES.indexOf(p) >= PHASES.indexOf(phase) ? 1 : -1);+ };++ return (+ <div className="guide" data-phase={phase}>+ <header className="topbar">+ <Link href="/" className="home-btn" aria-label="Bygga home">+ <LogoMark size={34} />+ </Link>+ <div className="tb-title">+ <b>{plan.spec.name}</b>+ <span>{plan.spec.variant}</span>+ </div>+ <Stepper phase={phase} step={step} total={steps.length} reached={reached} onJump={jump} />+ <div className="tb-actions">+ {phase === "steps" && (+ <button className="icon-btn" onClick={() => setOverview(true)} aria-label="All steps" data-tip="All steps">+ <IGrid />+ </button>+ )}+ <button+ className="icon-btn"+ onClick={() => {+ setSound(!sound);+ setSoundState(!sound);+ }}+ aria-pressed={sound}+ aria-label={sound ? "Sound on" : "Sound off"}+ data-tip={sound ? "Sound on" : "Sound off"}+ >+ {sound ? <ISound /> : <ISoundOff />}+ </button>+ {phase === "steps" && (+ <button className={"icon-btn" + (handsFree ? " live" : "")} onClick={() => setHandsFree((h) => !h)} aria-pressed={handsFree} aria-label="Hands-free mode" data-tip={canListen ? "Hands-free" : "Read aloud"}>+ <IMic />+ </button>+ )}+ <button className="icon-btn" onClick={() => setHelp({})} aria-label="Help" data-tip="Help">+ <IHelp />+ </button>+ </div>+ </header>++ <main className="guide-main">+ <section className="sheet" aria-label="Assembly drawing">+ <StageView+ plan={plan}+ mode={mode}+ highlight={highlight}+ paused={paused}+ speed={slow ? 0.5 : 1}+ options={{ callout: true, interactive: true }}+ onReady={(h) => (stage.current = h)}+ onIntroDone={() => setIntroPlayed(true)}+ onHover={setHover3d}+ onUserView={setMoved}+ />++ {phase === "steps" && cur && (+ <div className="corner" aria-hidden="true">+ <div className="num-wrap">+ <AnimatePresence mode="popLayout" initial={false}>+ <motion.span+ key={step}+ className="big-n"+ initial={{ y: 46 * dir, opacity: 0 }}+ animate={{ y: 0, opacity: 1 }}+ exit={{ y: -46 * dir, opacity: 0 }}+ transition={{ type: "spring", stiffness: 420, damping: 34 }}+ >+ {step + 1}+ </motion.span>+ </AnimatePresence>+ {cur.repeat && cur.repeat > 1 && <span className="corner-repeat">{cur.repeat}×</span>}+ </div>+ {contents && contents.hardware.length > 0 && (+ <motion.div key={"hw" + step} className="hw-box" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15, duration: 0.35 }}>+ {contents.hardware.slice(0, 4).map(({ type, count }) => (+ <span key={type.id} className={"hw-box-item" + (highlight?.includes(type.id) ? " lit" : "")}>+ <HwArt kind={type.kind} len={type.len} dia={type.dia} fit={40} />+ <b>{count}×</b>+ </span>+ ))}+ </motion.div>+ )}+ </div>+ )}++ <AnimatePresence>+ {stamp > 0 && phase === "steps" && (+ <motion.span+ key={stamp}+ className="stamp"+ initial={{ scale: 0.3, opacity: 0, rotate: -20 }}+ animate={{ scale: [0.3, 1.12, 1], opacity: [0, 1, 1, 0], rotate: 0 }}+ transition={{ duration: 0.85, times: [0, 0.35, 0.6, 1] }}+ >+ <ICheck size={34} strokeWidth={3} />+ </motion.span>+ )}+ </AnimatePresence>++ <AnimatePresence>+ {toast && (+ <motion.div key={toast.id} className="toast" initial={{ opacity: 0, y: 16, scale: 0.96 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: -8 }} transition={{ type: "spring", stiffness: 420, damping: 30 }}>+ <Figure pose="cheer" size={40} />+ <span>{toast.text}</span>+ </motion.div>+ )}+ </AnimatePresence>++ {phase === "steps" && (+ <div className="stage-ctl">+ <button className="icon-btn float" onClick={() => stage.current?.replay()} aria-label="Replay animation" data-tip="Replay (R)">+ <IReplay />+ </button>+ <button className="icon-btn float" onClick={() => setPaused((p) => !p)} aria-label={paused ? "Play" : "Pause"} data-tip={paused ? "Play" : "Pause"}>+ {paused ? <IPlay /> : <IPause />}+ </button>+ <button className={"pill-btn float" + (slow ? " on" : "")} onClick={() => setSlow((s) => !s)} aria-pressed={slow}>+ Slow+ </button>+ <AnimatePresence>+ {moved && (+ <motion.button initial={{ opacity: 0, x: -8 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0 }} className="pill-btn float" onClick={() => stage.current?.resetView()}>+ <IRotate size={15} /> Reset view+ </motion.button>+ )}+ </AnimatePresence>+ </div>+ )}+ {phase === "steps" && step === 0 && !moved && <span className="drag-hint">Drag to turn it around</span>}+ {phase === "parts" && <span className="sheet-caption">Lay your panels out like this</span>}+ {handsFree && phase === "steps" && (+ <div className="listening">+ <span className={"eq" + (listening ? " on" : "")} aria-hidden="true">+ <i />+ <i />+ <i />+ </span>+ <span>{canListen ? (heard ? `Heard “${heard}”` : "Say “next”, “back” or “repeat”") : "Reading steps aloud"}</span>+ </div>+ )}+ {(via === "ai" || via === "scan") && phase === "cover" && (+ <span className="sheet-caption ai">+ <ISparkle size={15} /> {via === "scan" ? "Made from your manual with Together AI" : "Drafted with Together AI"}+ </span>+ )}+ </section>++ <aside className="panel">+ <AnimatePresence mode="wait" initial={false}>+ <motion.div+ key={phase}+ className="panel-inner"+ initial={{ opacity: 0, y: 14 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -10 }}+ transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}+ >+ {phase === "cover" && (+ <CoverPanel+ plan={plan}+ via={via}+ resume={resume}+ onStart={() => {+ setMissing(new Set());+ setStartedAt(Date.now());+ setDoneAt(undefined);+ setMaxStep(0);+ setReached(0);+ go("tools");+ }}+ onResume={() => {+ if (!resume) return;+ if (resume.phase === "steps") go("steps", Math.min(resume.step, steps.length - 1));+ else go(resume.phase === "cover" ? "tools" : resume.phase);+ }}+ />+ )}+ {phase === "tools" && (+ <ToolsPanel+ plan={plan}+ onNext={(have: ToolId[]) => {+ setTools(have);+ next();+ }}+ onBack={back}+ />+ )}+ {phase === "parts" && (+ <PartsPanel+ plan={plan}+ missing={missing}+ onToggle={(id) => setMissing((s) => toggle(s, id))}+ onNext={next}+ onBack={back}+ onHover={setHl}+ onMissingHelp={() => setHelp({ missing: true })}+ />+ )}+ {phase === "steps" && <StepPanel plan={plan} index={step} dir={dir} onNext={next} onBack={back} onHover={setHl} onHelp={() => setHelp({})} />}+ {phase === "done" && <DonePanel plan={plan} slug={slug} startedAt={startedAt} doneAt={doneAt} onReview={back} />}+ </motion.div>+ </AnimatePresence>+ </aside>+ </main>++ {phase === "done" && <Confetti />}+ <p className="sr-only" aria-live="polite">+ {phase === "steps" ? `Step ${step + 1} of ${steps.length}. ${cur?.title ?? ""}. ${cur?.detail ?? ""}` : phase === "done" ? `You built ${plan.spec.name}.` : ""}+ </p>++ <AnimatePresence>+ {help && <HelpSheet plan={plan} index={phase === "steps" ? step : -1} ai={ai} focusMissing={help.missing} onClose={() => setHelp(null)} />}+ </AnimatePresence>+ <AnimatePresence>+ {overview && (+ <Overview+ plan={plan}+ current={step}+ doneUpTo={maxStep}+ onPick={(i) => {+ setOverview(false);+ go("steps", i, i >= step ? 1 : -1);+ }}+ onClose={() => setOverview(false)}+ />+ )}+ </AnimatePresence>+ </div>+ );+}++const PHASES: Phase[] = ["cover", "tools", "parts", "steps", "done"];++function toggle(s: Set<string>, id: string) {+ const n = new Set(s);+ if (n.has(id)) n.delete(id);+ else n.add(id);+ return n;+}++/** Labeled phase stepper: Tools, Parts, Build (with step progress), Done. */+function Stepper({ phase, step, total, reached, onJump }: { phase: Phase; step: number; total: number; reached: number; onJump: (p: Phase) => void }) {+ const items: { id: Phase; label: string; icon: React.ReactNode }[] = [+ { id: "tools", label: "Tools", icon: <IWrench size={16} /> },+ { id: "parts", label: "Parts", icon: <IBox size={16} /> },+ { id: "steps", label: "Build", icon: <IHammer size={16} /> },+ { id: "done", label: "Done", icon: <IFlag size={16} /> },+ ];+ const cur = PHASES.indexOf(phase);+ const pct = phase === "done" ? 1 : phase === "steps" ? (step + 1) / total : 0;+ return (+ <nav className="stepper" aria-label="Progress">+ {items.map((it, i) => {+ const idx = PHASES.indexOf(it.id);+ const state = idx < cur ? "done" : idx === cur ? "now" : "next";+ const can = idx <= reached && idx !== cur && it.id !== "done";+ return (+ <div key={it.id} className="stp-wrap">+ {i > 0 && <span className={"stp-line" + (idx <= cur ? " on" : "")} />}+ <button className={"stp " + state} disabled={!can} onClick={() => onJump(it.id)} aria-current={state === "now" ? "step" : undefined}>+ {state === "now" && <motion.span layoutId="stp-bg" className="stp-bg" transition={{ type: "spring", stiffness: 460, damping: 38 }} />}+ <span className="stp-ico">{state === "done" ? <ICheck size={14} strokeWidth={3} /> : it.icon}</span>+ <span className="stp-label">{it.label}</span>+ {it.id === "steps" && phase === "steps" && (+ <span className="stp-count">+ {step + 1}/{total}+ </span>+ )}+ {it.id === "steps" && (phase === "steps" || phase === "done") && (+ <span className="stp-bar">+ <motion.i initial={false} animate={{ scaleX: pct }} transition={{ type: "spring", stiffness: 160, damping: 24 }} />+ </span>+ )}+ </button>+ </div>+ );+ })}+ </nav>+ );+}diff --git a/src/components/guide/HelpSheet.tsx b/src/components/guide/HelpSheet.tsxnew file mode 100644index 0000000..2bec080--- /dev/null+++ b/src/components/guide/HelpSheet.tsx@@ -0,0 +1,214 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { AnimatePresence, motion } from "motion/react";+import type { Plan } from "@/lib/types";+import { faqFor } from "@/lib/faq";+import { stepContents } from "@/lib/plan/contents";+import { ICamera, IChevronDown, IClose, ISend, ISparkle } from "../art/Icons";+import { Figure } from "../art/Figure";+import { keyHeaders } from "@/lib/userKey";++interface Msg {+ role: "user" | "assistant";+ content: string;+ image?: string;+}++export function helpContext(plan: Plan, index: number) {+ const s = plan.spec;+ const lines = [`Product: ${s.name}, ${s.variant} (${s.category}), ${s.size.w} x ${s.size.h} x ${s.size.d} cm.`];+ if (index >= 0) {+ const st = plan.steps[index];+ const c = stepContents(plan, index);+ lines.push(`Current step ${index + 1} of ${plan.steps.length}: ${st.title}. ${st.detail ?? ""}`);+ if (st.repeat) lines.push(`This step is repeated ${st.repeat} times.`);+ if (c.parts.length) lines.push("Parts in this step: " + c.parts.map((p) => `${p.type.label} ${p.type.name} x${p.count}`).join(", "));+ if (c.hardware.length) lines.push("Hardware in this step: " + c.hardware.map((h) => `${h.type.name} ${h.type.spec} x${h.count}`).join(", "));+ if (st.tools.length) lines.push("Tools: " + st.tools.join(", "));+ if (index > 0) lines.push(`Previous step: ${plan.steps[index - 1].title}.`);+ }+ lines.push("All panels: " + plan.parts.filter((p) => !p.extra).map((p) => `${p.label} ${p.name} x${p.qty}`).join(", "));+ lines.push("All hardware: " + plan.hardware.map((h) => `${h.name} ${h.spec} x${h.qty}${h.notIncluded ? " (not included)" : ""}`).join(", "));+ return lines.join("\n");+}++async function shrink(file: File): Promise<string> {+ const url = URL.createObjectURL(file);+ try {+ const img = await new Promise<HTMLImageElement>((res, rej) => {+ const i = new Image();+ i.onload = () => res(i);+ i.onerror = rej;+ i.src = url;+ });+ const k = Math.min(1, 1024 / Math.max(img.width, img.height));+ const c = document.createElement("canvas");+ c.width = Math.round(img.width * k);+ c.height = Math.round(img.height * k);+ c.getContext("2d")!.drawImage(img, 0, 0, c.width, c.height);+ return c.toDataURL("image/jpeg", 0.82);+ } finally {+ URL.revokeObjectURL(url);+ }+}++export default function HelpSheet({ plan, index, ai, onClose, focusMissing }: { plan: Plan; index: number; ai: boolean; onClose: () => void; focusMissing?: boolean }) {+ const kind = index >= 0 ? plan.steps[index].kind : "general";+ const faqs = faqFor(kind);+ const [open, setOpen] = useState<number | null>(focusMissing ? faqs.length - 2 : null);+ const [msgs, setMsgs] = useState<Msg[]>([]);+ const [q, setQ] = useState("");+ const [busy, setBusy] = useState(false);+ const file = useRef<HTMLInputElement>(null);+ const scroller = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ useEffect(() => {+ scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: "smooth" });+ }, [msgs]);++ async function ask(question: string, image?: string) {+ if (busy || (!question.trim() && !image)) return;+ const history = msgs.map((m) => ({ role: m.role, content: m.content }));+ const next: Msg[] = [...msgs, { role: "user", content: question || "Which part is this?", image }, { role: "assistant", content: "" }];+ setMsgs(next);+ setQ("");+ setBusy(true);+ try {+ const res = await fetch("/api/help", {+ method: "POST",+ headers: { "Content-Type": "application/json", ...keyHeaders() },+ body: JSON.stringify({ context: helpContext(plan, index), question: question || "Which part is this? Match it to the parts list.", history, image }),+ });+ if (!res.ok || !res.body) throw new Error(String(res.status));+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ let text = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ text += dec.decode(value, { stream: true });+ setMsgs((m) => {+ const c = [...m];+ c[c.length - 1] = { role: "assistant", content: text };+ return c;+ });+ }+ if (!text.trim()) throw new Error("empty");+ } catch {+ setMsgs((m) => {+ const c = [...m];+ c[c.length - 1] = { role: "assistant", content: "I couldn't reach the helper just now. Try the quick answers above, or ask again in a moment." };+ return c;+ });+ } finally {+ setBusy(false);+ }+ }++ return (+ <motion.div className="sheet-back" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={onClose}>+ <motion.aside+ className="side-sheet"+ role="dialog"+ aria-label="Help"+ initial={{ x: 40, opacity: 0 }}+ animate={{ x: 0, opacity: 1 }}+ exit={{ x: 40, opacity: 0 }}+ transition={{ type: "spring", stiffness: 380, damping: 36 }}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="sheet-head">+ <Figure pose="think" bubble="?" size={64} />+ <div>+ <h2>{index >= 0 ? `Stuck on step ${index + 1}?` : "Need a hand?"}</h2>+ <p className="sub">{index >= 0 ? plan.steps[index].title : "Common questions while unpacking."}</p>+ </div>+ <button className="btn round small" onClick={onClose} aria-label="Close help">+ <IClose />+ </button>+ </div>+ <div className="sheet-body" ref={scroller}>+ <div className="faq">+ {faqs.map((f, i) => (+ <div key={f.q} className={"faq-item" + (open === i ? " open" : "")}>+ <button onClick={() => setOpen(open === i ? null : i)} aria-expanded={open === i}>+ <span>{f.q}</span>+ <IChevronDown size={18} />+ </button>+ <AnimatePresence initial={false}>+ {open === i && (+ <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.25, ease: [0.22, 1, 0.36, 1] }}>+ <p>{f.a}</p>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ ))}+ </div>++ <div className="ask-head">+ <ISparkle size={18} />+ <b>Ask about this step</b>+ <span className="muted">{ai ? "Answers by Together AI" : "Needs a Together AI key"}</span>+ </div>+ {msgs.length === 0 && ai && (+ <div className="ask-suggest">+ {["The panels don't line up", "Which screw goes where?", "Is it normal to have parts left over?"].map((s) => (+ <button key={s} className="chip" onClick={() => ask(s)}>+ {s}+ </button>+ ))}+ </div>+ )}+ <div className="msgs">+ {msgs.map((m, i) => (+ <motion.div key={i} className={"msg " + m.role} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {m.image && <img src={m.image} alt="Your photo" />}+ {m.content ? <p>{m.content}</p> : <span className="typing">Thinking</span>}+ </motion.div>+ ))}+ </div>+ {!ai && <p className="note">Live answers switch on when the server has a Together AI key. The quick answers above always work.</p>}+ </div>+ <form+ className="ask-bar"+ onSubmit={(e) => {+ e.preventDefault();+ ask(q);+ }}+ >+ <button type="button" className="btn round small" onClick={() => file.current?.click()} disabled={!ai || busy} aria-label="Which part is this? Take a photo" title="Which part is this?">+ <ICamera />+ </button>+ <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder={ai ? "Type your question" : "Live answers are off"} disabled={!ai} aria-label="Your question" />+ <button type="submit" className="btn round small primary" disabled={!ai || busy || !q.trim()} aria-label="Send">+ <ISend />+ </button>+ <input+ ref={file}+ type="file"+ accept="image/*"+ capture="environment"+ hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (!f) return;+ const img = await shrink(f);+ ask("Which part is this?", img);+ }}+ />+ </form>+ </motion.aside>+ </motion.div>+ );+}diff --git a/src/components/guide/Loader.tsx b/src/components/guide/Loader.tsxnew file mode 100644index 0000000..bae5541--- /dev/null+++ b/src/components/guide/Loader.tsx@@ -0,0 +1,53 @@+"use client";++import { useEffect, useState } from "react";+import { AnimatePresence, motion } from "motion/react";+import { Figure } from "../art/Figure";+import { ISparkle } from "../art/Icons";++/** Shown while Together AI works out an unknown product: a flat pack box opening, panels peeking out. */+export default function Loader({ query, ai }: { query: string; ai: boolean }) {+ const lines = [`Looking up ${query.toUpperCase()}`, "Reading the measurements", "Sorting the hardware", "Counting the fittings", "Drawing the steps"];+ const [i, setI] = useState(0);+ useEffect(() => {+ const t = setInterval(() => setI((x) => Math.min(lines.length - 1, x + 1)), 1700);+ return () => clearInterval(t);+ }, [lines.length]);+ return (+ <div className="loader">+ <div className="loader-art">+ <svg viewBox="0 0 260 190" width="260" height="190" aria-hidden="true">+ <g className="ld-panels">+ <path className="p1" d="M92 96 l40 -78 l14 6 l-40 78 z" fill="#fff" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path className="p2" d="M120 98 l18 -84 l15 3 l-18 84 z" fill="var(--accent-soft)" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path className="p3" d="M146 100 l-6 -76 l15 -1 l6 76 z" fill="#fff" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ </g>+ <path d="M40 92 L130 120 L220 92 L220 160 L130 188 L40 160 Z" fill="#fff" stroke="var(--ink)" strokeWidth="2.4" strokeLinejoin="round" />+ <path d="M130 120 V188" stroke="var(--ink)" strokeWidth="2.2" />+ <path d="M40 92 L130 66 L220 92" fill="none" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path className="flap-l" d="M40 92 L130 120 L106 140 L16 112 Z" fill="#f1efe9" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path className="flap-r" d="M220 92 L130 120 L154 140 L244 112 Z" fill="#f1efe9" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <path d="M70 150 l26 8 M70 158 l18 5.5" stroke="var(--ink)" strokeWidth="1.6" strokeLinecap="round" opacity="0.5" />+ </svg>+ <div className="loader-fig">+ <Figure pose="read" size={92} />+ </div>+ </div>+ <div className="loader-text" aria-live="polite">+ <AnimatePresence mode="wait">+ <motion.p key={i} initial={{ y: 12, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: -12, opacity: 0 }} transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}>+ {lines[i]}+ </motion.p>+ </AnimatePresence>+ <div className="loader-bar">+ <span style={{ width: `${((i + 1) / lines.length) * 100}%` }} />+ </div>+ {ai && (+ <span className="ai-badge quiet">+ <ISparkle size={15} /> Thinking with Together AI+ </span>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/guide/Overview.tsx b/src/components/guide/Overview.tsxnew file mode 100644index 0000000..2ba221f--- /dev/null+++ b/src/components/guide/Overview.tsx@@ -0,0 +1,61 @@+"use client";++import { useEffect } from "react";+import { motion } from "motion/react";+import type { Plan } from "@/lib/types";+import Thumb from "../Thumb";+import { ICheck, IClose } from "../art/Icons";++export default function Overview({ plan, current, doneUpTo, onPick, onClose }: { plan: Plan; current: number; doneUpTo: number; onPick: (i: number) => void; onClose: () => void }) {+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);+ const id = plan.spec.name + plan.spec.variant;+ return (+ <motion.div className="overlay-back" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={onClose}>+ <motion.div+ className="overview"+ role="dialog"+ aria-label="All steps"+ initial={{ y: 30, opacity: 0 }}+ animate={{ y: 0, opacity: 1 }}+ exit={{ y: 20, opacity: 0 }}+ transition={{ type: "spring", stiffness: 340, damping: 34 }}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="overview-head">+ <div>+ <h2>All steps</h2>+ <p className="sub">Like flipping through the manual. Tap any page to jump there.</p>+ </div>+ <button className="btn round small" onClick={onClose} aria-label="Close">+ <IClose />+ </button>+ </div>+ <div className="overview-grid">+ {plan.steps.map((s, i) => (+ <motion.button+ key={i}+ className={"page" + (i === current ? " current" : "") + (i < doneUpTo ? " done" : "")}+ onClick={() => onPick(i)}+ initial={{ opacity: 0, y: 12 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ delay: Math.min(0.4, i * 0.025) }}+ >+ <span className="page-n">{i + 1}</span>+ {i < doneUpTo && (+ <span className="page-done">+ <ICheck size={14} strokeWidth={3} />+ </span>+ )}+ <Thumb id={id} plan={plan} mode={{ kind: "step", index: i }} w={260} h={190} className="page-thumb" />+ <span className="page-title">{s.title}</span>+ </motion.button>+ ))}+ </div>+ </motion.div>+ </motion.div>+ );+}diff --git a/src/components/guide/PartsPanel.tsx b/src/components/guide/PartsPanel.tsxnew file mode 100644index 0000000..616266c--- /dev/null+++ b/src/components/guide/PartsPanel.tsx@@ -0,0 +1,248 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { AnimatePresence, motion } from "motion/react";+import type { Plan } from "@/lib/types";+import { HwArt, canActualSize } from "../art/Hardware";+import { IAlert, IArrowLeft, IArrowRight, ICheck, IClose, IRuler } from "../art/Icons";+import Thumb from "../Thumb";+import { haptic } from "./hooks";+import { playTick } from "./sound";+import { getPref, setPref } from "@/lib/store";++/**+ * Parts are an exception check too: tap only what is missing.+ * "Everything's here" ticks the whole list in a quick cascade.+ */+export default function PartsPanel({+ plan,+ missing,+ onToggle,+ onNext,+ onBack,+ onHover,+ onMissingHelp,+}: {+ plan: Plan;+ missing: Set<string>;+ onToggle: (id: string) => void;+ onNext: () => void;+ onBack: () => void;+ onHover: (ids: string[] | null) => void;+ onMissingHelp: () => void;+}) {+ const panels = plan.parts.filter((p) => !p.extra);+ const hw = plan.hardware.filter((h) => !h.notIncluded);+ const extra = plan.hardware.filter((h) => h.notIncluded);+ const ids = [...panels.map((p) => p.id), ...hw.map((h) => h.id)];+ const [actual, setActual] = useState(false);+ const [ppm, setPpm] = useState(() => getPref("ppm", 96 / 25.4));+ const [calib, setCalib] = useState(false);+ const [ok, setOk] = useState<Set<string>>(new Set());+ const [going, setGoing] = useState(false);+ const timers = useRef<ReturnType<typeof setTimeout>[]>([]);+ useEffect(() => () => timers.current.forEach(clearTimeout), []);+ const nMissing = ids.filter((i) => missing.has(i)).length;++ const confirm = () => {+ if (going) return;+ setGoing(true);+ const list = ids.filter((i) => !missing.has(i));+ const gap = Math.min(70, 900 / Math.max(1, list.length));+ list.forEach((id, i) =>+ timers.current.push(+ setTimeout(() => {+ setOk((s) => new Set(s).add(id));+ if (i % 2 === 0) playTick();+ haptic(4);+ }, 60 + i * gap),+ ),+ );+ timers.current.push(setTimeout(onNext, 60 + list.length * gap + 420));+ };++ const row = (id: string, i: number, content: React.ReactNode, qty: number) => {+ const miss = missing.has(id);+ const good = ok.has(id);+ return (+ <motion.button+ key={id}+ className={"prow" + (miss ? " miss" : "") + (good ? " ok" : "")}+ onClick={() => {+ if (going) return;+ haptic();+ onToggle(id);+ }}+ onMouseEnter={() => onHover([id])}+ onMouseLeave={() => onHover(null)}+ onFocus={() => onHover([id])}+ onBlur={() => onHover(null)}+ aria-pressed={miss}+ aria-label={`${miss ? "Marked missing" : "Mark missing"}`}+ initial={{ opacity: 0, x: 12 }}+ animate={{ opacity: 1, x: 0 }}+ transition={{ delay: Math.min(0.5, 0.03 * i), duration: 0.35, ease: [0.22, 1, 0.36, 1] }}+ >+ {content}+ <span className="pqty">{qty}×</span>+ <span className="pstate">+ <AnimatePresence mode="popLayout" initial={false}>+ {miss ? (+ <motion.span key="m" className="pmiss" initial={{ scale: 0.6, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.6, opacity: 0 }}>+ Missing+ </motion.span>+ ) : good ? (+ <motion.span key="o" className="pok" initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: "spring", stiffness: 600, damping: 20 }}>+ <ICheck size={15} strokeWidth={3} />+ </motion.span>+ ) : (+ <motion.span key="n" className="pdot" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} />+ )}+ </AnimatePresence>+ </span>+ </motion.button>+ );+ };++ return (+ <div className="pane">+ <div className="pane-scroll">+ <header className="pane-head">+ <p className="eyebrow">Unpack</p>+ <h2>Check the box</h2>+ <p className="sub">Lay everything out like the drawing. Tap anything that's missing.</p>+ </header>++ <h3 className="section-title">+ Panels <span className="count-pill">{panels.reduce((s, p) => s + p.qty, 0)}</span>+ </h3>+ <div className="plist">+ {panels.map((p, i) =>+ row(+ p.id,+ i,+ <>+ <Thumb id={plan.spec.name + plan.spec.variant} plan={plan} mode={{ kind: "part", ref: p.id }} w={120} h={84} className="pthumb" />+ <span className="letter sm">{p.label}</span>+ <span className="ptext">+ <b>{p.name}</b>+ <span>{dims(p.size)}</span>+ </span>+ </>,+ p.qty,+ ),+ )}+ </div>++ <h3 className="section-title">+ Hardware <span className="count-pill">{hw.reduce((s, h) => s + h.qty, 0)}</span>+ <button className={"toggle" + (actual ? " on" : "")} onClick={() => setActual(!actual)} aria-pressed={actual}>+ <IRuler size={15} /> Actual size+ </button>+ </h3>+ {actual && (+ <p className="note">+ Lay a piece on the screen to compare.{" "}+ <button className="btn link inline" onClick={() => setCalib(true)}>+ Calibrate+ </button>+ </p>+ )}+ <div className={"plist" + (actual ? " actual" : "")}>+ {hw.map((h, i) =>+ row(+ h.id,+ panels.length + i,+ <>+ <span className="part-art">{actual && canActualSize(h.kind) ? <HwArt kind={h.kind} len={h.len} dia={h.dia} pxPerMm={ppm} /> : <HwArt kind={h.kind} len={h.len} dia={h.dia} fit={56} />}</span>+ <span className="ptext">+ <b>{h.name}</b>+ <span>{h.spec || " "}</span>+ </span>+ </>,+ h.qty,+ ),+ )}+ </div>++ {extra.length > 0 && (+ <div className="notbox">+ <IAlert size={18} />+ <div>+ <b>Not in the box</b>+ <span>Wall screws and plugs for fixing it to the wall. Pick ones that suit your wall.</span>+ </div>+ </div>+ )}++ <AnimatePresence>+ {nMissing > 0 && (+ <motion.div className="missbox" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: 8 }}>+ <b>+ {nMissing} {nMissing === 1 ? "thing" : "things"} missing+ </b>+ <span>You can still build the steps that don't need {nMissing === 1 ? "it" : "them"}. Spare fittings are usually free at IKEA.</span>+ <button className="btn link inline" onClick={onMissingHelp}>+ How to get spare parts+ </button>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ <div className="pane-foot">+ <button className="btn round" onClick={onBack} aria-label="Back">+ <IArrowLeft />+ </button>+ <button className={"btn primary big" + (going ? " going" : "")} onClick={confirm}>+ <span>{going ? "All set" : nMissing ? "Continue anyway" : "Everything's here"}</span>+ <IArrowRight />+ </button>+ </div>++ <AnimatePresence>+ {calib && (+ <Calibrate+ ppm={ppm}+ onClose={(v) => {+ if (v) {+ setPpm(v);+ setPref("ppm", v);+ }+ setCalib(false);+ }}+ />+ )}+ </AnimatePresence>+ </div>+ );+}++function dims(s: [number, number, number]) {+ const v = [...s].sort((a, b) => b - a).map((x) => Math.round(x / 10));+ return v[2] < 1 ? `${v[0]} × ${v[1]} cm` : `${v[0]} × ${v[1]} × ${Math.max(1, v[2])} cm`;+}++function Calibrate({ ppm, onClose }: { ppm: number; onClose: (v?: number) => void }) {+ const [v, setV] = useState(ppm);+ const w = 85.6 * v, h = 53.98 * v;+ return (+ <motion.div className="modal-back" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => onClose()}>+ <motion.div className="modal" initial={{ y: 30, scale: 0.98 }} animate={{ y: 0, scale: 1 }} exit={{ y: 20, opacity: 0 }} onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Calibrate actual size">+ <button className="btn round small close" onClick={() => onClose()} aria-label="Close">+ <IClose />+ </button>+ <h3>Match a bank card</h3>+ <p className="sub">Hold any card against the screen and slide until the outline matches its edges.</p>+ <div className="calib-stage">+ <div className="calib-card" style={{ width: w, height: h }}>+ <span />+ </div>+ </div>+ <input type="range" min={2.4} max={7.5} step={0.01} value={v} onChange={(e) => setV(Number(e.target.value))} aria-label="Card size" />+ <button className="btn primary" onClick={() => onClose(v)}>+ Looks right+ </button>+ </motion.div>+ </motion.div>+ );+}diff --git a/src/components/guide/StepPanel.tsx b/src/components/guide/StepPanel.tsxnew file mode 100644index 0000000..5095582--- /dev/null+++ b/src/components/guide/StepPanel.tsx@@ -0,0 +1,214 @@+"use client";++import { motion } from "motion/react";+import type { Plan, StepKind, TipKey, WarnId } from "@/lib/types";+import { stepContents } from "@/lib/plan/contents";+import { HwArt } from "../art/Hardware";+import { ToolArt, TOOL_INFO } from "../art/Tools";+import { IArrowLeft, IArrowRight, ICheck, IClock, IHelp, ISparkle, WarnIcon, WARN_TEXT } from "../art/Icons";+import { TwoPeople } from "../art/Figure";+import Thumb from "../Thumb";++const TIP_FOR: Partial<Record<StepKind, TipKey>> = {+ join: "frame",+ cams: "frame",+ dowels: "frame",+ bolts: "frame",+ nails: "back",+ square: "back",+ shelves: "shelves",+ drawer: "drawers",+ runners: "drawers",+ doors: "doors",+ hinges: "doors",+ legs: "legs",+ slats: "slats",+ anchor: "anchor",+};++export function tipFor(plan: Plan, index: number) {+ const s = plan.steps[index];+ const key = TIP_FOR[s.kind];+ if (!key || !plan.spec.tips?.[key]) return index === 0 ? plan.spec.tips?.general : undefined;+ const first = plan.steps.findIndex((x) => TIP_FOR[x.kind] === key);+ return first === index ? plan.spec.tips[key] : undefined;+}++export function minutesLeft(plan: Plan, index: number) {+ return plan.steps.slice(index).reduce((s, x) => s + x.minutes, 0);+}++export default function StepPanel({+ plan,+ index,+ dir,+ onNext,+ onBack,+ onHover,+ onHelp,+}: {+ plan: Plan;+ index: number;+ dir: number;+ onNext: () => void;+ onBack: () => void;+ onHover: (ids: string[] | null) => void;+ onHelp: () => void;+}) {+ const s = plan.steps[index];+ const c = stepContents(plan, index);+ const last = index === plan.steps.length - 1;+ const tip = tipFor(plan, index);+ const isBig = (w: WarnId) => w === "two" || w === "tip" || w === "wall";+ const big = s.warnings.filter((w) => isBig(w) && !(w === "wall" && s.warnings.includes("tip")));+ const small = s.warnings.filter((w) => !isBig(w));+ const next = plan.steps[index + 1];+ const twoAhead = s.people === 1 ? plan.steps.slice(index + 1, index + 3).findIndex((x) => x.people === 2) : -1;+ const id = plan.spec.name + plan.spec.variant;+ const hasNeeds = c.parts.length + c.hardware.length + s.tools.length > 0;+ const left = minutesLeft(plan, index);++ return (+ <div className="pane step-pane">+ <div className="pane-scroll">+ <motion.div key={index} initial={{ opacity: 0, x: 22 * dir }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}>+ <header className="pane-head">+ <div className="step-meta">+ <span className="eyebrow">+ Step {index + 1} of {plan.steps.length}+ </span>+ <span className="time-pill" title="Time left for the whole build">+ <IClock size={14} /> {left < 60 ? `${left} min left` : `${Math.round(left / 6) / 10} h left`}+ </span>+ </div>+ <h2 className="step-title">{s.title}</h2>+ {s.detail && <p className="sub">{s.detail}</p>}+ </header>++ {s.repeat && s.repeat > 1 && (+ <div className="callout repeat">+ <span className="repeat-badge">{s.repeat}×</span>+ <span>+ Do this for all {s.repeat} {plan.spec.archetype === "drawers" ? "drawers" : "of them"}. Counts below are for one.+ </span>+ </div>+ )}++ {big.map((w) => (+ <div key={w} className={"callout warn " + w}>+ {w === "two" ? <TwoPeople size={36} /> : <WarnIcon id={w} size={36} />}+ <div>+ <b>{w === "two" ? "Grab a second person" : w === "tip" ? "This stops it tipping over" : "You'll need to drill"}</b>+ <span>{w === "two" ? "It's heavy or awkward for one." : w === "tip" ? "Kids climb. Always fix it to the wall." : "Fixings for your wall are not in the box."}</span>+ </div>+ </div>+ ))}++ {hasNeeds && (+ <>+ <h3 className="section-title">You need</h3>+ <ul className="needs">+ {c.parts.map(({ type, count }) => (+ <li key={type.id} onMouseEnter={() => onHover([type.id])} onMouseLeave={() => onHover(null)}>+ <Thumb id={id} plan={plan} mode={{ kind: "part", ref: type.id }} w={96} h={68} className="need-thumb" />+ <span className="letter sm">{type.label}</span>+ <span className="need-name">{type.name}</span>+ <span className="need-qty">{count}×</span>+ </li>+ ))}+ {c.hardware.map(({ type, count }) => (+ <li key={type.id} onMouseEnter={() => onHover([type.id])} onMouseLeave={() => onHover(null)}>+ <span className="need-art">+ <HwArt kind={type.kind} len={type.len} dia={type.dia} fit={40} />+ </span>+ <span className="need-name">+ {type.notIncluded ? (type.kind === "plug" ? "Wall plug" : "Wall screw") : type.name}+ {type.spec && <small>{type.spec}</small>}+ </span>+ <span className="need-qty">{count}×</span>+ </li>+ ))}+ {s.tools.map((t) => (+ <li key={t} className="tool">+ <span className="need-art">+ <ToolArt id={t} size={40} />+ </span>+ <span className="need-name">{TOOL_INFO[t].name}</span>+ </li>+ ))}+ </ul>+ </>+ )}++ {small.length > 0 && (+ <div className="warn-row">+ {small.map((w) => (+ <span key={w} className="warn-chip">+ <WarnIcon id={w} size={24} />+ {WARN_TEXT[w]}+ </span>+ ))}+ </div>+ )}++ {tip && (+ <div className="callout tip">+ <ISparkle size={18} />+ <span>{tip}</span>+ </div>+ )}++ {twoAhead >= 0 && (+ <p className="heads-up">+ <TwoPeople size={22} /> Heads up: step {index + 2 + twoAhead} needs a second pair of hands.+ </p>+ )}++ {next ? (+ <button className="upnext" onClick={onNext}>+ <span className="upnext-label">Up next</span>+ <span className="upnext-body">+ <Thumb id={id} plan={plan} mode={{ kind: "step", index: index + 1 }} w={150} h={110} className="upnext-thumb" />+ <span className="upnext-text">+ <b>{index + 2}</b>+ <span>{next.title}</span>+ </span>+ <IArrowRight size={18} />+ </span>+ </button>+ ) : (+ <div className="upnext final">+ <span className="upnext-label">Last step</span>+ <span className="upnext-body">+ <span className="upnext-text">+ <span>After this one, it's built.</span>+ </span>+ </span>+ </div>+ )}+ </motion.div>+ </div>+ <div className="pane-foot">+ <button className="btn round" onClick={onBack} aria-label="Previous step" title="Previous (left arrow)">+ <IArrowLeft />+ </button>+ <button className="btn primary big done-btn" onClick={onNext} title="Next (right arrow or space)">+ <span className="done-ico">+ <ICheck size={18} strokeWidth={2.8} />+ </span>+ <span className="done-label">{last ? "Done, finish up" : "Done, next step"}</span>+ <IArrowRight />+ </button>+ <div className="foot-row">+ <button className="btn link stuck" onClick={onHelp}>+ <IHelp size={17} /> Stuck?+ </button>+ <span className="kbd-hint" aria-hidden="true">+ <kbd>←</kbd>+ <kbd>→</kbd> to move, <kbd>R</kbd> to replay+ </span>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/guide/ToolsPanel.tsx b/src/components/guide/ToolsPanel.tsxnew file mode 100644index 0000000..48ecdf7--- /dev/null+++ b/src/components/guide/ToolsPanel.tsx@@ -0,0 +1,105 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { motion } from "motion/react";+import type { Plan, ToolId } from "@/lib/types";+import { ToolArt, TOOL_INFO } from "../art/Tools";+import { IArrowLeft, IArrowRight, ICheck, IRotate } from "../art/Icons";+import { haptic } from "./hooks";+import { playTick } from "./sound";++/**+ * Tools are an exception check: one tap says "I have everything".+ * Tapping a card flips it to show what to use instead.+ */+export default function ToolsPanel({ plan, onNext, onBack }: { plan: Plan; onNext: (have: ToolId[]) => void; onBack: () => void }) {+ const required = plan.tools.filter((t) => !t.optional);+ const optional = plan.tools.filter((t) => t.optional);+ const [flipped, setFlipped] = useState<ToolId | null>(null);+ const [checked, setChecked] = useState<Set<ToolId>>(new Set());+ const [going, setGoing] = useState(false);+ const timers = useRef<ReturnType<typeof setTimeout>[]>([]);+ useEffect(() => () => timers.current.forEach(clearTimeout), []);++ const confirm = () => {+ if (going) return;+ setGoing(true);+ setFlipped(null);+ const all = [...required, ...optional].map((t) => t.id);+ all.forEach((id, i) => {+ timers.current.push(+ setTimeout(() => {+ setChecked((s) => new Set(s).add(id));+ haptic(6);+ playTick();+ }, 90 + i * 85),+ );+ });+ timers.current.push(setTimeout(() => onNext(all), 90 + all.length * 85 + 380));+ };++ const card = (id: ToolId, i: number, small?: boolean) => {+ const t = plan.tools.find((x) => x.id === id)!;+ const info = TOOL_INFO[id];+ const on = checked.has(id);+ const flip = flipped === id;+ return (+ <motion.div+ key={id}+ className={"tcard" + (small ? " small" : "") + (on ? " on" : "")}+ initial={{ opacity: 0, y: 12 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ delay: 0.05 + i * 0.04, duration: 0.45, ease: [0.22, 1, 0.36, 1] }}+ >+ <button className={"tcard-inner" + (flip ? " flipped" : "")} onClick={() => !going && setFlipped(flip ? null : id)} aria-label={`${info.name}. ${flip ? "Hide" : "Show"} a workaround`}>+ <span className="tface front">+ <span className="tart">+ <ToolArt id={id} size={small ? 58 : 84} />+ </span>+ <span className="tname">{info.name}</span>+ <span className="thint">{t.why ?? info.hint}</span>+ {t.included && <span className="tbadge">In the box</span>}+ <motion.span className="tcheck" initial={false} animate={{ scale: on ? 1 : 0, opacity: on ? 1 : 0 }} transition={{ type: "spring", stiffness: 600, damping: 22 }}>+ <ICheck size={16} strokeWidth={3} />+ </motion.span>+ </span>+ <span className="tface back">+ <span className="tback-title">No {info.name.toLowerCase()}?</span>+ <span className="tback-text">{info.alt}</span>+ <span className="tback-flip">+ <IRotate size={14} /> Tap to flip back+ </span>+ </span>+ </button>+ </motion.div>+ );+ };++ return (+ <div className="pane">+ <div className="pane-scroll">+ <header className="pane-head">+ <p className="eyebrow">Before you start</p>+ <h2>Grab your tools</h2>+ <p className="sub">Missing one? Tap it for a workaround.</p>+ </header>+ <div className="tgrid">{required.map((t, i) => card(t.id, i))}</div>+ {optional.length > 0 && (+ <>+ <h3 className="section-title">Nice to have</h3>+ <div className="tgrid three">{optional.map((t, i) => card(t.id, required.length + i, true))}</div>+ </>+ )}+ </div>+ <div className="pane-foot">+ <button className="btn round" onClick={onBack} aria-label="Back">+ <IArrowLeft />+ </button>+ <button className={"btn primary big" + (going ? " going" : "")} onClick={confirm} autoFocus>+ <span>{going ? "Great, let's go" : "I have everything"}</span>+ <IArrowRight />+ </button>+ </div>+ </div>+ );+}diff --git a/src/components/guide/hooks.ts b/src/components/guide/hooks.tsnew file mode 100644index 0000000..470b5d4--- /dev/null+++ b/src/components/guide/hooks.ts@@ -0,0 +1,130 @@+"use client";++import { useEffect, useRef, useState } from "react";++/** Keeps the screen on while building. */+export function useWakeLock(active: boolean) {+ useEffect(() => {+ if (!active || typeof navigator === "undefined" || !("wakeLock" in navigator)) return;+ let lock: WakeLockSentinel | null = null;+ let cancelled = false;+ const get = async () => {+ try {+ lock = await navigator.wakeLock.request("screen");+ if (cancelled) lock.release();+ } catch {+ /* denied or unsupported */+ }+ };+ get();+ const onVis = () => {+ if (document.visibilityState === "visible" && !cancelled) get();+ };+ document.addEventListener("visibilitychange", onVis);+ return () => {+ cancelled = true;+ document.removeEventListener("visibilitychange", onVis);+ lock?.release().catch(() => {});+ };+ }, [active]);+}++type Cmd = "next" | "back" | "repeat" | "help" | "stop";++interface SR {+ continuous: boolean;+ interimResults: boolean;+ lang: string;+ start(): void;+ stop(): void;+ abort(): void;+ onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }> & { isFinal: boolean }>; resultIndex: number }) => void) | null;+ onend: (() => void) | null;+ onerror: ((e: { error: string }) => void) | null;+}++export function speechSupported() {+ if (typeof window === "undefined") return false;+ const w = window as unknown as { SpeechRecognition?: unknown; webkitSpeechRecognition?: unknown };+ return !!(w.SpeechRecognition || w.webkitSpeechRecognition);+}++/** Voice commands ("next", "back", "repeat", "help") and spoken step instructions. */+export function useHandsFree(enabled: boolean, onCmd: (c: Cmd) => void) {+ const cb = useRef(onCmd);+ useEffect(() => {+ cb.current = onCmd;+ });+ const [listening, setListening] = useState(false);+ const [heard, setHeard] = useState("");++ useEffect(() => {+ if (!enabled) return;+ const w = window as unknown as { SpeechRecognition?: new () => SR; webkitSpeechRecognition?: new () => SR };+ const Ctor = w.SpeechRecognition || w.webkitSpeechRecognition;+ if (!Ctor) return;+ let stop = false;+ let rec: SR | null = null;+ const start = () => {+ if (stop) return;+ rec = new Ctor();+ rec.continuous = true;+ rec.interimResults = false;+ rec.lang = "en-US";+ rec.onresult = (e) => {+ for (let i = e.resultIndex; i < e.results.length; i++) {+ const text = e.results[i][0].transcript.toLowerCase().trim();+ setHeard(text);+ if (/\b(next|done|continue|forward|okay next)\b/.test(text)) cb.current("next");+ else if (/\b(back|previous|go back)\b/.test(text)) cb.current("back");+ else if (/\b(repeat|again|replay|show me)\b/.test(text)) cb.current("repeat");+ else if (/\b(help|stuck)\b/.test(text)) cb.current("help");+ }+ };+ rec.onend = () => {+ setListening(false);+ if (!stop) setTimeout(start, 250);+ };+ rec.onerror = (e) => {+ if (e.error === "not-allowed" || e.error === "service-not-allowed") {+ stop = true;+ cb.current("stop");+ }+ };+ try {+ rec.start();+ setListening(true);+ } catch {+ /* already started */+ }+ };+ start();+ return () => {+ stop = true;+ rec?.abort();+ setListening(false);+ };+ }, [enabled]);++ return { listening, heard };+}++export function speak(text: string) {+ if (typeof window === "undefined" || !("speechSynthesis" in window)) return;+ window.speechSynthesis.cancel();+ const u = new SpeechSynthesisUtterance(text);+ u.rate = 1;+ u.pitch = 1;+ const voices = window.speechSynthesis.getVoices();+ const v = voices.find((x) => /en[-_](GB|US)/i.test(x.lang) && /natural|premium|enhanced|samantha|daniel/i.test(x.name)) ?? voices.find((x) => /^en/i.test(x.lang));+ if (v) u.voice = v;+ window.speechSynthesis.speak(u);+}++export function haptic(ms = 8) {+ try {+ navigator.vibrate?.(ms);+ } catch {+ /* ignore */+ }+}diff --git a/src/components/guide/sound.ts b/src/components/guide/sound.tsnew file mode 100644index 0000000..68714a0--- /dev/null+++ b/src/components/guide/sound.ts@@ -0,0 +1,63 @@+"use client";++import { getPref, setPref } from "@/lib/store";++let ctx: AudioContext | null = null;+let enabled: boolean | null = null;++export function soundOn() {+ if (enabled === null) enabled = getPref("sound", true);+ return enabled;+}+export function setSound(v: boolean) {+ enabled = v;+ setPref("sound", v);+}++function ac() {+ if (typeof window === "undefined") return null;+ if (!ctx) {+ const C = window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;+ if (!C) return null;+ ctx = new C();+ }+ if (ctx.state === "suspended") ctx.resume().catch(() => {});+ return ctx;+}++function blip(freq: number, at: number, dur: number, gain: number, type: OscillatorType = "sine") {+ const c = ac();+ if (!c) return;+ const t = c.currentTime + at;+ const o = c.createOscillator();+ const g = c.createGain();+ o.type = type;+ o.frequency.setValueAtTime(freq, t);+ o.frequency.exponentialRampToValueAtTime(freq * 0.92, t + dur);+ g.gain.setValueAtTime(0, t);+ g.gain.linearRampToValueAtTime(gain, t + 0.008);+ g.gain.exponentialRampToValueAtTime(0.0001, t + dur);+ o.connect(g).connect(c.destination);+ o.start(t);+ o.stop(t + dur + 0.02);+}++/** A soft wooden click, like a dowel seating. */+export function playTick() {+ if (!soundOn()) return;+ blip(880, 0, 0.06, 0.05, "triangle");+ blip(1320, 0.012, 0.05, 0.025, "sine");+}++/** Step done: two quick rising notes. */+export function playStep() {+ if (!soundOn()) return;+ blip(660, 0, 0.12, 0.06, "triangle");+ blip(990, 0.07, 0.16, 0.05, "triangle");+}++/** Finished: a small chord. */+export function playDone() {+ if (!soundOn()) return;+ [523, 659, 784, 1047].forEach((f, i) => blip(f, i * 0.07, 0.5, 0.045, "triangle"));+}diff --git a/src/components/guide/ui.tsx b/src/components/guide/ui.tsxnew file mode 100644index 0000000..cb55da0--- /dev/null+++ b/src/components/guide/ui.tsx@@ -0,0 +1,80 @@+"use client";++import { motion } from "motion/react";++/** Round check that fills and draws its tick. */+export function CheckDot({ on, size = 28 }: { on: boolean; size?: number }) {+ return (+ <span className={"checkdot" + (on ? " on" : "")} style={{ width: size, height: size }} aria-hidden="true">+ <svg viewBox="0 0 24 24" width={size} height={size}>+ <motion.circle+ cx="12"+ cy="12"+ r="10.5"+ initial={false}+ animate={{ fill: on ? "var(--ink)" : "rgba(255,255,255,1)", stroke: on ? "var(--ink)" : "var(--line-2)" }}+ strokeWidth="1.8"+ transition={{ duration: 0.18 }}+ />+ <motion.path+ d="M7 12.4l3.3 3.3L17.2 8.8"+ fill="none"+ stroke="#fff"+ strokeWidth="2.4"+ strokeLinecap="round"+ strokeLinejoin="round"+ initial={false}+ animate={{ pathLength: on ? 1 : 0, opacity: on ? 1 : 0 }}+ transition={{ duration: on ? 0.32 : 0.12, ease: [0.65, 0, 0.35, 1], delay: on ? 0.05 : 0 }}+ />+ </svg>+ </span>+ );+}++export function Count({ n }: { n: number }) {+ return (+ <span className="count" key={n}>+ <motion.span key={n} initial={{ y: 10, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ type: "spring", stiffness: 500, damping: 30 }}>+ {n}+ </motion.span>+ </span>+ );+}++export function Ring({ value, size = 44, label }: { value: number; size?: number; label?: React.ReactNode }) {+ const r = size / 2 - 3;+ const c = Math.PI * 2 * r;+ return (+ <span className="ring" style={{ width: size, height: size }}>+ <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">+ <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--line)" strokeWidth={4} />+ <motion.circle+ cx={size / 2}+ cy={size / 2}+ r={r}+ fill="none"+ stroke={value >= 1 ? "var(--ink)" : "var(--accent)"}+ strokeWidth={4}+ strokeLinecap="round"+ strokeDasharray={c}+ initial={false}+ animate={{ strokeDashoffset: c * (1 - value) }}+ transition={{ type: "spring", stiffness: 120, damping: 20 }}+ transform={`rotate(-90 ${size / 2} ${size / 2})`}+ />+ </svg>+ <span className="ring-label">{label}</span>+ </span>+ );+}++export function Dots({ value, max = 3 }: { value: number; max?: number }) {+ return (+ <span className="dots" aria-label={`Difficulty ${value} of ${max}`}>+ {Array.from({ length: max }, (_, i) => (+ <i key={i} className={i < value ? "on" : ""} />+ ))}+ </span>+ );+}diff --git a/src/components/home/FloorFeatures.tsx b/src/components/home/FloorFeatures.tsxnew file mode 100644index 0000000..36c0594--- /dev/null+++ b/src/components/home/FloorFeatures.tsx@@ -0,0 +1,162 @@+"use client";++import { useState } from "react";++const C = Math.cos(Math.PI / 6);+const S = 0.5;+const OX = 280;+const OY = 352;+type V = [number, number, number];+const P = ([x, y, z]: V): [number, number] => [OX + (x - z) * C, OY + (x + z) * S - y];+const path = (...pts: V[]) => "M" + pts.map((p) => P(p).map((n) => n.toFixed(1)).join(" ")).join(" L") + " Z";++/** Iso box faces we can see from the front corner: top, right (+x) and left (+z). */+function box(x0: number, x1: number, y0: number, y1: number, z0: number, z1: number) {+ return {+ top: path([x0, y1, z0], [x1, y1, z0], [x1, y1, z1], [x0, y1, z1]),+ right: path([x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]),+ left: path([x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]),+ };+}++const FEATURES = [+ { title: "Say “next”", text: "Voice control moves the steps along while your hands hold the panels." },+ { title: "The screen stays on", text: "No tapping with dusty fingers. It won't dim halfway through a step." },+ { title: "Which screw is this?", text: "Snap a photo of a loose part and we'll tell you where it goes." },+ { title: "Turn it around", text: "Drag any drawing to see it from the side, the back or underneath." },+];++const PHONE = { x0: -66, x1: 66, y0: 18, y1: 246, z0: 0, z1: 12 };+const BOX = box(-40, 104, 0, 34, -214, -78);+const STAND = box(-48, 48, 0, 18, -10, 34);+const PH = box(PHONE.x0, PHONE.x1, PHONE.y0, PHONE.y1, PHONE.z0, PHONE.z1);+const SCREEN = P([PHONE.x0, PHONE.y1, PHONE.z1]);+const LABEL = P([-4, 34, -150]);++// callout anchors (target) and badge positions+const CALLOUTS: { n: number; at: [number, number]; badge: [number, number] }[] = [+ { n: 1, at: [70, 112], badge: [40, 64] },+ { n: 2, at: [P([46, 226, 12])[0], P([46, 226, 12])[1]], badge: [384, 120] },+ { n: 3, at: [454, 410], badge: [526, 352] },+ { n: 4, at: [P([0, 92, 12])[0] - 2, P([0, 92, 12])[1] + 6], badge: [124, 300] },+];++export default function FloorFeatures() {+ const [on, setOn] = useState<number | null>(null);+ return (+ <section className="floor">+ <div className="floor-copy">+ <h2 className="sec-title">Works with your hands full</h2>+ <p className="floor-sub">Made for building on the floor, with a phone propped against the box.</p>+ <ol className="floor-list">+ {FEATURES.map((f, i) => (+ <li key={f.title} className={on === i + 1 ? "on" : ""} onMouseEnter={() => setOn(i + 1)} onMouseLeave={() => setOn(null)}>+ <span className="fl-n">{i + 1}</span>+ <span className="fl-text">+ <b>{f.title}</b>+ <span>{f.text}</span>+ </span>+ </li>+ ))}+ </ol>+ </div>++ <div className="floor-art" data-on={on ?? undefined}>+ <svg viewBox="0 0 600 460" aria-hidden="true">+ {/* ground shadow */}+ <ellipse cx="320" cy="392" rx="230" ry="30" fill="#efede7" />++ {/* the flat pack box lying behind */}+ <g strokeLinejoin="round" stroke="var(--ink)" strokeWidth="2.2">+ <path d={BOX.left} fill="#fff" />+ <path d={BOX.right} fill="#efede7" />+ <path d={BOX.top} fill="#fff" />+ </g>+ <g transform={`translate(${LABEL[0]} ${LABEL[1]}) matrix(${C} ${S} ${-C} ${S} 0 0)`}>+ <rect x="0" y="-14" width="58" height="28" rx="3" fill="var(--accent)" stroke="var(--ink)" strokeWidth="1.8" />+ <path d="M8 -4 h30 M8 4 h20" stroke="var(--ink)" strokeWidth="2" strokeLinecap="round" />+ </g>++ {/* stand */}+ <g strokeLinejoin="round" stroke="var(--ink)" strokeWidth="2.2">+ <path d={STAND.left} fill="#fff" />+ <path d={STAND.right} fill="#efede7" />+ <path d={STAND.top} fill="#fff" />+ </g>++ {/* phone */}+ <g strokeLinejoin="round" stroke="var(--ink)" strokeWidth="2.2">+ <path d={PH.right} fill="#efede7" />+ <path d={PH.top} fill="#fff" />+ <path d={PH.left} fill="#fff" />+ </g>+ <g transform={`translate(${SCREEN[0]} ${SCREEN[1]}) matrix(${C} ${S} 0 1 0 0)`} className="fa-screen">+ <rect x="8" y="8" width="116" height="212" rx="12" fill="#fff" stroke="var(--ink)" strokeWidth="1.6" />+ <text x="18" y="30" fontSize="10.5" fontWeight="600" fill="var(--ink-2)" fontFamily="var(--font)">+ Step 4 of 9+ </text>+ <g className="fa-sun">+ <circle cx="110" cy="26" r="3.4" fill="none" stroke="var(--ink)" strokeWidth="1.5" />+ <path d="M110 18.5v2M110 31.5v2M102.5 26h2M115.5 26h2M104.7 20.7l1.4 1.4M113.9 29.9l1.4 1.4M104.7 31.3l1.4-1.4M113.9 22.1l1.4-1.4" stroke="var(--ink)" strokeWidth="1.3" strokeLinecap="round" />+ </g>+ {/* mini KALLAX */}+ <g strokeLinejoin="round" stroke="var(--ink)" strokeWidth="1.6">+ <path d="M40 92 L76 71 L102 86 L66 107 Z" fill="#fff" />+ <path d="M66 107 L102 86 L102 132 L66 153 Z" fill="#efede7" />+ <path d="M40 92 L66 107 L66 153 L40 138 Z" fill="#fff" />+ <path d="M53 99.5 V145.5 M40 115 L66 130" fill="none" />+ </g>+ <g className="fa-rot">+ <path d="M32 160 Q66 182 106 154" fill="none" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round" />+ <path d="M101 149 L109 152 L104 159" fill="none" stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />+ </g>+ <rect x="18" y="186" width="96" height="4" rx="2" fill="#e8e6e0" stroke="none" />+ <rect x="18" y="186" width="43" height="4" rx="2" fill="var(--ink)" stroke="none" />+ <rect x="18" y="196" width="96" height="16" rx="8" fill="var(--ink)" stroke="none" />+ <text x="66" y="207.5" fontSize="9.5" fontWeight="600" fill="#fff" textAnchor="middle" fontFamily="var(--font)">+ Next+ </text>+ </g>++ {/* speech bubble */}+ <g className="fa-voice">+ <path d="M58 112 h92 a14 14 0 0 1 14 14 v12 a14 14 0 0 1 -14 14 h-58 l-16 14 l2 -14 h-20 a14 14 0 0 1 -14 -14 v-12 a14 14 0 0 1 14 -14 z" fill="#fff" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />+ <text x="104" y="138" fontSize="17" fontWeight="600" textAnchor="middle" fill="var(--ink)" fontFamily="var(--font)">+ “Next”+ </text>+ <path d="M174 118 q8 14 0 28 M184 110 q14 22 0 44" fill="none" stroke="var(--ink)" strokeWidth="2" strokeLinecap="round" />+ </g>++ {/* loose hardware on the floor */}+ <g className="fa-hw" stroke="var(--ink)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round">+ <g transform="translate(430 404) rotate(28)">+ <rect x="-4" y="-7" width="11" height="14" rx="2.5" fill="#fff" />+ <path d="M7 -3.5 H40 L44 0 L40 3.5 H7 Z" fill="#fff" />+ <path d="M14 -3.5 l2 7 M20 -3.5 l2 7 M26 -3.5 l2 7 M32 -3.5 l2 7" fill="none" strokeWidth="1.4" />+ </g>+ <g transform="translate(494 392) rotate(-22)">+ <rect x="-18" y="-5.5" width="36" height="11" rx="5.5" fill="#f6efd2" />+ <path d="M-11 -5.5 v11 M-4 -5.5 v11 M3 -5.5 v11 M10 -5.5 v11" fill="none" strokeWidth="1.2" />+ </g>+ <g transform="translate(516 426)">+ <ellipse cx="0" cy="0" rx="15" ry="9" fill="#fff" />+ <path d="M-7 -1.5 L6 2.5" fill="none" strokeWidth="2.4" />+ </g>+ </g>++ {/* callouts */}+ {CALLOUTS.map((c) => (+ <g key={c.n} className={"co co-" + c.n}>+ <path d={`M${c.badge[0]} ${c.badge[1]} L${c.at[0]} ${c.at[1]}`} className="co-line" />+ <circle cx={c.at[0]} cy={c.at[1]} r="3.4" className="co-dot" />+ <circle cx={c.badge[0]} cy={c.badge[1]} r="15" className="co-badge" />+ <text x={c.badge[0]} y={c.badge[1] + 5} textAnchor="middle" className="co-n">+ {c.n}+ </text>+ </g>+ ))}+ </svg>+ </div>+ </section>+ );+}diff --git a/src/components/home/HeroStage.tsx b/src/components/home/HeroStage.tsxnew file mode 100644index 0000000..bac6e39--- /dev/null+++ b/src/components/home/HeroStage.tsx@@ -0,0 +1,72 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";+import { AnimatePresence, motion } from "motion/react";+import StageView from "../StageView";+import { catalogSpec } from "@/lib/catalog";+import { buildPlan } from "@/lib/plan";+import type { StageMode } from "@/engine/stage";+import { IArrowRight } from "../art/Icons";++const SHOW = ["kallax-2x2", "malm-3-drawers", "bissa-shoe-cabinet-2-compartments", "lack-coffee-table", "kivik-3-seat-sofa", "billy-80x202"];+const HOLD = 3200;++/** A manual page that keeps building furniture by itself. Tabs pick what it builds. */+export default function HeroStage() {+ const [i, setI] = useState(0);+ const plans = useMemo(() => SHOW.map((s) => buildPlan(catalogSpec(s)!)), []);+ const plan = plans[i];+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const mode: StageMode = useMemo(() => ({ kind: "intro", dims: true }), []);++ useEffect(+ () => () => {+ if (timer.current) clearTimeout(timer.current);+ },+ [],+ );++ const pick = (k: number) => {+ if (timer.current) clearTimeout(timer.current);+ setI(k);+ };++ return (+ <div className="hero-visual">+ <div className="hero-sheet">+ <StageView+ key={i}+ plan={plan}+ mode={mode}+ options={{ interactive: false, labels: false, margins: { t: 20, r: 20, b: 90, l: 20 } }}+ onIntroDone={() => {+ timer.current = setTimeout(() => pick((i + 1) % plans.length), HOLD);+ }}+ className="hero-stage"+ />+ <div className="hero-cap">+ <AnimatePresence mode="wait">+ <motion.div key={i} className="hero-cap-text" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -6 }} transition={{ duration: 0.35 }}>+ <b>{plan.spec.name}</b>+ <span>+ {plan.spec.variant}, {plan.steps.length} steps+ </span>+ </motion.div>+ </AnimatePresence>+ <Link href={`/build/${SHOW[i]}`} className="hero-go">+ Build this <IArrowRight size={16} />+ </Link>+ </div>+ </div>+ <div className="hero-tabs" role="tablist" aria-label="Pick a product to watch">+ {plans.map((p, k) => (+ <button key={SHOW[k]} role="tab" aria-selected={k === i} className={"hero-tab" + (k === i ? " on" : "")} onClick={() => pick(k)}>+ {p.spec.name}+ {k === i && <motion.i layoutId="hero-tab" className="hero-tab-bg" transition={{ type: "spring", stiffness: 500, damping: 38 }} />}+ </button>+ ))}+ </div>+ </div>+ );+}diff --git a/src/components/home/HomeClient.tsx b/src/components/home/HomeClient.tsxnew file mode 100644index 0000000..016f13f--- /dev/null+++ b/src/components/home/HomeClient.tsx@@ -0,0 +1,9 @@+"use client";++import Search from "./Search";+import { useAiStatus } from "./Sections";++export function HeroSearch() {+ const ai = useAiStatus();+ return <Search ai={ai} />;+}diff --git a/src/components/home/Search.tsx b/src/components/home/Search.tsxnew file mode 100644index 0000000..57e4b24--- /dev/null+++ b/src/components/home/Search.tsx@@ -0,0 +1,223 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import { AnimatePresence, motion } from "motion/react";+import { searchCatalog, slugify, matchCatalog } from "@/lib/search";+import { CATALOG, toSpec } from "@/lib/catalog";+import { buildPlan } from "@/lib/plan";+import Thumb from "../Thumb";+import { keyHeaders } from "@/lib/userKey";+import { IArrowRight, ICamera, ISearch, ISparkle } from "../art/Icons";++const EXAMPLES = ["KALLAX", "MALM 3 drawers", "BILLY bookcase", "LACK side table", "HEMNES chest", "BRIMNES wardrobe"];++export default function Search({ ai, autoFocus }: { ai: boolean; autoFocus?: boolean }) {+ const router = useRouter();+ const [q, setQ] = useState("");+ const [focus, setFocus] = useState(false);+ const [sel, setSel] = useState(0);+ const [ph, setPh] = useState("");+ const [reading, setReading] = useState(false);+ const [msg, setMsg] = useState("");+ const input = useRef<HTMLInputElement>(null);+ const file = useRef<HTMLInputElement>(null);++ // typewriter placeholder+ useEffect(() => {+ if (q) return;+ let i = 0, c = 0, del = false;+ let t: ReturnType<typeof setTimeout>;+ const tick = () => {+ const w = EXAMPLES[i % EXAMPLES.length];+ if (!del) {+ c++;+ setPh(w.slice(0, c));+ if (c >= w.length) {+ del = true;+ t = setTimeout(tick, 1600);+ return;+ }+ t = setTimeout(tick, 70 + Math.random() * 60);+ } else {+ c--;+ setPh(w.slice(0, c));+ if (c <= 0) {+ del = false;+ i++;+ t = setTimeout(tick, 300);+ return;+ }+ t = setTimeout(tick, 32);+ }+ };+ t = setTimeout(tick, 600);+ return () => clearTimeout(t);+ }, [q]);++ const hits = useMemo(() => (q.trim() ? searchCatalog(q, 6) : []), [q]);+ const exact = useMemo(() => (q.trim() ? matchCatalog(q) : null), [q]);+ const showAi = q.trim().length >= 2 && !exact;+ const rows = hits.length + (showAi ? 1 : 0);++ function go(target?: string) {+ const text = (target ?? q).trim();+ if (!text) {+ input.current?.focus();+ return;+ }+ const m = matchCatalog(text);+ if (m?.slug) router.push(`/build/${m.slug}`);+ else router.push(`/build/${slugify(text)}?q=${encodeURIComponent(text)}`);+ }++ function choose(i: number) {+ if (i < hits.length) router.push(`/build/${hits[i].entry.slug}`);+ else go();+ }++ async function onPhoto(f: File) {+ setReading(true);+ setMsg("");+ try {+ const img = await shrink(f);+ const r = await fetch("/api/identify", { method: "POST", headers: { "Content-Type": "application/json", ...keyHeaders() }, body: JSON.stringify({ image: img }) });+ const j = await r.json();+ if (!r.ok) throw new Error(j.error);+ if (j.name) {+ setQ(j.query || j.name);+ setMsg(`Found ${j.name}${j.variant ? `, ${j.variant}` : ""}`);+ setTimeout(() => go(j.query || j.name), 650);+ } else setMsg("Couldn't read a name. Try a closer photo of the label.");+ } catch {+ setMsg(ai ? "Couldn't read that photo. Try again or type the name." : "Photo search needs Together AI on the server.");+ } finally {+ setReading(false);+ }+ }++ const open = focus && q.trim().length > 0 && rows > 0;++ return (+ <div className={"search" + (open ? " open" : "")}>+ <form+ className="search-box"+ onSubmit={(e) => {+ e.preventDefault();+ if (open && sel < rows) choose(sel);+ else go();+ }}+ >+ <ISearch size={24} className="search-ico" />+ <input+ ref={input}+ value={q}+ onChange={(e) => {+ setQ(e.target.value);+ setSel(0);+ }}+ onFocus={() => setFocus(true)}+ onBlur={() => setTimeout(() => setFocus(false), 150)}+ onKeyDown={(e) => {+ if (!open) return;+ if (e.key === "ArrowDown") {+ e.preventDefault();+ setSel((s) => (s + 1) % rows);+ } else if (e.key === "ArrowUp") {+ e.preventDefault();+ setSel((s) => (s - 1 + rows) % rows);+ } else if (e.key === "Escape") input.current?.blur();+ }}+ placeholder={reading ? "Reading your photo" : ph ? `Try ${ph}` : "Product name"}+ aria-label="Product name from your box"+ autoComplete="off"+ spellCheck={false}+ autoFocus={autoFocus}+ enterKeyHint="go"+ />+ <button type="button" className={"cam-btn" + (reading ? " busy" : "")} onClick={() => file.current?.click()} aria-label="Search with a photo of the box label" title="Snap the box label">+ <ICamera size={22} />+ </button>+ <button type="submit" className="go-btn" aria-label="Find assembly steps">+ <IArrowRight size={22} strokeWidth={2.4} />+ </button>+ <input+ ref={file}+ type="file"+ accept="image/*"+ capture="environment"+ hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (f) onPhoto(f);+ }}+ />+ </form>+ <AnimatePresence>{msg && <motion.p className="search-msg" initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>{msg}</motion.p>}</AnimatePresence>+ <AnimatePresence>+ {open && (+ <motion.ul className="suggest" role="listbox" initial={{ opacity: 0, y: -6, scale: 0.99 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: -6 }} transition={{ duration: 0.18 }}>+ {hits.map((h, i) => (+ <SuggestRow key={h.entry.slug} slug={h.entry.slug} name={h.entry.name} variant={h.entry.variant} minutes={h.entry.minutes} active={i === sel} onPick={() => choose(i)} onHover={() => setSel(i)} />+ ))}+ {showAi && (+ <li role="option" aria-selected={sel === hits.length} className={"suggest-row ai" + (sel === hits.length ? " active" : "")} onMouseDown={(e) => e.preventDefault()} onClick={() => go()} onMouseEnter={() => setSel(hits.length)}>+ <span className="s-ai">+ <ISparkle size={22} />+ </span>+ <span className="s-text">+ <b>Find “{q.trim()}”</b>+ <span>{ai ? "Together AI will work out the steps" : "Pick what it looks like, we'll do the rest"}</span>+ </span>+ <IArrowRight size={18} />+ </li>+ )}+ </motion.ul>+ )}+ </AnimatePresence>+ </div>+ );+}++function SuggestRow({ slug, name, variant, minutes, active, onPick, onHover }: { slug: string; name: string; variant: string; minutes: number; active: boolean; onPick: () => void; onHover: () => void }) {+ const plan = useMemo(() => {+ const spec = matchSlug(slug);+ return spec ? buildPlan(spec) : null;+ }, [slug]);+ return (+ <li role="option" aria-selected={active} className={"suggest-row" + (active ? " active" : "")} onMouseDown={(e) => e.preventDefault()} onClick={onPick} onMouseEnter={onHover}>+ <Thumb id={slug} plan={plan} mode={{ kind: "assembled" }} w={112} h={84} className="s-thumb" />+ <span className="s-text">+ <b>{name}</b>+ <span>{variant}</span>+ </span>+ <span className="s-min">{minutes} min</span>+ </li>+ );+}++function matchSlug(slug: string) {+ const e = CATALOG.find((c) => c.slug === slug);+ return e ? toSpec(e) : null;+}++async function shrink(file: File): Promise<string> {+ const url = URL.createObjectURL(file);+ try {+ const img = await new Promise<HTMLImageElement>((res, rej) => {+ const i = new Image();+ i.onload = () => res(i);+ i.onerror = rej;+ i.src = url;+ });+ const k = Math.min(1, 1280 / Math.max(img.width, img.height));+ const c = document.createElement("canvas");+ c.width = Math.round(img.width * k);+ c.height = Math.round(img.height * k);+ c.getContext("2d")!.drawImage(img, 0, 0, c.width, c.height);+ return c.toDataURL("image/jpeg", 0.85);+ } finally {+ URL.revokeObjectURL(url);+ }+}diff --git a/src/components/home/Sections.tsx b/src/components/home/Sections.tsxnew file mode 100644index 0000000..42b0c4a--- /dev/null+++ b/src/components/home/Sections.tsx@@ -0,0 +1,105 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { AnimatePresence, motion } from "motion/react";+import { POPULAR, fold } from "@/lib/search";+import { PRODUCTS, toSpec, type CatalogEntry } from "@/lib/catalog";+import { buildPlan } from "@/lib/plan";+import type { Archetype } from "@/lib/types";+import Thumb from "../Thumb";+import { getUserKey } from "@/lib/userKey";+import { Dots } from "../guide/ui";+import { IArrowRight, IClock, ISearch } from "../art/Icons";++export const CATS: { id: string; label: string; arch: Archetype[] }[] = [+ { id: "all", label: "All", arch: [] },+ { id: "shelves", label: "Shelves", arch: ["shelf"] },+ { id: "drawers", label: "Drawers", arch: ["drawers"] },+ { id: "storage", label: "Storage", arch: ["cabinet"] },+ { id: "tables", label: "Tables", arch: ["table"] },+ { id: "beds", label: "Beds", arch: ["bed"] },+ { id: "seating", label: "Seating", arch: ["seat", "sofa"] },+];++export function ProductCard({ e, i = 0 }: { e: CatalogEntry; i?: number }) {+ const lazyPlan = useMemo(() => () => buildPlan(toSpec(e)), [e]);+ return (+ <motion.div layout initial={{ opacity: 0, y: 14 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.97 }} transition={{ duration: 0.4, delay: Math.min(0.3, (i % 12) * 0.03), ease: [0.22, 1, 0.36, 1] }}>+ <Link href={`/build/${e.slug}`} className="pcard">+ <span className="pcard-art">+ <Thumb id={e.slug} plan={lazyPlan} mode={{ kind: "assembled" }} w={420} h={320} className="pcard-thumb" alt={`${e.name} line drawing`} lazy />+ </span>+ <span className="pcard-text">+ <span className="pcard-top">+ <b>{e.name}</b>+ <span className="pcard-go">+ <IArrowRight size={17} />+ </span>+ </span>+ <span className="pcard-variant">{e.variant}</span>+ <span className="pcard-meta">+ <span>+ <IClock size={15} /> {e.minutes < 60 ? `${e.minutes} min` : `${Math.round(e.minutes / 6) / 10} h`}+ </span>+ <Dots value={e.difficulty} />+ <span>{e.category}</span>+ </span>+ </span>+ </Link>+ </motion.div>+ );+}++/** Category tabs plus a grid. On the home page it shows a short pick; /browse shows everything with a filter. */+export function Catalog({ limit, search }: { limit?: number; search?: boolean }) {+ const [cat, setCat] = useState("all");+ const [q, setQ] = useState("");+ const list = useMemo(() => {+ const c = CATS.find((x) => x.id === cat)!;+ let l = c.arch.length ? PRODUCTS.filter((p) => c.arch.includes(p.archetype)) : limit ? POPULAR : PRODUCTS;+ const f = fold(q);+ if (f) l = l.filter((p) => fold([p.name, p.variant, p.category, ...(p.keywords ?? [])].join(" ")).includes(f));+ if (!limit) l = [...l].sort((a, b) => a.name.localeCompare(b.name, "sv"));+ return limit ? l.slice(0, limit) : l;+ }, [cat, q, limit]);+ return (+ <div className="catalog">+ <div className="cat-bar">+ <div className="cat-tabs" role="tablist">+ {CATS.map((c) => (+ <button key={c.id} role="tab" aria-selected={cat === c.id} className={"cat-tab" + (cat === c.id ? " on" : "")} onClick={() => setCat(c.id)}>+ {cat === c.id && <motion.i layoutId={"cat-bg" + (search ? "b" : "h")} className="cat-bg" transition={{ type: "spring", stiffness: 500, damping: 40 }} />}+ <span>{c.label}</span>+ </button>+ ))}+ </div>+ {search && (+ <label className="cat-search">+ <ISearch size={18} />+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Filter by name" aria-label="Filter products" />+ </label>+ )}+ </div>+ <motion.div layout className="pgrid">+ <AnimatePresence mode="popLayout">+ {list.map((e, i) => (+ <ProductCard key={e.slug} e={e} i={i} />+ ))}+ </AnimatePresence>+ </motion.div>+ {list.length === 0 && <p className="empty">Nothing matches. Try another name, or search for it on the home page.</p>}+ </div>+ );+}++export function useAiStatus() {+ const [ai, setAi] = useState(false);+ useEffect(() => {+ fetch("/api/status")+ .then((r) => r.json())+ .then((j) => setAi(!!j.ai || !!getUserKey()))+ .catch(() => {});+ }, []);+ return ai;+}diff --git a/src/components/scan/Scanner.tsx b/src/components/scan/Scanner.tsxnew file mode 100644index 0000000..2940daa--- /dev/null+++ b/src/components/scan/Scanner.tsx@@ -0,0 +1,540 @@+"use client";++import { useEffect, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { useRouter } from "next/navigation";+import { AnimatePresence, motion } from "motion/react";+import type { ProductSpec } from "@/lib/types";+import { buildPlan } from "@/lib/plan";+import { slugify } from "@/lib/search";+import { cacheSpec } from "@/lib/store";+import { getUserKey, setUserKey, subscribeKey } from "@/lib/userKey";+import Thumb from "../Thumb";+import { IArrowRight, ICamera, ICheck, IClose, IExternal, IImage, IKey, ILock, IPlus } from "../art/Icons";++const MAX_PAGES = 12;+const KEY_URL = "https://api.together.ai/settings/api-keys";++interface Page {+ id: string;+ url: string;+ label?: string;+ read?: boolean;+}++type Stage = "reading" | "planning" | "checking" | "fixing";+type Err = "key" | "credits" | "busy" | "unreadable" | "failed" | "pages";++const ERRORS: Record<Err, string> = {+ key: "Together AI didn't accept your key. Check it and try again.",+ credits: "Your Together AI account is out of credits. Top it up, then try again.",+ busy: "Too many scans at once. Give it a minute, then try again.",+ unreadable: "We couldn't read those photos. Try bright, flat, straight on shots of each page.",+ failed: "Something went wrong while drawing your guide. Try again.",+ pages: "Those photos didn't come through. Add them again.",+};++export default function Scanner() {+ const router = useRouter();+ const key = useSyncExternalStore(subscribeKey, getUserKey, () => "");+ const [pages, setPages] = useState<Page[]>([]);+ const [hint, setHint] = useState("");+ const [busy, setBusy] = useState(false);+ const [stage, setStage] = useState<Stage | null>(null);+ const [found, setFound] = useState<{ name?: string; brand?: string; parts?: number; steps?: number }>({});+ const [read, setRead] = useState(0);+ const [result, setResult] = useState<{ slug: string; spec: ProductSpec } | null>(null);+ const [err, setErr] = useState<Err | null>(null);+ const [started, setStarted] = useState(0);+ const [now, setNow] = useState(0);+ const [drag, setDrag] = useState(false);+ const ac = useRef<AbortController | null>(null);+ const files = useRef<HTMLInputElement>(null);+ const cam = useRef<HTMLInputElement>(null);+ const keyBox = useRef<{ edit: () => void } | null>(null);++ useEffect(() => {+ if (!busy) return;+ const t = setInterval(() => setNow(Date.now()), 500);+ return () => clearInterval(t);+ }, [busy]);+ useEffect(() => () => ac.current?.abort(), []);++ async function addFiles(list: FileList | File[]) {+ const room = MAX_PAGES - pages.length;+ const pick = [...list].filter((f) => f.type.startsWith("image/")).slice(0, room);+ const next: Page[] = [];+ for (const f of pick) {+ try {+ next.push({ id: Math.random().toString(36).slice(2), url: await shrink(f) });+ } catch {+ /* unreadable image */+ }+ }+ setPages((p) => [...p, ...next].slice(0, MAX_PAGES));+ setErr(null);+ }++ async function start() {+ if (!key) {+ keyBox.current?.edit();+ return;+ }+ if (!pages.length) {+ files.current?.click();+ return;+ }+ const c = new AbortController();+ ac.current = c;+ setBusy(true);+ setErr(null);+ setStage("reading");+ setFound({});+ setRead(0);+ setResult(null);+ setPages((p) => p.map((x) => ({ ...x, read: false, label: undefined })));+ const t0 = Date.now();+ window.scrollTo({ top: 0, behavior: "smooth" });+ setStarted(t0);+ setNow(t0);+ try {+ const res = await fetch("/api/scan", {+ method: "POST",+ headers: { "Content-Type": "application/json", "x-together-key": key },+ body: JSON.stringify({ pages: pages.map((p) => p.url), hint }),+ signal: c.signal,+ });+ if (!res.ok || !res.body) {+ const j = (await res.json().catch(() => ({}))) as { error?: Err };+ throw new Error(j.error ?? "failed");+ }+ const reader = res.body.getReader();+ const dec = new TextDecoder();+ let buf = "";+ let done: ProductSpec | null = null;+ for (;;) {+ const { value, done: end } = await reader.read();+ if (end) break;+ buf += dec.decode(value, { stream: true });+ let nl: number;+ while ((nl = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, nl).trim();+ buf = buf.slice(nl + 1);+ if (!line) continue;+ const ev = JSON.parse(line);+ if (ev.type === "stage") setStage(ev.stage);+ else if (ev.type === "page") {+ setRead(ev.read);+ setPages((p) => p.map((x, i) => (i === ev.index ? { ...x, read: true, label: ev.label } : x)));+ if (ev.product) setFound((f) => ({ ...f, name: f.name ?? ev.product, brand: f.brand ?? ev.brand }));+ } else if (ev.type === "drafted") setFound((f) => ({ ...f, name: ev.name ?? f.name, brand: ev.brand ?? f.brand, parts: ev.parts, steps: ev.steps }));+ else if (ev.type === "error") throw new Error(ev.code);+ else if (ev.type === "done") done = ev.spec;+ }+ }+ if (!done) throw new Error("failed");+ const slug = `scan-${slugify(done.name).slice(0, 30) || "build"}-${Math.random().toString(36).slice(2, 6)}`;+ const spec: ProductSpec = { ...done, slug, source: "scan" };+ cacheSpec(slug, spec);+ setResult({ slug, spec });+ if (navigator.vibrate) navigator.vibrate(18);+ } catch (e) {+ if (c.signal.aborted) return;+ const code = (e as Error).message as Err;+ setErr(code in ERRORS ? code : "failed");+ if (code === "key") keyBox.current?.edit();+ } finally {+ setBusy(false);+ setStage(null);+ }+ }++ function cancel() {+ ac.current?.abort();+ setBusy(false);+ setStage(null);+ setPages((p) => p.map((x) => ({ ...x, read: false, label: undefined })));+ }++ const plan = useMemo(() => {+ if (!result) return null;+ try {+ return buildPlan(result.spec);+ } catch {+ return null;+ }+ }, [result]);++ const elapsed = busy ? Math.max(0, Math.round((now - started) / 1000)) : 0;+ const working = busy || !!result;++ return (+ <div className="scan">+ <header className="scan-head">+ <h1>Scan a paper manual</h1>+ <p className="lead">For furniture that isn't from IKEA. Photograph the manual and Together AI turns it into a step by step guide in 3D.</p>+ </header>++ <AnimatePresence mode="wait" initial={false}>+ {!working ? (+ <motion.div key="form" className="scan-form" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -8 }} transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}>+ <section className="sf-row">+ <span className="sf-n">1</span>+ <div className="sf-body">+ <h2>Your Together AI key</h2>+ <KeyBox value={key} api={keyBox} />+ </div>+ </section>++ <section className="sf-row">+ <span className="sf-n">2</span>+ <div className="sf-body">+ <h2>Photos of the manual</h2>+ <p className="sf-help">Just the cover works. Every page gives an exact match.</p>+ <div+ className={"drop" + (drag ? " over" : "") + (pages.length ? " has" : "")}+ onDragOver={(e) => {+ e.preventDefault();+ setDrag(true);+ }}+ onDragLeave={() => setDrag(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDrag(false);+ addFiles(e.dataTransfer.files);+ }}+ >+ {pages.length === 0 ? (+ <div className="drop-empty">+ <ManualArt />+ <p>+ Drop photos here, or <button onClick={() => files.current?.click()}>choose them</button>+ </p>+ <button className="btn ghost cam-only" onClick={() => cam.current?.click()}>+ <ICamera size={18} /> Take a photo+ </button>+ </div>+ ) : (+ <ol className="pages">+ <AnimatePresence initial={false}>+ {pages.map((p, i) => (+ <motion.li key={p.id} layout initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.9 }} transition={{ duration: 0.22 }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={p.url} alt={`Page ${i + 1}`} />+ <span className="pg-n">{i + 1}</span>+ <button className="pg-x" onClick={() => setPages((x) => x.filter((y) => y.id !== p.id))} aria-label={`Remove page ${i + 1}`}>+ <IClose size={14} />+ </button>+ </motion.li>+ ))}+ </AnimatePresence>+ {pages.length < MAX_PAGES && (+ <li className="pg-add">+ <button onClick={() => files.current?.click()}>+ <IPlus size={20} />+ <span>Add</span>+ </button>+ <button className="cam-only" onClick={() => cam.current?.click()} aria-label="Take a photo">+ <ICamera size={20} />+ </button>+ </li>+ )}+ </ol>+ )}+ </div>+ <input ref={files} type="file" accept="image/*" multiple hidden onChange={(e) => e.target.files && addFiles(e.target.files).then(() => (e.target.value = ""))} />+ <input ref={cam} type="file" accept="image/*" capture="environment" hidden onChange={(e) => e.target.files && addFiles(e.target.files).then(() => (e.target.value = ""))} />+ <p className="sf-tip">+ <IImage size={15} /> Got a PDF? Screenshots of its pages work too. Up to {MAX_PAGES} pages.+ </p>+ </div>+ </section>++ <section className="sf-row">+ <span className="sf-n">3</span>+ <div className="sf-body">+ <h2>+ What is it? <span>Optional</span>+ </h2>+ <input className="sf-input" value={hint} onChange={(e) => setHint(e.target.value.slice(0, 80))} placeholder="Like “record player stand from Nordwood”" />+ </div>+ </section>++ <AnimatePresence>+ {err && (+ <motion.p className="scan-err" role="alert" initial={{ opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>+ {ERRORS[err]}+ {err === "credits" && (+ <a href="https://api.together.ai/settings/billing" target="_blank" rel="noreferrer">+ Billing <IExternal size={13} />+ </a>+ )}+ </motion.p>+ )}+ </AnimatePresence>++ <div className="scan-go">+ <button className="btn primary big" onClick={start}>+ <span>{!key ? "Add your key to start" : pages.length ? `Make my guide from ${pages.length} ${pages.length === 1 ? "photo" : "photos"}` : "Add photos to start"}</span>+ <IArrowRight />+ </button>+ <p>Takes about a minute. Uses your Together AI credits, usually a few cents.</p>+ </div>+ </motion.div>+ ) : (+ <motion.div key="work" className="scan-work" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}>+ {result && plan ? (+ <div className="sw-done">+ <motion.div className="sw-art" initial={{ opacity: 0, scale: 0.94 }} animate={{ opacity: 1, scale: 1 }} transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}>+ <Thumb id={"scan-" + result.slug} plan={plan} mode={{ kind: "assembled" }} w={520} h={380} className="sw-thumb" alt={result.spec.name} />+ </motion.div>+ <div className="sw-done-text">+ <span className="sw-ok">+ <ICheck size={16} strokeWidth={2.6} /> Guide ready+ </span>+ <h2>{result.spec.name}</h2>+ <p>+ {[result.spec.brand, result.spec.variant].filter(Boolean).join(", ")}. {plan.steps.length} steps, {plan.parts.reduce((s, p) => s + p.qty, 0)} parts, about {result.spec.minutes} minutes.+ </p>+ <div className="sw-actions">+ <button className="btn primary" onClick={() => router.push(`/build/${result.slug}`)}>+ Start building <IArrowRight size={18} />+ </button>+ <button+ className="btn ghost"+ onClick={() => {+ setResult(null);+ setPages([]);+ setHint("");+ }}+ >+ Scan another+ </button>+ </div>+ <p className="sw-note">Saved in this browser. Check each step against your paper manual.</p>+ </div>+ </div>+ ) : (+ <div className="sw-live">+ <div className="sw-stack" aria-hidden="true">+ {pages.slice(0, 8).map((p, i, list) => {+ const firstUnread = list.findIndex((x) => !x.read);+ const reading = stage === "reading" && i === firstUnread;+ const order = p.read ? list.filter((x) => x.read).indexOf(p) : i;+ const tilt = ((i * 37) % 7) - 3;+ return (+ <motion.div+ key={p.id}+ className={"sw-page" + (p.read ? " read" : "") + (reading ? " now" : "")}+ style={{ zIndex: p.read ? 20 + order : 20 - i }}+ initial={{ opacity: 0, y: 16, x: -54 }}+ animate={p.read ? { opacity: 1, y: -order * 2, x: 62, rotate: 3 + tilt * 0.6 } : { opacity: 1, y: (i - (firstUnread < 0 ? 0 : firstUnread)) * 3, x: -54, rotate: tilt }}+ transition={{ type: "spring", stiffness: 220, damping: 26, delay: p.read ? 0 : i * 0.05 }}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={p.url} alt="" />+ {reading && <span className="sw-scanline" />}+ {p.read && (+ <span className="sw-tag">+ <ICheck size={12} strokeWidth={3} /> {p.label ?? "Read"}+ </span>+ )}+ </motion.div>+ );+ })}+ </div>+ <ol className="sw-steps" aria-live="polite">+ <Row on={stage === "reading"} done={!!stage && stage !== "reading"} title={`Reading ${pages.length} ${pages.length === 1 ? "page" : "pages"}`} note={stage === "reading" ? `${read} of ${pages.length}` : found.name ? `Found ${found.name}${found.brand ? ` by ${found.brand}` : ""}` : undefined} />+ <Row on={stage === "planning"} done={stage === "checking" || stage === "fixing"} title="Working out the parts and steps" note={found.parts ? `${found.parts} parts, ${found.steps} steps` : stage === "planning" ? "The longest part" : undefined} />+ <Row on={stage === "checking" || stage === "fixing"} done={false} title="Checking it all fits" note={stage === "fixing" ? "Fixing a few joints" : undefined} />+ </ol>+ <div className="sw-foot">+ <span>+ {Math.floor(elapsed / 60)}:{String(elapsed % 60).padStart(2, "0")}+ </span>+ <button className="btn ghost sm" onClick={cancel}>+ Cancel+ </button>+ </div>+ </div>+ )}+ </motion.div>+ )}+ </AnimatePresence>++ <p className="scan-privacy">+ <ILock size={14} /> Your key and photos go straight to Together AI for this scan. We don't keep them. The finished guide is saved only in this browser.+ </p>+ </div>+ );+}++function Row({ on, done, title, note }: { on: boolean; done: boolean; title: string; note?: string }) {+ return (+ <li className={"sw-row" + (on ? " on" : "") + (done ? " done" : "")}>+ <span className="sw-ico">{done ? <ICheck size={14} strokeWidth={3} /> : on ? <span className="spin" /> : null}</span>+ <span className="sw-text">+ <b>{title}</b>+ <AnimatePresence mode="wait">+ {note && (+ <motion.span key={note} initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -4 }} transition={{ duration: 0.2 }}>+ {note}+ </motion.span>+ )}+ </AnimatePresence>+ </span>+ </li>+ );+}++function KeyBox({ value, api }: { value: string; api: React.RefObject<{ edit: () => void } | null> }) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");+ const [state, setState] = useState<"idle" | "checking" | "bad" | "offline">("idle");+ const input = useRef<HTMLInputElement>(null);+ const open = editing || !value;++ useImperativeHandle(api, () => ({+ edit: () => {+ setEditing(true);+ setTimeout(() => input.current?.focus(), 50);+ },+ }));++ async function save() {+ const k = draft.trim();+ if (!k) return;+ setState("checking");+ try {+ const r = await fetch("/api/key", { method: "POST", headers: { "x-together-key": k } });+ const j = (await r.json()) as { ok: boolean; reason?: string };+ if (j.ok || j.reason === "unavailable") {+ setUserKey(k);+ setDraft("");+ setEditing(false);+ setState(j.ok ? "idle" : "offline");+ } else setState("bad");+ } catch {+ setUserKey(k);+ setDraft("");+ setEditing(false);+ setState("offline");+ }+ }++ if (!open)+ return (+ <div className="key-saved">+ <span className="key-ico">+ <IKey size={17} />+ </span>+ <span className="key-text">+ <b>Key saved</b>+ <span>Ending in {value.slice(-4)}{state === "offline" ? ". We couldn't check it just now." : ""}</span>+ </span>+ <button className="link-btn" onClick={() => api.current?.edit()}>+ Change+ </button>+ <button className="link-btn" onClick={() => setUserKey("")}>+ Remove+ </button>+ </div>+ );++ return (+ <div className="key-edit">+ <form+ className={"key-field" + (state === "bad" ? " bad" : "")}+ onSubmit={(e) => {+ e.preventDefault();+ save();+ }}+ >+ <IKey size={17} />+ <input+ ref={input}+ type="password"+ value={draft}+ onChange={(e) => {+ setDraft(e.target.value);+ setState("idle");+ }}+ placeholder="Paste your key"+ aria-label="Together AI API key"+ autoComplete="off"+ spellCheck={false}+ />+ <button className="btn primary sm" type="submit" disabled={!draft.trim() || state === "checking"}>+ {state === "checking" ? "Checking" : "Save"}+ </button>+ {value && (+ <button+ type="button"+ className="link-btn"+ onClick={() => {+ setEditing(false);+ setDraft("");+ setState("idle");+ }}+ >+ Cancel+ </button>+ )}+ </form>+ <p className={"sf-help" + (state === "bad" ? " bad" : "")}>+ {state === "bad" ? (+ "Together AI didn't accept that key. Copy it again from your dashboard."+ ) : (+ <>+ Scanning runs on your own key, so you control the cost.{" "}+ <a href={KEY_URL} target="_blank" rel="noreferrer">+ Get a key <IExternal size={12} />+ </a>+ </>+ )}+ </p>+ </div>+ );+}++function ManualArt() {+ return (+ <svg viewBox="0 0 180 110" width="180" height="110" aria-hidden="true">+ <g transform="rotate(-7 60 60)">+ <rect x="22" y="14" width="66" height="88" rx="3" fill="#fff" stroke="var(--ink)" strokeWidth="2" />+ <path d="M34 34 h30 M34 42 h42" stroke="var(--line-2)" strokeWidth="3" strokeLinecap="round" />+ <path d="M40 80 l14 -8 l18 9 l-14 8 z M40 80 v6 l18 9 v-6 M72 81 v6 l-14 8" fill="var(--accent-soft)" stroke="var(--ink)" strokeWidth="1.6" strokeLinejoin="round" />+ </g>+ <g transform="rotate(6 120 60)">+ <rect x="92" y="10" width="66" height="88" rx="3" fill="#fff" stroke="var(--ink)" strokeWidth="2" />+ <text x="104" y="32" fontSize="15" fontWeight="800" fill="var(--ink)" fontFamily="var(--font)">+ 1+ </text>+ <path d="M108 70 l20 -11 l20 10 l-20 11 z" fill="#fff" stroke="var(--ink)" strokeWidth="1.6" strokeLinejoin="round" />+ <path d="M128 40 v14 h-4 l6 7 l6 -7 h-4 v-14 z" fill="var(--ink)" />+ </g>+ </svg>+ );+}++async function shrink(file: File): Promise<string> {+ const url = URL.createObjectURL(file);+ try {+ const img = await new Promise<HTMLImageElement>((res, rej) => {+ const i = new Image();+ i.onload = () => res(i);+ i.onerror = rej;+ i.src = url;+ });+ const k = Math.min(1, 1400 / Math.max(img.width, img.height));+ const c = document.createElement("canvas");+ c.width = Math.round(img.width * k);+ c.height = Math.round(img.height * k);+ const g = c.getContext("2d")!;+ g.fillStyle = "#fff";+ g.fillRect(0, 0, c.width, c.height);+ g.drawImage(img, 0, 0, c.width, c.height);+ return c.toDataURL("image/jpeg", 0.82);+ } finally {+ URL.revokeObjectURL(url);+ }+}diff --git a/src/components/workshop/Workshop.tsx b/src/components/workshop/Workshop.tsxnew file mode 100644index 0000000..df1a900--- /dev/null+++ b/src/components/workshop/Workshop.tsx@@ -0,0 +1,409 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";+import { AnimatePresence, motion } from "motion/react";+import { catalogSpec } from "@/lib/catalog";+import { buildPlan } from "@/lib/plan";+import { totals } from "@/lib/plan/contents";+import { lineup } from "@/lib/plan/lineup";+import { listProgress, removeProgress, type Progress } from "@/lib/store";+import type { Plan, ProductSpec } from "@/lib/types";+import { useMounted } from "@/lib/useMounted";+import { peekShot, shot, type Shot } from "@/engine/thumbs";+import Thumb from "../Thumb";+import { Figure } from "../art/Figure";+import { IArrowRight, IBox, ICheck, IClock, IClose, ILibrary, IPeople, WarnIcon } from "../art/Icons";++interface Row {+ p: Progress;+ spec: ProductSpec;+ plan: Plan;+ done: boolean;+}++function fmtTime(min: number) {+ if (min < 60) return `${min} min`;+ const h = Math.floor(min / 60), r = min % 60;+ return r ? `${h} h ${r} min` : `${h} h`;+}++const spentOf = (r: Row) => (r.p.startedAt && r.p.doneAt && r.p.doneAt > r.p.startedAt ? Math.max(1, Math.round((r.p.doneAt - r.p.startedAt) / 60000)) : null);++export default function Workshop() {+ const mounted = useMounted();+ const [removed, setRemoved] = useState<string[]>([]);+ const rows: Row[] = useMemo(() => {+ if (!mounted) return [];+ return listProgress()+ .filter((p) => p.phase !== "cover" && !removed.includes(p.slug))+ .map((p) => {+ const spec = p.spec ?? catalogSpec(p.slug);+ if (!spec) return null;+ try {+ return { p, spec, plan: buildPlan(spec), done: p.phase === "done" };+ } catch {+ return null;+ }+ })+ .filter(Boolean) as Row[];+ }, [mounted, removed]);++ const built = rows.filter((r) => r.done).sort((a, b) => (a.p.doneAt ?? a.p.updatedAt) - (b.p.doneAt ?? b.p.updatedAt));+ const going = rows.filter((r) => !r.done);+ const minutes = built.reduce((s, r) => s + (spentOf(r) ?? r.spec.minutes), 0);+ const fittings = built.reduce((s, r) => s + totals(r.plan).fittings, 0);+ const panels = built.reduce((s, r) => s + totals(r.plan).panels, 0);+ const badges = earned(built);+ const remove = (slug: string) => {+ removeProgress(slug);+ setRemoved((x) => [...x, slug]);+ };++ if (!mounted) return <div className="ws-loading" />;++ return (+ <div className="workshop">+ <header className="ws-head">+ <div>+ <h1>Your workshop</h1>+ <p className="lead">Everything you've built, side by side and to scale.</p>+ </div>+ {built.length > 0 && (+ <dl className="ws-stats">+ <div>+ <dt>Built</dt>+ <dd>{built.length}</dd>+ </div>+ <div>+ <dt>Time</dt>+ <dd>{fmtTime(minutes)}</dd>+ </div>+ <div>+ <dt>Panels</dt>+ <dd>{panels}</dd>+ </div>+ <div>+ <dt>Fittings</dt>+ <dd>{fittings}</dd>+ </div>+ </dl>+ )}+ </header>++ {rows.length === 0 ? (+ <Empty />+ ) : (+ <>+ {built.length > 0 ? <Showroom rows={built} /> : <EmptyFloor note="Your first finished build will stand here." />}++ {going.length > 0 && (+ <section className="ws-section">+ <div className="ws-sec-head">+ <h2>Still building</h2>+ <span>{going.length}</span>+ </div>+ <div className="ws-going">+ <AnimatePresence initial={false}>+ {going.map((r) => (+ <GoingRow key={r.p.slug} r={r} onRemove={() => remove(r.p.slug)} />+ ))}+ </AnimatePresence>+ </div>+ </section>+ )}++ {built.length > 0 && (+ <section className="ws-section">+ <div className="ws-sec-head">+ <h2>Built</h2>+ <span>{built.length}</span>+ </div>+ <div className="ws-grid">+ <AnimatePresence initial={false}>+ {[...built].reverse().map((r) => (+ <BuiltCard key={r.p.slug} r={r} onRemove={() => remove(r.p.slug)} />+ ))}+ </AnimatePresence>+ </div>+ </section>+ )}++ <section className="ws-section">+ <div className="ws-sec-head">+ <h2>Badges</h2>+ <span>+ {badges.size} of {BADGES.length}+ </span>+ </div>+ <div className="badges">+ {BADGES.map((b) => {+ const on = badges.has(b.id);+ return (+ <div key={b.id} className={"badge" + (on ? " on" : "")}>+ <span className="badge-ico">{b.icon}</span>+ <span className="badge-text">+ <b>{b.name}</b>+ <span>{b.hint}</span>+ </span>+ </div>+ );+ })}+ </div>+ </section>+ </>+ )}+ </div>+ );+}++/* ---------- the lineup: one drawing, one camera, real scale ---------- */++const VIEW = { az: 0.34, el: 0.3 };+const PERSON = 1750;++function Showroom({ rows }: { rows: Row[] }) {+ const wrap = useRef<HTMLDivElement>(null);+ const [w, setW] = useState(0);+ useEffect(() => {+ const el = wrap.current;+ if (!el) return;+ const ro = new ResizeObserver(() => setW(Math.round(el.clientWidth)));+ ro.observe(el);+ setW(Math.round(el.clientWidth));+ return () => ro.disconnect();+ }, []);++ const line = useMemo(() => lineup(rows.map((r) => r.plan)), [rows]);+ const personX = line.span[0] - 520;+ const h = w < 640 ? 300 : 400;+ const key = `lineup:${rows.map((r) => r.p.slug).join(",")}:${w}x${h}`;+ const mode = useMemo(+ () => ({+ kind: "assembled" as const,+ view: VIEW,+ frame: [+ [personX - 300, 0, 0],+ [personX - 300, PERSON, 0],+ [line.span[1] + 300, 0, 0],+ ] as [number, number, number][],+ }),+ [personX, line],+ );+ const probes = useMemo(+ () => [+ [personX, 0, 0] as [number, number, number],+ [personX, PERSON, 0] as [number, number, number],+ ...rows.map((r, i) => [line.centers[i], 0, (r.spec.size.d * 10) / 2] as [number, number, number]),+ ],+ [rows, line, personX],+ );+ const [res, setRes] = useState<{ key: string; s: Shot } | null>(null);+ const cached = w ? peekShot(key) : undefined;+ const s = cached ?? (res?.key === key ? res.s : null);++ useEffect(() => {+ if (!w || peekShot(key)) return;+ let alive = true;+ shot(key, line.plan, mode, w, h, probes).then((x) => alive && setRes({ key, s: x }));+ return () => {+ alive = false;+ };+ }, [key, w, h, line, mode, probes]);++ const feet = s?.points[0], head = s?.points[1];+ const figH = feet && head ? feet.y - head.y : 0;++ return (+ <section className="showroom" aria-label="Everything you built, to scale">+ <div className="sr-stage" ref={wrap} style={{ height: h }}>+ {s && (+ <motion.div className="sr-img" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.5 }}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={s.url} alt="" draggable={false} />+ {feet && figH > 20 && (+ <div className="sr-person" style={{ left: feet.x, top: feet.y, height: figH }}>+ <ScalePerson />+ <span>You, about 175 cm</span>+ </div>+ )}+ {rows.map((r, i) => {+ const pt = s.points[i + 2];+ if (!pt) return null;+ return (+ <Link key={r.p.slug} href={`/build/${r.p.slug}`} className="sr-tag" style={{ left: pt.x, top: pt.y }}>+ <b>{r.spec.name}</b>+ <span>{r.spec.size.w} × {r.spec.size.h} cm</span>+ </Link>+ );+ })}+ </motion.div>+ )}+ </div>+ </section>+ );+}++/** A quiet scale figure, like the ones on architects' drawings. viewBox is 175 units tall, one per cm. */+function ScalePerson() {+ return (+ <svg viewBox="0 0 60 175" className="scale-person" aria-hidden="true">+ <circle cx="30" cy="11.5" r="10.5" />+ <rect x="17" y="26" width="26" height="62" rx="11" />+ <rect x="8.5" y="28" width="7.5" height="60" rx="3.75" transform="rotate(4 12 28)" />+ <rect x="44" y="28" width="7.5" height="60" rx="3.75" transform="rotate(-4 48 28)" />+ <rect x="19" y="78" width="10.5" height="96" rx="5.25" />+ <rect x="30.5" y="78" width="10.5" height="96" rx="5.25" />+ </svg>+ );+}++/* ---------- lists ---------- */++function GoingRow({ r, onRemove }: { r: Row; onRemove: () => void }) {+ const p = r.p;+ const pct = p.phase === "steps" ? (p.step + 1) / Math.max(1, p.steps) : p.phase === "parts" ? 0.06 : 0.03;+ const href = `/build/${p.slug}${p.spec ? `?q=${encodeURIComponent(p.spec.name)}` : ""}`;+ const status = p.phase === "steps" ? `Step ${p.step + 1} of ${p.steps}` : p.phase === "parts" ? "Checking parts" : "Checking tools";+ return (+ <motion.div className="going" layout initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, height: 0, marginTop: 0 }} transition={{ duration: 0.3 }}>+ <Link href={href} className="going-link">+ <Thumb id={"go-" + p.slug} plan={r.plan} mode={{ kind: "assembled" }} w={150} h={112} className="going-thumb" />+ <span className="going-text">+ <b>{r.spec.name}</b>+ <span>{r.spec.variant}</span>+ </span>+ <span className="going-progress">+ <span className="going-status">{status}</span>+ <span className="going-bar">+ <i style={{ width: `${Math.max(4, pct * 100)}%` }} />+ </span>+ </span>+ <span className="going-go">+ Continue <IArrowRight size={15} />+ </span>+ </Link>+ <button className="x-btn" onClick={onRemove} aria-label={`Remove ${r.spec.name}`} title="Remove">+ <IClose size={15} />+ </button>+ </motion.div>+ );+}++function BuiltCard({ r, onRemove }: { r: Row; onRemove: () => void }) {+ const p = r.p;+ const when = new Date(p.doneAt ?? p.updatedAt);+ const spent = spentOf(r);+ return (+ <motion.div className="built" layout initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.96 }} transition={{ duration: 0.3 }}>+ <Link href={`/build/${p.slug}${p.spec ? `?q=${encodeURIComponent(p.spec.name)}` : ""}`} className="built-link">+ <Thumb id={"bt-" + p.slug} plan={r.plan} mode={{ kind: "assembled" }} w={360} h={270} className="built-thumb" />+ <span className="built-text">+ <b>{r.spec.name}</b>+ <span>{r.spec.variant}</span>+ <span className="built-meta">+ <span>+ <ICheck size={14} strokeWidth={2.4} /> {when.toLocaleDateString(undefined, { day: "numeric", month: "short" })}+ </span>+ {spent && (+ <span>+ <IClock size={14} /> {fmtTime(spent)}+ </span>+ )}+ </span>+ </span>+ </Link>+ <button className="x-btn" onClick={onRemove} aria-label={`Remove ${r.spec.name}`} title="Remove">+ <IClose size={15} />+ </button>+ </motion.div>+ );+}++/* ---------- empty ---------- */++const STARTERS = [+ { slug: "lack-side-table", name: "LACK", note: "15 min, a good first build" },+ { slug: "kallax-2x2", name: "KALLAX", note: "Cube shelf, 45 min" },+ { slug: "malm-3-drawers", name: "MALM", note: "Chest of drawers, 2 h" },+];++function EmptyFloor({ note }: { note: string }) {+ return (+ <div className="ws-floor">+ <div className="ws-floor-row">+ <span className="ws-floor-fig">+ <Figure pose="wave" size={150} />+ </span>+ <svg viewBox="140 50 440 160" aria-hidden="true" className="ws-ghosts">+ <g fill="none" stroke="var(--line-2)" strokeWidth="2" strokeDasharray="6 6" strokeLinejoin="round">+ <path d="M150 178 V70 L196 56 L262 76 V186 L216 200 Z M150 70 L216 90 L262 76 M216 90 V200" />+ <path d="M330 186 V120 L370 108 L430 126 V194 L390 206 Z M330 120 L390 138 L430 126 M390 138 V206 M330 142 L390 160 L430 148 M330 164 L390 182 L430 170" />+ <path d="M490 150 h70 M498 150 v42 M552 150 v42 M490 150 l12 -8 h70 l-12 8 M572 142 v36" />+ </g>+ </svg>+ </div>+ <p>{note}</p>+ </div>+ );+}++function Empty() {+ return (+ <div className="ws-empty">+ <EmptyFloor note="Nothing here yet" />+ <div className="ws-empty-copy">+ <h2>Your finished builds will stand here</h2>+ <p>Side by side and to scale, next to a person for size. Pick something to build first.</p>+ <div className="ws-starters">+ {STARTERS.map((s) => (+ <Link key={s.slug} href={`/build/${s.slug}`} className="starter">+ <b>{s.name}</b>+ <span>{s.note}</span>+ <IArrowRight size={16} />+ </Link>+ ))}+ </div>+ <Link href="/browse" className="ws-browse">+ Or browse all guides+ </Link>+ </div>+ </div>+ );+}++/* ---------- badges ---------- */++const BED = (+ <svg viewBox="0 0 24 24" width={20} height={20} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">+ <path d="M3 18V7M3 13h18v5M21 18v-5a3 3 0 0 0-3-3h-7v3" />+ <circle cx="7" cy="10.5" r="1.6" />+ </svg>+);++const BADGES: { id: string; name: string; hint: string; icon: React.ReactNode }[] = [+ { id: "first", name: "First build", hint: "Finish anything", icon: <ICheck size={19} strokeWidth={2.4} /> },+ { id: "drawers", name: "Drawer whisperer", hint: "Build something with drawers", icon: <IBox size={19} /> },+ { id: "anchor", name: "Anchored", hint: "Fix a build to the wall", icon: <WarnIcon id="wall" size={24} /> },+ { id: "team", name: "Team player", hint: "Finish a two person build", icon: <IPeople size={19} /> },+ { id: "fast", name: "Quick hands", hint: "Beat the typical time", icon: <IClock size={19} /> },+ { id: "bed", name: "Sweet dreams", hint: "Build a bed", icon: BED },+ { id: "books", name: "Bookworm", hint: "Build a bookcase or shelf", icon: <ILibrary size={19} /> },+ { id: "five", name: "Regular", hint: "Finish five builds", icon: <span className="bi">5</span> },+];++function earned(built: Row[]) {+ const s = new Set<string>();+ if (built.length) s.add("first");+ if (built.length >= 5) s.add("five");+ for (const r of built) {+ if (r.spec.archetype === "drawers") s.add("drawers");+ if (r.plan.steps.some((x) => x.kind === "anchor")) s.add("anchor");+ if (r.spec.people === 2) s.add("team");+ if (r.spec.archetype === "bed") s.add("bed");+ if (r.spec.archetype === "shelf") s.add("books");+ const spent = spentOf(r);+ if (spent && spent < r.spec.minutes) s.add("fast");+ }+ return s;+}diff --git a/src/engine/drawable.ts b/src/engine/drawable.tsnew file mode 100644index 0000000..d3135f9--- /dev/null+++ b/src/engine/drawable.ts@@ -0,0 +1,251 @@+import * as THREE from "three";+import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";+import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js";+import type { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";+import { faceMaterial, hullMaterial, lineMaterial, withBoxHullDir, withCylHullDir, withHullDir } from "./materials";+import type { HwKind, Hole, PartType } from "@/lib/types";+import { FACE } from "./materials";++export class Drawable {+ root = new THREE.Group();+ faces: THREE.ShaderMaterial[] = [];+ lines: LineMaterial[] = [];+ thin: LineMaterial[] = [];+ hulls: THREE.ShaderMaterial[] = [];+ meshes: THREE.Mesh[] = [];+ base: THREE.Color[] = [];+ opacity = 1;+}++interface GeoEntry {+ geo: THREE.BufferGeometry;+ edges: LineSegmentsGeometry;+}+const geoCache = new Map<string, GeoEntry>();++function entry(key: string, make: () => THREE.BufferGeometry, threshold = 30): GeoEntry {+ let e = geoCache.get(key);+ if (!e) {+ const geo = make();+ const edges = new LineSegmentsGeometry().fromEdgesGeometry(new THREE.EdgesGeometry(geo, threshold));+ e = { geo, edges };+ geoCache.set(key, e);+ }+ return e;+}++type HullKind = "cyl" | "radial" | "box" | null;++export function addSolid(+ d: Drawable,+ key: string,+ make: () => THREE.BufferGeometry,+ color: THREE.Color,+ o: { hull?: HullKind; half?: THREE.Vector3Tuple; cy?: number; position?: THREE.Vector3Tuple; rotation?: THREE.Vector3Tuple; edges?: boolean; parent?: THREE.Object3D } = {},+) {+ const e = entry(key, () => {+ const g = make();+ if (o.hull === "cyl") withCylHullDir(g, o.cy ?? 0);+ else if (o.hull === "box" && o.half) withBoxHullDir(g, ...o.half);+ else if (o.hull === "radial") {+ g.computeBoundingBox();+ const c = new THREE.Vector3();+ g.boundingBox!.getCenter(c);+ withHullDir(g, c);+ }+ return g;+ });+ const holder = new THREE.Group();+ if (o.position) holder.position.set(...o.position);+ if (o.rotation) holder.rotation.set(...o.rotation);+ const fm = faceMaterial(color);+ const mesh = new THREE.Mesh(e.geo, fm);+ holder.add(mesh);+ d.faces.push(fm);+ d.base.push(color.clone());+ d.meshes.push(mesh);+ if (o.edges !== false) {+ const lm = lineMaterial(1.6);+ const ls = new LineSegments2(e.edges, lm);+ holder.add(ls);+ d.lines.push(lm);+ }+ if (o.hull) {+ const hm = hullMaterial(1.6);+ const hull = new THREE.Mesh(e.geo, hm);+ if (o.hull === "box") hm.uniforms.uWidth.value = 2;+ hull.renderOrder = -1;+ holder.add(hull);+ d.hulls.push(hm);+ }+ (o.parent ?? d.root).add(holder);+ return holder;+}++/* ---------------- parts ---------------- */++const MAT_COLOR: Record<string, THREE.Color> = {+ board: FACE.board,+ fiber: FACE.fiber,+ wood: FACE.wood,+ metal: FACE.metal,+ soft: FACE.soft,+};++export function partDrawable(p: PartType, holes: Hole[]) {+ const d = new Drawable();+ const [sx, sy, sz] = p.size;+ const color = MAT_COLOR[p.material] ?? FACE.board;+ if (p.shape === "cyl") {+ addSolid(d, `cyl:${sx}:${sy}`, () => new THREE.CylinderGeometry(sx / 2, sx / 2, sy, 32), color, { hull: "cyl" });+ } else if (p.material === "soft") {+ addSolid(d, `soft:${sx}:${sy}:${sz}`, () => roundedBox(sx, sy, sz, Math.min(42, sy / 2.4, sx / 3, sz / 3)), color, { hull: "box", half: [sx / 2, sy / 2, sz / 2], edges: false });+ } else {+ addSolid(d, `box:${sx}:${sy}:${sz}`, () => new THREE.BoxGeometry(sx, sy, sz), color);+ }+ if (holes.length) {+ const pts: number[] = [];+ const seg = 14;+ const n = new THREE.Vector3();+ const a = new THREE.Vector3();+ const b = new THREE.Vector3();+ const c = new THREE.Vector3();+ for (const h of holes) {+ n.set(...h.n).normalize();+ a.set(Math.abs(n.y) < 0.9 ? 0 : 1, Math.abs(n.y) < 0.9 ? 1 : 0, 0).cross(n).normalize();+ b.copy(n).cross(a).normalize();+ c.set(...h.p).addScaledVector(n, 0.35);+ for (let i = 0; i < seg; i++) {+ const t0 = (i / seg) * Math.PI * 2, t1 = ((i + 1) / seg) * Math.PI * 2;+ pts.push(+ c.x + (a.x * Math.cos(t0) + b.x * Math.sin(t0)) * h.r,+ c.y + (a.y * Math.cos(t0) + b.y * Math.sin(t0)) * h.r,+ c.z + (a.z * Math.cos(t0) + b.z * Math.sin(t0)) * h.r,+ c.x + (a.x * Math.cos(t1) + b.x * Math.sin(t1)) * h.r,+ c.y + (a.y * Math.cos(t1) + b.y * Math.sin(t1)) * h.r,+ c.z + (a.z * Math.cos(t1) + b.z * Math.sin(t1)) * h.r,+ );+ }+ }+ const g = new LineSegmentsGeometry();+ g.setPositions(pts);+ const lm = lineMaterial(1);+ d.root.add(new LineSegments2(g, lm));+ d.thin.push(lm);+ }+ return d;+}++function roundedBox(w: number, h: number, dpt: number, r: number) {+ const shape = new THREE.Shape();+ const x = -w / 2, y = -dpt / 2;+ shape.moveTo(x + r, y);+ shape.lineTo(x + w - r, y);+ shape.quadraticCurveTo(x + w, y, x + w, y + r);+ shape.lineTo(x + w, y + dpt - r);+ shape.quadraticCurveTo(x + w, y + dpt, x + w - r, y + dpt);+ shape.lineTo(x + r, y + dpt);+ shape.quadraticCurveTo(x, y + dpt, x, y + dpt - r);+ shape.lineTo(x, y + r);+ shape.quadraticCurveTo(x, y, x + r, y);+ const g = new THREE.ExtrudeGeometry(shape, { depth: h - r, bevelEnabled: true, bevelThickness: r / 2, bevelSize: r / 3, bevelSegments: 3, curveSegments: 6 });+ g.rotateX(-Math.PI / 2);+ g.translate(0, -(h - r) / 2, 0);+ return g;+}++/* ---------------- hardware ---------------- */++const cyl = (r: number, h: number, seg = 18) => () => new THREE.CylinderGeometry(r, r, h, seg);++/**+ * Hardware is modelled along +Y with the origin on the surface it goes into.+ * Everything below y = 0 ends up inside the panel.+ */+export function hwDrawable(kind: HwKind, len: number, dia: number) {+ const d = new Drawable();+ const metal = FACE.hwMetal, wood = FACE.hwWood, plastic = FACE.hwPlastic;+ const r = dia / 2;+ switch (kind) {+ case "dowel":+ // seated 12 mm deep, like real face-drilled holes, so it never shows through a 15 mm panel+ addSolid(d, `dowel:${len}:${dia}`, cyl(r, len, 16), wood, { hull: "cyl", position: [0, len / 2 - 12, 0] });+ break;+ case "camScrew":+ addSolid(d, "cs:thread", cyl(2.9, 11, 12), metal, { hull: "cyl", position: [0, -5.5, 0] });+ addSolid(d, "cs:neck", cyl(2.2, 17, 12), metal, { hull: "cyl", position: [0, 8.5, 0] });+ addSolid(d, "cs:head", () => new THREE.SphereGeometry(3.6, 14, 10), metal, { hull: "radial", position: [0, 19.5, 0], edges: false });+ break;+ case "cam": {+ addSolid(d, "cam:body", cyl(7.4, 12.4, 22), metal, { hull: "cyl", position: [0, -6.2, 0] });+ addSolid(d, "cam:slot", () => new THREE.BoxGeometry(9, 0.8, 1.6), FACE.hwMetal, { position: [0, 0.4, 0] });+ addSolid(d, "cam:arrow", () => new THREE.ConeGeometry(1.4, 2.6, 3), FACE.hwMetal, { position: [5.2, 0.4, 0], rotation: [0, 0, -Math.PI / 2], edges: true });+ break;+ }+ case "screw": {+ const hr = Math.max(dia, 3.2);+ addSolid(d, `sc:shank:${len}:${dia}`, cyl(r * 0.92, len - 2, 10), metal, { hull: "cyl", position: [0, -(len - 2) / 2 - 2, 0] });+ addSolid(d, `sc:tip:${dia}`, () => new THREE.ConeGeometry(r * 0.92, 2.6, 10), metal, { position: [0, -len - 0.7, 0], rotation: [Math.PI, 0, 0], edges: false });+ addSolid(d, `sc:head:${dia}`, cyl(hr, 1.9, 18), metal, { hull: "cyl", position: [0, 0.95, 0] });+ addSolid(d, `sc:x1:${dia}`, () => new THREE.BoxGeometry(hr * 1.2, 0.4, 0.5), metal, { position: [0, 2.0, 0] });+ addSolid(d, `sc:x2:${dia}`, () => new THREE.BoxGeometry(0.5, 0.4, hr * 1.2), metal, { position: [0, 2.0, 0] });+ break;+ }+ case "nail":+ addSolid(d, `nail:${len}`, cyl(r, len, 8), metal, { hull: "cyl", position: [0, -len / 2, 0] });+ addSolid(d, "nail:head", cyl(r * 1.7, 0.7, 12), metal, { hull: "cyl", position: [0, 0.35, 0] });+ break;+ case "pin":+ addSolid(d, `pin:${dia}`, cyl(r, 16, 12), metal, { hull: "cyl" });+ addSolid(d, `pin:collar:${dia}`, cyl(r + 1.2, 1.2, 14), metal, { hull: "cyl", position: [0, 0.6, 0] });+ break;+ case "legScrew":+ addSolid(d, `leg:${len}`, cyl(r, len, 14), metal, { hull: "cyl" });+ break;+ case "bolt":+ addSolid(d, `bolt:${len}:${dia}`, cyl(r, len, 12), metal, { hull: "cyl", position: [0, -len / 2, 0] });+ addSolid(d, `bolt:head:${dia}`, cyl(dia * 0.85, 5, 18), metal, { hull: "cyl", position: [0, 2.5, 0] });+ addSolid(d, `bolt:hex:${dia}`, cyl(dia * 0.4, 0.6, 6), FACE.hwMetal, { position: [0, 5.2, 0] });+ break;+ case "plate":+ addSolid(d, "plate", () => new THREE.BoxGeometry(70, 3, 70), metal, { position: [0, 1.5, 0] });+ addSolid(d, "plate:sock", cyl(9, 10, 18), metal, { hull: "cyl", position: [0, 8, 0] });+ break;+ case "bracket":+ addSolid(d, "br:h", () => new THREE.BoxGeometry(40, 2, 32), metal, { position: [0, 1, 0] });+ addSolid(d, "br:v", () => new THREE.BoxGeometry(40, 42, 2), metal, { position: [0, 21, -15] });+ break;+ case "runner":+ addSolid(d, `run:${len}`, () => new THREE.BoxGeometry(20, 11, len), metal, { position: [0, 5.5, 0] });+ addSolid(d, `run:lip:${len}`, () => new THREE.BoxGeometry(4, 6, len), metal, { position: [-8, 14, 0] });+ break;+ case "knob":+ addSolid(d, "knob:stem", cyl(5.5, 12, 14), wood, { hull: "cyl", position: [0, 6, 0] });+ addSolid(d, "knob:head", () => new THREE.SphereGeometry(14, 22, 12, 0, Math.PI * 2, 0, Math.PI * 0.62), wood, { hull: "radial", position: [0, 14, 0], edges: false });+ break;+ case "handle":+ for (const x of [-len / 2, len / 2]) addSolid(d, "hd:post", cyl(5, 26, 12), metal, { hull: "cyl", position: [x, 13, 0] });+ addSolid(d, `hd:bar:${len}`, () => new THREE.CylinderGeometry(6, 6, len + 24, 14).rotateZ(Math.PI / 2), metal, { hull: "radial", position: [0, 30, 0] });+ break;+ case "hinge":+ addSolid(d, "hg:cup", cyl(17.5, 12, 24), metal, { hull: "cyl", position: [0, -6, 0] });+ addSolid(d, "hg:flange", () => new THREE.BoxGeometry(52, 1.6, 14), metal, { position: [0, 0.8, 0] });+ addSolid(d, "hg:arm", () => new THREE.BoxGeometry(12, 40, 11), metal, { position: [4, 20, 0] });+ addSolid(d, "hg:plate", () => new THREE.BoxGeometry(4, 18, 40), metal, { position: [-4, 34, 0] });+ break;+ case "glide":+ addSolid(d, "glide", cyl(10, 4, 18), plastic, { hull: "cyl", position: [0, 2, 0] });+ break;+ case "plug":+ addSolid(d, `plug:${len}`, cyl(r, len, 12), plastic, { hull: "cyl", position: [0, -len / 2, 0] });+ addSolid(d, "plug:lip", cyl(r + 1.5, 1.5, 14), plastic, { hull: "cyl", position: [0, 0.75, 0] });+ break;+ }+ return d;+}++export function wallDrawable(w: number, h: number) {+ const d = new Drawable();+ addSolid(d, `wall:${w}:${h}`, () => new THREE.BoxGeometry(w, h, 40), FACE.wall);+ return d;+}diff --git a/src/engine/materials.ts b/src/engine/materials.tsnew file mode 100644index 0000000..94ee972--- /dev/null+++ b/src/engine/materials.ts@@ -0,0 +1,162 @@+import * as THREE from "three";+import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";++export const INK = new THREE.Color("#141414");+export const INK_OLD = new THREE.Color("#94918b");+export const TINT_NEW = new THREE.Color("#fff3c4");++export const FACE: Record<string, THREE.Color> = {+ board: new THREE.Color("#ffffff"),+ fiber: new THREE.Color("#f5f1e8"),+ wood: new THREE.Color("#fdfaf4"),+ metal: new THREE.Color("#eceef0"),+ soft: new THREE.Color("#f6f6f4"),+ hwMetal: new THREE.Color("#dfe1e3"),+ hwWood: new THREE.Color("#f1e2c3"),+ hwPlastic: new THREE.Color("#f4f4f2"),+ wall: new THREE.Color("#f3f2ee"),+};++const faceVert = /* glsl */ `+varying vec3 vN;+void main() {+ vN = normalize(mat3(modelMatrix) * normal);+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+}`;++const faceFrag = /* glsl */ `+uniform vec3 uColor;+uniform vec3 uTint;+uniform float uTintAmt;+uniform float uOpacity;+varying vec3 vN;+void main() {+ vec3 n = normalize(vN);+ vec3 L = normalize(vec3(-0.35, 1.0, 0.55));+ float d = dot(n, L);+ float shade = d > 0.72 ? 1.0 : (d > 0.18 ? 0.968 : (d > -0.2 ? 0.938 : 0.915));+ vec3 c = mix(uColor, uTint, uTintAmt) * shade;+ gl_FragColor = vec4(c, uOpacity);+}`;++export function faceMaterial(color: THREE.Color) {+ return new THREE.ShaderMaterial({+ uniforms: {+ uColor: { value: color.clone() },+ uTint: { value: TINT_NEW.clone() },+ uTintAmt: { value: 0 },+ uOpacity: { value: 1 },+ },+ vertexShader: faceVert,+ fragmentShader: faceFrag,+ polygonOffset: true,+ polygonOffsetFactor: 1,+ polygonOffsetUnits: 1,+ transparent: true,+ });+}++const hullVert = /* glsl */ `+attribute vec3 hullDir;+uniform float uWidth;+uniform vec2 uRes;+void main() {+ vec4 clip = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ vec3 n = normalize(normalMatrix * hullDir);+ vec2 dir = n.xy;+ float l = length(dir);+ dir = l > 1e-4 ? dir / l : vec2(0.0);+ clip.xy += dir * uWidth * 2.0 / uRes * clip.w;+ gl_Position = clip;+}`;+const hullFrag = /* glsl */ `+uniform vec3 uColor;+uniform float uOpacity;+void main() { gl_FragColor = vec4(uColor, uOpacity); }`;++export function hullMaterial(width: number) {+ return new THREE.ShaderMaterial({+ uniforms: {+ uColor: { value: INK.clone() },+ uOpacity: { value: 1 },+ uWidth: { value: width },+ uRes: { value: new THREE.Vector2(1, 1) },+ },+ vertexShader: hullVert,+ fragmentShader: hullFrag,+ side: THREE.BackSide,+ transparent: true,+ });+}++export function lineMaterial(width: number) {+ const m = new LineMaterial({+ color: INK.getHex(),+ linewidth: width,+ worldUnits: false,+ transparent: true,+ dashed: false,+ });+ return m;+}++/** Add an attribute pointing away from the shape centre: used by the screen space outline. */+export function withHullDir(geo: THREE.BufferGeometry, center = new THREE.Vector3()) {+ const pos = geo.getAttribute("position");+ const arr = new Float32Array(pos.count * 3);+ const v = new THREE.Vector3();+ for (let i = 0; i < pos.count; i++) {+ v.fromBufferAttribute(pos, i).sub(center);+ if (v.lengthSq() < 1e-8) v.set(0, 1, 0);+ v.normalize();+ arr[i * 3] = v.x;+ arr[i * 3 + 1] = v.y;+ arr[i * 3 + 2] = v.z;+ }+ geo.setAttribute("hullDir", new THREE.BufferAttribute(arr, 3));+ return geo;+}++/** Outline direction for cylinders along Y: diagonal at the rims so sides and caps both get a clean outline. */+export function withCylHullDir(geo: THREE.BufferGeometry, cy = 0) {+ const pos = geo.getAttribute("position");+ const arr = new Float32Array(pos.count * 3);+ const v = new THREE.Vector3();+ for (let i = 0; i < pos.count; i++) {+ v.fromBufferAttribute(pos, i);+ const rl = Math.hypot(v.x, v.z);+ const rx = rl > 1e-4 ? v.x / rl : 0;+ const rz = rl > 1e-4 ? v.z / rl : 0;+ const ay = v.y - cy >= 0 ? 1 : -1;+ const d = new THREE.Vector3(rx, ay * 0.35, rz);+ if (rl <= 1e-4) d.set(0, ay, 0);+ d.normalize();+ arr[i * 3] = d.x;+ arr[i * 3 + 1] = d.y;+ arr[i * 3 + 2] = d.z;+ }+ geo.setAttribute("hullDir", new THREE.BufferAttribute(arr, 3));+ return geo;+}++/** Outline direction for rounded boxes: the gradient of a superellipsoid, so flat faces push straight out. */+export function withBoxHullDir(geo: THREE.BufferGeometry, hx: number, hy: number, hz: number) {+ const pos = geo.getAttribute("position");+ const arr = new Float32Array(pos.count * 3);+ const v = new THREE.Vector3();+ const k = 7;+ for (let i = 0; i < pos.count; i++) {+ v.fromBufferAttribute(pos, i);+ const gx = (Math.sign(v.x) * Math.pow(Math.abs(v.x / hx), k)) / hx;+ const gy = (Math.sign(v.y) * Math.pow(Math.abs(v.y / hy), k)) / hy;+ const gz = (Math.sign(v.z) * Math.pow(Math.abs(v.z / hz), k)) / hz;+ v.set(gx, gy, gz);+ if (v.lengthSq() < 1e-12) v.set(0, 1, 0);+ v.normalize();+ arr[i * 3] = v.x;+ arr[i * 3 + 1] = v.y;+ arr[i * 3 + 2] = v.z;+ }+ geo.setAttribute("hullDir", new THREE.BufferAttribute(arr, 3));+ return geo;+}diff --git a/src/engine/stage.ts b/src/engine/stage.tsnew file mode 100644index 0000000..8f0963d--- /dev/null+++ b/src/engine/stage.ts@@ -0,0 +1,1407 @@+import * as THREE from "three";+import type { HwItem, PartItem, PartType, Plan, Step, Vec3 } from "@/lib/types";+import { POSE_EULER } from "@/lib/plan/math";+import { Drawable, hwDrawable, partDrawable, wallDrawable } from "./drawable";+import { INK, INK_OLD } from "./materials";++export type StageMode =+ | { kind: "intro"; dims?: boolean }+ | { kind: "assembled"; turntable?: boolean; dims?: boolean; view?: { az: number; el: number }; frame?: Vec3[] }+ | { kind: "layout" }+ | { kind: "step"; index: number }+ | { kind: "part"; ref: string };++export interface StageOptions {+ callout?: boolean;+ interactive?: boolean;+ labels?: boolean;+ offscreen?: boolean;+ loop?: boolean;+ onIntroDone?: () => void;+ onHover?: (ref: string | null) => void;+ onUserView?: (changed: boolean) => void;+ margins?: { t: number; r: number; b: number; l: number };+}++const easeOut = (x: number) => 1 - Math.pow(1 - x, 4);+const easeInOut = (x: number) => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2);+const clamp01 = (x: number) => Math.max(0, Math.min(1, x));++const PART_DUR = 0.95;+const HW_DUR = 0.6;+const CAM_TURN = 0.62;+const HOLD = 2.4;+const FADE = 0.35;++interface PNode {+ item: PartItem;+ type: PartType;+ d: Drawable;+ node: THREE.Group;+ corners: THREE.Vector3[]; // local box corners+}+interface HNode {+ item: HwItem;+ d: Drawable;+ holder: THREE.Group;+ inner: THREE.Group;+ parent?: PNode;+}++interface Xf {+ p: THREE.Vector3;+ q: THREE.Quaternion;+}++const tmpV = new THREE.Vector3();+const tmpQ = new THREE.Quaternion();+const Y = new THREE.Vector3(0, 1, 0);++function quatFromEuler(e: Vec3) {+ return new THREE.Quaternion().setFromEuler(new THREE.Euler(e[0], e[1], e[2], "XYZ"));+}++export class Stage {+ el: HTMLElement;+ renderer: THREE.WebGLRenderer;+ scene = new THREE.Scene();+ camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 40000);+ root = new THREE.Group();+ plan: Plan | null = null;+ parts: PNode[] = [];+ hws: HNode[] = [];+ byKey = new Map<string, PNode>();+ mode: StageMode = { kind: "assembled" };+ opts: StageOptions;++ // overlay+ overlay?: SVGSVGElement;+ labelLayer?: HTMLDivElement;+ tooltip?: HTMLDivElement;+ callout?: {+ wrap: HTMLDivElement;+ renderer: THREE.WebGLRenderer;+ camera: THREE.OrthographicCamera;+ svg: SVGSVGElement;+ size: number;+ visible: number;+ };+ leader?: SVGPathElement;+ leaderDot?: SVGCircleElement;+ arrows: SVGPathElement[] = [];+ labels = new Map<string, HTMLDivElement>();+ squareEls: SVGElement[] = [];+ dimsEl?: SVGGElement;++ // view state+ w = 1;+ h = 1;+ az = 0.62;+ el0 = 0.46;+ userAz = 0;+ userEl = 0;+ userZoom = 1;+ dragging = false;+ autoReset = true;+ camTarget = new THREE.Vector3();+ camHalf = 1000;+ camReady = false;+ rootQ = new THREE.Quaternion();+ rootReady = false;+ t = 0;+ last = 0;+ raf = 0;+ speed = 1;+ paused = false;+ stepEnd = 0;+ loopCount = 0;+ highlight: Set<string> | null = null;+ hovered: string | null = null;+ wall?: { d: Drawable; node: THREE.Group; on: number };+ shadow: THREE.Mesh;+ disposed = false;+ visible = true;+ introDone = false;+ private io?: IntersectionObserver;+ private ro?: ResizeObserver;+ private pointers = new Map<number, { x: number; y: number }>();+ private pinch0 = 0;+ private zoom0 = 1;+ private downAt = { x: 0, y: 0, t: 0 };+ private extents = new Map<string, THREE.Vector3[]>();+ private typeFirst = new Map<string, number>();+ private frameLocal: THREE.Vector3[] = [];+ private stack = new Map<string, Xf>();+ private layout = new Map<string, Xf>();+ private focus?: { local: THREE.Vector3; dir: THREE.Vector3; size: number; hw: HNode };+ margins?: { t: number; r: number; b: number; l: number };++ constructor(el: HTMLElement, opts: StageOptions = {}) {+ this.el = el;+ this.opts = opts;+ this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: !!opts.offscreen });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.renderer.setClearColor(0xffffff, 0);+ const c = this.renderer.domElement;+ c.className = "stage-canvas";+ el.appendChild(c);+ this.scene.add(this.root);++ // soft floor shadow+ const cv = document.createElement("canvas");+ cv.width = cv.height = 128;+ const g = cv.getContext("2d")!;+ const grd = g.createRadialGradient(64, 64, 4, 64, 64, 64);+ grd.addColorStop(0, "rgba(20,20,20,0.16)");+ grd.addColorStop(0.55, "rgba(20,20,20,0.07)");+ grd.addColorStop(1, "rgba(20,20,20,0)");+ g.fillStyle = grd;+ g.fillRect(0, 0, 128, 128);+ const tex = new THREE.CanvasTexture(cv);+ this.shadow = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false }));+ this.shadow.rotation.x = -Math.PI / 2;+ this.shadow.position.y = -1;+ this.shadow.renderOrder = -5;+ this.scene.add(this.shadow);++ if (!opts.offscreen) {+ const ns = "http://www.w3.org/2000/svg";+ this.overlay = document.createElementNS(ns, "svg") as SVGSVGElement;+ this.overlay.setAttribute("class", "stage-overlay");+ el.appendChild(this.overlay);+ if (opts.labels !== false) {+ this.labelLayer = document.createElement("div");+ this.labelLayer.className = "stage-labels";+ el.appendChild(this.labelLayer);+ }+ if (opts.callout) this.makeCallout();+ if (opts.interactive) this.bindPointer();+ this.ro = new ResizeObserver(() => this.resize());+ this.ro.observe(el);+ this.io = new IntersectionObserver((e) => {+ this.visible = e[0]?.isIntersecting ?? true;+ });+ this.io.observe(el);+ this.resize();+ this.last = performance.now();+ const loop = (now: number) => {+ if (this.disposed) return;+ this.raf = requestAnimationFrame(loop);+ const dt = Math.min(0.05, (now - this.last) / 1000);+ this.last = now;+ if (!this.visible || document.hidden) return;+ this.tick(dt);+ this.render();+ };+ this.raf = requestAnimationFrame(loop);+ // Some embedded webviews pause rAF while still reporting the page as visible: keep a slow fallback clock.+ this.fallback = window.setInterval(() => {+ const now = performance.now();+ if (this.disposed || document.hidden || now - this.last < 120) return;+ const dt = Math.min(0.05, (now - this.last) / 1000);+ this.last = now;+ this.tick(dt);+ this.render();+ }, 40);+ }+ }+ private fallback = 0;++ /* ---------------- setup ---------------- */++ private makeCallout() {+ const wrap = document.createElement("div");+ wrap.className = "stage-callout";+ wrap.style.opacity = "0";+ wrap.style.visibility = "hidden";+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.setClearColor(0xffffff, 1);+ wrap.appendChild(renderer.domElement);+ const ns = "http://www.w3.org/2000/svg";+ const svg = document.createElementNS(ns, "svg") as SVGSVGElement;+ svg.setAttribute("class", "stage-callout-svg");+ wrap.appendChild(svg);+ this.el.appendChild(wrap);+ this.callout = { wrap, renderer, camera: new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 4000), svg, size: 200, visible: 0 };+ this.leader = document.createElementNS(ns, "path") as SVGPathElement;+ this.leader.setAttribute("class", "leader");+ this.leaderDot = document.createElementNS(ns, "circle") as SVGCircleElement;+ this.leaderDot.setAttribute("class", "leader-dot");+ this.leaderDot.setAttribute("r", "4");+ this.overlay!.appendChild(this.leader);+ this.overlay!.appendChild(this.leaderDot);+ }++ resize(w?: number, h?: number) {+ if (w && h) {+ this.w = w;+ this.h = h;+ } else {+ const r = this.el.getBoundingClientRect();+ this.w = Math.max(1, r.width);+ this.h = Math.max(1, r.height);+ }+ this.renderer.setSize(this.w, this.h, false);+ if (this.callout) {+ const size = Math.round(Math.min(220, Math.max(120, Math.min(this.w, this.h) * 0.34)));+ this.callout.size = size;+ this.callout.renderer.setSize(size, size, false);+ this.callout.wrap.style.width = this.callout.wrap.style.height = size + "px";+ }+ }++ setPlan(plan: Plan) {+ if (this.plan === plan) return;+ this.clear();+ this.plan = plan;+ const types = new Map(plan.parts.map((p) => [p.id, p]));+ for (const it of plan.items) {+ if (it.kind !== "part") continue;+ const type = types.get(it.ref);+ if (!type) continue;+ const d = partDrawable(type, it.holes);+ const node = new THREE.Group();+ node.add(d.root);+ node.userData.key = it.key;+ d.meshes.forEach((m) => (m.userData.ref = it.ref));+ this.root.add(node);+ const [sx, sy, sz] = type.size;+ const corners: THREE.Vector3[] = [];+ for (const a of [-1, 1]) for (const b of [-1, 1]) for (const c of [-1, 1]) corners.push(new THREE.Vector3((a * sx) / 2, (b * sy) / 2, (c * sz) / 2));+ const pn: PNode = { item: it, type, d, node, corners };+ this.parts.push(pn);+ this.byKey.set(it.key, pn);+ }+ const hwTypes = new Map(plan.hardware.map((h) => [h.id, h]));+ for (const it of plan.items) {+ if (it.kind !== "hw") continue;+ const ht = hwTypes.get(it.ref)!;+ const d = hwDrawable(ht.kind, ht.len, ht.dia);+ const holder = new THREE.Group();+ const inner = new THREE.Group();+ holder.add(inner);+ inner.add(d.root);+ holder.position.set(...it.pos);+ const dir = new THREE.Vector3(...it.dir).normalize();+ holder.quaternion.setFromUnitVectors(new THREE.Vector3(0, -1, 0), dir);+ if (it.twist) holder.quaternion.premultiply(new THREE.Quaternion().setFromAxisAngle(dir, it.twist));+ const parent = it.parent ? this.byKey.get(it.parent) : undefined;+ (parent ? parent.node : this.root).add(holder);+ d.meshes.forEach((m) => (m.userData.ref = it.ref));+ this.hws.push({ item: it, d, holder, inner, parent });+ }+ this.computeExtents();+ this.computeArrangements();+ this.typeFirst.clear();+ this.introOrderCache.clear();+ for (const p of this.parts) {+ const f = Math.min(...p.item.states.map((x) => x.step));+ this.typeFirst.set(p.type.id, Math.min(this.typeFirst.get(p.type.id) ?? 1e9, f));+ }+ this.camReady = false;+ this.rootReady = false;+ }++ private clear() {+ for (const p of this.parts) {+ this.root.remove(p.node);+ disposeDrawable(p.d);+ }+ for (const h of this.hws) disposeDrawable(h.d);+ this.root.clear();+ this.parts = [];+ this.hws = [];+ this.byKey.clear();+ this.labels.forEach((l) => l.remove());+ this.labels.clear();+ this.arrows.forEach((a) => a.remove());+ this.arrows = [];+ if (this.wall) {+ this.wall.node.removeFromParent();+ disposeDrawable(this.wall.d);+ this.wall = undefined;+ }+ }++ private stateAt(p: PNode, s: number) {+ let st = null;+ let prev = null;+ for (const x of p.item.states) {+ if (x.step <= s) {+ prev = st;+ st = x;+ }+ }+ return { st, prev };+ }++ private corners(p: PNode, pos: Vec3, rot: Vec3) {+ const q = quatFromEuler(rot);+ const o = new THREE.Vector3(...pos);+ return p.corners.map((c) => c.clone().applyQuaternion(q).add(o));+ }++ private computeExtents() {+ const m = new Map<string, THREE.Vector3[]>();+ for (const p of this.parts) {+ for (const s of p.item.states) {+ const arr = m.get(s.scene) ?? [];+ arr.push(...this.corners(p, s.pos, s.rot));+ m.set(s.scene, arr);+ }+ const fin = m.get("final") ?? [];+ fin.push(...this.corners(p, p.item.final.pos, p.item.final.rot));+ m.set("final", fin);+ }+ this.extents = m;+ }++ private flatQuat(t: PartType) {+ const s = t.size;+ const idx = [0, 1, 2];+ const mi = idx.reduce((a, b) => (s[b] < s[a] ? b : a));+ const rest = idx.filter((i) => i !== mi);+ const Mi = s[rest[0]] >= s[rest[1]] ? rest[0] : rest[1];+ const ki = rest.find((i) => i !== Mi)!;+ const cols: THREE.Vector3[] = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];+ cols[mi].set(0, 1, 0);+ cols[Mi].set(1, 0, 0);+ cols[ki].set(0, 0, 1);+ const m = new THREE.Matrix4().makeBasis(cols[0], cols[1], cols[2]);+ if (m.determinant() < 0) {+ cols[ki].set(0, 0, -1);+ m.makeBasis(cols[0], cols[1], cols[2]);+ }+ return { q: new THREE.Quaternion().setFromRotationMatrix(m), thick: s[mi], long: s[Mi], wide: s[ki] };+ }++ private computeArrangements() {+ this.stack.clear();+ this.layout.clear();+ const items = this.parts.filter((p) => !p.type.extra);+ // stack: biggest at the bottom+ const sorted = [...items].sort((a, b) => b.type.size[0] * b.type.size[2] + b.type.size[0] * b.type.size[1] - (a.type.size[0] * a.type.size[2] + a.type.size[0] * a.type.size[1]));+ let y = 0;+ const fq = new Map<string, ReturnType<Stage["flatQuat"]>>();+ for (const p of sorted) {+ const f = this.flatQuat(p.type);+ fq.set(p.item.key, f);+ this.stack.set(p.item.key, { p: new THREE.Vector3(0, y + f.thick / 2, 0), q: f.q });+ y += f.thick + 3;+ }+ // layout: grouped by label, rows+ const byType = [...items].sort((a, b) => a.type.label.localeCompare(b.type.label));+ const area = byType.reduce((s, p) => s + fq.get(p.item.key)!.long * fq.get(p.item.key)!.wide, 0);+ const maxLong = Math.max(...byType.map((p) => fq.get(p.item.key)!.long), 1);+ const rowW = Math.max(maxLong, Math.sqrt(area) * 1.7);+ let x = 0, z = 0, rowD = 0;+ const gap = Math.max(50, maxLong * 0.05);+ const placed: { key: string; x: number; z: number; f: ReturnType<Stage["flatQuat"]> }[] = [];+ for (const p of byType) {+ const f = fq.get(p.item.key)!;+ if (x > 0 && x + f.long > rowW) {+ x = 0;+ z += rowD + gap * 1.6;+ rowD = 0;+ }+ placed.push({ key: p.item.key, x: x + f.long / 2, z: z + f.wide / 2, f });+ x += f.long + gap;+ rowD = Math.max(rowD, f.wide);+ }+ const mx = Math.max(...placed.map((p) => p.x + p.f.long / 2));+ const mz = Math.max(...placed.map((p) => p.z + p.f.wide / 2));+ for (const p of placed) this.layout.set(p.key, { p: new THREE.Vector3(p.x - mx / 2, p.f.thick / 2, p.z - mz / 2), q: p.f.q });+ }++ /* ---------------- modes ---------------- */++ setMode(mode: StageMode, o: { instant?: boolean } = {}) {+ const prev = this.mode;+ this.mode = mode;+ this.t = o.instant ? 999 : 0;+ this.loopCount = 0;+ this.autoReset = true;+ this.introDone = mode.kind !== "intro";+ if (prev.kind === "step" && mode.kind === "step" && this.plan) {+ const a = this.plan.steps[prev.index]?.scene;+ const b = this.plan.steps[mode.index]?.scene;+ if (a !== b) this.flash();+ } else if (prev.kind !== mode.kind && !o.instant) this.flash();+ this.prepareMode();+ if (o.instant) {+ this.camReady = false;+ this.rootReady = false;+ this.tick(0);+ }+ }++ replay() {+ this.t = 0;+ this.loopCount = 0;+ }++ setPaused(p: boolean) {+ this.paused = p;+ }+ setSpeed(s: number) {+ this.speed = s;+ }++ setHighlight(refs: string[] | null) {+ this.highlight = refs && refs.length ? new Set(refs) : null;+ }++ resetView() {+ this.autoReset = true;+ this.opts.onUserView?.(false);+ }++ private flash() {+ const c = this.renderer.domElement;+ c.animate([{ opacity: 0.15 }, { opacity: 1 }], { duration: 420, easing: "cubic-bezier(.2,.8,.2,1)" });+ }++ get step(): Step | null {+ if (this.mode.kind !== "step" || !this.plan) return null;+ return this.plan.steps[this.mode.index] ?? null;+ }++ private prepareMode() {+ const plan = this.plan;+ if (!plan) return;+ this.focus = undefined;+ this.frameLocal = [];+ const m = this.mode;+ if (m.kind === "step") {+ const s = m.index;+ const step = plan.steps[s];+ let end = 0;+ for (const p of this.parts) {+ const { st } = this.stateAt(p, s);+ if (!st || st.scene !== step.scene) continue;+ this.frameLocal.push(...this.corners(p, st.pos, st.rot));+ if (st.step === s) end = Math.max(end, st.delay + PART_DUR + (st.spin ? 0.4 : 0));+ }+ let first: HNode | undefined;+ for (const h of this.hws) {+ if (h.item.step !== s) continue;+ const dur = HW_DUR + (h.item.turn ? CAM_TURN : 0);+ end = Math.max(end, h.item.delay + dur);+ if (h.item.travel > 0 && (!first || h.item.delay < first.item.delay)) first = h;+ }+ this.stepEnd = Math.max(end, 0.6);+ if (first && this.callout) {+ const loc = new THREE.Vector3(...first.item.pos);+ const dir = new THREE.Vector3(...first.item.dir).normalize();+ if (first.parent) {+ const { st } = this.stateAt(first.parent, s);+ if (st) {+ const q = quatFromEuler(st.rot);+ loc.applyQuaternion(q).add(new THREE.Vector3(...st.pos));+ dir.applyQuaternion(q);+ }+ }+ const ht = plan.hardware.find((x) => x.id === first!.item.ref)!;+ const size =+ ht.kind === "runner" ? 55 : ht.kind === "hinge" ? 55 : ht.kind === "bracket" ? 50 : ht.kind === "plate" ? 55 : ht.kind === "knob" || ht.kind === "handle" ? 50 : Math.max(17, Math.min(55, Math.max(ht.len, ht.dia * 2) * 0.72));+ this.focus = { local: loc, dir, size, hw: first };+ }+ // wall+ if (step.wall) this.ensureWall();+ if (step.check === "square") this.ensureSquare();+ } else if (m.kind === "intro") {+ this.frameLocal = [...(this.extents.get("final") ?? [])];+ for (const [k, xf] of this.stack) {+ const p = this.byKey.get(k)!;+ this.frameLocal.push(...p.corners.map((c) => c.clone().applyQuaternion(xf.q).add(xf.p)));+ }+ this.stepEnd = 0.3 + this.parts.length * this.introGap() + PART_DUR + 0.6;+ } else if (m.kind === "assembled") {+ this.frameLocal = [...(this.extents.get("final") ?? [])];+ for (const f of m.frame ?? []) this.frameLocal.push(new THREE.Vector3(...f));+ } else if (m.kind === "layout") {+ for (const [k, xf] of this.layout) {+ const p = this.byKey.get(k)!;+ this.frameLocal.push(...p.corners.map((c) => c.clone().applyQuaternion(xf.q).add(xf.p)));+ }+ } else if (m.kind === "part") {+ const p = this.parts.find((x) => x.item.ref === m.ref);+ if (p) this.frameLocal = p.corners.map((c) => c.clone());+ }+ }++ private introGap() {+ return Math.min(0.14, 2.0 / Math.max(1, this.parts.length));+ }++ private ensureWall() {+ if (this.wall) return;+ const fin = this.extents.get("final") ?? [];+ const box = new THREE.Box3().setFromPoints(fin);+ const w = box.max.x - box.min.x + 700;+ const h = box.max.y + 420;+ const d = wallDrawable(w, h);+ const node = new THREE.Group();+ node.add(d.root);+ node.position.set((box.min.x + box.max.x) / 2, h / 2, box.min.z - 20);+ this.root.add(node);+ for (const l of d.lines) l.color.copy(INK_OLD);+ this.wall = { d, node, on: 0 };+ }++ private ensureSquare() {+ if (!this.overlay || this.squareEls.length) return;+ const ns = "http://www.w3.org/2000/svg";+ for (let i = 0; i < 2; i++) {+ const p = document.createElementNS(ns, "path");+ p.setAttribute("class", "diag");+ this.overlay.appendChild(p);+ this.squareEls.push(p);+ }+ const eq = document.createElementNS(ns, "g");+ eq.setAttribute("class", "diag-eq");+ eq.innerHTML = '<circle r="17"></circle><path d="M-7 -3.5 H7 M-7 3.5 H7"></path>';+ this.overlay.appendChild(eq);+ this.squareEls.push(eq);+ }++ /* ---------------- per frame ---------------- */++ tick(dt: number) {+ if (!this.plan) return;+ if (!this.paused) this.t += dt * this.speed;+ const m = this.mode;+ if (m.kind === "step" && this.opts.loop !== false) {+ const cycle = this.stepEnd + HOLD + FADE;+ if (this.t > cycle) {+ this.t = 0;+ this.loopCount++;+ }+ }+ if (m.kind === "intro" && !this.introDone && this.t > this.stepEnd) {+ this.introDone = true;+ this.opts.onIntroDone?.();+ this.mode = { kind: "assembled", turntable: true, dims: m.kind === "intro" && !!m.dims };+ this.t = 0;+ this.prepareMode();+ }+ this.updateRoot(dt);+ this.updateItems();+ this.updateCamera(dt);+ }++ private targetPoseQ() {+ const st = this.step;+ if (st) return quatFromEuler(POSE_EULER[st.pose]);+ return new THREE.Quaternion();+ }++ private sceneName() {+ const st = this.step;+ if (st) return st.scene === "main" ? "final" : st.scene;+ return "final";+ }++ private updateRoot(dt: number) {+ const q = this.targetPoseQ();+ if (!this.rootReady || dt === 0) {+ this.rootQ.copy(q);+ this.rootReady = true;+ } else {+ this.rootQ.slerp(q, 1 - Math.exp(-dt * 3.2));+ }+ this.root.quaternion.copy(this.rootQ);+ // ground and centre+ const pts = this.extents.get(this.sceneName()) ?? [];+ if (!pts.length) return;+ let minY = Infinity, minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;+ for (const c of pts) {+ tmpV.copy(c).applyQuaternion(this.rootQ);+ minY = Math.min(minY, tmpV.y);+ minX = Math.min(minX, tmpV.x);+ maxX = Math.max(maxX, tmpV.x);+ minZ = Math.min(minZ, tmpV.z);+ maxZ = Math.max(maxZ, tmpV.z);+ }+ if (this.mode.kind === "layout" || this.mode.kind === "intro") minY = 0;+ this.root.position.set(-(minX + maxX) / 2, -minY, -(minZ + maxZ) / 2);+ if (this.mode.kind === "layout" || this.mode.kind === "intro" || this.mode.kind === "part") this.root.position.set(0, 0, 0);+ // shadow footprint+ const sw = (maxX - minX) * 1.35 + 200, sd = (maxZ - minZ) * 1.35 + 200;+ this.shadow.scale.set(sw, sd, 1);+ this.shadow.visible = this.mode.kind !== "layout" && this.mode.kind !== "part";+ this.root.updateMatrixWorld(true);+ }++ private styleDrawable(d: Drawable, o: { opacity: number; ink: boolean; tint: number; width: number }) {+ d.opacity = o.opacity;+ for (const f of d.faces) {+ f.uniforms.uOpacity.value = o.opacity;+ f.uniforms.uTintAmt.value = o.tint;+ f.depthWrite = o.opacity > 0.05;+ }+ const col = o.ink ? INK : INK_OLD;+ const lw = this.opts.offscreen ? o.width * 1.15 : o.width;+ for (const l of d.lines) {+ l.color.copy(col);+ l.opacity = o.opacity;+ l.linewidth = lw;+ }+ for (const l of d.thin) {+ l.color.copy(col);+ l.opacity = o.opacity * 0.9;+ l.linewidth = Math.max(0.8, o.width * 0.62);+ }+ for (const hm of d.hulls) {+ hm.uniforms.uColor.value.copy(col);+ hm.uniforms.uOpacity.value = o.opacity;+ hm.uniforms.uWidth.value = o.width * 0.95;+ }+ }++ private updateItems() {+ const m = this.mode;+ const t = this.t;+ const step = this.step;+ const sIdx = m.kind === "step" ? m.index : -1;+ const scene = step?.scene ?? "main";+ const loops = this.opts.loop !== false;+ const fadeOut = loops && m.kind === "step" && t > this.stepEnd + HOLD ? 1 - clamp01((t - this.stepEnd - HOLD) / FADE) : 1;+ const hl = this.highlight;++ const visibleParts = new Set<PNode>();+ for (const p of this.parts) {+ const node = p.node;+ const ref = p.item.ref;+ const hover = this.hovered === ref;+ const lit = hl?.has(ref) ?? false;+ if (m.kind === "step") {+ const { st, prev } = this.stateAt(p, sIdx);+ if (!st || st.scene !== scene) {+ node.visible = false;+ continue;+ }+ node.visible = true;+ visibleParts.add(p);+ const isNew = st.step === sIdx;+ const fin = { p: new THREE.Vector3(...st.pos), q: quatFromEuler(st.rot) };+ if (isNew) {+ const k = clamp01((t - st.delay) / (PART_DUR + (st.spin ? 0.4 : 0)));+ const e = easeOut(k);+ let op = clamp01((t - st.delay) / 0.22) * fadeOut;+ if (prev && prev.scene === st.scene) {+ node.position.lerpVectors(new THREE.Vector3(...prev.pos), fin.p, easeInOut(k));+ node.quaternion.slerpQuaternions(quatFromEuler(prev.rot), fin.q, easeInOut(k));+ op = 1;+ } else {+ const from = st.from ? new THREE.Vector3(...st.from) : new THREE.Vector3();+ node.position.copy(fin.p).addScaledVector(from, 1 - e);+ node.quaternion.copy(fin.q);+ if (st.spin) {+ tmpQ.setFromAxisAngle(Y, -(1 - e) * st.spin * Math.PI * 2);+ node.quaternion.multiply(tmpQ);+ }+ }+ const landed = k >= 1 ? clamp01((t - st.delay - PART_DUR) / 0.5) : 0;+ this.styleDrawable(p.d, { opacity: op, ink: true, tint: (hover || lit ? 0.75 : 0.34 - landed * 0.1), width: 2.2 });+ } else {+ node.position.copy(fin.p);+ node.quaternion.copy(fin.q);+ this.styleDrawable(p.d, { opacity: 1, ink: hover || lit, tint: hover || lit ? 0.7 : 0, width: hover || lit ? 1.9 : 1.5 });+ }+ } else if (m.kind === "intro") {+ node.visible = true;+ visibleParts.add(p);+ const order = this.introOrder(p);+ const gap = this.introGap();+ const delay = 0.3 + order * gap;+ const k = clamp01((t - delay) / PART_DUR);+ const e = easeInOut(k);+ const a = this.stack.get(p.item.key);+ const fin = { p: new THREE.Vector3(...p.item.final.pos), q: quatFromEuler(p.item.final.rot) };+ if (a) {+ node.position.lerpVectors(a.p, fin.p, e);+ node.position.y += Math.sin(Math.PI * e) * 260;+ node.quaternion.slerpQuaternions(a.q, fin.q, e);+ this.styleDrawable(p.d, { opacity: 1, ink: true, tint: k > 0 && k < 1 ? 0.5 : 0, width: 1.9 });+ } else {+ node.position.copy(fin.p).add(new THREE.Vector3(0, 400 * (1 - easeOut(k)), 0));+ node.quaternion.copy(fin.q);+ this.styleDrawable(p.d, { opacity: clamp01((t - delay) / 0.3), ink: true, tint: 0, width: 1.9 });+ }+ } else if (m.kind === "layout") {+ const a = this.layout.get(p.item.key);+ if (!a) {+ node.visible = false;+ continue;+ }+ node.visible = true;+ visibleParts.add(p);+ node.position.copy(a.p);+ node.quaternion.copy(a.q);+ this.styleDrawable(p.d, { opacity: hl && !lit ? 0.35 : 1, ink: true, tint: lit || hover ? 0.85 : 0, width: lit || hover ? 2.3 : 1.8 });+ } else if (m.kind === "part") {+ const first = this.parts.find((x) => x.item.ref === m.ref);+ node.visible = first === p;+ if (first === p) {+ visibleParts.add(p);+ node.position.set(0, 0, 0);+ node.quaternion.identity();+ this.styleDrawable(p.d, { opacity: 1, ink: true, tint: 0, width: 2 });+ }+ } else {+ node.visible = true;+ visibleParts.add(p);+ node.position.set(...p.item.final.pos);+ node.quaternion.copy(quatFromEuler(p.item.final.rot));+ this.styleDrawable(p.d, { opacity: 1, ink: true, tint: hover || lit ? 0.6 : 0, width: 1.9 });+ }+ }++ // hardware+ for (const h of this.hws) {+ const it = h.item;+ let vis = false;+ if (m.kind === "step") {+ vis = it.step <= sIdx && (h.parent ? visibleParts.has(h.parent) : it.scene === scene);+ } else if (m.kind === "assembled") vis = !!h.parent && !this.plan?.steps[it.step]?.wall;+ else if (m.kind === "intro") vis = t > this.stepEnd - 0.7 && !!h.parent && !this.plan?.steps[it.step]?.wall;+ h.holder.visible = vis;+ if (!vis) continue;+ const isNew = m.kind === "step" && it.step === sIdx;+ if (isNew && it.travel > 0) {+ const k = clamp01((t - it.delay) / HW_DUR);+ const e = easeInOut(k);+ h.inner.position.set(0, it.travel * (1 - e), 0);+ let ang = (it.spin ?? 0) * Math.PI * 2 * e;+ if (it.turn) ang += it.turn * easeInOut(clamp01((t - it.delay - HW_DUR) / CAM_TURN));+ h.inner.quaternion.setFromAxisAngle(Y, ang);+ const op = clamp01((t - it.delay) / 0.15) * fadeOut;+ this.styleDrawable(h.d, { opacity: op, ink: true, tint: 0, width: 1.6 });+ } else {+ h.inner.position.set(0, 0, 0);+ h.inner.quaternion.setFromAxisAngle(Y, (it.spin ?? 0) * Math.PI * 2 + (it.turn ?? 0));+ const op = m.kind === "intro" ? clamp01((t - this.stepEnd + 0.7) / 0.5) : 1;+ const lit = this.highlight?.has(it.ref) ?? false;+ this.styleDrawable(h.d, { opacity: op, ink: isNew || lit || m.kind !== "step", tint: lit ? 0.8 : 0, width: lit ? 1.7 : 1.25 });+ }+ }++ // wall+ if (this.wall) {+ const on = !!step?.wall;+ this.wall.on += ((on ? 1 : 0) - this.wall.on) * 0.12;+ this.wall.node.visible = this.wall.on > 0.02;+ this.styleDrawable(this.wall.d, { opacity: this.wall.on * 0.9, ink: false, tint: 0, width: 1.2 });+ }+ }++ private introOrderCache = new Map<string, number>();+ private introOrder(p: PNode) {+ if (!this.introOrderCache.size) {+ const sorted = [...this.parts].sort((a, b) => {+ const sa = a.item.states[a.item.states.length - 1].step, sb = b.item.states[b.item.states.length - 1].step;+ return sa - sb || a.item.states[a.item.states.length - 1].delay - b.item.states[b.item.states.length - 1].delay;+ });+ sorted.forEach((x, i) => this.introOrderCache.set(x.item.key, i));+ }+ return this.introOrderCache.get(p.item.key) ?? 0;+ }++ private camAngles() {+ let az = this.az, el = this.el0;+ if (this.mode.kind === "layout") {+ az = 0.22;+ el = 1.0;+ }+ if (this.mode.kind === "assembled" && this.mode.view) {+ az = this.mode.view.az;+ el = this.mode.view.el;+ }+ if (this.mode.kind === "assembled" && this.mode.turntable) az += Math.sin(performance.now() / 1000 / 3.2) * 0.32;+ if (this.mode.kind === "part") {+ az = 0.7;+ el = 0.5;+ }+ return { az: az + this.userAz, el: Math.max(0.05, Math.min(1.45, el + this.userEl)) };+ }++ private updateCamera(dt: number) {+ if (this.autoReset && !this.dragging) {+ const k = dt === 0 ? 1 : 1 - Math.exp(-dt * 4);+ this.userAz += (0 - this.userAz) * k;+ this.userEl += (0 - this.userEl) * k;+ this.userZoom += (1 - this.userZoom) * k;+ }+ const { az, el } = this.camAngles();+ const dir = new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el));+ const right = new THREE.Vector3().crossVectors(Y, dir).normalize();+ const up = new THREE.Vector3().crossVectors(dir, right).normalize();+ // fit+ const pts = this.frameLocal;+ let minR = Infinity, maxR = -Infinity, minU = Infinity, maxU = -Infinity;+ const center = new THREE.Vector3();+ const w = new THREE.Vector3();+ if (pts.length) {+ for (const c of pts) {+ w.copy(c).applyMatrix4(this.root.matrixWorld);+ const r = w.dot(right), u = w.dot(up);+ minR = Math.min(minR, r);+ maxR = Math.max(maxR, r);+ minU = Math.min(minU, u);+ maxU = Math.max(maxU, u);+ }+ } else {+ minR = minU = -500;+ maxR = maxU = 500;+ }+ const aspect = this.w / this.h;+ const mob = this.w < 640;+ const k = this.mode.kind;+ const m = this.opts.margins ?? { t: 0, r: 0, b: 0, l: 0 };+ let mT = 40, mR = 40, mB = 40, mL = 40;+ if (this.opts.offscreen) {+ const pad = Math.round(Math.min(this.w, this.h) * 0.07);+ mT = mR = mB = mL = k === "part" ? 4 : pad;+ } else if (k === "step") {+ const co = this.callout && this.focus ? this.callout.size + (mob ? 24 : 56) : 0;+ mT = (mob ? 70 : 96) + m.t;+ mL = (mob ? 18 : 36) + m.l;+ mB = (mob ? 56 : 72) + m.b;+ mR = Math.max(mob ? 18 : 36, co * (mob ? 0.55 : 1)) + m.r;+ } else if (k === "part") {+ mT = mR = mB = mL = 4;+ } else if (k === "layout") {+ mT = mob ? 30 : 60;+ mB = mob ? 40 : 70;+ mL = mR = mob ? 16 : 40;+ } else {+ mT = (mob ? 36 : 70) + m.t;+ mB = (mob ? 36 : 70) + m.b;+ mL = (mob ? 24 : 70) + m.l;+ mR = (mob ? 24 : 70) + m.r;+ }+ const fit = (l: number, t: number, r: number, b: number) => {+ const aw = Math.max(60, this.w - l - r), ah = Math.max(60, this.h - t - b);+ return { l, t, aw, ah, s: Math.max((maxR - minR) / aw, (maxU - minU) / ah, 0.05) };+ };+ let best = fit(mL, mT, mR, mB);+ if (k === "step" && this.callout && this.focus) {+ // the circle only blocks the top right corner: try keeping the drawing below it instead+ const below = fit(mL, Math.max(mT, this.callout.size + 34), (mob ? 18 : 36) + m.r, mB);+ if (below.s < best.s) best = below;+ }+ mL = best.l;+ mT = best.t;+ const availW = best.aw, availH = best.ah;+ const scale = best.s * (k === "part" ? 1.04 : 1.06);+ let halfH = (scale * this.h) / 2;+ const offX = mL + availW / 2 - this.w / 2, offY = mT + availH / 2 - this.h / 2;+ const cr = (minR + maxR) / 2 - offX * scale * this.userZoom, cu = (minU + maxU) / 2 + offY * scale * this.userZoom;+ void aspect;+ halfH = Math.max(halfH, 60) * this.userZoom;+ center.copy(right).multiplyScalar(cr).addScaledVector(up, cu);+ // keep depth component around the bbox centre+ if (pts.length) {+ const box = new THREE.Box3();+ for (const c of pts) box.expandByPoint(w.copy(c).applyMatrix4(this.root.matrixWorld));+ const bc = box.getCenter(new THREE.Vector3());+ center.addScaledVector(dir, bc.dot(dir));+ }+ if (!this.camReady || dt === 0) {+ this.camTarget.copy(center);+ this.camHalf = halfH;+ this.camReady = true;+ } else {+ const k = 1 - Math.exp(-dt * 4.2);+ this.camTarget.lerp(center, k);+ this.camHalf += (halfH - this.camHalf) * k;+ }+ const cam = this.camera;+ cam.left = -this.camHalf * aspect;+ cam.right = this.camHalf * aspect;+ cam.top = this.camHalf;+ cam.bottom = -this.camHalf;+ cam.position.copy(this.camTarget).addScaledVector(dir, 8000);+ cam.up.copy(Y);+ cam.lookAt(this.camTarget);+ cam.near = 10;+ cam.far = 30000;+ cam.updateProjectionMatrix();+ cam.updateMatrixWorld();+ }++ /* ---------------- render ---------------- */++ private setRes(w: number, h: number) {+ const dpr = this.renderer.getPixelRatio();+ const set = (d: Drawable) => {+ for (const l of d.lines) l.resolution.set(w, h);+ for (const l of d.thin) l.resolution.set(w, h);+ for (const hm of d.hulls) hm.uniforms.uRes.value.set(w, h);+ };+ void dpr;+ this.parts.forEach((p) => set(p.d));+ this.hws.forEach((x) => set(x.d));+ if (this.wall) set(this.wall.d);+ }++ render() {+ this.setRes(this.w, this.h);+ this.renderer.render(this.scene, this.camera);+ if (!this.overlay) return;+ this.updateOverlay();+ this.renderCallout();+ }++ /** Render once at a size and return a PNG data URL (offscreen stages). */+ snapshot(w: number, h: number) {+ this.resize(w, h);+ this.camReady = false;+ this.rootReady = false;+ this.tick(0);+ this.setRes(w, h);+ this.renderer.render(this.scene, this.camera);+ return this.renderer.domElement.toDataURL("image/png");+ }++ /** Image coordinates of a point given in the plan's assembled frame, for the last render. */+ locate(p: Vec3) {+ const v = new THREE.Vector3(...p);+ this.root.updateMatrixWorld(true);+ this.root.localToWorld(v);+ return this.project(v);+ }++ private project(v: THREE.Vector3) {+ const p = v.clone().project(this.camera);+ return { x: ((p.x + 1) / 2) * this.w, y: ((1 - p.y) / 2) * this.h };+ }++ private updateOverlay() {+ const plan = this.plan;+ if (!plan || !this.overlay) return;+ const m = this.mode;+ const t = this.t;+ const step = this.step;+ const ns = "http://www.w3.org/2000/svg";+ this.overlay.setAttribute("viewBox", `0 0 ${this.w} ${this.h}`);++ // arrows for parts flying in+ const wanted: { d: string; o: number }[] = [];+ const arrowKeys = new Set<string>();+ const wantedLabels = new Map<string, { x: number; y: number; text: string; sub?: string; o: number; lit: boolean }>();+ if (m.kind === "step" && step) {+ const fade = this.opts.loop !== false && t > this.stepEnd + HOLD ? 1 - clamp01((t - this.stepEnd - HOLD) / FADE) : 1;+ for (const p of this.parts) {+ if (!p.node.visible) continue;+ const { st, prev } = this.stateAt(p, m.index);+ if (!st || st.step !== m.index) continue;+ const akey = st.from ? st.from.join(",") + "@" + st.delay.toFixed(2) : "";+ if (st.from && !(prev && prev.scene === st.scene) && !arrowKeys.has(akey)) {+ arrowKeys.add(akey);+ const fin = new THREE.Vector3(...st.pos);+ const from = new THREE.Vector3(...st.from);+ const len = from.length();+ if (len > 60) {+ const k = (t - st.delay) / PART_DUR;+ const o = (k < 0 ? clamp01(1 + k * 4) : k < 0.75 ? 1 : clamp01(1 - (k - 0.75) * 4)) * fade;+ if (o > 0.01) {+ const a = this.root.localToWorld(fin.clone().addScaledVector(from, 1.12));+ const b = this.root.localToWorld(fin.clone().addScaledVector(from, 0.42));+ const pa = this.project(a), pb = this.project(b);+ const dd = Math.hypot(pb.x - pa.x, pb.y - pa.y);+ if (dd > 26) wanted.push({ d: arrowPath(pa, pb, Math.min(1, dd / 60)), o });+ }+ }+ }+ if (this.labelLayer && !p.type.extra && this.typeFirst.get(p.type.id) === m.index) {+ const k = clamp01((t - st.delay - PART_DUR * 0.55) / 0.3) * fade;+ if (!wantedLabels.has(p.type.id) && k > 0) {+ const c = new THREE.Vector3();+ p.node.getWorldPosition(c);+ const sp = this.project(c);+ wantedLabels.set(p.type.id, { x: sp.x, y: sp.y, text: p.type.label, o: k, lit: this.highlight?.has(p.type.id) ?? false });+ }+ }+ }+ }+ if (m.kind === "layout" && this.labelLayer) {+ const counts = new Map<string, number>();+ this.parts.forEach((p) => counts.set(p.type.id, (counts.get(p.type.id) ?? 0) + 1));+ for (const p of this.parts) {+ if (!p.node.visible || wantedLabels.has(p.type.id) || p.type.extra) continue;+ const c = new THREE.Vector3();+ p.node.getWorldPosition(c);+ const sp = this.project(c);+ const n = counts.get(p.type.id) ?? 1;+ wantedLabels.set(p.type.id, { x: sp.x, y: sp.y, text: p.type.label, sub: n > 1 ? `${n}×` : undefined, o: 1, lit: this.highlight?.has(p.type.id) ?? false });+ }+ }+ while (this.arrows.length < wanted.length) {+ const a = document.createElementNS(ns, "path") as SVGPathElement;+ a.setAttribute("class", "arrow");+ this.overlay.insertBefore(a, this.overlay.firstChild);+ this.arrows.push(a);+ }+ this.arrows.forEach((a, i) => {+ const w = wanted[i];+ if (!w) {+ a.style.opacity = "0";+ return;+ }+ a.setAttribute("d", w.d);+ a.style.opacity = String(w.o);+ });++ // labels+ if (this.labelLayer) {+ for (const [id, el] of this.labels) {+ if (!wantedLabels.has(id)) {+ el.remove();+ this.labels.delete(id);+ }+ }+ for (const [id, l] of wantedLabels) {+ let el = this.labels.get(id);+ if (!el) {+ el = document.createElement("div");+ el.className = "stage-label";+ this.labelLayer.appendChild(el);+ this.labels.set(id, el);+ }+ const html = `<b>${l.text}</b>${l.sub ? `<span>${l.sub}</span>` : ""}`;+ if (el.innerHTML !== html) el.innerHTML = html;+ el.style.transform = `translate(${l.x}px, ${l.y}px) translate(-50%, -50%) scale(${0.7 + 0.3 * l.o})`;+ el.style.opacity = String(l.o);+ el.classList.toggle("lit", l.lit);+ }+ }++ // dimension lines on the cover+ this.updateDims();++ // square check+ if (this.squareEls.length) {+ const on = step?.check === "square";+ const [d1, d2, eq] = this.squareEls;+ if (on && plan) {+ const fin = this.extents.get("final")!;+ const box = new THREE.Box3().setFromPoints(fin);+ const z = box.min.z;+ const cs = [+ new THREE.Vector3(box.min.x + 30, box.min.y + 30, z),+ new THREE.Vector3(box.max.x - 30, box.max.y - 30, z),+ new THREE.Vector3(box.max.x - 30, box.min.y + 30, z),+ new THREE.Vector3(box.min.x + 30, box.max.y - 30, z),+ ].map((v) => this.project(this.root.localToWorld(v)));+ const k = easeInOut(clamp01((t - 0.3) / 1.2));+ const seg = (a: { x: number; y: number }, b: { x: number; y: number }) => {+ const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;+ const ax = mx + (a.x - mx) * k, ay = my + (a.y - my) * k, bx = mx + (b.x - mx) * k, by = my + (b.y - my) * k;+ return doubleArrow({ x: ax, y: ay }, { x: bx, y: by });+ };+ d1.setAttribute("d", seg(cs[0], cs[1]));+ d2.setAttribute("d", seg(cs[2], cs[3]));+ const cx = (cs[0].x + cs[1].x) / 2, cy = (cs[0].y + cs[1].y) / 2;+ eq.setAttribute("transform", `translate(${cx} ${cy}) scale(${k})`);+ for (const e of this.squareEls) (e as SVGElement).style.opacity = String(k > 0 ? 1 : 0);+ } else for (const e of this.squareEls) (e as SVGElement).style.opacity = "0";+ }+ }++ private updateDims() {+ const m = this.mode;+ const on = m.kind === "assembled" && !!m.dims && this.plan;+ if (!on) {+ if (this.dimsEl) this.dimsEl.style.opacity = "0";+ return;+ }+ const ns = "http://www.w3.org/2000/svg";+ if (!this.dimsEl) {+ this.dimsEl = document.createElementNS(ns, "g") as SVGGElement;+ this.dimsEl.setAttribute("class", "dims");+ this.overlay!.appendChild(this.dimsEl);+ }+ const fin = this.extents.get("final") ?? [];+ if (!fin.length) return;+ const box = new THREE.Box3().setFromPoints(fin);+ const size = this.plan!.spec.size;+ const k = easeInOut(clamp01((this.t - 0.2) / 0.9));+ const sz = Math.max(box.max.x - box.min.x, box.max.y - box.min.y);+ const off = sz * 0.07;+ const P = (x: number, y: number, z: number) => this.project(this.root.localToWorld(new THREE.Vector3(x, y, z)));+ const line = (a: THREE.Vector3Tuple, b: THREE.Vector3Tuple, o: THREE.Vector3Tuple, label: string, side: number) => {+ const a0 = P(...a), b0 = P(...b);+ const a1 = P(a[0] + o[0], a[1] + o[1], a[2] + o[2]), b1 = P(b[0] + o[0], b[1] + o[1], b[2] + o[2]);+ const mx = (a1.x + b1.x) / 2, my = (a1.y + b1.y) / 2;+ const ax = mx + (a1.x - mx) * k, ay = my + (a1.y - my) * k, bx = mx + (b1.x - mx) * k, by = my + (b1.y - my) * k;+ const dx = b1.x - a1.x, dy = b1.y - a1.y, L = Math.hypot(dx, dy) || 1;+ const ux = dx / L, uy = dy / L, h = 7;+ const head = (x: number, y: number, s2: number) => `M${x + s2 * ux * h + uy * h * 0.55} ${y + s2 * uy * h - ux * h * 0.55} L${x} ${y} L${x + s2 * ux * h - uy * h * 0.55} ${y + s2 * uy * h + ux * h * 0.55}`;+ const ext = `M${a0.x} ${a0.y} L${a1.x + (a1.x - a0.x) * 0.25} ${a1.y + (a1.y - a0.y) * 0.25} M${b0.x} ${b0.y} L${b1.x + (b1.x - b0.x) * 0.25} ${b1.y + (b1.y - b0.y) * 0.25}`;+ const lx = mx - uy * 16 * side, ly = my + ux * 16 * side;+ return `<path class="ext" d="${ext}" style="opacity:${k * 0.6}"/><path class="dim" d="M${ax} ${ay} L${bx} ${by} ${k > 0.98 ? head(a1.x, a1.y, 1) + head(b1.x, b1.y, -1) : ""}"/><text x="${lx}" y="${ly + 5}" style="opacity:${clamp01((k - 0.6) / 0.4)}">${label}</text>`;+ };+ const { min, max } = box;+ let html = "";+ html += line([min.x, min.y, max.z], [max.x, min.y, max.z], [0, -off * 0.2, off], `${Math.round(size.w)} cm`, 1);+ html += line([max.x, min.y, max.z], [max.x, min.y, min.z], [off, -off * 0.2, 0], `${Math.round(size.d)} cm`, 1);+ html += line([min.x, min.y, max.z], [min.x, max.y, max.z], [-off, 0, off * 0.3], `${Math.round(size.h)} cm`, -1);+ if (this.dimsEl.innerHTML !== html) this.dimsEl.innerHTML = html;+ this.dimsEl.style.opacity = "1";+ }++ private renderCallout() {+ const co = this.callout;+ if (!co || !this.leader || !this.leaderDot) return;+ const f = this.mode.kind === "step" ? this.focus : undefined;+ const t = this.t;+ let target = 0;+ if (f) {+ const k = (t - f.hw.item.delay + 0.5) / 0.4;+ target = clamp01(k);+ if (t > this.stepEnd + HOLD) target = 1;+ }+ co.visible += (target - co.visible) * 0.18;+ const show = co.visible > 0.02 && !!f;+ co.wrap.style.opacity = String(co.visible);+ co.wrap.style.transform = `scale(${0.85 + 0.15 * co.visible})`;+ co.wrap.style.visibility = show ? "visible" : "hidden";+ this.leader.style.opacity = this.leaderDot.style.opacity = String(show ? co.visible : 0);+ if (!show || !f) return;++ const world = this.root.localToWorld(f.local.clone());+ const dirW = f.dir.clone().applyQuaternion(this.root.quaternion).normalize();+ const camDir = new THREE.Vector3().subVectors(this.camera.position, this.camTarget).normalize().negate();+ const view = dirW.clone().multiplyScalar(0.85).addScaledVector(camDir, 0.55).normalize();+ const cam = co.camera;+ const half = f.size;+ cam.left = -half;+ cam.right = half;+ cam.top = half;+ cam.bottom = -half;+ cam.position.copy(world).addScaledVector(view, -900);+ cam.up.copy(Math.abs(view.y) > 0.92 ? new THREE.Vector3(0, 0, -1) : Y);+ cam.lookAt(world);+ cam.near = 900 - Math.max(120, half * 2.2);+ cam.far = 900 + 900;+ cam.updateProjectionMatrix();+ cam.updateMatrixWorld();+ const s = co.size;+ this.setRes(s, s);+ const sh = this.shadow.visible;+ this.shadow.visible = false;+ if (this.wall) this.wall.node.visible = this.wall.on > 0.02;+ co.renderer.render(this.scene, cam);+ this.shadow.visible = sh;+ this.setRes(this.w, this.h);++ // leader line from the spot in the main view to the circle+ const sp = this.project(world);+ const rect = co.wrap.getBoundingClientRect();+ const host = this.el.getBoundingClientRect();+ const cx = rect.left - host.left + rect.width / 2;+ const cy = rect.top - host.top + rect.height / 2;+ const r = rect.width / 2;+ const ang = Math.atan2(sp.y - cy, sp.x - cx);+ const ex = cx + Math.cos(ang) * r, ey = cy + Math.sin(ang) * r;+ this.leader.setAttribute("d", `M${sp.x} ${sp.y} L${ex} ${ey}`);+ this.leaderDot.setAttribute("cx", String(sp.x));+ this.leaderDot.setAttribute("cy", String(sp.y));++ // callout arrows: insertion + rotation+ const ns = "http://www.w3.org/2000/svg";+ const svg = co.svg;+ svg.setAttribute("viewBox", `0 0 ${s} ${s}`);+ const it = f.hw.item;+ const k = clamp01((t - it.delay) / HW_DUR);+ const proj = (v: THREE.Vector3) => {+ const p = v.clone().project(cam);+ return { x: ((p.x + 1) / 2) * s, y: ((1 - p.y) / 2) * s };+ };+ const a = proj(world.clone().addScaledVector(dirW, -half * 1.15));+ const b = proj(world.clone().addScaledVector(dirW, -half * 0.45));+ let html = "";+ const op1 = k < 1 ? 1 : clamp01(1 - (t - it.delay - HW_DUR) * 2);+ if (Math.hypot(b.x - a.x, b.y - a.y) > 18) html += `<path class="arrow" style="opacity:${op1}" d="${arrowPath(a, b, 0.9)}"/>`;+ const turning = (it.turn ?? 0) > 0 || (it.spin ?? 0) > 0;+ if (turning) {+ const c = proj(world);+ const tk = it.turn ? clamp01((t - it.delay - HW_DUR) / CAM_TURN) : k;+ const op2 = it.turn ? (tk > 0 ? 1 : 0) : 1;+ html += `<path class="arrow turn" style="opacity:${op2}" d="${arcArrow(c.x, c.y, Math.min(34, s * 0.2), -2.4 + tk * 0.4, 0.9 + tk * 0.4)}"/>`;+ }+ if (svg.innerHTML !== html) svg.innerHTML = html;+ void ns;+ }++ /* ---------------- pointer ---------------- */++ private bindPointer() {+ const c = this.renderer.domElement;+ c.style.touchAction = "none";+ c.addEventListener("pointerdown", (e) => {+ c.setPointerCapture(e.pointerId);+ this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ this.downAt = { x: e.clientX, y: e.clientY, t: performance.now() };+ if (this.pointers.size === 2) {+ const [p1, p2] = [...this.pointers.values()];+ this.pinch0 = Math.hypot(p1.x - p2.x, p1.y - p2.y);+ this.zoom0 = this.userZoom;+ }+ this.dragging = true;+ });+ c.addEventListener("pointermove", (e) => {+ const prev = this.pointers.get(e.pointerId);+ if (!prev) {+ this.hoverAt(e.clientX, e.clientY);+ return;+ }+ if (this.pointers.size === 2) {+ this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ const [p1, p2] = [...this.pointers.values()];+ const d = Math.hypot(p1.x - p2.x, p1.y - p2.y);+ if (this.pinch0 > 0) this.userZoom = Math.max(0.35, Math.min(2.5, (this.zoom0 * this.pinch0) / d));+ } else {+ const dx = e.clientX - prev.x, dy = e.clientY - prev.y;+ this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ this.userAz -= dx * 0.0075;+ this.userEl += dy * 0.005;+ this.userEl = Math.max(-0.4, Math.min(0.95, this.userEl));+ }+ if (Math.hypot(e.clientX - this.downAt.x, e.clientY - this.downAt.y) > 4 && this.autoReset) {+ this.autoReset = false;+ this.opts.onUserView?.(true);+ }+ this.setHover(null);+ });+ const up = (e: PointerEvent) => {+ this.pointers.delete(e.pointerId);+ if (this.pointers.size === 0) this.dragging = false;+ this.pinch0 = 0;+ };+ c.addEventListener("pointerup", up);+ c.addEventListener("pointercancel", up);+ c.addEventListener("pointerleave", () => this.setHover(null));+ c.addEventListener(+ "wheel",+ (e) => {+ if (!e.ctrlKey && Math.abs(e.deltaY) < 1) return;+ e.preventDefault();+ this.userZoom = Math.max(0.35, Math.min(2.5, this.userZoom * Math.exp(e.deltaY * 0.0015)));+ if (this.autoReset) {+ this.autoReset = false;+ this.opts.onUserView?.(true);+ }+ },+ { passive: false },+ );+ c.addEventListener("dblclick", () => this.resetView());+ this.tooltip = document.createElement("div");+ this.tooltip.className = "stage-tip";+ this.el.appendChild(this.tooltip);+ }++ private ray = new THREE.Raycaster();+ private hoverAt(x: number, y: number) {+ if (!this.plan || matchMedia("(hover: none)").matches) return;+ const r = this.el.getBoundingClientRect();+ const nx = ((x - r.left) / r.width) * 2 - 1, ny = -((y - r.top) / r.height) * 2 + 1;+ this.ray.setFromCamera(new THREE.Vector2(nx, ny), this.camera);+ const meshes: THREE.Object3D[] = [];+ for (const p of this.parts) if (p.node.visible && p.d.opacity > 0.5) meshes.push(...p.d.meshes);+ const hit = this.ray.intersectObjects(meshes, false)[0];+ const ref = (hit?.object.userData.ref as string) ?? null;+ this.setHover(ref);+ if (this.tooltip) {+ const type = ref ? this.plan.parts.find((p) => p.id === ref) : null;+ if (type && !type.extra) {+ this.tooltip.innerHTML = `<b>${type.label}</b>${type.name}`;+ this.tooltip.style.transform = `translate(${x - r.left + 14}px, ${y - r.top + 16}px)`;+ this.tooltip.style.opacity = "1";+ } else this.tooltip.style.opacity = "0";+ }+ }++ private setHover(ref: string | null) {+ if (this.hovered === ref) return;+ this.hovered = ref;+ this.opts.onHover?.(ref);+ if (!ref && this.tooltip) this.tooltip.style.opacity = "0";+ }++ dispose() {+ this.disposed = true;+ cancelAnimationFrame(this.raf);+ clearInterval(this.fallback);+ this.ro?.disconnect();+ this.io?.disconnect();+ this.clear();+ this.renderer.dispose();+ this.renderer.forceContextLoss();+ this.renderer.domElement.remove();+ if (this.callout) {+ this.callout.renderer.dispose();+ this.callout.renderer.forceContextLoss();+ this.callout.wrap.remove();+ }+ this.overlay?.remove();+ this.labelLayer?.remove();+ this.tooltip?.remove();+ }+}++function disposeDrawable(d: Drawable) {+ d.faces.forEach((m) => m.dispose());+ d.lines.forEach((m) => m.dispose());+ d.thin.forEach((m) => m.dispose());+ d.hulls.forEach((m) => m.dispose());+}++/** Thick IKEA style arrow from a to b (screen space). */+export function arrowPath(a: { x: number; y: number }, b: { x: number; y: number }, s = 1) {+ const dx = b.x - a.x, dy = b.y - a.y;+ const L = Math.hypot(dx, dy) || 1;+ const ux = dx / L, uy = dy / L;+ const px = -uy, py = ux;+ const hw = 4.2 * s + 1.5, head = 16 * s + 4, hl = Math.min(L * 0.55, 18 * s + 6);+ const bx = b.x - ux * hl, by = b.y - uy * hl;+ return [+ `M${a.x + px * hw} ${a.y + py * hw}`,+ `L${bx + px * hw} ${by + py * hw}`,+ `L${bx + (px * head) / 1.6} ${by + (py * head) / 1.6}`,+ `L${b.x} ${b.y}`,+ `L${bx - (px * head) / 1.6} ${by - (py * head) / 1.6}`,+ `L${bx - px * hw} ${by - py * hw}`,+ `L${a.x - px * hw} ${a.y - py * hw}`,+ "Z",+ ].join(" ");+}++function doubleArrow(a: { x: number; y: number }, b: { x: number; y: number }) {+ const dx = b.x - a.x, dy = b.y - a.y;+ const L = Math.hypot(dx, dy) || 1;+ const ux = dx / L, uy = dy / L, px = -uy, py = ux;+ const h = 9;+ return `M${a.x} ${a.y} L${b.x} ${b.y} M${a.x + ux * h + px * h * 0.6} ${a.y + uy * h + py * h * 0.6} L${a.x} ${a.y} L${a.x + ux * h - px * h * 0.6} ${a.y + uy * h - py * h * 0.6} M${b.x - ux * h + px * h * 0.6} ${b.y - uy * h + py * h * 0.6} L${b.x} ${b.y} L${b.x - ux * h - px * h * 0.6} ${b.y - uy * h - py * h * 0.6}`;+}++/** Curved rotation arrow (clockwise on screen). */+export function arcArrow(cx: number, cy: number, r: number, a0: number, a1: number) {+ const w = 3.4;+ const pt = (a: number, rr: number) => `${cx + Math.cos(a) * rr} ${cy + Math.sin(a) * rr}`;+ const large = a1 - a0 > Math.PI ? 1 : 0;+ const tip = a1 + 0.42;+ return [+ `M${pt(a0, r - w)}`,+ `A${r - w} ${r - w} 0 ${large} 1 ${pt(a1, r - w)}`,+ `L${pt(a1, r - w - 6)}`,+ `L${pt(tip, r)}`,+ `L${pt(a1, r + w + 6)}`,+ `L${pt(a1, r + w)}`,+ `A${r + w} ${r + w} 0 ${large} 0 ${pt(a0, r + w)}`,+ "Z",+ ].join(" ");+}diff --git a/src/engine/thumbs.ts b/src/engine/thumbs.tsnew file mode 100644index 0000000..a391c94--- /dev/null+++ b/src/engine/thumbs.ts@@ -0,0 +1,73 @@+import type { Plan, Vec3 } from "@/lib/types";+import type { Stage, StageMode } from "./stage";++export interface Shot {+ url: string;+ /** Image coordinates of the probe points, in CSS pixels of the requested size. */+ points: { x: number; y: number }[];+}++let stage: Stage | null = null;+let busy = false;+const cache = new Map<string, Shot>();+const waiting = new Map<string, ((s: Shot) => void)[]>();+const queue: { key: string; plan: Plan; mode: StageMode; w: number; h: number; probes?: Vec3[] }[] = [];++async function ensure() {+ if (stage) return stage;+ const { Stage } = await import("./stage");+ const host = document.createElement("div");+ host.style.cssText = "position:fixed;left:-9999px;top:0;width:10px;height:10px;pointer-events:none;";+ document.body.appendChild(host);+ stage = new Stage(host, { offscreen: true, loop: false, labels: false });+ stage.renderer.setPixelRatio(2);+ return stage;+}++async function pump() {+ if (busy) return;+ busy = true;+ try {+ const s = await ensure();+ while (queue.length) {+ const job = queue.shift()!;+ if (cache.has(job.key)) continue;+ s.setPlan(job.plan);+ s.setMode(job.mode, { instant: true });+ const url = s.snapshot(job.w, job.h);+ const shot: Shot = { url, points: (job.probes ?? []).map((p) => s.locate(p)) };+ cache.set(job.key, shot);+ waiting.get(job.key)?.forEach((cb) => cb(shot));+ waiting.delete(job.key);+ await new Promise((r) => setTimeout(r, 8));+ }+ } finally {+ busy = false;+ }+}++/** Render a static line drawing and report where the probe points landed in the image. */+export function shot(key: string, plan: Plan, mode: StageMode, w = 360, h = 270, probes?: Vec3[]): Promise<Shot> {+ const hit = cache.get(key);+ if (hit) return Promise.resolve(hit);+ return new Promise((resolve) => {+ const list = waiting.get(key) ?? [];+ list.push(resolve);+ waiting.set(key, list);+ if (!queue.some((q) => q.key === key)) queue.push({ key, plan, mode, w, h, probes });+ pump();+ });+}++/** Render a static line drawing of a plan (whole product, one part, or one step). */+export function thumbnail(key: string, plan: Plan, mode: StageMode, w = 360, h = 270): Promise<string> {+ return shot(key, plan, mode, w, h).then((s) => s.url);+}++export function peekThumbnail(key: string) {+ return cache.get(key)?.url;+}++export function peekShot(key: string) {+ return cache.get(key);+}diff --git a/src/lib/catalog.ts b/src/lib/catalog.tsnew file mode 100644index 0000000..1fbc060--- /dev/null+++ b/src/lib/catalog.ts@@ -0,0 +1,451 @@+import type { ProductSpec } from "./types";+import { ROWS, specFor } from "./products";+import { fold } from "./fold";++type Entry = Omit<ProductSpec, "source" | "slug" | "variants" | "siblings"> & { slug: string; family: string; keywords?: string[]; featured?: boolean; checked?: boolean };++/** Hand-checked starting points for popular flat packs. Dimensions in cm. */+export const CATALOG: Entry[] = [+ {+ slug: "kallax-2x2",+ family: "kallax",+ featured: true,+ name: "KALLAX",+ variant: "Shelving unit, 2 × 2",+ category: "Shelving unit",+ archetype: "shelf",+ size: { w: 77, h: 77, d: 39 },+ minutes: 40,+ people: 1,+ difficulty: 1,+ material: "Particleboard",+ shelf: { style: "grid", cols: 2, rows: 2, outer: 40, inner: 16, back: false },+ keywords: ["2x2", "4 cube", "cube", "77x77"],+ tips: { frame: "The thick outer panels are hollow. Tap dowels in gently or they can split the edge." },+ },+ {+ slug: "kallax-2x4",+ family: "kallax",+ name: "KALLAX",+ variant: "Shelving unit, 2 × 4",+ category: "Shelving unit",+ archetype: "shelf",+ size: { w: 77, h: 147, d: 39 },+ minutes: 70,+ people: 2,+ difficulty: 2,+ shelf: { style: "grid", cols: 2, rows: 4, outer: 40, inner: 16, back: false },+ keywords: ["2x4", "4x2", "8 cube", "77x147"],+ },+ {+ slug: "kallax-4x4",+ family: "kallax",+ name: "KALLAX",+ variant: "Shelving unit, 4 × 4",+ category: "Shelving unit",+ archetype: "shelf",+ size: { w: 147, h: 147, d: 39 },+ minutes: 120,+ people: 2,+ difficulty: 2,+ shelf: { style: "grid", cols: 4, rows: 4, outer: 40, inner: 16, back: false },+ keywords: ["4x4", "16 cube", "147x147"],+ },+ {+ slug: "kallax-1x4",+ family: "kallax",+ name: "KALLAX",+ variant: "Shelving unit, 1 × 4",+ category: "Shelving unit",+ archetype: "shelf",+ size: { w: 42, h: 147, d: 39 },+ minutes: 45,+ people: 1,+ difficulty: 1,+ shelf: { style: "grid", cols: 1, rows: 4, outer: 40, inner: 16, back: false },+ keywords: ["1x4", "4x1", "42x147"],+ },+ {+ slug: "billy-80x202",+ family: "billy",+ featured: true,+ name: "BILLY",+ variant: "Bookcase, 80 × 202 cm",+ category: "Bookcase",+ archetype: "shelf",+ size: { w: 80, h: 202, d: 28 },+ minutes: 60,+ people: 2,+ difficulty: 2,+ material: "Particleboard, fibreboard back",+ shelf: { style: "bookcase", shelves: 4, fixedShelf: true, back: true, plinth: true, outer: 15 },+ keywords: ["80x202", "tall", "bookshelf"],+ tips: { back: "Keep the back panel square while nailing. It is what stops the bookcase from wobbling." },+ },+ {+ slug: "billy-40x202",+ family: "billy",+ name: "BILLY",+ variant: "Bookcase, 40 × 202 cm",+ category: "Bookcase",+ archetype: "shelf",+ size: { w: 40, h: 202, d: 28 },+ minutes: 45,+ people: 2,+ difficulty: 2,+ shelf: { style: "bookcase", shelves: 4, fixedShelf: true, back: true, plinth: true, outer: 15 },+ keywords: ["40x202", "narrow"],+ },+ {+ slug: "billy-80x106",+ family: "billy",+ name: "BILLY",+ variant: "Bookcase, 80 × 106 cm",+ category: "Bookcase",+ archetype: "shelf",+ size: { w: 80, h: 106, d: 28 },+ minutes: 35,+ people: 1,+ difficulty: 1,+ shelf: { style: "bookcase", shelves: 2, fixedShelf: false, back: true, plinth: true, outer: 15 },+ keywords: ["80x106", "low", "short"],+ },+ {+ slug: "malm-3-drawers",+ family: "malm",+ featured: true,+ name: "MALM",+ variant: "Chest of 3 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 80, h: 78, d: 48 },+ minutes: 90,+ people: 1,+ difficulty: 3,+ drawers: { cols: 1, rows: 3, knobs: "none", plinth: false, thickness: 16 },+ keywords: ["3 drawer", "three", "dresser", "chest"],+ tips: { drawers: "Build one drawer completely before starting the next. It is much easier to spot mistakes." },+ },+ {+ slug: "malm-6-drawers",+ family: "malm",+ name: "MALM",+ variant: "Chest of 6 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 160, h: 78, d: 48 },+ minutes: 180,+ people: 2,+ difficulty: 3,+ drawers: { cols: 2, rows: 3, knobs: "none", plinth: false, thickness: 16 },+ keywords: ["6 drawer", "six", "wide", "dresser"],+ },+ {+ slug: "malm-4-drawers",+ family: "malm",+ name: "MALM",+ variant: "Chest of 4 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 80, h: 100, d: 48 },+ minutes: 120,+ people: 1,+ difficulty: 3,+ drawers: { cols: 1, rows: 4, knobs: "none", plinth: false, thickness: 16 },+ keywords: ["4 drawer", "four", "tall dresser"],+ },+ {+ slug: "malm-2-drawers",+ family: "malm",+ name: "MALM",+ variant: "Chest of 2 drawers",+ category: "Nightstand",+ archetype: "drawers",+ size: { w: 40, h: 55, d: 48 },+ minutes: 45,+ people: 1,+ difficulty: 2,+ drawers: { cols: 1, rows: 2, knobs: "none", plinth: false, thickness: 16 },+ keywords: ["2 drawer", "two", "nightstand", "bedside"],+ },+ {+ slug: "malm-bed-160",+ family: "malm",+ name: "MALM",+ variant: "Bed frame, 160 × 200 cm",+ category: "Bed frame",+ archetype: "bed",+ size: { w: 176, h: 100, d: 209 },+ minutes: 120,+ people: 2,+ difficulty: 2,+ bed: { mattressW: 160, mattressL: 200, headH: 100, footH: 38, slats: 17, centerBeam: true },+ keywords: ["bed", "queen", "double", "160"],+ },+ {+ slug: "hemnes-3-drawers",+ family: "hemnes",+ name: "HEMNES",+ variant: "Chest of 3 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 108, h: 96, d: 50 },+ minutes: 150,+ people: 1,+ difficulty: 3,+ material: "Solid pine",+ drawers: { cols: 1, rows: 3, knobs: "knob", plinth: true, thickness: 20 },+ keywords: ["3 drawer", "dresser", "chest"],+ },+ {+ slug: "rast-3-drawers",+ family: "rast",+ name: "RAST",+ variant: "Chest of 3 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 62, h: 70, d: 30 },+ minutes: 45,+ people: 1,+ difficulty: 2,+ material: "Solid pine",+ drawers: { cols: 1, rows: 3, knobs: "knob", plinth: false, thickness: 18 },+ keywords: ["3 drawer", "pine"],+ },+ {+ slug: "kullen-3-drawers",+ family: "kullen",+ name: "KULLEN",+ variant: "Chest of 3 drawers",+ category: "Chest of drawers",+ archetype: "drawers",+ size: { w: 70, h: 72, d: 40 },+ minutes: 60,+ people: 1,+ difficulty: 2,+ drawers: { cols: 1, rows: 3, knobs: "knob", plinth: false, thickness: 15 },+ keywords: ["3 drawer"],+ },+ {+ slug: "alex-drawer-unit",+ family: "alex",+ name: "ALEX",+ variant: "Drawer unit, 5 drawers",+ category: "Drawer unit",+ archetype: "drawers",+ size: { w: 36, h: 70, d: 58 },+ minutes: 60,+ people: 1,+ difficulty: 2,+ drawers: { cols: 1, rows: 5, knobs: "none", plinth: false, thickness: 16 },+ keywords: ["5 drawer", "desk drawers"],+ },+ {+ slug: "lack-side-table",+ family: "lack",+ featured: true,+ name: "LACK",+ variant: "Side table, 55 × 55 cm",+ category: "Side table",+ archetype: "table",+ size: { w: 55, h: 45, d: 55 },+ minutes: 10,+ people: 1,+ difficulty: 1,+ material: "Particleboard, honeycomb paper filling",+ table: { topThickness: 50, legs: "square", legSize: 50, shelf: false, attach: "screw" },+ keywords: ["side table", "end table", "55x55"],+ },+ {+ slug: "lack-coffee-table",+ family: "lack",+ name: "LACK",+ variant: "Coffee table, 118 × 78 cm",+ category: "Coffee table",+ archetype: "table",+ size: { w: 118, h: 45, d: 78 },+ minutes: 20,+ people: 1,+ difficulty: 1,+ table: { topThickness: 50, legs: "square", legSize: 50, shelf: true, attach: "screw" },+ keywords: ["coffee table", "118"],+ },+ {+ slug: "lack-tv-bench",+ family: "lack",+ name: "LACK",+ variant: "TV bench, 90 × 26 cm",+ category: "TV bench",+ archetype: "table",+ size: { w: 90, h: 45, d: 26 },+ minutes: 15,+ people: 1,+ difficulty: 1,+ table: { topThickness: 50, legs: "square", legSize: 50, shelf: true, attach: "screw" },+ keywords: ["tv", "bench", "media"],+ },+ {+ slug: "linnmon-adils-desk",+ family: "linnmon",+ featured: true,+ name: "LINNMON / ADILS",+ variant: "Desk, 100 × 60 cm",+ category: "Desk",+ archetype: "table",+ size: { w: 100, h: 74, d: 60 },+ minutes: 15,+ people: 1,+ difficulty: 1,+ table: { topThickness: 34, legs: "round", legSize: 34, shelf: false, attach: "plate" },+ keywords: ["desk", "adils", "table top", "100x60"],+ },+ {+ slug: "melltorp-table",+ family: "melltorp",+ name: "MELLTORP",+ variant: "Table, 125 × 75 cm",+ category: "Dining table",+ archetype: "table",+ size: { w: 125, h: 74, d: 75 },+ minutes: 30,+ people: 2,+ difficulty: 2,+ table: { topThickness: 22, legs: "square", legSize: 45, shelf: false, attach: "apron" },+ keywords: ["dining", "kitchen table"],+ },+ {+ slug: "brimnes-wardrobe",+ family: "brimnes",+ name: "BRIMNES",+ variant: "Wardrobe with 2 doors",+ category: "Wardrobe",+ archetype: "cabinet",+ size: { w: 78, h: 190, d: 50 },+ minutes: 120,+ people: 2,+ difficulty: 3,+ cabinet: { doors: 2, shelves: 1, rail: true, plinth: true, handles: "knob", thickness: 18 },+ keywords: ["wardrobe", "closet", "armoire"],+ },+ {+ slug: "pax-frame",+ family: "pax",+ name: "PAX",+ variant: "Wardrobe frame, 100 × 201 cm",+ category: "Wardrobe frame",+ archetype: "cabinet",+ size: { w: 100, h: 201, d: 58 },+ minutes: 90,+ people: 2,+ difficulty: 3,+ cabinet: { doors: 0, shelves: 2, rail: true, plinth: true, handles: "none", thickness: 18 },+ keywords: ["wardrobe", "frame", "closet", "201"],+ tips: { anchor: "PAX must be fixed to the wall. Its frame is tall and narrow front to back." },+ },+ {+ slug: "eket-cabinet",+ family: "eket",+ name: "EKET",+ variant: "Cabinet with door, 35 × 35 cm",+ category: "Cabinet",+ archetype: "cabinet",+ size: { w: 35, h: 35, d: 35 },+ minutes: 20,+ people: 1,+ difficulty: 1,+ cabinet: { doors: 1, shelves: 0, rail: false, plinth: false, handles: "none", thickness: 16 },+ keywords: ["cube", "small cabinet"],+ },+ {+ slug: "frosta-stool",+ family: "frosta",+ name: "FROSTA",+ variant: "Stool",+ category: "Stool",+ archetype: "seat",+ size: { w: 35, h: 45, d: 35 },+ minutes: 10,+ people: 1,+ difficulty: 1,+ seat: { kind: "stool", seat: "round", seatH: 45, splay: true },+ keywords: ["stool"],+ },+ {+ slug: "marius-stool",+ family: "marius",+ name: "MARIUS",+ variant: "Stool",+ category: "Stool",+ archetype: "seat",+ size: { w: 32, h: 45, d: 32 },+ minutes: 10,+ people: 1,+ difficulty: 1,+ seat: { kind: "stool", seat: "round", seatH: 45, splay: true, stretchers: true },+ keywords: ["stool", "metal"],+ },+ {+ slug: "ingolf-chair",+ family: "ingolf",+ name: "INGOLF",+ variant: "Chair",+ category: "Chair",+ archetype: "seat",+ size: { w: 43, h: 91, d: 52 },+ minutes: 30,+ people: 1,+ difficulty: 2,+ seat: { kind: "chair", seat: "square", seatH: 45, backH: 91 },+ keywords: ["chair", "dining chair"],+ },+];++function rowSlug(name: string, variant: string, used: Set<string>) {+ const base = (fold(name) + " " + fold(variant).replace(/\b(cm|with|of)\b/g, " "))+ .replace(/\s+/g, " ")+ .trim()+ .replace(/ /g, "-")+ .slice(0, 48)+ .replace(/-+$/, "");+ let slug = base;+ let n = 2;+ while (used.has(slug)) slug = `${base}-${n++}`;+ used.add(slug);+ return slug;+}++const used = new Set(CATALOG.map((c) => c.slug));+const GENERATED: Entry[] = ROWS.map(([name, kind, variant, w, h, d, x, kw]) => ({+ ...specFor(kind, name, variant, w, h, d, x),+ slug: rowSlug(name, variant, used),+ family: fold(name),+ keywords: kw ? kw.split(" ") : undefined,+}));++/** Every product we can draw offline: hand-checked entries first, then the wider index. */+export const PRODUCTS: Entry[] = [...CATALOG.map((c) => ({ ...c, checked: true })), ...GENERATED];++export function catalogSpec(slug: string): ProductSpec | null {+ const e = PRODUCTS.find((x) => x.slug === slug);+ if (!e) return null;+ return toSpec(e);+}++export function toSpec(e: Entry): ProductSpec {+ const { family, keywords, featured, checked, ...rest } = e;+ void keywords;+ void featured;+ void checked;+ const same = PRODUCTS.filter((x) => x.family === family && x.category === e.category);+ const variants = same.map((x) => ({ label: x.variant, slug: x.slug }));+ const seen = new Set<string>([e.category]);+ const siblings: { label: string; slug: string }[] = [];+ for (const x of PRODUCTS) {+ if (x.family !== family || seen.has(x.category)) continue;+ seen.add(x.category);+ siblings.push({ label: x.category, slug: x.slug });+ }+ return { ...rest, source: "catalog", variants: variants.length > 1 ? variants : undefined, siblings: siblings.length ? siblings : undefined };+}++export type CatalogEntry = Entry;diff --git a/src/lib/faq.ts b/src/lib/faq.tsnew file mode 100644index 0000000..507ac33--- /dev/null+++ b/src/lib/faq.ts@@ -0,0 +1,74 @@+import type { StepKind } from "./types";++export interface Faq {+ q: string;+ a: string;+}++const COMMON: Faq[] = [+ { q: "A part is missing or broken", a: "Note the number printed on the panel or the bag. IKEA stores and customer service usually replace small fittings for free, and you can keep building the steps that don't need it." },+ { q: "I think I did an earlier step wrong", a: "Open the overview, jump back to that step and watch it again. Most fittings come out easily if you haven't locked the cams yet." },+];++export const FAQ: Partial<Record<StepKind, Faq[]>> = {+ dowels: [+ { q: "The dowel won't go in", a: "Twist it while pushing, or tap it gently with a hammer. Don't force it sideways. If the hole has sawdust in it, blow it out first." },+ { q: "How far should dowels go in?", a: "About halfway. The other half goes into the next panel." },+ { q: "Do I need glue?", a: "No. The fit is tight on purpose. Glue makes it impossible to take apart later." },+ ],+ bolts: [+ { q: "How tight should the bolts be?", a: "Snug, then a little more. If the step says don't tighten fully yet, leave a few turns so the parts can still line up." },+ { q: "The bolt spins without tightening", a: "The thread may have stripped. Try the spare from the bag, or move the bolt slightly and turn it in slowly." },+ ],+ cams: [+ { q: "The cam lock won't turn", a: "Check the arrow on the cam points at the bolt hole before you turn. The bolt head must sit inside the cam's opening." },+ { q: "Which way do I turn it?", a: "Clockwise, about half a turn, until you feel it pull the panels together. Stop when it feels firm." },+ { q: "The panels still have a gap", a: "Push the panels together by hand while you turn the cam. If it still gaps, the bolt may not be screwed in far enough." },+ ],+ nails: [+ { q: "The nail keeps bending", a: "Hold it straight with a pair of pliers or a folded piece of cardboard, and use lighter taps." },+ { q: "How many nails do I use?", a: "Space them about every 15 cm along each edge. Start at the corners so the back stays square." },+ ],+ square: [+ { q: "The diagonals don't match", a: "Push gently on the corner of the longer diagonal until both measurements are equal. Then nail the back on straight away." },+ { q: "No tape measure?", a: "Use a piece of string. Hold it corner to corner, pinch it, and compare with the other diagonal." },+ ],+ flip: [{ q: "How do I turn it without breaking it?", a: "Keep it flat and lift by the sides, not the top. For anything tall, do this with a second person." }],+ standup: [{ q: "It feels wobbly once standing", a: "That's normal before it's against the wall. Check the floor is level and the back panel is fully nailed." }],+ shelves: [+ { q: "The shelf rocks", a: "One of the pins is in a different row. Count the holes from the top on each corner and match them." },+ { q: "Can I change shelf heights later?", a: "Yes. Lift the shelf out, move the four pins, and drop it back in." },+ ],+ anchor: [+ { q: "Do I really need to fix it to the wall?", a: "Yes for anything tall or with drawers. It stops it from tipping over, especially around children." },+ { q: "Which screws should I use?", a: "It depends on your wall. Plasterboard, brick and wood all need different plugs. A hardware store can match them if you bring the bracket." },+ { q: "I rent and can't drill", a: "Ask your landlord: most allow anchoring for safety. Some walls take adhesive anchors, but screws are always safer." },+ ],+ drawer: [+ { q: "The drawer bottom won't slide in", a: "Make sure the grooves line up on both sides. The bottom goes in shiny side up and slides along until it stops." },+ { q: "The drawer sticks or won't close", a: "Check the runners on both sides are at the same height and the open end faces the front." },+ ],+ runners: [{ q: "Which way round do the runners go?", a: "The wheel or open end goes to the front. Left and right are mirror images, so check the marks on each one." }],+ legs: [+ { q: "The table wobbles", a: "Loosen the wobbly leg a quarter turn, press the table down, then tighten again. Check the floor is level." },+ { q: "The leg won't screw in straight", a: "Back it out, line it up straight above the hole, and start turning gently. Don't force it if it catches." },+ ],+ doors: [+ { q: "The door gap is uneven", a: "Each hinge has small adjustment screws. The front one moves the door sideways, the back one moves it in and out." },+ { q: "The door won't stay closed", a: "Check both hinge arms clicked onto their plates. Press firmly until you hear the click." },+ ],+ hinges: [{ q: "The hinge doesn't sit flat", a: "Press the cup fully into the round hole before putting the screws in." }],+ slats: [{ q: "There are slats left over", a: "Check the spacing: they should be spread evenly. Some beds include a spare." }],+ join: [+ { q: "The panels don't line up", a: "Check the holes face each other and the finished edge points to the front." },+ { q: "It's hard to hold everything", a: "Lean the panels against a wall or ask someone to hold them for a minute." },+ ],+ screws: [+ { q: "The screw won't bite", a: "Push firmly while turning slowly. If it spins freely, the hole may be stripped: try the spare screw." },+ { q: "Can I use a drill?", a: "Only on the lowest setting, and finish by hand. Power tools strip the soft board easily." },+ ],+};++export function faqFor(kind: StepKind): Faq[] {+ return [...(FAQ[kind] ?? []), ...COMMON];+}diff --git a/src/lib/fold.ts b/src/lib/fold.tsnew file mode 100644index 0000000..92ed498--- /dev/null+++ b/src/lib/fold.ts@@ -0,0 +1,9 @@+export function fold(s: string) {+ return s+ .normalize("NFD")+ .replace(/[̀-ͯ]/g, "")+ .toLowerCase()+ .replace(/×/g, "x")+ .replace(/[^a-z0-9x]+/g, " ")+ .trim();+}diff --git a/src/lib/github.ts b/src/lib/github.tsnew file mode 100644index 0000000..2ba088c--- /dev/null+++ b/src/lib/github.ts@@ -0,0 +1,20 @@+import "server-only";+import { cacheLife } from "next/cache";+import { GITHUB_REPO } from "./site";++/** Star count for the repo, cached for an hour. Null when the repo can't be reached. */+export async function getStars(): Promise<number | null> {+ "use cache";+ cacheLife("hours");+ try {+ const r = await fetch(`https://api.github.com/repos/${GITHUB_REPO}`, {+ headers: { Accept: "application/vnd.github+json", "User-Agent": "bygga" },+ signal: AbortSignal.timeout(4000),+ });+ if (!r.ok) return null;+ const j = (await r.json()) as { stargazers_count?: unknown };+ return typeof j.stargazers_count === "number" ? j.stargazers_count : null;+ } catch {+ return null;+ }+}diff --git a/src/lib/plan/bed.ts b/src/lib/plan/bed.tsnew file mode 100644index 0000000..1d11f43--- /dev/null+++ b/src/lib/plan/bed.ts@@ -0,0 +1,164 @@+import type { BedParams, ProductSpec } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { clamp } from "./math";++export function defaultsBed(s: ProductSpec): BedParams {+ const p = s.bed ?? {};+ const mw = clamp(p.mattressW ?? Math.max(80, s.size.w - 16), 70, 200);+ return {+ mattressW: mw,+ mattressL: clamp(p.mattressL ?? 200, 140, 220),+ headH: clamp(p.headH ?? s.size.h, 40, 140),+ footH: clamp(p.footH ?? 38, 0, 100),+ slats: clamp(Math.round(p.slats ?? 17), 8, 30),+ centerBeam: p.centerBeam ?? mw >= 120,+ };+}++export function buildBed(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsBed(s);+ const Wm = p.mattressW * 10, Lm = p.mattressL * 10;+ const t = 22;+ const railTop = 380, railH = 170;+ const slatTop = railTop - 50;+ const headH = p.headH * 10;+ const footH = Math.max(p.footH * 10, railTop);+ const outerW = Wm + 20 + 2 * t;+ const zh = -(Lm / 2 + 10 + t / 2), zf = Lm / 2 + 10 + t / 2;+ const rx = Wm / 2 + 10 + t / 2;++ const headT = b.part("Headboard", [outerW, headH, t]);+ const head = b.place(headT, [0, headH / 2, zh]);+ const footT = b.part("Footboard", [outerW, footH, t]);+ const foot = b.place(footT, [0, footH / 2, zf]);+ const railT = b.part("Side rail", [t, railH, Lm + 20]);+ const rails = [b.place(railT, [-rx, railTop - railH / 2, 0]), b.place(railT, [rx, railTop - railH / 2, 0])];+ const ledgeT = b.part("Slat support", [24, 30, Lm], { material: "wood" });+ const lx = Wm / 2 + 10 - 12;+ const ledgeY = slatTop - 10 - 15;+ const ledges = [b.place(ledgeT, [-lx, ledgeY, 0]), b.place(ledgeT, [lx, ledgeY, 0])];+ const slatT = b.part("Slat", [Wm - 4, 10, 68], { material: "wood" });+ const pitch = (Lm - 60) / (p.slats - 1);+ const slats = Array.from({ length: p.slats }, (_, i) => b.place(slatT, [0, slatTop - 5, -Lm / 2 + 30 + i * pitch]));++ b.step(+ {+ title: "Attach the side rails to the headboard",+ detail: "One person holds, one bolts. Don't tighten fully yet.",+ tools: ["allen"],+ people: 2,+ kind: "bolts",+ warnings: ["two", "loose"],+ },+ () => {+ b.add(head, [0, 0, -260]);+ b.then(0.1);+ b.stagger(0.3);+ rails.forEach((r) => b.add(r, [0, 0, 420]));+ b.then(0.1);+ const bolts: FitOpts[] = [];+ for (const x of [-rx, rx]) for (const dy of [-45, 45]) bolts.push({ on: head, at: [x, railTop - railH / 2 + dy, zh - t / 2], dir: [0, 0, 1], mate: rails[x < 0 ? 0 : 1] });+ b.fits(HW.boltL, bolts, 0.1);+ },+ );++ b.step(+ {+ title: "Attach the footboard",+ detail: "Now tighten every bolt firmly.",+ tools: ["allen"],+ people: 2,+ kind: "bolts",+ warnings: ["two"],+ },+ () => {+ b.add(foot, [0, 0, 360]);+ b.then(0.1);+ const bolts: FitOpts[] = [];+ for (const x of [-rx, rx]) for (const dy of [-45, 45]) bolts.push({ on: foot, at: [x, railTop - railH / 2 + dy, zf + t / 2], dir: [0, 0, -1], mate: rails[x < 0 ? 0 : 1] });+ b.fits(HW.boltL, bolts, 0.1);+ },+ );++ b.step(+ {+ title: "Screw the slat supports to the rails",+ detail: "Keep them level with the bottom of the marks.",+ tools: ["screwdriver"],+ kind: "screws",+ },+ () => {+ b.stagger(0.25);+ ledges.forEach((l, i) => b.add(l, [i === 0 ? 260 : -260, 0, 0]));+ b.then(0.1);+ const sc: FitOpts[] = [];+ ledges.forEach((l, i) => {+ const x = i === 0 ? -lx + 12 : lx - 12;+ for (let k = 0; k < 5; k++) sc.push({ on: l, at: [x, ledgeY, -Lm / 2 + 120 + (k * (Lm - 240)) / 4], dir: [i === 0 ? -1 : 1, 0, 0] });+ });+ b.fits(HW.screwM, sc, 0.05);+ },+ );++ if (p.centerBeam) {+ const beamT = b.part("Center beam", [50, 70, Lm + 20], { material: "metal" });+ const by = slatTop - 10 - 35;+ const beam = b.place(beamT, [0, by, 0]);+ const legH = by - 35;+ const legT = b.part("Support leg", [36, legH, 36], { shape: "cyl", material: "metal" });+ const bl = [b.place(legT, [0, legH / 2, -Lm / 4]), b.place(legT, [0, legH / 2, Lm / 4])];+ b.step(+ {+ title: "Screw the legs onto the center beam",+ detail: "Turn them until they're firm.",+ scene: "beam",+ pose: "-y",+ kind: "legs",+ warnings: ["hand"],+ },+ () => {+ b.stage(beam, [0, by, 0], [0, 0, 0], [0, -200, 0]);+ b.then(0.1);+ b.stagger(0.3);+ bl.forEach((l) => b.stage(l, b.partItem(l).final.pos, [0, 0, 0], [0, -260, 0]));+ },+ );+ b.step(+ {+ title: "Hook the beam onto the head and foot",+ detail: "Its feet should stand flat on the floor.",+ kind: "join",+ },+ () => {+ b.stagger(0);+ b.add(beam, [0, 360, 0]);+ bl.forEach((l) => b.add(l, [0, 360, 0]));+ },+ );+ }++ b.step(+ {+ title: "Lay out the slats",+ detail: "Curved side up, spread evenly from head to foot.",+ kind: "slats",+ },+ () => {+ b.stagger(Math.min(0.08, 1.6 / slats.length));+ slats.forEach((sl) => b.add(sl, [0, 260, 0]));+ },+ );++ const mT = b.part("Your mattress", [Wm, 180, Lm], { material: "soft", extra: true });+ const m = b.place(mT, [0, slatTop + 90, 0]);+ b.step(+ {+ title: "Add your mattress",+ detail: "Done. Check the bolts again after a week of use.",+ people: 2,+ kind: "general",+ warnings: ["two"],+ },+ () => b.add(m, [0, 420, 0]),+ );+}diff --git a/src/lib/plan/builder.ts b/src/lib/plan/builder.tsnew file mode 100644index 0000000..3e13c98--- /dev/null+++ b/src/lib/plan/builder.ts@@ -0,0 +1,444 @@+import type {+ HwItem,+ HwKind,+ HwType,+ Item,+ PartItem,+ PartMaterial,+ PartType,+ Plan,+ Pose,+ ProductSpec,+ Step,+ StepKind,+ ToolId,+ ToolNeed,+ Vec3,+ WarnId,+} from "../types";+import { toLocal, unrotate } from "./math";++const LETTERS = "ABCDEFGHJKLMNPRSTUVWXYZ";++export interface HwDef {+ kind: HwKind;+ len: number;+ dia: number;+ notIncluded?: boolean;+}++export const HW = {+ dowel: { kind: "dowel", len: 30, dia: 8 },+ camScrew: { kind: "camScrew", len: 34, dia: 7 },+ cam: { kind: "cam", len: 13, dia: 15 },+ screwS: { kind: "screw", len: 14, dia: 3.5 },+ screwM: { kind: "screw", len: 30, dia: 4 },+ screwL: { kind: "screw", len: 50, dia: 5 },+ nail: { kind: "nail", len: 20, dia: 1.6 },+ pin: { kind: "pin", len: 16, dia: 5 },+ legScrew: { kind: "legScrew", len: 70, dia: 8 },+ boltS: { kind: "bolt", len: 40, dia: 6 },+ boltL: { kind: "bolt", len: 70, dia: 6 },+ plate: { kind: "plate", len: 80, dia: 80 },+ bracket: { kind: "bracket", len: 60, dia: 40 },+ knob: { kind: "knob", len: 25, dia: 30 },+ handle: { kind: "handle", len: 128, dia: 12 },+ hinge: { kind: "hinge", len: 50, dia: 35 },+ glide: { kind: "glide", len: 4, dia: 20 },+ wallScrew: { kind: "screw", len: 50, dia: 5, notIncluded: true },+ plug: { kind: "plug", len: 35, dia: 8, notIncluded: true },+} satisfies Record<string, HwDef>;++const HW_NAMES: Record<HwKind, string> = {+ dowel: "Wooden dowel",+ camScrew: "Cam bolt",+ cam: "Cam lock",+ screw: "Screw",+ nail: "Nail",+ pin: "Shelf pin",+ legScrew: "Leg bolt",+ bolt: "Allen bolt",+ plate: "Leg plate",+ bracket: "Wall bracket",+ runner: "Drawer runner",+ knob: "Knob",+ handle: "Handle",+ hinge: "Hinge",+ glide: "Felt pad",+ plug: "Wall plug",+};++export function hwSpecText(kind: HwKind, len: number, dia: number) {+ switch (kind) {+ case "dowel":+ case "screw":+ case "nail":+ case "legScrew":+ case "bolt":+ case "plug":+ return `${dia} × ${len} mm`;+ case "camScrew":+ return `${len} mm`;+ case "cam":+ return `${dia} mm`;+ case "pin":+ return `${dia} mm`;+ case "runner":+ return `${len} mm`;+ case "handle":+ return `${len} mm`;+ default:+ return "";+ }+}++const DUR = { part: 0.95, hw: 0.6 };++export interface StepDef {+ title: string;+ detail?: string;+ tools?: ToolId[];+ people?: 1 | 2;+ repeat?: number;+ scene?: string;+ pose?: Pose;+ warnings?: WarnId[];+ kind: StepKind;+ check?: "square";+ wall?: boolean;+ weight?: number;+}++export interface FitOpts {+ on?: string;+ at: Vec3; // assembled frame (or scene frame when no parent)+ dir: Vec3;+ twist?: number;+ travel?: number;+ spin?: number;+ turn?: number;+ mate?: string; // part that receives the protruding end+ hole?: number | false;+ mateHole?: number;+ scale?: number;+}++export class PlanBuilder {+ parts: PartType[] = [];+ hw = new Map<string, HwType>();+ items: Item[] = [];+ map = new Map<string, Item>();+ steps: Step[] = [];+ private n = 0;+ private t = 0;+ private end = 0;+ private gap = 0;+ private cur: Step | null = null;++ constructor(public spec: ProductSpec) {}++ part(name: string, size: Vec3, o: { shape?: "box" | "cyl"; material?: PartMaterial; extra?: boolean; label?: string } = {}) {+ const id = "p" + this.parts.length;+ this.parts.push({+ id,+ label: o.label ?? "",+ name,+ size,+ shape: o.shape ?? "box",+ material: o.material ?? "board",+ qty: 0,+ extra: o.extra,+ });+ return id;+ }++ place(ref: string, pos: Vec3, rot: Vec3 = [0, 0, 0]) {+ const key = "i" + this.n++;+ const it: PartItem = { key, kind: "part", ref, final: { pos, rot }, states: [], holes: [] };+ this.items.push(it);+ this.map.set(key, it);+ return key;+ }++ partItem(key: string) {+ const it = this.map.get(key);+ if (!it || it.kind !== "part") throw new Error("not a part " + key);+ return it;+ }++ hole(key: string, at: Vec3, n: Vec3, r: number) {+ const it = this.partItem(key);+ it.holes.push({ p: toLocal(at, it.final.pos, it.final.rot), n: unrotate(n, it.final.rot), r });+ }++ hwType(def: HwDef) {+ const id = `${def.kind}-${def.len}-${def.dia}${def.notIncluded ? "-x" : ""}`;+ if (!this.hw.has(id)) {+ this.hw.set(id, {+ id,+ kind: def.kind,+ name: HW_NAMES[def.kind],+ spec: hwSpecText(def.kind, def.len, def.dia),+ len: def.len,+ dia: def.dia,+ qty: 0,+ notIncluded: def.notIncluded,+ });+ }+ return id;+ }++ /* ---------- step context ---------- */++ step(def: StepDef, body: () => void) {+ const s: Step = {+ n: this.steps.length,+ title: def.title,+ detail: def.detail,+ tools: def.tools ?? [],+ people: def.people ?? 1,+ repeat: def.repeat,+ scene: def.scene ?? "main",+ pose: def.pose ?? "+y",+ warnings: def.warnings ?? [],+ kind: def.kind,+ check: def.check,+ wall: def.wall,+ minutes: def.weight ?? 0,+ };+ this.steps.push(s);+ this.cur = s;+ this.t = 0.15;+ this.end = 0.15;+ this.gap = 0.22;+ body();+ this.cur = null;+ return s;+ }++ private get step_(): Step {+ if (!this.cur) throw new Error("outside step");+ return this.cur;+ }++ stagger(gap: number) {+ this.gap = gap;+ }+ then(pause = 0.12) {+ this.t = this.end + pause;+ }+ wait(sec: number) {+ this.t += sec;+ }++ private slot(dur: number) {+ const d = this.t;+ this.t += this.gap;+ this.end = Math.max(this.end, d + dur);+ return d;+ }++ /** Part reaches its assembled position in this step. */+ add(key: string, from?: Vec3, o: { spin?: number } = {}) {+ const it = this.partItem(key);+ const s = this.step_;+ it.states.push({ step: s.n, scene: s.scene, pos: it.final.pos, rot: it.final.rot, from, spin: o.spin, delay: this.slot(DUR.part + (o.spin ? 0.4 : 0)) });+ }++ /** Part is shown somewhere else (laid flat, upside down...) from this step until it is added. */+ stage(key: string, pos: Vec3, rot: Vec3, from?: Vec3) {+ const it = this.partItem(key);+ const s = this.step_;+ it.states.push({ step: s.n, scene: s.scene, pos, rot, from, delay: this.slot(DUR.part) });+ }++ fit(def: HwDef, o: FitOpts) {+ const s = this.step_;+ const ref = this.hwType(def);+ const key = "h" + this.n++;+ let pos = o.at;+ let dir = o.dir;+ if (o.on) {+ const p = this.partItem(o.on);+ pos = toLocal(o.at, p.final.pos, p.final.rot);+ dir = unrotate(o.dir, p.final.rot);+ const r = o.hole === false ? 0 : (o.hole ?? holeR(def));+ if (r > 0) p.holes.push({ p: pos, n: [-dir[0], -dir[1], -dir[2]], r });+ }+ if (o.mate) this.hole(o.mate, o.at, o.dir, o.mateHole ?? Math.max(holeR(def), 3));+ const travel = o.travel ?? defaultTravel(def);+ const extra = def.kind === "cam" ? 0.7 : o.spin ? 0.35 : 0;+ const it: HwItem = {+ key,+ kind: "hw",+ ref,+ parent: o.on,+ scene: o.on ? undefined : s.scene,+ step: s.n,+ pos,+ dir,+ twist: o.twist,+ travel,+ spin: o.spin ?? defaultSpin(def),+ turn: o.turn ?? (def.kind === "cam" ? Math.PI * 0.75 : undefined),+ delay: this.slot(DUR.hw + extra),+ scale: o.scale,+ };+ this.items.push(it);+ this.map.set(key, it);+ return key;+ }++ fits(def: HwDef, list: FitOpts[], gap = 0.06) {+ const g = this.gap;+ this.gap = gap;+ const keys = list.map((o) => this.fit(def, o));+ this.gap = g;+ return keys;+ }++ /** Hardware already in place on a part (e.g. the 2nd and 3rd drawer): appears with the part, no animation. */+ preset(def: HwDef, o: FitOpts) {+ const k = this.fit(def, { ...o, travel: 0, spin: 0, turn: 0 });+ const it = this.map.get(k) as HwItem;+ it.delay = 0;+ it.preset = true;+ return k;+ }++ /* ---------- finalize ---------- */++ build(): Plan {+ // drop unused parts, assign letters by first appearance+ const firstStep = new Map<string, number>();+ const counts = new Map<string, number>();+ for (const it of this.items) {+ if (it.kind === "part") {+ if (!it.states.length) throw new Error(`part ${it.key} never added`);+ const s = Math.min(...it.states.map((x) => x.step));+ firstStep.set(it.ref, Math.min(firstStep.get(it.ref) ?? 1e9, s));+ counts.set(it.ref, (counts.get(it.ref) ?? 0) + 1);+ } else {+ const t = this.hw.get(it.ref)!;+ t.qty++;+ }+ }+ const used = this.parts.filter((p) => counts.has(p.id));+ used.sort((a, b) => (firstStep.get(a.id)! - firstStep.get(b.id)!) || this.parts.indexOf(a) - this.parts.indexOf(b));+ let li = 0;+ for (const p of used) {+ p.qty = counts.get(p.id)!;+ p.label = p.extra ? "" : p.label || LETTERS[li++ % LETTERS.length];+ }+ used.sort((a, b) => (a.extra ? 1 : 0) - (b.extra ? 1 : 0) || a.label.localeCompare(b.label, undefined, { numeric: true }));++ // step weights -> minutes+ const weights = this.steps.map((s) => {+ if (s.minutes) return s.minutes;+ if (s.quiet) return 1.6;+ const parts = this.items.filter((i) => i.kind === "part" && i.states[0]?.step === s.n).length + this.items.filter((i) => i.kind === "part" && i.states.length > 1 && i.states.some((x, k) => k > 0 && x.step === s.n)).length * 0.5;+ const hws = this.items.filter((i) => i.kind === "hw" && i.step === s.n && !i.preset).length;+ return (0.8 + parts * 0.6 + hws * 0.12) * (s.repeat ?? 1);+ });+ const total = weights.reduce((a, b) => a + b, 0) || 1;+ this.steps.forEach((s, i) => {+ s.minutes = Math.max(1, Math.round((weights[i] / total) * this.spec.minutes));+ });++ // tools+ const toolSet = new Set<ToolId>();+ this.steps.forEach((s) => s.tools.forEach((t) => toolSet.add(t)));+ const order: ToolId[] = ["allen", "screwdriver", "flathead", "hammer", "wrench", "tape", "drill", "pencil", "level", "knife"];+ const tools: ToolNeed[] = order+ .filter((t) => toolSet.has(t) || t === "knife")+ .map((id) => {+ const n: ToolNeed = { id };+ if (id === "allen" || id === "wrench") n.included = true;+ if (id === "drill") {+ n.optional = true;+ n.why = "Only for fixing it to the wall";+ }+ if (id === "tape") {+ n.optional = true;+ n.why = "To check it is square";+ }+ if (id === "pencil" || id === "level") {+ n.optional = true;+ n.why = "Handy for marking the wall";+ }+ if (id === "knife") {+ n.optional = true;+ n.why = "To open the box. Cut the tape, not the panels";+ }+ return n;+ });++ const hardware = [...this.hw.values()].sort((a, b) => (a.notIncluded ? 1 : 0) - (b.notIncluded ? 1 : 0));++ return { spec: this.spec, parts: used, hardware, items: this.items, steps: this.steps, tools };+ }+}++function holeR(def: HwDef) {+ switch (def.kind) {+ case "dowel":+ return 4;+ case "camScrew":+ return 2.5;+ case "cam":+ return 7.5;+ case "screw":+ return def.notIncluded ? 0 : 1.6;+ case "pin":+ return 2.5;+ case "legScrew":+ return 4;+ case "bolt":+ return 3.5;+ default:+ return 0;+ }+}++function defaultTravel(def: HwDef) {+ switch (def.kind) {+ case "dowel":+ return 34;+ case "camScrew":+ return 30;+ case "cam":+ return 24;+ case "screw":+ return def.len + 14;+ case "nail":+ return 22;+ case "pin":+ return 18;+ case "legScrew":+ return 50;+ case "bolt":+ return def.len + 10;+ case "plug":+ return 40;+ case "knob":+ case "handle":+ return 40;+ default:+ return 50;+ }+}++function defaultSpin(def: HwDef) {+ switch (def.kind) {+ case "camScrew":+ return 3;+ case "screw":+ return 4;+ case "bolt":+ return 3;+ case "legScrew":+ return 2;+ default:+ return 0;+ }+}diff --git a/src/lib/plan/cabinet.ts b/src/lib/plan/cabinet.tsnew file mode 100644index 0000000..7c8d842--- /dev/null+++ b/src/lib/plan/cabinet.ts@@ -0,0 +1,236 @@+import type { CabinetParams, ProductSpec, Vec3 } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { FrameKit } from "./frame";+import { clamp } from "./math";++export function defaultsCabinet(s: ProductSpec): CabinetParams {+ const p = s.cabinet ?? {};+ const tilt = p.fronts === "tilt";+ return {+ fronts: tilt ? "tilt" : "doors",+ compartments: clamp(Math.round(p.compartments ?? 2), 1, 5),+ doors: tilt ? 0 : p.doors === 0 || p.doors === 1 || p.doors === 2 ? p.doors : s.size.w > 60 ? 2 : 1,+ shelves: clamp(Math.round(p.shelves ?? 1), 0, 5),+ rail: p.rail ?? s.size.h > 160,+ plinth: p.plinth ?? s.size.h > 120,+ handles: p.handles ?? "knob",+ thickness: clamp(p.thickness ?? 18, 12, 25),+ };+}++export function buildCabinet(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsCabinet(s);+ if (p.fronts === "tilt") return tiltCabinet(b, s, p);+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const t = p.thickness;+ const base = p.plinth ? 70 : 0;+ const lying = H > 1100;+ const f = new FrameKit(b, {+ W, H, D, t, base,+ plinth: p.plinth,+ fixed: [],+ back: true,+ pinRows: p.shelves > 0,+ lying,+ });++ f.prepSides();+ f.join(lying ? 1 : 1);+ f.otherSide();+ f.cams();+ f.plinthStep();+ f.backSteps();+ f.standUp();++ // shelves sit lower when there is a rail+ if (p.shelves > 0) f.shelves(p.shelves);++ if (p.rail) {+ const rT = b.part("Clothes rail", [24, W - 2 * t - 2, 24], { shape: "cyl", material: "metal" });+ const ry = H - t - 70;+ const rail = b.place(rT, [0, ry, 0], [0, 0, Math.PI / 2]);+ b.step(+ {+ title: "Fit the clothes rail",+ detail: "Clip the holders on first, then drop the rail in.",+ tools: ["screwdriver"],+ kind: "screws",+ },+ () => {+ const holders: FitOpts[] = f.sides.map((sd, i) => ({+ on: sd,+ at: [(i === 0 ? -1 : 1) * (W / 2 - t), ry, 0] as Vec3,+ dir: [i === 0 ? -1 : 1, 0, 0] as Vec3,+ hole: false,+ }));+ b.fits(HW.screwS, holders, 0.1);+ b.then(0.1);+ b.add(rail, [0, -180, 260]);+ },+ );+ }++ if (p.doors > 0) {+ const nd = p.doors;+ const dw = nd === 2 ? W / 2 - 3 : W - 4;+ const dh = H - base - 4;+ const dy = base + 2 + dh / 2;+ const doorT = b.part("Door", [dw, dh, t]);+ const doors = Array.from({ length: nd }, (_, i) => {+ const x = nd === 2 ? (i === 0 ? -1 : 1) * (W / 4) : 0;+ return b.place(doorT, [x, dy, D / 2 + t / 2]);+ });+ const hn = dh > 1500 ? 4 : dh > 900 ? 3 : 2;+ const hingeYs = Array.from({ length: hn }, (_, i) => base + 110 + (i * (dh - 220)) / (hn - 1));+ const hingeX = (i: number) => {+ // left door hinges on the left, right on the right, single door on the left+ const sgn = nd === 2 && i === 1 ? 1 : -1;+ return { x: sgn * (W / 2 - 22), sgn };+ };+ b.step(+ {+ title: nd > 1 ? "Press the hinges into the doors" : "Press the hinges into the door",+ detail: "Two small screws hold each one.",+ tools: ["screwdriver"],+ scene: "doors",+ repeat: undefined,+ kind: "hinges",+ warnings: ["floor"],+ },+ () => {+ b.stagger(0.2);+ doors.forEach((d, i) => b.stage(d, [(i - (nd - 1) / 2) * (dw + 80), t / 2, 0], [Math.PI / 2, 0, 0], [0, 160, 0]));+ b.then(0.1);+ const hinges: FitOpts[] = [];+ const screws: FitOpts[] = [];+ doors.forEach((d, i) => {+ const { x, sgn } = hingeX(i);+ for (const y of hingeYs) {+ hinges.push({ on: d, at: [x, y, D / 2], dir: [0, 0, 1], twist: sgn > 0 ? Math.PI : 0 });+ for (const dy2 of [-24, 24]) screws.push({ on: d, at: [x + sgn * 4, y + dy2, D / 2], dir: [0, 0, 1], hole: false });+ }+ });+ b.fits(HW.hinge, hinges, 0.1);+ b.then(0.05);+ b.fits(HW.screwS, screws, 0.03);+ },+ );+ b.step(+ {+ title: nd > 1 ? "Hang the doors" : "Hang the door",+ detail: "Slide each hinge arm onto its plate until it clicks.",+ kind: "doors",+ people: dh > 1500 ? 2 : 1,+ warnings: dh > 1500 ? ["two"] : [],+ },+ () => {+ b.stagger(0.35);+ doors.forEach((d) => b.add(d, [0, 0, 380]));+ },+ );+ b.step(+ {+ title: "Line up the doors",+ detail: "Turn the hinge screws a little until the gaps look even.",+ tools: ["screwdriver"],+ kind: "doors",+ },+ () => {},+ );+ if (p.handles !== "none") {+ const def = p.handles === "bar" ? HW.handle : HW.knob;+ b.step(+ {+ title: p.handles === "bar" ? "Screw on the handles" : "Screw on the knobs",+ detail: "Screw from the inside of the door.",+ tools: ["screwdriver"],+ kind: "screws",+ },+ () => {+ const list: FitOpts[] = doors.map((d, i) => {+ const { sgn } = hingeX(i);+ const x = b.partItem(d).final.pos[0] - sgn * (dw / 2 - 40);+ return { on: d, at: [x, Math.min(dy, 1050), D / 2 + t], dir: [0, 0, -1], hole: false, twist: p.handles === "bar" ? Math.PI / 2 : 0 };+ });+ b.fits(def, list, 0.12);+ },+ );+ }+ }++ if (H >= 800) f.anchor();+}++/** Shoe cabinets like BISSA or HEMNES: stacked compartments with fronts that tip open from the bottom. */+function tiltCabinet(b: PlanBuilder, s: ProductSpec, p: CabinetParams) {+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const t = p.thickness;+ const base = p.plinth ? 60 : 0;+ const n = p.compartments;+ const innerH = H - base - 2 * t;+ const compH = (innerH - (n - 1) * t) / n;+ const fixed = Array.from({ length: n - 1 }, (_, i) => base + t + (i + 1) * compH + i * t + t / 2);+ const lying = H > 1100;+ const f = new FrameKit(b, { W, H, D, t, base, plinth: p.plinth, fixed, back: true, pinRows: false, lying, names: { fixed: "Divider shelf" } });+ f.prepSides();+ f.join();+ f.otherSide();+ f.cams();+ f.plinthStep();+ f.backSteps();+ f.standUp();++ const fh = (H - base) / n - 4;+ const frontT = b.part("Front", [W - 4, fh, t]);+ const fronts = Array.from({ length: n }, (_, i) => b.place(frontT, [0, base + 2 + i * (fh + 4) + fh / 2, D / 2 + t / 2]));+ b.step(+ {+ title: n > 1 ? "Fit the hinges to the fronts" : "Fit the hinges to the front",+ detail: "They go on the inside, along the bottom edge.",+ tools: ["screwdriver"],+ scene: "fronts",+ kind: "hinges",+ warnings: ["floor"],+ },+ () => {+ b.stagger(0.2);+ fronts.forEach((k, i) => b.stage(k, [(i - (n - 1) / 2) * (W + 80), t / 2, 0], [Math.PI / 2, 0, 0], [0, 160, 0]));+ b.then(0.1);+ const list: FitOpts[] = [];+ fronts.forEach((k) => {+ const y = b.partItem(k).final.pos[1] - fh / 2 + 34;+ for (const sx of [-1, 1]) list.push({ on: k, at: [sx * (W / 2 - 60), y, D / 2], dir: [0, 0, 1], twist: sx > 0 ? Math.PI : 0 });+ });+ b.fits(HW.hinge, list, 0.1);+ },+ );+ b.step(+ {+ title: n > 1 ? "Hang the fronts, bottom first" : "Hang the front",+ detail: "Each one tips open from the top. Check it swings freely before the next.",+ kind: "doors",+ },+ () => {+ b.stagger(0.35);+ fronts.forEach((k) => b.add(k, [0, -60, 360]));+ },+ );+ if (p.handles !== "none") {+ const def = p.handles === "bar" ? HW.handle : HW.knob;+ b.step(+ {+ title: p.handles === "bar" ? "Screw on the handles" : "Screw on the knobs",+ detail: "Near the top edge, so the fronts tip open easily.",+ tools: ["screwdriver"],+ kind: "screws",+ },+ () => {+ const list: FitOpts[] = fronts.map((k) => ({ on: k, at: [0, b.partItem(k).final.pos[1] + fh / 2 - 50, D / 2 + t] as Vec3, dir: [0, 0, -1] as Vec3, hole: false, twist: p.handles === "bar" ? 0 : 0 }));+ b.fits(def, list, 0.12);+ },+ );+ }+ f.anchor();+ const last = b.steps[b.steps.length - 1];+ last.detail = "Shoe cabinets are shallow and tip forward easily. Always fix it to the wall. Wall screws aren't included.";+}diff --git a/src/lib/plan/contents.ts b/src/lib/plan/contents.tsnew file mode 100644index 0000000..1385b47--- /dev/null+++ b/src/lib/plan/contents.ts@@ -0,0 +1,51 @@+import type { HwType, PartType, Plan } from "../types";++export interface StepContents {+ parts: { type: PartType; count: number }[];+ hardware: { type: HwType; count: number }[];+}++const memo = new WeakMap<Plan, StepContents[]>();++/** What the person needs in their hands for each step. */+export function stepContents(plan: Plan, index: number): StepContents {+ let all = memo.get(plan);+ if (!all) {+ all = plan.steps.map((s) => {+ const parts = new Map<string, number>();+ const hw = new Map<string, number>();+ if (!s.quiet)+ for (const it of plan.items) {+ if (it.kind !== "part") continue;+ const first = it.states[0];+ if (first && first.step === s.n) parts.set(it.ref, (parts.get(it.ref) ?? 0) + 1);+ }+ for (const it of plan.items) {+ if (it.kind !== "hw" || it.step !== s.n || it.preset) continue;+ hw.set(it.ref, (hw.get(it.ref) ?? 0) + 1);+ }+ return {+ parts: [...parts].map(([id, count]) => ({ type: plan.parts.find((p) => p.id === id)!, count })).filter((x) => x.type),+ hardware: [...hw].map(([id, count]) => ({ type: plan.hardware.find((h) => h.id === id)!, count })).filter((x) => x.type),+ };+ });+ memo.set(plan, all);+ }+ return all[index] ?? { parts: [], hardware: [] };+}++export function totals(plan: Plan) {+ const panels = plan.parts.filter((p) => !p.extra).reduce((s, p) => s + p.qty, 0);+ const fittings = plan.hardware.filter((h) => !h.notIncluded).reduce((s, h) => s + h.qty, 0);+ const minutes = plan.steps.reduce((s, x) => s + x.minutes, 0);+ const twoAt = plan.steps.filter((s) => s.people === 2).map((s) => s.n + 1);+ return { panels, fittings, minutes, twoAt };+}++export function floorSpace(plan: Plan) {+ const { w, h, d } = plan.spec.size;+ const a = Math.max(w, h) + 100;+ const b = Math.max(d, Math.min(w, h)) + 100;+ const r = (x: number) => Math.max(1, Math.round(x / 50) / 2);+ return `${r(a)} × ${r(b)} m`;+}diff --git a/src/lib/plan/custom.ts b/src/lib/plan/custom.tsnew file mode 100644index 0000000..eb8a991--- /dev/null+++ b/src/lib/plan/custom.ts@@ -0,0 +1,562 @@+import type { CustomFix, CustomPart, CustomStep, HwKind, PartMaterial, Pose, ProductSpec, StepKind, ToolId, Vec3, WarnId } from "../types";+import { HW, PlanBuilder, type FitOpts, type HwDef } from "./builder";+import { POSE_EULER, unrotate } from "./math";++/**+ * Builds a guide from a product someone scanned from their own manual.+ * The AI only describes boxes (where each part sits in the finished product) and which parts each step adds.+ * Everything fiddly is worked out here: where parts touch, where each dowel, bolt or screw goes,+ * which way parts arrive from, and which tools a step needs.+ */++type Box = { min: Vec3; max: Vec3 };+interface Node {+ id: string;+ part: CustomPart;+ key: string;+ box: Box;+}+interface Contact {+ a: Node;+ b: Node;+ n: 0 | 1 | 2;+ plane: number;+ rect: [[number, number], [number, number]];+ uv: [0 | 1 | 2, 0 | 1 | 2];+}++const AXES = [0, 1, 2] as const;+const PRE: HwKind[] = ["dowel", "camScrew", "pin", "legScrew", "plate"];++export function boxOf(p: { size: Vec3; pos: Vec3 }): Box {+ return {+ min: [p.pos[0] - p.size[0] / 2, p.pos[1] - p.size[1] / 2, p.pos[2] - p.size[2] / 2],+ max: [p.pos[0] + p.size[0] / 2, p.pos[1] + p.size[1] / 2, p.pos[2] + p.size[2] / 2],+ };+}++const ext = (b: Box, k: number) => b.max[k] - b.min[k];+const mid = (b: Box, k: number) => (b.max[k] + b.min[k]) / 2;+const unit = (k: number, s: number): Vec3 => {+ const v: Vec3 = [0, 0, 0];+ v[k] = s;+ return v;+};++function contactOf(a: Node, b: Node, tol = 4): Contact | null {+ const ov = AXES.map((k) => Math.min(a.box.max[k], b.box.max[k]) - Math.max(a.box.min[k], b.box.min[k]));+ let n = -1;+ let best = Infinity;+ for (const k of AXES) {+ if (Math.abs(ov[k]) > tol) continue;+ const others = AXES.filter((j) => j !== k);+ if (others.every((j) => ov[j] > 2) && Math.abs(ov[k]) < best) {+ best = Math.abs(ov[k]);+ n = k;+ }+ }+ if (n < 0) return null;+ const [u, v] = AXES.filter((j) => j !== n) as [0 | 1 | 2, 0 | 1 | 2];+ const aLow = mid(a.box, n) < mid(b.box, n);+ const plane = aLow ? (a.box.max[n] + b.box.min[n]) / 2 : (a.box.min[n] + b.box.max[n]) / 2;+ return {+ a,+ b,+ n: n as 0 | 1 | 2,+ plane,+ rect: [+ [Math.max(a.box.min[u], b.box.min[u]), Math.min(a.box.max[u], b.box.max[u])],+ [Math.max(a.box.min[v], b.box.min[v]), Math.min(a.box.max[v], b.box.max[v])],+ ],+ uv: [u, v],+ };+}++const longLen = (c: Contact) => Math.max(c.rect[0][1] - c.rect[0][0], c.rect[1][1] - c.rect[1][0]);++/** Evenly spaced points along the long side of a contact, centred across the short side. */+function along(c: Contact, count: number, o: { inset?: number; across?: number } = {}): Vec3[] {+ const lu = c.rect[0][1] - c.rect[0][0], lv = c.rect[1][1] - c.rect[1][0];+ const li = lu >= lv ? 0 : 1;+ const L = c.rect[li], S = c.rect[1 - li];+ const len = L[1] - L[0];+ const pad = count === 1 ? 0 : Math.min(len * (o.inset ?? 0.16), 70);+ const out: Vec3[] = [];+ for (let i = 0; i < count; i++) {+ const t = count === 1 ? 0.5 : i / (count - 1);+ const p: Vec3 = [0, 0, 0];+ p[c.n] = c.plane;+ p[c.uv[li]] = L[0] + pad + (len - 2 * pad) * t;+ p[c.uv[1 - li]] = o.across ?? (S[0] + S[1]) / 2;+ out.push(p);+ }+ return out;+}++/** Split a fitting count over contacts, longest contacts first. */+function share(count: number, contacts: Contact[]) {+ if (!contacts.length || count <= 0) return [];+ const sorted = [...contacts].sort((a, b) => longLen(b) - longLen(a));+ if (count <= sorted.length) return sorted.slice(0, count).map((c) => ({ c, k: 1 }));+ const total = sorted.reduce((s, c) => s + longLen(c), 0) || 1;+ const ks = sorted.map((c) => Math.max(1, Math.round((count * longLen(c)) / total)));+ let left = count - ks.reduce((a, b) => a + b, 0);+ for (let i = 0; left > 0; i = (i + 1) % ks.length, left--) ks[i]++;+ for (let i = ks.length - 1; left < 0; i = (i - 1 + ks.length) % ks.length) {+ if (ks[i] > 1) {+ ks[i]--;+ left++;+ }+ }+ return sorted.map((c, i) => ({ c, k: ks[i] }));+}++function defFor(f: CustomFix, thick?: number): HwDef {+ const base: HwDef = (() => {+ switch (f.kind) {+ case "dowel":+ return HW.dowel;+ case "camScrew":+ return HW.camScrew;+ case "cam":+ return HW.cam;+ case "nail":+ return HW.nail;+ case "pin":+ return HW.pin;+ case "legScrew":+ return HW.legScrew;+ case "bolt":+ return HW.boltS;+ case "plate":+ return HW.plate;+ case "bracket":+ return HW.bracket;+ case "knob":+ return HW.knob;+ case "handle":+ return HW.handle;+ case "hinge":+ return HW.hinge;+ case "glide":+ return HW.glide;+ default:+ return HW.screwM;+ }+ })();+ const len = f.len && f.len > 2 && f.len < 400 ? Math.round(f.len) : base.kind === "screw" && thick ? Math.round(Math.min(70, Math.max(14, thick + 16)) / 2) * 2 : base.len;+ const dia = f.dia && f.dia > 0.8 && f.dia < 60 ? Math.round(f.dia * 10) / 10 : base.dia;+ return { ...base, len, dia };+}++function inferMaterial(p: CustomPart): PartMaterial {+ if (p.material) return p.material;+ const n = p.name.toLowerCase();+ if (/back|hardboard|fibre|fiber/.test(n)) return "fiber";+ if (/cushion|pillow|mattress|seat pad|upholster/.test(n)) return "soft";+ if (/metal|steel|tube|rail|rod|bar/.test(n)) return "metal";+ if (/leg|slat|beam|rail|frame|dowel|post/.test(n)) return "wood";+ return "board";+}++const KIND_OF: Partial<Record<HwKind, StepKind>> = {+ dowel: "dowels",+ camScrew: "cams",+ cam: "cams",+ screw: "screws",+ nail: "nails",+ bolt: "bolts",+ legScrew: "legs",+ pin: "shelves",+ hinge: "hinges",+ knob: "screws",+ handle: "screws",+ bracket: "anchor",+};++const TOOLS_OF: Partial<Record<HwKind, ToolId>> = {+ camScrew: "screwdriver",+ cam: "screwdriver",+ screw: "screwdriver",+ nail: "hammer",+ bolt: "allen",+ hinge: "screwdriver",+ knob: "screwdriver",+ handle: "screwdriver",+ bracket: "drill",+};++export function buildCustom(b: PlanBuilder, s: ProductSpec) {+ const c = s.custom;+ if (!c || !c.parts.length) throw new Error("no parts");+ const nodes = new Map<string, Node>();+ const center: Vec3 = [0, 0, 0];+ const all = c.parts.map((p) => boxOf(p));+ const lo: Vec3 = [Math.min(...all.map((x) => x.min[0])), Math.min(...all.map((x) => x.min[1])), Math.min(...all.map((x) => x.min[2]))];+ const hi: Vec3 = [Math.max(...all.map((x) => x.max[0])), Math.max(...all.map((x) => x.max[1])), Math.max(...all.map((x) => x.max[2]))];+ for (const k of AXES) center[k] = (lo[k] + hi[k]) / 2;++ // one part type per distinct name and size, so identical panels share a letter+ const labelsOk = c.parts.every((p) => p.label && p.label.length <= 3) && new Set(c.parts.map((p) => p.label)).size === new Set(c.parts.map((p) => `${p.name}|${p.size.map(Math.round).join("x")}`)).size;+ const types = new Map<string, string>();+ for (const p of c.parts) {+ const material = inferMaterial(p);+ const horizontalRod = p.shape === "cyl" && Math.max(p.size[0], p.size[2]) > p.size[1] * 1.5;+ const tk = `${p.name.toLowerCase()}|${p.size.map((n) => Math.round(n)).join("x")}|${p.shape ?? "box"}|${material}`;+ let ref = types.get(tk);+ if (!ref) {+ const size: Vec3 = p.shape === "cyl" ? (horizontalRod ? [Math.min(p.size[1], p.size[2], p.size[0]), Math.max(p.size[0], p.size[2]), Math.min(p.size[1], p.size[2], p.size[0])] : [p.size[0], p.size[1], p.size[2]]) : p.size;+ ref = b.part(p.name, size, { shape: p.shape ?? "box", material, label: labelsOk ? p.label : undefined });+ types.set(tk, ref);+ }+ const rot: Vec3 = horizontalRod ? (p.size[0] >= p.size[2] ? [0, 0, Math.PI / 2] : [Math.PI / 2, 0, 0]) : [0, 0, 0];+ const key = b.place(ref, p.pos, rot);+ nodes.set(p.id, { id: p.id, part: p, key, box: boxOf(p) });+ }++ const placed: Node[] = [];+ let lastAdded: Node[] = [];+ let stepHosts: Node[] = [];+ const used: Vec3[] = [];+ const ctx: Ctx = { center, lo, hi };+ const isPlaced = (n: Node) => placed.includes(n);+ const steps = normalizeSteps(c.steps, c.parts);+ let pose: Pose = "+y";++ steps.forEach((st, si) => {+ const adds = (st.add ?? []).map((id) => nodes.get(id)).filter((n): n is Node => !!n && !isPlaced(n));+ const fixes = (st.fix ?? []).filter((f) => f.count > 0).slice(0, 6);+ const nextPose = st.pose ?? pose;+ const turned = nextPose !== pose;+ pose = nextPose;+ const kind: StepKind = adds.length+ ? fixes.length+ ? (KIND_OF[fixes.find((f) => !PRE.includes(f.kind))?.kind ?? fixes[0].kind] ?? "join")+ : "join"+ : fixes.length+ ? (KIND_OF[fixes[0].kind] ?? "general")+ : turned+ ? pose === "+y"+ ? "standup"+ : "flip"+ : "general";+ const tools = new Set<ToolId>(st.tools ?? []);+ for (const f of fixes) {+ const t = TOOLS_OF[f.kind];+ if (t) tools.add(t);+ }+ const warnings = new Set<WarnId>(st.warnings ?? []);+ const wall = fixes.some((f) => f.kind === "bracket");+ if (wall) {+ warnings.add("wall");+ tools.add("pencil");+ tools.add("screwdriver");+ }+ if ((st.people ?? 1) === 2) warnings.add("two");++ b.step(+ {+ title: st.title,+ detail: st.detail,+ tools: [...tools],+ people: st.people ?? 1,+ pose,+ kind,+ wall,+ warnings: [...warnings].slice(0, 3),+ },+ () => {+ const targets = new Set(fixes.flatMap((f) => f.to ?? []));+ const hits = (x: Node, y: Node) => !targets.size || targets.has(x.id) || targets.has(y.id);+ const pairs = (pool: Node[], keep: (x: Node, y: Node) => boolean) => {+ const out: Contact[] = [];+ for (let i = 0; i < pool.length; i++)+ for (let j = 0; j < i; j++) {+ if (!keep(pool[i], pool[j])) continue;+ const ct = contactOf(pool[i], pool[j]);+ if (ct) out.push(ct);+ }+ return out;+ };+ // joints made in this step, joints about to be made (dowels go in first), and joints already made (cams, screws)+ const now = adds.length ? pairs([...placed, ...adds], (x, y) => adds.includes(x) || adds.includes(y)) : [];+ const future = adds.length ? [] : lookahead(steps, si, nodes, placed);+ const soon = future.length ? pairs([...placed, ...future], (x, y) => (future.includes(x) || future.includes(y)) && hits(x, y)) : [];+ const recent = lastAdded.length ? lastAdded : placed;+ const made = pairs(placed, (x, y) => (targets.size ? hits(x, y) : recent.includes(x) || recent.includes(y)));+ const jointsFor = (f: CustomFix) => (adds.length ? now : PRE.includes(f.kind) ? (soon.length ? soon : made) : made.length ? made : soon);+ const freshFor = (f: CustomFix) => (adds.length ? adds : PRE.includes(f.kind) && soon.length ? future : recent);++ const pre = fixes.filter((f) => PRE.includes(f.kind));+ const post = fixes.filter((f) => !PRE.includes(f.kind));+ const preGroups = pre.flatMap((f) => planFits(f, jointsFor(f), freshFor(f), placed, ctx));++ // a part that receives fittings before it is joined shows up now, so you can see where they go+ const hosts = adds.length ? [] : [...new Set(preGroups.flatMap((g) => g.fits.map((x) => x.host)))].filter((n) => !isPlaced(n));+ const arriving = [...hosts, ...adds];+ b.stagger(arriving.length > 3 ? 0.18 : 0.26);+ const inStep: Node[] = [];+ if (hosts.length) {+ for (const n of hosts) {+ b.add(n.key, approach(n, [...placed, ...inStep], pose));+ inStep.push(n);+ }+ b.then(0.15);+ }++ b.stagger(0.05);+ if (preGroups.length) {+ emit(b, preGroups, used);+ b.then(0.15);+ }++ b.stagger(adds.length > 3 ? 0.18 : 0.26);+ for (const n of adds) {+ b.add(n.key, approach(n, [...placed, ...inStep], pose));+ inStep.push(n);+ }+ if (adds.length) b.then(0.12);++ b.stagger(0.05);+ for (const f of post) {+ emit(b, planFits(f, jointsFor(f), freshFor(f), [...placed, ...inStep], ctx), used);+ b.then(0.1);+ }+ stepHosts = hosts;+ },+ );+ placed.push(...stepHosts, ...adds);+ if (adds.length || stepHosts.length) lastAdded = [...stepHosts, ...adds];+ stepHosts = [];+ });+}++/** Parts the next step attaches, so hardware-only steps ("tap in the dowels") land where those joints will be. */+function lookahead(steps: CustomStep[], si: number, nodes: Map<string, Node>, placed: Node[]): Node[] {+ for (let j = si + 1; j < Math.min(steps.length, si + 4); j++) {+ const next = (steps[j].add ?? []).map((id) => nodes.get(id)).filter((n): n is Node => !!n && !placed.includes(n));+ if (next.length) return next;+ }+ return [];+}++function approach(n: Node, others: Node[], pose: Pose): Vec3 {+ let best: Contact | null = null;+ let bestLen = 0;+ for (const o of others) {+ const ct = contactOf(n, o);+ if (ct && longLen(ct) > bestLen) {+ best = ct;+ bestLen = longLen(ct);+ }+ }+ const size = Math.max(...n.part.size);+ const d = Math.min(520, Math.max(240, size * 0.45));+ if (!best) return unrotate([0, d, 0], POSE_EULER[pose]).map((x) => Math.round(x)) as Vec3;+ const k = best.n;+ const away = mid(n.box, k) < mid(best.b.box, k) ? -1 : 1;+ return unit(k, away * d);+}++interface Fit extends FitOpts {+ host: Node;+ slide?: number;+}+interface Group {+ def: HwDef;+ fits: Fit[];+}+interface Ctx {+ center: Vec3;+ lo: Vec3;+ hi: Vec3;+}++/** Work out where each fitting of one kind goes. Nothing is emitted yet, so the step can show the host parts first. */+function planFits(f: CustomFix, contacts: Contact[], fresh: Node[], placed: Node[], ctx: Ctx): Group[] {+ const count = Math.min(48, Math.max(1, Math.round(f.count)));+ const to = new Set(f.to ?? []);+ const pick = to.size ? contacts.filter((c) => to.has(c.a.id) || to.has(c.b.id)) : contacts;+ const list = pick.length ? pick : contacts;+ const thinner = (c: Contact) => (ext(c.a.box, c.n) <= ext(c.b.box, c.n) ? c.a : c.b);+ const otherOf = (c: Contact, x: Node) => (x === c.a ? c.b : c.a);+ const into = (c: Contact, x: Node) => unit(c.n, mid(x.box, c.n) > c.plane ? 1 : -1);+ const fits: Fit[] = [];+ let slide: number | undefined;+ const one = (host: Node, o: FitOpts) => fits.push({ ...o, on: host.key, host, slide });+ const longAxis = (c: Contact) => (c.rect[0][1] - c.rect[0][0] >= c.rect[1][1] - c.rect[1][0] ? c.uv[0] : c.uv[1]);++ switch (f.kind) {+ case "dowel":+ case "camScrew": {+ for (const { c, k } of share(count, list)) {+ // dowels go into the part already standing (or the panel whose edge meets the joint), cam bolts into the face+ slide = longAxis(c);+ const named = to.has(c.a.id) ? c.a : to.has(c.b.id) ? c.b : null;+ const host = named ?? (f.kind === "camScrew" ? thinner(c) : placed.includes(c.b) && !placed.includes(c.a) ? c.b : thinner(c));+ for (const p of along(c, k, { inset: f.kind === "dowel" ? 0.3 : 0.1 })) one(host, { at: p, dir: into(c, host), mate: otherOf(c, host).key });+ }+ break;+ }+ case "cam": {+ for (const { c, k } of share(count, list)) {+ slide = longAxis(c);+ const face = thinner(c);+ const edge = otherOf(c, face);+ const t = ([0, 1, 2] as const).filter((x) => x !== c.n).reduce((a, x) => (ext(edge.box, x) < ext(edge.box, a) ? x : a), c.uv[0]);+ const inward = mid(edge.box, t) > ctx.center[t];+ for (const p of along(c, k, { inset: 0.1 })) {+ const q: Vec3 = [...p];+ const depth = Math.min(30, ext(edge.box, c.n) / 3);+ q[c.n] += mid(edge.box, c.n) > c.plane ? depth : -depth;+ q[t] = inward ? edge.box.min[t] : edge.box.max[t];+ one(edge, { at: q, dir: unit(t, inward ? 1 : -1) });+ }+ }+ break;+ }+ case "pin": {+ for (const { c, k } of share(count, list)) {+ // a shelf rests on pins pushed into the side it touches+ const shelf = ext(c.a.box, 1) <= ext(c.b.box, 1) ? c.a : c.b;+ const side = otherOf(c, shelf);+ for (const q of along(c, k, { inset: 0.12 })) {+ if (c.n !== 1) q[1] = shelf.box.min[1] - 4;+ one(side, { at: q, dir: into(c, side), hole: false });+ }+ }+ break;+ }+ case "legScrew":+ case "plate": {+ for (const { c } of share(count, list)) {+ const leg = ext(c.a.box, c.n) >= ext(c.b.box, c.n) ? c.a : c.b;+ const top = otherOf(c, leg);+ const p = along(c, 1)[0];+ if (f.kind === "legScrew") one(leg, { at: p, dir: into(c, leg), mate: top.key });+ else one(top, { at: p, dir: into(c, top), hole: false });+ }+ break;+ }+ case "knob":+ case "handle": {+ const pool = to.size ? [...fresh, ...placed].filter((n) => to.has(n.id)) : fresh.length ? fresh : placed;+ const fronts = pool.filter((n) => n.box.max[2] >= ctx.hi[2] - 30);+ for (const n of (fronts.length ? fronts : pool).slice(0, count)) {+ const tall = ext(n.box, 1) > ext(n.box, 0) * 1.3;+ const x = tall ? (mid(n.box, 0) > ctx.center[0] ? n.box.min[0] + 40 : n.box.max[0] - 40) : mid(n.box, 0);+ const y = tall ? n.box.min[1] + ext(n.box, 1) * 0.55 : mid(n.box, 1);+ one(n, { at: [x, y, n.box.max[2]], dir: [0, 0, -1], hole: false, twist: f.kind === "handle" && tall ? Math.PI / 2 : 0 });+ }+ break;+ }+ case "hinge": {+ for (const { c, k } of share(count, list)) {+ const door = thinner(c);+ for (const q of along(c, Math.max(2, k), { inset: 0.12 }).slice(0, k)) one(door, { at: q, dir: into(c, door), twist: mid(door.box, 0) > ctx.center[0] ? Math.PI : 0 });+ }+ break;+ }+ case "glide": {+ // felt pads go under the corners of the whole footprint+ const floor = [...fresh, ...placed].filter((n, i, a) => n.box.min[1] < 3 && a.indexOf(n) === i);+ const corners: [number, number][] = [+ [ctx.lo[0], ctx.lo[2]],+ [ctx.hi[0], ctx.lo[2]],+ [ctx.hi[0], ctx.hi[2]],+ [ctx.lo[0], ctx.hi[2]],+ ];+ for (const [cx, cz] of corners.slice(0, count)) {+ let best: { n: Node; p: Vec3; d: number } | null = null;+ for (const n of floor) {+ const ix = Math.min(25, ext(n.box, 0) / 4), iz = Math.min(25, ext(n.box, 2) / 4);+ const p: Vec3 = [Math.min(n.box.max[0] - ix, Math.max(n.box.min[0] + ix, cx)), 0, Math.min(n.box.max[2] - iz, Math.max(n.box.min[2] + iz, cz))];+ const d = Math.hypot(p[0] - cx, p[2] - cz);+ if (!best || d < best.d) best = { n, p, d };+ }+ if (best) one(best.n, { at: best.p, dir: [0, 1, 0], hole: false });+ }+ break;+ }+ case "bracket": {+ const top = [...placed, ...fresh].reduce<Node | null>((a, n) => (!a || n.box.max[1] > a.box.max[1] ? n : a), null);+ if (top) {+ const n = Math.min(count, ext(top.box, 0) > 1000 ? 2 : 1);+ for (let i = 0; i < n; i++) {+ const x = n === 1 ? mid(top.box, 0) : top.box.min[0] + (ext(top.box, 0) * (i + 1)) / 3;+ one(top, { at: [x, top.box.max[1], top.box.min[2] + 16], dir: [0, -1, 0], travel: 60 });+ }+ }+ break;+ }+ default: {+ // screws, bolts and nails go through the thinner part into the other one+ const groups: Group[] = [];+ for (const { c, k } of share(count, list)) {+ const through = thinner(c);+ const other = otherOf(c, through);+ const dir = into(c, other);+ const face = dir[c.n] > 0 ? through.box.min[c.n] : through.box.max[c.n];+ const g: Group = { def: defFor(f, ext(through.box, c.n)), fits: [] };+ const sl = longAxis(c);+ for (const p of along(c, k, { inset: 0.14 })) {+ const q: Vec3 = [...p];+ q[c.n] = face;+ g.fits.push({ on: through.key, host: through, slide: sl, at: q, dir, mate: other.key, hole: f.kind === "nail" ? false : undefined });+ }+ groups.push(g);+ }+ return groups;+ }+ }+ return fits.length ? [{ def: defFor(f), fits }] : [];+}++/** Emit fittings, nudging any that would sit on top of one placed earlier. */+function emit(b: PlanBuilder, groups: Group[], used: Vec3[]) {+ const total = groups.reduce((s, g) => s + g.fits.length, 0);+ for (const g of groups) {+ const list: FitOpts[] = g.fits.map(({ host: _host, slide, ...o }) => {+ void _host;+ const at: Vec3 = [...o.at];+ const free = (p: Vec3) => used.every((u) => Math.hypot(u[0] - p[0], u[1] - p[1], u[2] - p[2]) > 22);+ if (!free(at)) {+ const axis = slide !== undefined ? [slide] : [0, 1, 2].filter((k) => !o.dir[k]);+ search: for (const step of [36, -36, 72, -72]) {+ for (const k of axis) {+ const p: Vec3 = [...at];+ p[k] += step;+ if (free(p)) {+ at[0] = p[0];+ at[1] = p[1];+ at[2] = p[2];+ break search;+ }+ }+ }+ }+ used.push(at);+ return { ...o, at };+ });+ b.fits(g.def, list, Math.min(0.07, 2.4 / Math.max(1, total)));+ }+}++/** Every part gets added exactly once, in order, and steps stay short enough to follow. */+function normalizeSteps(steps: CustomStep[], parts: CustomPart[]): CustomStep[] {+ const seen = new Set<string>();+ const ids = new Set(parts.map((p) => p.id));+ const out: CustomStep[] = steps.slice(0, 40).map((s) => {+ const add = (s.add ?? []).filter((id) => ids.has(id) && !seen.has(id));+ add.forEach((id) => seen.add(id));+ return { ...s, add };+ });+ const missing = parts.filter((p) => !seen.has(p.id)).map((p) => p.id);+ if (missing.length) {+ const last = [...out].reverse().find((s) => s.add && s.add.length);+ if (last && missing.length <= 2) last.add = [...(last.add ?? []), ...missing];+ else out.push({ title: "Fit the remaining parts", detail: "Check each one against the drawing before you fix it.", add: missing });+ }+ if (!out.length) out.push({ title: "Put it together", add: parts.map((p) => p.id) });+ return out;+}diff --git a/src/lib/plan/drawers.ts b/src/lib/plan/drawers.tsnew file mode 100644index 0000000..a8fc685--- /dev/null+++ b/src/lib/plan/drawers.ts@@ -0,0 +1,273 @@+import type { DrawersParams, ProductSpec } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { FrameKit } from "./frame";+import { clamp } from "./math";++export function defaultsDrawers(s: ProductSpec): DrawersParams {+ const p = s.drawers ?? {};+ return {+ cols: p.cols === 2 ? 2 : 1,+ rows: clamp(Math.round(p.rows ?? 3), 1, 6),+ knobs: p.knobs ?? "none",+ plinth: p.plinth ?? false,+ thickness: clamp(p.thickness ?? 16, 12, 24),+ };+}++export function buildDrawers(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsDrawers(s);+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const t = p.thickness;+ const base = p.plinth ? 70 : 0;+ const f = new FrameKit(b, { W, H, D, t, base, plinth: p.plinth, fixed: [], back: true, pinRows: false, lying: false });+ const { cols, rows } = p;++ // divider for two columns+ const innerH = H - 2 * t - base;+ let divider: string | undefined;+ if (cols === 2) {+ const dT = b.part("Middle panel", [t, innerH, D - 4]);+ divider = b.place(dT, [0, base + t + innerH / 2, -2]);+ }+ const colW = cols === 2 ? (W - 3 * t) / 2 : W - 2 * t;+ const colX = (c: number) => (cols === 2 ? (c === 0 ? -1 : 1) * (t / 2 + colW / 2) : 0);+ const slotH = innerH / rows;+ const runLen = Math.round((D - 60) / 10) * 10;+ const runner = { kind: "runner" as const, len: runLen, dia: 20 };++ // drawer geometry+ const fw = colW - 4, fh = slotH - 4;+ const bw = colW - 26; // box width between runners+ const sh = Math.min(fh - 46, 170);+ const dd = D - t - 50;+ const frT = b.part("Drawer front", [fw, fh, t]);+ const dsT = b.part("Drawer side", [12, sh, dd]);+ const dbT = b.part("Drawer back", [bw - 24, sh - 22, 12]);+ const dbtT = b.part("Drawer bottom", [bw - 10, 3, dd - 8], { material: "fiber" });++ interface Drawer {+ front: string;+ sides: [string, string];+ back: string;+ bottom: string;+ x: number;+ ys: number;+ }+ const drawers: Drawer[] = [];+ for (let c = 0; c < cols; c++)+ for (let r = rows - 1; r >= 0; r--) {+ const ys = base + t + r * slotH;+ const x = colX(c);+ const zBack = D / 2 - t - dd;+ const sy = ys + 24 + sh / 2;+ drawers.push({+ x,+ ys,+ front: b.place(frT, [x, ys + slotH / 2, D / 2 - t / 2]),+ sides: [b.place(dsT, [x - bw / 2 + 6, sy, D / 2 - t - dd / 2]), b.place(dsT, [x + bw / 2 - 6, sy, D / 2 - t - dd / 2])],+ back: b.place(dbT, [x, ys + 24 + 22 + (sh - 22) / 2, zBack + 6]),+ bottom: b.place(dbtT, [x, ys + 24 + 9, D / 2 - t - dd / 2 - 2]),+ });+ }+ // top row first reads naturally, but build the bottom one first so later drawers are hidden by it+ drawers.sort((a, b2) => a.ys - b2.ys || a.x - b2.x);++ f.prepSides();++ // runners on the sides while they lie flat+ b.step(+ {+ title: "Screw the runners onto the sides",+ detail: "The open end of each runner points to the front.",+ tools: ["screwdriver"],+ scene: "prep",+ kind: "runners",+ warnings: ["face"],+ },+ () => {+ const list: FitOpts[] = [];+ const screws: FitOpts[] = [];+ f.sides.forEach((side, i) => {+ const xi = i === 0 ? -W / 2 + t : W / 2 - t;+ const into: [number, number, number] = [i === 0 ? -1 : 1, 0, 0];+ for (let r = 0; r < rows; r++) {+ const y = base + t + r * slotH + 14;+ list.push({ on: side, at: [xi, y, D / 2 - t - runLen / 2 - 8], dir: into, hole: false });+ for (const dz of [-runLen / 2 + 30, runLen / 2 - 30])+ screws.push({ on: side, at: [xi + (i === 0 ? 12 : -12), y, D / 2 - t - runLen / 2 - 8 + dz], dir: into, hole: false });+ }+ });+ b.fits(runner, list, 0.12);+ b.then(0.1);+ b.fits(HW.screwS, screws, 0.04);+ },+ );++ f.join();+ if (divider) {+ b.step(+ {+ title: "Slide in the middle panel",+ detail: "Its runners face both columns.",+ tools: ["screwdriver"],+ kind: "join",+ },+ () => {+ b.add(divider!, [0, 0, 420]);+ b.then(0.1);+ const list: FitOpts[] = [];+ for (const sgn of [-1, 1])+ for (let r = 0; r < rows; r++) {+ const y = base + t + r * slotH + 14;+ list.push({ on: divider!, at: [sgn * (t / 2), y, D / 2 - t - runLen / 2 - 8], dir: [-sgn, 0, 0], hole: false });+ }+ b.fits(runner, list, 0.08);+ b.then(0.1);+ const sc: FitOpts[] = [];+ for (const y of [base + t, H - t])+ for (const z of [-D / 4, D / 4]) sc.push({ on: divider!, at: [0, y === base + t ? base : H, z], dir: [0, y === base + t ? 1 : -1, 0], hole: false });+ b.fits(HW.screwM, sc, 0.08);+ },+ );+ }+ f.otherSide();+ f.cams();+ f.plinthStep();+ f.backSteps();+ f.standUp();++ // build the first drawer in its own scene, front face down+ const n = drawers.length;+ const d0 = drawers[0];+ const c0: [number, number, number] = [d0.x, d0.ys + slotH / 2, D / 2 - t - dd / 2];+ const rel = (k: string) => {+ const it = b.partItem(k);+ return [it.final.pos[0] - c0[0], it.final.pos[1] - c0[1], it.final.pos[2] - c0[2]] as [number, number, number];+ };+ const rep = n > 1 ? n : undefined;+ b.step(+ {+ title: "Push the dowels into the drawer front",+ detail: "Lay the front face down on something soft.",+ tools: ["hammer"],+ scene: "drawer",+ pose: "-z",+ repeat: rep,+ kind: "dowels",+ warnings: ["floor"],+ },+ () => {+ b.stage(d0.front, rel(d0.front), [0, 0, 0], [0, 0, -160]);+ b.then(0.1);+ const list: FitOpts[] = [];+ for (const sd of d0.sides) {+ const x = b.partItem(sd).final.pos[0];+ const sy = b.partItem(sd).final.pos[1];+ for (const dy of [-sh / 4, sh / 4]) list.push({ on: d0.front, at: [x, sy + dy, D / 2 - t], dir: [0, 0, 1], mate: sd });+ }+ b.fits(HW.dowel, list, 0.08);+ },+ );+ b.step(+ {+ title: "Attach the drawer sides",+ detail: "Grooves face inwards and down, ready for the bottom.",+ scene: "drawer",+ pose: "-z",+ repeat: rep,+ kind: "drawer",+ warnings: ["face"],+ },+ () => {+ b.stagger(0.25);+ for (const sd of d0.sides) b.stage(sd, rel(sd), [0, 0, 0], [0, 0, -300]);+ },+ );+ b.step(+ {+ title: "Slide in the drawer bottom",+ detail: "Smooth side up. It runs along the grooves until it stops.",+ scene: "drawer",+ pose: "-z",+ repeat: rep,+ kind: "drawer",+ },+ () => b.stage(d0.bottom, rel(d0.bottom), [0, 0, 0], [0, 0, -420]),+ );+ const backScrews = (d: Drawer): FitOpts[] => {+ const by = b.partItem(d.back).final.pos[1];+ const bz = b.partItem(d.back).final.pos[2];+ const out: FitOpts[] = [];+ d.sides.forEach((sd, i) => {+ const xo = b.partItem(sd).final.pos[0] + (i === 0 ? -6 : 6);+ for (const dy of [-(sh - 22) / 4, (sh - 22) / 4]) out.push({ on: sd, at: [xo, by + dy, bz], dir: [i === 0 ? 1 : -1, 0, 0] });+ });+ return out;+ };+ b.step(+ {+ title: "Screw on the drawer back",+ detail: "Check the bottom sits in the back's groove before you tighten.",+ tools: ["screwdriver"],+ scene: "drawer",+ pose: "-z",+ repeat: rep,+ kind: "screws",+ },+ () => {+ b.stage(d0.back, rel(d0.back), [0, 0, 0], [0, 0, -260]);+ b.then(0.15);+ b.fits(HW.screwM, backScrews(d0), 0.12);+ },+ );++ // insert all drawers+ b.step(+ {+ title: n > 1 ? `Slide in all ${n} drawers` : "Slide in the drawer",+ detail: "Rest the back on the runners, then push until it clicks closed.",+ kind: "drawer",+ },+ () => {+ for (const [i, d] of drawers.entries()) {+ b.stagger(0);+ for (const k of [d.front, d.sides[0], d.sides[1], d.back, d.bottom]) b.add(k, [0, 0, 520]);+ if (i > 0) {+ for (const sd of d.sides) {+ const x = b.partItem(sd).final.pos[0];+ const sy = b.partItem(sd).final.pos[1];+ for (const dy of [-sh / 4, sh / 4]) b.preset(HW.dowel, { on: d.front, at: [x, sy + dy, D / 2 - t], dir: [0, 0, 1], mate: sd });+ }+ for (const o of backScrews(d)) b.preset(HW.screwM, o);+ }+ b.wait(0.22);+ }+ },+ );+ b.steps[b.steps.length - 1].quiet = true;++ if (p.knobs !== "none") {+ const def = p.knobs === "bar" ? HW.handle : HW.knob;+ b.step(+ {+ title: p.knobs === "bar" ? "Screw on the handles" : "Screw on the knobs",+ detail: "Screw from inside the drawer. Snug is enough.",+ tools: ["screwdriver"],+ kind: "screws",+ },+ () => {+ const list: FitOpts[] = drawers.map((d) => ({+ on: d.front,+ at: [d.x, b.partItem(d.front).final.pos[1] + (fh > 220 ? fh * 0.22 : 0), D / 2],+ dir: [0, 0, -1],+ hole: false,+ }));+ b.fits(def, list, 0.1);+ },+ );+ }++ f.anchor(f.top, H);+ const last = b.steps[b.steps.length - 1];+ last.detail = "Chests of drawers can tip over if they're not fixed. Wall screws aren't included: pick ones made for your wall.";+}diff --git a/src/lib/plan/frame.ts b/src/lib/plan/frame.tsnew file mode 100644index 0000000..50aa45c--- /dev/null+++ b/src/lib/plan/frame.ts@@ -0,0 +1,371 @@+import type { Pose, ToolId, Vec3 } from "../types";+import { HW, PlanBuilder } from "./builder";++/**+ * Shared carcass used by bookcases, chests and wardrobes:+ * two full-height sides with bolts and dowels, horizontal panels with cam locks between them,+ * optional plinth and a nailed fibreboard back.+ */+export interface FrameOpts {+ W: number;+ H: number;+ D: number;+ t: number;+ base: number; // underside of the bottom panel+ plinth: boolean;+ fixed: number[]; // y centres of extra fixed shelves+ back: boolean;+ pinRows: boolean;+ lying: boolean;+ names?: { side?: string; top?: string; bottom?: string; fixed?: string };+}++export class FrameKit {+ sides!: [string, string];+ top!: string;+ bottom!: string;+ fixed: string[] = [];+ plinth?: string;+ backPanel?: string;+ pose: Pose;+ innerW: number;+ joints: { key: string; y: number; camDir: 1 | -1; face: number }[] = [];+ pinYs: number[] = [];++ constructor(+ public b: PlanBuilder,+ public o: FrameOpts,+ ) {+ this.pose = o.lying ? "+z" : "+y";+ this.innerW = o.W - 2 * o.t;+ this.make();+ }++ get zb() {+ const { D } = this.o;+ return D >= 300 ? D / 2 - 50 : D / 2 - 36;+ }+ get zd() {+ const { D } = this.o;+ return Math.max(D / 2 - 110, 26);+ }++ private make() {+ const { b, o } = this;+ const { W, H, D, t, base } = o;+ const sideT = b.part(o.names?.side ?? "Side panel", [t, H, D]);+ const sx = W / 2 - t / 2;+ this.sides = [b.place(sideT, [-sx, H / 2, 0]), b.place(sideT, [sx, H / 2, 0], [0, Math.PI, 0])];++ const iw = W - 2 * t;+ const topT = b.part(o.names?.top ?? "Top panel", [iw, t, D]);+ this.top = b.place(topT, [0, H - t / 2, 0]);+ const botT = b.part(o.names?.bottom ?? "Bottom panel", [iw, t, D]);+ this.bottom = b.place(botT, [0, base + t / 2, 0]);+ this.joints.push({ key: this.top, y: H - t / 2, camDir: 1, face: H - t });+ this.joints.push({ key: this.bottom, y: base + t / 2, camDir: -1, face: base + t });+ if (o.fixed.length) {+ const fxT = b.part(o.names?.fixed ?? "Fixed shelf", [iw, t, D - 4]);+ for (const y of o.fixed) {+ const k = b.place(fxT, [0, y, -2]);+ this.fixed.push(k);+ this.joints.push({ key: k, y, camDir: 1, face: y - t / 2 });+ }+ }+ if (o.plinth && base > 0) {+ const plT = b.part("Plinth", [iw, base, t]);+ this.plinth = b.place(plT, [0, base / 2, D / 2 - t / 2 - 12]);+ }+ if (o.back) {+ const bh = H - 4;+ const bkT = b.part("Back panel", [W - 4, bh, 3], { material: "fiber" });+ this.backPanel = b.place(bkT, [0, H / 2, -D / 2 - 1.5]);+ }++ // shelf pin hole rows+ if (o.pinRows) {+ const y0 = base + t + 110;+ const y1 = H - t - 110;+ for (let y = y0; y <= y1; y += 64) {+ if (o.fixed.some((f) => Math.abs(f - y) < 50)) continue;+ this.pinYs.push(y);+ for (const [i, side] of this.sides.entries()) {+ const xi = i === 0 ? -W / 2 + t : W / 2 - t;+ const n: Vec3 = [i === 0 ? 1 : -1, 0, 0];+ for (const z of [D / 2 - 40, -D / 2 + 40]) b.hole(side, [xi, y, z], n, 2.5);+ }+ }+ }+ }++ /** Step: both sides laid flat, dowels and bolts in. */+ prepSides(extra?: () => void) {+ const { b, o } = this;+ const { W, D, t } = o;+ b.step(+ {+ title: "Fit the dowels and bolts into both sides",+ detail: "Tap the dowels in gently. Twist the bolts in by hand until they stop.",+ tools: ["hammer", "screwdriver"],+ scene: "prep",+ kind: "dowels",+ warnings: ["floor"],+ },+ () => {+ b.stagger(0.18);+ this.sides.forEach((s, i) => b.stage(s, [0, t / 2, (i === 0 ? -1 : 1) * (D / 2 + 70)], [0, 0, Math.PI / 2], [0, 120, 0]));+ b.then(0.2);+ const dowels: Parameters<PlanBuilder["fits"]>[1] = [];+ const bolts: Parameters<PlanBuilder["fits"]>[1] = [];+ this.sides.forEach((side, i) => {+ const xi = i === 0 ? -W / 2 + t : W / 2 - t;+ const into: Vec3 = [i === 0 ? -1 : 1, 0, 0];+ for (const j of this.joints) {+ for (const z of [-this.zd, this.zd]) dowels.push({ on: side, at: [xi, j.y, z], dir: into, mate: j.key });+ for (const z of [-this.zb, this.zb]) bolts.push({ on: side, at: [xi, j.y, z], dir: into, mate: j.key, mateHole: 4 });+ }+ if (this.plinth) dowels.push({ on: side, at: [xi, o.base / 2, D / 2 - t / 2 - 12], dir: into, mate: this.plinth });+ });+ b.fits(HW.dowel, dowels, 0.05);+ b.then(0.15);+ b.fits(HW.camScrew, bolts, 0.05);+ extra?.();+ },+ );+ }++ join(people: 1 | 2 = 1) {+ const { b, o } = this;+ b.step(+ {+ title: o.lying ? "Lay one side down and add the panels" : "Attach the panels to one side",+ detail: "The holes should face each other. Push each panel onto the dowels.",+ scene: "main",+ pose: this.pose,+ kind: "join",+ people,+ warnings: ["face"],+ },+ () => {+ b.add(this.sides[0], [-260, 0, 0]);+ b.then(0.1);+ b.stagger(0.22);+ for (const j of this.joints) b.add(j.key, [380, 0, 0]);+ },+ );+ }++ otherSide(people: 1 | 2 = 1) {+ const { b } = this;+ b.step(+ {+ title: "Add the other side",+ detail: "Line up the bolts with the holes, then press it on evenly.",+ pose: this.pose,+ kind: "join",+ people,+ },+ () => {+ b.add(this.sides[1], [420, 0, 0]);+ },+ );+ }++ cams() {+ const { b, o } = this;+ const { W, t } = o;+ b.step(+ {+ title: "Lock the cam locks",+ detail: "Drop each one in with the arrow pointing at the bolt, then turn clockwise until it bites.",+ tools: ["screwdriver"],+ pose: this.pose,+ kind: "cams",+ },+ () => {+ const list: Parameters<PlanBuilder["fits"]>[1] = [];+ for (const j of this.joints) {+ for (const x of [-W / 2 + t + 24, W / 2 - t - 24])+ for (const z of [-this.zb, this.zb]) list.push({ on: j.key, at: [x, j.face, z], dir: [0, j.camDir, 0] });+ }+ b.fits(HW.cam, list, 0.07);+ },+ );+ }++ plinthStep() {+ if (!this.plinth) return;+ const { b } = this;+ b.step(+ {+ title: "Fit the plinth",+ detail: "Press it onto the dowels at the front, below the bottom panel.",+ pose: this.pose,+ kind: "join",+ },+ () => b.add(this.plinth!, [0, 0, 320]),+ );+ }++ backSteps() {+ if (!this.backPanel) return;+ const { b, o } = this;+ const { W, H, D, t, base } = o;+ const big = H > 1100 || W > 1000;+ b.step(+ {+ title: "Turn it face down",+ detail: big ? "Lift it together and lay it on the box." : "Lay it on the flattened box so the front doesn't scratch.",+ pose: "-z",+ kind: "flip",+ people: big ? 2 : 1,+ warnings: big ? ["two", "floor"] : ["floor"],+ },+ () => {},+ );+ b.step(+ {+ title: "Check that it's square",+ detail: "Measure both diagonals. Push the corners gently until they match.",+ tools: ["tape"],+ pose: "-z",+ kind: "square",+ check: "square",+ warnings: ["square"],+ },+ () => {},+ );+ b.step(+ {+ title: "Nail on the back panel",+ detail: "Start at the corners, then work along the edges.",+ tools: ["hammer"],+ pose: "-z",+ kind: "nails",+ },+ () => {+ b.add(this.backPanel!, [0, 0, -340]);+ b.then(0.25);+ const z = -D / 2 - 3;+ const list: Parameters<PlanBuilder["fits"]>[1] = [];+ const pts = (a: number, c: number, n: number) => Array.from({ length: n }, (_, i) => a + ((c - a) * i) / Math.max(1, n - 1));+ // sides+ const ny = Math.max(3, Math.round(H / 170));+ for (const [i, s] of this.sides.entries()) {+ const x = (i === 0 ? -1 : 1) * (W / 2 - t / 2);+ for (const y of pts(base + 30, H - 30, ny)) list.push({ on: s, at: [x, y, z], dir: [0, 0, 1], hole: false });+ }+ const nx = Math.max(2, Math.round((W - 2 * t) / 180));+ for (const j of this.joints) {+ for (const x of pts(-W / 2 + t + 40, W / 2 - t - 40, nx)) list.push({ on: j.key, at: [x, j.y, z], dir: [0, 0, 1], hole: false });+ }+ // corners first+ list.sort((a, b2) => Math.abs(b2.at[0]) + Math.abs(b2.at[1] - H / 2) - (Math.abs(a.at[0]) + Math.abs(a.at[1] - H / 2)));+ b.fits(HW.nail, list, Math.min(0.05, 2.2 / list.length));+ },+ );+ }++ standUp() {+ const { b, o } = this;+ const big = o.H > 1000;+ b.step(+ {+ title: big ? "Stand it up together" : "Stand it up",+ detail: big ? "Lift from the top, keep the bottom on the floor, and walk it up." : "Turn it upright on a flat floor.",+ pose: "+y",+ kind: "standup",+ people: big ? 2 : 1,+ warnings: big ? ["two"] : [],+ },+ () => {},+ );+ }++ shelves(count: number) {+ if (count <= 0) return;+ const { b, o } = this;+ const { W, D, t } = o;+ const shT = b.part("Shelf", [W - 2 * t - 3, t, D - 26]);+ // choose evenly spaced pin rows+ const ys = this.pinYs;+ if (!ys.length) return;+ const slots: number[] = [];+ const gaps = this.gapsForShelves(count);+ for (const target of gaps) {+ let best = ys[0];+ for (const y of ys) if (Math.abs(y - target) < Math.abs(best - target)) best = y;+ if (!slots.includes(best)) slots.push(best);+ }+ const shelves = slots.map((y) => b.place(shT, [0, y + 3 + t / 2, 13 - 2]));+ b.step(+ {+ title: count > 1 ? "Add the shelf pins and shelves" : "Add the shelf pins and the shelf",+ detail: "Pick any height you like. Use the same hole on all four corners.",+ kind: "shelves",+ },+ () => {+ const pins: Parameters<PlanBuilder["fits"]>[1] = [];+ for (const y of slots)+ for (const [i, s] of this.sides.entries()) {+ const x = i === 0 ? -W / 2 + t : W / 2 - t;+ for (const z of [D / 2 - 40, -D / 2 + 40]) pins.push({ on: s, at: [x, y, z], dir: [i === 0 ? -1 : 1, 0, 0], hole: false });+ }+ b.fits(HW.pin, pins, 0.05);+ b.then(0.2);+ b.stagger(0.25);+ shelves.forEach((k) => b.add(k, [0, 0, 420]));+ },+ );+ return shelves;+ }++ private gapsForShelves(count: number) {+ const { H, t, base } = this.o;+ const bounds = [base + t, ...this.o.fixed, H - t].sort((a, b) => a - b);+ // distribute shelves across compartments by height+ const comps = bounds.slice(1).map((y, i) => ({ a: bounds[i], b: y, n: 0 }));+ for (let k = 0; k < count; k++) {+ comps.sort((x, y) => (y.b - y.a) / (y.n + 1) - (x.b - x.a) / (x.n + 1));+ comps[0].n++;+ }+ const out: number[] = [];+ for (const c of comps) for (let i = 1; i <= c.n; i++) out.push(c.a + ((c.b - c.a) * i) / (c.n + 1));+ return out.sort((a, b) => a - b);+ }++ anchor(top = this.top, ySurface = this.o.H, tools: ToolId[] = ["drill", "screwdriver", "pencil"]) {+ anchorStep(this.b, { W: this.o.W, D: this.o.D, top, y: ySurface, backZ: -this.o.D / 2 - (this.backPanel ? 3 : 0), tools });+ }+}++export function anchorStep(+ b: PlanBuilder,+ o: { W: number; D: number; top: string; y: number; backZ: number; tools?: ToolId[]; severe?: boolean },+) {+ const xs = o.W > 1000 ? [-o.W / 3, o.W / 3] : [0];+ b.step(+ {+ title: "Fix it to the wall",+ detail: o.severe+ ? "Furniture like this can tip over if it isn't fixed. Wall screws aren't included: pick ones made for your wall."+ : "Wall screws aren't included. Pick ones made for your wall.",+ tools: o.tools ?? ["drill", "screwdriver", "pencil"],+ kind: "anchor",+ wall: true,+ warnings: ["wall", "tip"],+ },+ () => {+ b.stagger(0.2);+ for (const x of xs) b.fit(HW.bracket, { on: o.top, at: [x, o.y, o.backZ + 16], dir: [0, -1, 0], travel: 60 });+ b.then(0.1);+ const sc: Parameters<PlanBuilder["fits"]>[1] = [];+ for (const x of xs) for (const dx of [-11, 11]) sc.push({ on: o.top, at: [x + dx, o.y + 2, o.backZ + 22], dir: [0, -1, 0], hole: false });+ b.fits(HW.screwS, sc, 0.1);+ b.then(0.1);+ for (const x of xs) b.fit(HW.plug, { at: [x, o.y + 26, o.backZ], dir: [0, 0, -1] });+ b.then(0.05);+ for (const x of xs) b.fit(HW.wallScrew, { at: [x, o.y + 26, o.backZ + 2], dir: [0, 0, -1] });+ },+ );+}diff --git a/src/lib/plan/index.ts b/src/lib/plan/index.tsnew file mode 100644index 0000000..1f95c49--- /dev/null+++ b/src/lib/plan/index.ts@@ -0,0 +1,48 @@+import type { Plan, ProductSpec } from "../types";+import { PlanBuilder } from "./builder";+import { buildShelf } from "./shelf";+import { buildDrawers } from "./drawers";+import { buildTable } from "./table";+import { buildBed } from "./bed";+import { buildCabinet } from "./cabinet";+import { buildSeat } from "./seat";+import { buildSofa } from "./sofa";+import { buildCustom } from "./custom";++const cache = new Map<string, Plan>();++export function buildPlan(spec: ProductSpec): Plan {+ const key = JSON.stringify(spec);+ const hit = cache.get(key);+ if (hit) return hit;+ const b = new PlanBuilder(spec);+ switch (spec.archetype) {+ case "shelf":+ buildShelf(b, spec);+ break;+ case "drawers":+ buildDrawers(b, spec);+ break;+ case "table":+ buildTable(b, spec);+ break;+ case "bed":+ buildBed(b, spec);+ break;+ case "cabinet":+ buildCabinet(b, spec);+ break;+ case "seat":+ buildSeat(b, spec);+ break;+ case "sofa":+ buildSofa(b, spec);+ break;+ case "custom":+ buildCustom(b, spec);+ break;+ }+ const plan = b.build();+ cache.set(key, plan);+ return plan;+}diff --git a/src/lib/plan/lineup.ts b/src/lib/plan/lineup.tsnew file mode 100644index 0000000..7c43677--- /dev/null+++ b/src/lib/plan/lineup.ts@@ -0,0 +1,51 @@+import type { HwType, Item, PartType, Plan, Vec3 } from "../types";++export interface Lineup {+ plan: Plan;+ /** x centre of each product along the row, in mm */+ centers: number[];+ /** left and right ends of the row */+ span: [number, number];+}++/** Stand several finished products side by side in one scene, so they share a camera and a scale. */+export function lineup(plans: Plan[], gap = 420): Lineup {+ const parts: PartType[] = [];+ const hardware: HwType[] = [];+ const items: Item[] = [];+ const centers: number[] = [];+ const widths = plans.map((p) => Math.max(...p.items.filter((i) => i.kind === "part").map((i) => Math.abs((i as Extract<Item, { kind: "part" }>).final.pos[0])), 0) * 2 + 40);+ const total = widths.reduce((a, b) => a + b, 0) + gap * Math.max(0, plans.length - 1);+ let x = -total / 2;+ plans.forEach((p, i) => {+ const w = Math.max(widths[i], p.spec.size.w * 10);+ const cx = x + w / 2;+ const pre = `L${i}`;+ const wallSteps = new Set(p.steps.filter((s) => s.wall).map((s) => s.n));+ for (const t of p.parts) parts.push({ ...t, id: pre + t.id });+ for (const h of p.hardware) hardware.push({ ...h, id: pre + h.id });+ for (const it of p.items) {+ if (it.kind === "part") {+ const pos: Vec3 = [it.final.pos[0] + cx, it.final.pos[1], it.final.pos[2]];+ items.push({ ...it, key: pre + it.key, ref: pre + it.ref, final: { pos, rot: it.final.rot }, states: [{ step: 0, scene: "main", pos, rot: it.final.rot, delay: 0 }] });+ } else if (it.parent && !wallSteps.has(it.step)) {+ items.push({ ...it, key: pre + it.key, ref: pre + it.ref, parent: pre + it.parent, step: 0 });+ }+ }+ centers.push(cx);+ x += w + gap;+ });+ const first = plans[0];+ return {+ plan: {+ spec: { ...first.spec, name: "Workshop", variant: "" },+ parts,+ hardware,+ items,+ steps: [{ n: 0, title: "", tools: [], people: 1, scene: "main", pose: "+y", warnings: [], kind: "general", minutes: 1 }],+ tools: [],+ },+ centers,+ span: [-total / 2, total / 2],+ };+}diff --git a/src/lib/plan/math.ts b/src/lib/plan/math.tsnew file mode 100644index 0000000..46d5186--- /dev/null+++ b/src/lib/plan/math.ts@@ -0,0 +1,46 @@+import type { Pose, Vec3 } from "../types";++export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+export const mul = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];+export const neg = (a: Vec3): Vec3 => [-a[0], -a[1], -a[2]];++function rx(v: Vec3, a: number): Vec3 {+ const c = Math.cos(a), s = Math.sin(a);+ return [v[0], v[1] * c - v[2] * s, v[1] * s + v[2] * c];+}+function ry(v: Vec3, a: number): Vec3 {+ const c = Math.cos(a), s = Math.sin(a);+ return [v[0] * c + v[2] * s, v[1], -v[0] * s + v[2] * c];+}+function rz(v: Vec3, a: number): Vec3 {+ const c = Math.cos(a), s = Math.sin(a);+ return [v[0] * c - v[1] * s, v[0] * s + v[1] * c, v[2]];+}++/** Rotate by an XYZ Euler (same convention as three.js): R = Rx * Ry * Rz */+export function rotate(v: Vec3, e: Vec3): Vec3 {+ return rx(ry(rz(v, e[2]), e[1]), e[0]);+}+export function unrotate(v: Vec3, e: Vec3): Vec3 {+ return rz(ry(rx(v, -e[0]), -e[1]), -e[2]);+}++export function toLocal(p: Vec3, pos: Vec3, rot: Vec3): Vec3 {+ return unrotate(sub(p, pos), rot);+}+export function toWorld(p: Vec3, pos: Vec3, rot: Vec3): Vec3 {+ return add(rotate(p, rot), pos);+}++export const POSE_EULER: Record<Pose, Vec3> = {+ "+y": [0, 0, 0],+ "-y": [Math.PI, 0, 0],+ "+z": [-Math.PI / 2, 0, 0],+ "-z": [Math.PI / 2, 0, 0],+ "+x": [0, 0, Math.PI / 2],+ "-x": [0, 0, -Math.PI / 2],+};++export const round = (n: number) => Math.round(n * 10) / 10;+export const clamp = (n: number, a: number, b: number) => Math.min(b, Math.max(a, n));diff --git a/src/lib/plan/seat.ts b/src/lib/plan/seat.tsnew file mode 100644index 0000000..40c045c--- /dev/null+++ b/src/lib/plan/seat.ts@@ -0,0 +1,223 @@+import type { ProductSpec, SeatParams, Vec3 } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { clamp, rotate } from "./math";++export function defaultsSeat(s: ProductSpec): SeatParams {+ const p = s.seat ?? {};+ const kind = p.kind ?? (s.size.h > 70 ? "chair" : "stool");+ return {+ kind,+ seat: p.seat ?? (kind === "stool" ? "round" : "square"),+ seatH: clamp(p.seatH ?? (kind === "chair" ? 45 : s.size.h), 25, 85),+ backH: clamp(p.backH ?? s.size.h, 60, 120),+ stretchers: p.stretchers ?? false,+ splay: p.splay ?? kind === "stool",+ };+}++export function buildSeat(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsSeat(s);+ if (p.kind === "chair") return chair(b, s, p);+ return stool(b, s, p);+}++function stool(b: PlanBuilder, s: ProductSpec, p: SeatParams) {+ const W = s.size.w * 10, D = s.size.d * 10;+ const H = p.seatH * 10;+ const st = 28;+ const round = p.seat === "round";+ const seatT = b.part("Seat", round ? [W, st, W] : [W, st, D], { shape: round ? "cyl" : "box", material: "wood" });+ const seat = b.place(seatT, [0, H - st / 2, 0]);+ const ld = 34;+ const a = p.splay ? 0.11 : 0;+ const Lh = (H - st) / Math.cos(a) + 4;+ const legT = b.part("Leg", [ld, Lh, ld], { shape: "cyl", material: "wood" });+ const r = round ? W / 2 - ld * 0.9 - 10 : 0;+ const corners: [number, number][] = round+ ? [0, 1, 2, 3].map((i) => [Math.cos(Math.PI / 4 + (i * Math.PI) / 2), Math.sin(Math.PI / 4 + (i * Math.PI) / 2)])+ : [+ [-1, 1],+ [1, 1],+ [1, -1],+ [-1, -1],+ ];+ const legs = corners.map(([cx, cz]) => {+ const tx = round ? cx * r : cx * (W / 2 - ld / 2 - 20);+ const tz = round ? cz * r : cz * (D / 2 - ld / 2 - 20);+ const len = Math.hypot(cx, cz) || 1;+ const rot: Vec3 = [-(cz / len) * a, 0, (cx / len) * a];+ const half = rotate([0, -Lh / 2, 0], rot);+ const topPt: Vec3 = [tx, H - st, tz];+ return { key: b.place(legT, [topPt[0] + half[0], topPt[1] + half[1], topPt[2] + half[2]], rot), rot, topPt };+ });++ b.step(+ {+ title: "Lay the seat upside down",+ detail: "On the flattened box, so it doesn't scratch.",+ pose: "-y",+ kind: "general",+ warnings: ["floor"],+ },+ () => b.add(seat, [0, 200, 0]),+ );++ b.step(+ {+ title: "Screw a bolt into each leg",+ detail: "By hand, until half of it is showing.",+ scene: "legs",+ kind: "legs",+ },+ () => {+ b.stagger(0.15);+ legs.forEach((l, i) => b.stage(l.key, [(i - 1.5) * 150, Lh / 2, 0], [0, 0, 0], [0, 200, 0]));+ b.then(0.1);+ b.fits(+ { ...HW.legScrew, len: 2 * (st - 8) },+ legs.map((l) => ({ on: l.key, at: l.topPt, dir: rotate([0, -1, 0], l.rot), mate: seat })),+ 0.12,+ );+ },+ );++ b.step(+ {+ title: "Screw in the legs",+ detail: "Clockwise, by hand. Stop when each leg feels firm.",+ pose: "-y",+ kind: "legs",+ warnings: ["hand"],+ },+ () => {+ b.stagger(0.3);+ legs.forEach((l) => b.add(l.key, rotate([0, -300, 0], l.rot), { spin: 2 }));+ },+ );++ if (p.stretchers) {+ const ry = H * 0.35;+ const pts = legs.map((l) => {+ const dy = H - st - ry;+ const v = rotate([0, -1, 0], l.rot);+ const k = dy / -v[1];+ return [l.topPt[0] + v[0] * k, ry, l.topPt[2] + v[2] * k] as Vec3;+ });+ const span = Math.hypot(pts[1][0] - pts[0][0], pts[1][2] - pts[0][2]) - ld;+ const strT = b.part("Rail", [18, span, 18], { shape: "cyl", material: "wood" });+ const rails = pts.map((pt, i) => {+ const q = pts[(i + 1) % 4];+ const mid: Vec3 = [(pt[0] + q[0]) / 2, ry, (pt[2] + q[2]) / 2];+ const ang = Math.atan2(q[2] - pt[2], q[0] - pt[0]);+ return b.place(strT, mid, [0, -ang, Math.PI / 2]);+ });+ b.step(+ {+ title: "Fit the rails between the legs",+ detail: "Ease the legs apart a little to slot each one in.",+ pose: "-y",+ kind: "join",+ },+ () => {+ b.stagger(0.2);+ rails.forEach((rk) => {+ const pos = b.partItem(rk).final.pos;+ const n = Math.hypot(pos[0], pos[2]) || 1;+ b.add(rk, [(pos[0] / n) * 200, 0, (pos[2] / n) * 200]);+ });+ },+ );+ }++ b.step(+ {+ title: "Turn it over",+ detail: "Sit carefully the first time and check nothing wobbles.",+ pose: "+y",+ kind: "flip",+ },+ () => {},+ );+}++function chair(b: PlanBuilder, s: ProductSpec, p: SeatParams) {+ const W = s.size.w * 10, D = s.size.d * 10;+ const H = p.seatH * 10, BH = p.backH * 10;+ const ls = 38, st = 28;+ const sx = W / 2 - ls / 2, sz = D / 2 - ls / 2;+ const backT = b.part("Back leg", [ls, BH, ls], { material: "wood" });+ const frontT = b.part("Front leg", [ls, H - st, ls], { material: "wood" });+ const restT = b.part("Backrest", [W - 2 * ls, 130, 20], { material: "wood" });+ const seatT = b.part("Seat", [W - 2 * ls, st, D - ls], { material: "wood" });+ const bl = [b.place(backT, [-sx, BH / 2, -sz]), b.place(backT, [sx, BH / 2, -sz])];+ const fl = [b.place(frontT, [-sx, (H - st) / 2, sz]), b.place(frontT, [sx, (H - st) / 2, sz])];+ const rest = b.place(restT, [0, BH - 110, -sz]);+ const seat = b.place(seatT, [0, H - st / 2, ls / 2]);+ const lowT = b.part("Front rail", [W - 2 * ls, 50, 20], { material: "wood" });+ const low = b.place(lowT, [0, H - st - 25, sz]);+ const sideT = b.part("Side rail", [20, 50, D - 2 * ls], { material: "wood" });+ const sides = [b.place(sideT, [-sx, H - st - 25, 0]), b.place(sideT, [sx, H - st - 25, 0])];++ b.step(+ {+ title: "Join the backrest to the back legs",+ detail: "Don't tighten fully yet.",+ tools: ["allen"],+ scene: "back",+ pose: "+z",+ kind: "bolts",+ warnings: ["loose"],+ },+ () => {+ b.stagger(0.2);+ bl.forEach((k, i) => b.stage(k, b.partItem(k).final.pos, [0, 0, 0], [i === 0 ? -200 : 200, 0, 0]));+ b.then(0.05);+ b.stage(rest, b.partItem(rest).final.pos, [0, 0, 0], [0, 0, 260]);+ b.then(0.1);+ const bolts: FitOpts[] = [];+ for (const [i, k] of bl.entries()) for (const dy of [-30, 30]) bolts.push({ on: k, at: [(i === 0 ? -1 : 1) * (W / 2), BH - 110 + dy, -sz], dir: [i === 0 ? 1 : -1, 0, 0], mate: rest });+ b.fits(HW.boltL, bolts, 0.1);+ },+ );++ b.step(+ {+ title: "Add the front legs and rails",+ detail: "Rails slot into the legs. Bolt them loosely.",+ tools: ["allen"],+ kind: "bolts",+ warnings: ["loose"],+ },+ () => {+ b.stagger(0);+ [...bl, rest].forEach((k) => b.add(k, [0, 0, -200]));+ b.then(0.1);+ b.stagger(0.2);+ sides.forEach((k, i) => b.add(k, [i === 0 ? -220 : 220, 0, 0]));+ b.then(0.05);+ b.stagger(0);+ [...fl, low].forEach((k) => b.add(k, [0, 0, 300]));+ b.then(0.1);+ const bolts: FitOpts[] = [];+ for (const [i, k] of fl.entries()) bolts.push({ on: k, at: [(i === 0 ? -1 : 1) * (W / 2), H - st - 25, sz], dir: [i === 0 ? 1 : -1, 0, 0], mate: sides[i] });+ for (const [i, k] of bl.entries()) bolts.push({ on: k, at: [(i === 0 ? -1 : 1) * (W / 2), H - st - 25, -sz], dir: [i === 0 ? 1 : -1, 0, 0], mate: sides[i] });+ b.fits(HW.boltL, bolts, 0.08);+ },+ );++ b.step(+ {+ title: "Lay the seat in and screw it down",+ detail: "Then tighten every bolt firmly, and again after a week.",+ tools: ["allen", "screwdriver"],+ kind: "screws",+ },+ () => {+ b.add(seat, [0, 300, 0]);+ b.then(0.1);+ const sc: FitOpts[] = [];+ for (const x of [-(W / 2 - ls - 30), W / 2 - ls - 30]) for (const z of [-(D / 2 - ls - 40), D / 2 - ls - 50]) sc.push({ on: seat, at: [x, H, z + ls / 2], dir: [0, -1, 0], hole: false });+ b.fits(HW.screwL, sc, 0.1);+ },+ );+}diff --git a/src/lib/plan/shelf.ts b/src/lib/plan/shelf.tsnew file mode 100644index 0000000..5854da8--- /dev/null+++ b/src/lib/plan/shelf.ts@@ -0,0 +1,227 @@+import type { ProductSpec, ShelfParams, Vec3 } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { FrameKit, anchorStep } from "./frame";+import { clamp } from "./math";++export function defaultsShelf(s: ProductSpec): ShelfParams {+ const p = s.shelf ?? {};+ const grid = p.style === "grid";+ return {+ style: grid ? "grid" : "bookcase",+ cols: clamp(Math.round(p.cols ?? (grid ? 2 : 1)), 1, 5),+ rows: clamp(Math.round(p.rows ?? (grid ? 2 : 1)), 1, 5),+ shelves: clamp(Math.round(p.shelves ?? Math.max(1, Math.round(s.size.h / 45) - 1)), 0, 6),+ fixedShelf: p.fixedShelf ?? s.size.h > 150,+ back: p.back ?? !grid,+ plinth: p.plinth ?? (!grid && s.size.h > 150),+ outer: clamp(p.outer ?? (grid ? 40 : 16), 12, 50),+ inner: clamp(p.inner ?? 16, 12, 30),+ };+}++export function buildShelf(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsShelf(s);+ if (p.style === "grid") return grid(b, s, p);+ return bookcase(b, s, p);+}++function bookcase(b: PlanBuilder, s: ProductSpec, p: ShelfParams) {+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const t = p.outer;+ const base = p.plinth ? 60 : 0;+ const lying = H > 1100;+ const f = new FrameKit(b, {+ W, H, D, t, base,+ plinth: p.plinth,+ fixed: p.fixedShelf ? [Math.round((base + H) / 2 / 32) * 32] : [],+ back: p.back,+ pinRows: p.shelves > 0,+ lying,+ });+ const two: 1 | 2 = H > 1500 ? 2 : 1;+ f.prepSides();+ f.join(lying ? 1 : two);+ f.otherSide(lying ? 1 : two);+ f.cams();+ f.plinthStep();+ if (p.back) f.backSteps();+ if (p.back || lying) f.standUp();+ f.shelves(p.shelves);+ if (H >= 900) f.anchor();+}++/** Cube shelving: full-width top and bottom, sides between, an inner grid on dowels. Built upright from the bottom. */+function grid(b: PlanBuilder, s: ProductSpec, p: ShelfParams) {+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const T = p.outer, ti = p.inner;+ const { cols, rows } = p;+ const cellW = (W - 2 * T - (cols - 1) * ti) / cols;+ const cellH = (H - 2 * T - (rows - 1) * ti) / rows;+ const zb = D / 2 - 55;+ const zd = Math.max(D / 2 - 120, 30);+ const zi = Math.max(D / 2 - 90, 30);++ const tbT = b.part("Top and bottom", [W, T, D]);+ const bottom = b.place(tbT, [0, T / 2, 0]);+ const top = b.place(tbT, [0, H - T / 2, 0]);+ const sideT = b.part("Side panel", [T, H - 2 * T, D]);+ const sides = [b.place(sideT, [-(W / 2 - T / 2), H / 2, 0]), b.place(sideT, [W / 2 - T / 2, H / 2, 0], [0, Math.PI, 0])];+ const longT = rows > 1 ? b.part("Long shelf", [W - 2 * T, ti, D]) : "";+ const divT = cols > 1 ? b.part("Divider", [ti, cellH, D]) : "";++ const rowY0 = (r: number) => T + r * (cellH + ti); // bottom of row r+ const longs = Array.from({ length: rows - 1 }, (_, r) => b.place(longT, [0, rowY0(r) + cellH + ti / 2, 0]));+ const divX = (c: number) => -W / 2 + T + (c + 1) * cellW + c * ti + ti / 2;+ const divs = Array.from({ length: rows }, (_, r) =>+ Array.from({ length: cols - 1 }, (_, c) => b.place(divT, [divX(c), rowY0(r) + cellH / 2, 0])),+ );+ const below = (r: number) => (r === 0 ? bottom : longs[r - 1]);+ const above = (r: number) => (r === rows - 1 ? top : longs[r]);+ const sx = W / 2 - T / 2;++ // 1. bottom+ b.step(+ {+ title: "Fit bolts and dowels into the bottom",+ detail: "Twist the bolts in by hand. Tap the dowels in halfway.",+ tools: ["screwdriver", "hammer"],+ kind: "dowels",+ warnings: ["floor"],+ },+ () => {+ b.add(bottom, [0, 160, 0]);+ b.then(0.15);+ const bolts: FitOpts[] = [];+ const dowels: FitOpts[] = [];+ for (const [i, x] of [-sx, sx].entries()) {+ for (const z of [-zb, zb]) bolts.push({ on: bottom, at: [x, T, z], dir: [0, -1, 0], mate: sides[i], mateHole: 4 });+ for (const z of [-zd, zd]) dowels.push({ on: bottom, at: [x, T, z], dir: [0, -1, 0], mate: sides[i] });+ }+ for (const d of divs[0]) for (const z of [-zi, zi]) dowels.push({ on: bottom, at: [b.partItem(d).final.pos[0], T, z], dir: [0, -1, 0], mate: d });+ b.fits(HW.camScrew, bolts, 0.08);+ b.then(0.1);+ b.fits(HW.dowel, dowels, 0.05);+ },+ );++ for (let r = 0; r < rows; r++) {+ if (cols > 1) {+ b.step(+ {+ title: r === 0 ? "Stand the dividers on the dowels" : "Add the next row of dividers",+ detail: "Then tap dowels into their top edges.",+ tools: ["hammer"],+ kind: "join",+ },+ () => {+ b.stagger(0.2);+ divs[r].forEach((d) => b.add(d, [0, 260, 0]));+ b.then(0.15);+ const list: FitOpts[] = [];+ for (const d of divs[r]) {+ const x = b.partItem(d).final.pos[0];+ for (const z of [-zi, zi]) list.push({ on: d, at: [x, rowY0(r) + cellH, z], dir: [0, -1, 0], mate: above(r) });+ }+ b.fits(HW.dowel, list, 0.06);+ },+ );+ }+ if (r < rows - 1) {+ const L = longs[r];+ const yc = rowY0(r) + cellH + ti / 2;+ b.step(+ {+ title: r === 0 ? "Lay the long shelf on top" : "Add the next long shelf",+ detail: "Dowels go into both ends, and on top for the next row.",+ tools: ["hammer"],+ kind: "join",+ },+ () => {+ b.add(L, [0, 280, 0]);+ b.then(0.15);+ const list: FitOpts[] = [];+ for (const [i, x] of [-(W / 2 - T), W / 2 - T].entries())+ for (const z of [-zi, zi]) list.push({ on: L, at: [x, yc, z], dir: [i === 0 ? 1 : -1, 0, 0], mate: sides[i] });+ if (cols > 1)+ for (const d of divs[r + 1]) {+ const x = b.partItem(d).final.pos[0];+ for (const z of [-zi, zi]) list.push({ on: L, at: [x, yc + ti / 2, z], dir: [0, -1, 0], mate: d });+ }+ b.fits(HW.dowel, list, 0.05);+ },+ );+ }+ }+ void below;++ b.step(+ {+ title: "Add both sides",+ detail: "Slide them onto the bolts and dowels from the outside.",+ kind: "join",+ people: H > 1200 ? 2 : 1,+ },+ () => {+ b.stagger(0.3);+ b.add(sides[0], [-420, 0, 0]);+ b.add(sides[1], [420, 0, 0]);+ },+ );++ // top prepared upside down in its own scene+ b.step(+ {+ title: "Fit bolts and dowels into the top",+ detail: "Lay it upside down on the box first.",+ tools: ["screwdriver", "hammer"],+ scene: "top",+ kind: "dowels",+ warnings: ["floor"],+ },+ () => {+ b.stage(top, [0, T / 2, 0], [Math.PI, 0, 0], [0, 160, 0]);+ b.then(0.15);+ const bolts: FitOpts[] = [];+ const dowels: FitOpts[] = [];+ for (const [i, x] of [-sx, sx].entries()) {+ for (const z of [-zb, zb]) bolts.push({ on: top, at: [x, H - T, z], dir: [0, 1, 0], mate: sides[i], mateHole: 4 });+ for (const z of [-zd, zd]) dowels.push({ on: top, at: [x, H - T, z], dir: [0, 1, 0], mate: sides[i] });+ }+ b.fits(HW.camScrew, bolts, 0.08);+ b.then(0.1);+ b.fits(HW.dowel, dowels, 0.06);+ },+ );++ b.step(+ {+ title: "Put the top on",+ detail: "Lower it evenly so every dowel finds its hole.",+ kind: "join",+ people: H > 1200 ? 2 : 1,+ warnings: H > 1200 ? ["two"] : [],+ },+ () => b.add(top, [0, 320, 0]),+ );++ b.step(+ {+ title: "Lock all the cam locks",+ detail: "Arrow towards the bolt, then turn clockwise until it's snug.",+ tools: ["screwdriver"],+ kind: "cams",+ },+ () => {+ const list: FitOpts[] = [];+ for (const [i, side] of sides.entries()) {+ const xi = i === 0 ? -W / 2 + T : W / 2 - T;+ for (const y of [T + 26, H - T - 26]) for (const z of [-zb, zb]) list.push({ on: side, at: [xi, y, z], dir: [i === 0 ? -1 : 1, 0, 0] });+ }+ b.fits(HW.cam, list, 0.08);+ },+ );++ if (H >= 700) anchorStep(b, { W, D, top, y: H, backZ: -D / 2, severe: H > 1200 });+}++export type { Vec3 };diff --git a/src/lib/plan/sofa.ts b/src/lib/plan/sofa.tsnew file mode 100644index 0000000..87661e0--- /dev/null+++ b/src/lib/plan/sofa.ts@@ -0,0 +1,150 @@+import type { ProductSpec, SofaParams, Vec3 } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { clamp } from "./math";++export function defaultsSofa(s: ProductSpec): SofaParams {+ const p = s.sofa ?? {};+ return {+ seats: clamp(Math.round(p.seats ?? Math.max(1, Math.round((s.size.w - 30) / 62))), 1, 4),+ arms: p.arms ?? "wide",+ legs: p.legs ?? "round",+ };+}++/** Upholstered sofas and armchairs: legs on the base, arms and back bolted on, cushions last. */+export function buildSofa(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsSofa(s);+ const W = s.size.w * 10, H = s.size.h * 10, D = s.size.d * 10;+ const a = p.arms === "wide" ? Math.min(170, W * 0.12) : p.arms === "slim" ? 80 : 0;+ const legH = p.legs === "round" ? 110 : 70;+ const baseTop = 300;+ const backT = Math.min(200, D * 0.22);+ const armH = Math.min(H - 60, 640);+ const seatT = 140;+ const big = W > 1500;++ const baseT = b.part("Seat frame", [W - 2 * a, baseTop - legH, D], { material: "soft" });+ const base = b.place(baseT, [0, legH + (baseTop - legH) / 2, 0]);+ const legT = b.part("Leg", p.legs === "round" ? [42, legH, 42] : [56, legH, 56], { shape: p.legs === "round" ? "cyl" : "box", material: "wood" });+ const lx = W / 2 - a - 60, lz = D / 2 - 70;+ const legPts: [number, number][] = [+ [-lx, lz],+ [lx, lz],+ [lx, -lz],+ [-lx, -lz],+ ];+ if (W > 2000) legPts.push([0, lz], [0, -lz]);+ const legs = legPts.map(([x, z]) => b.place(legT, [x, legH / 2, z]));+ const arms: string[] = [];+ if (a > 0) {+ const armT = b.part("Armrest", [a, armH - legH + 40, D], { material: "soft" });+ for (const sgn of [-1, 1]) arms.push(b.place(armT, [sgn * (W / 2 - a / 2), legH - 40 + (armH - legH + 40) / 2, 0]));+ }+ const backPT = b.part("Backrest", [W - 2 * a, H - baseTop, backT], { material: "soft" });+ const back = b.place(backPT, [0, baseTop + (H - baseTop) / 2, -D / 2 + backT / 2]);+ const cw = (W - 2 * a) / p.seats;+ const seatCT = b.part("Seat cushion", [cw - 8, seatT, D - backT - 16], { material: "soft" });+ const seats = Array.from({ length: p.seats }, (_, i) => b.place(seatCT, [-(W - 2 * a) / 2 + cw * (i + 0.5), baseTop + seatT / 2, backT / 2 + 4]));+ const bh = Math.max(240, H - baseTop - seatT - 40);+ const backCT = b.part("Back cushion", [cw - 14, bh, 170], { material: "soft" });+ const backs = Array.from({ length: p.seats }, (_, i) =>+ b.place(backCT, [-(W - 2 * a) / 2 + cw * (i + 0.5), baseTop + seatT + bh / 2 - 6, -D / 2 + backT + 80], [-0.16, 0, 0]),+ );++ b.step(+ {+ title: "Lay the seat frame upside down",+ detail: "Put a blanket or the flattened box under it first.",+ pose: "-y",+ kind: "general",+ people: big ? 2 : 1,+ warnings: big ? ["two", "floor"] : ["floor"],+ },+ () => b.add(base, [0, 220, 0]),+ );+ b.step(+ {+ title: "Screw in the legs",+ detail: "Clockwise by hand until each one is snug.",+ pose: "-y",+ kind: "legs",+ warnings: ["hand"],+ },+ () => {+ b.stagger(0.22);+ legs.forEach((l) => b.add(l, [0, -260, 0], { spin: 2 }));+ },+ );+ b.step(+ {+ title: big ? "Turn it over together" : "Turn it over",+ detail: "Lift it by the frame, never by the legs.",+ pose: "+y",+ kind: "flip",+ people: big ? 2 : 1,+ warnings: big ? ["two"] : [],+ },+ () => {},+ );+ if (arms.length) {+ b.step(+ {+ title: "Bolt on the armrests",+ detail: "Line up the holes, then bolt loosely. Tighten once both arms are on.",+ tools: ["allen"],+ kind: "bolts",+ warnings: ["loose"],+ },+ () => {+ b.stagger(0.3);+ arms.forEach((k, i) => b.add(k, [(i === 0 ? -1 : 1) * 420, 0, 0]));+ b.then(0.1);+ const bolts: FitOpts[] = [];+ arms.forEach((k, i) => {+ const sgn = i === 0 ? -1 : 1;+ for (const z of [-D / 4, D / 4]) bolts.push({ on: k, at: [sgn * (W / 2 - a), legH + 90, z] as Vec3, dir: [sgn, 0, 0] as Vec3, mate: base });+ });+ b.fits(HW.boltL, bolts, 0.1);+ },+ );+ }+ b.step(+ {+ title: "Attach the backrest",+ detail: "Slide it down behind the seat, then bolt it from the back.",+ tools: ["allen"],+ kind: "bolts",+ people: big ? 2 : 1,+ warnings: big ? ["two"] : [],+ },+ () => {+ b.add(back, [0, 120, -420]);+ b.then(0.1);+ const n = W > 1600 ? 3 : 2;+ const bolts: FitOpts[] = Array.from({ length: n }, (_, i) => ({ on: back, at: [-(W - 2 * a) / 2 + ((W - 2 * a) * (i + 1)) / (n + 1), baseTop + 60, -D / 2] as Vec3, dir: [0, 0, 1] as Vec3, mate: base }));+ b.fits(HW.boltL, bolts, 0.12);+ },+ );+ b.step(+ {+ title: p.seats > 1 ? "Drop in the seat cushions" : "Drop in the seat cushion",+ detail: "Zips face the back.",+ kind: "cushions",+ },+ () => {+ b.stagger(0.18);+ seats.forEach((k) => b.add(k, [0, 320, 0]));+ },+ );+ b.step(+ {+ title: p.seats > 1 ? "Add the back cushions" : "Add the back cushion",+ detail: "Plump them up and lean them against the backrest.",+ kind: "cushions",+ },+ () => {+ b.stagger(0.18);+ backs.forEach((k) => b.add(k, [0, 160, 360]));+ },+ );+}diff --git a/src/lib/plan/table.ts b/src/lib/plan/table.tsnew file mode 100644index 0000000..0406bc2--- /dev/null+++ b/src/lib/plan/table.ts@@ -0,0 +1,196 @@+import type { ProductSpec, TableParams, Vec3 } from "../types";+import { HW, PlanBuilder, type FitOpts } from "./builder";+import { clamp } from "./math";++export function defaultsTable(s: ProductSpec): TableParams {+ const p = s.table ?? {};+ return {+ topThickness: clamp(p.topThickness ?? 30, 15, 60),+ legs: p.legs === "round" ? "round" : "square",+ legSize: clamp(p.legSize ?? 50, 25, 90),+ shelf: p.shelf ?? false,+ attach: p.attach ?? "screw",+ };+}++export function buildTable(b: PlanBuilder, s: ProductSpec) {+ const p = defaultsTable(s);+ const W = s.size.w * 10, D = s.size.d * 10, H = s.size.h * 10;+ const tt = p.topThickness, ls = p.legSize;+ const inset = p.attach === "screw" ? 0 : p.attach === "plate" ? 30 : 45;+ const Lh = H - tt;+ const big = W > 1000;++ const topT = b.part(s.category.toLowerCase().includes("desk") ? "Desk top" : "Table top", [W, tt, D]);+ const top = b.place(topT, [0, H - tt / 2, 0]);+ const legT = b.part("Leg", p.legs === "round" ? [ls, Lh, ls] : [ls, Lh, ls], { shape: p.legs === "round" ? "cyl" : "box", material: "wood" });+ const corners: [number, number][] = [+ [-1, 1],+ [1, 1],+ [1, -1],+ [-1, -1],+ ];+ const lx = W / 2 - ls / 2 - inset, lz = D / 2 - ls / 2 - inset;+ const legs = corners.map(([sx, sz]) => b.place(legT, [sx * lx, Lh / 2, sz * lz]));++ b.step(+ {+ title: "Lay the top upside down",+ detail: "Put the flattened box under it so the surface stays scratch free.",+ pose: "-y",+ kind: "general",+ warnings: ["floor"],+ people: big ? 2 : 1,+ },+ () => b.add(top, [0, 200, 0]),+ );++ if (p.attach === "plate") {+ b.step(+ {+ title: "Screw a leg plate into each corner",+ detail: "Use the pre-drilled holes. Four screws per plate.",+ tools: ["screwdriver"],+ pose: "-y",+ kind: "screws",+ },+ () => {+ const plates: FitOpts[] = corners.map(([sx, sz]) => ({ on: top, at: [sx * lx, H - tt, sz * lz], dir: [0, 1, 0], hole: false }));+ b.fits(HW.plate, plates, 0.15);+ b.then(0.1);+ const sc: FitOpts[] = [];+ for (const [sx, sz] of corners)+ for (const [dx, dz] of [[-28, -28], [28, -28], [28, 28], [-28, 28]])+ sc.push({ on: top, at: [sx * lx + dx, H - tt - 3, sz * lz + dz], dir: [0, 1, 0], hole: false });+ b.fits(HW.screwM, sc, 0.04);+ },+ );+ }++ let rails: string[] = [];+ if (p.attach === "apron") {+ const rh = 80, rt = 20;+ const longT = b.part("Long rail", [W - 2 * inset - 2 * ls, rh, rt], { material: "wood" });+ const shortT = b.part("Short rail", [rt, rh, D - 2 * inset - 2 * ls], { material: "wood" });+ const ry = H - tt - rh / 2;+ rails = [+ b.place(longT, [0, ry, lz + ls / 2 - rt / 2]),+ b.place(longT, [0, ry, -(lz + ls / 2 - rt / 2)]),+ b.place(shortT, [lx + ls / 2 - rt / 2, ry, 0]),+ b.place(shortT, [-(lx + ls / 2 - rt / 2), ry, 0]),+ ];+ b.step(+ {+ title: "Screw the rails under the top",+ detail: "They frame the underside, set in from the edge.",+ tools: ["screwdriver"],+ pose: "-y",+ kind: "screws",+ },+ () => {+ b.stagger(0.2);+ rails.forEach((r) => b.add(r, [0, -260, 0]));+ b.then(0.1);+ const sc: FitOpts[] = [];+ for (const r of rails) {+ const it = b.partItem(r);+ const along = it.final.pos[0] === 0 ? 0 : 2;+ const len = along === 0 ? W - 2 * inset - 2 * ls : D - 2 * inset - 2 * ls;+ for (const f of [-0.33, 0.33]) {+ const at: Vec3 = [...it.final.pos] as Vec3;+ at[along] += f * len;+ at[1] = H - tt - rh;+ sc.push({ on: r, at, dir: [0, 1, 0], hole: false });+ }+ }+ b.fits(HW.screwL, sc, 0.06);+ },+ );+ }++ if (p.attach === "screw") {+ b.step(+ {+ title: "Screw a bolt into each leg",+ detail: "Turn them in by hand until only half is showing.",+ scene: "legs",+ kind: "legs",+ },+ () => {+ b.stagger(0.15);+ legs.forEach((l, i) => b.stage(l, [(i - 1.5) * (ls + 110), Lh / 2, 0], [0, 0, 0], [0, 200, 0]));+ b.then(0.1);+ b.fits(+ { ...HW.legScrew, len: Math.round(Math.max(30, Math.min(70, 2 * (tt - 8))) / 2) * 2 },+ legs.map((l) => {+ const pos = b.partItem(l).final.pos;+ return { on: l, at: [pos[0], Lh, pos[2]], dir: [0, -1, 0], mate: top };+ }),+ 0.12,+ );+ },+ );+ }++ b.step(+ {+ title: p.attach === "apron" ? "Bolt the legs into the corners" : "Screw in the legs",+ detail: p.attach === "apron" ? "Hand tight for now. Tighten them all once every leg is on." : "Turn each one clockwise by hand. Hand tight is enough.",+ tools: p.attach === "apron" ? ["allen"] : [],+ pose: "-y",+ kind: "legs",+ warnings: p.attach === "apron" ? ["loose"] : ["hand"],+ },+ () => {+ b.stagger(0.3);+ legs.forEach((l) => b.add(l, [0, -360, 0], { spin: p.attach === "apron" ? 0 : 2 }));+ if (p.attach === "apron") {+ b.then(0.1);+ const bolts: FitOpts[] = [];+ const y = H - tt - 40;+ const off = ls / 2 - 10;+ corners.forEach(([sx, sz], i) => {+ bolts.push({ on: legs[i], at: [sx * (lx + ls / 2), y, sz * (lz + off)], dir: [-sx, 0, 0] });+ bolts.push({ on: legs[i], at: [sx * (lx + off), y, sz * (lz + ls / 2)], dir: [0, 0, -sz] });+ });+ b.fits(HW.boltL, bolts, 0.08);+ }+ },+ );++ if (p.shelf) {+ const shT = b.part("Shelf", [W - 2 * ls - 2, 16, D], { material: "board" });+ const sy = Math.max(110, H * 0.26);+ const shelf = b.place(shT, [0, sy, 0]);+ b.step(+ {+ title: "Fit the shelf between the legs",+ detail: "Two screws through each leg.",+ tools: ["screwdriver"],+ pose: "-y",+ kind: "screws",+ },+ () => {+ b.add(shelf, [0, -320, 0]);+ b.then(0.1);+ const sc: FitOpts[] = [];+ corners.forEach(([sx, sz], i) => {+ for (const dz of [-ls / 5, ls / 5]) sc.push({ on: legs[i], at: [sx * (W / 2), sy, sz * lz + dz], dir: [-sx, 0, 0], hole: false });+ });+ b.fits(HW.screwL, sc, 0.06);+ },+ );+ }++ b.step(+ {+ title: big ? "Turn it over together" : "Turn it over",+ detail: "Lift it by the top, not the legs.",+ pose: "+y",+ kind: "flip",+ people: big ? 2 : 1,+ warnings: big ? ["two"] : [],+ },+ () => {},+ );+}diff --git a/src/lib/products.ts b/src/lib/products.tsnew file mode 100644index 0000000..6448689--- /dev/null+++ b/src/lib/products.ts@@ -0,0 +1,312 @@+import type { Archetype, ProductSpec } from "./types";++/**+ * A wide offline index of real IKEA product names. Each row is a kind plus outer size (cm);+ * the kind decides the archetype and sensible parameters. Hand-tuned catalog entries win over these.+ */+export type Kind =+ | "cube"+ | "bookcase"+ | "open"+ | "chest"+ | "nightstand"+ | "desk"+ | "coffee"+ | "side"+ | "dining"+ | "bed"+ | "wardrobe"+ | "cabinet"+ | "sideboard"+ | "tv"+ | "shoe"+ | "chair"+ | "stool"+ | "bench"+ | "sofa"+ | "armchair";++type X = {+ rows?: number;+ cols?: 1 | 2;+ knobs?: "none" | "knob" | "bar";+ plinth?: boolean;+ doors?: 0 | 1 | 2;+ shelves?: number;+ c?: number;+ m?: number;+ l?: number;+ f?: number;+ seats?: number;+ arms?: "wide" | "slim" | "none";+ legs?: "round" | "square";+ attach?: "screw" | "plate" | "apron";+ shelf?: boolean;+ min?: number;+};++type Row = [name: string, kind: Kind, variant: string, w: number, h: number, d: number, x?: X, keywords?: string];++export const ROWS: Row[] = [+ // shelving and bookcases+ ["HEMNES", "bookcase", "Bookcase, 90 × 197 cm", 90, 197, 37, { shelves: 4 }, "bookshelf"],+ ["HEMNES", "bookcase", "Bookcase, 49 × 197 cm", 49, 197, 31, { shelves: 4 }, "narrow bookshelf"],+ ["IVAR", "open", "Shelving unit, 89 × 179 cm", 89, 179, 30, { shelves: 3 }, "pine shelf"],+ ["FINNBY", "bookcase", "Bookcase, 60 × 180 cm", 60, 180, 24, { shelves: 3 }],+ ["GERSBY", "bookcase", "Bookcase, 60 × 180 cm", 60, 180, 24, { shelves: 3 }],+ ["LAIVA", "bookcase", "Bookcase, 62 × 165 cm", 62, 165, 24, { shelves: 3 }],+ ["BRIMNES", "bookcase", "Bookcase, 60 × 190 cm", 60, 190, 35, { shelves: 3 }, "bookshelf"],+ ["HAUGA", "bookcase", "Bookcase, 80 × 199 cm", 80, 199, 35, { shelves: 3 }],+ ["IDANÄS", "bookcase", "Bookcase, 81 × 225 cm", 81, 225, 39, { shelves: 4 }],+ ["FJÄLKINGE", "open", "Shelving unit, 118 × 193 cm", 118, 193, 35, { shelves: 4 }],+ ["BAGGEBO", "open", "Shelf unit, 50 × 160 cm", 50, 160, 30, { shelves: 4 }, "metal shelf"],+ ["HYLLIS", "open", "Shelf unit, 60 × 140 cm", 60, 140, 27, { shelves: 3 }, "metal shelf"],+ ["OMAR", "open", "Shelf section, 92 × 181 cm", 92, 181, 36, { shelves: 4 }, "metal shelving"],+ ["ALBERT", "open", "Shelving unit, 64 × 159 cm", 64, 159, 28, { shelves: 3 }],+ ["BROR", "open", "Shelving unit, 85 × 190 cm", 85, 190, 40, { shelves: 3 }, "garage shelf"],+ ["VITTSJÖ", "open", "Shelving unit, 51 × 175 cm", 51, 175, 36, { shelves: 4 }],+ ["KOLBJÖRN", "open", "Shelving unit, 80 × 81 cm", 80, 81, 37, { shelves: 1 }],+ ["TROFAST", "cube", "Storage frame, 99 × 94 cm", 99, 94, 44, {}, "kids toy storage"],+ ["EKET", "cube", "Cabinet combination, 70 × 70 cm", 70, 70, 35],+ ["KALLAX", "cube", "Shelving unit, 112 × 112 cm", 112, 112, 39, {}, "3x3 9 cube"],+ ["KALLAX", "cube", "Shelving unit, 147 × 77 cm", 147, 77, 39, {}, "4x2"],+ // chests of drawers+ ["HEMNES", "chest", "Chest of 8 drawers", 160, 96, 50, { cols: 2, rows: 4, knobs: "knob", plinth: true, min: 240 }, "dresser"],+ ["HEMNES", "chest", "Chest of 6 drawers", 108, 131, 50, { cols: 2, rows: 3, knobs: "knob", plinth: true, min: 210 }, "dresser"],+ ["HEMNES", "nightstand", "Nightstand, 2 drawers", 46, 70, 35, { rows: 2, knobs: "knob", plinth: true }, "bedside table"],+ ["KULLEN", "chest", "Chest of 5 drawers", 35, 103, 40, { rows: 5, knobs: "knob" }],+ ["KULLEN", "chest", "Chest of 6 drawers", 140, 72, 40, { cols: 2, rows: 3, knobs: "knob" }],+ ["KULLEN", "nightstand", "Chest of 2 drawers", 35, 49, 40, { rows: 2, knobs: "knob" }, "bedside"],+ ["NORDLI", "chest", "Chest of 8 drawers", 160, 99, 47, { cols: 2, rows: 4, knobs: "none", min: 240 }],+ ["NORDLI", "chest", "Chest of 4 drawers", 40, 99, 47, { rows: 4, knobs: "none" }],+ ["TARVA", "chest", "Chest of 5 drawers", 79, 129, 48, { rows: 5, knobs: "knob" }, "pine"],+ ["TARVA", "chest", "Chest of 6 drawers", 118, 92, 48, { cols: 2, rows: 3, knobs: "knob" }, "pine"],+ ["TARVA", "nightstand", "Nightstand", 39, 61, 38, { rows: 1, knobs: "knob" }, "bedside pine"],+ ["KOPPANG", "chest", "Chest of 3 drawers", 90, 83, 55, { rows: 3, knobs: "bar" }],+ ["KOPPANG", "chest", "Chest of 6 drawers", 172, 83, 55, { cols: 2, rows: 3, knobs: "bar" }],+ ["SONGESAND", "chest", "Chest of 4 drawers", 82, 104, 50, { rows: 4, knobs: "knob", plinth: true }],+ ["SONGESAND", "chest", "Chest of 6 drawers", 161, 81, 50, { cols: 2, rows: 3, knobs: "knob", plinth: true }],+ ["SONGESAND", "nightstand", "Nightstand", 42, 58, 40, { rows: 2, knobs: "knob" }],+ ["BRIMNES", "chest", "Chest of 3 drawers", 78, 95, 41, { rows: 3, knobs: "none" }],+ ["BRIMNES", "nightstand", "Nightstand", 39, 41, 41, { rows: 1, knobs: "none" }],+ ["HAUGA", "chest", "Chest of 6 drawers", 138, 84, 46, { cols: 2, rows: 3, knobs: "bar" }],+ ["HAUGA", "chest", "Chest of 3 drawers", 70, 84, 46, { rows: 3, knobs: "bar" }],+ ["IDANÄS", "chest", "Chest of 6 drawers", 162, 95, 47, { cols: 2, rows: 3, knobs: "bar", min: 210 }],+ ["GURSKEN", "chest", "Chest of 3 drawers", 69, 74, 39, { rows: 3, knobs: "knob" }],+ ["GURSKEN", "nightstand", "Bedside table", 39, 55, 40, { rows: 2, knobs: "knob" }],+ ["VIHALS", "chest", "Chest of 6 drawers", 140, 85, 47, { cols: 2, rows: 3, knobs: "bar" }],+ ["HELMER", "chest", "Drawer unit on castors", 28, 69, 43, { rows: 6, knobs: "none" }, "metal office"],+ ["NESNA", "nightstand", "Bedside table", 36, 45, 35, { rows: 1, knobs: "none" }],+ ["MALM", "nightstand", "Bedside table, 1 drawer", 40, 55, 48, { rows: 1, knobs: "none" }],+ // tables and desks+ ["MICKE", "desk", "Desk, 105 × 50 cm", 105, 75, 50, { attach: "apron", legs: "square" }, "computer desk"],+ ["LAGKAPTEN", "desk", "Desk, 120 × 60 cm", 120, 73, 60, { attach: "plate", legs: "round" }, "adils olov desk"],+ ["BEKANT", "desk", "Desk, 160 × 80 cm", 160, 65, 80, { attach: "apron", legs: "square" }, "office"],+ ["IDÅSEN", "desk", "Desk, 160 × 80 cm", 160, 72, 80, { attach: "apron", legs: "square" }, "sit stand standing"],+ ["TROTTEN", "desk", "Desk, 120 × 70 cm", 120, 75, 70, { attach: "apron", legs: "square" }, "office"],+ ["LINNMON", "desk", "Table top with legs, 120 × 60 cm", 120, 74, 60, { attach: "plate", legs: "round" }],+ ["LISABO", "dining", "Table, 140 × 78 cm", 140, 74, 78, {}, "dining table ash"],+ ["EKEDALEN", "dining", "Extendable table, 120 × 80 cm", 120, 75, 80, {}, "dining"],+ ["MÖRBYLÅNGA", "dining", "Table, 220 × 100 cm", 220, 74, 100, {}, "oak dining"],+ ["INGO", "dining", "Table, 120 × 75 cm", 120, 73, 75, {}, "pine dining"],+ ["NORRÅKER", "dining", "Table, 125 × 74 cm", 125, 74, 74, {}, "birch dining"],+ ["VANGSTA", "dining", "Extendable table, 120 × 75 cm", 120, 73, 75, {}, "dining"],+ ["SKOGSTA", "dining", "Dining table, 235 × 100 cm", 235, 74, 100, {}, "acacia"],+ ["LERHAMN", "dining", "Table, 118 × 74 cm", 118, 74, 74, {}, "dining"],+ ["SANDSBERG", "dining", "Table, 110 × 67 cm", 110, 75, 67, {}, "dining"],+ ["INGATORP", "dining", "Extendable table, 155 × 87 cm", 155, 74, 87, {}, "dining"],+ ["TOMMARYD", "dining", "Table, 130 × 70 cm", 130, 75, 70, {}, "dining"],+ ["HEMNES", "coffee", "Coffee table, 118 × 75 cm", 118, 46, 75, { attach: "apron", shelf: true }],+ ["LISTERBY", "coffee", "Coffee table, 140 × 60 cm", 140, 50, 60, { attach: "apron", shelf: false }],+ ["HOLMERUD", "coffee", "Coffee table, 90 × 55 cm", 90, 50, 55, { shelf: true }],+ ["VITTSJÖ", "coffee", "Coffee table, 90 × 50 cm", 90, 40, 50, { legs: "square", shelf: true }],+ ["LACK", "coffee", "Coffee table, 90 × 55 cm", 90, 45, 55, { shelf: true }],+ ["HEMNES", "side", "Side table, 55 × 55 cm", 55, 55, 55, { attach: "apron" }, "end table"],+ ["KLIMPEN", "desk", "Table, 120 × 60 cm", 120, 75, 60, { attach: "apron" }],+ // beds+ ["MALM", "bed", "Bed frame, 140 × 200 cm", 156, 100, 209, { m: 140 }, "double"],+ ["MALM", "bed", "Bed frame, 90 × 200 cm", 106, 100, 209, { m: 90 }, "single"],+ ["HEMNES", "bed", "Bed frame, 160 × 200 cm", 174, 120, 211, { m: 160, f: 66 }, "queen double"],+ ["HEMNES", "bed", "Bed frame, 90 × 200 cm", 105, 120, 211, { m: 90, f: 66 }, "single"],+ ["TARVA", "bed", "Bed frame, 140 × 200 cm", 147, 92, 209, { m: 140, f: 40 }, "pine double"],+ ["TARVA", "bed", "Bed frame, 90 × 200 cm", 97, 92, 209, { m: 90, f: 40 }, "pine single"],+ ["NEIDEN", "bed", "Bed frame, 90 × 200 cm", 97, 72, 206, { m: 90, f: 46 }, "single pine"],+ ["BRIMNES", "bed", "Bed frame, 160 × 200 cm", 166, 102, 206, { m: 160 }, "storage"],+ ["SONGESAND", "bed", "Bed frame, 160 × 200 cm", 167, 95, 207, { m: 160, f: 59 }],+ ["SLATTUM", "bed", "Upholstered bed frame, 160 × 200 cm", 168, 85, 213, { m: 160, f: 30 }],+ ["KLEPPSTAD", "bed", "Bed frame, 160 × 200 cm", 168, 96, 206, { m: 160 }],+ ["IDANÄS", "bed", "Bed frame, 160 × 200 cm", 174, 101, 211, { m: 160 }],+ ["SAGSTUA", "bed", "Bed frame, 160 × 200 cm", 167, 123, 209, { m: 160, f: 84 }, "metal"],+ ["NORDLI", "bed", "Bed frame with storage, 160 × 200 cm", 168, 64, 207, { m: 160 }],+ ["KRITTER", "bed", "Kids bed frame, 70 × 160 cm", 75, 64, 165, { m: 70, l: 160, f: 50 }, "children"],+ ["SUNDVIK", "bed", "Extendable bed, 80 × 200 cm", 85, 80, 207, { m: 80, f: 60 }, "kids"],+ // wardrobes, cabinets, sideboards+ ["PAX", "wardrobe", "Wardrobe frame, 50 × 236 cm", 50, 236, 58, { doors: 0, shelves: 2 }],+ ["PAX", "wardrobe", "Wardrobe frame, 100 × 236 cm", 100, 236, 58, { doors: 0, shelves: 2 }],+ ["HEMNES", "wardrobe", "Wardrobe with 2 doors, 120 × 197 cm", 120, 197, 59, { knobs: "knob" }],+ ["KLEPPSTAD", "wardrobe", "Wardrobe with 2 doors, 79 × 176 cm", 79, 176, 55],+ ["SONGESAND", "wardrobe", "Wardrobe, 120 × 191 cm", 120, 191, 60],+ ["RAKKESTAD", "wardrobe", "Wardrobe with 2 doors, 79 × 176 cm", 79, 176, 51],+ ["VISTHUS", "wardrobe", "Wardrobe, 122 × 216 cm", 122, 216, 59],+ ["DOMBÅS", "wardrobe", "Wardrobe, 140 × 181 cm", 140, 181, 51],+ ["HAUGA", "wardrobe", "Wardrobe, 70 × 199 cm", 70, 199, 55],+ ["IDANÄS", "wardrobe", "Wardrobe, 121 × 211 cm", 121, 211, 59],+ ["BRIMNES", "wardrobe", "Wardrobe with 3 doors, 117 × 190 cm", 117, 190, 50],+ ["HAVSTA", "cabinet", "Cabinet with doors, 81 × 123 cm", 81, 123, 35],+ ["HEMNES", "cabinet", "Glass-door cabinet, 90 × 197 cm", 90, 197, 37, { shelves: 3 }, "display vitrine"],+ ["FABRIKÖR", "cabinet", "Glass-door cabinet, 81 × 113 cm", 81, 113, 41, { shelves: 2 }, "metal display"],+ ["DETOLF", "cabinet", "Glass-door cabinet, 43 × 163 cm", 43, 163, 37, { doors: 1, shelves: 3 }, "display"],+ ["RUDSTA", "cabinet", "Glass-door cabinet, 80 × 170 cm", 80, 170, 37, { shelves: 3 }],+ ["MILSBO", "cabinet", "Glass-door cabinet, 101 × 186 cm", 101, 186, 42, { shelves: 3 }],+ ["KOLBJÖRN", "cabinet", "Cabinet, 80 × 81 cm", 80, 81, 37, { shelves: 1 }, "outdoor balcony"],+ ["IVAR", "cabinet", "Cabinet with doors, 80 × 83 cm", 80, 83, 30, { shelves: 1 }, "pine"],+ ["BESTÅ", "cabinet", "Shelf unit with doors, 60 × 64 cm", 60, 64, 40, { doors: 1, shelves: 1, knobs: "none" }],+ ["BRIMNES", "cabinet", "Cabinet with doors, 39 × 95 cm", 39, 95, 34, { doors: 1, shelves: 2 }],+ ["HEMNES", "sideboard", "Sideboard, 157 × 88 cm", 157, 88, 47, { knobs: "knob" }, "buffet"],+ ["HAVSTA", "sideboard", "Sideboard, 100 × 89 cm", 100, 89, 47],+ ["TONSTAD", "sideboard", "Sideboard, 121 × 81 cm", 121, 81, 47],+ ["IDANÄS", "sideboard", "Sideboard, 160 × 87 cm", 160, 87, 47],+ ["BESTÅ", "tv", "TV bench, 120 × 40 cm", 120, 40, 42, { knobs: "none" }],+ ["BESTÅ", "tv", "TV bench, 180 × 38 cm", 180, 38, 42, { knobs: "none" }],+ ["BRIMNES", "tv", "TV bench, 120 × 53 cm", 120, 53, 41, { knobs: "none" }],+ ["HEMNES", "tv", "TV bench, 148 × 57 cm", 148, 57, 47, { knobs: "knob" }],+ ["HAUGA", "tv", "TV bench, 138 × 54 cm", 138, 54, 36, { knobs: "bar" }],+ // shoe cabinets+ ["BISSA", "shoe", "Shoe cabinet with 2 compartments", 49, 93, 28, { c: 2 }, "shoe storage"],+ ["BISSA", "shoe", "Shoe cabinet with 3 compartments", 49, 135, 28, { c: 3 }, "shoe storage"],+ ["HEMNES", "shoe", "Shoe cabinet with 2 compartments", 89, 127, 30, { c: 2, knobs: "knob" }, "shoe storage"],+ ["HEMNES", "shoe", "Shoe cabinet with 4 compartments", 107, 101, 22, { c: 2, knobs: "knob" }, "shoe storage"],+ ["STÄLL", "shoe", "Shoe cabinet with 3 compartments", 79, 148, 29, { c: 3, knobs: "knob" }, "shoe storage"],+ ["TRONES", "shoe", "Shoe cabinet, 52 × 39 cm", 52, 39, 18, { c: 1, knobs: "none" }, "shoe storage wall"],+ ["BRUSALI", "shoe", "Shoe cabinet with 3 compartments", 61, 130, 31, { c: 3, knobs: "knob" }],+ ["MACKAPÄR", "shoe", "Shoe cabinet, 80 × 102 cm", 80, 102, 35, { c: 2, knobs: "bar" }],+ // seating+ ["POÄNG", "armchair", "Armchair", 68, 100, 82, { arms: "slim" }, "rocking chair"],+ ["STRANDMON", "armchair", "Wing chair", 82, 101, 96, { arms: "wide" }],+ ["EKERÖ", "armchair", "Armchair", 70, 73, 73, { arms: "slim" }],+ ["KIVIK", "sofa", "3-seat sofa", 228, 83, 95, { seats: 3 }, "couch"],+ ["KLIPPAN", "sofa", "2-seat sofa", 180, 66, 88, { seats: 2, arms: "slim" }, "couch"],+ ["EKTORP", "sofa", "3-seat sofa", 218, 88, 88, { seats: 3 }, "couch"],+ ["FRIHETEN", "sofa", "Corner sofa-bed", 230, 66, 151, { seats: 3, arms: "slim" }, "couch sleeper"],+ ["SÖDERHAMN", "sofa", "3-seat sofa", 198, 69, 99, { seats: 3, arms: "slim" }, "couch"],+ ["VIMLE", "sofa", "3-seat sofa", 241, 83, 98, { seats: 3 }, "couch"],+ ["LANDSKRONA", "sofa", "3-seat sofa", 204, 89, 89, { seats: 3, arms: "slim" }, "couch"],+ ["GLOSTAD", "sofa", "2-seat sofa", 145, 78, 82, { seats: 2 }, "couch"],+ ["UPPLAND", "sofa", "3-seat sofa", 231, 89, 98, { seats: 3 }, "couch"],+ ["HEMLINGBY", "sofa", "2-seat sofa", 156, 80, 80, { seats: 2, arms: "slim" }, "couch"],+ ["STEFAN", "chair", "Chair", 42, 90, 49, {}, "dining chair pine"],+ ["ODGER", "chair", "Chair", 45, 80, 52, {}, "dining chair"],+ ["TEODORES", "chair", "Chair", 46, 80, 53, {}, "dining chair"],+ ["ADDE", "chair", "Chair", 39, 77, 47, {}, "dining chair"],+ ["LISABO", "chair", "Chair", 45, 76, 51, {}, "dining chair"],+ ["NORRÅKER", "chair", "Chair", 41, 81, 50, {}, "dining chair"],+ ["JANINGE", "chair", "Chair", 50, 76, 47, {}, "dining chair"],+ ["EKEDALEN", "chair", "Chair", 45, 95, 51, {}, "dining chair"],+ ["BERGMUND", "chair", "Chair", 52, 95, 59, {}, "dining chair upholstered"],+ ["TERJE", "chair", "Folding chair", 44, 79, 50, {}, "folding"],+ ["STIG", "stool", "Bar stool, 74 cm", 37, 74, 37, {}, "bar"],+ ["DALFRED", "stool", "Bar stool", 50, 74, 50, {}, "bar"],+ ["KYRRE", "stool", "Stool", 35, 45, 35],+ ["BEKVÄM", "stool", "Step stool", 43, 50, 43, {}, "step"],+ ["ÄPPLARÖ", "bench", "Bench, outdoor", 114, 44, 41, {}, "garden outdoor"],+ ["HEMNES", "bench", "Bench", 98, 45, 37, {}, "hallway"],+];++const MIN: Record<Kind, number> = {+ cube: 40, bookcase: 50, open: 40, chest: 90, nightstand: 40, desk: 25, coffee: 20, side: 15, dining: 40,+ bed: 100, wardrobe: 120, cabinet: 60, sideboard: 80, tv: 60, shoe: 45, chair: 25, stool: 12, bench: 20, sofa: 40, armchair: 30,+};++const CATEGORY: Record<Kind, string> = {+ cube: "Shelving unit", bookcase: "Bookcase", open: "Shelving unit", chest: "Chest of drawers", nightstand: "Nightstand",+ desk: "Desk", coffee: "Coffee table", side: "Side table", dining: "Dining table", bed: "Bed frame", wardrobe: "Wardrobe",+ cabinet: "Cabinet", sideboard: "Sideboard", tv: "TV bench", shoe: "Shoe cabinet", chair: "Chair", stool: "Stool",+ bench: "Bench", sofa: "Sofa", armchair: "Armchair",+};++export const KIND_ARCH: Record<Kind, Archetype> = {+ cube: "shelf", bookcase: "shelf", open: "shelf", chest: "drawers", nightstand: "drawers", desk: "table", coffee: "table",+ side: "table", dining: "table", bed: "bed", wardrobe: "cabinet", cabinet: "cabinet", sideboard: "cabinet", tv: "cabinet",+ shoe: "cabinet", chair: "seat", stool: "seat", bench: "seat", sofa: "sofa", armchair: "sofa",+};++/** Turn a kind and a size into a full product spec. */+export function specFor(kind: Kind, name: string, variant: string, w: number, h: number, d: number, x: X = {}): Omit<ProductSpec, "source"> {+ const big = h > 150 || w > 150;+ const base = {+ name,+ variant,+ category: CATEGORY[kind],+ archetype: KIND_ARCH[kind],+ size: { w, h, d },+ minutes: x.min ?? MIN[kind],+ people: (big ? 2 : 1) as 1 | 2,+ difficulty: (["chest", "wardrobe", "sideboard"].includes(kind) ? 3 : ["cube", "side", "stool", "coffee"].includes(kind) ? 1 : 2) as 1 | 2 | 3,+ };+ switch (kind) {+ case "cube":+ return { ...base, shelf: { style: "grid", cols: Math.max(1, Math.round((w - 6) / 35)), rows: Math.max(1, Math.round((h - 6) / 35)), outer: 40, inner: 16, back: false } };+ case "bookcase":+ return { ...base, shelf: { style: "bookcase", shelves: x.shelves ?? Math.max(1, Math.round(h / 45) - 1), fixedShelf: h > 150, back: true, plinth: h > 100, outer: 16 } };+ case "open":+ return { ...base, difficulty: 1, shelf: { style: "bookcase", shelves: x.shelves ?? Math.max(1, Math.round(h / 45) - 1), fixedShelf: h > 150, back: false, plinth: false, outer: 18 } };+ case "chest":+ case "nightstand":+ return { ...base, minutes: x.min ?? (kind === "nightstand" ? 30 + 15 * (x.rows ?? 2) : 30 + 20 * (x.rows ?? 3) * (x.cols ?? 1)), drawers: { cols: x.cols ?? 1, rows: x.rows ?? (kind === "nightstand" ? 2 : 3), knobs: x.knobs ?? "knob", plinth: x.plinth ?? false, thickness: 16 } };+ case "desk":+ return { ...base, table: { attach: x.attach ?? "plate", legs: x.legs ?? "round", legSize: x.legs === "square" ? 45 : 34, topThickness: 28, shelf: false } };+ case "coffee":+ return { ...base, table: { attach: x.attach ?? "screw", legs: x.legs ?? "square", legSize: 48, topThickness: 40, shelf: x.shelf ?? true } };+ case "side":+ return { ...base, table: { attach: x.attach ?? "screw", legs: "square", legSize: 40, topThickness: 30, shelf: false } };+ case "dining":+ return { ...base, people: w > 140 ? 2 : 1, table: { attach: "apron", legs: x.legs ?? "square", legSize: 55, topThickness: 25, shelf: false } };+ case "bed":+ return { ...base, people: 2, bed: { mattressW: x.m ?? Math.max(80, w - 16), mattressL: x.l ?? 200, headH: h, footH: x.f ?? 38, slats: x.l && x.l < 190 ? 13 : 17, centerBeam: (x.m ?? w) >= 120 } };+ case "wardrobe":+ return { ...base, people: 2, cabinet: { doors: x.doors ?? (w >= 60 ? 2 : 1), shelves: x.shelves ?? 1, rail: true, plinth: true, handles: x.knobs ?? "knob", thickness: 18 } };+ case "cabinet":+ return { ...base, cabinet: { doors: x.doors ?? (w > 50 ? 2 : 1), shelves: x.shelves ?? (h > 100 ? 2 : 1), rail: false, plinth: h > 100, handles: x.knobs ?? "knob", thickness: 18 } };+ case "sideboard":+ return { ...base, cabinet: { doors: 2, shelves: 1, rail: false, plinth: true, handles: x.knobs ?? "knob", thickness: 18 } };+ case "tv":+ return { ...base, cabinet: { doors: 2, shelves: 0, rail: false, plinth: false, handles: x.knobs ?? "knob", thickness: 16 } };+ case "shoe":+ return { ...base, cabinet: { fronts: "tilt", compartments: x.c ?? 2, doors: 0, shelves: 0, rail: false, plinth: false, handles: x.knobs ?? "knob", thickness: 16 } };+ case "chair":+ return { ...base, seat: { kind: "chair", seat: "square", seatH: 45, backH: h } };+ case "stool":+ return { ...base, seat: { kind: "stool", seat: "round", seatH: h, splay: true, stretchers: h > 60 } };+ case "bench":+ return { ...base, seat: { kind: "bench", seat: "square", seatH: h, splay: false } };+ case "sofa":+ case "armchair":+ return { ...base, people: kind === "sofa" ? 2 : 1, sofa: { seats: x.seats ?? (kind === "armchair" ? 1 : Math.max(1, Math.round((w - 30) / 62))), arms: x.arms ?? "wide", legs: "round" } };+ }+}++export const KIND_LABELS: { kind: Kind; label: string }[] = [+ { kind: "bookcase", label: "Bookcase" },+ { kind: "cube", label: "Cube shelf" },+ { kind: "chest", label: "Chest of drawers" },+ { kind: "nightstand", label: "Nightstand" },+ { kind: "wardrobe", label: "Wardrobe" },+ { kind: "cabinet", label: "Cabinet" },+ { kind: "shoe", label: "Shoe cabinet" },+ { kind: "tv", label: "TV bench" },+ { kind: "desk", label: "Desk" },+ { kind: "dining", label: "Dining table" },+ { kind: "coffee", label: "Coffee table" },+ { kind: "bed", label: "Bed frame" },+ { kind: "sofa", label: "Sofa" },+ { kind: "chair", label: "Chair" },+ { kind: "stool", label: "Stool" },+ { kind: "bench", label: "Bench" },+];++export const KIND_DEFAULT_SIZE: Record<Kind, [number, number, number]> = {+ cube: [77, 77, 39], bookcase: [80, 190, 30], open: [80, 180, 35], chest: [80, 90, 48], nightstand: [42, 55, 40], desk: [120, 74, 60],+ coffee: [110, 45, 60], side: [50, 50, 50], dining: [140, 74, 80], bed: [156, 100, 209], wardrobe: [100, 200, 58], cabinet: [80, 120, 40],+ sideboard: [140, 85, 45], tv: [150, 50, 42], shoe: [60, 100, 28], chair: [44, 88, 50], stool: [35, 45, 35], bench: [100, 45, 38],+ sofa: [210, 85, 92], armchair: [75, 90, 80],+};diff --git a/src/lib/scan/parse.ts b/src/lib/scan/parse.tsnew file mode 100644index 0000000..6491a01--- /dev/null+++ b/src/lib/scan/parse.ts@@ -0,0 +1,339 @@+import { z } from "zod";+import type { CustomFix, CustomPart, CustomStep, HwKind, PartMaterial, Pose, ProductSpec, ToolId, Vec3, WarnId } from "../types";+import { parseSpec } from "../spec";+import { boxOf } from "../plan/custom";++/* ---------- lenient schema: models drift, so coerce what we can and drop the rest ---------- */++const str = (max: number) => z.coerce.string().transform((s) => clean(s).slice(0, max));+const vec = z+ .array(z.coerce.number())+ .min(3)+ .transform((a) => [a[0], a[1], a[2]] as Vec3)+ .refine((a) => a.every((n) => Number.isFinite(n)));++const Part = z.object({+ id: z.coerce.string(),+ label: z.coerce.string().optional().catch(undefined),+ name: str(40).catch("Part"),+ size: vec,+ pos: vec,+ shape: z.enum(["box", "cyl"]).optional().catch(undefined),+ material: z.enum(["board", "fiber", "wood", "metal", "soft"]).optional().catch(undefined),+});++const Fix = z.object({+ kind: z.coerce.string(),+ count: z.coerce.number().catch(1),+ len: z.coerce.number().optional().catch(undefined),+ dia: z.coerce.number().optional().catch(undefined),+ to: z.array(z.coerce.string()).optional().catch(undefined),+});++const Step = z.object({+ title: str(80).catch("Next step"),+ detail: str(240).optional().catch(undefined),+ add: z.array(z.coerce.string()).optional().catch(undefined),+ fix: z.array(z.unknown()).optional().catch(undefined),+ tools: z.array(z.coerce.string()).optional().catch(undefined),+ people: z.coerce.number().optional().catch(undefined),+ pose: z.coerce.string().optional().catch(undefined),+ warnings: z.array(z.coerce.string()).optional().catch(undefined),+});++const Root = z.object({+ name: str(40),+ brand: str(40).optional().catch(undefined),+ variant: str(60).optional().catch(undefined),+ category: str(40).optional().catch(undefined),+ size: z.object({ w: z.coerce.number(), h: z.coerce.number(), d: z.coerce.number() }).optional().catch(undefined),+ minutes: z.coerce.number().optional().catch(undefined),+ people: z.coerce.number().optional().catch(undefined),+ difficulty: z.coerce.number().optional().catch(undefined),+ archetype: z.coerce.string().optional().catch(undefined),+ fromCover: z.coerce.boolean().optional().catch(undefined),+ parts: z.array(z.unknown()),+ steps: z.array(z.unknown()),+ watchOut: z.array(z.coerce.string()).optional().catch(undefined),+});++export function clean(s: string) {+ return s+ .replace(/\s*[‒-―]\s*/g, ", ")+ .replace(/\s+,/g, ",")+ .replace(/\s+/g, " ")+ .trim();+}++/* ---------- synonyms ---------- */++const HW_WORDS: [RegExp, HwKind | null][] = [+ [/cam\s*(bolt|screw)|connect(ing|or)\s*(bolt|screw)|camscrew|minifix bolt/, "camScrew"],+ [/cam|minifix|lock disc|eccentric/, "cam"],+ [/dowel|wood pin|peg/, "dowel"],+ [/shelf\s*(pin|support|peg)|^pin$|support pin/, "pin"],+ [/leg\s*(bolt|screw)|hanger bolt|double.?ended|legscrew/, "legScrew"],+ [/hinge/, "hinge"],+ [/knob/, "knob"],+ [/handle|pull/, "handle"],+ [/bracket|wall|anchor|anti.?tip|strap/, "bracket"],+ [/felt|glide|pad|foot/, "glide"],+ [/plate/, "plate"],+ [/nail|tack|staple/, "nail"],+ [/bolt|machine screw|allen|hex|connector/, "bolt"],+ [/nut|washer|insert|cap|cover|sticker|label/, null],+ [/screw|runner|slide/, "screw"],+];++export function hwKind(raw: string): HwKind | null {+ const s = raw.toLowerCase().trim();+ const direct: Record<string, HwKind> = { camscrew: "camScrew", legscrew: "legScrew" };+ if (direct[s]) return direct[s];+ for (const [re, k] of HW_WORDS) if (re.test(s)) return k;+ return "screw";+}++const TOOL_WORDS: [RegExp, ToolId][] = [+ [/allen|hex key|hex wrench|l.?key/, "allen"],+ [/flat|slotted/, "flathead"],+ [/screwdriver|phillips|cross|pozi/, "screwdriver"],+ [/hammer|mallet/, "hammer"],+ [/drill/, "drill"],+ [/spanner|wrench/, "wrench"],+ [/level/, "level"],+ [/tape|measure|ruler/, "tape"],+ [/pencil|marker/, "pencil"],+ [/knife|cutter|scissors/, "knife"],+];+function tool(raw: string): ToolId | null {+ const s = raw.toLowerCase();+ for (const [re, t] of TOOL_WORDS) if (re.test(s)) return t;+ return null;+}++const POSES: [RegExp, Pose][] = [+ [/upside|^-y$|inverted/, "-y"],+ [/on[ _]?(its |the )?back|front (facing )?up|^\+z$/, "+z"],+ [/face[ _]?down|front down|back (facing )?up|^-z$/, "-z"],+ [/left[ _]?side|on (its|the) left|^\+x$/, "+x"],+ [/right[ _]?side|on (its|the) right|on (its|the) side|^-x$/, "-x"],+ [/upright|standing|^\+y$|normal/, "+y"],+];+function pose(raw?: string): Pose | undefined {+ if (!raw) return undefined;+ const s = raw.toLowerCase().replace(/\s+/g, " ").trim();+ for (const [re, p] of POSES) if (re.test(s)) return p;+ return undefined;+}++const WARN_WORDS: [RegExp, WarnId][] = [+ [/two|2 people|second person|helper/, "two"],+ [/wall|anchor/, "wall"],+ [/tip/, "tip"],+ [/floor|soft surface|scratch|carpet|blanket/, "floor"],+ [/loose|don.?t tighten|not fully/, "loose"],+ [/hand/, "hand"],+ [/square|diagonal/, "square"],+ [/face|finished side|direction|orientation/, "face"],+];+function warn(raw: string): WarnId | null {+ const s = raw.toLowerCase();+ for (const [re, w] of WARN_WORDS) if (re.test(s)) return w;+ return null;+}++/* ---------- geometry clean up ---------- */++export interface ScanCheck {+ ok: boolean;+ issues: string[];+}++function scaleFix(parts: CustomPart[], size?: { w: number; h: number; d: number }) {+ const boxes = parts.map(boxOf);+ const H = Math.max(...boxes.map((b) => b.max[1])) - Math.min(...boxes.map((b) => b.min[1]));+ const W = Math.max(...boxes.map((b) => b.max[0])) - Math.min(...boxes.map((b) => b.min[0]));+ const big = Math.max(H, W);+ let k = 1;+ if (size && size.h > 0) {+ const r = (size.h * 10) / Math.max(1, H);+ if (r > 6 && r < 16) k = 10;+ else if (r > 0.06 && r < 0.16) k = 0.1;+ } else if (big < 300 && parts.some((p) => Math.min(...p.size) < 3)) k = 10;+ if (k !== 1) for (const p of parts) {+ p.size = p.size.map((n) => n * k) as Vec3;+ p.pos = p.pos.map((n) => n * k) as Vec3;+ }+}++function ground(parts: CustomPart[]) {+ const boxes = parts.map(boxOf);+ const minY = Math.min(...boxes.map((b) => b.min[1]));+ const cx = (Math.min(...boxes.map((b) => b.min[0])) + Math.max(...boxes.map((b) => b.max[0]))) / 2;+ const cz = (Math.min(...boxes.map((b) => b.min[2])) + Math.max(...boxes.map((b) => b.max[2]))) / 2;+ for (const p of parts) p.pos = [round1(p.pos[0] - cx), round1(p.pos[1] - minY), round1(p.pos[2] - cz)];+}++const round1 = (n: number) => Math.round(n * 10) / 10;++/** Close small gaps and overlaps between parts that are clearly meant to touch. Earlier parts stay put. */+function snap(parts: CustomPart[], order: string[]) {+ const byId = new Map(parts.map((p) => [p.id, p]));+ const seq = [...order.map((id) => byId.get(id)).filter(Boolean), ...parts.filter((p) => !order.includes(p.id))] as CustomPart[];+ const done: CustomPart[] = [];+ for (const p of seq) {+ for (let k = 0; k < 3; k++) {+ const a = boxOf(p);+ let best: number | null = null;+ for (const q of done) {+ const b = boxOf(q);+ const others = [0, 1, 2].filter((j) => j !== k);+ if (!others.every((j) => Math.min(a.max[j], b.max[j]) - Math.max(a.min[j], b.min[j]) > 5)) continue;+ const aAbove = a.min[k] + a.max[k] > b.min[k] + b.max[k];+ const gap = aAbove ? a.min[k] - b.max[k] : b.min[k] - a.max[k];+ if (gap > 0.5 && gap < 25) {+ const move = aAbove ? -gap : gap;+ if (best === null || Math.abs(move) < Math.abs(best)) best = move;+ } else if (gap < -0.5 && gap > -12) {+ const move = aAbove ? -gap : gap;+ if (best === null || Math.abs(move) < Math.abs(best)) best = move;+ }+ }+ if (best !== null) p.pos[k] = round1(p.pos[k] + best);+ }+ done.push(p);+ }+}++/** Is this something we can draw with a straight face? */+export function checkScan(parts: CustomPart[]): ScanCheck {+ const issues: string[] = [];+ if (parts.length < 2) issues.push("There are fewer than two parts.");+ const boxes = parts.map(boxOf);+ const touching = (i: number, j: number, tol = 3) => {+ const a = boxes[i], b = boxes[j];+ const ov = [0, 1, 2].map((k) => Math.min(a.max[k], b.max[k]) - Math.max(a.min[k], b.min[k]));+ return ov.every((o) => o > -tol) && ov.filter((o) => o > 2).length >= 2;+ };+ let floating = 0;+ parts.forEach((p, i) => {+ const onFloor = boxes[i].min[1] < 3;+ if (!onFloor && !parts.some((_, j) => j !== i && touching(i, j))) {+ floating++;+ if (issues.length < 8) issues.push(`Part ${p.id} (${p.name}) doesn't touch any other part or the floor.`);+ }+ });+ let clashes = 0;+ for (let i = 0; i < parts.length; i++)+ for (let j = 0; j < i; j++) {+ const a = boxes[i], b = boxes[j];+ const ov = [0, 1, 2].map((k) => Math.min(a.max[k], b.max[k]) - Math.max(a.min[k], b.min[k]));+ if (ov.every((o) => o > 8)) {+ const vol = ov[0] * ov[1] * ov[2];+ const small = Math.min(...[a, b].map((x) => (x.max[0] - x.min[0]) * (x.max[1] - x.min[1]) * (x.max[2] - x.min[2])));+ if (vol > small * 0.3) {+ clashes++;+ if (issues.length < 8) issues.push(`Parts ${parts[i].id} and ${parts[j].id} sit inside each other.`);+ }+ }+ }+ const bad = floating > Math.max(1, parts.length * 0.25) || clashes > Math.max(1, parts.length * 0.2);+ return { ok: !bad && parts.length >= 2, issues };+}++/* ---------- entry ---------- */++export interface ScanResult {+ spec: ProductSpec | null;+ check: ScanCheck;+ raw?: unknown;+}++/** Turn model output into a product spec with a custom plan. Returns the problems found so the model can fix them. */+export function parseScan(raw: unknown): ScanResult {+ const r = Root.safeParse(raw);+ if (!r.success) return { spec: null, check: { ok: false, issues: ["The reply didn't match the JSON shape: it needs name, parts and steps."] } };+ const v = r.data;++ const parts: CustomPart[] = [];+ const ids = new Set<string>();+ for (const x of v.parts.slice(0, 80)) {+ const p = Part.safeParse(x);+ if (!p.success) continue;+ let id = p.data.id.trim() || `P${parts.length + 1}`;+ while (ids.has(id)) id += "'";+ ids.add(id);+ const size = p.data.size.map((n) => Math.min(3200, Math.max(0.1, Math.abs(n)))) as Vec3;+ const label = p.data.label?.trim();+ parts.push({ id, label: label && label.length <= 3 ? label : undefined, name: p.data.name || "Part", size, pos: p.data.pos, shape: p.data.shape, material: p.data.material as PartMaterial | undefined });+ }+ if (!parts.length) return { spec: null, check: { ok: false, issues: ["No usable parts: each needs id, name, size [w,h,d] and pos [x,y,z] in mm."] } };++ const idMap = new Map<string, string>();+ for (const p of parts) idMap.set(p.id.toLowerCase(), p.id);+ const ref = (s: string) => idMap.get(s.trim().toLowerCase());++ const steps: CustomStep[] = [];+ for (const x of v.steps.slice(0, 40)) {+ const st = Step.safeParse(x);+ if (!st.success) continue;+ const fixes: CustomFix[] = [];+ for (const f of st.data.fix ?? []) {+ const ff = Fix.safeParse(f);+ if (!ff.success) continue;+ const kind = hwKind(ff.data.kind);+ if (!kind) continue;+ const count = Math.round(ff.data.count);+ if (!(count > 0)) continue;+ fixes.push({ kind, count: Math.min(48, count), len: ff.data.len, dia: ff.data.dia, to: (ff.data.to ?? []).map(ref).filter((id): id is string => !!id) });+ }+ steps.push({+ title: st.data.title,+ detail: st.data.detail || undefined,+ add: (st.data.add ?? []).map(ref).filter((id): id is string => !!id),+ fix: fixes,+ tools: [...new Set((st.data.tools ?? []).map(tool).filter((t): t is ToolId => !!t))],+ people: (st.data.people ?? 1) >= 2 ? 2 : 1,+ pose: pose(st.data.pose),+ warnings: [...new Set((st.data.warnings ?? []).map(warn).filter((w): w is WarnId => !!w))],+ });+ }++ scaleFix(parts, v.size);+ for (const p of parts) p.size = p.size.map((n) => Math.min(3200, Math.max(2, round1(n)))) as Vec3;+ ground(parts);+ snap(parts, steps.flatMap((s) => s.add ?? []));+ ground(parts);+ const check = checkScan(parts);++ const boxes = parts.map(boxOf);+ const span = (k: number) => Math.max(...boxes.map((b) => b.max[k])) - Math.min(...boxes.map((b) => b.min[k]));+ const size = { w: Math.max(5, Math.round(span(0) / 10)), h: Math.max(5, Math.round(span(1) / 10)), d: Math.max(5, Math.round(span(2) / 10)) };+ const name = v.name || "My build";+ const spec: ProductSpec = {+ name: name.slice(0, 40),+ brand: v.brand || undefined,+ variant: v.variant || v.category || "Your build",+ category: v.category || "Furniture",+ archetype: "custom",+ size,+ minutes: Math.round(Math.min(480, Math.max(5, v.minutes ?? 30 + steps.length * 4))),+ people: (v.people ?? 1) >= 2 || steps.some((s) => s.people === 2) ? 2 : 1,+ difficulty: (v.difficulty ?? 2) >= 3 ? 3 : (v.difficulty ?? 2) <= 1 ? 1 : 2,+ source: "scan",+ custom: { parts, steps, fromCover: v.fromCover || undefined },+ watchOut: v.watchOut?.map(clean).filter(Boolean).slice(0, 2),+ };+ return { spec, check, raw };+}++/** When the model's geometry can't be saved, fall back to the closest simple type with the same name and size. */+export function fallbackSpec(raw: unknown): ProductSpec | null {+ const r = raw as Record<string, unknown> | null;+ if (!r || typeof r !== "object") return null;+ const arch = String(r.archetype ?? "");+ const archetype = ["shelf", "drawers", "table", "bed", "cabinet", "seat", "sofa"].includes(arch) ? arch : "shelf";+ const spec = parseSpec({ ...r, archetype, size: r.size ?? { w: 60, h: 80, d: 40 }, name: String(r.name ?? "My build") });+ if (!spec) return null;+ return { ...spec, source: "scan", brand: typeof r.brand === "string" ? clean(r.brand) : undefined };+}diff --git a/src/lib/scan/prompts.ts b/src/lib/scan/prompts.tsnew file mode 100644index 0000000..e301b74--- /dev/null+++ b/src/lib/scan/prompts.ts@@ -0,0 +1,84 @@+export const PAGE_PROMPT = `You are reading one photo of a page from a product assembly manual. It can be furniture or anything else that gets assembled, from any brand. Report what is on this page as JSON only, no prose.++{+ "kind": "cover" | "parts" | "hardware" | "tools" | "steps" | "warnings" | "other",+ "product": { "name": "", "brand": "", "type": "", "size": "" },+ "parts": [{ "label": "1", "name": "side panel", "qty": 2, "size": "60 x 30 x 1.8 cm", "notes": "" }],+ "hardware": [{ "label": "A", "kind": "dowel", "qty": 8, "size": "8 x 30 mm" }],+ "tools": ["Phillips screwdriver"],+ "steps": [{ "n": 3, "shows": "what happens in the drawing, in one or two plain sentences", "parts": ["1", "2"], "hardware": [{ "label": "A", "qty": 4 }], "people": 1, "orientation": "upright | upside down | lying on its back | face down | on its side" }],+ "warnings": ["two people needed"]+}++Rules:+- Only include what you can actually see on this page. Leave out empty fields.+- Hardware kinds: dowel, cam bolt, cam lock, screw, nail, shelf pin, bolt, leg bolt, hinge, knob, handle, wall bracket, felt pad, plate, other.+- For steps, say plainly where things go: on top, underneath, left, right, front or back, and which parts touch.+- Read part sizes from any dimension lines or numbers printed next to the drawings.+- If the photo shows the box or the finished product rather than a page, use kind "cover", and describe its shape in product.type, like "low media stand with two shelves and a vertical divider, about 70 cm wide".`;++export const PLAN_PROMPT = `You turn an assembly manual into data for an animated 3D step by step guide. You get notes read from photos of the manual's pages, in order, and maybe a name the person typed.++Reply with JSON only, no prose:+{+ "name": "LOOP",+ "brand": "Nordwood",+ "variant": "Record player stand",+ "category": "Media stand",+ "size": { "w": 70, "h": 66, "d": 40 },+ "minutes": 35,+ "people": 1,+ "difficulty": 2,+ "archetype": "shelf",+ "fromCover": false,+ "parts": [ { "id": "A", "label": "1", "name": "Side panel", "size": [18, 660, 400], "pos": [-341, 330, 0], "shape": "box", "material": "board" } ],+ "steps": [ { "title": "Tap the dowels into one side", "detail": "Lay it flat with the holes facing up.", "add": [], "fix": [ { "kind": "dowel", "count": 4, "to": ["A"] } ], "tools": ["hammer"], "people": 1, "pose": "upright", "warnings": ["floor"] } ],+ "watchOut": ["One short, common mistake with this product."]+}++Fields:+- name: the product name as printed. brand: the maker. variant: a short plain description. size: outer size in centimetres.+- difficulty: 1, 2 or 3. people: 2 only if a step really needs a second person.+- archetype: the closest of shelf, drawers, table, bed, cabinet, seat, sofa. It is only a backup.++Geometry, read this carefully:+- Units are millimetres.+- One entry per physical piece. Two identical side panels are two entries with different ids and the same label.+- size is [width, height, depth] of the piece as it sits in the FINISHED product. A side panel 18 thick, 660 tall and 400 deep is [18, 660, 400]. A top is [664, 18, 400].+- pos is the centre of the piece in the finished product. y is the height above the floor, x runs left to right seen from the front, z runs from the back (negative) to the front (positive). The product is centred on x = 0 and z = 0 and stands on y = 0.+- Pieces that are joined touch face to face exactly, with no gap and no overlap. Do the arithmetic for every piece: if sides 18 thick stand at x = -341 and x = 341, their inner faces are at -332 and 332, so a top that fits between them is 664 wide.+- Legs, rails, slats and rods are boxes too. Use "shape": "cyl" for round ones, with size [diameter, length, diameter] when upright or [length, diameter, diameter] when lying along x.+- materials: board (particleboard, MDF, plywood), fiber (thin hardboard backs and drawer bottoms), wood (solid wood, legs, slats), metal, soft (cushions, mattresses).+- Leave out hardware and packaging. At most 60 parts. If there are many identical slats, keep up to 12.++Steps:+- Follow the manual's own order. Write each title as one short instruction, under 60 characters. detail is one or two short sentences. Never use em dashes or en dashes.+- add lists the ids of pieces that join the product in that step. Every piece is added exactly once, in the first step that uses it.+- fix lists the hardware used in that step and how many. kind is one of: dowel, camScrew (cam bolt or connecting screw), cam (cam lock disc), screw, nail, pin (shelf pin), bolt (allen bolt or machine screw), legScrew (double ended leg bolt), hinge, knob, handle, bracket (wall fixing), glide (felt pad), plate. Use "to" with the ids it goes into when the manual makes that clear. Add len and dia in mm when they are printed.+- pose is how the product lies while you work: upright, upside_down, on_back (front facing up), face_down (back facing up), on_left_side, on_right_side.+- tools: allen, screwdriver, flathead, hammer, drill, wrench, level, tape, pencil, knife.+- warnings: two (needs two people), floor (work on a soft surface), loose (don't fully tighten yet), hand (hand tight only), wall (fix it to the wall), tip (can tip over), square (check it is square), face (mind which way the finished side faces).+- Usually 6 to 20 steps.++If you only have the cover or a photo of the product, design the most typical assembly for that exact product, with the usual pieces, hardware and steps for its shape and size, and set "fromCover": true.++Example, a small bedside table:+{"name":"KUBO","brand":"Acme","variant":"Bedside table","category":"Bedside table","size":{"w":40,"h":50,"d":35},"minutes":25,"people":1,"difficulty":1,"archetype":"cabinet",+"parts":[{"id":"A","label":"1","name":"Side panel","size":[16,500,350],"pos":[-192,250,0]},{"id":"B","label":"1","name":"Side panel","size":[16,500,350],"pos":[192,250,0]},{"id":"C","label":"2","name":"Top","size":[368,16,350],"pos":[0,492,0]},{"id":"D","label":"3","name":"Bottom","size":[368,16,350],"pos":[0,58,0]},{"id":"E","label":"4","name":"Back panel","size":[396,496,3],"pos":[0,252,-176.5],"material":"fiber"}],+"steps":[{"title":"Tap the dowels into the top and bottom","fix":[{"kind":"dowel","count":8,"to":["C","D"]}],"tools":["hammer"]},+{"title":"Fit the top and bottom to one side","add":["A","C","D"],"fix":[{"kind":"camScrew","count":4}],"pose":"on_back"},+{"title":"Lock the cam locks","fix":[{"kind":"cam","count":4}],"tools":["screwdriver"],"pose":"on_back"},+{"title":"Add the other side","add":["B"],"fix":[{"kind":"camScrew","count":4},{"kind":"cam","count":4}],"tools":["screwdriver"],"pose":"on_back"},+{"title":"Nail on the back panel","detail":"Start at the corners.","add":["E"],"fix":[{"kind":"nail","count":12}],"tools":["hammer"],"pose":"face_down","warnings":["square"]},+{"title":"Stand it up","pose":"upright"}]}+The top (368 wide) fits between the sides, whose inner faces are at x = -184 and 184. The back panel sits behind the sides, touching their back edges at z = -175.`;++export function planInput(pages: unknown[], hint: string) {+ const lines = [hint ? `The person says it is: ${hint}` : "The person didn't type a name.", `Pages read, in order (${pages.length}):`];+ pages.forEach((p, i) => lines.push(`Page ${i + 1}: ${JSON.stringify(p)}`));+ return lines.join("\n");+}++export function repairInput(issues: string[]) {+ return `Some parts don't fit together yet:\n${issues.map((x) => `- ${x}`).join("\n")}\nFix the sizes and positions so joined pieces touch face to face, then reply with the full corrected JSON only.`;+}diff --git a/src/lib/scan/sample.ts b/src/lib/scan/sample.tsnew file mode 100644index 0000000..37fd324--- /dev/null+++ b/src/lib/scan/sample.ts@@ -0,0 +1,39 @@+import type { ProductSpec } from "../types";++/** A hand-written scan result, used by the dev-only mock and tests. A record player stand from a made-up brand. */+export const SAMPLE_SCAN: ProductSpec = {+ name: "LOOP",+ brand: "Nordwood",+ variant: "Record player stand",+ category: "Media stand",+ archetype: "custom",+ size: { w: 70, h: 66, d: 40 },+ minutes: 35,+ people: 1,+ difficulty: 2,+ source: "scan",+ custom: {+ parts: [+ { id: "S1", label: "1", name: "Side panel", size: [18, 660, 400], pos: [-341, 330, 0] },+ { id: "S2", label: "1", name: "Side panel", size: [18, 660, 400], pos: [341, 330, 0] },+ { id: "T", label: "2", name: "Top", size: [664, 18, 400], pos: [0, 651, 0] },+ { id: "M", label: "3", name: "Shelf", size: [664, 18, 380], pos: [0, 330, -10] },+ { id: "B", label: "4", name: "Bottom", size: [664, 18, 380], pos: [0, 60, -10] },+ { id: "D", label: "5", name: "Record divider", size: [18, 252, 380], pos: [0, 195, -10] },+ { id: "R", label: "6", name: "Back rail", size: [664, 80, 18], pos: [0, 602, -191] },+ { id: "P", label: "7", name: "Plinth", size: [664, 51, 18], pos: [0, 25.5, 191] },+ ],+ steps: [+ { title: "Tap the dowels into one side", detail: "Lay the side flat with the holes facing up.", fix: [{ kind: "dowel", count: 6, to: ["S1"] }], tools: ["hammer"], warnings: ["floor"] },+ { title: "Fit the top, shelf and bottom", detail: "Press each panel onto the dowels. The holes face the side.", add: ["S1", "T", "M", "B"], fix: [{ kind: "camScrew", count: 6 }], pose: "+z" },+ { title: "Lock the cam locks", detail: "Arrow towards the bolt, then turn clockwise until it bites.", fix: [{ kind: "cam", count: 6, to: ["T", "M", "B"] }], pose: "+z" },+ { title: "Screw in the record divider", detail: "It sits in the middle of the bottom shelf.", add: ["D"], fix: [{ kind: "screw", count: 4, len: 30 }], pose: "+z" },+ { title: "Add the other side", add: ["S2"], fix: [{ kind: "dowel", count: 6 }, { kind: "camScrew", count: 6 }], pose: "+z" },+ { title: "Lock the other cams", fix: [{ kind: "cam", count: 6, to: ["S2"] }], pose: "+z" },+ { title: "Screw on the back rail", detail: "It keeps the stand from wobbling.", add: ["R"], fix: [{ kind: "screw", count: 4, len: 40 }], pose: "-z" },+ { title: "Fit the plinth", add: ["P"], fix: [{ kind: "dowel", count: 2 }], pose: "-z" },+ { title: "Stand it up", detail: "Lift from the top and set it down on all four corners.", pose: "+y" },+ { title: "Stick on the felt pads", fix: [{ kind: "glide", count: 4 }], pose: "+y" },+ ],+ },+};diff --git a/src/lib/scan/share.ts b/src/lib/scan/share.tsnew file mode 100644index 0000000..190c788--- /dev/null+++ b/src/lib/scan/share.ts@@ -0,0 +1,28 @@+import type { ProductSpec } from "../types";+import { parseScan } from "./parse";++/** Pack a scanned guide into a link, so it opens on another device without a server copy. */+export async function encodeSpec(spec: ProductSpec): Promise<string> {+ const bytes = new TextEncoder().encode(JSON.stringify(spec));+ const cs = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate-raw"));+ const buf = new Uint8Array(await new Response(cs).arrayBuffer());+ let bin = "";+ for (let i = 0; i < buf.length; i++) bin += String.fromCharCode(buf[i]);+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++export async function decodeSpec(s: string): Promise<ProductSpec | null> {+ try {+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");+ const bin = atob(b64 + "===".slice((b64.length + 3) % 4));+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));+ const ds = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));+ const raw = JSON.parse(await new Response(ds).text()) as ProductSpec;+ if (!raw || raw.archetype !== "custom" || !raw.custom?.parts?.length) return null;+ // a link is someone else's data: run it through the same checks as a fresh scan+ const r = parseScan({ ...raw, parts: raw.custom.parts, steps: raw.custom.steps, fromCover: raw.custom.fromCover });+ return r.spec ? { ...r.spec, variant: raw.variant ?? r.spec.variant } : null;+ } catch {+ return null;+ }+}diff --git a/src/lib/search.ts b/src/lib/search.tsnew file mode 100644index 0000000..c0343f5--- /dev/null+++ b/src/lib/search.ts@@ -0,0 +1,122 @@+import { PRODUCTS, toSpec, type CatalogEntry } from "./catalog";+import { fold } from "./fold";+import { KIND_DEFAULT_SIZE, KIND_LABELS, specFor, type Kind } from "./products";+import type { Archetype, ProductSpec } from "./types";++export { fold };++export function slugify(s: string) {+ return fold(s).replace(/\s+/g, "-").slice(0, 60) || "product";+}++const CATEGORY_WORDS: [Kind, string[]][] = [+ ["shoe", ["shoe", "shoes", "shoe cabinet", "shoe rack"]],+ ["nightstand", ["nightstand", "bedside", "night stand"]],+ ["chest", ["drawer", "drawers", "chest", "dresser"]],+ ["cube", ["cube", "cubes"]],+ ["bookcase", ["bookcase", "bookshelf", "shelf", "shelving", "shelves"]],+ ["tv", ["tv", "media"]],+ ["coffee", ["coffee"]],+ ["desk", ["desk"]],+ ["dining", ["dining", "table", "kitchen table"]],+ ["bed", ["bed", "bedframe", "daybed", "bunk"]],+ ["wardrobe", ["wardrobe", "closet", "armoire"]],+ ["sideboard", ["sideboard", "buffet"]],+ ["cabinet", ["cabinet", "cupboard", "vitrine", "display"]],+ ["sofa", ["sofa", "couch", "loveseat", "sectional"]],+ ["armchair", ["armchair", "wing chair", "recliner"]],+ ["chair", ["chair", "chairs"]],+ ["stool", ["stool", "stools"]],+ ["bench", ["bench"]],+];++export function kindOf(q: string): Kind | null {+ const f = " " + fold(q) + " ";+ for (const [k, words] of CATEGORY_WORDS) if (words.some((w) => f.includes(" " + w + " ") || f.includes(" " + w + "s "))) return k;+ return null;+}++export function categoryOf(q: string): Archetype | null {+ const k = kindOf(q);+ return k ? specFor(k, "X", "", 1, 1, 1).archetype : null;+}++function lev(a: string, b: string) {+ if (Math.abs(a.length - b.length) > 2) return 9;+ const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);+ for (let j = 1; j <= b.length; j++) dp[0][j] = j;+ for (let i = 1; i <= a.length; i++)+ for (let j = 1; j <= b.length; j++) dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));+ return dp[a.length][b.length];+}++export interface Hit {+ entry: CatalogEntry;+ score: number;+}++export function searchCatalog(q: string, limit = 8): Hit[] {+ const f = fold(q);+ if (!f) return [];+ const tokens = f.split(" ");+ const kind = kindOf(q);+ const hits: Hit[] = [];+ for (const e of PRODUCTS) {+ const name = fold(e.name);+ const nameKey = name.replace(/\s+/g, "");+ const hay = fold([e.name, e.variant, e.category, ...(e.keywords ?? [])].join(" "));+ const words = hay.split(" ");+ let score = 0;+ const first = tokens[0];+ const joined = f.replace(/\s+/g, "");+ if (name === f || nameKey === joined) score += 100;+ else if (name.split(" ").includes(first) || nameKey === first) score += 80;+ else if (first.length >= 2 && name.split(" ").some((w) => w.startsWith(first))) score += 60;+ else if (first.length >= 4 && lev(first, nameKey) === 1) score += 52;+ else if (first.length >= 6 && lev(first, nameKey) === 2) score += 42;+ else if (first.length >= 3 && words.some((w) => w.startsWith(first))) score += 20;+ for (const t of tokens.slice(1)) if (t.length && words.some((w) => w.startsWith(t) || (t.length > 2 && w.includes(t)))) score += 12;+ if (kind) {+ const cat = fold(e.category);+ const kw = CATEGORY_WORDS.find(([k]) => k === kind)![1];+ const padded = ` ${cat} ${hay} `;+ if (kw.some((w) => padded.includes(` ${w} `) || padded.includes(` ${w}s `))) score += 14;+ else score -= 30;+ }+ if (e.checked) score += 3;+ if (e.featured) score += 2;+ if (score > 15) hits.push({ entry: e, score });+ }+ hits.sort((a, b) => b.score - a.score);+ return hits.slice(0, limit);+}++/** Best confident match, or null. */+export function matchCatalog(q: string): ProductSpec | null {+ const [a, b] = searchCatalog(q, 2);+ if (!a || a.score < 50) return null;+ // a typo match only counts when it is clearly the best one+ if (a.score < 60 && b && b.score >= a.score - 4 && fold(b.entry.name) !== fold(a.entry.name)) return null;+ return toSpec(a.entry);+}++/** A typical build for a product we don't know, from the kind of furniture it is. */+export function specForKind(kind: Kind, name: string): ProductSpec {+ const [w, h, d] = KIND_DEFAULT_SIZE[kind];+ const label = KIND_LABELS.find((k) => k.kind === kind)?.label ?? "Furniture";+ return { ...specFor(kind, name.toUpperCase(), label, w, h, d), source: "guess" };+}++export function guessSpec(q: string): ProductSpec | null {+ const kind = kindOf(q);+ if (!kind) return null;+ const words = q.trim().split(/\s+/);+ const name = words.find((w) => w.length > 2 && !kindOf(w)) ?? words[0];+ return specForKind(kind, name);+}++export const FEATURED = PRODUCTS.filter((e) => e.featured);+export const POPULAR = ["kallax-2x2", "billy-80x202", "malm-3-drawers", "lack-side-table", "linnmon-adils-desk", "malm-bed-160", "brimnes-wardrobe", "hemnes-3-drawers", "frosta-stool"]+ .map((s) => PRODUCTS.find((e) => e.slug === s)!)+ .filter(Boolean);+export const PRODUCT_COUNT = new Set(PRODUCTS.map((p) => fold(p.name) + "|" + p.category)).size;diff --git a/src/lib/site.ts b/src/lib/site.tsnew file mode 100644index 0000000..ff5b1b9--- /dev/null+++ b/src/lib/site.ts@@ -0,0 +1,2 @@+export const GITHUB_REPO = process.env.NEXT_PUBLIC_GITHUB_REPO ?? "Luffixos/bygga";+export const GITHUB_URL = `https://github.com/${GITHUB_REPO}`;diff --git a/src/lib/spec.ts b/src/lib/spec.tsnew file mode 100644index 0000000..1b8c5c9--- /dev/null+++ b/src/lib/spec.ts@@ -0,0 +1,172 @@+import { z } from "zod";+import type { ProductSpec } from "./types";++const num = (lo: number, hi: number) => z.coerce.number().transform((n) => Math.min(hi, Math.max(lo, n)));+const optNum = (lo: number, hi: number) => num(lo, hi).optional().catch(undefined);+const optBool = z.coerce.boolean().optional().catch(undefined);+const optEnum = <T extends [string, ...string[]]>(v: T) => z.enum(v).optional().catch(undefined);++const Spec = z.object({+ found: z.boolean().optional(),+ name: z.string().min(1).max(40),+ variant: z.string().max(60).catch(""),+ category: z.string().max(40).catch("Furniture"),+ archetype: z.enum(["shelf", "drawers", "table", "bed", "cabinet", "seat", "sofa"]),+ size: z.object({ w: num(20, 320), h: num(20, 260), d: num(15, 240) }),+ minutes: num(5, 360).catch(45),+ people: z.coerce.number().transform((n) => (n >= 2 ? 2 : 1)).catch(1),+ difficulty: z.coerce.number().transform((n) => (n >= 3 ? 3 : n <= 1 ? 1 : 2)).catch(2),+ material: z.string().max(80).optional().catch(undefined),+ shelf: z+ .object({+ style: optEnum(["grid", "bookcase"]),+ cols: optNum(1, 5),+ rows: optNum(1, 5),+ shelves: optNum(0, 6),+ fixedShelf: optBool,+ back: optBool,+ plinth: optBool,+ outer: optNum(12, 50),+ inner: optNum(12, 30),+ })+ .partial()+ .optional()+ .catch(undefined),+ drawers: z+ .object({+ cols: z.coerce.number().transform((n) => (n >= 2 ? 2 : 1)).optional().catch(undefined),+ rows: optNum(1, 6),+ knobs: optEnum(["none", "knob", "bar"]),+ plinth: optBool,+ thickness: optNum(12, 24),+ })+ .partial()+ .optional()+ .catch(undefined),+ table: z+ .object({+ topThickness: optNum(15, 60),+ legs: optEnum(["square", "round"]),+ legSize: optNum(25, 90),+ shelf: optBool,+ attach: optEnum(["screw", "plate", "apron"]),+ })+ .partial()+ .optional()+ .catch(undefined),+ bed: z+ .object({+ mattressW: optNum(70, 200),+ mattressL: optNum(180, 220),+ headH: optNum(40, 140),+ footH: optNum(0, 100),+ slats: optNum(8, 30),+ centerBeam: optBool,+ })+ .partial()+ .optional()+ .catch(undefined),+ cabinet: z+ .object({+ fronts: optEnum(["doors", "tilt"]),+ compartments: optNum(1, 5),+ doors: z.coerce.number().transform((n) => (n >= 2 ? 2 : n <= 0 ? 0 : 1)).optional().catch(undefined),+ shelves: optNum(0, 5),+ rail: optBool,+ plinth: optBool,+ handles: optEnum(["knob", "bar", "none"]),+ thickness: optNum(12, 25),+ })+ .partial()+ .optional()+ .catch(undefined),+ seat: z+ .object({+ kind: optEnum(["stool", "chair", "bench"]),+ seat: optEnum(["round", "square"]),+ seatH: optNum(25, 85),+ backH: optNum(60, 120),+ stretchers: optBool,+ splay: optBool,+ })+ .partial()+ .optional()+ .catch(undefined),+ sofa: z+ .object({+ seats: optNum(1, 4),+ arms: optEnum(["wide", "slim", "none"]),+ legs: optEnum(["round", "block"]),+ })+ .partial()+ .optional()+ .catch(undefined),+ tips: z.record(z.string(), z.string().max(220)).optional().catch(undefined),+ watchOut: z.array(z.string().max(200)).max(4).optional().catch(undefined),+});++export function parseSpec(raw: unknown): ProductSpec | null {+ const r = Spec.safeParse(raw);+ if (!r.success) return null;+ const v = r.data;+ const clean = (s: string) => s.replace(/\s*[\u2012-\u2015]\s*/g, ", ").replace(/\s+,/g, ",").trim();+ const spec: ProductSpec = {+ name: clean(v.name).toUpperCase(),+ variant: clean(v.variant || v.category),+ category: clean(v.category),+ archetype: v.archetype,+ size: v.size,+ minutes: Math.round(v.minutes),+ people: v.people as 1 | 2,+ difficulty: v.difficulty as 1 | 2 | 3,+ material: v.material ? clean(v.material) : undefined,+ source: "ai",+ };+ const key = v.archetype;+ const params = (v as Record<string, unknown>)[key];+ if (params && typeof params === "object") (spec as unknown as Record<string, unknown>)[key] = stripUndefined(params as Record<string, unknown>);+ if (v.tips) {+ const allowed = ["general", "frame", "back", "shelves", "drawers", "doors", "legs", "slats", "anchor"];+ spec.tips = Object.fromEntries(Object.entries(v.tips).filter(([k]) => allowed.includes(k)).map(([k, t]) => [k, clean(t)]));+ }+ if (v.watchOut) spec.watchOut = v.watchOut.map(clean).filter(Boolean).slice(0, 3);+ return spec;+}++function stripUndefined(o: Record<string, unknown>) {+ return Object.fromEntries(Object.entries(o).filter(([, x]) => x !== undefined));+}++export const SPEC_PROMPT = `You help people assemble IKEA flat pack furniture. Given what a person typed (usually a product name, sometimes with a size), identify the product and describe it so our generator can draw an assembly guide.++Reply with JSON only, no prose. Shape:+{+ "found": true,+ "name": "KALLAX", // product name in capitals as printed on the box+ "variant": "Shelving unit, 2 x 4", // short, human readable+ "category": "Shelving unit",+ "archetype": "shelf" | "drawers" | "table" | "bed" | "cabinet" | "seat" | "sofa",+ "size": { "w": 77, "h": 147, "d": 39 }, // outer size in centimetres (for beds: d = length)+ "minutes": 60, // realistic assembly time for one person+ "people": 1 | 2, // 2 if lifting or holding needs a second person+ "difficulty": 1 | 2 | 3,+ "material": "Particleboard",+ // exactly ONE of these objects, matching the archetype:+ "shelf": { "style": "grid" | "bookcase", "cols": 2, "rows": 4, "shelves": 3, "fixedShelf": true, "back": true, "plinth": true, "outer": 16, "inner": 16 },+ "drawers": { "cols": 1 | 2, "rows": 3, "knobs": "none" | "knob" | "bar", "plinth": false, "thickness": 16 },+ "table": { "topThickness": 30, "legs": "square" | "round", "legSize": 50, "shelf": false, "attach": "screw" | "plate" | "apron" },+ "bed": { "mattressW": 160, "mattressL": 200, "headH": 100, "footH": 38, "slats": 17, "centerBeam": true },+ "cabinet": { "fronts": "doors" | "tilt", "compartments": 2, "doors": 0 | 1 | 2, "shelves": 2, "rail": true, "plinth": true, "handles": "knob" | "bar" | "none", "thickness": 18 },+ "seat": { "kind": "stool" | "chair" | "bench", "seat": "round" | "square", "seatH": 45, "backH": 90, "stretchers": false, "splay": true },+ "sofa": { "seats": 3, "arms": "wide" | "slim" | "none", "legs": "round" | "block" },+ "tips": { "frame": "...", "back": "...", "drawers": "...", "anchor": "..." }, // optional, 1 short practical sentence each, only if you are confident+ "watchOut": ["..."] // optional, max 2 common mistakes people make with THIS product+}++Rules:+- grid = cube shelving like KALLAX or EKET walls. bookcase = sides with shelves like BILLY or HEMNES bookcase.+- Wardrobes, sideboards, TV units with doors and cabinets are "cabinet". Shoe cabinets with fronts that tip open (BISSA, HEMNES, STÄLL, TRONES) are "cabinet" with "fronts": "tilt" and one compartment per front.+- Desks and TV benches without doors are "table". Nightstands with drawers are "drawers". Sofas and upholstered armchairs are "sofa".+- Use the most common size if the person didn't give one.+- If it is not an IKEA product that needs assembly (lamps, textiles, plants, food, or unknown), reply {"found": false, "suggestions": ["NAME", "NAME"]} with up to 3 real product names they might mean.+- Never use em dashes or en dashes. Keep every sentence short and plain.`;diff --git a/src/lib/store.ts b/src/lib/store.tsnew file mode 100644index 0000000..61f232b--- /dev/null+++ b/src/lib/store.ts@@ -0,0 +1,93 @@+import type { ProductSpec } from "./types";++export type Phase = "cover" | "tools" | "parts" | "steps" | "done";++export interface Progress {+ slug: string;+ name: string;+ variant: string;+ phase: Phase;+ step: number;+ steps: number;+ tools: string[];+ parts: string[];+ missing?: string[];+ category?: string;+ minutes?: number;+ people?: 1 | 2;+ startedAt?: number;+ doneAt?: number;+ updatedAt: number;+ spec?: ProductSpec;+}++const KEY = "bygga:builds";++function read(): Record<string, Progress> {+ try {+ return JSON.parse(localStorage.getItem(KEY) || "{}");+ } catch {+ return {};+ }+}++function write(all: Record<string, Progress>) {+ try {+ localStorage.setItem(KEY, JSON.stringify(all));+ } catch {+ /* storage full or blocked */+ }+}++export function loadProgress(slug: string): Progress | null {+ return read()[slug] ?? null;+}++export function saveProgress(p: Progress) {+ const all = read();+ all[p.slug] = { ...p, updatedAt: Date.now() };+ write(all);+}++export function removeProgress(slug: string) {+ const all = read();+ delete all[slug];+ write(all);+}++export function listProgress(): Progress[] {+ return Object.values(read()).sort((a, b) => b.updatedAt - a.updatedAt);+}++const SPEC_KEY = "bygga:spec:";+export function cacheSpec(slug: string, spec: ProductSpec) {+ try {+ localStorage.setItem(SPEC_KEY + slug, JSON.stringify(spec));+ } catch {+ /* ignore */+ }+}+export function cachedSpec(slug: string): ProductSpec | null {+ try {+ const s = localStorage.getItem(SPEC_KEY + slug);+ return s ? JSON.parse(s) : null;+ } catch {+ return null;+ }+}++export function getPref<T>(k: string, d: T): T {+ try {+ const v = localStorage.getItem("bygga:pref:" + k);+ return v ? (JSON.parse(v) as T) : d;+ } catch {+ return d;+ }+}+export function setPref(k: string, v: unknown) {+ try {+ localStorage.setItem("bygga:pref:" + k, JSON.stringify(v));+ } catch {+ /* ignore */+ }+}diff --git a/src/lib/together.ts b/src/lib/together.tsnew file mode 100644index 0000000..55ed4cb--- /dev/null+++ b/src/lib/together.ts@@ -0,0 +1,123 @@+import "server-only";++const BASE = "https://api.together.xyz/v1";++export const MODELS = {+ plan: (process.env.TOGETHER_PLAN_MODEL ?? "openai/gpt-oss-120b,deepseek-ai/DeepSeek-V3.1,zai-org/GLM-5.2,meta-llama/Llama-3.3-70B-Instruct-Turbo").split(","),+ text: (process.env.TOGETHER_TEXT_MODEL ?? "openai/gpt-oss-120b,zai-org/GLM-5.2,deepseek-ai/DeepSeek-V3.1,meta-llama/Llama-3.3-70B-Instruct-Turbo").split(","),+ vision: (process.env.TOGETHER_VISION_MODEL ?? "Qwen/Qwen3-VL-32B-Instruct,Qwen/Qwen2.5-VL-72B-Instruct,meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8").split(","),+};++export function hasKey() {+ return !!process.env.TOGETHER_API_KEY?.trim();+}++type Content = string | ({ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } })[];+export interface Msg {+ role: "system" | "user" | "assistant";+ content: Content;+}++interface ChatOpts {+ models: string[];+ messages: Msg[];+ json?: boolean;+ maxTokens?: number;+ temperature?: number;+ stream?: boolean;+ signal?: AbortSignal;+ /** The person's own key. Falls back to the server key. */+ key?: string;+ reasoning?: "low" | "medium" | "high";+}++export class TogetherError extends Error {+ constructor(+ message: string,+ public status: number,+ ) {+ super(message);+ }+}++/** Calls Together's chat completions, falling back through the model list when one is unavailable. */+export async function chat(o: ChatOpts): Promise<{ res: Response; model: string }> {+ const key = o.key?.trim() || process.env.TOGETHER_API_KEY?.trim();+ if (!key) throw new TogetherError("missing key", 401);+ let lastErr: TogetherError | null = null;+ for (const model of o.models.map((m) => m.trim()).filter(Boolean)) {+ const reasoning = model.includes("gpt-oss") ? { reasoning_effort: o.reasoning ?? "low" } : {};+ for (const withExtras of [true, false]) {+ const body = {+ model,+ messages: o.messages,+ max_tokens: o.maxTokens ?? 1400,+ temperature: o.temperature ?? 0.3,+ stream: !!o.stream,+ ...(o.json && withExtras ? { response_format: { type: "json_object" } } : {}),+ ...(withExtras ? reasoning : {}),+ };+ let res: Response;+ try {+ res = await fetch(`${BASE}/chat/completions`, {+ method: "POST",+ headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal: o.signal,+ });+ } catch (e) {+ lastErr = new TogetherError((e as Error).message, 502);+ break;+ }+ if (res.ok) return { res, model };+ const text = await res.text().catch(() => "");+ lastErr = new TogetherError(text.slice(0, 300) || res.statusText, res.status);+ if (res.status === 401 || res.status === 402 || res.status === 403 || res.status === 429) throw lastErr;+ // 400 may be an unsupported extra parameter: retry once without extras, otherwise move on+ if (res.status !== 400) break;+ }+ }+ throw lastErr ?? new TogetherError("no model available", 503);+}++export async function chatText(o: Omit<ChatOpts, "stream">) {+ const { res, model } = await chat(o);+ const j = await res.json();+ const text: string = j?.choices?.[0]?.message?.content ?? "";+ return { text, model };+}++export function extractJson(text: string): unknown {+ const t = text.replace(/<think>[\s\S]*?<\/think>/g, "").trim();+ const fence = t.match(/```(?:json)?\s*([\s\S]*?)```/);+ const body = fence ? fence[1] : t;+ const start = body.indexOf("{");+ const end = body.lastIndexOf("}");+ if (start < 0 || end < start) return null;+ try {+ return JSON.parse(body.slice(start, end + 1));+ } catch {+ return null;+ }+}++/** Tiny in-memory rate limiter per IP. */+const hits = new Map<string, number[]>();+export function rateLimited(ip: string, max = 20, windowMs = 60_000) {+ const now = Date.now();+ const arr = (hits.get(ip) ?? []).filter((t) => now - t < windowMs);+ arr.push(now);+ hits.set(ip, arr);+ if (hits.size > 5000) hits.clear();+ return arr.length > max;+}++/** A key the person pasted into the app, sent along with their request. Never stored or logged. */+export function userKey(req: Request) {+ const k = req.headers.get("x-together-key")?.trim() ?? "";+ return k.length >= 20 && k.length <= 200 && /^[\w.-]+$/.test(k) ? k : undefined;+}++export function ipOf(req: Request) {+ return req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || req.headers.get("x-real-ip") || "local";+}diff --git a/src/lib/types.ts b/src/lib/types.tsnew file mode 100644index 0000000..41c4b2c--- /dev/null+++ b/src/lib/types.ts@@ -0,0 +1,309 @@+export type Vec3 = [number, number, number];++export type Archetype = "shelf" | "drawers" | "table" | "bed" | "cabinet" | "seat" | "sofa" | "custom";++export interface ShelfParams {+ style: "grid" | "bookcase";+ cols: number;+ rows: number;+ shelves: number; // adjustable shelves (bookcase)+ fixedShelf: boolean;+ back: boolean;+ plinth: boolean;+ outer: number; // mm panel thickness of frame+ inner: number; // mm thickness of inner shelves/dividers+}++export interface DrawersParams {+ cols: 1 | 2;+ rows: number;+ knobs: "none" | "knob" | "bar";+ plinth: boolean;+ thickness: number;+}++export interface TableParams {+ topThickness: number;+ legs: "square" | "round";+ legSize: number;+ shelf: boolean;+ attach: "screw" | "plate" | "apron";+}++export interface BedParams {+ mattressW: number; // cm+ mattressL: number; // cm+ headH: number; // cm+ footH: number; // cm, 0 for none+ slats: number;+ centerBeam: boolean;+}++export interface CabinetParams {+ fronts: "doors" | "tilt";+ compartments: number;+ doors: 0 | 1 | 2;+ shelves: number;+ rail: boolean;+ plinth: boolean;+ handles: "knob" | "bar" | "none";+ thickness: number;+}++export interface SeatParams {+ kind: "stool" | "chair" | "bench";+ seat: "round" | "square";+ seatH: number; // cm+ backH: number; // cm (chair total height)+ stretchers: boolean;+ splay: boolean;+}++export interface SofaParams {+ seats: number;+ arms: "wide" | "slim" | "none";+ legs: "round" | "block";+}++/** A product read from someone's own manual: parts as boxes in the assembled product, steps that add them. */+export interface CustomPart {+ id: string;+ label?: string; // the manual's own part number or letter, when short+ name: string;+ size: Vec3; // mm along x (width), y (height), z (depth) as it sits in the finished product+ pos: Vec3; // mm, centre of the part; y up from the floor, x left to right, z back to front+ shape?: "box" | "cyl";+ material?: PartMaterial;+}++export interface CustomFix {+ kind: HwKind;+ count: number;+ len?: number;+ dia?: number;+ to?: string[]; // parts it goes into, when the manual says+}++export interface CustomStep {+ title: string;+ detail?: string;+ add?: string[];+ fix?: CustomFix[];+ tools?: ToolId[];+ people?: 1 | 2;+ pose?: Pose;+ warnings?: WarnId[];+}++export interface CustomParams {+ parts: CustomPart[];+ steps: CustomStep[];+ fromCover?: boolean;+}++export type TipKey =+ | "general"+ | "frame"+ | "back"+ | "shelves"+ | "drawers"+ | "doors"+ | "legs"+ | "slats"+ | "cushions"+ | "anchor";++export interface ProductSpec {+ name: string;+ variant: string;+ category: string;+ archetype: Archetype;+ size: { w: number; h: number; d: number }; // cm+ minutes: number;+ people: 1 | 2;+ difficulty: 1 | 2 | 3;+ material?: string;+ shelf?: Partial<ShelfParams>;+ drawers?: Partial<DrawersParams>;+ table?: Partial<TableParams>;+ bed?: Partial<BedParams>;+ cabinet?: Partial<CabinetParams>;+ seat?: Partial<SeatParams>;+ sofa?: Partial<SofaParams>;+ custom?: CustomParams;+ brand?: string;+ tips?: Partial<Record<TipKey, string>>;+ watchOut?: string[];+ source: "catalog" | "ai" | "guess" | "scan";+ slug?: string;+ variants?: { label: string; slug: string }[];+ siblings?: { label: string; slug: string }[];+}++/* ---------- generated plan ---------- */++export type PartMaterial = "board" | "fiber" | "wood" | "metal" | "soft";++export interface PartType {+ id: string;+ label: string; // letter+ name: string;+ size: Vec3; // mm, box extents or cylinder [dia, length, dia]+ shape: "box" | "cyl";+ material: PartMaterial;+ qty: number;+ extra?: boolean; // not in the box (e.g. mattress)+}++export type HwKind =+ | "dowel"+ | "camScrew"+ | "cam"+ | "screw"+ | "nail"+ | "pin"+ | "legScrew"+ | "bolt"+ | "plate"+ | "bracket"+ | "runner"+ | "knob"+ | "handle"+ | "hinge"+ | "glide"+ | "plug";++export interface HwType {+ id: string;+ kind: HwKind;+ name: string;+ spec: string;+ len: number;+ dia: number;+ qty: number;+ notIncluded?: boolean;+}++export interface Hole {+ p: Vec3;+ n: Vec3;+ r: number;+}++/** A display state of a part: from `step` on it sits at pos/rot inside `scene`. The last state is the assembled one. */+export interface PartState {+ step: number;+ scene: string;+ pos: Vec3;+ rot: Vec3;+ from?: Vec3; // approach offset in scene frame+ spin?: number; // revolutions about local Y while approaching+ delay: number;+}++export interface PartItem {+ key: string;+ kind: "part";+ ref: string;+ final: { pos: Vec3; rot: Vec3 };+ states: PartState[];+ holes: Hole[];+}++export interface HwItem {+ key: string;+ kind: "hw";+ ref: string;+ parent?: string; // part key (local coords) or none (scene coords)+ scene?: string;+ step: number;+ pos: Vec3;+ dir: Vec3; // insertion direction, pointing into the material+ twist?: number;+ travel: number;+ spin?: number;+ turn?: number;+ delay: number;+ scale?: number;+ preset?: boolean;+}++export type Item = PartItem | HwItem;++export type ToolId =+ | "allen"+ | "screwdriver"+ | "flathead"+ | "hammer"+ | "drill"+ | "level"+ | "tape"+ | "pencil"+ | "wrench"+ | "knife";++export type WarnId =+ | "two"+ | "loose"+ | "hand"+ | "wall"+ | "square"+ | "floor"+ | "face"+ | "tip";++export type Pose = "+y" | "-y" | "+z" | "-z" | "+x" | "-x";++export type StepKind =+ | "dowels"+ | "bolts"+ | "cams"+ | "nails"+ | "square"+ | "flip"+ | "standup"+ | "shelves"+ | "anchor"+ | "drawer"+ | "runners"+ | "legs"+ | "doors"+ | "hinges"+ | "slats"+ | "join"+ | "screws"+ | "cushions"+ | "general";++export interface Step {+ n: number;+ title: string;+ detail?: string;+ tools: ToolId[];+ people: 1 | 2;+ repeat?: number;+ scene: string;+ pose: Pose;+ warnings: WarnId[];+ kind: StepKind;+ check?: "square";+ wall?: boolean;+ quiet?: boolean;+ minutes: number;+}++export interface ToolNeed {+ id: ToolId;+ included?: boolean;+ optional?: boolean;+ why?: string;+}++export interface Plan {+ spec: ProductSpec;+ parts: PartType[];+ hardware: HwType[];+ items: Item[];+ steps: Step[];+ tools: ToolNeed[];+}diff --git a/src/lib/useMounted.ts b/src/lib/useMounted.tsnew file mode 100644index 0000000..fed6d3b--- /dev/null+++ b/src/lib/useMounted.ts@@ -0,0 +1,14 @@+"use client";++import { useSyncExternalStore } from "react";++const noop = () => () => {};++/** False during SSR and hydration, true once running in the browser. */+export function useMounted() {+ return useSyncExternalStore(+ noop,+ () => true,+ () => false,+ );+}diff --git a/src/lib/userKey.ts b/src/lib/userKey.tsnew file mode 100644index 0000000..2c318c2--- /dev/null+++ b/src/lib/userKey.ts@@ -0,0 +1,36 @@+"use client";++/** The person's own Together AI key. It lives only in this browser and rides along with AI requests. */+const K = "bygga:together-key";++export function getUserKey(): string {+ try {+ return localStorage.getItem(K) ?? "";+ } catch {+ return "";+ }+}++export function setUserKey(v: string) {+ try {+ if (v) localStorage.setItem(K, v.trim());+ else localStorage.removeItem(K);+ window.dispatchEvent(new Event("bygga:key"));+ } catch {+ /* storage blocked */+ }+}++export function keyHeaders(): Record<string, string> {+ const k = getUserKey();+ return k ? { "x-together-key": k } : {};+}++export function subscribeKey(cb: () => void) {+ window.addEventListener("bygga:key", cb);+ window.addEventListener("storage", cb);+ return () => {+ window.removeEventListener("bygga:key", cb);+ window.removeEventListener("storage", cb);+ };+}