mirror of https://github.com/usememos/memos
refactor(web): remove masonry memo layout (#5746)
Co-authored-by: memoclaw <265580040+memoclaw@users.noreply.github.com>pull/5749/head
parent
05810e7882
commit
a7cabb7ce6
@ -1,34 +0,0 @@
|
||||
import { MasonryItem } from "./MasonryItem";
|
||||
import { MasonryColumnProps } from "./types";
|
||||
|
||||
export function MasonryColumn({
|
||||
memoIndices,
|
||||
memoList,
|
||||
renderer,
|
||||
renderContext,
|
||||
onHeightChange,
|
||||
isFirstColumn,
|
||||
prefixElement,
|
||||
prefixElementRef,
|
||||
}: MasonryColumnProps) {
|
||||
return (
|
||||
<div className="min-w-0 mx-auto w-full max-w-2xl">
|
||||
{/* Prefix element (like memo editor) goes in first column */}
|
||||
{isFirstColumn && prefixElement && <div ref={prefixElementRef}>{prefixElement}</div>}
|
||||
|
||||
{/* Render all memos assigned to this column */}
|
||||
{memoIndices?.map((memoIndex) => {
|
||||
const memo = memoList[memoIndex];
|
||||
return memo ? (
|
||||
<MasonryItem
|
||||
key={`${memo.name}-${memo.displayTime}`}
|
||||
memo={memo}
|
||||
renderer={renderer}
|
||||
renderContext={renderContext}
|
||||
onHeightChange={onHeightChange}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { MasonryItemProps } from "./types";
|
||||
|
||||
export function MasonryItem({ memo, renderer, renderContext, onHeightChange }: MasonryItemProps) {
|
||||
const itemRef = useRef<HTMLDivElement>(null);
|
||||
const resizeObserverRef = useRef<ResizeObserver | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!itemRef.current) return;
|
||||
|
||||
const measureHeight = () => {
|
||||
if (itemRef.current) {
|
||||
const height = itemRef.current.offsetHeight;
|
||||
onHeightChange(memo.name, height);
|
||||
}
|
||||
};
|
||||
|
||||
// Initial measurement
|
||||
measureHeight();
|
||||
|
||||
// Set up ResizeObserver to track dynamic content changes
|
||||
resizeObserverRef.current = new ResizeObserver(measureHeight);
|
||||
resizeObserverRef.current.observe(itemRef.current);
|
||||
|
||||
// Cleanup on unmount
|
||||
return () => {
|
||||
resizeObserverRef.current?.disconnect();
|
||||
};
|
||||
}, [memo.name, onHeightChange]);
|
||||
|
||||
return <div ref={itemRef}>{renderer(memo, renderContext)}</div>;
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
import { useMemo, useRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MasonryColumn } from "./MasonryColumn";
|
||||
import { MasonryViewProps, MemoRenderContext } from "./types";
|
||||
import { useMasonryLayout } from "./useMasonryLayout";
|
||||
|
||||
const MasonryView = ({ memoList, renderer, prefixElement, listMode = false }: MasonryViewProps) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const prefixElementRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { columns, distribution, handleHeightChange } = useMasonryLayout(memoList, listMode, containerRef, prefixElementRef);
|
||||
|
||||
// Create render context: always enable compact mode for list views
|
||||
const renderContext: MemoRenderContext = useMemo(
|
||||
() => ({
|
||||
compact: true,
|
||||
columns,
|
||||
}),
|
||||
[columns],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn("w-full grid gap-2")}
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${columns}, 1fr)`,
|
||||
}}
|
||||
>
|
||||
{Array.from({ length: columns }).map((_, columnIndex) => (
|
||||
<MasonryColumn
|
||||
key={columnIndex}
|
||||
memoIndices={distribution[columnIndex] || []}
|
||||
memoList={memoList}
|
||||
renderer={renderer}
|
||||
renderContext={renderContext}
|
||||
onHeightChange={handleHeightChange}
|
||||
isFirstColumn={columnIndex === 0}
|
||||
prefixElement={prefixElement}
|
||||
prefixElementRef={prefixElementRef}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MasonryView;
|
||||
@ -1,116 +0,0 @@
|
||||
# MasonryView - Height-Based Masonry Layout
|
||||
|
||||
## Overview
|
||||
|
||||
This improved MasonryView component implements a true masonry layout that distributes memo cards based on their actual rendered heights, creating a balanced waterfall-style layout instead of naive sequential distribution.
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. Height Measurement
|
||||
|
||||
- **MemoItem Wrapper**: Each memo is wrapped in a `MemoItem` component that measures its actual height
|
||||
- **ResizeObserver**: Automatically detects height changes when content changes (e.g., images load, content expands)
|
||||
- **Real-time Updates**: Heights are measured on mount and updated dynamically
|
||||
|
||||
### 2. Smart Distribution Algorithm
|
||||
|
||||
- **Shortest Column First**: Memos are assigned to the column with the smallest total height
|
||||
- **Dynamic Balancing**: As new memos are added or heights change, the layout rebalances
|
||||
- **Prefix Element Support**: Properly accounts for the MemoEditor height in the first column
|
||||
|
||||
### 3. Performance Optimizations
|
||||
|
||||
- **Memoized Callbacks**: `handleHeightChange` is memoized to prevent unnecessary re-renders
|
||||
- **Efficient State Updates**: Only redistributes when necessary (memo list changes, column count changes)
|
||||
- **ResizeObserver Cleanup**: Properly disconnects observers to prevent memory leaks
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
MasonryView
|
||||
├── State Management
|
||||
│ ├── columns: number of columns based on viewport width
|
||||
│ ├── itemHeights: Map<memoName, height> for each memo
|
||||
│ ├── columnHeights: current total height of each column
|
||||
│ └── distribution: which memos belong to which column
|
||||
├── MemoItem (for each memo)
|
||||
│ ├── Ref for height measurement
|
||||
│ ├── ResizeObserver for dynamic updates
|
||||
│ └── Callback to parent on height changes
|
||||
└── Distribution Algorithm
|
||||
├── Finds shortest column
|
||||
├── Assigns memo to that column
|
||||
└── Updates column height tracking
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The component maintains the same API as before, so no changes are needed in consuming components:
|
||||
|
||||
```tsx
|
||||
<MasonryView memoList={memos} renderer={(memo) => <MemoView memo={memo} />} prefixElement={<MemoEditor />} listMode={false} />
|
||||
```
|
||||
|
||||
## Benefits vs Previous Implementation
|
||||
|
||||
### Before (Naive)
|
||||
|
||||
- Distributed memos by index: `memo[i % columns]`
|
||||
- No consideration of actual heights
|
||||
- Resulted in unbalanced columns
|
||||
- Static layout that didn't adapt to content
|
||||
|
||||
### After (Height-Based)
|
||||
|
||||
- Distributes memos by actual rendered height
|
||||
- Creates balanced columns with similar total heights
|
||||
- Adapts to dynamic content changes
|
||||
- Smoother visual layout
|
||||
|
||||
## Technical Implementation Details
|
||||
|
||||
### Height Measurement
|
||||
|
||||
```tsx
|
||||
const measureHeight = () => {
|
||||
if (itemRef.current) {
|
||||
const height = itemRef.current.offsetHeight;
|
||||
onHeightChange(memo.name, height);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Distribution Algorithm
|
||||
|
||||
```tsx
|
||||
const shortestColumnIndex = columnHeights.reduce(
|
||||
(minIndex, currentHeight, currentIndex) => (currentHeight < columnHeights[minIndex] ? currentIndex : minIndex),
|
||||
0,
|
||||
);
|
||||
```
|
||||
|
||||
### Dynamic Updates
|
||||
|
||||
- **Window Resize**: Recalculates column count and redistributes
|
||||
- **Content Changes**: ResizeObserver triggers height remeasurement
|
||||
- **Memo List Changes**: Redistributes all memos with new ordering
|
||||
|
||||
## Browser Support
|
||||
|
||||
- Modern browsers with ResizeObserver support
|
||||
- Fallback behavior: Falls back to sequential distribution if ResizeObserver is not available
|
||||
- CSS Grid support required for column layout
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Initial Load**: Slight delay as heights are measured
|
||||
2. **Memory Usage**: Stores height data for each memo
|
||||
3. **Re-renders**: Optimized to only update when necessary
|
||||
4. **Large Lists**: Scales well with proper virtualization (if needed in future)
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **Virtualization**: For very large memo lists
|
||||
2. **Animation**: Smooth transitions when items change position
|
||||
3. **Gap Optimization**: More sophisticated gap handling
|
||||
4. **Estimated Heights**: Faster initial layout with height estimation
|
||||
@ -1,3 +0,0 @@
|
||||
export const MINIMUM_MEMO_VIEWPORT_WIDTH = 512;
|
||||
|
||||
export const REDISTRIBUTION_DEBOUNCE_MS = 100;
|
||||
@ -1,68 +0,0 @@
|
||||
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { DistributionResult } from "./types";
|
||||
|
||||
export function distributeItemsToColumns(
|
||||
memos: Memo[],
|
||||
columns: number,
|
||||
itemHeights: Map<string, number>,
|
||||
prefixElementHeight: number = 0,
|
||||
): DistributionResult {
|
||||
if (columns === 1) {
|
||||
const totalHeight = memos.reduce((sum, memo) => sum + (itemHeights.get(memo.name) || 0), prefixElementHeight);
|
||||
return {
|
||||
distribution: [Array.from({ length: memos.length }, (_, i) => i)],
|
||||
columnHeights: [totalHeight],
|
||||
};
|
||||
}
|
||||
|
||||
const distribution: number[][] = Array.from({ length: columns }, () => []);
|
||||
const columnHeights: number[] = Array(columns).fill(0);
|
||||
const columnCounts: number[] = Array(columns).fill(0);
|
||||
|
||||
if (prefixElementHeight > 0) {
|
||||
columnHeights[0] = prefixElementHeight;
|
||||
}
|
||||
|
||||
let startIndex = 0;
|
||||
|
||||
if (memos.length > 0) {
|
||||
const firstMemoHeight = itemHeights.get(memos[0].name) || 0;
|
||||
distribution[0].push(0);
|
||||
columnHeights[0] += firstMemoHeight;
|
||||
columnCounts[0] += 1;
|
||||
startIndex = 1;
|
||||
}
|
||||
|
||||
for (let i = startIndex; i < memos.length; i++) {
|
||||
const memo = memos[i];
|
||||
const height = itemHeights.get(memo.name) || 0;
|
||||
|
||||
const shortestColumnIndex = findShortestColumnIndex(columnHeights, columnCounts);
|
||||
|
||||
distribution[shortestColumnIndex].push(i);
|
||||
columnHeights[shortestColumnIndex] += height;
|
||||
columnCounts[shortestColumnIndex] += 1;
|
||||
}
|
||||
|
||||
return { distribution, columnHeights };
|
||||
}
|
||||
|
||||
function findShortestColumnIndex(columnHeights: number[], columnCounts: number[]): number {
|
||||
let minIndex = 0;
|
||||
let minHeight = columnHeights[0];
|
||||
|
||||
for (let i = 1; i < columnHeights.length; i++) {
|
||||
const currentHeight = columnHeights[i];
|
||||
if (currentHeight < minHeight) {
|
||||
minHeight = currentHeight;
|
||||
minIndex = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentHeight === minHeight && columnCounts[i] < columnCounts[minIndex]) {
|
||||
minIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
return minIndex;
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
// Main component
|
||||
|
||||
// Constants
|
||||
export { MINIMUM_MEMO_VIEWPORT_WIDTH, REDISTRIBUTION_DEBOUNCE_MS } from "./constants";
|
||||
// Utilities
|
||||
export { distributeItemsToColumns } from "./distributeItems";
|
||||
// Sub-components (exported for testing or advanced usage)
|
||||
export { MasonryColumn } from "./MasonryColumn";
|
||||
export { MasonryItem } from "./MasonryItem";
|
||||
export { default } from "./MasonryView";
|
||||
|
||||
// Types
|
||||
export type {
|
||||
DistributionResult,
|
||||
MasonryColumnProps,
|
||||
MasonryItemProps,
|
||||
MasonryViewProps,
|
||||
MemoRenderContext,
|
||||
MemoWithHeight,
|
||||
} from "./types";
|
||||
// Hooks
|
||||
export { useMasonryLayout } from "./useMasonryLayout";
|
||||
@ -1,41 +0,0 @@
|
||||
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
|
||||
|
||||
export interface MemoRenderContext {
|
||||
compact: boolean;
|
||||
columns: number;
|
||||
}
|
||||
|
||||
export interface MasonryViewProps {
|
||||
memoList: Memo[];
|
||||
renderer: (memo: Memo, context?: MemoRenderContext) => JSX.Element;
|
||||
prefixElement?: JSX.Element;
|
||||
listMode?: boolean;
|
||||
}
|
||||
|
||||
export interface MasonryItemProps {
|
||||
memo: Memo;
|
||||
renderer: (memo: Memo, context?: MemoRenderContext) => JSX.Element;
|
||||
renderContext: MemoRenderContext;
|
||||
onHeightChange: (memoName: string, height: number) => void;
|
||||
}
|
||||
|
||||
export interface MasonryColumnProps {
|
||||
memoIndices: number[];
|
||||
memoList: Memo[];
|
||||
renderer: (memo: Memo, context?: MemoRenderContext) => JSX.Element;
|
||||
renderContext: MemoRenderContext;
|
||||
onHeightChange: (memoName: string, height: number) => void;
|
||||
isFirstColumn: boolean;
|
||||
prefixElement?: JSX.Element;
|
||||
prefixElementRef?: React.RefObject<HTMLDivElement>;
|
||||
}
|
||||
|
||||
export interface DistributionResult {
|
||||
distribution: number[][];
|
||||
columnHeights: number[];
|
||||
}
|
||||
|
||||
export interface MemoWithHeight {
|
||||
index: number;
|
||||
height: number;
|
||||
}
|
||||
@ -1,106 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Memo } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { MINIMUM_MEMO_VIEWPORT_WIDTH, REDISTRIBUTION_DEBOUNCE_MS } from "./constants";
|
||||
import { distributeItemsToColumns } from "./distributeItems";
|
||||
|
||||
export function useMasonryLayout(
|
||||
memoList: Memo[],
|
||||
listMode: boolean,
|
||||
containerRef: React.RefObject<HTMLDivElement>,
|
||||
prefixElementRef: React.RefObject<HTMLDivElement>,
|
||||
) {
|
||||
const [columns, setColumns] = useState(1);
|
||||
const [itemHeights, setItemHeights] = useState<Map<string, number>>(new Map());
|
||||
const [distribution, setDistribution] = useState<number[][]>([[]]);
|
||||
|
||||
const redistributionTimeoutRef = useRef<number | null>(null);
|
||||
const itemHeightsRef = useRef<Map<string, number>>(itemHeights);
|
||||
|
||||
useEffect(() => {
|
||||
itemHeightsRef.current = itemHeights;
|
||||
}, [itemHeights]);
|
||||
|
||||
const calculateColumns = useCallback(() => {
|
||||
if (!containerRef.current || listMode) return 1;
|
||||
|
||||
const containerWidth = containerRef.current.offsetWidth;
|
||||
const scale = containerWidth / MINIMUM_MEMO_VIEWPORT_WIDTH;
|
||||
return scale >= 1.2 ? Math.ceil(scale) : 1;
|
||||
}, [containerRef, listMode]);
|
||||
|
||||
const redistributeMemos = useCallback(() => {
|
||||
const prefixHeight = prefixElementRef.current?.offsetHeight || 0;
|
||||
setDistribution(() => {
|
||||
const { distribution: newDistribution } = distributeItemsToColumns(memoList, columns, itemHeightsRef.current, prefixHeight);
|
||||
return newDistribution;
|
||||
});
|
||||
}, [memoList, columns, prefixElementRef]);
|
||||
|
||||
const debouncedRedistribute = useCallback(
|
||||
(newItemHeights: Map<string, number>) => {
|
||||
if (redistributionTimeoutRef.current) {
|
||||
clearTimeout(redistributionTimeoutRef.current);
|
||||
}
|
||||
|
||||
redistributionTimeoutRef.current = window.setTimeout(() => {
|
||||
const prefixHeight = prefixElementRef.current?.offsetHeight || 0;
|
||||
setDistribution(() => {
|
||||
const { distribution: newDistribution } = distributeItemsToColumns(memoList, columns, newItemHeights, prefixHeight);
|
||||
return newDistribution;
|
||||
});
|
||||
}, REDISTRIBUTION_DEBOUNCE_MS);
|
||||
},
|
||||
[memoList, columns, prefixElementRef],
|
||||
);
|
||||
|
||||
const handleHeightChange = useCallback(
|
||||
(memoName: string, height: number) => {
|
||||
setItemHeights((prevHeights) => {
|
||||
const newItemHeights = new Map(prevHeights);
|
||||
const previousHeight = prevHeights.get(memoName);
|
||||
|
||||
if (previousHeight === height) {
|
||||
return prevHeights;
|
||||
}
|
||||
|
||||
newItemHeights.set(memoName, height);
|
||||
debouncedRedistribute(newItemHeights);
|
||||
return newItemHeights;
|
||||
});
|
||||
},
|
||||
[debouncedRedistribute],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
const newColumns = calculateColumns();
|
||||
if (newColumns !== columns) {
|
||||
setColumns(newColumns);
|
||||
}
|
||||
};
|
||||
|
||||
handleResize();
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, [calculateColumns, columns, containerRef]);
|
||||
|
||||
useEffect(() => {
|
||||
redistributeMemos();
|
||||
}, [columns, memoList, redistributeMemos]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (redistributionTimeoutRef.current) {
|
||||
clearTimeout(redistributionTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
columns,
|
||||
distribution,
|
||||
handleHeightChange,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in New Issue