@skillre/dsh-plugin-sticky-wall 0.5.0 → 0.6.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/README.en.md CHANGED
@@ -17,7 +17,7 @@ Non-goals: task management (no scheduling, assignment or reminders), collaborati
17
17
  - **Sidebar entry** — a "Notes" glyph in `sidebar.panellist`; clicking it swaps the centre column to the wall.
18
18
  - **Free canvas** — notes are cards on a canvas, not list rows. Position, rotation and a three-step width (small/medium/large) are note data owned by the Host, so the same wall opens with the same arrangement in another window.
19
19
  - **Drag to place** — press anywhere on a card and drag; the drop lands on the new position immediately and then writes it to the Host, so the card never snaps back first. A drag does **not** bump `updatedAt`, so tidying your desk never reshuffles a "by updated" sort.
20
- - **A wall with a middle** — "Tidy" packs every note into a **phyllotaxis ring centred on the world origin**, leaving a clear **rectangle** at the middle for the greeting and the quick-capture field; the camera opens with the whole wall framed and centred. The reserve is measured against each card's **edge** and converted from screen space at the current zoom, so zooming out widens it and no card can cover the field at any zoom.
20
+ - **A wall with a middle** — "Tidy" packs every note into a **compact composition hugging a clear rectangle** at the world origin, which is kept free for the greeting and the quick-capture field; the camera opens with the whole wall framed and centred. The packer follows the rectangle's own **contour** rather than a circle, so every card is only half its own size away from the middle: the same fourteen notes occupy 1261x705 instead of 1645x1794, and frame at **84% instead of 36%**. Each candidate slot is scored by the zoom the whole wall would need, so the result is a wide, low cluster rather than a disc that leaves the window's sides empty. The reserve is measured against each card's **edge** and stays constant in world space, so no card can cover the field at any zoom.
21
21
  - **The centre is the entry point** — the middle of the wall is an always-available capture field: type a line, press Enter, and it becomes a note without opening the form. The new note lands in the **nearest free gap** rather than being thrown off screen.
22
22
  - **The arrival is visible** — a new card pops in and holds a ring for about 0.9s; if the gap is outside the current viewport the camera **glides and zooms out just enough** to bring it into view, so a capture never leaves you guessing whether it worked.
23
23
  - **The reserve is a magnetic edge** — dragging a card onto the capture field pushes it to the nearest clear spot instead of letting it cover the input.
package/README.md CHANGED
@@ -17,7 +17,7 @@
17
17
  - **左侧栏入口**:`sidebar.panellist` 中的「便签墙」图标,点击把中央区域切换到便签墙页面。
18
18
  - **自由画布**:便签不是列表项,而是画布上的卡片。位置、旋转角、宽度三档(小/中/大)都属于便签数据,由 Host 保存;同一面墙在另一个窗口打开时摆位一致。
19
19
  - **拖动摆放**:按住卡片任意位置即可拖动,松手立刻落到新位置再把结果写回 Host(不会先弹回原处)。拖动本身**不会**改 `updatedAt`,所以「按更新」排序不会因为你整理桌面而乱掉。
20
- - **圆心构图**:整理把整面墙排成一个**以原点为中心的圆环**(向日葵螺旋排布),中心空出一块**矩形留白**给问候语和快速记录框;相机打开时把整面墙框进视野并居中。留白按**卡片边缘**判定,并按当前缩放换算成世界坐标 —— 缩小看全墙时留白会同步变大,任何缩放下都不会有卡片压住记录框。
20
+ - **圆心构图**:整理把整面墙排成**贴着中心留白的一圈紧凑构图**,中心空出一块**矩形留白**给问候语和快速记录框;相机打开时把整面墙框进视野并居中。排布不是按「圆环」而是按**留白矩形的轮廓**铺开,所以每张卡片离中心都只有它自己的一半尺寸那么远 —— 同样 14 张便签,0.5.0 的圆环要占 1645×1794、只能框到 36%,现在占 1261×705、能框到 84%。留白按**卡片边缘**判定,并在世界坐标里恒定 —— 任何缩放下都不会有卡片压住记录框。
21
21
  - **中心即入口**:便签墙正中是随时可用的快速记录框 —— 写一句按回车就落成一张便签,不用打开表单。新便签落在**离中心最近的空缺位置**,不会甩到视野之外。
22
22
  - **落点可见**:新便签生成时会在落点**弹入并亮一圈**(约 0.9 秒);如果落点在当前视野之外,相机**自动滑动并适度缩小**把它带进视野 —— 记下一条之后不用猜它到底有没有生成。
23
23
  - **留白是磁吸边界**:把卡片拖到中间记录框上会被自动推到最近的空位,不会盖住输入框。
