Skip to content

Architecture

Claude edited this page Nov 30, 2026 · 17 revisions

Architecture

The app is a Next.js 15 static export (output: 'export') with React 18, raw Three.js (no react-three-fiber), Tailwind and a little Zustand. There's no backend and no runtime data fetching: everything runs in the browser, persistence is localStorage (and IndexedDB for the photo album, the floor-plan images and a Replace restore's safety copy), and sharing is a URL. Since 1.37.0 a service worker keeps a copy of the app's own files so it opens offline; it never holds the houses. The project is deliberately light on runtime dependencies; please open an issue before adding one.

This page is the map. For a file-by-file list see docs/architecture.md in the repository, and for the reasoning behind individual decisions docs/design-notes.md.

docs/architecture.md is kept honest by a unit test, lib/docs-drift.test.ts: it fails when a source file under components/room-organizer/, app/ or scripts/, or a root *.config.* file, has no line there, or when the furniture count it states (or the README's) differs from the catalogue. A new module gets its line in the same pull request.

Where the code lives

app/                      Next.js shell: layout (with the head script and the JavaScript-off notice), page, error boundaries, the 404 page, icons, the install manifest (which also opens .json house files in the installed app) and the committed fonts
docs/                     architecture.md (the module layout, file by file), design-notes.md, and changelog/<lang>.md: What's new in the other languages
scripts/                  the post-build steps (chunk preloads, CSP, licence notices, the offline service worker), What's new lines from the changelog, the bundle budget and smoke test, and the icon and people.glb generators
components/ui/            shadcn-style primitives (button, card, native select, …)
components/room-organizer/
  room-organizer.tsx      the orchestrator: wires hooks into contexts and composes the panels
  lib/                    pure domain logic
  three/                  Three.js scene builders
  hooks/                  React glue: state, scene lifecycle, interaction
  contexts/               React contexts for the editor and the selection
  panels/                 presentational UI
  canvas-2d/              the 2D renderer
  plotcraft/              the SVG icon set

The orchestrator

room-organizer.tsx wires the hooks into the contexts and composes the panels. It used to hold much of the editor's behaviour itself; since 1.32.0 that is split by seam into hooks, each with its own tests where it has logic of its own:

  • use-selection-actions.ts: the selection (primary, extras, the selected wall), group expansion and custom sets.
  • use-wall-draft.ts: the wall tool's draft: the anchor and snapped tip, a typed length, the room stamp in hand, reset on a tool or floor change.
  • use-item-commands.ts: rotate, twist, remove, duplicate, copy and paste, nudge and lock on the selection, with their refusals and cues.
  • use-scene-life.ts: what moves on its own: the walk and its exit, the walkers and the people model, the weather, the camera cones; since 1.35.0 also the clock the walkers read (a ref the view store writes, so a clock tick re-renders nothing), the door swinger for the player and the walkers, the lamp switch and the ambience.
  • use-start-challenge.ts: a challenge brief over the house through the whole-house load path, like use-load-template.ts.
  • use-house-loading.ts: the loads the editor makes on its own: the opening house (a share link's as a read-only tour), a toured house kept with Keep a copy, another tab's save, each by the load rules.
  • use-load-template.ts: a template over the house through the whole-house load path, shared by the Templates panel and the start chooser.
  • use-set-game-mode.ts: the DESIGN / FURNISH / EXPLORE switch with what it brings along, shared by the mode panel and the Getting started card.
  • useCameraPad (in use-camera-presets.ts): the camera pad's orbit and zoom.

New behaviour belongs in one of these, or a new hook, rather than back in the orchestrator.

The layers

The layering inside components/room-organizer/ is strict. Put new code in the lowest layer it can live in.

  • lib/: pure domain logic. No React, no Three.js. Types, the catalogue and constants, geometry and collision, snapping, schema migration and repair, persistence, the share-URL codec, themes, achievements, storeys, the site and street, dormers, stairs, version history and restore points, zones, the walkthrough's world (walk-world.ts: floors, treads and the lot; walk-collision.ts: furniture, shell and neighbour colliders; walk-spawn.ts; walk-interact.ts for seats), walker navigation (npc-path.ts, a grid with A*), the seats walkers can sit on, the end of a bed among them (npc-seats.ts), their needs (npc-needs.ts: hunger, energy and fun running down, what meets each, and the weighted pick of where to go) and the hand-off that makes the player and the walkers each other's obstacles (npc-bodies.ts: the walkers' boxes for the player's collision, the player's spot and seat for the walkers and the camera cones), how a door swings in EXPLORE (door-swing.ts: openness by distance, the eased angle, the side away from the walker), room types and scores for Statistics (room-score.ts), the photo mode switch and the photo's size and file name (photo-mode.ts), the catalogue's colour variants (catalog-variants.ts), the hard budget and the house's funds (budget.ts), the traced plan's placement by fit mode or calibration, with the two-point calibration maths (floor-plan-fit.ts), the one way lengths, areas, ages and money are written (format.ts: formatMetres, formatSize and formatArea in metres or feet and inches, parseLength for typed lengths such as 12'6" or 12.5 ft, the display-unit mirror the view store sets for strings written outside React, and formatMoney with its compact "$100M"), the Getting started card's five steps (first-steps.ts: progress derived from edits like achievements, never from loads, per-step tips, and the stored record of the card's state and a boolean per step), the shared-link tour's page phase (tour-session.ts: touring, kept or none, read from the hash on first use, so the editor's first render already knows it), the "reduce motion" query (reduced-motion.ts), the placement preview's maths (placement-ghost.ts), the in-app question queue and notices (confirm-dialog.ts, editor-notices.ts), the storage meter and one-file backup (storage-meter.ts, backup.ts), which floor undo lands on (history-floor.ts), the one table of seat heights (seat-surface.ts) and the one key guard (isTypingTarget in walk-input.ts), the render quality tiers (render-quality.ts), the stairwell holes a floor is cut with, shared by the 3D slab and the plans (floor-holes.ts), the first frame's hold while shaders compile (shader-warmup.ts), what a storey's contact-shadow map shows (contact-shadow.ts), the furniture's wood, fabric and leather detail images (detail-patterns.ts), the saved house's raw read and crash flag for the error screens, and leaveCrashedTour, which drops a share link from the address when a tour crashes so the reload opens the visitor's own house (saved-house.ts), keyboard selection on the scene (item-cycle.ts: the floor's items in plan order, rows from the top, each left to right, and the status line Tab announces), the touch buzz beside the sound cues (haptics.ts: a coarse pointer with navigator.vibrate only, never under reduced motion, a per-device switch, and the snap ticker that buzzes once as a dragged item meets a wall), and the plan exporters (lib/plan-export/: SVG, DXF, print to scale, loaded on click; print-popup.ts opens the print window inside the click, print-scale.ts holds the scale maths the editor needs up front). Since 1.35.0 also: the challenge briefs (challenges.ts: five lots with funds and goals read from the room scores, the spend and the storey count, the starting house, live progress and the layout.challenge repair), the walkers' clock (npc-schedule.ts: the 23:00 to 07:00 sleep window and the mealtime tilt of the needs), the fourth need and what each storey lacks (npc-needs.ts: hygiene, householdLacks), pushed-in chairs and bed places (npc-seats.ts), the room goals (achievements.ts, 19 achievements, four read from furnishedRooms in room-score.ts, which also gives the plan's stars line and the zone chip's hint), E on lamps (walk-interact.ts: findInteractable), EXPLORE's ambience (ambience.ts: rain by weather and indoors, footsteps by distance walked, a Web Audio graph on the shared context of sounds.ts) and the photo album (photo-album.ts: per-house JPEG copies in IndexedDB, loaded with import()). Since 1.36.0 also: the roof's shape (roof-shape.ts: peak height, pitch, the gable's ridge axis, the eave overhang and the party walls that rule out a north–south ridge, read by the roof, the dormers, the GLB, the street and the camera framing; dormers.ts swaps dormers across when the ridge turns and lists the ones a pitch can't take), fence, hedge and stepping-stone runs (item-run.ts: sections along a line, the end snap, corner insets, the lot a run stays in and fitRun, which leaves out what stands in the house and names a blocker), door and window types (opening-style.ts: single, double, sliding and arch, standard, tall and fixed, with leaf spans, the sliding door's walkable span and the arch head), what stands in a door's swing (door-clearance.ts: a soft warning for the plan and the popover, never a collision), the outer walls' outside finish (facade.ts: the facade's own pattern and colours over the inside finish, and the porch wall facing the street), and the stairwell guard rail (stairwell-rail.ts: runs along each hole, left open at the arrival and along walls, shared by the scene, the walker colliders, the plan and the exports). geometry.ts gained the partition faces that Snap to walls pulls to, and plan-export/plan-geometry.ts the double, sliding and archway symbols and outward swings. Since 1.37.0 also: the one key table (keymap.ts: the event.key and event.code values the shortcuts, the placement preview and the walker match, the shortcut sheet's rows by context, and formatBinding/withShortcut, which write ⌘ and ⇧ on a Mac; a test presses every key on the shortcut hook and checks each one that does something is listed), the one screen-reader status line (announce.ts: announce, de-duplicated, announceSettled for held keys, and the wording of undo, redo, nudges, turns and locks, where an item stands said by compass side from footprint.ts's shell walls), eased camera moves (camera-tween.ts: an arc round the target, about 350 ms, reduced motion cuts), the offline worker's registration (service-worker.ts: production only, after the first frame, the kill switch, the take-over message for a single tab), the version stamps (app-version.ts: this build's version and the last one this browser opened; saved-by.ts: the version that last saved the house, and the once-a-session "Save here anyway" question an older build asks), kept versions (in version-history.ts: their own key beside the ring, keep, keep the house on screen, rename, unkeep back into the ring, the backup import, and setItemEvictingSnapshots's evictKept for the open house's save alone), keeping the storage (backup-reminder.ts: the browser's persist() answer and the last backup time in one small record, and the reminder rule, shown since 1.39.0), files dropped on the page (file-drop.ts: whether a drag carries files, house or backup, why a drop is refused; backup-file.ts: the question, the add-only restore and the notice, shared by Restore… and a dropped backup) and the house as a file when a share link can't carry all of it (share-delivery.ts: the share sheet where it takes a JSON file, else a download). Since 1.38.0 also: the measure tool's snapping (measure-snap.ts: corners, item centres and side middles, then item edges and wall faces, shared by the plan and the 3D floor click) and pinned dimensions (plan-dimensions.ts: the pin rules, the repair and the move of pin ends that stand on the walls when the house is resized or cut), garden surfaces (grounds.ts: the lot they lie on, the draw gesture's fit and refusals, shownGrounds and the repair), whole-room moves (room-transfer.ts: roomArrangement picks the closed room's items, zones and own partitions, planRoomTransfer plans a move, mirror, copy or paste with the reducer's own refusals, pasteSpot finds the nearest free spot; the room clipboard is in clipboard.ts), the walkers' garden (npc-garden.ts: the ground storey's lot for the nav, its doors, the seats and spots out there, and gardenOpen from 06:00 to 19:30 in dry weather), meals at the table (npc-needs.ts: sitsToEat, pickMealSpot; npc-seats.ts: the chairs at a table), the walker card (walker-card.ts: what a walker is doing, the bubble's need, the card's place; walker-card-text.ts: the names and the words, loaded with the card), the ambience's calls and doors (ambience.ts: wildlifeSound, nextCallDelay, doorSoundGain; ambience-engine.ts, the Web Audio graph, loaded on demand), E on a TV (walk-interact.ts), photo presets (photo-presets.ts), the brief badges and terms (challenges.ts: the Lived-in brief, challengeAchievementId, briefTermsBroken; achievements.ts adds a badge per brief), the door-swing part of the space star (door-clearance.ts: swingBlockerIds, read by room-score.ts), the traced plan's mode (floor-plan-fit.ts: planIsDrawing, drawnFloorPlanImage), Fence the lot (item-run.ts: layLotRun, lotRunLines, the front gate, and onLotRun, which the plan and the blueprint draw whole), and overlapping stairwells cut as their own holes joined (floor-holes.ts). Almost all unit tests are here. Since 1.39.0 also: What's new (whats-new.ts: the newest release's Added lines, stamped in at build time by scripts/whats-new.mjs from CHANGELOG.md and loaded with the card; app-version.ts: offersWhatsNew, whatsNewIsNews, settleSeenVersion, which never moves the stamp back), the ? overlay's open state (shortcut-overlay.ts), AR (ar-view.ts: quickLookSupported from relList.supports('ar'), the file name and the link image, loaded after mount) and the floor-plan image store (plan-image-ref.ts, the light half a save needs: refs, confirmed images, compactPlanImage; plan-image-store.ts, loaded with import(): IndexedDB keyed by SHA-256, read-back check, resolvePlanImage and the inlining for files; see Data safety). camera-tween.ts gained cameraMoveEnd, so the lamp pool lights the storey a floor-switch glide is heading for. Version 2.0.0 added the translations (i18n/, with language.ts, language-boot.ts and message-lists.ts; see Languages), the visit count (visit-count.ts; see The visit count), and for Catalogue II opening-walls.ts (which wall an opening stands in and what that means: a barn door's rail and leaf, a pocket door's pocket, a window's shutters, and the track refusals), canopy.ts (the parasol: only its base and pole are in the way of anything lower than the canopy) and plan-order.ts's overhead units (the wall cupboard, cooker hood, boiler and mirror cabinet drawn dashed over what stands below). Version 2.1.0 added the architect career (career/; see The architect career), each storey's own tracing image (storey-plans.ts: the only way to a storey's plan fields, see Data safety), the Replace restore (backup-replace.ts, the plan and the commit; replace-recovery.ts, the safety copy in IndexedDB), the roof over an L (l-roof.ts: the two wings' solids joined into one closed body, valleys cut where the slopes meet, and the fascia along the eaves; roof-shape.ts' lRoofWings gives the numbers), what goes with a removed wall (wall-edit.ts' itemsOnRemovedWalls: the openings seated on it and the decor hung on it, unless another wall still holds them) and the opening's turn on its wall (opening-snap.ts' openingTurn), and zone areas less the storey's keep-out (zones.ts: porch and stairwells, so a rectangle over a stairwell agrees with the room's outline).
  • three/: Three.js scene builders. No React. Furniture mesh builders live in three/builders/builders-<category>.ts and are registered in three/furniture-builders.ts. The people model (people-model.ts) and how each person is dressed (people-outfits.ts: the shared mannequin geometry is split into body regions, one material per region, with hair hung on the head bone). Also the room (with an upper storey's floor slab), walls, interior walls and openings, the reveals round doors and windows (reveals.ts), roof and dormers, terrain, entrance, neighbours, procedural CanvasTexture patterns and their relief (surface-maps.ts), furniture materials (furniture-materials.ts), contact shadows (contact-shadow.ts), the sky (sky.ts) and ground surfaces (ground-surfaces.ts), the door leaves the walkthrough swings and shuts again on the way out (door-leaves.ts), lighting, the night glow (night-glow.ts) and the mask that keeps indoor lamps indoors (outdoor-lamps.ts), weather, overlays, the frame budget the decorative loops share (frame-budget.ts), and the GLB building export. Since 1.35.0 door-leaves.ts swings each door for the nearest person on its storey, the player or a walker (doorWalkersOf), and night-glow.ts darkens the shades of lamps switched off in EXPLORE. Since 1.36.0 door-leaves.ts also turns both leaves of a double door, slides a sliding pane and keeps an outward door to its side; stairwell-rail.ts builds the rail (posts, handrail, bottom rail and balusters merged into one mesh per storey, hidden with the partitions); roof.ts builds at the pitch and ridge of lib/roof-shape.ts; room-builder.ts, entrance.ts and reveals.ts give the outside faces the facade; and interior-walls.ts draws a pattern on each face of a partition. Since 1.38.0 also: garden surfaces (ground-patches.ts, one merged mesh per kind on the slope), lit TV screens (tv-screens.ts), the walkers' thought bubbles (need-bubbles.ts), and reveals.ts' openingOnHiddenWall, which leaves a hidden wall's doors and windows out of the scene and the GLB. The engine imports Three.js only through three/three-runtime.ts, which re-exports the named symbols the app uses so the bundler can drop the rest; to use a new symbol, add it there. Since 1.39.0 usdz-export.ts builds the USDZ from the GLB's building (buildExportBuilding) under a TableModel node at 1:50, with only the textures USDZExporter can draw. Since 2.1.0 also: the settled frame (settled-frame.ts: ambient occlusion over the resting frame on explicit High, GTAOPass loaded lazily, and the stills photos and PNGs use; occlusion-overlays.ts: the WeakSet of what it never darkens), the walkers' feet discs and sun streaks in contact-shadow.ts, and roof.ts over an L through lib/l-roof.ts. See Rendering.
  • hooks/: the React glue. The layout store and reducer, undo history, the scene lifecycle (use-three-scene.ts), the effects that rebuild scene pieces (use-scene-effects.ts), dragging in both views (use-item-drag.ts, fed by use-canvas-2d-interaction.ts in 2D), placement and the placement preview (use-placement-ghost.ts), keyboard shortcuts, the walkthrough, the walkers (use-npcs.ts, kept per storey by floor id and parked while their storey isn't drawn), photo mode (use-photo-mode.ts: html[data-photo], the key guard and the 2× capture), the traced plan's calibration session (plan-calibration.ts: points, length, move), achievements, the Getting started session (use-first-steps.ts: steps done from edits, markFirstStep for the walk and the share, stored with the card's offered or dismissed state), the tour phase as React state (use-tour-phase.ts), persistence and import/export. Since 1.35.0 also: a challenge brief's start through the whole-house load path (use-start-challenge.ts), one house's album photos (use-photo-album.ts), and EXPLORE's rain and footsteps on the frame budget (use-ambience.ts). Since 1.36.0 use-placement-ghost.ts lays a run when a fence, hedge or stepping stone is dragged (each preview mesh built once and moved, by the drag fast-path rule), and use-item-placement.ts buys the run as one purchase in one dispatch, so it is one undo step. Since 1.37.0 also: the page-wide drop target and the installed app's launch queue (use-file-drop.ts: one JSON file opens through handleImport or the add-only restore; refused under a modal, in a tour, in EXPLORE and in photo mode), the Android back gesture (use-back-dismiss.ts: one CloseWatcher at a time, for the top surface, layered dialog > drawer > item sheet, so back closes what Escape would; a close request that follows an Escape keydown is ignored), the storage request (use-storage-persist.ts: navigator.storage.persist() after the first real edit of a session), the worker's registration once the first frame is up (use-service-worker.ts) and whether keys are written the Mac way (use-apple-keys.ts). Since 1.38.0 also: the distance tool's points, tip and pins (use-measure-tool.ts), the garden-surface tool's kind (ground-draw.ts, view state outside the house), the room commands (use-room-transfer.ts: one cue, the hard budget asked on a paste, one history step), and in use-npcs.ts the garden walkers (those out on the lot keep walking while another storey is drawn), the walker card's feed and the bubbles; use-photo-mode.ts sets a preset's hour and weather and puts the scene's back on Done. use-camera-presets.ts runs presets, Fit and Focus through lib/camera-tween.ts on the frame budget's addFrameJob; anything else that writes the camera calls settleCameraMove first, so a glide never fights it. Since 1.39.0 also: the What's new state (use-whats-new.ts: offered once per page load to a returning visit, opened from Help, mounted only outside a tour, EXPLORE and photo mode), the backup reminder (use-backup-reminder.ts, with downloadBackup/backUpFromClick shared by Storage & backup), the update prompt (use-update-prompt.ts, on lib/service-worker.ts's updateKind and applyUpdate) and the USDZ export (use-usdz-export.ts: Quick Look in two taps through a real <a rel="ar">, a download elsewhere). use-camera-presets.ts glides a floor switch through glideCameraTo; input on the scene lands it. Since 2.1.0 also the career's glue (see The architect career): use-app-mode.ts, use-career.ts, use-start-commission.ts, commission-offers-store.ts, use-quick-job.ts, use-hand-over.ts and use-move-in-reveal.ts.
  • contexts/: RoomEditorContext (layout, actions, history, collisions, engine state), EditorViewContext (carries the view store), SelectionContext (single and multi-select), and HeldEditorContexts (freezes the editor and selection for the closed drawer so it doesn't re-render).
  • panels/: presentational components. Among the newer ones: welcome-banner.tsx (the first-run start chooser: start empty, a template with its plan, or a random one), first-steps-card.tsx (the Getting started checklist, a thin occluding line on phones), tour-banner.tsx (the shared-link tour's HUD: the house's name, Walk through, Keep a copy, Build your own), photo-bar.tsx (the shutter: Take photo, Save to album, Album and Done, the one HUD photo mode leaves on screen), photo-album.tsx (the album above the shutter, loaded lazily), challenge-chip.tsx (a brief's live checklist under the house card, folded on phones, hidden on a walk, in a tour or under a tool's top chip), variant-dots.tsx (a tile's colour dots, or the one colour button on touch) and plan-calibration-chip.tsx (the chip that walks through a calibration), and since 1.37.0 file-drop-overlay.tsx (what dropping the dragged file will do, or why it can't), announcer.tsx (the one visually hidden role="status" node lib/announce.ts speaks through) and the kept rows in library-panel.tsx. Since 1.38.0 also grounds-panel.tsx and ground-draw-chip.tsx (garden surfaces and their tool's chip), room-transfer-row.tsx (the zone chip's Select room row), walker-card.tsx (lazy) and the presets in photo-bar.tsx. They read state through contexts and store selectors, not props; props are kept for one-off callbacks with side effects. Since 1.39.0 also whats-new-card.tsx (lazy lines, in the Getting started card's place), hud-card.tsx (the frame both cards share), shortcuts-overlay.tsx and shortcuts-dialog.tsx (the ? overlay, the dialog loaded on first use), the AR/USDZ button in actions-panel.tsx, the reminder switch in storage-panel.tsx and the unreadable-image note in room-settings-panel.tsx. Since 2.1.0 also house-menu.tsx (the 🌐 menu under the lot badge, or a card at the top of the drawer on the narrowest phones: language, Game or Home builder, Show every tool), language-picker.tsx (LanguageRadios for View options, LanguageSelect for the start chooser and the house menu), the two-step chooser in welcome-banner.tsx, Replace… and Undo replace in storage-panel.tsx, and the career's panels (see below).
  • canvas-2d/render.ts: the pure top-down renderer behind the 2D plan, the minimap, the printed blueprint and the thumbnails. get2DViewTransform and canvasToWorld are the only source of plan ↔ world coordinates: never work out the scale or offsets anywhere else.
  • canvas-2d/plan-zoom.ts: the on-screen plan's own zoom and pan (pinch, wheel, a drag on empty floor, double tap back to the fit). It is view state, never layout state, so nothing is saved, undone or shared. It's held in world terms over the fit (zoom times the fit's scale, with a plan point at the canvas centre), so a sheet opening or a rotation that changes the fit keeps the same point in the middle. zoomedTransform applies it to the fit; the plan's paint, its overlays, the placement outline and the pointer all read that one transform. The minimap, blueprint and print never pass a zoom and keep the plain fit.

The data model

RoomLayout is a building: it owns floors[], the roof and dormers, the footprint (width × height, where height is the depth), the terrain, neighbours, frontage and entrance, the floor-plan image and its calibration (floorPlanTransform), the budget (budget: the hard budget switch, what selling back wrote off, and the house's funds), the challenge brief it is played under (challenge: an id and a start time), since 2.1.0 the client's commission it is built for (commission: the brief's id, seed and level, and the brief itself, never regenerated on load), since 1.38.0 the garden surfaces (grounds) and the traced plan's floorPlanMode, and a house id. Each FloorLayout owns its items, interior walls, zones, floor and wall finishes (since 1.36.0 with an optional facade for the outside faces), hidden walls, storey height, since 1.38.0 its pinned dimensions, and since 2.1.0, above the ground floor, its own floor-plan image fields (the ground floor's stay on the house, where older saves have them). The roof carries an optional pitch and ridge, a door an optional swingOut and a door or window an optional openingStyle; each is left out when it is the default, so older saves load unchanged. Types are in lib/types.ts.

State flow

All changes to the house go through actions on hooks/layout-reducer.ts:

panel / hook  →  action  →  layoutReducer  →  layoutStore  →  selectors re-render subscribers
                                                   │
                                                   ├→ use-history (snapshots for undo)
                                                   ├→ use-layout-persistence (autosave, restore points)
                                                   └→ use-scene-effects (rebuild what changed)
  • Item actions target the active floor through the reducer's withActiveFloor helper. New item operations should follow the same pattern.
  • Undo is snapshot-based at the layout level (use-history.ts, debounced, 50 entries), so any reducer action is undoable without extra code. Undo and redo go through the store's restoreLayout, which picks the floor (lib/history-floor.ts). A whole-house load calls history.commitNow() first, so a recent edit keeps its own step.
  • No-op actions return the same state object. A refused or unchanged mutation must hand back its input, or it creates an undo entry and an autosave with nothing visible. patchItem treats a null patch as "refused".
  • Rules live in the reducer, not in callers. Geometry changes refuse locked items, and wall-mounted items (doors, windows, cameras) are re-settled onto a wall after every move, align or rotate. A lock pins position, not existence: removal paths ignore locks.
  • Collision checks go through hasCollisions(item, items, width, depth, { keepOut, interiorWalls, … }). The porch and stairwell keep-out come from useFloorKeepOut, and hung decor uses its mount band (lib/mount-band.ts).

Stores

Fast-changing state sits in Zustand stores read through selectors, so a change re-renders only the components showing it:

  • layoutStore (hooks/use-layout-store.ts) holds the layout and reuses layoutReducer unchanged. use-layout-state.ts is a thin adapter over it.
  • The editor view store (hooks/editor-view-store.ts) holds view settings, the catalogue search, the game mode, the time auto-cycle and the length unit. The unit is a per-browser preference with its own storage key, never part of the house; geometry is always metres, and only what is shown follows it. Components read it with useLengthUnit() and pass it to the format.ts helpers. Its context carries only the store, so components select the fields they need (useViewSettings('view2D')) instead of the whole view. It also applies view invariants, such as zone drawing only existing on the 2D plan. Since 1.35.0 it also holds lampsOff, the lamps switched off with E in EXPLORE: session state, never part of the house, cleared when EXPLORE ends and on a whole-house load. The sound tile's three settings are soundsEnabled and ambienceEnabled (nextSoundSetting in lib/view-options.ts).
  • The save status (saving, last saved, save error) has its own small store that only the header subscribes to.

SidebarDrawer and BottomHud are memoised and get stable callbacks through useEvent, so an edit to the house doesn't re-render ~70 catalogue tiles.

Questions and refusals

Native window.confirm, alert and prompt freeze the render loop and the autosave, so the app doesn't use them. Both channels below are plain module-level queues, because many callers are hooks outside any provider or effects that run long after the click.

  • askConfirm(options) (lib/confirm-dialog.ts) returns a promise of the answer; one host, panels/confirm-dialog.tsx, shows the oldest open question. The dialog traps focus, Enter presses the focused button, Escape cancels, and a short grace period stops the rest of the opening gesture from answering. danger: true starts focus on Cancel. Window key handlers check confirmOpen() and stand back. The answer takes time, so read current state again after it.
  • notifyRefused(message, playCue) (lib/editor-notices.ts) plays the refused cue and shows an error notice, so no refusal is silent and none plays its cue twice. Don't add a second playCue at a call site. Components can use hooks/use-refusal.ts.
  • notify(message, tone, options) shows a status notice, with an optional action button. notifyWithUndo adds an Undo that only runs while the state it was raised for is still on screen.

Under the hard budget, purchases go through purchaseRefusal and refuseOverBudget.

Photo mode hides, it doesn't remove

Photo mode sets html[data-photo], and CSS hides everything in the HUD but the 3D canvas and the shutter with visibility: hidden, so no box moves and the scene occluders keep their size. The projection shift that keeps the house clear of the HUD is dropped while it's on and put back after. A photo is one frame rendered at twice the pixel ratio and read with toBlob in the same task, so the renderer still runs without preserveDrawingBuffer. Save to album encodes the same capture to a JPEG copy and keeps it in IndexedDB (see Data safety); a save still running when photo mode ends stops, and its question is withdrawn. Escape is claimed by the open album first (claimPhotoEscape in lib/photo-mode.ts).

EXPLORE never edits

EXPLORE is a game mode, not just the 3D walk, so gate edits on it rather than on the walkthrough being active: useExploring() (hooks/use-exploring.ts) for a single control, with NOT_WHILE_EXPLORING as its hint, and EditLock in panels/sidebar-drawer.tsx around a whole panel. A press on an item in EXPLORE selects it and arms no drag (selectOnly in three/drag-handlers.ts), as the 2D plan already did, and the orchestrator drops any drag that slips past.

The shared-link tour

A #layout= hash opens the house read-only. lib/tour-session.ts reads the phase from the hash before the first render, so the editor starts in EXPLORE with TourBanner in place of the lot badge, header stats, bottom HUD and drawer, and without the start chooser or Getting started card. While touring nothing saves: no autosave, no flush on pagehide, no restore point, no cross-tab notice, and the visitor's own save isn't even read. Keep a copy goes through saveOverStoredHouse (lib/persistence.ts): the visitor's house, if it has work in it or can't be read, becomes a recovered copy first, then the toured house is saved; if either step fails, every entry of the saved house is put back and the action is refused. Only then does the ordinary whole-house load run (snapshotBeforeReplace where it fits, history.commitNow(), applyLayout, markLayoutLoaded), with hydration re-baselined so that load isn't an edit. Build your own hydrates the visitor's house, or a fresh lot.

Offline, and older builds

scripts/build-sw.mjs writes out/sw.js after the export: the page, the shell and every file under _next/static/, each with its SHA-256, checked at install and before serving. Hashed files are served cache first, the page network first. A new worker takes over when the only open tab reloads; with several tabs, an older build can keep running, so every main save stamps its version (lib/saved-by.ts) and an older build refuses to save over a newer one's house until the user picks Save here anyway. The repository variable SERVICE_WORKER=off builds a worker that removes itself. See Data safety and Releasing.

Keys come from one table

Handlers never hold a key literal: they import from lib/keymap.ts (EDIT_KEYS, GHOST_KEYS, the walk codes), and the shortcut sheet (panels/shortcuts-panel.tsx) and the tooltips (withShortcut) render from its KEYMAP. Adding a shortcut means a row there; the test fails if a key the hook acts on isn't listed. Every key action still needs its event.repeat guard. The wiki's Keyboard shortcuts tables are generated from the same table.

Responsive layout

The HUD has desktop, tablet and phone layouts. The media queries live in lib/hud-layout.ts and must match app/globals.css. Panels that cover the canvas carry data-scene-occluder; the camera framing (lib/scene-insets.ts) and the 2D plan fit (lib/plan-view-fit.ts) use those rectangles to place the house in the free space. The design notes cover the details.

Languages

Version 2.0.0 translated the editor into German, Turkish, French, Simplified Chinese and Japanese, and 2.1.0 added Indonesian, Spanish and Brazilian Portuguese: nine languages in all. The pieces:

  • lib/i18n/: core.ts holds t, plural, the language list (LANGS, with each language's own name in LANG_NAMES and its lang tag in LANG_TAGS: zh-Hans, pt-BR) and the lazy loaders; index.ts gives typed ns.key ids. Each language is a folder (en/, de/, tr/, fr/, zh/, ja/, id/, es/, pt/) with one file per namespace (refusals.ts, notices.ts, storage.ts, catalogue.ts, keys.ts, exports.ts, format.ts, the panel namespaces, …), each with the same keys as English; the Translation type and a missing-key test hold them to it. English ships with the app, and the other languages load on demand as their own chunk. A message is a whole sentence with {name} slots, or a function when the grammar needs more (German cases, Turkish suffixes, plurals); never glue a message together at the call site.
  • Long text: German, French, Turkish, Indonesian, Spanish and Portuguese run longer than English. While one shows, <html> carries data-long-text (markDocumentLanguage in core.ts), and the CSS rules that let labels wrap or widen, tiles hyphenate and the phone dock fit key on it, so English and Chinese keep their layout. A label may carry soft hyphens for a narrow tile; plainLabel strips them for an aria-label or a tooltip.
  • t works outside React: notices, refusals and labels built in lib/ translate at the moment they're built; components re-render on a change through hooks/use-t.ts.
  • lib/language.ts is the preference: per browser, never in the house. A stored choice (validated) wins, else the browser's navigator.languages (pickLanguage: "de-AT" → German, every Chinese tag → Simplified, every Portuguese tag → Brazilian, the old code in → Indonesian). lib/language-boot.ts is the head script that sets <html lang> before the first paint; a dictionary that can't load (offline before it was cached) keeps the current language and stores nothing. A tour writes nothing: a choice made there is stored when the tour ends.
  • Saves stay English. Catalogue names, variant names and default floor and house names are stored as English, and lib/i18n/names.ts (itemLabel, catalogueName, variantLabel, floorLabel, …) translates only a name the catalogue or the defaults know, so anything the player typed shows as typed.
  • Formats go through lib/format.ts, which reads one table per language: decimal comma and grouping, dates in the language's locale, full-width digits read in Chinese and Japanese, money in dollars with the language's grouping. Never toLocaleString.
  • Lists go through lib/message-lists.ts (listAnd, listOr via Intl.ListFormat, and the plain, semicolon and clause joints from messages), never a separator written in code: Chinese and Japanese join with 、 and no space.
  • Keys come from lib/keymap.ts: letter shortcuts match event.key, place-based keys (the walk keys, the clock keys right of P) match event.code, labels follow the language, and an input method's composition is never taken as a shortcut (isComposingKey in lib/walk-input.ts).
  • Exports: lib/plan-export/ writes SVG, print and blueprint text in the current language (namespace exports), the DXF always in English, and an English export is byte for byte what it was. What's new comes from docs/changelog/<lang>.md at build time (scripts/whats-new.mjs).

The architect career

Since 2.1.0 the app has two modes (see Architect career for what the player sees). The code keeps the free builder's cost unchanged:

  • lib/career/ is pure, like the rest of lib/: the shared shapes (types.ts), the seeded commissions and their repair on load (commissions.ts: the same seed and level always give the same client; the fee is always worked out again with feeFor, never read from a save), the wishes as predicates over the house (wishes.ts, with their data in wish-data.ts, so the generator can price a brief without loading the checks), the move-in day (move-in.ts: a headless day from 07:00 to 23:00 on the walkers' own pure modules, seeded by the commission, no Math.random and no clock, lived six times and averaged) and the critic (critic.ts: the findings and the dealbreakers), the levels and what they open (levels.ts, unlocks.ts), the career save with the one pay rule (career-store.ts: payFor, finishCommission, mergeCareer), the daily brief (daily.ts: a seed from the local date alone; daily-result.ts, import-free so the share-link codec stays light), the quick job (quick-job.ts), the move-in reveal's script (move-in-reveal.ts, move-in-text.ts) and the house's world for the day (house-world.ts).
  • The mode (app-mode.ts): Game or Home builder in one validated key, never part of a house; a player from before the choice is Home builder without anything written, and a tour reads the mode but never writes it. mode-houses.ts keeps each mode's house and switches them as one transaction; mode-guard.ts stamps the main save with its mode, so a tab another tab switched under can't save over the other mode's house. See Data safety.
  • What the game hides comes from one table, mode-tools.ts (toolShown, catalogItemShown, categoryShown), read in React through useToolShown, useToolFilter and useCatalogShown (hooks/use-app-mode.ts). A new professional tool gets a row there. What a level locks comes from unlocks.ts (typeLockedLevel, careerFloorLimit), which gate game mode only; careerLockRefusal covers paste, sets and room copies.
  • The lazy chunk: the career's UI loads on demand. panels/career-lazy.tsx loads career-layer.tsx (the commission card, the daily brief, the offers, the quick job's hints, and the move-in reveal with its driver, and with it the move-in day and the critic) and career-panel.tsx (the career screen in Manage) through React.lazy, in game mode only and after the first frame, the career screen when idle. Home builder loads none of it. The quick job's studio and brief also load with import() on first use.
  • The panels: commission-offers.tsx (the three clients), commission-card.tsx (wishes ticking live, Hand over), career-hud.tsx (what game mode shows on the scene when no commission is open), daily-card.tsx and daily-result-card.tsx, move-in-card.tsx (the rating card, its pay from payFor), quick-job-hints.tsx and career-panel.tsx. The reveal sets html[data-reveal], which hides the HUD as photo mode does, stops the house's keys and takes Escape to skip.
  • Text: the career's strings are their own namespaces (careerMode, careerOffers, careerClients, careerMoveIn, careerReveal, careerProgress, careerDaily, careerQuick), one file each per language folder. Residents' names come from each language's own pool, and a commission stores name keys, never names.

The visit count

lib/visit-count.ts counts visits to the live site with GoatCounter, sent by the app itself rather than GoatCounter's count.js, so no third-party script loads. hooks/use-visit-count.ts sends the page view once the first frame is on screen and the page is idle: /, or /tour for a share link (never the URL or its hash, which is the whole house), with the referrer's origin only and the screen width. A few events (explore, photo, ar-view, usdz, backup, share-link, template) are sent at most once per visit. The request is a credential-free keepalive fetch, never sendBeacon (which sends cookies) or an image.

countRefusal sends nothing when the build has no site code (NEXT_PUBLIC_GOATCOUNTER unset is the kill switch), off the host the build targets (NEXT_PUBLIC_GOATCOUNTER_HOST, set in next.config.mjs), in an automated browser (navigator.webdriver, which covers the CI smoke test), under Do Not Track or Global Privacy Control, offline, or with the per-device switch (Storage & backup → Anonymous usage count) off. The guards are read on every send, so turning the switch off stops the count at once. scripts/add-csp.mjs adds the GoatCounter origin to connect-src only when the site code is set.

Adding a furniture item

  1. Add the catalogue entry to FURNITURE_CATALOG in lib/constants.ts. Its name is English and is what saves keep.
  2. Write a mesh builder in three/builders/builders-<category>.ts and register it in three/furniture-builders.ts.
  3. Give the type its shown name (and any colour variants theirs) in lib/i18n/<lang>/catalogue.ts for every language. The docs drift test also checks the item count stated in docs/architecture.md and the README.

In the builder, give parts a surface with surfaceMaterial(ctx, colour, 'woodOiled' | 'fabric' | …) (three/furniture-materials.ts), and pass { detailed: true } only on softBox geometry, whose UVs are in metres. Use softBox with an EDGE radius rather than a plain box, and join static parts that share a material with mergeParts (both in three/builder-utils.ts).

Placement, dragging, collision, persistence, sharing and undo then work without further changes. Check it in 3D and on the 2D plan.

A feature that changes the plan

The 2D plan, minimap, blueprint, SVG and DXF all draw from floor data and know nothing about the 3D-only build. A feature that changes the footprint or the usable floor must be drawn in all of them, or the plan misleads. Shared plan maths lives in lib/plan-export/plan-geometry.ts.

See also Rendering and Data safety.

Clone this wiki locally