@dxos/react-ui-masonry 0.10.0 → 0.11.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 +482 -0
- package/dist/lib/index.mjs.map +1 -0
- package/dist/types/src/Masonry.d.ts +43 -6
- package/dist/types/src/Masonry.d.ts.map +1 -1
- package/dist/types/src/Masonry.stories.d.ts +9 -1
- package/dist/types/src/Masonry.stories.d.ts.map +1 -1
- package/dist/types/src/layout.d.ts +50 -0
- package/dist/types/src/layout.d.ts.map +1 -0
- package/dist/types/src/layout.test.d.ts +2 -0
- package/dist/types/src/layout.test.d.ts.map +1 -0
- package/dist/types/src/useFlip.d.ts +37 -0
- package/dist/types/src/useFlip.d.ts.map +1 -0
- package/dist/types/src/useFlip.test.d.ts +2 -0
- package/dist/types/src/useFlip.test.d.ts.map +1 -0
- package/dist/types/src/useMasonryLayout.d.ts +42 -0
- package/dist/types/src/useMasonryLayout.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +21 -22
- package/src/Masonry.stories.tsx +149 -37
- package/src/Masonry.tsx +238 -98
- package/src/layout.test.ts +108 -0
- package/src/layout.ts +105 -0
- package/src/useFlip.test.ts +34 -0
- package/src/useFlip.ts +137 -0
- package/src/useMasonryLayout.ts +241 -0
- package/dist/lib/browser/index.mjs +0 -138
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/node-esm/index.mjs +0 -140
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
import { useArrowNavigationGroup } from "@fluentui/react-tabster";
|
|
2
|
+
import { createContext } from "@radix-ui/react-context";
|
|
3
|
+
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
4
|
+
import { useResizeDetector } from "react-resize-detector";
|
|
5
|
+
import { ScrollArea, composable, composableProps, usePx } from "@dxos/react-ui";
|
|
6
|
+
import { cardMaxInlineSize, cardMinInlineSize } from "@dxos/ui-theme";
|
|
7
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
8
|
+
//#region src/useFlip.ts
|
|
9
|
+
var DURATION = 200;
|
|
10
|
+
var EASING = "cubic-bezier(0.2, 0, 0, 1)";
|
|
11
|
+
/**
|
|
12
|
+
* Above this many tiles added/removed in a single layout, snap instead of animate.
|
|
13
|
+
* Reflows this large are the initial bulk render or a data swap, not an incremental
|
|
14
|
+
* edit, and animating dozens of tiles at once is the source of the perf/bunching jank.
|
|
15
|
+
*/
|
|
16
|
+
var ANIMATE_MAX_DELTA = 8;
|
|
17
|
+
var prefersReducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
|
18
|
+
/**
|
|
19
|
+
* Decide whether a layout transition should animate. Animate only genuine small
|
|
20
|
+
* incremental edits on a stable container: a resize snaps (the whole grid moves),
|
|
21
|
+
* and a zero add/remove delta means either the initial bulk render's height-settling
|
|
22
|
+
* pass or a pure resize — both snap so the grid never animates into place from the
|
|
23
|
+
* degenerate all-heights-zero layout.
|
|
24
|
+
*/
|
|
25
|
+
var shouldAnimateReflow = ({ added, removed, resized, maxDelta = ANIMATE_MAX_DELTA }) => !resized && added + removed > 0 && added + removed <= maxDelta;
|
|
26
|
+
/**
|
|
27
|
+
* Animates tile position changes with FLIP: tiles that moved between layouts
|
|
28
|
+
* transition from their previous translate to the new one via the Web Animations
|
|
29
|
+
* API; freshly-added tiles fade/scale in. Respects `prefers-reduced-motion`.
|
|
30
|
+
*/
|
|
31
|
+
var useFlip = ({ nodes, ids, rects, columnCount, containerWidth, enabled }) => {
|
|
32
|
+
const previous = useRef(/* @__PURE__ */ new Map());
|
|
33
|
+
const previousLayout = useRef(null);
|
|
34
|
+
useLayoutEffect(() => {
|
|
35
|
+
const hasPriorPositions = previous.current.size > 0;
|
|
36
|
+
const idSet = new Set(ids);
|
|
37
|
+
let added = 0;
|
|
38
|
+
for (const id of ids) if (!previous.current.has(id)) added += 1;
|
|
39
|
+
let removed = 0;
|
|
40
|
+
for (const id of previous.current.keys()) if (!idSet.has(id)) removed += 1;
|
|
41
|
+
const resized = previousLayout.current !== null && (previousLayout.current.columnCount !== columnCount || previousLayout.current.containerWidth !== containerWidth);
|
|
42
|
+
previousLayout.current = {
|
|
43
|
+
columnCount,
|
|
44
|
+
containerWidth
|
|
45
|
+
};
|
|
46
|
+
const animate = hasPriorPositions && enabled && !prefersReducedMotion() && shouldAnimateReflow({
|
|
47
|
+
added,
|
|
48
|
+
removed,
|
|
49
|
+
resized
|
|
50
|
+
});
|
|
51
|
+
const seen = /* @__PURE__ */ new Set();
|
|
52
|
+
ids.forEach((id, index) => {
|
|
53
|
+
const rect = rects[index];
|
|
54
|
+
const element = nodes.current.get(id);
|
|
55
|
+
if (!rect || !element) return;
|
|
56
|
+
seen.add(id);
|
|
57
|
+
const prior = previous.current.get(id);
|
|
58
|
+
previous.current.set(id, {
|
|
59
|
+
x: rect.x,
|
|
60
|
+
y: rect.y
|
|
61
|
+
});
|
|
62
|
+
if (!animate) return;
|
|
63
|
+
if (prior) {
|
|
64
|
+
if (prior.x !== rect.x || prior.y !== rect.y) element.animate([{ transform: `translate(${prior.x}px, ${prior.y}px)` }, { transform: `translate(${rect.x}px, ${rect.y}px)` }], {
|
|
65
|
+
duration: DURATION,
|
|
66
|
+
easing: EASING
|
|
67
|
+
});
|
|
68
|
+
} else element.animate([{
|
|
69
|
+
opacity: 0,
|
|
70
|
+
transform: `translate(${rect.x}px, ${rect.y}px) scale(0.98)`
|
|
71
|
+
}, {
|
|
72
|
+
opacity: 1,
|
|
73
|
+
transform: `translate(${rect.x}px, ${rect.y}px) scale(1)`
|
|
74
|
+
}], {
|
|
75
|
+
duration: DURATION,
|
|
76
|
+
easing: EASING
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
for (const id of previous.current.keys()) if (!seen.has(id)) previous.current.delete(id);
|
|
80
|
+
}, [
|
|
81
|
+
nodes,
|
|
82
|
+
ids,
|
|
83
|
+
rects,
|
|
84
|
+
columnCount,
|
|
85
|
+
containerWidth,
|
|
86
|
+
enabled
|
|
87
|
+
]);
|
|
88
|
+
};
|
|
89
|
+
//#endregion
|
|
90
|
+
//#region src/layout.ts
|
|
91
|
+
/**
|
|
92
|
+
* Lay tiles out into balanced columns using column-major greedy assignment: each
|
|
93
|
+
* tile is placed in the currently shortest column (ties resolve to the lowest
|
|
94
|
+
* index for stable ordering). Pure and synchronous so column balancing is unit
|
|
95
|
+
* testable without a DOM.
|
|
96
|
+
*
|
|
97
|
+
* Columns are separated by a single gap. They stretch to fill `containerWidth`
|
|
98
|
+
* unless `maxColumnWidthPx` caps them narrower, in which case the leftover width
|
|
99
|
+
* is split evenly so the grid stays centred (the outer margin grows beyond the
|
|
100
|
+
* gap) — or, with `centered` off, left entirely at the end so the columns align to
|
|
101
|
+
* the start. The base left/right perimeter is owned by the scroll container (via
|
|
102
|
+
* its `--gutter`); the layout adds any centring offset plus the top/bottom perimeter.
|
|
103
|
+
*/
|
|
104
|
+
/**
|
|
105
|
+
* Width every column gets, before any tile is placed. Independent of the tiles themselves — which is
|
|
106
|
+
* what lets a caller key cached tile heights by the width they were measured at.
|
|
107
|
+
*/
|
|
108
|
+
var getColumnWidth = ({ columnCount, containerWidth, gapPx, maxColumnWidthPx }) => {
|
|
109
|
+
const columns = Math.max(1, Math.floor(columnCount));
|
|
110
|
+
const fillColumnWidth = (containerWidth - (columns - 1) * gapPx) / columns;
|
|
111
|
+
return maxColumnWidthPx && maxColumnWidthPx > 0 ? Math.min(fillColumnWidth, maxColumnWidthPx) : fillColumnWidth;
|
|
112
|
+
};
|
|
113
|
+
var layout = ({ heights, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered = true }) => {
|
|
114
|
+
const columns = Math.max(1, Math.floor(columnCount));
|
|
115
|
+
const columnWidth = getColumnWidth({
|
|
116
|
+
columnCount,
|
|
117
|
+
containerWidth,
|
|
118
|
+
gapPx,
|
|
119
|
+
maxColumnWidthPx
|
|
120
|
+
});
|
|
121
|
+
const usedWidth = columns * columnWidth + (columns - 1) * gapPx;
|
|
122
|
+
const sideInset = centered ? Math.max(0, (containerWidth - usedWidth) / 2) : 0;
|
|
123
|
+
const columnHeights = new Array(columns).fill(gapPx);
|
|
124
|
+
const rects = heights.map((tileHeight) => {
|
|
125
|
+
let target = 0;
|
|
126
|
+
for (let column = 1; column < columns; ++column) if (columnHeights[column] < columnHeights[target]) target = column;
|
|
127
|
+
const rect = {
|
|
128
|
+
x: sideInset + target * (columnWidth + gapPx),
|
|
129
|
+
y: columnHeights[target],
|
|
130
|
+
column: target
|
|
131
|
+
};
|
|
132
|
+
columnHeights[target] += tileHeight + gapPx;
|
|
133
|
+
return rect;
|
|
134
|
+
});
|
|
135
|
+
const tallest = columnHeights.reduce((max, value) => Math.max(max, value), 0);
|
|
136
|
+
return {
|
|
137
|
+
rects,
|
|
138
|
+
columnWidth,
|
|
139
|
+
height: heights.length === 0 ? 0 : tallest
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/useMasonryLayout.ts
|
|
144
|
+
/** Sub-pixel changes below this threshold (px) don't trigger a re-layout. */
|
|
145
|
+
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
|
+
/**
|
|
149
|
+
* Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the
|
|
150
|
+
* column width the tile was measured at. Module scope on purpose: a grid unmounts whenever its tab
|
|
151
|
+
* or route does, and re-measuring from scratch is what makes a remount wait — hidden — for the
|
|
152
|
+
* layout to settle. With a warm entry the first layout is already final, so the grid can be shown on
|
|
153
|
+
* the first frame.
|
|
154
|
+
*
|
|
155
|
+
* The `cacheKey` scope is required rather than optional: tile ids default to the array index, so a
|
|
156
|
+
* process-wide cache keyed on id alone would serve one grid's height for `"0"` to an unrelated grid
|
|
157
|
+
* and reveal it before it was ever measured. A grid that passes no key keeps its heights to itself.
|
|
158
|
+
*
|
|
159
|
+
* Height is stored with its width because a card reflows: at a different width the entry is still a
|
|
160
|
+
* far better estimate than the default, but it is not a measurement.
|
|
161
|
+
*/
|
|
162
|
+
var heightCache = /* @__PURE__ */ new Map();
|
|
163
|
+
/** Cap on remembered tiles; oldest are evicted first (insertion order). */
|
|
164
|
+
var HEIGHT_CACHE_LIMIT = 2e3;
|
|
165
|
+
/** Cache entries are namespaced by scope; `\u0000` cannot occur in an id or a caller's key. */
|
|
166
|
+
var scopedKey = (scope, id) => `${scope}\u0000${id}`;
|
|
167
|
+
var rememberHeight = (scope, id, width, height) => {
|
|
168
|
+
if (scope === void 0) return;
|
|
169
|
+
const key = scopedKey(scope, id);
|
|
170
|
+
heightCache.delete(key);
|
|
171
|
+
heightCache.set(key, {
|
|
172
|
+
width,
|
|
173
|
+
height
|
|
174
|
+
});
|
|
175
|
+
if (heightCache.size > HEIGHT_CACHE_LIMIT) {
|
|
176
|
+
const oldest = heightCache.keys().next();
|
|
177
|
+
if (!oldest.done) heightCache.delete(oldest.value);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* Measures tile heights via a shared ResizeObserver and computes balanced column
|
|
182
|
+
* positions. Heights are keyed by item id so reorders and removals reuse prior
|
|
183
|
+
* measurements; a version counter re-runs the pure layout when a height changes.
|
|
184
|
+
*/
|
|
185
|
+
var useMasonryLayout = ({ ids, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered, cacheKey }) => {
|
|
186
|
+
const heights = useRef(/* @__PURE__ */ new Map());
|
|
187
|
+
const estimate = useRef(ESTIMATED_TILE_HEIGHT);
|
|
188
|
+
const nodes = useRef(/* @__PURE__ */ new Map());
|
|
189
|
+
const elementIds = useRef(/* @__PURE__ */ new WeakMap());
|
|
190
|
+
const refCallbacks = useRef(/* @__PURE__ */ new Map());
|
|
191
|
+
const [version, setVersion] = useState(0);
|
|
192
|
+
const widthRef = useRef(0);
|
|
193
|
+
const scopeRef = useRef(cacheKey);
|
|
194
|
+
const observer = useMemo(() => {
|
|
195
|
+
if (typeof ResizeObserver === "undefined") return;
|
|
196
|
+
return new ResizeObserver((entries) => {
|
|
197
|
+
let changed = false;
|
|
198
|
+
for (const entry of entries) {
|
|
199
|
+
const id = elementIds.current.get(entry.target);
|
|
200
|
+
if (!id) continue;
|
|
201
|
+
const height = entry.target.offsetHeight;
|
|
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);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}, []);
|
|
216
|
+
useEffect(() => () => observer?.disconnect(), [observer]);
|
|
217
|
+
const getTileRef = useCallback((id) => {
|
|
218
|
+
let callback = refCallbacks.current.get(id);
|
|
219
|
+
if (!callback) {
|
|
220
|
+
callback = (element) => {
|
|
221
|
+
const previous = nodes.current.get(id);
|
|
222
|
+
if (previous === element) return;
|
|
223
|
+
if (previous) {
|
|
224
|
+
observer?.unobserve(previous);
|
|
225
|
+
elementIds.current.delete(previous);
|
|
226
|
+
}
|
|
227
|
+
if (element) {
|
|
228
|
+
nodes.current.set(id, element);
|
|
229
|
+
elementIds.current.set(element, id);
|
|
230
|
+
if (observer) observer.observe(element);
|
|
231
|
+
else {
|
|
232
|
+
heights.current.set(id, element.offsetHeight);
|
|
233
|
+
rememberHeight(scopeRef.current, id, widthRef.current, element.offsetHeight);
|
|
234
|
+
setVersion((value) => value + 1);
|
|
235
|
+
}
|
|
236
|
+
} else nodes.current.delete(id);
|
|
237
|
+
};
|
|
238
|
+
refCallbacks.current.set(id, callback);
|
|
239
|
+
}
|
|
240
|
+
return callback;
|
|
241
|
+
}, [observer]);
|
|
242
|
+
const columnWidth = Math.round(getColumnWidth({
|
|
243
|
+
columnCount,
|
|
244
|
+
containerWidth,
|
|
245
|
+
gapPx,
|
|
246
|
+
maxColumnWidthPx
|
|
247
|
+
}));
|
|
248
|
+
widthRef.current = columnWidth;
|
|
249
|
+
scopeRef.current = cacheKey;
|
|
250
|
+
return {
|
|
251
|
+
...useMemo(() => {
|
|
252
|
+
const present = new Set(ids);
|
|
253
|
+
for (const id of heights.current.keys()) if (!present.has(id)) heights.current.delete(id);
|
|
254
|
+
for (const id of refCallbacks.current.keys()) if (!present.has(id)) refCallbacks.current.delete(id);
|
|
255
|
+
const measuredIds = /* @__PURE__ */ new Set();
|
|
256
|
+
const knownIds = /* @__PURE__ */ new Set();
|
|
257
|
+
return {
|
|
258
|
+
...layout({
|
|
259
|
+
heights: ids.map((id) => {
|
|
260
|
+
const measured = heights.current.get(id);
|
|
261
|
+
if (measured !== void 0) {
|
|
262
|
+
measuredIds.add(id);
|
|
263
|
+
knownIds.add(id);
|
|
264
|
+
return measured;
|
|
265
|
+
}
|
|
266
|
+
const cached = cacheKey === void 0 ? void 0 : heightCache.get(scopedKey(cacheKey, id));
|
|
267
|
+
if (cached) {
|
|
268
|
+
knownIds.add(id);
|
|
269
|
+
if (cached.width === columnWidth) measuredIds.add(id);
|
|
270
|
+
return cached.height;
|
|
271
|
+
}
|
|
272
|
+
return estimate.current;
|
|
273
|
+
}),
|
|
274
|
+
columnCount,
|
|
275
|
+
containerWidth,
|
|
276
|
+
gapPx,
|
|
277
|
+
maxColumnWidthPx,
|
|
278
|
+
centered
|
|
279
|
+
}),
|
|
280
|
+
measured: measuredIds.size === ids.length,
|
|
281
|
+
knownIds
|
|
282
|
+
};
|
|
283
|
+
}, [
|
|
284
|
+
ids,
|
|
285
|
+
columnCount,
|
|
286
|
+
containerWidth,
|
|
287
|
+
gapPx,
|
|
288
|
+
maxColumnWidthPx,
|
|
289
|
+
centered,
|
|
290
|
+
columnWidth,
|
|
291
|
+
cacheKey,
|
|
292
|
+
version
|
|
293
|
+
]),
|
|
294
|
+
getTileRef,
|
|
295
|
+
nodes
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region src/Masonry.tsx
|
|
300
|
+
/** Reveal the grid once the layout has been stable for this long (the initial reflow has settled). */
|
|
301
|
+
var REVEAL_SETTLE_MS = 80;
|
|
302
|
+
/** Reveal the grid no later than this after mount, so churning content never hides it indefinitely. */
|
|
303
|
+
var REVEAL_DEADLINE_MS = 1200;
|
|
304
|
+
var [MasonryProvider, useMasonryContext] = createContext("Masonry");
|
|
305
|
+
var MasonryRoot = ({ children, Tile, columns = void 0, maxColumns = void 0, minColumnWidth = cardMinInlineSize, maxColumnWidth = cardMaxInlineSize, gap = .75, animate = true, centered = true }) => /* @__PURE__ */ jsx(MasonryProvider, {
|
|
306
|
+
Tile,
|
|
307
|
+
columns,
|
|
308
|
+
maxColumns,
|
|
309
|
+
minColumnWidth,
|
|
310
|
+
maxColumnWidth,
|
|
311
|
+
gap,
|
|
312
|
+
animate,
|
|
313
|
+
centered,
|
|
314
|
+
children
|
|
315
|
+
});
|
|
316
|
+
MasonryRoot.displayName = "Masonry.Root";
|
|
317
|
+
var MasonryContentInner = composable(({ children, scrollbars, centered = true, thin = true, padding = true, ...props }, forwardedRef) => {
|
|
318
|
+
const { gap } = useMasonryContext("Masonry.Content");
|
|
319
|
+
return /* @__PURE__ */ jsx(ScrollArea.Root, {
|
|
320
|
+
...composableProps(props, { style: { "--gutter": `${gap}rem` } }),
|
|
321
|
+
scrollbars,
|
|
322
|
+
centered,
|
|
323
|
+
thin,
|
|
324
|
+
padding,
|
|
325
|
+
ref: forwardedRef,
|
|
326
|
+
children
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
MasonryContentInner.displayName = "Masonry.Content";
|
|
330
|
+
var MasonryContent = MasonryContentInner;
|
|
331
|
+
var MasonryViewportInner = composable(({ items, getId, cacheKey, selectedIds, onSelect, scroll = true, ...props }, forwardedRef) => {
|
|
332
|
+
const { Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered } = useMasonryContext("Masonry.Viewport");
|
|
333
|
+
const remInPx = usePx(1);
|
|
334
|
+
const viewportRef = useRef(null);
|
|
335
|
+
const { width: contentWidth = 0 } = useResizeDetector({
|
|
336
|
+
targetRef: viewportRef,
|
|
337
|
+
refreshMode: "throttle",
|
|
338
|
+
refreshRate: 200
|
|
339
|
+
});
|
|
340
|
+
const columnCount = useColumnCount(contentWidth, columns, maxColumns, minColumnWidth, maxColumnWidth, gap);
|
|
341
|
+
const gapPx = gap * remInPx;
|
|
342
|
+
const ids = useMemo(() => items.map((item, index) => getId?.(item) ?? String(index)), [items, getId]);
|
|
343
|
+
const { rects, columnWidth, height, getTileRef, nodes, measured, knownIds } = useMasonryLayout({
|
|
344
|
+
ids,
|
|
345
|
+
columnCount,
|
|
346
|
+
containerWidth: contentWidth,
|
|
347
|
+
gapPx,
|
|
348
|
+
maxColumnWidthPx: maxColumnWidth * remInPx,
|
|
349
|
+
centered,
|
|
350
|
+
cacheKey
|
|
351
|
+
});
|
|
352
|
+
useFlip({
|
|
353
|
+
nodes,
|
|
354
|
+
ids,
|
|
355
|
+
rects,
|
|
356
|
+
columnCount,
|
|
357
|
+
containerWidth: contentWidth,
|
|
358
|
+
enabled: animate
|
|
359
|
+
});
|
|
360
|
+
const [revealed, setRevealed] = useState(false);
|
|
361
|
+
const firstPass = useRef(true);
|
|
362
|
+
useEffect(() => {
|
|
363
|
+
if (revealed) return;
|
|
364
|
+
if (contentWidth <= 0) return;
|
|
365
|
+
if (!measured) {
|
|
366
|
+
firstPass.current = false;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (firstPass.current) {
|
|
370
|
+
setRevealed(true);
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
const timer = setTimeout(() => setRevealed(true), REVEAL_SETTLE_MS);
|
|
374
|
+
return () => clearTimeout(timer);
|
|
375
|
+
}, [
|
|
376
|
+
revealed,
|
|
377
|
+
measured,
|
|
378
|
+
rects,
|
|
379
|
+
contentWidth
|
|
380
|
+
]);
|
|
381
|
+
useEffect(() => {
|
|
382
|
+
const deadline = setTimeout(() => setRevealed(true), REVEAL_DEADLINE_MS);
|
|
383
|
+
return () => clearTimeout(deadline);
|
|
384
|
+
}, []);
|
|
385
|
+
const arrowNavigationAttrs = useArrowNavigationGroup({
|
|
386
|
+
axis: "both",
|
|
387
|
+
memorizeCurrent: true,
|
|
388
|
+
tabbable: true
|
|
389
|
+
});
|
|
390
|
+
const grid = /* @__PURE__ */ jsx(Fragment, { children: contentWidth > 0 && /* @__PURE__ */ jsx("div", {
|
|
391
|
+
...composableProps(props, {
|
|
392
|
+
classNames: "relative",
|
|
393
|
+
style: {
|
|
394
|
+
width: `${contentWidth}px`,
|
|
395
|
+
height: `${height}px`,
|
|
396
|
+
opacity: revealed ? 1 : 0,
|
|
397
|
+
visibility: revealed ? "visible" : "hidden",
|
|
398
|
+
transition: animate && !prefersReducedMotion() ? "opacity 200ms cubic-bezier(0.2, 0, 0, 1)" : void 0
|
|
399
|
+
}
|
|
400
|
+
}),
|
|
401
|
+
...arrowNavigationAttrs,
|
|
402
|
+
role: "list",
|
|
403
|
+
ref: forwardedRef,
|
|
404
|
+
children: items.map((item, index) => {
|
|
405
|
+
const id = ids[index];
|
|
406
|
+
const rect = rects[index];
|
|
407
|
+
const selectable = !!onSelect;
|
|
408
|
+
const selected = selectedIds?.has(id) ?? false;
|
|
409
|
+
const estimated = !knownIds.has(id);
|
|
410
|
+
return /* @__PURE__ */ jsx("div", {
|
|
411
|
+
className: [
|
|
412
|
+
"[&>*]:min-w-0!",
|
|
413
|
+
selectable && "cursor-pointer",
|
|
414
|
+
selected && "rounded-md ring-2 ring-inset ring-primary-500"
|
|
415
|
+
].filter(Boolean).join(" "),
|
|
416
|
+
ref: getTileRef(id),
|
|
417
|
+
role: "listitem",
|
|
418
|
+
"aria-selected": selectable ? selected : void 0,
|
|
419
|
+
onClick: onSelect ? (event) => onSelect(id, event) : void 0,
|
|
420
|
+
style: {
|
|
421
|
+
position: "absolute",
|
|
422
|
+
insetBlockStart: 0,
|
|
423
|
+
insetInlineStart: 0,
|
|
424
|
+
width: `${columnWidth}px`,
|
|
425
|
+
transform: rect ? `translate(${rect.x}px, ${rect.y}px)` : void 0,
|
|
426
|
+
visibility: estimated ? "hidden" : void 0
|
|
427
|
+
},
|
|
428
|
+
children: /* @__PURE__ */ jsx(Tile, {
|
|
429
|
+
index,
|
|
430
|
+
data: item,
|
|
431
|
+
selected
|
|
432
|
+
})
|
|
433
|
+
}, id);
|
|
434
|
+
})
|
|
435
|
+
}) });
|
|
436
|
+
return scroll ? /* @__PURE__ */ jsx(ScrollArea.Viewport, {
|
|
437
|
+
ref: viewportRef,
|
|
438
|
+
children: grid
|
|
439
|
+
}) : /* @__PURE__ */ jsx("div", {
|
|
440
|
+
className: "flex-1 w-full min-w-0",
|
|
441
|
+
ref: viewportRef,
|
|
442
|
+
children: grid
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
MasonryViewportInner.displayName = "Masonry.Viewport";
|
|
446
|
+
var MasonryViewport = MasonryViewportInner;
|
|
447
|
+
/** Compute column count from container width and column constraints. */
|
|
448
|
+
var useColumnCount = (width, columns, maxColumns, minColumnWidth, maxColumnWidth, gap) => {
|
|
449
|
+
const remInPx = usePx(1);
|
|
450
|
+
return useMemo(() => {
|
|
451
|
+
if (columns != null) return columns;
|
|
452
|
+
const minColumnWidthPx = minColumnWidth * remInPx;
|
|
453
|
+
const maxColumnWidthPx = maxColumnWidth * remInPx;
|
|
454
|
+
const gapPx = gap * remInPx;
|
|
455
|
+
if (width <= 0 || minColumnWidthPx <= 0) return 1;
|
|
456
|
+
let cols = Math.max(1, Math.floor((width + gapPx) / (minColumnWidthPx + gapPx)));
|
|
457
|
+
if (maxColumnWidthPx > 0) {
|
|
458
|
+
if ((width - (cols - 1) * gapPx) / cols > maxColumnWidthPx) {
|
|
459
|
+
const maxCols = Math.ceil((width + gapPx) / (maxColumnWidthPx + gapPx));
|
|
460
|
+
if ((width - (maxCols - 1) * gapPx) / maxCols >= minColumnWidthPx) cols = maxCols;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return Math.max(1, maxColumns != null ? Math.min(cols, maxColumns) : cols);
|
|
464
|
+
}, [
|
|
465
|
+
remInPx,
|
|
466
|
+
width,
|
|
467
|
+
columns,
|
|
468
|
+
maxColumns,
|
|
469
|
+
minColumnWidth,
|
|
470
|
+
maxColumnWidth,
|
|
471
|
+
gap
|
|
472
|
+
]);
|
|
473
|
+
};
|
|
474
|
+
var Masonry = {
|
|
475
|
+
Root: MasonryRoot,
|
|
476
|
+
Content: MasonryContent,
|
|
477
|
+
Viewport: MasonryViewport
|
|
478
|
+
};
|
|
479
|
+
//#endregion
|
|
480
|
+
export { Masonry };
|
|
481
|
+
|
|
482
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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,WAAW;EAGf,MAAM,UACJ,eAAe,YAAY,SAC1B,eAAe,QAAQ,gBAAgB,eAAe,eAAe,QAAQ,mBAAmB;EACnG,eAAe,UAAU;GAAE;GAAa;EAAe;EAEvD,MAAM,UACJ,qBAAqB,WAAW,CAAC,qBAAqB,KAAK,oBAAoB;GAAE;GAAO;GAAS;EAAQ,CAAC;EAC5G,MAAM,uBAAO,IAAI,IAAY;EAE7B,IAAI,SAAS,IAAI,UAAU;GACzB,MAAM,OAAO,MAAM;GACnB,MAAM,UAAU,MAAM,QAAQ,IAAI,EAAE;GACpC,IAAI,CAAC,QAAQ,CAAC,SACZ;GAEF,KAAK,IAAI,EAAE;G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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;QACM,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,10 +1,11 @@
|
|
|
1
|
-
import { type ComponentType, type JSX, type PropsWithChildren, type Ref } from 'react';
|
|
1
|
+
import { type ComponentType, type JSX, type MouseEvent, type PropsWithChildren, type Ref } from 'react';
|
|
2
2
|
import { ScrollAreaRootProps, ThemedClassName } from '@dxos/react-ui';
|
|
3
3
|
type MasonryContextValue = {
|
|
4
|
-
/** Render component for each masonry item. */
|
|
4
|
+
/** Render component for each masonry item. Receives `selected` when the grid is selectable. */
|
|
5
5
|
Tile: ComponentType<{
|
|
6
6
|
data: any;
|
|
7
7
|
index: number;
|
|
8
|
+
selected?: boolean;
|
|
8
9
|
}>;
|
|
9
10
|
/** Override auto-calculated column count. */
|
|
10
11
|
columns: number | undefined;
|
|
@@ -14,11 +15,23 @@ type MasonryContextValue = {
|
|
|
14
15
|
minColumnWidth: number;
|
|
15
16
|
/** Maximum column width in rem. */
|
|
16
17
|
maxColumnWidth: number;
|
|
17
|
-
/** Space between
|
|
18
|
-
|
|
18
|
+
/** Space applied uniformly between tiles and around the grid perimeter, in rem. */
|
|
19
|
+
gap: number;
|
|
20
|
+
/**
|
|
21
|
+
* Animate reflow when a small number of tiles are added or removed. Disabled, or on a
|
|
22
|
+
* bulk change (initial render, data swap) or resize, tiles snap to position instead.
|
|
23
|
+
*/
|
|
24
|
+
animate: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Centre the columns when `maxColumnWidth` caps them narrower than the container. Off aligns them
|
|
27
|
+
* to the start instead, which reads better when the grid sits in a form or list flow whose other
|
|
28
|
+
* rows are start-aligned. Distinct from `Masonry.Content`'s `centered`, which is ScrollArea's
|
|
29
|
+
* scrollbar-padding balance and says nothing about column alignment.
|
|
30
|
+
*/
|
|
31
|
+
centered: boolean;
|
|
19
32
|
};
|
|
20
33
|
type MasonryRootProps = PropsWithChildren<Partial<MasonryContextValue>>;
|
|
21
|
-
declare function MasonryRoot({ children, Tile, columns, maxColumns, minColumnWidth, maxColumnWidth,
|
|
34
|
+
declare function MasonryRoot({ children, Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered }: MasonryRootProps): JSX.Element;
|
|
22
35
|
declare namespace MasonryRoot {
|
|
23
36
|
var displayName: string;
|
|
24
37
|
}
|
|
@@ -28,10 +41,34 @@ type MasonryViewportProps<Item> = ThemedClassName<{
|
|
|
28
41
|
items: readonly Item[];
|
|
29
42
|
/** Extract a stable key from an item, aligned with react-ui-mosaic's getId. */
|
|
30
43
|
getId?: (data: Item) => string;
|
|
44
|
+
/**
|
|
45
|
+
* Scope for remembering tile heights across mounts, e.g. the collection's URI. With one, a
|
|
46
|
+
* remount renders on the first frame instead of waiting for the layout to settle. Omit it when
|
|
47
|
+
* `getId` is omitted: the default index ids are not unique across grids.
|
|
48
|
+
*/
|
|
49
|
+
cacheKey?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Ids of the currently-selected tiles. When `onSelect` is also provided the grid becomes
|
|
52
|
+
* selectable: selected tiles render an outline + `aria-selected`, and clicking a tile emits
|
|
53
|
+
* {@link onSelect}. Selection STATE (single/multi semantics) is owned by the consumer — pair this
|
|
54
|
+
* with `useListSelection` from `@dxos/react-ui-list`.
|
|
55
|
+
*/
|
|
56
|
+
selectedIds?: ReadonlySet<string>;
|
|
57
|
+
/** Emitted when a tile is clicked while selectable. The consumer toggles its own selection state. */
|
|
58
|
+
onSelect?: (id: string, event: MouseEvent) => void;
|
|
59
|
+
/**
|
|
60
|
+
* Whether this layer owns scrolling. Set `false` when an ancestor already scrolls (e.g. a form's
|
|
61
|
+
* viewport) to render the grid in a plain full-width block instead of a nested scroll container —
|
|
62
|
+
* the `ScrollArea.Root` that `Masonry.Content` provides is then not needed. Nesting scroll
|
|
63
|
+
* containers also risks collapsing the measured width to the scrollbar gutter, which would
|
|
64
|
+
* suppress the grid entirely (see the width gate below).
|
|
65
|
+
* @default true
|
|
66
|
+
*/
|
|
67
|
+
scroll?: boolean;
|
|
31
68
|
}>;
|
|
32
69
|
export declare const Masonry: {
|
|
33
70
|
Root: {
|
|
34
|
-
({ children, Tile, columns, maxColumns, minColumnWidth, maxColumnWidth,
|
|
71
|
+
({ children, Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gap, animate, centered, }: MasonryRootProps): JSX.Element;
|
|
35
72
|
displayName: string;
|
|
36
73
|
};
|
|
37
74
|
Content: (props: MasonryContentProps & {
|