@7365admin1/layer-common 4.26.1-staging.354 → 4.26.1-staging.355

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.
@@ -31,7 +31,7 @@
31
31
  :disabled="loading || !!error"
32
32
  @click="startEditing"
33
33
  >
34
- {{ savedMap ? "Edit layout" : "Add doors & lifts" }}
34
+ {{ savedMap ? "Edit layout" : "Draw layout" }}
35
35
  </AppButton>
36
36
  <AppButton
37
37
  variant="icon"
@@ -71,9 +71,27 @@
71
71
  density="compact"
72
72
  hide-details
73
73
  style="max-width: 150px"
74
+ @focus="remember"
74
75
  />
75
76
  <span class="text-caption text-medium-emphasis">{{ toolHint }}</span>
77
+ <AppButton
78
+ v-if="tool === 'zone' && pendingZone.length >= 3"
79
+ variant="ghost"
80
+ icon="mdi-vector-polygon"
81
+ @click="finishZone"
82
+ >
83
+ Finish zone
84
+ </AppButton>
76
85
  <v-spacer />
86
+ <AppButton
87
+ variant="ghost"
88
+ icon="mdi-undo"
89
+ :disabled="saving || !undoStack.length"
90
+ aria-label="Undo the last change"
91
+ @click="undo"
92
+ >
93
+ Undo
94
+ </AppButton>
77
95
  <AppButton
78
96
  v-if="savedMap"
79
97
  variant="ghost"
@@ -90,7 +108,13 @@
90
108
  </div>
91
109
  <p v-if="editError" class="text-body-2 text-error px-4 pt-2 mb-0">{{ editError }}</p>
92
110
 
93
- <div ref="stage" class="robot-map3d" :class="{ 'robot-map3d--placing': editing && tool !== 'select' }">
111
+ <div
112
+ ref="stage"
113
+ class="robot-map3d"
114
+ :class="{ 'robot-map3d--placing': editing && tool !== 'select' }"
115
+ :tabindex="editing ? 0 : undefined"
116
+ @keydown="onKeyDown"
117
+ >
94
118
  <canvas
95
119
  ref="canvasEl"
96
120
  class="robot-map3d__canvas"
@@ -127,13 +151,19 @@
127
151
  <!-- The feature being edited. -->
128
152
  <div v-if="editing && selectedFeature" class="robot-map3d__panel px-4 py-3">
129
153
  <v-text-field
154
+ v-if="selectedFeature && 'name' in selectedFeature"
130
155
  v-model="selectedFeature.name"
131
- :label="selected?.kind === 'lift' ? 'Lift name' : 'Door name'"
156
+ :label="nameLabel"
132
157
  density="compact"
133
158
  hide-details
134
159
  maxlength="60"
135
160
  style="max-width: 220px"
161
+ @focus="remember"
136
162
  />
163
+ <span v-if="selected?.kind === 'wall'" class="text-body-2">Drawn wall, {{ selectedWallLength }} m</span>
164
+ <span v-if="selected?.kind === 'zone'" class="text-caption text-medium-emphasis">
165
+ {{ selectedZoneArea }} m² · drag a corner to reshape it
166
+ </span>
137
167
  <AppSelect
138
168
  v-if="selected?.kind === 'door'"
139
169
  v-model="doorType"
@@ -234,7 +264,7 @@
234
264
  * saved layout: doors, lift shafts and floor heights, which the floor plan
235
265
  * cannot say by itself.
236
266
  *
237
- * Nobody draws walls. The robot's map image is a SLAM occupancy grid — walls
267
+ * Nobody has to draw walls. The robot's map image is a SLAM occupancy grid — walls
238
268
  * are already dark pixels — so it is fetched into a canvas, thresholded, traced
239
269
  * into wall segments and extruded. Open-RMF does the same thing from an
240
270
  * annotated plan; this skips the annotation because the robot has surveyed the
@@ -242,8 +272,10 @@
242
272
  *
243
273
  * ## The saved layout
244
274
  *
245
- * Doors and lift shafts are placed by hand in edit mode (flat plan, one floor)
246
- * and saved to the building map (`/api/robots/building-maps`). With no saved
275
+ * Doors, lift shafts, extra walls (glass or anything else the scan missed) and
276
+ * named zones are placed by hand in edit mode (flat plan, one floor) and saved
277
+ * to the building map (`/api/robots/building-maps`) - walls and zones per level.
278
+ * Every change can be undone until the layout is saved. With no saved
247
279
  * map the view is exactly what it was before - the saved map only adds. A lift
248
280
  * shaft runs through every floor it stops at, which the stacked view shows.
249
281
  *
@@ -268,20 +300,34 @@ import {
268
300
  depthOf,
269
301
  distanceToSegment,
270
302
  doorSolid,
303
+ drawnWallSolid,
304
+ featuresForLevel,
271
305
  fitView,
272
306
  gridFromImageData,
273
307
  insideLift,
308
+ layoutProblem,
274
309
  levelElevations,
310
+ levelFeatures,
275
311
  levelSolids,
276
312
  liftSolid,
313
+ MAX_ZONE_POINTS,
314
+ MIN_WALL_M,
315
+ nearestPoint,
277
316
  nextFeatureName,
317
+ pointInPolygon,
318
+ polygonArea,
319
+ polygonCentre,
320
+ popUndo,
278
321
  projectPoint,
322
+ pushUndo,
279
323
  unprojectPoint,
280
324
  wallCorners,
281
325
  wallsFromOccupancyGrid,
282
326
  type TMapDoor,
327
+ type TMapDrawnWall,
283
328
  type TMapLift,
284
329
  type TMapPointM,
330
+ type TMapZone,
285
331
  type TView,
286
332
  type TWallSolid,
287
333
  } from "../../utils/building-map";
@@ -329,9 +375,13 @@ const savedLoadFailed = ref(false);
329
375
  const doors = ref<TMapDoor[]>([]);
330
376
  const lifts = ref<TMapLift[]>([]);
331
377
  const heights = ref<Record<number, number | undefined>>({});
378
+ const drawnWalls = ref<TMapDrawnWall[]>([]);
379
+ const zones = ref<TMapZone[]>([]);
332
380
 
