@7365admin1/layer-common 4.26.0 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/components/AccessCardAddForm.vue +5 -4
  3. package/components/AccessCardAssignToUnitForm.vue +3 -2
  4. package/components/AccessCardPreviewDialog.vue +4 -3
  5. package/components/Dialog/UpdateMoreAction.vue +11 -1
  6. package/components/DocumentForm.vue +407 -112
  7. package/components/DocumentManagement.vue +213 -12
  8. package/components/EntryPass/QrTemplatePreview.vue +21 -25
  9. package/components/EntryPassInformation.vue +119 -24
  10. package/components/Facility/BookingSetup.vue +63 -0
  11. package/components/HidAccessLogDashboard.vue +29 -5
  12. package/components/HidAccessPermissions.vue +424 -0
  13. package/components/HidIntercomManagement.vue +148 -14
  14. package/components/HidProfileQrCode.vue +323 -0
  15. package/components/HidReaderManagement.vue +26 -0
  16. package/components/HidReaderUserRoster.vue +32 -2
  17. package/components/HidUserEnrollment.vue +833 -152
  18. package/components/InvitationClientForm.vue +19 -1
  19. package/components/Robot/Fleet.vue +3 -0
  20. package/components/Robot/Map3D.vue +1158 -39
  21. package/components/RolePermissionFormCreate.vue +163 -19
  22. package/components/RolePermissionFormPreviewUpdate.vue +230 -19
  23. package/components/RolePermissionMain.vue +19 -0
  24. package/components/VisitorManagement.vue +267 -5
  25. package/composables/useAccessManagement.ts +5 -0
  26. package/composables/useDocument.ts +7 -0
  27. package/composables/useFacility.ts +11 -0
  28. package/composables/useHidAmico.ts +117 -0
  29. package/composables/useHidNavigation.ts +25 -1
  30. package/composables/usePeople.ts +19 -0
  31. package/composables/useRobots.ts +88 -0
  32. package/composables/useSiteCategory.ts +45 -0
  33. package/composables/useSiteEntryPassSettings.ts +26 -0
  34. package/composables/useWebUsb.ts +14 -11
  35. package/package.json +1 -1
  36. package/pages/[org]/[site]/access-mgmt/administrator/index.vue +1 -1
  37. package/pages/[org]/[site]/access-mgmt/hid-cards/index.vue +1 -1
  38. package/pages/[org]/[site]/access-mgmt/hid-qr-code/index.vue +23 -0
  39. package/pages/[org]/[site]/access-mgmt/hid-readers/index.vue +1 -1
  40. package/types/document.d.ts +14 -0
  41. package/types/facility.d.ts +4 -0
  42. package/types/people.d.ts +28 -1
  43. package/utils/building-map.ts +316 -0
  44. package/utils/hid-permission-assignments.ts +190 -0
  45. package/utils/occupancy-role.ts +109 -0
  46. package/utils/permission-labels.ts +30 -0
@@ -4,7 +4,7 @@
4
4
  <template #left>
5
5
  <AppSelect
6
6
  v-model="selectedFloor"
7
- :items="floorOptions"
7
+ :items="editing ? realFloorOptions : floorOptions"
8
8
  item-title="title"
9
9
  item-value="value"
10
10
  label="Level"
@@ -16,8 +16,23 @@
16
16
  <span v-if="wallCount" class="text-caption text-medium-emphasis ml-4">
17
17
  {{ wallCount }} walls found
18
18
  </span>
19
+ <span v-if="savedMap" class="text-caption text-medium-emphasis ml-3">
20
+ · saved layout (version {{ savedMap.version }})
21
+ </span>
22
+ <span v-else-if="savedLoadFailed" class="text-caption text-error ml-3">
23
+ · saved layout could not be loaded
24
+ </span>
19
25
  </template>
20
26
  <template #right>
27
+ <AppButton
28
+ v-if="canEdit && !editing && !savedLoadFailed"
29
+ variant="ghost"
30
+ icon="mdi-pencil-ruler"
31
+ :disabled="loading || !!error"
32
+ @click="startEditing"
33
+ >
34
+ {{ savedMap ? "Edit layout" : "Draw layout" }}
35
+ </AppButton>
21
36
  <AppButton
22
37
  variant="icon"
23
38
  icon="mdi-rotate-left"
@@ -36,14 +51,78 @@
36
51
  variant="icon"
37
52
  :icon="tilted ? 'mdi-cube-outline' : 'mdi-floor-plan'"
38
53
  :aria-label="tilted ? 'Show as a flat plan' : 'Show in 3D'"
39
- :disabled="loading"
54
+ :disabled="loading || editing"
40
55
  @click="toggleTilt"
41
56
  />
42
57
  </template>
43
58
  </CardToolbar>
44
59
 
45
- <div ref="stage" class="robot-map3d">
46
- <canvas ref="canvasEl" class="robot-map3d__canvas" />
60
+ <!--
61
+ Editing happens on the flat plan of one floor, so a click lands exactly
62
+ where it looks like it lands.
63
+ -->
64
+ <div v-if="editing" class="robot-map3d__editbar px-4 py-2">
65
+ <AppSegmented v-model="tool" :options="toolOptions" />
66
+ <v-text-field
67
+ v-model.number="currentHeight"
68
+ type="number"
69
+ step="0.1"
70
+ label="Floor height (m)"
71
+ density="compact"
72
+ hide-details
73
+ style="max-width: 150px"
74
+ @focus="remember"
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>
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>
95
+ <AppButton
96
+ v-if="savedMap"
97
+ variant="ghost"
98
+ icon="mdi-delete-outline"
99
+ :disabled="saving"
100
+ @click="removeSaved"
101
+ >
102
+ {{ confirmRemove ? "Confirm remove" : "Remove saved layout" }}
103
+ </AppButton>
104
+ <AppButton variant="ghost" :disabled="saving" @click="cancelEditing">Cancel</AppButton>
105
+ <AppButton icon="mdi-content-save-outline" :disabled="saving" @click="save">
106
+ {{ saving ? "Saving…" : "Save layout" }}
107
+ </AppButton>
108
+ </div>
109
+ <p v-if="editError" class="text-body-2 text-error px-4 pt-2 mb-0">{{ editError }}</p>
110
+
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
+ >
118
+ <canvas
119
+ ref="canvasEl"
120
+ class="robot-map3d__canvas"
121
+ @pointerdown="onPointerDown"
122
+ @pointermove="onPointerMove"
123
+ @pointerup="onPointerUp"
124
+ @pointercancel="onPointerUp"
125
+ />
47
126
 
