repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/web/components/virtual-stream.js.ts

Raw
File outline
export type VirtualWindowOptions = {
	selectedId: number;
	threshold?: number;
	radius?: number;
};

export function virtualWindow<T extends { id: number }>(
	events: T[],
	options: VirtualWindowOptions,
): T[] {
	const threshold = options.threshold ?? 200;
	if (events.length <= threshold) return events;
	const radius = options.radius ?? 30;
	const index = events.findIndex((event) => event.id === options.selectedId);
	if (index === -1) return events.slice(-threshold);
	return events.slice(Math.max(0, index - radius), index + radius + 1);
}

export function renderVirtualStreamJs(): string {
	return `function appendStreamRows(fragment) {
	requestAnimationFrame(() => stream.append(fragment));
}
function maybeVirtualizeStream() {
	const rows = [...stream.children];
	if (rows.length <= 500) return;
	for (const row of rows.slice(0, rows.length - 500)) row.remove();
}
const streamBatchChannel = new MessageChannel();
streamBatchChannel.port1.onmessage = maybeVirtualizeStream;
`;
}