@skillre/dsh-plugin-sticky-wall 0.5.0 → 0.7.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.
package/lib/layout.js CHANGED
@@ -5,17 +5,17 @@
5
5
  * rotation and a width preset. Two operations produce those numbers:
6
6
  *
7
7
  * - {@link arrangeLayouts} is the Host-side "tidy" pass. It packs the wall into
8
- * a phyllotaxis (sunflower) disc **centred on the world origin**, so the wall
9
- * has a middle instead of a top-left corner: the Client opens looking at that
10
- * middle, and a tidied wall reads as one composition rather than a list that
11
- * happens to wrap. It is deterministic — the same notes always produce the
12
- * same wall — and it is collision-checked rather than estimated, so two cards
13
- * can never overlap even at the height cap.
8
+ * a compact cluster **centred on the world origin**, hugging the rectangle the
9
+ * centrepiece reserves: the Client opens looking at that middle, and a tidied
10
+ * wall reads as one composition rather than a list that happens to wrap. It is
11
+ * deterministic — the same notes always produce the same wall — and it is
12
+ * collision-checked rather than estimated, so two cards can never overlap even
13
+ * at the height cap.
14
14
  * - {@link previewLayout} is the Client-side fallback for a note that was never
15
15
  * placed (a wall written before the canvas existed, or a note created by the
16
- * agent tool). It is the same spiral without the collision check: O(1) per
17
- * note, index-stable, and centred, so the first render is already a scattered
18
- * wall around the middle instead of one tall stack.
16
+ * agent tool). It is a golden-angle spiral without the collision check: O(1)
17
+ * per note, index-stable, and centred, so the first render is already a
18
+ * scattered wall around the middle instead of one tall stack.
19
19
  *
20
20
  * Both halves import this module, so the geometry never drifts between the
21
21
  * value the Host persists and the value the Client previews.
@@ -25,30 +25,49 @@ import { CENTRE_RESERVE, LAYOUT_LIMITS, WIDTHS, WIDTH_PX, } from './types.js';
25
25
  const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
26
26
  /** Breathing room kept between two tidied cards, in world pixels. */
27
27
  const TIDY_GAP = 26;
28
- /** Hash-driven radial offset applied to a tidied card, in world pixels. */
29
- const TIDY_JITTER = 5;
30
28
  /** Maximum rotation the tidy pass adds, in degrees. */
31
29
  const TIDY_TILT = 3.4;
32
30
  /** Radial growth per derived (never-placed) note, in world pixels. */
33
31
  const PREVIEW_STEP = 196;
34
32
  /** Height assumed for a derived position, so the derived box looks centred. */
35
33
  const PREVIEW_NOMINAL_HEIGHT = 200;
34
+ /**
35
+ * Horizontal stretch applied to the derived spiral, matching the reference
36
+ * viewport's aspect. A derived wall is never tidied, so its shape is the only
37
+ * thing keeping it framable at a legible zoom.
38
+ */
39
+ const PREVIEW_SQUASH = 1.4;
36
40
  /** Clearance the free-spot search keeps between a new card and its neighbours. */
37
41
  const SPOT_GAP = 24;
38
42
  /** Candidate positions the free-spot search tries before falling back. */
39
43
  const MAX_SPOTS = 2048;
40
44
  /**
41
- * How strongly an outer ring prefers horizontal slots, in world pixels of
42
- * clearance. A wall reads better in a wide window when its outer cards sit left
43
- * and right, and this is small enough that a genuinely freer slot still wins.
45
+ * How far each successive contour grows past the reserved rectangle, in world
46
+ * pixels. A contour is only tried when every slot on the previous one is taken,
47
+ * so this is the radial grain of the packing: smaller packs tighter but costs
48
+ * more candidate tests.
44
49
  */
45
- const HORIZON_BIAS = 140;
50
+ const FRAME_STEP = 20;
51
+ /** Spacing between two candidate slots along one contour, in world pixels. */
52
+ const CONTOUR_STEP = 14;
53
+ /** Contours walked outward before a card gives up and takes the safety spot. */
54
+ const MAX_FRAMES = 1024;
55
+ /** Upper bound on slots tested per contour, so a huge wall stays bounded. */
56
+ const MAX_SLOTS = 320;
57
+ /**
58
+ * The framing the tidy pass packs FOR: the usable canvas of a typical window, in
59
+ * world pixels at zoom 1. A candidate slot is scored by how much this rectangle
60
+ * would have to zoom out to hold the wall, which is the number the user actually
61
+ * feels. The exact window is unknown to the Host, so this is a shape, not a size.
62
+ */
63
+ const FRAMING_WIDTH = 1064;
64
+ const FRAMING_HEIGHT = 664;
65
+ /** The reference viewport's own aspect; the contour is grown to match it. */
66
+ const FRAMING_ASPECT = 1.5;
46
67
  /** Maximum rotation the preview fallback adds, in degrees. */
47
68
  const PREVIEW_TILT = 4;
48
69
  /** Spatial-grid cell; wider than the biggest rotated card plus the gap. */
49
70
  const GRID_CELL = 430;
50
- /** Candidate spiral positions tried per card before the safety fallback. */
51
- const MAX_CANDIDATES = 4096;
52
71
  /** Deterministic 32-bit FNV-1a hash; no crypto, identical on both halves. */
