Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { createMemo, createRoot, For } from "solid-js";
import { useEditorContext } from "../context";
import { useTimelineContext } from "./context";
import {
SegmentContent,
SegmentHandle,
SegmentLabel,
SegmentRoot,
TrackRoot,
} from "./Track";
export type CaptionSegmentDragState =
| { type: "idle" }
| { type: "movePending" }
| { type: "moving" };
const MIN_SEGMENT_SECS = 0.5;
const MIN_SEGMENT_PIXELS = 40;
export function CaptionsTrack(props: {
onDragStateChanged: (v: CaptionSegmentDragState) => void;
handleUpdatePlayhead: (e: MouseEvent) => void;
onGenerate: () => void | Promise<void>;
isGenerating: boolean;
}) {
const {
project,
setProject,
editorState,
setEditorState,
totalDuration,
projectHistory,
projectActions,
} = useEditorContext();
const { secsPerPixel } = useTimelineContext();
const minDuration = () =>
Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);
const captionSegments = createMemo(() =>
(project.timeline?.captionSegments ?? []).filter(
(s) => s.start < totalDuration(),
),
);
const selectedCaptionIndices = createMemo(() => {
const selection = editorState.timeline.selection;
if (!selection || selection.type !== "caption") return null;
return new Set(selection.indices);
});
const neighborBounds = (index: number) => {
const segments = captionSegments();
return {
prevEnd: segments[index - 1]?.end ?? 0,
nextStart: segments[index + 1]?.start ?? totalDuration(),
};
};
function createMouseDownDrag<T>(
segmentIndex: () => number,
setup: () => T,
update: (e: MouseEvent, value: T, initialMouseX: number) => void,
) {
return (downEvent: MouseEvent) => {
if (editorState.timeline.interactMode !== "seek") return;
downEvent.stopPropagation();
const initial = setup();
let moved = false;
let initialMouseX: number | null = null;
const resumeHistory = projectHistory.pause();
props.onDragStateChanged({ type: "movePending" });
function finish(e: MouseEvent) {
resumeHistory();
if (!moved) {
e.stopPropagation();
const index = segmentIndex();
const isMultiSelect = e.ctrlKey || e.metaKey;
if (isMultiSelect) {
const currentSelection = editorState.timeline.selection;
if (currentSelection?.type === "caption") {
const base = currentSelection.indices;
const exists = base.includes(index);
const next = exists
? base.filter((i) => i !== index)
: [...base, index];
setEditorState(
"timeline",
"selection",
next.length > 0 ? { type: "caption", indices: next } : null,
);
} else {
setEditorState("timeline", "selection", {
type: "caption",
indices: [index],
});
}
} else {
setEditorState("timeline", "selection", {
type: "caption",
indices: [index],
});
}
props.handleUpdatePlayhead(e);
}
props.onDragStateChanged({ type: "idle" });
}
function handleUpdate(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);
}
createRoot((dispose) => {
createEventListenerMap(window, {
mousemove: (e) => handleUpdate(e),
mouseup: (e) => {
handleUpdate(e);
finish(e);
dispose();
},
});
});
};
}
return (
<TrackRoot
onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "caption")}
onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
>
<For
each={captionSegments()}
fallback={
<div class="cap-empty-lane">
<span>No captions</span>
<button
type="button"
class="cap-empty-lane-action outline-hidden"
disabled={props.isGenerating}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
void props.onGenerate();
}}
>
· {props.isGenerating ? "Generating..." : "Generate captions"}
</button>
</div>
}
>
{(segment, i) => {
const isSelected = createMemo(() => {
const indices = selectedCaptionIndices();
if (!indices) return false;
return indices.has(i());
});
const segmentWidth = () =>
Math.min(segment.end, totalDuration()) - segment.start;
// Truncation degrades gracefully, so the same row serves both the
// full and compact tiers; it just clips against a smaller box.
const captionLabel = () => (
<div class="cap-seg-labels">
<span class="cap-seg-label truncate max-w-full">
{segment.text || "Caption"}
</span>
</div>
);
return (
<SegmentRoot
data-caption-segment
data-index={i()}
segColor="var(--track-caption)"
class="group"
selected={isSelected()}
title={segment.text || "Caption"}
segment={{
start: segment.start,
end: Math.min(segment.end, totalDuration()),
}}
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 * segmentWidth();
projectActions.splitCaptionSegment(i(), splitTime);
}
}}
>
<SegmentHandle
position="start"
onMouseDown={createMouseDownDrag(
i,
() => {
const bounds = neighborBounds(i());
const start = segment.start;
const minValue = bounds.prevEnd;
const maxValue = Math.max(
minValue,
Math.min(
segment.end - minDuration(),
bounds.nextStart - minDuration(),
),
);
return { start, minValue, maxValue };
},
(e, value, initialMouseX) => {
const delta = (e.clientX - initialMouseX) * secsPerPixel();
const next = Math.max(
value.minValue,
Math.min(value.maxValue, value.start + delta),
);
setProject(
"timeline",
"captionSegments",
i(),
"start",
next,
);
},
)}
/>
<SegmentContent
class="flex items-center cursor-grab overflow-hidden"
onMouseDown={createMouseDownDrag(
i,
() => {
const original = { ...segment };
const bounds = neighborBounds(i());
const minDelta = bounds.prevEnd - original.start;
const maxDelta = bounds.nextStart - original.end;
return { original, minDelta, maxDelta };
},
(e, value, initialMouseX) => {
const delta = (e.clientX - initialMouseX) * secsPerPixel();
const lowerBound = Math.min(value.minDelta, value.maxDelta);
const upperBound = Math.max(value.minDelta, value.maxDelta);
const clampedDelta = Math.min(
upperBound,
Math.max(lowerBound, delta),
);
setProject("timeline", "captionSegments", i(), {
...value.original,
start: value.original.start + clampedDelta,
end: value.original.end + clampedDelta,
});
},
)}
>
<SegmentLabel
compactAt={24}
full={captionLabel}
compact={captionLabel}
/>
</SegmentContent>
<SegmentHandle
position="end"
onMouseDown={createMouseDownDrag(
i,
() => {
const bounds = neighborBounds(i());
const end = segment.end;
const minValue = segment.start + minDuration();
const maxValue = Math.max(minValue, bounds.nextStart);
return { end, minValue, maxValue };
},
(e, value, initialMouseX) => {
const delta = (e.clientX - initialMouseX) * secsPerPixel();
const next = Math.max(
value.minValue,
Math.min(value.maxValue, value.end + delta),
);
setProject("timeline", "captionSegments", i(), "end", next);
},
)}
/>
</SegmentRoot>
);
}}
</For>
</TrackRoot>
);
}