1
This commit is contained in:
+46
@@ -0,0 +1,46 @@
|
||||
import * as React from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { SemanticClassNamesType, SemanticStylesType } from '../_util/hooks';
|
||||
import type { Breakpoint } from '../_util/responsiveObserver';
|
||||
import type { RowProps } from '../grid';
|
||||
import type { MasonryItemType } from './MasonryItem';
|
||||
export type Gap = number | undefined;
|
||||
export type Key = string | number;
|
||||
export type MasonrySemanticName = keyof MasonrySemanticClassNames & keyof MasonrySemanticStyles;
|
||||
export type MasonrySemanticClassNames = {
|
||||
root?: string;
|
||||
item?: string;
|
||||
};
|
||||
export type MasonrySemanticStyles = {
|
||||
root?: React.CSSProperties;
|
||||
item?: React.CSSProperties;
|
||||
};
|
||||
export type MasonryClassNamesType = SemanticClassNamesType<MasonryProps, MasonrySemanticClassNames>;
|
||||
export type MasonryStylesType = SemanticStylesType<MasonryProps, MasonrySemanticStyles>;
|
||||
export interface MasonryProps<ItemDataType = any> {
|
||||
prefixCls?: string;
|
||||
className?: string;
|
||||
rootClassName?: string;
|
||||
style?: CSSProperties;
|
||||
classNames?: MasonryClassNamesType;
|
||||
styles?: MasonryStylesType;
|
||||
/** Spacing between items */
|
||||
gutter?: RowProps['gutter'];
|
||||
items?: MasonryItemType<ItemDataType>[];
|
||||
itemRender?: (itemInfo: MasonryItemType<ItemDataType> & {
|
||||
index: number;
|
||||
}) => React.ReactNode;
|
||||
/** Number of columns in the masonry grid layout */
|
||||
columns?: number | Partial<Record<Breakpoint, number>>;
|
||||
/** Trigger when item layout order changed */
|
||||
onLayoutChange?: (sortInfo: {
|
||||
key: React.Key;
|
||||
column: number;
|
||||
}[]) => void;
|
||||
fresh?: boolean;
|
||||
}
|
||||
export interface MasonryRef {
|
||||
nativeElement: HTMLDivElement;
|
||||
}
|
||||
declare const _default: (<ItemDataType = any>(props: React.PropsWithChildren<MasonryProps<ItemDataType>> & React.RefAttributes<MasonryRef>) => React.ReactElement) & Pick<React.FC, "displayName">;
|
||||
export default _default;
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
"use client";
|
||||
|
||||
import * as React from 'react';
|
||||
import { CSSMotionList } from '@rc-component/motion';
|
||||
import ResizeObserver from '@rc-component/resize-observer';
|
||||
import useLayoutEffect from "@rc-component/util/es/hooks/useLayoutEffect";
|
||||
import isEqual from "@rc-component/util/es/isEqual";
|
||||
import { composeRef } from "@rc-component/util/es/ref";
|
||||
import { clsx } from 'clsx';
|
||||
import { useMergeSemantic } from '../_util/hooks';
|
||||
import { isNumber } from '../_util/is';
|
||||
import { responsiveArray } from '../_util/responsiveObserver';
|
||||
import { useComponentConfig } from '../config-provider/context';
|
||||
import useCSSVarCls from '../config-provider/hooks/useCSSVarCls';
|
||||
import useBreakpoint from '../grid/hooks/useBreakpoint';
|
||||
import useGutter from '../grid/hooks/useGutter';
|
||||
import { genCssVar } from '../theme/util/genStyleUtils';
|
||||
import useDelay from './hooks/useDelay';
|
||||
import usePositions from './hooks/usePositions';
|
||||
import useRefs from './hooks/useRefs';
|
||||
import MasonryItem from './MasonryItem';
|
||||
import useStyle from './style';
|
||||
const Masonry = /*#__PURE__*/React.forwardRef((props, ref) => {
|
||||
const {
|
||||
rootClassName,
|
||||
className,
|
||||
style,
|
||||
classNames,
|
||||
styles,
|
||||
columns,
|
||||
prefixCls: customizePrefixCls,
|
||||
gutter = 0,
|
||||
items,
|
||||
itemRender,
|
||||
onLayoutChange,
|
||||
fresh
|
||||
} = props;
|
||||
// ======================= MISC =======================
|
||||
const {
|
||||
getPrefixCls,
|
||||
direction,
|
||||
className: contextClassName,
|
||||
style: contextStyle,
|
||||
classNames: contextClassNames,
|
||||
styles: contextStyles
|
||||
} = useComponentConfig('masonry');
|
||||
const prefixCls = getPrefixCls('masonry', customizePrefixCls);
|
||||
const rootPrefixCls = getPrefixCls();
|
||||
const rootCls = useCSSVarCls(prefixCls);
|
||||
const [hashId, cssVarCls] = useStyle(prefixCls, rootCls);
|
||||
const [varName, varRef] = genCssVar(rootPrefixCls, 'masonry');
|
||||
// ======================= Refs =======================
|
||||
const containerRef = React.useRef(null);
|
||||
React.useImperativeHandle(ref, () => ({
|
||||
nativeElement: containerRef.current
|
||||
}));
|
||||
const [setItemRef, getItemRef] = useRefs();
|
||||
// ======================= Item =======================
|
||||
const [mergedItems, setMergedItems] = React.useState([]);
|
||||
React.useEffect(() => {
|
||||
setMergedItems(items || []);
|
||||
}, [items]);
|
||||
// ==================== Breakpoint ====================
|
||||
const screens = useBreakpoint();
|
||||
const gutters = useGutter(gutter, screens);
|
||||
const [horizontalGutter = 0, verticalGutter = horizontalGutter] = gutters;
|
||||
// ====================== Layout ======================
|
||||
const columnCount = React.useMemo(() => {
|
||||
if (!columns) {
|
||||
return 3;
|
||||
}
|
||||
if (isNumber(columns)) {
|
||||
return columns;
|
||||
}
|
||||
// Find first matching responsive breakpoint
|
||||
const matchingBreakpoint = responsiveArray.find(breakpoint => screens[breakpoint] && columns[breakpoint] !== undefined);
|
||||
if (matchingBreakpoint) {
|
||||
return columns[matchingBreakpoint];
|
||||
}
|
||||
return columns.xs ?? 1;
|
||||
}, [columns, screens]);
|
||||
// =========== Merged Props for Semantic ==========
|
||||
const mergedProps = {
|
||||
...props,
|
||||
columns: columnCount
|
||||
};
|
||||
const [mergedClassNames, mergedStyles] = useMergeSemantic([contextClassNames, classNames], [contextStyles, styles], {
|
||||
props: mergedProps
|
||||
});
|
||||
// ================== Items Position ==================
|
||||
const [itemHeights, setItemHeights] = React.useState([]);
|
||||
const collectItemSize = useDelay(() => {
|
||||
const nextItemsHeight = mergedItems.map((item, index) => {
|
||||
const itemKey = item.key ?? index;
|
||||
const itemEle = getItemRef(itemKey);
|
||||
const rect = itemEle?.getBoundingClientRect();
|
||||
return [itemKey, rect ? rect.height : 0, item.column];
|
||||
});
|
||||
setItemHeights(prevItemsHeight => isEqual(prevItemsHeight, nextItemsHeight) ? prevItemsHeight : nextItemsHeight);
|
||||
});
|
||||
const [itemPositions, totalHeight] = usePositions(itemHeights, columnCount, verticalGutter);
|
||||
const itemWithPositions = React.useMemo(() => mergedItems.map((item, index) => {
|
||||
const key = item.key ?? index;
|
||||
return {
|
||||
item,
|
||||
itemIndex: index,
|
||||
// CSSMotion will transform key to string.
|
||||
// Let's keep the original key here.
|
||||
itemKey: key,
|
||||
key,
|
||||
position: itemPositions.get(key)
|
||||
};
|
||||
}), [mergedItems, itemPositions]);
|
||||
React.useEffect(() => {
|
||||
collectItemSize();
|
||||
}, [mergedItems, columnCount]);
|
||||
// Trigger for `onLayoutChange`
|
||||
const [itemColumns, setItemColumns] = React.useState([]);
|
||||
useLayoutEffect(() => {
|
||||
if (onLayoutChange && itemWithPositions.every(({
|
||||
position
|
||||
}) => position)) {
|
||||
setItemColumns(prevItemColumns => {
|
||||
const nextItemColumns = itemWithPositions.map(({
|
||||
item,
|
||||
position
|
||||
}) => [item, position.column]);
|
||||
return isEqual(prevItemColumns, nextItemColumns) ? prevItemColumns : nextItemColumns;
|
||||
});
|
||||
}
|
||||
}, [itemWithPositions]);
|
||||
useLayoutEffect(() => {
|
||||
if (onLayoutChange && items && items.length === itemColumns.length) {
|
||||
onLayoutChange(itemColumns.map(([item, column]) => ({
|
||||
...item,
|
||||
column
|
||||
})));
|
||||
}
|
||||
}, [itemColumns]);
|
||||
// ====================== Render ======================
|
||||
return /*#__PURE__*/React.createElement(ResizeObserver, {
|
||||
onResize: collectItemSize
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
ref: containerRef,
|
||||
className: clsx(prefixCls, contextClassName, mergedClassNames.root, rootClassName, className, hashId, cssVarCls, {
|
||||
[`${prefixCls}-rtl`]: direction === 'rtl'
|
||||
}),
|
||||
style: {
|
||||
height: totalHeight,
|
||||
...mergedStyles.root,
|
||||
...contextStyle,
|
||||
...style
|
||||
},
|
||||
// Listen for image events
|
||||
onLoad: collectItemSize,
|
||||
onError: collectItemSize
|
||||
}, /*#__PURE__*/React.createElement(CSSMotionList, {
|
||||
keys: itemWithPositions,
|
||||
component: false,
|
||||
// Motion config
|
||||
motionAppear: true,
|
||||
motionLeave: true,
|
||||
motionName: `${prefixCls}-item-fade`
|
||||
}, (motionInfo, motionRef) => {
|
||||
const {
|
||||
item,
|
||||
itemKey,
|
||||
position = {},
|
||||
itemIndex,
|
||||
key,
|
||||
className: motionClassName,
|
||||
style: motionStyle
|
||||
} = motionInfo;
|
||||
const {
|
||||
column: columnIndex = 0
|
||||
} = position;
|
||||
const itemStyle = {
|
||||
[varName('item-width')]: `calc((100% + ${horizontalGutter}px) / ${columnCount})`,
|
||||
insetInlineStart: `calc(${varRef('item-width')} * ${columnIndex})`,
|
||||
width: `calc(${varRef('item-width')} - ${horizontalGutter}px)`,
|
||||
top: position.top,
|
||||
position: 'absolute'
|
||||
};
|
||||
return /*#__PURE__*/React.createElement(MasonryItem, {
|
||||
prefixCls: prefixCls,
|
||||
key: key,
|
||||
item: item,
|
||||
style: {
|
||||
...motionStyle,
|
||||
...mergedStyles.item,
|
||||
...itemStyle
|
||||
},
|
||||
className: clsx(mergedClassNames.item, motionClassName),
|
||||
ref: composeRef(motionRef, ele => setItemRef(itemKey, ele)),
|
||||
index: itemIndex,
|
||||
itemRender: itemRender,
|
||||
column: columnIndex,
|
||||
onResize: fresh ? collectItemSize : null
|
||||
});
|
||||
})));
|
||||
});
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
Masonry.displayName = 'Masonry';
|
||||
}
|
||||
export default Masonry;
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import React from 'react';
|
||||
import type { MasonryProps } from './Masonry';
|
||||
export interface MasonryItemType<T = any> {
|
||||
key: React.Key;
|
||||
column?: number;
|
||||
height?: number;
|
||||
children?: React.ReactNode;
|
||||
data: T;
|
||||
}
|
||||
interface MasonryItemProps<T = any> extends Pick<MasonryProps, 'itemRender'> {
|
||||
prefixCls: string;
|
||||
item: MasonryItemType<T>;
|
||||
style: React.CSSProperties;
|
||||
className?: string;
|
||||
index: number;
|
||||
column: number;
|
||||
onResize: VoidFunction | null;
|
||||
}
|
||||
declare const MasonryItem: React.ForwardRefExoticComponent<MasonryItemProps<any> & React.RefAttributes<HTMLDivElement>>;
|
||||
export default MasonryItem;
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
import ResizeObserver from '@rc-component/resize-observer';
|
||||
import { clsx } from 'clsx';
|
||||
const MasonryItem = /*#__PURE__*/React.forwardRef((props, ref) => {
|
||||
const {
|
||||
item,
|
||||
style,
|
||||
prefixCls,
|
||||
itemRender,
|
||||
className,
|
||||
index,
|
||||
column,
|
||||
onResize
|
||||
} = props;
|
||||
const itemPrefix = `${prefixCls}-item`;
|
||||
// ====================== Render ======================
|
||||
const renderNode = useMemo(() => {
|
||||
return item.children ?? itemRender?.({
|
||||
...item,
|
||||
index,
|
||||
column
|
||||
});
|
||||
}, [item, itemRender, column, index]);
|
||||
let returnNode = /*#__PURE__*/React.createElement("div", {
|
||||
ref: ref,
|
||||
style: style,
|
||||
className: clsx(itemPrefix, className)
|
||||
}, renderNode);
|
||||
// Listen for resize
|
||||
if (onResize) {
|
||||
returnNode = /*#__PURE__*/React.createElement(ResizeObserver, {
|
||||
onResize: onResize
|
||||
}, returnNode);
|
||||
}
|
||||
return returnNode;
|
||||
});
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
MasonryItem.displayName = 'MasonryItem';
|
||||
}
|
||||
export default MasonryItem;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function useDelay(callback: VoidFunction): () => void;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import * as React from 'react';
|
||||
import { useEvent } from '@rc-component/util';
|
||||
import raf from "@rc-component/util/es/raf";
|
||||
export default function useDelay(callback) {
|
||||
const idRef = React.useRef(0);
|
||||
const clearRaf = () => {
|
||||
raf.cancel(idRef.current);
|
||||
};
|
||||
React.useEffect(() => clearRaf, []);
|
||||
const triggerFn = useEvent(() => {
|
||||
clearRaf();
|
||||
idRef.current = raf(callback);
|
||||
});
|
||||
return triggerFn;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { Key } from 'react';
|
||||
export type ItemHeightData = [key: Key, height: number, column?: number];
|
||||
export type ItemPositions = Map<Key, {
|
||||
column: number;
|
||||
top: number;
|
||||
}>;
|
||||
/**
|
||||
* Auto arrange the items in the masonry layout.
|
||||
* Always get stable positions by order
|
||||
* instead of dynamic adjust for next item height.
|
||||
*/
|
||||
export default function usePositions(itemHeights: ItemHeightData[], columnCount: number, verticalGutter: number): readonly [ItemPositions, number];
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
|
||||
// Disabled the rule since `fill` is safe here
|
||||
// but `Array.from` will increase bundle size.
|
||||
/* eslint-disable unicorn/no-new-array */
|
||||
import * as React from 'react';
|
||||
/**
|
||||
* Auto arrange the items in the masonry layout.
|
||||
* Always get stable positions by order
|
||||
* instead of dynamic adjust for next item height.
|
||||
*/
|
||||
export default function usePositions(itemHeights, columnCount, verticalGutter) {
|
||||
// ==================== Auto Order ====================
|
||||
const [orderItemPositions, orderTotalHeight] = React.useMemo(() => {
|
||||
const columnHeights = new Array(columnCount).fill(0);
|
||||
const itemPositions = new Map();
|
||||
for (let i = 0; i < itemHeights.length; i += 1) {
|
||||
const [itemKey, itemHeight, itemColumn] = itemHeights[i];
|
||||
let targetColumnIndex = itemColumn ?? columnHeights.indexOf(Math.min.apply(Math, _toConsumableArray(columnHeights)));
|
||||
targetColumnIndex = Math.min(targetColumnIndex, columnCount - 1);
|
||||
const top = columnHeights[targetColumnIndex];
|
||||
itemPositions.set(itemKey, {
|
||||
column: targetColumnIndex,
|
||||
top
|
||||
});
|
||||
columnHeights[targetColumnIndex] += itemHeight + verticalGutter;
|
||||
}
|
||||
return [itemPositions, Math.max(0, Math.max.apply(Math, _toConsumableArray(columnHeights)) - verticalGutter)];
|
||||
}, [columnCount, itemHeights, verticalGutter]);
|
||||
// ====================== Return ======================
|
||||
return [orderItemPositions, orderTotalHeight];
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import * as React from 'react';
|
||||
export default function useRefs(): readonly [(key: React.Key, element: HTMLDivElement | null) => void, (key: React.Key) => HTMLDivElement | null | undefined];
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import * as React from 'react';
|
||||
export default function useRefs() {
|
||||
const ref = React.useRef(null);
|
||||
if (ref.current === null) {
|
||||
ref.current = new Map();
|
||||
}
|
||||
const setRef = (key, element) => {
|
||||
ref.current.set(key, element);
|
||||
};
|
||||
const getRef = key => ref.current.get(key);
|
||||
return [setRef, getRef];
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import Masonry from './Masonry';
|
||||
export type { MasonryProps, MasonrySemanticClassNames, MasonrySemanticName, MasonrySemanticStyles, } from './Masonry';
|
||||
export default Masonry;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
"use client";
|
||||
|
||||
import Masonry from './Masonry';
|
||||
export default Masonry;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { CSSObject } from '@ant-design/cssinjs';
|
||||
import type { FullToken, GenerateStyle } from '../../theme/internal';
|
||||
export interface ComponentToken {
|
||||
}
|
||||
export interface MasonryToken extends FullToken<'Masonry'> {
|
||||
}
|
||||
export declare const genMasonryStyle: GenerateStyle<MasonryToken, CSSObject>;
|
||||
declare const _default: (prefixCls: string, rootCls?: string) => readonly [string, string];
|
||||
export default _default;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { genStyleHooks } from '../../theme/internal';
|
||||
export const genMasonryStyle = token => {
|
||||
const {
|
||||
componentCls
|
||||
} = token;
|
||||
const itemCls = `${componentCls}-item`;
|
||||
return {
|
||||
[componentCls]: {
|
||||
position: 'relative',
|
||||
boxSizing: 'border-box',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flexWrap: 'wrap',
|
||||
'&-rtl': {
|
||||
direction: 'rtl'
|
||||
},
|
||||
[`& > ${itemCls}`]: {
|
||||
boxSizing: 'border-box',
|
||||
// Motion
|
||||
'&-fade': {
|
||||
'&-appear': {
|
||||
transition: `opacity ${token.motionDurationSlow} ${token.motionEaseOut}`,
|
||||
opacity: 0,
|
||||
'&-active': {
|
||||
opacity: 1
|
||||
}
|
||||
},
|
||||
'&-leave': {
|
||||
transition: `opacity ${token.motionDurationFast} ${token.motionEaseOut}`,
|
||||
opacity: 1,
|
||||
'&-active': {
|
||||
opacity: 0
|
||||
}
|
||||
}
|
||||
},
|
||||
[`&:not(${itemCls}-fade)`]: {
|
||||
transition: ['left', 'right', 'top'].map(prop => `${prop} ${token.motionDurationSlow} ${token.motionEaseOut}`).join(',')
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
export default genStyleHooks('Masonry', genMasonryStyle);
|
||||
Reference in New Issue
Block a user