@dxos/react-ui-masonry 0.13.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-masonry",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "A masonry component.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -26,8 +26,8 @@
26
26
  ],
27
27
  "dependencies": {
28
28
  "react-resize-detector": "^11.0.1",
29
- "@dxos/react-hooks": "0.13.0",
30
- "@dxos/react-focus": "0.13.0"
29
+ "@dxos/react-focus": "0.14.0",
30
+ "@dxos/react-hooks": "0.14.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@storybook/react-vite": "^10.6.0",
@@ -36,16 +36,16 @@
36
36
  "react": "~19.2.7",
37
37
  "react-dom": "~19.2.7",
38
38
  "vite": "^8.2.2",
39
- "@dxos/random": "0.13.0",
40
- "@dxos/react-ui": "0.13.0",
41
- "@dxos/ui-theme": "0.13.0"
39
+ "@dxos/random": "0.14.0",
40
+ "@dxos/react-ui": "0.14.0",
41
+ "@dxos/ui-theme": "0.14.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "effect": "4.0.0",
45
45
  "react": "~19.2.7",
46
46
  "react-dom": "~19.2.7",
47
- "@dxos/react-ui": "^0.13.0",
48
- "@dxos/ui-theme": "^0.13.0"
47
+ "@dxos/react-ui": "^0.14.0",
48
+ "@dxos/ui-theme": "^0.14.0"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"
@@ -0,0 +1,70 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import React, { act } from 'react';
6
+ import { type Root, createRoot } from 'react-dom/client';
7
+ import { afterEach, describe, test } from 'vitest';
8
+
9
+ import { Masonry } from './Masonry.tsx';
10
+ import { ESTIMATED_TILE_HEIGHT } from './useMasonryLayout.ts';
11
+
12
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
13
+
14
+ const TILE_HEIGHT = 50;
15
+
16
+ const Tile = ({ data }: { data: string }) => <div style={{ height: TILE_HEIGHT }}>{data}</div>;
17
+
18
+ const items = ['a', 'b', 'c', 'd'];
19
+
20
+ let root: Root | undefined;
21
+ let container: HTMLElement | undefined;
22
+
23
+ const mount = (cacheKey?: string) => {
24
+ container = document.createElement('div');
25
+ container.style.width = '800px';
26
+ document.body.appendChild(container);
27
+ const reactRoot = createRoot(container);
28
+ root = reactRoot;
29
+ act(() =>
30
+ reactRoot.render(
31
+ <Masonry.Root Tile={Tile}>
32
+ <Masonry.Content padding={false} scrollbars={false}>
33
+ <Masonry.Viewport items={items} getId={(item: string) => item} cacheKey={cacheKey} />
34
+ </Masonry.Content>
35
+ </Masonry.Root>,
36
+ ),
37
+ );
38
+ const grid = container.querySelector<HTMLElement>('[role="list"]');
39
+ if (!grid) {
40
+ throw new Error('Masonry rendered no grid in its first commit');
41
+ }
42
+ return grid;
43
+ };
44
+
45
+ const unmount = () => {
46
+ act(() => root?.unmount());
47
+ container?.remove();
48
+ root = undefined;
49
+ container = undefined;
50
+ };
51
+
52
+ afterEach(unmount);
53
+
54
+ describe('Masonry', () => {
55
+ test('lays out at its measured height in the first commit', ({ expect }) => {
56
+ const grid = mount();
57
+
58
+ expect(grid.offsetHeight).toBeGreaterThanOrEqual(2 * TILE_HEIGHT);
59
+ expect(grid.offsetHeight).toBeLessThan(ESTIMATED_TILE_HEIGHT);
60
+ });
61
+
62
+ test('reveals at once only when every height was cached by an earlier mount', ({ expect }) => {
63
+ const cold = mount('masonry-reveal');
64
+ expect(cold.style.visibility).toBe('hidden');
65
+ unmount();
66
+
67
+ const warm = mount('masonry-reveal');
68
+ expect(warm.style.visibility).toBe('visible');
69
+ });
70
+ });
package/src/Masonry.tsx CHANGED
@@ -10,7 +10,9 @@ import React, {
10
10
  type MouseEvent,
11
11
  type PropsWithChildren,
12
12
  type Ref,
13
+ type RefObject,
13
14
  useEffect,
15
+ useLayoutEffect,
14
16
  useMemo,
15
17
  useRef,
16
18
  useState,
@@ -35,6 +37,25 @@ const REVEAL_SETTLE_MS = 80;
35
37
  /** Reveal the grid no later than this after mount, so churning content never hides it indefinitely. */
36
38
  const REVEAL_DEADLINE_MS = 1200;
37
39
 
40
+ /** The element's content-box width, as the resize detector reports it: net of padding and scrollbar. */
41
+ const getContentWidth = (element: HTMLElement): number => {
42
+ const style = getComputedStyle(element);
43
+ return element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
44
+ };
45
+
46
+ const useContentWidth = (ref: RefObject<HTMLDivElement | null>): number => {
47
+ // Throttle width changes: each update recomputes the column count and the full tile layout,
48
+ // so coalesce rapid resizes (drag, ScrollArea reflow) into at most one relayout per interval.
49
+ const { width: observedWidth } = useResizeDetector({ targetRef: ref, refreshMode: 'throttle', refreshRate: 200 });
50
+ const [mountWidth, setMountWidth] = useState(0);
51
+ useLayoutEffect(() => {
52
+ if (ref.current) {
53
+ setMountWidth(getContentWidth(ref.current));
54
+ }
55
+ }, [ref]);
56
+ return observedWidth ?? mountWidth;
57
+ };
58
+
38
59
  //
39
60
  // Context
40
61
  //
@@ -194,28 +215,24 @@ const MasonryViewportInner = Util.composable<HTMLDivElement, MasonryViewportProp
194
215
  // width for any ScrollArea density (thin/scrollbars/padding) without duplicating
195
216
  // the theme's gutter math.
196
217
  const viewportRef = useRef<HTMLDivElement | null>(null);
197
- // Throttle width changes: each update recomputes the column count and the full tile layout,
198
- // so coalesce rapid resizes (drag, ScrollArea reflow) into at most one relayout per interval.
199
- const { width: contentWidth = 0 } = useResizeDetector({
200
- targetRef: viewportRef,
201
- refreshMode: 'throttle',
202
- refreshRate: 200,
203
- });
218
+ const contentWidth = useContentWidth(viewportRef);
204
219
  const columnCount = useColumnCount(contentWidth, columns, maxColumns, minColumnWidth, maxColumnWidth, gap);
205
220
 
206
221
  // The grid fills the measured content box; the layout caps columns at
207
222
  // `maxColumnWidth` and centres them, so no scrollbar/padding math is duplicated here.
208
223
  const gapPx = gap * remInPx;
209
224
  const ids = useMemo(() => items.map((item, index) => getId?.(item) ?? String(index)), [items, getId]);
210
- const { rects, columnWidth, height, getTileRef, nodes, measured, knownIds } = useMasonryLayout({
211
- ids,
212
- columnCount,
213
- containerWidth: contentWidth,
214
- gapPx,
215
- maxColumnWidthPx: maxColumnWidth * remInPx,
216
- centered,
217
- cacheKey,
218
- });
225
+ const { rects, columnWidth, height, getTileRef, nodes, measured, cachedAtFirstLayout, knownIds } = useMasonryLayout(
226
+ {
227
+ ids,
228
+ columnCount,
229
+ containerWidth: contentWidth,
230
+ gapPx,
231
+ maxColumnWidthPx: maxColumnWidth * remInPx,
232
+ centered,
233
+ cacheKey,
234
+ },
235
+ );
219
236
  useFlip({ nodes, ids, rects, columnCount, containerWidth: contentWidth, enabled: animate });
220
237
 
221
238
  // Hide the grid until the layout stops changing, then fade in; latch on so later edits never
@@ -223,32 +240,21 @@ const MasonryViewportInner = Util.composable<HTMLDivElement, MasonryViewportProp
223
240
  // poster reserves height a frame later), so the first pass stacks them bunched at the top and
224
241
  // only settles over the next few reflows. Debounce on `rects` identity — which changes on every
225
242
  // relayout — and reveal once it has been stable for a beat, with a hard deadline as a backstop.
226
- //
227
- // None of that applies when every tile's height was already known on the first pass (the height
228
- // cache is warm from an earlier mount): the layout is final before paint, so waiting for it to
229
- // settle would just be a delay. That is the common case after the first visit.
230
243
  const [revealed, setRevealed] = useState(false);
231
- const firstPass = useRef(true);
232
244
  useEffect(() => {
233
- if (revealed) {
245
+ if (revealed || contentWidth <= 0) {
234
246
  return;
235
247
  }
236
- // Nothing has been laid out until the viewport reports a width, so this does not count as the
237
- // first pass — consuming it here would forfeit the fast path on every mount.
238
- if (contentWidth <= 0) {
248
+ if (cachedAtFirstLayout) {
249
+ setRevealed(true);
239
250
  return;
240
251
  }
241
252
  if (!measured) {
242
- firstPass.current = false;
243
- return;
244
- }
245
- if (firstPass.current) {
246
- setRevealed(true);
247
253
  return;
248
254
  }
249
255
  const timer = setTimeout(() => setRevealed(true), REVEAL_SETTLE_MS);
250
256
  return () => clearTimeout(timer);
251
- }, [revealed, measured, rects, contentWidth]);
257
+ }, [revealed, measured, cachedAtFirstLayout, rects, contentWidth]);
252
258
  useEffect(() => {
253
259
  const deadline = setTimeout(() => setRevealed(true), REVEAL_DEADLINE_MS);
254
260
  return () => clearTimeout(deadline);
@@ -2,7 +2,7 @@
2
2
  // Copyright 2026 DXOS.org
3
3
  //
4
4
 
5
- import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
+ import { type RefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
6
6
 
7
7
  import { type LayoutResult, getColumnWidth, layout } from './layout.ts';
8
8
 
@@ -10,7 +10,7 @@ import { type LayoutResult, getColumnWidth, layout } from './layout.ts';
10
10
  const HEIGHT_EPSILON = 0.5;
11
11
 
12
12
  /** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */
13
- const ESTIMATED_TILE_HEIGHT = 280;
13
+ export const ESTIMATED_TILE_HEIGHT = 280;
14
14
 
15
15
  /**
16
16
  * Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the
@@ -54,9 +54,13 @@ const rememberHeight = (scope: string | undefined, id: string, width: number, he
54
54
  /** Clears the shared height cache. Exported for tests and for callers that recycle ids. */
55
55
  export const clearHeightCache = (): void => heightCache.clear();
56
56
 
57
+ const allCached = (scope: string | undefined, ids: readonly string[], width: number): boolean =>
58
+ scope !== undefined && ids.every((id) => heightCache.get(scopedKey(scope, id))?.width === width);
59
+
57
60
  export type MasonryLayout = LayoutResult & {
58
61
  /** True once every tile has a height measured at the current column width, so positions are final. */
59
62
  measured: boolean;
63
+ cachedAtFirstLayout: boolean | undefined;
60
64
  /**
61
65
  * Ids the layout has some height for — measured now, or remembered from a previous mount or width.
62
66
  * Anything outside this set is sitting at a guess and should not be painted.
@@ -113,6 +117,25 @@ export const useMasonryLayout = ({
113
117
  // The observer is created once, so it reads the current column width and scope through refs.
114
118
  const widthRef = useRef(0);
115
119
  const scopeRef = useRef<string | undefined>(cacheKey);
120
+ const cachedAtFirstLayout = useRef<boolean | undefined>(undefined);
121
+
122
+ const record = (id: string, height: number): boolean => {
123
+ const previous = heights.current.get(id);
124
+ if (previous !== undefined && Math.abs(previous - height) <= HEIGHT_EPSILON) {
125
+ return false;
126
+ }
127
+ heights.current.set(id, height);
128
+ rememberHeight(scopeRef.current, id, widthRef.current, height);
129
+ return true;
130
+ };
131
+
132
+ const relayout = (): void => {
133
+ const values = [...heights.current.values()];
134
+ if (values.length > 0) {
135
+ estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;
136
+ }
137
+ setVersion((value) => value + 1);
138
+ };
116
139
 
117
140
  const observer = useMemo(() => {
118
141
  if (typeof ResizeObserver === 'undefined') {
@@ -123,29 +146,30 @@ export const useMasonryLayout = ({
123
146
  let changed = false;
124
147
  for (const entry of entries) {
125
148
  const id = elementIds.current.get(entry.target);
126
- if (!id) {
127
- continue;
128
- }
129
- // ResizeObserver types `target` as Element; we only ever observe HTMLElement tile wrappers,
130
- // whose border-box height (offsetHeight) is what the layout stacks.
131
- const height = (entry.target as HTMLElement).offsetHeight;
132
- const previous = heights.current.get(id);
133
- if (previous === undefined || Math.abs(previous - height) > HEIGHT_EPSILON) {
134
- heights.current.set(id, height);
135
- rememberHeight(scopeRef.current, id, widthRef.current, height);
136
- changed = true;
149
+ const element = id === undefined ? undefined : nodes.current.get(id);
150
+ if (id !== undefined && element) {
151
+ changed = record(id, element.offsetHeight) || changed;
137
152
  }
138
153
  }
139
154
  if (changed) {
140
- const values = [...heights.current.values()];
141
- if (values.length > 0) {
142
- estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;
143
- }
144
- setVersion((value) => value + 1);
155
+ relayout();
145
156
  }
146
157
  });
147
158
  }, []);
148
159
 
160
+ const measureNewTiles = (): void => {
161
+ let changed = false;
162
+ for (const [id, element] of nodes.current) {
163
+ if (!heights.current.has(id)) {
164
+ changed = record(id, element.offsetHeight) || changed;
165
+ }
166
+ }
167
+ if (changed) {
168
+ relayout();
169
+ }
170
+ };
171
+ useLayoutEffect(measureNewTiles);
172
+
149
173
  useEffect(() => () => observer?.disconnect(), [observer]);
150
174
 
151
175
  const getTileRef = useCallback(
@@ -207,6 +231,10 @@ export const useMasonryLayout = ({
207
231
  // Height for each tile, best source first: measured this mount, remembered at this exact column
208
232
  // width (as good as measured — the tile has not reflowed), remembered at some other width (a
209
233
  // close estimate, since content usually dominates), else the running average.
234
+ if (cachedAtFirstLayout.current === undefined && containerWidth > 0) {
235
+ cachedAtFirstLayout.current = allCached(cacheKey, ids, columnWidth);
236
+ }
237
+
210
238
  const measuredIds = new Set<string>();
211
239
  const knownIds = new Set<string>();
212
240
  const tileHeights = ids.map((id) => {
@@ -232,6 +260,7 @@ export const useMasonryLayout = ({
232
260
  return {
233
261
  ...layout({ heights: tileHeights, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered }),
234
262
  measured: measuredIds.size === ids.length,
263
+ cachedAtFirstLayout: cachedAtFirstLayout.current,
235
264
  knownIds,
236
265
  };
237
266
  // `version` re-runs layout when a measured height changes.