@7365admin1/layer-common 4.35.1-staging.370 → 4.35.1-staging.371

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1009,7 +1009,7 @@
1009
1009
  .hero-seg__kbd { opacity: 0.55; }
1010
1010
  .hero .hero-input.hero-editor__floor { width: auto; min-height: 32px; padding: 4px 26px 4px 8px; }
1011
1011
  .hero .hero-input.hero-editor__zone { width: 220px; min-height: 32px; }
1012
- .hero-editor__hint { font-size: 12px; opacity: 0.7; }
1012
+ .hero-editor__hint { font-size: 12px; opacity: 0.7; order: 1; flex-basis: 100%; } /* own line: switching tools never moves the plan */
1013
1013
  .hero .v-btn.hero-editor__fs { margin-left: auto; }
1014
1014
  .hero .v-btn.hero-editor__fs .v-btn__content { gap: 8px; }
1015
1015
  .hero-editor__notice { padding: 10px 12px; font-size: 12.5px; border-left: 2px solid var(--hero-accent); background: var(--hero-surface); }
@@ -1017,6 +1017,7 @@
1017
1017
  .hero-editor__split { display: flex; flex-wrap: wrap; gap: 24px; align-items: stretch; flex: 1; }
1018
1018
  .hero-editor__plan {
1019
1019
  flex: 999 1 460px;
1020
+ align-self: flex-start; /* a taller side list must not stretch the plan under the pointer */
1020
1021
  min-width: 0;
1021
1022
  position: relative;
1022
1023
  min-height: max(480px, calc(100vh - 330px));
@@ -1027,6 +1028,18 @@
1027
1028
  border: 1px solid var(--hero-divider);
1028
1029
  overflow: hidden;
1029
1030
  cursor: crosshair;
1031
+ touch-action: none; /* a finger drags shapes, not the page */
1032
+ user-select: none;
1033
+ }
1034
+ .hero-editor__plan--default { cursor: default; }
1035
+ .hero-editor__plan--pointer { cursor: pointer; }
1036
+ .hero-editor__plan--move { cursor: move; }
1037
+ .hero-editor__plan--ns { cursor: ns-resize; }
1038
+ .hero-editor__plan--ew { cursor: ew-resize; }
1039
+ .hero-editor__plan--nwse { cursor: nwse-resize; }
1040
+ .hero-editor__plan--nesw { cursor: nesw-resize; }
1041
+ .hero-editor__plan--rotate, .hero-editor__handle--rotate {
1042
+ cursor: url("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2724%27 height=%2724%27 viewBox=%270 0 24 24%27%3E%3Cpath d=%27M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5%27 fill=%27none%27 stroke=%27%23fff%27 stroke-width=%274%27/%3E%3Cpath d=%27M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5%27 fill=%27none%27 stroke=%27%23000%27 stroke-width=%272%27/%3E%3C/svg%3E") 12 12, grab;
1030
1043
  }
1031
1044
  .hero-editor__plan:focus-visible { outline: 2px solid var(--hero-accent); outline-offset: 0; }
1032
1045
  .hero-editor__room { position: absolute; border: 2px solid var(--hero-text); opacity: 0.4; pointer-events: none; }
