perf(studio): add timeline clip-window index primitive

This commit is contained in:
Miguel Angel Simon Sierra
2026-07-31 15:45:57 +02:00
parent 3572dc8689
commit 9258e94156
9 changed files with 508 additions and 22 deletions
@@ -1,7 +1,8 @@
import { memo, useRef, useState } from "react";
import { moveBeatCompositionTime, deleteBeatAtCompositionTime } from "../../utils/beatEditActions";
import { usePlayerStore } from "../store/playerStore";
import { CLIP_Y } from "./timelineLayout";
import { CLIP_Y, getTimelineBeatEntries } from "./timelineLayout";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
export const BEAT_BAND_H = 14; // dark band height at top of track
const BEAT_HIT_W = 12; // grab width per beat (px)
@@ -24,23 +25,30 @@ export const BeatBackgroundLines = memo(function BeatBackgroundLines({
beatStrengths,
pps,
highlightTime,
renderTimeRange,
}: {
beatTimes: number[] | undefined;
beatStrengths: number[] | undefined;
pps: number;
/** Snap guide time — drawn as a bright line even when it is not a beat. */
highlightTime?: number | null;
renderTimeRange?: TimelineTimeRange;
}) {
const visibleBeatTimes = beatTimes && !beatsTooDense(beatTimes, pps) ? beatTimes : null;
const highlightIsBeat =
highlightTime != null &&
visibleBeatTimes?.some((t) => Math.abs(t - highlightTime) < 1e-3) === true;
if (!visibleBeatTimes && highlightTime == null) return null;
const beatEntries = getTimelineBeatEntries(
visibleBeatTimes ?? undefined,
beatStrengths,
renderTimeRange,
);
return (
<div className="absolute inset-0 pointer-events-none" style={{ zIndex: 0 }}>
{visibleBeatTimes?.map((t, i) => {
{beatEntries.map(({ time: t, index: i, strength: beatStrength }) => {
const isHighlight = highlightTime != null && Math.abs(t - highlightTime) < 1e-3;
const strength = Math.pow(Math.min(1, beatStrengths?.[i] ?? 0.5), 2.2);
const strength = Math.pow(Math.min(1, beatStrength ?? 0.5), 2.2);
const opacity = isHighlight ? 1 : 0.06 + strength * 0.16;
return (
<div
@@ -81,10 +89,12 @@ export const BeatStrip = memo(function BeatStrip({
beatTimes,
beatStrengths,
pps,
renderTimeRange,
}: {
beatTimes: number[] | undefined;
beatStrengths: number[] | undefined;
pps: number;
renderTimeRange?: TimelineTimeRange;
}) {
// Active drag: which beat and how far (px) it's been dragged.
const [drag, setDrag] = useState<{ index: number; dx: number } | null>(null);
@@ -92,15 +102,21 @@ export const BeatStrip = memo(function BeatStrip({
if (!beatTimes || beatsTooDense(beatTimes, pps)) return null;
const cy = BEAT_BAND_H / 2;
const beatEntries = getTimelineBeatEntries(
beatTimes,
beatStrengths,
renderTimeRange,
drag ? new Set([drag.index]) : undefined,
);
return (
<div
className="absolute left-0 right-0 pointer-events-none"
style={{ top: CLIP_Y, height: BEAT_BAND_H, background: "rgba(0,0,0,0.28)", zIndex: 11 }}
>
{beatTimes.map((t, i) => {
{beatEntries.map(({ time: t, index: i, strength: beatStrength }) => {
// Louder beats → larger, brighter dot. Gamma curve widens the contrast.
const strength = Math.pow(Math.min(1, beatStrengths?.[i] ?? 0.5), 2.2);
const strength = Math.pow(Math.min(1, beatStrength ?? 0.5), 2.2);
const r = 1.5 + strength * 2.5;
const opacity = 0.25 + strength * 0.75;
const dxPx = drag?.index === i ? drag.dx : 0;
@@ -1,10 +1,11 @@
import { memo } from "react";
import type { TimelineTheme } from "./timelineTheme";
import { RULER_H } from "./timelineLayout";
import { RULER_H, getTimelineBeatEntries } from "./timelineLayout";
import { formatTimelineTickLabel } from "./timelineRulerGeometry";
import { usePlayerStore } from "../store/playerStore";
import { secondsToFrame } from "../lib/time";
import type { MusicBeatAnalysis } from "@hyperframes/core/beats";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
interface TimelineRulerProps {
major: number[];
@@ -17,6 +18,7 @@ interface TimelineRulerProps {
theme: TimelineTheme;
beatAnalysis?: MusicBeatAnalysis | null;
contentOrigin: number;
renderTimeRange?: TimelineTimeRange;
}
export const TimelineRuler = memo(function TimelineRuler({
@@ -30,10 +32,12 @@ export const TimelineRuler = memo(function TimelineRuler({
theme,
beatAnalysis,
contentOrigin,
renderTimeRange,
}: TimelineRulerProps) {
const timeDisplayMode = usePlayerStore((s) => s.timeDisplayMode);
const beatTimes = beatAnalysis?.beatTimes ?? [];
const beatStrengths = beatAnalysis?.beatStrengths ?? [];
const beatEntries = getTimelineBeatEntries(beatTimes, beatStrengths, renderTimeRange);
// Only draw beat lines when they'd be at least 5px apart
const avgBeatInterval =
@@ -52,13 +56,14 @@ export const TimelineRuler = memo(function TimelineRuler({
height={totalH}
>
{showBeats &&
beatTimes.map((t, i) => {
beatEntries.map(({ time: t, index: i, strength: beatStrength }) => {
const x = t * pps;
// Louder beats → brighter line. Gamma curve widens the contrast.
const strength = Math.pow(Math.min(1, beatStrengths[i] ?? 0.5), 2.2);
const strength = Math.pow(Math.min(1, beatStrength ?? 0.5), 2.2);
const opacity = 0.08 + strength * 0.62;
return (
<line
data-timeline-grid-cell="beat"
key={`b-${t}-${i}`}
x1={x}
y1={0}
@@ -104,13 +109,23 @@ export const TimelineRuler = memo(function TimelineRuler({
contentOrigin + t * pps (see getTimelinePlayheadLeft). Without the shift
a tick spans [x, x+1) and its center is half a pixel right. */}
{minor.map((t) => (
<div key={`m-${t}`} className="absolute bottom-0" style={{ left: t * pps - 0.5 }}>
<div
key={`m-${t}`}
data-timeline-grid-cell="minor"
className="absolute bottom-0"
style={{ left: t * pps - 0.5 }}
>
<div className="w-px h-2" style={{ background: theme.tickMinor }} />
</div>
))}
{major.map((t) => (
<div key={`M-${t}`} className="absolute top-0" style={{ left: t * pps - 0.5 }}>
<div
key={`M-${t}`}
data-timeline-grid-cell="major"
className="absolute top-0"
style={{ left: t * pps - 0.5 }}
>
<span
className="absolute font-mono tabular-nums leading-none whitespace-nowrap"
style={{
@@ -19,7 +19,46 @@ import {
getTimelineRowGeometry,
trackHeights,
resolveTimelineAssetDrop,
getTimelineBeatEntries,
} from "./timelineLayout";
import { generateTicks, getTimelineMajorTickInterval } from "./timelineRulerGeometry";
import { getTimelineRenderTimeRange } from "./timelineViewportGeometry";
describe("horizontal timeline window", () => {
it("adds the shared quarter-viewport overscan on each side and clamps to duration", () => {
expect(getTimelineRenderTimeRange({ scrollLeft: 300, clientWidth: 500 }, 100, 200, 20)).toEqual(
{ start: 0, end: 7.25 },
);
expect(
getTimelineRenderTimeRange({ scrollLeft: 1_900, clientWidth: 500 }, 100, 200, 20),
).toEqual({ start: 15.75, end: 20 });
});
it("generates globally aligned ticks directly inside the bounded window", () => {
const ticks = generateTicks(10_000, 100, undefined, { start: 500.2, end: 501.8 });
const interval = getTimelineMajorTickInterval(10_000, 100);
expect(ticks.major.every((time) => time >= 500.2 && time <= 501.8)).toBe(true);
expect(
ticks.major.every((time) => Math.abs(time / interval - Math.round(time / interval)) < 1e-6),
).toBe(true);
expect(ticks.major.length + ticks.minor.length).toBeLessThan(100);
});
it("slices beat records with original strength indexes and unions a pinned beat", () => {
expect(
getTimelineBeatEntries(
[0, 1, 2, 3],
[0.1, 0.2, 0.3, 0.4],
{ start: 1, end: 3 },
new Set([3]),
),
).toEqual([
{ index: 1, time: 1, strength: 0.2 },
{ index: 2, time: 2, strength: 0.3 },
{ index: 3, time: 3, strength: 0.4 },
]);
});
});
/** N collapsed rows, the shape every caller passes when nothing is expanded. */
const baseRows = (count: number) => Array.from({ length: count }, () => TRACK_H);
@@ -1,4 +1,5 @@
import type { ZoomMode } from "../store/playerStore";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
/* ── Layout constants ──────────────────────────────────────────────── */
export const GUTTER = 32;
@@ -9,6 +10,47 @@ export const RULER_H = 24;
export const CLIP_Y = 3;
export const CLIP_HANDLE_W = 18;
export interface TimelineBeatEntry {
readonly index: number;
readonly time: number;
readonly strength: number | undefined;
}
function findFirstTimeAtOrAfter(times: readonly number[], target: number): number {
let low = 0;
let high = times.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if ((times[mid] ?? Number.POSITIVE_INFINITY) < target) low = mid + 1;
else high = mid;
}
return low;
}
/** Slice sorted beat data without allocating entries outside the render window. */
export function getTimelineBeatEntries(
beatTimes: readonly number[] | undefined,
beatStrengths: readonly number[] | undefined,
range: TimelineTimeRange | undefined,
pinnedIndexes: ReadonlySet<number> = new Set(),
): readonly TimelineBeatEntry[] {
if (!beatTimes?.length) return [];
const start = range?.start ?? Number.NEGATIVE_INFINITY;
const end = range?.end ?? Number.POSITIVE_INFINITY;
const selected = new Set<number>();
for (let index = findFirstTimeAtOrAfter(beatTimes, start); index < beatTimes.length; index++) {
const time = beatTimes[index];
if (time === undefined || time >= end) break;
selected.add(index);
}
for (const index of pinnedIndexes) {
if (index >= 0 && index < beatTimes.length) selected.add(index);
}
return [...selected]
.sort((left, right) => left - right)
.map((index) => ({ index, time: beatTimes[index]!, strength: beatStrengths?.[index] }));
}
export function getTimelineLaneTop(laneIndex: number): number {
return TRACK_H + Math.max(0, Math.trunc(laneIndex)) * LANE_H;
}
@@ -1,7 +1,8 @@
import { formatTime } from "../lib/time";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
// fallow-ignore-next-line complexity
function getTimelineMajorTickInterval(
export function getTimelineMajorTickInterval(
duration: number,
pixelsPerSecond?: number,
frameRate?: number,
@@ -58,14 +59,41 @@ function roundTickValue(time: number): number {
return Math.round(time * 1e6) / 1e6;
}
function isSupportedTickDuration(duration: number): boolean {
return duration > 0 && Number.isFinite(duration) && duration <= 14400;
}
function getTickRange(duration: number, range?: TimelineTimeRange): TimelineTimeRange {
return {
start: Math.max(0, range?.start ?? 0),
end: Math.min(duration, range?.end ?? duration),
};
}
function appendMinorTicks(
minor: number[],
majorTime: number,
minorInterval: number,
subdivisions: number,
range: TimelineTimeRange,
maxTicks: number,
majorCount: number,
): void {
for (let part = 1; part < subdivisions && majorCount + minor.length < maxTicks; part++) {
const time = majorTime + part * minorInterval;
if (time >= range.start - 0.001 && time <= range.end + 0.001) {
minor.push(roundTickValue(time));
}
}
}
export function generateTicks(
duration: number,
pixelsPerSecond?: number,
frameRate?: number,
range?: TimelineTimeRange,
): { major: number[]; minor: number[] } {
if (duration <= 0 || !Number.isFinite(duration) || duration > 14400) {
return { major: [], minor: [] };
}
if (!isSupportedTickDuration(duration)) return { major: [], minor: [] };
const majorInterval = getTimelineMajorTickInterval(duration, pixelsPerSecond, frameRate);
const subdivisions = getMinorSubdivisions(majorInterval, pixelsPerSecond, frameRate);
const minorInterval = subdivisions > 0 ? majorInterval / subdivisions : 0;
@@ -73,14 +101,13 @@ export function generateTicks(
const minor: number[] = [];
// Safety cap prevents malformed inputs from creating an unbounded ruler.
const maxTicks = 2000;
for (let index = 0; major.length < maxTicks; index++) {
const tickRange = getTickRange(duration, range);
const firstMajorIndex = Math.max(0, Math.floor(tickRange.start / majorInterval));
for (let index = firstMajorIndex; major.length < maxTicks; index++) {
const time = index * majorInterval;
if (time > duration + 0.001) break;
major.push(roundTickValue(time));
for (let part = 1; part < subdivisions && major.length + minor.length < maxTicks; part++) {
const minorTime = time + part * minorInterval;
if (minorTime <= duration + 0.001) minor.push(roundTickValue(minorTime));
}
if (time > tickRange.end + 0.001) break;
if (time >= tickRange.start - 0.001) major.push(roundTickValue(time));
appendMinorTicks(minor, time, minorInterval, subdivisions, tickRange, maxTicks, major.length);
}
return { major, minor };
}
@@ -1,6 +1,26 @@
import { RULER_H, type TimelineRowGeometry } from "./timelineLayout";
import { TIMELINE_VIEWPORT_BUDGETS } from "../lib/timelineViewportBudgets";
import type { TimelineTimeRange } from "../lib/timelineClipIndex";
import type { TimelineScrollViewportSnapshot } from "./useTimelineScrollViewport";
export function getTimelineRenderTimeRange(
viewport: Pick<TimelineScrollViewportSnapshot, "scrollLeft" | "clientWidth">,
pixelsPerSecond: number,
contentOrigin: number,
duration: number,
): TimelineTimeRange {
if (!(pixelsPerSecond > 0) || !(duration > 0) || !(viewport.clientWidth > 0)) {
return { start: 0, end: 0 };
}
const overscanPx = viewport.clientWidth * TIMELINE_VIEWPORT_BUDGETS.timeOverscanViewportRatio;
const startPx = viewport.scrollLeft - contentOrigin - overscanPx;
const endPx = viewport.scrollLeft + viewport.clientWidth - contentOrigin + overscanPx;
return {
start: Math.min(duration, Math.max(0, startPx / pixelsPerSecond)),
end: Math.min(duration, Math.max(0, endPx / pixelsPerSecond)),
};
}
export function getTimelineVisibleTimeRange(
viewport: Pick<TimelineScrollViewportSnapshot, "scrollLeft" | "clientWidth">,
pixelsPerSecond: number,
@@ -25,7 +25,7 @@ export function extractTimelineVirtualRowRange(
return [...indexes].sort((left, right) => left - right);
}
export function extractTimelineVirtualRowSeed(
function extractTimelineVirtualRowSeed(
count: number,
pinnedRowIndexes: readonly number[],
): number[] {
@@ -0,0 +1,153 @@
import { describe, expect, it } from "vitest";
import type { TimelineElement } from "../store/playerStore";
import { getTimelineElementIdentity } from "./timelineElementHelpers";
import { createTimelineClipIndex, queryTimelineClipIndex } from "./timelineClipIndex";
function clip(
id: string,
start: number,
duration: number,
track = 1,
hidden = false,
): TimelineElement {
return { id, tag: "div", start, duration, track, hidden };
}
function ids(elements: readonly TimelineElement[]): string[] {
return elements.map(getTimelineElementIdentity);
}
function createDeterministicRandom(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0;
return state / 0x1_0000_0000;
};
}
function linearOracle(
elements: readonly TimelineElement[],
range: { start: number; end: number },
pinned: ReadonlySet<string>,
): readonly TimelineElement[] {
return elements.filter((element) => {
if (!Number.isFinite(element.start) || !Number.isFinite(element.duration)) return false;
if (pinned.has(getTimelineElementIdentity(element))) return true;
if (range.end <= range.start) return false;
const end = element.start + Math.max(0, element.duration);
if (end <= element.start) return element.start >= range.start && element.start < range.end;
return element.start < range.end && end > range.start;
});
}
describe("timelineClipIndex", () => {
it("finds a long predecessor spanning the window", () => {
const index = createTimelineClipIndex([[1, [clip("long", 0, 100), clip("late", 80, 1)]]]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 50, end: 51 }))).toEqual(["long"]);
});
it("prunes 50k ended clips around one long interval in a late window", () => {
const elements = [
clip("long", 0, 50_000),
...Array.from({ length: 49_999 }, (_, index) => clip(`short-${index}`, index, 0.25)),
];
const index = createTimelineClipIndex([[1, elements]]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 49_999, end: 49_999.5 }))).toEqual([
"long",
]);
});
it("uses half-open render boundaries and retains zero-duration points", () => {
const index = createTimelineClipIndex([
[
1,
[
clip("left", 0, 2),
clip("right", 2, 2),
clip("point", 3, 0),
clip("negative", 3.5, -2),
clip("micro", 4, 1e-9),
],
],
]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 2, end: 4 }))).toEqual([
"right",
"point",
"negative",
]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 4, end: 5 }))).toEqual(["micro"]);
});
it("preserves projection order after overlap and pin union", () => {
const index = createTimelineClipIndex([
[1, [clip("pinned", 10, 1), clip("visible-b", 2, 1), clip("visible-a", 1, 3)]],
]);
expect(
ids(queryTimelineClipIndex(index, 1, { start: 1.5, end: 2.5 }, new Set(["pinned"]))),
).toEqual(["pinned", "visible-b", "visible-a"]);
});
it("keeps duplicate identities deterministic and ignores stale pins", () => {
const index = createTimelineClipIndex([
[1, [clip("duplicate", 10, 1), clip("duplicate", 20, 1), clip("hidden", 30, 1, 1, true)]],
[2, [clip("duplicate", 40, 1, 2)]],
]);
expect(
ids(queryTimelineClipIndex(index, 1, { start: 0, end: 1 }, new Set(["duplicate", "stale"]))),
).toEqual(["duplicate", "duplicate"]);
expect(
ids(queryTimelineClipIndex(index, 2, { start: 0, end: 1 }, new Set(["duplicate"]))),
).toEqual(["duplicate"]);
});
it("keeps an immutable interval snapshot when the source projection array changes", () => {
const source = [clip("first", 0, 2), clip("second", 5, 2)];
const index = createTimelineClipIndex([[1, source]]);
source.splice(0, source.length, clip("replacement", 0, 20));
expect(ids(queryTimelineClipIndex(index, 1, { start: 0, end: 1 }))).toEqual(["first"]);
});
it("excludes clips with non-finite timing", () => {
const index = createTimelineClipIndex([
[1, [clip("bad-start", Number.NaN, 1), clip("bad-duration", 0, Number.POSITIVE_INFINITY)]],
]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 0, end: 1 }))).toEqual([]);
});
it("indexes synthetic fractional display rows independently", () => {
const index = createTimelineClipIndex([
[1, [clip("host", 0, 1)]],
[1.5, [clip("child", 10, 1, 1.5)]],
]);
expect(ids(queryTimelineClipIndex(index, 1.5, { start: 10, end: 11 }))).toEqual(["child"]);
expect(ids(queryTimelineClipIndex(index, 1, { start: 10, end: 11 }))).toEqual([]);
});
it("matches a linear oracle across deterministic randomized windows and pins", () => {
const random = createDeterministicRandom(0x2698);
for (let scenario = 0; scenario < 50; scenario += 1) {
const elements = Array.from({ length: 60 }, (_, index) => {
const element = clip(
`clip-${scenario}-${index}`,
Math.floor(random() * 120) - 10,
random() < 0.15 ? -Math.floor(random() * 5) : Math.floor(random() * 30),
);
if (index % 4 === 0) element.key = `index.html#${element.id}`;
return element;
});
const index = createTimelineClipIndex([[1, elements]]);
for (let query = 0; query < 12; query += 1) {
const start = Math.floor(random() * 120) - 10;
const range = { start, end: start + Math.floor(random() * 35) };
const pinned = new Set(
elements
.filter(() => random() < 0.05)
.map((element) => getTimelineElementIdentity(element)),
);
expect(queryTimelineClipIndex(index, 1, range, pinned)).toEqual(
linearOracle(elements, range, pinned),
);
}
}
});
});
@@ -0,0 +1,174 @@
import type { TimelineElement } from "../store/playerStore";
import { getTimelineElementIdentity } from "./timelineElementHelpers";
export interface TimelineTimeRange {
readonly start: number;
readonly end: number;
}
interface TimelineClipInterval {
readonly element: TimelineElement;
readonly identity: string;
readonly ordinal: number;
readonly start: number;
readonly end: number;
}
interface TimelineClipRowIndex {
readonly byStart: readonly TimelineClipInterval[];
readonly treeLeafCount: number;
readonly maxPositiveEndTree: readonly number[];
readonly maxPointStartTree: readonly number[];
readonly byIdentity: ReadonlyMap<string, readonly TimelineClipInterval[]>;
}
export interface TimelineClipIndex {
readonly rows: ReadonlyMap<number, TimelineClipRowIndex>;
}
function clipInterval(element: TimelineElement, ordinal: number): TimelineClipInterval | null {
if (!Number.isFinite(element.start) || !Number.isFinite(element.duration)) return null;
const duration = Math.max(0, element.duration);
return Object.freeze({
element,
identity: getTimelineElementIdentity(element),
ordinal,
start: element.start,
end: element.start + duration,
});
}
function createTimelineClipMaxTrees(intervals: readonly TimelineClipInterval[]) {
let treeLeafCount = 1;
while (treeLeafCount < intervals.length) treeLeafCount *= 2;
const maxPositiveEndTree = Array<number>(treeLeafCount * 2).fill(Number.NEGATIVE_INFINITY);
const maxPointStartTree = Array<number>(treeLeafCount * 2).fill(Number.NEGATIVE_INFINITY);
for (let index = 0; index < intervals.length; index += 1) {
const interval = intervals[index];
if (!interval) continue;
const leaf = treeLeafCount + index;
if (interval.end > interval.start) maxPositiveEndTree[leaf] = interval.end;
else maxPointStartTree[leaf] = interval.start;
}
for (let node = treeLeafCount - 1; node > 0; node -= 1) {
maxPositiveEndTree[node] = Math.max(
maxPositiveEndTree[node * 2] ?? Number.NEGATIVE_INFINITY,
maxPositiveEndTree[node * 2 + 1] ?? Number.NEGATIVE_INFINITY,
);
maxPointStartTree[node] = Math.max(
maxPointStartTree[node * 2] ?? Number.NEGATIVE_INFINITY,
maxPointStartTree[node * 2 + 1] ?? Number.NEGATIVE_INFINITY,
);
}
return {
treeLeafCount,
maxPositiveEndTree: Object.freeze(maxPositiveEndTree),
maxPointStartTree: Object.freeze(maxPointStartTree),
};
}
/**
* Build an immutable snapshot for one exact display-track projection.
* Rebuild only when that projection's array identity changes. Construction is
* O(n log n) overall because each row is sorted once.
*/
export function createTimelineClipIndex(
tracks: readonly (readonly [number, readonly TimelineElement[]])[],
): TimelineClipIndex {
const rows = new Map<number, TimelineClipRowIndex>();
for (const [rowKey, elements] of tracks) {
const intervals = elements
.map(clipInterval)
.filter((interval): interval is TimelineClipInterval => interval !== null);
const byStart = Object.freeze(
[...intervals].sort(
(left, right) => left.start - right.start || left.ordinal - right.ordinal,
),
);
const maxTrees = createTimelineClipMaxTrees(byStart);
const mutableByIdentity = new Map<string, TimelineClipInterval[]>();
for (const interval of intervals) {
const matches = mutableByIdentity.get(interval.identity) ?? [];
matches.push(interval);
mutableByIdentity.set(interval.identity, matches);
}
const byIdentity = new Map(
[...mutableByIdentity].map(([identity, matches]) => [identity, Object.freeze(matches)]),
);
rows.set(rowKey, Object.freeze({ byStart, ...maxTrees, byIdentity }));
}
return Object.freeze({ rows });
}
function upperBoundStart(intervals: readonly TimelineClipInterval[], end: number): number {
let low = 0;
let high = intervals.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if ((intervals[mid]?.start ?? Number.POSITIVE_INFINITY) < end) low = mid + 1;
else high = mid;
}
return low;
}
function overlaps(interval: TimelineClipInterval, range: TimelineTimeRange): boolean {
if (interval.end <= interval.start)
return interval.start >= range.start && interval.start < range.end;
return interval.start < range.end && interval.end > range.start;
}
function collectTimelineClipOverlaps(
row: TimelineClipRowIndex,
candidateCount: number,
range: TimelineTimeRange,
selected: Set<TimelineClipInterval>,
): void {
const visit = (node: number, left: number, right: number) => {
if (
left >= candidateCount ||
((row.maxPositiveEndTree[node] ?? Number.NEGATIVE_INFINITY) <= range.start &&
(row.maxPointStartTree[node] ?? Number.NEGATIVE_INFINITY) < range.start)
) {
return;
}
if (right - left === 1) {
const interval = row.byStart[left];
if (interval && overlaps(interval, range)) selected.add(interval);
return;
}
const middle = Math.floor((left + right) / 2);
visit(node * 2, left, middle);
visit(node * 2 + 1, middle, right);
};
visit(1, 0, row.treeLeafCount);
}
/**
* Query one display row. The overlap set and explicit actor pins are returned
* in the row's original projection order, so windowing never changes z/DOM order.
* The start lookup is O(log n). Balanced max trees prune both children whose
* positive intervals and point clips cannot reach the window. The overlap walk
* is O((k + 1) log n) for k matches; pin lookup is O(p), followed by the
* projection-order sort of the unique result set.
*/
export function queryTimelineClipIndex(
index: TimelineClipIndex,
rowKey: number,
range: TimelineTimeRange,
pinnedIdentities: ReadonlySet<string> = new Set(),
): readonly TimelineElement[] {
const row = index.rows.get(rowKey);
if (!row) return Object.freeze([]);
const selected = new Set<TimelineClipInterval>();
if (range.end > range.start) {
collectTimelineClipOverlaps(row, upperBoundStart(row.byStart, range.end), range, selected);
}
for (const identity of pinnedIdentities) {
for (const interval of row.byIdentity.get(identity) ?? []) selected.add(interval);
}
return Object.freeze(
[...selected]
.sort((left, right) => left.ordinal - right.ordinal)
.map((interval) => interval.element),
);
}