Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

control zoom via timeline

Brendan Allaneeb7b8010f36
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index ab2d59e22..80b2e4788 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -470,7 +470,10 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
}
ProjectConfiguration {
- timeline: Some(TimelineConfiguration { segments }),
+ timeline: Some(TimelineConfiguration {
+ segments,
+ zoom_segments: vec![],
+ }),
..Default::default()
}
};
diff --git a/apps/desktop/src/flags.ts b/apps/desktop/src/flags.ts
index 1f80535b2..24295d60d 100644
--- a/apps/desktop/src/flags.ts
+++ b/apps/desktop/src/flags.ts
@@ -1,4 +1,5 @@
export const flags = {
split: false, //import.meta.env.DEV,
pauseResume: false, //import.meta.env.DEV,
+ zoom: false, //import.meta.env.DEV,
};
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 69208512c..7e0330c2b 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -148,7 +148,7 @@ function Inner() {
return (
<div
- class="p-5 flex flex-col gap-4 w-screen h-screen divide-y bg-gray-50 rounded-lg leading-5 animate-in fade-in"
+ class="p-5 flex flex-col gap-4 w-screen h-screen bg-gray-50 rounded-lg leading-5 animate-in fade-in"
data-tauri-drag-region
>
<Header />
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index b26c0c773..76fd79b04 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -1,5 +1,15 @@
import { createElementBounds } from "@solid-primitives/bounds";
-import { For, Show, createRoot, createSignal, onMount } from "solid-js";
+import {
+ Accessor,
+ ComponentProps,
+ For,
+ Show,
+ createContext,
+ createRoot,
+ createSignal,
+ onMount,
+ useContext,
+} from "solid-js";
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { cx } from "cva";
import { produce } from "solid-js/store";
@@ -7,6 +17,11 @@ import { produce } from "solid-js/store";
import { commands } from "~/utils/tauri";
import { useEditorContext } from "./context";
import { formatTime } from "./utils";
+import { flags } from "~/flags";
+
+const TimelineContext = createContext<{ duration: Accessor<number> }>({
+ duration: () => 0,
+});
export function Timeline() {
const {
@@ -41,35 +56,52 @@ export function Timeline() {
const segments = () =>
project.timeline?.segments ?? [{ start: 0, end: duration(), timescale: 1 }];
+ if (flags.zoom)
+ if (
+ !project.timeline?.zoomSegments ||
+ project.timeline.zoomSegments.length < 1
+ ) {
+ setProject(
+ produce((project) => {
+ project.timeline ??= {
+ segments: [{ start: 0, end: duration(), timescale: 1 }],
+ };
+ project.timeline.zoomSegments = [
+ { start: 0, end: duration(), amount: 1 },
+ ];
+ })
+ );
+ }
+
return (
- <div
- class="py-[2rem] relative overflow-hidden"
- style={{
- "padding-left": `${xPadding}px`,
- "padding-right": `${xPadding}px`,
- }}
- onMouseDown={(e) => {
- const { left, width } = timelineBounds;
- commands.setPlayheadPosition(
- videoId,
- Math.round(
- 30 *
- editorInstance.recordingDuration *
- ((e.clientX - left!) / width!)
- )
- );
- }}
- onMouseMove={(e) => {
- const { left, width } = timelineBounds;
- setPreviewTime(
- editorInstance.recordingDuration * ((e.clientX - left!) / width!)
- );
- }}
- onMouseLeave={() => {
- setPreviewTime(undefined);
- }}
- >
- <div ref={setTimelineRef} class="flex flex-row">
+ <TimelineContext.Provider value={{ duration }}>
+ <div
+ class="py-[2rem] relative overflow-hidden space-y-0.5"
+ style={{
+ "padding-left": `${xPadding}px`,
+ "padding-right": `${xPadding}px`,
+ }}
+ onMouseDown={(e) => {
+ const { left, width } = timelineBounds;
+ commands.setPlayheadPosition(
+ videoId,
+ Math.round(
+ 30 *
+ editorInstance.recordingDuration *
+ ((e.clientX - left!) / width!)
+ )
+ );
+ }}
+ onMouseMove={(e) => {
+ const { left, width } = timelineBounds;
+ setPreviewTime(
+ editorInstance.recordingDuration * ((e.clientX - left!) / width!)
+ );
+ }}
+ onMouseLeave={() => {
+ setPreviewTime(undefined);
+ }}
+ >
<Show when={previewTime()}>
{(time) => (
<div
@@ -109,41 +141,41 @@ export function Timeline() {
<div class="size-2 bg-red-300 rounded-full -mt-2 -ml-[calc(0.25rem-0.5px)]" />
</div>
</Show>
- <For each={segments()}>
- {(segment, i) => (
- <div
- class="border border-blue-300 rounded-[calc(0.75rem+1px)] relative h-[3rem]"
- style={{
- width: `${(100 * (segment.end - segment.start)) / duration()}%`,
- }}
- onMouseDown={(e) => {
- if (!split()) return;
- e.stopPropagation();
-
- const rect = e.currentTarget.getBoundingClientRect();
- const fraction = (e.clientX - rect.left) / rect.width;
-
- const splitTime =
- segment.start + fraction * (segment.end - segment.start);
-
- setProject(
- "timeline",
- "segments",
- produce((segments) => {
- console.log({ splitTime });
- segments.splice(i() + 1, 0, {
- start: splitTime,
- end: segment.end,
- timescale: 1,
- });
- segments[i()].end = splitTime;
- })
- );
- }}
- >
- <div class="h-full border border-white ring-1 ring-blue-300 flex flex-row rounded-xl overflow-hidden group">
- <div
- class="bg-blue-300 w-[0.5rem] cursor-col-resize"
+
+ <TrackRoot ref={setTimelineRef} isFreeForm={false}>
+ <For each={segments()}>
+ {(segment, i) => (
+ <SegmentRoot
+ class="border-blue-300"
+ innerClass="ring-blue-300"
+ segment={segment}
+ onMouseDown={(e) => {
+ if (!split()) return;
+ e.stopPropagation();
+
+ const rect = e.currentTarget.getBoundingClientRect();
+ const fraction = (e.clientX - rect.left) / rect.width;
+
+ const splitTime =
+ segment.start + fraction * (segment.end - segment.start);
+
+ setProject(
+ "timeline",
+ "segments",
+ produce((segments) => {
+ console.log({ splitTime });
+ segments.splice(i() + 1, 0, {
+ start: splitTime,
+ end: segment.end,
+ timescale: 1,
+ });
+ segments[i()].end = splitTime;
+ })
+ );
+ }}
+ >
+ <SegmentHandle
+ class="bg-blue-300"
onMouseDown={(downEvent) => {
const start = segment.start;
@@ -173,8 +205,7 @@ export function Timeline() {
"start",
Math.min(
Math.max(
- newStart,
- // Math.max(newStart, 0),
+ Math.max(newStart, 0),
segment.end - maxDuration
),
segment.end - 1
@@ -195,7 +226,7 @@ export function Timeline() {
});
}}
/>
- <div class="bg-blue-50 relative w-full h-full flex flex-row items-center justify-between px-[0.5rem] py-[0.25rem]">
+ <SegmentContent class="bg-blue-50">
<span class="text-black-transparent-60 text-[0.625rem] mt-auto">
{formatTime(segment.start)}
</span>
@@ -218,9 +249,9 @@ export function Timeline() {
<span class="text-black-transparent-60 text-[0.625rem] mt-auto">
{formatTime(segment.end)}
</span>
- </div>
- <div
- class="bg-blue-300 w-[0.5rem] cursor-col-resize"
+ </SegmentContent>
+ <SegmentHandle
+ class="bg-blue-300"
onMouseDown={(downEvent) => {
const end = segment.end;
@@ -268,11 +299,235 @@ export function Timeline() {
});
}}
/>
- </div>
- </div>
- )}
- </For>
+ </SegmentRoot>
+ )}
+ </For>
+ </TrackRoot>
+ {flags.zoom && (
+ <TrackRoot isFreeForm>
+ <For each={project.timeline?.zoomSegments}>
+ {(segment, i) => (
+ <SegmentRoot
+ class="border-red-300"
+ innerClass="ring-red-300"
+ segment={segment}
+ >
+ <SegmentHandle
+ class="bg-red-300"
+ onMouseDown={(downEvent) => {
+ const start = segment.start;
+
+ const maxDuration =
+ editorInstance.recordingDuration -
+ segments().reduce(
+ (acc, segment, segmentI) =>
+ segmentI === i()
+ ? acc
+ : acc +
+ (segment.end - segment.start) /
+ segment.timescale,
+ 0
+ );
+
+ function update(event: MouseEvent) {
+ const { width } = timelineBounds;
+
+ const newStart =
+ start +
+ ((event.clientX - downEvent.clientX) / width!) *
+ duration();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "start",
+ Math.min(
+ Math.max(
+ newStart,
+ // Math.max(newStart, 0),
+ segment.end - maxDuration
+ ),
+ segment.end - 1
+ )
+ );
+ }
+
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ },
+ });
+ });
+ }}
+ />
+ <SegmentContent class="bg-red-50">
+ {/*<button
+ onClick={() => {
+ // setProject(
+ // "timeline",
+ // "zoomSegments",
+ // produce((segments) => {
+ // segments.splice(i(), 1);
+ // })
+ // );
+ }}
+ class="size-7 opacity-0 group/button group-hover:opacity-100 transition-opacity bg-gray-50 rounded-full flex flex-col items-center justify-center"
+ >
+ <IconCapTrash class="size-4 text-gray-400 group-hover/button:text-gray-500 transition-colors" />
+ </button>*/}
+ </SegmentContent>
+ <SegmentHandle
+ class="bg-red-300"
+ onMouseDown={(downEvent) => {
+ const end = segment.end;
+
+ const maxDuration =
+ editorInstance.recordingDuration -
+ segments().reduce(
+ (acc, segment, segmentI) =>
+ segmentI === i()
+ ? acc
+ : acc +
+ (segment.end - segment.start) /
+ segment.timescale,
+ 0
+ );
+
+ function update(event: MouseEvent) {
+ const { width } = timelineBounds;
+
+ const newEnd =
+ end +
+ ((event.clientX - downEvent.clientX) / width!) *
+ duration();
+
+ setProject(
+ "timeline",
+ "zoomSegments",
+ i(),
+ "end",
+ Math.max(
+ Math.min(newEnd, segment.start + maxDuration),
+ segment.start + 1
+ )
+ );
+ }
+
+ const resumeHistory = history.pause();
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mousemove: update,
+ mouseup: (e) => {
+ dispose();
+ resumeHistory();
+ update(e);
+ },
+ });
+ });
+ }}
+ />
+ </SegmentRoot>
+ )}
+ </For>
+ </TrackRoot>
+ )}
+ </div>
+ </TimelineContext.Provider>
+ );
+}
+
+const TrackContext = createContext<{
+ trackBounds: ReturnType<typeof createElementBounds>;
+ isFreeForm: boolean;
+}>();
+
+function TrackRoot(
+ props: Omit<ComponentProps<"div">, "ref"> & { isFreeForm: boolean }
+) {
+ const [ref, setRef] = createSignal<HTMLDivElement>();
+
+ const bounds = createElementBounds(ref);
+ return (
+ <TrackContext.Provider
+ value={{ trackBounds: bounds, isFreeForm: props.isFreeForm }}
+ >
+ <div
+ {...props}
+ ref={setRef}
+ class={cx("flex flex-row relative h-[3rem]", props.class)}
+ >
+ {props.children}
+ </div>
+ </TrackContext.Provider>
+ );
+}
+
+function SegmentRoot(
+ props: Pick<
+ ComponentProps<"div">,
+ "children" | "onMouseDown" | "class" | "ref"
+ > & {
+ innerClass: string;
+ segment: { start: number; end: number };
+ }
+) {
+ const { duration } = useContext(TimelineContext)!;
+ const { trackBounds, isFreeForm } = useContext(TrackContext)!;
+
+ return (
+ <div
+ class={cx(
+ "absolute border rounded-[calc(0.75rem+1px)] h-[3rem] w-full",
+ props.class
+ )}
+ style={{
+ transform: isFreeForm
+ ? `translateX(${
+ (props.segment.start / duration()) * (trackBounds.width ?? 0)
+ }px)`
+ : undefined,
+ width: `${
+ (100 * (props.segment.end - props.segment.start)) / duration()
+ }%`,
+ }}
+ onMouseDown={props.onMouseDown}
+ ref={props.ref}
+ >
+ <div
+ class={cx(
+ "h-full border border-white ring-1 flex flex-row rounded-xl overflow-hidden group",
+ props.innerClass
+ )}
+ >
+ {props.children}
</div>
</div>
);
}
+
+function SegmentContent(
+ props: Pick<ComponentProps<"div">, "class" | "children">
+) {
+ return (
+ <div
+ class={cx(
+ "relative w-full h-full flex flex-row items-center justify-between px-[0.5rem] py-[0.25rem]",
+ props.class
+ )}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+function SegmentHandle(props: ComponentProps<"div">) {
+ return (
+ <div {...props} class={cx("w-[0.5rem] cursor-col-resize", props.class)} />
+ );
+}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index b38607280..3a20701ed 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -421,12 +421,13 @@ export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | ({ v
export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string; prettyName: string }
export type SharingMeta = { id: string; link: string }
export type ShowCapturesPanel = null
-export type TimelineConfiguration = { segments: TimelineSegment[] }
+export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments?: ZoomSegment[] }
export type TimelineSegment = { timescale: number; start: number; end: number }
export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"
export type Video = { duration: number; width: number; height: number; fps: number }
export type VideoType = "screen" | "output"
export type XY<T> = { x: T; y: T }
+export type ZoomSegment = { start: number; end: number; amount: number }
/** tauri-specta globals **/
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index d76c3aec1..ab8418aa9 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -186,10 +186,21 @@ impl TimelineSegment {
}
}
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct ZoomSegment {
+ pub start: f64,
+ pub end: f64,
+ pub amount: f64,
+ // pub mode: Z
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct TimelineConfiguration {
pub segments: Vec<TimelineSegment>,
+ #[serde(default)]
+ pub zoom_segments: Vec<ZoomSegment>,
}
impl TimelineConfiguration {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index feb026785..3fc34c12e 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -425,6 +425,8 @@ impl ProjectUniforms {
let cursor_position = interpolate_cursor_position(&constants.cursor, time);
+ let zoom_keyframes = ZoomKeyframes::new(project);
+
let display = {
let output_size = [output_size.0 as f32, output_size.1 as f32];
let size = [options.screen_size.0 as f32, options.screen_size.1 as f32];
@@ -482,7 +484,10 @@ impl ProjectUniforms {
];
let (zoom, zoom_origin_uv) = if let Some(cursor_position) = cursor_position {
- (1.0, (cursor_position.0 as f32, cursor_position.1 as f32))
+ (
+ dbg!(zoom_keyframes.get_amount(time as f64)),
+ (cursor_position.0 as f32, cursor_position.1 as f32),
+ )
} else {
(1.0, (0.0, 0.0))
};
@@ -581,6 +586,82 @@ impl ProjectUniforms {
}
}
+#[derive(Debug)]
+pub struct ZoomKeyframe {
+ time: f64,
+ amount: f64,
+}
+#[derive(Debug)]
+pub struct ZoomKeyframes(Vec<ZoomKeyframe>);
+
+const ZOOM_DURATION: f64 = 0.3;
+
+impl ZoomKeyframes {
+ pub fn new(config: &ProjectConfiguration) -> Self {
+ let Some(zoom_segments) = config.timeline().map(|t| &t.zoom_segments) else {
+ return Self(vec![]);
+ };
+
+ if zoom_segments.is_empty() {
+ return Self(vec![]);
+ }
+
+ let mut keyframes = vec![];
+
+ for segment in zoom_segments {
+ keyframes.push(ZoomKeyframe {
+ time: segment.start,
+ amount: 1.0,
+ });
+ keyframes.push(ZoomKeyframe {
+ time: segment.start + ZOOM_DURATION,
+ amount: segment.amount,
+ });
+ keyframes.push(ZoomKeyframe {
+ time: segment.end,
+ amount: segment.amount,
+ });
+ keyframes.push(ZoomKeyframe {
+ time: segment.end + ZOOM_DURATION,
+ amount: 1.0,
+ });
+ }
+
+ dbg!(&keyframes);
+
+ Self(keyframes)
+ }
+
+ pub fn get_amount(&self, time: f64) -> f64 {
+ let prev_index = self
+ .0
+ .iter()
+ .rev()
+ .position(|k| time >= k.time)
+ .map(|p| self.0.len() - 1 - p);
+
+ let Some(prev_index) = prev_index else {
+ return 1.0;
+ };
+
+ let next_index = prev_index + 1;
+
+ let Some((prev, next)) = self.0.get(prev_index).zip(self.0.get(next_index)) else {
+ return 1.0;
+ };
+
+ let keyframe_length = next.time - prev.time;
+ let delta_time = time - prev.time;
+
+ let t = delta_time / keyframe_length;
+ let t = t.powf(0.5);
+
+ let amount = prev.amount + (next.amount - prev.amount) * t;
+
+ amount
+ }
+}
+
pub async fn produce_frame(
constants: &RenderVideoConstants,
screen_frame: &Vec<u8>,
@@ -1387,7 +1468,7 @@ fn find_cursor_event<'a>(cursor: &'a CursorData, time: f32) -> &'a CursorEvent {
.iter()
.rev()
.find(|event| {
- println!("Checking event at time: {}ms", event.process_time_ms);
+ // println!("Checking event at time: {}ms", event.process_time_ms);
event.process_time_ms <= time_ms.into()
})
.unwrap_or(&cursor.moves[0]);