@skillre/dsh-plugin-sticky-wall 0.4.0 → 0.5.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
@@ -20,7 +20,7 @@
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.
22
22
  */
23
- import { CENTRE_RADIUS, LAYOUT_LIMITS, WIDTHS, WIDTH_PX } from './types.js';
23
+ import { CENTRE_RESERVE, LAYOUT_LIMITS, WIDTHS, WIDTH_PX, } from './types.js';
24
24
  /** Golden angle: the phyllotaxis constant that keeps a spiral from lining up. */
25
25
  const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
26
26
  /** Breathing room kept between two tidied cards, in world pixels. */
@@ -33,6 +33,16 @@ const TIDY_TILT = 3.4;
33
33
  const PREVIEW_STEP = 196;
34
34
  /** Height assumed for a derived position, so the derived box looks centred. */
35
35
  const PREVIEW_NOMINAL_HEIGHT = 200;
36
+ /** Clearance the free-spot search keeps between a new card and its neighbours. */
37
+ const SPOT_GAP = 24;
38
+ /** Candidate positions the free-spot search tries before falling back. */
39
+ const MAX_SPOTS = 2048;
40
+ /**
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.
44
+ */
45
+ const HORIZON_BIAS = 140;
36
46
  /** Maximum rotation the preview fallback adds, in degrees. */
37
47
  const PREVIEW_TILT = 4;
38
48
  /** Spatial-grid cell; wider than the biggest rotated card plus the gap. */
