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

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.
@@ -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;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * HERO Fleet Core building helpers (pure, tested in test/robot-fleet-core.test.mjs).
3
+ *
4
+ * The fleet building (`GET /api/robots/fleet-core/building`) comes in the same
5
+ * shape as a saved building map - levels / doors / lifts in the HERO plan frame -
6
+ * plus live `doorStates` and `liftStates` in the lift / door contract shape.
7
+ * Not part of the mobile-synced rules (`robot-display.ts`), so web only for now.
8
+ */
9
+
10
+ export const FLEET_CORE_BRAND = "fleet-core";
11
+
12
+ /** Is this building the read-only fleet building rather than a saved map? */
13
+ export const isFleetBuilding = (map: Record<string, any> | null | undefined) => map?.source === FLEET_CORE_BRAND;
14
+
15
+ /** Does the site have fleet robots (then their building is the one to draw)? */
16
+ export const hasFleetRobots = (rows: Array<Record<string, any>>) => rows.some((r) => r?.brand === FLEET_CORE_BRAND);
17
+
18
+ /** "L2" -> 2, "B1" -> -1, "G" -> 0 (the fleet names its floors). */
19
+ export function fleetFloorNo(name: unknown): number | null {
20
+ if (typeof name !== "string") return null;
21
+ const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
22
+ if (m) return m[1]!.toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
23
+ return /^G$/i.test(name.trim()) ? 0 : null;
24
+ }
25
+
26
+ /** Names of the doors that read OPEN (door contract mode 2). */
27
+ export function openDoorNames(map: Record<string, any> | null | undefined): Set<string> {
28
+ return new Set((map?.doorStates ?? []).filter((d: any) => d?.currentMode === 2).map((d: any) => String(d.doorName)));
29
+ }
30
+
31
+ /**
32
+ * The fleet's lifts as lift-queue items (the shape `liftCard` reads): the car's
33
+ * floor from the live state, and the robot holding the lift (its session is
34
+ * "<fleet>/<robot>", our robotSn) as the one riding, from its floor to the
35
+ * lift's destination. The fleet runs no waiting queue we can read.
36
+ */
37
+ export function fleetLiftItems(map: Record<string, any> | null | undefined, rows: Array<Record<string, any>>) {
38
+ if (!isFleetBuilding(map)) return [];
39
+ const states = new Map<string, any>((map!.liftStates ?? []).map((s: any) => [String(s.liftName), s]));
40
+ return (map!.lifts ?? []).map((lift: any) => {
41
+ const st = states.get(String(lift.name));
42
+ const current = fleetFloorNo(st?.currentFloor);
43
+ const dest = fleetFloorNo(st?.destinationFloor);
44
+ const holder = st?.sessionId ? rows.find((r) => r?.robotSn === st.sessionId) : null;
45
+ return {
46
+ liftName: String(lift.name),
47
+ floors: lift.floors ?? [],
48
+ state: { currentFloor: current },
49
+ active: holder
50
+ ? { _id: `fleet-${lift.name}`, robotId: String(holder._id), robotName: holder.name, fromFloor: current ?? dest, toFloor: dest ?? current }
51
+ : null,
52
+ queue: [],
53
+ recent: [],
54
+ simulated: false,
55
+ };
56
+ });
57
+ }