mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
refactor: rebuild desktop app with Tauri
This commit is contained in:
1 parent
a3ec2a0dfc
commit
4053a7fb20
808 files changed
+87359
-181491
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.root { position: relative; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.scrollArea { width: 100%; height: 100%; }
|
||||
.horizontal .scrollArea { padding-bottom: 7px; }
|
||||
.horizontalViewport { overflow-x: auto; }
|
||||
.horizontalTrack { position: absolute; z-index: 20; right: 0; bottom: 0; left: 0; height: 7px; opacity: 0; pointer-events: none; touch-action: none; user-select: none; transition: opacity 120ms ease; }
|
||||
.horizontalTrack.visible { opacity: 1; pointer-events: auto; }
|
||||
.horizontalThumb { height: 7px; min-width: 20px; background: var(--vscode-scrollbarSlider-background, rgb(0 0 0 / 10%)); border-radius: 999px; cursor: default; }
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { ScrollArea } from "../scrollable/ScrollArea";
|
||||
import styles from "./ScrollableContent.module.scss";
|
||||
|
||||
type ScrollableContentProps = {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
viewportClassName?: string;
|
||||
contentClassName?: string;
|
||||
scrollbarInsetTop?: string;
|
||||
horizontal?: boolean;
|
||||
alwaysShowVertical?: boolean;
|
||||
};
|
||||
|
||||
export function ScrollableContent({ children, className, viewportClassName, contentClassName, scrollbarInsetTop, horizontal = false, alwaysShowVertical = false }: ScrollableContentProps) {
|
||||
const viewport = useRef<HTMLDivElement>(null);
|
||||
const content = useRef<HTMLDivElement>(null);
|
||||
const track = useRef<HTMLDivElement>(null);
|
||||
const horizontalDragOffset = useRef<number | null>(null);
|
||||
const [metrics, setMetrics] = useState({ visible: false, left: 0, width: 0 });
|
||||
useEffect(() => {
|
||||
if (!horizontal || !viewport.current || !content.current || !track.current) return;
|
||||
const viewportNode = viewport.current;
|
||||
const contentNode = content.current;
|
||||
const update = () => {
|
||||
const maximum = Math.max(0, viewportNode.scrollWidth - viewportNode.clientWidth);
|
||||
const trackWidth = track.current?.clientWidth ?? 0;
|
||||
const width = maximum > 0 ? Math.max(20, trackWidth * viewportNode.clientWidth / viewportNode.scrollWidth) : 0;
|
||||
setMetrics({ visible: maximum > 0, left: maximum > 0 ? viewportNode.scrollLeft / maximum * Math.max(0, trackWidth - width) : 0, width });
|
||||
};
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(viewportNode);
|
||||
observer.observe(contentNode);
|
||||
viewportNode.addEventListener("scroll", update, { passive: true });
|
||||
update();
|
||||
return () => { observer.disconnect(); viewportNode.removeEventListener("scroll", update); };
|
||||
}, [horizontal]);
|
||||
const moveHorizontal = (clientX: number, thumbOffset: number) => {
|
||||
const viewportNode = viewport.current;
|
||||
const trackNode = track.current;
|
||||
if (!viewportNode || !trackNode) return;
|
||||
const rect = trackNode.getBoundingClientRect();
|
||||
const maximum = viewportNode.scrollWidth - viewportNode.clientWidth;
|
||||
const maximumThumb = rect.width - metrics.width;
|
||||
if (maximum <= 0 || maximumThumb <= 0) return;
|
||||
viewportNode.scrollLeft = Math.max(0, Math.min(maximumThumb, clientX - rect.left - thumbOffset)) / maximumThumb * maximum;
|
||||
};
|
||||
return <div className={[styles.root, horizontal && styles.horizontal, className].filter(Boolean).join(" ")}>
|
||||
<ScrollArea className={styles.scrollArea} viewportClassName={[horizontal && styles.horizontalViewport, viewportClassName].filter(Boolean).join(" ")} contentClassName={contentClassName} viewportRef={viewport} contentRef={content} scrollbarSize={7} scrollbarInsetTop={scrollbarInsetTop} scrollbarVisibility={alwaysShowVertical ? "always" : "auto"}>{children}</ScrollArea>
|
||||
{horizontal && <div
|
||||
ref={track}
|
||||
className={[styles.horizontalTrack, metrics.visible && styles.visible].filter(Boolean).join(" ")}
|
||||
onPointerDown={(event) => {
|
||||
if (event.target !== event.currentTarget) return;
|
||||
event.preventDefault();
|
||||
moveHorizontal(event.clientX, metrics.width / 2);
|
||||
}}
|
||||
><div
|
||||
className={styles.horizontalThumb}
|
||||
style={{ width: metrics.width, transform: `translateX(${metrics.left}px)` }}
|
||||
onPointerDown={(event) => {
|
||||
if (event.pointerType === "mouse" && event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
horizontalDragOffset.current = event.clientX - event.currentTarget.getBoundingClientRect().left;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
if (horizontalDragOffset.current === null || !event.currentTarget.hasPointerCapture(event.pointerId)) return;
|
||||
event.preventDefault();
|
||||
moveHorizontal(event.clientX, horizontalDragOffset.current);
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
horizontalDragOffset.current = null;
|
||||
}}
|
||||
onPointerCancel={() => { horizontalDragOffset.current = null; }}
|
||||
onLostPointerCapture={() => { horizontalDragOffset.current = null; }}
|
||||
/></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useCallback, type CSSProperties, type ReactNode } from "react";
|
||||
import { VirtualList as VirtualListEngine } from "./VirtualListEngine";
|
||||
import type { VirtualListApi } from "./virtualTypes";
|
||||
|
||||
type ItemKey<TItem> = keyof TItem | ((item: TItem, index: number) => string | number);
|
||||
|
||||
export type VirtualListProps<TItem> = {
|
||||
items: TItem[];
|
||||
itemKey: ItemKey<TItem>;
|
||||
children: (item: TItem, index: number) => ReactNode;
|
||||
empty?: ReactNode;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
style?: CSSProperties;
|
||||
overscan?: number;
|
||||
itemGap?: number;
|
||||
estimatedItemHeight?: number;
|
||||
scrollbarInsetTop?: CSSProperties["top"];
|
||||
onReady?: (api: VirtualListApi) => void;
|
||||
};
|
||||
|
||||
export function VirtualList<TItem>({
|
||||
items,
|
||||
itemKey,
|
||||
children,
|
||||
empty = null,
|
||||
className,
|
||||
contentClassName,
|
||||
style,
|
||||
overscan = 4,
|
||||
itemGap = 0,
|
||||
estimatedItemHeight = 54,
|
||||
scrollbarInsetTop,
|
||||
onReady,
|
||||
}: VirtualListProps<TItem>) {
|
||||
const getKey = useCallback((item: TItem, index: number) => {
|
||||
const key = typeof itemKey === "function" ? itemKey(item, index) : item[itemKey];
|
||||
return String(key);
|
||||
}, [itemKey]);
|
||||
|
||||
const estimateSize = useCallback(() => estimatedItemHeight, [estimatedItemHeight]);
|
||||
|
||||
if (!items.length) {
|
||||
return <div className={className} style={style}>{empty}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<VirtualListEngine
|
||||
items={items}
|
||||
getKey={getKey}
|
||||
estimateSize={estimateSize}
|
||||
renderItem={(item, context) => children(item, context.index)}
|
||||
overscan={overscan}
|
||||
itemGap={itemGap}
|
||||
scrollbarSize={7}
|
||||
scrollbarInsetTop={scrollbarInsetTop}
|
||||
onReady={onReady}
|
||||
className={className}
|
||||
contentClassName={contentClassName}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import {
|
||||
ScrollArea,
|
||||
type ScrollAreaApi,
|
||||
type ScrollAreaState,
|
||||
} from "../scrollable/ScrollArea"
|
||||
import { RangeMap } from "./rangeMap"
|
||||
import type {
|
||||
VirtualListApi,
|
||||
VirtualListProps,
|
||||
VirtualListRenderContext,
|
||||
} from "./virtualTypes"
|
||||
|
||||
interface RenderRange {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
interface ViewportAnchor {
|
||||
index: number
|
||||
topDelta: number
|
||||
}
|
||||
|
||||
interface ContentInsets {
|
||||
top: number
|
||||
bottom: number
|
||||
}
|
||||
|
||||
interface VirtualRowProps {
|
||||
index: number
|
||||
top: number
|
||||
measure: (index: number, node: HTMLElement | null) => void
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function getVisibleRange(
|
||||
rangeMap: RangeMap,
|
||||
scrollTop: number,
|
||||
viewportHeight: number
|
||||
): RenderRange {
|
||||
if (rangeMap.count === 0 || viewportHeight <= 0) return { start: 0, end: 0 }
|
||||
|
||||
return {
|
||||
start: rangeMap.indexAt(scrollTop),
|
||||
end: rangeMap.indexAfter(scrollTop + viewportHeight - 1),
|
||||
}
|
||||
}
|
||||
|
||||
function getRenderRange(
|
||||
rangeMap: RangeMap,
|
||||
scrollTop: number,
|
||||
viewportHeight: number,
|
||||
overscan: number
|
||||
): RenderRange {
|
||||
const visibleRange = getVisibleRange(rangeMap, scrollTop, viewportHeight)
|
||||
|
||||
return {
|
||||
start: Math.max(0, visibleRange.start - overscan),
|
||||
end: Math.min(rangeMap.count, visibleRange.end + overscan),
|
||||
}
|
||||
}
|
||||
|
||||
function getViewportAnchor(
|
||||
rangeMap: RangeMap,
|
||||
scrollTop: number,
|
||||
viewportHeight: number
|
||||
): ViewportAnchor | null {
|
||||
const visibleRange = getVisibleRange(rangeMap, scrollTop, viewportHeight)
|
||||
if (visibleRange.end <= visibleRange.start) return null
|
||||
|
||||
if (scrollTop === rangeMap.positionAt(visibleRange.start)) {
|
||||
return {
|
||||
index: visibleRange.start,
|
||||
topDelta: 0,
|
||||
}
|
||||
}
|
||||
|
||||
if (visibleRange.end - visibleRange.start > 1) {
|
||||
const index = visibleRange.start + 1
|
||||
return {
|
||||
index,
|
||||
topDelta: rangeMap.positionAt(index) - scrollTop,
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function isSameRange(left: RenderRange, right: RenderRange): boolean {
|
||||
return left.start === right.start && left.end === right.end
|
||||
}
|
||||
|
||||
function VirtualRow(props: VirtualRowProps) {
|
||||
const { index, top, measure, children } = props
|
||||
const rowRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const node = rowRef.current
|
||||
if (!node) return
|
||||
|
||||
measure(index, node)
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
measure(index, node)
|
||||
})
|
||||
resizeObserver.observe(node)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
measure(index, null)
|
||||
}
|
||||
}, [index, measure])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rowRef}
|
||||
data-index={index}
|
||||
style={{
|
||||
left: 0,
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
transform: `translateY(${top}px)`,
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function VirtualList<TItem>(props: VirtualListProps<TItem>) {
|
||||
const {
|
||||
items,
|
||||
getKey,
|
||||
estimateSize,
|
||||
renderItem,
|
||||
overscan = 0,
|
||||
itemGap = 0,
|
||||
deferInitialRender = false,
|
||||
scrollbarSize,
|
||||
minThumbSize,
|
||||
scrollbarVisibility,
|
||||
scrollbarInsetTop,
|
||||
className,
|
||||
contentClassName,
|
||||
style,
|
||||
onRangeChange,
|
||||
onReady,
|
||||
} = props
|
||||
|
||||
const itemSnapshot = useMemo(
|
||||
() =>
|
||||
items.map((item, index) => {
|
||||
const key = getKey(item, index)
|
||||
const estimatedSize = estimateSize(item, index) + (index < items.length - 1 ? itemGap : 0)
|
||||
return { key, estimatedSize }
|
||||
}),
|
||||
[estimateSize, getKey, itemGap, items]
|
||||
)
|
||||
const rangeMapRef = useRef(
|
||||
new RangeMap(itemSnapshot.map((item) => item.estimatedSize))
|
||||
)
|
||||
const itemSignature = itemSnapshot
|
||||
.map((item) => `${item.key}:${item.estimatedSize}`)
|
||||
.join("\0")
|
||||
const itemSignatureRef = useRef(itemSignature)
|
||||
const shouldResetScrollRef = useRef(false)
|
||||
const scrollApiRef = useRef<ScrollAreaApi | null>(null)
|
||||
const scrollStateRef = useRef<ScrollAreaState | null>(null)
|
||||
const spacerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [contentInsets, setContentInsets] = useState<ContentInsets>({
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
})
|
||||
const renderRangeRef = useRef<RenderRange>({ start: 0, end: 0 })
|
||||
const [initialRenderReady, setInitialRenderReady] = useState(
|
||||
() => !deferInitialRender
|
||||
)
|
||||
const [scrollState, setScrollState] = useState<ScrollAreaState>({
|
||||
scrollTop: 0,
|
||||
viewportHeight: 0,
|
||||
scrollHeight: rangeMapRef.current.totalSize,
|
||||
isScrollable: false,
|
||||
isScrolling: false,
|
||||
})
|
||||
const [, forceUpdate] = useState(0)
|
||||
|
||||
const setContentRef = useCallback((node: HTMLDivElement | null) => {
|
||||
const styles = node ? getComputedStyle(node) : null
|
||||
const nextInsets = {
|
||||
top: styles ? Number.parseFloat(styles.paddingTop) || 0 : 0,
|
||||
bottom: styles ? Number.parseFloat(styles.paddingBottom) || 0 : 0,
|
||||
}
|
||||
setContentInsets((currentInsets) =>
|
||||
currentInsets.top === nextInsets.top && currentInsets.bottom === nextInsets.bottom
|
||||
? currentInsets
|
||||
: nextInsets
|
||||
)
|
||||
}, [])
|
||||
|
||||
const contentInsetTop = contentInsets.top
|
||||
|
||||
if (!scrollStateRef.current) {
|
||||
scrollStateRef.current = scrollState
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!deferInitialRender) {
|
||||
setInitialRenderReady(true)
|
||||
return
|
||||
}
|
||||
|
||||
let firstFrame = 0
|
||||
let secondFrame = 0
|
||||
firstFrame = requestAnimationFrame(() => {
|
||||
secondFrame = requestAnimationFrame(() => {
|
||||
setInitialRenderReady(true)
|
||||
})
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(firstFrame)
|
||||
cancelAnimationFrame(secondFrame)
|
||||
}
|
||||
}, [deferInitialRender])
|
||||
|
||||
if (itemSignatureRef.current !== itemSignature) {
|
||||
const estimatedSizes = itemSnapshot.map((item) => item.estimatedSize)
|
||||
rangeMapRef.current.reset(estimatedSizes)
|
||||
itemSignatureRef.current = itemSignature
|
||||
shouldResetScrollRef.current = true
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldResetScrollRef.current) return
|
||||
shouldResetScrollRef.current = false
|
||||
scrollApiRef.current?.scrollToTop()
|
||||
forceUpdate((current) => current + 1)
|
||||
}, [itemSignature])
|
||||
|
||||
const rangeMap = rangeMapRef.current
|
||||
const initialRenderCount = Math.max(1, overscan * 2 + 1)
|
||||
const canRenderItems =
|
||||
initialRenderReady &&
|
||||
(!deferInitialRender || scrollState.viewportHeight > 0)
|
||||
let renderRange: RenderRange
|
||||
if (!canRenderItems) {
|
||||
renderRange = { start: 0, end: 0 }
|
||||
} else if (scrollState.viewportHeight > 0) {
|
||||
renderRange = getRenderRange(
|
||||
rangeMap,
|
||||
Math.max(0, scrollState.scrollTop - contentInsetTop),
|
||||
scrollState.viewportHeight,
|
||||
overscan
|
||||
)
|
||||
} else {
|
||||
renderRange = {
|
||||
start: 0,
|
||||
end: Math.min(rangeMap.count, initialRenderCount),
|
||||
}
|
||||
}
|
||||
renderRangeRef.current = renderRange
|
||||
|
||||
useEffect(() => {
|
||||
if (renderRange.end > renderRange.start) {
|
||||
onRangeChange?.({ start: renderRange.start, end: renderRange.end - 1 })
|
||||
}
|
||||
}, [onRangeChange, renderRange.end, renderRange.start])
|
||||
|
||||
const measure = useCallback((index: number, node: HTMLElement | null) => {
|
||||
if (!node) return
|
||||
|
||||
const rangeMap = rangeMapRef.current
|
||||
const currentScrollState = scrollStateRef.current
|
||||
let anchor: ViewportAnchor | null = null
|
||||
if (currentScrollState) {
|
||||
anchor = getViewportAnchor(
|
||||
rangeMap,
|
||||
Math.max(0, currentScrollState.scrollTop - contentInsetTop),
|
||||
currentScrollState.viewportHeight
|
||||
)
|
||||
}
|
||||
|
||||
const measuredGap = index < items.length - 1 ? itemGap : 0
|
||||
const sizeDelta = rangeMap.updateSize(
|
||||
index,
|
||||
node.getBoundingClientRect().height + measuredGap
|
||||
)
|
||||
if (sizeDelta === 0) return
|
||||
|
||||
if (spacerRef.current) {
|
||||
spacerRef.current.style.height = `${rangeMap.totalSize}px`
|
||||
}
|
||||
|
||||
if (anchor && index < anchor.index) {
|
||||
scrollApiRef.current?.scrollTo(
|
||||
Math.max(0, contentInsetTop + rangeMap.positionAt(anchor.index) - anchor.topDelta)
|
||||
)
|
||||
}
|
||||
|
||||
forceUpdate((current) => current + 1)
|
||||
}, [contentInsetTop, itemGap, items.length])
|
||||
|
||||
const handleScroll = useCallback(
|
||||
(nextState: ScrollAreaState) => {
|
||||
const previousState = scrollStateRef.current
|
||||
scrollStateRef.current = nextState
|
||||
|
||||
const nextRange = getRenderRange(
|
||||
rangeMapRef.current,
|
||||
Math.max(0, nextState.scrollTop - contentInsetTop),
|
||||
nextState.viewportHeight,
|
||||
overscan
|
||||
)
|
||||
const dimensionsChanged =
|
||||
!previousState ||
|
||||
previousState.viewportHeight !== nextState.viewportHeight ||
|
||||
previousState.scrollHeight !== nextState.scrollHeight
|
||||
const scrollingChanged =
|
||||
!previousState || previousState.isScrolling !== nextState.isScrolling
|
||||
const rangeChanged = !isSameRange(nextRange, renderRangeRef.current)
|
||||
|
||||
if (
|
||||
dimensionsChanged ||
|
||||
scrollingChanged ||
|
||||
rangeChanged
|
||||
) {
|
||||
setScrollState(nextState)
|
||||
}
|
||||
},
|
||||
[contentInsetTop, overscan]
|
||||
)
|
||||
|
||||
const api = useMemo<VirtualListApi>(
|
||||
() => ({
|
||||
scrollToIndex(index, align = "auto") {
|
||||
const rangeMap = rangeMapRef.current
|
||||
const itemTop = contentInsetTop + rangeMap.positionAt(index)
|
||||
const itemHeight = rangeMap.sizeAt(index)
|
||||
const currentScrollState = scrollStateRef.current
|
||||
const viewportHeight = currentScrollState?.viewportHeight ?? 0
|
||||
const currentTop = currentScrollState?.scrollTop ?? 0
|
||||
const currentBottom = currentTop + viewportHeight
|
||||
|
||||
let nextTop = itemTop
|
||||
if (align === "center") {
|
||||
nextTop = itemTop - (viewportHeight - itemHeight) / 2
|
||||
} else if (align === "end") {
|
||||
nextTop = itemTop - viewportHeight + itemHeight
|
||||
} else if (align === "auto") {
|
||||
if (itemTop >= currentTop && itemTop + itemHeight <= currentBottom) {
|
||||
return
|
||||
}
|
||||
if (itemTop < currentTop) nextTop = itemTop
|
||||
else nextTop = itemTop - viewportHeight + itemHeight
|
||||
}
|
||||
|
||||
scrollApiRef.current?.scrollTo(nextTop)
|
||||
},
|
||||
scrollToOffset(offset) {
|
||||
scrollApiRef.current?.scrollTo(offset)
|
||||
},
|
||||
scrollToTop() {
|
||||
scrollApiRef.current?.scrollToTop()
|
||||
},
|
||||
}),
|
||||
[contentInsetTop]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
onReady?.(api)
|
||||
}, [api, onReady])
|
||||
|
||||
const visibleItems = []
|
||||
for (let index = renderRange.start; index < renderRange.end; index += 1) {
|
||||
visibleItems.push(index)
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
className={className}
|
||||
contentClassName={contentClassName}
|
||||
contentRef={setContentRef}
|
||||
style={style}
|
||||
contentHeight={contentInsetTop + rangeMap.totalSize + contentInsets.bottom}
|
||||
onReady={(scrollApi) => {
|
||||
scrollApiRef.current = scrollApi
|
||||
}}
|
||||
onScroll={handleScroll}
|
||||
scrollbarSize={scrollbarSize}
|
||||
minThumbSize={minThumbSize}
|
||||
scrollbarVisibility={scrollbarVisibility}
|
||||
scrollbarInsetTop={scrollbarInsetTop}
|
||||
>
|
||||
<div
|
||||
ref={spacerRef}
|
||||
style={{
|
||||
height: `${rangeMap.totalSize}px`,
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
{visibleItems.map((index) => {
|
||||
const item = items[index]
|
||||
const context: VirtualListRenderContext = {
|
||||
index,
|
||||
isScrolling: scrollState.isScrolling,
|
||||
measureElement: (node) => measure(index, node),
|
||||
}
|
||||
|
||||
return (
|
||||
<VirtualRow
|
||||
key={getKey(item, index)}
|
||||
index={index}
|
||||
top={rangeMap.positionAt(index)}
|
||||
measure={measure}
|
||||
>
|
||||
{renderItem(item, context)}
|
||||
</VirtualRow>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
|
||||
export type {
|
||||
VirtualListApi,
|
||||
VirtualListProps,
|
||||
VirtualListRenderContext,
|
||||
} from "./virtualTypes"
|
||||
@@ -0,0 +1,88 @@
|
||||
function clampIndex(index: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(index, min), max)
|
||||
}
|
||||
|
||||
export class RangeMap {
|
||||
private sizes: number[]
|
||||
private prefixSums: number[]
|
||||
|
||||
constructor(sizes: number[]) {
|
||||
this.sizes = sizes.map((size) => Math.max(1, size))
|
||||
this.prefixSums = []
|
||||
this.rebuildPrefixSums()
|
||||
}
|
||||
|
||||
get count(): number {
|
||||
return this.sizes.length
|
||||
}
|
||||
|
||||
get totalSize(): number {
|
||||
return this.prefixSums[this.prefixSums.length - 1] ?? 0
|
||||
}
|
||||
|
||||
reset(sizes: number[]): void {
|
||||
this.sizes = sizes.map((size) => Math.max(1, size))
|
||||
this.rebuildPrefixSums()
|
||||
}
|
||||
|
||||
updateSize(index: number, size: number): number {
|
||||
if (index < 0 || index >= this.sizes.length) return 0
|
||||
|
||||
const nextSize = Math.max(1, Math.ceil(size))
|
||||
const previousSize = this.sizes[index]
|
||||
if (previousSize === nextSize) return 0
|
||||
|
||||
this.sizes[index] = nextSize
|
||||
this.rebuildPrefixSums(index)
|
||||
return nextSize - previousSize
|
||||
}
|
||||
|
||||
sizeAt(index: number): number {
|
||||
return this.sizes[clampIndex(index, 0, this.sizes.length - 1)] ?? 0
|
||||
}
|
||||
|
||||
positionAt(index: number): number {
|
||||
if (index <= 0) return 0
|
||||
if (index >= this.sizes.length) return this.totalSize
|
||||
return this.prefixSums[index - 1] ?? 0
|
||||
}
|
||||
|
||||
indexAt(offset: number): number {
|
||||
if (this.sizes.length === 0) return 0
|
||||
if (offset <= 0) return 0
|
||||
if (offset >= this.totalSize) return this.sizes.length - 1
|
||||
|
||||
let low = 0
|
||||
let high = this.prefixSums.length - 1
|
||||
while (low < high) {
|
||||
const mid = Math.floor((low + high) / 2)
|
||||
if (this.prefixSums[mid] > offset) high = mid
|
||||
else low = mid + 1
|
||||
}
|
||||
|
||||
return low
|
||||
}
|
||||
|
||||
indexAfter(offset: number): number {
|
||||
if (this.sizes.length === 0) return 0
|
||||
if (offset < 0) return 0
|
||||
if (offset >= this.totalSize) return this.sizes.length
|
||||
|
||||
return Math.min(this.indexAt(offset) + 1, this.sizes.length)
|
||||
}
|
||||
|
||||
private rebuildPrefixSums(startIndex = 0): void {
|
||||
if (startIndex <= 0 || this.prefixSums.length !== this.sizes.length) {
|
||||
this.prefixSums = new Array(this.sizes.length)
|
||||
startIndex = 0
|
||||
}
|
||||
|
||||
let runningTotal = 0
|
||||
if (startIndex > 0) runningTotal = this.prefixSums[startIndex - 1] ?? 0
|
||||
|
||||
for (let index = startIndex; index < this.sizes.length; index += 1) {
|
||||
runningTotal += this.sizes[index]
|
||||
this.prefixSums[index] = runningTotal
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { CSSProperties, ReactNode } from "react"
|
||||
|
||||
export interface VirtualListApi {
|
||||
scrollToIndex(
|
||||
index: number,
|
||||
align?: "start" | "center" | "end" | "auto"
|
||||
): void
|
||||
scrollToOffset(offset: number): void
|
||||
scrollToTop(): void
|
||||
}
|
||||
|
||||
export interface VirtualListRenderContext {
|
||||
index: number
|
||||
measureElement: (node: HTMLElement | null) => void
|
||||
isScrolling: boolean
|
||||
}
|
||||
|
||||
export interface VirtualListProps<TItem> {
|
||||
items: TItem[]
|
||||
getKey: (item: TItem, index: number) => string
|
||||
estimateSize: (item: TItem, index: number) => number
|
||||
renderItem: (item: TItem, context: VirtualListRenderContext) => ReactNode
|
||||
|
||||
overscan?: number
|
||||
itemGap?: number
|
||||
deferInitialRender?: boolean
|
||||
scrollbarSize?: number
|
||||
minThumbSize?: number
|
||||
scrollbarVisibility?: "auto" | "always" | "hidden"
|
||||
scrollbarInsetTop?: CSSProperties["top"]
|
||||
className?: string
|
||||
contentClassName?: string
|
||||
style?: CSSProperties
|
||||
onRangeChange?: (range: { start: number; end: number }) => void
|
||||
onReady?: (api: VirtualListApi) => void
|
||||
}
|
||||
|
||||
export interface VirtualTreeNode {
|
||||
id: string
|
||||
parentId?: string
|
||||
depth: number
|
||||
collapsible?: boolean
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export interface VirtualTreeRenderContext {
|
||||
index: number
|
||||
depth: number
|
||||
expanded: boolean
|
||||
selected: boolean
|
||||
toggleExpanded(): void
|
||||
measureElement: (node: HTMLElement | null) => void
|
||||
}
|
||||
|
||||
export interface VirtualTreeProps<TNode extends VirtualTreeNode> {
|
||||
nodes: TNode[]
|
||||
getKey?: (node: TNode) => string
|
||||
estimateSize: (node: TNode, index: number) => number
|
||||
renderNode: (node: TNode, context: VirtualTreeRenderContext) => ReactNode
|
||||
|
||||
expandedIds?: Set<string>
|
||||
defaultExpandedIds?: Set<string>
|
||||
onExpandedChange?: (expandedIds: Set<string>) => void
|
||||
|
||||
selectedId?: string
|
||||
onSelect?: (node: TNode) => void
|
||||
|
||||
overscan?: number
|
||||
scrollbarSize?: number
|
||||
minThumbSize?: number
|
||||
scrollbarVisibility?: "auto" | "always" | "hidden"
|
||||
className?: string
|
||||
style?: CSSProperties
|
||||
}
|
||||
|
||||
export interface VirtualComboboxOption {
|
||||
key: string
|
||||
label: string
|
||||
description?: string
|
||||
searchText?: string
|
||||
}
|
||||
|
||||
export interface VirtualComboboxProps {
|
||||
options: VirtualComboboxOption[]
|
||||
value: string
|
||||
placeholder: string
|
||||
emptyText: string
|
||||
ariaLabel?: string
|
||||
onChange: (key: string) => void
|
||||
className?: string
|
||||
estimateSize?: number
|
||||
maxPopupHeight?: number
|
||||
scrollbarSize?: number
|
||||
minThumbSize?: number
|
||||
scrollbarVisibility?: "auto" | "always" | "hidden"
|
||||
}
|
||||
Reference in new issue
Block a user