48
127
  <div v-if="loading" class="robot-map3d__overlay">
49
128
  <v-progress-circular indeterminate size="28" />
@@ -58,29 +137,148 @@
58
137
  <div v-else-if="error" class="robot-map3d__overlay">
59
138
  <v-icon size="36" class="mb-2">mdi-map-marker-off-outline</v-icon>
60
139
  <p class="text-body-2 mb-3">{{ error }}</p>
61
- <AppButton size="small" variant="outlined" @click="load">Try again</AppButton>
140
+ <AppButton variant="ghost" @click="load">Try again</AppButton>
62
141
  </div>
63
142
 
64
- <div v-else-if="!wallCount" class="robot-map3d__overlay">
143
+ <div v-else-if="!wallCount && !featureCount && !editing" class="robot-map3d__overlay">
65
144
  <v-icon size="36" class="mb-2">mdi-floor-plan</v-icon>
66
145
  <p class="text-body-2 mb-0">
67
146
  No walls could be found in this floor plan.
68
147
  </p>
69
148
  </div>
70
149
  </div>
150
+
151
+ <!-- The feature being edited. -->
152
+ <div v-if="editing && selectedFeature" class="robot-map3d__panel px-4 py-3">
153
+ <v-text-field
154
+ v-if="selectedFeature && 'name' in selectedFeature"
155
+ v-model="selectedFeature.name"
156
+ :label="nameLabel"
157
+ density="compact"
158
+ hide-details
159
+ maxlength="60"
160
+ style="max-width: 220px"
161
+ @focus="remember"
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>
167
+ <AppSelect
168
+ v-if="selected?.kind === 'door'"
169
+ v-model="doorType"
170
+ :items="doorTypes"
171
+ item-title="title"
172
+ item-value="value"
173
+ label="Type"
174
+ density="compact"
175
+ hide-details
176
+ style="max-width: 160px"
177
+ />
178
+ <AppSelect
179
+ v-if="selected?.kind === 'lift'"
180
+ v-model="liftFloors"
181
+ :items="realFloorOptions"
182
+ item-title="title"
183
+ item-value="value"
184
+ label="Stops at"
185
+ multiple
186
+ chips
187
+ density="compact"
188
+ hide-details
189
+ style="min-width: 260px"
190
+ />
191
+ <v-spacer />
192
+ <AppButton variant="ghost" icon="mdi-delete-outline" @click="removeSelected">Remove</AppButton>
193
+ </div>
194
+
195
+ <!--
196
+ The lift queue. The car is a SIMULATOR - there is no lift driver until
197
+ the lift maker supplies its register map - and the panel says so.
198
+ -->
199
+ <div v-if="!editing && savedMap?.lifts?.length" class="robot-map3d__lifts px-4 py-3">
200
+ <div class="d-flex align-center mb-2">
201
+ <span class="font-weight-medium">Lifts</span>
202
+ <span class="text-caption text-medium-emphasis ml-2">simulated — no real lift is controlled</span>
203
+ </div>
204
+ <p v-if="liftError" class="text-body-2 text-error mb-2">{{ liftError }}</p>
205
+ <div v-for="lift in liftQueue" :key="lift.liftName" class="robot-map3d__lift mb-3">
206
+ <div class="text-body-2">
207
+ <strong>{{ lift.liftName }}</strong>
208
+ — floor {{ lift.state?.currentFloor }}, {{ motionLabel(lift.state) }}, doors {{ doorLabel(lift.state) }}.
209
+ {{ phaseLabel(lift) }}
210
+ </div>
211
+ <div v-if="lift.active" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
212
+ <span>
213
+ In the lift: <strong>{{ lift.active.robotName }}</strong>
214
+ (floor {{ lift.active.fromFloor }} → {{ lift.active.toFloor }}), released automatically
215
+ {{ untilLabel(lift.active.expiresAt) }} unless it finishes first.
216
+ </span>
217
+ <AppButton v-if="canEdit" variant="ghost" @click="release(lift.active)">Release</AppButton>
218
+ </div>
219
+ <div v-for="(row, i) in lift.queue" :key="row._id" class="text-body-2 mt-1 d-flex align-center flex-wrap ga-2">
220
+ <span>Waiting {{ i + 1 }}: {{ row.robotName }} (floor {{ row.fromFloor }} → {{ row.toFloor }})</span>
221
+ <AppButton v-if="canEdit" variant="ghost" @click="release(row)">Remove from queue</AppButton>
222
+ </div>
223
+ <div v-if="!lift.active && !lift.queue?.length" class="text-caption text-medium-emphasis">
224
+ Nobody is waiting.
225
+ </div>
226
+
227
+ <div v-if="canEdit && robotBrand === 'demo' && !thisRobotWaiting" class="d-flex align-center flex-wrap ga-2 mt-2">
228
+ <AppSelect
229
+ v-model="requestFrom[lift.liftName]"
230
+ :items="lift.floors"
231
+ label="From floor"
232
+ density="compact"
233
+ hide-details
234
+ style="max-width: 130px"
235
+ />
236
+ <AppSelect
237
+ v-model="requestTo[lift.liftName]"
238
+ :items="lift.floors"
239
+ label="To floor"
240
+ density="compact"
241
+ hide-details
242
+ style="max-width: 130px"
243
+ />
244
+ <AppButton
245
+ variant="ghost"
246
+ icon="mdi-elevator-passenger-outline"
247
+ :disabled="requesting"
248
+ @click="askForLift(lift)"
249
+ >
250
+ Request lift for {{ robotName || "this robot" }}
251
+ </AppButton>
252
+ </div>
253
+ </div>
254
+ <p v-if="robotBrand !== 'demo'" class="text-caption text-medium-emphasis mb-0">
255
+ Only demo robots can ride a lift for now. Real lifts need the lift maker's driver, which is not available yet.
256
+ </p>
257
+ </div>
71
258
  </AppCard>
