cursedbelt 6.32.0 → 6.35.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.
Files changed (46) hide show
  1. package/dist/react/components/DataTable/useTableViewMode.d.ts +8 -8
  2. package/dist/react/components/DataTable/useTableViewMode.d.ts.map +1 -1
  3. package/dist/react/components/DataTable/useTableViewMode.js +8 -8
  4. package/dist/react/components/DataTable/useTableViewMode.js.map +1 -1
  5. package/dist/react/deep-link/index.d.ts +1 -1
  6. package/dist/react/deep-link/index.d.ts.map +1 -1
  7. package/dist/react/deep-link/index.js +1 -1
  8. package/dist/react/deep-link/index.js.map +1 -1
  9. package/dist/react/deep-link/links.d.ts +2 -3
  10. package/dist/react/deep-link/links.d.ts.map +1 -1
  11. package/dist/react/deep-link/links.js +4 -7
  12. package/dist/react/deep-link/links.js.map +1 -1
  13. package/dist/react/deep-link/resume.d.ts +17 -24
  14. package/dist/react/deep-link/resume.d.ts.map +1 -1
  15. package/dist/react/deep-link/resume.js +0 -127
  16. package/dist/react/deep-link/resume.js.map +1 -1
  17. package/dist/react/deep-link/useDeepLink.d.ts +4 -3
  18. package/dist/react/deep-link/useDeepLink.d.ts.map +1 -1
  19. package/dist/react/deep-link/useDeepLink.js +1 -1
  20. package/dist/react/deep-link/useDeepLink.js.map +1 -1
  21. package/dist/react/map-frame/MapFrame.d.ts +58 -8
  22. package/dist/react/map-frame/MapFrame.d.ts.map +1 -1
  23. package/dist/react/map-frame/MapFrame.js +132 -20
  24. package/dist/react/map-frame/MapFrame.js.map +1 -1
  25. package/dist/react/map-frame/geo.d.ts +66 -1
  26. package/dist/react/map-frame/geo.d.ts.map +1 -1
  27. package/dist/react/map-frame/geo.js +99 -1
  28. package/dist/react/map-frame/geo.js.map +1 -1
  29. package/dist/react/map-frame/index.d.ts +3 -3
  30. package/dist/react/map-frame/index.d.ts.map +1 -1
  31. package/dist/react/map-frame/index.js +2 -2
  32. package/dist/react/map-frame/index.js.map +1 -1
  33. package/package.json +2 -2
  34. package/src/react/components/DataTable/useTableViewMode.ts +9 -10
  35. package/src/react/deep-link/index.ts +0 -4
  36. package/src/react/deep-link/links.ts +5 -8
  37. package/src/react/deep-link/resume.spec.tsx +9 -215
  38. package/src/react/deep-link/resume.ts +13 -154
  39. package/src/react/deep-link/useDeepLink.tsx +5 -4
  40. package/src/react/map-frame/MapFrame.box.spec.tsx +73 -0
  41. package/src/react/map-frame/MapFrame.cover.spec.tsx +67 -0
  42. package/src/react/map-frame/MapFrame.tsx +168 -31
  43. package/src/react/map-frame/clusterFold.spec.ts +54 -0
  44. package/src/react/map-frame/fit.spec.ts +116 -0
  45. package/src/react/map-frame/geo.ts +132 -0
  46. package/src/react/map-frame/index.ts +12 -3
@@ -121,6 +121,7 @@
121
121
  import React from "react";
122
122
  import { CanvasZoomHint } from "../canvas-hud/HudControls.js";
123
123
  import { readWheel } from "../canvas-hud/useCanvasWheel.js";