@@ -168,8 +178,17 @@ export function layoutOf(note, index) {
168
178
  export function previewLayout(note, index) {
169
179
  const width = previewWidth(note.id);
170
180
  // The derived wall leaves the same clear middle as the tidy pass: the centre
171
- // is the wall's centrepiece, not another place for a card.
172
- const radius = PREVIEW_STEP * Math.sqrt(Math.max(0, index) + (CENTRE_RADIUS / PREVIEW_STEP) ** 2);
181
+ // is the wall's centrepiece, not another place for a card. The step out is
182
+ // derived from the reserve's own half-diagonal so the first derived card
183
+ // lands outside the rectangle at any reserve size.
184
+ const reserve = CENTRE_RESERVE;
185
+ // The reserve's half-diagonal is how far the RECTANGLE's corner is from the
186
+ // middle; the card's own half-diagonal is how far the CARD reaches back inward
187
+ // from its centre. Adding both is what guarantees the derived box cannot clip
188
+ // a corner of the reserved band.
189
+ const startRadius = Math.hypot(reserve.halfWidth, reserve.halfHeight) +
190
+ Math.hypot(WIDTH_PX[width], PREVIEW_NOMINAL_HEIGHT) / 2;
191
+ const radius = PREVIEW_STEP * Math.sqrt(Math.max(0, index) + (startRadius / PREVIEW_STEP) ** 2);
173
192
  const theta = index * GOLDEN_ANGLE + (unit(`${note.id}:pa`) - 0.5) * 0.55;
174
193
  return clampLayout({
175
194
  x: Math.cos(theta) * radius - WIDTH_PX[width] / 2,
@@ -193,18 +212,34 @@ export function rotatedExtent(width, height, rotate) {
193
212
  return { width: width * cos + height * sin, height: height * cos + width * sin };
194
213
  }
195
214
  /**
196
- * Distance from the world origin to the nearest point of one footprint.
215
+ * Whether a footprint stays out of a clear rectangle.
197
216
  *
198
217
  * The tidy pass keeps the wall's middle clear for the centrepiece, and "clear"
199
- * has to mean the card's EDGE: measuring from the centre let a wide card reach
200
- * over the capture field by half its own width.
218
+ * has to mean the card's EDGE: measuring from the card's centre let a wide card
219
+ * reach over the capture field by half its own width. A rectangle rather than a
220
+ * radius is the honest shape, because the centrepiece is a wide, short stack —
221
+ * a circle either wasted a tall column of paper above and below it or let wide
222
+ * cards in from the sides.
201
223
  */
202
- function nearestEdgeRadius(box) {
203
- const centreX = box.x + box.width / 2;
204
- const centreY = box.y + box.height / 2;
205
- const dx = Math.max(0, Math.abs(centreX) - box.width / 2);
206
- const dy = Math.max(0, Math.abs(centreY) - box.height / 2);
207
- return Math.hypot(dx, dy);
224
+ export function intersectsReserve(box, reserve = CENTRE_RESERVE) {
225
+ const clear = clearsReserve(box, reserve);
226
+ return !clear;
227
+ }
228
+ /**
229
+ * Tolerance for the reserve test, in world pixels.
230
+ *
231
+ * Positions are rounded to one decimal for storage, so a card packed exactly on
232
+ * the boundary comes back a hundredth of a pixel inside it. Without a tolerance
233
+ * that rounding reads as a violation — and worse, `pushOutOfReserve` would then
234
+ * "correct" a card that was already in the right place. A twentieth of a pixel is
235
+ * far below anything visible and well above the rounding error.
236
+ */
237
+ const RESERVE_EPSILON = 0.05;
238
+ 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);
208
243
  }
209
244
  /** Cell coordinate of one world value. */
210
245
  function cellOf(value) {
@@ -234,6 +269,27 @@ function collides(box, grid) {
234
269
  }
235
270
  return false;
236
271
  }
272
+ /**
273
+ * Distance from `box` to the nearest placed card, for tie-breaking between two
274
+ * candidates that both pass the collision test. Returns a large number when
275
+ * nothing is nearby.
276
+ */
277
+ function nearestGap(box, grid) {
278
+ let nearest = Number.POSITIVE_INFINITY;
279
+ for (let cellX = cellOf(box.x - GRID_CELL); cellX <= cellOf(box.x + box.width + GRID_CELL); cellX += 1) {
280
+ for (let cellY = cellOf(box.y - GRID_CELL); cellY <= cellOf(box.y + box.height + GRID_CELL); cellY += 1) {
281
+ const bucket = grid.get(`${cellX}:${cellY}`);
282
+ if (bucket === undefined)
283
+ continue;
284
+ for (const other of bucket) {
285
+ const gapX = Math.max(other.x - (box.x + box.width), box.x - (other.x + other.width), 0);
286
+ const gapY = Math.max(other.y - (box.y + box.height), box.y - (other.y + other.height), 0);
287
+ nearest = Math.min(nearest, Math.hypot(gapX, gapY));
288
+ }
289
+ }
290
+ }
291
+ return nearest;
292
+ }
237
293
  /** Register one accepted footprint in every cell it touches. */
238
294
  function remember(box, grid) {
239
295
  for (let cellX = cellOf(box.x); cellX <= cellOf(box.x + box.width); cellX += 1) {
@@ -250,16 +306,25 @@ function remember(box, grid) {
250
306
  /**
251
307
  * Deterministic tidy arrangement for the whole wall.
252
308
  *
253
- * Phyllotaxis packing around the world origin: candidate positions are visited
254
- * on a sunflower spiral and the first one that clears every placed card is
255
- * accepted. The spiral's step is derived from the wall's own average card area,
256
- * so a wall of small notes packs tightly while a wall of large ones does not
257
- * overlap, and a big wall grows outward in a disc instead of a column that runs
258
- * off the coordinate limit.
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.
319
+ *
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.
259
323
  *
260
- * A collision check rather than a shelf estimate is what makes the result
261
- * trustworthy: the estimate is only a height guess, so any packing that merely
262
- * trusts it can overlap at the cap. This one cannot.
324
+ * A collision check still runs on every candidate rather than trusting the
325
+ * 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.
263
328
  *
264
329
  * Returns a map from note id to its new layout, for every note that needs to
265
330
  * move. Notes already at exactly that layout are omitted by the caller, so
@@ -269,7 +334,7 @@ export function arrangeLayouts(notes, options = {}) {
269
334
  const placed = new Map();
270
335
  if (notes.length === 0)
271
336
  return placed;
272
- // Decide each card's rotation and footprint up front: the spiral step and the
337
+ // Decide each card's rotation and footprint up front: the ring pitch and the
273
338
  // collision test both work on the rotated box.
274
339
  const items = notes.map((note) => {
275
340
  const width = note.layout?.width ?? previewWidth(note.id);
@@ -279,45 +344,148 @@ export function arrangeLayouts(notes, options = {}) {
279
344
  const extent = rotatedExtent(cardWidth, cardHeight, rotate);
280
345
  return { note, width, cardWidth, cardHeight, rotate, extent };
281
346
  });
282
- const totalArea = items.reduce((sum, item) => sum + item.extent.width * item.extent.height, 0);
283
- // A phyllotaxis point at index k owns `PI * step^2` of area, so a step derived
284
- // from the average card area fills the disc without a hole in the middle or a
285
- // sparse rim. The 1.06 slack absorbs the gap the packing has to keep.
286
- const step = Math.max(72, Math.sqrt(totalArea / (Math.PI * items.length)) * 1.06);
287
- // Leave a clear disc in the middle.
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.
355
+ const ordered = [...items].sort((left, right) => {
356
+ const areaLeft = left.extent.width * left.extent.height;
357
+ const areaRight = right.extent.width * right.extent.height;
358
+ if (areaRight !== areaLeft)
359
+ return areaRight - areaLeft;
360
+ return left.note.id.localeCompare(right.note.id);
361
+ });
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.
288
370
  //
289
- // The wall is a composition around a centre, and that centre is where the
290
- // greeting and the quick-capture field live: packing a card on top of them
291
- // would make the wall fight its own centrepiece. Offsetting the spiral's start
292
- // index puts every card beyond `centreRadius` while keeping the same
293
- // phyllotaxis density, so the ring around the middle stays evenly packed.
294
- const centreRadius = Math.max(0, options.centreRadius ?? CENTRE_RADIUS);
295
- const startIndex = centreRadius > 0 ? (centreRadius / step) ** 2 : 0;
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
+ }
296
408
  const grid = new Map();
297
- let cursor = 0;
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;
298
418
  let fallbackY = 0;
299
- for (const item of items) {
419
+ /**
420
+ * Radius of one ring, in world pixels.
421
+ *
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.
424
+ */
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) {
300
437
  const { extent } = item;
301
438
  let box = null;
302
- for (let attempt = 0; attempt < MAX_CANDIDATES; attempt += 1) {
303
- const index = startIndex + cursor + attempt;
304
- const jitter = (unit(`${item.note.id}:aj`) - 0.5) * 2 * TIDY_JITTER;
305
- const radius = step * Math.sqrt(index) + jitter;
306
- const theta = index * GOLDEN_ANGLE;
307
- const candidate = {
308
- x: Math.cos(theta) * radius - extent.width / 2,
309
- y: Math.sin(theta) * radius - extent.height / 2,
310
- width: extent.width,
311
- height: extent.height,
312
- };
313
- // The reserve is measured to the card's NEAREST EDGE, not its centre: a
314
- // card whose centre clears the radius can still reach into the middle by
315
- // half its own width, which is what let a wide card sit on the centrepiece.
316
- if (nearestEdgeRadius(candidate) < centreRadius)
317
- continue;
318
- if (!collides(candidate, grid)) {
319
- box = candidate;
320
- cursor = index + 1;
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.
454
+ let best = null;
455
+ 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;
467
+ if (!clearsReserve(candidate, reserve))
468
+ continue;
469
+ if (collides(candidate, grid))
470
+ 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;
321
489
  break;
322
490
  }
323
491
  }
@@ -325,7 +493,7 @@ export function arrangeLayouts(notes, options = {}) {
325
493
  // Unreachable for a wall inside the note cap; the fallback exists so the
326
494
  // function still returns a placement for every note instead of throwing.
327
495
  fallbackY += extent.height + TIDY_GAP;
328
- box = { x: -extent.width / 2, y: fallbackY, width: extent.width, height: extent.height };
496
+ box = { x: -extent.width / 2, y: reserveCorner + fallbackY, width: extent.width, height: extent.height };
329
497
  }
330
498
  remember(box, grid);
331
499
  // The rotated footprint is centred on the card, so the card's own top-left
@@ -337,42 +505,90 @@ export function arrangeLayouts(notes, options = {}) {
337
505
  width: item.width,
338
506
  }));
339
507
  }
340
- // Re-centre the finished disc on its own centre of mass.
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.
341
516
  //
342
- // The spiral is centred on the origin, but the first cards sit near it and the
343
- // rest surround them unevenly, so the centroid of the PLACED cards is a few
344
- // dozen pixels off. The camera frames the centroid, so leaving the offset in
345
- // means the wall never looks quite centred after a tidy. A uniform translation
346
- // cannot change any of the collision guarantees above.
347
- let sumX = 0;
348
- let sumY = 0;
349
- for (const [id, layout] of placed) {
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]) => {
350
520
  const note = notes.find((candidate) => candidate.id === id);
351
- const width = layout.width;
352
- const height = note === undefined ? 0 : estimateHeight(note, width);
353
- sumX += layout.x + WIDTH_PX[width] / 2;
354
- sumY += layout.y + height / 2;
355
- }
356
- const shiftX = sumX / placed.size;
357
- const shiftY = sumY / placed.size;
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.
358
550
  if (Math.abs(shiftX) >= 0.05 || Math.abs(shiftY) >= 0.05) {
359
- // A uniform translation cannot create an overlap, but it CAN push a card back
360
- // into the reserved middle — which is exactly what happened when the shift
361
- // was applied unconditionally. Shift only when the reserve survives it.
362
- const safe = [...placed].every(([id, layout]) => {
551
+ for (const [id, layout] of placed) {
552
+ placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
553
+ }
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]) => {
363
568
  const note = notes.find((candidate) => candidate.id === id);
364
- const height = note === undefined ? 0 : estimateHeight(note, layout.width);
365
- const box = {
366
- x: layout.x - shiftX,
367
- y: layout.y - shiftY,
368
- width: WIDTH_PX[layout.width],
369
- height,
370
- };
371
- return nearestEdgeRadius(box) >= centreRadius - 0.5;
569
+ return note !== undefined && !clearsReserve(footprintOf(note, layout), reserve);
372
570
  });
373
- if (safe) {
374
- for (const [id, layout] of placed) {
375
- placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
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);
376
592
  }
377
593
  }
378
594
  }