72
259
  </template>
73
260
 
74
261
  <script lang="ts" setup>
75
262
  /**
76
- * The building, in 3D, generated from the robot's own floor plan.
263
+ * The building, in 3D, generated from the robot's own floor plan - plus the
264
+ * saved layout: doors, lift shafts and floor heights, which the floor plan
265
+ * cannot say by itself.
77
266
  *
78
- * 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
79
268
  * are already dark pixels — so it is fetched into a canvas, thresholded, traced
80
269
  * into wall segments and extruded. Open-RMF does the same thing from an
81
270
  * annotated plan; this skips the annotation because the robot has surveyed the
82
271
  * building already.
83
272
  *
273
+ * ## The saved layout
274
+ *
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
279
+ * map the view is exactly what it was before - the saved map only adds. A lift
280
+ * shaft runs through every floor it stops at, which the stacked view shows.
281
+ *
84
282
  * ## Why the image is fetched every time
85
283
  *
86
284
  * The vendor signs its map URLs for about an hour. A URL kept in a record is a
@@ -100,13 +298,36 @@
100
298
  */
101
299
  import {
102
300
  depthOf,
301
+ distanceToSegment,
302
+ doorSolid,
303
+ drawnWallSolid,
304
+ featuresForLevel,
103
305
  fitView,
104
306
  gridFromImageData,
307
+ insideLift,
308
+ layoutProblem,
309
+ levelElevations,
310
+ levelFeatures,
105
311
  levelSolids,
312
+ liftSolid,
313
+ MAX_ZONE_POINTS,
314
+ MIN_WALL_M,
315
+ nearestPoint,
316
+ nextFeatureName,
317
+ pointInPolygon,
318
+ polygonArea,
319
+ polygonCentre,
320
+ popUndo,
106
321
  projectPoint,
107
- stackedElevations,
322
+ pushUndo,
323
+ unprojectPoint,
108
324
  wallCorners,
109
325
  wallsFromOccupancyGrid,
326
+ type TMapDoor,
327
+ type TMapDrawnWall,
328
+ type TMapLift,
329
+ type TMapPointM,
330
+ type TMapZone,
110
331
  type TView,
111
332
  type TWallSolid,
112
333
  } from "../../utils/building-map";
@@ -117,43 +338,78 @@ const props = defineProps<{
117
338
  robotId: string;
118
339
  /** Drawn on the plan when its position and floor are both known. */
119
340
  robotState?: Record<string, any> | null;
341
+ /** May this person save the layout and use the lift (`update-robot`)? */
342
+ canEdit?: boolean;
343
+ robotName?: string;
344
+ /** Only the demo brand can ride the simulated lift. */
345
+ robotBrand?: string;
120
346
  }>();
121
347
 
122
- const { getRobotMaps, getRobotMapImages } = useRobots();
348
+ const {
349
+ getRobotMaps,
350
+ getRobotMapImages,
351
+ listBuildingMaps,
352
+ getBuildingMap,
353
+ createBuildingMap,
354
+ updateBuildingMap,
355
+ deleteBuildingMap,
356
+ getLiftQueue,
357
+ requestLift,
358
+ releaseLiftSession,
359
+ } = useRobots();
123
360
 
124
361
  const stage = ref<HTMLElement | null>(null);
125
362
  const canvasEl = ref<HTMLCanvasElement | null>(null);
126
363
 
127
364
  const maps = ref<Array<Record<string, any>>>([]);
128
365
  const selectedFloor = ref<number | null>(null);
129
- const solids = ref<TWallSolid[]>([]);
130
- const imageHeight = ref(0);
366
+ const wallSolids = ref<TWallSolid[]>([]);
131
367
  const loading = ref(true);
132
368
  const error = ref("");
133
369
  const rotation = ref(Math.PI / 5);
134
370
  const tilted = ref(true);
135
371
 
136
- const wallCount = computed(() => solids.value.length);
372
+ /* The saved layout, and the working copy the editor changes. */
373
+ const savedMap = ref<Record<string, any> | null>(null);
374
+ const savedLoadFailed = ref(false);
375
+ const doors = ref<TMapDoor[]>([]);
376
+ const lifts = ref<TMapLift[]>([]);
377
+ const heights = ref<Record<number, number | undefined>>({});
378
+ const drawnWalls = ref<TMapDrawnWall[]>([]);
379
+ const zones = ref<TMapZone[]>([]);
380
+
381
+ const wallCount = computed(() => wallSolids.value.length);
382
+ const featureCount = computed(
383
+ () => doors.value.length + lifts.value.length + drawnWalls.value.length + zones.value.length,
384
+ );
137
385
 
138
386
  /**
139
- * "All levels" stacks every floor the robot has mapped, one storey apart.
387
+ * "All levels" stacks every floor the robot has mapped.
140
388
  * A sentinel rather than null, because null already means "nothing chosen".
141
389
  */
142
390
  const ALL_LEVELS = -1_000_000;
143
391
 
144
- const floorOptions = computed(() => {
145
- const floors = maps.value
146
- .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: m.floorNo }))
147
- .sort((a, b) => a.value - b.value);
148
- return floors.length > 1
149
- ? [...floors, { title: "All levels (stacked)", value: ALL_LEVELS }]
150
- : floors;
151
- });
392
+ const realFloorOptions = computed(() =>
393
+ maps.value
394
+ .map((m) => ({ title: m.mapName?.trim() || `Floor ${m.floorNo}`, value: Number(m.floorNo) }))
395
+ .sort((a, b) => a.value - b.value),
396
+ );
397
+
398
+ const floorOptions = computed(() =>
399
+ realFloorOptions.value.length > 1
400
+ ? [...realFloorOptions.value, { title: "All levels (stacked)", value: ALL_LEVELS }]
401
+ : realFloorOptions.value,
402
+ );
152
403
 
