@7365admin1/layer-common 4.30.0 → 4.32.0

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.
@@ -103,7 +103,17 @@ export function floorLabel(state: {
103
103
  floorKnown?: unknown;
104
104
  } | null | undefined): string {
105
105
  if (!state || state.floorKnown !== true) return "Floor unknown";
106
- return typeof state.floorNo === "number" ? `Floor ${state.floorNo}` : "Floor unknown";
106
+ return typeof state.floorNo === "number" && Number.isInteger(state.floorNo) ? floorName(state.floorNo) : "Floor unknown";
107
+ }
108
+
109
+ /**
110
+ * A floor number as the building says it (the handoff's "L1" / "B1"):
111
+ * 1 and up = L1, L2…; below 0 = B1, B2…; 0 = G (ground). Anything else "—".
112
+ */
113
+ export function floorName(floorNo: unknown): string {
114
+ const n = typeof floorNo === "string" && floorNo.trim() !== "" ? Number(floorNo) : floorNo;
115
+ if (typeof n !== "number" || !Number.isInteger(n)) return "—";
116
+ return n > 0 ? `L${n}` : n < 0 ? `B${-n}` : "G";
107
117
  }
108
118
 
109
119
  /**
@@ -198,7 +208,7 @@ export function planSummary(plan: Record<string, any> | null | undefined) {
198
208
  const time = start && end ? `${start}–${end}` : start || end || "No time set";
199
209
 
200
210
  const jobs = (Array.isArray(plan?.jobList) ? plan!.jobList : []).map((job: any) => {
201
- const floor = typeof job?.floorNo === "number" ? `Floor ${job.floorNo}` : "Floor unknown";
211
+ const floor = typeof job?.floorNo === "number" ? floorName(job.floorNo) : "Floor unknown";
202
212
  const passes = typeof job?.cleanTimes === "number" ? `${job.cleanTimes} pass${job.cleanTimes === 1 ? "" : "es"}` : "";
203
213
  return [floor, passes].filter(Boolean).join(" · ");
204
214
  });
@@ -325,6 +335,13 @@ const REPORTED_FACTS: ReadonlyArray<{ fact: "battery" | "floor" | "position"; ne
325
335
  { fact: "floor", needs: "floorReporting" },
326
336
  { fact: "position", needs: "readLocation" },
327
337
  ];
338
+ /** The "Not reported by" line's words and order (the handoff's): battery, floor, spot clean, live position. */
339
+ const NOT_REPORTED: ReadonlyArray<{ word: string; needs: string; cleaningOnly?: boolean }> = [
340
+ { word: "battery", needs: "battery" },
341
+ { word: "floor", needs: "floorReporting" },
342
+ { word: "spot clean", needs: "spotClean", cleaningOnly: true },
343
+ { word: "live position", needs: "readLocation" },
344
+ ];
328
345
 
329
346
  /** Which facts this brand reports - a fact cell it cannot fill says "Not reported". */
330
347
  export function reportedFacts(capabilities: Record<string, unknown> | null | undefined) {
@@ -336,15 +353,25 @@ export function reportedFacts(capabilities: Record<string, unknown> | null | und
336
353
  }
337
354
 
338
355
  /**
339
- * "Not reported by Ounitech: battery, floor" - shown on robot detail so a
340
- * missing fact reads as the brand's limit, not a fault. The brand's trailing
341
- * model list ("Ounitech (Q3-G / Q3-W)") is dropped. Null when nothing is missing.
356
+ * "Not reported by Ounitech: battery, floor, spot clean" - shown on robot
357
+ * detail so a missing fact reads as the brand's limit, not a fault (the
358
+ * handoff's words and order). Spot clean is a cleaning job, so a security
359
+ * robot always lists it ("Not reported by Demo robots (simulated): spot clean"). The brand's trailing model list ("Ounitech
360
+ * (Q3-G / Q3-W)") is dropped. Null when nothing is missing.
342
361
  */
343
- export function notReportedLine(brand: unknown, capabilities: Record<string, unknown> | null | undefined): string | null {
344
- const facts = reportedFacts(capabilities);
345
- const missing = REPORTED_FACTS.filter((f) => !facts[f.fact]).map((f) => f.fact);
362
+ export function notReportedLine(
363
+ brand: unknown,
364
+ capabilities: Record<string, unknown> | null | undefined,
365
+ type?: unknown,
366
+ ): string | null {
367
+ const caps = capabilities ?? {};
368
+ // A security robot cannot spot clean whatever its brand declares, so it is listed too (the handoff's line).
369
+ const missing = NOT_REPORTED.filter((f) => caps[f.needs] !== true || (f.cleaningOnly && type === "security")).map(
370
+ (f) => f.word,
371
+ );
346
372
  if (!missing.length) return null;
347
- const name = (typeof brand === "string" ? brand : "").replace(/\s*\([^)]*\)\s*$/, "").trim() || "this brand";
373
+ // Drop a trailing MODEL list ("Ounitech (Q3-G / Q3-W)"), keep a qualifier ("Demo robots (simulated)").
374
+ const name = (typeof brand === "string" ? brand : "").replace(/\s*\([^)]*\/[^)]*\)\s*$/, "").trim() || "this brand";
348
375
  return `Not reported by ${name}: ${missing.join(", ")}`;
