@celestia-island/hikari 0.55.472 → 0.55.473

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.
@@ -57,7 +57,31 @@ export declare function needsAnchorCorrection(renderedTop: number, anchorTop: nu
57
57
  * no-op — a block that never animates never drifts, so there is nothing
58
58
  * to correct.
59
59
  */
60
- export declare function useAnchoredTop(target: Ref<HTMLElement | null>, options?: {
60
+ export interface UseAnchoredTopOptions {
61
+ /** Gate the correction (a surface that is not in its anchored mode). */
61
62
  enabled?: () => boolean;
62
- }): void;
63
+ /** Where the correction goes, in px (0 = no correction active).
64
+ *
65
+ * Defaults to an inline `transform: translateY(…)` on the target —
66
+ * right for a host that owns nothing else on that element. A surface
67
+ * that already animates `transform` (HkModal's open/close ride) or
68
+ * composes its offset through a CSS custom property supplies its own
69
+ * writer instead, so the anchor and the surface's own choreography
70
+ * never fight over one property. */
71
+ apply?: (shiftPx: number) => void;
72
+ }
73
+ export interface AnchoredTopHandle {
74
+ /** Drop the correction and adopt the element's current top as the new
75
+ * anchor (a reopen/remount edge). The sink always runs with 0, so a
76
+ * surface whose offset is not a DOM transform still gets its clear; the
77
+ * re-base itself is a no-op when the element is gone.
78
+ *
79
+ * ⚠️ Only call this on a frame at REST: the re-base adopts whatever top
80
+ * the element has at that instant, so calling it mid-morph pins the
81
+ * anchor to a transient geometry and the loop then bakes that transient
82
+ * into the resting position. A host that can be mid-motion (HkModal,
83
+ * during a height transition) must defer until it settles. */
84
+ reset: () => void;
85
+ }
86
+ export declare function useAnchoredTop(target: Ref<HTMLElement | null | undefined>, options?: UseAnchoredTopOptions): AnchoredTopHandle;
63
87
  export default useAnchoredTop;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celestia-island/hikari",
3
- "version": "0.55.472",
3
+ "version": "0.55.473",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Hikari UI library, Vue 3 runtime — one design system for Vue 3 and Rust/WASM applications",
@@ -309,8 +309,14 @@ const RIDE = [
309
309
 
310
310
  const child = (parent: MockElement, cls: string): MockElement => el([cls], parent);
311
311
 
312
+ // The centering translate carries TWO offsets: the drag shift and the
313
+ // top-edge anchor (useAnchoredTop — a centred frame lifts by half of every
314
+ // height growth, so the anchor folds the measured drift back). Both compose
315
+ // on the individual `translate` property, never on `transform`: the ride
316
+ // below animates `transform` outright.
312
317
  const CENTERING_TRANSLATE =
313
- "calc(-50% + var(--hk-modal-shift-x, 0px)) calc(-50% + var(--hk-modal-shift-y, 0px))";
318
+ "calc(-50% + var(--hk-modal-shift-x, 0px))"
319
+ + " calc(-50% + var(--hk-modal-shift-y, 0px) + var(--hk-modal-anchor-y, 0px))";
314
320
 
315
321
  /** Frame ride states: the centering translate lives on the INDIVIDUAL
316
322
  * `translate` property (never animated, re-resolves against the live box
@@ -141,8 +141,12 @@
141
141
  // order — center, then ride legs, drag shift included — is
142
142
  // unchanged. The ≤767px sheet block neutralizes it alongside its own
143
143
  // `transform: none`.)
144
+ // --hk-modal-anchor-y is the TOP-EDGE anchor (useAnchoredTop): the frame
145
+ // is centred, so a height morph would otherwise lift the whole window by
146
+ // half the growth. It composes here rather than on `transform` because the
147
+ // open/close ride owns that property outright (see the note above).
144
148
  translate: calc(-50% + var(--hk-modal-shift-x, 0px))
145
- calc(-50% + var(--hk-modal-shift-y, 0px));
149
+ calc(-50% + var(--hk-modal-shift-y, 0px) + var(--hk-modal-anchor-y, 0px));
146
150
  width: 100%;
147
151
  // Reasonable upper bound: a 2734px-wide viewport with width:100% gives
148
152
  // a modal frame wider than the content can usefully fill — the body
@@ -1044,3 +1044,357 @@ describe("HkModal blur plate", () => {
1044
1044
  }
1045
1045
  });
1046
1046
  });
1047
+
1048
+ describe("HkModal top-edge anchor (centred frame must not fly)", () => {
1049
+ // 2026-11-23 user direction: "where the content can change inside the
1050
+ // card, do not let the whole card fly." The frame is centred by
1051
+ // `translate: -50% -50%`, so a height morph of Δ lifts the whole window
1052
+ // by Δ/2; the anchor folds the measured drift into --hk-modal-anchor-y.
1053
+ function mountModal() {
1054
+ const container = document.createElement("div");
1055
+ document.body.appendChild(container);
1056
+ containers.push(container);
1057
+ const open = ref(true);
1058
+ const Wrapper = defineComponent({
1059
+ setup() {
1060
+ return () =>
1061
+ h(HkModal, { modelValue: open.value, title: "Anchor" },
1062
+ { default: () => h("div", "content") });
1063
+ },
1064
+ });
1065
+ const app = createApp(Wrapper);
1066
+ mounts.push(app);
1067
+ app.mount(container);
1068
+ return {
1069
+ container,
1070
+ open,
1071
+ frame: document.querySelector(".hk-modal-content") as HTMLElement,
1072
+ };
1073
+ }
1074
+
1075
+ it("folds a centred height drift into the anchor variable", async () => {
1076
+ // A stubbed observer + a rect that composes the frame's own anchor
1077
+ // variable (an engine reports the PAINTED box) makes the closed loop
1078
+ // observable without a browser.
1079
+ const callbacks: Array<() => void> = [];
1080
+ vi.stubGlobal("ResizeObserver", class {
1081
+ private readonly cb: () => void;
1082
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
1083
+ observe() {}
1084
+ disconnect() {}
1085
+ unobserve() {}
1086
+ });
1087
+ const top = { value: 200 };
1088
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
1089
+ function (this: Element) {
1090
+ const el = this as HTMLElement;
1091
+ const own = el.style?.getPropertyValue("--hk-modal-anchor-y") ?? "";
1092
+ const shift = Number(/(-?[\d.]+)px/.exec(own)?.[1] ?? 0);
1093
+ const rendered = top.value + shift;
1094
+ return {
1095
+ top: rendered, left: 0, bottom: rendered, right: 0,
1096
+ width: 0, height: 0, x: 0, y: rendered, toJSON: () => ({}),
1097
+ } as DOMRect;
1098
+ },
1099
+ );
1100
+ try {
1101
+ const { frame } = mountModal();
1102
+ for (let i = 0; i < 6; i++) await nextTick();
1103
+ expect(frame).not.toBeNull();
1104
+ // A centred growth lifted the top edge by 20px.
1105
+ top.value = 180;
1106
+ for (const cb of callbacks) cb();
1107
+ await nextTick();
1108
+ // MUT:modal-no-anchor (dropping the useAnchoredTop wiring leaves the
1109
+ // variable unset and this goes red).
1110
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("20px");
1111
+ } finally {
1112
+ vi.unstubAllGlobals();
1113
+ vi.restoreAllMocks();
1114
+ }
1115
+ });
1116
+
1117
+ it("never writes the anchor on the mobile sheet branch", async () => {
1118
+ // ≤767px the frame is a BOTTOM sheet: growth already goes upward from
1119
+ // a fixed bottom edge, so anchoring the TOP would invert the motion.
1120
+ const previousWidth = window.innerWidth;
1121
+ const callbacks: Array<() => void> = [];
1122
+ vi.stubGlobal("ResizeObserver", class {
1123
+ private readonly cb: () => void;
1124
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
1125
+ observe() {}
1126
+ disconnect() {}
1127
+ unobserve() {}
1128
+ });
1129
+ const top = { value: 200 };
1130
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
1131
+ () => ({ top: top.value, left: 0, bottom: top.value, right: 0,
1132
+ width: 0, height: 0, x: 0, y: top.value, toJSON: () => ({}) }) as DOMRect,
1133
+ );
1134
+ try {
1135
+ (window as { innerWidth: number }).innerWidth = 500;
1136
+ const { frame } = mountModal();
1137
+ for (let i = 0; i < 6; i++) await nextTick();
1138
+ top.value = 180;
1139
+ for (const cb of callbacks) cb();
1140
+ await nextTick();
1141
+ // MUT:modal-anchor-on-sheet (dropping the enabled gate writes the
1142
+ // variable on the sheet branch and this goes red).
1143
+
1144
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1145
+ } finally {
1146
+ (window as { innerWidth: number }).innerWidth = previousWidth;
1147
+ vi.unstubAllGlobals();
1148
+ vi.restoreAllMocks();
1149
+ }
1150
+ });
1151
+
1152
+ it("drops the offset on the next open (reopen never inherits the lift)", async () => {
1153
+ // The anchor holds after a morph settles (documented), so a dialog that
1154
+ // grew once is standing offset. The open edge must clear it, or the
1155
+ // SECOND open starts lifted.
1156
+ // MUT:modal-anchor-no-reopen-reset (deleting `anchor.reset()` at the
1157
+ // open edge leaves the variable set across close→open; this goes red).
1158
+ const callbacks: Array<() => void> = [];
1159
+ vi.stubGlobal("ResizeObserver", class {
1160
+ private readonly cb: () => void;
1161
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
1162
+ observe() {}
1163
+ disconnect() {}
1164
+ unobserve() {}
1165
+ });
1166
+ const top = { value: 200 };
1167
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
1168
+ function (this: Element) {
1169
+ const el = this as HTMLElement;
1170
+ const own = el.style?.getPropertyValue("--hk-modal-anchor-y") ?? "";
1171
+ const shift = Number(/(-?[\d.]+)px/.exec(own)?.[1] ?? 0);
1172
+ const rendered = top.value + shift;
1173
+ return { top: rendered, left: 0, bottom: rendered, right: 0,
1174
+ width: 0, height: 0, x: 0, y: rendered, toJSON: () => ({}) } as DOMRect;
1175
+ },
1176
+ );
1177
+ try {
1178
+ const { frame, open } = mountModal();
1179
+ for (let i = 0; i < 8; i++) await nextTick();
1180
+ top.value = 180;
1181
+ for (const cb of callbacks) cb();
1182
+ await nextTick();
1183
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("20px");
1184
+
1185
+ // CLOSE → OPEN as an INTERRUPT (one tick apart): the frame node
1186
+ // survives the abortive leave, so a stale offset would ride into the
1187
+ // next cycle. This is the only reachable path on which the open-edge
1188
+ // reset can matter — a full close unmounts the node and the variable
1189
+ // dies with it (verified: the same assertion without the reset and
1190
+ // with a settled close passes either way).
1191
+ open.value = false;
1192
+ await nextTick();
1193
+ open.value = true;
1194
+ for (let i = 0; i < 40; i++) await nextTick();
1195
+ const reopened = (document.querySelector(".hk-modal-content")
1196
+ ?? frame) as HTMLElement;
1197
+ expect(reopened.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1198
+ } finally {
1199
+ vi.unstubAllGlobals();
1200
+ vi.restoreAllMocks();
1201
+ }
1202
+ });
1203
+
1204
+ it("re-anchors only after the settle window has passed (controlled clock)", async () => {
1205
+ // The floor VALUE is what R7 flagged unpinnable: with real (sub-ms)
1206
+ // happy-dom rAF, any floor in 0-320 ms collapses into the same sample.
1207
+ // With the clock and the rAF queue under test control, the floor is
1208
+ // directly observable: inside the window the armed correction survives;
1209
+ // past it the re-anchor re-bases onto the landed top.
1210
+ // MUT:modal-settle-floor (setting the settle floor to 160 makes the
1211
+ // probe reset at the now=200 step and this goes red at the second
1212
+ // assertion).
1213
+ const callbacks: Array<() => void> = [];
1214
+ const rafQueue: Array<() => void> = [];
1215
+ vi.stubGlobal("ResizeObserver", class {
1216
+ private readonly cb: () => void;
1217
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
1218
+ observe() {}
1219
+ disconnect() {}
1220
+ unobserve() {}
1221
+ });
1222
+ vi.stubGlobal("requestAnimationFrame", (cb: () => void) => {
1223
+ rafQueue.push(cb);
1224
+ return rafQueue.length;
1225
+ });
1226
+ vi.stubGlobal("cancelAnimationFrame", () => {});
1227
+ const clock = { value: 0 };
1228
+ vi.spyOn(performance, "now").mockImplementation(() => clock.value);
1229
+ const top = { value: 200 };
1230
+ const height = { value: 200 };
1231
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
1232
+ function (this: Element) {
1233
+ const el = this as HTMLElement;
1234
+ const own = el.style?.getPropertyValue("--hk-modal-anchor-y") ?? "";
1235
+ const m = /(-?([\d.]+))px/.exec(own);
1236
+ const shift = m ? Number(m[1]) : 0;
1237
+ const rendered = top.value + shift;
1238
+ return { top: rendered, left: 0, bottom: rendered, right: 0,
1239
+ width: 0, height: height.value, x: 0, y: rendered,
1240
+ toJSON: () => ({}) } as DOMRect;
1241
+ },
1242
+ );
1243
+ const drive = (at: number) => {
1244
+ clock.value = at;
1245
+ const queued = rafQueue.splice(0);
1246
+ const run = () => { for (const cb of queued) cb(); return nextTick(); };
1247
+ return run();
1248
+ };
1249
+ try {
1250
+ (window as { innerWidth: number }).innerWidth = 1200;
1251
+ const { frame, open } = mountModal();
1252
+ open.value = true;
1253
+ for (let i = 0; i < 6; i++) await nextTick();
1254
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1255
+
1256
+ (window as { innerWidth: number }).innerWidth = 500;
1257
+ window.dispatchEvent(new Event("resize"));
1258
+ for (let i = 0; i < 4; i++) await nextTick();
1259
+ (window as { innerWidth: number }).innerWidth = 1200;
1260
+ window.dispatchEvent(new Event("resize"));
1261
+ for (let i = 0; i < 4; i++) await nextTick();
1262
+
1263
+ // The height is deliberately left UNCHANGED here (the stability probe
1264
+ // is satisfied from its second frame), so the ONLY variable left in
1265
+ // the wait is elapsed vs the settle floor.
1266
+ top.value = 170;
1267
+ for (const cb of callbacks) cb();
1268
+ await nextTick();
1269
+ // The armed correction folded in: +30 (anchor at the pre-crossing
1270
+ // 200; the lift to 170 needs the frame painted 30px LOWER). Written
1271
+ // IMMEDIATELY — the drift cb runs regardless of the pending probe.
1272
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("30px");
1273
+
1274
+ // Inside the settle window (now=200 < 320): a probe frame runs but
1275
+ // the re-anchor must not fire; the correction stays. MUT:modal-settle-
1276
+ // floor (a 160 ms floor makes the probe re-anchor HERE, zeroing the
1277
+ // correction to "" — this is the assertion that pins the floor value).
1278
+ await drive(200);
1279
+ await drive(200);
1280
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("30px");
1281
+
1282
+ await drive(400);
1283
+
1284
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1285
+ } finally {
1286
+ vi.unstubAllGlobals();
1287
+ vi.restoreAllMocks();
1288
+ }
1289
+ });
1290
+
1291
+ it("clears the offset when the dialog becomes the mobile sheet", async () => {
1292
+ // The gate alone only FREEZES the loop: an offset written on desktop
1293
+ // survived into the sheet branch and was re-applied stale on the way
1294
+ // back (R2 finding). The breakpoint watch clears it.
1295
+ // MUT:modal-anchor-sheet-roundtrip (dropping `watch(sheetMobile, …)`
1296
+ // leaves the variable set and this goes red).
1297
+ const previousWidth = window.innerWidth;
1298
+ const callbacks: Array<() => void> = [];
1299
+ vi.stubGlobal("ResizeObserver", class {
1300
+ private readonly cb: () => void;
1301
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
1302
+ observe() {}
1303
+ disconnect() {}
1304
+ unobserve() {}
1305
+ });
1306
+ const top = { value: 200 };
1307
+ /** The frame's live height — the stability probe's only clock. */
1308
+ const morphHeight = { value: 200 };
1309
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
1310
+ function (this: Element) {
1311
+ const el = this as HTMLElement;
1312
+ const own = el.style?.getPropertyValue("--hk-modal-anchor-y") ?? "";
1313
+ const shift = Number(/(-?[\d.]+)px/.exec(own)?.[1] ?? 0);
1314
+ const rendered = top.value + shift;
1315
+ return { top: rendered, left: 0, bottom: rendered, right: 0,
1316
+ width: 0, height: morphHeight.value, x: 0, y: rendered,
1317
+ toJSON: () => ({}) } as DOMRect;
1318
+ },
1319
+ );
1320
+ try {
1321
+ (window as { innerWidth: number }).innerWidth = 1200;
1322
+ const { frame } = mountModal();
1323
+ for (let i = 0; i < 6; i++) await nextTick();
1324
+ top.value = 180;
1325
+ for (const cb of callbacks) cb();
1326
+ await nextTick();
1327
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("20px");
1328
+
1329
+ // Cross into the sheet branch: the desktop offset must go.
1330
+ // useBreakpoint tracks the width through a `resize` listener, so the
1331
+ // probe must dispatch one — assigning innerWidth alone is invisible.
1332
+ (window as { innerWidth: number }).innerWidth = 500;
1333
+ window.dispatchEvent(new Event("resize"));
1334
+ for (let i = 0; i < 6; i++) await nextTick();
1335
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1336
+
1337
+ // …and coming back must not resurrect it.
1338
+ (window as { innerWidth: number }).innerWidth = 1200;
1339
+ window.dispatchEvent(new Event("resize"));
1340
+ for (let i = 0; i < 6; i++) await nextTick();
1341
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1342
+
1343
+ // R4's kill case: the frame is MID-MORPH when the crossing arrives.
1344
+ // A re-base at that instant adopts a transient top, and the loop then
1345
+ // bakes it into the resting position (a visible snap-then-lift).
1346
+ // `data-hk-morphing` is useSizeMorph's own marker, so the way-out
1347
+ // re-anchor defers until the frame settles.
1348
+ // The morph is LIVE (the frame's own height is still changing) and has
1349
+ // already moved the top edge — anything that re-bases NOW records a
1350
+ // geometry the frame will not rest at.
1351
+ morphHeight.value = 300;
1352
+ (window as { innerWidth: number }).innerWidth = 500;
1353
+ window.dispatchEvent(new Event("resize"));
1354
+ for (let i = 0; i < 6; i++) await nextTick();
1355
+ (window as { innerWidth: number }).innerWidth = 1200;
1356
+ window.dispatchEvent(new Event("resize"));
1357
+ // The drift fires MID-MORPH, just after the way-out crossing (the
1358
+ // height is still stepping; the top is still at the sheet-leg 180).
1359
+ // The fixed shape's deferred re-anchor has NOT fired yet (we are
1360
+ // inside the 220 ms settle window), so the anchor is still armed at
1361
+ // the pre-crossing 200 and a lift to 170 folds in as -30. The naive
1362
+ // shape reset at the crossing (adopting the transient 180) — its own
1363
+ // arms are already wrong.
1364
+ await new Promise((r) => setTimeout(r, 60));
1365
+ top.value = 170;
1366
+ for (const cb of callbacks) cb();
1367
+ await nextTick();
1368
+ // The crossing back lands MID-MORPH (the height is still stepping and
1369
+ // the frame still sits at the sheet-leg top). Two things happen at a
1370
+ // real crossing: the hook's own resize re-base adopts the geometry the
1371
+ // frame has at that instant (a viewport change legitimately moves the
1372
+ // block), and the deferred anchor reset re-bases again once the frame
1373
+ // has settled. The settle window is what keeps that second re-base
1374
+ // honest: a naive immediate reset re-bases on the TRANSIENT top and
1375
+ // the landed geometry then disagrees with it by 10px.
1376
+ top.value = 200;
1377
+ morphHeight.value = 400;
1378
+ await new Promise((r) => setTimeout(r, 320));
1379
+ for (let i = 0; i < 6; i++) await nextTick();
1380
+ // Settled: the anchor re-based onto the landed top, so no correction.
1381
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("");
1382
+
1383
+ // A fresh drift after the crossing corrects from the LANDED anchor:
1384
+ // 200 → 170 is a 30px lift the loop folds back in. MUT:modal-crossing-
1385
+ // rebase-midmorph (a naive immediate reset at the crossing re-based on
1386
+ // the transient 180 and leaves only 10px here).
1387
+ top.value = 170;
1388
+ for (const cb of callbacks) cb();
1389
+ await nextTick();
1390
+ // MUT:modal-crossing-rebase-midmorph (a naive immediate reset at the
1391
+ // crossing re-bases on the transient 180 and lands 10px here instead
1392
+ // of 30px).
1393
+ expect(frame.style.getPropertyValue("--hk-modal-anchor-y")).toBe("30px");
1394
+ } finally {
1395
+ (window as { innerWidth: number }).innerWidth = previousWidth;
1396
+ vi.unstubAllGlobals();
1397
+ vi.restoreAllMocks();
1398
+ }
1399
+ });
1400
+ });
@@ -14,6 +14,7 @@ import { useSurfaceTransition } from "../composables/useSurfaceTransition";
14
14
  import { useSurfaceMachine } from "../composables/useSurfaceMachine";