153
404
  const stacked = computed(() => selectedFloor.value === ALL_LEVELS);
154
405
 
155
- /** Each floor's height in the stack; a single floor sits at zero. */
156
- const elevations = computed(() => stackedElevations(maps.value.map((m) => Number(m.floorNo))));
406
+ /** Each floor's height: saved where set, otherwise one storey apart. */
407
+ const elevations = computed(() =>
408
+ levelElevations(
409
+ maps.value.map((m) => Number(m.floorNo)),
410
+ Object.entries(heights.value).map(([f, h]) => ({ floorNo: Number(f), elevationM: h })),
411
+ ),
412
+ );
157
413
 
158
414
  /* ------------------------------------------------------------------ load */
159
415
 
@@ -170,6 +426,7 @@ async function load() {
170
426
  }
171
427
  selectedFloor.value = floorOptions.value[0]?.value ?? null;
172
428
  }
429
+ await loadSaved();
173
430
  await buildLevel();
174
431
  } catch (e) {
175
432
  error.value = robotErrorMessage(e, "Could not load this building's floor plan.");
@@ -178,17 +435,48 @@ async function load() {
178
435
  }
179
436
  }
180
437
 
438
+ /**
439
+ * The newest saved map, if any. Never fails the view: without a saved map the
440
+ * building shows exactly as it always did. A map that exists but could not be
441
+ * read turns editing OFF - saving blind would create a second map beside it.
442
+ */
443
+ async function loadSaved() {
444
+ savedLoadFailed.value = false;
445
+ try {
446
+ const list = await listBuildingMaps(props.robotId, { limit: 1 });
447
+ const first = list?.items?.[0];
448
+ savedMap.value = first ? await getBuildingMap(String(first._id)) : null;
449
+ } catch {
450
+ savedMap.value = null;
451
+ savedLoadFailed.value = true;
452
+ }
453
+ applySaved(savedMap.value);
454
+ pollLifts();
455
+ }
456
+
457
+ function applySaved(map: Record<string, any> | null) {
458
+ const copy = (v: unknown) => JSON.parse(JSON.stringify(v ?? []));
459
+ doors.value = copy(map?.doors);
460
+ lifts.value = copy(map?.lifts);
461
+ const drawn = levelFeatures(map?.levels);
462
+ drawnWalls.value = drawn.walls;
463
+ zones.value = drawn.zones;
464
+ const h: Record<number, number | undefined> = {};
465
+ for (const level of map?.levels ?? []) {
466
+ if (typeof level.elevationM === "number") h[Number(level.floorNo)] = level.elevationM;
467
+ }
468
+ heights.value = h;
469
+ }
470
+
181
471
  /**
182
472
  * Fetch the selected floor's plan - or every floor's, stacked - trace the
183
- * walls and extrude them. Stacking uses only what the robot's maps already
184
- * return (floor number, plan image, scale, origin); floors sit one storey
185
- * apart because the maps carry no height.
473
+ * walls and extrude them.
186
474
  */
187
475
  async function buildLevel() {
188
- solids.value = [];
476
+ wallSolids.value = [];
189
477
  const chosen = stacked.value
190
478
  ? [...maps.value].sort((a, b) => a.floorNo - b.floorNo)
191
- : maps.value.filter((m) => m.floorNo === selectedFloor.value);
479
+ : maps.value.filter((m) => Number(m.floorNo) === selectedFloor.value);
192
480
 
193
481
  if (!chosen.length || chosen.some((m) => !m.backgroundFileKey)) {
194
482
  error.value = "This floor has no plan image.";
@@ -205,12 +493,13 @@ async function buildLevel() {
205
493
  error.value = "The floor plan image could not be fetched.";
206
494
  return;
207
495
  }
208
- const level = await traceLevel(map, url, stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0);
496
+ const z = stacked.value ? elevations.value.get(Number(map.floorNo)) ?? 0 : 0;
497
+ const level = await traceLevel(map, url, z);
209
498
  if (!level) return;
210
499
  built.push(...level);
211
500
  }
212
501
 
213
- solids.value = built;
502
+ wallSolids.value = built;
214
503
  draw();
215
504
  }
216
505
 
