Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

updates

Jareer37c3dbf4df33
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index f6de58d3..eb42ccaa 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isTauri } from "@tauri-apps/api/core";
+import { open as openDialog } from "@tauri-apps/plugin-dialog";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { getCurrentWindow } from "@tauri-apps/api/window";
@@ -7,7 +8,7 @@ import { ContextMenu, type ContextTarget } from "./components/ContextMenu";
import { ExportDialog } from "./components/ExportDialog";
import { Icon } from "./components/Icon";
import { ALL_MEDIA, MediaBin, type BinFilter } from "./components/MediaBin";
-import { Preview, type PreviewSource } from "./components/Preview";
+import { Preview, type PreviewSource, type TextOverlay } from "./components/Preview";
import { Resizer } from "./components/Resizer";
import { RightPanel, type RightTab } from "./components/RightPanel";
import { StartScreen, type ProjectSession } from "./components/StartScreen";
@@ -19,6 +20,7 @@ import {
engineVersion,
loadProject,
probeMedia,
+ readMediaBytes,
saveProject,
type ExportClip,
} from "./lib/engine";
@@ -34,11 +36,14 @@ import {
firstFreeTrack,
findMedia,
findTrack,
+ addFont,
+ addTextClip,
mergeClips,
moveClip,
moveClips,
projectDuration,
removeClips,
+ removeFont,
removeTrack,
renameTrack,
setClipSpeed,
@@ -54,6 +59,7 @@ import {
type Project,
} from "./lib/project";
import { buildChain, chainKey } from "./lib/filters";
+import { familyForPath, registerFont } from "./lib/text";
import { fromDocument, toDocument } from "./lib/persist";
import { useTheme, type Theme } from "./lib/theme";
import { useTransport } from "./lib/transport";
@@ -181,6 +187,99 @@ function Editor({
};
}, [session.path]);
+ // Bring back every font the project names, once, when it opens.
+ //
+ // Without this a reopened project renders its titles in the fallback face
+ // while still *claiming* the custom family, which looks like the styling was
+ // lost. A font whose file has moved is marked rather than dropped: the entry
+ // stays visible in the picker so it is obvious what is missing.
+ useEffect(() => {
+ if (!loaded || project.fonts.length === 0) return;
+
+ let cancelled = false;
+ void Promise.all(
+ project.fonts.map(async (font) => ({
+ family: font.family,
+ ok: await registerFont(font, readMediaBytes),
+ })),
+ ).then((results) => {
+ const failed = results.filter((result) => !result.ok).map((result) => result.family);
+ if (cancelled || failed.length === 0) return;
+
+ setProject((current) => ({
+ ...current,
+ fonts: current.fonts.map((font) =>
+ failed.includes(font.family) ? { ...font, missing: true } : font,
+ ),
+ }));
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ // Deliberately keyed on `loaded` alone. Depending on `project.fonts` would
+ // re-run this on the very state update it performs.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [loaded]);
+
+ /**
+ * Puts a title on the timeline at the playhead.
+ *
+ * It lands on the first track with room, the same rule dropped media
+ * follows, and is selected immediately with the Text tab open - the words
+ * are the first thing anyone wants to change, so putting the panel in front
+ * of them saves a click every single time.
+ */
+ const addText = useCallback(() => {
+ setProject((current) => {
+ const at = latest.current.playhead;
+ const track = firstFreeTrack(current, at, 4);
+ if (!track) return current;
+
+ const { project: next, clipId } = addTextClip(current, { trackId: track.id, start: at });
+ if (clipId) {
+ setSelectedClipIds([clipId]);
+ setSelectedMediaId(null);
+ setRightTab("text");
+ }
+ return next;
+ });
+ }, []);
+
+ /** Adds a font file to the project and makes it available immediately. */
+ const pickFont = useCallback(async () => {
+ try {
+ const picked = await openDialog({
+ multiple: false,
+ title: "Add a font",
+ filters: [{ name: "Fonts", extensions: ["ttf", "otf", "woff", "woff2", "ttc"] }],
+ });
+ if (typeof picked !== "string") return;
+
+ const current = latest.current.project;
+ if (current.fonts.some((font) => font.path === picked)) return;
+
+ const font = {
+ family: familyForPath(
+ picked,
+ current.fonts.map((existing) => existing.family),
+ ),
+ path: picked,
+ };
+
+ // Registered before it is stored, so a file the webview cannot parse is
+ // reported now rather than becoming a broken entry in the picker.
+ if (!(await registerFont(font, readMediaBytes))) {
+ setError(`Could not read ${picked.split(/[\/]/).pop() ?? picked} as a font.`);
+ return;
+ }
+
+ setProject((project) => addFont(project, font));
+ } catch (cause) {
+ setError(String(cause));
+ }
+ }, []);
+
const save = useCallback(async () => {
setSaveState("saving");
try {
@@ -292,10 +391,36 @@ function Editor({
audio.current?.sync(voices, playing);
}, [project, playhead, playing]);
+ /**
+ * Every title live at the playhead, bottom track first.
+ *
+ * All of them, not just the top one: titles stack, and a lower third plus a
+ * name card is a normal thing to want on screen at once. Order follows track
+ * order so the compositing matches what the timeline shows.
+ */
+ const textOverlays = useMemo<TextOverlay[]>(() => {
+ const depth = (trackId: string) => project.tracks.findIndex((track) => track.id === trackId);
+
+ return clipsAt(project, playhead)
+ .filter((clip) => clip.kind === "text" && clip.text !== undefined)
+ .filter((clip) => findTrack(project, clip.trackId)?.visible !== false)
+ .sort((a, b) => depth(a.trackId) - depth(b.trackId))
+ .map((clip) => ({
+ clipId: clip.id,
+ style: clip.text!,
+ offsetX: clip.offsetX,
+ offsetY: clip.offsetY,
+ }));
+ }, [project, playhead]);
+
// The top-most video clip under the playhead is what the monitor shows.
const previewSource = useMemo<PreviewSource | null>(() => {
// Stills are picture too, so they compete for the monitor with footage.
- const active = clipsAt(project, playhead).filter((clip) => clip.kind !== "audio");
+ // Titles do not: they are drawn *over* whatever is showing, so they are
+ // handled as overlays below rather than as a source.
+ const active = clipsAt(project, playhead).filter(
+ (clip) => clip.kind !== "audio" && clip.kind !== "text",
+ );
if (active.length === 0) return null;
const depth = (trackId: string) => project.tracks.findIndex((track) => track.id === trackId);
@@ -726,6 +851,7 @@ function Editor({
busy={busy}
error={error}
onFilter={setBinFilter}
+ onAddText={addText}
onSelect={(id) => {
setSelectedMediaId(id);
setSelectedClipIds([]);
@@ -754,6 +880,7 @@ function Editor({
<div className="min-w-0 flex-1">
<Preview
source={previewSource}
+ overlays={textOverlays}
playing={playing}
playhead={playhead}
duration={duration}
@@ -777,7 +904,10 @@ function Editor({
onTab={setRightTab}
clip={selectedClip}
media={inspectorMedia}
+ project={project}
frameRate={frameRate}
+ onAddFont={() => void pickFont()}
+ onRemoveFont={(family) => setProject((current) => removeFont(current, family))}
rendering={selectedClipIds.some((id) => renderingClips.has(id))}
onChangeClip={(patch) => {
if (selectedClipIds.length !== 1) return;
diff --git a/desktop/src/components/Icon.tsx b/desktop/src/components/Icon.tsx
index de58aef3..4e5ef67a 100644
--- a/desktop/src/components/Icon.tsx
+++ b/desktop/src/components/Icon.tsx
@@ -119,6 +119,14 @@ const GLYPHS = {
<path d="m3 17 5-4 4 3 3-2 6 5" />
</>
),
+ // a serif capital T: the universal mark for type
+ type: (
+ <>
+ <path d="M4 6.5V5h16v1.5" />
+ <path d="M12 5v14" />
+ <path d="M8.5 19h7" />
+ </>
+ ),
// waveform bars
waveform: (
<>
diff --git a/desktop/src/components/MediaBin.tsx b/desktop/src/components/MediaBin.tsx
index a1643c35..f0e7ef5b 100644
--- a/desktop/src/components/MediaBin.tsx
+++ b/desktop/src/components/MediaBin.tsx
@@ -35,6 +35,7 @@ export function MediaBin({
busy,
error,
onFilter,
+ onAddText,
onSelect,
onImport,
onRemove,
@@ -54,6 +55,8 @@ export function MediaBin({
busy: boolean;
error: string | null;
onFilter: (filter: BinFilter) => void;
+ /** Puts a new title on the timeline at the playhead. */
+ onAddText: () => void;
onSelect: (id: string) => void;
onImport: (paths: string[]) => void;
onRemove: (id: string) => void;
@@ -130,6 +133,26 @@ export function MediaBin({
</span>
}
>
+ {/*
+ Above the filter, because it is an action rather than a view setting -
+ and because "add something" belongs at the top of a panel whose job is
+ supplying things to the timeline. Text is the one kind of content that
+ needs no file, so this is the only way to create it.
+ */}
+ <div className="px-2 pt-2">
+ <button
+ type="button"
+ onClick={onAddText}
+ title="Add a title to the timeline"
+ className="flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg
+ bg-accent px-3 py-2 text-xs font-medium text-on-accent transition-opacity
+ hover:opacity-90"
+ >
+ <Icon name="type" size={13} />
+ Add text
+ </button>
+ </div>
+
<div className="px-2 pb-2 pt-2">
<Menu
groups={[
diff --git a/desktop/src/components/Preview.tsx b/desktop/src/components/Preview.tsx
index b67ce9b4..31fa71df 100644
--- a/desktop/src/components/Preview.tsx
+++ b/desktop/src/components/Preview.tsx
@@ -1,8 +1,9 @@
-import { useEffect, useRef } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { convertFileSrc } from "@tauri-apps/api/core";
import { connectElement } from "../lib/audio";
import { timecode } from "../lib/time";
+import { textCss, type TextStyle } from "../lib/text";
import { Icon, IconButton } from "./Icon";
import { PANEL_SHELL } from "./Panel";
@@ -19,6 +20,15 @@ export interface PreviewSource {
isStill: boolean;
}
+/** A title to draw over the picture, already positioned. */
+export interface TextOverlay {
+ clipId: string;
+ style: TextStyle;
+ /** Offset from centred, as a fraction of the frame. */
+ offsetX: number;
+ offsetY: number;
+}
+
/**
* The program monitor.
*
@@ -34,6 +44,7 @@ export interface PreviewSource {
*/
export function Preview({
source,
+ overlays,
playing,
playhead,
duration,
@@ -43,6 +54,8 @@ export function Preview({
onSeek,
}: {
source: PreviewSource | null;
+ /** Text clips live at the playhead, bottom-most first. */
+ overlays: TextOverlay[];
playing: boolean;
playhead: number;
duration: number;
@@ -54,6 +67,28 @@ export function Preview({
const video = useRef<HTMLVideoElement>(null);
const loadedClip = useRef<string | null>(null);
+ // Text is sized as a fraction of the frame, so drawing it needs the pixel
+ // height of the surface it lands on. That is a layout fact, not a prop, and
+ // it changes whenever the panel is resized - hence an observer rather than a
+ // one-off measurement.
+ const stage = useRef<HTMLDivElement>(null);
+ const [surface, setSurface] = useState({ width: 0, height: 0 });
+
+ useLayoutEffect(() => {
+ const element = stage.current;
+ if (!element) return;
+
+ const measure = () => {
+ const bounds = element.getBoundingClientRect();
+ setSurface({ width: bounds.width, height: bounds.height });
+ };
+
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, []);
+
// Swap the source only when the clip under the playhead actually changes.
// Reassigning `src` every frame would restart the decoder continuously.
useEffect(() => {
@@ -126,7 +161,7 @@ export function Preview({
that box, so it can never exceed the panel whatever its resolution.
*/}
<div className="min-h-0 min-w-0 flex-1 overflow-hidden bg-stage p-4">
- <div data-preview-surface className="relative h-full w-full">
+ <div ref={stage} data-preview-surface className="relative h-full w-full">
<video
ref={video}
playsInline
@@ -145,7 +180,37 @@ export function Preview({
className="absolute inset-0 h-full w-full object-contain"
/>
)}
- {!source && (
+ {/*
+ Titles sit above the picture and below the empty-state message.
+ `pointer-events-none` matters: the overlay covers the whole stage,
+ and without it the transport underneath would still be clickable
+ but the video would not.
+ */}
+ {surface.height > 0 &&
+ overlays.map((overlay) => (
+ <div
+ key={overlay.clipId}
+ className="pointer-events-none absolute inset-0 flex items-center justify-center"
+ >
+ <div
+ style={{
+ ...textCss(overlay.style, surface.height),
+ // Percentages here would resolve against the text block's
+ // own width, which varies with the words. The frame is the
+ // thing offsets are relative to, so they are converted
+ // against the measured surface instead.
+ transform: `translate(${overlay.offsetX * surface.width}px, ${
+ overlay.offsetY * surface.height
+ }px)`,
+ maxWidth: "92%",
+ }}
+ >
+ {overlay.style.content}
+ </div>
+ </div>
+ ))}
+
+ {!source && overlays.length === 0 && (
// No surface of its own: an empty monitor *is* black, and drawing
// a bordered card on top of it invents an edge that means nothing.
// Just the words, sitting on the stage.
diff --git a/desktop/src/components/RightPanel.tsx b/desktop/src/components/RightPanel.tsx
index b7c477c6..081a2e44 100644
--- a/desktop/src/components/RightPanel.tsx
+++ b/desktop/src/components/RightPanel.tsx
@@ -1,11 +1,12 @@
-import type { Clip, MediaItem } from "../lib/project";
+import type { Clip, MediaItem, Project } from "../lib/project";
import type { ClipFilter } from "../lib/filters";
import { AdjustPanel } from "./AdjustPanel";
import { FiltersPanel } from "./FiltersPanel";
import { Inspector } from "./Inspector";
import { Panel } from "./Panel";
+import { TextPanel } from "./TextPanel";
-export type RightTab = "details" | "adjust" | "filters";
+export type RightTab = "details" | "adjust" | "filters" | "text";
const TABS: { id: RightTab; label: string }[] = [
{ id: "details", label: "Details" },
@@ -13,6 +14,18 @@ const TABS: { id: RightTab; label: string }[] = [
{ id: "filters", label: "Filters" },
];
+/**
+ * Text replaces Adjust and Filters when a title is selected.
+ *
+ * A text clip has no volume, no speed and no audio filters, so offering those
+ * tabs would be offering three panels that can only say "nothing here". The
+ * tab strip therefore depends on what is selected rather than being fixed.
+ */
+const TEXT_TABS: { id: RightTab; label: string }[] = [
+ { id: "details", label: "Details" },
+ { id: "text", label: "Text" },
+];
+
/**
* The right-hand panel.
*
@@ -26,33 +39,47 @@ export function RightPanel({
onTab,
clip,
media,
+ project,
frameRate,
onChangeClip,
onSpeedChange,
+ onAddFont,
+ onRemoveFont,
rendering,
}: {
tab: RightTab;
onTab: (tab: RightTab) => void;
clip: Clip | null;
media: MediaItem | null;
+ project: Project;
frameRate: number;
onChangeClip: (patch: Partial<Clip>) => void;
onSpeedChange: (speed: number) => void;
+ onAddFont: () => void;
+ onRemoveFont: (family: string) => void;
/** True while the selected clip's filtered audio is being rendered. */
rendering: boolean;
}) {
+ const isText = clip?.kind === "text";
+ const tabs = isText ? TEXT_TABS : TABS;
+
+ // Selecting a title while sitting on Filters would otherwise leave the strip
+ // with nothing highlighted and the panel showing a tab that is no longer
+ // offered, so the selection falls back to one that exists.
+ const active = tabs.some((entry) => entry.id === tab) ? tab : "details";
+
return (
<Panel>
<div className="sticky top-0 z-10 border-b border-hairline bg-panel px-2 pb-2 pt-2">
<div className="flex rounded-lg bg-sunken p-0.5">
- {TABS.map((entry) => (
+ {tabs.map((entry) => (
<button
key={entry.id}
type="button"
- aria-pressed={tab === entry.id}
+ aria-pressed={active === entry.id}
onClick={() => onTab(entry.id)}
className={`flex-1 cursor-pointer rounded-[6px] px-2 py-1 text-[12px] transition-colors ${
- tab === entry.id
+ active === entry.id
? "bg-panel text-primary shadow-[0_1px_2px_rgba(0,0,0,0.14)]"
: "text-secondary hover:text-primary"
}`}
@@ -63,11 +90,20 @@ export function RightPanel({
</div>
</div>
- {tab === "details" && <Inspector clip={clip} media={media} frameRate={frameRate} />}
- {tab === "adjust" && (
+ {active === "details" && <Inspector clip={clip} media={media} frameRate={frameRate} />}
+ {active === "text" && (
+ <TextPanel
+ clip={clip}
+ project={project}
+ onChange={onChangeClip}
+ onAddFont={onAddFont}
+ onRemoveFont={onRemoveFont}
+ />
+ )}
+ {active === "adjust" && (
<AdjustPanel clip={clip} onChange={onChangeClip} onSpeedChange={onSpeedChange} />
)}
- {tab === "filters" && (
+ {active === "filters" && (
<FiltersPanel
clip={clip}
rendering={rendering}
diff --git a/desktop/src/components/TextPanel.tsx b/desktop/src/components/TextPanel.tsx
new file mode 100644
index 00000000..508bfa1d
--- /dev/null
+++ b/desktop/src/components/TextPanel.tsx
@@ -0,0 +1,347 @@
+import type { Clip, Project } from "../lib/project";
+import { FONTS, WEIGHTS, type CustomFont, type TextStyle } from "../lib/text";
+import { Group, Slider, Toggle } from "./controls";
+import { Icon } from "./Icon";
+import { Empty } from "./Panel";
+
+/**
+ * The Text tab: everything about how a title looks.
+ *
+ * Sizes are fractions of the frame rather than points, so a title composed
+ * against a 1080p project lands in the same place when the same project is
+ * exported at 4K. The panel converts for display - nobody thinks in "0.09 of
+ * the frame height" - but the stored value stays relative.
+ *
+ * The preview overlay and the export rasteriser both read these numbers
+ * through `textCss`, so what is on screen is what gets burned in.
+ */
+export function TextPanel({
+ clip,
+ project,
+ onChange,
+ onAddFont,
+ onRemoveFont,
+}: {
+ clip: Clip | null;
+ project: Project;
+ onChange: (patch: Partial<Clip>) => void;
+ onAddFont: () => void;
+ onRemoveFont: (family: string) => void;
+}) {
+ if (!clip || clip.kind !== "text" || !clip.text) {
+ return (
+ <Empty icon={<Icon name="type" size={26} strokeWidth={1.5} />}>
+ Select a text clip to style it.
+ </Empty>
+ );
+ }
+
+ const style = clip.text;
+
+ // Every edit rewrites the whole style, and the clip's name follows the first
+ // line so the timeline label tracks the words without a second control.
+ const set = (patch: Partial<TextStyle>) => {
+ const next = { ...style, ...patch };
+ onChange(
+ patch.content === undefined
+ ? { text: next }
+ : { text: next, name: firstLineOf(patch.content) },
+ );
+ };
+
+ const custom: CustomFont[] = project.fonts;
+
+ return (
+ <div className="px-3 py-3">
+ <Group title="Content">
+ <textarea
+ value={style.content}
+ onChange={(event) => set({ content: event.target.value })}
+ rows={3}
+ spellCheck={false}
+ placeholder="Your text"
+ className="mb-3 w-full resize-y rounded-lg border border-hairline-strong bg-sunken px-2.5
+ py-2 text-[13px] leading-snug text-primary outline-none
+ placeholder:text-tertiary focus:border-accent"
+ />
+ </Group>
+
+ <Group title="Font">
+ <select
+ value={style.fontFamily}
+ onChange={(event) => set({ fontFamily: event.target.value })}
+ className="mb-2 w-full cursor-pointer rounded-lg border border-hairline-strong bg-sunken
+ px-2.5 py-2 text-[12px] text-primary outline-none focus:border-accent"
+ >
+ <optgroup label="Bundled">
+ {FONTS.filter((font) => font.bundled).map((font) => (
+ <option key={font.value} value={font.value}>
+ {font.label}
+ </option>
+ ))}
+ </optgroup>
+ {custom.length > 0 && (
+ <optgroup label="Yours">
+ {custom.map((font) => (
+ <option key={font.family} value={`"${font.family}"`}>
+ {font.family}
+ {font.missing ? " (file missing)" : ""}
+ </option>
+ ))}
+ </optgroup>
+ )}
+ <optgroup label="System">
+ {FONTS.filter((font) => !font.bundled).map((font) => (
+ <option key={font.value} value={font.value}>
+ {font.label}
+ </option>
+ ))}
+ </optgroup>
+ </select>
+
+ <button
+ type="button"
+ onClick={onAddFont}
+ className="mb-3 flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg
+ border border-dashed border-hairline-strong px-3 py-2 text-[11px]
+ text-secondary transition-colors hover:border-accent hover:bg-hover
+ hover:text-primary"
+ >
+ <Icon name="import" size={12} />
+ Add font file
+ </button>
+
+ {custom.length > 0 && (
+ <ul className="mb-3 space-y-1">
+ {custom.map((font) => (
+ <li
+ key={font.family}
+ className="flex items-center gap-2 rounded-md px-2 py-1 text-[11px] hover:bg-hover"
+ >
+ <span
+ className="min-w-0 flex-1 truncate text-secondary"
+ style={{ fontFamily: `"${font.family}"` }}
+ title={font.path}
+ >
+ {font.family}
+ </span>
+ <button
+ type="button"
+ aria-label={`Remove ${font.family}`}
+ onClick={() => onRemoveFont(font.family)}
+ className="shrink-0 cursor-pointer text-tertiary hover:text-danger"
+ >
+ <Icon name="close" size={11} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <select
+ value={style.fontWeight}
+ onChange={(event) => set({ fontWeight: Number(event.target.value) })}
+ className="mb-3 w-full cursor-pointer rounded-lg border border-hairline-strong bg-sunken
+ px-2.5 py-2 text-[12px] text-primary outline-none focus:border-accent"
+ >
+ {WEIGHTS.map((weight) => (
+ <option key={weight.value} value={weight.value}>
+ {weight.label}
+ </option>
+ ))}
+ </select>
+
+ <Slider
+ label="Size"
+ value={style.fontSize}
+ min={0.02}
+ max={0.4}
+ step={0.005}
+ // Shown as a share of frame height, which is the thing it actually
+ // is. Points would be a lie: the frame can be any resolution.
+ format={(value) => `${(value * 100).toFixed(1)}% of height`}
+ onChange={(fontSize) => set({ fontSize })}
+ onReset={() => set({ fontSize: 0.09 })}
+ />
+
+ <Toggle label="Italic" checked={style.italic} onChange={(italic) => set({ italic })} />
+ </Group>
+
+ <Group title="Colour">
+ <Swatch label="Fill" value={style.color} onChange={(color) => set({ color })} />
+
+ <Slider
+ label="Opacity"
+ value={style.opacity}
+ min={0}
+ max={1}
+ format={(value) => `${Math.round(value * 100)}%`}
+ onChange={(opacity) => set({ opacity })}
+ onReset={() => set({ opacity: 1 })}
+ />
+
+ <Toggle
+ label="Drop shadow"
+ hint="Keeps text readable over bright footage."
+ checked={style.shadow}
+ onChange={(shadow) => set({ shadow })}
+ />
+
+ <Toggle
+ label="Plate behind text"
+ hint="A solid block, for when a shadow is not enough."
+ checked={style.background !== ""}
+ onChange={(on) => set({ background: on ? "#000000" : "" })}
+ />
+ {style.background !== "" && (
+ <Swatch
+ label="Plate colour"
+ value={style.background}
+ onChange={(background) => set({ background })}
+ />
+ )}
+ </Group>
+
+ <Group title="Outline">
+ <Slider
+ label="Width"
+ value={style.strokeWidth}
+ min={0}
+ max={0.15}
+ step={0.005}
+ format={(value) => (value === 0 ? "none" : `${(value * 100).toFixed(1)}%`)}
+ onChange={(strokeWidth) => set({ strokeWidth })}
+ onReset={() => set({ strokeWidth: 0 })}
+ />
+ {style.strokeWidth > 0 && (
+ <Swatch
+ label="Outline colour"
+ value={style.strokeColor}
+ onChange={(strokeColor) => set({ strokeColor })}
+ />
+ )}
+ </Group>
+
+ <Group title="Layout">
+ <div className="mb-3 flex rounded-lg bg-sunken p-0.5">
+ {(["left", "center", "right"] as const).map((align) => (
+ <button
+ key={align}
+ type="button"
+ aria-pressed={style.align === align}
+ onClick={() => set({ align })}
+ className={`flex-1 cursor-pointer rounded-[6px] px-2 py-1 text-[11px] capitalize
+ transition-colors ${
+ style.align === align
+ ? "bg-panel text-primary shadow-[0_1px_2px_rgba(0,0,0,0.14)]"
+ : "text-secondary hover:text-primary"
+ }`}
+ >
+ {align}
+ </button>
+ ))}
+ </div>
+
+ <Slider
+ label="Line height"
+ value={style.lineHeight}
+ min={0.8}
+ max={2.5}
+ step={0.05}
+ format={(value) => value.toFixed(2)}
+ onChange={(lineHeight) => set({ lineHeight })}
+ onReset={() => set({ lineHeight: 1.2 })}
+ />
+
+ <Slider
+ label="Tracking"
+ value={style.tracking}
+ min={-0.1}
+ max={0.4}
+ step={0.005}
+ format={(value) => `${value >= 0 ? "+" : ""}${(value * 100).toFixed(1)}%`}
+ onChange={(tracking) => set({ tracking })}
+ onReset={() => set({ tracking: 0 })}
+ />
+ </Group>
+
+ <Group title="Position">
+ {/*
+ Offsets are fractions of the frame, and centred is zero - so the
+ reset on each is "put it back in the middle", and a title composed
+ here sits in the same place at any export resolution.
+ */}
+ <Slider
+ label="Horizontal"
+ value={clip.offsetX}
+ min={-0.5}
+ max={0.5}
+ step={0.005}
+ format={(value) =>
+ Math.abs(value) < 0.0025 ? "centred" : `${(value * 100).toFixed(1)}%`
+ }
+ onChange={(offsetX) => onChange({ offsetX })}
+ onReset={() => onChange({ offsetX: 0 })}
+ />
+ <Slider
+ label="Vertical"
+ value={clip.offsetY}
+ min={-0.5}
+ max={0.5}
+ step={0.005}
+ format={(value) =>
+ Math.abs(value) < 0.0025 ? "centred" : `${(value * 100).toFixed(1)}%`
+ }
+ onChange={(offsetY) => onChange({ offsetY })}
+ onReset={() => onChange({ offsetY: 0 })}
+ />
+ </Group>
+ </div>
+ );
+}
+
+/** A colour well plus its hex, because one of the two is always the faster way. */
+function Swatch({
+ label,
+ value,
+ onChange,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ return (
+ <div className="mb-3 flex items-center justify-between gap-3">
+ <span className="text-[12px] text-primary">{label}</span>
+ <span className="flex items-center gap-2">
+ <input
+ type="text"
+ value={value}
+ spellCheck={false}
+ onChange={(event) => {
+ const next = event.target.value;
+ // Only commit a complete colour: repainting on "#f" would flash
+ // the title black on the way to "#ff0000".
+ if (/^#[0-9a-f]{6}$/i.test(next) || /^#[0-9a-f]{3}$/i.test(next)) onChange(next);
+ }}
+ className="w-[76px] rounded-md border border-hairline-strong bg-sunken px-1.5 py-1
+ text-right font-technical text-[11px] text-secondary outline-none
+ focus:border-accent"
+ />
+ <input
+ type="color"
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ aria-label={label}
+ className="h-[26px] w-[34px] cursor-pointer rounded-md border border-hairline-strong
+ bg-transparent p-0.5"
+ />
+ </span>
+ </div>
+ );
+}
+
+function firstLineOf(content: string): string {
+ const line = content.split("\n").find((candidate) => candidate.trim() !== "");
+ return (line ?? "Text").trim().slice(0, 40) || "Text";
+}
diff --git a/desktop/src/lib/persist.ts b/desktop/src/lib/persist.ts
index ba326ba2..68b5bfba 100644
--- a/desktop/src/lib/persist.ts
+++ b/desktop/src/lib/persist.ts
@@ -11,7 +11,8 @@
*/
import type { ProjectSession } from "../components/StartScreen";
-import type { Clip, MediaItem, Project, Track } from "./project";
+import type { Clip, ClipKind, MediaItem, Project, Track } from "./project";
+import { defaultTextStyle, type CustomFont, type TextStyle } from "./text";
/** Bumped only when a change cannot be absorbed by defaulting. */
const DOCUMENT_VERSION = 1;
@@ -24,6 +25,7 @@ export interface ProjectDocument {
media: MediaItem[];
tracks: Track[];
clips: Clip[];
+ fonts: CustomFont[];
}
export function toDocument(session: ProjectSession, project: Project): ProjectDocument {
@@ -40,6 +42,7 @@ export function toDocument(session: ProjectSession, project: Project): ProjectDo
media: project.media,
tracks: project.tracks,
clips: project.clips,
+ fonts: project.fonts,
};
}
@@ -121,14 +124,26 @@ export function fromDocument(raw: unknown): Project | null {
// to play. Dropping it beats keeping a reference that resolves to
// nothing everywhere it is used.
if (typeof clip.trackId !== "string" || !known.has(clip.trackId)) return [];
- if (typeof clip.mediaId !== "string" || !mediaIds.has(clip.mediaId)) return [];
- const kind = clip.kind === "audio" || clip.kind === "image" ? clip.kind : "video";
+ // A text clip is its own content, so it has no media to resolve. Only
+ // the kinds that come from the bin are dropped when their source is
+ // gone - applying that rule to titles would delete every one of them
+ // on reload, because an empty id is never in the media set.
+ const isText = clip.kind === "text";
+ if (!isText && (typeof clip.mediaId !== "string" || !mediaIds.has(clip.mediaId))) {
+ return [];
+ }
+
+ const kind: ClipKind = isText
+ ? "text"
+ : clip.kind === "audio" || clip.kind === "image"
+ ? clip.kind
+ : "video";
return [
{
id: clip.id,
trackId: clip.trackId,
- mediaId: clip.mediaId,
+ mediaId: isText ? "" : (clip.mediaId as string),
name: text(clip.name, "clip"),
kind,
start: Math.max(0, number(clip.start, 0)),
@@ -158,13 +173,56 @@ export function fromDocument(raw: unknown): Project | null {
];
})
: [],
+ ...(isText ? { text: readTextStyle(clip.text) } : {}),
},
];
})
: [];
+ const fonts: CustomFont[] = Array.isArray(document.fonts)
+ ? document.fonts.flatMap((entry) => {
+ if (typeof entry !== "object" || entry === null) return [];
+ const font = entry as Record<string, unknown>;
+ if (typeof font.family !== "string" || typeof font.path !== "string") return [];
+ return [{ family: font.family, path: font.path }];
+ })
+ : [];
+
// A file with no tracks at all is not something to open silently as empty.
if (tracks.length === 0) return null;
- return { media, tracks, clips };
+ return { media, tracks, clips, fonts };
+}
+
+/**
+ * Rebuilds a text style, defaulting every field.
+ *
+ * Same tolerance as the rest of this module: a title saved before a styling
+ * option existed opens with that option at its default rather than
+ * `undefined`, which would otherwise reach the CSS and render as nothing.
+ */
+function readTextStyle(raw: unknown): TextStyle {
+ const base = defaultTextStyle();
+ if (typeof raw !== "object" || raw === null) return base;
+ const style = raw as Record<string, unknown>;
+
+ const align = style.align;
+ return {
+ content: text(style.content, base.content),
+ fontFamily: text(style.fontFamily, base.fontFamily),
+ // Clamped, not just defaulted: a hand-edited 0 would render an invisible
+ // title, and a 10 would be one letter filling the frame.
+ fontSize: Math.min(1, Math.max(0.01, number(style.fontSize, base.fontSize))),
+ fontWeight: Math.min(900, Math.max(100, number(style.fontWeight, base.fontWeight))),
+ italic: flag(style.italic, base.italic),
+ color: text(style.color, base.color),
+ align: align === "left" || align === "center" || align === "right" ? align : base.align,
+ opacity: Math.min(1, Math.max(0, number(style.opacity, base.opacity))),
+ strokeWidth: Math.max(0, number(style.strokeWidth, base.strokeWidth)),
+ strokeColor: text(style.strokeColor, base.strokeColor),
+ shadow: flag(style.shadow, base.shadow),
+ background: text(style.background, base.background),
+ lineHeight: Math.max(0.5, number(style.lineHeight, base.lineHeight)),
+ tracking: number(style.tracking, base.tracking),
+ };
}
diff --git a/desktop/src/lib/project.ts b/desktop/src/lib/project.ts
index aa6a8f92..5ffb8abf 100644
--- a/desktop/src/lib/project.ts
+++ b/desktop/src/lib/project.ts
@@ -22,6 +22,7 @@
import type { MediaSummary } from "./engine";
import type { ClipFilter } from "./filters";
+import { defaultTextStyle, type CustomFont, type TextStyle } from "./text";
/**
* What a piece of media is.
@@ -37,6 +38,16 @@ export type MediaKind = "video" | "audio" | "image";
/** Kept as an alias so existing call sites read naturally. */
export type TrackKind = MediaKind;
+/**
+ * What a clip can be.
+ *
+ * Wider than `MediaKind` because a text clip has no file behind it - it *is*
+ * its own content. That is the whole reason for the distinction: everything in
+ * the bin is a `MediaKind`, but not everything on the timeline came from the
+ * bin. A text clip carries `mediaId: ""` and a `text` style instead.
+ */
+export type ClipKind = MediaKind | "text";
+
export interface MediaItem {
id: string;
path: string;
@@ -77,8 +88,9 @@ export interface Clip {
id: string;
trackId: string;
mediaId: string;
+ /** Empty for a text clip, which has no file behind it. */
name: string;
- kind: TrackKind;
+ kind: ClipKind;
/** Seconds from the start of the timeline. */
start: number;
duration: number;
@@ -134,12 +146,29 @@ export interface Clip {
* limiter is a different sound from the reverse.
*/
filters: ClipFilter[];
+
+ /**
+ * The overlay, when this is a text clip. Absent on every other kind.
+ *
+ * On the clip rather than in the bin because two titles are two different
+ * pieces of content even when they share a face - there is no shared source
+ * to point at, so there is nothing to put in the bin.
+ */
+ text?: TextStyle;
}
export interface Project {
media: MediaItem[];
tracks: Track[];
clips: Clip[];
+ /**
+ * Font files the user added, by path.
+ *
+ * On the project rather than in app settings because a title's face is part
+ * of the edit: opening the project has to bring the font back with it, or
+ * the composition silently changes.
+ */
+ fonts: CustomFont[];
}
/** Fallback length for media whose container reports no duration. */
@@ -155,6 +184,7 @@ const nextId = (prefix: string) => `${prefix}${(counter += 1)}`;
export function createProject(): Project {
return {
media: [],
+ fonts: [],
// Bottom-most first, matching the engine's compositing order, so track 1
// sits at the bottom of the screen the way it does in every other editor.
tracks: [1, 2, 3, 4].map((number) => ({
@@ -258,6 +288,78 @@ export function addClip(
return { project: { ...project, clips: [...project.clips, clip] }, clipId: clip.id };
}
+/** How long a title lasts when first placed. Editorial default, not a fact. */
+export const DEFAULT_TEXT_DURATION = 4;
+
+/**
+ * Puts a title on the timeline.
+ *
+ * Unlike `addClip` this needs no media, which is the entire point: a text clip
+ * carries its own content, so there is nothing to import first. It still takes
+ * a track and a start so it behaves like any other clip once placed - it can
+ * be moved, trimmed, split and stacked with no special cases downstream.
+ */
+export function addTextClip(
+ project: Project,
+ { trackId, start, style }: { trackId: string; start: number; style?: Partial<TextStyle> },
+): { project: Project; clipId: string | null } {
+ const track = findTrack(project, trackId);
+ if (!track) return { project, clipId: null };
+
+ const text: TextStyle = { ...defaultTextStyle(), ...style };
+
+ const clip: Clip = {
+ id: nextId("c"),
+ trackId,
+ // No media to point at. Every consumer keys off `kind` rather than
+ // probing this, so an empty id is never dereferenced.
+ mediaId: "",
+ // The name follows the words, so the timeline reads like the title looks.
+ // It is snapshotted rather than derived so that renaming the clip and
+ // editing the text stay independent.
+ name: firstLine(text.content),
+ kind: "text",
+ start: Math.max(0, start),
+ duration: DEFAULT_TEXT_DURATION,
+ sourceStart: 0,
+ volume: 1,
+ fadeIn: 0,
+ fadeOut: 0,
+ scale: 1,
+ offsetX: 0,
+ offsetY: 0,
+ speed: 1,
+ preservePitch: true,
+ filters: [],
+ text,
+ };
+
+ return { project: { ...project, clips: [...project.clips, clip] }, clipId: clip.id };
+}
+
+/** A one-line label for a block of text, for the timeline and the bin. */
+export function firstLine(content: string): string {
+ const line = content.split("\n").find((candidate) => candidate.trim() !== "");
+ return (line ?? "Text").trim().slice(0, 40) || "Text";
+}
+
+/** Registers a font file against the project, ignoring one already added. */
+export function addFont(project: Project, font: CustomFont): Project {
+ if (project.fonts.some((existing) => existing.path === font.path)) return project;
+ return { ...project, fonts: [...project.fonts, font] };
+}
+
+/**
+ * Forgets a font.
+ *
+ * Clips already using it keep the family name: the face may come back when the
+ * file does, and silently rewriting a title's styling because a list entry was
+ * removed would be a worse surprise than a temporary fallback.
+ */
+export function removeFont(project: Project, family: string): Project {
+ return { ...project, fonts: project.fonts.filter((font) => font.family !== family) };
+}
+
/** Moves a clip in time, and optionally to another track of the same kind. */
export function moveClip(
project: Project,
diff --git a/desktop/src/lib/text.ts b/desktop/src/lib/text.ts
index 0b02ba2b..16109070 100644
--- a/desktop/src/lib/text.ts
+++ b/desktop/src/lib/text.ts
@@ -56,6 +56,71 @@ export const FONTS: { label: string; value: string; bundled: boolean }[] = [
{ label: "Comic Sans", value: '"Comic Sans MS", cursive', bundled: false },
];
+/**
+ * A font the user added from disk.
+ *
+ * The path is what gets saved, not the bytes: a project file that embedded
+ * every face would grow without limit, and the same font on the same machine
+ * is the overwhelmingly common case. Reopening a project on a machine that
+ * lacks the file falls back to the default face rather than failing to open,
+ * which is why `missing` is tracked rather than thrown.
+ */
+export interface CustomFont {
+ /** The CSS family name, derived from the file name and made unique. */
+ family: string;
+ path: string;
+ /** True once a load attempt has failed - shown in the picker, not fatal. */
+ missing?: boolean;
+}
+
+/** Families already handed to the document, so reopening does not re-register. */
+const registered = new Set<string>();
+
+/**
+ * Turns a font file into a usable CSS family.
+ *
+ * `FontFace` accepts the raw bytes, so this works for any face the webview can
+ * parse - ttf, otf, woff, woff2 - without installing anything system-wide.
+ * Registration is idempotent: the same family loaded twice is a no-op, which
+ * matters because opening a project re-runs this for every font it names.
+ */
+export async function registerFont(
+ font: CustomFont,
+ read: (path: string) => Promise<ArrayBuffer>,
+): Promise<boolean> {
+ if (registered.has(font.family)) return true;
+
+ try {
+ const face = new FontFace(font.family, await read(font.path));
+ await face.load();
+ document.fonts.add(face);
+ registered.add(font.family);
+ return true;
+ } catch {
+ // A missing or unparseable file must not stop a project opening. The
+ // picker shows the face as unavailable and text falls back to the default.
+ return false;
+ }
+}
+
+/**
+ * A family name for a font file: its own name, made unique against what is
+ * already loaded.
+ *
+ * Two different files called `Regular.otf` in different folders would
+ * otherwise collide, and the second would silently render as the first.
+ */
+export function familyForPath(path: string, taken: readonly string[]): string {
+ const base = (path.split(/[\\/]/).pop() ?? path).replace(/\.[a-z0-9]+$/i, "");
+ const cleaned = base.replace(/[^\w\s-]/g, "").trim() || "Custom font";
+
+ if (!taken.includes(cleaned)) return cleaned;
+ for (let n = 2; ; n += 1) {
+ const candidate = `${cleaned} ${n}`;
+ if (!taken.includes(candidate)) return candidate;
+ }
+}
+
export const WEIGHTS: { label: string; value: number }[] = [
{ label: "Light", value: 300 },
{ label: "Regular", value: 400 },