124
+ import { useResizeObserver } from "../hooks/useResizeObserver.js";
124
125
  import {
125
126
  type LatLng,
126
127
  MAX_ZOOM,
@@ -129,6 +130,8 @@ import {
129
130
  scaleBar,
130
131
  snapZoom,
131
132
  unproject,
133
+ VIEW_HEIGHT,
134
+ VIEW_WIDTH,
132
135
  type Viewport,
133
136
  zoomAnchoredAt,
134
137
  } from "./geo.js";
@@ -140,8 +143,7 @@ import {
140
143
  * a fixed size is what keeps the cache key space tiny — see `/api/map`. The frame
141
144
  * is then CSS-scaled to whatever the layout gives it.
142
145
  */
143
- export const VIEW_WIDTH = 640;
144
- export const VIEW_HEIGHT = 400;
146
+ export { VIEW_HEIGHT, VIEW_WIDTH } from "./geo.js";
145
147
 
146
148
  /**
147
149
  * 🔴 How far the pointer must travel before this becomes a pan.
@@ -178,6 +180,9 @@ const ZOOM_PER_WHEEL_PIXEL = 1 / 380;
178
180
  * a gate that stops guarding the thing it was written for. */
179
181
  export const WHEEL_SETTLE_MS = 220;
180
182
 
183
+ /** How long a resized box must hold its size before the frame asks for a picture of its new shape. */
184
+ const BOX_REST_MS = 250;
185
+
181
186
  /**
182
187
  * Momentum: how fast a flick decays, as the time constant of an exponential.
183
188
  *
@@ -199,14 +204,89 @@ interface SettledImage {
199
204
  src: string;
200
205
  center: LatLng;
201
206
  zoom: number;
207
+ /** The viewport units the picture covers at `zoom`, centered on `center` — see {@link mapRender}. */
208
+ cover: { width: number; height: number };
209
+ }
210
+
211
+ /** The ground a render must cover, in viewport units: the whole 640×400 unless the frame knows its box. */
212
+ export type MapCover = { width: number; height: number };
213
+ const WHOLE_VIEW: MapCover = { width: VIEW_WIDTH, height: VIEW_HEIGHT };
214
+ /** Google refuses a render past 640 a side (before `scale`), and `/api/map` clamps under 120×80. */
215
+ const RENDER_MAX = 640;
216
+ const RENDER_MIN = { width: 120, height: 80 };
217
+
218
+ /**
219
+ * 🔴 How tall Google's own foot is in a render, in the render's logical pixels: the logo at its
220
+ * bottom-left and the "Map data ©" line at its bottom-right. Google's terms say neither may be
221
+ * obscured (forge task 5916: the zoom keys sat on the line on every phone), so the frame's distance key
222
+ * sits above it and {@link attributionFoot} tells a consumer how far to lift its own controls.
223
+ */
224
+ export const ATTRIBUTION_FOOT = 24;
225
+
226
+ /**
227
+ * Pure: the one picture that draws `cover` (viewport units, centered on the view) at `zoom` — which of
228
+ * Google's levels, and how many pixels wide and tall.
229
+ *
230
+ * 🔴 It covers what the box SHOWS, not the whole 640×400 (forge task 5916). The SVG slices the viewport
231
+ * into its box, so a phone's 4:5 box shows only the middle 320 units: a whole-viewport render paid for
232
+ * pixels nobody saw, and cropped Google's logo and attribution — which sit in the render's corners —
233
+ * clean off. A render of the visible area puts both in the box's own corners.
234
+ *
235
+ * And because a narrow cover is small, a zoom past the middle of a step is drawn from the level ABOVE,
236
+ * shrunk (up to 1/√2), instead of the level below stretched (up to 2×) — crisp, still one render, while
237
+ * it fits under Google's 640. Rounded to the NEARER level, never always up: a level above shown at half
238
+ * size halves Google's labels too. A whole zoom with the whole viewport is the 640×400 it always was.
239
+ */
240
+ export function mapRender(zoom: number, cover: MapCover = WHOLE_VIEW): { level: number; width: number; height: number; cover: MapCover } {
241
+ const below = Math.floor(zoom + 1e-9);
242
+ const fits = (level: number) => cover.width * 2 ** (level - zoom) <= RENDER_MAX + 1e-6 && cover.height * 2 ** (level - zoom) <= RENDER_MAX + 1e-6;
243
+ const level = zoom - below >= 0.5 - 1e-9 && below + 1 <= MAX_ZOOM && fits(below + 1) ? below + 1 : below;
244
+ const factor = 2 ** (level - zoom);
245
+ // A sliver of a box still gets a picture `/api/map` will draw at its own shape: grow it, centered.
246
+ const grow = Math.max(1, RENDER_MIN.width / (cover.width * factor), RENDER_MIN.height / (cover.height * factor));
247
+ const width = Math.min(RENDER_MAX, Math.round(cover.width * factor * grow));
248
+ const height = Math.min(RENDER_MAX, Math.round(cover.height * factor * grow));
249
+ return { level, width, height, cover: { width: width / factor, height: height / factor } };
250
+ }
251
+
252
+ /**
253
+ * Pure: how many CSS pixels at the foot of a frame `box` wide and tall Google's logo and attribution
254
+ * take at `zoom` — {@link ATTRIBUTION_FOOT} render pixels, as the frame stretches the render over the box.
255
+ * A control floated over the frame's bottom edge sits at least this high (forge task 5916). An
256
+ * unmeasured box (0×0) is read as the frame drawn at its logical size.
257
+ */
258
+ export function attributionFoot(box: { width: number; height: number }, zoom: number): number {
259
+ const area = visibleArea(box);
260
+ const render = mapRender(zoom, { width: Math.round(area.width), height: Math.round(area.height) });
261
+ return Math.ceil(ATTRIBUTION_FOOT * 2 ** (zoom - render.level) * cssPerUnit(box));
202
262
  }
203
263
 
204
- /** The URL of one rendered viewport. Pure, and exported so a test can name the
205
- * picture it expects without restating the query string. */
206
- export function mapImageSource(center: LatLng, zoom: number, theme: "light" | "dark"): string {
264
+ /**
265
+ * Pure: how many CSS pixels one viewport unit draws at in a `box` — the SVG slices the 640×400 over it.
266
+ * An unmeasured box (0×0) is read as the frame drawn at its logical size.
267
+ *
268
+ * 🔴 The frame's OWN marks (the distance key) are sized in CSS pixels through this, never in viewport
269
+ * units (forge task 5926): a desktop box draws a unit ~1.6–2 px, so a 12-unit label rendered ~23 px —
270
+ * larger than the page's headings. Google's picture is the one thing that stretches with the box: a
271
+ * single render is capped at 640 logical px a side (already at `scale=2`, so it is sharp on a retina
272
+ * screen), and only more renders per view could draw a wider box at Google's own label size.
273
+ */
274
+ function cssPerUnit(box: { width: number; height: number }): number {
275
+ return box.width > 0 && box.height > 0 ? Math.max(box.width / VIEW_WIDTH, box.height / VIEW_HEIGHT) : 1;
276
+ }
277
+
278
+ /**
279
+ * The URL of one rendered viewport. Pure, and exported so a test can name the picture it expects
280
+ * without restating the query string. {@link mapRender} chooses the level and the size: a zoom BETWEEN
281
+ * two of Google's levels (a `fitTight` view, forge task 5887) is a smaller picture the frame stretches
282
+ * (or shrinks) over the ground it covers, so the placement math stays true and the view still costs one
283
+ * render; a drag or a pinch, which commit whole levels, costs what it always did.
284
+ */
285
+ export function mapImageSource(center: LatLng, zoom: number, theme: "light" | "dark", cover: MapCover = WHOLE_VIEW): string {
286
+ const render = mapRender(zoom, cover);
207
287
  return (
208
288
  `/api/map?lat=${center.lat.toFixed(4)}&lng=${center.lng.toFixed(4)}` +
209
- `&z=${zoom}&w=${VIEW_WIDTH}&h=${VIEW_HEIGHT}&theme=${theme}`
289
+ `&z=${render.level}&w=${render.width}&h=${render.height}&theme=${theme}`
210
290
  );
211
291
  }
212
292
 
@@ -214,19 +294,20 @@ export function mapImageSource(center: LatLng, zoom: number, theme: "light" | "d
214
294
  * Where a already-rendered viewport sits inside the one being drawn now.
215
295
  *
216
296
  * Pure, and the whole reason a committed pan does not flash: it is the same
217
- * projection a pin gets, applied to a 640×400 picture. `scale` is the zoom
297
+ * projection a pin gets, applied to the picture — the ground it `cover`s (the whole 640×400 unless
298
+ * said), centered on its center. `scale` is the zoom
218
299
  * difference (a double-click leaves a half-size image covering the middle of the
219
300
  * frame until the closer render lands), and the position is the settled center
220
301
  * projected into the current view, minus half the scaled picture.
221
302
  */
222
303
  export function imagePlacement(
223
- settled: { center: LatLng; zoom: number },
304
+ settled: { center: LatLng; zoom: number; cover?: MapCover },
224
305
  view: Viewport,
225
306
  ): { x: number; y: number; width: number; height: number } {
226
307
  const scale = 2 ** (view.zoom - settled.zoom);
227
308
  const at = project(settled.center, view);
228
- const width = VIEW_WIDTH * scale;
229
- const height = VIEW_HEIGHT * scale;
309
+ const width = (settled.cover ?? WHOLE_VIEW).width * scale;
310
+ const height = (settled.cover ?? WHOLE_VIEW).height * scale;
230
311
  return { x: at.x - width / 2, y: at.y - height / 2, width, height };
231
312
  }
232
313
 
@@ -282,8 +363,10 @@ export interface MapFrameProps extends Omit<React.HTMLAttributes<HTMLDivElement>
282
363
  /** Announced to assistive technology. The map is decorative without one. */
283
364
  label: string;
284
365
  /** The URL of one rendered viewport. Defaults to {@link mapImageSource} — the app's own
285
- * `/api/map` proxy, which `cursedbelt-server/maps-static` serves the shared half of. */
286
- imageSource?: (center: LatLng, zoom: number, theme: "light" | "dark") => string;
366
+ * `/api/map` proxy, which `cursedbelt-server/maps-static` serves the shared half of. `cover` is
367
+ * the ground the picture must cover (the part of the viewport the frame's box shows), and the
368
+ * frame draws whatever comes back over exactly that; draw it with {@link mapRender}. */
369
+ imageSource?: (center: LatLng, zoom: number, theme: "light" | "dark", cover: MapCover) => string;
287
370
  /**
288
371
  * What a plain wheel means (DESIGN CNV-1, forge task 5761). `"fullscreen"` (the default) —
289
372
  * a map that IS the page, like family's atlas — zooms on every wheel. `"embedded"` — a map
@@ -354,9 +437,44 @@ export function MapFrame({
354
437
  height: VIEW_HEIGHT,
355
438
  };
356
439
 
440
+ /**
441
+ * The frame's own box, measured before the first paint — and null until then, because the render
442
+ * covers what the box shows (`mapRender`) and a fetch for the wrong shape is a render nobody sees
443
+ * and somebody pays for. A window dragged wider changes the box every frame; the picture follows
444
+ * once it has held still for {@link BOX_REST_MS}. jsdom measures 0×0, which is the whole viewport.
445
+ */
446
+ const rootRef = React.useRef<HTMLDivElement | null>(null);
447
+ const [box, setBox] = React.useState<{ width: number; height: number } | null>(null);
448
+ const boxRef = React.useRef(box);
449
+ const boxTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
450
+ useResizeObserver(
451
+ rootRef,
452
+ (element) => {
453
+ const next = { width: element.clientWidth, height: element.clientHeight };
454
+ const land = () => {
455
+ boxRef.current = next;
456
+ setBox(next);
457
+ };
458
+ if (boxTimer.current) clearTimeout(boxTimer.current);
459
+ const was = boxRef.current;
460
+ if (was === null) return land();
461
+ if (was.width === next.width && was.height === next.height) return;
462
+ boxTimer.current = setTimeout(land, BOX_REST_MS);
463
+ },
464
+ { layout: true },
465
+ );
466
+ React.useEffect(() => () => {
467
+ if (boxTimer.current) clearTimeout(boxTimer.current);
468
+ }, []);
469
+ const area = visibleArea(box ?? { width: 0, height: 0 });
470
+ const cover: MapCover = { width: Math.round(area.width), height: Math.round(area.height) };
471
+ /** The committed picture's level and the ground it covers — read by the distance key, and stored
472
+ * with the picture when it lands. */
473
+ const render = mapRender(zoom, cover);
474
+
357
475
  /** 🔴 Built from the PROPS, never from `effective`. The committed viewport is
358
476
  * the only one that is allowed to cost money. */
359
- const source = imageSource(center, zoom, theme);
477
+ const source = imageSource(center, zoom, theme, cover);
360
478
 
361
479
  /** The imagery on screen, which is the last one that LOADED — not the one the
362
480
  * props ask for. They differ only while a render is in flight. */
@@ -691,10 +809,10 @@ export function MapFrame({
691
809
  };
692
810
 
693
811
  const placement = settled ? imagePlacement(settled, view) : null;
694
- const loading = source !== settled?.src && !failed.has(source);
812
+ const loading = box !== null && source !== settled?.src && !failed.has(source);
695
813
 
696
814
  return (
697
- <div {...rest} className={className} style={style ? { ...FRAME_STYLE, ...style } : FRAME_STYLE} data-map-frame="" data-interactive={Boolean(onViewChange)}>
815
+ <div {...rest} ref={rootRef} className={className} style={style ? { ...FRAME_STYLE, ...style } : FRAME_STYLE} data-map-frame="" data-interactive={Boolean(onViewChange)}>
698
816
  {/*
699
817
  * The render currently being fetched, off-screen.
700
818
  *
@@ -713,7 +831,7 @@ export function MapFrame({
713
831
  style={PRELOAD_STYLE}
714
832
  draggable={false}
715
833
  data-testid="map-preload"
716
- onLoad={() => setSettled({ src: source, center, zoom })}
834
+ onLoad={() => setSettled({ src: source, center, zoom, cover: render.cover })}
717
835
  onError={() => setFailed((current) => new Set(current).add(source))}
718
836
  />
719
837
  ) : null}
@@ -912,7 +1030,7 @@ export function MapFrame({
912
1030
  )}
913
1031
  {children({ project: (point) => project(point, view), view })}
914
1032
  </g>
915
- <ScaleKey view={view} />
1033
+ <ScaleKey view={view} area={area} perUnit={cssPerUnit(box ?? { width: 0, height: 0 })} foot={ATTRIBUTION_FOOT * 2 ** (view.zoom - (settled ? mapRender(settled.zoom, settled.cover).level : render.level))} />
916
1034
  </svg>
917
1035
  {wheel === "embedded" && onViewChange ? <CanvasZoomHint show={wheelHint} /> : null}
918
1036
  </div>
@@ -938,16 +1056,35 @@ export function MapFrame({
938
1056
  * child announced separately only clutters the tree — the rule the graticule
939
1057
  * comment already states.
940
1058
  */
941
- /** About how wide one character of the 12-unit label runs, so the plate holds a label longer than its bar. */
1059
+ /** About how wide one character of the 12-px label runs, so the plate holds a label longer than its bar. */
942
1060
  const LABEL_EM = 6.6;
1061
+ /** The longest bar, in CSS px — a caption's width, at every box. */
1062
+ const BAR_MAX_PX = 110;
943
1063
 
944
- function ScaleKey({ view }: { view: Viewport }) {
945
- const bar = scaleBar(view);
1064
+ /**
1065
+ * 🔴 In the corner the box SHOWS (`area`), above Google's own foot (`foot`, viewport units): at x=12 of
1066
+ * the whole viewport it was cropped away on every phone, and at its foot it would sit on Google's logo
1067
+ * (forge task 5916). Every length but the bar's is in CSS px (`perUnit`, forge task 5926): the key is a
1068
+ * caption, the same 12 px on a phone and on a desktop box that draws a unit twice as large.
1069
+ */
1070
+ function ScaleKey({
1071
+ view,
1072
+ area,
1073
+ foot,
1074
+ perUnit,
1075
+ }: {
1076
+ view: Viewport;
1077
+ area: { x: number; y: number; width: number; height: number };
1078
+ foot: number;
1079
+ perUnit: number;
1080
+ }) {
1081
+ const px = (css: number) => css / perUnit;
1082
+ const bar = scaleBar(view, px(BAR_MAX_PX));
946
1083
  // A frame too small (or a zoom too far out) for even the smallest step of the
947
1084
  // 1/2/5 series draws nothing rather than a bar labeled with a fraction.
948
1085
  if (bar.widthUnits <= 0) return null;
949
- const left = 12;
950
- const bottom = VIEW_HEIGHT - 12;
1086
+ const left = area.x + px(12);
1087
+ const bottom = area.y + area.height - px(8) - foot;
951
1088
  return (
952
1089
  /*
953
1090
  * 🔴 No `aria-hidden`, and the graticule's comment beside it says why: the
@@ -960,24 +1097,24 @@ function ScaleKey({ view }: { view: Viewport }) {
960
1097
  {/* A dark plate under the mark, because the imagery underneath is a
961
1098
  photograph and a hairline over a bright field is unreadable. */}
962
1099
  <rect
963
- x={left - 5}
964
- y={bottom - 22}
965
- width={Math.max(bar.widthUnits, bar.label.length * LABEL_EM) + 10}
966
- height={28}
967
- rx={4}
1100
+ x={left - px(5)}
1101
+ y={bottom - px(22)}
1102
+ width={Math.max(bar.widthUnits, px(bar.label.length * LABEL_EM)) + px(10)}
1103
+ height={px(28)}
1104
+ rx={px(4)}
968
1105
  fill="var(--card)"
969
1106
  opacity={0.78}
970
1107
  />
971
1108
  <path
972
- d={`M${left} ${bottom - 5} v5 h${bar.widthUnits} v-5`}
1109
+ d={`M${left} ${bottom - px(5)} v${px(5)} h${bar.widthUnits} v${-px(5)}`}
973
1110
  fill="none"
974
1111
  stroke="var(--foreground)"
975
- strokeWidth={1.5}
1112
+ strokeWidth={px(1.5)}
976
1113
  />
977
1114
  <text
978
1115
  x={left}
979
- y={bottom - 8}
980
- fontSize={12}
1116
+ y={bottom - px(8)}
1117
+ fontSize={px(12)}
981
1118
  fill="var(--foreground)"
982
1119
  >
983
1120
  {bar.label}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * clusterByScreen's drawn-radius fold (forge tasks 5888 → 5912, moved with the code from photos' Places
3
+ * map test): no two returned tokens' discs touch. It reaches the fold only through clusterByScreen,
4
+ * which existed before the fold did, so a run without the fix fails here rather than on an import.
5
+ */
6
+ import { describe, expect, it } from "bun:test";
7
+ import { clusterByScreen, type LatLng, project, unproject } from "./geo.js";
8
+
9
+ describe("clusterByScreen with a drawn radius — no token is drawn over another (forge tasks 5888, 5912)", () => {
10
+ const view = { center: { lat: 50, lng: 5 }, zoom: 5, width: 640, height: 400 };
11
+ const at = (x: number, y: number): LatLng => unproject({ x, y }, view);
12
+ const pin = (id: string, x: number, y: number, weight: number) => ({ id, point: at(x, y), weight });
13
+ /** Photos' token: it grows with what it holds, within reach of a thumb at both ends. */
14
+ const tokenRadius = (weight: number): number => Math.min(16, 7 + Math.log2(1 + weight));
15
+ const tokens = (pins: ReturnType<typeof pin>[]) =>
16
+ clusterByScreen(pins, view, 22, { drawnRadius: tokenRadius }).map((c) => ({ ...c, ...project(c.point, view), r: tokenRadius(c.weight) }));
17
+ const touching = (list: ReturnType<typeof tokens>) =>
18
+ list.some((a, i) => list.slice(i + 1).some((b) => Math.hypot(a.x - b.x, a.y - b.y) < a.r + b.r + 2));
19
+
20
+ it("🔴 two heavy pins 24 units apart — past the fixed radius, discs that would touch — are one token holding both", () => {
21
+ const list = tokens([pin("london", 300, 200, 1600), pin("oxford", 324, 200, 174)]);
22
+ expect(list.map((t) => [t.id, t.weight, t.members.length])).toEqual([["london", 1774, 2]]);
23
+ // The heavier place keeps the seat: the token sits by London, not halfway to Oxford.
24
+ expect(list[0]?.x ?? 0).toBeLessThan(312);
25
+ });
26
+
27
+ it("without a drawn radius the fixed distance is the whole rule, as it always was", () => {
28
+ expect(clusterByScreen([pin("london", 300, 200, 1600), pin("oxford", 324, 200, 174)], view, 22).length).toBe(2);
29
+ });
30
+
31
+ it("two light pins 24 units apart have room, and stay two", () => {
32
+ const list = tokens([pin("a", 300, 200, 1), pin("b", 324, 200, 1)]);
33
+ expect(list.map((t) => t.id).sort()).toEqual(["a", "b"]);
34
+ expect(tokenRadius(1) * 2 + 2).toBeLessThan(24);
35
+ });
36
+
37
+ it("a row of heavy places ends with no two discs touching, nothing lost from the counts, heaviest first", () => {
38
+ const list = tokens([pin("rome", 300, 200, 259), pin("naples", 330, 200, 176), pin("bari", 362, 200, 120), pin("far", 500, 200, 300)]);
39
+ expect(touching(list)).toBe(false);
40
+ expect(list.reduce((n, t) => n + t.weight, 0)).toBe(855);
41
+ expect(list.map((t) => t.weight)).toEqual([...list.map((t) => t.weight)].sort((a, b) => b - a));
42
+ });
43
+
44
+ it("🔴 a radius with no ceiling — family's, which grows with a cluster's total — still ends with no two discs touching", () => {
45
+ const heaviest = 40;
46
+ const atlasRadius = (weight: number) => 6.5 + Math.sqrt(weight / heaviest) * 4.5;
47
+ const pins = [pin("a", 300, 200, 40), pin("b", 318, 200, 37), pin("c", 328, 200, 11), pin("d", 340, 214, 5)];
48
+ // Past the fixed radius the pairs are two clusters, and their discs touch: the fold is what parts them.
49
+ expect(touching(clusterByScreen(pins, view, 22).map((c) => ({ ...c, ...project(c.point, view), r: atlasRadius(c.weight) })))).toBe(true);
50
+ const list = clusterByScreen(pins, view, 22, { drawnRadius: atlasRadius }).map((c) => ({ ...c, ...project(c.point, view), r: atlasRadius(c.weight) }));
51
+ expect(touching(list)).toBe(false);
52
+ expect(list.reduce((n, t) => n + t.weight, 0)).toBe(93);
53
+ });
54
+ });
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The tight fit and the picture between two levels — moved with the code from
3
+ * photos' Places map test (apps/photos, now gone from it) (forge tasks 5879, 5888 → 5887, 5912), so every map that fits through
4
+ * the frame is held to them. The token fold's tests are clusterFold.spec.ts.
5
+ */
6
+ import { describe, expect, it } from "bun:test";
7
+ import { FIT_INSET, fitTight, type LatLng, project, snapTight, stepZoom, unproject, VIEW_HEIGHT, VIEW_WIDTH } from "./geo.js";
8
+ import { mapImageSource, visibleArea } from "./MapFrame.js";
9
+
10
+ /** Where each point lands in the frame's 640×400 at a view. */
11
+ const landed = (points: readonly LatLng[], view: { center: LatLng; zoom: number }) => points.map((point) => project(point, { ...view, width: VIEW_WIDTH, height: VIEW_HEIGHT }));
12
+
13
+ /** Every point inside the clear part of the box, and the pins reaching an edge of it on one axis within `slack` units. */
14
+ function expectTight(points: readonly LatLng[], box: { width: number; height: number }, slack: number): void {
15
+ const area = visibleArea(box);
16
+ const at = landed(points, fitTight(points, area));
17
+ const clear = { left: area.x + FIT_INSET.side, right: area.x + area.width - FIT_INSET.side, top: area.y + FIT_INSET.top, bottom: area.y + area.height - FIT_INSET.bottom };
18
+ const xs = at.map((p) => p.x);
19
+ const ys = at.map((p) => p.y);
20
+ expect(Math.min(...xs)).toBeGreaterThanOrEqual(clear.left - 1e-6);
21
+ expect(Math.max(...xs)).toBeLessThanOrEqual(clear.right + 1e-6);
22
+ expect(Math.min(...ys)).toBeGreaterThanOrEqual(clear.top - 1e-6);
23
+ expect(Math.max(...ys)).toBeLessThanOrEqual(clear.bottom + 1e-6);
24
+ const spare = Math.min(Math.min(...xs) - clear.left + (clear.right - Math.max(...xs)), Math.min(...ys) - clear.top + (clear.bottom - Math.max(...ys)));
25
+ expect(spare).toBeLessThan(slack);
26
+ }
27
+
28
+ describe("fitTight — the closest view that still holds every pin", () => {
29
+ // The owner's archive, about: the Pacific coast to the Nile, the Caribbean to Iceland.
30
+ const archive = [
31
+ { lat: 37.77, lng: -122.42 },
32
+ { lat: 13.19, lng: -59.54 },
33
+ { lat: 64.15, lng: -21.94 },
34
+ { lat: 30.01, lng: 31.21 },
35
+ { lat: 51.51, lng: -0.05 },
36
+ ];
37
+ const desk = { width: 1136, height: 710 };
38
+ const phone = { width: 358, height: 448 };
39
+
40
+ it("🔴 the whole archive is in view with no room to spare — on a desk's 16:10 and on a phone's 4:5", () => {
41
+ // A step of the picture's width is 16 of 640, so the spare room is under a twentieth of the clear box.
42
+ expectTight(archive, desk, 32);
43
+ expectTight(archive, phone, 32);
44
+ });
45
+
46
+ it("🔴 it is closer than the whole level a floored fit stops at — Asia and the south are cut away", () => {
47
+ const view = fitTight(archive, visibleArea(desk));
48
+ expect(view.zoom).toBeGreaterThan(2);
49
+ expect(view.zoom).toBeLessThan(3);
50
+ // The frame's left edge is the Pacific just off California, not the far side of the date line.
51
+ const west = unproject({ x: 0, y: VIEW_HEIGHT / 2 }, { ...view, width: VIEW_WIDTH, height: VIEW_HEIGHT });
52
+ expect(west.lng).toBeGreaterThan(-140);
53
+ });
54
+
55
+ it("Iceland stays in: the center is the middle on the map, not the middle of the latitudes", () => {
56
+ const tall = [
57
+ { lat: 13.19, lng: -59.54 },
58
+ { lat: 64.15, lng: -21.94 },
59
+ ];
60
+ expectTight(tall, desk, 32);
61
+ });
62
+
63
+ it("one street fits one section of a city, both on a step of the picture's width", () => {
64
+ const seattle = [
65
+ { lat: 47.66, lng: -122.4 },
66
+ { lat: 47.61, lng: -122.1 },
67
+ ];
68
+ expectTight(seattle, desk, 32);
69
+ expectTight(seattle, phone, 32);
70
+ expect(fitTight(seattle, visibleArea(phone)).zoom).toBeLessThan(fitTight(seattle, visibleArea(desk)).zoom);
71
+ });
72
+
73
+ it("one place is street level, never the frame's closest zoom", () => {
74
+ expect(fitTight([{ lat: 47.66, lng: -122.4 }], visibleArea(desk)).zoom).toBe(12);
75
+ });
76
+
77
+ it("nothing placed is the whole world", () => {
78
+ expect(fitTight([], visibleArea(phone))).toEqual({ center: { lat: 20, lng: 0 }, zoom: 1 });
79
+ });
80
+ });
81
+
82
+ describe("the picture behind a fit between two levels", () => {
83
+ const center = { lat: 40.123456, lng: -45.5 };
84
+
85
+ it("a whole level asks for the frame's 640×400 picture — a drag or a pinch costs what it always did", () => {
86
+ expect(mapImageSource(center, 3, "dark")).toBe("/api/map?lat=40.1235&lng=-45.5000&z=3&w=640&h=400&theme=dark");
87
+ });
88
+
89
+ it("🔴 between levels it is the level below, smaller by exactly the fraction — the ground the frame covers", () => {
90
+ for (const raw of [2.07, 2.31, 2.5, 2.77, 2.999, 9.4]) {
91
+ const zoom = snapTight(raw);
92
+ expect(zoom).toBeLessThanOrEqual(raw);
93
+ expect(raw - zoom).toBeLessThan(0.075);
94
+ const url = new URL(mapImageSource(center, zoom, "light"), "http://x");
95
+ const width = Number(url.searchParams.get("w"));
96
+ const height = Number(url.searchParams.get("h"));
97
+ expect(url.searchParams.get("z")).toBe(String(Math.floor(raw)));
98
+ expect(width % 16).toBe(0);
99
+ expect(height).toBe((width * 5) / 8);
100
+ expect(width).toBeGreaterThan(320);
101
+ // 640 frame units at the fraction are `width` picture pixels at the level below.
102
+ expect(VIEW_WIDTH / 2 ** (zoom - Math.floor(raw))).toBeCloseTo(width, 6);
103
+ expect(url.searchParams.get("lat")).toBe("40.1235");
104
+ }
105
+ });
106
+
107
+ it("a whole level stays itself, and the keys step onto whole levels from between them", () => {
108
+ expect(snapTight(4)).toBe(4);
109
+ expect(stepZoom(2.42, 1)).toBe(3);
110
+ expect(stepZoom(2.42, -1)).toBe(2);
111
+ expect(stepZoom(3, 1)).toBe(4);
112
+ expect(stepZoom(3, -1)).toBe(2);
113
+ expect(stepZoom(1, -1)).toBe(1);
114
+ expect(stepZoom(16, 1)).toBe(16);
115
+ });
116
+ });
@@ -205,6 +205,88 @@ export function zoomAnchoredAt(
205
205
  });
206
206
  }
207
207
 
208
+ // ─────────────────────────── fitting between two levels ─────────────────────────
209
+
210
+ /** The frame's fixed logical viewport, in units every overlay is drawn in. 640×400 because Google
211
+ * caps a single static render at 640px before `scale` — `MapFrame` re-exports these. */
212
+ export const VIEW_WIDTH = 640;
213
+ export const VIEW_HEIGHT = 400;
214
+
215
+ /** A between-levels picture's width moves in steps of this, so its height (5/8 of it) is whole too. */
216
+ export const TIGHT_STEP = 16;
217
+
218
+ /**
219
+ * The closest zoom at or under `zoom` whose picture is a whole step wide: level `n` plus
220
+ * `log2(640 / width)`, with the width on a step of {@link TIGHT_STEP} from 336 to 640 — 21 possible
221
+ * pictures a level, not one for every pixel a window is dragged through (`/api/map` bills each
222
+ * distinct view). Down, never up: a fit rounded up would push a pin off the edge.
223
+ */
224
+ export function snapTight(zoom: number): number {
225
+ const level = Math.floor(zoom);
226
+ const width = Math.min(VIEW_WIDTH, Math.ceil(VIEW_WIDTH / 2 ** (zoom - level) / TIGHT_STEP - 1e-9) * TIGHT_STEP);
227
+ return level + Math.log2(VIEW_WIDTH / width);
228
+ }
229
+
230
+ /** What a fit keeps clear around its points, in viewport units. */
231
+ export interface FitInset {
232
+ top: number;
233
+ side: number;
234
+ bottom: number;
235
+ }
236
+
237
+ /**
238
+ * The default {@link FitInset}: a token's radius and its ring at every edge, and at the foot the strip
239
+ * the frame's distance key and a HUD's zoom keys are drawn over — a place under a control is a place
240
+ * missing from the view. Both sit above Google's own foot (its logo and "Map data ©", 24 render px the
241
+ * frame's `ATTRIBUTION_FOOT` keeps clear — forge task 5916), so the foot inset carries it too.
242
+ */
243
+ export const FIT_INSET: FitInset = { top: 24, side: 24, bottom: 84 };
244
+
245
+ /**
246
+ * The closest viewport that holds every point inside `area` (the part of the frame its box shows —
247
+ * `visibleArea`) less `inset`, at a zoom BETWEEN Google's levels (forge task 5879, lifted in 5887).
248
+ * `zoomToFit` floors to a whole level, which can leave a spread a small island in a map twice as wide
249
+ * as it needs to be; this is {@link snapTight}ed instead, and `mapImageSource` draws it for one render.
250
+ *
251
+ * 🔴 The center is the middle of the points ON THE MAP (Mercator), not of their latitudes: from the
252
+ * Caribbean to Iceland those differ by a fifth of the frame, and a tight fit centered on the
253
+ * latitudes cuts Iceland off. And that middle lands on the middle of the CLEAR part of the area —
254
+ * above the frame's own middle when the foot inset is the larger — so one point sits above center.
255
+ */
256
+ export function fitTight(
257
+ points: readonly LatLng[],
258
+ area: { x: number; y: number; width: number; height: number },
259
+ options: { inset?: FitInset; maxZoom?: number; minZoom?: number; empty?: { center: LatLng; zoom: number } } = {},
260
+ ): { center: LatLng; zoom: number } {
261
+ const inset = options.inset ?? FIT_INSET;
262
+ const bounds = boundsOf([...points]);
263
+ if (!bounds) return options.empty ?? { center: { lat: 20, lng: 0 }, zoom: 1 };
264
+ const sw = worldFraction({ lat: bounds.south, lng: bounds.west });
265
+ const ne = worldFraction({ lat: bounds.north, lng: bounds.east });
266
+ const width = Math.max(32, area.width - inset.side * 2);
267
+ const height = Math.max(32, area.height - inset.top - inset.bottom);
268
+ const spanX = ne.x - sw.x;
269
+ const spanY = sw.y - ne.y;
270
+ const closest = Math.min(
271
+ spanX > 0 ? Math.log2(width / (TILE_SIZE * spanX)) : Number.POSITIVE_INFINITY,
272
+ spanY > 0 ? Math.log2(height / (TILE_SIZE * spanY)) : Number.POSITIVE_INFINITY,
273
+ );
274
+ const zoom = snapTight(clamp(closest, options.minZoom ?? MIN_ZOOM, options.maxZoom ?? 12));
275
+ const scale = TILE_SIZE * 2 ** zoom;
276
+ const clear = { x: area.x + inset.side + width / 2, y: area.y + inset.top + height / 2 };
277
+ return {
278
+ center: fromWorldFraction({
279
+ x: (sw.x + ne.x) / 2 - (clear.x - VIEW_WIDTH / 2) / scale,
280
+ y: (sw.y + ne.y) / 2 - (clear.y - VIEW_HEIGHT / 2) / scale,
281
+ }),
282
+ zoom,
283
+ };
284
+ }
285
+
286
+ /** One level in or out from wherever the view is — from a fit between two levels, onto the next whole one. */
287
+ export const stepZoom = (zoom: number, by: 1 | -1): number =>
288
+ clamp(by > 0 ? Math.floor(zoom + 1e-9) + 1 : Math.ceil(zoom - 1e-9) - 1, MIN_ZOOM, MAX_ZOOM);
289
+
208
290
  // ─────────────────────────── clustering the map's dots ──────────────────────────
209
291
 
210
292
  /** Anything the clusterer can place: an identity, a position and a magnitude. */
@@ -251,8 +333,25 @@ export function clusterByScreen<T extends Clusterable>(
251
333
  items: readonly T[],
252
334
  view: Viewport,
253
335
  radiusPx: number,
336
+ options: ClusterDrawing = {},
254
337
  ): Cluster<T>[] {
255
338
  if (items.length === 0) return [];
339
+ const clusters = clusterWithin(items, view, radiusPx);
340
+ return options.drawnRadius ? foldTouching(clusters, view, options.drawnRadius, options.gap ?? 2) : clusters;
341
+ }
342
+
343
+ /**
344
+ * How a caller draws its tokens, so {@link clusterByScreen} can promise no two of them touch.
345
+ * `drawnRadius` is a token's disc radius in viewport units for a cluster's TOTAL weight; `gap` is the
346
+ * clear space kept between two discs (a token's outline, half outside each disc — default 2).
347
+ */
348
+ export interface ClusterDrawing {
349
+ drawnRadius?: (weight: number) => number;
350
+ gap?: number;
351
+ }
352
+
353
+ /** The greedy pass: the heaviest unplaced item seeds a cluster of everything within `radiusPx` of it. */
354
+ function clusterWithin<T extends Clusterable>(items: readonly T[], view: Viewport, radiusPx: number): Cluster<T>[] {
256
355
  const placed = items.map((item) => ({ item, at: project(item.point, view) }));
257
356
  // Heaviest first, id as the tie-break: a stable order in, a stable answer out.
258
357
  placed.sort((a, b) => b.item.weight - a.item.weight || (a.item.id < b.item.id ? -1 : 1));
@@ -289,6 +388,39 @@ export function clusterByScreen<T extends Clusterable>(
289
388
  return clusters;
290
389
  }
291
390
 
391
+ /**
392
+ * 🔴 One fixed distance cannot be the whole rule (forge tasks 5888, 5912): a drawn token grows with its
393
+ * count, so two heavy clusters just past `radiusPx` drew discs over each other and hid a count — on
394
+ * photos' map and family's atlas alike. Raising the radius ends that too, but merges every light pin
395
+ * that had room. So any cluster whose DRAWN disc would touch a heavier one folds into it; folding
396
+ * repeats until nothing touches, because a fold grows the token and moves it to the weighted middle of
397
+ * what it now holds. The heavier keeps its id, the same rule the greedy pass keeps.
398
+ */
399
+ function foldTouching<T extends Clusterable>(start: Cluster<T>[], view: Viewport, drawnRadius: (weight: number) => number, gap: number): Cluster<T>[] {
400
+ type Placed = { cluster: Cluster<T>; x: number; y: number; r: number };
401
+ const place = (cluster: Cluster<T>): Placed => ({ cluster, ...project(cluster.point, view), r: drawnRadius(cluster.weight) });
402
+ let tokens = start.map(place);
403
+ for (let folded = true; folded; ) {
404
+ folded = false;
405
+ tokens.sort((a, b) => b.cluster.weight - a.cluster.weight || (a.cluster.id < b.cluster.id ? -1 : 1));
406
+ outer: for (let i = 0; i < tokens.length; i++) {
407
+ for (let j = i + 1; j < tokens.length; j++) {
408
+ const big = tokens[i] as Placed;
409
+ const small = tokens[j] as Placed;
410
+ const reach = big.r + small.r + gap;
411
+ if ((big.x - small.x) ** 2 + (big.y - small.y) ** 2 >= reach * reach) continue;
412
+ const members = [...big.cluster.members, ...small.cluster.members];
413
+ tokens = tokens.filter((t) => t !== big && t !== small);
414
+ tokens.push(place({ id: big.cluster.id, point: weightedCenter(members), members, weight: big.cluster.weight + small.cluster.weight }));
415
+ folded = true;
416
+ break outer;
417
+ }
418
+ }
419
+ }
420
+ tokens.sort((a, b) => b.cluster.weight - a.cluster.weight || (a.cluster.id < b.cluster.id ? -1 : 1));
421
+ return tokens.map((t) => t.cluster);
422
+ }
423
+
292
424
  /**
293
425
  * The weight-weighted center of some places.
294
426
  *