15
15
  import { useSurfaceContentHold } from "../composables/useSurfaceContentHold";
16
16
  import { useSizeMorph, type RideEntry } from "../composables/useSizeMorph";
17
+ import { useAnchoredTop } from "../composables/useAnchoredTop";
17
18
 
18
19
  import { STEPFLOW_SWAP_EVENT } from "./HkStepFlow";
19
20
 
@@ -138,6 +139,23 @@ const FOCUSABLE_SELECTOR =
138
139
  'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';
139
140
 
140
141
 
142
+ /**
143
+ * Crossing re-anchor timing (the top-edge anchor, see useAnchoredTop):
144
+ *
145
+ * - `CROSSING_SETTLE_MS` — how long a breakpoint crossing waits before
146
+ * re-anchoring the frame. The worst case is useSizeMorph's observer
147
+ * debounce (150 ms) plus the height transition it then starts
148
+ * (`--duration-fast`, 150 ms): inside those ~300 ms the frame's height is
149
+ * still moving, and a re-base would adopt a transient geometry. 320 ms
150
+ * covers both plus a small margin; the height-stability probe extends the
151
+ * wait on its own if the morph ends later than that.
152
+ * - `CROSSING_SETTLE_MAX_MS` — hard wall-time cap (2 s) for a frame that
153
+ * never settles for an unrelated reason; a stale anchor is the lesser
154
+ * evil vs a silently disarmed one.
155
+ */
156
+ const CROSSING_SETTLE_MS = 320;
157
+ const CROSSING_SETTLE_MAX_MS = 2000;
158
+
141
159
  export default defineComponent({
142
160
  name: "HkModal",
143
161
  props: {
@@ -369,6 +387,111 @@ export default defineComponent({
369
387
  },
370
388
  });
371
389
 
390
+ /**
391
+ * Top-edge anchoring (2026-11-23 user direction: "where the content
392
+ * can change inside the card, do not let the whole card fly").
393
+ *
394
+ * The frame is centred by `top: 50%; translate: -50% -50%`, so a height
395
+ * morph of Δ moves the TOP edge up by Δ/2 and the whole body travels
396
+ * with it — the wizard step / async-detail growth the field keeps
397
+ * reporting. This closed loop folds that measured drift into
398
+ * `--hk-modal-anchor-y`, which composes into the SAME `translate`
399
+ * property the centring already uses (so the open/close ride, which
400
+ * animates `transform` only, stays untouched and the two never fight
401
+ * over one property — that is why this is NOT written as a transform).
402
+ *
403
+ * Desktop only: the ≤767px branch is a BOTTOM sheet whose frame is
404
+ * pinned to the lower edge, where growth already goes upward from a
405
+ * fixed bottom — anchoring the top there would invert the motion.
406
+ *
407
+ * The offset is CLEARED on every open edge (see the phase machine's open edge)
408
+ * and on every breakpoint crossing (the watch below), so neither a
409
+ * reopen nor a resize that turns the dialog into a sheet can inherit a
410
+ * previous cycle's lift. Clearing is not "releasing the promise": the
411
+ * leave deliberately KEEPS the offset, because the frame is standing
412
+ * there with it — zeroing it at the close request would snap the
413
+ * window by the residual before its own exit animation starts.
414
+ */
415
+ const anchor = useAnchoredTop(contentRef, {
416
+ // The gate only stops the loop from CORRECTING; the watch below is
417
+ // what CLEARS the offset the loop already wrote. The two are not
418
+ // redundant: gating alone would freeze the value, so a crossing into
419
+ // the sheet would keep it and the crossing back would resume from a
420
+ // lift that belongs to a layout the frame no longer has.
421
+ enabled: () => !sheetMobile.value,
422
+ apply: (px) => {
423
+ const el = contentRef.value;
424
+ if (!el) return;
425
+ if (px === 0) el.style.removeProperty("--hk-modal-anchor-y");
426
+ else el.style.setProperty("--hk-modal-anchor-y", `${px}px`);
427
+ },
428
+ });
429
+
430
+ /** Breakpoint crossings re-anchor.
431
+ *
432
+ * INTO the sheet: drop the offset immediately. The sheet discards the
433
+ * variable anyway (`translate: none`), so this is invisible whatever
434
+ * the frame was doing — and it is what stops a stale lift from coming
435
+ * back later.
436
+ *
437
+ * BACK to desktop: the offset is already 0, so what is owed is only the
438
+ * RE-BASE — and a re-base adopts whatever top the frame has at that
439
+ * instant. Doing that mid-morph pins the anchor to a transient
440
+ * geometry and the loop then bakes the transient into the resting
441
+ * position (a visible snap-then-lift; R4's kill experiment). So this
442
+ * leg waits for the frame to be at rest first.
443
+ *
444
+ * "At rest" is measured HERE rather than read off `data-hk-morphing`:
445
+ * that marker is set only inside `heightMorph` (the stepflow swap),
446
+ * while the ordinary content-growth morph rides `remeasure` — the
447
+ * primary path of this very feature. A self-contained stability probe
448
+ * (the frame's height unchanged across two consecutive frames) covers
449
+ * every morph path without depending on another module's bookkeeping. */
450
+ let crossingRaf: number | null = null;
451
+ let crossingStart = 0;
452
+ let lastHeight = -1;
453
+ let stableFrames = 0;
454
+ function cancelCrossingWait(): void {
455
+ if (crossingRaf !== null && typeof cancelAnimationFrame === "function") {
456
+ cancelAnimationFrame(crossingRaf);
457
+ }
458
+ crossingRaf = null;
459
+ stableFrames = 0;
460
+ lastHeight = -1;
461
+ }
462
+ function reanchorWhenAtRest(): void {
463
+ const el = contentRef.value;
464
+ if (!el) return void cancelCrossingWait();
465
+ const h = Math.round(el.getBoundingClientRect().height);
466
+ stableFrames = h === lastHeight ? stableFrames + 1 : 0;
467
+ lastHeight = h;
468
+ const elapsed = performance.now() - crossingStart;
469
+ // "At rest" needs BOTH: the settle window over (useSizeMorph debounces
470
+ // its observer by 150 ms before its post-change remeasure, so a height
471
+ // can look stable for a beat and then move again when that lands), AND
472
+ // the height actually stable across frames. Re-basing inside the
473
+ // window adopts a transient geometry — the R4 kill case.
474
+ const settled = elapsed >= CROSSING_SETTLE_MS && stableFrames >= 1;
475
+ // Hard bound in WALL TIME (2 s), not frames: happy-dom fires rAF as
476
+ // fast as ~0.5 ms/frame, so a frame count is not a duration. Past the
477
+ // bound a stuck frame is the lesser evil vs a silently disarmed
478
+ // anchor.
479
+ const expired = elapsed > CROSSING_SETTLE_MAX_MS;
480
+ if (settled || expired) {
481
+ cancelCrossingWait();
482
+ anchor.reset();
483
+ return;
484
+ }
485
+ crossingRaf = requestAnimationFrame(reanchorWhenAtRest);
486
+ }
487
+ watch(sheetMobile, (isSheet) => {
488
+ cancelCrossingWait();
489
+ crossingStart = performance.now();
490
+ if (isSheet) anchor.reset();
491
+ else reanchorWhenAtRest();
492
+ });
493
+ onBeforeUnmount(cancelCrossingWait);
494
+
372
495
  /** The window ride's own state, translated from the surface phases:
373
496
  * the open/close endpoints are the compressed end (`--from`) and the
374
497
  * natural end (`--to`). Between and after them no ride class is
@@ -651,6 +774,12 @@ export default defineComponent({
651
774
  // later, the follow-up remeasure re-checks the natural height
652
775
  // under the base height transition (a growth that landed in the
653
776
  // last tick of the enter animates instead of snapping).
777
+ // A reopen must not inherit the previous cycle's lift. The reset
778
+ // runs BEFORE the morph arms: at this instant the enter has landed
779
+ // and nothing has pinned a height yet, so the top it adopts is the
780
+ // frame's true resting geometry — then the morph's own remeasure
781
+ // grows the frame from there with the anchor already live.
782
+ anchor.reset();
654
783
  morph.start();
655
784
  void nextTick(() => {
656
785
  if (machine.phase.value === "open") morph.remeasure();
@@ -262,3 +262,55 @@ describe("useAnchoredTop — correction wiring (fake ResizeObserver)", () => {
262
262
  expect(el!.style.transform).toBe("translateY(10px)");
263
263
  });
264
264
  });
265
+
266
+ describe("useAnchoredTop — reset / shift handle", () => {
267
+ const mounts: Array<{ app: ReturnType<typeof createApp>; container: HTMLElement }> = [];
268
+ afterEach(() => {
269
+ for (const { app, container } of mounts.splice(0)) { app.unmount(); container.remove(); }
270
+ vi.unstubAllGlobals(); vi.restoreAllMocks();
271
+ });
272
+
273
+ it("reset() clears the correction and re-bases", async () => {
274
+ // The handle the modal uses on its reopen and breakpoint edges: a
275
+ // surface that holds the offset after a morph must be able to drop it.
276
+ // MUT:anchor-reset-keeps-shift (making reset() only re-base leaves the
277
+ // shift applied and this goes red).
278
+ const callbacks: Array<() => void> = [];
279
+ vi.stubGlobal("ResizeObserver", class {
280
+ private readonly cb: () => void;
281
+ constructor(cb: () => void) { this.cb = cb; callbacks.push(cb); }
282
+ observe() {}
283
+ disconnect() {}
284
+ unobserve() {}
285
+ });
286
+ const applied: number[] = [];
287
+ const top = { value: 100 };
288
+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
289
+ () => ({ top: top.value, left: 0, bottom: top.value, right: 0,
290
+ width: 0, height: 0, x: 0, y: top.value, toJSON: () => ({}) }) as DOMRect,
291
+ );
292
+ const target = ref<HTMLElement | null>(null);
293
+ let handle: ReturnType<typeof useAnchoredTop> | null = null;
294
+ const Host = defineComponent({
295
+ setup() {
296
+ handle = useAnchoredTop(target, { apply: (px) => applied.push(px) });
297
+ return () => h("div", { ref: target, class: "probe" });
298
+ },
299
+ });
300
+ const container = document.createElement("div");
301
+ document.body.appendChild(container);
302
+ const app = createApp(Host);
303
+ app.mount(container);
304
+ mounts.push({ app, container });
305
+ await nextTick();
306
+
307
+ top.value = 90;
308
+ for (const cb of callbacks) cb();
309
+ expect(applied.at(-1)).toBe(10);
310
+
311
+ handle!.reset();
312
+ // The handle's only observable contract is what it hands the sink: a
313
+ // clear (0) after a live correction.
314
+ expect(applied.at(-1)).toBe(0);
315
+ });
316
+ });
@@ -75,10 +75,40 @@ export function needsAnchorCorrection(
75
75
  * no-op — a block that never animates never drifts, so there is nothing
76
76
  * to correct.
77
77
  */
78
+ export interface UseAnchoredTopOptions {
79
+ /** Gate the correction (a surface that is not in its anchored mode). */
80
+ enabled?: () => boolean;
81
+ /** Where the correction goes, in px (0 = no correction active).
82
+ *
83
+ * Defaults to an inline `transform: translateY(…)` on the target —
84
+ * right for a host that owns nothing else on that element. A surface
85
+ * that already animates `transform` (HkModal's open/close ride) or
86
+ * composes its offset through a CSS custom property supplies its own
87
+ * writer instead, so the anchor and the surface's own choreography
88
+ * never fight over one property. */
89
+ apply?: (shiftPx: number) => void;
90
+ }
91
+
92
+ export interface AnchoredTopHandle {
93
+ /** Drop the correction and adopt the element's current top as the new
94
+ * anchor (a reopen/remount edge). The sink always runs with 0, so a
95
+ * surface whose offset is not a DOM transform still gets its clear; the
96
+ * re-base itself is a no-op when the element is gone.
97
+ *
98
+ * ⚠️ Only call this on a frame at REST: the re-base adopts whatever top
99
+ * the element has at that instant, so calling it mid-morph pins the
100
+ * anchor to a transient geometry and the loop then bakes that transient
101
+ * into the resting position. A host that can be mid-motion (HkModal,
102
+ * during a height transition) must defer until it settles. */
103
+ reset: () => void;
104
+ }
105
+
78
106
  export function useAnchoredTop(
79
- target: Ref<HTMLElement | null>,
80
- options: { enabled?: () => boolean } = {},
81
- ): void {
107
+ // `undefined` is accepted alongside `null`: a host ref declared without
108
+ // an initial value (`ref<HTMLElement>()`) reads as undefined until mount.
109
+ target: Ref<HTMLElement | null | undefined>,
110
+ options: UseAnchoredTopOptions = {},
111
+ ): AnchoredTopHandle {
82
112
  let observer: ResizeObserver | null = null;
83
113
  /** Translate currently written on the target (px, 0 = none). */
84
114
  let shift = 0;
@@ -94,6 +124,10 @@ export function useAnchoredTop(
94
124
  }
95
125
 
96
126
  function applyShift(): void {
127
+ if (options.apply) {
128
+ options.apply(shift);
129
+ return;
130
+ }
97
131
  const el = target.value;
98
132
  if (!el) return;
99
133
  // `translateY(0)` would still create a containing block and a
@@ -166,6 +200,18 @@ export function useAnchoredTop(
166
200
  window.removeEventListener("resize", rebase);
167
201
  }
168
202
  });
203
+
204
+ /** Reopen edge: forget the correction and re-anchor where the block is
205
+ * now. A surface that holds its frame through a leave (HkModal) needs
206
+ * this, or the next open would inherit the previous cycle's offset. */
207
+ function reset(): void {
208
+ shift = 0;
209
+ anchored = false;
210
+ applyShift();
211
+ rebase();
212
+ }
213
+
214
+ return { reset };
169
215
  }
170
216
 
171
217
  export default useAnchoredTop;