349
376
  }
350
377
 
@@ -564,6 +591,11 @@ export type TLiveRobotState = {
564
591
  floorNo?: number | null;
565
592
  floorKnown?: boolean;
566
593
  position?: { x: number; y: number; theta: number } | null;
594
+ /** Where it is on its own floor plan, 0-100 from the top-left; absent when the brand cannot say. */
595
+ planPosition?: { x: number; y: number } | null;
596
+ /** The brand's own status words ("CLEANING_AUTO"), quoted as "Brand status". */
597
+ statusName?: string;
598
+ model?: string;
567
599
  fault?: { code: string; message?: string; since?: number } | null;
568
600
  capabilities?: Record<string, unknown>;
569
601
  lastSeenAt?: string | null;
@@ -603,3 +635,482 @@ export function rowStatus(
603
635
  if (row?.offline === true) return { kind: "offline" };
604
636
  return { kind: "checking" };
605
637
  }
638
+
639
+ /* ============================================ site fleet (HERO phase c) */
640
+
641
+ /** "Cleaning" / "Security"; anything else is cleaning, the class a row written before `type` existed belongs to. */
642
+ export function typeLabel(type: unknown): string {
643
+ return type === "security" ? "Security" : "Cleaning";
644
+ }
645
+
646
+ /**
647
+ * The fleet list's paging, from the API's `{ items, pages, total }`.
648
+ *
649
+ * THE PAGE-1 BUG: the old fleet screen read `totalPages`, which the API has
650
+ * never sent (core's `paginate()` answers `pages` and `pageRange`), so it
651
+ * always believed there was one page and never offered the next. This reads
652
+ * what the API sends: `total`, else the count in `pageRange` ("1-10 of 60"),
653
+ * else the rows in hand; `pages`, else derived from the total.
654
+ */
655
+ export function listMeta(res: Record<string, any> | null | undefined, limit: number): { total: number; pages: number } {
656
+ const size = limit > 0 ? Math.floor(limit) : 10;
657
+ const rows = Array.isArray(res?.items) ? res!.items.length : 0;
658
+ let total = typeof res?.total === "number" && res.total >= 0 ? Math.floor(res.total) : NaN;
659
+ if (!Number.isFinite(total)) {
660
+ const m = /of\s+(\d+)/.exec(String(res?.pageRange ?? ""));
661
+ total = m ? Number(m[1]) : rows;
662
+ }
663
+ const sent = Number(res?.pages ?? res?.totalPages);
664
+ const pages = Number.isFinite(sent) && sent >= 1 ? Math.floor(sent) : Math.ceil(total / size);
665
+ return { total, pages: Math.max(1, pages) };
666
+ }
667
+
668
+ /**
669
+ * The site's six summary cells (README §2): Total · Online · Cleaning|Patrolling
670
+ * · Charging · Faults · Offline. Live counts are null ("—") until the server
671
+ * has read the robots (`live.asOf`); nothing at all is known before the
672
+ * summary arrives. Faults and Offline turn accent when above zero.
673
+ */
674
+ export function siteSummaryCells(summary: Record<string, any> | null | undefined, type: unknown) {
675
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
676
+ const known = !!summary;
677
+ const total = known ? num(summary!.total) ?? 0 : 0;
678
+ const live = known && summary!.live?.asOf ? summary!.live : null;
679
+ return [
680
+ { label: "Total", value: known ? total : null, total },
681
+ { label: "Online", value: live ? num(live.online?.count) : null, total },
682
+ { label: type === "security" ? "Patrolling" : "Cleaning", value: live ? num(live.working?.count) : null, total },
683
+ { label: "Charging", value: live ? num(live.charging?.count) : null, total },
684
+ { label: "Faults", value: known ? num(summary!.faults?.count) ?? 0 : null, total, kind: "faults" },
685
+ { label: "Offline", value: known ? num(summary!.offline?.count) ?? 0 : null, total, kind: "offline" },
686
+ ];
687
+ }
688
+
689
+ /** The empty state: "No cleaning robots at this site" and what to do about it. */
690
+ export function siteEmptyText(type: unknown, canSetup: unknown) {
691
+ return {
692
+ title: `No ${typeLabel(type).toLowerCase()} robots at this site`,
693
+ hint: canSetup === true ? "Add a robot to this site to start monitoring." : "Nothing has been deployed here yet.",
694
+ };
695
+ }
696
+
697
+ /** The header's role tag. Super Admin holds every right; otherwise Manager (may command or set up) or View-only. */
698
+ export function roleLabel(input: { superAdmin?: unknown; canCommand?: unknown; canSetup?: unknown }): string {
699
+ if (input?.superAdmin === true) return "Full rights";
700
+ return input?.canCommand === true || input?.canSetup === true ? "Manager" : "View-only";
701
+ }
702
+
703
+ /**
704
+ * A brand's display name: the build's own (`/robots/brands`) with any
705
+ * trailing model list dropped ("Ounitech (Q3-G / Q3-W)" -> "Ounitech", but
706
+ * "Demo robots (simulated)" keeps its honesty), else a readable form of the
707
+ * stored key - a brand with no adapter here ("sentry") still has a name.
708
+ */
709
+ export function brandName(brand: unknown, brands?: Array<{ brand?: unknown; displayName?: unknown }> | null): string {
710
+ const key = typeof brand === "string" && brand.trim() ? brand.trim() : "ounitech";
711
+ const hit = (brands ?? []).find((b) => b?.brand === key);
712
+ if (typeof hit?.displayName === "string" && hit.displayName) {
713
+ return hit.displayName.replace(/\s*\(([^)]*)\)\s*$/, (m, inner) => (/simulated/i.test(inner) ? m : ""));
714
+ }
715
+ if (key === "demo") return "Demo robots (simulated)";
716
+ return key.charAt(0).toUpperCase() + key.slice(1);
717
+ }
718
+
719
+ /* ------------------------------------------------------------- mini-map */
720
+
721
+ export type TMapRobot = { id: string; name: string; mode?: string; type?: string; left: string; top: string; rot: string };
722
+
723
+ const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
724
+
725
+ /** A robot's point on its floor plan (`planPosition`, 0-100 from top-left) as CSS left/top, or null. */
726
+ export function planPoint(state: { planPosition?: { x?: unknown; y?: unknown } | null } | null | undefined) {
727
+ const p = state?.planPosition;
728
+ if (!p || !finite(p.x) || !finite(p.y)) return null;
729
+ const clamp = (v: number) => Math.min(100, Math.max(0, v));
730
+ return { left: `${clamp(p.x)}%`, top: `${clamp(p.y)}%` };
731
+ }
732
+
733
+ /**
734
+ * The heading as a CSS rotation. `position.theta` is radians in the robot's
735
+ * map frame (y up); the screen's y runs down, so the angle is negated.
736
+ * 0deg (no heading) points right, like the prototype's heading tick.
737
+ */
738
+ export function headingDeg(state: { position?: { theta?: unknown } | null } | null | undefined): number {
739
+ const t = state?.position?.theta;
740
+ if (!finite(t)) return 0;
741
+ return Math.round(((((-t * 180) / Math.PI) % 360) + 360) % 360);
742
+ }
743
+
744
+ /** Is the robot live on a known floor with a plan position - i.e. may it be drawn? */
745
+ function placeable(live: TLiveRobotState | null | undefined) {
746
+ return !!live?.ok && live.online !== false && live.floorKnown === true && finite(live.floorNo) && !!planPoint(live as any);
747
+ }
748
+
749
+ /** The floors the mini-map can show: every floor a robot on screen reports, lowest first. */
750
+ export function mapFloors(ids: string[], states: Record<string, TLiveRobotState>): number[] {
751
+ const floors = new Set<number>();
752
+ for (const id of ids) {
753
+ const s = states[id];
754
+ if (s?.ok && s.floorKnown === true && finite(s.floorNo)) floors.add(s.floorNo);
755
+ }
756
+ return [...floors].sort((a, b) => a - b);
757
+ }
758
+
759
+ /**
760
+ * Which floor the mini-map opens on: the one chosen if it still exists, else
761
+ * the busiest (most robots placed; the handoff's "best floor"), else the lowest.
762
+ */
763
+ export function pickFloor(floors: number[], chosen: unknown, ids: string[], states: Record<string, TLiveRobotState>): number | null {
764
+ if (finite(chosen) && floors.includes(chosen)) return chosen;
765
+ if (!floors.length) return null;
766
+ let best = floors[0]!;
767
+ let most = -1;
768
+ for (const f of floors) {
769
+ const n = ids.filter((id) => placeable(states[id]) && states[id]!.floorNo === f).length;
770
+ if (n > most) {
771
+ most = n;
772
+ best = f;
773
+ }
774
+ }
775
+ return best;
776
+ }
777
+
778
+ /** The robots drawn on `floor`: live, online, on that floor, with a plan position. Never a stale dot. */
779
+ export function mapRobots(
780
+ rows: Array<{ _id?: unknown; name?: unknown; type?: unknown }>,
781
+ states: Record<string, TLiveRobotState>,
782
+ floor: number | null,
783
+ ): TMapRobot[] {
784
+ if (floor === null) return [];
785
+ return rows.flatMap((r) => {
786
+ const id = String(r?._id ?? "");
787
+ const live = states[id];
788
+ if (!placeable(live) || live!.floorNo !== floor) return [];
789
+ const at = planPoint(live as any)!;
790
+ return [{ id, name: String(r.name ?? ""), mode: live!.mode, type: r.type as string, ...at, rot: `rotate(${headingDeg(live)}deg)` }];
791
+ });
792
+ }
793
+
794
+ /** Robots that answer but cannot report a floor - listed, never placed (a guessed floor is worse than none). */
795
+ export function unplacedRobots<T extends { _id?: unknown }>(rows: T[], states: Record<string, TLiveRobotState>): T[] {
796
+ return rows.filter((r) => {
797
+ const live = states[String(r?._id ?? "")];
798
+ return !!live?.ok && live.monitorable !== false && live.floorKnown !== true;
799
+ });
800
+ }
801
+
802
+ /** "2 robots (Ounitech) can't report a floor, so they are listed but not placed on the map." */
803
+ export function unplacedText(brandNames: string[]): string {
804
+ const n = brandNames.length;
805
+ if (!n) return "";
806
+ const brands = [...new Set(brandNames)].join(", ");
807
+ return `${n} ${n === 1 ? "robot" : "robots"} (${brands}) can't report a floor, so ${n === 1 ? "it is" : "they are"} listed but not placed on the map.`;
808
+ }
809
+
810
+ /* -------------------------------------------------------- patrol routes */
811
+
812
+ export type TPatrolRouteView = {
813
+ id: string;
814
+ name: string;
815
+ floorNo: number | null;
816
+ checkpoints: Array<{ name: string; x: number; y: number }>;
817
+ currentCheckpoint: number | null;
818
+ };
819
+
820
+ /** The SVG path of a closed route on a `w` x `h` viewBox (checkpoints are 0-100 shares of the plan). */
821
+ export function routePathD(checkpoints: Array<{ x: number; y: number }>, w = 400, h = 300): string {
822
+ if (!checkpoints?.length) return "";
823
+ return checkpoints.map((p, i) => `${i ? "L" : "M"}${((p.x / 100) * w).toFixed(1)} ${((p.y / 100) * h).toFixed(1)}`).join(" ") + " Z";
824
+ }
825
+
826
+ /** Numbered checkpoint markers for every route; `current` = the one the robot is heading for. */
827
+ export function routeMarks(routes: TPatrolRouteView[]) {
828
+ return routes.flatMap((r) =>
829
+ r.checkpoints.map((c, i) => ({
830
+ key: `${r.id}-${i}`,
831
+ n: i + 1,
832
+ left: `${c.x}%`,
833
+ top: `${c.y}%`,
834
+ label: c.name,
835
+ current: r.currentCheckpoint === i,
836
+ })),
837
+ );
838
+ }
839
+
840
+ /** A route-name tag at each route's first checkpoint. */
841
+ export function routeTags(routes: TPatrolRouteView[]) {
842
+ return routes
843
+ .filter((r) => r.checkpoints.length)
844
+ .map((r) => ({ key: r.id, name: r.name, count: r.checkpoints.length, left: `${r.checkpoints[0]!.x}%`, top: `${r.checkpoints[0]!.y}%` }));
845
+ }
846
+
847
+ /**
848
+ * CSS `left` that keeps a tag inside the plan: at its checkpoint, or pulled
849
+ * back from the right edge by its (estimated) width - "Route B · Back-of-house"
850
+ * starting at 62% would otherwise run off a narrow mini-map.
851
+ * ponytail: width estimated from the text (uppercase Archivo 800); measure the
852
+ * element if a tag ever needs to be exact.
853
+ */
854
+ export function insideLeft(left: string, text: string, pxPerChar: number, padPx: number): string {
855
+ return `min(${left}, calc(100% - ${Math.ceil(text.length * pxPerChar + padPx)}px))`;
856
+ }
857
+
858
+ const DAY_SHORT = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
859
+
860
+ /**
861
+ * Days as a person says them: every day = "Daily"; a run of three or more
862
+ * = "Mon–Fri"; otherwise a list ("Sat", "Mon, Wed"). 1-7, Monday first.
863
+ */
864
+ export function dayRange(days: unknown): string {
865
+ const list = [...new Set((Array.isArray(days) ? days : []).filter((d) => Number.isInteger(d) && d >= 1 && d <= 7))].sort(
866
+ (a, b) => a - b,
867
+ ) as number[];
868
+ if (!list.length) return "No days set";
869
+ if (list.length === 7) return "Daily";
870
+ const parts: string[] = [];
871
+ for (let i = 0; i < list.length; ) {
872
+ let j = i;
873
+ while (j + 1 < list.length && list[j + 1] === list[j]! + 1) j++;
874
+ if (j - i >= 2) parts.push(`${DAY_SHORT[list[i]! - 1]}–${DAY_SHORT[list[j]! - 1]}`);
875
+ else for (let k = i; k <= j; k++) parts.push(DAY_SHORT[list[k]! - 1]!);
876
+ i = j + 1;
877
+ }
878
+ return parts.join(", ");
879
+ }
880
+
881
+ export type TScheduleRow = { key: string; days: string; time: string; jobs: string };
882
+
883
+ /** A floor number the way a schedule says it: "L1" (the handoff's schedule rows). */
884
+ const levelText = (floorNo: unknown) => (finite(floorNo) ? `L${floorNo}` : "Floor unknown");
885
+ const timeWindow = (start: unknown, end: unknown) => {
886
+ const s = typeof start === "string" ? start : "";
887
+ const e = typeof end === "string" ? end : "";
888
+ return s && e ? `${s}–${e}` : s || e || "No time set";
889
+ };
890
+
891
+ /**
892
+ * Patrol schedule rows (the owner's words): "Daily · 20:00–06:00 · Route A ·
893
+ * Lobby loop · L1 · 4 checkpoints × 6 rounds". A row whose route is not in
894
+ * the plan is dropped rather than shown without a name.
895
+ */
896
+ export function patrolScheduleRows(
897
+ plan: { routes?: TPatrolRouteView[]; schedule?: Array<Record<string, any>> } | null | undefined,
898
+ ): TScheduleRow[] {
899
+ const routes = plan?.routes ?? [];
900
+ return (plan?.schedule ?? []).flatMap((row, i) => {
901
+ const route = routes.find((r) => r.id === row?.routeId);
902
+ if (!route) return [];
903
+ const rounds = finite(row.rounds) ? row.rounds : 1;
904
+ return [
905
+ {
906
+ key: `${route.id}-${i}`,
907
+ days: dayRange(row.days),
908
+ time: timeWindow(row.startTime, row.endTime),
909
+ jobs: `${route.name} · ${levelText(route.floorNo)} · ${route.checkpoints.length} checkpoints × ${rounds} ${rounds === 1 ? "round" : "rounds"}`,
910
+ },
911
+ ];
912
+ });
913
+ }
914
+
915
+ /** Cleaning schedule rows from the brand's plans: "Mon–Fri · 22:00–02:00 · L1 × 2 passes · L2 × 1 pass". */
916
+ export function cleaningScheduleRows(plans: Array<Record<string, any>> | null | undefined): TScheduleRow[] {
917
+ return (plans ?? []).map((plan, i) => ({
918
+ key: String(plan?.planId ?? i),
919
+ days: dayRange(plan?.dateList),
920
+ time: timeWindow(plan?.startTime, plan?.endTime),
921
+ jobs: (Array.isArray(plan?.jobList) ? plan!.jobList : [])
922
+ .map((job: any) => {
923
+ const n = finite(job?.cleanTimes) ? job.cleanTimes : 1;
924
+ return `${levelText(job?.floorNo)} × ${n} ${n === 1 ? "pass" : "passes"}`;
925
+ })
926
+ .join(" · "),
927
+ }));
928
+ }
929
+
930
+ /* ---------------------------------------------------------- robot detail */
931
+
932
+ /** Modes in which a robot moves on its own - its trail grows and its speed is shown. */
933
+ const MOVING: ReadonlySet<string> = new Set(["WORKING", "IN_TRANSIT", "MANUAL"]);
934
+
935
+ /** Is the robot moving on its own (its trail grows)? */
936
+ export function isMoving(mode: unknown): boolean {
937
+ return typeof mode === "string" && MOVING.has(mode);
938
+ }
939
+
940
+ /**
941
+ * The status a command leaves the robot in, shown at once (optimistically)
942
+ * until the next reading confirms or corrects it - the handoff's `send()`.
943
+ */
944
+ export function optimisticMode(kind: unknown, mode: unknown): string {
945
+ switch (kind) {
946
+ case "full":
947
+ case "area":
948
+ case "spot":
949
+ case "resume":
950
+ return "WORKING";
951
+ case "return":
952
+ return "CHARGING_CYCLE";
953
+ case "pause":
954
+ return "PAUSED";
955
+ case "cancel":
956
+ return "IDLE";
957
+ case "navigate":
958
+ return "IN_TRANSIT";
959
+ default:
960
+ return typeof mode === "string" ? mode : "UNKNOWN";
961
+ }
962
+ }
963
+
964
+ /** The command's label ("Clean all"), for the toast "Clean all → HERO-C03". */
965
+ export function commandLabel(kind: unknown): string {
966
+ if (kind === "spot") return "Spot clean";
967
+ return COMMANDS.find((c) => c.kind === kind)?.label ?? String(kind ?? "");
968
+ }
969
+
970
+ /**
971
+ * The POST body for a command-bar button. Go to point / Set position carry a
972
+ * pose; until a point picker exists (building map, phase d) they send the
973
+ * robot's current reported pose. Null when that pose is unknown - the command
974
+ * cannot be sent.
975
+ */
976
+ export function commandBody(kind: TRobotCommandKind, live: TLiveRobotState | null | undefined): Record<string, unknown> | null {
977
+ if (kind !== "navigate" && kind !== "relocalize") return { kind };
978
+ const p = live?.position;
979
+ if (!p || !finite(p.x) || !finite(p.y) || !finite(p.theta)) return null;
980
+ if (kind === "navigate") return { kind, x: p.x, y: p.y, theta: p.theta };
981
+ return finite(live?.floorNo) ? { kind, floorNo: live!.floorNo, x: p.x, y: p.y, theta: p.theta } : null;
982
+ }
983
+
984
+ /**
985
+ * May the plan take spot-clean clicks? A Manager, a cleaning robot, a brand
986
+ * that declares `spotClean`, and a robot confirmed online. (A busy robot keeps
987
+ * the control; the server refuses with its own words.)
988
+ */
989
+ export function showSpotClean(input: {
990
+ canCommand?: unknown;
991
+ capabilities?: Record<string, unknown> | null;
992
+ online?: unknown;
993
+ type?: unknown;
994
+ }): boolean {
995
+ return input?.canCommand === true && input.online === true && input.type !== "security" && input.capabilities?.spotClean === true;
996
+ }
997
+
998
+ /** The breadcrumb trail: newest first, the last `max` positions, no repeat of the same spot. */
999
+ export function trailPush(trail: Array<{ x: number; y: number }>, point: { x: number; y: number } | null, max = 14) {
1000
+ if (!point || !finite(point.x) || !finite(point.y)) return trail;
1001
+ const head = trail[0];
1002
+ if (head && Math.abs(head.x - point.x) < 0.05 && Math.abs(head.y - point.y) < 0.05) return trail;
1003
+ return [{ x: point.x, y: point.y }, ...trail].slice(0, max);
1004
+ }
1005
+
1006
+ /** Trail dots with the handoff's fade: newest 0.8, oldest near 0. */
1007
+ export function trailDots(trail: Array<{ x: number; y: number }>) {
1008
+ return trail.map((p, i) => ({ key: i, left: `${p.x}%`, top: `${p.y}%`, op: Number(((1 - i / trail.length) * 0.8).toFixed(3)) }));
1009
+ }
1010
+
1011
+ /**
1012
+ * Speed from two poses in metres with their times (ms): "0.4 m/s". A robot
1013
+ * that is not moving, or two poses too close in time to measure, reads "0.0 m/s".
1014
+ */
1015
+ export function speedText(
1016
+ prev: { x: number; y: number; at: number } | null | undefined,
1017
+ next: { x: number; y: number; at: number } | null | undefined,
1018
+ mode?: unknown,
1019
+ ): string {
1020
+ if (!prev || !next || !isMoving(mode)) return "0.0 m/s";
1021
+ const dt = (next.at - prev.at) / 1000;
1022
+ if (!(dt > 0.2)) return "0.0 m/s";
1023
+ const v = Math.hypot(next.x - prev.x, next.y - prev.y) / dt;
1024
+ return `${Math.min(v, 9.9).toFixed(1)} m/s`;
1025
+ }
1026
+
1027
+ /** "x 17.9 · y 34.1 · 53°" (metres, the robot's map frame) - or "Reconnecting", or "Not reported". */
1028
+ export function positionText(live: TLiveRobotState | null | undefined, capabilities: Record<string, unknown> | null | undefined): string {
1029
+ if (capabilities?.readLocation !== true) return "Not reported";
1030
+ const p = live?.position;
1031
+ if (!live?.ok || live.online === false || !p || !finite(p.x) || !finite(p.y)) return "Reconnecting";
1032
+ const deg = finite(p.theta) ? Math.round(((((p.theta * 180) / Math.PI) % 360) + 360) % 360) : 0;
1033
+ return `x ${p.x.toFixed(1)} · y ${p.y.toFixed(1)} · ${deg}°`;
1034
+ }
1035
+
1036
+ export type TRobotFact = { label: string; value: string; dim: boolean };
1037
+
1038
+ /**
1039
+ * The detail screen's facts grid (README §3): Connection · Battery · Floor ·
1040
+ * Live position · Brand status · Model · Serial · Last seen. A fact the brand
1041
+ * cannot report reads "Not reported" at 50%; a brand with no interface
1042
+ * reports nothing live at all.
1043
+ */
1044
+ export function robotFacts(input: {
1045
+ record?: Record<string, any> | null;
1046
+ live?: (TLiveRobotState & { statusName?: string; model?: string }) | null;
1047
+ now?: number;
1048
+ }): TRobotFact[] {
1049
+ const live = input.live ?? null;
1050
+ const record = input.record ?? {};
1051
+ const none = live?.monitorable === false;
1052
+ const caps: Record<string, unknown> | null = none ? {} : live?.ok ? live.capabilities ?? {} : null;
1053
+ const reports = (need: string) => (caps ? caps[need] === true : true);
1054
+ const nr = (label: string): TRobotFact => ({ label, value: "Not reported", dim: true });
1055
+ const fact = (label: string, value: unknown): TRobotFact => ({ label, value: String(value || "—"), dim: false });
1056
+
1057
+ const connection = none
1058
+ ? nr("Connection")
1059
+ : fact("Connection", !live ? "Checking…" : !live.ok ? "Reconnecting" : live.online === false ? "Offline" : "Online");
1060
+ const battery = !reports("battery") ? nr("Battery") : fact("Battery", batteryReading(live?.batteryPercent)?.text);
1061
+ const floor = !reports("floorReporting")
1062
+ ? nr("Floor")
1063
+ : fact("Floor", live?.ok ? floorLabel({ floorNo: live.floorNo, floorKnown: live.floorKnown }) : "");
1064
+ const position = !reports("readLocation")
1065
+ ? nr("Live position")
1066
+ : fact("Live position", live ? positionText(live, caps ?? { readLocation: true }) : "");
1067
+ return [
1068
+ connection,
1069
+ battery,
1070
+ floor,
1071
+ position,
1072
+ none ? nr("Brand status") : fact("Brand status", live?.ok ? live.statusName : ""),
1073
+ fact("Model", live?.ok ? live.model : ""),
1074
+ fact("Serial", record.robotSn),
1075
+ fact("Last seen", agoText(live?.lastSeenAt ?? record.lastSeenAt, input.now)),
1076
+ ];
1077
+ }
1078
+
1079
+ /**
1080
+ * Fold a live-stream event (`/robots/:id/track`) into the robot's state: a
1081
+ * pose moves it (and its plan point, when the stream carries one); anything
1082
+ * else leaves the polled state alone - the poll decides "Reconnecting".
1083
+ */
1084
+ export function mergePose(
1085
+ live: TLiveRobotState | null | undefined,
1086
+ event: { type?: unknown; pose?: { x?: unknown; y?: unknown; theta?: unknown; mode?: unknown } | null; planPosition?: unknown } | null | undefined,
1087
+ ): TLiveRobotState | null {
1088
+ if (!live || !live.ok || event?.type !== "pose" || !event.pose) return live ?? null;
1089
+ const { x, y, theta, mode } = event.pose;
1090
+ if (!finite(x) || !finite(y)) return live;
1091
+ const plan = event.planPosition as { x?: unknown; y?: unknown } | null | undefined;
1092
+ return {
1093
+ ...live,
1094
+ position: { x, y, theta: finite(theta) ? theta : live.position?.theta ?? 0 },
1095
+ ...(plan && finite(plan.x) && finite(plan.y) ? { planPosition: { x: plan.x, y: plan.y } } : {}),
1096
+ ...(typeof mode === "string" && mode ? { mode } : {}),
1097
+ } as TLiveRobotState;
1098
+ }
1099
+
1100
+ /**
1101
+ * Spot-clean points picked on the plan (0-100 shares) as the polygon the spot
1102
+ * command takes, in the robot's plan-image pixels. Three or more points are
1103
+ * the polygon itself; one or two become a small square around their centre
1104
+ * (a polygon needs three corners).
1105
+ */
1106
+ export function spotPixels(points: Array<{ x: number; y: number }>, size: { width: number; height: number }) {
1107
+ if (!points?.length || !(size?.width > 0) || !(size?.height > 0)) return [];
1108
+ const px = points.map((p) => ({
1109
+ x: Math.round((Math.min(100, Math.max(0, p.x)) / 100) * (size.width - 1)),
1110
+ y: Math.round((Math.min(100, Math.max(0, p.y)) / 100) * (size.height - 1)),
1111
+ }));
1112
+ if (px.length >= 3) return px;
1113
+ const cx = px.reduce((s, p) => s + p.x, 0) / px.length;
1114
+ const cy = px.reduce((s, p) => s + p.y, 0) / px.length;
1115
+ return spotPolygon(cx, cy, size);
1116
+ }