fix(virtualization): measure natural rows and align viewport geometry
This commit is contained in:
@@ -1,132 +1,145 @@
|
||||
/**
|
||||
* Row geometry for table-shaped virtual windows. Pure measurement helpers —
|
||||
* no state kernel: selection, identity and focus stay with the existing
|
||||
* collection/table models. Heights are px; a row height function returning
|
||||
* `undefined` falls back to `estimatedRowHeight`, and every input is read on
|
||||
* each layout pass (prefix sums, binary search) so reactive values update the
|
||||
* window without a remount.
|
||||
*
|
||||
* Geometry semantics match the pinned ListLayout/TableLayout contracts: `gap`
|
||||
* is the spacing between rows (body rows and the trailing loader row), while
|
||||
* `padding` is list padding rendered as spacer rows at both ends and carries
|
||||
* no gap. The loader area is a reservation at the end of the row stream (after
|
||||
* the last row's gap and before the trailing padding): it is included in
|
||||
* `totalHeight` and in `window.padBottom`, so a caller rendering a physical
|
||||
* loader row should place it inside that reserved span.
|
||||
*/
|
||||
/** Shared virtual geometry; collection selection and logical identity stay with their owners. */
|
||||
import {
|
||||
computed,
|
||||
shallowRef,
|
||||
toValue,
|
||||
nextTick,
|
||||
getCurrentScope,
|
||||
onScopeDispose,
|
||||
type ComputedRef,
|
||||
type MaybeRefOrGetter,
|
||||
} from "vue";
|
||||
import type { CollectionKey } from "./keys";
|
||||
|
||||
export type VirtualRowHeight = number | ((index: number) => number | undefined);
|
||||
|
||||
export interface UseVirtualRowsOptions {
|
||||
/** Number of virtualized body rows. */
|
||||
count: MaybeRefOrGetter<number>;
|
||||
/** Row height in px; a function maps the row index to a variable height. */
|
||||
/** Stable typed identities for measured rows. Defaults to the row index. */
|
||||
keys?: MaybeRefOrGetter<readonly CollectionKey[]>;
|
||||
/** Undefined heights are estimated until measureRow observes the real row. */
|
||||
rowHeight: VirtualRowHeight;
|
||||
/** Fallback height in px for rows whose height function returns undefined. */
|
||||
estimatedRowHeight?: number;
|
||||
/** Loader row reservation in px at the end of the row stream. */
|
||||
estimatedRowHeight?: number | ((index: number) => number);
|
||||
loaderHeight?: number;
|
||||
/** Gap in px between rows (body rows and the trailing loader reservation). */
|
||||
gap?: number;
|
||||
/** List padding in px as spacer rows at both ends. */
|
||||
padding?: number;
|
||||
/** Extra rows rendered beyond the viewport. */
|
||||
overscan?: number;
|
||||
}
|
||||
|
||||
export interface VirtualRowWindow {
|
||||
/** First rendered body row index. */
|
||||
start: number;
|
||||
/** Body row index after the last rendered row. */
|
||||
end: number;
|
||||
/** Spacer height in px before the first rendered row (incl. padding). */
|
||||
padTop: number;
|
||||
/**
|
||||
* Spacer height in px after the last rendered row: the unrendered rows, the
|
||||
* loader reservation and the trailing padding.
|
||||
*/
|
||||
padBottom: number;
|
||||
}
|
||||
|
||||
export interface VirtualRowsBindingOptions {
|
||||
/** Element at the row stream origin (e.g. tbody below the table header). */
|
||||
content?: HTMLElement;
|
||||
/** Visible sticky chrome occluding the start of the viewport, in px. */
|
||||
scrollPaddingStart?: number | (() => number);
|
||||
}
|
||||
export interface UseVirtualRows {
|
||||
window: ComputedRef<VirtualRowWindow>;
|
||||
/** Top offset in px of a body row within the row stream. */
|
||||
rowOffsetOf: (index: number) => number;
|
||||
/** Rendered extent in px of a body row (its height plus the gap after it). */
|
||||
rowExtentOf: (index: number) => number;
|
||||
/** Total row-stream height in px (padding, rows, gaps, loader reservation). */
|
||||
totalHeight: ComputedRef<number>;
|
||||
/** Recompute the window from a scroll position. */
|
||||
update: (scrollTop: number, viewportHeight: number) => void;
|
||||
/** Scroll a row into a viewport element, clamped to the row stream. */
|
||||
scrollToIndex: (element: HTMLElement, index: number) => void;
|
||||
/** Ref callback for naturally sized rows (accepts a DOM node or Vue component ref). */
|
||||
measureRow: (index: number, element: unknown) => void;
|
||||
/** Invalidate offscreen cached content sizes after caller-owned data changes. */
|
||||
resetMeasurements: () => void;
|
||||
}
|
||||
const positive = (value: number | undefined, fallback: number) =>
|
||||
value != null && Number.isFinite(value) && value > 0 ? value : fallback;
|
||||
const nonnegative = (value: number | undefined) =>
|
||||
value != null && Number.isFinite(value) ? Math.max(0, value) : 0;
|
||||
const binders = new WeakMap<
|
||||
UseVirtualRows,
|
||||
(element: HTMLElement, options: VirtualRowsBindingOptions) => () => void
|
||||
>();
|
||||
|
||||
export function useVirtualRows(options: UseVirtualRowsOptions): UseVirtualRows {
|
||||
const overscan = options.overscan ?? 8;
|
||||
const state = shallowRef({ scrollTop: 0, viewport: 0 });
|
||||
/** Prefix sums: offsets[i] = row stream top of body row i (incl. padding). */
|
||||
const sizes = shallowRef(new Map<CollectionKey, number>());
|
||||
const nodes = new Map<HTMLElement, CollectionKey>();
|
||||
const rowKeys = computed(() =>
|
||||
options.keys ? toValue(options.keys) : undefined,
|
||||
);
|
||||
const keyAt = (index: number) => rowKeys.value?.[index] ?? index;
|
||||
const rawHeight = (index: number) =>
|
||||
typeof options.rowHeight === "function"
|
||||
? options.rowHeight(index)
|
||||
: options.rowHeight;
|
||||
const estimate = (index: number) =>
|
||||
positive(
|
||||
typeof options.estimatedRowHeight === "function"
|
||||
? options.estimatedRowHeight(index)
|
||||
: options.estimatedRowHeight,
|
||||
48,
|
||||
);
|
||||
const geometry = computed(() => {
|
||||
const count = Math.max(0, toValue(options.count) ?? 0);
|
||||
const gap = (options.gap ?? 0) > 0 ? (options.gap ?? 0) : 0;
|
||||
const pad = (options.padding ?? 0) > 0 ? (options.padding ?? 0) : 0;
|
||||
const loader = (options.loaderHeight ?? 0) > 0 ? (options.loaderHeight ?? 0) : 0;
|
||||
// Rows and the loader reservation are content rows: gaps sit between
|
||||
// them, never between padding and content.
|
||||
const loaderSpan = loader > 0 ? (count > 0 ? gap : 0) + loader : 0;
|
||||
const rawCount = toValue(options.count);
|
||||
const count = Number.isFinite(rawCount)
|
||||
? Math.max(0, Math.floor(rawCount))
|
||||
: 0;
|
||||
const gap = nonnegative(options.gap),
|
||||
pad = nonnegative(options.padding),
|
||||
loader = nonnegative(options.loaderHeight);
|
||||
const offsets = new Float64Array(count + 1);
|
||||
let top = pad;
|
||||
for (let i = 0; i < count; i++) {
|
||||
offsets[i] = top;
|
||||
const raw =
|
||||
typeof options.rowHeight === "function"
|
||||
? options.rowHeight(i)
|
||||
: options.rowHeight;
|
||||
top += raw ?? options.estimatedRowHeight ?? 50;
|
||||
const raw = rawHeight(i);
|
||||
top += positive(raw ?? sizes.value.get(keyAt(i)), estimate(i));
|
||||
if (i < count - 1) top += gap;
|
||||
}
|
||||
offsets[count] = top;
|
||||
return { count, pad, loaderSpan, offsets };
|
||||
return {
|
||||
count,
|
||||
offsets,
|
||||
pad,
|
||||
loaderSpan: loader > 0 ? loader + (count ? gap : 0) : 0,
|
||||
};
|
||||
});
|
||||
const rowOffsetOf = (index: number) =>
|
||||
geometry.value.offsets[Math.min(Math.max(index, 0), geometry.value.count)];
|
||||
geometry.value.offsets[
|
||||
Math.min(geometry.value.count, Math.max(0, Math.floor(index) || 0))
|
||||
]!;
|
||||
const rowExtentOf = (index: number) =>
|
||||
rowOffsetOf(index + 1) - rowOffsetOf(index);
|
||||
const totalHeight = computed(
|
||||
() =>
|
||||
geometry.value.offsets[geometry.value.count]! +
|
||||
rowOffsetOf(geometry.value.count) +
|
||||
geometry.value.loaderSpan +
|
||||
geometry.value.pad,
|
||||
);
|
||||
const window = computed<VirtualRowWindow>(() => {
|
||||
function firstAt(top: number) {
|
||||
const { count, offsets } = geometry.value;
|
||||
const { scrollTop, viewport } = state.value;
|
||||
// First row whose extent reaches the viewport top.
|
||||
let low = 0;
|
||||
let high = count;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (offsets[mid + 1]! <= scrollTop) low = mid + 1;
|
||||
else high = mid;
|
||||
let lo = 0,
|
||||
hi = count;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (offsets[mid + 1]! <= top) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
const start = Math.max(0, low - overscan);
|
||||
// First row starting beyond the viewport bottom.
|
||||
let endLow = start;
|
||||
let endHigh = count;
|
||||
const limit = scrollTop + viewport;
|
||||
while (endLow < endHigh) {
|
||||
const mid = (endLow + endHigh) >> 1;
|
||||
if (offsets[mid]! < limit) endLow = mid + 1;
|
||||
else endHigh = mid;
|
||||
return lo;
|
||||
}
|
||||
const window = computed(() => {
|
||||
const { count, offsets } = geometry.value;
|
||||
const overscan = Math.floor(nonnegative(options.overscan ?? 8));
|
||||
const start = Math.max(0, firstAt(state.value.scrollTop) - overscan);
|
||||
let lo = start,
|
||||
hi = count;
|
||||
const limit = state.value.scrollTop + state.value.viewport;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (offsets[mid]! < limit) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
const end = Math.min(count, endLow + overscan);
|
||||
// Keep an initial window while a hidden/unmeasured container mounts.
|
||||
const end = Math.min(
|
||||
count,
|
||||
Math.max(lo + overscan, start + (count ? 1 : 0)),
|
||||
);
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
@@ -135,35 +148,250 @@ export function useVirtualRows(options: UseVirtualRowsOptions): UseVirtualRows {
|
||||
};
|
||||
});
|
||||
function update(scrollTop: number, viewportHeight: number) {
|
||||
state.value = { scrollTop, viewport: viewportHeight };
|
||||
const top = nonnegative(scrollTop),
|
||||
viewport = nonnegative(viewportHeight);
|
||||
if (state.value.scrollTop !== top || state.value.viewport !== viewport)
|
||||
state.value = { scrollTop: top, viewport };
|
||||
}
|
||||
function scrollToIndex(element: HTMLElement, index: number) {
|
||||
const top = rowOffsetOf(index);
|
||||
const extent = rowExtentOf(index);
|
||||
if (top < element.scrollTop) element.scrollTop = top;
|
||||
let binding:
|
||||
| {
|
||||
element: HTMLElement;
|
||||
options: VirtualRowsBindingOptions;
|
||||
origin: () => number;
|
||||
inset: () => number;
|
||||
measure: () => void;
|
||||
}
|
||||
| undefined;
|
||||
let pendingTarget:
|
||||
| { element: HTMLElement; key: CollectionKey; scrollTop?: number }
|
||||
| undefined;
|
||||
function withAnchor(change: () => void) {
|
||||
const index = firstAt(state.value.scrollTop);
|
||||
const anchorKey = keyAt(index),
|
||||
before = rowOffsetOf(index);
|
||||
change();
|
||||
if (binding && index < geometry.value.count) {
|
||||
const keys = rowKeys.value;
|
||||
const nextIndex = keys ? keys.indexOf(anchorKey) : index;
|
||||
if (nextIndex >= 0) {
|
||||
const delta = rowOffsetOf(nextIndex) - before;
|
||||
if (delta) {
|
||||
binding.element.scrollTop += delta;
|
||||
if (pendingTarget?.element === binding.element)
|
||||
pendingTarget.scrollTop = binding.element.scrollTop;
|
||||
}
|
||||
}
|
||||
binding.measure();
|
||||
}
|
||||
}
|
||||
function resetMeasurements() {
|
||||
if (sizes.value.size)
|
||||
withAnchor(() => {
|
||||
sizes.value = new Map();
|
||||
});
|
||||
}
|
||||
function measureNodes() {
|
||||
const next = new Map(sizes.value);
|
||||
let changed = false;
|
||||
for (const [node, key] of nodes) {
|
||||
if (!node.isConnected) {
|
||||
observer?.unobserve(node);
|
||||
nodes.delete(node);
|
||||
continue;
|
||||
}
|
||||
const h = node.getBoundingClientRect().height;
|
||||
if (
|
||||
Number.isFinite(h) &&
|
||||
h > 0 &&
|
||||
Math.abs((next.get(key) ?? 0) - h) > 0.25
|
||||
) {
|
||||
next.set(key, h);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed)
|
||||
withAnchor(() => {
|
||||
sizes.value = next;
|
||||
});
|
||||
if (pendingTarget && next.has(pendingTarget.key)) {
|
||||
const target = pendingTarget;
|
||||
pendingTarget = undefined;
|
||||
const keys = rowKeys.value;
|
||||
const index = keys ? keys.indexOf(target.key) : Number(target.key);
|
||||
if (index >= 0) scrollToIndex(target.element, index);
|
||||
}
|
||||
}
|
||||
const observer =
|
||||
typeof ResizeObserver === "undefined"
|
||||
? undefined
|
||||
: new ResizeObserver(measureNodes);
|
||||
let queued = false;
|
||||
function queueMeasurement() {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
void nextTick(() => {
|
||||
queued = false;
|
||||
measureNodes();
|
||||
});
|
||||
}
|
||||
function measureRow(index: number, value: unknown) {
|
||||
const element =
|
||||
value instanceof HTMLElement
|
||||
? value
|
||||
: (value as { $el?: unknown } | null)?.$el;
|
||||
if (!(element instanceof HTMLElement) || rawHeight(index) !== undefined) {
|
||||
queueMeasurement();
|
||||
return;
|
||||
}
|
||||
const key = keyAt(index);
|
||||
if (nodes.get(element) !== key) {
|
||||
nodes.set(element, key);
|
||||
observer?.observe(element);
|
||||
}
|
||||
queueMeasurement();
|
||||
}
|
||||
function scrollToIndex(element: HTMLElement, requested: number) {
|
||||
if (!geometry.value.count) return;
|
||||
const index = Math.max(
|
||||
0,
|
||||
Math.min(geometry.value.count - 1, Math.floor(requested) || 0),
|
||||
);
|
||||
const b = binding?.element === element ? binding : undefined;
|
||||
if (rawHeight(index) === undefined && !sizes.value.has(keyAt(index)))
|
||||
pendingTarget = { element, key: keyAt(index) };
|
||||
const origin = b?.origin() ?? 0,
|
||||
inset = b?.inset() ?? 0;
|
||||
const top = origin + rowOffsetOf(index),
|
||||
extent = rowExtentOf(index);
|
||||
if (
|
||||
top < element.scrollTop + inset ||
|
||||
extent > element.clientHeight - inset
|
||||
)
|
||||
element.scrollTop = Math.max(0, top - inset);
|
||||
else if (top + extent > element.scrollTop + element.clientHeight)
|
||||
element.scrollTop = top + extent - element.clientHeight;
|
||||
update(element.scrollTop, element.clientHeight);
|
||||
if (pendingTarget?.element === element)
|
||||
pendingTarget.scrollTop = element.scrollTop;
|
||||
if (b) b.measure();
|
||||
else update(element.scrollTop, element.clientHeight);
|
||||
}
|
||||
return { window, rowOffsetOf, rowExtentOf, totalHeight, update, scrollToIndex };
|
||||
const rows: UseVirtualRows = {
|
||||
window,
|
||||
rowOffsetOf,
|
||||
rowExtentOf,
|
||||
totalHeight,
|
||||
update,
|
||||
scrollToIndex,
|
||||
measureRow,
|
||||
resetMeasurements,
|
||||
};
|
||||
let disposeBinding: (() => void) | undefined;
|
||||
binders.set(rows, (element, config) => {
|
||||
disposeBinding?.();
|
||||
config = {
|
||||
...config,
|
||||
content:
|
||||
config.content ??
|
||||
element.querySelector<HTMLElement>(
|
||||
'[data-slot="table-content"] > tbody',
|
||||
) ??
|
||||
undefined,
|
||||
};
|
||||
const origin = () =>
|
||||
config.content
|
||||
? config.content.getBoundingClientRect().top -
|
||||
element.getBoundingClientRect().top -
|
||||
element.clientTop +
|
||||
element.scrollTop
|
||||
: 0;
|
||||
const inset = () =>
|
||||
nonnegative(
|
||||
typeof config.scrollPaddingStart === "function"
|
||||
? config.scrollPaddingStart()
|
||||
: config.scrollPaddingStart,
|
||||
);
|
||||
let width = element.clientWidth;
|
||||
const measure = () => {
|
||||
if (element.clientWidth !== width) {
|
||||
width = element.clientWidth;
|
||||
// Retain connected rows until their own ResizeObserver reports the
|
||||
// new natural size. Resetting them to estimates can toggle scrollbars
|
||||
// repeatedly when the whole collection is near the viewport height.
|
||||
const visible = new Set(
|
||||
[...nodes].filter(([node]) => node.isConnected).map(([, key]) => key),
|
||||
);
|
||||
withAnchor(() => {
|
||||
sizes.value = new Map(
|
||||
[...sizes.value].filter(([key]) => visible.has(key)),
|
||||
);
|
||||
});
|
||||
}
|
||||
update(
|
||||
Math.max(0, element.scrollTop + inset() - origin()),
|
||||
Math.max(0, element.clientHeight - inset()),
|
||||
);
|
||||
};
|
||||
binding = { element, options: config, origin, inset, measure };
|
||||
const previousAnchor = element.style.overflowAnchor;
|
||||
element.style.overflowAnchor = "none";
|
||||
const resize =
|
||||
typeof ResizeObserver === "undefined"
|
||||
? undefined
|
||||
: new ResizeObserver(measure);
|
||||
resize?.observe(element);
|
||||
if (config.content) {
|
||||
for (
|
||||
let node: HTMLElement | null = config.content;
|
||||
node && node !== element;
|
||||
node = node.parentElement
|
||||
) {
|
||||
resize?.observe(node);
|
||||
// Header/sticky chrome may move the stream without resizing it.
|
||||
for (
|
||||
let previous = node.previousElementSibling;
|
||||
previous;
|
||||
previous = previous.previousElementSibling
|
||||
)
|
||||
resize?.observe(previous);
|
||||
}
|
||||
}
|
||||
const onScroll = () => {
|
||||
if (
|
||||
pendingTarget?.element === element &&
|
||||
pendingTarget.scrollTop != null &&
|
||||
Math.abs(pendingTarget.scrollTop - element.scrollTop) > 1
|
||||
)
|
||||
pendingTarget = undefined;
|
||||
measure();
|
||||
};
|
||||
element.addEventListener("scroll", onScroll, { passive: true });
|
||||
let live = true;
|
||||
const dispose = () => {
|
||||
if (!live) return;
|
||||
live = false;
|
||||
resize?.disconnect();
|
||||
element.removeEventListener("scroll", onScroll);
|
||||
element.style.overflowAnchor = previousAnchor;
|
||||
if (binding?.element === element) binding = undefined;
|
||||
};
|
||||
disposeBinding = dispose;
|
||||
measure();
|
||||
return dispose;
|
||||
});
|
||||
if (getCurrentScope())
|
||||
onScopeDispose(() => {
|
||||
observer?.disconnect();
|
||||
nodes.clear();
|
||||
disposeBinding?.();
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach the window updater to a scroll container: recomputes on scroll and on
|
||||
* container resize. Returns a cleanup callable.
|
||||
*/
|
||||
/** Bind a real scroll viewport and the row stream's actual origin. */
|
||||
export function bindVirtualRows(
|
||||
rows: UseVirtualRows,
|
||||
element: HTMLElement,
|
||||
options: VirtualRowsBindingOptions = {},
|
||||
): () => void {
|
||||
const measure = () => rows.update(element.scrollTop, element.clientHeight);
|
||||
const observer =
|
||||
typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
|
||||
observer?.observe(element);
|
||||
element.addEventListener("scroll", measure, { passive: true });
|
||||
measure();
|
||||
return () => {
|
||||
element.removeEventListener("scroll", measure);
|
||||
observer?.disconnect();
|
||||
};
|
||||
return binders.get(rows)!(element, options);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
onBeforeUpdate,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
@@ -16,7 +17,7 @@ import {
|
||||
watch,
|
||||
watchEffect,
|
||||
} from "vue";
|
||||
import { useVirtualList } from "@vueuse/core";
|
||||
import { bindVirtualRows, useVirtualRows } from "../collection/virtual-rows";
|
||||
import { listboxVariants } from "@heroui-vue/styles";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import Header from "../header/HeaderRoot.vue";
|
||||
@@ -251,107 +252,166 @@ const source = computed(() => visibleItems.value);
|
||||
* `padding` renders as spacer rows at both ends.
|
||||
*/
|
||||
type VirtualRow =
|
||||
| { key: string; kind: "pad"; height: number }
|
||||
| { key: string; kind: "heading"; height: number; text: string }
|
||||
| { key: string; kind: "item"; height: number; item: T; index: number }
|
||||
| { key: string; kind: "loader"; height: number };
|
||||
| { key: string; kind: "pad"; height: number; gap: number }
|
||||
| {
|
||||
key: string;
|
||||
kind: "heading";
|
||||
height: number | undefined;
|
||||
gap: number;
|
||||
text: string;
|
||||
estimate: number;
|
||||
}
|
||||
| {
|
||||
key: string;
|
||||
kind: "item";
|
||||
height: number | undefined;
|
||||
gap: number;
|
||||
item: T;
|
||||
index: number;
|
||||
estimate: number;
|
||||
}
|
||||
| { key: string; kind: "loader"; height: number; gap: number };
|
||||
const fallbackRowHeight = computed(
|
||||
() =>
|
||||
props.estimatedRowHeight ??
|
||||
(typeof props.rowHeight === "number" ? props.rowHeight : 50),
|
||||
);
|
||||
const virtualRows = computed<VirtualRow[]>(() => {
|
||||
const items = source.value as T[];
|
||||
const gap = props.gap > 0 ? props.gap : 0;
|
||||
const rows: VirtualRow[] = [];
|
||||
const push = (row: VirtualRow) => {
|
||||
// Gap sits between content rows only (pinned ListLayout semantics).
|
||||
const prev = rows[rows.length - 1];
|
||||
if (row.kind !== "pad" && prev && prev.kind !== "pad") prev.height += gap;
|
||||
const prev = rows.at(-1);
|
||||
if (row.kind !== "pad" && prev && prev.kind !== "pad")
|
||||
prev.gap = Math.max(0, props.gap);
|
||||
rows.push(row);
|
||||
};
|
||||
if (props.padding > 0)
|
||||
push({ key: "pad-top", kind: "pad", height: props.padding });
|
||||
items.forEach((item, index) => {
|
||||
push({ key: "pad-top", kind: "pad", height: props.padding, gap: 0 });
|
||||
source.value.forEach((item, index) => {
|
||||
if (item.heading)
|
||||
push({
|
||||
key: `heading-${index}`,
|
||||
key: `heading-${encodeKey(item.id)}`,
|
||||
kind: "heading",
|
||||
height: props.headingHeight,
|
||||
height:
|
||||
typeof props.headingHeight === "function"
|
||||
? props.headingHeight(index)
|
||||
: props.headingHeight,
|
||||
estimate: props.estimatedHeadingHeight ?? 48,
|
||||
text: item.heading,
|
||||
gap: 0,
|
||||
});
|
||||
const height =
|
||||
(typeof props.rowHeight === "function"
|
||||
? props.rowHeight(index)
|
||||
: props.rowHeight) ?? fallbackRowHeight.value;
|
||||
push({ key: `item-${encodeKey(item.id)}`, kind: "item", height, item, index });
|
||||
push({
|
||||
key: `item-${encodeKey(item.id)}`,
|
||||
kind: "item",
|
||||
height:
|
||||
typeof props.rowHeight === "function"
|
||||
? props.rowHeight(index)
|
||||
: props.rowHeight,
|
||||
estimate: fallbackRowHeight.value,
|
||||
item,
|
||||
index,
|
||||
gap: 0,
|
||||
});
|
||||
});
|
||||
if (slots.loader)
|
||||
push({ key: "loader", kind: "loader", height: props.loaderHeight });
|
||||
if (slots.loader && props.loaderHeight > 0)
|
||||
push({ key: "loader", kind: "loader", height: props.loaderHeight, gap: 0 });
|
||||
if (props.padding > 0)
|
||||
push({ key: "pad-bottom", kind: "pad", height: props.padding });
|
||||
push({ key: "pad-bottom", kind: "pad", height: props.padding, gap: 0 });
|
||||
return rows;
|
||||
});
|
||||
/** Row stream index for a logical item index (headings/pads shift the row). */
|
||||
const virtualLayout = useVirtualRows({
|
||||
count: () => virtualRows.value.length,
|
||||
keys: () => virtualRows.value.map((row) => row.key),
|
||||
rowHeight: (index) => {
|
||||
const row = virtualRows.value[index];
|
||||
return row?.height === undefined ? undefined : row.height + row.gap;
|
||||
},
|
||||
estimatedRowHeight: (index) => {
|
||||
const row = virtualRows.value[index];
|
||||
return (
|
||||
(row && "estimate" in row ? row.estimate : fallbackRowHeight.value) +
|
||||
(row?.gap ?? 0)
|
||||
);
|
||||
},
|
||||
get overscan() {
|
||||
return props.overscan;
|
||||
},
|
||||
});
|
||||
const windowItems = computed(() => {
|
||||
const { start, end } = virtualLayout.window.value;
|
||||
return virtualRows.value
|
||||
.slice(start, end)
|
||||
.map((data, index) => ({ data, index: start + index }));
|
||||
});
|
||||
const wrapperProps = computed(() => ({
|
||||
style: {
|
||||
height: `${virtualLayout.totalHeight.value}px`,
|
||||
paddingTop: `${virtualLayout.window.value.padTop}px`,
|
||||
boxSizing: "border-box" as const,
|
||||
overflowAnchor: "none" as const,
|
||||
},
|
||||
}));
|
||||
function rowIndexOfItem(index: number): number {
|
||||
return virtualRows.value.findIndex(
|
||||
(row) => row.kind === "item" && row.index === index,
|
||||
);
|
||||
}
|
||||
// VueUse owns measurement, scroll range and cleanup; one logical collection
|
||||
// remains available for select-all/typeahead even while most rows are unmounted.
|
||||
const {
|
||||
list: windowItems,
|
||||
containerProps,
|
||||
wrapperProps,
|
||||
scrollTo,
|
||||
} = useVirtualList(virtualRows, {
|
||||
itemHeight: (rowIndex: number) =>
|
||||
virtualRows.value[rowIndex]?.height ?? fallbackRowHeight.value,
|
||||
overscan: props.overscan,
|
||||
});
|
||||
const root = shallowRef<HTMLElement | null>(null);
|
||||
/**
|
||||
* The scroll container drives the virtual window: the list root when it
|
||||
* scrolls itself (fixed rows inside a sized box) and the nearest scrolling
|
||||
* ancestor otherwise (popover-wide scrolling with sticky chrome, like the
|
||||
* pinned autocomplete example).
|
||||
*/
|
||||
function resolveScrollParent(): HTMLElement | null {
|
||||
const virtualContent = shallowRef<HTMLElement | null>(null);
|
||||
function resolveScrollParent() {
|
||||
const el = root.value;
|
||||
if (!el) return null;
|
||||
const scrolls = (node: HTMLElement) => {
|
||||
const overflowY = getComputedStyle(node).overflowY;
|
||||
return (
|
||||
(overflowY === "auto" || overflowY === "scroll") &&
|
||||
node.scrollHeight > node.clientHeight + 1
|
||||
);
|
||||
};
|
||||
if (scrolls(el)) return el;
|
||||
for (let node = el.parentElement; node; node = node.parentElement)
|
||||
if (scrolls(node)) return node;
|
||||
// Overflow policy matters even before an asynchronous collection overflows.
|
||||
for (let node: HTMLElement | null = el; node; node = node.parentElement)
|
||||
if (/^(auto|scroll)$/.test(getComputedStyle(node).overflowY)) return node;
|
||||
return el;
|
||||
}
|
||||
let scrollParent: HTMLElement | null = null;
|
||||
function onVirtualScroll() {
|
||||
containerProps.onScroll();
|
||||
let boundContent: HTMLElement | null = null;
|
||||
let detachVirtual: (() => void) | undefined;
|
||||
function stickyInset() {
|
||||
if (!scrollParent || scrollParent === root.value) return 0;
|
||||
let inset = 0;
|
||||
// Measure preceding sticky chrome, including caller-owned search wrappers.
|
||||
for (
|
||||
let node = root.value;
|
||||
node && node !== scrollParent;
|
||||
node = node.parentElement
|
||||
) {
|
||||
for (
|
||||
let previous = node.previousElementSibling;
|
||||
previous;
|
||||
previous = previous.previousElementSibling
|
||||
) {
|
||||
const style = getComputedStyle(previous);
|
||||
if (style.position === "sticky" && style.top !== "auto")
|
||||
inset = Math.max(
|
||||
inset,
|
||||
(parseFloat(style.top) || 0) +
|
||||
previous.getBoundingClientRect().height,
|
||||
);
|
||||
}
|
||||
}
|
||||
return inset;
|
||||
}
|
||||
watch(
|
||||
root,
|
||||
(el) => {
|
||||
scrollParent?.removeEventListener("scroll", onVirtualScroll);
|
||||
scrollParent = null;
|
||||
if (!el || !props.virtualized) return;
|
||||
const parent = resolveScrollParent();
|
||||
if (!parent) return;
|
||||
scrollParent = parent;
|
||||
containerProps.ref.value = parent;
|
||||
parent.addEventListener("scroll", onVirtualScroll, { passive: true });
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
function refreshVirtualBinding() {
|
||||
const parent = props.virtualized ? resolveScrollParent() : null;
|
||||
if (parent === scrollParent && virtualContent.value === boundContent) return;
|
||||
detachVirtual?.();
|
||||
detachVirtual = undefined;
|
||||
scrollParent = parent;
|
||||
boundContent = virtualContent.value;
|
||||
if (parent && boundContent)
|
||||
detachVirtual = bindVirtualRows(virtualLayout, parent, {
|
||||
content: boundContent,
|
||||
scrollPaddingStart: stickyInset,
|
||||
});
|
||||
}
|
||||
watch([root, virtualContent, () => props.virtualized], refreshVirtualBinding, {
|
||||
flush: "post",
|
||||
});
|
||||
onUpdated(refreshVirtualBinding);
|
||||
onBeforeUnmount(() => {
|
||||
scrollParent?.removeEventListener("scroll", onVirtualScroll);
|
||||
detachVirtual?.();
|
||||
scrollParent = null;
|
||||
});
|
||||
let restoringFocus = false;
|
||||
@@ -391,12 +451,6 @@ async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
|
||||
await nextFrame();
|
||||
}
|
||||
}
|
||||
/** Row stream top offset in px (sum of the heights before the row). */
|
||||
function rowOffsetOf(rowIndex: number): number {
|
||||
let top = 0;
|
||||
for (let i = 0; i < rowIndex; i++) top += virtualRows.value[i]!.height;
|
||||
return top;
|
||||
}
|
||||
/**
|
||||
* Bring a row into view without taking DOM focus. Virtualized lists move the
|
||||
* window by row offset (item rows may sit behind heading/padding rows); the
|
||||
@@ -413,17 +467,8 @@ async function revealRow(key: ListBoxKey, valid: () => boolean) {
|
||||
if (index < 0 || !valid()) return;
|
||||
const rowIndex = rowIndexOfItem(index);
|
||||
if (rowIndex < 0) return;
|
||||
const row = virtualRows.value[rowIndex]!;
|
||||
const rowTop = rowOffsetOf(rowIndex);
|
||||
const element = scrollParent ?? root.value;
|
||||
if (
|
||||
element &&
|
||||
(rowTop < element.scrollTop ||
|
||||
rowTop + row.height > element.scrollTop + element.clientHeight)
|
||||
) {
|
||||
if (!valid()) return;
|
||||
scrollTo(rowIndex);
|
||||
}
|
||||
if (element && valid()) virtualLayout.scrollToIndex(element, rowIndex);
|
||||
await waitForMountedRow(key, valid);
|
||||
return;
|
||||
}
|
||||
@@ -584,11 +629,29 @@ function keydown(event: KeyboardEvent) {
|
||||
const height = props.virtualized
|
||||
? activeHeight
|
||||
: current?.getBoundingClientRect().height || activeHeight;
|
||||
const page = Math.max(
|
||||
const viewport = Math.max(
|
||||
1,
|
||||
Math.floor((root.value?.clientHeight ?? 0) / height),
|
||||
((scrollParent ?? root.value)?.clientHeight ?? 0) - stickyInset(),
|
||||
);
|
||||
target = index + (event.key === "PageDown" ? page : -page);
|
||||
if (props.virtualized && index >= 0) {
|
||||
const direction = event.key === "PageDown" ? 1 : -1;
|
||||
const offsetOf = (itemIndex: number) => {
|
||||
const logical = source.value.findIndex(
|
||||
(item) => item.id === items[itemIndex].key,
|
||||
);
|
||||
return virtualLayout.rowOffsetOf(rowIndexOfItem(logical));
|
||||
};
|
||||
const goal = offsetOf(index) + viewport * direction;
|
||||
target = index;
|
||||
while (target + direction >= 0 && target + direction < items.length) {
|
||||
target += direction;
|
||||
if (direction > 0 ? offsetOf(target) >= goal : offsetOf(target) <= goal)
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
const page = Math.max(1, Math.floor(viewport / height));
|
||||
target = index + (event.key === "PageDown" ? page : -page);
|
||||
}
|
||||
} else if (event.key === backward) target = index - 1;
|
||||
else if (event.key === forward) target = index + 1;
|
||||
if (target !== undefined) {
|
||||
@@ -800,6 +863,7 @@ defineExpose({
|
||||
<slot v-if="!visibleItems.length" name="empty" />
|
||||
<div
|
||||
v-if="virtualized"
|
||||
ref="virtualContent"
|
||||
v-bind="wrapperProps"
|
||||
role="presentation"
|
||||
data-slot="list-box-virtual-content"
|
||||
@@ -808,7 +872,15 @@ defineExpose({
|
||||
v-for="entry in windowItems"
|
||||
:key="entry.data.key"
|
||||
role="presentation"
|
||||
:style="{ height: `${entry.data.height}px` }"
|
||||
:ref="(element) => virtualLayout.measureRow(entry.index, element)"
|
||||
:style="{
|
||||
height:
|
||||
entry.data.height === undefined
|
||||
? undefined
|
||||
: `${entry.data.height + entry.data.gap}px`,
|
||||
paddingBottom: `${entry.data.gap}px`,
|
||||
boxSizing: 'border-box',
|
||||
}"
|
||||
>
|
||||
<div v-if="entry.data.kind === 'pad'" aria-hidden="true" />
|
||||
<Header v-else-if="entry.data.kind === 'heading'">
|
||||
|
||||
@@ -44,7 +44,9 @@ export interface ListBoxOptions<T extends ListBoxDataItem = ListBoxDataItem> {
|
||||
/** Fallback height in px for variable rows whose function returns undefined. */
|
||||
estimatedRowHeight?: number;
|
||||
/** Heading row height in px for virtualized `heading` rows. */
|
||||
headingHeight?: number;
|
||||
headingHeight?: number | ((index: number) => number | undefined);
|
||||
/** Estimate used until an unknown heading is measured. */
|
||||
estimatedHeadingHeight?: number;
|
||||
/** Loader row height in px for the virtualized `#loader` row. */
|
||||
loaderHeight?: number;
|
||||
/** Gap in px between rows (counted after every row but the last). */
|
||||
|
||||
@@ -51,17 +51,23 @@ export default defineComponent({
|
||||
tabindex: attrs.tabindex ?? -1,
|
||||
class: [ctx?.slots.value.cell(), attrs.class],
|
||||
"data-slot": "table-cell",
|
||||
"data-fixed-height": row?.height?.value != null || undefined,
|
||||
"data-tree-column": isTreeColumn.value || undefined,
|
||||
"data-level": row?.level,
|
||||
colspan: props.colspan,
|
||||
},
|
||||
slots.default?.({
|
||||
isExpanded: row?.isExpanded.value ?? false,
|
||||
hasChildItems: row?.hasChildItems ?? false,
|
||||
isDisabled: row?.isDisabled.value ?? false,
|
||||
isTreeColumn: isTreeColumn.value,
|
||||
isSelected: row?.isSelected.value ?? false,
|
||||
}),
|
||||
(() => {
|
||||
const content = slots.default?.({
|
||||
isExpanded: row?.isExpanded.value ?? false,
|
||||
hasChildItems: row?.hasChildItems ?? false,
|
||||
isDisabled: row?.isDisabled.value ?? false,
|
||||
isTreeColumn: isTreeColumn.value,
|
||||
isSelected: row?.isSelected.value ?? false,
|
||||
});
|
||||
return row?.height?.value != null
|
||||
? [h("div", { class: "hv-table__fixed-cell-content" }, content)]
|
||||
: content;
|
||||
})(),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -31,6 +31,8 @@ export default defineComponent({
|
||||
level: { type: Number, default: undefined },
|
||||
rowKey: { type: [String, Number] as PropType<TableKey>, required: true },
|
||||
isDisabled: { type: Boolean, default: false },
|
||||
/** Exact virtual-row extent; omitted rows retain natural table sizing. */
|
||||
height: { type: Number, default: undefined },
|
||||
hasChildItems: { type: Boolean, default: false },
|
||||
as: { type: String, default: "tr" },
|
||||
},
|
||||
@@ -76,6 +78,7 @@ export default defineComponent({
|
||||
isSelected,
|
||||
isDisabled,
|
||||
isExpanded,
|
||||
height: computed(() => props.height),
|
||||
get hasChildItems() {
|
||||
return props.hasChildItems;
|
||||
},
|
||||
@@ -100,13 +103,11 @@ export default defineComponent({
|
||||
"aria-expanded": props.hasChildItems ? isExpanded.value : undefined,
|
||||
"aria-level": props.level,
|
||||
// 1-based level for CSS indent (matches upstream --table-row-level).
|
||||
style:
|
||||
props.level != null
|
||||
? ({ "--table-row-level": String(props.level) } as Record<
|
||||
string,
|
||||
string
|
||||
>)
|
||||
: undefined,
|
||||
style: {
|
||||
height: props.height != null ? `${props.height}px` : undefined,
|
||||
"--table-row-level":
|
||||
props.level != null ? String(props.level) : undefined,
|
||||
},
|
||||
"aria-selected":
|
||||
ctx && ctx.selectionMode.value !== "none"
|
||||
? isSelected.value
|
||||
|
||||
@@ -48,6 +48,7 @@ export const tableContextKey: InjectionKey<TableContextValue> =
|
||||
Symbol("hv-table");
|
||||
|
||||
export interface TableRowContextValue {
|
||||
height?: ComputedRef<number | undefined>;
|
||||
nextCellIndex: () => number;
|
||||
key: TableKey;
|
||||
isSelected: ComputedRef<boolean>;
|
||||
|
||||
Reference in New Issue
Block a user