Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Improve text overlay editing and add fade duration

Richie McIlroy93bdb2e5327a
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 7b56751f9..abeebad4d 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -2491,14 +2491,6 @@ function CornerStyleSelect(props: {
);
}
-const TEXT_FONT_OPTIONS = [
- { value: "sans-serif", label: "Sans" },
- { value: "serif", label: "Serif" },
- { value: "monospace", label: "Monospace" },
- { value: "Inter", label: "Inter" },
- { value: "Geist Sans", label: "Geist Sans" },
-];
-
const normalizeHexInput = (value: string, fallback: string) => {
const trimmed = value.trim();
const withHash = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
@@ -2522,32 +2514,28 @@ function HexColorInput(props: {
return (
<div class="flex items-center gap-3">
- <button
- type="button"
- class="w-10 h-10 rounded-md border border-gray-4"
- style={{ "background-color": text() }}
- onClick={() => {
- const input = colorInput as
- | (HTMLInputElement & { showPicker?: () => void })
- | undefined;
- input?.showPicker?.();
- input?.click();
- }}
- />
- <input
- ref={(el) => {
- colorInput = el;
- }}
- type="color"
- class="absolute w-0 h-0 opacity-0"
- value={text()}
- onInput={(e) => {
- const next = e.currentTarget.value;
- setText(next);
- prevColor = next;
- props.onChange(next);
- }}
- />
+ <div class="relative">
+ <button
+ type="button"
+ class="w-10 h-10 rounded-md border border-gray-4 cursor-pointer hover:border-gray-5 transition-colors"
+ style={{ "background-color": text() }}
+ onClick={() => colorInput?.click()}
+ />
+ <input
+ ref={(el) => {
+ colorInput = el;
+ }}
+ type="color"
+ class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
+ value={text()}
+ onInput={(e) => {
+ const next = e.currentTarget.value;
+ setText(next);
+ prevColor = next;
+ props.onChange(next);
+ }}
+ />
+ </div>
<TextInput
class="flex-1 px-3 py-2 rounded-lg border border-gray-3 bg-gray-2 text-sm text-gray-12"
value={text()}
@@ -2575,21 +2563,6 @@ function TextSegmentConfig(props: {
const { setProject } = useEditorContext();
const clampNumber = (value: number, min: number, max: number) =>
Math.min(Math.max(Number.isFinite(value) ? value : min), max);
- const textFontOptions = createMemo(() => {
- const font = props.segment.fontFamily;
- if (!font) return TEXT_FONT_OPTIONS;
- const exists = TEXT_FONT_OPTIONS.some((option) => option.value === font);
- return exists
- ? TEXT_FONT_OPTIONS
- : [...TEXT_FONT_OPTIONS, { value: font, label: font }];
- });
-
- const selectedFont = createMemo(
- () =>
- textFontOptions().find(
- (option) => option.value === props.segment.fontFamily,
- ) ?? textFontOptions()[0],
- );
const updateSegment = (fn: (segment: TextSegment) => void) => {
setProject(
@@ -2632,67 +2605,26 @@ function TextSegmentConfig(props: {
</div>
</div>
</Field>
- <Field name="Font" icon={<IconLucideType class="size-4" />}>
- <div class="grid grid-cols-2 gap-3">
- <KSelect<{ label: string; value: string }>
- options={textFontOptions()}
- optionValue="value"
- optionTextValue="label"
- value={selectedFont()}
- onChange={(option) => {
- if (option) {
- updateSegment((segment) => {
- segment.fontFamily = option.value;
- });
- }
- }}
- itemComponent={(selectProps) => (
- <MenuItem<typeof KSelect.Item>
- as={KSelect.Item}
- item={selectProps.item}
- >
- <KSelect.ItemLabel class="flex-1">
- {selectProps.item.rawValue.label}
- </KSelect.ItemLabel>
- </MenuItem>
- )}
- >
- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-9 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
- <KSelect.Value<{
- label: string;
- value: string;
- }> class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal">
- {(state) => <span>{state.selectedOption().label}</span>}
- </KSelect.Value>
- <KSelect.Icon<ValidComponent>
- as={(selectProps) => (
- <IconCapChevronDown
- {...selectProps}
- class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]"
- />
- )}
- />
- </KSelect.Trigger>
- <KSelect.Portal>
- <PopperContent<typeof KSelect.Content>
- as={KSelect.Content}
- class={cx(topSlideAnimateClasses, "z-50")}
- >
- <MenuItemList<typeof KSelect.Listbox>
- class="overflow-y-auto max-h-40"
- as={KSelect.Listbox}
- />
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
- </div>
- </Field>
<Field name="Size" icon={<IconCapEnlarge class="size-4" />}>
<Slider
value={[clampNumber(props.segment.fontSize, 8, 200)]}
onChange={([value]) =>
updateSegment((segment) => {
- segment.fontSize = clampNumber(value, 8, 200);
+ const newFontSize = clampNumber(value, 8, 200);
+ const oldFontSize = segment.fontSize || 48;
+ const scale = newFontSize / oldFontSize;
+
+ segment.fontSize = newFontSize;
+
+ if (
+ segment.size &&
+ segment.size.x > 0.025 &&
+ segment.size.y > 0.025
+ ) {
+ const maxSize = 0.95;
+ segment.size.x = Math.min(segment.size.x * scale, maxSize);
+ segment.size.y = Math.min(segment.size.y * scale, maxSize);
+ }
})
}
minValue={8}
@@ -2700,19 +2632,13 @@ function TextSegmentConfig(props: {
step={1}
/>
</Field>
- <Field name="Font Weight" icon={<IconLucideSparkles class="size-4" />}>
+ <Field name="Style" icon={<IconLucideSparkles class="size-4" />}>
<div class="flex flex-col gap-2">
<KSelect
options={[
- { label: "Thin", value: 100 },
- { label: "Extra Light", value: 200 },
- { label: "Light", value: 300 },
{ label: "Normal", value: 400 },
{ label: "Medium", value: 500 },
- { label: "Semi Bold", value: 600 },
{ label: "Bold", value: 700 },
- { label: "Extra Bold", value: 800 },
- { label: "Black", value: 900 },
]}
optionValue="value"
optionTextValue="label"
@@ -2726,13 +2652,13 @@ function TextSegmentConfig(props: {
segment.fontWeight = value.value;
});
}}
- itemComponent={(props) => (
+ itemComponent={(selectItemProps) => (
<MenuItem<typeof KSelect.Item>
as={KSelect.Item}
- item={props.item}
+ item={selectItemProps.item}
>
<KSelect.ItemLabel class="flex-1">
- {props.item.rawValue.label}
+ {selectItemProps.item.rawValue.label}
</KSelect.ItemLabel>
<KSelect.ItemIndicator class="ml-auto text-blue-9">
<IconCapCircleCheck />
@@ -2745,20 +2671,13 @@ function TextSegmentConfig(props: {
{(state) => {
const selected = state.selectedOption();
if (selected) return selected.label;
- // Find label for current weight
const weight = props.segment.fontWeight;
const option = [
- { label: "Thin", value: 100 },
- { label: "Extra Light", value: 200 },
- { label: "Light", value: 300 },
{ label: "Normal", value: 400 },
{ label: "Medium", value: 500 },
- { label: "Semi Bold", value: 600 },
{ label: "Bold", value: 700 },
- { label: "Extra Bold", value: 800 },
- { label: "Black", value: 900 },
].find((o) => o.value === weight);
- return option ? option.label : weight.toString();
+ return option ? option.label : "Normal";
}}
</KSelect.Value>
<KSelect.Icon>
@@ -2801,6 +2720,20 @@ function TextSegmentConfig(props: {
}
/>
</Field>
+ <Field name="Fade Duration" icon={<IconLucideTimer class="size-4" />}>
+ <Slider
+ value={[clampNumber(props.segment.fadeDuration ?? 0.15, 0, 1)]}
+ onChange={([value]) =>
+ updateSegment((segment) => {
+ segment.fadeDuration = clampNumber(value, 0, 1);
+ })
+ }
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ formatTooltip="s"
+ />
+ </Field>
</div>
);
}
@@ -2959,6 +2892,20 @@ function MaskSegmentConfig(props: {
/>
</Field>
</Show>
+ <Field name="Fade Duration" icon={<IconLucideTimer class="size-4" />}>
+ <Slider
+ value={[props.segment.fadeDuration ?? 0.15]}
+ onChange={([v]) =>
+ updateSegment((segment) => {
+ segment.fadeDuration = v;
+ })
+ }
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ formatTooltip="s"
+ />
+ </Field>
</div>
);
}
diff --git a/apps/desktop/src/routes/editor/TextOverlay.tsx b/apps/desktop/src/routes/editor/TextOverlay.tsx
index 71e9c3661..0b562681a 100644
--- a/apps/desktop/src/routes/editor/TextOverlay.tsx
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@ -1,8 +1,16 @@
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { cx } from "cva";
-import { createEffect, createMemo, createRoot, on, Show } from "solid-js";
+import {
+ createEffect,
+ createMemo,
+ createRoot,
+ createSignal,
+ For,
+ on,
+ onMount,
+} from "solid-js";
import { produce } from "solid-js/store";
-
+import type { TextSegment as TauriTextSegment } from "~/utils/tauri";
import { useEditorContext } from "./context";
import type { TextSegment } from "./text";
@@ -11,24 +19,37 @@ type TextOverlayProps = {
};
export function TextOverlay(props: TextOverlayProps) {
- const { project, setProject, editorState, projectHistory } =
+ const { project, setProject, editorState, setEditorState, projectHistory } =
useEditorContext();
- const selectedText = createMemo(() => {
+ const currentAbsoluteTime = () =>
+ editorState.previewTime ?? editorState.playbackTime ?? 0;
+
+ const visibleTextSegments = createMemo(() => {
+ const segments = project.timeline?.textSegments ?? [];
+ const time = currentAbsoluteTime();
+ return segments
+ .map((segment, index) => ({ segment, index }))
+ .filter(({ segment }) => time >= segment.start && time < segment.end);
+ });
+
+ const selectedTextIndex = createMemo(() => {
const selection = editorState.timeline.selection;
- if (!selection || selection.type !== "text") return;
- const index = selection.indices[0];
- const segment = project.timeline?.textSegments?.[index];
- if (!segment) return;
- return { index, segment };
+ if (!selection || selection.type !== "text") return null;
+ return selection.indices[0] ?? null;
});
- const clamp = (value: number, min: number, max: number) =>
- Math.min(Math.max(value, min), max);
+ const clamp = (value: number, min: number, max: number) => {
+ if (min > max) {
+ return (min + max) / 2;
+ }
+ return Math.min(Math.max(value, min), max);
+ };
- const updateSegment = (fn: (segment: TextSegment) => void) => {
- const index = selectedText()?.index;
- if (index === undefined) return;
+ const updateSegmentByIndex = (
+ index: number,
+ fn: (segment: TextSegment) => void,
+ ) => {
setProject(
"timeline",
"textSegments",
@@ -78,281 +99,418 @@ export function TextOverlay(props: TextOverlayProps) {
};
}
+ const handleSelectSegment = (index: number, e: MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setEditorState("timeline", "selection", {
+ type: "text",
+ indices: [index],
+ });
+ };
+
+ const handleBackgroundClick = (e: MouseEvent) => {
+ if (e.target === e.currentTarget && selectedTextIndex() !== null) {
+ e.preventDefault();
+ e.stopPropagation();
+ setEditorState("timeline", "selection", null);
+ }
+ };
+
+ const hasTextSelection = () => selectedTextIndex() !== null;
+
return (
- <Show when={selectedText()}>
- {(selected) => {
- const segment = () => selected().segment;
-
- // Measurement Logic
- let hiddenMeasureRef: HTMLDivElement | undefined;
-
- createEffect(
- on(
- () => ({
- content: segment().content,
- fontFamily: segment().fontFamily,
- fontSize: segment().fontSize,
- fontWeight: segment().fontWeight,
- italic: segment().italic,
- containerWidth: props.size.width,
- containerHeight: props.size.height,
- }),
- (deps) => {
- if (!hiddenMeasureRef) return;
-
- const { width: naturalWidth, height: naturalHeight } =
- hiddenMeasureRef.getBoundingClientRect();
-
- if (
- naturalWidth === 0 ||
- naturalHeight === 0 ||
- !deps.containerWidth ||
- !deps.containerHeight
- )
- return;
-
- // Normalize to [0-1]
- const normalizedWidth = naturalWidth / deps.containerWidth;
- const normalizedHeight = naturalHeight / deps.containerHeight;
-
- const _newFontSize = deps.fontSize;
- const newSizeX = normalizedWidth;
- const newSizeY = normalizedHeight;
-
- // Logic simplified: Trust the measurement.
-
- // Update if significant difference to avoid loops
- const sizeXDiff = Math.abs(newSizeX - segment().size.x);
- const sizeYDiff = Math.abs(newSizeY - segment().size.y);
- // const fontDiff = Math.abs(newFontSize - segment().fontSize); // We aren't changing font size anymore
-
- if (sizeXDiff > 0.001 || sizeYDiff > 0.001) {
- updateSegment((s) => {
- const oldHeight = s.size.y;
- s.size.x = newSizeX;
- s.size.y = newSizeY;
- // s.fontSize = newFontSize; // Don't override font size
-
- // Adjust Center Y to keep top anchor fixed (growing down)
- // If height changes by diff, center moves by diff/2
- const diff = newSizeY - oldHeight;
- s.center.y += diff / 2;
-
- // Frame constraints for center
- const halfH = s.size.y / 2;
- const halfW = s.size.x / 2;
-
- if (s.center.y + halfH > 1) {
- s.center.y -= s.center.y + halfH - 1;
- }
- if (s.center.y - halfH < 0) {
- s.center.y += 0 - (s.center.y - halfH);
- }
- if (s.center.x + halfW > 1) {
- s.center.x -= s.center.x + halfW - 1;
- }
- if (s.center.x - halfW < 0) {
- s.center.x += 0 - (s.center.x - halfW);
- }
- });
- }
- },
- ),
- );
+ <div
+ class="absolute inset-0"
+ classList={{ "pointer-events-none": !hasTextSelection() }}
+ onMouseDown={handleBackgroundClick}
+ >
+ <For each={visibleTextSegments()}>
+ {({ segment, index }) => (
+ <TextSegmentOverlay
+ size={props.size}
+ segment={segment}
+ index={index}
+ isSelected={selectedTextIndex() === index}
+ onSelect={(e) => handleSelectSegment(index, e)}
+ updateSegment={(fn) => updateSegmentByIndex(index, fn)}
+ createMouseDownDrag={createMouseDownDrag}
+ clamp={clamp}
+ />
+ )}
+ </For>
+ </div>
+ );
+}
+
+type SegmentWithDefaults = {
+ start: number;
+ end: number;
+ enabled: boolean;
+ content: string;
+ center: { x: number; y: number };
+ size: { x: number; y: number };
+ fontFamily: string;
+ fontSize: number;
+ fontWeight: number;
+ italic: boolean;
+ color: string;
+};
+
+function normalizeSegment(segment: TauriTextSegment): SegmentWithDefaults {
+ return {
+ start: segment.start,
+ end: segment.end,
+ enabled: segment.enabled ?? true,
+ content: segment.content ?? "Text",
+ center: segment.center ?? { x: 0.5, y: 0.5 },
+ size: segment.size ?? { x: 0.01, y: 0.01 },
+ fontFamily: segment.fontFamily ?? "sans-serif",
+ fontSize: segment.fontSize ?? 48,
+ fontWeight: segment.fontWeight ?? 700,
+ italic: segment.italic ?? false,
+ color: segment.color ?? "#ffffff",
+ };
+}
+
+function TextSegmentOverlay(props: {
+ size: { width: number; height: number };
+ segment: TauriTextSegment;
+ index: number;
+ isSelected: boolean;
+ onSelect: (e: MouseEvent) => void;
+ updateSegment: (fn: (segment: TextSegment) => void) => void;
+ createMouseDownDrag: <T>(
+ setup: () => T,
+ update: (
+ e: MouseEvent,
+ value: T,
+ initialMouse: { x: number; y: number },
+ ) => void,
+ ) => (downEvent: MouseEvent) => void;
+ clamp: (value: number, min: number, max: number) => number;
+}) {
+ const segment = createMemo(() => normalizeSegment(props.segment));
+ let hiddenMeasureRef: HTMLDivElement | undefined;
+ const [mounted, setMounted] = createSignal(false);
+ const [isResizing, setIsResizing] = createSignal(false);
+
+ onMount(() => {
+ setMounted(true);
+ });
+
+ const isDefaultSize = (size: { x: number; y: number }) =>
+ size.x <= 0.025 || size.y <= 0.025;
+
+ const [lastContent, setLastContent] = createSignal(segment().content);
+ const [lastFontSize, setLastFontSize] = createSignal(segment().fontSize);
- const rect = () => {
- const width = segment().size.x * props.size.width;
- const height = segment().size.y * props.size.height;
- const left = segment().center.x * props.size.width - width / 2;
- const top = segment().center.y * props.size.height - height / 2;
- return { width, height, left, top };
+ const measureAndUpdateSize = (forceUpdate = false) => {
+ if (!hiddenMeasureRef) return false;
+
+ const seg = segment();
+ if (!forceUpdate && !isDefaultSize(seg.size)) return true;
+
+ const { width: naturalWidth, height: naturalHeight } =
+ hiddenMeasureRef.getBoundingClientRect();
+
+ if (
+ naturalWidth === 0 ||
+ naturalHeight === 0 ||
+ !props.size.width ||
+ !props.size.height
+ )
+ return false;
+
+ const normalizedWidth = naturalWidth / props.size.width;
+ const normalizedHeight = naturalHeight / props.size.height;
+
+ props.updateSegment((s) => {
+ s.size.x = normalizedWidth;
+ s.size.y = normalizedHeight;
+ });
+ return true;
+ };
+
+ createEffect(
+ on(
+ () => ({
+ mounted: mounted(),
+ containerWidth: props.size.width,
+ containerHeight: props.size.height,
+ }),
+ () => {
+ if (!mounted()) return;
+ const tryMeasure = () => {
+ if (!measureAndUpdateSize()) {
+ requestAnimationFrame(tryMeasure);
+ }
};
+ queueMicrotask(tryMeasure);
+ },
+ ),
+ );
+
+ createEffect(
+ on(
+ () => ({
+ content: segment().content,
+ fontSize: segment().fontSize,
+ fontWeight: segment().fontWeight,
+ fontFamily: segment().fontFamily,
+ italic: segment().italic,
+ }),
+ (current) => {
+ if (!mounted()) return;
+ if (isResizing()) return;
+
+ const contentChanged = current.content !== lastContent();
+ const fontSizeChanged = current.fontSize !== lastFontSize();
- const onMove = createMouseDownDrag(
- () => ({
- startPos: { ...segment().center },
- startSize: { ...segment().size },
- }),
- (e, { startPos, startSize }, initialMouse) => {
- const dx = (e.clientX - initialMouse.x) / props.size.width;
- const dy = (e.clientY - initialMouse.y) / props.size.height;
-
- updateSegment((s) => {
- const newX = startPos.x + dx;
- const newY = startPos.y + dy;
-
- // Constrain to frame
- const halfW = startSize.x / 2;
- const halfH = startSize.y / 2;
-
- s.center.x = clamp(newX, halfW, 1 - halfW);
- s.center.y = clamp(newY, halfH, 1 - halfH);
+ if (contentChanged || fontSizeChanged) {
+ setLastContent(current.content);
+ setLastFontSize(current.fontSize);
+
+ queueMicrotask(() => {
+ requestAnimationFrame(() => {
+ if (!isResizing()) {
+ measureAndUpdateSize(true);
+ }
});
- },
+ });
+ }
+ },
+ ),
+ );
+
+ const rect = () => {
+ const seg = segment();
+ const minDimension = 20;
+ const width = Math.max(seg.size.x * props.size.width, minDimension);
+ const height = Math.max(seg.size.y * props.size.height, minDimension);
+ const left = Math.max(0, seg.center.x * props.size.width - width / 2);
+ const top = Math.max(0, seg.center.y * props.size.height - height / 2);
+ return { width, height, left, top };
+ };
+
+ const onMove = props.createMouseDownDrag(
+ () => {
+ const seg = segment();
+ return {
+ startPos: { ...seg.center },
+ startSize: { ...seg.size },
+ };
+ },
+ (e, { startPos, startSize }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ const minPadding = 0.02;
+
+ props.updateSegment((s) => {
+ const newX = startPos.x + dx;
+ const newY = startPos.y + dy;
+
+ const halfW = s.size.x / 2;
+ const halfH = s.size.y / 2;
+
+ s.center.x = props.clamp(
+ newX,
+ halfW + minPadding,
+ 1 - halfW - minPadding,
+ );
+ s.center.y = props.clamp(
+ newY,
+ halfH + minPadding,
+ 1 - halfH - minPadding,
);
+ });
+ },
+ );
+
+ const createResizeHandler = (dirX: -1 | 0 | 1, dirY: -1 | 0 | 1) => {
+ const isCorner = dirX !== 0 && dirY !== 0;
+
+ const handler = props.createMouseDownDrag(
+ () => {
+ if (isCorner) {
+ setIsResizing(true);
+ }
+ const seg = segment();
+ return {
+ startPos: { ...seg.center },
+ startSize: { ...seg.size },
+ startFontSize: seg.fontSize,
+ };
+ },
+ (e, { startPos, startSize, startFontSize }, initialMouse) => {
+ const dx = (e.clientX - initialMouse.x) / props.size.width;
+ const dy = (e.clientY - initialMouse.y) / props.size.height;
+
+ const isSide = dirX !== 0 && dirY === 0;
+
+ const minSize = 0.03;
+ const maxSize = 0.95;
+ const minPadding = 0.02;
+
+ props.updateSegment((s) => {
+ if (isSide) {
+ const targetWidth = startSize.x + dx * dirX;
+ const clampedWidth = props.clamp(targetWidth, minSize, maxSize);
+ const appliedDelta = clampedWidth - startSize.x;
+
+ s.size.x = clampedWidth;
+
+ const halfWidth = s.size.x / 2;
+ const halfHeight = s.size.y / 2;
+ s.center.x = props.clamp(
+ startPos.x + (dirX * appliedDelta) / 2,
+ halfWidth + minPadding,
+ 1 - halfWidth - minPadding,
+ );
+ s.center.y = props.clamp(
+ s.center.y,
+ halfHeight + minPadding,
+ 1 - halfHeight - minPadding,
+ );
+ } else if (isCorner) {
+ const currentHeightPx = startSize.y * props.size.height;
+ const deltaPxY = dy * props.size.height * dirY;
+
+ const scaleY = (currentHeightPx + deltaPxY) / currentHeightPx;
+ const scale = scaleY;
+
+ if (scale > 0.1 && scale < 10) {
+ const newFontSize = props.clamp(startFontSize * scale, 8, 400);
+ const newSizeX = props.clamp(
+ startSize.x * scale,
+ minSize,
+ maxSize,
+ );
+ const newSizeY = props.clamp(
+ startSize.y * scale,
+ minSize,
+ maxSize,
+ );
+
+ s.fontSize = newFontSize;
+ s.size.x = newSizeX;
+ s.size.y = newSizeY;
+
+ const widthDiff = s.size.x - startSize.x;
+ const heightDiff = s.size.y - startSize.y;
+
+ const halfWidth = s.size.x / 2;
+ const halfHeight = s.size.y / 2;
+ s.center.x = props.clamp(
+ startPos.x + (widthDiff * dirX) / 2,
+ halfWidth + minPadding,
+ 1 - halfWidth - minPadding,
+ );
+ s.center.y = props.clamp(
+ startPos.y + (heightDiff * dirY) / 2,
+ halfHeight + minPadding,
+ 1 - halfHeight - minPadding,
+ );
+ }
+ }
+ });
+ },
+ );
- const createResizeHandler = (dirX: -1 | 0 | 1, dirY: -1 | 0 | 1) => {
- return createMouseDownDrag(
- () => ({
- startPos: { ...segment().center },
- startSize: { ...segment().size },
- startFontSize: segment().fontSize,
- }),
- (e, { startPos, startSize, startFontSize }, initialMouse) => {
- const dx = (e.clientX - initialMouse.x) / props.size.width;
- const dy = (e.clientY - initialMouse.y) / props.size.height;
-
- updateSegment((s) => {
- // If Corner Drag -> Scale (change fontSize and Width)
- // If Side Drag -> Change Width (reflow)
-
- const isCorner = dirX !== 0 && dirY !== 0;
- const isSide = dirX !== 0 && dirY === 0;
-
- if (isSide) {
- // Standard resize logic: updates width, keeps center relative or fixed
- const targetWidth = startSize.x + dx * dirX;
- const clampedWidth = clamp(targetWidth, 0.05, 1);
- const appliedDelta = clampedWidth - startSize.x;
-
- s.size.x = clampedWidth;
- s.center.x = clamp(
- startPos.x + (dirX * appliedDelta) / 2,
- s.size.x / 2,
- 1 - s.size.x / 2,
- );
- } else if (isCorner) {
- // Scale uniformly
- const _currentWidthPx = startSize.x * props.size.width;
- const currentHeightPx = startSize.y * props.size.height;
-
- const _deltaPxX = dx * props.size.width * dirX;
- const deltaPxY = dy * props.size.height * dirY;
-
- const scaleY = (currentHeightPx + deltaPxY) / currentHeightPx;
- const scale = scaleY;
-
- if (scale > 0.1) {
- s.fontSize = clamp(startFontSize * scale, 8, 400);
- // Also scale width to maintain aspect ratio of the box
- s.size.x = clamp(startSize.x * scale, 0.05, 1);
-
- // Update center
- const widthDiff = s.size.x - startSize.x;
- const approxHeightDiff = startSize.y * scale - startSize.y;
-
- s.center.x = clamp(
- startPos.x + (widthDiff * dirX) / 2,
- s.size.x / 2,
- 1 - s.size.x / 2,
- );
- s.center.y = clamp(
- startPos.y + (approxHeightDiff * dirY) / 2,
- s.size.y / 2, // Use calculated height for clamping? Approximation
- 1 - s.size.y / 2,
- );
- }
- }
- });
- },
- );
+ return (downEvent: MouseEvent) => {
+ handler(downEvent);
+ if (isCorner) {
+ const onMouseUp = () => {
+ setIsResizing(false);
+ window.removeEventListener("mouseup", onMouseUp);
};
+ window.addEventListener("mouseup", onMouseUp);
+ }
+ };
+ };
- return (
- <div class="absolute inset-0 pointer-events-none">
- {/* Hidden Measurement Div */}
- <div
- ref={hiddenMeasureRef}
- style={{
- position: "absolute",
- visibility: "hidden",
- "white-space": "pre-wrap",
- "word-break": "break-word",
- "font-family": segment().fontFamily,
- "font-size": `${segment().fontSize}px`,
- "font-weight": segment().fontWeight,
- "font-style": segment().italic ? "italic" : "normal",
- "line-height": 1.2,
- // Use fixed width if we want to support wrapping when large?
- // Or max-width?
- // If we allow wrapping, we should set max-width to container width.
- "max-width": `${props.size.width}px`,
- width: "fit-content",
- height: "auto",
- top: "0",
- left: "0",
- }}
- >
- {segment().content}
- {/* Ensure height for empty lines if needed, though pre-wrap usually handles it */}
- {segment().content.endsWith("\n") ? <br /> : null}
- </div>
-
- <div
- class="absolute pointer-events-auto group"
- style={{
- left: `${rect().left}px`,
- top: `${rect().top}px`,
- width: `${rect().width}px`,
- height: `${rect().height}px`,
- }}
- onMouseDown={onMove}
- >
- {/* Visual placeholder (not used for measurement anymore) */}
- <div
- style={{
- "white-space": "pre-wrap",
- "word-break": "break-word",
- "font-family": segment().fontFamily,
- "font-size": `${segment().fontSize}px`,
- "font-weight": segment().fontWeight,
- "font-style": segment().italic ? "italic" : "normal",
- color: segment().color,
- "line-height": 1.2,
- width: "100%",
- height: "100%",
- display: "flex",
- "align-items": "center",
- "justify-content": "center",
- "text-align": "center",
- "pointer-events": "none",
- opacity: 0,
- }}
- class="w-full h-full overflow-hidden"
- >
- {segment().content}
- </div>
-
- <div class="absolute inset-0 rounded-md border-2 border-blue-9 bg-blue-9/10 cursor-move" />
- <ResizeHandle
- class="top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize"
- onMouseDown={createResizeHandler(-1, -1)}
- />
- <ResizeHandle
- class="top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize"
- onMouseDown={createResizeHandler(1, -1)}
- />
- <ResizeHandle
- class="bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize"
- onMouseDown={createResizeHandler(-1, 1)}
- />
- <ResizeHandle
- class="bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize"
- onMouseDown={createResizeHandler(1, 1)}
- />
- <ResizeHandle
- class="left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-w-resize"
- onMouseDown={createResizeHandler(-1, 0)}
- />
- <ResizeHandle
- class="right-0 top-1/2 translate-x-1/2 -translate-y-1/2 cursor-e-resize"
- onMouseDown={createResizeHandler(1, 0)}
- />
- </div>
- </div>
- );
- }}
- </Show>
+ return (
+ <>
+ <div
+ ref={hiddenMeasureRef}
+ style={{
+ position: "absolute",
+ visibility: "hidden",
+ "white-space": "pre-wrap",
+ "word-break": "break-word",
+ "font-family": segment().fontFamily,
+ "font-size": `${segment().fontSize}px`,
+ "font-weight": segment().fontWeight,
+ "font-style": segment().italic ? "italic" : "normal",
+ "line-height": 1.2,
+ "max-width": `${props.size.width}px`,
+ width: "fit-content",
+ height: "auto",
+ top: "0",
+ left: "0",
+ }}
+ >
+ {segment().content}
+ {segment().content.endsWith("\n") ? <br /> : null}
+ </div>
+
+ <div
+ class="absolute pointer-events-auto"
+ classList={{
+ "cursor-move": !props.isSelected,
+ group: props.isSelected,
+ }}
+ style={{
+ left: `${rect().left}px`,
+ top: `${rect().top}px`,
+ width: `${rect().width}px`,
+ height: `${rect().height}px`,
+ }}
+ onMouseDown={(e) => {
+ if (!props.isSelected) {
+ props.onSelect(e);
+ }
+ onMove(e);
+ }}
+ >
+ <div
+ class="absolute inset-0 rounded-md border-2 transition-colors"
+ classList={{
+ "border-blue-9 bg-blue-9/10 cursor-move": props.isSelected,
+ "border-transparent hover:border-blue-6 hover:bg-blue-9/5 cursor-pointer":
+ !props.isSelected,
+ }}
+ />
+ {props.isSelected && (
+ <>
+ <ResizeHandle
+ class="top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize"
+ onMouseDown={createResizeHandler(-1, -1)}
+ />
+ <ResizeHandle
+ class="top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize"
+ onMouseDown={createResizeHandler(1, -1)}
+ />
+ <ResizeHandle
+ class="bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize"
+ onMouseDown={createResizeHandler(-1, 1)}
+ />
+ <ResizeHandle
+ class="bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize"
+ onMouseDown={createResizeHandler(1, 1)}
+ />
+ <ResizeHandle
+ class="left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-w-resize"
+ onMouseDown={createResizeHandler(-1, 0)}
+ />
+ <ResizeHandle
+ class="right-0 top-1/2 translate-x-1/2 -translate-y-1/2 cursor-e-resize"
+ onMouseDown={createResizeHandler(1, 0)}
+ />
+ </>
+ )}
+ </div>
+ </>
);
}
diff --git a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
index 88a4c9fac..7cf30e709 100644
--- a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
@@ -288,7 +288,7 @@ export function TextTrack(props: {
)}
/>
<SegmentContent
- class="flex justify-center items-center cursor-grab px-3"
+ class="flex justify-center items-center cursor-grab px-3 overflow-hidden"
onMouseDown={createMouseDownDrag(
i,
() => {
@@ -325,10 +325,10 @@ export function TextTrack(props: {
},
)}
>
- <div class="flex flex-col gap-0.5 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
+ <div class="flex flex-col gap-0.5 justify-center items-center text-xs text-gray-1 dark:text-gray-12 w-full min-w-0 overflow-hidden">
<span class="opacity-70">Text</span>
- <div class="flex gap-1 items-center text-md">
- <span class="max-w-[10rem] truncate">
+ <div class="flex gap-1 items-center text-md w-full min-w-0 justify-center">
+ <span class="truncate max-w-full">
{segment.content || "Label"}
</span>
</div>
diff --git a/apps/desktop/src/routes/editor/Timeline/Track.tsx b/apps/desktop/src/routes/editor/Timeline/Track.tsx
index 85c954f32..bd22c98ea 100644
--- a/apps/desktop/src/routes/editor/Timeline/Track.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/Track.tsx
@@ -113,16 +113,16 @@ export function SegmentHandle(
props: ComponentProps<"div"> & { position: "start" | "end" },
) {
const ctx = useSegmentContext();
- const hidden = () => ctx.width() < 80;
+ const hidden = () => ctx.width() < 40;
return (
<div
{...props}
class={cx(
- "w-3 cursor-col-resize transition-opacity h-full flex flex-row items-center",
+ "w-4 min-w-4 cursor-col-resize transition-opacity h-full flex flex-row items-center relative z-10",
props.position === "start"
- ? "left-0 justify-end"
- : "right-0 justify-start",
+ ? "left-0 justify-center -ml-1"
+ : "right-0 justify-center -mr-1",
hidden() ? "opacity-0" : "opacity-0 group-hover:opacity-100",
props.class,
)}
diff --git a/apps/desktop/src/routes/editor/text.ts b/apps/desktop/src/routes/editor/text.ts
index d9cae709c..d7d5d47e8 100644
--- a/apps/desktop/src/routes/editor/text.ts
+++ b/apps/desktop/src/routes/editor/text.ts
@@ -12,6 +12,7 @@ export type TextSegment = {
fontWeight: number;
italic: boolean;
color: string;
+ fadeDuration: number;
};
export const defaultTextSegment = (
@@ -23,10 +24,11 @@ export const defaultTextSegment = (
enabled: true,
content: "Text",
center: { x: 0.5, y: 0.5 },
- size: { x: 0.35, y: 0.2 },
+ size: { x: 0.01, y: 0.01 },
fontFamily: "sans-serif",
fontSize: 48,
fontWeight: 700,
italic: false,
color: "#ffffff",
+ fadeDuration: 0.15,
});
diff --git a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
index 1fcc612fd..87abfc348 100644
--- a/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/AnnotationLayer.tsx
@@ -560,7 +560,6 @@ export function AnnotationLayer(props: {
ref={(el) => {
setTimeout(() => {
el.focus();
- // Select all text
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection();
@@ -568,29 +567,32 @@ export function AnnotationLayer(props: {
sel?.addRange(range);
});
}}
+ onInput={(e) => {
+ const text = e.currentTarget.innerText;
+ setAnnotations((a) => a.id === ann.id, "text", text);
+ }}
onBlur={(e) => {
const text = e.currentTarget.innerText;
- const originalText = annotations.find(
- (a) => a.id === ann.id,
- )?.text;
if (!text.trim()) {
- // If deleting, use snapshot
if (textSnapshot) projectHistory.push(textSnapshot);
setAnnotations((prev) =>
prev.filter((a) => a.id !== ann.id),
);
- } else if (text !== originalText) {
- // If changed, use snapshot
- if (textSnapshot) projectHistory.push(textSnapshot);
- setAnnotations((a) => a.id === ann.id, "text", text);
+ } else if (textSnapshot) {
+ const originalText = textSnapshot.annotations.find(
+ (a) => a.id === ann.id,
+ )?.text;
+ if (text !== originalText) {
+ projectHistory.push(textSnapshot);
+ }
}
textSnapshot = null;
setTextEditingId(null);
}}
onKeyDown={(e) => {
- e.stopPropagation(); // Prevent deleting annotation
+ e.stopPropagation();
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
e.currentTarget.blur();
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index dd122e78c..7c340a344 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -378,7 +378,7 @@ export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
export type CaptionData = { segments: CaptionSegment[]; settings: CaptionSettings | null }
export type CaptionSegment = { id: string; start: number; end: number; text: string; words?: CaptionWord[] }
-export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position?: string; bold: boolean; italic: boolean; outline: boolean; outlineColor: string; exportWithSubtitles: boolean; highlightColor?: string; fadeDuration?: number; lingerDuration?: number; wordTransitionDuration?: number }
+export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position?: string; bold: boolean; italic: boolean; fontWeight?: number; outline: boolean; outlineColor: string; exportWithSubtitles: boolean; highlightColor?: string; fadeDuration?: number; lingerDuration?: number; wordTransitionDuration?: number }
export type CaptionWord = { text: string; start: number; end: number }
export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings }
export type CaptureDisplay = { id: DisplayId; name: string; refresh_rate: number }
@@ -436,7 +436,7 @@ export type MainWindowRecordingStartBehaviour = "close" | "minimise"
export type MaskKeyframes = { position?: MaskVectorKeyframe[]; size?: MaskVectorKeyframe[]; intensity?: MaskScalarKeyframe[] }
export type MaskKind = "sensitive" | "highlight"
export type MaskScalarKeyframe = { time: number; value: number }
-export type MaskSegment = { start: number; end: number; enabled?: boolean; maskType: MaskKind; center: XY<number>; size: XY<number>; feather?: number; opacity?: number; pixelation?: number; darkness?: number; keyframes?: MaskKeyframes }
+export type MaskSegment = { start: number; end: number; enabled?: boolean; maskType: MaskKind; center: XY<number>; size: XY<number>; feather?: number; opacity?: number; pixelation?: number; darkness?: number; fadeDuration?: number; keyframes?: MaskKeyframes }
export type MaskType = "blur" | "pixelate"
export type MaskVectorKeyframe = { time: number; x: number; y: number }
export type ModelIDType = string
@@ -495,7 +495,7 @@ export type StereoMode = "stereo" | "monoL" | "monoR"
export type StudioRecordingMeta = { segment: SingleSegment } | { inner: MultipleSegments }
export type StudioRecordingStatus = { status: "InProgress" } | { status: "NeedsRemux" } | { status: "Failed"; error: string } | { status: "Complete" }
export type TargetUnderCursor = { display_id: DisplayId | null; window: WindowUnderCursor | null }
-export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string }
+export type TextSegment = { start: number; end: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; fadeDuration?: number }
export type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[]; sceneSegments?: SceneSegment[]; maskSegments?: MaskSegment[]; textSegments?: TextSegment[] }
export type TimelineSegment = { recordingSegment?: number; timescale: number; start: number; end: number }
export type UploadMeta = { state: "MultipartUpload"; video_id: string; file_path: string; pre_created_video: VideoUploadInfo; recording_dir: string } | { state: "SinglePartUpload"; video_id: string; recording_dir: string; file_path: string; screenshot_path: string } | { state: "Failed"; error: string } | { state: "Complete" }
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
index 59265eeb1..75453cd54 100644
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@ -53,11 +53,12 @@ impl TextLayer {
let mut text_area_data = Vec::with_capacity(texts.len());
for text in texts {
+ let alpha = text.color[3].clamp(0.0, 1.0) * text.opacity.clamp(0.0, 1.0);
let color = Color::rgba(
(text.color[0].clamp(0.0, 1.0) * 255.0) as u8,
(text.color[1].clamp(0.0, 1.0) * 255.0) as u8,
(text.color[2].clamp(0.0, 1.0) * 255.0) as u8,
- (text.color[3].clamp(0.0, 1.0) * 255.0) as u8,
+ (alpha * 255.0) as u8,
);
let width = (text.bounds[2] - text.bounds[0]).max(1.0);
diff --git a/crates/rendering/src/text.rs b/crates/rendering/src/text.rs
index 6c4e508b2..661eabee5 100644
--- a/crates/rendering/src/text.rs
+++ b/crates/rendering/src/text.rs
@@ -1,6 +1,7 @@
use cap_project::{TextSegment, XY};
const BASE_TEXT_HEIGHT: f64 = 0.2;
+const MAX_FONT_SIZE_PX: f32 = 256.0;
#[derive(Debug, Clone)]
pub struct PreparedText {
@@ -11,6 +12,7 @@ pub struct PreparedText {
pub font_size: f32,
pub font_weight: f32,
pub italic: bool,
+ pub opacity: f32,
}
fn parse_color(hex: &str) -> [f32; 4] {
@@ -70,14 +72,29 @@ pub fn prepare_texts(
let right = (left + width).min(output_size.x as f32);
let bottom = (top + height).min(output_size.y as f32);
+ let fade_duration = segment.fade_duration.max(0.0);
+ let opacity = if fade_duration > 0.0 {
+ let time_since_start = (frame_time - segment.start).max(0.0);
+ let time_until_end = (segment.end - frame_time).max(0.0);
+
+ let fade_in = (time_since_start / fade_duration).min(1.0);
+ let fade_out = (time_until_end / fade_duration).min(1.0);
+
+ (fade_in * fade_out) as f32
+ } else {
+ 1.0
+ };
+
prepared.push(PreparedText {
content: segment.content.clone(),
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
font_family: segment.font_family.clone(),
- font_size: (segment.font_size * size_scale).max(1.0) * height_scale,
+ font_size: ((segment.font_size * size_scale).max(1.0) * height_scale)
+ .min(MAX_FONT_SIZE_PX),
font_weight: segment.font_weight,
italic: segment.italic,
+ opacity,
});
}