@@ -384,3 +600,175 @@ export function normalizeWidth(raw) {
384
600
  const match = WIDTHS.find((width) => width === value);
385
601
  return match ?? 'md';
386
602
  }
603
+ /**
604
+ * Clamp a reserve into something the packer can actually honour.
605
+ *
606
+ * The Client sends a zoom-corrected reserve, so it can arrive as a huge number
607
+ * (a deeply zoomed-out wall) or as garbage. Both extremes are refused here: a
608
+ * non-finite or negative half-extent becomes zero, and the whole reserve is
609
+ * capped well inside the world bounds so the packer can never be asked to keep
610
+ * a middle clear that leaves no paper for the cards.
611
+ */
612
+ export function normalizeReserve(raw) {
613
+ const cap = LAYOUT_LIMITS.coord / 4;
614
+ const clampHalf = (value) => {
615
+ const number = Number(value);
616
+ if (!Number.isFinite(number) || number <= 0)
617
+ return 0;
618
+ return Math.min(cap, number);
619
+ };
620
+ return { halfWidth: clampHalf(raw?.halfWidth), halfHeight: clampHalf(raw?.halfHeight) };
621
+ }
622
+ /**
623
+ * The nearest free spot for one new card, in world coordinates.
624
+ *
625
+ * Creating a note used to leave its placement to the Host, which stored `null`
626
+ * and let the Client derive a position from the note's index — and that derived
627
+ * position is a spiral that grows outward, so the tenth note could land a
628
+ * screen and a half away from where the user was looking. The card existed, but
629
+ * the user could not see it, which reads exactly like the capture silently
630
+ * failing.
631
+ *
632
+ * This searches outward from the middle instead: the spiral is walked from just
633
+ * outside the centrepiece's reserve, and the first candidate that clears every
634
+ * 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.
637
+ *
638
+ * Deterministic for the same inputs, so two windows creating at once cannot
639
+ * disagree about the free spot for the same wall.
640
+ */
641
+ export function findFreeLayout(note, existing, options = {}) {
642
+ const width = note.layout?.width ?? previewWidth(note.id);
643
+ const cardWidth = WIDTH_PX[width];
644
+ const cardHeight = estimateHeight(note, width);
645
+ const rotate = (unit(`${note.id}:ar`) - 0.5) * 2 * TIDY_TILT;
646
+ const extent = rotatedExtent(cardWidth, cardHeight, rotate);
647
+ const reserve = normalizeReserve(options.centreReserve ?? CENTRE_RESERVE);
648
+ const grid = new Map();
649
+ for (const other of existing) {
650
+ // `layoutOf` with index 0 is enough here: a stored layout is used as-is, and
651
+ // a legacy note's derived position only has to be approximately right for
652
+ // the collision check to keep the new card off it.
653
+ const layout = other.layout ?? previewLayout(other, existing.indexOf(other));
654
+ const otherWidth = WIDTH_PX[layout.width];
655
+ const otherHeight = estimateHeight(other, layout.width);
656
+ const otherExtent = rotatedExtent(otherWidth, otherHeight, layout.rotate);
657
+ remember({
658
+ x: layout.x + otherWidth / 2 - otherExtent.width / 2,
659
+ y: layout.y + otherHeight / 2 - otherExtent.height / 2,
660
+ width: otherExtent.width,
661
+ height: otherExtent.height,
662
+ }, grid);
663
+ }
664
+ // Start just outside the reserve so the first candidate is the closest legal
665
+ // ring, then walk the same golden-angle spiral the tidy pass uses. A step near
666
+ // the card's own size keeps the search local: the answer is the first gap, not
667
+ // a far-away hole.
668
+ const step = Math.max(64, Math.sqrt(extent.width * extent.height) * 0.92);
669
+ const startRadius = Math.hypot(reserve.halfWidth, reserve.halfHeight);
670
+ const startIndex = (startRadius / step) ** 2;
671
+ for (let attempt = 0; attempt < MAX_SPOTS; attempt += 1) {
672
+ const index = startIndex + attempt;
673
+ const radius = step * Math.sqrt(index);
674
+ const theta = index * GOLDEN_ANGLE;
675
+ const candidate = {
676
+ x: Math.cos(theta) * radius - extent.width / 2,
677
+ y: Math.sin(theta) * radius - extent.height / 2,
678
+ width: extent.width,
679
+ height: extent.height,
680
+ };
681
+ if (!clearsReserve(candidate, reserve))
682
+ continue;
683
+ if (collides(candidate, grid))
684
+ continue;
685
+ return clampLayout({
686
+ x: candidate.x + extent.width / 2 - cardWidth / 2,
687
+ y: candidate.y + extent.height / 2 - cardHeight / 2,
688
+ rotate,
689
+ width,
690
+ });
691
+ }
692
+ // A wall this full is already at the note cap, so this is a safety net rather
693
+ // than a real path: place just outside the reserve on the first ring.
694
+ const fallbackRadius = startRadius + Math.max(extent.width, extent.height);
695
+ return clampLayout({
696
+ x: -cardWidth / 2,
697
+ y: -fallbackRadius - cardHeight / 2,
698
+ rotate,
699
+ width,
700
+ });
701
+ }
702
+ /**
703
+ * The footprint one note occupies on the wall, as an axis-aligned box.
704
+ *
705
+ * Exposed because the Client needs it for two things the packer already knows:
706
+ * testing whether a card is inside the current viewport, and drawing the reserve
707
+ * it must not cover.
708
+ */
709
+ export function noteBox(note, index) {
710
+ return footprintOf(note, layoutOf(note, index));
711
+ }
712
+ /**
713
+ * The footprint a note occupies at a GIVEN layout.
714
+ *
715
+ * Split out from {@link noteBox} because the useful question is often about a
716
+ * layout that is not stored yet — a planned tidy position, or a candidate spot
717
+ * for a card that does not exist. `noteBox` answers "where is this note now";
718
+ * this answers "where would it be".
719
+ */
720
+ /**
721
+ * Nudge a layout out of the centrepiece's reserved rectangle.
722
+ *
723
+ * The reserve is not only a packing rule: a user can drag a card straight over
724
+ * the quick-capture field, and a card parked there hides the wall's own controls
725
+ * behind itself. This returns the smallest translation that puts the card's
726
+ * footprint clear of the rectangle, which makes the reserve behave like a
727
+ * magnetic edge during a drag rather than a rule that is only enforced on tidy.
728
+ */
729
+ /**
730
+ * Every way out of the reserve, shortest first.
731
+ *
732
+ * Exposed separately from {@link pushOutOfReserve} because the shortest escape is
733
+ * not always usable — it can land on a neighbour — so a caller that cares about
734
+ * collisions needs the whole ordered list, not just the first answer.
735
+ */
736
+ export function escapesFromReserve(note, layout, reserve = CENTRE_RESERVE) {
737
+ const box = footprintOf(note, layout);
738
+ 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 },
743
+ ];
744
+ return moves
745
+ .sort((left, right) => (Math.abs(left.dx) + Math.abs(left.dy)) - (Math.abs(right.dx) + Math.abs(right.dy)))
746
+ .map((move) => clampLayout({ ...layout, x: layout.x + move.dx, y: layout.y + move.dy }));
747
+ }
748
+ export function pushOutOfReserve(note, layout, reserve = CENTRE_RESERVE) {
749
+ const box = footprintOf(note, layout);
750
+ if (!intersectsReserve(box, reserve))
751
+ return layout;
752
+ // Four ways out, one per edge; the shortest wins so the card slides to the
753
+ // nearest side instead of jumping around the rectangle.
754
+ 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 },
759
+ ];
760
+ let best = moves[0];
761
+ for (const move of moves) {
762
+ if (Math.abs(move.dx) + Math.abs(move.dy) < Math.abs(best.dx) + Math.abs(best.dy))
763
+ best = move;
764
+ }
765
+ return clampLayout({ ...layout, x: layout.x + best.dx, y: layout.y + best.dy });
766
+ }
767
+ export function footprintOf(note, layout) {
768
+ const cardWidth = WIDTH_PX[layout.width];
769
+ const cardHeight = estimateHeight(note, layout.width);
770
+ const extent = rotatedExtent(cardWidth, cardHeight, layout.rotate);
771
+ const centreX = layout.x + cardWidth / 2;
772
+ const centreY = layout.y + cardHeight / 2;
773
+ return { x: centreX - extent.width / 2, y: centreY - extent.height / 2, width: extent.width, height: extent.height };
774
+ }