Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Refactor: Improve editor performance and UI responsiveness

Cursor Agent9bb14bb8c437
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 38020839e..5ef0f84d5 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -1,7 +1,7 @@
import { Button } from "@cap/ui-solid";
import { NumberField } from "@kobalte/core/number-field";
import { trackDeep } from "@solid-primitives/deep";
-import { throttle } from "@solid-primitives/scheduled";
+import { debounce, throttle } from "@solid-primitives/scheduled";
import { makePersisted } from "@solid-primitives/storage";
import { createMutation } from "@tanstack/solid-query";
import { convertFileSrc } from "@tauri-apps/api/core";
@@ -13,6 +13,7 @@ import {
createSignal,
Match,
on,
+ onCleanup,
Show,
Switch,
} from "solid-js";
@@ -85,19 +86,49 @@ function Inner() {
const { project, editorState, setEditorState } = useEditorContext();
createTauriEventListener(events.editorStateChanged, (payload) => {
- renderFrame.clear();
+ renderFrameThrottled.clear();
setEditorState("playbackTime", payload.playhead_position / FPS);
});
- const renderFrame = throttle((time: number) => {
- if (!editorState.playing) {
- events.renderFrameEvent.emit({
- frame_number: Math.max(Math.floor(time * FPS), 0),
- fps: FPS,
- resolution_base: OUTPUT_SIZE,
- });
+ let rafId: number | null = null;
+ let pendingFrameTime: number | null = null;
+
+ const emitFrame = (time: number) => {
+ events.renderFrameEvent.emit({
+ frame_number: Math.max(Math.floor(time * FPS), 0),
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ });
+ };
+
+ const renderFrameThrottled = throttle((time: number) => {
+ if (editorState.playing) return;
+
+ if (rafId !== null) {
+ pendingFrameTime = time;
+ return;
+ }
+
+ rafId = requestAnimationFrame(() => {
+ rafId = null;
+ const frameTime = pendingFrameTime ?? time;
+ pendingFrameTime = null;
+ emitFrame(frameTime);
+ });
+ }, 1000 / 30);
+
+ const renderFrameDebounced = debounce((time: number) => {
+ if (editorState.playing) return;
+ emitFrame(time);
+ }, 50);
+
+ onCleanup(() => {
+ if (rafId !== null) {
+ cancelAnimationFrame(rafId);
}
- }, 1000 / FPS);
+ renderFrameThrottled.clear();
+ renderFrameDebounced.clear();
+ });
const frameNumberToRender = createMemo(() => {
const preview = editorState.previewTime;
@@ -108,14 +139,23 @@ function Inner() {
createEffect(
on(frameNumberToRender, (number) => {
if (editorState.playing) return;
- renderFrame(number);
+ renderFrameThrottled(number);
}),
);
+ let lastProjectUpdateTime = 0;
createEffect(
on(
() => trackDeep(project),
- () => renderFrame(editorState.playbackTime),
+ () => {
+ const now = performance.now();
+ if (now - lastProjectUpdateTime < 100) {
+ renderFrameDebounced(editorState.playbackTime);
+ } else {
+ renderFrameThrottled(editorState.playbackTime);
+ }
+ lastProjectUpdateTime = now;
+ },
),
);
diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
index 0d1fcc13f..4ffbc601f 100644
--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
@@ -10,6 +10,7 @@ import {
createRoot,
createSignal,
For,
+ Index,
Match,
onCleanup,
Show,
@@ -188,7 +189,7 @@ export function ClipTrack(
systemAudioWaveforms,
} = useEditorContext();
- const { secsPerPixel, duration } = useTimelineContext();
+ const { secsPerPixel, duration, isSegmentVisible } = useTimelineContext();
const segments = (): Array<TimelineSegment> =>
project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];
@@ -204,6 +205,21 @@ export function ClipTrack(
return offsets;
});
+ const visibleSegmentIndices = createMemo(() => {
+ const segs = segments();
+ const offsets = segmentOffsets();
+ const visible: number[] = [];
+ for (let i = 0; i < segs.length; i++) {
+ const seg = segs[i];
+ const segStart = offsets[i];
+ const segEnd = segStart + (seg.end - seg.start) / seg.timescale;
+ if (isSegmentVisible(segStart, segEnd)) {
+ visible.push(i);
+ }
+ }
+ return visible;
+ });
+
function onHandleReleased() {
const { transform } = editorState.timeline;
@@ -223,8 +239,10 @@ export function ClipTrack(
onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "clip")}
onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
>
- <For each={segments()}>
- {(segment, i) => {
+ <Index each={visibleSegmentIndices()}>
+ {(segmentIndex) => {
+ const i = segmentIndex;
+ const segment = () => segments()[i()];
const [startHandleDrag, setStartHandleDrag] = createSignal<null | {
offset: number;
initialStart: number;
@@ -235,14 +253,15 @@ export function ClipTrack(
const relativeSegment = createMemo(() => {
const ds = startHandleDrag();
const offset = ds?.offset ?? 0;
+ const seg = segment();
return {
start: Math.max(prevDuration() + offset, 0),
end:
prevDuration() +
- (offset + (segment.end - segment.start)) / segment.timescale,
- timescale: segment.timescale,
- recordingSegment: segment.recordingSegment,
+ (offset + (seg.end - seg.start)) / seg.timescale,
+ timescale: seg.timescale,
+ recordingSegment: seg.recordingSegment,
};
});
@@ -269,9 +288,10 @@ export function ClipTrack(
const isSelected = createMemo(() => {
const selection = editorState.timeline.selection;
if (!selection || selection.type !== "clip") return false;
+ const seg = segment();
const segmentIndex = project.timeline?.segments?.findIndex(
- (s) => s.start === segment.start && s.end === segment.end,
+ (s) => s.start === seg.start && s.end === seg.end,
);
if (segmentIndex === undefined || segmentIndex === -1) return false;
@@ -283,7 +303,7 @@ export function ClipTrack(
if (project.audio.micVolumeDb && project.audio.micVolumeDb < -30)
return;
- const idx = segment.recordingSegment ?? i();
+ const idx = segment().recordingSegment ?? i();
return micWaveforms()?.[idx] ?? [];
};
@@ -294,7 +314,7 @@ export function ClipTrack(
)
return;
- const idx = segment.recordingSegment ?? i();
+ const idx = segment().recordingSegment ?? i();
return systemAudioWaveforms()?.[idx] ?? [];
};
@@ -401,8 +421,9 @@ export function ClipTrack(
if (editorState.timeline.interactMode === "split") {
const rect = e.currentTarget.getBoundingClientRect();
const fraction = (e.clientX - rect.left) / rect.width;
+ const seg = segment();
- const splitTime = fraction * (segment.end - segment.start);
+ const splitTime = fraction * (seg.end - seg.start);
projectActions.splitClipSegment(prevDuration() + splitTime);
} else {
@@ -486,23 +507,24 @@ export function ClipTrack(
}
}}
>
- {segment.timescale === 1 && (
+ {segment().timescale === 1 && (
<WaveformCanvas
micWaveform={micWaveform()}
systemWaveform={systemAudioWaveform()}
- segment={segment}
+ segment={segment()}
/>
)}
- <Markings segment={segment} prevDuration={prevDuration()} />
+ <Markings segment={segment()} prevDuration={prevDuration()} />
<SegmentHandle
position="start"
class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
if (split()) return;
+ const seg = segment();
- const initialStart = segment.start;
+ const initialStart = seg.start;
setStartHandleDrag({
offset: 0,
initialStart,
@@ -510,17 +532,16 @@ export function ClipTrack(
const maxSegmentDuration =
editorInstance.recordings.segments[
- segment.recordingSegment ?? 0
+ seg.recordingSegment ?? 0
].display.duration;
const availableTimelineDuration =
editorInstance.recordingDuration -
segments().reduce(
- (acc, segment, segmentI) =>
+ (acc, s, segmentI) =>
segmentI === i()
? acc
- : acc +
- (segment.end - segment.start) / segment.timescale,
+ : acc + (s.end - s.start) / s.timescale,
0,
);
@@ -532,8 +553,7 @@ export function ClipTrack(
const prevSegment = segments()[i() - 1];
const prevSegmentIsSameClip =
prevSegment?.recordingSegment !== undefined
- ? prevSegment.recordingSegment ===
- segment.recordingSegment
+ ? prevSegment.recordingSegment === seg.recordingSegment
: false;
function update(event: MouseEvent) {
@@ -541,15 +561,15 @@ export function ClipTrack(
initialStart +
(event.clientX - downEvent.clientX) *
secsPerPixel() *
- segment.timescale;
+ seg.timescale;
const clampedStart = Math.min(
Math.max(
newStart,
prevSegmentIsSameClip ? prevSegment.end : 0,
- segment.end - maxDuration,
+ seg.end - maxDuration,
),
- segment.end - 1,
+ seg.end - 1,
);
setStartHandleDrag({
@@ -590,22 +610,23 @@ export function ClipTrack(
<SegmentContent class="relative justify-center items-center">
{(() => {
const ctx = useSegmentContext();
+ const seg = segment();
return (
<Show when={ctx.width() > 100}>
<div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-12">
<span class="text-white/70">
{hasMultipleRecordingSegments()
- ? `Clip ${segment.recordingSegment}`
+ ? `Clip ${seg.recordingSegment}`
: "Clip"}
</span>
<div class="flex gap-1 items-center text-md dark:text-gray-12 text-gray-1">
<IconLucideClock class="size-3.5" />{" "}
- {formatTime(segment.end - segment.start)}
- <Show when={segment.timescale !== 1}>
+ {formatTime(seg.end - seg.start)}
+ <Show when={seg.timescale !== 1}>
<div class="w-0.5" />
<IconLucideFastForward class="size-3" />
- {segment.timescale}x
+ {seg.timescale}x
</Show>
</div>
</div>
@@ -617,37 +638,36 @@ export function ClipTrack(
position="end"
class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
- const end = segment.end;
+ const seg = segment();
+ const end = seg.end;
if (split()) return;
const maxSegmentDuration =
editorInstance.recordings.segments[
- segment.recordingSegment ?? 0
+ seg.recordingSegment ?? 0
].display.duration;
const availableTimelineDuration =
editorInstance.recordingDuration -
segments().reduce(
- (acc, segment, segmentI) =>
+ (acc, s, segmentI) =>
segmentI === i()
? acc
- : acc +
- (segment.end - segment.start) / segment.timescale,
+ : acc + (s.end - s.start) / s.timescale,
0,
);
const nextSegment = segments()[i() + 1];
const nextSegmentIsSameClip =
nextSegment?.recordingSegment !== undefined
- ? nextSegment.recordingSegment ===
- segment.recordingSegment
+ ? nextSegment.recordingSegment === seg.recordingSegment
: false;
function update(event: MouseEvent) {
const deltaRecorded =
(event.clientX - downEvent.clientX) *
secsPerPixel() *
- segment.timescale;
+ seg.timescale;
const newEnd = end + deltaRecorded;
setProject(
@@ -658,13 +678,12 @@ export function ClipTrack(
Math.max(
Math.min(
newEnd,
- // availableTimelineDuration is in timeline seconds; convert to recorded seconds
- end + availableTimelineDuration * segment.timescale,
+ end + availableTimelineDuration * seg.timescale,
nextSegmentIsSameClip
? nextSegment.start
: maxSegmentDuration,
),
- segment.start + 1,
+ seg.start + 1,
),
);
}
@@ -737,7 +756,7 @@ export function ClipTrack(
</>
);
}}
- </For>
+ </Index>
</TrackRoot>
);
}
diff --git a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
index 1d476bdf8..d3238d646 100644
--- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
@@ -8,6 +8,7 @@ import {
createRoot,
createSignal,
For,
+ Index,
Match,
Show,
Switch,
@@ -44,7 +45,19 @@ export function ZoomTrack(props: {
projectActions,
} = useEditorContext();
- const { duration, secsPerPixel } = useTimelineContext();
+ const { duration, secsPerPixel, isSegmentVisible } = useTimelineContext();
+
+ const visibleZoomIndices = createMemo(() => {
+ const zoomSegments = project.timeline?.zoomSegments ?? [];
+ const visible: number[] = [];
+ for (let i = 0; i < zoomSegments.length; i++) {
+ const seg = zoomSegments[i];
+ if (isSegmentVisible(seg.start, seg.end)) {
+ visible.push(i);
+ }
+ }
+ return visible;
+ });
const [creatingSegmentViaDrag, setCreatingSegmentViaDrag] =
createSignal(false);
@@ -266,8 +279,8 @@ export function ZoomTrack(props: {
});
}}
>
- <For
- each={project.timeline?.zoomSegments}
+ <Show
+ when={(project.timeline?.zoomSegments ?? []).length > 0}
fallback={
<div class="text-center text-sm text-[--text-tertiary] flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
<div>Click to add zoom segment</div>
@@ -277,331 +290,352 @@ export function ZoomTrack(props: {
</div>
}
>
- {(segment, i) => {
- const { setTrackState } = useTrackContext();
-
- const zoomPercentage = () => {
- const amount = segment.amount;
- return `${amount.toFixed(1)}x`;
- };
-
- const zoomSegments = () => project.timeline?.zoomSegments ?? [];
-
- function createMouseDownDrag<T>(
- setup: () => T,
- _update: (e: MouseEvent, v: T, initialMouseX: number) => void,
- ) {
- return (downEvent: MouseEvent) => {
- if (editorState.timeline.interactMode !== "seek") return;
+ <Index each={visibleZoomIndices()}>
+ {(segmentIndex) => {
+ const i = segmentIndex;
+ const segment = () => (project.timeline?.zoomSegments ?? [])[i()];
+ const { setTrackState } = useTrackContext();
+
+ const zoomPercentage = () => {
+ const seg = segment();
+ if (!seg) return "1.0x";
+ const amount = seg.amount;
+ return `${amount.toFixed(1)}x`;
+ };
- downEvent.stopPropagation();
+ const zoomSegments = () => project.timeline?.zoomSegments ?? [];
- const initial = setup();
+ function createMouseDownDrag<T>(
+ setup: () => T,
+ _update: (e: MouseEvent, v: T, initialMouseX: number) => void,
+ ) {
+ return (downEvent: MouseEvent) => {
+ if (editorState.timeline.interactMode !== "seek") return;
- let moved = false;
- let initialMouseX: null | number = null;
+ downEvent.stopPropagation();
- setTrackState("draggingSegment", true);
+ const initial = setup();
- const resumeHistory = projectHistory.pause();
+ let moved = false;
+ let initialMouseX: null | number = null;
- props.onDragStateChanged({ type: "movePending" });
+ setTrackState("draggingSegment", true);
- function finish(e: MouseEvent) {
- resumeHistory();
- if (!moved) {
- e.stopPropagation();
+ const resumeHistory = projectHistory.pause();
- const currentSelection = editorState.timeline.selection;
- const segmentIndex = i();
- const isMultiSelect = e.ctrlKey || e.metaKey;
- const isRangeSelect = e.shiftKey;
+ props.onDragStateChanged({ type: "movePending" });
- if (isRangeSelect && currentSelection?.type === "zoom") {
- // Range selection: select from last selected to current
- const existingIndices = currentSelection.indices;
- const lastIndex =
- existingIndices[existingIndices.length - 1];
- const start = Math.min(lastIndex, segmentIndex);
- const end = Math.max(lastIndex, segmentIndex);
- const rangeIndices: number[] = [];
- for (let idx = start; idx <= end; idx++) {
- rangeIndices.push(idx);
- }
+ function finish(e: MouseEvent) {
+ resumeHistory();
+ if (!moved) {
+ e.stopPropagation();
+
+ const currentSelection = editorState.timeline.selection;
+ const segmentIndex = i();
+ const isMultiSelect = e.ctrlKey || e.metaKey;
+ const isRangeSelect = e.shiftKey;
+
+ if (isRangeSelect && currentSelection?.type === "zoom") {
+ // Range selection: select from last selected to current
+ const existingIndices = currentSelection.indices;
+ const lastIndex =
+ existingIndices[existingIndices.length - 1];
+ const start = Math.min(lastIndex, segmentIndex);
+ const end = Math.max(lastIndex, segmentIndex);
+ const rangeIndices: number[] = [];
+ for (let idx = start; idx <= end; idx++) {
+ rangeIndices.push(idx);
+ }
- setEditorState("timeline", "selection", {
- type: "zoom",
- indices: rangeIndices,
- });
- } else if (isMultiSelect) {
- // Handle multi-selection with Ctrl/Cmd+click
- if (currentSelection?.type === "zoom") {
- const baseIndices = currentSelection.indices;
- const exists = baseIndices.includes(segmentIndex);
- const newIndices = exists
- ? baseIndices.filter((idx) => idx !== segmentIndex)
- : [...baseIndices, segmentIndex];
-
- if (newIndices.length > 0) {
+ setEditorState("timeline", "selection", {
+ type: "zoom",
+ indices: rangeIndices,
+ });
+ } else if (isMultiSelect) {
+ // Handle multi-selection with Ctrl/Cmd+click
+ if (currentSelection?.type === "zoom") {
+ const baseIndices = currentSelection.indices;
+ const exists = baseIndices.includes(segmentIndex);
+ const newIndices = exists
+ ? baseIndices.filter((idx) => idx !== segmentIndex)
+ : [...baseIndices, segmentIndex];
+
+ if (newIndices.length > 0) {
+ setEditorState("timeline", "selection", {
+ type: "zoom",
+ indices: newIndices,
+ });
+ } else {
+ setEditorState("timeline", "selection", null);
+ }
+ } else {
+ // Start new multi-selection
setEditorState("timeline", "selection", {
type: "zoom",
- indices: newIndices,
+ indices: [segmentIndex],
});
- } else {
- setEditorState("timeline", "selection", null);
}
} else {
- // Start new multi-selection
+ // Normal single selection
setEditorState("timeline", "selection", {
type: "zoom",
indices: [segmentIndex],
});
}
- } else {
- // Normal single selection
- setEditorState("timeline", "selection", {
- type: "zoom",
- indices: [segmentIndex],
- });
+ props.handleUpdatePlayhead(e);
}
- props.handleUpdatePlayhead(e);
+ props.onDragStateChanged({ type: "idle" });
+ setTrackState("draggingSegment", false);
}
- props.onDragStateChanged({ type: "idle" });
- setTrackState("draggingSegment", false);
- }
- function update(event: MouseEvent) {
- if (Math.abs(event.clientX - downEvent.clientX) > 2) {
- if (!moved) {
- moved = true;
- initialMouseX = event.clientX;
- props.onDragStateChanged({
- type: "moving",
- });
+ function update(event: MouseEvent) {
+ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
+ if (!moved) {
+ moved = true;
+ initialMouseX = event.clientX;
+ props.onDragStateChanged({
+ type: "moving",
+ });
+ }
}
+
+ if (initialMouseX === null) return;
+
+ _update(event, initial, initialMouseX);
}
- if (initialMouseX === null) return;
-
- _update(event, initial, initialMouseX);
- }
-
- createRoot((dispose) => {
- createEventListenerMap(window, {
- mousemove: (e) => {
- update(e);
- },
- mouseup: (e) => {
- update(e);
- finish(e);
- dispose();
- },
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: (e) => {
+ update(e);
+ },
+ mouseup: (e) => {
+ update(e);
+ finish(e);
+ dispose();
+ },
+ });
});
- });
- };
- }
-
- const isSelected = createMemo(() => {
- const selection = editorState.timeline.selection;
- if (!selection || selection.type !== "zoom") return false;
+ };
+ }
- const segmentIndex = project.timeline?.zoomSegments?.findIndex(
- (s) => s.start === segment.start && s.end === segment.end,
- );
+ const isSelected = createMemo(() => {
+ const selection = editorState.timeline.selection;
+ if (!selection || selection.type !== "zoom") return false;
+ const seg = segment();
+ if (!seg) return false;
- // Support both single selection (index) and multi-selection (indices)
- if (segmentIndex === undefined || segmentIndex === -1) return false;
+ const segmentIndex = project.timeline?.zoomSegments?.findIndex(
+ (s) => s.start === seg.start && s.end === seg.end,
+ );
- return selection.indices.includes(segmentIndex);
- });
+ if (segmentIndex === undefined || segmentIndex === -1)
+ return false;
- return (
- <SegmentRoot
- class={cx(
- "border duration-200 hover:border-gray-12 transition-colors group",
- "bg-gradient-to-r from-[#292929] via-[#434343] to-[#292929] shadow-[inset_0_8px_12px_3px_rgba(255,255,255,0.2)]",
- isSelected()
- ? "wobble-wrapper border-gray-12"
- : "border-transparent",
- )}
- innerClass="ring-red-5"
- segment={segment}
- onMouseDown={(e) => {
- e.stopPropagation();
-
- if (editorState.timeline.interactMode === "split") {
- const rect = e.currentTarget.getBoundingClientRect();
- const fraction = (e.clientX - rect.left) / rect.width;
-
- const splitTime = fraction * (segment.end - segment.start);
-
- projectActions.splitZoomSegment(i(), splitTime);
- }
- }}
- >
- <SegmentHandle
- position="start"
- onMouseDown={createMouseDownDrag(
- () => {
- const start = segment.start;
-
- let minValue = 0;
-
- const maxValue = segment.end - 1;
-
- for (let i = zoomSegments().length - 1; i >= 0; i--) {
- const segment = zoomSegments()[i]!;
- if (segment.end <= start) {
- minValue = segment.end;
- break;
- }
- }
+ return selection.indices.includes(segmentIndex);
+ });
- return { start, minValue, maxValue };
- },
- (e, value, initialMouseX) => {
- const newStart =
- value.start +
- (e.clientX - initialMouseX) * secsPerPixel();
-
- setProject(
- "timeline",
- "zoomSegments",
- i(),
- "start",
- Math.min(
- value.maxValue,
- Math.max(value.minValue, newStart),
- ),
- );
-
- setProject(
- "timeline",
- "zoomSegments",
- produce((s) => {
- s.sort((a, b) => a.start - b.start);
- }),
- );
- },
- )}
- />
- <SegmentContent
- class="flex justify-center items-center cursor-grab"
- onMouseDown={createMouseDownDrag(
- () => {
- const original = { ...segment };
-
- const prevSegment = zoomSegments()[i() - 1];
- const nextSegment = zoomSegments()[i() + 1];
-
- const minStart = prevSegment?.end ?? 0;
- const maxEnd = nextSegment?.start ?? duration();
-
- return {
- original,
- minStart,
- maxEnd,
- };
- },
- (e, value, initialMouseX) => {
- const rawDelta =
- (e.clientX - initialMouseX) * secsPerPixel();
-
- const newStart = value.original.start + rawDelta;
- const newEnd = value.original.end + rawDelta;
-
- let delta = rawDelta;
-
- if (newStart < value.minStart)
- delta = value.minStart - value.original.start;
- else if (newEnd > value.maxEnd)
- delta = value.maxEnd - value.original.end;
-
- setProject("timeline", "zoomSegments", i(), {
- start: value.original.start + delta,
- end: value.original.end + delta,
- });
- },
- )}
- >
- {(() => {
- const ctx = useSegmentContext();
-
- return (
- <Switch>
- <Match when={ctx.width() < 40}>
- <div class="flex justify-center items-center">
- <IconLucideSearch class="size-3.5 text-gray-1 dark:text-gray-12" />
- </div>
- </Match>
- <Match when={ctx.width() < 100}>
- <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
- <IconLucideSearch class="size-3" />
- <span>{zoomPercentage()}</span>
- </div>
- </Match>
- <Match when={true}>
- <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">
- <span class="opacity-70">Zoom</span>
- <div class="flex gap-1 items-center text-md">
- <IconLucideSearch class="size-3.5" />
- {zoomPercentage()}
- </div>
- </div>
- </Match>
- </Switch>
- );
- })()}
- </SegmentContent>
- <SegmentHandle
- position="end"
- onMouseDown={createMouseDownDrag(
- () => {
- const end = segment.end;
-
- const minValue = segment.start + 1;
-
- let maxValue = duration();
-
- for (let i = 0; i < zoomSegments().length; i++) {
- const segment = zoomSegments()[i]!;
- if (segment.start > end) {
- maxValue = segment.start;
- break;
+ return (
+ <Show when={segment()}>
+ {(seg) => (
+ <SegmentRoot
+ class={cx(
+ "border duration-200 hover:border-gray-12 transition-colors group",
+ "bg-gradient-to-r from-[#292929] via-[#434343] to-[#292929] shadow-[inset_0_8px_12px_3px_rgba(255,255,255,0.2)]",
+ isSelected()
+ ? "wobble-wrapper border-gray-12"
+ : "border-transparent",
+ )}
+ innerClass="ring-red-5"
+ segment={seg()}
+ onMouseDown={(e) => {
+ e.stopPropagation();
+
+ if (editorState.timeline.interactMode === "split") {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+
+ const splitTime = fraction * (seg().end - seg().start);
+
+ projectActions.splitZoomSegment(i(), splitTime);
}
- }
-
- return { end, minValue, maxValue };
- },
- (e, value, initialMouseX) => {
- const newEnd =
- value.end + (e.clientX - initialMouseX) * secsPerPixel();
-
- setProject(
- "timeline",
- "zoomSegments",
- i(),
- "end",
- Math.min(
- value.maxValue,
- Math.max(value.minValue, newEnd),
- ),
- );
-
- setProject(
- "timeline",
- "zoomSegments",
- produce((s) => {
- s.sort((a, b) => a.start - b.start);
- }),
- );
- },
+ }}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const start = seg().start;
+
+ let minValue = 0;
+
+ const maxValue = seg().end - 1;
+
+ for (
+ let idx = zoomSegments().length - 1;
+ idx >= 0;
+ idx--
+ ) {
+ const zs = zoomSegments()[idx]!;
+ if (zs.end <= start) {
+ minValue = zs.end;
+ break;
+ }
+ }
+
+ return { start, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const newStart =
+ value.start +
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "start",
+ Math.min(
+ value.maxValue,
+ Math.max(value.minValue, newStart),
+ ),
+ );
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ produce((s) => {
+ s.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ <SegmentContent
+ class="flex justify-center items-center cursor-grab"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const original = { ...seg() };
+
+ const prevSegment = zoomSegments()[i() - 1];
+ const nextSegment = zoomSegments()[i() + 1];
+
+ const minStart = prevSegment?.end ?? 0;
+ const maxEnd = nextSegment?.start ?? duration();
+
+ return {
+ original,
+ minStart,
+ maxEnd,
+ };
+ },
+ (e, value, initialMouseX) => {
+ const rawDelta =
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ const newStart = value.original.start + rawDelta;
+ const newEnd = value.original.end + rawDelta;
+
+ let delta = rawDelta;
+
+ if (newStart < value.minStart)
+ delta = value.minStart - value.original.start;
+ else if (newEnd > value.maxEnd)
+ delta = value.maxEnd - value.original.end;
+
+ setProject("timeline", "zoomSegments", i(), {
+ start: value.original.start + delta,
+ end: value.original.end + delta,
+ });
+ },
+ )}
+ >
+ {(() => {
+ const ctx = useSegmentContext();
+
+ return (
+ <Switch>
+ <Match when={ctx.width() < 40}>
+ <div class="flex justify-center items-center">
+ <IconLucideSearch class="size-3.5 text-gray-1 dark:text-gray-12" />
+ </div>
+ </Match>
+ <Match when={ctx.width() < 100}>
+ <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
+ <IconLucideSearch class="size-3" />
+ <span>{zoomPercentage()}</span>
+ </div>
+ </Match>
+ <Match when={true}>
+ <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">
+ <span class="opacity-70">Zoom</span>
+ <div class="flex gap-1 items-center text-md">
+ <IconLucideSearch class="size-3.5" />
+ {zoomPercentage()}
+ </div>
+ </div>
+ </Match>
+ </Switch>
+ );
+ })()}
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={createMouseDownDrag(
+ () => {
+ const end = seg().end;
+
+ const minValue = seg().start + 1;
+
+ let maxValue = duration();
+
+ for (
+ let idx = 0;
+ idx < zoomSegments().length;
+ idx++
+ ) {
+ const zs = zoomSegments()[idx]!;
+ if (zs.start > end) {
+ maxValue = zs.start;
+ break;
+ }
+ }
+
+ return { end, minValue, maxValue };
+ },
+ (e, value, initialMouseX) => {
+ const newEnd =
+ value.end +
+ (e.clientX - initialMouseX) * secsPerPixel();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "end",
+ Math.min(
+ value.maxValue,
+ Math.max(value.minValue, newEnd),
+ ),
+ );
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ produce((s) => {
+ s.sort((a, b) => a.start - b.start);
+ }),
+ );
+ },
+ )}
+ />
+ </SegmentRoot>
)}
- />
- </SegmentRoot>
- );
- }}
- </For>
+ </Show>
+ );
+ }}
+ </Index>
+ </Show>
<Show
when={
!useTrackContext().trackState.draggingSegment && newSegmentDetails()
diff --git a/apps/desktop/src/routes/editor/Timeline/context.ts b/apps/desktop/src/routes/editor/Timeline/context.ts
index 8383bf2c1..2ec890dbb 100644
--- a/apps/desktop/src/routes/editor/Timeline/context.ts
+++ b/apps/desktop/src/routes/editor/Timeline/context.ts
@@ -3,7 +3,7 @@ import {
type NullableBounds,
} from "@solid-primitives/bounds";
import { createContextProvider } from "@solid-primitives/context";
-import type { Accessor } from "solid-js";
+import { type Accessor, createMemo } from "solid-js";
import { createStore } from "solid-js/store";
import { useEditorContext } from "../context";
@@ -11,6 +11,8 @@ import { useEditorContext } from "../context";
export const MAX_TIMELINE_MARKINGS = 20;
const TIMELINE_MARKING_RESOLUTIONS = [0.5, 1, 2.5, 5, 10, 30];
+const SEGMENT_RENDER_PADDING = 2;
+
export const [TimelineContextProvider, useTimelineContext] =
createContextProvider(
(props: {
@@ -20,16 +22,33 @@ export const [TimelineContextProvider, useTimelineContext] =
}) => {
const { editorState: state } = useEditorContext();
- const markingResolution = () =>
- TIMELINE_MARKING_RESOLUTIONS.find(
- (r) => state.timeline.transform.zoom / r <= MAX_TIMELINE_MARKINGS,
- ) ?? 30;
+ const markingResolution = createMemo(
+ () =>
+ TIMELINE_MARKING_RESOLUTIONS.find(
+ (r) => state.timeline.transform.zoom / r <= MAX_TIMELINE_MARKINGS,
+ ) ?? 30,
+ );
+
+ const visibleTimeRange = createMemo(() => {
+ const { transform } = state.timeline;
+ const start = transform.position - SEGMENT_RENDER_PADDING;
+ const end =
+ transform.position + transform.zoom + SEGMENT_RENDER_PADDING;
+ return { start: Math.max(0, start), end };
+ });
+
+ const isSegmentVisible = (segmentStart: number, segmentEnd: number) => {
+ const range = visibleTimeRange();
+ return segmentEnd >= range.start && segmentStart <= range.end;
+ };
return {
duration: () => props.duration,
secsPerPixel: () => props.secsPerPixel,
timelineBounds: props.timelineBounds,
markingResolution,
+ visibleTimeRange,
+ isSegmentVisible,
};
},
null!,
diff --git a/core b/core
new file mode 100644
index 000000000..9e3a48817
Binary files /dev/null and b/core differ
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 8875f6324..6cde5af02 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -47,7 +47,7 @@ pub fn pts_to_frame(pts: i64, time_base: Rational, fps: u32) -> u32 {
.round() as u32
}
-pub const FRAME_CACHE_SIZE: usize = 100;
+pub const FRAME_CACHE_SIZE: usize = 300;
#[derive(Clone)]
pub struct AsyncVideoDecoderHandle {