ai-chatbot/packages/editor/src/lib/snapping-mode.ts
Wassim SAMAD 22af31dea8
editor: snapping overhaul — shared-wall rooms, deterministic slab elevation, cursor-true transfers (#458)
* fix(snapping): show alignment lines in all modes, snap only in lines; north export; R/T hint; grid default

- Alignment guides display in every snapping mode (grid/lines/angles/off);
  magnetic pull applies only in 'lines'. New isAlignmentGuideActive() predicate
  decouples guide display from the snap delta across all placement/move/draw
  producers (item, wall, fence, slab/ceiling/roof, column/shelf/spawn, door/
  window, MEP, 2D floorplan drafting, surface snap).
- Floorplan PDF export now rotates to north-up (FLOORPLAN_VIEW_ROTATION_DEG -
  building rotation), matching the on-screen aligned-to-north view.
- Item placement rotate hint collapsed to a single 'R / T  Rotate' row.
- Default item snapping mode changed lines -> grid.

* feat(walls): detect rooms across shared walls + tight connect-snap in all modes

Room detection: planarize the wall graph before face-finding — split straight
walls at T-junctions where another wall ends mid-span, so a room closed against
the middle of an existing wall is detected, not just isolated 4-wall rooms.

Auto-close: wire the wall builder's "Room (auto-close)" to the same room graph
via wallClosesRoom(), so drafting stops when a segment seals a room against the
existing structure — not only when the chain returns to its own start.

Connectivity snap: add a tight wall-connect snap (WALL_CONNECT_SNAP_RADIUS 0.05)
that also runs in grid/off/angles — within range of a wall (body or corner,
uniform radius) the endpoint sticks onto it and the beacon shows, so rooms close
in every mode. Lines keeps its wider magnetic radii. Gate alignment guides in
non-magnetic modes to the same connect distance so a corner dot no longer
magnetises the cursor from far.

Tests: cover T-junction detection + wallClosesRoom; update the item-default and
wall-split tests for the mode-driven behaviour.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(surfaces): gate alignment guides to connect distance in non-magnetic modes

Port the wall drafting/endpoint gating to the shared slab/ceiling/roof snap
(resolveSurfacePlanPointSnap): in grid/off/angles, only anchors within the
connect distance are fed to the alignment resolver, so guides form to nearby
points and far corner dots stop lighting up from across the plan. Filtering the
candidates (local-frame, like the cursor) rather than the resolved guides avoids
the floor-plan view rotation baked into the guide coords. Lines mode keeps the
full-range guides; the surface wall connect-snap is unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(slabs): deterministic wall-slab overlap via clipped overlap length

Wall elevation used ray-cast point samples that landed exactly on the
slab boundary for perpendicular walls, so whether a butting wall
followed the slab's elevation depended on which side of the slab it
touched. Clip the wall centerline and face lines against the polygon
and require >=5cm of on/inside length instead: walls along the slab
edge follow it on every side, point contact never does.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(grid): lift lattice 1mm off slab tops; wall-align on wall-item move start

The horizontal snap lattice sat exactly at the followed surface Y, so it
z-fought elevated slab tops while moving items. The visual mesh now rides
1mm above; the grid event plane keeps the true height.

Moving a wall-hosted item showed a horizontal grid until the first
pointer move published a wall surface — the mesh fallback assumed UP.
Derive the host wall normal from the item mesh's world orientation
(local +Z faces out of the wall) so the lattice is wall-aligned from
the first frame.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): unify selection shortcuts + truthful select-mode hints

Shift+click now toggles selection membership in 3D like Cmd/Ctrl (and
appends on box-select release), matching the 2D floorplan. The HUD rows
describe what actually works in both views: move is plain left-drag (the
grip/dot), the two vague selection rows collapse into one Cmd/Shift
or-group, and the modifier-held variants (freely / with guides / bypass
snaps) are gone — guides follow the snapping mode now. Key pills join
with + for combos and / for alternatives; Shift renders as the shift
icon.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): group gizmos — reliable rotate grabs, mutual hide, snapping-mode integration

The group-rotate gizmo never received pointer events through the shared
invisible hit-area path (EDITOR_LAYER + custom raycast) in its portalled
context; its handlers now live on the visible arrow plus a plain
default-layer invisible torus, so hover and drag work with a fat target.

Group drags begin a handle-drag scope: each gizmo hides while its
sibling drags (the frozen corner goes stale), idle hints leave the HUD,
and the drag gets contextual hints — Shift free-rotation for rotate, the
snapping chips for move.