333
381
  const wallCount = computed(() => wallSolids.value.length);
334
- const featureCount = computed(() => doors.value.length + lifts.value.length);
382
+ const featureCount = computed(
383
+ () => doors.value.length + lifts.value.length + drawnWalls.value.length + zones.value.length,
384
+ );
335
385
 
336
386
  /**
337
387
  * "All levels" stacks every floor the robot has mapped.
@@ -408,6 +458,9 @@ function applySaved(map: Record<string, any> | null) {
408
458
  const copy = (v: unknown) => JSON.parse(JSON.stringify(v ?? []));
409
459
  doors.value = copy(map?.doors);
410
460
  lifts.value = copy(map?.lifts);
461
+ const drawn = levelFeatures(map?.levels);
462
+ drawnWalls.value = drawn.walls;
463
+ zones.value = drawn.zones;
411
464
  const h: Record<number, number | undefined> = {};
412
465
  for (const level of map?.levels ?? []) {
413
466
  if (typeof level.elevationM === "number") h[Number(level.floorNo)] = level.elevationM;
@@ -521,6 +574,14 @@ function featureSolids(): TWallSolid[] {
521
574
  out.push(solid);
522
575
  });
523
576
 
577
+ drawnWalls.value.forEach((wall, i) => {
578
+ if (stacked.value ? !elev.has(wall.floorNo) : wall.floorNo !== floor) return;
579
+ const solid = drawnWallSolid(wall, stacked.value ? elev.get(wall.floorNo) ?? 0 : 0);
580
+ if (!solid) return;
581
+ if (selected.value?.kind === "wall" && selected.value.index === i) highlighted.add(solid);
582
+ out.push(solid);
583
+ });
584
+
524
585
  lifts.value.forEach((lift, i) => {
525
586
  const solid = stacked.value ? liftSolid(lift, elev) : liftSolid(lift, elev, floor);
526
587
  if (!solid) return;
@@ -572,7 +633,10 @@ function draw() {
572
633
 
573
634
  // Framed on the walls when there are any, so adding or dragging a feature
574
635
  // does not move the whole picture under the pointer.
575
- const view: TView = fitView(wallSolids.value.length ? wallSolids.value : scene, { width, height }, {
636
+ // With no traced walls, editing keeps the view still too (an empty scene
637
+ // frames on the origin) rather than re-framing on every added shape.
638
+ const frameOn = wallSolids.value.length ? wallSolids.value : editing.value ? [] : scene;
639
+ const view: TView = fitView(frameOn, { width, height }, {
576
640
  rotation: rotation.value,
577
641
  tilt: tilted.value ? 0.95 : 0,
578
642
  });
@@ -585,8 +649,19 @@ function draw() {
585
649
  (a, b) => a.centre.z - b.centre.z || depthOf(a.centre, view) - depthOf(b.centre, view),
586
650
  );
587
651
 
588
- for (const solid of ordered) drawBox(ctx, solid, view);
652
+ // Zones lie flat on their floor: each is painted just before the first box
653
+ // standing on or above that floor, so walls cover it and it covers the
654
+ // storeys below.
655
+ const flat = visibleZones();
656
+ let z = 0;
657
+ for (const solid of ordered) {
658
+ const base = solid.centre.z - solid.heightM / 2;
659
+ while (z < flat.length && flat[z].elevationM <= base + 1e-6) drawZone(ctx, flat[z++], view);
660
+ drawBox(ctx, solid, view);
661
+ }
662
+ while (z < flat.length) drawZone(ctx, flat[z++], view);
589
663
  drawPending(ctx, view);
664
+ drawHandles(ctx, view);
590
665
  drawRobot(ctx, view);
591
666
  }
592
667
 
@@ -602,6 +677,8 @@ function fillFor(solid: TWallSolid, shade: number): string {
602
677
  return c(60, 130, 230, highlighted.has(solid) ? 0.45 : 0.28);
603
678
  case "car":
604
679
  return c(255, 150, 40);
680
+ case "drawn":
681
+ return c(120, 132, 170);
605
682
  default: {
606
683
  const v = Math.round(150 * shade + 60);
607
684
  return `rgb(${v},${v + 4},${v + 8})`;
@@ -633,15 +710,84 @@ function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView)
633
710
  }
634
711
  }
635
712
 
636
- /** The first click of a door being drawn. */
637
- function drawPending(ctx: CanvasRenderingContext2D, view: TView) {
638
- const p = pendingDoorStart.value;
639
- if (!editing.value || !p) return;
640
- const s = projectPoint(p.x, p.y, 0, view);
713
+ /** Zones for the current view, lowest floor first, at their floor's height. */
714
+ function visibleZones(): Array<{ zone: TMapZone; index: number; elevationM: number }> {
715
+ const elev = elevations.value;
716
+ const floor = selectedFloor.value;
717
+ return zones.value
718
+ .map((zone, index) => ({
719
+ zone,
720
+ index,
721
+ elevationM: stacked.value ? elev.get(zone.floorNo) ?? NaN : zone.floorNo === floor ? 0 : NaN,
722
+ }))
723
+ .filter((z) => Number.isFinite(z.elevationM))
724
+ .sort((a, b) => a.elevationM - b.elevationM);
725
+ }
726
+
727
+ function drawZone(
728
+ ctx: CanvasRenderingContext2D,
729
+ item: { zone: TMapZone; index: number; elevationM: number },
730
+ view: TView,
731
+ ) {
732
+ const lit = editing.value && selected.value?.kind === "zone" && selected.value.index === item.index;
733
+ const pts = item.zone.points.map((p) => projectPoint(p.x, p.y, item.elevationM, view));
641
734
  ctx.beginPath();
642
- ctx.arc(s.x, s.y, 5, 0, Math.PI * 2);
643
- ctx.fillStyle = "#C48042";
735
+ pts.forEach((p, n) => (n === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
736
+ ctx.closePath();
737
+ ctx.fillStyle = lit ? "rgba(46,160,110,0.34)" : "rgba(46,160,110,0.18)";
644
738
  ctx.fill();
739
+ ctx.strokeStyle = lit ? "rgba(255,90,31,0.9)" : "rgba(30,120,80,0.7)";
740
+ ctx.lineWidth = lit ? 1.6 : 1;
741
+ ctx.stroke();
742
+
743
+ const c = polygonCentre(item.zone.points);
744
+ const at = projectPoint(c.x, c.y, item.elevationM, view);
745
+ ctx.font = "12px sans-serif";
746
+ ctx.textAlign = "center";
747
+ ctx.textBaseline = "middle";
748
+ ctx.fillStyle = "rgba(20,70,50,0.95)";
749
+ ctx.fillText(item.zone.name || "Zone", at.x, at.y);
750
+ }
751
+
752
+ const dot = (ctx: CanvasRenderingContext2D, s: { x: number; y: number }, fill: string, r = 5) => {
753
+ ctx.beginPath();
754
+ ctx.arc(s.x, s.y, r, 0, Math.PI * 2);
755
+ ctx.fillStyle = fill;
756
+ ctx.fill();
757
+ };
758
+
759
+ /** What is half-drawn: a door's first click, a wall's rubber band, a zone's corners so far. */
760
+ function drawPending(ctx: CanvasRenderingContext2D, view: TView) {
761
+ if (!editing.value) return;
762
+ const at = (p: TMapPointM) => projectPoint(p.x, p.y, 0, view);
763
+ if (pendingDoorStart.value) dot(ctx, at(pendingDoorStart.value), "#C48042");
764
+
765
+ const chain: TMapPointM[] = pendingWallStart.value
766
+ ? [pendingWallStart.value]
767
+ : tool.value === "zone" ? pendingZone.value : [];
768
+ if (!chain.length) return;
769
+ const pts = [...chain, ...(hover.value ? [hover.value] : [])].map(at);
770
+ ctx.beginPath();
771
+ pts.forEach((p, n) => (n === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
772
+ ctx.setLineDash([6, 4]);
773
+ ctx.strokeStyle = pendingWallStart.value ? "#78849A" : "#2EA06E";
774
+ ctx.lineWidth = 2;
775
+ ctx.stroke();
776
+ ctx.setLineDash([]);
777
+ chain.forEach((p, i) => dot(ctx, at(p), i === 0 && !pendingWallStart.value ? "#FF5A1F" : "#2EA06E", 4));
778
+ }
779
+
780
+ /** Corner handles on the selected wall or zone, which drag to reshape it. */
781
+ function drawHandles(ctx: CanvasRenderingContext2D, view: TView) {
782
+ if (!editing.value) return;
783
+ for (const p of selectedHandles()) {
784
+ const s = projectPoint(p.x, p.y, 0, view);
785
+ ctx.fillStyle = "#fff";
786
+ ctx.fillRect(s.x - 4, s.y - 4, 8, 8);
787
+ ctx.strokeStyle = "#FF5A1F";
788
+ ctx.lineWidth = 1.5;
789
+ ctx.strokeRect(s.x - 4, s.y - 4, 8, 8);
790
+ }
645
791
  }
646
792
 
647
793
  /**
@@ -690,16 +836,35 @@ function toggleTilt() {
690
836
  /* ------------------------------------------------------------------- edit */
691
837
 
692
838
  const editing = ref(false);
693
- const tool = ref<"select" | "door" | "lift">("select");
694
- const selected = ref<{ kind: "door" | "lift"; index: number } | null>(null);
839
+ type TTool = "select" | "door" | "lift" | "wall" | "zone";
840
+ type TKind = "door" | "lift" | "wall" | "zone";
841
+ const tool = ref<TTool>("select");
842
+ const selected = ref<{ kind: TKind; index: number } | null>(null);
695
843
  const pendingDoorStart = ref<TMapPointM | null>(null);
844
+ /** The wall being drawn starts here; each click ends one wall and starts the next. */
845
+ const pendingWallStart = ref<TMapPointM | null>(null);
846
+ /** The zone being drawn, corner by corner. */
847
+ const pendingZone = ref<TMapPointM[]>([]);
848
+ /** Where the pointer is, for the rubber band while drawing. */
849
+ const hover = ref<TMapPointM | null>(null);
696
850
  const saving = ref(false);
697
851
  const editError = ref("");
698
852
  const confirmRemove = ref(false);
699
- let dragging: { kind: "door" | "lift"; index: number; last: TMapPointM } | null = null;
853
+ /** Snapshots of the layout before each change, newest last. */
854
+ const undoStack = ref<string[]>([]);
855
+ let dragging: {
856
+ kind: TKind;
857
+ index: number;
858
+ /** A corner of a wall (0 start, 1 end) or of a zone; absent = the whole shape. */
859
+ handle?: number;
860
+ last: TMapPointM;
861
+ moved: boolean;
862
+ } | null = null;
700
863
 
701
864
  const toolOptions = [
702
865
  { label: "Select / move", value: "select" },
866
+ { label: "Draw walls", value: "wall" },
867
+ { label: "Draw zone", value: "zone" },
703
868
  { label: "Add door", value: "door" },
704
869
  { label: "Add lift shaft", value: "lift" },
705
870
  ];
@@ -713,13 +878,36 @@ const toolHint = computed(() => {
713
878
  return pendingDoorStart.value ? "Click where the door ends." : "Click where the door starts.";
714
879
  }
715
880
  if (tool.value === "lift") return "Click the middle of the lift shaft.";
716
- return "Click a door or lift to select it; drag to move it.";
881
+ if (tool.value === "wall") {
882
+ return pendingWallStart.value
883
+ ? "Click the next corner. Click the same point again or press Esc to stop."
884
+ : "Click where the wall starts.";
885
+ }
886
+ if (tool.value === "zone") {
887
+ return pendingZone.value.length
888
+ ? "Click each corner; click the first corner (or Finish zone) to close it. Esc cancels."
889
+ : "Click the first corner of the zone.";
890
+ }
891
+ return "Click a shape to select it; drag to move it, or drag a corner to reshape it.";
717
892
  });
718
893
 
719
- const selectedFeature = computed<TMapDoor | TMapLift | null>(() => {
894
+ const selectedFeature = computed<TMapDoor | TMapLift | TMapDrawnWall | TMapZone | null>(() => {
720
895
  const s = selected.value;
721
896
  if (!s) return null;
722
- return (s.kind === "door" ? doors.value[s.index] : lifts.value[s.index]) ?? null;
897
+ const list = { door: doors.value, lift: lifts.value, wall: drawnWalls.value, zone: zones.value }[s.kind];
898
+ return list[s.index] ?? null;
899
+ });
900
+
901
+ const nameLabel = computed(
902
+ () => ({ lift: "Lift name", door: "Door name", zone: "Zone name", wall: "" })[selected.value?.kind ?? "wall"],
903
+ );
904
+ const selectedWallLength = computed(() => {
905
+ const w = selected.value?.kind === "wall" ? drawnWalls.value[selected.value.index] : null;
906
+ return w ? Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y).toFixed(2) : "0";
907
+ });
908
+ const selectedZoneArea = computed(() => {
909
+ const z = selected.value?.kind === "zone" ? zones.value[selected.value.index] : null;
910
+ return z ? polygonArea(z.points).toFixed(1) : "0";
723
911
  });
724
912
 
725
913
  /* The selected door's type and the selected lift's floors, as plain models. */
@@ -727,7 +915,10 @@ const doorType = computed<string>({
727
915
  get: () => (selected.value?.kind === "door" ? doors.value[selected.value.index]?.type ?? "hinged" : "hinged"),
728
916
  set: (v) => {
729
917
  const s = selected.value;
730
- if (s?.kind === "door" && doors.value[s.index]) doors.value[s.index].type = v === "sliding" ? "sliding" : "hinged";
918
+ if (s?.kind === "door" && doors.value[s.index]) {
919
+ remember();
920
+ doors.value[s.index].type = v === "sliding" ? "sliding" : "hinged";
921
+ }
731
922
  },
732
923
  });
733
924
  const liftFloors = computed<number[]>({
@@ -735,6 +926,7 @@ const liftFloors = computed<number[]>({
735
926
  set: (v) => {
736
927
  const s = selected.value;
737
928
  if (s?.kind === "lift" && lifts.value[s.index]) {
929
+ remember();
738
930
  lifts.value[s.index].floors = [...new Set(v.map(Number))].sort((a, b) => a - b);
739
931
  draw();
740
932
  }
@@ -751,12 +943,54 @@ const currentHeight = computed<number | string>({
751
943
  },
752
944
  });
753
945
 
946
+ /* ------------------------------------------------------------------- undo */
947
+
948
+ type TLayoutSnapshot = {
949
+ doors: TMapDoor[];
950
+ lifts: TMapLift[];
951
+ walls: TMapDrawnWall[];
952
+ zones: TMapZone[];
953
+ heights: Record<number, number | undefined>;
954
+ };
955
+
956
+ /** Record the layout as it is, before a change. A repeat of the last snapshot is ignored. */
957
+ function remember() {
958
+ pushUndo<TLayoutSnapshot>(undoStack.value, {
959
+ doors: doors.value,
960
+ lifts: lifts.value,
961
+ walls: drawnWalls.value,
962
+ zones: zones.value,
963
+ heights: heights.value,
964
+ });
965
+ }
966
+
967
+ function undo() {
968
+ const snap = popUndo<TLayoutSnapshot>(undoStack.value);
969
+ if (!snap) return;
970
+ doors.value = snap.doors;
971
+ lifts.value = snap.lifts;
972
+ drawnWalls.value = snap.walls;
973
+ zones.value = snap.zones;
974
+ heights.value = snap.heights;
975
+ selected.value = null;
976
+ clearPending();
977
+ editError.value = "";
978
+ draw();
979
+ }
980
+
981
+ function clearPending() {
982
+ pendingDoorStart.value = null;
983
+ pendingWallStart.value = null;
984
+ pendingZone.value = [];
985
+ }
986
+
754
987
  function startEditing() {
755
988
  editing.value = true;
756
989
  editError.value = "";
757
990
  confirmRemove.value = false;
758
991
  tool.value = "select";
759
992
  selected.value = null;
993
+ undoStack.value = [];
760
994
  tilted.value = false;
761
995
  if (stacked.value) selectedFloor.value = realFloorOptions.value[0]?.value ?? null;
762
996
  else draw();
@@ -765,7 +999,9 @@ function startEditing() {
765
999
  function stopEditing() {
766
1000
  editing.value = false;
767
1001
  selected.value = null;
768
- pendingDoorStart.value = null;
1002
+ clearPending();
1003
+ hover.value = null;
1004
+ undoStack.value = [];
769
1005
  dragging = null;
770
1006
  draw();
771
1007
  }
@@ -782,16 +1018,48 @@ function worldAt(e: PointerEvent): TMapPointM | null {
782
1018
  return unprojectPoint(e.clientX - r.left, e.clientY - r.top, lastView, 0);
783
1019
  }
784
1020
 
785
- /** The feature under the pointer on this floor, lifts first (they are bigger). */
786
- function hitTest(p: TMapPointM): { kind: "door" | "lift"; index: number } | null {
787
- const tolerance = lastView ? 10 / lastView.zoom : 0.5;
1021
+ /** Ten screen pixels, in metres: how close a click must be to count. */
1022
+ const tolerance = () => (lastView ? 10 / lastView.zoom : 0.5);
1023
+
1024
+ /** Snap to a drawn wall end or zone corner on this floor, so shapes join up. */
1025
+ function snap(p: TMapPointM): TMapPointM {
1026
+ const floor = selectedFloor.value;
1027
+ const corners = [
1028
+ ...drawnWalls.value.filter((w) => w.floorNo === floor).flatMap((w) => [w.start, w.end]),
1029
+ ...zones.value.filter((z) => z.floorNo === floor).flatMap((z) => z.points),
1030
+ ...(pendingZone.value.length ? [pendingZone.value[0]] : []),
1031
+ ];
1032
+ const i = nearestPoint(p, corners, tolerance());
1033
+ return i >= 0 ? { ...corners[i] } : roundPoint(p);
1034
+ }
1035
+
1036
+ /** The shape under the pointer on this floor: lifts, doors, walls, then zones (the biggest). */
1037
+ function hitTest(p: TMapPointM): { kind: TKind; index: number } | null {
1038
+ const tol = tolerance();
788
1039
  const floor = selectedFloor.value;
789
1040
  const li = lifts.value.findIndex((l) => l.floors.includes(floor ?? NaN) && insideLift(p, l));
790
1041
  if (li >= 0) return { kind: "lift", index: li };
791
1042
  const di = doors.value.findIndex(
792
- (d) => d.floorNo === floor && distanceToSegment(p, d.start, d.end) <= tolerance,
1043
+ (d) => d.floorNo === floor && distanceToSegment(p, d.start, d.end) <= tol,
793
1044
  );
794
- return di >= 0 ? { kind: "door", index: di } : null;
1045
+ if (di >= 0) return { kind: "door", index: di };
1046
+ const wi = drawnWalls.value.findIndex(
1047
+ (w) => w.floorNo === floor && distanceToSegment(p, w.start, w.end) <= tol,
1048
+ );
1049
+ if (wi >= 0) return { kind: "wall", index: wi };
1050
+ const zi = zones.value.findIndex((z) => z.floorNo === floor && pointInPolygon(p, z.points));
1051
+ return zi >= 0 ? { kind: "zone", index: zi } : null;
1052
+ }
1053
+
1054
+ /** The corners of the selected wall or zone, which can be dragged. */
1055
+ function selectedHandles(): TMapPointM[] {
1056
+ const s = selected.value;
1057
+ if (s?.kind === "wall") {
1058
+ const w = drawnWalls.value[s.index];
1059
+ return w ? [w.start, w.end] : [];
1060
+ }
1061
+ if (s?.kind === "zone") return zones.value[s.index]?.points ?? [];
1062
+ return [];
795
1063
  }
796
1064
 
797
1065
  const round = (n: number) => Math.round(n * 100) / 100;
@@ -802,6 +1070,7 @@ function onPointerDown(e: PointerEvent) {
802
1070
  const p = worldAt(e);
803
1071
  if (!p) return;
804
1072
  editError.value = "";
1073
+ stage.value?.focus?.({ preventScroll: true });
805
1074
 
806
1075
  if (tool.value === "door") {
807
1076
  const start = pendingDoorStart.value;
@@ -810,6 +1079,7 @@ function onPointerDown(e: PointerEvent) {
810
1079
  } else {
811
1080
  pendingDoorStart.value = null;
812
1081
  if (Math.hypot(p.x - start.x, p.y - start.y) >= 0.3) {
1082
+ remember();
813
1083
  doors.value.push({
814
1084
  name: nextFeatureName(doors.value.map((d) => d.name), "door"),
815
1085
  floorNo: selectedFloor.value,
@@ -826,12 +1096,47 @@ function onPointerDown(e: PointerEvent) {
826
1096
  return;
827
1097
  }
828
1098
 
1099
+ if (tool.value === "wall") {
1100
+ const q = snap(p);
1101
+ const start = pendingWallStart.value;
1102
+ if (!start) {
1103
+ pendingWallStart.value = q;
1104
+ } else if (Math.hypot(q.x - start.x, q.y - start.y) < MIN_WALL_M) {
1105
+ // Clicking the same point again ends the run of walls.
1106
+ pendingWallStart.value = null;
1107
+ } else {
1108
+ remember();
1109
+ drawnWalls.value.push({ floorNo: selectedFloor.value, start, end: q });
1110
+ selected.value = { kind: "wall", index: drawnWalls.value.length - 1 };
1111
+ pendingWallStart.value = q;
1112
+ }
1113
+ draw();
1114
+ return;
1115
+ }
1116
+
1117
+ if (tool.value === "zone") {
1118
+ const q = snap(p);
1119
+ const first = pendingZone.value[0];
1120
+ if (pendingZone.value.length >= 3 && first && q.x === first.x && q.y === first.y) {
1121
+ finishZone();
1122
+ return;
1123
+ }
1124
+ if (pendingZone.value.length >= MAX_ZONE_POINTS) {
1125
+ editError.value = `A zone can have ${MAX_ZONE_POINTS} corners at most - close it now.`;
1126
+ return;
1127
+ }
1128
+ pendingZone.value = [...pendingZone.value, q];
1129
+ draw();
1130
+ return;
1131
+ }
1132
+
829
1133
  if (tool.value === "lift") {
830
1134
  const floors = realFloorOptions.value.map((f) => f.value);
831
1135
  if (floors.length < 2) {
832
1136
  editError.value = "A lift shaft needs at least two floors on this robot's map.";
833
1137
  return;
834
1138
  }
1139
+ remember();
835
1140
  lifts.value.push({
836
1141
  name: nextFeatureName(lifts.value.map((l) => l.name), "lift"),
837
1142
  ...roundPoint(p),
@@ -845,29 +1150,83 @@ function onPointerDown(e: PointerEvent) {
845
1150
  return;
846
1151
  }
847
1152
 
848
- selected.value = hitTest(p);
849
- if (selected.value) {
850
- dragging = { ...selected.value, last: p };
851
- canvasEl.value?.setPointerCapture?.(e.pointerId);
1153
+ // A corner of the selected wall or zone first, so a reshape wins over a move.
1154
+ const handle = selected.value ? nearestPoint(p, selectedHandles(), tolerance()) : -1;
1155
+ if (selected.value && handle >= 0) {
1156
+ dragging = { ...selected.value, handle, last: p, moved: false };
1157
+ } else {
1158
+ selected.value = hitTest(p);
1159
+ dragging = selected.value ? { ...selected.value, last: p, moved: false } : null;
852
1160
  }
1161
+ if (dragging) canvasEl.value?.setPointerCapture?.(e.pointerId);
1162
+ draw();
1163
+ }
1164
+
1165
+ /** Close the zone being drawn and select it, so it can be named. */
1166
+ function finishZone() {
1167
+ const points = pendingZone.value;
1168
+ if (points.length < 3) {
1169
+ editError.value = "A zone needs at least three corners.";
1170
+ return;
1171
+ }
1172
+ if (polygonArea(points) < 0.01) {
1173
+ editError.value = "Those corners are in a line - a zone needs an area.";
1174
+ return;
1175
+ }
1176
+ remember();
1177
+ zones.value.push({
1178
+ floorNo: selectedFloor.value as number,
1179
+ name: nextFeatureName(zones.value.map((z) => z.name), "zone"),
1180
+ points,
1181
+ });
1182
+ pendingZone.value = [];
1183
+ selected.value = { kind: "zone", index: zones.value.length - 1 };
1184
+ tool.value = "select";
853
1185
  draw();
854
1186
  }
855
1187
 
856
1188
  function onPointerMove(e: PointerEvent) {
857
- if (!dragging) return;
1189
+ if (!editing.value) return;
858
1190
  const p = worldAt(e);
859
1191
  if (!p) return;
1192
+ if (!dragging) {
1193
+ if (pendingWallStart.value || pendingZone.value.length) {
1194
+ hover.value = snap(p);
1195
+ draw();
1196
+ }
1197
+ return;
1198
+ }
860
1199
  const dx = p.x - dragging.last.x;
861
1200
  const dy = p.y - dragging.last.y;
1201
+ if (!dx && !dy) return;
1202
+ if (!dragging.moved) {
1203
+ remember();
1204
+ dragging.moved = true;
1205
+ }
862
1206
  dragging.last = p;
1207
+ const move = (q: TMapPointM) => roundPoint({ x: q.x + dx, y: q.y + dy });
1208
+
863
1209
  if (dragging.kind === "lift") {
864
1210
  const lift = lifts.value[dragging.index];
865
1211
  lift.x = round(lift.x + dx);
866
1212
  lift.y = round(lift.y + dy);
867
- } else {
1213
+ } else if (dragging.kind === "door") {
868
1214
  const door = doors.value[dragging.index];
869
- door.start = roundPoint({ x: door.start.x + dx, y: door.start.y + dy });
870
- door.end = roundPoint({ x: door.end.x + dx, y: door.end.y + dy });
1215
+ door.start = move(door.start);
1216
+ door.end = move(door.end);
1217
+ } else if (dragging.kind === "wall") {
1218
+ const wall = drawnWalls.value[dragging.index];
1219
+ if (dragging.handle === 0) wall.start = roundPoint(p);
1220
+ else if (dragging.handle === 1) wall.end = roundPoint(p);
1221
+ else {
1222
+ wall.start = move(wall.start);
1223
+ wall.end = move(wall.end);
1224
+ }
1225
+ } else {
1226
+ const zone = zones.value[dragging.index];
1227
+ zone.points = dragging.handle !== undefined
1228
+ ? zone.points.map((q, i) => (i === dragging!.handle ? roundPoint(p) : q))
1229
+ : zone.points.map(move);
871
1230
  }
872
1231
  draw();
873
1232
  }
@@ -876,20 +1235,45 @@ function onPointerUp() {
876
1235
  dragging = null;
877
1236
  }
878
1237
 
1238
+ /** Esc stops drawing, Enter closes a zone, Delete removes, Ctrl/Cmd+Z undoes. */
1239
+ function onKeyDown(e: KeyboardEvent) {
1240
+ if (!editing.value) return;
1241
+ const typing = (e.target as HTMLElement | null)?.closest?.("input, textarea, select");
1242
+ if (typing) return;
1243
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
1244
+ e.preventDefault();
1245
+ undo();
1246
+ } else if (e.key === "Escape") {
1247
+ clearPending();
1248
+ hover.value = null;
1249
+ draw();
1250
+ } else if (e.key === "Enter" && tool.value === "zone") {
1251
+ finishZone();
1252
+ } else if ((e.key === "Delete" || e.key === "Backspace") && selected.value) {
1253
+ e.preventDefault();
1254
+ removeSelected();
1255
+ }
1256
+ }
1257
+
879
1258
  function removeSelected() {
880
1259
  const s = selected.value;
881
1260
  if (!s) return;
882
- if (s.kind === "door") doors.value.splice(s.index, 1);
883
- else lifts.value.splice(s.index, 1);
1261
+ remember();
1262
+ ({ door: doors.value, lift: lifts.value, wall: drawnWalls.value, zone: zones.value })[s.kind].splice(s.index, 1);
884
1263
  selected.value = null;
885
1264
  draw();
886
1265
  }
887
1266
 
888
- /** What gets saved. Drawn walls and zones already on the map are kept as they are. */
1267
+ /** What gets saved. Walls and zones on floors this robot no longer maps are kept as they are. */
889
1268
  function payload() {
890
1269
  const savedLevels: Array<Record<string, any>> = savedMap.value?.levels ?? [];
891
1270
  const floorNos = [
892
- ...new Set([...maps.value.map((m) => Number(m.floorNo)), ...savedLevels.map((l) => Number(l.floorNo))]),
1271
+ ...new Set([
1272
+ ...maps.value.map((m) => Number(m.floorNo)),
1273
+ ...savedLevels.map((l) => Number(l.floorNo)),
1274
+ ...drawnWalls.value.map((w) => w.floorNo),
1275
+ ...zones.value.map((z) => z.floorNo),
1276
+ ]),
893
1277
  ].sort((a, b) => a - b);
894
1278
 
895
1279
  const levels = floorNos.map((floorNo) => {
@@ -898,9 +1282,8 @@ function payload() {
898
1282
  const level: Record<string, any> = {
899
1283
  floorNo,
900
1284
  name: robotMap?.mapName?.trim() || saved.name || "",
1285
+ ...featuresForLevel(floorNo, drawnWalls.value, zones.value),
901
1286
  };
902
- if (saved.walls?.length) level.walls = saved.walls;
903
- if (saved.zones?.length) level.zones = saved.zones;
904
1287
  const h = heights.value[floorNo];
905
1288
  if (typeof h === "number" && Number.isFinite(h)) level.elevationM = h;
906
1289
  return level;
@@ -915,6 +1298,15 @@ function payload() {
915
1298
  }
916
1299
 
917
1300
  async function save() {
1301
+ if (pendingZone.value.length) {
1302
+ editError.value = "Finish the zone you are drawing (or press Esc) before saving.";
1303
+ return;
1304
+ }
1305
+ const problem = layoutProblem(drawnWalls.value, zones.value);
1306
+ if (problem) {
1307
+ editError.value = problem;
1308
+ return;
1309
+ }
918
1310
  const body = payload();
919
1311
  const short = body.lifts.find((l) => l.floors.length < 2);
920
1312
  if (short) {
@@ -1060,7 +1452,7 @@ function untilLabel(when: string) {
1060
1452
 
1061
1453
  watch(selectedFloor, async () => {
1062
1454
  selected.value = null;
1063
- pendingDoorStart.value = null;
1455
+ clearPending();
1064
1456
  if (!maps.value.length) return;
1065
1457
  loading.value = true;
1066
1458
  error.value = "";
@@ -1074,11 +1466,14 @@ watch(selectedFloor, async () => {
1074
1466
  });
1075
1467
 
1076
1468
  watch(tool, () => {
1077
- pendingDoorStart.value = null;
1469
+ clearPending();
1470
+ hover.value = null;
1078
1471
  draw();
1079
1472
  });
1080
1473
 
1081
1474
  watch(() => props.robotState, draw, { deep: true });
1475
+ // Zone names are written on the plan, so renaming one redraws it.
1476
+ watch(() => zones.value.map((z) => z.name).join("\n"), draw);
1082
1477
 
1083
1478
  let onResize: (() => void) | undefined;
1084
1479
  let pollTimer: ReturnType<typeof setInterval> | undefined;
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.26.1-staging.354",
5
+ "version": "4.26.1-staging.355",
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.",
@@ -48,7 +48,7 @@ export type TWallSolid = {
48
48
  heightM: number;
49
49
  yaw: number;
50
50
  /** What the box is, so the renderer can colour it. Absent = a wall. */
51
- kind?: "wall" | "door" | "lift" | "car";
51
+ kind?: "wall" | "drawn" | "door" | "lift" | "car";
52
52
  };
53
53
 
54
54
  /* ------------------------------------------------- image to occupancy grid */
@@ -524,14 +524,191 @@ export function insideLift(p: TMapPointM, lift: TMapLift): boolean {
524
524
  return Math.abs(p.x - lift.x) <= lift.widthM / 2 && Math.abs(p.y - lift.y) <= lift.depthM / 2;
525
525
  }
526
526
 
527
- /** The next free default name: Lift A, Lift B, ... / Door 1, Door 2, ... */
528
- export function nextFeatureName(existing: string[], kind: "lift" | "door"): string {
527
+ /** The next free default name: Lift A, Lift B, ... / Door 1, ... / Zone 1, ... */
528
+ export function nextFeatureName(existing: string[], kind: "lift" | "door" | "zone"): string {
529
529
  const taken = new Set(existing);
530
+ const word = kind === "lift" ? "Lift" : kind === "door" ? "Door" : "Zone";
530
531
  for (let i = 0; i < 500; i++) {
531
532
  const name = kind === "lift"
532
533
  ? `Lift ${i < 26 ? String.fromCharCode(65 + i) : i + 1}`
533
- : `Door ${i + 1}`;
534
+ : `${word} ${i + 1}`;
534
535
  if (!taken.has(name)) return name;
535
536
  }
536
- return `${kind === "lift" ? "Lift" : "Door"} ${existing.length + 1}`;
537
+ return `${word} ${existing.length + 1}`;
538
+ }
539
+
540
+ /* ------------------------------------------- drawn walls and zones */
541
+
542
+ /**
543
+ * Walls and zones somebody drew, flattened with their floor so the editor can
544
+ * treat them like doors. Saved per level (`levels[].walls` / `levels[].zones`,
545
+ * the shapes core's `robot-building-map.model.ts` validates).
546
+ */
547
+ export type TMapDrawnWall = { floorNo: number; start: TMapPointM; end: TMapPointM };
548
+ export type TMapZone = { floorNo: number; name: string; points: TMapPointM[] };
549
+
550
+ /** The API's limits, checked before a save so the message names the problem. */
551
+ export const MAX_WALLS_PER_LEVEL = 2000;
552
+ export const MAX_ZONES_PER_LEVEL = 200;
553
+ export const MAX_ZONE_POINTS = 200;
554
+ export const COORD_LIMIT_M = 1000;
555
+ /** Shorter than this, a click pair is a slip, not a wall. */
556
+ export const MIN_WALL_M = 0.1;
557
+
558
+ /** A drawn wall as a full-height box. Null for a zero-length wall. */
559
+ export function drawnWallSolid(wall: TMapDrawnWall, elevationM: number): TWallSolid | null {
560
+ const lengthM = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y);
561
+ if (!(lengthM > 0)) return null;
562
+ return {
563
+ kind: "drawn",
564
+ centre: {
565
+ x: (wall.start.x + wall.end.x) / 2,
566
+ y: (wall.start.y + wall.end.y) / 2,
567
+ z: elevationM + WALL_HEIGHT_M / 2,
568
+ },
569
+ lengthM,
570
+ thicknessM: WALL_THICKNESS_M * 1.5,
571
+ heightM: WALL_HEIGHT_M,
572
+ yaw: Math.atan2(wall.end.y - wall.start.y, wall.end.x - wall.start.x),
573
+ };
574
+ }
575
+
576
+ /** Even-odd ray cast. The editor's zone hit test. */
577
+ export function pointInPolygon(p: TMapPointM, points: TMapPointM[]): boolean {
578
+ let inside = false;
579
+ for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
580
+ const a = points[i];
581
+ const b = points[j];
582
+ if (a.y > p.y !== b.y > p.y && p.x < ((b.x - a.x) * (p.y - a.y)) / (b.y - a.y) + a.x) {
583
+ inside = !inside;
584
+ }
585
+ }
586
+ return inside;
587
+ }
588
+
589
+ /** Shoelace area, square metres, always positive. */
590
+ export function polygonArea(points: TMapPointM[]): number {
591
+ let twice = 0;
592
+ for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
593
+ twice += (points[j].x + points[i].x) * (points[j].y - points[i].y);
594
+ }
595
+ return Math.abs(twice) / 2;
596
+ }
597
+
598
+ /** Where a zone's name is written: the mean of its corners. */
599
+ export function polygonCentre(points: TMapPointM[]): TMapPointM {
600
+ const n = points.length || 1;
601
+ return {
602
+ x: points.reduce((t, p) => t + p.x, 0) / n,
603
+ y: points.reduce((t, p) => t + p.y, 0) / n,
604
+ };
605
+ }
606
+
607
+ /** Index of the nearest candidate within `tolerance` metres, or -1. */
608
+ export function nearestPoint(p: TMapPointM, candidates: TMapPointM[], tolerance: number): number {
609
+ let best = -1;
610
+ let bestD = tolerance;
611
+ candidates.forEach((c, i) => {
612
+ const d = Math.hypot(c.x - p.x, c.y - p.y);
613
+ if (d <= bestD) {
614
+ best = i;
615
+ bestD = d;
616
+ }
617
+ });
618
+ return best;
619
+ }
620
+
621
+ /** A saved map's levels to the editor's flat lists. Malformed entries are skipped. */
622
+ export function levelFeatures(
623
+ levels: Array<Record<string, any>> = [],
624
+ ): { walls: TMapDrawnWall[]; zones: TMapZone[] } {
625
+ const ok = (p: any) => p && Number.isFinite(p.x) && Number.isFinite(p.y);
626
+ const walls: TMapDrawnWall[] = [];
627
+ const zones: TMapZone[] = [];
628
+ for (const level of levels ?? []) {
629
+ const floorNo = Number(level?.floorNo);
630
+ if (!Number.isFinite(floorNo)) continue;
631
+ for (const w of level.walls ?? []) {
632
+ if (ok(w?.start) && ok(w?.end)) {
633
+ walls.push({ floorNo, start: { x: w.start.x, y: w.start.y }, end: { x: w.end.x, y: w.end.y } });
634
+ }
635
+ }
636
+ for (const z of level.zones ?? []) {
637
+ const points = (z?.points ?? []).filter(ok).map((p: TMapPointM) => ({ x: p.x, y: p.y }));
638
+ if (points.length >= 3) zones.push({ floorNo, name: String(z.name ?? ""), points });
639
+ }
640
+ }
641
+ return { walls, zones };
642
+ }
643
+
644
+ type TSavedLevelFeatures = {
645
+ walls?: Array<{ start: TMapPointM; end: TMapPointM }>;
646
+ zones?: Array<{ name: string; points: TMapPointM[] }>;
647
+ };
648
+
649
+ /** One floor's drawn walls and zones in the saved shape; keys omitted when empty. */
650
+ export function featuresForLevel(
651
+ floorNo: number,
652
+ walls: TMapDrawnWall[],
653
+ zones: TMapZone[],
654
+ ): TSavedLevelFeatures {
655
+ const out: TSavedLevelFeatures = {};
656
+ const w = walls.filter((x) => x.floorNo === floorNo).map(({ start, end }) => ({ start, end }));
657
+ const z = zones
658
+ .filter((x) => x.floorNo === floorNo)
659
+ .map(({ name, points }) => ({ name: name.trim() || "Zone", points }));
660
+ if (w.length) out.walls = w;
661
+ if (z.length) out.zones = z;
662
+ return out;
663
+ }
664
+
665
+ /**
666
+ * The first reason the API would refuse these walls and zones, in words, or
667
+ * null. Checked before a save so the person sees which shape is wrong instead
668
+ * of a validation error.
669
+ */
670
+ export function layoutProblem(walls: TMapDrawnWall[], zones: TMapZone[]): string | null {
671
+ const far = (p: TMapPointM) => Math.abs(p.x) > COORD_LIMIT_M || Math.abs(p.y) > COORD_LIMIT_M;
672
+ const count = new Map<string, number>();
673
+ const bump = (k: string) => {
674
+ count.set(k, (count.get(k) ?? 0) + 1);
675
+ return count.get(k) as number;
676
+ };
677
+ for (const w of walls) {
678
+ if (far(w.start) || far(w.end)) return `A wall on floor ${w.floorNo} is too far from the map.`;
679
+ if (bump(`w${w.floorNo}`) > MAX_WALLS_PER_LEVEL) {
680
+ return `Floor ${w.floorNo} has more than ${MAX_WALLS_PER_LEVEL} drawn walls.`;
681
+ }
682
+ }
683
+ for (const z of zones) {
684
+ const name = z.name.trim() || "A zone";
685
+ if (name.length > 60) return `"${name.slice(0, 20)}…" is too long - a zone name can be 60 characters at most.`;
686
+ if (z.points.length < 3) return `${name} needs at least three corners.`;
687
+ if (z.points.length > MAX_ZONE_POINTS) return `${name} has more than ${MAX_ZONE_POINTS} corners.`;
688
+ if (z.points.some(far)) return `${name} is too far from the map.`;
689
+ if (polygonArea(z.points) < 0.01) return `${name} has no area - its corners are in a line.`;
690
+ if (bump(`z${z.floorNo}`) > MAX_ZONES_PER_LEVEL) {
691
+ return `Floor ${z.floorNo} has more than ${MAX_ZONES_PER_LEVEL} zones.`;
692
+ }
693
+ }
694
+ return null;
695
+ }
696
+
697
+ /**
698
+ * Undo history: whole-layout snapshots, newest last. A layout is a few KB, so
699
+ * a snapshot per edit is simpler and safer than inverse operations.
700
+ *
701
+ * ponytail: snapshots capped at `limit`. Diff-based history if layouts ever
702
+ * reach megabytes.
703
+ */
704
+ export function pushUndo<T>(stack: string[], state: T, limit = 50): void {
705
+ const snap = JSON.stringify(state);
706
+ if (stack[stack.length - 1] === snap) return;
707
+ stack.push(snap);
708
+ if (stack.length > limit) stack.splice(0, stack.length - limit);
709
+ }
710
+
711
+ export function popUndo<T>(stack: string[]): T | null {
712
+ const snap = stack.pop();
713
+ return snap === undefined ? null : (JSON.parse(snap) as T);
537
714
  }