53
72
  function hash(text) {
54
73
  let value = 0x811c9dc5;
@@ -170,10 +189,14 @@ export function layoutOf(note, index) {
170
189
  /**
171
190
  * Derived position for a note the user never placed.
172
191
  *
173
- * Index-based so two never-placed notes cannot collide, golden-angle spiralled
174
- * so the result reads as a wall scattered around the middle rather than a grid.
175
- * The height used for centring is a nominal constant, not the real estimate:
176
- * a derived position must not move when the user edits the note's text.
192
+ * Index-based so two never-placed notes cannot collide, and laid out on a
193
+ * SQUASHED spiral — the same golden-angle walk with its radius stretched along
194
+ * the x axis — so the result reads as a wide cluster around the middle rather
195
+ * than a circle or a grid. The squash matters: a circle leaves the left and
196
+ * right of a wide window empty and the camera then has to zoom out to frame the
197
+ * empty corners, which is the same "everything looks small" failure the tidy
198
+ * pass fixes. The height used for centring is a nominal constant, not the real
199
+ * estimate: a derived position must not move when the user edits the text.
177
200
  */
178
201
  export function previewLayout(note, index) {
179
202
  const width = previewWidth(note.id);
@@ -191,7 +214,7 @@ export function previewLayout(note, index) {
191
214
  const radius = PREVIEW_STEP * Math.sqrt(Math.max(0, index) + (startRadius / PREVIEW_STEP) ** 2);
192
215
  const theta = index * GOLDEN_ANGLE + (unit(`${note.id}:pa`) - 0.5) * 0.55;
193
216
  return clampLayout({
194
- x: Math.cos(theta) * radius - WIDTH_PX[width] / 2,
217
+ x: Math.cos(theta) * radius * PREVIEW_SQUASH - WIDTH_PX[width] / 2,
195
218
  y: Math.sin(theta) * radius - PREVIEW_NOMINAL_HEIGHT / 2,
196
219
  rotate: (unit(`${note.id}:pr`) - 0.5) * 2 * PREVIEW_TILT,
197
220
  width,
@@ -222,8 +245,7 @@ export function rotatedExtent(width, height, rotate) {
222
245
  * cards in from the sides.
223
246
  */
224
247
  export function intersectsReserve(box, reserve = CENTRE_RESERVE) {
225
- const clear = clearsReserve(box, reserve);
226
- return !clear;
248
+ return !clearsReserve(box, normalizeReserve(reserve));
227
249
  }
228
250
  /**
229
251
  * Tolerance for the reserve test, in world pixels.
@@ -235,11 +257,20 @@ export function intersectsReserve(box, reserve = CENTRE_RESERVE) {
235
257
  * far below anything visible and well above the rounding error.
236
258
  */
237
259
  const RESERVE_EPSILON = 0.05;
260
+ /**
261
+ * Whether a footprint stays out of the clear rectangle.
262
+ *
263
+ * The rectangle has a POSITION as well as a size. The centrepiece is a
264
+ * screen-space overlay, so the world patch it covers moves as the camera pans
265
+ * and zooms; a reserve that only knew its half-extents therefore described the
266
+ * world origin, and a card captured from a panned wall was placed clear of the
267
+ * wrong place — which is exactly how a fresh card ended up behind the field.
268
+ */
238
269
  function clearsReserve(box, reserve) {
239
- return !(box.x < reserve.halfWidth - RESERVE_EPSILON &&
240
- box.x + box.width > -reserve.halfWidth + RESERVE_EPSILON &&
241
- box.y < reserve.halfHeight - RESERVE_EPSILON &&
242
- box.y + box.height > -reserve.halfHeight + RESERVE_EPSILON);
270
+ return !(box.x < reserve.x + reserve.halfWidth - RESERVE_EPSILON &&
271
+ box.x + box.width > reserve.x - reserve.halfWidth + RESERVE_EPSILON &&
272
+ box.y < reserve.y + reserve.halfHeight - RESERVE_EPSILON &&
273
+ box.y + box.height > reserve.y - reserve.halfHeight + RESERVE_EPSILON);
243
274
  }
244
275
  /** Cell coordinate of one world value. */
245
276
  function cellOf(value) {
@@ -290,6 +321,51 @@ function nearestGap(box, grid) {
290
321
  }
291
322
  return nearest;
292
323
  }
324
+ /**
325
+ * The point at arc length `distance` around a rectangle's outline, with the
326
+ * outward normal there.
327
+ *
328
+ * This is the contour the tidy pass walks. Unlike a circle, a rectangle's
329
+ * outline stays a card's own half-size away from the reserve in every direction,
330
+ * which is what keeps the innermost cards as close to the middle as their size
331
+ * allows instead of at the rectangle's corner distance all the way round.
332
+ *
333
+ * `halfWidth`/`halfHeight` are the contour's own half-extents, so a contour is
334
+ * just "the reserve grown by one frame".
335
+ */
336
+ function contourPoint(halfWidth, halfHeight, distance) {
337
+ const width = halfWidth * 2;
338
+ const height = halfHeight * 2;
339
+ const perimeter = 2 * (width + height);
340
+ let along = ((distance % perimeter) + perimeter) % perimeter;
341
+ // Clockwise from the top-left corner: top edge, right edge, bottom, left.
342
+ if (along < width)
343
+ return { x: -halfWidth + along, y: -halfHeight, nx: 0, ny: -1 };
344
+ along -= width;
345
+ if (along < height)
346
+ return { x: halfWidth, y: -halfHeight + along, nx: 1, ny: 0 };
347
+ along -= height;
348
+ if (along < width)
349
+ return { x: halfWidth - along, y: halfHeight, nx: 0, ny: 1 };
350
+ along -= width;
351
+ return { x: -halfWidth, y: halfHeight - along, nx: -1, ny: 0 };
352
+ }
353
+ /**
354
+ * The footprint of a card whose nearest edge sits on a contour point.
355
+ *
356
+ * The reach is half the card's extent MEASURED ALONG THE NORMAL, not half its
357
+ * width: on the top and bottom edges a tilted card reaches out by half its
358
+ * height, and charging it half its width there would let it clip the reserve.
359
+ */
360
+ function boxOnContour(point, extent) {
361
+ const reach = (Math.abs(point.nx) * extent.width + Math.abs(point.ny) * extent.height) / 2;
362
+ return {
363
+ x: point.x + point.nx * reach - extent.width / 2,
364
+ y: point.y + point.ny * reach - extent.height / 2,
365
+ width: extent.width,
366
+ height: extent.height,
367
+ };
368
+ }
293
369
  /** Register one accepted footprint in every cell it touches. */
294
370
  function remember(box, grid) {
295
371
  for (let cellX = cellOf(box.x); cellX <= cellOf(box.x + box.width); cellX += 1) {
@@ -306,25 +382,45 @@ function remember(box, grid) {
306
382
  /**
307
383
  * Deterministic tidy arrangement for the whole wall.
308
384
  *
309
- * The wall is packed into CONCENTRIC RINGS around the world origin, outside the
310
- * rectangle the centrepiece reserves. This replaced a phyllotaxis first-fit
311
- * spiral, and the reason is measurable rather than aesthetic: a sunflower spiral
312
- * has to keep every candidate clear of a card's full bounding circle, so it
313
- * saturates at roughly a quarter of the available area and the only way to place
314
- * the next card is to walk further out. A fourteen-card wall therefore spread
315
- * over ~2700px of paper while its cards covered ~430,000px² — a sparse scatter,
316
- * not a wall. Ring packing instead computes how many cards fit on each circle
317
- * (`2πR / pitch`) and fills that circle evenly, so the same fourteen cards fit
318
- * within ~1200px and the result reads as a ring around the middle.
385
+ * The wall is packed against a CONTOUR: the reserved rectangle's own outline,
386
+ * walked outward frame by frame. This is the third packer in this file's
387
+ * history and each replacement fixed a measured failure rather than a taste.
319
388
  *
320
- * Cards are sorted largest-first within the ring they land on, which is the
321
- * classic first-fit-decreasing heuristic: big cards claim the inner ring where
322
- * there is less room to waste, and small cards take up the slack outside.
389
+ * 1. A phyllotaxis first-fit spiral had to keep every candidate clear of a
390
+ * card's full bounding circle, so it saturated at roughly a quarter of the
391
+ * available area and the only way to place the next card was to walk further
392
+ * out: fourteen cards spread over ~2700px of paper.
393
+ * 2. Concentric RINGS fixed that density but paid for it with distance. A ring
394
+ * is a circle, and the first ring's radius is the reserve's half-DIAGONAL —
395
+ * so the innermost cards sit at the rectangle's corner distance in every
396
+ * direction, including the four directions where the rectangle is only a
397
+ * card's width away. A fourteen-card wall then filled a 1645x1794 box, which
398
+ * the camera could only frame at 36%: the cards were individually packed
399
+ * tightly but the wall as a whole looked small and far away. That is the
400
+ * complaint this packer answers.
401
+ * 3. A contour hugs the rectangle instead: along the left and right edges a card
402
+ * sits one card-half-width from the reserve, and along the top and bottom one
403
+ * card-half-height from it. Every card is therefore as close to the middle as
404
+ * its own size allows, which is what makes the wall read as one composition.
405
+ *
406
+ * Two further decisions do the rest of the work:
407
+ *
408
+ * - **Score by how well the wall FRAMES, not by how free the slot is.** A
409
+ * candidate slot is judged by the zoom the whole wall would need in a
410
+ * reference viewport if the card went there. Filling a slot that widens the
411
+ * wall's box costs zoom, so the packer prefers slots that keep the box close
412
+ * to the window's own aspect — which is why the result is a wide, low cluster
413
+ * instead of a disc that leaves the left and right of the window empty.
414
+ * - **The first frame with room wins.** Walking outward frame by frame and
415
+ * taking the best-scoring slot on the first frame that has any is what makes
416
+ * every card land near the middle: an outer frame is only reached when the
417
+ * inner ones are genuinely full.
323
418
  *
324
419
  * A collision check still runs on every candidate rather than trusting the
325
420
  * height estimate, because the estimate is a line count and a code block's
326
- * padding is not something a line count can see. If a candidate does not fit the
327
- * check pushes to the next ring — the packer never produces an overlap.
421
+ * padding is not something a line count can see. The packer never produces an
422
+ * overlap, and the final centring passes repair any card the centring shift
423
+ * nudged into the reserved rectangle.
328
424
  *
329
425
  * Returns a map from note id to its new layout, for every note that needs to
330
426
  * move. Notes already at exactly that layout are omitted by the caller, so
@@ -334,8 +430,8 @@ export function arrangeLayouts(notes, options = {}) {
334
430
  const placed = new Map();
335
431
  if (notes.length === 0)
336
432
  return placed;
337
- // Decide each card's rotation and footprint up front: the ring pitch and the
338
- // collision test both work on the rotated box.
433
+ // Decide each card's rotation and footprint up front: the contour offsets and
434
+ // the collision test both work on the rotated box.
339
435
  const items = notes.map((note) => {
340
436
  const width = note.layout?.width ?? previewWidth(note.id);
341
437
  const cardWidth = WIDTH_PX[width];
@@ -344,14 +440,24 @@ export function arrangeLayouts(notes, options = {}) {
344
440
  const extent = rotatedExtent(cardWidth, cardHeight, rotate);
345
441
  return { note, width, cardWidth, cardHeight, rotate, extent };
346
442
  });
347
- const reserve = normalizeReserve(options.centreReserve ?? CENTRE_RESERVE);
348
- // The first ring's radius is the distance from the origin to the reserve's
349
- // corner plus the largest card's half-diagonal: the smallest circle that can
350
- // hold a card clear of the whole rectangle.
351
- const reserveCorner = Math.hypot(reserve.halfWidth, reserve.halfHeight);
352
- const largestHalfDiagonal = Math.max(...items.map((item) => Math.hypot(item.extent.width, item.extent.height) / 2));
353
- // Largest first: see the first-fit-decreasing note above. Ties break on id so
354
- // the result stays deterministic across two windows.
443
+ // The contour is anchored on the ORIGIN, deliberately, even when the caller
444
+ // sends a positioned reserve.
445
+ //
446
+ // Tidy ends by centring the finished wall's bounding box on the origin, and the
447
+ // Client then refits the camera so that box fills the viewport — which puts the
448
+ // centrepiece back over the origin. So the origin is where the field is going to
449
+ // be, not where it happens to be at the instant tidy was pressed. Honouring a
450
+ // transient camera position here would pack the wall around a point the refit is
451
+ // about to move away from. The SIZE is still honoured, because that is the part
452
+ // that does not change.
453
+ //
454
+ // `findFreeLayout` is the opposite case: it places one card on the CURRENT view,
455
+ // with no refit to follow, so it orbits the reserve's real position.
456
+ const reserve = { ...normalizeReserve(options.centreReserve ?? CENTRE_RESERVE), x: 0, y: 0 };
457
+ // Largest first: the classic first-fit-decreasing heuristic. Big cards claim
458
+ // the inner frames where there is less room to waste, and small cards fill the
459
+ // gaps they leave. Ties break on id so the result stays deterministic across
460
+ // two windows.
355
461
  const ordered = [...items].sort((left, right) => {
356
462
  const areaLeft = left.extent.width * left.extent.height;
357
463
  const areaRight = right.extent.width * right.extent.height;
@@ -359,238 +465,191 @@ export function arrangeLayouts(notes, options = {}) {
359
465
  return areaRight - areaLeft;
360
466
  return left.note.id.localeCompare(right.note.id);
361
467
  });
362
- // Plan the rings before placing anything.
363
- //
364
- // Filling ring by ring on demand left the last ring a PARTIAL ARC: cards went
365
- // onto it from angle 0 and stopped, so the wall's centre of mass leaned toward
366
- // that arc by ~180px and the camera framed a wall whose middle was not its
367
- // visual middle. Planning the counts first means each ring can spread its own
368
- // cards over the whole circle, so a partially filled ring is still balanced.
369
- // Two different spacings, and conflating them was a real capacity bug.
370
- //
371
- // Along a circle, cards are separated by their WIDTH (the tangential direction);
372
- // between circles, by their HEIGHT (the radial direction). The first version
373
- // pitched both by `max(width, height)`, so a ring was charged its cards' height
374
- // where only their width mattered — a 14-card wall then fit 11 cards on the
375
- // inner ring and spilled 3 onto a much wider outer ring, making the wall 2400px
376
- // tall where 1400 would do.
377
- const halfDepth = (item) => item.extent.height / 2;
378
- const ringPlan = [];
379
- const ringRadii = [];
380
- {
381
- let remaining = ordered.length;
382
- let cursor = 0;
383
- let radius = reserveCorner + largestHalfDiagonal;
384
- while (remaining > 0) {
385
- const group = ordered.slice(cursor, cursor + remaining);
386
- // Tangential pitch from the MEAN width of the cards that could land here;
387
- // the collision check still guards the real geometry.
388
- const meanWidth = group.reduce((sum, item) => sum + item.extent.width, 0) / group.length + TIDY_GAP;
389
- const capacity = Math.max(1, Math.floor((2 * Math.PI * radius) / meanWidth));
390
- const take = Math.min(capacity, remaining);
391
- ringPlan.push(take);
392
- ringRadii.push(radius);
393
- // Radial step: the deepest card on this ring plus the deepest on the next.
394
- //
395
- // This is the worst case (both rings' deepest cards at the same angle), and
396
- // it is charged deliberately. Tightening it below the worst case did fit
397
- // more cards per ring, but `pushOutOfReserve` runs after the final centring
398
- // shift and can then move a card INTO a neighbour — the shift preserves the
399
- // reserve, not the inter-card gaps. Charging the honest step keeps the
400
- // post-shift corrections small enough that they cannot collide.
401
- const deepest = Math.max(...ordered.slice(cursor, cursor + take).map(halfDepth));
402
- const nextDeepest = cursor + take < ordered.length ? Math.max(...ordered.slice(cursor + take).map(halfDepth)) : deepest;
403
- radius += deepest + nextDeepest + TIDY_GAP;
404
- remaining -= take;
405
- cursor += take;
406
- }
407
- }
408
468
  const grid = new Map();
409
- // Where the packer currently is: a ring, and the next angle on it to try.
410
- //
411
- // The cursor advances ONLY when a card is placed. Advancing it on a collision
412
- // as well looked equivalent and was not: every rejected candidate burned a
413
- // slot, so a ring "filled up" before its angles were exhausted and the packer
414
- // jumped outward on the next attempt — a 300-card wall then ran to radius
415
- // 25,000 and had 56 cards clamped onto the world edge.
416
- let ringIndex = 0;
417
- let slotIndex = 0;
418
- let fallbackY = 0;
469
+ // The wall's box so far, extended by each accepted card. The framing score
470
+ // needs it, and it is cheaper to maintain than to recompute per candidate.
471
+ let wall = null;
472
+ const extendWall = (box) => wall === null
473
+ ? { x: box.x, y: box.y, width: box.width, height: box.height }
474
+ : {
475
+ x: Math.min(wall.x, box.x),
476
+ y: Math.min(wall.y, box.y),
477
+ width: Math.max(wall.x + wall.width, box.x + box.width) - Math.min(wall.x, box.x),
478
+ height: Math.max(wall.y + wall.height, box.y + box.height) - Math.min(wall.y, box.y),
479
+ };
419
480
  /**
420
- * Radius of one ring, in world pixels.
481
+ * The best slot for one card, or null when no contour has room.
421
482
  *
422
- * A ring beyond the plan is only reached when the collision check rejects
423
- * every planned slot, so it continues the same outward progression.
483
+ * `soft` is used for the repair passes: a repair may not disturb a card that
484
+ * already sits legally, so it is asked to stay a hair further out, which keeps
485
+ * the rounding of a stored position from reading as a fresh violation.
424
486
  */
425
- const radiusOf = (index) => {
426
- const planned = ringRadii[index];
427
- if (planned !== undefined)
428
- return planned;
429
- const last = ringRadii[ringRadii.length - 1] ?? reserveCorner + largestHalfDiagonal;
430
- return last + (index - (ringRadii.length - 1)) * RADIAL_STEP;
431
- };
432
- /** Angles available on one ring: the plan, or the geometric capacity past it. */
433
- const slotsOf = (index) => Math.max(1, ringPlan[index] ?? Math.floor((2 * Math.PI * radiusOf(index)) / (largestHalfDiagonal * 2 + TIDY_GAP)));
434
- /** Radial step used when a ring beyond the plan has to be invented. */
435
- const RADIAL_STEP = largestHalfDiagonal * 2 + TIDY_GAP;
436
- for (const item of ordered) {
487
+ const pick = (item, settled, soft, seed) => {
437
488
  const { extent } = item;
438
- let box = null;
439
- let attempts = 0;
440
- // Walk rings outward from the current one. Each ring is tried at every one of
441
- // its own angles before the next ring is considered, which is what keeps the
442
- // wall compact: the first ring with a free slot wins.
443
- for (let ring = ringIndex; attempts < MAX_CANDIDATES; ring += 1) {
444
- const radius = radiusOf(ring);
445
- const slots = slotsOf(ring);
446
- // A deterministic phase per ring, so one ring's gaps do not line up with
447
- // the next ring's cards.
448
- const phase = (unit(`${item.note.id}:ring${ring}`) - 0.5) * (Math.PI / slots);
449
- // Try every slot on this ring and take the one whose angle is farthest from
450
- // the cards already placed. Filling slots in index order instead packed the
451
- // first few cards onto one arc, which left a partially filled outer ring
452
- // lopsided and the wall's centre of mass ~120px off the origin — visibly
453
- // off-centre after a tidy. "Farthest from a neighbour" spreads them.
489
+ for (let frame = 0; frame < MAX_FRAMES; frame += 1) {
490
+ const halfWidth = soft.halfWidth + frame * FRAME_STEP;
491
+ // Grow the height FASTER than the width until the contour itself is as wide
492
+ // as the framing rectangle. Growing both equally makes the left and right
493
+ // edges (already the reserve's long ones) longer still, so every extra frame
494
+ // adds room for a vertical column and none for a horizontal row: the wall
495
+ // grew into an 1114x966 block that framed at 69% where a window-shaped one
496
+ // frames at 90%. A contour whose own aspect matches the window puts the
497
+ // spare slots on the short edges, which is where they are useful.
498
+ const halfHeight = Math.max(soft.halfHeight, halfWidth / FRAMING_ASPECT);
499
+ const perimeter = 4 * (halfWidth + halfHeight);
500
+ const slots = Math.min(MAX_SLOTS, Math.max(12, Math.round(perimeter / CONTOUR_STEP)));
501
+ // A deterministic phase per frame, so two frames' slots do not line up and
502
+ // the same wall always packs to the same coordinates.
503
+ const phase = unit(`${seed}:f${frame}`) * perimeter;
454
504
  let best = null;
455
505
  for (let slot = 0; slot < slots; slot += 1) {
456
- const theta = phase + (slot / slots) * Math.PI * 2;
457
- // Jitter the radius, never the angle: an angular jitter would slide a card
458
- // toward its neighbour, while a radial one only opens a small gap.
459
- const jitter = (unit(`${item.note.id}:aj`) - 0.5) * 2 * TIDY_JITTER;
460
- const candidate = {
461
- x: Math.cos(theta) * (radius + jitter) - extent.width / 2,
462
- y: Math.sin(theta) * (radius + jitter) - extent.height / 2,
463
- width: extent.width,
464
- height: extent.height,
465
- };
466
- attempts += 1;
506
+ const candidate = boxOnContour(contourPoint(halfWidth, halfHeight, phase + (slot / slots) * perimeter), extent);
467
507
  if (!clearsReserve(candidate, reserve))
468
508
  continue;
469
- if (collides(candidate, grid))
509
+ if (collides(candidate, settled))
470
510
  continue;
471
- // Score = clearance, biased toward the HORIZONTAL axis on outer rings.
472
- //
473
- // A wall is viewed in a window that is wider than it is tall, so an outer
474
- // arc is much cheaper to frame if it sits on the left and right rather than
475
- // above and below. Without the bias the outer cards landed wherever the
476
- // slot order put them, which made a two-ring wall ~2100px TALL and 1600
477
- // wide — the shape the viewport is worst at. The bias is small enough that
478
- // a genuinely freer slot still wins.
479
- const clearance = nearestGap(candidate, grid);
480
- const horizontal = Math.abs(Math.cos(theta));
481
- const score = clearance + horizontal * (ring === 0 ? 0 : HORIZON_BIAS);
482
- if (best === null || score > best.score)
483
- best = { box: candidate, slot, score };
484
- }
485
- if (best !== null) {
486
- box = best.box;
487
- ringIndex = ring;
488
- slotIndex = best.slot + 1;
489
- break;
511
+ const next = extendWall(candidate);
512
+ // How much this wall would have to shrink to fit the reference viewport.
513
+ // Higher is better; it is the number the camera will actually apply.
514
+ const score = Math.min(1, FRAMING_WIDTH / Math.max(1, next.width), FRAMING_HEIGHT / Math.max(1, next.height));
515
+ // HOW WINDOW-SHAPED the wall becomes, as a log ratio so being too wide
516
+ // and being too tall are penalised equally. This is the tie-break, and it
517
+ // is what actually produces a wide wall: for the first several cards
518
+ // almost every slot frames at the same zoom, because the wall is still
519
+ // smaller than the viewport either way. Without a shape preference the
520
+ // tie fell to placement noise, the wall grew equally in all four
521
+ // directions, and the result was a tall block that framed at 69% where a
522
+ // wide one frames at 90%.
523
+ const shape = Math.abs(Math.log((next.width + 1) / (next.height + 1) / FRAMING_ASPECT));
524
+ // How far this slot sits from the cards already placed. Even distribution
525
+ // is the point of a wall: a slot that hugs one neighbour leaves a hole
526
+ // elsewhere that the NEXT card then has to reach across.
527
+ const clearance = nearestGap(candidate, settled);
528
+ // Nearest-the-origin last, because that is the middle the camera frames.
529
+ const offset = Math.hypot(next.x + next.width / 2, next.y + next.height / 2);
530
+ const better = best === null ||
531
+ score > best.score + 1e-9 ||
532
+ (Math.abs(score - best.score) <= 1e-9 &&
533
+ (shape < best.shape - 1e-9 ||
534
+ (Math.abs(shape - best.shape) <= 1e-9 &&
535
+ (clearance > best.clearance + 1e-9 ||
536
+ (Math.abs(clearance - best.clearance) <= 1e-9 && offset < best.offset)))));
537
+ if (better)
538
+ best = { box: candidate, score, shape, clearance, offset };
490
539
  }
540
+ // The first frame with ANY free slot wins. Walking further out would find
541
+ // roomier slots, and taking them is exactly how a wall grows into a sparse
542
+ // scatter instead of a composition.
543
+ if (best !== null)
544
+ return best.box;
491
545
  }
492
- if (box === null) {
546
+ return null;
547
+ };
548
+ for (const item of ordered) {
549
+ const box = pick(item, grid, reserve, item.note.id) ?? {
493
550
  // Unreachable for a wall inside the note cap; the fallback exists so the
494
551
  // function still returns a placement for every note instead of throwing.
495
- fallbackY += extent.height + TIDY_GAP;
496
- box = { x: -extent.width / 2, y: reserveCorner + fallbackY, width: extent.width, height: extent.height };
497
- }
552
+ x: -item.extent.width / 2,
553
+ y: -9000,
554
+ width: item.extent.width,
555
+ height: item.extent.height,
556
+ };
498
557
  remember(box, grid);
558
+ wall = extendWall(box);
499
559
  // The rotated footprint is centred on the card, so the card's own top-left
500
560
  // is the footprint centre minus the UNROTATED half size.
501
561
  placed.set(item.note.id, clampLayout({
502
- x: box.x + extent.width / 2 - item.cardWidth / 2,
503
- y: box.y + extent.height / 2 - item.cardHeight / 2,
562
+ x: box.x + item.extent.width / 2 - item.cardWidth / 2,
563
+ y: box.y + item.extent.height / 2 - item.cardHeight / 2,
504
564
  rotate: item.rotate,
505
565
  width: item.width,
506
566
  }));
507
567
  }
508
- // Centre the finished ring on the world origin.
509
- //
510
- // This is not cosmetic — it is what makes the reserved middle correct. The
511
- // centrepiece is a SCREEN-space block at the viewport's middle, and the camera
512
- // frames the wall's BOUNDING BOX centre at that same middle. So the world
513
- // rectangle the packer keeps clear is only under the field if the wall's box is
514
- // centred on the origin. Leave the offset in and a tidy wall's capture field
515
- // drifts off its own reserve by however far the box was off.
516
- //
517
- // Measured on the bounding box (what the camera frames), not the centroid, and
518
- // on the ROTATED footprint (what the packer placed).
519
- const boxes = [...placed].map(([id, layout]) => {
568
+ /**
569
+ * Centre the finished wall on the world origin.
570
+ *
571
+ * This is not cosmetic — it is what makes the reserved middle correct. The
572
+ * centrepiece is a SCREEN-space block at the viewport's middle, and the camera
573
+ * frames the wall's BOUNDING BOX centre at that same middle. So the world
574
+ * rectangle the packer keeps clear is only under the field if the wall's box is
575
+ * centred on the origin. Leave the offset in and a tidy wall's capture field
576
+ * drifts off its own reserve by however far the box was off.
577
+ *
578
+ * It alternates the shift with a repair, because a shift can push a card into
579
+ * the reserve: the repair displaces the wall again, so the shift has to be
580
+ * re-measured. A single pass left a 20-card wall ~56px off centre.
581
+ */
582
+ const footprintOfId = (id, layout) => {
520
583
  const note = notes.find((candidate) => candidate.id === id);
521
- const width = WIDTH_PX[layout.width];
522
- const height = note === undefined ? 0 : estimateHeight(note, layout.width);
523
- const extent = rotatedExtent(width, height, layout.rotate);
524
- const centreX = layout.x + width / 2;
525
- const centreY = layout.y + height / 2;
526
- return {
527
- id,
528
- note,
529
- layout,
530
- extent,
531
- box: { x: centreX - extent.width / 2, y: centreY - extent.height / 2, width: extent.width, height: extent.height },
532
- };
533
- });
534
- const minX = Math.min(...boxes.map((entry) => entry.box.x));
535
- const maxX = Math.max(...boxes.map((entry) => entry.box.x + entry.box.width));
536
- const minY = Math.min(...boxes.map((entry) => entry.box.y));
537
- const maxY = Math.max(...boxes.map((entry) => entry.box.y + entry.box.height));
538
- const shiftX = (minX + maxX) / 2;
539
- const shiftY = (minY + maxY) / 2;
540
- // Apply the FULL shift, then push any card the shift nudged into the reserve
541
- // back out of it.
542
- //
543
- // A partial shift (the previous bisection) left the wall's box off the origin,
544
- // and that is not a cosmetic problem: the centrepiece is a screen-space block at
545
- // the viewport's middle and the camera frames the box centre, so a box off the
546
- // origin puts the field off its own reserved rectangle — a card then legitimately
547
- // sits behind the capture field while every world-space check says it is clear.
548
- // Keeping the box ON the origin is what makes the reserve and the field the same
549
- // thing.
550
- if (Math.abs(shiftX) >= 0.05 || Math.abs(shiftY) >= 0.05) {
584
+ if (note === undefined)
585
+ return { x: layout.x, y: layout.y, width: 0, height: 0 };
586
+ return footprintOf(note, layout);
587
+ };
588
+ const wallBounds = () => {
589
+ let minX = Number.POSITIVE_INFINITY;
590
+ let minY = Number.POSITIVE_INFINITY;
591
+ let maxX = Number.NEGATIVE_INFINITY;
592
+ let maxY = Number.NEGATIVE_INFINITY;
551
593
  for (const [id, layout] of placed) {
552
- placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
594
+ const box = footprintOfId(id, layout);
595
+ minX = Math.min(minX, box.x);
596
+ minY = Math.min(minY, box.y);
597
+ maxX = Math.max(maxX, box.x + box.width);
598
+ maxY = Math.max(maxY, box.y + box.height);
553
599
  }
554
- // A card packed just outside the reserve moves INTO it when the wall slides
555
- // toward that side. Repair those cards properly rather than nudging them.
556
- //
557
- // Two earlier attempts were wrong in instructive ways. Pushing along the
558
- // nearest axis ignored the neighbours and could land a card on top of one.
559
- // Collision-checking that push was better, but when no escape was clear it
560
- // left the card where it was — a reserve violation, which is the invariant the
561
- // whole design exists to keep.
562
- //
563
- // So the repair reuses `findFreeLayout`: it already searches outward from the
564
- // reserve for a spot that clears both the rectangle and every placed card, and
565
- // it is deterministic. Violating cards are relocated one at a time against the
566
- // set of cards that are already settled.
567
- const violators = [...placed].filter(([id, layout]) => {
568
- const note = notes.find((candidate) => candidate.id === id);
569
- return note !== undefined && !clearsReserve(footprintOf(note, layout), reserve);
570
- });
571
- if (violators.length > 0) {
572
- const settled = new Map(placed);
573
- for (const [id] of violators)
574
- settled.delete(id);
575
- for (const [id, layout] of violators) {
576
- const note = notes.find((candidate) => candidate.id === id);
577
- if (note === undefined)
578
- continue;
579
- // `findFreeLayout` needs the OTHER notes; the candidate note's own width is
580
- // preserved so a card never changes size just because it had to move.
581
- const others = [];
582
- for (const [otherId, otherLayout] of settled) {
583
- const other = notes.find((candidate) => candidate.id === otherId);
584
- if (other !== undefined)
585
- others.push({ ...other, layout: otherLayout });
586
- }
587
- const relocated = findFreeLayout({ ...note, layout }, others, { centreReserve: reserve });
588
- // Keep the width the card already had: `findFreeLayout` honours a submitted
589
- // layout's width, and the layout passed in carries it.
590
- settled.set(id, relocated);
591
- placed.set(id, relocated);
592
- }
600
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
601
+ };
602
+ /** Repair every card that sits in the reserve, one at a time, against the rest. */
603
+ const repairReserve = (soft) => {
604
+ const violators = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve));
605
+ if (violators.length === 0)
606
+ return;
607
+ const settled = new Map(placed);
608
+ for (const [id] of violators)
609
+ settled.delete(id);
610
+ const repairGrid = new Map();
611
+ for (const [id, layout] of settled)
612
+ remember(footprintOfId(id, layout), repairGrid);
613
+ for (const [id] of violators) {
614
+ const item = items.find((candidate) => candidate.note.id === id);
615
+ if (item === undefined)
616
+ continue;
617
+ const box = pick(item, repairGrid, soft, `${id}:repair`);
618
+ if (box === null)
619
+ continue;
620
+ remember(box, repairGrid);
621
+ placed.set(id, clampLayout({
622
+ x: box.x + item.extent.width / 2 - item.cardWidth / 2,
623
+ y: box.y + item.extent.height / 2 - item.cardHeight / 2,
624
+ rotate: item.rotate,
625
+ width: item.width,
626
+ }));
627
+ }
628
+ };
629
+ // Ask the repair to stay a hair clear, so a card packed exactly on the boundary
630
+ // is not re-placed by rounding noise.
631
+ const softReserve = { halfWidth: reserve.halfWidth + 1.5, halfHeight: reserve.halfHeight + 1.5 };
632
+ for (let pass = 0; pass < 6; pass += 1) {
633
+ const box = wallBounds();
634
+ const shiftX = box.x + box.width / 2;
635
+ const shiftY = box.y + box.height / 2;
636
+ if (Math.abs(shiftX) < 0.5 && Math.abs(shiftY) < 0.5)
637
+ break;
638
+ for (const [id, layout] of placed) {
639
+ placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
593
640
  }
641
+ repairReserve(softReserve);
642
+ }
643
+ // The loop above can exit with violators left over: its last repair is itself
644
+ // displaced by the shift it was responding to. Settle them without shifting.
645
+ for (let pass = 0; pass < 24; pass += 1) {
646
+ const before = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve)).length;
647
+ if (before === 0)
648
+ break;
649
+ repairReserve(softReserve);
650
+ const after = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve)).length;
651
+ if (after >= before)
652
+ break;
594
653
  }
595
654
  return placed;
596
655
  }
@@ -609,6 +668,20 @@ export function normalizeWidth(raw) {
609
668
  * capped well inside the world bounds so the packer can never be asked to keep
610
669
  * a middle clear that leaves no paper for the cards.
611
670
  */
671
+ /**
672
+ * Clamp a reserve into something the packer can actually honour.
673
+ *
674
+ * The Client sends a reserve positioned where the centrepiece currently sits in
675
+ * world space, so it can arrive with huge coordinates (a deeply zoomed-out wall)
676
+ * or as garbage. Both extremes are refused here: a non-finite coordinate becomes
677
+ * the origin, and the half-extents are capped well inside the world bounds so the
678
+ * packer can never be asked to keep a middle clear that leaves no paper for the
679
+ * cards.
680
+ *
681
+ * The position is clamped to the world bounds rather than to zero: a panned wall
682
+ * legitimately puts the field far from the origin, and snapping it back to the
683
+ * origin would reintroduce the very bug this position exists to fix.
684
+ */
612
685
  export function normalizeReserve(raw) {
613
686
  const cap = LAYOUT_LIMITS.coord / 4;
614
687
  const clampHalf = (value) => {
@@ -617,7 +690,18 @@ export function normalizeReserve(raw) {
617
690
  return 0;
618
691
  return Math.min(cap, number);
619
692
  };
620
- return { halfWidth: clampHalf(raw?.halfWidth), halfHeight: clampHalf(raw?.halfHeight) };
693
+ const clampCoord = (value) => {
694
+ const number = Number(value);
695
+ if (!Number.isFinite(number))
696
+ return 0;
697
+ return Math.min(LAYOUT_LIMITS.coord, Math.max(-LAYOUT_LIMITS.coord, number));
698
+ };
699
+ return {
700
+ x: clampCoord(raw?.x ?? 0),
701
+ y: clampCoord(raw?.y ?? 0),
702
+ halfWidth: clampHalf(raw?.halfWidth),
703
+ halfHeight: clampHalf(raw?.halfHeight),
704
+ };
621
705
  }
622
706
  /**
623
707
  * The nearest free spot for one new card, in world coordinates.
@@ -629,11 +713,19 @@ export function normalizeReserve(raw) {
629
713
  * the user could not see it, which reads exactly like the capture silently
630
714
  * failing.
631
715
  *
632
- * This searches outward from the middle instead: the spiral is walked from just
716
+ * This searches outward from the field instead: the spiral is walked from just
633
717
  * outside the centrepiece's reserve, and the first candidate that clears every
634
718
  * existing card (plus a gap) and stays out of the reserve is the answer. The
635
- * result is therefore the gap nearest the centre of the wall, which is both
636
- * where the user is looking and where the wall has room.
719
+ * result is therefore the gap nearest the place the user is actually looking at,
720
+ * which is where the wall has room.
721
+ *
722
+ * The spiral orbits the RESERVE, not the world origin. That distinction is the
723
+ * fix for a note appearing behind the capture field: the field is a screen-space
724
+ * overlay, so on a panned wall it covers a patch of world that is nowhere near
725
+ * the origin. Orbiting the origin placed the card beside a point the user could
726
+ * not see, and the reveal then centred that point — with the field drawn on top
727
+ * of it. Orbiting the reserve puts the card next to the field, which is both
728
+ * visible and the only placement that can never be hidden by it.
637
729
  *
638
730
  * Deterministic for the same inputs, so two windows creating at once cannot
639
731
  * disagree about the free spot for the same wall.
@@ -664,7 +756,8 @@ export function findFreeLayout(note, existing, options = {}) {
664
756
  // Start just outside the reserve so the first candidate is the closest legal
665
757
  // ring, then walk the same golden-angle spiral the tidy pass uses. A step near
666
758
  // the card's own size keeps the search local: the answer is the first gap, not
667
- // a far-away hole.
759
+ // a far-away hole. The whole spiral is offset by the reserve's centre, because
760
+ // the field it protects is wherever the camera has put it.
668
761
  const step = Math.max(64, Math.sqrt(extent.width * extent.height) * 0.92);
669
762
  const startRadius = Math.hypot(reserve.halfWidth, reserve.halfHeight);
670
763
  const startIndex = (startRadius / step) ** 2;
@@ -673,8 +766,8 @@ export function findFreeLayout(note, existing, options = {}) {
673
766
  const radius = step * Math.sqrt(index);
674
767
  const theta = index * GOLDEN_ANGLE;
675
768
  const candidate = {
676
- x: Math.cos(theta) * radius - extent.width / 2,
677
- y: Math.sin(theta) * radius - extent.height / 2,
769
+ x: reserve.x + Math.cos(theta) * radius - extent.width / 2,
770
+ y: reserve.y + Math.sin(theta) * radius - extent.height / 2,
678
771
  width: extent.width,
679
772
  height: extent.height,
680
773
  };
@@ -693,8 +786,8 @@ export function findFreeLayout(note, existing, options = {}) {
693
786
  // than a real path: place just outside the reserve on the first ring.
694
787
  const fallbackRadius = startRadius + Math.max(extent.width, extent.height);
695
788
  return clampLayout({
696
- x: -cardWidth / 2,
697
- y: -fallbackRadius - cardHeight / 2,
789
+ x: reserve.x - cardWidth / 2,
790
+ y: reserve.y + fallbackRadius - cardHeight / 2,
698
791
  rotate,
699
792
  width,
700
793
  });
@@ -734,28 +827,30 @@ export function noteBox(note, index) {
734
827
  * collisions needs the whole ordered list, not just the first answer.
735
828
  */
736
829
  export function escapesFromReserve(note, layout, reserve = CENTRE_RESERVE) {
830
+ const rect = normalizeReserve(reserve);
737
831
  const box = footprintOf(note, layout);
738
832
  const moves = [
739
- { dx: -reserve.halfWidth - (box.x + box.width), dy: 0 },
740
- { dx: reserve.halfWidth - box.x, dy: 0 },
741
- { dx: 0, dy: -reserve.halfHeight - (box.y + box.height) },
742
- { dx: 0, dy: reserve.halfHeight - box.y },
833
+ { dx: rect.x - rect.halfWidth - (box.x + box.width), dy: 0 },
834
+ { dx: rect.x + rect.halfWidth - box.x, dy: 0 },
835
+ { dx: 0, dy: rect.y - rect.halfHeight - (box.y + box.height) },
836
+ { dx: 0, dy: rect.y + rect.halfHeight - box.y },
743
837
  ];
744
838
  return moves
745
839
  .sort((left, right) => (Math.abs(left.dx) + Math.abs(left.dy)) - (Math.abs(right.dx) + Math.abs(right.dy)))
746
840
  .map((move) => clampLayout({ ...layout, x: layout.x + move.dx, y: layout.y + move.dy }));
747
841
  }
748
842
  export function pushOutOfReserve(note, layout, reserve = CENTRE_RESERVE) {
843
+ const rect = normalizeReserve(reserve);
749
844
  const box = footprintOf(note, layout);
750
- if (!intersectsReserve(box, reserve))
845
+ if (clearsReserve(box, rect))
751
846
  return layout;
752
847
  // Four ways out, one per edge; the shortest wins so the card slides to the
753
848
  // nearest side instead of jumping around the rectangle.
754
849
  const moves = [
755
- { dx: -reserve.halfWidth - (box.x + box.width), dy: 0 },
756
- { dx: reserve.halfWidth - box.x, dy: 0 },
757
- { dx: 0, dy: -reserve.halfHeight - (box.y + box.height) },
758
- { dx: 0, dy: reserve.halfHeight - box.y },
850
+ { dx: rect.x - rect.halfWidth - (box.x + box.width), dy: 0 },
851
+ { dx: rect.x + rect.halfWidth - box.x, dy: 0 },
852
+ { dx: 0, dy: rect.y - rect.halfHeight - (box.y + box.height) },
853
+ { dx: 0, dy: rect.y + rect.halfHeight - box.y },
759
854
  ];
760
855
  let best = moves[0];
761
856
  for (const move of moves) {