@@ -1038,11 +1051,35 @@ polygon.hero-editor__sel { stroke: var(--hero-accent); stroke-width: 2; stroke-d
1038
1051
  div.hero-editor__sel { outline: 2px solid var(--hero-accent); }
1039
1052
  .hero-editor__label { position: absolute; display: grid; place-items: center; font-size: 10px; font-weight: 600; pointer-events: none; }
1040
1053
  .hero-editor__lift { position: absolute; box-sizing: border-box; display: grid; place-items: center; font-size: 10px; font-weight: 600; background: color-mix(in srgb, var(--hero-accent) 30%, transparent); border: 1px solid var(--hero-accent); }
1041
- .hero-editor__door { position: absolute; width: 3%; height: 3%; margin: -1.5% 0 0 -1.5%; background: var(--hero-accent); }
1054
+ .hero-editor__door { stroke: var(--hero-accent); stroke-width: 4; stroke-linecap: square; }
1055
+ line.hero-editor__door.hero-editor__sel { stroke: var(--hero-text); }
1056
+ .hero-editor__swing { fill: none; stroke: var(--hero-text); stroke-width: 1; stroke-dasharray: 3 2; opacity: 0.7; }
1057
+ .hero-editor__rotline { stroke: var(--hero-accent); stroke-width: 1; stroke-dasharray: 3 2; }
1058
+ /* Handles: 24px to hit (36px for a finger), a 10px square to see. */
1059
+ .hero-editor__handle { position: absolute; z-index: 2; width: 24px; height: 24px; margin: -12px 0 0 -12px; display: grid; place-items: center; touch-action: none; }
1060
+ .hero-editor__handle::before { content: ""; box-sizing: border-box; width: 10px; height: 10px; background: var(--hero-surface); border: 2px solid var(--hero-accent); }
1061
+ .hero-editor__handle--vertex::before { background: var(--hero-accent); border-color: var(--hero-surface); outline: 1px solid var(--hero-accent); }
1062
+ .hero-editor__handle--on::before { background: var(--hero-text); outline-color: var(--hero-text); }
1063
+ .hero-editor__handle--rotate::before { width: 11px; height: 11px; background: var(--hero-accent); border-color: var(--hero-surface); transform: rotate(45deg); }
1064
+ @media (pointer: coarse) {
1065
+ .hero-editor__handle { width: 36px; height: 36px; margin: -18px 0 0 -18px; }
1066
+ .hero-editor__handle::before { width: 14px; height: 14px; }
1067
+ }
1068
+ .hero-editor__marquee { position: absolute; border: 1px dashed var(--hero-accent); background: color-mix(in srgb, var(--hero-accent) 8%, transparent); pointer-events: none; }
1069
+ .hero-editor .hero-seg__opt--redo { font-weight: 400; }
1070
+ .hero-editor__grid { font: inherit; font-size: 12px; padding: 7px 8px; color: inherit; background: transparent; border: 0; border-left: 1px solid var(--hero-divider); cursor: pointer; }
1071
+ .hero-editor__grid option { color: var(--hero-text); background: var(--hero-surface); }
1072
+ .hero-editor__actions { display: flex; flex-wrap: wrap; gap: 6px; }
1073
+ .hero-editor__act { font: inherit; font-size: 12px; padding: 6px 10px; min-height: 32px; color: inherit; background: transparent; border: 1px solid var(--hero-divider); cursor: pointer; }
1074
+ .hero-editor__act:hover { background: color-mix(in srgb, var(--hero-text) 7%, transparent); }
1075
+ .hero-editor__act:disabled { opacity: 0.45; cursor: not-allowed; }
1076
+ .hero-editor__act--del { color: var(--hero-accent); }
1042
1077
  .hero-editor__cursor { position: absolute; width: 14px; height: 14px; margin: -7px 0 0 -7px; border: 2px solid var(--hero-accent); pointer-events: none; }
1043
1078
  .hero-editor__aside { font-size: 12px; display: flex; flex-direction: column; gap: 8px; flex: 1 1 260px; max-width: 360px; min-width: 0; align-self: stretch; }
1044
1079
  .hero-editor__asidetitle { border-top: 2px solid var(--hero-divider); padding-top: 8px; }
1045
- .hero-editor__row { display: flex; justify-content: space-between; gap: 8px; border-bottom: 1px solid var(--hero-divider); padding: 4px 0; }
1080
+ .hero-editor__row { display: flex; justify-content: space-between; gap: 8px; border: 0; border-bottom: 1px solid var(--hero-divider); padding: 4px 0; font: inherit; color: inherit; background: transparent; text-align: left; cursor: pointer; }
1081
+ .hero-editor__row:hover { background: color-mix(in srgb, var(--hero-text) 5%, transparent); }
1082
+ .hero-editor__row--sel { box-shadow: inset 2px 0 0 var(--hero-accent); padding-left: 6px; font-weight: 600; }
1046
1083
  .hero-editor__pos { opacity: 0.55; font-variant-numeric: tabular-nums; }
1047
1084
  .hero-editor__note { opacity: 0.6; margin-top: auto; }
1048
1085
 
@@ -1,29 +1,41 @@
1
1
  <template>
2
2
  <!--
3
3
  Map editor (README §4 "Edit mode"): Wall · Zone · Door · Lift shaft · Move
4
- · Delete | Undo ⌃Z | Save, one floor at a time on a flat 2D plan. A click
5
- places the tool's shape; Move = click a shape, then its destination;
6
- Delete = click a shape. Keyboard: Tab to the plan, arrows move the
7
- cursor, Enter places. Save checks in plain words first, then writes the
8
- building map through the API (versioned; a stale save is refused).
4
+ · Delete | Undo · Redo | Save, one floor at a time on a flat 2D plan.
5
+ A drawing tool places its shape where you click (the new shape comes
6
+ selected with its handles). Move: click selects (Shift adds), drag moves
7
+ the selection, drag on empty space selects an area; handles resize a lift
8
+ shaft or zone, drag a wall's or door's ends and a zone's corners, and turn
9
+ a door or lift shaft. Snaps to the grid (Shift while dragging = free).
10
+ Keyboard: arrows move the cursor or nudge the selection, Enter places or
11
+ selects, Delete removes, Esc clears, Ctrl/Cmd+Z undo, Ctrl/Cmd+Shift+Z or
12
+ Ctrl+Y redo. Every drag is one undo step. Save checks in plain words
13
+ first, then writes the building map through the API (versioned).
9
14
  -->
10
15
  <div ref="root" class="hero-editor" :class="{ 'hero-editor--fs': isFs }">
11
16
  <div class="hero-editor__bar">
12
17
  <div class="hero-seg" role="toolbar" aria-label="Map editor tools">
13
18
  <button v-for="t in MAP_TOOLS" :key="t.id" type="button" class="hero-seg__opt" :aria-pressed="tool === t.id" @click="pickTool(t.id)">{{ t.label }}</button>
14
- <button type="button" class="hero-seg__opt hero-seg__opt--undo" @click="state = editorReduce(state, { type: 'undo' })">Undo <span class="hero-seg__kbd">⌃Z</span></button>
19
+ <button type="button" class="hero-seg__opt hero-seg__opt--undo" :disabled="!state.undo.length" @click="dispatch({ type: 'undo' })">Undo <span class="hero-seg__kbd">⌃Z</span></button>
20
+ <button type="button" class="hero-seg__opt hero-seg__opt--redo" :disabled="!state.redo.length" @click="dispatch({ type: 'redo' })">Redo <span class="hero-seg__kbd">⌃⇧Z</span></button>
15
21
  <button type="button" class="hero-seg__opt hero-seg__opt--save" :disabled="saving" @click="save">{{ saving ? "Saving…" : "Save" }}</button>
16
22
  </div>
23
+ <div class="hero-seg" role="group" aria-label="Grid">
24
+ <button type="button" class="hero-seg__opt" :aria-pressed="snapOn" title="Snap to the grid while dragging (hold Shift to place freely)" @click="snapOn = !snapOn">Snap</button>
25
+ <select v-model.number="gridM" class="hero-editor__grid" aria-label="Grid step">
26
+ <option v-for="g in GRID_STEPS_M" :key="g" :value="g">Grid {{ g }} m</option>
27
+ </select>
28
+ </div>
17
29
  <select v-model.number="floor" class="hero-input hero-select hero-editor__floor" aria-label="Floor">
18
30
  <option v-for="f in floors" :key="f" :value="f">{{ floorName(f) }}</option>
19
31
  </select>
20
32
  <input
21
- v-if="tool === 'zone'"
33
+ v-if="tool === 'zone' || selectedZone"
22
34
  v-model="zoneName"
23
35
  class="hero-input hero-editor__zone"
24
36
  aria-label="Zone name"
25
37
  placeholder="Zone name (required to save)"
26
- @input="state = editorReduce(state, { type: 'rename', name: zoneName })"
38
+ @input="dispatch({ type: 'rename', name: zoneName })"
27
39
  />
28
40
  <span class="hero-editor__hint">{{ TOOL_HINTS[tool] }}</span>
29
41
  <v-btn variant="outlined" class="hero-editor__fs" @click="fullscreen">
@@ -38,10 +50,16 @@
38
50
  <div
39
51
  ref="plan"
40
52
  class="hero-editor__plan"
53
+ :class="`hero-editor__plan--${planCursor}`"
54
+ :style="gridStyle"
41
55
  tabindex="0"
42
56
  role="application"
43
- :aria-label="`Floor plan ${floorName(floor)}. Arrow keys move the cursor, Enter places.`"
44
- @click="onPlanClick"
57
+ :aria-label="`Floor plan ${floorName(floor)}. Arrow keys move the cursor or nudge the selection, Enter places or selects, Delete removes, Escape clears.`"
58
+ @pointerdown="onPlanDown"
59
+ @pointermove="onPointerMove"
60
+ @pointerup="onPointerUp"
61
+ @pointercancel="onPointerCancel"
62
+ @dblclick="onDoubleClick"
45
63
  @keydown="onKey"
46
64
  @blur="keyboard = false"
47
65
  >
@@ -50,25 +68,45 @@
50
68
  <span class="hero-editor__room" style="left: 8%; top: 62%; width: 60%; height: 28%" aria-hidden="true" />
51
69
  <svg class="hero-editor__svg" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
52
70
  <template v-for="s in visible" :key="s.id">
53
- <polygon v-if="s.kind === 'zone'" class="hero-editor__zone-shape" :class="{ 'hero-editor__sel': state.moving === s.id }" :points="pts(s)" vector-effect="non-scaling-stroke" />
54
- <line v-else-if="s.kind === 'wall'" class="hero-editor__wall" :class="{ 'hero-editor__sel': state.moving === s.id }" :x1="s.points[0]!.x" :y1="s.points[0]!.y" :x2="s.points[1]!.x" :y2="s.points[1]!.y" />
71
+ <polygon v-if="s.kind === 'zone'" class="hero-editor__zone-shape" :class="{ 'hero-editor__sel': isSel(s.id) }" :points="pts(s.points)" vector-effect="non-scaling-stroke" />
72
+ <line v-else-if="s.kind === 'wall'" class="hero-editor__wall" :class="{ 'hero-editor__sel': isSel(s.id) }" :x1="s.points[0]!.x" :y1="s.points[0]!.y" :x2="s.points[1]!.x" :y2="s.points[1]!.y" />
73
+ <template v-else-if="s.kind === 'door'">
74
+ <polyline v-if="swings[s.id]" class="hero-editor__swing" :points="pts([...swings[s.id]!.leaf, ...swings[s.id]!.arc.slice().reverse()])" vector-effect="non-scaling-stroke" />
75
+ <line class="hero-editor__door" :class="{ 'hero-editor__sel': isSel(s.id) }" :x1="s.points[0]!.x" :y1="s.points[0]!.y" :x2="s.points[1]!.x" :y2="s.points[1]!.y" vector-effect="non-scaling-stroke" />
76
+ </template>
55
77
  </template>
78
+ <line v-if="rotateLine" class="hero-editor__rotline" :x1="rotateLine.x1" :y1="rotateLine.y1" :x2="rotateLine.x2" :y2="rotateLine.y2" vector-effect="non-scaling-stroke" />
56
79
  </svg>
57
80
  <template v-for="s in visible" :key="`l-${s.id}`">
58
81
  <div v-if="s.kind === 'zone'" class="hero-editor__label" :style="boxStyle(s)" :title="shapeTitle(s)">{{ s.name || "Unnamed zone" }}</div>
59
- <div v-else-if="s.kind === 'lift'" class="hero-editor__lift" :class="{ 'hero-editor__sel': state.moving === s.id }" :style="boxStyle(s)" :title="shapeTitle(s)">Lift</div>
60
- <div v-else-if="s.kind === 'door'" class="hero-editor__door" :class="{ 'hero-editor__sel': state.moving === s.id }" :style="{ left: `${shapeAnchor(s).x}%`, top: `${shapeAnchor(s).y}%` }" :title="shapeTitle(s)" />
82
+ <div v-else-if="s.kind === 'lift'" class="hero-editor__lift" :class="{ 'hero-editor__sel': isSel(s.id) }" :style="boxStyle(s)" :title="shapeTitle(s)">Lift</div>
61
83
  </template>
84
+ <div v-for="h in handles" :key="h.key" class="hero-editor__handle" :class="[`hero-editor__handle--${h.kind}`, { 'hero-editor__handle--on': h.kind === 'vertex' && state.vertex?.index === h.index }]" :style="{ left: `${h.x}%`, top: `${h.y}%`, cursor: h.kind === 'rotate' ? undefined : h.cursor }" aria-hidden="true" @pointerdown.stop="onHandleDown($event, h)" />
85
+ <span v-if="marquee" class="hero-editor__marquee" :style="rectStyle(marquee)" aria-hidden="true" />
62
86
  <span v-if="keyboard" class="hero-editor__cursor" :style="{ left: `${cursor.x}%`, top: `${cursor.y}%` }" aria-hidden="true" />
63
87
  </div>
64
88
 
65
89
  <aside class="hero-editor__aside">
90
+ <template v-if="selectedShapes.length">
91
+ <div class="hero-aside__title hero-editor__asidetitle">{{ selectedShapes.length === 1 ? shapeTitle(selectedShapes[0]!) : `${selectedShapes.length} selected` }}</div>
92
+ <div class="hero-editor__actions">
93
+ <button v-if="selectedShapes.some((s) => s.kind === 'door')" type="button" class="hero-editor__act" @click="dispatch({ type: 'flip' })">Flip swing <span class="hero-seg__kbd">F</span></button>
94
+ <button v-if="selectedShapes.some((s) => s.kind === 'door' || s.kind === 'lift')" type="button" class="hero-editor__act" @click="dispatch({ type: 'turn' })">Turn 90° <span class="hero-seg__kbd">R</span></button>
95
+ <template v-if="selectedZone">
96
+ <button type="button" class="hero-editor__act" @click="addCorner">Add corner</button>
97
+ <button type="button" class="hero-editor__act" :disabled="state.vertex?.id !== selectedZone.id || selectedZone.points.length <= 3" @click="dispatch({ type: 'remove' })">Remove corner</button>
98
+ </template>
99
+ <button type="button" class="hero-editor__act hero-editor__act--del" @click="removeSelection">Delete <span class="hero-seg__kbd">Del</span></button>
100
+ </div>
101
+ <div v-if="selectedZone" class="hero-muted">Double-click an edge to add a corner; double-click a corner to remove it.</div>
102
+ <div v-if="selectedShapes.some((s) => s.kind === 'lift')" class="hero-muted">A lift shaft turns a quarter at a time.</div>
103
+ </template>
66
104
  <div class="hero-aside__title hero-editor__asidetitle">On {{ floorName(floor) }}</div>
67
- <div v-for="s in visible" :key="`r-${s.id}`" class="hero-editor__row">
105
+ <button v-for="s in visible" :key="`r-${s.id}`" type="button" class="hero-editor__row" :class="{ 'hero-editor__row--sel': isSel(s.id) }" :aria-pressed="isSel(s.id)" @click="onRow($event, s)">
68
106
  <span>{{ shapeTitle(s) }}</span><span class="hero-editor__pos">{{ shapeAnchor(s).x }}, {{ shapeAnchor(s).y }}</span>
69
- </div>
107
+ </button>
70
108
  <div v-if="!visible.length" class="hero-muted">Nothing drawn yet. Pick a tool and click the plan.</div>
71
- <div class="hero-editor__note">The plan image comes from the robot; everything here is drawn on top of it. Keyboard: Tab to the plan, arrow keys move the cursor, Enter places.</div>
109
+ <div class="hero-editor__note">The plan image comes from the robot; everything here is drawn on top of it. Keyboard: Tab to the plan; arrow keys move the cursor (or nudge what is selected, Shift for 1 m); Enter places or selects; Delete removes; Esc clears the selection.</div>
72
110
  </aside>
73
111
  </div>
74
112
  </div>
@@ -78,21 +116,37 @@
78
116
  import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
79
117
  import { floorName, MAP_TOOLS } from "../../utils/robot-display";
80
118
  import {
119
+ DEFAULT_GRID_M,
120
+ doorSwing,
81
121
  editorProblem,
82
122
  editorReduce,
83
123
  emptyEditor,
124
+ GRID_STEPS_M,
125
+ gridShares,
126
+ hitShape,
127
+ NUDGE_BIG_M,
128
+ NUDGE_M,
129
+ PLAN_H_M,
130
+ PLAN_W_M,
84
131
  saveErrorText,
85
132
  savedNotice,
86
133
  shapeAnchor,
87
134
  shapeBox,
135
+ shapeHandles,
88
136
  shapesFromMap,
137
+ shapesInRect,
89
138
  shapesOnFloor,
90
139
  shapeTitle,
140
+ snapToGrid,
91
141
  toMapBody,
92
142
  TOOL_HINTS,
143
+ turnCentre,
144
+ type TDragOp,
145
+ type TEditorAction,
93
146
  type TEditorShape,
94
147
  type TEditorState,
95
148
  type TEditorTool,
149
+ type TShapeHandle,
96
150
  } from "../../utils/robot-building";
97
151
 
98
152
  const props = withDefaults(
@@ -112,77 +166,277 @@ const emit = defineEmits<{ saved: [] }>();
112
166
  const { createBuildingMap, updateBuildingMap } = useRobots();
113
167
 
114
168
  const state = ref<TEditorState>(emptyEditor(shapesFromMap(props.map)));
169
+ const dispatch = (a: TEditorAction) => (state.value = editorReduce(state.value, a));
115
170
  /** A newer map (after our own save, or another tab's) replaces the shapes only while nothing is unsaved. */
116
171
  watch(
117
172
  () => props.map,
118
173
  (m) => {
119
- if (!state.value.dirty) state.value = { ...emptyEditor(shapesFromMap(m)), notice: state.value.notice };
174
+ if (!state.value.dirty && !state.value.drag) state.value = { ...emptyEditor(shapesFromMap(m)), notice: state.value.notice };
120
175
  },
121
176
  );
122
177
 
123
178
  const tool = ref<TEditorTool>("wall");
124
179
  const zoneName = ref("");
180
+ const snapOn = ref(true);
181
+ const gridM = ref(DEFAULT_GRID_M);
182
+ const gridStyle = computed(() => {
183
+ const g = gridShares(gridM.value);
184
+ return { backgroundSize: `${g.x}% ${g.y}%` };
185
+ });
125
186
  const floor = ref<number>(props.startFloor !== null && props.floors.includes(props.startFloor) ? props.startFloor : props.floors[0] ?? 1);
126
187
  watch(() => props.floors, (f) => {
127
188
  if (!f.includes(floor.value)) floor.value = f[0] ?? 1;
128
189
  });
190
+ watch(floor, () => dispatch({ type: "select", ids: [] }));
129
191
  const visible = computed(() => shapesOnFloor(state.value.shapes, floor.value));
192
+ const isSel = (id: string) => state.value.selected.includes(id);
193
+ const selectedShapes = computed(() => visible.value.filter((s) => isSel(s.id)));
194
+ const single = computed(() => (selectedShapes.value.length === 1 ? selectedShapes.value[0]! : null));
195
+ const selectedZone = computed(() => (single.value?.kind === "zone" ? single.value : null));
196
+ watch(selectedZone, (z) => {
197
+ if (z) zoneName.value = z.name ?? "";
198
+ });
199
+ const handles = computed<TShapeHandle[]>(() => (single.value ? shapeHandles(single.value) : []));
200
+ const rotateLine = computed(() => {
201
+ const r = handles.value.find((h) => h.kind === "rotate");
202
+ if (!r || !single.value) return null;
203
+ const c = turnCentre(single.value);
204
+ return { x1: c.x, y1: c.y, x2: r.x, y2: r.y };
205
+ });
206
+ const swings = computed(() => Object.fromEntries(visible.value.filter((s) => s.kind === "door").map((s) => [s.id, doorSwing(s)])));
130
207
 
131
208
  function pickTool(id: TEditorTool) {
132
209
  tool.value = id;
133
- state.value = editorReduce(state.value, { type: "tool" });
210
+ dispatch({ type: "tool", tool: id });
134
211
  }
135
212
 
136
- /* ---- the plan: a click (or Enter at the keyboard cursor) ---- */
213
+ /* ---- pointer: mouse, touch and pen alike ---- */
137
214
  const plan = ref<HTMLElement | null>(null);
138
215
  const cursor = ref({ x: 50, y: 50 });
139
216
  const keyboard = ref(false);
217
+ const marquee = ref<{ x: number; y: number; w: number; h: number } | null>(null);
218
+ const hoverId = ref<string | null>(null);
219
+ type TPress = { pointer: number; x: number; y: number; cx: number; cy: number; mode: "drag" | "marquee" | "click"; op?: TDragOp; shift: boolean; started: boolean };
220
+ let press: TPress | null = null;
221
+ /** The cursor a drag in progress shows: move, rotate or a resize direction. */
222
+ const dragKind = ref("");
140
223
 
141
- /** The topmost shape under a point (walls and doors get a little slack). */
142
- function hit(x: number, y: number): TEditorShape | null {
143
- for (const s of [...visible.value].reverse()) {
144
- const b = shapeBox(s);
145
- const pad = s.kind === "wall" || s.kind === "door" ? 1.8 : 0;
146
- if (x >= b.x - pad && x <= b.x + b.w + pad && y >= b.y - pad && y <= b.y + b.h + pad) return s;
224
+ function at(e: { clientX: number; clientY: number }) {
225
+ const r = plan.value!.getBoundingClientRect();
226
+ const c = (v: number) => Math.max(0, Math.min(100, v));
227
+ return { x: c(((e.clientX - r.left) / r.width) * 100), y: c(((e.clientY - r.top) / r.height) * 100) };
228
+ }
229
+ /** How near counts as "on" a line or corner: 10 screen pixels (16 for a finger), in metres. */
230
+ function tolerance(pointerType = "mouse") {
231
+ const r = plan.value?.getBoundingClientRect();
232
+ if (!r?.width) return 0.4;
233
+ return Math.max(PLAN_W_M / r.width, PLAN_H_M / r.height) * (pointerType === "touch" ? 16 : 10);
234
+ }
235
+
236
+ function startPress(e: PointerEvent, mode: TPress["mode"], op?: TDragOp) {
237
+ const p = at(e);
238
+ press = { pointer: e.pointerId, x: p.x, y: p.y, cx: e.clientX, cy: e.clientY, mode, op, shift: e.shiftKey, started: false };
239
+ plan.value?.setPointerCapture?.(e.pointerId);
240
+ }
241
+
242
+ function onPlanDown(e: PointerEvent) {
243
+ if (e.pointerType === "mouse" && e.button !== 0) return;
244
+ plan.value?.focus({ preventScroll: true });
245
+ keyboard.value = false;
246
+ const p = at(e);
247
+ const target = hitShape(visible.value, p, tolerance(e.pointerType));
248
+ const t = tool.value;
249
+ if (t === "delete") {
250
+ if (target) dispatch({ type: "pick", id: target.id, tool: "delete" });
251
+ return;
147
252
  }
148
- return null;
149
- }
150
- function act(x: number, y: number) {
151
- const target = hit(x, y);
152
- // Move with a shape picked: this point is its destination, even over another shape.
153
- if (target && !(tool.value === "move" && state.value.moving)) {
154
- state.value = editorReduce(state.value, { type: "pick", id: target.id, tool: tool.value, zoneName: zoneName.value });
155
- if (tool.value === "move" && target.kind === "zone") zoneName.value = target.name ?? "";
253
+ if (t === "zone" && target?.kind === "zone" && zoneName.value.trim() && !isSel(target.id)) {
254
+ dispatch({ type: "pick", id: target.id, tool: "zone", zoneName: zoneName.value });
156
255
  return;
157
256
  }
158
- state.value = editorReduce(state.value, { type: "place", tool: tool.value, floorNo: floor.value, x, y, zoneName: zoneName.value, floors: props.floors });
257
+ // Move grabs anything; a drawing tool grabs only its own kind (a wall tool draws walls inside a zone, a door goes on a wall).
258
+ if (t === "move" || target?.kind === t) {
259
+ if (!target) return startPress(e, "marquee");
260
+ if (e.shiftKey) {
261
+ dispatch({ type: "select", ids: [target.id], mode: "toggle" });
262
+ return;
263
+ }
264
+ if (!isSel(target.id)) dispatch({ type: "select", ids: [target.id] });
265
+ return startPress(e, "drag", { kind: "move" });
266
+ }
267
+ // A drawing tool: place (on the grid while snapping), and select the new shape.
268
+ e.preventDefault();
269
+ const q = snapOn.value && !e.shiftKey ? snapToGrid(p, gridM.value) : p;
270
+ dispatch({ type: "place", tool: t, floorNo: floor.value, x: Math.min(98, q.x), y: Math.min(98, q.y), zoneName: zoneName.value, floors: props.floors });
271
+ }
272
+
273
+ function onHandleDown(e: PointerEvent, h: TShapeHandle) {
274
+ if ((e.pointerType === "mouse" && e.button !== 0) || !single.value) return;
275
+ plan.value?.focus({ preventScroll: true });
276
+ const id = single.value.id;
277
+ const op: TDragOp =
278
+ h.kind === "resize" ? { kind: "handle", id, handle: h.handle! } : h.kind === "vertex" ? { kind: "vertex", id, index: h.index! } : { kind: "rotate", id };
279
+ // Grabbing a zone corner marks it, so Delete / Remove corner acts on it even without a drag.
280
+ if (h.kind === "vertex" && single.value.kind === "zone") state.value = { ...state.value, vertex: { id, index: h.index! } };
281
+ startPress(e, "drag", op);
282
+ }
283
+
284
+ function onPointerMove(e: PointerEvent) {
285
+ if (!press) {
286
+ if (e.pointerType === "mouse") hoverId.value = hitShape(visible.value, at(e), tolerance())?.id ?? null;
287
+ return;
288
+ }
289
+ if (e.pointerId !== press.pointer) return;
290
+ const p = at(e);
291
+ if (!press.started) {
292
+ if (Math.hypot(e.clientX - press.cx, e.clientY - press.cy) < 3) return;
293
+ press.started = true;
294
+ if (press.mode === "drag") {
295
+ dispatch({ type: "dragStart", op: press.op!, x: press.x, y: press.y });
296
+ dragKind.value = press.op!.kind === "rotate" ? "rotate" : press.op!.kind === "handle" ? handleCursor(press.op!.handle) : "move";
297
+ }
298
+ }
299
+ if (press.mode === "drag") {
300
+ const snap = snapOn.value && !e.shiftKey;
301
+ dispatch({ type: "dragMove", x: p.x, y: p.y, grid: snap ? gridM.value : 0, tolerance: snap ? tolerance(e.pointerType) : 0 });
302
+ } else if (press.mode === "marquee") {
303
+ marquee.value = { x: press.x, y: press.y, w: p.x - press.x, h: p.y - press.y };
304
+ }
305
+ }
306
+
307
+ function endPress() {
308
+ if (press) plan.value?.releasePointerCapture?.(press.pointer);
309
+ press = null;
310
+ marquee.value = null;
311
+ dragKind.value = "";
312
+ }
313
+
314
+ function onPointerUp(e: PointerEvent) {
315
+ if (!press || e.pointerId !== press.pointer) return;
316
+ if (press.mode === "drag" && press.started) dispatch({ type: "dragEnd" });
317
+ else if (press.mode === "marquee") {
318
+ if (press.started && marquee.value) dispatch({ type: "select", ids: shapesInRect(visible.value, marquee.value), mode: press.shift ? "add" : "replace" });
319
+ else if (!press.shift) dispatch({ type: "select", ids: [] });
320
+ }
321
+ endPress();
322
+ }
323
+
324
+ function onPointerCancel() {
325
+ if (press?.mode === "drag" && press.started) dispatch({ type: "dragCancel" });
326
+ endPress();
159
327
  }
160
- function onPlanClick(e: MouseEvent) {
161
- const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
162
- const clamp = (v: number) => Math.max(0, Math.min(98, v));
163
- act(clamp(((e.clientX - r.left) / r.width) * 100), clamp(((e.clientY - r.top) / r.height) * 100));
328
+
329
+ /**
330
+ * Double-click on a selected zone: on a corner removes it, on an edge adds a
331
+ * corner there. (The plan holds the pointer during a press, so the double
332
+ * click always arrives here, even over a handle.)
333
+ */
334
+ function onDoubleClick(e: MouseEvent) {
335
+ const z = selectedZone.value;
336
+ if (!z || tool.value === "delete") return;
337
+ const p = at(e);
338
+ const r = plan.value!.getBoundingClientRect();
339
+ const reach = 14; // px
340
+ const corner = z.points.findIndex((q) => Math.hypot(((q.x - p.x) / 100) * r.width, ((q.y - p.y) / 100) * r.height) <= reach);
341
+ if (corner >= 0) dispatch({ type: "removeVertex", id: z.id, index: corner });
342
+ else dispatch({ type: "addVertex", id: z.id, x: p.x, y: p.y, within: tolerance() * 1.5 });
164
343
  }
344
+
345
+ /** Add corner (button): the middle of the zone's longest edge. */
346
+ function addCorner() {
347
+ const z = selectedZone.value;
348
+ if (!z) return;
349
+ let best = { len: -1, x: 0, y: 0 };
350
+ z.points.forEach((a, i) => {
351
+ const b = z.points[(i + 1) % z.points.length]!;
352
+ const len = Math.hypot((b.x - a.x) * PLAN_W_M, (b.y - a.y) * PLAN_H_M);
353
+ if (len > best.len) best = { len, x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
354
+ });
355
+ dispatch({ type: "addVertex", id: z.id, x: best.x, y: best.y });
356
+ }
357
+
358
+ function removeSelection() {
359
+ state.value = { ...state.value, vertex: null };
360
+ dispatch({ type: "remove" });
361
+ }
362
+
363
+ function onRow(e: MouseEvent, s: TEditorShape) {
364
+ if (tool.value !== "move") pickTool("move");
365
+ dispatch({ type: "select", ids: [s.id], mode: e.shiftKey ? "toggle" : "replace" });
366
+ }
367
+
368
+ const handleCursor = (h: string) => (h === "n" || h === "s" ? "ns" : h === "e" || h === "w" ? "ew" : h === "nw" || h === "se" ? "nwse" : "nesw");
369
+ /** The plan's cursor: what a drag is doing, else what a press would do here. */
370
+ const planCursor = computed(() => {
371
+ if (dragKind.value) return dragKind.value;
372
+ if (tool.value === "delete") return hoverId.value ? "pointer" : "default";
373
+ const hover = hoverId.value ? visible.value.find((s) => s.id === hoverId.value) : null;
374
+ if (hover && (tool.value === "move" || hover.kind === tool.value)) return "move";
375
+ return tool.value === "move" ? "default" : "crosshair";
376
+ });
377
+
378
+ /* ---- keyboard ---- */
379
+ function act(x: number, y: number, shift = false) {
380
+ const target = hitShape(visible.value, { x, y }, tolerance());
381
+ const t = tool.value;
382
+ if (t === "delete") return void (target && dispatch({ type: "pick", id: target.id, tool: "delete" }));
383
+ if (t === "zone" && target?.kind === "zone" && zoneName.value.trim() && !isSel(target.id)) {
384
+ return void dispatch({ type: "pick", id: target.id, tool: "zone", zoneName: zoneName.value });
385
+ }
386
+ if (t === "move" || target?.kind === t) {
387
+ if (target) dispatch({ type: "select", ids: [target.id], mode: shift ? "toggle" : "replace" });
388
+ return;
389
+ }
390
+ dispatch({ type: "place", tool: t, floorNo: floor.value, x: Math.min(98, x), y: Math.min(98, y), zoneName: zoneName.value, floors: props.floors });
391
+ }
392
+
165
393
  function onKey(e: KeyboardEvent) {
166
- const step = e.shiftKey ? 10 : 2;
167
- const move: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
168
- if (move[e.key]) {
394
+ const k = e.key;
395
+ if (k === "Escape") {
396
+ if (state.value.drag) onPointerCancel();
397
+ else if (state.value.selected.length) dispatch({ type: "select", ids: [] });
398
+ else keyboard.value = false;
399
+ return;
400
+ }
401
+ if (k === "Delete" || k === "Backspace") {
402
+ e.preventDefault();
403
+ return void dispatch({ type: "remove" });
404
+ }
405
+ if ((e.ctrlKey || e.metaKey) && k.toLowerCase() === "a") {
169
406
  e.preventDefault();
407
+ return void dispatch({ type: "selectAll", floorNo: floor.value });
408
+ }
409
+ if (!e.ctrlKey && !e.metaKey && !e.altKey && (k === "f" || k === "F")) return void dispatch({ type: "flip" });
410
+ if (!e.ctrlKey && !e.metaKey && !e.altKey && (k === "r" || k === "R")) return void dispatch({ type: "turn" });
411
+ const dir: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
412
+ if (dir[k]) {
413
+ e.preventDefault();
414
+ const [dx, dy] = dir[k]!;
415
+ if (state.value.selected.length && !state.value.drag) {
416
+ const m = e.shiftKey ? NUDGE_BIG_M : NUDGE_M;
417
+ return void dispatch({ type: "nudge", dx: dx * m, dy: dy * m });
418
+ }
170
419
  keyboard.value = true;
171
- const [dx, dy] = move[e.key]!;
172
- cursor.value = { x: Math.max(0, Math.min(98, cursor.value.x + dx)), y: Math.max(0, Math.min(98, cursor.value.y + dy)) };
173
- } else if (e.key === "Enter" || e.key === " ") {
420
+ const step = e.shiftKey ? 10 : 2;
421
+ cursor.value = { x: Math.max(0, Math.min(98, cursor.value.x + dx * step)), y: Math.max(0, Math.min(98, cursor.value.y + dy * step)) };
422
+ } else if (k === "Enter" || k === " ") {
174
423
  e.preventDefault();
175
424
  keyboard.value = true;
176
- act(cursor.value.x, cursor.value.y);
425
+ act(cursor.value.x, cursor.value.y, e.shiftKey);
177
426
  }
178
427
  }
179
428
 
180
- /** Ctrl/Cmd+Z anywhere in the editor except while typing a name. */
429
+ /** Ctrl/Cmd+Z undo, Ctrl/Cmd+Shift+Z or Ctrl+Y redo - anywhere in the editor except while typing. */
181
430
  function onUndoKey(e: KeyboardEvent) {
182
- if (!(e.ctrlKey || e.metaKey) || e.key.toLowerCase() !== "z" || e.shiftKey) return;
183
- if ((e.target as HTMLElement)?.tagName === "INPUT") return;
431
+ if (!(e.ctrlKey || e.metaKey)) return;
432
+ const k = e.key.toLowerCase();
433
+ const redo = (k === "z" && e.shiftKey) || (k === "y" && !e.shiftKey);
434
+ if (!(k === "z" && !e.shiftKey) && !redo) return;
435
+ const tag = (e.target as HTMLElement)?.tagName;
436
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
184
437
  e.preventDefault();
185
- state.value = editorReduce(state.value, { type: "undo" });
438
+ if (state.value.drag) return;
439
+ dispatch({ type: redo ? "redo" : "undo" });
186
440
  }
187
441
  onMounted(() => window.addEventListener("keydown", onUndoKey));
188
442
  onBeforeUnmount(() => window.removeEventListener("keydown", onUndoKey));
@@ -191,13 +445,13 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onUndoKey));
191
445
  const saving = ref(false);
192
446
  async function save() {
193
447
  const problem = editorProblem(state.value);
194
- if (problem) return void (state.value = editorReduce(state.value, { type: "notice", text: problem, ok: false }));
448
+ if (problem) return void dispatch({ type: "notice", text: problem, ok: false });
195
449
  if (!props.map?._id && !props.ownerRobotId) {
196
- return void (state.value = editorReduce(state.value, {
450
+ return void dispatch({
197
451
  type: "notice",
198
452
  text: "Can't save yet: this site has no robot to keep the map with. Add a robot to the site first, then draw the map.",
199
453
  ok: false,
200
- }));
454
+ });
201
455
  }
202
456
  const name = String(props.map?.name || `${props.siteName || "Site"} building`).slice(0, 60);
203
457
  const body = toMapBody(state.value.shapes, name, props.map);
@@ -205,21 +459,24 @@ async function save() {
205
459
  try {
206
460
  if (props.map?._id) await updateBuildingMap(String(props.map._id), { ...body, version: Number(props.map.version) || 1 });
207
461
  else await createBuildingMap({ ...body, robotId: props.ownerRobotId });
208
- state.value = editorReduce(state.value, { type: "saved", text: savedNotice(new Date(), state.value.shapes.length, props.siteName) });
462
+ dispatch({ type: "saved", text: savedNotice(new Date(), state.value.shapes.length, props.siteName) });
209
463
  emit("saved");
210
464
  } catch (e) {
211
- state.value = editorReduce(state.value, { type: "notice", text: saveErrorText(e), ok: false });
465
+ dispatch({ type: "notice", text: saveErrorText(e), ok: false });
212
466
  } finally {
213
467
  saving.value = false;
214
468
  }
215
469
  }
216
470
 
217
471
  /* ---- drawing helpers + full screen ---- */
218
- const pts = (s: TEditorShape) => s.points.map((p) => `${p.x},${p.y}`).join(" ");
472
+ const pts = (list: Array<{ x: number; y: number }>) => list.map((p) => `${p.x},${p.y}`).join(" ");
219
473
  function boxStyle(s: TEditorShape) {
220
474
  const b = shapeBox(s);
221
475
  return { left: `${b.x}%`, top: `${b.y}%`, width: `${b.w}%`, height: `${b.h}%` };
222
476
  }
477
+ function rectStyle(r: { x: number; y: number; w: number; h: number }) {
478
+ return { left: `${Math.min(r.x, r.x + r.w)}%`, top: `${Math.min(r.y, r.y + r.h)}%`, width: `${Math.abs(r.w)}%`, height: `${Math.abs(r.h)}%` };
479
+ }
223
480
  const root = ref<HTMLElement | null>(null);
224
481
  const isFs = ref(false);
225
482
  const onFs = () => (isFs.value = document.fullscreenElement === root.value);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@7365admin1/layer-common",
3
3
  "license": "MIT",
4
4
  "type": "module",
5
- "version": "4.35.1-staging.370",
5
+ "version": "4.35.1-staging.371",
6
6
  "author": "7365admin1",
7
7
  "main": "./nuxt.config.ts",
8
8
  "//files": "What a consumer extending this layer actually loads. Without this npm ships the whole working tree - the changesets, the CI workflows, the render harness in tools/ and any scratch directory that happened to exist at publish time. Nuxt resolves a layer by directory, so every runtime directory below has to stay listed; adding a new top-level runtime directory means adding it here too.",
@@ -5,7 +5,19 @@
5
5
  * pins every number the handoff states (clamps, presets, zoom bounds, the
6
6
  * editor's words, the lift chips).
7
7
  */
8
- import { layoutProblem, nextFeatureName, popUndo, pushUndo, type TMapPointM } from "./building-map";
8
+ import {
9
+ distanceToSegment,
10
+ layoutProblem,
11
+ MAX_ZONE_POINTS,
12
+ MIN_WALL_M,
13
+ nearestPoint,
14
+ nextFeatureName,
15
+ pointInPolygon,
16
+ polygonArea,
17
+ popUndo,
18
+ pushUndo,
19
+ type TMapPointM,
20
+ } from "./building-map";
9
21
  import { floorName } from "./robot-display";
10
22
 
11
23
  /* ================================================================ camera */
@@ -153,11 +165,27 @@ export type TEditorShape = {
153
165
  meta?: Record<string, unknown>;
154
166
  };
155
167
 
168
+ /** A drag handle: the eight box handles (corners + edges). */
169
+ export type THandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
170
+
171
+ /** What a pointer drag does: move the selection, resize from a box handle, drag one corner/end, or turn. */
172
+ export type TDragOp =
173
+ | { kind: "move" }
174
+ | { kind: "handle"; id: string; handle: THandle }
175
+ | { kind: "vertex"; id: string; index: number }
176
+ | { kind: "rotate"; id: string };
177
+
156
178
  export type TEditorState = {
157
179
  shapes: TEditorShape[];
158
180
  undo: string[];
159
- /** The shape Move picked (outlined), waiting for its destination. */
160
- moving: string | null;
181
+ /** Undone layouts, newest last; any new edit clears it. */
182
+ redo: string[];
183
+ /** Selected shape ids (Shift adds; a box drag selects an area). */
184
+ selected: string[];
185
+ /** The zone corner last grabbed - Delete removes that corner instead of the zone. */
186
+ vertex: { id: string; index: number } | null;
187
+ /** A drag in progress and the layout it started from: the whole drag is one undo step, and Esc puts it back. */
188
+ drag: { base: TEditorShape[]; op: TDragOp; x: number; y: number } | null;
161
189
  notice: { text: string; ok: boolean } | null;
162
190
  dirty: boolean;
163
191
  };
@@ -166,11 +194,27 @@ export type TEditorAction =
166
194
  | { type: "place"; tool: TEditorTool; floorNo: number; x: number; y: number; zoneName?: string; floors?: number[]; id?: string }
167
195
  | { type: "pick"; id: string; tool: TEditorTool; zoneName?: string }
168
196
  | { type: "rename"; name: string }
169
- | { type: "tool" }
197
+ | { type: "tool"; tool?: TEditorTool }
170
198
  | { type: "undo" }
199
+ | { type: "redo" }
171
200
  | { type: "notice"; text: string; ok: boolean }
172
201
  | { type: "saved"; text: string }
173
- | { type: "load"; shapes: TEditorShape[] };
202
+ | { type: "load"; shapes: TEditorShape[] }
203
+ | { type: "select"; ids: string[]; mode?: "replace" | "add" | "toggle" }
204
+ | { type: "selectAll"; floorNo: number }
205
+ | { type: "dragStart"; op: TDragOp; x: number; y: number }
206
+ /** `grid` = snap step in metres (0 = off, e.g. Shift held); `tolerance` = how near (metres) an end snaps onto another shape's end. */
207
+ | { type: "dragMove"; x: number; y: number; grid?: number; tolerance?: number }
208
+ | { type: "dragEnd" }
209
+ | { type: "dragCancel" }
210
+ /** Arrow keys, in metres. */
211
+ | { type: "nudge"; dx: number; dy: number }
212
+ /** Delete / Backspace: the grabbed zone corner, else the selection. */
213
+ | { type: "remove" }
214
+ | { type: "flip" }
215
+ | { type: "turn" }
216
+ | { type: "addVertex"; id: string; x: number; y: number; within?: number }
217
+ | { type: "removeVertex"; id: string; index: number };
174
218
 
175
219
  /** The handoff's default sizes (shares of the plan): wall 16 x 1.5, zone 22 x 24, door 3, lift 8 x 14. */
176
220
  export const SHAPE_SIZE: Record<TShapeKind, { w: number; h: number }> = {
@@ -185,7 +229,7 @@ export const TOOL_HINTS: Record<TEditorTool, string> = {
185
229
  zone: "Click to place a zone, then name it.",
186
230
  door: "Click a wall position to place a door.",
187
231
  lift: "Click to place a lift shaft; it runs through every floor.",
188
- move: "Click a shape, then click where it should go.",
232
+ move: "Click to select (Shift adds), drag to move, drag a handle to resize or turn. Drag on empty space to select an area. Shift while dragging turns snapping off.",
189
233
  delete: "Click a shape to delete it.",
190
234
  };
191
235
 
@@ -243,31 +287,347 @@ export function shapeTitle(s: TEditorShape): string {
243
287
  return s.kind === "door" ? "Door" : "Wall";
244
288
  }
245
289
 
246
- /** Moved so its anchor lands on (x, y), kept inside the plan. */
247
- export function moveShape(s: TEditorShape, x: number, y: number): TEditorShape {
248
- const a = anchorOf(s);
249
- const b = shapeBox(s);
250
- let dx = clampShare(x) - a.x;
251
- let dy = clampShare(y) - a.y;
252
- dx = Math.max(-b.x, Math.min(100 - (b.x + b.w), dx));
253
- dy = Math.max(-b.y, Math.min(100 - (b.y + b.h), dy));
254
- return { ...s, points: s.points.map((p) => ({ x: round2(p.x + dx), y: round2(p.y + dy) })) };
255
- }
256
-
257
290
  /** The shapes on one floor: its own, plus every lift shaft (they run through all floors). */
258
291
  export const shapesOnFloor = (shapes: TEditorShape[], floorNo: number) =>
259
292
  shapes.filter((s) => s.kind === "lift" || s.floorNo === floorNo);
260
293
 
261
294
  export function emptyEditor(shapes: TEditorShape[] = []): TEditorState {
262
- return { shapes, undo: [], moving: null, notice: null, dirty: false };
295
+ return { shapes, undo: [], redo: [], selected: [], vertex: null, drag: null, notice: null, dirty: false };
296
+ }
297
+
298
+ /* ---- editing geometry: the plan is in shares (0-100 each way); angles and distances are real metres ---- */
299
+
300
+ const MX = PLAN_W_M / 100;
301
+ const MY = PLAN_H_M / 100;
302
+ const inM = (p: { x: number; y: number }) => ({ x: p.x * MX, y: p.y * MY });
303
+ const inShare = (p: { x: number; y: number }) => ({ x: p.x / MX, y: p.y / MY });
304
+ const r2 = (p: { x: number; y: number }) => ({ x: round2(p.x), y: round2(p.y) });
305
+ const clamp100 = (n: number) => Math.max(0, Math.min(100, n));
306
+
307
+ /** Lift shafts: what the API accepts (0.5-10 m a side). Zones: at least 0.5 m a side while resizing. */
308
+ export const LIFT_MIN_M = 0.5;
309
+ export const LIFT_MAX_M = 10;
310
+ export const ZONE_MIN_M = 0.5;
311
+ /** Grid steps offered (metres) and the default. */
312
+ export const GRID_STEPS_M = [0.25, 0.5, 1, 2];
313
+ export const DEFAULT_GRID_M = 1;
314
+ /** Arrow-key nudge: 0.1 m, Shift 1 m. A door turn snaps to 15 degrees while snapping is on. */
315
+ export const NUDGE_M = 0.1;
316
+ export const NUDGE_BIG_M = 1;
317
+ export const ROTATE_SNAP_DEG = 15;
318
+
319
+ /** One grid step in shares across and down (the plan is 40 x 26 m). */
320
+ export const gridShares = (stepM: number) => ({ x: (stepM / PLAN_W_M) * 100, y: (stepM / PLAN_H_M) * 100 });
321
+
322
+ /** The nearest grid crossing, in shares, inside the plan. No step = only rounded. */
323
+ export function snapToGrid(p: { x: number; y: number }, stepM: number): { x: number; y: number } {
324
+ if (!(stepM > 0)) return r2({ x: clamp100(p.x), y: clamp100(p.y) });
325
+ const m = inM(p);
326
+ const q = inShare({ x: Math.round(m.x / stepM) * stepM, y: Math.round(m.y / stepM) * stepM });
327
+ return r2({ x: clamp100(q.x), y: clamp100(q.y) });
328
+ }
329
+
330
+ /** A dragged corner or end: onto another shape's corner or end within `toleranceM`, else the grid (if on). */
331
+ export function snapPoint(p: { x: number; y: number }, gridM: number, targets: Array<{ x: number; y: number }>, toleranceM: number) {
332
+ const i = targets.length && toleranceM > 0 ? nearestPoint(inM(p), targets.map(inM), toleranceM) : -1;
333
+ return i >= 0 ? { ...targets[i]! } : snapToGrid(p, gridM);
334
+ }
335
+
336
+ /**
337
+ * The shape under a point (shares): doors, then lift shafts, walls, then
338
+ * zones (the smallest first); the newest first within a kind. Walls and doors
339
+ * count within `toleranceM` of their line; a zone inside or near its edge.
340
+ */
341
+ export function hitShape(shapes: TEditorShape[], p: { x: number; y: number }, toleranceM: number): TEditorShape | null {
342
+ const q = inM(p);
343
+ const rank: Record<TShapeKind, number> = { door: 0, lift: 1, wall: 2, zone: 3 };
344
+ const hits = [...shapes].reverse().filter((s) => {
345
+ const pts = s.points.map(inM);
346
+ if (s.kind === "wall" || s.kind === "door") return pts.length > 1 && distanceToSegment(q, pts[0]!, pts[1]!) <= toleranceM;
347
+ if (s.kind === "lift") {
348
+ const b = shapeBox(s);
349
+ return p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h;
350
+ }
351
+ return pointInPolygon(q, pts) || pts.some((a, i) => distanceToSegment(q, a, pts[(i + 1) % pts.length]!) <= toleranceM);
352
+ });
353
+ const area = (s: TEditorShape) => (s.kind === "zone" ? polygonArea(s.points.map(inM)) : 0);
354
+ hits.sort((a, b) => rank[a.kind] - rank[b.kind] || area(a) - area(b));
355
+ return hits[0] ?? null;
356
+ }
357
+
358
+ /** The ids a box drag (shares) selects: every shape whose outline box it touches. */
359
+ export function shapesInRect(shapes: TEditorShape[], r: { x: number; y: number; w: number; h: number }): string[] {
360
+ const x0 = Math.min(r.x, r.x + r.w);
361
+ const x1 = Math.max(r.x, r.x + r.w);
362
+ const y0 = Math.min(r.y, r.y + r.h);
363
+ const y1 = Math.max(r.y, r.y + r.h);
364
+ return shapes
365
+ .filter((s) => {
366
+ const b = shapeBox(s);
367
+ return b.x <= x1 && b.x + b.w >= x0 && b.y <= y1 && b.y + b.h >= y0;
368
+ })
369
+ .map((s) => s.id);
370
+ }
371
+
372
+ export type TShapeHandle = {
373
+ key: string;
374
+ kind: "resize" | "vertex" | "rotate";
375
+ x: number;
376
+ y: number;
377
+ cursor: string;
378
+ handle?: THandle;
379
+ index?: number;
380
+ };
381
+
382
+ const HANDLE_CURSOR: Record<THandle, string> = {
383
+ nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize", n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize",
384
+ };
385
+ const HANDLES: THandle[] = ["nw", "n", "ne", "e", "se", "s", "sw", "w"];
386
+
387
+ function boxHandles(s: TEditorShape): TShapeHandle[] {
388
+ const b = shapeBox(s);
389
+ return HANDLES.map((h) => ({
390
+ key: h,
391
+ kind: "resize",
392
+ handle: h,
393
+ x: h.includes("w") ? b.x : h.includes("e") ? b.x + b.w : b.x + b.w / 2,
394
+ y: h.includes("n") ? b.y : h.includes("s") ? b.y + b.h : b.y + b.h / 2,
395
+ cursor: HANDLE_CURSOR[h],
396
+ }));
397
+ }
398
+
399
+ /** What a turn goes round (shares): a door's middle, a lift shaft's centre. */
400
+ export function turnCentre(s: TEditorShape) {
401
+ if (s.kind === "door") {
402
+ const [a, b] = s.points;
403
+ return { x: ((a?.x ?? 0) + (b?.x ?? 0)) / 2, y: ((a?.y ?? 0) + (b?.y ?? 0)) / 2 };
404
+ }
405
+ const b = shapeBox(s);
406
+ return { x: b.x + b.w / 2, y: b.y + b.h / 2 };
407
+ }
408
+
409
+ /**
410
+ * The handles one selected shape shows: a wall's two ends; a door's two ends
411
+ * + a turn handle 2 m out on the side away from its swing; a lift shaft's
412
+ * eight box handles + a turn handle above it; a zone's eight box handles + a
413
+ * handle on every corner the box handles don't already cover.
414
+ */
415
+ export function shapeHandles(s: TEditorShape): TShapeHandle[] {
416
+ const ends = (): TShapeHandle[] => s.points.map((p, i) => ({ key: `v${i}`, kind: "vertex", index: i, x: p.x, y: p.y, cursor: "move" }));
417
+ if (s.kind === "wall") return ends();
418
+ if (s.kind === "door") {
419
+ const [a, b] = s.points.map(inM);
420
+ const len = Math.hypot(b!.x - a!.x, b!.y - a!.y) || 1;
421
+ const c = inM(turnCentre(s));
422
+ const t = inShare({ x: c.x - ((b!.y - a!.y) / len) * 2, y: c.y + ((b!.x - a!.x) / len) * 2 });
423
+ return [...ends(), { key: "rot", kind: "rotate", x: round2(clamp100(t.x)), y: round2(clamp100(t.y)), cursor: "grab" }];
424
+ }
425
+ const box = boxHandles(s);
426
+ if (s.kind === "lift") {
427
+ const b = shapeBox(s);
428
+ const gap = gridShares(1.5).y;
429
+ const y = b.y - gap >= 0 ? b.y - gap : b.y + b.h + gap;
430
+ return [...box, { key: "rot", kind: "rotate", x: round2(b.x + b.w / 2), y: round2(y), cursor: "grab" }];
431
+ }
432
+ const corners = box.filter((h) => h.handle!.length === 2);
433
+ const own = ends().filter((v) => !corners.some((c) => Math.abs(c.x - v.x) < 0.3 && Math.abs(c.y - v.y) < 0.3));
434
+ return [...box, ...own];
435
+ }
436
+
437
+ /**
438
+ * Resize a box from one handle: the opposite side stays put, the dragged side
439
+ * follows the point, never smaller than `min` or larger than `max` (shares)
440
+ * and never past the plan's edge. Width and height change independently.
441
+ */
442
+ export function resizeBox(
443
+ b: { x: number; y: number; w: number; h: number },
444
+ handle: THandle,
445
+ p: { x: number; y: number },
446
+ min: { w: number; h: number },
447
+ max: { w: number; h: number } = { w: Infinity, h: Infinity },
448
+ ) {
449
+ let x0 = b.x;
450
+ let y0 = b.y;
451
+ let x1 = b.x + b.w;
452
+ let y1 = b.y + b.h;
453
+ if (handle.includes("w")) x0 = Math.min(Math.max(p.x, x1 - max.w, 0), x1 - min.w);
454
+ if (handle.includes("e")) x1 = Math.max(Math.min(p.x, x0 + max.w, 100), x0 + min.w);
455
+ if (handle.includes("n")) y0 = Math.min(Math.max(p.y, y1 - max.h, 0), y1 - min.h);
456
+ if (handle.includes("s")) y1 = Math.max(Math.min(p.y, y0 + max.h, 100), y0 + min.h);
457
+ return { x: round2(x0), y: round2(y0), w: round2(x1 - x0), h: round2(y1 - y0) };
263
458
  }
264
459
 
460
+ /** A lift shaft or zone resized from a box handle; a zone's corners scale with its box. */
461
+ export function resizeShape(s: TEditorShape, handle: THandle, p: { x: number; y: number }): TEditorShape {
462
+ const b = shapeBox(s);
463
+ if (s.kind === "lift") {
464
+ const min = gridShares(LIFT_MIN_M);
465
+ const max = gridShares(LIFT_MAX_M);
466
+ const n = resizeBox(b, handle, p, { w: min.x, h: min.y }, { w: max.x, h: max.y });
467
+ return { ...s, points: rect(n.x, n.y, n.w, n.h).map(r2) };
468
+ }
469
+ if (s.kind !== "zone") return s;
470
+ const min = gridShares(ZONE_MIN_M);
471
+ const n = resizeBox(b, handle, p, { w: min.x, h: min.y });
472
+ return {
473
+ ...s,
474
+ points: s.points.map((q) => r2({ x: n.x + (b.w ? ((q.x - b.x) / b.w) * n.w : 0), y: n.y + (b.h ? ((q.y - b.y) / b.h) * n.h : 0) })),
475
+ };
476
+ }
477
+
478
+ /** Drag one corner of a zone or one end of a wall / door. A wall or door never gets shorter than 0.1 m. */
479
+ export function moveVertex(s: TEditorShape, index: number, p: { x: number; y: number }): TEditorShape {
480
+ if (!s.points[index]) return s;
481
+ const points = s.points.map((q, i) => (i === index ? r2({ x: clamp100(p.x), y: clamp100(p.y) }) : q));
482
+ if (s.kind === "wall" || s.kind === "door") {
483
+ const [a, b] = points.map(inM);
484
+ if (Math.hypot(b!.x - a!.x, b!.y - a!.y) < MIN_WALL_M) return s;
485
+ }
486
+ return { ...s, points };
487
+ }
488
+
489
+ /** Shifted back inside the plan if a turn pushed it over an edge. */
490
+ function keepInside(s: TEditorShape): TEditorShape {
491
+ const b = shapeBox(s);
492
+ const dx = b.x < 0 ? -b.x : b.x + b.w > 100 ? 100 - (b.x + b.w) : 0;
493
+ const dy = b.y < 0 ? -b.y : b.y + b.h > 100 ? 100 - (b.y + b.h) : 0;
494
+ return dx || dy ? { ...s, points: s.points.map((q) => r2({ x: q.x + dx, y: q.y + dy })) } : s;
495
+ }
496
+
497
+ /**
498
+ * Turn a door (any angle, round its middle) or a lift shaft (quarter turns
499
+ * round its centre - width and depth swap). The building map stores a lift
500
+ * shaft as width x depth with no angle, so a shaft only turns in 90 degree
501
+ * steps. Other shapes do not turn.
502
+ * ponytail: quarter turns only until the map stores a lift angle (spec batch 2).
503
+ */
504
+ export function rotateShape(s: TEditorShape, deg: number): TEditorShape {
505
+ const c = inM(turnCentre(s));
506
+ if (s.kind === "door") {
507
+ const rad = (deg * Math.PI) / 180;
508
+ const cos = Math.cos(rad);
509
+ const sin = Math.sin(rad);
510
+ const points = s.points.map((q) => {
511
+ const m = inM(q);
512
+ return r2(inShare({ x: c.x + (m.x - c.x) * cos - (m.y - c.y) * sin, y: c.y + (m.x - c.x) * sin + (m.y - c.y) * cos }));
513
+ });
514
+ return keepInside({ ...s, points });
515
+ }
516
+ if (s.kind !== "lift") return s;
517
+ const quarter = ((Math.round(deg / 90) % 4) + 4) % 4;
518
+ if (quarter % 2 === 0) return s;
519
+ const b = shapeBox(s);
520
+ const w = (b.h * MY) / MX;
521
+ const h = (b.w * MX) / MY;
522
+ const ctr = turnCentre(s);
523
+ return keepInside({ ...s, points: rect(ctr.x - w / 2, ctr.y - h / 2, w, h).map(r2) });
524
+ }
525
+
526
+ /** The angle (degrees, in real metres) from `c` to `p`. */
527
+ export function angleAt(c: { x: number; y: number }, p: { x: number; y: number }): number {
528
+ const a = inM(c);
529
+ const b = inM(p);
530
+ return (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;
531
+ }
532
+
533
+ /** A door's swing flipped: its two ends swap, so the hinge moves to the other end and it opens to the other side. */
534
+ export const flipDoor = (s: TEditorShape): TEditorShape => (s.kind === "door" ? { ...s, points: [s.points[1]!, s.points[0]!] } : s);
535
+
536
+ /** A new zone corner at the point, on the edge nearest it (and its index) - or null when the zone is full or no edge is within `withinM`. */
537
+ export function addVertex(s: TEditorShape, p: { x: number; y: number }, withinM = Infinity): { shape: TEditorShape; index: number } | null {
538
+ if (s.kind !== "zone" || s.points.length >= MAX_ZONE_POINTS) return null;
539
+ const q = inM(p);
540
+ const pts = s.points.map(inM);
541
+ let best = 0;
542
+ let bestD = Infinity;
543
+ pts.forEach((a, i) => {
544
+ const d = distanceToSegment(q, a, pts[(i + 1) % pts.length]!);
545
+ if (d < bestD) {
546
+ bestD = d;
547
+ best = i;
548
+ }
549
+ });
550
+ if (bestD > withinM) return null;
551
+ const points = [...s.points];
552
+ points.splice(best + 1, 0, r2({ x: clamp100(p.x), y: clamp100(p.y) }));
553
+ return { shape: { ...s, points }, index: best + 1 };
554
+ }
555
+
556
+ /** A zone corner removed - or null: a zone keeps at least three. */
557
+ export function removeVertex(s: TEditorShape, index: number): TEditorShape | null {
558
+ if (s.kind !== "zone" || s.points.length <= 3 || !s.points[index]) return null;
559
+ return { ...s, points: s.points.filter((_, i) => i !== index) };
560
+ }
561
+
562
+ /** The listed shapes moved together by (dx, dy) shares, stopping at the plan's edge as a group. */
563
+ export function translateShapes(shapes: TEditorShape[], ids: string[], dx: number, dy: number): TEditorShape[] {
564
+ const moving = shapes.filter((s) => ids.includes(s.id));
565
+ if (!moving.length) return shapes;
566
+ const boxes = moving.map(shapeBox);
567
+ const x0 = Math.min(...boxes.map((b) => b.x));
568
+ const y0 = Math.min(...boxes.map((b) => b.y));
569
+ const x1 = Math.max(...boxes.map((b) => b.x + b.w));
570
+ const y1 = Math.max(...boxes.map((b) => b.y + b.h));
571
+ const mx = Math.max(-x0, Math.min(100 - x1, dx));
572
+ const my = Math.max(-y0, Math.min(100 - y1, dy));
573
+ if (!mx && !my) return shapes;
574
+ return shapes.map((s) => (ids.includes(s.id) ? { ...s, points: s.points.map((q) => r2({ x: q.x + mx, y: q.y + my })) } : s));
575
+ }
576
+
577
+ /** A hinged door's swing (shares): the leaf standing open from the hinge (its start) and the quarter arc. Sliding doors have none. */
578
+ export function doorSwing(s: TEditorShape): { leaf: Array<{ x: number; y: number }>; arc: Array<{ x: number; y: number }> } | null {
579
+ if (s.kind !== "door" || s.meta?.type === "sliding" || s.points.length < 2) return null;
580
+ const [h, e] = s.points.map(inM);
581
+ const len = Math.hypot(e!.x - h!.x, e!.y - h!.y);
582
+ if (!len) return null;
583
+ const a0 = Math.atan2(e!.y - h!.y, e!.x - h!.x);
584
+ const at = (a: number) => r2(inShare({ x: h!.x + Math.cos(a) * len, y: h!.y + Math.sin(a) * len }));
585
+ const arc = Array.from({ length: 9 }, (_, i) => at(a0 - (Math.PI / 2) * (i / 8)));
586
+ return { leaf: [r2(inShare(h!)), arc[8]!], arc };
587
+ }
588
+
589
+ /* ---- the reducer ---- */
590
+
591
+ const sameLayout = (a: TEditorShape[], b: TEditorShape[]) => a === b || JSON.stringify(a) === JSON.stringify(b);
592
+ const keepSelected = (ids: string[], shapes: TEditorShape[]) => ids.filter((id) => shapes.some((s) => s.id === id));
593
+
265
594
  function commit(state: TEditorState, shapes: TEditorShape[]): TEditorState {
266
595
  const undo = [...state.undo];
267
596
  pushUndo(undo, state.shapes);
268
- return { ...state, shapes, undo, notice: null, dirty: true };
597
+ return { ...state, shapes, undo, redo: [], selected: keepSelected(state.selected, shapes), vertex: null, drag: null, notice: null, dirty: true };
598
+ }
599
+
600
+ /** The layout a drag gives, worked out from where it started - so snapping never drifts and one drag is one step. */
601
+ function dragShapes(state: TEditorState, x: number, y: number, gridM: number, toleranceM: number): TEditorShape[] {
602
+ const d = state.drag!;
603
+ const base = d.base;
604
+ const op = d.op;
605
+ if (op.kind === "move") {
606
+ const first = base.find((s) => state.selected.includes(s.id));
607
+ if (!first) return base;
608
+ const ref = first.points[0]!;
609
+ const raw = { x: ref.x + x - d.x, y: ref.y + y - d.y };
610
+ const to = gridM > 0 ? snapToGrid(raw, gridM) : raw;
611
+ return translateShapes(base, state.selected, to.x - ref.x, to.y - ref.y);
612
+ }
613
+ const target = base.find((s) => s.id === op.id);
614
+ if (!target) return base;
615
+ let next: TEditorShape;
616
+ if (op.kind === "handle") next = resizeShape(target, op.handle, snapToGrid({ x, y }, gridM));
617
+ else if (op.kind === "vertex") {
618
+ const ends = shapesOnFloor(base, target.floorNo).filter((s) => s.id !== target.id).flatMap((s) => s.points);
619
+ next = moveVertex(target, op.index, snapPoint({ x, y }, gridM, ends, toleranceM));
620
+ } else {
621
+ const c = turnCentre(target);
622
+ let deg = angleAt(c, { x, y }) - angleAt(c, { x: d.x, y: d.y });
623
+ if (target.kind === "door" && gridM > 0) deg = Math.round(deg / ROTATE_SNAP_DEG) * ROTATE_SNAP_DEG;
624
+ next = rotateShape(target, deg);
625
+ }
626
+ return base.map((s) => (s.id === target.id ? next : s));
269
627
  }
270
628
 
629
+ const TOO_FEW_CORNERS = "A zone needs at least three corners - this one can't lose another.";
630
+
271
631
  let seq = 0;
272
632
  const nextId = () => `sh${Date.now().toString(36)}${(seq++).toString(36)}`;
273
633
 
@@ -276,28 +636,108 @@ export function editorReduce(state: TEditorState, action: TEditorAction): TEdito
276
636
  case "load":
277
637
  return emptyEditor(action.shapes);
278
638
  case "tool":
279
- return { ...state, moving: null, notice: null };
639
+ // Move keeps the selection (place, then adjust); a drawing tool starts clean.
640
+ return { ...state, selected: action.tool === "move" ? state.selected : [], vertex: null, notice: null };
280
641
  case "notice":
281
642
  return { ...state, notice: { text: action.text, ok: action.ok } };
282
643
  case "saved":
283
- return { ...state, undo: [], moving: null, dirty: false, notice: { text: action.text, ok: true } };
284
- case "undo": {
285
- if (!state.undo.length) return { ...state, notice: { text: "Nothing to undo.", ok: false } };
286
- const undo = [...state.undo];
287
- const shapes = popUndo<TEditorShape[]>(undo) ?? state.shapes;
288
- return { ...state, shapes, undo, moving: null, notice: null, dirty: true };
644
+ return { ...state, undo: [], redo: [], drag: null, dirty: false, notice: { text: action.text, ok: true } };
645
+ case "undo":
646
+ case "redo": {
647
+ const isUndo = action.type === "undo";
648
+ const from = [...(isUndo ? state.undo : state.redo)];
649
+ if (!from.length) return { ...state, notice: { text: isUndo ? "Nothing to undo." : "Nothing to redo.", ok: false } };
650
+ const to = [...(isUndo ? state.redo : state.undo)];
651
+ const shapes = popUndo<TEditorShape[]>(from) ?? state.shapes;
652
+ pushUndo(to, state.shapes);
653
+ return {
654
+ ...state,
655
+ shapes,
656
+ undo: isUndo ? from : to,
657
+ redo: isUndo ? to : from,
658
+ selected: keepSelected(state.selected, shapes),
659
+ vertex: null,
660
+ drag: null,
661
+ notice: null,
662
+ dirty: true,
663
+ };
289
664
  }
290
665
  case "rename": {
291
- // Typing in the Zone field renames the zone Move has picked (no undo step per key).
292
- const target = state.shapes.find((s) => s.id === state.moving);
666
+ // Typing in the Zone field renames the selected zone (no undo step per key).
667
+ const target = state.selected.length === 1 ? state.shapes.find((s) => s.id === state.selected[0]) : undefined;
293
668
  if (!target || target.kind !== "zone") return state;
294
669
  return { ...state, dirty: true, shapes: state.shapes.map((s) => (s.id === target.id ? { ...s, name: action.name.trim() } : s)) };
295
670
  }
671
+ case "select": {
672
+ const mode = action.mode ?? "replace";
673
+ const sel = mode === "replace" ? [] : [...state.selected];
674
+ for (const id of action.ids) {
675
+ const i = sel.indexOf(id);
676
+ if (i >= 0 && mode === "toggle") sel.splice(i, 1);
677
+ else if (i < 0) sel.push(id);
678
+ }
679
+ return { ...state, selected: keepSelected(sel, state.shapes), vertex: null, notice: null };
680
+ }
681
+ case "selectAll":
682
+ return { ...state, selected: shapesOnFloor(state.shapes, action.floorNo).map((s) => s.id), vertex: null };
683
+ case "dragStart": {
684
+ if (action.op.kind === "move" && !state.selected.length) return state;
685
+ const vertex = action.op.kind === "vertex" ? { id: action.op.id, index: action.op.index } : null;
686
+ return { ...state, drag: { base: state.shapes, op: action.op, x: action.x, y: action.y }, vertex, notice: null };
687
+ }
688
+ case "dragMove":
689
+ if (!state.drag) return state;
690
+ return { ...state, shapes: dragShapes(state, action.x, action.y, action.grid ?? 0, action.tolerance ?? 0) };
691
+ case "dragEnd": {
692
+ if (!state.drag) return state;
693
+ const base = state.drag.base;
694
+ if (sameLayout(base, state.shapes)) return { ...state, drag: null };
695
+ const undo = [...state.undo];
696
+ pushUndo(undo, base);
697
+ return { ...state, undo, redo: [], drag: null, dirty: true };
698
+ }
699
+ case "dragCancel":
700
+ return state.drag ? { ...state, shapes: state.drag.base, drag: null } : state;
701
+ case "nudge": {
702
+ if (!state.selected.length) return state;
703
+ const shapes = translateShapes(state.shapes, state.selected, action.dx / MX, action.dy / MY);
704
+ return shapes === state.shapes ? state : commit(state, shapes);
705
+ }
706
+ case "remove": {
707
+ const v = state.vertex;
708
+ if (v && state.selected.length === 1 && state.selected[0] === v.id) {
709
+ const zone = state.shapes.find((s) => s.id === v.id);
710
+ const next = zone ? removeVertex(zone, v.index) : null;
711
+ if (!next) return { ...state, notice: { text: TOO_FEW_CORNERS, ok: false } };
712
+ return { ...commit(state, state.shapes.map((s) => (s.id === v.id ? next : s))), vertex: null };
713
+ }
714
+ if (!state.selected.length) return state;
715
+ return { ...commit(state, state.shapes.filter((s) => !state.selected.includes(s.id))), selected: [], vertex: null };
716
+ }
717
+ case "flip":
718
+ case "turn": {
719
+ const kinds: TShapeKind[] = action.type === "flip" ? ["door"] : ["door", "lift"];
720
+ const targets = new Set(state.shapes.filter((s) => state.selected.includes(s.id) && kinds.includes(s.kind)).map((s) => s.id));
721
+ if (!targets.size) return state;
722
+ return commit(state, state.shapes.map((s) => (targets.has(s.id) ? (action.type === "flip" ? flipDoor(s) : rotateShape(s, 90)) : s)));
723
+ }
724
+ case "addVertex": {
725
+ const zone = state.shapes.find((s) => s.id === action.id);
726
+ const added = zone ? addVertex(zone, { x: action.x, y: action.y }, action.within) : null;
727
+ if (!added) return state;
728
+ return { ...commit(state, state.shapes.map((s) => (s.id === action.id ? added.shape : s))), selected: [action.id], vertex: { id: action.id, index: added.index } };
729
+ }
730
+ case "removeVertex": {
731
+ const zone = state.shapes.find((s) => s.id === action.id);
732
+ const next = zone ? removeVertex(zone, action.index) : null;
733
+ if (!next) return { ...state, notice: { text: TOO_FEW_CORNERS, ok: false } };
734
+ return { ...commit(state, state.shapes.map((s) => (s.id === action.id ? next : s))), vertex: null };
735
+ }
296
736
  case "pick": {
297
737
  const shape = state.shapes.find((s) => s.id === action.id);
298
738
  if (!shape) return state;
299
739
  if (action.tool === "delete") return commit(state, state.shapes.filter((s) => s.id !== shape.id));
300
- if (action.tool === "move") return { ...state, moving: shape.id, notice: null };
740
+ if (action.tool === "move") return { ...state, selected: [shape.id], vertex: null, notice: null };
301
741
  // Zone tool on a zone: apply the typed name ("click the zone again to apply it").
302
742
  if (action.tool === "zone" && shape.kind === "zone" && (action.zoneName ?? "").trim()) {
303
743
  return commit(state, state.shapes.map((s) => (s.id === shape.id ? { ...s, name: (action.zoneName ?? "").trim() } : s)));
@@ -305,17 +745,13 @@ export function editorReduce(state: TEditorState, action: TEditorAction): TEdito
305
745
  return state;
306
746
  }
307
747
  case "place": {
308
- if (action.tool === "move") {
309
- const target = state.shapes.find((s) => s.id === state.moving);
310
- if (!target) return state;
311
- return { ...commit(state, state.shapes.map((s) => (s.id === target.id ? moveShape(s, action.x, action.y) : s))), moving: null };
312
- }
313
- if (action.tool === "delete") return state;
748
+ if (action.tool === "move" || action.tool === "delete") return state;
314
749
  const shape = newShape(action.tool, action.id ?? nextId(), action.floorNo, action.x, action.y, {
315
750
  name: action.zoneName,
316
751
  floors: action.floors,
317
752
  });
318
- return commit(state, [...state.shapes, shape]);
753
+ // The new shape comes selected, so its handles are there to size it straight away.
754
+ return { ...commit(state, [...state.shapes, shape]), selected: [shape.id], vertex: null };
319
755
  }
320
756
  default:
321
757
  return state;