@dxos/react-ui-masonry 0.10.0 → 0.11.1
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
package/src/layout.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
export type Rect = {
|
|
6
|
+
/** Horizontal offset (px) of the tile's left edge. */
|
|
7
|
+
x: number;
|
|
8
|
+
/** Vertical offset (px) of the tile's top edge. */
|
|
9
|
+
y: number;
|
|
10
|
+
/** Column the tile was assigned to. */
|
|
11
|
+
column: number;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type LayoutResult = {
|
|
15
|
+
/** Position of each tile, in input order. */
|
|
16
|
+
rects: Rect[];
|
|
17
|
+
/** Width (px) shared by every column. */
|
|
18
|
+
columnWidth: number;
|
|
19
|
+
/** Total content height (px), including the perimeter gap. */
|
|
20
|
+
height: number;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type LayoutOptions = {
|
|
24
|
+
/** Measured tile heights (px), in item order. Unmeasured tiles pass 0. */
|
|
25
|
+
heights: readonly number[];
|
|
26
|
+
/** Number of columns to lay out across. */
|
|
27
|
+
columnCount: number;
|
|
28
|
+
/** Available content width (px), already net of any scrollbar allowance. */
|
|
29
|
+
containerWidth: number;
|
|
30
|
+
/** Space (px) between tiles and, vertically, around the grid perimeter. */
|
|
31
|
+
gapPx: number;
|
|
32
|
+
/** Optional cap on column width (px); leftover width centers the columns. */
|
|
33
|
+
maxColumnWidthPx?: number;
|
|
34
|
+
/** Centre capped columns in the container. Off aligns them to the start, leaving the slack at the end. */
|
|
35
|
+
centered?: boolean;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Lay tiles out into balanced columns using column-major greedy assignment: each
|
|
40
|
+
* tile is placed in the currently shortest column (ties resolve to the lowest
|
|
41
|
+
* index for stable ordering). Pure and synchronous so column balancing is unit
|
|
42
|
+
* testable without a DOM.
|
|
43
|
+
*
|
|
44
|
+
* Columns are separated by a single gap. They stretch to fill `containerWidth`
|
|
45
|
+
* unless `maxColumnWidthPx` caps them narrower, in which case the leftover width
|
|
46
|
+
* is split evenly so the grid stays centred (the outer margin grows beyond the
|
|
47
|
+
* gap) — or, with `centered` off, left entirely at the end so the columns align to
|
|
48
|
+
* the start. The base left/right perimeter is owned by the scroll container (via
|
|
49
|
+
* its `--gutter`); the layout adds any centring offset plus the top/bottom perimeter.
|
|
50
|
+
*/
|
|
51
|
+
/**
|
|
52
|
+
* Width every column gets, before any tile is placed. Independent of the tiles themselves — which is
|
|
53
|
+
* what lets a caller key cached tile heights by the width they were measured at.
|
|
54
|
+
*/
|
|
55
|
+
export const getColumnWidth = ({
|
|
56
|
+
columnCount,
|
|
57
|
+
containerWidth,
|
|
58
|
+
gapPx,
|
|
59
|
+
maxColumnWidthPx,
|
|
60
|
+
}: Pick<LayoutOptions, 'columnCount' | 'containerWidth' | 'gapPx' | 'maxColumnWidthPx'>): number => {
|
|
61
|
+
const columns = Math.max(1, Math.floor(columnCount));
|
|
62
|
+
const fillColumnWidth = (containerWidth - (columns - 1) * gapPx) / columns;
|
|
63
|
+
return maxColumnWidthPx && maxColumnWidthPx > 0 ? Math.min(fillColumnWidth, maxColumnWidthPx) : fillColumnWidth;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const layout = ({
|
|
67
|
+
heights,
|
|
68
|
+
columnCount,
|
|
69
|
+
containerWidth,
|
|
70
|
+
gapPx,
|
|
71
|
+
maxColumnWidthPx,
|
|
72
|
+
centered = true,
|
|
73
|
+
}: LayoutOptions): LayoutResult => {
|
|
74
|
+
const columns = Math.max(1, Math.floor(columnCount));
|
|
75
|
+
const columnWidth = getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx });
|
|
76
|
+
|
|
77
|
+
// Centre the (possibly capped) columns within the container, unless start-aligned.
|
|
78
|
+
const usedWidth = columns * columnWidth + (columns - 1) * gapPx;
|
|
79
|
+
const sideInset = centered ? Math.max(0, (containerWidth - usedWidth) / 2) : 0;
|
|
80
|
+
|
|
81
|
+
// Seed each column with the top gap so the first row clears the perimeter.
|
|
82
|
+
const columnHeights = new Array<number>(columns).fill(gapPx);
|
|
83
|
+
|
|
84
|
+
const rects: Rect[] = heights.map((tileHeight) => {
|
|
85
|
+
let target = 0;
|
|
86
|
+
for (let column = 1; column < columns; ++column) {
|
|
87
|
+
if (columnHeights[column] < columnHeights[target]) {
|
|
88
|
+
target = column;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const rect: Rect = {
|
|
93
|
+
x: sideInset + target * (columnWidth + gapPx),
|
|
94
|
+
y: columnHeights[target],
|
|
95
|
+
column: target,
|
|
96
|
+
};
|
|
97
|
+
columnHeights[target] += tileHeight + gapPx;
|
|
98
|
+
return rect;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Each column already carries a trailing gap, which becomes the bottom perimeter.
|
|
102
|
+
const tallest = columnHeights.reduce((max, value) => Math.max(max, value), 0);
|
|
103
|
+
const height = heights.length === 0 ? 0 : tallest;
|
|
104
|
+
return { rects, columnWidth, height };
|
|
105
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { describe, test } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { shouldAnimateReflow } from './useFlip';
|
|
8
|
+
|
|
9
|
+
describe('shouldAnimateReflow', () => {
|
|
10
|
+
test('animates a small add', ({ expect }) => {
|
|
11
|
+
expect(shouldAnimateReflow({ added: 1, removed: 0, resized: false })).toBe(true);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('animates a small remove', ({ expect }) => {
|
|
15
|
+
expect(shouldAnimateReflow({ added: 0, removed: 2, resized: false })).toBe(true);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('snaps the initial bulk render', ({ expect }) => {
|
|
19
|
+
expect(shouldAnimateReflow({ added: 36, removed: 0, resized: false })).toBe(false);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('snaps a height-settling reflow (no add/remove)', ({ expect }) => {
|
|
23
|
+
expect(shouldAnimateReflow({ added: 0, removed: 0, resized: false })).toBe(false);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('snaps on resize even for a small delta', ({ expect }) => {
|
|
27
|
+
expect(shouldAnimateReflow({ added: 1, removed: 0, resized: true })).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('snaps at the delta boundary and animates just below it', ({ expect }) => {
|
|
31
|
+
expect(shouldAnimateReflow({ added: 4, removed: 4, resized: false, maxDelta: 8 })).toBe(true);
|
|
32
|
+
expect(shouldAnimateReflow({ added: 5, removed: 4, resized: false, maxDelta: 8 })).toBe(false);
|
|
33
|
+
});
|
|
34
|
+
});
|
package/src/useFlip.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { type RefObject, useLayoutEffect, useRef } from 'react';
|
|
6
|
+
|
|
7
|
+
import { type Rect } from './layout';
|
|
8
|
+
|
|
9
|
+
const DURATION = 200;
|
|
10
|
+
const EASING = 'cubic-bezier(0.2, 0, 0, 1)';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Above this many tiles added/removed in a single layout, snap instead of animate.
|
|
14
|
+
* Reflows this large are the initial bulk render or a data swap, not an incremental
|
|
15
|
+
* edit, and animating dozens of tiles at once is the source of the perf/bunching jank.
|
|
16
|
+
*/
|
|
17
|
+
const ANIMATE_MAX_DELTA = 8;
|
|
18
|
+
|
|
19
|
+
export const prefersReducedMotion = () =>
|
|
20
|
+
typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Decide whether a layout transition should animate. Animate only genuine small
|
|
24
|
+
* incremental edits on a stable container: a resize snaps (the whole grid moves),
|
|
25
|
+
* and a zero add/remove delta means either the initial bulk render's height-settling
|
|
26
|
+
* pass or a pure resize — both snap so the grid never animates into place from the
|
|
27
|
+
* degenerate all-heights-zero layout.
|
|
28
|
+
*/
|
|
29
|
+
export const shouldAnimateReflow = ({
|
|
30
|
+
added,
|
|
31
|
+
removed,
|
|
32
|
+
resized,
|
|
33
|
+
maxDelta = ANIMATE_MAX_DELTA,
|
|
34
|
+
}: {
|
|
35
|
+
added: number;
|
|
36
|
+
removed: number;
|
|
37
|
+
resized: boolean;
|
|
38
|
+
maxDelta?: number;
|
|
39
|
+
}): boolean => !resized && added + removed > 0 && added + removed <= maxDelta;
|
|
40
|
+
|
|
41
|
+
export type UseFlipOptions = {
|
|
42
|
+
/** Tile wrappers by id, kept live by the layout hook. */
|
|
43
|
+
nodes: RefObject<Map<string, HTMLElement>>;
|
|
44
|
+
/** Item ids in render order (aligned with `rects`). */
|
|
45
|
+
ids: readonly string[];
|
|
46
|
+
/** Target positions (aligned with `ids`). */
|
|
47
|
+
rects: readonly Rect[];
|
|
48
|
+
/** Current column count; a change marks a resize, which snaps rather than animates. */
|
|
49
|
+
columnCount: number;
|
|
50
|
+
/** Current content width (px); a change marks a resize, which snaps rather than animates. */
|
|
51
|
+
containerWidth: number;
|
|
52
|
+
/** Disable to snap without animating (also skipped under reduced-motion and on bulk reflows). */
|
|
53
|
+
enabled: boolean;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Animates tile position changes with FLIP: tiles that moved between layouts
|
|
58
|
+
* transition from their previous translate to the new one via the Web Animations
|
|
59
|
+
* API; freshly-added tiles fade/scale in. Respects `prefers-reduced-motion`.
|
|
60
|
+
*/
|
|
61
|
+
export const useFlip = ({ nodes, ids, rects, columnCount, containerWidth, enabled }: UseFlipOptions): void => {
|
|
62
|
+
const previous = useRef(new Map<string, { x: number; y: number }>());
|
|
63
|
+
const previousLayout = useRef<{ columnCount: number; containerWidth: number } | null>(null);
|
|
64
|
+
|
|
65
|
+
useLayoutEffect(() => {
|
|
66
|
+
// Without committed positions this is the first non-empty layout — snap it (the initial
|
|
67
|
+
// render), even for a small set that would otherwise read as a handful of added tiles.
|
|
68
|
+
const hasPriorPositions = previous.current.size > 0;
|
|
69
|
+
// Classify the reflow before recording new positions: added/removed relative to
|
|
70
|
+
// the last rendered id set, and whether the container dimensions changed (resize).
|
|
71
|
+
const idSet = new Set(ids);
|
|
72
|
+
let added = 0;
|
|
73
|
+
for (const id of ids) {
|
|
74
|
+
if (!previous.current.has(id)) {
|
|
75
|
+
added += 1;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
let removed = 0;
|
|
79
|
+
for (const id of previous.current.keys()) {
|
|
80
|
+
if (!idSet.has(id)) {
|
|
81
|
+
removed += 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const resized =
|
|
85
|
+
previousLayout.current !== null &&
|
|
86
|
+
(previousLayout.current.columnCount !== columnCount || previousLayout.current.containerWidth !== containerWidth);
|
|
87
|
+
previousLayout.current = { columnCount, containerWidth };
|
|
88
|
+
|
|
89
|
+
const animate =
|
|
90
|
+
hasPriorPositions && enabled && !prefersReducedMotion() && shouldAnimateReflow({ added, removed, resized });
|
|
91
|
+
const seen = new Set<string>();
|
|
92
|
+
|
|
93
|
+
ids.forEach((id, index) => {
|
|
94
|
+
const rect = rects[index];
|
|
95
|
+
const element = nodes.current.get(id);
|
|
96
|
+
if (!rect || !element) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
seen.add(id);
|
|
100
|
+
|
|
101
|
+
const prior = previous.current.get(id);
|
|
102
|
+
previous.current.set(id, { x: rect.x, y: rect.y });
|
|
103
|
+
|
|
104
|
+
// Style already holds the target translate; snapping needs no animation.
|
|
105
|
+
if (!animate) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (prior) {
|
|
110
|
+
if (prior.x !== rect.x || prior.y !== rect.y) {
|
|
111
|
+
element.animate(
|
|
112
|
+
[
|
|
113
|
+
{ transform: `translate(${prior.x}px, ${prior.y}px)` },
|
|
114
|
+
{ transform: `translate(${rect.x}px, ${rect.y}px)` },
|
|
115
|
+
],
|
|
116
|
+
{ duration: DURATION, easing: EASING },
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
} else {
|
|
120
|
+
element.animate(
|
|
121
|
+
[
|
|
122
|
+
{ opacity: 0, transform: `translate(${rect.x}px, ${rect.y}px) scale(0.98)` },
|
|
123
|
+
{ opacity: 1, transform: `translate(${rect.x}px, ${rect.y}px) scale(1)` },
|
|
124
|
+
],
|
|
125
|
+
{ duration: DURATION, easing: EASING },
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
// Forget positions for tiles no longer rendered.
|
|
131
|
+
for (const id of previous.current.keys()) {
|
|
132
|
+
if (!seen.has(id)) {
|
|
133
|
+
previous.current.delete(id);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}, [nodes, ids, rects, columnCount, containerWidth, enabled]);
|
|
137
|
+
};
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
6
|
+
|
|
7
|
+
import { type LayoutResult, getColumnWidth, layout } from './layout';
|
|
8
|
+
|
|
9
|
+
/** Sub-pixel changes below this threshold (px) don't trigger a re-layout. */
|
|
10
|
+
const HEIGHT_EPSILON = 0.5;
|
|
11
|
+
|
|
12
|
+
/** Assumed tile height (px) before any real measurement exists, so the first layout is spaced out. */
|
|
13
|
+
const ESTIMATED_TILE_HEIGHT = 280;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Tile heights measured anywhere in the app, keyed by the caller's `cacheKey`, the tile id, and the
|
|
17
|
+
* column width the tile was measured at. Module scope on purpose: a grid unmounts whenever its tab
|
|
18
|
+
* or route does, and re-measuring from scratch is what makes a remount wait — hidden — for the
|
|
19
|
+
* layout to settle. With a warm entry the first layout is already final, so the grid can be shown on
|
|
20
|
+
* the first frame.
|
|
21
|
+
*
|
|
22
|
+
* The `cacheKey` scope is required rather than optional: tile ids default to the array index, so a
|
|
23
|
+
* process-wide cache keyed on id alone would serve one grid's height for `"0"` to an unrelated grid
|
|
24
|
+
* and reveal it before it was ever measured. A grid that passes no key keeps its heights to itself.
|
|
25
|
+
*
|
|
26
|
+
* Height is stored with its width because a card reflows: at a different width the entry is still a
|
|
27
|
+
* far better estimate than the default, but it is not a measurement.
|
|
28
|
+
*/
|
|
29
|
+
const heightCache = new Map<string, { width: number; height: number }>();
|
|
30
|
+
|
|
31
|
+
/** Cap on remembered tiles; oldest are evicted first (insertion order). */
|
|
32
|
+
const HEIGHT_CACHE_LIMIT = 2_000;
|
|
33
|
+
|
|
34
|
+
/** Cache entries are namespaced by scope; `\u0000` cannot occur in an id or a caller's key. */
|
|
35
|
+
const scopedKey = (scope: string, id: string) => `${scope}\u0000${id}`;
|
|
36
|
+
|
|
37
|
+
const rememberHeight = (scope: string | undefined, id: string, width: number, height: number): void => {
|
|
38
|
+
if (scope === undefined) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const key = scopedKey(scope, id);
|
|
42
|
+
// Re-insert so recently-seen tiles move to the end and survive eviction.
|
|
43
|
+
heightCache.delete(key);
|
|
44
|
+
heightCache.set(key, { width, height });
|
|
45
|
+
if (heightCache.size > HEIGHT_CACHE_LIMIT) {
|
|
46
|
+
const oldest = heightCache.keys().next();
|
|
47
|
+
if (!oldest.done) {
|
|
48
|
+
heightCache.delete(oldest.value);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Clears the shared height cache. Exported for tests and for callers that recycle ids. */
|
|
54
|
+
export const clearHeightCache = (): void => heightCache.clear();
|
|
55
|
+
|
|
56
|
+
export type MasonryLayout = LayoutResult & {
|
|
57
|
+
/** True once every tile has a height measured at the current column width, so positions are final. */
|
|
58
|
+
measured: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Ids the layout has some height for — measured now, or remembered from a previous mount or width.
|
|
61
|
+
* Anything outside this set is sitting at a guess and should not be painted.
|
|
62
|
+
*/
|
|
63
|
+
knownIds: ReadonlySet<string>;
|
|
64
|
+
/** Stable ref callback for the tile wrapper of `id` (measures + registers it). */
|
|
65
|
+
getTileRef: (id: string) => (element: HTMLElement | null) => void;
|
|
66
|
+
/** Live map of currently-mounted tile wrappers by id (for FLIP positioning). */
|
|
67
|
+
nodes: RefObject<Map<string, HTMLElement>>;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export type UseMasonryLayoutOptions = {
|
|
71
|
+
/** Ids of the items to lay out, in render order. */
|
|
72
|
+
ids: readonly string[];
|
|
73
|
+
columnCount: number;
|
|
74
|
+
/** Available content width (px), net of scrollbar allowance. */
|
|
75
|
+
containerWidth: number;
|
|
76
|
+
gapPx: number;
|
|
77
|
+
/** Optional cap on column width (px). */
|
|
78
|
+
maxColumnWidthPx?: number;
|
|
79
|
+
/** Centre capped columns in the container (see `layout`). */
|
|
80
|
+
centered?: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Scope for remembered tile heights, e.g. the collection's URI. Omit when ids are not stable and
|
|
83
|
+
* unique across the app (the default index ids are not) — heights are then per-instance, and a
|
|
84
|
+
* remount re-measures.
|
|
85
|
+
*/
|
|
86
|
+
cacheKey?: string;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Measures tile heights via a shared ResizeObserver and computes balanced column
|
|
91
|
+
* positions. Heights are keyed by item id so reorders and removals reuse prior
|
|
92
|
+
* measurements; a version counter re-runs the pure layout when a height changes.
|
|
93
|
+
*/
|
|
94
|
+
export const useMasonryLayout = ({
|
|
95
|
+
ids,
|
|
96
|
+
columnCount,
|
|
97
|
+
containerWidth,
|
|
98
|
+
gapPx,
|
|
99
|
+
maxColumnWidthPx,
|
|
100
|
+
centered,
|
|
101
|
+
cacheKey,
|
|
102
|
+
}: UseMasonryLayoutOptions): MasonryLayout => {
|
|
103
|
+
const heights = useRef(new Map<string, number>());
|
|
104
|
+
// Survives pruning, unlike `heights`: when the item set is replaced wholesale (paging through
|
|
105
|
+
// duplicate groups) every id is new, and without a remembered average the estimate would fall back
|
|
106
|
+
// to the ~280px default and paint the swap hundreds of pixels out before the real heights land.
|
|
107
|
+
const estimate = useRef(ESTIMATED_TILE_HEIGHT);
|
|
108
|
+
const nodes = useRef(new Map<string, HTMLElement>());
|
|
109
|
+
const elementIds = useRef(new WeakMap<Element, string>());
|
|
110
|
+
const refCallbacks = useRef(new Map<string, (element: HTMLElement | null) => void>());
|
|
111
|
+
const [version, setVersion] = useState(0);
|
|
112
|
+
// The observer is created once, so it reads the current column width and scope through refs.
|
|
113
|
+
const widthRef = useRef(0);
|
|
114
|
+
const scopeRef = useRef<string | undefined>(cacheKey);
|
|
115
|
+
|
|
116
|
+
const observer = useMemo(() => {
|
|
117
|
+
if (typeof ResizeObserver === 'undefined') {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return new ResizeObserver((entries) => {
|
|
122
|
+
let changed = false;
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
const id = elementIds.current.get(entry.target);
|
|
125
|
+
if (!id) {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
// ResizeObserver types `target` as Element; we only ever observe HTMLElement tile wrappers,
|
|
129
|
+
// whose border-box height (offsetHeight) is what the layout stacks.
|
|
130
|
+
const height = (entry.target as HTMLElement).offsetHeight;
|
|
131
|
+
const previous = heights.current.get(id);
|
|
132
|
+
if (previous === undefined || Math.abs(previous - height) > HEIGHT_EPSILON) {
|
|
133
|
+
heights.current.set(id, height);
|
|
134
|
+
rememberHeight(scopeRef.current, id, widthRef.current, height);
|
|
135
|
+
changed = true;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (changed) {
|
|
139
|
+
const values = [...heights.current.values()];
|
|
140
|
+
if (values.length > 0) {
|
|
141
|
+
estimate.current = values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
142
|
+
}
|
|
143
|
+
setVersion((value) => value + 1);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}, []);
|
|
147
|
+
|
|
148
|
+
useEffect(() => () => observer?.disconnect(), [observer]);
|
|
149
|
+
|
|
150
|
+
const getTileRef = useCallback(
|
|
151
|
+
(id: string) => {
|
|
152
|
+
let callback = refCallbacks.current.get(id);
|
|
153
|
+
if (!callback) {
|
|
154
|
+
callback = (element: HTMLElement | null) => {
|
|
155
|
+
const previous = nodes.current.get(id);
|
|
156
|
+
if (previous === element) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (previous) {
|
|
160
|
+
observer?.unobserve(previous);
|
|
161
|
+
elementIds.current.delete(previous);
|
|
162
|
+
}
|
|
163
|
+
if (element) {
|
|
164
|
+
nodes.current.set(id, element);
|
|
165
|
+
elementIds.current.set(element, id);
|
|
166
|
+
if (observer) {
|
|
167
|
+
observer.observe(element);
|
|
168
|
+
} else {
|
|
169
|
+
// Without a ResizeObserver nothing would ever report a height, leaving every tile
|
|
170
|
+
// hidden behind the estimate gate. One measurement at mount is worse than live
|
|
171
|
+
// tracking, but it is a layout rather than a blank grid.
|
|
172
|
+
heights.current.set(id, element.offsetHeight);
|
|
173
|
+
rememberHeight(scopeRef.current, id, widthRef.current, element.offsetHeight);
|
|
174
|
+
setVersion((value) => value + 1);
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
nodes.current.delete(id);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
refCallbacks.current.set(id, callback);
|
|
181
|
+
}
|
|
182
|
+
return callback;
|
|
183
|
+
},
|
|
184
|
+
[observer],
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
const columnWidth = Math.round(getColumnWidth({ columnCount, containerWidth, gapPx, maxColumnWidthPx }));
|
|
188
|
+
widthRef.current = columnWidth;
|
|
189
|
+
scopeRef.current = cacheKey;
|
|
190
|
+
|
|
191
|
+
const result = useMemo(() => {
|
|
192
|
+
// Prune measurements/callbacks for ids no longer present so the maps track the
|
|
193
|
+
// live item set.
|
|
194
|
+
const present = new Set(ids);
|
|
195
|
+
for (const id of heights.current.keys()) {
|
|
196
|
+
if (!present.has(id)) {
|
|
197
|
+
heights.current.delete(id);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
for (const id of refCallbacks.current.keys()) {
|
|
201
|
+
if (!present.has(id)) {
|
|
202
|
+
refCallbacks.current.delete(id);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Height for each tile, best source first: measured this mount, remembered at this exact column
|
|
207
|
+
// width (as good as measured — the tile has not reflowed), remembered at some other width (a
|
|
208
|
+
// close estimate, since content usually dominates), else the running average.
|
|
209
|
+
const measuredIds = new Set<string>();
|
|
210
|
+
const knownIds = new Set<string>();
|
|
211
|
+
const tileHeights = ids.map((id) => {
|
|
212
|
+
const measured = heights.current.get(id);
|
|
213
|
+
if (measured !== undefined) {
|
|
214
|
+
measuredIds.add(id);
|
|
215
|
+
knownIds.add(id);
|
|
216
|
+
return measured;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const cached = cacheKey === undefined ? undefined : heightCache.get(scopedKey(cacheKey, id));
|
|
220
|
+
if (cached) {
|
|
221
|
+
knownIds.add(id);
|
|
222
|
+
if (cached.width === columnWidth) {
|
|
223
|
+
measuredIds.add(id);
|
|
224
|
+
}
|
|
225
|
+
return cached.height;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return estimate.current;
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
...layout({ heights: tileHeights, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered }),
|
|
233
|
+
measured: measuredIds.size === ids.length,
|
|
234
|
+
knownIds,
|
|
235
|
+
};
|
|
236
|
+
// `version` re-runs layout when a measured height changes.
|
|
237
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
238
|
+
}, [ids, columnCount, containerWidth, gapPx, maxColumnWidthPx, centered, columnWidth, cacheKey, version]);
|
|
239
|
+
|
|
240
|
+
return { ...result, getTileRef, nodes };
|
|
241
|
+
};
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
// src/Masonry.tsx
|
|
2
|
-
import { useArrowNavigationGroup } from "@fluentui/react-tabster";
|
|
3
|
-
import { useComposedRefs } from "@radix-ui/react-compose-refs";
|
|
4
|
-
import { createContext } from "@radix-ui/react-context";
|
|
5
|
-
import { VirtuosoMasonry as NaturalVirtuosoMasonry } from "@virtuoso.dev/masonry";
|
|
6
|
-
import React, { useMemo, useRef } from "react";
|
|
7
|
-
import { useResizeDetector } from "react-resize-detector";
|
|
8
|
-
import { ScrollArea, usePx } from "@dxos/react-ui";
|
|
9
|
-
import { composable, composableProps, scrollbar } from "@dxos/react-ui";
|
|
10
|
-
import { cardMaxInlineSize, cardMinInlineSize } from "@dxos/ui-theme";
|
|
11
|
-
var MASONRY_NAME = "Masonry";
|
|
12
|
-
var [MasonryProvider, useMasonryContext] = createContext(MASONRY_NAME);
|
|
13
|
-
var [MasonryContentProvider, useMasonryContentContext] = createContext("Masonry.Content");
|
|
14
|
-
var MasonryRoot = ({ children, Tile, columns = void 0, maxColumns = void 0, minColumnWidth = cardMinInlineSize, maxColumnWidth = cardMaxInlineSize, gutter = 0.75 }) => /* @__PURE__ */ React.createElement(MasonryProvider, {
|
|
15
|
-
Tile,
|
|
16
|
-
columns,
|
|
17
|
-
maxColumns,
|
|
18
|
-
minColumnWidth,
|
|
19
|
-
maxColumnWidth,
|
|
20
|
-
gutter
|
|
21
|
-
}, children);
|
|
22
|
-
MasonryRoot.displayName = "Masonry.Root";
|
|
23
|
-
var MasonryContentInner = composable(({ children, scrollbars, centered, thin = true, padding = true, ...props }, forwardedRef) => {
|
|
24
|
-
const rootRef = useRef(null);
|
|
25
|
-
const composedRef = useComposedRefs(rootRef, forwardedRef);
|
|
26
|
-
const { width = 0 } = useResizeDetector({
|
|
27
|
-
targetRef: rootRef
|
|
28
|
-
});
|
|
29
|
-
return /* @__PURE__ */ React.createElement(ScrollArea.Root, {
|
|
30
|
-
...composableProps(props, {
|
|
31
|
-
classNames: "pt-trim-md"
|
|
32
|
-
}),
|
|
33
|
-
scrollbars,
|
|
34
|
-
centered,
|
|
35
|
-
thin,
|
|
36
|
-
padding,
|
|
37
|
-
ref: composedRef
|
|
38
|
-
}, /* @__PURE__ */ React.createElement(MasonryContentProvider, {
|
|
39
|
-
width
|
|
40
|
-
}, children));
|
|
41
|
-
});
|
|
42
|
-
MasonryContentInner.displayName = "Masonry.Content";
|
|
43
|
-
var MasonryContent = MasonryContentInner;
|
|
44
|
-
var MasonryViewportInner = composable(({ items, getId, ...props }, forwardedRef) => {
|
|
45
|
-
const { Tile, columns, maxColumns, minColumnWidth, maxColumnWidth, gutter } = useMasonryContext("Masonry.Viewport");
|
|
46
|
-
const { width } = useMasonryContentContext("Masonry.Viewport");
|
|
47
|
-
const columnCount = useColumnCount(width - (scrollbar.md.size + scrollbar.md.padding), columns, maxColumns, minColumnWidth, maxColumnWidth, gutter);
|
|
48
|
-
const arrowNavigationAttrs = useArrowNavigationGroup({
|
|
49
|
-
axis: "both",
|
|
50
|
-
memorizeCurrent: true,
|
|
51
|
-
tabbable: true
|
|
52
|
-
});
|
|
53
|
-
const TileAdapter = useMemo(() => {
|
|
54
|
-
const Adapter = ({ data, index }) => /* @__PURE__ */ React.createElement("div", {
|
|
55
|
-
role: "listitem",
|
|
56
|
-
style: {
|
|
57
|
-
paddingBottom: `${gutter}rem`
|
|
58
|
-
}
|
|
59
|
-
}, /* @__PURE__ */ React.createElement(Tile, {
|
|
60
|
-
index,
|
|
61
|
-
data
|
|
62
|
-
}));
|
|
63
|
-
Adapter.displayName = "Masonry.TileAdapter";
|
|
64
|
-
return Adapter;
|
|
65
|
-
}, [
|
|
66
|
-
Tile,
|
|
67
|
-
gutter
|
|
68
|
-
]);
|
|
69
|
-
if (width <= 0) {
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
return /* @__PURE__ */ React.createElement(ScrollArea.Viewport, {
|
|
73
|
-
asChild: true
|
|
74
|
-
}, /* @__PURE__ */ React.createElement(VirtuosoMasonry, {
|
|
75
|
-
...composableProps(props, {
|
|
76
|
-
classNames: [
|
|
77
|
-
"justify-center",
|
|
78
|
-
"[&>div]:max-w-[var(--dx-masonry-column-max)]"
|
|
79
|
-
],
|
|
80
|
-
style: {
|
|
81
|
-
"gap": `${gutter}rem`,
|
|
82
|
-
"--dx-masonry-column-max": `${maxColumnWidth}rem`
|
|
83
|
-
}
|
|
84
|
-
}),
|
|
85
|
-
...arrowNavigationAttrs,
|
|
86
|
-
ItemContent: TileAdapter,
|
|
87
|
-
columnCount,
|
|
88
|
-
data: items
|
|
89
|
-
}));
|
|
90
|
-
});
|
|
91
|
-
MasonryViewportInner.displayName = "Masonry.Viewport";
|
|
92
|
-
var VirtuosoMasonry = composable(({ ...props }, _forwardedRef) => {
|
|
93
|
-
return /* @__PURE__ */ React.createElement(NaturalVirtuosoMasonry, props);
|
|
94
|
-
});
|
|
95
|
-
var MasonryViewport = MasonryViewportInner;
|
|
96
|
-
var useColumnCount = (width, columns, maxColumns, minColumnWidth, maxColumnWidth, gutter) => {
|
|
97
|
-
const remInPx = usePx(1);
|
|
98
|
-
return useMemo(() => {
|
|
99
|
-
if (columns != null) {
|
|
100
|
-
return columns;
|
|
101
|
-
}
|
|
102
|
-
const minColumnWidthPx = minColumnWidth * remInPx;
|
|
103
|
-
const maxColumnWidthPx = maxColumnWidth * remInPx;
|
|
104
|
-
const gutterPx = gutter * remInPx;
|
|
105
|
-
if (width <= 0 || minColumnWidthPx <= 0) {
|
|
106
|
-
return 1;
|
|
107
|
-
}
|
|
108
|
-
let cols = Math.floor(width / (minColumnWidthPx + gutterPx));
|
|
109
|
-
if (maxColumnWidthPx > 0) {
|
|
110
|
-
const effectiveColWidth = width / cols - gutterPx;
|
|
111
|
-
if (effectiveColWidth > maxColumnWidthPx) {
|
|
112
|
-
const maxCols = Math.ceil(width / (maxColumnWidthPx + gutterPx));
|
|
113
|
-
if (width / maxCols - gutterPx >= minColumnWidthPx) {
|
|
114
|
-
cols = maxCols;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
const clamped = maxColumns != null ? Math.min(cols, maxColumns) : cols;
|
|
119
|
-
return Math.max(1, clamped);
|
|
120
|
-
}, [
|
|
121
|
-
remInPx,
|
|
122
|
-
width,
|
|
123
|
-
columns,
|
|
124
|
-
maxColumns,
|
|
125
|
-
minColumnWidth,
|
|
126
|
-
maxColumnWidth,
|
|
127
|
-
gutter
|
|
128
|
-
]);
|
|
129
|
-
};
|
|
130
|
-
var Masonry = {
|
|
131
|
-
Root: MasonryRoot,
|
|
132
|
-
Content: MasonryContent,
|
|
133
|
-
Viewport: MasonryViewport
|
|
134
|
-
};
|
|
135
|
-
export {
|
|
136
|
-
Masonry
|
|
137
|
-
};
|
|
138
|
-
//# sourceMappingURL=index.mjs.map
|