Group move joins the snapping-mode system via the 'item' context: Shift
cycles the mode, Ctrl the grid step (both read live mid-drag), and
'lines' runs the same Figma-style alignment as single-node moves against
the group's bbox anchors. Chip clicks now tick like the keyboard cycles.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): group-move ticks in every snapping mode

Mirror the single-node move's sfx: emit per delta change rather than
only on grid crossings, so lines/off get the same rate-limited texture.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(items): keep host transfers glued to the cursor

Moving between hosts used to diverge from the pointer and mangle state:

- Grab offsets: every surface anchor (wall / ceiling / shelf / item
  surface / floor) preserved the grab offset by re-seeding from the
  item's carried-over position on each new host, landing it far from
  the cursor. The grab offset now survives only on the original host
  and only until the item anchors anywhere else — after that every
  host (the original included) centers the item under the cursor.
  Applied uniformly to the placement coordinator and the window/door
  move tools.

- Rotation: detaching from a rotated shelf/table back to the floor kept
  the HOST-local yaw as the level yaw, visibly spinning the item. The
  detach now re-expresses the item's world yaw in the level frame.

- Elevation: the same detach wrote the level parentId to the store but
  not the draft ref, so the floor-elevation resolver bailed on its
  parent-must-be-a-level guard — the snap grid and the item stopped
  following slab elevations for the rest of the drag.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(items): latch grab-offset forgetting across every host kind