@@ -4,7 +4,7 @@
4
4
  "verified": [
5
5
  {
6
6
  "dsh": "0.2.2-rc.1",
7
- "verifiedAt": "2026-11-08",
7
+ "verifiedAt": "2026-11-09",
8
8
  "result": "passed",
9
9
  "checks": [
10
10
  "dump-config",
@@ -38,7 +38,7 @@
38
38
  "browser-theme-switch",
39
39
  "display-detail-image",
40
40
  "display-locale-detail",
41
- "browser-canvas-centred-disc",
41
+ "browser-canvas-centred-cluster",
42
42
  "browser-camera-centre-framing",
43
43
  "browser-camera-transform-not-scroll",
44
44
  "browser-canvas-pan",
@@ -56,7 +56,7 @@
56
56
  "browser-dock-menu-show-archived",
57
57
  "browser-wall-is-a-ring"
58
58
  ],
59
- "notes": "Packed tarball 0.2.0 installed into an owned, disposable, non-Desktop web profile created from the shipped template (DSH 0.2.2-rc.1). dsh --profile <test> --dump-config composed the bundle row; a bounded real startup served the Web app; the authenticated browser transport exercised the exact /api/skillre-sticky-wall/execute route: list, create, update, move (placement echoed back without bumping updatedAt), an out-of-bounds move CLAMPED into the world while a non-finite one is refused as sticky-wall/bad-request, arrange, archive, delete, plus storage persistence of both the note and its canvas placement across a full restart, and an unauthenticated request returning 401. Cleanup stopped every owned process, removed the owned profile root and verified it was gone. The real DSH Web UI was then driven in headless Chromium against a FRESH owned profile: the 便签墙 sidebar entry appeared and selected the panel (the shell's own preview-notice mask was dismissed first, otherwise it swallows pointer input), the wall mounted with the seeded welcome note, the composer created a note whose Markdown body rendered as strong/code/list elements with no literal markers left, pin moved it first, search filtered to it, archive hid it from the default wall, the archived toggle showed it again, the note survived a full page reload, canvas cards were absolutely positioned from stored layouts, a real pointer drag wrote a new placement through the Host, 整理 repacked the wall and left NO overlapping cards, grid and list views rendered the same note set, and the note palette switched between light and dark. 24/24 UI assertions passed with no uncaught errors. Cleanup stopped the harness, killed Chrome, removed both the owned profile and the Chrome scratch directory, and verified they were gone. The display contract was verified offline: meta.detail resolves to docs/DETAIL*.md, each carries exactly one banner image at the 640x300 ratio, and both SVGs render (evidence PNGs committed). Two real defects were found and fixed during this verification: card heights were under-estimated for CJK text (so the tidy pass overlapped cards), and arrange packed only the live set (so an archived visible card stayed on top of tidied ones). A post-review pass fixed four defects the independent review found and proved each with a test that fails when the fix is reverted: (1) the height estimate charged a long title a flat 1.4 lines, so a 120-char CJK title estimated 104px against a rendered ~244px and tidy overlapped; the title and tag pills are now measured by columns. (2) The packer silently clamped cards past the world coordinate limit, pinning hundreds to one edge; the shelf width now scales with the wall and a 300-card worst case is asserted overlap-free. (3) Every drag wrote rotate: 0, destroying the tilt tidy applied; the drag now carries rotation through and the UI harness asserts it. (4) Derived preview positions were indexed off the filtered list, so legacy notes jumped while typing in the search box; the index now comes from the unfiltered snapshot. Rotation is also budgeted into the shelf gap, and the transport clamps instead of rejecting an out-of-bounds drag. 0.2.1 makes the drag direct: the canvas card no longer transitions its transform (which turned every per-frame write into an animation target and made the card trail the pointer), the drag flag moved from React state to a node attribute so pressing no longer re-renders the wall, pointer moves are coalesced into one write per animation frame, the pointer loop is registered once instead of per press, and the hover lift no longer overwrites the drag transform on the canvas. The UI harness caught a regression in that rewrite (the drop cleared the inline transform and stripped the card's tilt) and the fix is covered by a test. 0.3.0 gives the wall a centre and makes the canvas direct. Tidy now packs a phyllotaxis spiral centred on the world origin with a real spatial-grid collision check (no shelf estimate), and the finished disc is re-centred on its centre of mass; the camera opens on that middle and frames the whole wall, capped at 100%. The canvas became a clipping viewport with one transform-driven world instead of a padded scroll container, so panning and zooming cost zero React renders and dragging a card can no longer move the wall under it. Pan is drag-on-paper or wheel, zoom is ctrl/cmd+wheel anchored on the pointer, and reset re-frames the wall. The drop is optimistic: the card lands on its final world position before the Host round-trip. Cards are memoized and note objects are reconciled by identity, the per-note full-size wrapper element is gone, and body clamping follows the width preset. Verified in the real DSH Web UI with 31/31 assertions on a fresh owned profile, including a 14-note wall that tidies into a centred disc with zero overlaps (aspect ratio 0.94) and is framed at 54% by the camera, a real pointer drag that persists its placement and keeps its rotation, a real drag on empty paper that pans the camera by exactly the pointer delta, a wheel zoom that keeps the world point under the cursor fixed to under 2px, and a reset that re-frames the whole wall. The harness itself caught two real defects during this verification: the wheel listener was bound to a canvas node that did not exist yet while the wall was loading (so zoom silently did nothing), and a pan that ended inside a single animation frame was dropped entirely. Both are fixed and asserted. 0.4.0 turns the wall into a centre-anchored board. The tidy pass now packs a phyllotaxis RING that leaves a clear disc (CENTRE_RADIUS, measured to each card's nearest EDGE, not its centre) at the middle, and the re-centring shift is applied only when it preserves that reserve. The wall's middle is now its centrepiece: a time-aware greeting, a running tally and an always-available quick-capture field, rendered as a screen-space overlay that stays put under pan and zoom. The header and toolbar rows are gone — the canvas fills the whole window and every control lives in one floating dock along the bottom. Auto-framing measures the RENDERED card boxes from the DOM instead of deriving them, is capped at 100% and floored at 50% for legibility, and runs one animation frame after the reconcile so tidy frames the wall it actually produced. Canvas cards are rendered at exactly the height the Host estimated, which is what makes the packer's collision geometry true by construction. Verified in the real DSH Web UI with 36/36 assertions: the centrepiece sits at the exact viewport middle and does not move while panning, tidy leaves the centre clear with zero card overlaps, a 14-note wall tidies to a centred ring (offset 1,1; aspect 1.01), quick capture creates a note and clears the field, the canvas covers 100% of the page with a single-row dock, and a real drag, a paper pan and a pointer-anchored wheel zoom all behave. The harness caught four real defects during this pass: the wheel listener bound to a canvas that did not exist yet, a same-frame pan being dropped, tidy consuming a fit request against the pre-tidy bounds, and a fit floor that shrank a large wall to unreadable size.",
59
+ "notes": "Packed tarball 0.2.0 installed into an owned, disposable, non-Desktop web profile created from the shipped template (DSH 0.2.2-rc.1). dsh --profile <test> --dump-config composed the bundle row; a bounded real startup served the Web app; the authenticated browser transport exercised the exact /api/skillre-sticky-wall/execute route: list, create, update, move (placement echoed back without bumping updatedAt), an out-of-bounds move CLAMPED into the world while a non-finite one is refused as sticky-wall/bad-request, arrange, archive, delete, plus storage persistence of both the note and its canvas placement across a full restart, and an unauthenticated request returning 401. Cleanup stopped every owned process, removed the owned profile root and verified it was gone. The real DSH Web UI was then driven in headless Chromium against a FRESH owned profile: the 便签墙 sidebar entry appeared and selected the panel (the shell's own preview-notice mask was dismissed first, otherwise it swallows pointer input), the wall mounted with the seeded welcome note, the composer created a note whose Markdown body rendered as strong/code/list elements with no literal markers left, pin moved it first, search filtered to it, archive hid it from the default wall, the archived toggle showed it again, the note survived a full page reload, canvas cards were absolutely positioned from stored layouts, a real pointer drag wrote a new placement through the Host, 整理 repacked the wall and left NO overlapping cards, grid and list views rendered the same note set, and the note palette switched between light and dark. 24/24 UI assertions passed with no uncaught errors. Cleanup stopped the harness, killed Chrome, removed both the owned profile and the Chrome scratch directory, and verified they were gone. The display contract was verified offline: meta.detail resolves to docs/DETAIL*.md, each carries exactly one banner image at the 640x300 ratio, and both SVGs render (evidence PNGs committed). Two real defects were found and fixed during this verification: card heights were under-estimated for CJK text (so the tidy pass overlapped cards), and arrange packed only the live set (so an archived visible card stayed on top of tidied ones). A post-review pass fixed four defects the independent review found and proved each with a test that fails when the fix is reverted: (1) the height estimate charged a long title a flat 1.4 lines, so a 120-char CJK title estimated 104px against a rendered ~244px and tidy overlapped; the title and tag pills are now measured by columns. (2) The packer silently clamped cards past the world coordinate limit, pinning hundreds to one edge; the shelf width now scales with the wall and a 300-card worst case is asserted overlap-free. (3) Every drag wrote rotate: 0, destroying the tilt tidy applied; the drag now carries rotation through and the UI harness asserts it. (4) Derived preview positions were indexed off the filtered list, so legacy notes jumped while typing in the search box; the index now comes from the unfiltered snapshot. Rotation is also budgeted into the shelf gap, and the transport clamps instead of rejecting an out-of-bounds drag. 0.2.1 makes the drag direct: the canvas card no longer transitions its transform (which turned every per-frame write into an animation target and made the card trail the pointer), the drag flag moved from React state to a node attribute so pressing no longer re-renders the wall, pointer moves are coalesced into one write per animation frame, the pointer loop is registered once instead of per press, and the hover lift no longer overwrites the drag transform on the canvas. The UI harness caught a regression in that rewrite (the drop cleared the inline transform and stripped the card's tilt) and the fix is covered by a test. 0.3.0 gives the wall a centre and makes the canvas direct. Tidy now packs a phyllotaxis spiral centred on the world origin with a real spatial-grid collision check (no shelf estimate), and the finished disc is re-centred on its centre of mass; the camera opens on that middle and frames the whole wall, capped at 100%. The canvas became a clipping viewport with one transform-driven world instead of a padded scroll container, so panning and zooming cost zero React renders and dragging a card can no longer move the wall under it. Pan is drag-on-paper or wheel, zoom is ctrl/cmd+wheel anchored on the pointer, and reset re-frames the wall. The drop is optimistic: the card lands on its final world position before the Host round-trip. Cards are memoized and note objects are reconciled by identity, the per-note full-size wrapper element is gone, and body clamping follows the width preset. Verified in the real DSH Web UI with 31/31 assertions on a fresh owned profile, including a 14-note wall that tidies into a centred disc with zero overlaps (aspect ratio 0.94) and is framed at 54% by the camera, a real pointer drag that persists its placement and keeps its rotation, a real drag on empty paper that pans the camera by exactly the pointer delta, a wheel zoom that keeps the world point under the cursor fixed to under 2px, and a reset that re-frames the whole wall. The harness itself caught two real defects during this verification: the wheel listener was bound to a canvas node that did not exist yet while the wall was loading (so zoom silently did nothing), and a pan that ended inside a single animation frame was dropped entirely. Both are fixed and asserted. 0.4.0 turns the wall into a centre-anchored board. The tidy pass now packs a phyllotaxis RING that leaves a clear disc (CENTRE_RADIUS, measured to each card's nearest EDGE, not its centre) at the middle, and the re-centring shift is applied only when it preserves that reserve. The wall's middle is now its centrepiece: a time-aware greeting, a running tally and an always-available quick-capture field, rendered as a screen-space overlay that stays put under pan and zoom. The header and toolbar rows are gone — the canvas fills the whole window and every control lives in one floating dock along the bottom. Auto-framing measures the RENDERED card boxes from the DOM instead of deriving them, is capped at 100% and floored at 50% for legibility, and runs one animation frame after the reconcile so tidy frames the wall it actually produced. Canvas cards are rendered at exactly the height the Host estimated, which is what makes the packer's collision geometry true by construction. Verified in the real DSH Web UI with 36/36 assertions: the centrepiece sits at the exact viewport middle and does not move while panning, tidy leaves the centre clear with zero card overlaps, a 14-note wall tidies to a centred ring (offset 1,1; aspect 1.01), quick capture creates a note and clears the field, the canvas covers 100% of the page with a single-row dock, and a real drag, a paper pan and a pointer-anchored wheel zoom all behave. The harness caught four real defects during this pass: the wheel listener bound to a canvas that did not exist yet, a same-frame pan being dropped, tidy consuming a fit request against the pre-tidy bounds, and a fit floor that shrank a large wall to unreadable size. 0.6.0 re-verified on the same DSH line: contour packing replaces ring packing (see CHANGELOG 0.6.0); the packed 0.6.0 tarball mounts, composes, boots and passes the full API suite in an owned isolated profile, and the 38-check real-UI run passes.",
60
60
  "evidence": [
61
61
  "docs/evidence/market-install-0.2.1.json",
62
62
  "docs/evidence/ui-verification.json",
@@ -73,7 +73,7 @@
73
73
  "tests/layout.spec.ts",
74
74
  "tests/markdown.spec.tsx",
75
75
  "docs/evidence/sticky-wall-canvas-many.png",
76
- "docs/evidence/isolated-mount-0.5.0.json"
76
+ "docs/evidence/isolated-mount-0.6.0.json"
77
77
  ]
78
78
  }
79
79
  ],
