Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

8.2 KB
Raw Blame
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 KeyboardSegmentDragState =
	| { type: "idle" }
	| { type: "movePending" }
	| { type: "moving" };

const MIN_SEGMENT_SECS = 0.3;
const MIN_SEGMENT_PIXELS = 30;

export function KeyboardTrack(props: {
	onDragStateChanged: (v: KeyboardSegmentDragState) => void;
	handleUpdatePlayhead: (e: MouseEvent) => void;
}) {
	const {
		project,
		setProject,
		editorState,
		setEditorState,
		totalDuration,
		projectHistory,
		projectActions,
	} = useEditorContext();
	const { secsPerPixel } = useTimelineContext();

	const minDuration = () =>
		Math.max(MIN_SEGMENT_SECS, secsPerPixel() * MIN_SEGMENT_PIXELS);

	const keyboardSegments = createMemo(() =>
		(project.timeline?.keyboardSegments ?? []).filter(
			(s) => s.start < totalDuration(),
		),
	);
	const selectedKeyboardIndices = createMemo(() => {
		const selection = editorState.timeline.selection;
		if (!selection || selection.type !== "keyboard") return null;
		return new Set(selection.indices);
	});

	const neighborBounds = (index: number) => {
		const segments = keyboardSegments();
		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 === "keyboard") {
							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: "keyboard", indices: next } : null,
							);
						} else {
							setEditorState("timeline", "selection", {
								type: "keyboard",
								indices: [index],
							});
						}
					} else {
						setEditorState("timeline", "selection", {
							type: "keyboard",
							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", "keyboard")
			}
			onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
		>
			<For
				each={keyboardSegments()}
				fallback={
					<div class="cap-empty-lane pointer-events-none">
						<span>No keyboard events</span>
						<span class="cap-empty-lane-action">
							· Record keyboard presses or generate from recording
						</span>
					</div>
				}
			>
				{(segment, i) => {
					const isSelected = createMemo(() => {
						const indices = selectedKeyboardIndices();
						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 keysLabel = () => (
						<div class="cap-seg-labels font-mono">
							<span class="cap-seg-label truncate max-w-full">
								{segment.displayText || "⌨"}
							</span>
						</div>
					);

					return (
						<SegmentRoot
							data-keyboard-segment
							data-index={i()}
							segColor="var(--track-keyboard)"
							class="group"
							selected={isSelected()}
							title={segment.displayText || "Keyboard"}
							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.splitKeyboardSegment(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",
											"keyboardSegments",
											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", "keyboardSegments", i(), {
											...value.original,
											start: value.original.start + clampedDelta,
											end: value.original.end + clampedDelta,
										});
									},
								)}
							>
								<SegmentLabel
									compactAt={24}
									full={keysLabel}
									compact={keysLabel}
									glyph={() => <span class="cap-seg-label font-mono">⌨</span>}
								/>
							</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",
											"keyboardSegments",
											i(),
											"end",
											next,
										);
									},
								)}
							/>
						</SegmentRoot>
					);
				}}
			</For>
		</TrackRoot>
	);
}