Review follow-up (PR #458): unify the per-surface grab-forget rule into
one grabForgotten latch. A wall/ceiling item could not actually reach a
shelf or the floor (item-surface enter rejects attachTo assets), but a
wall item CAN anchor on a roof face — and returning to its original
wall then restored the stale grab offset. Roof-wall transitions (and
floor landings after a host visit) now trip the latch in the
coordinator and the window/door move tools alike.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 16:18:37 -04:00

180 lines
7.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { SnapProfile } from '@pascal-app/core'
import { GROUP_MOVE_DRAG_LABEL } from './contextual-help'
/**
* Snapping mode is a single global, user-cyclable control that maps onto the
* two pre-existing snap knobs (`gridSnapStep` grid snap + `magneticSnap`).
* The default `'grid'` resolves to the exact pair the editor shipped with
* before this control existed (grid on, magnetic on), so the default path is
* behaviourally unchanged — only when a user opts into `'lines'` or `'off'`
* does any snap math get suppressed.
*/
export type SnappingMode = 'grid' | 'lines' | 'angles' | 'off'
export const SNAPPING_MODES: SnappingMode[] = ['grid', 'lines', 'angles', 'off']
export const DEFAULT_SNAPPING_MODE: SnappingMode = 'grid'
export type SnapFlags = {
grid: boolean
magnetic: boolean
angles: boolean
}
/**
* Pure mapping from the mode enum onto the individual snap knobs. Modes are
* EXCLUSIVE — each does exactly what its chip label says, one guide at a time,
* so the HUD is honest:
*
* - `grid` → grid lattice only.
* - `lines` → magnetic only: alignment axes + wall corner-join (connectivity
* is part of the "lines" magnetic snap, not a separate always-on behaviour).
* - `angles` → angle lock only (15°/45° rays).
* - `off` → nothing snaps (raw cursor).
*/
export function resolveSnapFlags(mode: SnappingMode): SnapFlags {
switch (mode) {
case 'grid':
return { grid: true, magnetic: false, angles: false }
case 'lines':
return { grid: false, magnetic: true, angles: false }
case 'angles':
return { grid: false, magnetic: false, angles: true }
case 'off':
return { grid: false, magnetic: false, angles: false }
}
}
const SNAPPING_MODE_LABELS: Record<SnappingMode, string> = {
grid: 'Grid',
lines: 'Lines',
angles: 'Angles',
off: 'Off',
}
export function getSnappingModeLabel(mode: SnappingMode): string {
return SNAPPING_MODE_LABELS[mode]
}
export function nextSnappingMode(mode: SnappingMode): SnappingMode {
const index = SNAPPING_MODES.indexOf(mode)
return SNAPPING_MODES[(index + 1) % SNAPPING_MODES.length] ?? DEFAULT_SNAPPING_MODE
}
// ── Per-context snapping ──────────────────────────────────────────────────────
//
// Snapping is no longer one global value: each *activity* has its own mode set
// and default, because they want different behaviour (drawing a wall wants a
// grid + angle lock; nudging an item wants free movement that only catches on
// alignment lines). The mode is remembered per context and shown live, so it's
// never a silent surprise — it just matches what you're doing.
export type SnapContext = 'wall' | 'item' | 'polygon'
// The cyclable mode-set for a context (distinct from the node's `SnapProfile`).
type SnapModeSet = { modes: SnappingMode[]; default: SnappingMode }
// `modes[0]` is the cycle's first entry; `default` is what a context starts at.
// The 'wall' set is the ONLY one with an angle lock — it applies solely when
// you're setting a segment's DIRECTION (wall/fence drafting + endpoint drag).
// Translating a whole wall, curving it, or drawing/moving a slab can't change an
// angle, so those use the no-angle 'polygon' set.
const SNAP_PROFILES: Record<SnapContext, SnapModeSet> = {
// Wall / fence drafting + endpoint reshape: direction matters → angle lock.
wall: { modes: ['grid', 'lines', 'angles', 'off'], default: 'grid' },
// Item placement / move: grid by default; lines = magnetic alignment only (no
// grid lattice), no angle lock (meaningless for a footprint).
item: { modes: ['lines', 'grid', 'off'], default: 'grid' },
// Structural / surface, no direction to set: slab / ceiling / roof draft+move,
// whole wall/fence translate, curve reshape, polygon boundary edit. Grid by
// default, NO angle lock.
polygon: { modes: ['grid', 'lines', 'off'], default: 'grid' },
}
export const SNAP_CONTEXTS: SnapContext[] = ['wall', 'item', 'polygon']
export function snappingModesFor(context: SnapContext): SnappingMode[] {
return SNAP_PROFILES[context].modes
}
export function defaultSnappingModeFor(context: SnapContext): SnappingMode {
return SNAP_PROFILES[context].default
}
// Cycle within the context's own set (clamps a foreign value to the first entry).
export function cycleSnappingModeIn(context: SnapContext, mode: SnappingMode): SnappingMode {
const modes = SNAP_PROFILES[context].modes
const index = modes.indexOf(mode)
return modes[(index + 1) % modes.length] ?? modes[0] ?? DEFAULT_SNAPPING_MODE
}
// The kind's declared `snapProfile` (from the registry) → the active mode-set
// context. The only behaviour difference is the angle lock, which a `structural`
// kind gets while SETTING DIRECTION (drafting a run/polygon, dragging an endpoint
// or a polygon vertex) — never while translating or curving. A node with no
// declared profile has no snapping UI (chip) yet — returns null.
function contextForProfile(
profile: SnapProfile | undefined,
directionSetting: boolean,
): SnapContext | null {
if (profile === 'item') return 'item'
if (profile === 'structural') return directionSetting ? 'wall' : 'polygon'
return null
}
/**
* The active snapping context, derived from what the user is doing — fully
* node-declared: the kind's `snapProfile` (looked up via the injected
* `profileOf`) supplies the data, and this maps (profile × action) to the
* mode-set. No per-kind switch lives here. `profileOf` is injected so this stays
* pure + testable and `snapping-mode` need not import the registry.
*
* Prefers the authoritative interaction scope; falls back to the build tool
* because the `drafting` scope isn't wired yet (wall/slab draw runs idle).
* Returns null when nothing snappable is active → no chip, safe-default snap.
*/
export function snapContextOf(args: {
scope: {
kind: string
nodeType?: string
reshape?: string
nodeId?: string
tool?: string
handle?: string
}
mode: string
tool: string | null
profileOf: (typeOrTool: string) => SnapProfile | undefined
// Whether drafting a kind sets a direction (angle-lock meaningful). Injected
// like `profileOf` so `snapping-mode` need not import the registry; defaults
// to `true` (the structural draw default) when not supplied.
draftDirectionalOf?: (typeOrTool: string) => boolean
}): SnapContext | null {
const { scope, mode, tool, profileOf, draftDirectionalOf } = args
// The group-move gizmo translates the whole selection — same no-angle
// treatment as a single-node move, so Shift cycles the 'item' modes and the
// HUD shows the item snapping chips for the drag.
if (scope.kind === 'handle-drag' && scope.handle === GROUP_MOVE_DRAG_LABEL) {
return 'item'
}
switch (scope.kind) {
case 'placing':
case 'moving':
// A whole-node translate never sets direction → no angle.
return scope.nodeType ? contextForProfile(profileOf(scope.nodeType), false) : null
case 'reshaping':
// Dragging a wall ENDPOINT sets the segment's direction → angle-bearing
// 'wall'. Curving, and polygon vertex/edge edits (boundary / hole), don't
// — they use the no-angle 'polygon' set (grid / lines / off).
return scope.reshape === 'endpoint' ? 'wall' : 'polygon'
case 'drafting':
return scope.tool
? contextForProfile(profileOf(scope.tool), draftDirectionalOf?.(scope.tool) ?? true)
: null
default:
return mode === 'build' && tool
? contextForProfile(profileOf(tool), draftDirectionalOf?.(tool) ?? true)
: null
}
}