package/lib/client.js CHANGED
@@ -293,6 +293,7 @@ window.__ModuleLoader__.load({
293
293
  var GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
294
294
  var PREVIEW_STEP = 196;
295
295
  var PREVIEW_NOMINAL_HEIGHT = 200;
296
+ var PREVIEW_SQUASH = 1.4;
296
297
  var PREVIEW_TILT = 4;
297
298
  function hash(text) {
298
299
  let value = 2166136261;
@@ -373,7 +374,7 @@ window.__ModuleLoader__.load({
373
374
  const radius = PREVIEW_STEP * Math.sqrt(Math.max(0, index) + (startRadius / PREVIEW_STEP) ** 2);
374
375
  const theta = index * GOLDEN_ANGLE + (unit(`${note.id}:pa`) - 0.5) * 0.55;
375
376
  return clampLayout({
376
- x: Math.cos(theta) * radius - WIDTH_PX[width] / 2,
377
+ x: Math.cos(theta) * radius * PREVIEW_SQUASH - WIDTH_PX[width] / 2,
377
378
  y: Math.sin(theta) * radius - PREVIEW_NOMINAL_HEIGHT / 2,
378
379
  rotate: (unit(`${note.id}:pr`) - 0.5) * 2 * PREVIEW_TILT,
379
380
  width
package/lib/layout.d.ts 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.
@@ -44,10 +44,14 @@ export declare function layoutOf(note: Note, index: number): NoteLayout;
44
44
  /**
45
45
  * Derived position for a note the user never placed.
46
46
  *
47
- * Index-based so two never-placed notes cannot collide, golden-angle spiralled
48
- * so the result reads as a wall scattered around the middle rather than a grid.
49
- * The height used for centring is a nominal constant, not the real estimate:
50
- * a derived position must not move when the user edits the note's text.
47
+ * Index-based so two never-placed notes cannot collide, and laid out on a
48
+ * SQUASHED spiral — the same golden-angle walk with its radius stretched along
49
+ * the x axis — so the result reads as a wide cluster around the middle rather
50
+ * than a circle or a grid. The squash matters: a circle leaves the left and
51
+ * right of a wide window empty and the camera then has to zoom out to frame the
52
+ * empty corners, which is the same "everything looks small" failure the tidy
53
+ * pass fixes. The height used for centring is a nominal constant, not the real
54
+ * estimate: a derived position must not move when the user edits the text.
51
55
  */
52
56
  export declare function previewLayout(note: Note, index: number): NoteLayout;
53
57
  /**
@@ -83,25 +87,45 @@ export interface Box {
83
87
  /**
84
88
  * Deterministic tidy arrangement for the whole wall.
85
89
  *
86
- * The wall is packed into CONCENTRIC RINGS around the world origin, outside the
87
- * rectangle the centrepiece reserves. This replaced a phyllotaxis first-fit
88
- * spiral, and the reason is measurable rather than aesthetic: a sunflower spiral
89
- * has to keep every candidate clear of a card's full bounding circle, so it
90
- * saturates at roughly a quarter of the available area and the only way to place
91
- * the next card is to walk further out. A fourteen-card wall therefore spread
92
- * over ~2700px of paper while its cards covered ~430,000px² — a sparse scatter,
93
- * not a wall. Ring packing instead computes how many cards fit on each circle
94
- * (`2πR / pitch`) and fills that circle evenly, so the same fourteen cards fit
95
- * within ~1200px and the result reads as a ring around the middle.
96
- *
97
- * Cards are sorted largest-first within the ring they land on, which is the
98
- * classic first-fit-decreasing heuristic: big cards claim the inner ring where
99
- * there is less room to waste, and small cards take up the slack outside.
90
+ * The wall is packed against a CONTOUR: the reserved rectangle's own outline,
91
+ * walked outward frame by frame. This is the third packer in this file's
92
+ * history and each replacement fixed a measured failure rather than a taste.
93
+ *
94
+ * 1. A phyllotaxis first-fit spiral had to keep every candidate clear of a
95
+ * card's full bounding circle, so it saturated at roughly a quarter of the
96
+ * available area and the only way to place the next card was to walk further
97
+ * out: fourteen cards spread over ~2700px of paper.
98
+ * 2. Concentric RINGS fixed that density but paid for it with distance. A ring
99
+ * is a circle, and the first ring's radius is the reserve's half-DIAGONAL —
100
+ * so the innermost cards sit at the rectangle's corner distance in every
101
+ * direction, including the four directions where the rectangle is only a
102
+ * card's width away. A fourteen-card wall then filled a 1645x1794 box, which
103
+ * the camera could only frame at 36%: the cards were individually packed
104
+ * tightly but the wall as a whole looked small and far away. That is the
105
+ * complaint this packer answers.
106
+ * 3. A contour hugs the rectangle instead: along the left and right edges a card
107
+ * sits one card-half-width from the reserve, and along the top and bottom one
108
+ * card-half-height from it. Every card is therefore as close to the middle as
109
+ * its own size allows, which is what makes the wall read as one composition.
110
+ *
111
+ * Two further decisions do the rest of the work:
112
+ *
113
+ * - **Score by how well the wall FRAMES, not by how free the slot is.** A
114
+ * candidate slot is judged by the zoom the whole wall would need in a
115
+ * reference viewport if the card went there. Filling a slot that widens the
116
+ * wall's box costs zoom, so the packer prefers slots that keep the box close
117
+ * to the window's own aspect — which is why the result is a wide, low cluster
118
+ * instead of a disc that leaves the left and right of the window empty.
119
+ * - **The first frame with room wins.** Walking outward frame by frame and
120
+ * taking the best-scoring slot on the first frame that has any is what makes
121
+ * every card land near the middle: an outer frame is only reached when the
122
+ * inner ones are genuinely full.
100
123
  *
101
124
  * A collision check still runs on every candidate rather than trusting the
102
125
  * height estimate, because the estimate is a line count and a code block's
103
- * padding is not something a line count can see. If a candidate does not fit the
104
- * check pushes to the next ring — the packer never produces an overlap.
126
+ * padding is not something a line count can see. The packer never produces an
127
+ * overlap, and the final centring passes repair any card the centring shift
128
+ * nudged into the reserved rectangle.
105
129
  *
106
130
  * Returns a map from note id to its new layout, for every note that needs to
107
131
  * move. Notes already at exactly that layout are omitted by the caller, so
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.
49
+ */
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.
44
62
  */
45
- const HORIZON_BIAS = 140;
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,
@@ -290,6 +313,51 @@ function nearestGap(box, grid) {
290
313
  }
291
314
  return nearest;
292
315
  }
316
+ /**
317
+ * The point at arc length `distance` around a rectangle's outline, with the
318
+ * outward normal there.
319
+ *
320
+ * This is the contour the tidy pass walks. Unlike a circle, a rectangle's
321
+ * outline stays a card's own half-size away from the reserve in every direction,
322
+ * which is what keeps the innermost cards as close to the middle as their size
323
+ * allows instead of at the rectangle's corner distance all the way round.
324
+ *
325
+ * `halfWidth`/`halfHeight` are the contour's own half-extents, so a contour is
326
+ * just "the reserve grown by one frame".
327
+ */
328
+ function contourPoint(halfWidth, halfHeight, distance) {
329
+ const width = halfWidth * 2;
330
+ const height = halfHeight * 2;
331
+ const perimeter = 2 * (width + height);
332
+ let along = ((distance % perimeter) + perimeter) % perimeter;
333
+ // Clockwise from the top-left corner: top edge, right edge, bottom, left.
334
+ if (along < width)
335
+ return { x: -halfWidth + along, y: -halfHeight, nx: 0, ny: -1 };
336
+ along -= width;
337
+ if (along < height)
338
+ return { x: halfWidth, y: -halfHeight + along, nx: 1, ny: 0 };
339
+ along -= height;
340
+ if (along < width)
341
+ return { x: halfWidth - along, y: halfHeight, nx: 0, ny: 1 };
342
+ along -= width;
343
+ return { x: -halfWidth, y: halfHeight - along, nx: -1, ny: 0 };
344
+ }
345
+ /**
346
+ * The footprint of a card whose nearest edge sits on a contour point.
347
+ *
348
+ * The reach is half the card's extent MEASURED ALONG THE NORMAL, not half its
349
+ * width: on the top and bottom edges a tilted card reaches out by half its
350
+ * height, and charging it half its width there would let it clip the reserve.
351
+ */
352
+ function boxOnContour(point, extent) {
353
+ const reach = (Math.abs(point.nx) * extent.width + Math.abs(point.ny) * extent.height) / 2;
354
+ return {
355
+ x: point.x + point.nx * reach - extent.width / 2,
356
+ y: point.y + point.ny * reach - extent.height / 2,
357
+ width: extent.width,
358
+ height: extent.height,
359
+ };
360
+ }
293
361
  /** Register one accepted footprint in every cell it touches. */
294
362
  function remember(box, grid) {
295
363
  for (let cellX = cellOf(box.x); cellX <= cellOf(box.x + box.width); cellX += 1) {
@@ -306,25 +374,45 @@ function remember(box, grid) {
306
374
  /**
307
375
  * Deterministic tidy arrangement for the whole wall.
308
376
  *
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.
377
+ * The wall is packed against a CONTOUR: the reserved rectangle's own outline,
378
+ * walked outward frame by frame. This is the third packer in this file's
379
+ * history and each replacement fixed a measured failure rather than a taste.
319
380
  *
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.
381
+ * 1. A phyllotaxis first-fit spiral had to keep every candidate clear of a
382
+ * card's full bounding circle, so it saturated at roughly a quarter of the
383
+ * available area and the only way to place the next card was to walk further
384
+ * out: fourteen cards spread over ~2700px of paper.
385
+ * 2. Concentric RINGS fixed that density but paid for it with distance. A ring
386
+ * is a circle, and the first ring's radius is the reserve's half-DIAGONAL —
387
+ * so the innermost cards sit at the rectangle's corner distance in every
388
+ * direction, including the four directions where the rectangle is only a
389
+ * card's width away. A fourteen-card wall then filled a 1645x1794 box, which
390
+ * the camera could only frame at 36%: the cards were individually packed
391
+ * tightly but the wall as a whole looked small and far away. That is the
392
+ * complaint this packer answers.
393
+ * 3. A contour hugs the rectangle instead: along the left and right edges a card
394
+ * sits one card-half-width from the reserve, and along the top and bottom one
395
+ * card-half-height from it. Every card is therefore as close to the middle as
396
+ * its own size allows, which is what makes the wall read as one composition.
397
+ *
398
+ * Two further decisions do the rest of the work:
399
+ *
400
+ * - **Score by how well the wall FRAMES, not by how free the slot is.** A
401
+ * candidate slot is judged by the zoom the whole wall would need in a
402
+ * reference viewport if the card went there. Filling a slot that widens the
403
+ * wall's box costs zoom, so the packer prefers slots that keep the box close
404
+ * to the window's own aspect — which is why the result is a wide, low cluster
405
+ * instead of a disc that leaves the left and right of the window empty.
406
+ * - **The first frame with room wins.** Walking outward frame by frame and
407
+ * taking the best-scoring slot on the first frame that has any is what makes
408
+ * every card land near the middle: an outer frame is only reached when the
409
+ * inner ones are genuinely full.
323
410
  *
324
411
  * A collision check still runs on every candidate rather than trusting the
325
412
  * 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.
413
+ * padding is not something a line count can see. The packer never produces an
414
+ * overlap, and the final centring passes repair any card the centring shift
415
+ * nudged into the reserved rectangle.
328
416
  *
329
417
  * Returns a map from note id to its new layout, for every note that needs to
330
418
  * move. Notes already at exactly that layout are omitted by the caller, so
@@ -334,8 +422,8 @@ export function arrangeLayouts(notes, options = {}) {
334
422
  const placed = new Map();
335
423
  if (notes.length === 0)
336
424
  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.
425
+ // Decide each card's rotation and footprint up front: the contour offsets and
426
+ // the collision test both work on the rotated box.
339
427
  const items = notes.map((note) => {
340
428
  const width = note.layout?.width ?? previewWidth(note.id);
341
429
  const cardWidth = WIDTH_PX[width];
@@ -345,13 +433,10 @@ export function arrangeLayouts(notes, options = {}) {
345
433
  return { note, width, cardWidth, cardHeight, rotate, extent };
346
434
  });
347
435
  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.
436
+ // Largest first: the classic first-fit-decreasing heuristic. Big cards claim
437
+ // the inner frames where there is less room to waste, and small cards fill the
438
+ // gaps they leave. Ties break on id so the result stays deterministic across
439
+ // two windows.
355
440
  const ordered = [...items].sort((left, right) => {
356
441
  const areaLeft = left.extent.width * left.extent.height;
357
442
  const areaRight = right.extent.width * right.extent.height;
@@ -359,238 +444,191 @@ export function arrangeLayouts(notes, options = {}) {
359
444
  return areaRight - areaLeft;
360
445
  return left.note.id.localeCompare(right.note.id);
361
446
  });
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
447
  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;
448
+ // The wall's box so far, extended by each accepted card. The framing score
449
+ // needs it, and it is cheaper to maintain than to recompute per candidate.
450
+ let wall = null;
451
+ const extendWall = (box) => wall === null
452
+ ? { x: box.x, y: box.y, width: box.width, height: box.height }
453
+ : {
454
+ x: Math.min(wall.x, box.x),
455
+ y: Math.min(wall.y, box.y),
456
+ width: Math.max(wall.x + wall.width, box.x + box.width) - Math.min(wall.x, box.x),
457
+ height: Math.max(wall.y + wall.height, box.y + box.height) - Math.min(wall.y, box.y),
458
+ };
419
459
  /**
420
- * Radius of one ring, in world pixels.
460
+ * The best slot for one card, or null when no contour has room.
421
461
  *
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.
462
+ * `soft` is used for the repair passes: a repair may not disturb a card that
463
+ * already sits legally, so it is asked to stay a hair further out, which keeps
464
+ * the rounding of a stored position from reading as a fresh violation.
424
465
  */
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) {
466
+ const pick = (item, settled, soft, seed) => {
437
467
  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.
468
+ for (let frame = 0; frame < MAX_FRAMES; frame += 1) {
469
+ const halfWidth = soft.halfWidth + frame * FRAME_STEP;
470
+ // Grow the height FASTER than the width until the contour itself is as wide
471
+ // as the framing rectangle. Growing both equally makes the left and right
472
+ // edges (already the reserve's long ones) longer still, so every extra frame
473
+ // adds room for a vertical column and none for a horizontal row: the wall
474
+ // grew into an 1114x966 block that framed at 69% where a window-shaped one
475
+ // frames at 90%. A contour whose own aspect matches the window puts the
476
+ // spare slots on the short edges, which is where they are useful.
477
+ const halfHeight = Math.max(soft.halfHeight, halfWidth / FRAMING_ASPECT);
478
+ const perimeter = 4 * (halfWidth + halfHeight);
479
+ const slots = Math.min(MAX_SLOTS, Math.max(12, Math.round(perimeter / CONTOUR_STEP)));
480
+ // A deterministic phase per frame, so two frames' slots do not line up and
481
+ // the same wall always packs to the same coordinates.
482
+ const phase = unit(`${seed}:f${frame}`) * perimeter;
454
483
  let best = null;
455
484
  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;
485
+ const candidate = boxOnContour(contourPoint(halfWidth, halfHeight, phase + (slot / slots) * perimeter), extent);
467
486
  if (!clearsReserve(candidate, reserve))
468
487
  continue;
469
- if (collides(candidate, grid))
488
+ if (collides(candidate, settled))
470
489
  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;
490
+ const next = extendWall(candidate);
491
+ // How much this wall would have to shrink to fit the reference viewport.
492
+ // Higher is better; it is the number the camera will actually apply.
493
+ const score = Math.min(1, FRAMING_WIDTH / Math.max(1, next.width), FRAMING_HEIGHT / Math.max(1, next.height));
494
+ // HOW WINDOW-SHAPED the wall becomes, as a log ratio so being too wide
495
+ // and being too tall are penalised equally. This is the tie-break, and it
496
+ // is what actually produces a wide wall: for the first several cards
497
+ // almost every slot frames at the same zoom, because the wall is still
498
+ // smaller than the viewport either way. Without a shape preference the
499
+ // tie fell to placement noise, the wall grew equally in all four
500
+ // directions, and the result was a tall block that framed at 69% where a
501
+ // wide one frames at 90%.
502
+ const shape = Math.abs(Math.log((next.width + 1) / (next.height + 1) / FRAMING_ASPECT));
503
+ // How far this slot sits from the cards already placed. Even distribution
504
+ // is the point of a wall: a slot that hugs one neighbour leaves a hole
505
+ // elsewhere that the NEXT card then has to reach across.
506
+ const clearance = nearestGap(candidate, settled);
507
+ // Nearest-the-origin last, because that is the middle the camera frames.
508
+ const offset = Math.hypot(next.x + next.width / 2, next.y + next.height / 2);
509
+ const better = best === null ||
510
+ score > best.score + 1e-9 ||
511
+ (Math.abs(score - best.score) <= 1e-9 &&
512
+ (shape < best.shape - 1e-9 ||
513
+ (Math.abs(shape - best.shape) <= 1e-9 &&
514
+ (clearance > best.clearance + 1e-9 ||
515
+ (Math.abs(clearance - best.clearance) <= 1e-9 && offset < best.offset)))));
516
+ if (better)
517
+ best = { box: candidate, score, shape, clearance, offset };
490
518
  }
519
+ // The first frame with ANY free slot wins. Walking further out would find
520
+ // roomier slots, and taking them is exactly how a wall grows into a sparse
521
+ // scatter instead of a composition.
522
+ if (best !== null)
523
+ return best.box;
491
524
  }
492
- if (box === null) {
525
+ return null;
526
+ };
527
+ for (const item of ordered) {
528
+ const box = pick(item, grid, reserve, item.note.id) ?? {
493
529
  // Unreachable for a wall inside the note cap; the fallback exists so the
494
530
  // 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
- }
531
+ x: -item.extent.width / 2,
532
+ y: -9000,
533
+ width: item.extent.width,
534
+ height: item.extent.height,
535
+ };
498
536
  remember(box, grid);
537
+ wall = extendWall(box);
499
538
  // The rotated footprint is centred on the card, so the card's own top-left
500
539
  // is the footprint centre minus the UNROTATED half size.
501
540
  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,
541
+ x: box.x + item.extent.width / 2 - item.cardWidth / 2,
542
+ y: box.y + item.extent.height / 2 - item.cardHeight / 2,
504
543
  rotate: item.rotate,
505
544
  width: item.width,
506
545
  }));
507
546
  }
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]) => {
547
+ /**
548
+ * Centre the finished wall on the world origin.
549
+ *
550
+ * This is not cosmetic — it is what makes the reserved middle correct. The
551
+ * centrepiece is a SCREEN-space block at the viewport's middle, and the camera
552
+ * frames the wall's BOUNDING BOX centre at that same middle. So the world
553
+ * rectangle the packer keeps clear is only under the field if the wall's box is
554
+ * centred on the origin. Leave the offset in and a tidy wall's capture field
555
+ * drifts off its own reserve by however far the box was off.
556
+ *
557
+ * It alternates the shift with a repair, because a shift can push a card into
558
+ * the reserve: the repair displaces the wall again, so the shift has to be
559
+ * re-measured. A single pass left a 20-card wall ~56px off centre.
560
+ */
561
+ const footprintOfId = (id, layout) => {
520
562
  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) {
563
+ if (note === undefined)
564
+ return { x: layout.x, y: layout.y, width: 0, height: 0 };
565
+ return footprintOf(note, layout);
566
+ };
567
+ const wallBounds = () => {
568
+ let minX = Number.POSITIVE_INFINITY;
569
+ let minY = Number.POSITIVE_INFINITY;
570
+ let maxX = Number.NEGATIVE_INFINITY;
571
+ let maxY = Number.NEGATIVE_INFINITY;
551
572
  for (const [id, layout] of placed) {
552
- placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
573
+ const box = footprintOfId(id, layout);
574
+ minX = Math.min(minX, box.x);
575
+ minY = Math.min(minY, box.y);
576
+ maxX = Math.max(maxX, box.x + box.width);
577
+ maxY = Math.max(maxY, box.y + box.height);
553
578
  }
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
- }
579
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
580
+ };
581
+ /** Repair every card that sits in the reserve, one at a time, against the rest. */
582
+ const repairReserve = (soft) => {
583
+ const violators = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve));
584
+ if (violators.length === 0)
585
+ return;
586
+ const settled = new Map(placed);
587
+ for (const [id] of violators)
588
+ settled.delete(id);
589
+ const repairGrid = new Map();
590
+ for (const [id, layout] of settled)
591
+ remember(footprintOfId(id, layout), repairGrid);
592
+ for (const [id] of violators) {
593
+ const item = items.find((candidate) => candidate.note.id === id);
594
+ if (item === undefined)
595
+ continue;
596
+ const box = pick(item, repairGrid, soft, `${id}:repair`);
597
+ if (box === null)
598
+ continue;
599
+ remember(box, repairGrid);
600
+ placed.set(id, clampLayout({
601
+ x: box.x + item.extent.width / 2 - item.cardWidth / 2,
602
+ y: box.y + item.extent.height / 2 - item.cardHeight / 2,
603
+ rotate: item.rotate,
604
+ width: item.width,
605
+ }));
593
606
  }
607
+ };
608
+ // Ask the repair to stay a hair clear, so a card packed exactly on the boundary
609
+ // is not re-placed by rounding noise.
610
+ const softReserve = { halfWidth: reserve.halfWidth + 1.5, halfHeight: reserve.halfHeight + 1.5 };
611
+ for (let pass = 0; pass < 6; pass += 1) {
612
+ const box = wallBounds();
613
+ const shiftX = box.x + box.width / 2;
614
+ const shiftY = box.y + box.height / 2;
615
+ if (Math.abs(shiftX) < 0.5 && Math.abs(shiftY) < 0.5)
616
+ break;
617
+ for (const [id, layout] of placed) {
618
+ placed.set(id, clampLayout({ ...layout, x: layout.x - shiftX, y: layout.y - shiftY }));
619
+ }
620
+ repairReserve(softReserve);
621
+ }
622
+ // The loop above can exit with violators left over: its last repair is itself
623
+ // displaced by the shift it was responding to. Settle them without shifting.
624
+ for (let pass = 0; pass < 24; pass += 1) {
625
+ const before = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve)).length;
626
+ if (before === 0)
627
+ break;
628
+ repairReserve(softReserve);
629
+ const after = [...placed].filter(([id, layout]) => !clearsReserve(footprintOfId(id, layout), reserve)).length;
630
+ if (after >= before)
631
+ break;
594
632
  }
595
633
  return placed;
596
634
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skillre/dsh-plugin-sticky-wall",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "便签墙:DSH 侧栏的自由画布便签板,可拖动摆放、一键整理,正文按 Markdown 渲染",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",