@@ -221,7 +510,6 @@ async function traceLevel(
221
510
  elevationM: number,
222
511
  ): Promise<TWallSolid[] | null> {
223
512
  const image = await loadImage(url);
224
- imageHeight.value = image.height;
225
513
 
226
514
  const work = document.createElement("canvas");
227
515
  work.width = image.width;
@@ -268,6 +556,60 @@ function loadImage(url: string): Promise<HTMLImageElement> {
268
556
 
269
557
  /* ------------------------------------------------------------------ draw */
270
558
 
559
+ /** Solids that are the thing being edited, so they draw highlighted. */
560
+ let highlighted = new WeakSet<TWallSolid>();
561
+
562
+ /** Doors, lift shafts and the simulated car, for the current view. */
563
+ function featureSolids(): TWallSolid[] {
564
+ highlighted = new WeakSet();
565
+ const out: TWallSolid[] = [];
566
+ const elev = elevations.value;
567
+ const floor = selectedFloor.value ?? undefined;
568
+
569
+ doors.value.forEach((door, i) => {
570
+ if (stacked.value ? !elev.has(door.floorNo) : door.floorNo !== floor) return;
571
+ const solid = doorSolid(door, stacked.value ? elev.get(door.floorNo) ?? 0 : 0);
572
+ if (!solid) return;
573
+ if (selected.value?.kind === "door" && selected.value.index === i) highlighted.add(solid);
574
+ out.push(solid);
575
+ });
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
+
585
+ lifts.value.forEach((lift, i) => {
586
+ const solid = stacked.value ? liftSolid(lift, elev) : liftSolid(lift, elev, floor);
587
+ if (!solid) return;
588
+ if (selected.value?.kind === "lift" && selected.value.index === i) highlighted.add(solid);
589
+ out.push(solid);
590
+ });
591
+
592
+ // The simulated car, on the floor it is at - stacked only, where floors differ.
593
+ if (stacked.value && !editing.value) {
594
+ for (const q of liftQueue.value) {
595
+ const lift = lifts.value.find((l) => l.name === q.liftName);
596
+ const at = Number(q.state?.currentFloor);
597
+ if (!lift || !elev.has(at)) continue;
598
+ out.push({
599
+ kind: "car",
600
+ centre: { x: lift.x, y: lift.y, z: (elev.get(at) ?? 0) + 1.1 },
601
+ lengthM: lift.widthM * 0.8,
602
+ thicknessM: lift.depthM * 0.8,
603
+ heightM: 2.2,
604
+ yaw: 0,
605
+ });
606
+ }
607
+ }
608
+ return out;
609
+ }
610
+
611
+ let lastView: TView | null = null;
612
+
271
613
  function draw() {
272
614
  const canvas = canvasEl.value;
273
615
  const host = stage.value;
@@ -286,22 +628,64 @@ function draw() {
286
628
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
287
629
  ctx.clearRect(0, 0, width, height);
288
630
 
289
- const view: TView = fitView(solids.value, { width, height }, {
631
+ const features = featureSolids();
632
+ const scene = [...wallSolids.value, ...features];
633
+
634
+ // Framed on the walls when there are any, so adding or dragging a feature
635
+ // does not move the whole picture under the pointer.
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 }, {
290
640
  rotation: rotation.value,
291
641
  tilt: tilted.value ? 0.95 : 0,
292
642
  });
643
+ lastView = view;
293
644
 
294
645
  // Painter's algorithm: with no depth buffer, draw order IS the depth test.
295
646
  // Lower storeys first when stacked - seen from above, a floor hides the one
296
647
  // beneath it, never the other way round.
297
- const ordered = [...solids.value].sort(
648
+ const ordered = [...scene].sort(
298
649
  (a, b) => a.centre.z - b.centre.z || depthOf(a.centre, view) - depthOf(b.centre, view),
299
650
  );
300
651
 
301
- 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);
663
+ drawPending(ctx, view);
664
+ drawHandles(ctx, view);
302
665
  drawRobot(ctx, view);
303
666
  }
304
667
 
668
+ /** Fill colour per kind of box; the face shade multiplies it. */
669
+ function fillFor(solid: TWallSolid, shade: number): string {
670
+ const lit = highlighted.has(solid) ? 1.15 : 1;
671
+ const c = (r: number, g: number, b: number, a = 1) =>
672
+ `rgba(${Math.min(255, Math.round(r * shade * lit))},${Math.min(255, Math.round(g * shade * lit))},${Math.min(255, Math.round(b * shade * lit))},${a})`;
673
+ switch (solid.kind) {
674
+ case "door":
675
+ return c(196, 128, 66);
676
+ case "lift":
677
+ return c(60, 130, 230, highlighted.has(solid) ? 0.45 : 0.28);
678
+ case "car":
679
+ return c(255, 150, 40);
680
+ case "drawn":
681
+ return c(120, 132, 170);
682
+ default: {
683
+ const v = Math.round(150 * shade + 60);
684
+ return `rgb(${v},${v + 4},${v + 8})`;
685
+ }
686
+ }
687
+ }
688
+
305
689
  /** The three visible faces of a box: top, and two sides. */
306
690
  function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView) {
307
691
  const c = wallCorners(solid).map((p) => projectPoint(p.x, p.y, p.z, view));
@@ -318,15 +702,94 @@ function drawBox(ctx: CanvasRenderingContext2D, solid: TWallSolid, view: TView)
318
702
  ctx.beginPath();
319
703
  face.idx.forEach((i, n) => (n === 0 ? ctx.moveTo(c[i].x, c[i].y) : ctx.lineTo(c[i].x, c[i].y)));
320
704
  ctx.closePath();
321
- const v = Math.round(150 * face.shade + 60);
322
- ctx.fillStyle = `rgb(${v},${v + 4},${v + 8})`;
705
+ ctx.fillStyle = fillFor(solid, face.shade);
323
706
  ctx.fill();
324
- ctx.strokeStyle = "rgba(20,28,38,0.22)";
325
- ctx.lineWidth = 0.6;
707
+ ctx.strokeStyle = highlighted.has(solid) ? "rgba(255,90,31,0.9)" : "rgba(20,28,38,0.22)";
708
+ ctx.lineWidth = highlighted.has(solid) ? 1.4 : 0.6;
326
709
  ctx.stroke();
327
710
  }
328
711
  }
329
712
 
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));
734
+ ctx.beginPath();
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)";
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
+ }
791
+ }
792
+
330
793
  /**
331
794
  * The robot, only when its position AND its floor are both known.
332
795
  *
@@ -370,7 +833,626 @@ function toggleTilt() {
370
833
  draw();
371
834
  }
372
835
 
836
+ /* ------------------------------------------------------------------- edit */
837
+
838
+ const editing = ref(false);
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);
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);
850
+ const saving = ref(false);
851
+ const editError = ref("");
852
+ const confirmRemove = ref(false);
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;
863
+
864
+ const toolOptions = [
865
+ { label: "Select / move", value: "select" },
866
+ { label: "Draw walls", value: "wall" },
867
+ { label: "Draw zone", value: "zone" },
868
+ { label: "Add door", value: "door" },
869
+ { label: "Add lift shaft", value: "lift" },
870
+ ];
871
+ const doorTypes = [
872
+ { title: "Hinged", value: "hinged" },
873
+ { title: "Sliding", value: "sliding" },
874
+ ];
875
+
876
+ const toolHint = computed(() => {
877
+ if (tool.value === "door") {
878
+ return pendingDoorStart.value ? "Click where the door ends." : "Click where the door starts.";
879
+ }
880
+ if (tool.value === "lift") return "Click the middle of the lift shaft.";
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.";
892
+ });
893
+
894
+ const selectedFeature = computed<TMapDoor | TMapLift | TMapDrawnWall | TMapZone | null>(() => {
895
+ const s = selected.value;
896
+ if (!s) return 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";
911
+ });
912
+
913
+ /* The selected door's type and the selected lift's floors, as plain models. */
914
+ const doorType = computed<string>({
915
+ get: () => (selected.value?.kind === "door" ? doors.value[selected.value.index]?.type ?? "hinged" : "hinged"),
916
+ set: (v) => {
917
+ const s = selected.value;
918
+ if (s?.kind === "door" && doors.value[s.index]) {
919
+ remember();
920
+ doors.value[s.index].type = v === "sliding" ? "sliding" : "hinged";
921
+ }
922
+ },
923
+ });
924
+ const liftFloors = computed<number[]>({
925
+ get: () => (selected.value?.kind === "lift" ? lifts.value[selected.value.index]?.floors ?? [] : []),
926
+ set: (v) => {
927
+ const s = selected.value;
928
+ if (s?.kind === "lift" && lifts.value[s.index]) {
929
+ remember();
930
+ lifts.value[s.index].floors = [...new Set(v.map(Number))].sort((a, b) => a - b);
931
+ draw();
932
+ }
933
+ },
934
+ });
935
+
936
+ /** The selected floor's saved height, editable. Blank = one storey above. */
937
+ const currentHeight = computed<number | string>({
938
+ get: () => (selectedFloor.value !== null ? heights.value[selectedFloor.value] ?? "" : ""),
939
+ set: (v) => {
940
+ if (selectedFloor.value === null) return;
941
+ const n = typeof v === "number" ? v : parseFloat(String(v));
942
+ heights.value = { ...heights.value, [selectedFloor.value]: Number.isFinite(n) ? n : undefined };
943
+ },
944
+ });
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
+
987
+ function startEditing() {
988
+ editing.value = true;
989
+ editError.value = "";
990
+ confirmRemove.value = false;
991
+ tool.value = "select";
992
+ selected.value = null;
993
+ undoStack.value = [];
994
+ tilted.value = false;
995
+ if (stacked.value) selectedFloor.value = realFloorOptions.value[0]?.value ?? null;
996
+ else draw();
997
+ }
998
+
999
+ function stopEditing() {
1000
+ editing.value = false;
1001
+ selected.value = null;
1002
+ clearPending();
1003
+ hover.value = null;
1004
+ undoStack.value = [];
1005
+ dragging = null;
1006
+ draw();
1007
+ }
1008
+
1009
+ function cancelEditing() {
1010
+ applySaved(savedMap.value);
1011
+ stopEditing();
1012
+ }
1013
+
1014
+ function worldAt(e: PointerEvent): TMapPointM | null {
1015
+ const canvas = canvasEl.value;
1016
+ if (!canvas || !lastView) return null;
1017
+ const r = canvas.getBoundingClientRect();
1018
+ return unprojectPoint(e.clientX - r.left, e.clientY - r.top, lastView, 0);
1019
+ }
1020
+
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();
1039
+ const floor = selectedFloor.value;
1040
+ const li = lifts.value.findIndex((l) => l.floors.includes(floor ?? NaN) && insideLift(p, l));
1041
+ if (li >= 0) return { kind: "lift", index: li };
1042
+ const di = doors.value.findIndex(
1043
+ (d) => d.floorNo === floor && distanceToSegment(p, d.start, d.end) <= tol,
1044
+ );
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 [];
1063
+ }
1064
+
1065
+ const round = (n: number) => Math.round(n * 100) / 100;
1066
+ const roundPoint = (p: TMapPointM) => ({ x: round(p.x), y: round(p.y) });
1067
+
1068
+ function onPointerDown(e: PointerEvent) {
1069
+ if (!editing.value || selectedFloor.value === null) return;
1070
+ const p = worldAt(e);
1071
+ if (!p) return;
1072
+ editError.value = "";
1073
+ stage.value?.focus?.({ preventScroll: true });
1074
+
1075
+ if (tool.value === "door") {
1076
+ const start = pendingDoorStart.value;
1077
+ if (!start) {
1078
+ pendingDoorStart.value = roundPoint(p);
1079
+ } else {
1080
+ pendingDoorStart.value = null;
1081
+ if (Math.hypot(p.x - start.x, p.y - start.y) >= 0.3) {
1082
+ remember();
1083
+ doors.value.push({
1084
+ name: nextFeatureName(doors.value.map((d) => d.name), "door"),
1085
+ floorNo: selectedFloor.value,
1086
+ type: "hinged",
1087
+ start,
1088
+ end: roundPoint(p),
1089
+ });
1090
+ selected.value = { kind: "door", index: doors.value.length - 1 };
1091
+ } else {
1092
+ editError.value = "A door must be at least 30 cm wide.";
1093
+ }
1094
+ }
1095
+ draw();
1096
+ return;
1097
+ }
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
+
1133
+ if (tool.value === "lift") {
1134
+ const floors = realFloorOptions.value.map((f) => f.value);
1135
+ if (floors.length < 2) {
1136
+ editError.value = "A lift shaft needs at least two floors on this robot's map.";
1137
+ return;
1138
+ }
1139
+ remember();
1140
+ lifts.value.push({
1141
+ name: nextFeatureName(lifts.value.map((l) => l.name), "lift"),
1142
+ ...roundPoint(p),
1143
+ widthM: 2,
1144
+ depthM: 2,
1145
+ floors,
1146
+ });
1147
+ selected.value = { kind: "lift", index: lifts.value.length - 1 };
1148
+ tool.value = "select";
1149
+ draw();
1150
+ return;
1151
+ }
1152
+
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;
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";
1185
+ draw();
1186
+ }
1187
+
1188
+ function onPointerMove(e: PointerEvent) {
1189
+ if (!editing.value) return;
1190
+ const p = worldAt(e);
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
+ }
1199
+ const dx = p.x - dragging.last.x;
1200
+ const dy = p.y - dragging.last.y;
1201
+ if (!dx && !dy) return;
1202
+ if (!dragging.moved) {
1203
+ remember();
1204
+ dragging.moved = true;
1205
+ }
1206
+ dragging.last = p;
1207
+ const move = (q: TMapPointM) => roundPoint({ x: q.x + dx, y: q.y + dy });
1208
+
1209
+ if (dragging.kind === "lift") {
1210
+ const lift = lifts.value[dragging.index];
1211
+ lift.x = round(lift.x + dx);
1212
+ lift.y = round(lift.y + dy);
1213
+ } else if (dragging.kind === "door") {
1214
+ const door = doors.value[dragging.index];
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);
1230
+ }
1231
+ draw();
1232
+ }
1233
+
1234
+ function onPointerUp() {
1235
+ dragging = null;
1236
+ }
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
+
1258
+ function removeSelected() {
1259
+ const s = selected.value;
1260
+ if (!s) return;
1261
+ remember();
1262
+ ({ door: doors.value, lift: lifts.value, wall: drawnWalls.value, zone: zones.value })[s.kind].splice(s.index, 1);
1263
+ selected.value = null;
1264
+ draw();
1265
+ }
1266
+
1267
+ /** What gets saved. Walls and zones on floors this robot no longer maps are kept as they are. */
1268
+ function payload() {
1269
+ const savedLevels: Array<Record<string, any>> = savedMap.value?.levels ?? [];
1270
+ const floorNos = [
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
+ ]),
1277
+ ].sort((a, b) => a - b);
1278
+
1279
+ const levels = floorNos.map((floorNo) => {
1280
+ const saved = savedLevels.find((l) => Number(l.floorNo) === floorNo) ?? {};
1281
+ const robotMap = maps.value.find((m) => Number(m.floorNo) === floorNo);
1282
+ const level: Record<string, any> = {
1283
+ floorNo,
1284
+ name: robotMap?.mapName?.trim() || saved.name || "",
1285
+ ...featuresForLevel(floorNo, drawnWalls.value, zones.value),
1286
+ };
1287
+ const h = heights.value[floorNo];
1288
+ if (typeof h === "number" && Number.isFinite(h)) level.elevationM = h;
1289
+ return level;
1290
+ });
1291
+
1292
+ return {
1293
+ name: savedMap.value?.name || `${props.robotName || "Robot"} building`,
1294
+ levels,
1295
+ doors: doors.value.map((d) => ({ ...d, name: d.name.trim() || "Door" })),
1296
+ lifts: lifts.value.map((l) => ({ ...l, name: l.name.trim() || "Lift" })),
1297
+ };
1298
+ }
1299
+
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
+ }
1310
+ const body = payload();
1311
+ const short = body.lifts.find((l) => l.floors.length < 2);
1312
+ if (short) {
1313
+ editError.value = `${short.name} must stop at two floors or more.`;
1314
+ return;
1315
+ }
1316
+ saving.value = true;
1317
+ editError.value = "";
1318
+ try {
1319
+ if (savedMap.value?._id) {
1320
+ await updateBuildingMap(String(savedMap.value._id), { ...body, version: savedMap.value.version });
1321
+ savedMap.value = await getBuildingMap(String(savedMap.value._id));
1322
+ } else {
1323
+ const res = await createBuildingMap({ ...body, robotId: props.robotId });
1324
+ savedMap.value = await getBuildingMap(String(res.id));
1325
+ }
1326
+ applySaved(savedMap.value);
1327
+ stopEditing();
1328
+ // Heights may have changed the stack.
1329
+ if (stacked.value) await buildLevel();
1330
+ pollLifts();
1331
+ } catch (e) {
1332
+ editError.value = robotErrorMessage(e, "Could not save the layout.");
1333
+ } finally {
1334
+ saving.value = false;
1335
+ }
1336
+ }
1337
+
1338
+ let confirmTimer: ReturnType<typeof setTimeout> | undefined;
1339
+ async function removeSaved() {
1340
+ if (!savedMap.value?._id) return;
1341
+ if (!confirmRemove.value) {
1342
+ confirmRemove.value = true;
1343
+ clearTimeout(confirmTimer);
1344
+ confirmTimer = setTimeout(() => (confirmRemove.value = false), 4000);
1345
+ return;
1346
+ }
1347
+ saving.value = true;
1348
+ try {
1349
+ await deleteBuildingMap(String(savedMap.value._id));
1350
+ savedMap.value = null;
1351
+ liftQueue.value = [];
1352
+ applySaved(null);
1353
+ stopEditing();
1354
+ } catch (e) {
1355
+ editError.value = robotErrorMessage(e, "Could not remove the layout.");
1356
+ } finally {
1357
+ saving.value = false;
1358
+ confirmRemove.value = false;
1359
+ }
1360
+ }
1361
+
1362
+ /* ------------------------------------------------------------------ lifts */
1363
+
1364
+ const liftQueue = ref<Array<Record<string, any>>>([]);
1365
+ const liftError = ref("");
1366
+ const requesting = ref(false);
1367
+ const requestFrom = ref<Record<string, number>>({});
1368
+ const requestTo = ref<Record<string, number>>({});
1369
+
1370
+ const thisRobotWaiting = computed(() =>
1371
+ liftQueue.value.some(
1372
+ (l) =>
1373
+ String(l.active?.robotId ?? "") === props.robotId ||
1374
+ (l.queue ?? []).some((q: any) => String(q.robotId) === props.robotId),
1375
+ ),
1376
+ );
1377
+
1378
+ async function pollLifts() {
1379
+ const id = savedMap.value?._id;
1380
+ if (!id || !savedMap.value?.lifts?.length || editing.value) return;
1381
+ try {
1382
+ const res = await getLiftQueue(String(id));
1383
+ liftQueue.value = res?.items ?? [];
1384
+ liftError.value = "";
1385
+ for (const lift of liftQueue.value) {
1386
+ requestFrom.value[lift.liftName] ??= lift.floors?.[0];
1387
+ requestTo.value[lift.liftName] ??= lift.floors?.[lift.floors.length - 1];
1388
+ }
1389
+ if (stacked.value) draw();
1390
+ } catch (e) {
1391
+ liftError.value = robotErrorMessage(e, "Could not read the lift queue.");
1392
+ }
1393
+ }
1394
+
1395
+ async function askForLift(lift: Record<string, any>) {
1396
+ if (!savedMap.value?._id) return;
1397
+ requesting.value = true;
1398
+ liftError.value = "";
1399
+ try {
1400
+ await requestLift(String(savedMap.value._id), lift.liftName, {
1401
+ robotId: props.robotId,
1402
+ fromFloor: Number(requestFrom.value[lift.liftName]),
1403
+ toFloor: Number(requestTo.value[lift.liftName]),
1404
+ });
1405
+ await pollLifts();
1406
+ } catch (e) {
1407
+ liftError.value = robotErrorMessage(e, "Could not request the lift.");
1408
+ } finally {
1409
+ requesting.value = false;
1410
+ }
1411
+ }
1412
+
1413
+ async function release(row: Record<string, any>) {
1414
+ liftError.value = "";
1415
+ try {
1416
+ await releaseLiftSession(String(row._id));
1417
+ await pollLifts();
1418
+ } catch (e) {
1419
+ liftError.value = robotErrorMessage(e, "Could not release the lift.");
1420
+ }
1421
+ }
1422
+
1423
+ function motionLabel(state: any) {
1424
+ return ["stopped", "going up", "going down", "position unknown"][state?.motionState] ?? "position unknown";
1425
+ }
1426
+ function doorLabel(state: any) {
1427
+ return ["closed", "moving", "open"][state?.doorState] ?? "unknown";
1428
+ }
1429
+ function phaseLabel(lift: any) {
1430
+ const a = lift.active;
1431
+ switch (lift.phase) {
1432
+ case "to-pickup":
1433
+ return `Going to floor ${a?.fromFloor} to collect ${a?.robotName}.`;
1434
+ case "boarding":
1435
+ return `${a?.robotName} is getting in.`;
1436
+ case "to-destination":
1437
+ return `Carrying ${a?.robotName} to floor ${a?.toFloor}.`;
1438
+ case "arrived":
1439
+ return `${a?.robotName} can get out at floor ${a?.toFloor}.`;
1440
+ default:
1441
+ return "Free.";
1442
+ }
1443
+ }
1444
+ function untilLabel(when: string) {
1445
+ const ms = new Date(when).getTime() - Date.now();
1446
+ if (!Number.isFinite(ms) || ms <= 0) return "now";
1447
+ const s = Math.round(ms / 1000);
1448
+ return `in ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
1449
+ }
1450
+
1451
+ /* ---------------------------------------------------------------- watches */
1452
+
373
1453
  watch(selectedFloor, async () => {
1454
+ selected.value = null;
1455
+ clearPending();
374
1456
  if (!maps.value.length) return;
375
1457
  loading.value = true;
376
1458
  error.value = "";
@@ -383,16 +1465,30 @@ watch(selectedFloor, async () => {
383
1465
  }
384
1466
  });
385
1467
 
1468
+ watch(tool, () => {
1469
+ clearPending();
1470
+ hover.value = null;
1471
+ draw();
1472
+ });
1473
+
386
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);
387
1477
 
388
1478
  let onResize: (() => void) | undefined;
1479
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
389
1480
  onMounted(() => {
390
1481
  load();
391
1482
  onResize = () => draw();
392
1483
  window.addEventListener("resize", onResize);
1484
+ // The queue moves on its own (leases run out, the car travels), so it is
1485
+ // re-read while the layout is open - and only then.
1486
+ pollTimer = setInterval(pollLifts, 3000);
393
1487
  });
394
1488
  onBeforeUnmount(() => {
395
1489
  if (onResize) window.removeEventListener("resize", onResize);
1490
+ clearInterval(pollTimer);
1491
+ clearTimeout(confirmTimer);
396
1492
  });
397
1493
  </script>
398
1494
 
@@ -403,10 +1499,14 @@ onBeforeUnmount(() => {
403
1499
  height: 460px;
404
1500
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.02), rgba(0, 0, 0, 0.06));
405
1501
  }
1502
+ .robot-map3d--placing .robot-map3d__canvas {
1503
+ cursor: crosshair;
1504
+ }
406
1505
  .robot-map3d__canvas {
407
1506
  display: block;
408
1507
  width: 100%;
409
1508
  height: 100%;
1509
+ touch-action: none;
410
1510
  }
411
1511
  .robot-map3d__overlay {
412
1512
  position: absolute;
@@ -417,5 +1517,24 @@ onBeforeUnmount(() => {
417
1517
  justify-content: center;
418
1518
  text-align: center;
419
1519
  padding: 24px;
1520
+ pointer-events: none;
1521
+ }
1522
+ .robot-map3d__overlay :deep(button) {
1523
+ pointer-events: auto;
1524
+ }
1525
+ .robot-map3d__editbar,
1526
+ .robot-map3d__panel {
1527
+ display: flex;
1528
+ flex-wrap: wrap;
1529
+ align-items: center;
1530
+ gap: 12px;
1531
+ border-bottom: 1px solid rgba(0, 0, 0, 0.08);
1532
+ }
1533
+ .robot-map3d__panel {
1534
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
1535
+ border-bottom: none;
1536
+ }
1537
+ .robot-map3d__lifts {
1538
+ border-top: 1px solid rgba(0, 0, 0, 0.08);
420
1539
  }
421
1540
  </style>