@dxos/react-ui-masonry 0.12.0-next-73daef452f1464b62efdbca75fb0067c1066f264 → 0.14.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/dist/lib/index.mjs +72 -48
- package/dist/lib/index.mjs.map +1 -1
- package/dist/types/src/Masonry.browser.test.d.ts +2 -0
- package/dist/types/src/Masonry.browser.test.d.ts.map +1 -0
- package/dist/types/src/Masonry.d.ts +11 -6
- package/dist/types/src/Masonry.d.ts.map +1 -1
- package/dist/types/src/Masonry.stories.d.ts +1 -1
- package/dist/types/src/Masonry.stories.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/useFlip.d.ts +1 -1
- package/dist/types/src/useFlip.d.ts.map +1 -1
- package/dist/types/src/useMasonryLayout.d.ts +4 -1
- package/dist/types/src/useMasonryLayout.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +12 -12
- package/src/Masonry.browser.test.tsx +70 -0
- package/src/Masonry.stories.tsx +18 -15
- package/src/Masonry.tsx +82 -73
- package/src/index.ts +1 -1
- package/src/layout.test.ts +1 -1
- package/src/useFlip.test.ts +1 -1
- package/src/useFlip.ts +1 -1
- package/src/useMasonryLayout.ts +49 -19
package/dist/lib/index.mjs
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { useArrowNavigationGroup } from "@fluentui/react-tabster";
|
|
2
|
-
import { createContext } from "@radix-ui/react-context";
|
|
3
1
|
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
4
2
|
import { useResizeDetector } from "react-resize-detector";
|
|
5
|
-
import {
|
|
3
|
+
import { useFocusGroup } from "@dxos/react-focus";
|
|
4
|
+
import { createContext } from "@dxos/react-hooks";
|
|
5
|
+
import * as Hooks from "@dxos/react-ui/Hooks";
|
|
6
|
+
import * as ScrollArea from "@dxos/react-ui/ScrollArea";
|
|
7
|
+
import * as Util from "@dxos/react-ui/Util";
|
|
6
8
|
import { cardMaxInlineSize, cardMinInlineSize } from "@dxos/ui-theme";
|
|
7
9
|
import { Fragment, jsx } from "react/jsx-runtime";
|
|
8
10
|
//#region src/useFlip.ts
|
|
@@ -143,8 +145,6 @@ var layout = ({ heights, columnCount, containerWidth, gapPx, maxColumnWidthPx, c
|
|
|
143
145
|
//#region src/useMasonryLayout.ts
|
|
144
146
|
/** Sub-pixel changes below this threshold (px) don't trigger a re-layout. */
|
|
145
147
|
var HEIGHT_EPSILON = .5;
|
|
146
|
-
/** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */
|
|
147
|
-
var ESTIMATED_TILE_HEIGHT = 280;
|
|
148
148
|
/**
|
|
149
149
|
* Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the
|
|
150
150
|
* column width the tile was measured at. Module scope on purpose: a grid unmounts whenever its tab
|
|
@@ -177,6 +177,7 @@ var rememberHeight = (scope, id, width, height) => {
|
|
|
177
177
|
if (!oldest.done) heightCache.delete(oldest.value);
|
|
178
178
|
}
|
|
179
179
|
};
|
|
180
|
+
var allCached = (scope, ids, width) => scope !== void 0 && ids.every((id) => heightCache.get(scopedKey(scope, id))?.width === width);
|
|
180
181
|
/**
|
|
181
182
|
* Measures tile heights via a shared ResizeObserver and computes balanced column
|
|
182
183
|
* positions. Heights are keyed by item id so reorders and removals reuse prior
|
|
@@ -184,35 +185,44 @@ var rememberHeight = (scope, id, width, height) => {
|
|
|
184
185
|
*/
|
|
185
186
|
var useMasonryLayout = ({ ids, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered, cacheKey }) => {
|
|
186
187
|
const heights = useRef(/* @__PURE__ */ new Map());
|
|
187
|
-
const estimate = useRef(
|
|
188
|
+
const estimate = useRef(280);
|
|
188
189
|
const nodes = useRef(/* @__PURE__ */ new Map());
|
|
189
190
|
const elementIds = useRef(/* @__PURE__ */ new WeakMap());
|
|
190
191
|
const refCallbacks = useRef(/* @__PURE__ */ new Map());
|
|
191
192
|
const [version, setVersion] = useState(0);
|
|
192
193
|
const widthRef = useRef(0);
|
|
193
194
|
const scopeRef = useRef(cacheKey);
|
|
195
|
+
const cachedAtFirstLayout = useRef(void 0);
|
|
196
|
+
const record = (id, height) => {
|
|
197
|
+
const previous = heights.current.get(id);
|
|
198
|
+
if (previous !== void 0 && Math.abs(previous - height) <= HEIGHT_EPSILON) return false;
|
|
199
|
+
heights.current.set(id, height);
|
|
200
|
+
rememberHeight(scopeRef.current, id, widthRef.current, height);
|
|
201
|
+
return true;
|
|
202
|
+
};
|
|
203
|
+
const relayout = () => {
|
|
204
|
+
const values = [...heights.current.values()];
|
|
205
|
+
if (values.length > 0) estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
206
|
+
setVersion((value) => value + 1);
|
|
207
|
+
};
|
|
194
208
|
const observer = useMemo(() => {
|
|
195
209
|
if (typeof ResizeObserver === "undefined") return;
|
|
196
210
|
return new ResizeObserver((entries) => {
|
|
197
211
|
let changed = false;
|
|
198
212
|
for (const entry of entries) {
|
|
199
213
|
const id = elementIds.current.get(entry.target);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const previous = heights.current.get(id);
|
|
203
|
-
if (previous === void 0 || Math.abs(previous - height) > HEIGHT_EPSILON) {
|
|
204
|
-
heights.current.set(id, height);
|
|
205
|
-
rememberHeight(scopeRef.current, id, widthRef.current, height);
|
|
206
|
-
changed = true;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
if (changed) {
|
|
210
|
-
const values = [...heights.current.values()];
|
|
211
|
-
if (values.length > 0) estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
212
|
-
setVersion((value) => value + 1);
|
|
214
|
+
const element = id === void 0 ? void 0 : nodes.current.get(id);
|
|
215
|
+
if (id !== void 0 && element) changed = record(id, element.offsetHeight) || changed;
|
|
213
216
|
}
|
|
217
|
+
if (changed) relayout();
|
|
214
218
|
});
|
|
215
219
|
}, []);
|
|
220
|
+
const measureNewTiles = () => {
|
|
221
|
+
let changed = false;
|
|
222
|
+
for (const [id, element] of nodes.current) if (!heights.current.has(id)) changed = record(id, element.offsetHeight) || changed;
|
|
223
|
+
if (changed) relayout();
|
|
224
|
+
};
|
|
225
|
+
useLayoutEffect(measureNewTiles);
|
|
216
226
|
useEffect(() => () => observer?.disconnect(), [observer]);
|
|
217
227
|
const getTileRef = useCallback((id) => {
|
|
218
228
|
let callback = refCallbacks.current.get(id);
|
|
@@ -252,6 +262,7 @@ var useMasonryLayout = ({ ids, columnCount, containerWidth, gapPx, maxColumnWidt
|
|
|
252
262
|
const present = new Set(ids);
|
|
253
263
|
for (const id of heights.current.keys()) if (!present.has(id)) heights.current.delete(id);
|
|
254
264
|
for (const id of refCallbacks.current.keys()) if (!present.has(id)) refCallbacks.current.delete(id);
|
|
265
|
+
if (cachedAtFirstLayout.current === void 0 && containerWidth > 0) cachedAtFirstLayout.current = allCached(cacheKey, ids, columnWidth);
|
|
255
266
|
const measuredIds = /* @__PURE__ */ new Set();
|
|
256
267
|
const knownIds = /* @__PURE__ */ new Set();
|
|
257
268
|
return {
|
|
@@ -278,6 +289,7 @@ var useMasonryLayout = ({ ids, columnCount, containerWidth, gapPx, maxColumnWidt
|
|
|
278
289
|
centered
|
|
279
290
|
}),
|
|
280
291
|
measured: measuredIds.size === ids.length,
|
|
292
|
+
cachedAtFirstLayout: cachedAtFirstLayout.current,
|
|
281
293
|
knownIds
|
|
282
294
|
};
|
|
283
295
|
}, [
|
|
@@ -297,10 +309,26 @@ var useMasonryLayout = ({ ids, columnCount, containerWidth, gapPx, maxColumnWidt
|
|
|
297
309
|
};
|
|
298
310
|
//#endregion
|
|
299
311
|
//#region src/Masonry.tsx
|
|
300
|
-
/** Reveal the grid once the layout has been stable for this long (the initial reflow has settled). */
|
|
301
312
|
var REVEAL_SETTLE_MS = 80;
|
|
302
313
|
/** Reveal the grid no later than this after mount, so churning content never hides it indefinitely. */
|
|
303
314
|
var REVEAL_DEADLINE_MS = 1200;
|
|
315
|
+
/** The element's content-box width, as the resize detector reports it: net of padding and scrollbar. */
|
|
316
|
+
var getContentWidth = (element) => {
|
|
317
|
+
const style = getComputedStyle(element);
|
|
318
|
+
return element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
|
319
|
+
};
|
|
320
|
+
var useContentWidth = (ref) => {
|
|
321
|
+
const { width: observedWidth } = useResizeDetector({
|
|
322
|
+
targetRef: ref,
|
|
323
|
+
refreshMode: "throttle",
|
|
324
|
+
refreshRate: 200
|
|
325
|
+
});
|
|
326
|
+
const [mountWidth, setMountWidth] = useState(0);
|
|
327
|
+
useLayoutEffect(() => {
|
|
328
|
+
if (ref.current) setMountWidth(getContentWidth(ref.current));
|
|
329
|
+
}, [ref]);
|
|
330
|
+
return observedWidth ?? mountWidth;
|
|
331
|
+
};
|
|
304
332
|
var [MasonryProvider, useMasonryContext] = createContext("Masonry");
|
|
305
333
|
var MasonryRoot = ({ children, Tile, columns = void 0, maxColumns = void 0, minColumnWidth = cardMinInlineSize, maxColumnWidth = cardMaxInlineSize, gap = .75, animate = true, centered = true }) => /* @__PURE__ */ jsx(MasonryProvider, {
|
|
306
334
|
Tile,
|
|
@@ -314,33 +342,30 @@ var MasonryRoot = ({ children, Tile, columns = void 0, maxColumns = void 0, minC
|
|
|
314
342
|
children
|
|
315
343
|
});
|
|
316
344
|
MasonryRoot.displayName = "Masonry.Root";
|
|
317
|
-
var MasonryContentInner = composable(({ children, scrollbars,
|
|
345
|
+
var MasonryContentInner = Util.composable(({ children, scrollbars, padding = true, ...props }, forwardedRef) => {
|
|
318
346
|
const { gap } = useMasonryContext("Masonry.Content");
|
|
347
|
+
const style = { "--gutter": padding ? `${gap}rem` : "0px" };
|
|
319
348
|
return /* @__PURE__ */ jsx(ScrollArea.Root, {
|
|
320
|
-
...composableProps(props, {
|
|
349
|
+
...Util.composableProps(props, {
|
|
350
|
+
classNames: "size-full",
|
|
351
|
+
style
|
|
352
|
+
}),
|
|
321
353
|
scrollbars,
|
|
322
|
-
centered,
|
|
323
|
-
thin,
|
|
324
|
-
padding,
|
|
325
354
|
ref: forwardedRef,
|
|
326
355
|
children
|
|
327
356
|
});
|
|
328
357
|
});
|
|
329
358
|
MasonryContentInner.displayName = "Masonry.Content";
|
|
330
359
|
var MasonryContent = MasonryContentInner;
|
|
331
|
-
var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, onSelect, scroll = true, ...props }, forwardedRef) => {
|
|
360
|
+
var MasonryViewportInner = Util.composable(({ items, getId, cacheKey, selectedIds, onSelect, scroll = true, ...props }, forwardedRef) => {
|
|
332
361
|
const { Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered } = useMasonryContext("Masonry.Viewport");
|
|
333
|
-
const remInPx = usePx(1);
|
|
362
|
+
const remInPx = Hooks.usePx(1);
|
|
334
363
|
const viewportRef = useRef(null);
|
|
335
|
-
const
|
|
336
|
-
targetRef: viewportRef,
|
|
337
|
-
refreshMode: "throttle",
|
|
338
|
-
refreshRate: 200
|
|
339
|
-
});
|
|
364
|
+
const contentWidth = useContentWidth(viewportRef);
|
|
340
365
|
const columnCount = useColumnCount(contentWidth, columns, maxColumns, minColumnWidth, maxColumnWidth, gap);
|
|
341
366
|
const gapPx = gap * remInPx;
|
|
342
367
|
const ids = useMemo(() => items.map((item, index) => getId?.(item) ?? String(index)), [items, getId]);
|
|
343
|
-
const { rects, columnWidth, height, getTileRef, nodes, measured, knownIds } = useMasonryLayout({
|
|
368
|
+
const { rects, columnWidth, height, getTileRef, nodes, measured, cachedAtFirstLayout, knownIds } = useMasonryLayout({
|
|
344
369
|
ids,
|
|
345
370
|
columnCount,
|
|
346
371
|
containerWidth: contentWidth,
|
|
@@ -358,23 +383,19 @@ var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, on
|
|
|
358
383
|
enabled: animate
|
|
359
384
|
});
|
|
360
385
|
const [revealed, setRevealed] = useState(false);
|
|
361
|
-
const firstPass = useRef(true);
|
|
362
386
|
useEffect(() => {
|
|
363
|
-
if (revealed) return;
|
|
364
|
-
if (
|
|
365
|
-
if (!measured) {
|
|
366
|
-
firstPass.current = false;
|
|
367
|
-
return;
|
|
368
|
-
}
|
|
369
|
-
if (firstPass.current) {
|
|
387
|
+
if (revealed || contentWidth <= 0) return;
|
|
388
|
+
if (cachedAtFirstLayout) {
|
|
370
389
|
setRevealed(true);
|
|
371
390
|
return;
|
|
372
391
|
}
|
|
392
|
+
if (!measured) return;
|
|
373
393
|
const timer = setTimeout(() => setRevealed(true), REVEAL_SETTLE_MS);
|
|
374
394
|
return () => clearTimeout(timer);
|
|
375
395
|
}, [
|
|
376
396
|
revealed,
|
|
377
397
|
measured,
|
|
398
|
+
cachedAtFirstLayout,
|
|
378
399
|
rects,
|
|
379
400
|
contentWidth
|
|
380
401
|
]);
|
|
@@ -382,13 +403,15 @@ var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, on
|
|
|
382
403
|
const deadline = setTimeout(() => setRevealed(true), REVEAL_DEADLINE_MS);
|
|
383
404
|
return () => clearTimeout(deadline);
|
|
384
405
|
}, []);
|
|
385
|
-
const
|
|
406
|
+
const { ref: focusGroupRef, ...focusGroupProps } = useFocusGroup({
|
|
386
407
|
axis: "both",
|
|
387
408
|
memorizeCurrent: true,
|
|
388
|
-
tabbable: true
|
|
409
|
+
tabbable: true,
|
|
410
|
+
cyclic: true
|
|
389
411
|
});
|
|
412
|
+
const gridRef = Hooks.useMergeRefs([forwardedRef, focusGroupRef]);
|
|
390
413
|
const grid = /* @__PURE__ */ jsx(Fragment, { children: contentWidth > 0 && /* @__PURE__ */ jsx("div", {
|
|
391
|
-
...composableProps(props, {
|
|
414
|
+
...Util.composableProps(props, {
|
|
392
415
|
classNames: "relative",
|
|
393
416
|
style: {
|
|
394
417
|
width: `${contentWidth}px`,
|
|
@@ -398,9 +421,9 @@ var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, on
|
|
|
398
421
|
transition: animate && !prefersReducedMotion() ? "opacity 200ms cubic-bezier(0.2, 0, 0, 1)" : void 0
|
|
399
422
|
}
|
|
400
423
|
}),
|
|
401
|
-
...
|
|
424
|
+
...focusGroupProps,
|
|
402
425
|
role: "list",
|
|
403
|
-
ref:
|
|
426
|
+
ref: gridRef,
|
|
404
427
|
children: items.map((item, index) => {
|
|
405
428
|
const id = ids[index];
|
|
406
429
|
const rect = rects[index];
|
|
@@ -409,7 +432,7 @@ var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, on
|
|
|
409
432
|
const estimated = !knownIds.has(id);
|
|
410
433
|
return /* @__PURE__ */ jsx("div", {
|
|
411
434
|
className: [
|
|
412
|
-
"
|
|
435
|
+
"*:min-w-0!",
|
|
413
436
|
selectable && "cursor-pointer",
|
|
414
437
|
selected && "rounded-md ring-2 ring-inset ring-primary-500"
|
|
415
438
|
].filter(Boolean).join(" "),
|
|
@@ -434,6 +457,7 @@ var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, on
|
|
|
434
457
|
})
|
|
435
458
|
}) });
|
|
436
459
|
return scroll ? /* @__PURE__ */ jsx(ScrollArea.Viewport, {
|
|
460
|
+
classNames: "px-(--gutter)",
|
|
437
461
|
ref: viewportRef,
|
|
438
462
|
children: grid
|
|
439
463
|
}) : /* @__PURE__ */ jsx("div", {
|
|
@@ -446,7 +470,7 @@ MasonryViewportInner.displayName = "Masonry.Viewport";
|
|
|
446
470
|
var MasonryViewport = MasonryViewportInner;
|
|
447
471
|
/** Compute column count from container width and column constraints. */
|
|
448
472
|
var useColumnCount = (width, columns, maxColumns, minColumnWidth, maxColumnWidth, gap) => {
|
|
449
|
-
const remInPx = usePx(1);
|
|
473
|
+
const remInPx = Hooks.usePx(1);
|
|
450
474
|
return useMemo(() => {
|
|
451
475
|
if (columns != null) return columns;
|
|
452
476
|
const minColumnWidthPx = minColumnWidth * remInPx;
|
package/dist/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/useFlip.ts","../../src/layout.ts","../../src/useMasonryLayout.ts","../../src/Masonry.tsx"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport { type RefObject, useLayoutEffect, useRef } from 'react';\n\nimport { type Rect } from './layout';\n\nconst DURATION = 200;\nconst EASING = 'cubic-bezier(0.2, 0, 0, 1)';\n\n/**\n * Above this many tiles added/removed in a single layout, snap instead of animate.\n * Reflows this large are the initial bulk render or a data swap, not an incremental\n * edit, and animating dozens of tiles at once is the source of the perf/bunching jank.\n */\nconst ANIMATE_MAX_DELTA = 8;\n\nexport const prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n\n/**\n * Decide whether a layout transition should animate. Animate only genuine small\n * incremental edits on a stable container: a resize snaps (the whole grid moves),\n * and a zero add/remove delta means either the initial bulk render's height-settling\n * pass or a pure resize — both snap so the grid never animates into place from the\n * degenerate all-heights-zero layout.\n */\nexport const shouldAnimateReflow = ({\n added,\n removed,\n resized,\n maxDelta = ANIMATE_MAX_DELTA,\n}: {\n added: number;\n removed: number;\n resized: boolean;\n maxDelta?: number;\n}): boolean => !resized && added + removed > 0 && added + removed <= maxDelta;\n\nexport type UseFlipOptions = {\n /** Tile wrappers by id, kept live by the layout hook. */\n nodes: RefObject<Map<string, HTMLElement>>;\n /** Item ids in render order (aligned with `rects`). */\n ids: readonly string[];\n /** Target positions (aligned with `ids`). */\n rects: readonly Rect[];\n /** Current column count; a change marks a resize, which snaps rather than animates. */\n columnCount: number;\n /** Current content width (px); a change marks a resize, which snaps rather than animates. */\n containerWidth: number;\n /** Disable to snap without animating (also skipped under reduced-motion and on bulk reflows). */\n enabled: boolean;\n};\n\n/**\n * Animates tile position changes with FLIP: tiles that moved between layouts\n * transition from their previous translate to the new one via the Web Animations\n * API; freshly-added tiles fade/scale in. Respects `prefers-reduced-motion`.\n */\nexport const useFlip = ({ nodes, ids, rects, columnCount, containerWidth, enabled }: UseFlipOptions): void => {\n const previous = useRef(new Map<string, { x: number; y: number }>());\n const previousLayout = useRef<{ columnCount: number; containerWidth: number } | null>(null);\n\n useLayoutEffect(() => {\n // Without committed positions this is the first non-empty layout — snap it (the initial\n // render), even for a small set that would otherwise read as a handful of added tiles.\n const hasPriorPositions = previous.current.size > 0;\n // Classify the reflow before recording new positions: added/removed relative to\n // the last rendered id set, and whether the container dimensions changed (resize).\n const idSet = new Set(ids);\n let added = 0;\n for (const id of ids) {\n if (!previous.current.has(id)) {\n added += 1;\n }\n }\n let removed = 0;\n for (const id of previous.current.keys()) {\n if (!idSet.has(id)) {\n removed += 1;\n }\n }\n const resized =\n previousLayout.current !== null &&\n (previousLayout.current.columnCount !== columnCount || previousLayout.current.containerWidth !== containerWidth);\n previousLayout.current = { columnCount, containerWidth };\n\n const animate =\n hasPriorPositions && enabled && !prefersReducedMotion() && shouldAnimateReflow({ added, removed, resized });\n const seen = new Set<string>();\n\n ids.forEach((id, index) => {\n const rect = rects[index];\n const element = nodes.current.get(id);\n if (!rect || !element) {\n return;\n }\n seen.add(id);\n\n const prior = previous.current.get(id);\n previous.current.set(id, { x: rect.x, y: rect.y });\n\n // Style already holds the target translate; snapping needs no animation.\n if (!animate) {\n return;\n }\n\n if (prior) {\n if (prior.x !== rect.x || prior.y !== rect.y) {\n element.animate(\n [\n { transform: `translate(${prior.x}px, ${prior.y}px)` },\n { transform: `translate(${rect.x}px, ${rect.y}px)` },\n ],\n { duration: DURATION, easing: EASING },\n );\n }\n } else {\n element.animate(\n [\n { opacity: 0, transform: `translate(${rect.x}px, ${rect.y}px) scale(0.98)` },\n { opacity: 1, transform: `translate(${rect.x}px, ${rect.y}px) scale(1)` },\n ],\n { duration: DURATION, easing: EASING },\n );\n }\n });\n\n // Forget positions for tiles no longer rendered.\n for (const id of previous.current.keys()) {\n if (!seen.has(id)) {\n previous.current.delete(id);\n }\n }\n }, [nodes, ids, rects, columnCount, containerWidth, enabled]);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nexport type Rect = {\n /** Horizontal offset (px) of the tile's left edge. */\n x: number;\n /** Vertical offset (px) of the tile's top edge. */\n y: number;\n /** Column the tile was assigned to. */\n column: number;\n};\n\nexport type LayoutResult = {\n /** Position of each tile, in input order. */\n rects: Rect[];\n /** Width (px) shared by every column. */\n columnWidth: number;\n /** Total content height (px), including the perimeter gap. */\n height: number;\n};\n\nexport type LayoutOptions = {\n /** Measured tile heights (px), in item order. Unmeasured tiles pass 0. */\n heights: readonly number[];\n /** Number of columns to lay out across. */\n columnCount: number;\n /** Available content width (px), already net of any scrollbar allowance. */\n containerWidth: number;\n /** Space (px) between tiles and, vertically, around the grid perimeter. */\n gapPx: number;\n /** Optional cap on column width (px); leftover width centers the columns. */\n maxColumnWidthPx?: number;\n /** Centre capped columns in the container. Off aligns them to the start, leaving the slack at the end. */\n centered?: boolean;\n};\n\n/**\n * Lay tiles out into balanced columns using column-major greedy assignment: each\n * tile is placed in the currently shortest column (ties resolve to the lowest\n * index for stable ordering). Pure and synchronous so column balancing is unit\n * testable without a DOM.\n *\n * Columns are separated by a single gap. They stretch to fill `containerWidth`\n * unless `maxColumnWidthPx` caps them narrower, in which case the leftover width\n * is split evenly so the grid stays centred (the outer margin grows beyond the\n * gap) — or, with `centered` off, left entirely at the end so the columns align to\n * the start. The base left/right perimeter is owned by the scroll container (via\n * its `--gutter`); the layout adds any centring offset plus the top/bottom perimeter.\n */\n/**\n * Width every column gets, before any tile is placed. Independent of the tiles themselves — which is\n * what lets a caller key cached tile heights by the width they were measured at.\n */\nexport const getColumnWidth = ({\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n}: Pick<LayoutOptions, 'columnCount' | 'containerWidth' | 'gapPx' | 'maxColumnWidthPx'>): number => {\n const columns = Math.max(1, Math.floor(columnCount));\n const fillColumnWidth = (containerWidth - (columns - 1) * gapPx) / columns;\n return maxColumnWidthPx && maxColumnWidthPx > 0 ? Math.min(fillColumnWidth, maxColumnWidthPx) : fillColumnWidth;\n};\n\nexport const layout = ({\n heights,\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n centered = true,\n}: LayoutOptions): LayoutResult => {\n const columns = Math.max(1, Math.floor(columnCount));\n const columnWidth = getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx });\n\n // Centre the (possibly capped) columns within the container, unless start-aligned.\n const usedWidth = columns * columnWidth + (columns - 1) * gapPx;\n const sideInset = centered ? Math.max(0, (containerWidth - usedWidth) / 2) : 0;\n\n // Seed each column with the top gap so the first row clears the perimeter.\n const columnHeights = new Array<number>(columns).fill(gapPx);\n\n const rects: Rect[] = heights.map((tileHeight) => {\n let target = 0;\n for (let column = 1; column < columns; ++column) {\n if (columnHeights[column] < columnHeights[target]) {\n target = column;\n }\n }\n\n const rect: Rect = {\n x: sideInset + target * (columnWidth + gapPx),\n y: columnHeights[target],\n column: target,\n };\n columnHeights[target] += tileHeight + gapPx;\n return rect;\n });\n\n // Each column already carries a trailing gap, which becomes the bottom perimeter.\n const tallest = columnHeights.reduce((max, value) => Math.max(max, value), 0);\n const height = heights.length === 0 ? 0 : tallest;\n return { rects, columnWidth, height };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { type LayoutResult, getColumnWidth, layout } from './layout';\n\n/** Sub-pixel changes below this threshold (px) don't trigger a re-layout. */\nconst HEIGHT_EPSILON = 0.5;\n\n/** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */\nconst ESTIMATED_TILE_HEIGHT = 280;\n\n/**\n * Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the\n * column width the tile was measured at. Module scope on purpose: a grid unmounts whenever its tab\n * or route does, and re-measuring from scratch is what makes a remount wait — hidden — for the\n * layout to settle. With a warm entry the first layout is already final, so the grid can be shown on\n * the first frame.\n *\n * The `cacheKey` scope is required rather than optional: tile ids default to the array index, so a\n * process-wide cache keyed on id alone would serve one grid's height for `\"0\"` to an unrelated grid\n * and reveal it before it was ever measured. A grid that passes no key keeps its heights to itself.\n *\n * Height is stored with its width because a card reflows: at a different width the entry is still a\n * far better estimate than the default, but it is not a measurement.\n */\nconst heightCache = new Map<string, { width: number; height: number }>();\n\n/** Cap on remembered tiles; oldest are evicted first (insertion order). */\nconst HEIGHT_CACHE_LIMIT = 2_000;\n\n/** Cache entries are namespaced by scope; `\\u0000` cannot occur in an id or a caller's key. */\nconst scopedKey = (scope: string, id: string) => `${scope}\\u0000${id}`;\n\nconst rememberHeight = (scope: string | undefined, id: string, width: number, height: number): void => {\n if (scope === undefined) {\n return;\n }\n const key = scopedKey(scope, id);\n // Re-insert so recently-seen tiles move to the end and survive eviction.\n heightCache.delete(key);\n heightCache.set(key, { width, height });\n if (heightCache.size > HEIGHT_CACHE_LIMIT) {\n const oldest = heightCache.keys().next();\n if (!oldest.done) {\n heightCache.delete(oldest.value);\n }\n }\n};\n\n/** Clears the shared height cache. Exported for tests and for callers that recycle ids. */\nexport const clearHeightCache = (): void => heightCache.clear();\n\nexport type MasonryLayout = LayoutResult & {\n /** True once every tile has a height measured at the current column width, so positions are final. */\n measured: boolean;\n /**\n * Ids the layout has some height for — measured now, or remembered from a previous mount or width.\n * Anything outside this set is sitting at a guess and should not be painted.\n */\n knownIds: ReadonlySet<string>;\n /** Stable ref callback for the tile wrapper of `id` (measures + registers it). */\n getTileRef: (id: string) => (element: HTMLElement | null) => void;\n /** Live map of currently-mounted tile wrappers by id (for FLIP positioning). */\n nodes: RefObject<Map<string, HTMLElement>>;\n};\n\nexport type UseMasonryLayoutOptions = {\n /** Ids of the items to lay out, in render order. */\n ids: readonly string[];\n columnCount: number;\n /** Available content width (px), net of scrollbar allowance. */\n containerWidth: number;\n gapPx: number;\n /** Optional cap on column width (px). */\n maxColumnWidthPx?: number;\n /** Centre capped columns in the container (see `layout`). */\n centered?: boolean;\n /**\n * Scope for remembered tile heights, e.g. the collection's URI. Omit when ids are not stable and\n * unique across the app (the default index ids are not) — heights are then per-instance, and a\n * remount re-measures.\n */\n cacheKey?: string;\n};\n\n/**\n * Measures tile heights via a shared ResizeObserver and computes balanced column\n * positions. Heights are keyed by item id so reorders and removals reuse prior\n * measurements; a version counter re-runs the pure layout when a height changes.\n */\nexport const useMasonryLayout = ({\n ids,\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n centered,\n cacheKey,\n}: UseMasonryLayoutOptions): MasonryLayout => {\n const heights = useRef(new Map<string, number>());\n // Survives pruning, unlike `heights`: when the item set is replaced wholesale (paging through\n // duplicate groups) every id is new, and without a remembered average the estimate would fall back\n // to the ~280px default and paint the swap hundreds of pixels out before the real heights land.\n const estimate = useRef(ESTIMATED_TILE_HEIGHT);\n const nodes = useRef(new Map<string, HTMLElement>());\n const elementIds = useRef(new WeakMap<Element, string>());\n const refCallbacks = useRef(new Map<string, (element: HTMLElement | null) => void>());\n const [version, setVersion] = useState(0);\n // The observer is created once, so it reads the current column width and scope through refs.\n const widthRef = useRef(0);\n const scopeRef = useRef<string | undefined>(cacheKey);\n\n const observer = useMemo(() => {\n if (typeof ResizeObserver === 'undefined') {\n return undefined;\n }\n\n return new ResizeObserver((entries) => {\n let changed = false;\n for (const entry of entries) {\n const id = elementIds.current.get(entry.target);\n if (!id) {\n continue;\n }\n // ResizeObserver types `target` as Element; we only ever observe HTMLElement tile wrappers,\n // whose border-box height (offsetHeight) is what the layout stacks.\n const height = (entry.target as HTMLElement).offsetHeight;\n const previous = heights.current.get(id);\n if (previous === undefined || Math.abs(previous - height) > HEIGHT_EPSILON) {\n heights.current.set(id, height);\n rememberHeight(scopeRef.current, id, widthRef.current, height);\n changed = true;\n }\n }\n if (changed) {\n const values = [...heights.current.values()];\n if (values.length > 0) {\n estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;\n }\n setVersion((value) => value + 1);\n }\n });\n }, []);\n\n useEffect(() => () => observer?.disconnect(), [observer]);\n\n const getTileRef = useCallback(\n (id: string) => {\n let callback = refCallbacks.current.get(id);\n if (!callback) {\n callback = (element: HTMLElement | null) => {\n const previous = nodes.current.get(id);\n if (previous === element) {\n return;\n }\n if (previous) {\n observer?.unobserve(previous);\n elementIds.current.delete(previous);\n }\n if (element) {\n nodes.current.set(id, element);\n elementIds.current.set(element, id);\n if (observer) {\n observer.observe(element);\n } else {\n // Without a ResizeObserver nothing would ever report a height, leaving every tile\n // hidden behind the estimate gate. One measurement at mount is worse than live\n // tracking, but it is a layout rather than a blank grid.\n heights.current.set(id, element.offsetHeight);\n rememberHeight(scopeRef.current, id, widthRef.current, element.offsetHeight);\n setVersion((value) => value + 1);\n }\n } else {\n nodes.current.delete(id);\n }\n };\n refCallbacks.current.set(id, callback);\n }\n return callback;\n },\n [observer],\n );\n\n const columnWidth = Math.round(getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx }));\n widthRef.current = columnWidth;\n scopeRef.current = cacheKey;\n\n const result = useMemo(() => {\n // Prune measurements/callbacks for ids no longer present so the maps track the\n // live item set.\n const present = new Set(ids);\n for (const id of heights.current.keys()) {\n if (!present.has(id)) {\n heights.current.delete(id);\n }\n }\n for (const id of refCallbacks.current.keys()) {\n if (!present.has(id)) {\n refCallbacks.current.delete(id);\n }\n }\n\n // Height for each tile, best source first: measured this mount, remembered at this exact column\n // width (as good as measured — the tile has not reflowed), remembered at some other width (a\n // close estimate, since content usually dominates), else the running average.\n const measuredIds = new Set<string>();\n const knownIds = new Set<string>();\n const tileHeights = ids.map((id) => {\n const measured = heights.current.get(id);\n if (measured !== undefined) {\n measuredIds.add(id);\n knownIds.add(id);\n return measured;\n }\n\n const cached = cacheKey === undefined ? undefined : heightCache.get(scopedKey(cacheKey, id));\n if (cached) {\n knownIds.add(id);\n if (cached.width === columnWidth) {\n measuredIds.add(id);\n }\n return cached.height;\n }\n\n return estimate.current;\n });\n\n return {\n ...layout({ heights: tileHeights, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered }),\n measured: measuredIds.size === ids.length,\n knownIds,\n };\n // `version` re-runs layout when a measured height changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ids, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered, columnWidth, cacheKey, version]);\n\n return { ...result, getTileRef, nodes };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport { useArrowNavigationGroup } from '@fluentui/react-tabster';\nimport { createContext } from '@radix-ui/react-context';\nimport React, {\n type ComponentType,\n type CSSProperties,\n type JSX,\n type MouseEvent,\n type PropsWithChildren,\n type Ref,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useResizeDetector } from 'react-resize-detector';\n\nimport { ScrollArea, ScrollAreaRootProps, ThemedClassName, usePx } from '@dxos/react-ui';\nimport { composable, composableProps } from '@dxos/react-ui';\nimport { cardMaxInlineSize, cardMinInlineSize } from '@dxos/ui-theme';\n\nimport { prefersReducedMotion, useFlip } from './useFlip';\nimport { useMasonryLayout } from './useMasonryLayout';\n\n/** Reveal the grid once the layout has been stable for this long (the initial reflow has settled). */\nconst REVEAL_SETTLE_MS = 80;\n\n/** Reveal the grid no later than this after mount, so churning content never hides it indefinitely. */\nconst REVEAL_DEADLINE_MS = 1200;\n\n//\n// Context\n//\n\ntype MasonryContextValue = {\n /** Render component for each masonry item. Receives `selected` when the grid is selectable. */\n Tile: ComponentType<{ data: any; index: number; selected?: boolean }>;\n /** Override auto-calculated column count. */\n columns: number | undefined;\n /** Upper bound on number of columns. */\n maxColumns: number | undefined;\n /** Minimum column width in rem. */\n minColumnWidth: number;\n /** Maximum column width in rem. */\n maxColumnWidth: number;\n /** Space applied uniformly between tiles and around the grid perimeter, in rem. */\n gap: number;\n /**\n * Animate reflow when a small number of tiles are added or removed. Disabled, or on a\n * bulk change (initial render, data swap) or resize, tiles snap to position instead.\n */\n animate: boolean;\n /**\n * Centre the columns when `maxColumnWidth` caps them narrower than the container. Off aligns them\n * to the start instead, which reads better when the grid sits in a form or list flow whose other\n * rows are start-aligned. Distinct from `Masonry.Content`'s `centered`, which is ScrollArea's\n * scrollbar-padding balance and says nothing about column alignment.\n */\n centered: boolean;\n};\n\nconst MASONRY_NAME = 'Masonry';\n\nconst [MasonryProvider, useMasonryContext] = createContext<MasonryContextValue>(MASONRY_NAME);\n\n//\n// Root\n//\n\ntype MasonryRootProps = PropsWithChildren<Partial<MasonryContextValue>>;\n\nconst MasonryRoot = ({\n children,\n Tile,\n columns = undefined,\n maxColumns = undefined,\n minColumnWidth = cardMinInlineSize,\n maxColumnWidth = cardMaxInlineSize,\n gap = 0.75,\n animate = true,\n centered = true,\n}: MasonryRootProps) => (\n <MasonryProvider\n Tile={Tile!}\n columns={columns}\n maxColumns={maxColumns}\n minColumnWidth={minColumnWidth}\n maxColumnWidth={maxColumnWidth}\n gap={gap}\n animate={animate}\n centered={centered}\n >\n {children}\n </MasonryProvider>\n);\n\nMasonryRoot.displayName = 'Masonry.Root';\n\n//\n// Content\n//\n// The outer wrapper: renders the ScrollArea.Root. Style this layer\n// (centered/thin/padding) to control the scroll container; the Viewport measures\n// its own content box, so scrollbar width and padding are accounted for whatever\n// density is configured here.\n//\n\ntype MasonryContentProps = ThemedClassName<\n PropsWithChildren<Pick<ScrollAreaRootProps, 'scrollbars' | 'centered' | 'thin' | 'padding'>>\n>;\n\nconst MasonryContentInner = composable<HTMLDivElement, MasonryContentProps>(\n ({ children, scrollbars, centered = true, thin = true, padding = true, ...props }, forwardedRef) => {\n const { gap } = useMasonryContext('Masonry.Content');\n return (\n <ScrollArea.Root\n // Drive the ScrollArea gutter to the grid gap so the left/right perimeter\n // matches the inter-column gap: the centered+padding theme resolves this to\n // pl = gap and pr = gap - scrollbar, keeping both sides symmetric with the\n // scrollbar accounted for at any density. Cast: CSSProperties has no index\n // signature for CSS custom properties, so `--gutter` cannot be typed directly.\n {...composableProps(props, { style: { '--gutter': `${gap}rem` } as CSSProperties })}\n scrollbars={scrollbars}\n centered={centered}\n thin={thin}\n padding={padding}\n ref={forwardedRef}\n >\n {children}\n </ScrollArea.Root>\n );\n },\n);\n\nMasonryContentInner.displayName = 'Masonry.Content';\n\nconst MasonryContent = MasonryContentInner as (\n props: MasonryContentProps & {\n ref?: Ref<HTMLDivElement | null>;\n },\n) => JSX.Element;\n\n//\n// Viewport\n//\n// The inner render layer: renders the ScrollArea.Viewport wrapped around the\n// absolute layout engine. Each tile is positioned with translate(x, y) into a\n// balanced (shortest-column-first) grid; reflow is animated with FLIP. Style\n// this layer separately from Content to control the tile grid.\n//\n\ntype MasonryViewportProps<Item> = ThemedClassName<{\n /** Items to render in the masonry grid. */\n items: readonly Item[];\n /** Extract a stable key from an item, aligned with react-ui-mosaic's getId. */\n getId?: (data: Item) => string;\n /**\n * Scope for remembering tile heights across mounts, e.g. the collection's URI. With one, a\n * remount renders on the first frame instead of waiting for the layout to settle. Omit it when\n * `getId` is omitted: the default index ids are not unique across grids.\n */\n cacheKey?: string;\n /**\n * Ids of the currently-selected tiles. When `onSelect` is also provided the grid becomes\n * selectable: selected tiles render an outline + `aria-selected`, and clicking a tile emits\n * {@link onSelect}. Selection STATE (single/multi semantics) is owned by the consumer — pair this\n * with `useListSelection` from `@dxos/react-ui-list`.\n */\n selectedIds?: ReadonlySet<string>;\n /** Emitted when a tile is clicked while selectable. The consumer toggles its own selection state. */\n onSelect?: (id: string, event: MouseEvent) => void;\n /**\n * Whether this layer owns scrolling. Set `false` when an ancestor already scrolls (e.g. a form's\n * viewport) to render the grid in a plain full-width block instead of a nested scroll container —\n * the `ScrollArea.Root` that `Masonry.Content` provides is then not needed. Nesting scroll\n * containers also risks collapsing the measured width to the scrollbar gutter, which would\n * suppress the grid entirely (see the width gate below).\n * @default true\n */\n scroll?: boolean;\n}>;\n\nconst MasonryViewportInner = composable<HTMLDivElement, MasonryViewportProps<any>>(\n ({ items, getId, cacheKey, selectedIds, onSelect, scroll = true, ...props }, forwardedRef) => {\n const { Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered } =\n useMasonryContext('Masonry.Viewport');\n const remInPx = usePx(1);\n // Measure the viewport's own content box (net of padding and scrollbar) rather\n // than deriving it from the root width, so the grid tracks the actual available\n // width for any ScrollArea density (thin/scrollbars/padding) without duplicating\n // the theme's gutter math.\n const viewportRef = useRef<HTMLDivElement | null>(null);\n // Throttle width changes: each update recomputes the column count and the full tile layout,\n // so coalesce rapid resizes (drag, ScrollArea reflow) into at most one relayout per interval.\n const { width: contentWidth = 0 } = useResizeDetector({\n targetRef: viewportRef,\n refreshMode: 'throttle',\n refreshRate: 200,\n });\n const columnCount = useColumnCount(contentWidth, columns, maxColumns, minColumnWidth, maxColumnWidth, gap);\n\n // The grid fills the measured content box; the layout caps columns at\n // `maxColumnWidth` and centres them, so no scrollbar/padding math is duplicated here.\n const gapPx = gap * remInPx;\n const ids = useMemo(() => items.map((item, index) => getId?.(item) ?? String(index)), [items, getId]);\n const { rects, columnWidth, height, getTileRef, nodes, measured, knownIds } = useMasonryLayout({\n ids,\n columnCount,\n containerWidth: contentWidth,\n gapPx,\n maxColumnWidthPx: maxColumnWidth * remInPx,\n centered,\n cacheKey,\n });\n useFlip({ nodes, ids, rects, columnCount, containerWidth: contentWidth, enabled: animate });\n\n // Hide the grid until the layout stops changing, then fade in; latch on so later edits never\n // re-hide it. Revealing on the first measurement is not enough: tiles mount collapsed (their\n // poster reserves height a frame later), so the first pass stacks them bunched at the top and\n // only settles over the next few reflows. Debounce on `rects` identity — which changes on every\n // relayout — and reveal once it has been stable for a beat, with a hard deadline as a backstop.\n //\n // None of that applies when every tile's height was already known on the first pass (the height\n // cache is warm from an earlier mount): the layout is final before paint, so waiting for it to\n // settle would just be a delay. That is the common case after the first visit.\n const [revealed, setRevealed] = useState(false);\n const firstPass = useRef(true);\n useEffect(() => {\n if (revealed) {\n return;\n }\n // Nothing has been laid out until the viewport reports a width, so this does not count as the\n // first pass — consuming it here would forfeit the fast path on every mount.\n if (contentWidth <= 0) {\n return;\n }\n if (!measured) {\n firstPass.current = false;\n return;\n }\n if (firstPass.current) {\n setRevealed(true);\n return;\n }\n const timer = setTimeout(() => setRevealed(true), REVEAL_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [revealed, measured, rects, contentWidth]);\n useEffect(() => {\n const deadline = setTimeout(() => setRevealed(true), REVEAL_DEADLINE_MS);\n return () => clearTimeout(deadline);\n }, []);\n\n // Arrow-key navigation across tiles. Uses Tabster's `both` axis so all four\n // arrows move focus through the items as flat next/previous-focusable, giving\n // predictable wrap-around in DOM order.\n const arrowNavigationAttrs = useArrowNavigationGroup({\n axis: 'both',\n memorizeCurrent: true,\n tabbable: true,\n });\n\n // The viewport is the full-width scroll container; its centered+padded theme\n // (with `--gutter` set to the gap) balances the scrollbar into symmetric inline\n // gutters. The grid fills the content box and the layout centres capped columns,\n // so nothing overflows and left/right spacing matches the gap. The viewport always\n // renders so it can be measured; tiles render once a width is known.\n const grid = (\n <>\n {contentWidth > 0 && (\n <div\n {...composableProps(props, {\n classNames: 'relative',\n style: {\n width: `${contentWidth}px`,\n height: `${height}px`,\n opacity: revealed ? 1 : 0,\n // Hidden (not just transparent) before reveal so the settling tiles are neither\n // focusable nor hit-testable; the opacity fade only runs when motion is allowed.\n visibility: revealed ? 'visible' : 'hidden',\n transition: animate && !prefersReducedMotion() ? 'opacity 200ms cubic-bezier(0.2, 0, 0, 1)' : undefined,\n },\n })}\n {...arrowNavigationAttrs}\n role='list'\n ref={forwardedRef}\n >\n {items.map((item, index) => {\n const id = ids[index];\n const rect = rects[index];\n const selectable = !!onSelect;\n const selected = selectedIds?.has(id) ?? false;\n // A tile with no height at all — never measured, nothing remembered — is positioned by\n // a guess. Painting that guess is what flashed a tile hundreds of pixels out of place\n // when the item set was swapped wholesale. A remembered height from another width is\n // close enough to paint, so a resize reflows in place instead of blanking.\n // `visibility` rather than `display`, so the ResizeObserver can still measure it.\n const estimated = !knownIds.has(id);\n return (\n <div\n key={id}\n // Let the tile clamp its card: a card's own min-width must not exceed\n // the column, or a narrow (single-column, mobile) container overflows\n // and shows a horizontal scrollbar.\n className={[\n '[&>*]:min-w-0!',\n selectable && 'cursor-pointer',\n selected && 'rounded-md ring-2 ring-inset ring-primary-500',\n ]\n .filter(Boolean)\n .join(' ')}\n ref={getTileRef(id)}\n role='listitem'\n aria-selected={selectable ? selected : undefined}\n onClick={onSelect ? (event) => onSelect(id, event) : undefined}\n style={{\n position: 'absolute',\n insetBlockStart: 0,\n insetInlineStart: 0,\n width: `${columnWidth}px`,\n transform: rect ? `translate(${rect.x}px, ${rect.y}px)` : undefined,\n visibility: estimated ? 'hidden' : undefined,\n }}\n >\n <Tile index={index} data={item} selected={selected} />\n </div>\n );\n })}\n </div>\n )}\n </>\n );\n\n // Not `dx-expander` in the non-scrolling case: the width gate needs a definite inline size\n // (`w-full min-w-0`) without claiming the block axis, which would fight the surrounding flow —\n // the grid's height comes from the computed layout.\n return scroll ? (\n <ScrollArea.Viewport ref={viewportRef}>{grid}</ScrollArea.Viewport>\n ) : (\n <div className='flex-1 w-full min-w-0' ref={viewportRef}>\n {grid}\n </div>\n );\n },\n);\n\nMasonryViewportInner.displayName = 'Masonry.Viewport';\n\nconst MasonryViewport = MasonryViewportInner as <Item>(\n props: MasonryViewportProps<Item> & {\n ref?: Ref<HTMLDivElement | null>;\n },\n) => JSX.Element;\n\n/** Compute column count from container width and column constraints. */\nconst useColumnCount = (\n width: number,\n columns: number | undefined,\n maxColumns: number | undefined,\n minColumnWidth: number,\n maxColumnWidth: number,\n gap: number,\n) => {\n const remInPx = usePx(1);\n return useMemo(() => {\n if (columns != null) {\n return columns;\n }\n\n const minColumnWidthPx = minColumnWidth * remInPx;\n const maxColumnWidthPx = maxColumnWidth * remInPx;\n const gapPx = gap * remInPx;\n if (width <= 0 || minColumnWidthPx <= 0) {\n return 1;\n }\n\n // `width` is the content box; the outer perimeter is owned by the scroll\n // container, so only interior gaps count: N columns fit when\n // N * colWidth + (N - 1) * gap <= width, i.e. N <= (width + gap) / (colWidth + gap).\n let cols = Math.max(1, Math.floor((width + gapPx) / (minColumnWidthPx + gapPx)));\n if (maxColumnWidthPx > 0) {\n const effectiveColWidth = (width - (cols - 1) * gapPx) / cols;\n if (effectiveColWidth > maxColumnWidthPx) {\n // Try to add columns to keep cards below maxColumnWidth, but never violate minColumnWidth.\n const maxCols = Math.ceil((width + gapPx) / (maxColumnWidthPx + gapPx));\n if ((width - (maxCols - 1) * gapPx) / maxCols >= minColumnWidthPx) {\n cols = maxCols;\n }\n }\n }\n\n const clamped = maxColumns != null ? Math.min(cols, maxColumns) : cols;\n return Math.max(1, clamped);\n }, [remInPx, width, columns, maxColumns, minColumnWidth, maxColumnWidth, gap]);\n};\n\n//\n// Masonry\n//\n\nexport const Masonry = {\n Root: MasonryRoot,\n Content: MasonryContent,\n Viewport: MasonryViewport,\n};\n\nexport type { MasonryContentProps, MasonryRootProps, MasonryViewportProps };\n"],"mappings":";;;;;;;;AAQA,IAAM,WAAW;AACjB,IAAM,SAAS;;;;;;AAOf,IAAM,oBAAoB;AAE1B,IAAa,6BACX,OAAO,WAAW,eAAe,OAAO,aAAa,kCAAkC,CAAC,CAAC;;;;;;;;AAS3F,IAAa,uBAAuB,EAClC,OACA,SACA,SACA,WAAW,wBAME,CAAC,WAAW,QAAQ,UAAU,KAAK,QAAQ,WAAW;;;;;;AAsBrE,IAAa,WAAW,EAAE,OAAO,KAAK,OAAO,aAAa,gBAAgB,cAAoC;CAC5G,MAAM,WAAW,uBAAO,IAAI,IAAsC,CAAC;CACnE,MAAM,iBAAiB,OAA+D,IAAI;CAE1F,sBAAsB;EAGpB,MAAM,oBAAoB,SAAS,QAAQ,OAAO;EAGlD,MAAM,QAAQ,IAAI,IAAI,GAAG;EACzB,IAAI,QAAQ;EACZ,KAAK,MAAM,MAAM,KACf,IAAI,CAAC,SAAS,QAAQ,IAAI,EAAE,GAC1B,SAAS;EAGb,IAAI,UAAU;EACd,KAAK,MAAM,MAAM,SAAS,QAAQ,KAAK,GACrC,IAAI,CAAC,MAAM,IAAI,EAAE,GACf,WA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,KAAA;IACrC;IAEA,UAAA,oBAAC,MAAD;KAAa;KAAO,MAAM;KAAgB;IAAW,CAAA;GAClD,GAzBE,EAyBF;EAET,CAAC;CACE,CAAA,EAEP,CAAA;CAMJ,OAAO,SACL,oBAAC,WAAW,UAAZ;EAAqB,KAAK;EAAc,UAAA;CAA0B,CAAA,IAElE,oBAAC,OAAD;EAAK,WAAU;EAAwB,KAAK;EACzC,UAAA;CACE,CAAA;AAET,CACF;AAEA,qBAAqB,cAAc;AAEnC,IAAM,kBAAkB;;AAOxB,IAAM,kBACJ,OACA,SACA,YACA,gBACA,gBACA,QACG;CACH,MAAM,UAAU,MAAM,CAAC;CACvB,OAAO,cAAc;EACnB,IAAI,WAAW,MACb,OAAO;EAGT,MAAM,mBAAmB,iBAAiB;EAC1C,MAAM,mBAAmB,iBAAiB;EAC1C,MAAM,QAAQ,MAAM;EACpB,IAAI,SAAS,KAAK,oBAAoB,GACpC,OAAO;EAMT,IAAI,OAAO,KAAK,IAAI,GAAG,KAAK,OAAO,QAAQ,UAAU,mBAAmB,MAAM,CAAC;EAC/E,IAAI,mBAAmB,GACM;QAAA,SAAS,OAAO,KAAK,SAAS,OACjC,kBAAkB;IAExC,MAAM,UAAU,KAAK,MAAM,QAAQ,UAAU,mBAAmB,MAAM;IACtE,KAAK,SAAS,UAAU,KAAK,SAAS,WAAW,kBAC/C,OAAO;GAEX;;EAIF,OAAO,KAAK,IAAI,GADA,cAAc,OAAO,KAAK,IAAI,MAAM,UAAU,IAAI,IACxC;CAC5B,GAAG;EAAC;EAAS;EAAO;EAAS;EAAY;EAAgB;EAAgB;CAAG,CAAC;AAC/E;AAMA,IAAa,UAAU;CACrB,MAAM;CACN,SAAS;CACT,UAAU;AACZ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/useFlip.ts","../../src/layout.ts","../../src/useMasonryLayout.ts","../../src/Masonry.tsx"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport { type RefObject, useLayoutEffect, useRef } from 'react';\n\nimport { type Rect } from './layout.ts';\n\nconst DURATION = 200;\nconst EASING = 'cubic-bezier(0.2, 0, 0, 1)';\n\n/**\n * Above this many tiles added/removed in a single layout, snap instead of animate.\n * Reflows this large are the initial bulk render or a data swap, not an incremental\n * edit, and animating dozens of tiles at once is the source of the perf/bunching jank.\n */\nconst ANIMATE_MAX_DELTA = 8;\n\nexport const prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n\n/**\n * Decide whether a layout transition should animate. Animate only genuine small\n * incremental edits on a stable container: a resize snaps (the whole grid moves),\n * and a zero add/remove delta means either the initial bulk render's height-settling\n * pass or a pure resize — both snap so the grid never animates into place from the\n * degenerate all-heights-zero layout.\n */\nexport const shouldAnimateReflow = ({\n added,\n removed,\n resized,\n maxDelta = ANIMATE_MAX_DELTA,\n}: {\n added: number;\n removed: number;\n resized: boolean;\n maxDelta?: number;\n}): boolean => !resized && added + removed > 0 && added + removed <= maxDelta;\n\nexport type UseFlipOptions = {\n /** Tile wrappers by id, kept live by the layout hook. */\n nodes: RefObject<Map<string, HTMLElement>>;\n /** Item ids in render order (aligned with `rects`). */\n ids: readonly string[];\n /** Target positions (aligned with `ids`). */\n rects: readonly Rect[];\n /** Current column count; a change marks a resize, which snaps rather than animates. */\n columnCount: number;\n /** Current content width (px); a change marks a resize, which snaps rather than animates. */\n containerWidth: number;\n /** Disable to snap without animating (also skipped under reduced-motion and on bulk reflows). */\n enabled: boolean;\n};\n\n/**\n * Animates tile position changes with FLIP: tiles that moved between layouts\n * transition from their previous translate to the new one via the Web Animations\n * API; freshly-added tiles fade/scale in. Respects `prefers-reduced-motion`.\n */\nexport const useFlip = ({ nodes, ids, rects, columnCount, containerWidth, enabled }: UseFlipOptions): void => {\n const previous = useRef(new Map<string, { x: number; y: number }>());\n const previousLayout = useRef<{ columnCount: number; containerWidth: number } | null>(null);\n\n useLayoutEffect(() => {\n // Without committed positions this is the first non-empty layout — snap it (the initial\n // render), even for a small set that would otherwise read as a handful of added tiles.\n const hasPriorPositions = previous.current.size > 0;\n // Classify the reflow before recording new positions: added/removed relative to\n // the last rendered id set, and whether the container dimensions changed (resize).\n const idSet = new Set(ids);\n let added = 0;\n for (const id of ids) {\n if (!previous.current.has(id)) {\n added += 1;\n }\n }\n let removed = 0;\n for (const id of previous.current.keys()) {\n if (!idSet.has(id)) {\n removed += 1;\n }\n }\n const resized =\n previousLayout.current !== null &&\n (previousLayout.current.columnCount !== columnCount || previousLayout.current.containerWidth !== containerWidth);\n previousLayout.current = { columnCount, containerWidth };\n\n const animate =\n hasPriorPositions && enabled && !prefersReducedMotion() && shouldAnimateReflow({ added, removed, resized });\n const seen = new Set<string>();\n\n ids.forEach((id, index) => {\n const rect = rects[index];\n const element = nodes.current.get(id);\n if (!rect || !element) {\n return;\n }\n seen.add(id);\n\n const prior = previous.current.get(id);\n previous.current.set(id, { x: rect.x, y: rect.y });\n\n // Style already holds the target translate; snapping needs no animation.\n if (!animate) {\n return;\n }\n\n if (prior) {\n if (prior.x !== rect.x || prior.y !== rect.y) {\n element.animate(\n [\n { transform: `translate(${prior.x}px, ${prior.y}px)` },\n { transform: `translate(${rect.x}px, ${rect.y}px)` },\n ],\n { duration: DURATION, easing: EASING },\n );\n }\n } else {\n element.animate(\n [\n { opacity: 0, transform: `translate(${rect.x}px, ${rect.y}px) scale(0.98)` },\n { opacity: 1, transform: `translate(${rect.x}px, ${rect.y}px) scale(1)` },\n ],\n { duration: DURATION, easing: EASING },\n );\n }\n });\n\n // Forget positions for tiles no longer rendered.\n for (const id of previous.current.keys()) {\n if (!seen.has(id)) {\n previous.current.delete(id);\n }\n }\n }, [nodes, ids, rects, columnCount, containerWidth, enabled]);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nexport type Rect = {\n /** Horizontal offset (px) of the tile's left edge. */\n x: number;\n /** Vertical offset (px) of the tile's top edge. */\n y: number;\n /** Column the tile was assigned to. */\n column: number;\n};\n\nexport type LayoutResult = {\n /** Position of each tile, in input order. */\n rects: Rect[];\n /** Width (px) shared by every column. */\n columnWidth: number;\n /** Total content height (px), including the perimeter gap. */\n height: number;\n};\n\nexport type LayoutOptions = {\n /** Measured tile heights (px), in item order. Unmeasured tiles pass 0. */\n heights: readonly number[];\n /** Number of columns to lay out across. */\n columnCount: number;\n /** Available content width (px), already net of any scrollbar allowance. */\n containerWidth: number;\n /** Space (px) between tiles and, vertically, around the grid perimeter. */\n gapPx: number;\n /** Optional cap on column width (px); leftover width centers the columns. */\n maxColumnWidthPx?: number;\n /** Centre capped columns in the container. Off aligns them to the start, leaving the slack at the end. */\n centered?: boolean;\n};\n\n/**\n * Lay tiles out into balanced columns using column-major greedy assignment: each\n * tile is placed in the currently shortest column (ties resolve to the lowest\n * index for stable ordering). Pure and synchronous so column balancing is unit\n * testable without a DOM.\n *\n * Columns are separated by a single gap. They stretch to fill `containerWidth`\n * unless `maxColumnWidthPx` caps them narrower, in which case the leftover width\n * is split evenly so the grid stays centred (the outer margin grows beyond the\n * gap) — or, with `centered` off, left entirely at the end so the columns align to\n * the start. The base left/right perimeter is owned by the scroll container (via\n * its `--gutter`); the layout adds any centring offset plus the top/bottom perimeter.\n */\n/**\n * Width every column gets, before any tile is placed. Independent of the tiles themselves — which is\n * what lets a caller key cached tile heights by the width they were measured at.\n */\nexport const getColumnWidth = ({\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n}: Pick<LayoutOptions, 'columnCount' | 'containerWidth' | 'gapPx' | 'maxColumnWidthPx'>): number => {\n const columns = Math.max(1, Math.floor(columnCount));\n const fillColumnWidth = (containerWidth - (columns - 1) * gapPx) / columns;\n return maxColumnWidthPx && maxColumnWidthPx > 0 ? Math.min(fillColumnWidth, maxColumnWidthPx) : fillColumnWidth;\n};\n\nexport const layout = ({\n heights,\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n centered = true,\n}: LayoutOptions): LayoutResult => {\n const columns = Math.max(1, Math.floor(columnCount));\n const columnWidth = getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx });\n\n // Centre the (possibly capped) columns within the container, unless start-aligned.\n const usedWidth = columns * columnWidth + (columns - 1) * gapPx;\n const sideInset = centered ? Math.max(0, (containerWidth - usedWidth) / 2) : 0;\n\n // Seed each column with the top gap so the first row clears the perimeter.\n const columnHeights = new Array<number>(columns).fill(gapPx);\n\n const rects: Rect[] = heights.map((tileHeight) => {\n let target = 0;\n for (let column = 1; column < columns; ++column) {\n if (columnHeights[column] < columnHeights[target]) {\n target = column;\n }\n }\n\n const rect: Rect = {\n x: sideInset + target * (columnWidth + gapPx),\n y: columnHeights[target],\n column: target,\n };\n columnHeights[target] += tileHeight + gapPx;\n return rect;\n });\n\n // Each column already carries a trailing gap, which becomes the bottom perimeter.\n const tallest = columnHeights.reduce((max, value) => Math.max(max, value), 0);\n const height = heights.length === 0 ? 0 : tallest;\n return { rects, columnWidth, height };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\n\nimport { type LayoutResult, getColumnWidth, layout } from './layout.ts';\n\n/** Sub-pixel changes below this threshold (px) don't trigger a re-layout. */\nconst HEIGHT_EPSILON = 0.5;\n\n/** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */\nexport const ESTIMATED_TILE_HEIGHT = 280;\n\n/**\n * Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the\n * column width the tile was measured at. Module scope on purpose: a grid unmounts whenever its tab\n * or route does, and re-measuring from scratch is what makes a remount wait — hidden — for the\n * layout to settle. With a warm entry the first layout is already final, so the grid can be shown on\n * the first frame.\n *\n * The `cacheKey` scope is required rather than optional: tile ids default to the array index, so a\n * process-wide cache keyed on id alone would serve one grid's height for `\"0\"` to an unrelated grid\n * and reveal it before it was ever measured. A grid that passes no key keeps its heights to itself.\n *\n * Height is stored with its width because a card reflows: at a different width the entry is still a\n * far better estimate than the default, but it is not a measurement.\n */\nconst heightCache = new Map<string, { width: number; height: number }>();\n\n/** Cap on remembered tiles; oldest are evicted first (insertion order). */\nconst HEIGHT_CACHE_LIMIT = 2_000;\n\n/** Cache entries are namespaced by scope; `\\u0000` cannot occur in an id or a caller's key. */\nconst scopedKey = (scope: string, id: string) => `${scope}\\u0000${id}`;\n\nconst rememberHeight = (scope: string | undefined, id: string, width: number, height: number): void => {\n if (scope === undefined) {\n return;\n }\n\n const key = scopedKey(scope, id);\n // Re-insert so recently-seen tiles move to the end and survive eviction.\n heightCache.delete(key);\n heightCache.set(key, { width, height });\n if (heightCache.size > HEIGHT_CACHE_LIMIT) {\n const oldest = heightCache.keys().next();\n if (!oldest.done) {\n heightCache.delete(oldest.value);\n }\n }\n};\n\n/** Clears the shared height cache. Exported for tests and for callers that recycle ids. */\nexport const clearHeightCache = (): void => heightCache.clear();\n\nconst allCached = (scope: string | undefined, ids: readonly string[], width: number): boolean =>\n scope !== undefined && ids.every((id) => heightCache.get(scopedKey(scope, id))?.width === width);\n\nexport type MasonryLayout = LayoutResult & {\n /** True once every tile has a height measured at the current column width, so positions are final. */\n measured: boolean;\n cachedAtFirstLayout: boolean | undefined;\n /**\n * Ids the layout has some height for — measured now, or remembered from a previous mount or width.\n * Anything outside this set is sitting at a guess and should not be painted.\n */\n knownIds: ReadonlySet<string>;\n /** Stable ref callback for the tile wrapper of `id` (measures + registers it). */\n getTileRef: (id: string) => (element: HTMLElement | null) => void;\n /** Live map of currently-mounted tile wrappers by id (for FLIP positioning). */\n nodes: RefObject<Map<string, HTMLElement>>;\n};\n\nexport type UseMasonryLayoutOptions = {\n /** Ids of the items to lay out, in render order. */\n ids: readonly string[];\n columnCount: number;\n /** Available content width (px), net of scrollbar allowance. */\n containerWidth: number;\n gapPx: number;\n /** Optional cap on column width (px). */\n maxColumnWidthPx?: number;\n /** Centre capped columns in the container (see `layout`). */\n centered?: boolean;\n /**\n * Scope for remembered tile heights, e.g. the collection's URI. Omit when ids are not stable and\n * unique across the app (the default index ids are not) — heights are then per-instance, and a\n * remount re-measures.\n */\n cacheKey?: string;\n};\n\n/**\n * Measures tile heights via a shared ResizeObserver and computes balanced column\n * positions. Heights are keyed by item id so reorders and removals reuse prior\n * measurements; a version counter re-runs the pure layout when a height changes.\n */\nexport const useMasonryLayout = ({\n ids,\n columnCount,\n containerWidth,\n gapPx,\n maxColumnWidthPx,\n centered,\n cacheKey,\n}: UseMasonryLayoutOptions): MasonryLayout => {\n const heights = useRef(new Map<string, number>());\n // Survives pruning, unlike `heights`: when the item set is replaced wholesale (paging through\n // duplicate groups) every id is new, and without a remembered average the estimate would fall back\n // to the ~280px default and paint the swap hundreds of pixels out before the real heights land.\n const estimate = useRef(ESTIMATED_TILE_HEIGHT);\n const nodes = useRef(new Map<string, HTMLElement>());\n const elementIds = useRef(new WeakMap<Element, string>());\n const refCallbacks = useRef(new Map<string, (element: HTMLElement | null) => void>());\n const [version, setVersion] = useState(0);\n // The observer is created once, so it reads the current column width and scope through refs.\n const widthRef = useRef(0);\n const scopeRef = useRef<string | undefined>(cacheKey);\n const cachedAtFirstLayout = useRef<boolean | undefined>(undefined);\n\n const record = (id: string, height: number): boolean => {\n const previous = heights.current.get(id);\n if (previous !== undefined && Math.abs(previous - height) <= HEIGHT_EPSILON) {\n return false;\n }\n heights.current.set(id, height);\n rememberHeight(scopeRef.current, id, widthRef.current, height);\n return true;\n };\n\n const relayout = (): void => {\n const values = [...heights.current.values()];\n if (values.length > 0) {\n estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;\n }\n setVersion((value) => value + 1);\n };\n\n const observer = useMemo(() => {\n if (typeof ResizeObserver === 'undefined') {\n return undefined;\n }\n\n return new ResizeObserver((entries) => {\n let changed = false;\n for (const entry of entries) {\n const id = elementIds.current.get(entry.target);\n const element = id === undefined ? undefined : nodes.current.get(id);\n if (id !== undefined && element) {\n changed = record(id, element.offsetHeight) || changed;\n }\n }\n if (changed) {\n relayout();\n }\n });\n }, []);\n\n const measureNewTiles = (): void => {\n let changed = false;\n for (const [id, element] of nodes.current) {\n if (!heights.current.has(id)) {\n changed = record(id, element.offsetHeight) || changed;\n }\n }\n if (changed) {\n relayout();\n }\n };\n useLayoutEffect(measureNewTiles);\n\n useEffect(() => () => observer?.disconnect(), [observer]);\n\n const getTileRef = useCallback(\n (id: string) => {\n let callback = refCallbacks.current.get(id);\n if (!callback) {\n callback = (element: HTMLElement | null) => {\n const previous = nodes.current.get(id);\n if (previous === element) {\n return;\n }\n if (previous) {\n observer?.unobserve(previous);\n elementIds.current.delete(previous);\n }\n if (element) {\n nodes.current.set(id, element);\n elementIds.current.set(element, id);\n if (observer) {\n observer.observe(element);\n } else {\n // Without a ResizeObserver nothing would ever report a height, leaving every tile\n // hidden behind the estimate gate. One measurement at mount is worse than live\n // tracking, but it is a layout rather than a blank grid.\n heights.current.set(id, element.offsetHeight);\n rememberHeight(scopeRef.current, id, widthRef.current, element.offsetHeight);\n setVersion((value) => value + 1);\n }\n } else {\n nodes.current.delete(id);\n }\n };\n refCallbacks.current.set(id, callback);\n }\n return callback;\n },\n [observer],\n );\n\n const columnWidth = Math.round(getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx }));\n widthRef.current = columnWidth;\n scopeRef.current = cacheKey;\n\n const result = useMemo(() => {\n // Prune measurements/callbacks for ids no longer present so the maps track the\n // live item set.\n const present = new Set(ids);\n for (const id of heights.current.keys()) {\n if (!present.has(id)) {\n heights.current.delete(id);\n }\n }\n for (const id of refCallbacks.current.keys()) {\n if (!present.has(id)) {\n refCallbacks.current.delete(id);\n }\n }\n\n // Height for each tile, best source first: measured this mount, remembered at this exact column\n // width (as good as measured — the tile has not reflowed), remembered at some other width (a\n // close estimate, since content usually dominates), else the running average.\n if (cachedAtFirstLayout.current === undefined && containerWidth > 0) {\n cachedAtFirstLayout.current = allCached(cacheKey, ids, columnWidth);\n }\n\n const measuredIds = new Set<string>();\n const knownIds = new Set<string>();\n const tileHeights = ids.map((id) => {\n const measured = heights.current.get(id);\n if (measured !== undefined) {\n measuredIds.add(id);\n knownIds.add(id);\n return measured;\n }\n\n const cached = cacheKey === undefined ? undefined : heightCache.get(scopedKey(cacheKey, id));\n if (cached) {\n knownIds.add(id);\n if (cached.width === columnWidth) {\n measuredIds.add(id);\n }\n return cached.height;\n }\n\n return estimate.current;\n });\n\n return {\n ...layout({ heights: tileHeights, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered }),\n measured: measuredIds.size === ids.length,\n cachedAtFirstLayout: cachedAtFirstLayout.current,\n knownIds,\n };\n // `version` re-runs layout when a measured height changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ids, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered, columnWidth, cacheKey, version]);\n\n return { ...result, getTileRef, nodes };\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport React, {\n type ComponentProps,\n type ComponentType,\n type CSSProperties,\n type JSX,\n type MouseEvent,\n type PropsWithChildren,\n type Ref,\n type RefObject,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\nimport { useResizeDetector } from 'react-resize-detector';\n\nimport { useFocusGroup } from '@dxos/react-focus';\nimport { createContext } from '@dxos/react-hooks';\nimport * as Hooks from '@dxos/react-ui/Hooks';\nimport * as ScrollArea from '@dxos/react-ui/ScrollArea';\nimport * as Util from '@dxos/react-ui/Util';\nimport { cardMaxInlineSize, cardMinInlineSize } from '@dxos/ui-theme';\n\nimport { prefersReducedMotion, useFlip } from './useFlip.ts';\nimport { useMasonryLayout } from './useMasonryLayout.ts';\n\n/** Reveal the grid once the layout has been stable for this long (the initial reflow has settled). */\ntype ScrollAreaRootProps = ComponentProps<typeof ScrollArea.Root>;\n\nconst REVEAL_SETTLE_MS = 80;\n\n/** Reveal the grid no later than this after mount, so churning content never hides it indefinitely. */\nconst REVEAL_DEADLINE_MS = 1200;\n\n/** The element's content-box width, as the resize detector reports it: net of padding and scrollbar. */\nconst getContentWidth = (element: HTMLElement): number => {\n const style = getComputedStyle(element);\n return element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);\n};\n\nconst useContentWidth = (ref: RefObject<HTMLDivElement | null>): number => {\n // Throttle width changes: each update recomputes the column count and the full tile layout,\n // so coalesce rapid resizes (drag, ScrollArea reflow) into at most one relayout per interval.\n const { width: observedWidth } = useResizeDetector({ targetRef: ref, refreshMode: 'throttle', refreshRate: 200 });\n const [mountWidth, setMountWidth] = useState(0);\n useLayoutEffect(() => {\n if (ref.current) {\n setMountWidth(getContentWidth(ref.current));\n }\n }, [ref]);\n return observedWidth ?? mountWidth;\n};\n\n//\n// Context\n//\n\ntype MasonryContextValue = {\n /** Render component for each masonry item. Receives `selected` when the grid is selectable. */\n Tile: ComponentType<{ data: any; index: number; selected?: boolean }>;\n /** Override auto-calculated column count. */\n columns: number | undefined;\n /** Upper bound on number of columns. */\n maxColumns: number | undefined;\n /** Minimum column width in rem. */\n minColumnWidth: number;\n /** Maximum column width in rem. */\n maxColumnWidth: number;\n /** Space applied uniformly between tiles and around the grid perimeter, in rem. */\n gap: number;\n /**\n * Animate reflow when a small number of tiles are added or removed. Disabled, or on a\n * bulk change (initial render, data swap) or resize, tiles snap to position instead.\n */\n animate: boolean;\n /**\n * Centre the columns when `maxColumnWidth` caps them narrower than the container. Off aligns them\n * to the start instead, which reads better when the grid sits in a form or list flow whose other\n * rows are start-aligned.\n */\n centered: boolean;\n};\n\nconst MASONRY_NAME = 'Masonry';\n\nconst [MasonryProvider, useMasonryContext] = createContext<MasonryContextValue>(MASONRY_NAME);\n\n//\n// Root\n//\n\ntype MasonryRootProps = PropsWithChildren<Partial<MasonryContextValue>>;\n\nconst MasonryRoot = ({\n children,\n Tile,\n columns = undefined,\n maxColumns = undefined,\n minColumnWidth = cardMinInlineSize,\n maxColumnWidth = cardMaxInlineSize,\n gap = 0.75,\n animate = true,\n centered = true,\n}: MasonryRootProps) => (\n <MasonryProvider\n Tile={Tile!}\n columns={columns}\n maxColumns={maxColumns}\n minColumnWidth={minColumnWidth}\n maxColumnWidth={maxColumnWidth}\n gap={gap}\n animate={animate}\n centered={centered}\n >\n {children}\n </MasonryProvider>\n);\n\nMasonryRoot.displayName = 'Masonry.Root';\n\n//\n// Content\n//\n// The outer wrapper: renders the ScrollArea.Root. `padding` sets the inline gutter the\n// Viewport pads its content with (`--gutter`, the grid gap); the Viewport measures its own\n// content box, so the gutter and the thumb are accounted for whatever is configured here.\n//\n\ntype MasonryContentProps = Util.ThemedClassName<\n PropsWithChildren<\n Pick<ScrollAreaRootProps, 'scrollbars'> & {\n /** Inline gutter equal to the grid gap, so the perimeter matches the inter-column gap. */\n padding?: boolean;\n }\n >\n>;\n\nconst MasonryContentInner = Util.composable<HTMLDivElement, MasonryContentProps>(\n ({ children, scrollbars, padding = true, ...props }, forwardedRef) => {\n const { gap } = useMasonryContext('Masonry.Content');\n const style: CSSProperties & Record<'--gutter', string> = { '--gutter': padding ? `${gap}rem` : '0px' };\n return (\n <ScrollArea.Root\n // `size-full`: the grid is a pane of its own and fills its host, as a Panel does, whatever the host's display.\n {...Util.composableProps(props, { classNames: 'size-full', style })}\n scrollbars={scrollbars}\n ref={forwardedRef}\n >\n {children}\n </ScrollArea.Root>\n );\n },\n);\n\nMasonryContentInner.displayName = 'Masonry.Content';\n\nconst MasonryContent = MasonryContentInner as (\n props: MasonryContentProps & {\n ref?: Ref<HTMLDivElement | null>;\n },\n) => JSX.Element;\n\n//\n// Viewport\n//\n// The inner render layer: renders the ScrollArea.Viewport wrapped around the\n// absolute layout engine. Each tile is positioned with translate(x, y) into a\n// balanced (shortest-column-first) grid; reflow is animated with FLIP. Style\n// this layer separately from Content to control the tile grid.\n//\n\ntype MasonryViewportProps<Item> = Util.ThemedClassName<{\n /** Items to render in the masonry grid. */\n items: readonly Item[];\n /** Extract a stable key from an item, aligned with react-ui-mosaic's getId. */\n getId?: (data: Item) => string;\n /**\n * Scope for remembering tile heights across mounts, e.g. the collection's URI. With one, a\n * remount renders on the first frame instead of waiting for the layout to settle. Omit it when\n * `getId` is omitted: the default index ids are not unique across grids.\n */\n cacheKey?: string;\n /**\n * Ids of the currently-selected tiles. When `onSelect` is also provided the grid becomes\n * selectable: selected tiles render an outline + `aria-selected`, and clicking a tile emits\n * {@link onSelect}. Selection STATE (single/multi semantics) is owned by the consumer — pair this\n * with `useListSelection` from `@dxos/react-ui-list`.\n */\n selectedIds?: ReadonlySet<string>;\n /** Emitted when a tile is clicked while selectable. The consumer toggles its own selection state. */\n onSelect?: (id: string, event: MouseEvent) => void;\n /**\n * Whether this layer owns scrolling. Set `false` when an ancestor already scrolls (e.g. a form's\n * viewport) to render the grid in a plain full-width block instead of a nested scroll container —\n * the `ScrollArea.Root` that `Masonry.Content` provides is then not needed. Nesting scroll\n * containers also risks collapsing the measured width to the scrollbar gutter, which would\n * suppress the grid entirely (see the width gate below).\n * @default true\n */\n scroll?: boolean;\n}>;\n\nconst MasonryViewportInner = Util.composable<HTMLDivElement, MasonryViewportProps<any>>(\n ({ items, getId, cacheKey, selectedIds, onSelect, scroll = true, ...props }, forwardedRef) => {\n const { Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered } =\n useMasonryContext('Masonry.Viewport');\n const remInPx = Hooks.usePx(1);\n // Measure the viewport's own content box (net of padding and scrollbar) rather\n // than deriving it from the root width, so the grid tracks the actual available\n // width for any ScrollArea density (thin/scrollbars/padding) without duplicating\n // the theme's gutter math.\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const contentWidth = useContentWidth(viewportRef);\n const columnCount = useColumnCount(contentWidth, columns, maxColumns, minColumnWidth, maxColumnWidth, gap);\n\n // The grid fills the measured content box; the layout caps columns at\n // `maxColumnWidth` and centres them, so no scrollbar/padding math is duplicated here.\n const gapPx = gap * remInPx;\n const ids = useMemo(() => items.map((item, index) => getId?.(item) ?? String(index)), [items, getId]);\n const { rects, columnWidth, height, getTileRef, nodes, measured, cachedAtFirstLayout, knownIds } = useMasonryLayout(\n {\n ids,\n columnCount,\n containerWidth: contentWidth,\n gapPx,\n maxColumnWidthPx: maxColumnWidth * remInPx,\n centered,\n cacheKey,\n },\n );\n useFlip({ nodes, ids, rects, columnCount, containerWidth: contentWidth, enabled: animate });\n\n // Hide the grid until the layout stops changing, then fade in; latch on so later edits never\n // re-hide it. Revealing on the first measurement is not enough: tiles mount collapsed (their\n // poster reserves height a frame later), so the first pass stacks them bunched at the top and\n // only settles over the next few reflows. Debounce on `rects` identity — which changes on every\n // relayout — and reveal once it has been stable for a beat, with a hard deadline as a backstop.\n const [revealed, setRevealed] = useState(false);\n useEffect(() => {\n if (revealed || contentWidth <= 0) {\n return;\n }\n if (cachedAtFirstLayout) {\n setRevealed(true);\n return;\n }\n if (!measured) {\n return;\n }\n const timer = setTimeout(() => setRevealed(true), REVEAL_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [revealed, measured, cachedAtFirstLayout, rects, contentWidth]);\n useEffect(() => {\n const deadline = setTimeout(() => setRevealed(true), REVEAL_DEADLINE_MS);\n return () => clearTimeout(deadline);\n }, []);\n\n // Arrow-key navigation across tiles. The `both` axis moves focus through the items as flat\n // next/previous in DOM order on all four arrows; `tabbable` keeps each tile its own tab stop.\n const { ref: focusGroupRef, ...focusGroupProps } = useFocusGroup({\n axis: 'both',\n memorizeCurrent: true,\n tabbable: true,\n cyclic: true,\n });\n const gridRef = Hooks.useMergeRefs<HTMLDivElement>([forwardedRef, focusGroupRef]);\n\n // The viewport is the full-width scroll container, padded inline by `--gutter`\n // (the gap, set by Masonry.Content). The grid fills the content box and the layout centres capped columns,\n // so nothing overflows and left/right spacing matches the gap. The viewport always\n // renders so it can be measured; tiles render once a width is known.\n const grid = (\n <>\n {contentWidth > 0 && (\n <div\n {...Util.composableProps(props, {\n classNames: 'relative',\n style: {\n width: `${contentWidth}px`,\n height: `${height}px`,\n opacity: revealed ? 1 : 0,\n // Hidden (not just transparent) before reveal so the settling tiles are neither\n // focusable nor hit-testable; the opacity fade only runs when motion is allowed.\n visibility: revealed ? 'visible' : 'hidden',\n transition: animate && !prefersReducedMotion() ? 'opacity 200ms cubic-bezier(0.2, 0, 0, 1)' : undefined,\n },\n })}\n {...focusGroupProps}\n role='list'\n ref={gridRef}\n >\n {items.map((item, index) => {\n const id = ids[index];\n const rect = rects[index];\n const selectable = !!onSelect;\n const selected = selectedIds?.has(id) ?? false;\n // A tile with no height at all — never measured, nothing remembered — is positioned by\n // a guess. Painting that guess is what flashed a tile hundreds of pixels out of place\n // when the item set was swapped wholesale. A remembered height from another width is\n // close enough to paint, so a resize reflows in place instead of blanking.\n // `visibility` rather than `display`, so the ResizeObserver can still measure it.\n const estimated = !knownIds.has(id);\n return (\n <div\n key={id}\n // Let the tile clamp its card: a card's own min-width must not exceed\n // the column, or a narrow (single-column, mobile) container overflows\n // and shows a horizontal scrollbar.\n className={[\n '*:min-w-0!',\n selectable && 'cursor-pointer',\n selected && 'rounded-md ring-2 ring-inset ring-primary-500',\n ]\n .filter(Boolean)\n .join(' ')}\n ref={getTileRef(id)}\n role='listitem'\n aria-selected={selectable ? selected : undefined}\n onClick={onSelect ? (event) => onSelect(id, event) : undefined}\n style={{\n position: 'absolute',\n insetBlockStart: 0,\n insetInlineStart: 0,\n width: `${columnWidth}px`,\n transform: rect ? `translate(${rect.x}px, ${rect.y}px)` : undefined,\n visibility: estimated ? 'hidden' : undefined,\n }}\n >\n <Tile index={index} data={item} selected={selected} />\n </div>\n );\n })}\n </div>\n )}\n </>\n );\n\n // Not `dx-expand` in the non-scrolling case: the width gate needs a definite inline size\n // (`w-full min-w-0`) without claiming the block axis, which would fight the surrounding flow —\n // the grid's height comes from the computed layout.\n return scroll ? (\n <ScrollArea.Viewport classNames='px-(--gutter)' ref={viewportRef}>\n {grid}\n </ScrollArea.Viewport>\n ) : (\n <div className='flex-1 w-full min-w-0' ref={viewportRef}>\n {grid}\n </div>\n );\n },\n);\n\nMasonryViewportInner.displayName = 'Masonry.Viewport';\n\nconst MasonryViewport = MasonryViewportInner as <Item>(\n props: MasonryViewportProps<Item> & {\n ref?: Ref<HTMLDivElement | null>;\n },\n) => JSX.Element;\n\n/** Compute column count from container width and column constraints. */\nconst useColumnCount = (\n width: number,\n columns: number | undefined,\n maxColumns: number | undefined,\n minColumnWidth: number,\n maxColumnWidth: number,\n gap: number,\n) => {\n const remInPx = Hooks.usePx(1);\n return useMemo(() => {\n if (columns != null) {\n return columns;\n }\n\n const minColumnWidthPx = minColumnWidth * remInPx;\n const maxColumnWidthPx = maxColumnWidth * remInPx;\n const gapPx = gap * remInPx;\n if (width <= 0 || minColumnWidthPx <= 0) {\n return 1;\n }\n\n // `width` is the content box; the outer perimeter is owned by the scroll\n // container, so only interior gaps count: N columns fit when\n // N * colWidth + (N - 1) * gap <= width, i.e. N <= (width + gap) / (colWidth + gap).\n let cols = Math.max(1, Math.floor((width + gapPx) / (minColumnWidthPx + gapPx)));\n if (maxColumnWidthPx > 0) {\n const effectiveColWidth = (width - (cols - 1) * gapPx) / cols;\n if (effectiveColWidth > maxColumnWidthPx) {\n // Try to add columns to keep cards below maxColumnWidth, but never violate minColumnWidth.\n const maxCols = Math.ceil((width + gapPx) / (maxColumnWidthPx + gapPx));\n if ((width - (maxCols - 1) * gapPx) / maxCols >= minColumnWidthPx) {\n cols = maxCols;\n }\n }\n }\n\n const clamped = maxColumns != null ? Math.min(cols, maxColumns) : cols;\n return Math.max(1, clamped);\n }, [remInPx, width, columns, maxColumns, minColumnWidth, maxColumnWidth, gap]);\n};\n\n//\n// Masonry\n//\n\nexport const Masonry = {\n Root: MasonryRoot,\n Content: MasonryContent,\n Viewport: MasonryViewport,\n};\n\nexport type { MasonryContentProps, MasonryRootProps, MasonryViewportProps };\n"],"mappings":";;;;;;;;;;AAQA,IAAM,WAAW;AACjB,IAAM,SAAS;;;;;;AAOf,IAAM,oBAAoB;AAE1B,IAAa,6BACX,OAAO,WAAW,eAAe,OAAO,aAAa,kCAAkC,CAAC,CAAC;;;;;;;;AAS3F,IAAa,uBAAuB,EAClC,OACA,SACA,SACA,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,KAAK,IAAI,GADA,cAAc,OAAO,KAAK,IAAI,MAAM,UAAU,IAAI,IACxC;CAC5B,GAAG;EAAC;EAAS;EAAO;EAAS;EAAY;EAAgB;EAAgB;CAAG,CAAC;AAC/E;AAMA,IAAa,UAAU;CACrB,MAAM;CACN,SAAS;CACT,UAAU;AACZ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Masonry.browser.test.d.ts","sourceRoot":"","sources":["../../../src/Masonry.browser.test.tsx"],"names":[],"mappings":""}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
import { type ComponentType, type JSX, type MouseEvent, type PropsWithChildren, type Ref } from 'react';
|
|
2
|
-
import
|
|
1
|
+
import { type ComponentProps, type ComponentType, type JSX, type MouseEvent, type PropsWithChildren, type Ref } from 'react';
|
|
2
|
+
import * as ScrollArea from '@dxos/react-ui/ScrollArea';
|
|
3
|
+
import * as Util from '@dxos/react-ui/Util';
|
|
4
|
+
/** Reveal the grid once the layout has been stable for this long (the initial reflow has settled). */
|
|
5
|
+
type ScrollAreaRootProps = ComponentProps<typeof ScrollArea.Root>;
|
|
3
6
|
type MasonryContextValue = {
|
|
4
7
|
/** Render component for each masonry item. Receives `selected` when the grid is selectable. */
|
|
5
8
|
Tile: ComponentType<{
|
|
@@ -25,8 +28,7 @@ type MasonryContextValue = {
|
|
|
25
28
|
/**
|
|
26
29
|
* Centre the columns when `maxColumnWidth` caps them narrower than the container. Off aligns them
|
|
27
30
|
* to the start instead, which reads better when the grid sits in a form or list flow whose other
|
|
28
|
-
* rows are start-aligned.
|
|
29
|
-
* scrollbar-padding balance and says nothing about column alignment.
|
|
31
|
+
* rows are start-aligned.
|
|
30
32
|
*/
|
|
31
33
|
centered: boolean;
|
|
32
34
|
};
|
|
@@ -35,8 +37,11 @@ declare const MasonryRoot: {
|
|
|
35
37
|
({ children, Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered, }: MasonryRootProps): JSX.Element;
|
|
36
38
|
displayName: string;
|
|
37
39
|
};
|
|
38
|
-
type MasonryContentProps = ThemedClassName<PropsWithChildren<Pick<ScrollAreaRootProps, 'scrollbars'
|
|
39
|
-
|
|
40
|
+
type MasonryContentProps = Util.ThemedClassName<PropsWithChildren<Pick<ScrollAreaRootProps, 'scrollbars'> & {
|
|
41
|
+
/** Inline gutter equal to the grid gap, so the perimeter matches the inter-column gap. */
|
|
42
|
+
padding?: boolean;
|
|
43
|
+
}>>;
|
|
44
|
+
type MasonryViewportProps<Item> = Util.ThemedClassName<{
|
|
40
45
|
/** Items to render in the masonry grid. */
|
|
41
46
|
items: readonly Item[];
|
|
42
47
|
/** Extract a stable key from an item, aligned with react-ui-mosaic's getId. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Masonry.d.ts","sourceRoot":"","sources":["../../../src/Masonry.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Masonry.d.ts","sourceRoot":"","sources":["../../../src/Masonry.tsx"],"names":[],"mappings":"AAIA,OAAc,EACZ,KAAK,cAAc,EACnB,KAAK,aAAa,EAElB,KAAK,GAAG,EACR,KAAK,UAAU,EACf,KAAK,iBAAiB,EACtB,KAAK,GAAG,EAOT,MAAM,OAAO,CAAC;AAMf,OAAO,KAAK,UAAU,MAAM,2BAA2B,CAAC;AACxD,OAAO,KAAK,IAAI,MAAM,qBAAqB,CAAC;AAM5C,sGAAsG;AACtG,KAAK,mBAAmB,GAAG,cAAc,CAAC,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;AA8BlE,KAAK,mBAAmB,GAAG;IACzB,+FAA+F;IAC/F,IAAI,EAAE,aAAa,CAAC;QAAE,IAAI,EAAE,GAAG,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACtE,6CAA6C;IAC7C,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,wCAAwC;IACxC,UAAU,EAAE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AG,CAAC,OAAO;IAyPd,QAAQ,GAvDuC,IAAI,SAC5C,oBAAoB,CAAC,IAAI,CAAC,GAAG;QAClC,GAAG,CAAC,EAAE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;KAClC,KACE,GAAG,CAAC,OAAO;CAoDf,CAAC;AAEF,YAAY,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type StoryObj } from '@storybook/react-vite';
|
|
2
2
|
import React from 'react';
|
|
3
|
-
import { type MasonryRootProps } from './Masonry';
|
|
3
|
+
import { type MasonryRootProps } from './Masonry.tsx';
|
|
4
4
|
declare const DefaultStory: (props: MasonryRootProps) => React.JSX.Element;
|
|
5
5
|
declare const meta: {
|
|
6
6
|
title: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Masonry.stories.d.ts","sourceRoot":"","sources":["../../../src/Masonry.stories.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAa,KAAK,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAmB,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"Masonry.stories.d.ts","sourceRoot":"","sources":["../../../src/Masonry.stories.tsx"],"names":[],"mappings":"AAIA,OAAO,EAAa,KAAK,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAmB,MAAM,OAAO,CAAC;AASxC,OAAO,EAAW,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AA2G/D,QAAA,MAAM,YAAY,UAAW,gBAAgB,sBAgD5C,CAAC;AAEF,QAAA,MAAM,IAAI;;;;;QAKN,MAAM;;;;;;;;;;CAQ2B,CAAC;eAEvB,IAAI;AAEnB,KAAK,KAAK,GAAG,QAAQ,CAAC,OAAO,IAAI,CAAC,CAAC;AAEnC,eAAO,MAAM,OAAO,EAAE,KAAU,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export * from './Masonry';
|
|
1
|
+
export * from './Masonry.tsx';
|
|
2
2
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,eAAe,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RefObject } from 'react';
|
|
2
|
-
import { type Rect } from './layout';
|
|
2
|
+
import { type Rect } from './layout.ts';
|
|
3
3
|
export declare const prefersReducedMotion: () => boolean;
|
|
4
4
|
/**
|
|
5
5
|
* Decide whether a layout transition should animate. Animate only genuine small
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useFlip.d.ts","sourceRoot":"","sources":["../../../src/useFlip.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAA2B,MAAM,OAAO,CAAC;AAEhE,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"useFlip.d.ts","sourceRoot":"","sources":["../../../src/useFlip.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAA2B,MAAM,OAAO,CAAC;AAEhE,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AAYxC,eAAO,MAAM,oBAAoB,eACiE,CAAC;AAEnG;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,2CAK7B;IACD,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,KAAG,OAAyE,CAAC;AAE9E,MAAM,MAAM,cAAc,GAAG;IAC3B,yDAAyD;IACzD,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;IAC3C,uDAAuD;IACvD,GAAG,EAAE,SAAS,MAAM,EAAE,CAAC;IACvB,6CAA6C;IAC7C,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;IACvB,uFAAuF;IACvF,WAAW,EAAE,MAAM,CAAC;IACpB,6FAA6F;IAC7F,cAAc,EAAE,MAAM,CAAC;IACvB,iGAAiG;IACjG,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,OAAO,gEAAiE,cAAc,KAAG,IA4ErG,CAAC"}
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { type RefObject } from 'react';
|
|
2
|
-
import { type LayoutResult } from './layout';
|
|
2
|
+
import { type LayoutResult } from './layout.ts';
|
|
3
|
+
/** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */
|
|
4
|
+
export declare const ESTIMATED_TILE_HEIGHT = 280;
|
|
3
5
|
/** Clears the shared height cache. Exported for tests and for callers that recycle ids. */
|
|
4
6
|
export declare const clearHeightCache: () => void;
|
|
5
7
|
export type MasonryLayout = LayoutResult & {
|
|
6
8
|
/** True once every tile has a height measured at the current column width, so positions are final. */
|
|
7
9
|
measured: boolean;
|
|
10
|
+
cachedAtFirstLayout: boolean | undefined;
|
|
8
11
|
/**
|
|
9
12
|
* Ids the layout has some height for — measured now, or remembered from a previous mount or width.
|
|
10
13
|
* Anything outside this set is sitting at a guess and should not be painted.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useMasonryLayout.d.ts","sourceRoot":"","sources":["../../../src/useMasonryLayout.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,
|
|
1
|
+
{"version":3,"file":"useMasonryLayout.d.ts","sourceRoot":"","sources":["../../../src/useMasonryLayout.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAAsE,MAAM,OAAO,CAAC;AAE3G,OAAO,E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