Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Skills installed and kept on or off, projects and tabs in step, playback settings and component properties (#145)

riverisbuildingf6b1df146ee5
diff --git a/.changeset/component-properties.md b/.changeset/component-properties.md
new file mode 100644
index 0000000..2948b7e
--- /dev/null
+++ b/.changeset/component-properties.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Page clips have component properties. Select a layer and click ◇ beside its words, its picture or its appearance to make it a property; the clip's Properties section lists only those, each renamed with a double-click, filled in for this clip, and reset on its own or all at once. Variables of the page can be added from the section's +. A clip added to Saved keeps its properties and shows as a component, and every clip taken from it offers them. The Template section that listed everything a page holds is gone.
diff --git a/.changeset/export-button-and-outlines.md b/.changeset/export-button-and-outlines.md
new file mode 100644
index 0000000..2072631
--- /dev/null
+++ b/.changeset/export-button-and-outlines.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Studio: Export in the top bar is a button that says Export. A chosen project's outline shows whole, never cut by the edge of the list. Settings › Keyboard shortcuts lists the keys without a panel behind them.
diff --git a/.changeset/folder-tree-picker.md b/.changeset/folder-tree-picker.md
new file mode 100644
index 0000000..3fee574
--- /dev/null
+++ b/.changeset/folder-tree-picker.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Moving a project now opens a folder tree that shows where everything is. Folders can be moved too, with everything they hold.
diff --git a/.changeset/move-to-folder-picker.md b/.changeset/move-to-folder-picker.md
new file mode 100644
index 0000000..de6351a
--- /dev/null
+++ b/.changeset/move-to-folder-picker.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Projects: "Move to folder" says where the project goes. Its title is "Move “name” to"; the first place is the project list itself, not in a folder; each folder says how many projects it holds, and the one the project is in now says "Here now". A new folder is named in the field at the bottom, and Create and move (or Enter) puts the project in it.
diff --git a/.changeset/project-delete-settles.md b/.changeset/project-delete-settles.md
new file mode 100644
index 0000000..6402e2c
--- /dev/null
+++ b/.changeset/project-delete-settles.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Studio: deleting projects, the open one among them, no longer says "Delete failed" and puts them back when they were deleted: the list is read again, and only a project still there comes back. The top bar's Export is an icon again.
diff --git a/.changeset/replace-pictures-on-picture.md b/.changeset/replace-pictures-on-picture.md
new file mode 100644
index 0000000..2eb8cd3
--- /dev/null
+++ b/.changeset/replace-pictures-on-picture.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+A picture inside a page can be replaced right on the picture: Replace picture on its bar and its menu, or drop a picture from the media pane onto it. A frame holding one photo replaces the photo. A layer's inspector has a Picture section with its thumbnail.
diff --git a/.changeset/saved-pages-play.md b/.changeset/saved-pages-play.md
new file mode 100644
index 0000000..907f817
--- /dev/null
+++ b/.changeset/saved-pages-play.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+A page clip with a size of its own (a portrait scene in a landscape film) is drawn laid out at that size in its thumbnails and in its picture in Saved, as the film shows it. A page saved to Saved now plays in the viewer, at its clip's size and with the changes made in it, instead of showing a still.
diff --git a/.changeset/skills-kept-on.md b/.changeset/skills-kept-on.md
deleted file mode 100644
index 9cca0bf..0000000
--- a/.changeset/skills-kept-on.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@openfilm/desktop": patch
----
-
-The chat can keep skills on in a project: the pin on a skill's pill in the message keeps it for every message, so it no longer has to be put in each one. Kept-on skills show above the message box, where × turns one off. Each conversation gives an agent a kept-on skill once, with its next message; they are saved with the project's chat.
diff --git a/.changeset/skills-on-off.md b/.changeset/skills-on-off.md
new file mode 100644
index 0000000..9f59afa
--- /dev/null
+++ b/.changeset/skills-on-off.md
@@ -0,0 +1,6 @@
+---
+"openfilm": patch
+"@openfilm/desktop": patch
+---
+
+Skills are installed, then kept on or off. Installed lists yours first, then the OpenFilm skills you installed, this project's, and your agent's own (off until you turn one on). Each has a switch: on, an agent takes it up whenever it fits; off, no agent gets it. Discover is OpenFilm's catalog: install one to use it. A skill opens as a page with its preview, what it does, a switch, Uninstall (or Move to trash for your own), and Try now, which starts a new conversation with the skill named. `openfilm skills` lists the same skills agents get. A skill named in a message is for that message only; its instructions go to the agent once per conversation, unseen in the chat.
diff --git a/.changeset/speed-keeps-pitch.md b/.changeset/speed-keeps-pitch.md
new file mode 100644
index 0000000..f742f65
--- /dev/null
+++ b/.changeset/speed-keeps-pitch.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Sound played faster or slower in Studio keeps its pitch, at a clip's speed and at the viewer's playback speed, as it does in an export. Before, the preview sped sound up like a tape, so it was heard higher or lower.
diff --git a/.changeset/tabs-follow-projects.md b/.changeset/tabs-follow-projects.md
new file mode 100644
index 0000000..aae06d2
--- /dev/null
+++ b/.changeset/tabs-follow-projects.md
@@ -0,0 +1,6 @@
+---
+"openfilm": patch
+"@openfilm/desktop": patch
+---
+
+Projects and tabs keep in step. A project deleted (in the Projects window, another tab, by an agent) or whose folder is gone closes its tabs without asking, all of them together, and the front goes to a tab that stays; none of them comes back with Reopen Closed Tab. The Projects window never stays on "Creating project" or "Opening project", reads the list again whenever it is shown, and has the tabs in its top bar while any are open. Closing the last tab starts the next launch on the Projects window. Changes to the projects list made at the same moment (several deleted together, one made meanwhile) all hold, and a rename shows in its tab's title.
diff --git a/.changeset/viewer-playback-settings.md b/.changeset/viewer-playback-settings.md
new file mode 100644
index 0000000..a2891bc
--- /dev/null
+++ b/.changeset/viewer-playback-settings.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+The viewer's loop button is now a playback settings menu: loop, subtitles on the picture, and playback speed from 0.25× to 2×. The aspect ratio button under the picture is gone; the inspector's Stage menu has every shape, with Original at the top.
diff --git a/.github/workflows/agents.yml b/.github/workflows/agents.yml
index 81ecc3b..f3483e2 100644
--- a/.github/workflows/agents.yml
+++ b/.github/workflows/agents.yml
@@ -33,6 +33,14 @@ jobs:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
+ # setup-node puts node and npm's global programs on the job's PATH only. A person who installs with npm has them
+ # on their shell's PATH, and the app reads the login shell's: put them there, as nvm's installer does.
+ - name: Node on the login shell's PATH
+ if: runner.os == 'macOS'
+ run: |
+ line="export PATH=\"$(dirname "$(command -v node)"):\$PATH\""
+ echo "$line" >> ~/.zprofile
+ echo "$line" >> ~/.bash_profile
- name: The newest agents from npm
run: npm install -g @openai/codex@latest @anthropic-ai/claude-code@latest @github/copilot@latest opencode-ai@latest @qwen-code/qwen-code@latest @tencent-ai/codebuddy-code@latest
- name: Found, started and spoken to
diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsx
index e910574..d3ac77d 100644
--- a/apps/desktop/chat/src/App.tsx
+++ b/apps/desktop/chat/src/App.tsx
@@ -71,8 +71,8 @@ import { app, type FfmpegState, type Project, type SkillListing, type StudioRef,
import { Divider } from './components/Divider';
import { draftRefs, pillCard, refFromPill, refPill, sameStudioThing, selectionMoment, selectionRange, selectionRefs, studioReferencesText } from './studio-refs';
import { inChat } from './lib/chat-layer';
-import { chatSkillsOn, setChatSkillsOn, useProjectChat } from './lib/chat-store';
-import { sentAfter, skillsOnLine, skillsToSend } from './lib/skills-on';
+import { useProjectChat } from './lib/chat-store';
+import { givenAfter, pagesToSend } from './lib/skill-pages';
import { ChatProjectContext, WaitingContext } from './lib/developer';
const NO_ITEMS: TranscriptItem[] = [];
@@ -350,13 +350,6 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
setSkillRefs((list) => (list.some((p) => p.id === pill.id) ? list : [...list, pill]));
return pill;
}, [skillWords]);
- /* the skills kept on in this project (a skill pill's pin): every message's agent gets them (lib/skills-on) */
- const [skillsOn, setSkillsOn] = React.useState<string[]>(() => chatSkillsOn(projectKey));
- const keepSkillsOn = React.useCallback((names: string[]) => { setSkillsOn(names); setChatSkillsOn(projectKey, names); }, [projectKey]);
- const pinSkill = React.useCallback((pill: PromptReference) => {
- const name = skillReferencePackage(pill.id);
- if (name && !skillsOn.includes(name)) keepSkillsOn([...skillsOn, name]);
- }, [skillsOn, keepSkillsOn]);
const pickSkill = React.useCallback((skill: PickedSkill) => {
const pill = skillPill(skill);
requestAnimationFrame(() => { composerRef.current?.insertReference(pill); composerRef.current?.focus(); });
@@ -366,12 +359,16 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
...(skillListing?.openfilm ?? []),
...(skillListing?.own.skills ?? []).filter((s) => !skillListing?.own.filtered || s.allowed),
], [skillListing]);
- /* a skill picked in the examples (Studio's, over the film): named in the message; "Add a skill" there: its dialog */
- React.useEffect(() => app.onUseSkill?.((skill) => pickSkill(skill)), [pickSkill]);
- /* a skill added from the examples (AddSkillDialog, at the chat's root): the list read again; "make one with the
- agent" there: its message put in the composer */
+ /* a skill picked in Studio's skills: named in the message; Try now there: in a new conversation */
+ const newConversation = React.useRef<() => void>(() => {});
+ React.useEffect(() => app.onUseSkill?.((skill) => {
+ if (skill.newConversation) newConversation.current();
+ pickSkill(skill);
+ }), [pickSkill]);
+ /* a skill added from the examples (AddSkillDialog, at the chat's root), or turned on or off in them: the list read
+ again, and the agents' sessions take it up; "make one with the agent" there: its message put in the composer */
React.useEffect(() => {
- const changed = () => { void reloadSkills(); };
+ const changed = () => { void reloadSkills(); void app.skills?.changed?.().catch(() => {}); };
const make = () => { composerRef.current?.setText(t('skills.makePrompt').replace('{folder}', skillListing?.mine ?? '')); composerRef.current?.focus(); };
window.addEventListener(SKILLS_CHANGED, changed);
window.addEventListener(MAKE_SKILL, make);
@@ -634,7 +631,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
* Send a turn to the agent: what it is sent (`prepared`: the text, and the pictures) may take a moment to make. It
* settles the turn the agent's run ends on: this one, or the last message sent into it while it ran (steerTurn).
*/
- function runTurn(opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[] }>): void {
+ function runTurn(opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[]; skills?: string[] }>): void {
const { turn, meta, prefs, ready } = opened;
const id = meta.turnId;
const finish = (lastTurnId: string | undefined, patch: Partial<Turn & TurnBalance>) => {
@@ -643,7 +640,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
};
/* the agent's own session of this conversation, gone on with (after a restart too); a new one is kept for next time */
const resume = sessions.find((s) => s.id === sessionId)?.agentSessions?.[agent] ?? null;
- const run = Promise.all([prepared, ready]).then(([{ text, images }]) => runLocalAgentTurn({
+ const run = Promise.all([prepared, ready]).then(([{ text, images, skills }]) => runLocalAgentTurn({
projectId: projectKey,
conversation: sessionId,
resume,
@@ -656,8 +653,13 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
meta,
onSessionInfo: (info) => {
useLocalAgents.getState().noteOptions(agent, info.configOptions);
- if (info.sessionId && info.sessionId !== resume) {
- touchSession(sessionId, (s) => ({ agentSessions: { ...s.agentSessions, [agent]: info.sessionId } }));
+ /* a session it could not take up again has none of the skills' pages from before: those of this message only */
+ const fresh = !info.resumed || info.sessionId !== resume;
+ if (info.sessionId && fresh) {
+ touchSession(sessionId, (s) => ({
+ agentSessions: { ...s.agentSessions, [agent]: info.sessionId },
+ skillsGiven: givenAfter(s.skillsGiven, agent, info.sessionId, skills ?? [], { fresh }),
+ }));
}
},
})).then(
@@ -680,16 +682,16 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
* (an agent that takes steering). It shows as a turn of its own, what the agent says from then on under it, and the
* running one is done. One that did not join (the turn ended meanwhile) is sent once that run ends.
*/
- function steerTurn(fromId: string, opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[] }>): void {
+ function steerTurn(fromId: string, opened: ReturnType<typeof openTurn>, prepared: Promise<{ text: string; images: PromptImage[]; skills?: string[] }>): void {
/* the agent's run going now (one at a time in a conversation): a message that did not join waits for it */
const run = [...runs.current.values()].at(-1) ?? Promise.resolve();
- void Promise.all([prepared, opened.ready]).then(async ([{ text, images }]) => {
+ void Promise.all([prepared, opened.ready]).then(async ([{ text, images, skills }]) => {
if (await steerLocalAgentTurn(fromId, opened.turn, text, images)) {
settlers.current.get(fromId)?.({ status: 'ready' });
return;
}
await run.catch(() => {});
- runTurn(opened, Promise.resolve({ text, images }));
+ runTurn(opened, Promise.resolve({ text, images, ...(skills ? { skills } : {}) }));
});
}
@@ -707,11 +709,10 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
used[index - 1] = ref;
return `[${index}: ${refPill(pillId, ref).label}]`;
}, (pillId) => { const name = skillReferencePackage(pillId); return name ? `skill “${name}”` : null; }).trim();
- /* the skills it names: each one's SKILL.md follows the message, for the agent to read; and those kept on that this
- conversation's agent has not had yet (lib/skills-on) */
- const skillNames = activatedSkillIds(followUpRefs);
- const usable = skillsOn.filter((name) => nameableSkills.some((s) => s.name === name));
- const keptOn = skillsToSend(usable, sessions.find((s) => s.id === sessionId)?.skillsSent, agent, skillNames);
+ /* the skills it names, for this message: each one's SKILL.md follows it, unseen in the chat, the first time this
+ conversation's agent session meets that skill (lib/skill-pages) */
+ const agentSession = sessions.find((s) => s.id === sessionId)?.agentSessions?.[agent] ?? null;
+ const skillNames = pagesToSend(activatedSkillIds(followUpRefs), sessions.find((s) => s.id === sessionId)?.skillsGiven, agent, agentSession);
if (!instruction) return;
const blocker = attachmentBlocker(composerFiles.files, t);
if (blocker) { setFollowUpError(blocker); return; }
@@ -726,13 +727,12 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
setSkillRefs([]);
const files = composerFiles.take();
const id = makeLocalAgentTurnId();
- const said = instruction + skillsOnLine(keptOn) + attachedText(files);
+ const said = instruction + attachedText(files);
const refs = used.filter(Boolean);
const stage = selection?.stage ?? null;
/* each reference's picture is kept in the project for the agent (the block names it), and sent to one that takes pictures */
- const pages = [...skillNames, ...keptOn];
- const skillTexts = pages.length ? (app.skills?.texts(project.path, agent, pages).catch(() => []) ?? Promise.resolve([])) : Promise.resolve([]);
- if (keptOn.length) touchSession(sessionId, (s) => ({ skillsSent: sentAfter(s.skillsSent, agent, keptOn) }));
+ const skillTexts = skillNames.length ? (app.skills?.texts(project.path, agent, skillNames).catch(() => []) ?? Promise.resolve([])) : Promise.resolve([]);
+ if (skillNames.length) touchSession(sessionId, (s) => ({ skillsGiven: givenAfter(s.skillsGiven, agent, agentSession, skillNames) }));
/* an example pointed at: its folder fetched now if it is not yet (the turn waits, as it waits for its reply) */
const withFolders = Promise.all(refs.map(async (ref) => (ref.kind === 'example' && !ref.folder
? { ...ref, folder: await app.exampleFolder?.(ref.id).catch(() => undefined) } : ref)));
@@ -741,6 +741,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
.then(async ([{ pictures, images }, skills]) => ({
text: said + studioReferencesText(ready, { stage, pictures }) + skills.map((s) => `\n\n${s.text}`).join(''),
images: [...images, ...await attachedPictures(files, PROMPT_PICTURES_MAX - images.length)],
+ skills: skills.map((s) => s.name),
})));
const opened = openTurn(id, instruction, promptDisplay ?? null, turnAttachments(files));
if (steer && asset) steerTurn(asset.id, opened, prepared);
@@ -755,6 +756,7 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
setSessionId(newSession().id);
composerRef.current?.focus();
};
+ newConversation.current = onNewSession;
const onSelectSession = (id: string) => { if (!active) setSessionId(id); };
const onRenameSession = async (title: string) => { touchSession(sessionId, () => ({ title })); };
const shownSessions = React.useMemo(
@@ -865,27 +867,6 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
</div>
)}
{openedFile ? <AttachmentPreview item={openedFile} onClose={() => setOpenedFile(null)} /> : null}
- {/* the skills kept on: every message goes with them; × turns one off */}
- {skillsOn.length ? (
- <div className="flex flex-wrap items-center gap-1.5 px-3.5 pt-2.5">
- <span className="text-[11.5px] text-[var(--text-faint)]">{t('skills.keptOn')}</span>
- {skillsOn.map((name) => {
- const words = skillWords(name, nameableSkills.find((s) => s.name === name)?.description);
- return (
- <span key={name} title={words.summary || words.title}
- className="inline-flex h-6 max-w-[220px] items-center gap-1 rounded-[6px] border border-[var(--border)] pl-1.5 pr-0.5 text-[12px] text-[var(--text)]">
- <Blocks size={12} className="shrink-0 text-[var(--text-muted)]" aria-hidden />
- <span className="min-w-0 truncate">{words.title}</span>
- <button type="button" aria-label={t('skills.turnOff').replace('{name}', words.title)} title={t('skills.turnOff').replace('{name}', words.title)}
- onClick={() => keepSkillsOn(skillsOn.filter((n) => n !== name))}
- className="flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
- <X size={10} />
- </button>
- </span>
- );
- })}
- </div>
- ) : null}
<div className="flex items-end gap-1 py-2.5 pl-3.5 pr-2">
<div className="min-w-0 flex-1">
<PromptEditor
@@ -899,8 +880,6 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
onTransferReferences={onTransferReferences}
revealLabel={t('library.revealReference')}
removeLabel={t('library.removeReference')}
- onPin={pinSkill}
- pinLabel={t('skills.keepOn')}
placeholder={t(blank ? 'project.composerPlaceholderBlank' : 'project.composerPlaceholder')}
minHeight={22}
maxHeight={158}
diff --git a/apps/desktop/chat/src/app-bridge.ts b/apps/desktop/chat/src/app-bridge.ts
index d87e79e..8442985 100644
--- a/apps/desktop/chat/src/app-bridge.ts
+++ b/apps/desktop/chat/src/app-bridge.ts
@@ -35,7 +35,8 @@ interface AppBridge {
/** the Community over the film; `open`: on that skill's or example's page */
showExamples?(open?: CommunityItem): void;
/** a skill picked in the examples, to be named in the message */
- onUseSkill?(listener: (skill: { name: string; description: string }) => void): () => void;
+ /** a skill picked or tried in Studio's skills: named in the message being written (`newConversation`: in a new one) */
+ onUseSkill?(listener: (skill: { name: string; description: string; newConversation?: boolean }) => void): () => void;
/** "Add a skill" in the examples */
onAddSkill?(listener: () => void): () => void;
/** name a skill in the message being written (as one picked in the examples) */
@@ -62,8 +63,8 @@ interface AppBridge {
setMenuOpen(open: boolean): void;
/** the project's chat record, in its folder: conversations and finished turns (.film/chat), each turn's log (.film/logs) */
chat: {
- load(project: string): Promise<{ sessions: unknown[]; last: string | null; skills?: unknown[]; turns: unknown[] }>;
- saveSessions(project: string, sessions: unknown[], last: string | null, skills?: string[]): Promise<unknown>;
+ load(project: string): Promise<{ sessions: unknown[]; last: string | null; turns: unknown[] }>;
+ saveSessions(project: string, sessions: unknown[], last: string | null): Promise<unknown>;
saveTurn(project: string, turn: unknown, items: unknown[]): Promise<unknown>;
/** `unless`: the sizes of the log already read; when it has not grown, `{ same: true }` */
log(project: string, turnId: string, unless?: { size: number; callsSize: number }): Promise<TurnLog | { same: true } | null>;
@@ -90,6 +91,8 @@ interface AppBridge {
texts(project: string, agent: string, names: string[]): Promise<Array<{ name: string; text: string }>>;
/** one of the agent's own skills let into OpenFilm, or not */
allow(agent: string, name: string, allowed: boolean): Promise<{ ok: boolean }>;
+ /** OpenFilm's skills changed (one added, or turned on or off): the agents' sessions take them up */
+ changed?(): Promise<unknown>;
/** a GitHub or GitLab address fetched to be looked at; then kept (`commit`) or let go (`discard`) */
preview(url: string): Promise<{ ok: true; id: string; skills: SkillPreview[] } | { ok: false; error: string }>;
/** a folder on this computer looked at where it is: one dropped (its path), or null: picked in the system's dialog
diff --git a/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx b/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx
index edd3e57..61b9e5f 100644
--- a/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx
+++ b/apps/desktop/chat/src/components/prompt-editor/PromptEditor.tsx
@@ -98,9 +98,6 @@ export interface PromptEditorProps {
onReveal?: (reference: PromptReference) => void;
revealLabel?: string;
removeLabel: string;
- /** A skill pill's pin: keep that skill on (for every message); without it, skill pills have none. */
- onPin?: (reference: PromptReference) => void;
- pinLabel?: string;
placeholder: string;
ariaLabel?: string;
minHeight: number;
@@ -137,8 +134,6 @@ export const PromptEditor = React.forwardRef<PromptEditorHandle, PromptEditorPro
onReveal,
revealLabel,
removeLabel,
- onPin,
- pinLabel,
placeholder,
ariaLabel,
minHeight,
@@ -163,11 +158,9 @@ export const PromptEditor = React.forwardRef<PromptEditorHandle, PromptEditorPro
...(onReveal ? { onReveal } : {}),
...(revealLabel ? { revealLabel } : {}),
...(describe ? { describe } : {}),
- ...(onPin ? { onPin } : {}),
- ...(pinLabel ? { pinLabel } : {}),
removeLabel,
}),
- [onReveal, removeLabel, revealLabel, describe, onPin, pinLabel],
+ [onReveal, removeLabel, revealLabel, describe],
);
const initialConfig = React.useMemo(
diff --git a/apps/desktop/chat/src/components/prompt-editor/PromptReferenceNode.tsx b/apps/desktop/chat/src/components/prompt-editor/PromptReferenceNode.tsx
index fc2cab0..c55887a 100644
--- a/apps/desktop/chat/src/components/prompt-editor/PromptReferenceNode.tsx
+++ b/apps/desktop/chat/src/components/prompt-editor/PromptReferenceNode.tsx
@@ -1,7 +1,7 @@
'use client';
import React from 'react';
-import { Pin, X } from 'lucide-react';
+import { X } from 'lucide-react';
import {
$getNodeByKey,
DecoratorNode,
@@ -102,9 +102,6 @@ interface PromptReferencePillHandlers {
onReveal?: (reference: PromptReference) => void;
revealLabel?: string;
removeLabel: string;
- /** A skill pill's pin: keep that skill on for every message. */
- onPin?: (reference: PromptReference) => void;
- pinLabel?: string;
/** What the hover card says. */
describe?: (reference: PromptReference) => PromptPillCard | null;
}
@@ -145,40 +142,22 @@ function PromptReferencePill({
} : {})}
{...(reveal && handlers?.revealLabel ? { title: `${reference.label} · ${handlers.revealLabel}` } : {})}
trailing={(
- <>
- {reference.kind === 'skill' && handlers?.onPin ? (
- <button
- type="button"
- aria-label={handlers.pinLabel}
- title={handlers.pinLabel}
- onMouseDown={(event) => event.preventDefault()}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- handlers.onPin?.(reference);
- }}
- className="flex h-[1.05em] w-[1.05em] shrink-0 items-center justify-center rounded-[4px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- <Pin size={10} />
- </button>
- ) : null}
- <button
- type="button"
- aria-label={handlers?.removeLabel}
- /* Keep focus in the editor on mouse down, so typing continues after removing. */
- onMouseDown={(event) => event.preventDefault()}
- onClick={(event) => {
- event.preventDefault();
- event.stopPropagation();
- editor.update(() => {
- $getNodeByKey(nodeKey)?.remove();
- });
- }}
- className="flex h-[1.05em] w-[1.05em] shrink-0 items-center justify-center rounded-[4px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- <X size={10} />
- </button>
- </>
+ <button
+ type="button"
+ aria-label={handlers?.removeLabel}
+ /* Keep focus in the editor on mouse down, so typing continues after removing. */
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ editor.update(() => {
+ $getNodeByKey(nodeKey)?.remove();
+ });
+ }}
+ className="flex h-[1.05em] w-[1.05em] shrink-0 items-center justify-center rounded-[4px] text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
+ >
+ <X size={10} />
+ </button>
)}
/>
);
diff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.ts
index 832a652..4d4d0e9 100644
--- a/apps/desktop/chat/src/i18n/locales/en-US.ts
+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts
@@ -273,9 +273,6 @@ export const enUS = {
/* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */
community: { button: 'Community', tooltip: 'Community: skills and examples' },
skills: {
- keepOn: 'Keep on for every message in this project',
- keptOn: 'Always on',
- turnOff: 'Turn off {name}',
chooseCover: 'Choose cover',
removeCover: 'Undo cover choice',
coverHint: 'Optional · PNG, JPEG or WebP, up to 5 MB. Keeps the original cover when left unchanged.',
diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.ts
index 9235afe..28f101f 100644
--- a/apps/desktop/chat/src/i18n/locales/es.ts
+++ b/apps/desktop/chat/src/i18n/locales/es.ts
@@ -273,9 +273,6 @@ export const es: Words = {
/* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */
community: { button: 'Comunidad', tooltip: 'Comunidad: skills y ejemplos' },
skills: {
- keepOn: 'Usar en todos los mensajes de este proyecto',
- keptOn: 'Siempre activas',
- turnOff: 'Desactivar {name}',
chooseCover: 'Elegir portada',
removeCover: 'Deshacer selección',
coverHint: 'Opcional · PNG, JPEG o WebP, hasta 5 MB. Sin cambios, se conserva la portada original.',
diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.ts
index 8a564c4..29a4b9b 100644
--- a/apps/desktop/chat/src/i18n/locales/ja.ts
+++ b/apps/desktop/chat/src/i18n/locales/ja.ts
@@ -273,9 +273,6 @@ export const ja: Words = {
/* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */
community: { button: 'コミュニティ', tooltip: 'コミュニティ:スキルとサンプル' },
skills: {
- keepOn: 'このプロジェクトのすべてのメッセージで使う',
- keptOn: '常に使用',
- turnOff: '{name} をオフにする',
chooseCover: 'カバーを選択',
removeCover: '選択を元に戻す',
coverHint: '任意 · PNG、JPEG、WebP、最大 5 MB。変更しなければ元のカバーを保持します。',
diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.ts
index 4aed049..1fcf152 100644
--- a/apps/desktop/chat/src/i18n/locales/ko.ts
+++ b/apps/desktop/chat/src/i18n/locales/ko.ts
@@ -273,9 +273,6 @@ export const ko: Words = {
/* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */
community: { button: '커뮤니티', tooltip: '커뮤니티: 스킬과 예시' },
skills: {
- keepOn: '이 프로젝트의 모든 메시지에 계속 사용',
- keptOn: '항상 사용',
- turnOff: '{name} 끄기',
chooseCover: '표지 선택',
removeCover: '표지 선택 취소',
coverHint: '선택 사항 · PNG, JPEG 또는 WebP, 최대 5 MB. 변경하지 않으면 원래 표지를 유지합니다.',
diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
index c63e9de..68e698d 100644
--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
@@ -273,9 +273,6 @@ export const zhCN: Words = {
/* the composer's button that opens the Community over the film: skills and examples (Studio's ExamplesGallery) */
community: { button: '社区', tooltip: '社区:Skill 和示例' },
skills: {
- keepOn: '在这个项目里常驻:每条消息都带上它',
- keptOn: '常驻',
- turnOff: '关闭 {name}',
chooseCover: '选择封面',
removeCover: '撤销封面选择',
coverHint: '可选 · PNG、JPEG 或 WebP,最大 5 MB。不选择则保留原封面。',
diff --git a/apps/desktop/chat/src/lib/chat-store.ts b/apps/desktop/chat/src/lib/chat-store.ts
index 1a04d1f..287c133 100644
--- a/apps/desktop/chat/src/lib/chat-store.ts
+++ b/apps/desktop/chat/src/lib/chat-store.ts
@@ -10,14 +10,14 @@ import type { ProjectSessionItem } from '@/lib/project-sessions';
import { app } from '../app-bridge';
export interface SavedTurn { turn: Turn; items: TranscriptItem[] }
-interface ProjectChat { sessions: ProjectSessionItem[]; last: string | null; skills: string[]; turns: SavedTurn[] }
+interface ProjectChat { sessions: ProjectSessionItem[]; last: string | null; turns: SavedTurn[] }
const projects = new Map<string, ProjectChat>();
const loading = new Map<string, Promise<void>>();
/** which project each folder's record was read for: a project deleted and another made in its folder (a new
* "Untitled" where the last one was) is not the same project, and does not get its chat */
const readFor = new Map<string, string>();
-const EMPTY: ProjectChat = { sessions: [], last: null, skills: [], turns: [] };
+const EMPTY: ProjectChat = { sessions: [], last: null, turns: [] };
/**
* Read the project's record from its folder (once a launch, and again when another project takes the folder); the
@@ -39,12 +39,11 @@ export function openProjectChat(project: string, id: string): Promise<void> {
projects.set(project, {
sessions: Array.isArray(chat?.sessions) ? chat.sessions as ProjectSessionItem[] : [],
last: typeof chat?.last === 'string' ? chat.last : null,
- skills: Array.isArray(chat?.skills) ? (chat.skills as unknown[]).filter((n): n is string => typeof n === 'string') : [],
turns: Array.isArray(chat?.turns) ? chat.turns as SavedTurn[] : [],
});
})
/* not readable (not one of Studio's projects yet, a folder gone): an empty record, written once it changes */
- .catch(() => { if (mine()) projects.set(project, { ...EMPTY, sessions: [], skills: [], turns: [] }); })
+ .catch(() => { if (mine()) projects.set(project, { ...EMPTY, sessions: [], turns: [] }); })
.finally(() => { loading.delete(key); });
loading.set(key, pending);
return pending;
@@ -52,7 +51,7 @@ export function openProjectChat(project: string, id: string): Promise<void> {
const record = (project: string): ProjectChat => {
let chat = projects.get(project);
- if (!chat) { chat = { ...EMPTY, sessions: [], skills: [], turns: [] }; projects.set(project, chat); }
+ if (!chat) { chat = { ...EMPTY, sessions: [], turns: [] }; projects.set(project, chat); }
return chat;
};
@@ -63,7 +62,7 @@ function writeSessions(project: string) {
sessionWrites.set(project, setTimeout(() => {
sessionWrites.delete(project);
const chat = record(project);
- void app.chat.saveSessions(project, chat.sessions, chat.last, chat.skills).catch(() => { /* written next time */ });
+ void app.chat.saveSessions(project, chat.sessions, chat.last).catch(() => { /* written next time */ });
}, 150));
}
@@ -81,13 +80,6 @@ export function setLastSession(project: string, id: string) {
writeSessions(project);
}
-/** The skills kept on in this project: each message's agent gets them without their pill (lib/skills-on). */
-export const chatSkillsOn = (project: string): string[] => record(project).skills;
-export function setChatSkillsOn(project: string, names: string[]) {
- record(project).skills = [...new Set(names)];
- writeSessions(project);
-}
-
export const chatTurns = (project: string): SavedTurn[] => record(project).turns;
export function putChatTurn(project: string, entry: SavedTurn) {
const chat = record(project);
diff --git a/apps/desktop/chat/src/lib/project-sessions.ts b/apps/desktop/chat/src/lib/project-sessions.ts
index 57952a1..8c1281f 100644
--- a/apps/desktop/chat/src/lib/project-sessions.ts
+++ b/apps/desktop/chat/src/lib/project-sessions.ts
@@ -1,3 +1,5 @@
+import type { SkillsGiven } from './skill-pages';
+
/**
* A project's sessions: their shape on the client, and how the session bar groups them by when they were last used.
*/
@@ -11,8 +13,8 @@ export interface ProjectSessionItem {
turns: number;
/** Each agent's own id of this conversation (by agent): its next turn goes on with it, after a restart too. */
agentSessions?: Record<string, string>;
- /** The skills kept on in the project that each agent has had in this conversation (lib/skills-on), by agent. */
- skillsSent?: Record<string, string[]>;
+ /** The skills whose SKILL.md each agent's session has had in this conversation (lib/skill-pages), by agent. */
+ skillsGiven?: SkillsGiven;
}
export type SessionRecencyKey = 'today' | 'yesterday' | 'week' | 'earlier';
diff --git a/apps/desktop/chat/src/lib/skill-pages.ts b/apps/desktop/chat/src/lib/skill-pages.ts
new file mode 100644
index 0000000..c0b797b
--- /dev/null
+++ b/apps/desktop/chat/src/lib/skill-pages.ts
@@ -0,0 +1,29 @@
+/**
+ * A skill named in a message (its pill) is for that message. Its SKILL.md goes to the agent with it, unseen in the
+ * chat, once per conversation: the agent keeps it in its own session from then on, so naming the skill again sends only
+ * its name. What each agent's session was given is kept with the conversation (`skillsGiven`, by agent); a session the
+ * agent could not take up again starts with nothing. Reads nothing, so `node --test` can use it.
+ */
+
+/** Per agent: its own session id (null before it has one) and the skills whose pages that session was given. */
+export type SkillsGiven = Record<string, { session: string | null; names: string[] }>;
+
+/** The skills named in this message whose pages go with it: those `agent`'s current `session` has not had. */
+export function pagesToSend(named: readonly string[], given: Readonly<SkillsGiven> | undefined, agent: string, session: string | null): string[] {
+ const had = given?.[agent];
+ const known = new Set(had && had.session === session ? had.names : []);
+ return [...new Set(named)].filter((name) => !known.has(name));
+}
+
+/**
+ * What `agent` has been given once a message goes with the pages of `sent`. `session`: its session the message went to;
+ * `fresh`: one just started that has nothing from before (the pages it holds are those of this message only).
+ */
+export function givenAfter(given: Readonly<SkillsGiven> | undefined, agent: string, session: string | null, sent: readonly string[], { fresh = false } = {}): SkillsGiven {
+ const out: SkillsGiven = {};
+ for (const [by, had] of Object.entries(given ?? {})) out[by] = { session: had.session, names: [...had.names] };
+ const had = out[agent];
+ const before = !fresh && had && had.session === session ? had.names : [];
+ out[agent] = { session, names: [...new Set([...before, ...sent])] };
+ return out;
+}
diff --git a/apps/desktop/chat/src/lib/skills-on.ts b/apps/desktop/chat/src/lib/skills-on.ts
deleted file mode 100644
index 863554c..0000000
--- a/apps/desktop/chat/src/lib/skills-on.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Skills kept on in a project (a skill pill's pin in the composer): every message's agent works with them, without
- * their pill. Each conversation gives an agent a skill's SKILL.md once, with the first message it
- * gets after the skill is on; the agent keeps it from then on. Reads nothing, so `node --test` can use it.
- */
-
-/**
- * The skills kept on that go with this message: those `agent` has not had in this conversation (`sent`, by agent),
- * and not named in the message already (`named`, whose pages go with it anyway).
- */
-export function skillsToSend(on: readonly string[], sent: Readonly<Record<string, readonly string[]>> | undefined, agent: string, named: readonly string[]): string[] {
- const had = new Set([...(sent?.[agent] ?? []), ...named]);
- return on.filter((name) => !had.has(name));
-}
-
-/** What the conversation has given `agent` once this message goes: the skills kept on that are with it now too. */
-export function sentAfter(sent: Readonly<Record<string, readonly string[]>> | undefined, agent: string, given: readonly string[]): Record<string, string[]> {
- const out: Record<string, string[]> = {};
- for (const [by, names] of Object.entries(sent ?? {})) out[by] = [...names];
- out[agent] = [...new Set([...(out[agent] ?? []), ...given])];
- return out;
-}
-
-/** The line the agent reads for them, before their pages: the skills, as a pill names one. */
-export function skillsOnLine(names: readonly string[]): string {
- return names.length ? `\n\nKept on in this project: ${names.map((name) => `skill “${name}”`).join(', ')}.` : '';
-}
diff --git a/apps/desktop/shell/bridge.ts b/apps/desktop/shell/bridge.ts
index 972d748..9161976 100644
--- a/apps/desktop/shell/bridge.ts
+++ b/apps/desktop/shell/bridge.ts
@@ -167,7 +167,7 @@ projectReady = follow();
const selection = signal<StudioSelection | null>(null);
const refer = events<StudioRef>();
/* a skill picked in the examples (Studio's ExamplesDialog), to be named in the message; and "Add a skill" there */
-const skillPicked = events<{ name: string; description: string }>();
+const skillPicked = events<{ name: string; description: string; newConversation?: boolean }>();
const skillAdd = events<void>();
/** what the pointer is over in Studio (null: nothing), for the chat to light its pills that point at it */
const hover = signal<StudioRef | null>(null);
@@ -378,7 +378,7 @@ function commandFor(ref: StudioRef): StudioCommand {
showExamples: (open?: CommunityItem) => command?.({ type: 'show-examples', ...(open ? { open } : {}) }),
onUseSkill: skillPicked.on,
onAddSkill: skillAdd.on,
- useSkill: (skill: { name: string; description: string }) => skillPicked.set(skill),
+ useSkill: (skill: { name: string; description: string; newConversation?: boolean }) => skillPicked.set(skill),
/* a reference made in the chat (⌘L there, the @ menu) gets its picture as Studio's own do */
withPicture: (ref: StudioRef) => { const done = pictured.then(() => withPicture(ref)); pictured = done.then(() => {}); return done; },
/* what a pill hovered in the chat points at, lit in Studio while it is (null: none); and the references of the
diff --git a/apps/desktop/src/agent-skills.mjs b/apps/desktop/src/agent-skills.mjs
index 8c02535..ea4e65b 100644
--- a/apps/desktop/src/agent-skills.mjs
+++ b/apps/desktop/src/agent-skills.mjs
@@ -242,13 +242,14 @@ function defaultsFile(dir, name, settings) {
* additionalDirectories?, env?, args?, piSkills?, log }` (agents.mjs puts each where it goes). `log`: what the turn log
* says of it (agents.mjs `opened.skills`). `allowed`, `mcpAllowed`: the person's own let in, by name.
* @param {string} agent
- * `mine`: the person's own skills folder (openfilm/skills mySkillsDir).
- * @param {{ cwd: string, env?: Record<string, string>, dataDir: string, mine?: string, allowed?: string[],
+ * `mine`: the person's own skills folder (openfilm/skills mySkillsDir); `prefsHome`: the Studio home whose prefs.json
+ * says which official skills are installed and which skills are off (openfilm/skills usableSkills).
+ * @param {{ cwd: string, env?: Record<string, string>, dataDir: string, mine?: string, prefsHome?: string, allowed?: string[],
* mcpAllowed?: string[], home?: string }} o
*/
-export async function sessionSkills(agent, { cwd, env = {}, dataDir, mine, allowed = [], mcpAllowed = [], home = homedir() }) {
- const { listSkills, mySkillsDir } = await skillsLib();
- const openfilm = listSkills({ project: cwd, mine: mine ?? mySkillsDir() });
+export async function sessionSkills(agent, { cwd, env = {}, dataDir, mine, prefsHome, allowed = [], mcpAllowed = [], home = homedir() }) {
+ const { mySkillsDir, usableSkills } = await skillsLib();
+ const openfilm = usableSkills({ project: cwd, mine: mine ?? mySkillsDir(), ...(prefsHome ? { home: prefsHome } : {}) });
const names = openfilm.map((s) => s.name);
const filtered = FILTERED_AGENTS.includes(agent);
const base = { openfilm: names, allowed: [...allowed], mcpAllowed: [...mcpAllowed], filtered, mcpFiltered: MCP_AGENTS.includes(agent) };
diff --git a/apps/desktop/src/agent-skills.test.mjs b/apps/desktop/src/agent-skills.test.mjs
index a177069..63f5ada 100644
--- a/apps/desktop/src/agent-skills.test.mjs
+++ b/apps/desktop/src/agent-skills.test.mjs
@@ -5,6 +5,10 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { codexServers, mergeConfig, ownMcpServers, ownSkills, sessionSkills, skillStore } from './agent-skills.mjs';
+/* which official skills are installed is read from Studio's prefs.json: a scratch home, never the person's */
+process.env.OPENFILM_HOME = mkdtempSync(join(tmpdir(), 'of-agent-skills-home-'));
+delete process.env.OPENFILM_SHARED_HOME;
+
const skill = (dir, name, description = `${name} skill`) => {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${description}\n---\n\nBody.\n`);
@@ -89,22 +93,37 @@ test("Codex: each of the person's own not let in turned off by its file, OpenFil
test("OpenCode: every skill denied but its own, OpenFilm's and those let in; Pi: OpenFilm's only; the others unfiltered", async () => {
const w = world();
- const oc = await sessionSkills('opencode', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), allowed: ['research'] });
+ mkdirSync(w.openfilmHome, { recursive: true });
+ writeFileSync(join(w.openfilmHome, 'prefs.json'), JSON.stringify({ skillsInstalled: [readdirSync(new URL('../../../packages/openfilm/skills/', import.meta.url), { withFileTypes: true }).find((e) => e.isDirectory()).name] }));
+ const oc = await sessionSkills('opencode', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), prefsHome: w.openfilmHome, allowed: ['research'] });
const config = JSON.parse(oc.env.OPENCODE_CONFIG_CONTENT);
- /* with the project's brand and lyric-pv: the official skills that come with the package */
+ /* the project's brand and lyric-pv; of the official skills that come with the package, only one installed */
const official = readdirSync(new URL('../../../packages/openfilm/skills/', import.meta.url), { withFileTypes: true }).filter((e) => e.isDirectory());
- const names = [...official.map((e) => e.name), 'brand', 'lyric-pv'].sort();
+ const names = [official[0].name, 'brand', 'lyric-pv'].sort();
assert.deepEqual(config.permission.skill, { '*': 'deny', 'customize-opencode': 'allow', ...Object.fromEntries([...names, 'research'].sort().map((n) => [n, 'allow'])) });
assert.deepEqual(config.mcp, { search: { enabled: false } });
assert.match(config.skills.paths[0], /agent-skills[\\/].+[\\/]skills$/);
- const pi = await sessionSkills('byok', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });
+ const pi = await sessionSkills('byok', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), prefsHome: w.openfilmHome });
assert.deepEqual(pi.piSkills.names, names);
- const kimi = await sessionSkills('kimi', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills') });
+ const kimi = await sessionSkills('kimi', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), prefsHome: w.openfilmHome });
assert.deepEqual(kimi.log, { openfilm: names, allowed: [], mcpAllowed: [], filtered: false, mcpFiltered: false });
/* a link (a junction on Windows) to the project's own folder */
assert.equal(realpathSync(join(pi.piSkills.paths[0], 'brand')), realpathSync(join(w.project, 'skills', 'brand')));
});
+test("an OpenFilm skill the person turned off is given to no session", async () => {
+ const w = world();
+ mkdirSync(w.openfilmHome, { recursive: true });
+ writeFileSync(join(w.openfilmHome, 'prefs.json'), JSON.stringify({ skillsOff: ['brand'] }));
+ const pi = await sessionSkills('byok', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), prefsHome: w.openfilmHome });
+ assert.ok(!pi.piSkills.names.includes('brand'));
+ assert.ok(pi.piSkills.names.includes('lyric-pv'));
+ assert.ok(!existsSync(join(pi.piSkills.paths[0], 'brand')), 'not in the folder the agent reads');
+ const codex = await sessionSkills('codex', { cwd: w.project, home: w.home, dataDir: w.dataDir, mine: join(w.openfilmHome, 'skills'), prefsHome: w.openfilmHome });
+ assert.ok(!existsSync(join(codex.additionalDirectories[0], '.agents', 'skills', 'brand')));
+ assert.ok(existsSync(join(codex.additionalDirectories[0], '.agents', 'skills', 'lyric-pv', 'SKILL.md')));
+});
+
test("OpenFilm's own skill for terminal agents is known, never offered, and always off in the app", async () => {
const w = world();
skill(join(w.home, '.claude', 'skills', 'openfilm'), 'openfilm', 'Make videos as web pages with OpenFilm.');
diff --git a/apps/desktop/src/chat-ipc.mjs b/apps/desktop/src/chat-ipc.mjs
index 5dfc67b..2db0606 100644
--- a/apps/desktop/src/chat-ipc.mjs
+++ b/apps/desktop/src/chat-ipc.mjs
@@ -81,7 +81,7 @@ export function registerChatIpc(ipcMain, { trusted, projects, dataDir, reveal, t
});
handle('desktop:chat:load', async ({ project: path }) => loadChat(await project(path)));
- handle('desktop:chat:sessions', async ({ project: path, sessions, last, skills }) => { saveSessions(await project(path), { sessions, last, skills }); return { ok: true }; });
+ handle('desktop:chat:sessions', async ({ project: path, sessions, last }) => { saveSessions(await project(path), { sessions, last }); return { ok: true }; });
handle('desktop:chat:turn', async ({ project: path, turn, items }) => { saveTurn(await project(path), { turn, items }); return { ok: true }; });
handle('desktop:chat:ref-image', async ({ project: path, turnId, n, bytes }) => saveRefImage(await project(path), turnId, n, bytes));
handle('desktop:chat:attachment', async ({ project: path, name, bytes }) => saveAttachment(await project(path), name, bytes));
diff --git a/apps/desktop/src/chat-store.mjs b/apps/desktop/src/chat-store.mjs
index 4e48522..7b2e221 100644
--- a/apps/desktop/src/chat-store.mjs
+++ b/apps/desktop/src/chat-store.mjs
@@ -73,20 +73,13 @@ export function loadChat(project) {
if (entry?.turn?.id && Array.isArray(entry.items)) turns.push(entry);
}
turns.sort((a, b) => String(a.turn.createdAt).localeCompare(String(b.turn.createdAt)));
- return { sessions, last: typeof kept.last === 'string' ? kept.last : null, skills: skillNames(kept.skills), turns };
+ return { sessions, last: typeof kept.last === 'string' ? kept.last : null, turns };
}
-/** The skills kept on in a project's chat: names only, each once. */
-const skillNames = (names) => [...new Set(Array.isArray(names) ? names.filter((n) => typeof n === 'string' && SKILL_NAME.test(n)) : [])];
-const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
-
-/** The conversations, the one shown last, and `skills`: the skills kept on for every message in this project. */
-export function saveSessions(project, { sessions, last, skills }) {
+export function saveSessions(project, { sessions, last }) {
const dir = chatDir(project);
mkdirSync(dir, { recursive: true });
- writeAtomic(join(dir, 'sessions.json'), `${JSON.stringify({
- version: 1, last: typeof last === 'string' ? last : null, skills: skillNames(skills), sessions: Array.isArray(sessions) ? sessions : [],
- }, null, 1)}\n`);
+ writeAtomic(join(dir, 'sessions.json'), `${JSON.stringify({ version: 1, last: typeof last === 'string' ? last : null, sessions: Array.isArray(sessions) ? sessions : [] }, null, 1)}\n`);
}
export function saveTurn(project, entry) {
diff --git a/apps/desktop/src/chat-store.test.mjs b/apps/desktop/src/chat-store.test.mjs
index 8efc337..b989156 100644
--- a/apps/desktop/src/chat-store.test.mjs
+++ b/apps/desktop/src/chat-store.test.mjs
@@ -20,7 +20,7 @@ const logOnDisk = (dir, id, lines = 1) => until(() => readLog(dir, id), (read) =
test('a project with no chat yet has none; what is saved comes back, the turns in the order they were asked', () => {
const dir = project();
- assert.deepEqual(loadChat(dir), { sessions: [], last: null, skills: [], turns: [] });
+ assert.deepEqual(loadChat(dir), { sessions: [], last: null, turns: [] });
saveSessions(dir, { sessions: [{ id: 's1', title: 'One', createdAt: '2026-10-07T00:00:00Z' }], last: 's1' });
saveTurn(dir, turn('t2', '2026-10-07T00:00:02Z'));
saveTurn(dir, turn('t1', '2026-10-07T00:00:01Z'));
@@ -32,14 +32,6 @@ test('a project with no chat yet has none; what is saved comes back, the turns i
assert.deepEqual(loadChat(dir).turns.find((t) => t.turn.id === 't1').items, [], 'a turn saved again replaces itself');
});
-test("the skills kept on in a project's chat are kept with its conversations: names only, each once", () => {
- const dir = project();
- saveSessions(dir, { sessions: [], last: null, skills: ['brand-voice', 'pace', 'brand-voice', '../x', 7, ''] });
- assert.deepEqual(loadChat(dir).skills, ['brand-voice', 'pace']);
- saveSessions(dir, { sessions: [], last: null });
- assert.deepEqual(loadChat(dir).skills, [], 'none given: none kept');
-});
-
test('a turn is written to its log as it happens and read back, a broken last line left out', async () => {
const dir = project();
const log = openLog(dir, 't1');
diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjs
index a89db4a..801b94e 100644
--- a/apps/desktop/src/local-agents-ipc.mjs
+++ b/apps/desktop/src/local-agents-ipc.mjs
@@ -449,12 +449,12 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
/** an agent disconnected in Settings: its sessions close */
closeAgent: (agent) => { for (const [key, entry] of [...sessions]) if (entry.agent === agent) close(key); },
/**
- * The skills or MCP servers let in changed for an agent: its sessions close (one at work once its turn ends), and the next message
- * takes each conversation up again with them.
+ * The skills or MCP servers let in changed for an agent (none named: for every agent): its sessions close (one at
+ * work once its turn ends), and the next message takes each conversation up again with them.
*/
refreshSkills: (agent) => {
for (const [key, entry] of [...sessions]) {
- if (entry.agent !== agent) continue;
+ if (agent && entry.agent !== agent) continue;
if (entry.running > 0) entry.stale = true; else close(key);
}
},
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index 0af7f64..fe03368 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -83,6 +83,8 @@ const broadcast = (channel, value) => { for (const v of views.values()) if (!v.w
const tabOf = (contents) => { for (const [id, v] of views) if (v.webContents === contents) return id; return null; };
/** a tab behind for this long lets its page go (it comes back when shown), unless an agent works in it or it exports */
const IDLE_PAGE_MS = 5 * 60_000;
+/** How long the tabs of projects gone are gathered before they close together (several pages told at once). */
+const GONE_TOGETHER_MS = 150;
/** @type {Awaited<ReturnType<typeof startWindowStudio>> | null} */
let studio = null;
let state = readWindowState(DATA);
@@ -200,7 +202,12 @@ function presentation() {
});
return { view: v, ready };
},
- present(_id, v) { if (win) revealPage(win.contentView, v, views.values()); },
+ present(_id, v) {
+ if (!win) return;
+ revealPage(win.contentView, v, views.values());
+ /* the pages now behind it are told: one waiting to be covered (its projects window opening another tab) is done */
+ for (const page of views.values()) if (page !== v && !page.webContents.isDestroyed()) page.webContents.send('desktop:tabs:covered');
+ },
discard: destroyView,
onError: (error) => { if (!quitting) log(`page: could not prepare replacement (${String(error.message).replace(/key=[^&\s)]+/g, 'key=…')})\n`); },
});
@@ -260,6 +267,29 @@ async function closeTab(id) {
else { showPage(HOME); tellTabs(); }
}
+/**
+ * Projects gone (deleted, here or elsewhere; their folders gone): their tabs close without asking, all those told within
+ * a moment together, so the front never lands on a tab about to close, and none can be opened again (tabs.mjs
+ * `closeProjects`). Each page of such a project says so, and the page that deleted them says which.
+ */
+const goneProjects = new Set();
+let goneTimer = /** @type {NodeJS.Timeout | null} */ (null);
+function projectsGone(/** @type {string[]} */ projectIds) {
+ for (const id of projectIds) if (typeof id === 'string' && id) goneProjects.add(id);
+ if (!goneTimer) goneTimer = setTimeout(closeGoneTabs, GONE_TOGETHER_MS);
+}
+function closeGoneTabs() {
+ goneTimer = null;
+ const ids = [...goneProjects];
+ goneProjects.clear();
+ if (!tabs || !win || !ids.length) return;
+ const { closed, front } = tabs.closeProjects(ids);
+ if (!closed.length) return;
+ for (const id of closed) presentation().retire(id);
+ if (front) showTab(front.id);
+ else { showPage(HOME); tellTabs(); }
+}
+
/**
* Studio's "open this project" (`openfilm open`, File › Open Project…), heard by every page at once: once only. Its
* tab comes to the front, opened if it is not.
@@ -273,14 +303,17 @@ function openInTabs(to) {
if (projectId) newTab(projectId);
}
-/** The tabs open when the window opens: those left last time, else the last project's; none: the projects. */
+/**
+ * The tabs open when the window opens: those left last time (none, when the last were closed: the projects), else, the
+ * first time, the last project's; none: the projects.
+ */
async function openTabs() {
const projects = (await studioApi('/api/projects').catch(() => ({ projects: [] }))).projects.filter((p) => !p.missing);
- tabs = createTabs({ saved: state.tabs?.tabs?.length ? state.tabs : null });
- /* a tab of a project no longer there is left out */
+ tabs = createTabs({ saved: state.tabs ?? null });
+ /* a tab of a project no longer there is left out, and not kept to open again */
const known = new Set(projects.map((p) => p.id));
- for (const t of tabs.list()) if (!known.has(t.projectId)) tabs.close(t.id);
- if (!tabs.list().length && !state.tabs?.tabs?.length && projects[0]) tabs.open({ projectId: projects[0].id, title: projects[0].name });
+ tabs.closeProjects(tabs.list().map((t) => t.projectId).filter((id) => !known.has(id)));
+ if (!tabs.list().length && !state.tabs && projects[0]) tabs.open({ projectId: projects[0].id, title: projects[0].name });
const front = tabs.activeId();
if (front) showTab(front);
else { showPage(HOME); tellTabs(); }
@@ -516,12 +549,17 @@ async function start() {
/* what a page shows now: its project's title, an export's progress; or its project gone */
tabHandle('desktop:tabs:report', (self, { title, exporting, gone }) => {
if (!tabs) return { ok: false };
- /* its project deleted (in this page or another): its tab closes */
- if (gone === true) { void closeTab(self); return { ok: true }; }
+ /* its project gone (deleted, in this page or another; its folder gone): its tab closes, without asking */
+ if (gone === true) { const tab = tabs.get(self); if (tab) projectsGone([tab.projectId]); return { ok: true }; }
tabs.report(self, { ...(typeof title === 'string' ? { title: title.slice(0, 200) } : {}), ...(exporting !== undefined ? { exporting: typeof exporting === 'number' ? exporting : null } : {}) });
tellTabs();
return { ok: true };
});
+ /* projects this page deleted: their tabs close together (projectsGone) */
+ tabHandle('desktop:tabs:gone', (_self, { projectIds }) => {
+ if (Array.isArray(projectIds)) projectsGone(projectIds.filter((id) => typeof id === 'string'));
+ return { ok: true };
+ });
/* another tab's project renamed from this page's tabs: its title, also while that tab has no page to say it */
tabHandle('desktop:tabs:retitle', (_self, { id, title }) => {
if (typeof title === 'string' && tabs?.report(String(id), { title: title.slice(0, 200) })) tellTabs();
@@ -534,6 +572,8 @@ async function start() {
/* the agents: Studio's home and library go with them, so the `openfilm` they run finds this window's Studio */
/* the person's own skills: Skills/ beside this app's projects (~/Movies/OpenFilm/Skills), as its `openfilm` finds them */
+ /* which official skills are installed and which skills are off: the prefs.json every OpenFilm here shares (openfilm/skills usableSkills) */
+ const prefsHome = env.OPENFILM_SHARED_HOME || env.OPENFILM_HOME;
const mySkills = process.env.OPENFILM_SKILLS || (env.OPENFILM_LIBRARY ? join(dirname(env.OPENFILM_LIBRARY), 'Skills') : (await import('openfilm/skills')).mySkillsDir());
localAgents = registerLocalAgentIpc(ipcMain, {
trusted: fromPage,
@@ -555,7 +595,7 @@ async function start() {
/* Developer mode: an agent whose own record lacks what its model got logs it here (agent-logs.mjs) */
logDir: () => (readPreferences(DATA).developer ? join(DATA, 'agent-logs') : null),
/* each session's skills: its maker's, OpenFilm's, and of the person's own those let in (agent-skills.mjs) */
- skills: { dataDir: DATA, mine: mySkills },
+ skills: { dataDir: DATA, mine: mySkills, prefsHome },
});
/* the composer's Skills button */
registerSkillsIpc(ipcMain, {
@@ -563,6 +603,7 @@ async function start() {
projects: async () => (await studioApi('/api/projects')).projects.filter((p) => !p.missing).map((p) => p.path),
dataDir: DATA,
mine: mySkills,
+ prefsHome,
oldMine: join(env.OPENFILM_HOME, 'skills'),
reveal: (path) => { void shell.openPath(path); },
pickFolder: (words) => pickFolder(words),
diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs
index 2fe7543..de4eadd 100644
--- a/apps/desktop/src/preload.cjs
+++ b/apps/desktop/src/preload.cjs
@@ -35,9 +35,11 @@ contextBridge.exposeInMainWorld('openfilmNative', {
open: (projectId) => ipcRenderer.invoke('desktop:tabs:new', { projectId }),
move: (id, index) => ipcRenderer.invoke('desktop:tabs:move', { id, index }),
report: (state) => ipcRenderer.invoke('desktop:tabs:report', state ?? {}),
+ gone: (projectIds) => ipcRenderer.invoke('desktop:tabs:gone', { projectIds }),
retitle: (id, title) => ipcRenderer.invoke('desktop:tabs:retitle', { id, title }),
openRequest: (to) => ipcRenderer.invoke('desktop:tabs:open', { to }),
onPick: on('desktop:tabs:pick'),
+ onCovered: on('desktop:tabs:covered'),
},
/* the roster (agent-roster.mjs): Settings → Agents and the chat's menu */
@@ -87,7 +89,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
/* the chat's record of a project (chat-store.mjs): conversations, finished turns (.film/chat), each turn's log (.film/logs) */
chat: {
load: (project) => ipcRenderer.invoke('desktop:chat:load', { project }),
- saveSessions: (project, sessions, last, skills) => ipcRenderer.invoke('desktop:chat:sessions', { project, sessions, last, skills }),
+ saveSessions: (project, sessions, last) => ipcRenderer.invoke('desktop:chat:sessions', { project, sessions, last }),
saveTurn: (project, turn, items) => ipcRenderer.invoke('desktop:chat:turn', { project, turn, items }),
log: (project, turnId, unless) => ipcRenderer.invoke('desktop:chat:log', { project, turnId, unless }),
reveal: (project, turnId) => ipcRenderer.invoke('desktop:chat:reveal', { project, turnId }),
@@ -103,6 +105,8 @@ contextBridge.exposeInMainWorld('openfilmNative', {
list: (project, agent) => ipcRenderer.invoke('desktop:skills:list', { project, agent }),
texts: (project, agent, names) => ipcRenderer.invoke('desktop:skills:texts', { project, agent, names }),
allow: (agent, name, allowed) => ipcRenderer.invoke('desktop:skills:allow', { agent, name, allowed }),
+ /* one of OpenFilm's skills turned on or off: the agents' sessions take it up */
+ changed: () => ipcRenderer.invoke('desktop:skills:changed'),
preview: (url) => ipcRenderer.invoke('desktop:skills:preview', { url }),
/* a folder dropped (its path), or null: one picked in the system's dialog, with the page's words { title, button } */
previewFolder: (path, words) => ipcRenderer.invoke('desktop:skills:preview', { folder: typeof path === 'string' ? path : null, words }),
diff --git a/apps/desktop/src/skill-pages.test.mjs b/apps/desktop/src/skill-pages.test.mjs
new file mode 100644
index 0000000..ff818f1
--- /dev/null
+++ b/apps/desktop/src/skill-pages.test.mjs
@@ -0,0 +1,24 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { givenAfter, pagesToSend } from '../chat/src/lib/skill-pages.ts';
+
+test('a skill named in a message sends its page the first time a session meets it, then only its name', () => {
+ assert.deepEqual(pagesToSend(['brand', 'pace', 'brand'], undefined, 'codex', null), ['brand', 'pace']);
+ /* the first message, before the agent has a session of its own; then the session it started */
+ let given = givenAfter(undefined, 'codex', null, ['brand']);
+ given = givenAfter(given, 'codex', 's1', ['brand'], { fresh: true });
+ assert.deepEqual(pagesToSend(['brand', 'pace'], given, 'codex', 's1'), ['pace']);
+ given = givenAfter(given, 'codex', 's1', ['pace']);
+ assert.deepEqual(given.codex, { session: 's1', names: ['brand', 'pace'] });
+ assert.deepEqual(pagesToSend(['brand', 'pace'], given, 'codex', 's1'), []);
+});
+
+test('another agent, or a session that could not be taken up again, has none of the pages from before', () => {
+ const given = givenAfter(undefined, 'codex', 's1', ['brand']);
+ assert.deepEqual(pagesToSend(['brand'], given, 'claude', null), ['brand'], 'another agent');
+ assert.deepEqual(pagesToSend(['brand'], given, 'codex', 's2'), ['brand'], 'another session');
+ const fresh = givenAfter(given, 'codex', 's2', ['pace'], { fresh: true });
+ assert.deepEqual(fresh.codex, { session: 's2', names: ['pace'] });
+ assert.deepEqual(givenAfter(given, 'codex', 's1', ['pace'], { fresh: true }).codex, { session: 's1', names: ['pace'] }, 'started again under its id: what this message sent');
+ assert.deepEqual(given.codex, { session: 's1', names: ['brand'] }, 'the record given is left as it was');
+});
diff --git a/apps/desktop/src/skills-ipc.mjs b/apps/desktop/src/skills-ipc.mjs
index 2618171..855f131 100644
--- a/apps/desktop/src/skills-ipc.mjs
+++ b/apps/desktop/src/skills-ipc.mjs
@@ -46,12 +46,13 @@ const shown = (s) => ({ name: s.name, description: s.description, source: s.sour
/**
* @param {import('electron').IpcMain} ipcMain
* @param {{ trusted: (event: any) => boolean, projects: () => Promise<string[]>, dataDir: string, mine: string,
- * oldMine?: string, reveal: (path: string) => void, pickFolder: (words: unknown) => Promise<string | null>,
- * refreshSkills: (agent: string) => void, log: (line: string) => void }} opts
- * `mine`: the person's own skills folder; `oldMine`: where they were kept before, moved from as this starts;
+ * prefsHome?: string, oldMine?: string, reveal: (path: string) => void, pickFolder: (words: unknown) => Promise<string | null>,
+ * refreshSkills: (agent?: string) => void, log: (line: string) => void }} opts
+ * `mine`: the person's own skills folder; `prefsHome`: the Studio home whose prefs.json says which skills are turned
+ * off; `oldMine`: where they were kept before, moved from as this starts;
* `pickFolder`: a folder of skills picked in the system's dialog (null: cancelled)
*/
-export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, oldMine, reveal, pickFolder, refreshSkills, log }) {
+export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, prefsHome, oldMine, reveal, pickFolder, refreshSkills, log }) {
const store = skillStore(dataDir);
/* read as the app starts, so the composer's first list does not wait on them: the skills' module, and the login
shell the agents' own skills are found with */
@@ -79,10 +80,11 @@ export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, o
handle('desktop:skills:list', async ({ project: path, agent }) => {
const cwd = await project(path);
- const { listSkills } = await lib();
+ const { usableSkills } = await lib();
const allowed = new Set(store.allowed(agent));
return {
- openfilm: listSkills({ project: cwd, mine }).map(shown),
+ /* installed and on (Studio's Skills) */
+ openfilm: usableSkills({ project: cwd, mine, ...(prefsHome ? { home: prefsHome } : {}) }).map(shown),
own: { agent, filtered: FILTERED_AGENTS.includes(agent), skills: (await agentOwn(agent, cwd)).map((s) => ({ name: s.name, description: s.description, folder: s.folder, allowed: allowed.has(s.name) })) },
mine,
};
@@ -90,9 +92,9 @@ export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, o
handle('desktop:skills:texts', async ({ project: path, agent, names }) => {
const cwd = await project(path);
- const { listSkills, readSkill, skillText } = await lib();
+ const { readSkill, skillText, usableSkills } = await lib();
const wanted = Array.isArray(names) ? names.filter((n) => typeof n === 'string') : [];
- const openfilm = new Map(listSkills({ project: cwd, mine }).map((s) => [s.name, s]));
+ const openfilm = new Map(usableSkills({ project: cwd, mine, ...(prefsHome ? { home: prefsHome } : {}) }).map((s) => [s.name, s]));
const own = new Map((await agentOwn(agent, cwd)).map((s) => [s.name, s]));
return wanted.flatMap((name) => {
const skill = openfilm.get(name) ?? (own.has(name) ? readSkill(own.get(name).folder, 'mine') : null);
@@ -152,6 +154,9 @@ export function registerSkillsIpc(ipcMain, { trusted, projects, dataDir, mine, o
return { filtered: FILTERED_AGENTS.includes(agent), skills: (await agentOwn(agent, '')).map((s) => ({ name: s.name, description: s.description, allowed: allowed.has(s.name) })) };
});
+ /* one of OpenFilm's skills turned on or off (Studio's Skills): every agent's sessions take it up */
+ handle('desktop:skills:changed', async () => { refreshSkills(); return { ok: true }; });
+
handle('desktop:skills:allow', async ({ agent, name, allowed }) => {
if (typeof agent !== 'string' || typeof name !== 'string' || !name) return { ok: false };
store.setAllowed(agent, name, allowed === true);
diff --git a/apps/desktop/src/skills-on.test.mjs b/apps/desktop/src/skills-on.test.mjs
deleted file mode 100644
index 8e3874e..0000000
--- a/apps/desktop/src/skills-on.test.mjs
+++ /dev/null
@@ -1,18 +0,0 @@
-import { test } from 'node:test';
-import assert from 'node:assert/strict';
-import { sentAfter, skillsOnLine, skillsToSend } from '../chat/src/lib/skills-on.ts';
-
-test('a skill kept on goes to each agent once a conversation, and not again beside its own pill', () => {
- assert.deepEqual(skillsToSend(['brand', 'pace'], undefined, 'codex', []), ['brand', 'pace']);
- const sent = sentAfter(undefined, 'codex', ['brand', 'pace']);
- assert.deepEqual(skillsToSend(['brand', 'pace'], sent, 'codex', []), [], 'the agent has them');
- assert.deepEqual(skillsToSend(['brand', 'pace'], sent, 'claude', []), ['brand', 'pace'], 'another agent has not');
- assert.deepEqual(skillsToSend(['brand', 'pace', 'new'], sent, 'codex', []), ['new'], 'one kept on since');
- assert.deepEqual(skillsToSend(['brand'], undefined, 'codex', ['brand']), [], 'named in the message, it goes with its pill');
- assert.deepEqual(sentAfter(sent, 'codex', ['new']).codex, ['brand', 'pace', 'new']);
-});
-
-test('the agent reads them named as a pill names a skill', () => {
- assert.equal(skillsOnLine([]), '');
- assert.equal(skillsOnLine(['brand', 'pace']), '\n\nKept on in this project: skill “brand”, skill “pace”.');
-});
diff --git a/apps/desktop/src/tabs.mjs b/apps/desktop/src/tabs.mjs
index 1f90702..7a5b8dc 100644
--- a/apps/desktop/src/tabs.mjs
+++ b/apps/desktop/src/tabs.mjs
@@ -6,7 +6,8 @@
*
* Rules: a project is in one tab at most; a tab is always a project's (a project is picked first, in the projects
* window, and its tab opens); with none open, the window shows the projects; a tab closed can be opened again, last
- * closed first.
+ * closed first. A project gone (deleted, its folder gone) takes its tabs with it at once, all of them together, and
+ * none of them can be opened again (`closeProjects`).
*/
import { randomUUID } from 'node:crypto';
@@ -87,6 +88,28 @@ export function createTabs({ saved = null, now = Date.now, newId = randomUUID }
else if (active === id) api.activate(tabs[Math.min(i, tabs.length - 1)].id);
return api.get(active ?? '');
},
+ /**
+ * Projects gone: their tabs close together, without being kept to open again (nor any closed before), and the
+ * front goes to the nearest tab that stays (right, else left). → { closed: the tabs closed, front: the tab in front
+ * now (null: none left) }
+ * @param {Iterable<string>} projectIds
+ */
+ closeProjects(projectIds) {
+ const gone = new Set(projectIds);
+ for (let i = closed.length - 1; i >= 0; i--) if (gone.has(closed[i].projectId)) closed.splice(i, 1);
+ const order = tabs.map((t) => t.id);
+ const leaving = new Set(tabs.filter((t) => gone.has(t.projectId)).map((t) => t.id));
+ if (!leaving.size) return { closed: [], front: api.get(active ?? '') };
+ tabs = tabs.filter((t) => !leaving.has(t.id));
+ if (!tabs.length) active = null;
+ else if (active && leaving.has(active)) {
+ const at = order.indexOf(active);
+ const next = order.slice(at + 1).find((id) => !leaving.has(id)) ?? order.slice(0, at).reverse().find((id) => !leaving.has(id));
+ active = null;
+ if (next) api.activate(next);
+ }
+ return { closed: [...leaving], front: api.get(active ?? '') };
+ },
/** The tab closed last, open again where it was (its project in front if it is open already). → the tab, or null */
reopen() {
while (closed.length) {
diff --git a/apps/desktop/src/tabs.test.mjs b/apps/desktop/src/tabs.test.mjs
index 91aef2a..3189317 100644
--- a/apps/desktop/src/tabs.test.mjs
+++ b/apps/desktop/src/tabs.test.mjs
@@ -52,3 +52,26 @@ test('saved and restored, moved; agents and exports keep a page from being let g
assert.equal(tabs.setAgents([], ['A']), true);
assert.equal(tabs.list().find((x) => x.projectId === 'A').asking, true);
});
+
+test('projects gone take their tabs together: the front to the nearest that stays, none kept to open again', () => {
+ let n = 0;
+ const tabs = createTabs({ newId: () => `t${++n}` });
+ for (const projectId of ['a', 'b', 'c', 'd']) tabs.open({ projectId });
+ tabs.activate(tabs.byProject('b').id);
+ /* b in front, and c (where the front would go) gone too: d comes forward, never c */
+ const { closed, front } = tabs.closeProjects(['b', 'c']);
+ assert.deepEqual(closed.sort(), ['t2', 't3']);
+ assert.equal(front.projectId, 'd');
+ assert.deepEqual(tabs.list().map((t) => t.projectId), ['a', 'd']);
+ /* the last ones gone: none in front; nothing of theirs to open again, nor a tab of them closed before */
+ tabs.close(tabs.byProject('a').id);
+ assert.equal(tabs.closeProjects(['a', 'd']).front, null);
+ assert.equal(tabs.list().length, 0);
+ assert.equal(tabs.reopen(), null);
+ /* the front at the right end, gone: the one to its left */
+ for (const projectId of ['x', 'y', 'z']) tabs.open({ projectId });
+ assert.equal(tabs.closeProjects(['z']).front.projectId, 'y');
+ /* a project with no tab changes nothing */
+ assert.deepEqual(tabs.closeProjects(['nope']).closed, []);
+ assert.equal(tabs.get(tabs.activeId()).projectId, 'y');
+});
diff --git a/packages/openfilm/src/film-doc.d.mts b/packages/openfilm/src/film-doc.d.mts
index c75e327..02b9eaf 100644
--- a/packages/openfilm/src/film-doc.d.mts
+++ b/packages/openfilm/src/film-doc.d.mts
@@ -48,6 +48,8 @@ export type FilmClip = {
time?: FilmTimeSpan;
/** pictures: pages, videos, stills */
box?: FilmBox;
+ /** pages: the CSS pixels a page without a size of its own is laid out at */
+ size?: { w: number; h: number };
/** videos and sounds */
volume?: number;
/** videos and sounds */
diff --git a/packages/openfilm/src/film-doc.mjs b/packages/openfilm/src/film-doc.mjs
index 4cda326..8540776 100644
--- a/packages/openfilm/src/film-doc.mjs
+++ b/packages/openfilm/src/film-doc.mjs
@@ -916,7 +916,11 @@ export function clipTag(clip) {
];
if (style.length) parts.push(`style="${escapeAttr(style.join('; '))}"`);
if (clip.overrides?.length) parts.push(`overrides='${JSON.stringify(clip.overrides).replace(/&/g, '&amp;').replace(/'/g, '&#39;')}'`);
- for (const [k, v] of Object.entries(clip.attrs ?? {})) parts.push(`${k}="${escapeAttr(v)}"`);
+ /* a value with double quotes in it (JSON, as Studio's data-props): in single quotes, as overrides are, so it reads as
+ written */
+ for (const [k, v] of Object.entries(clip.attrs ?? {})) {
+ parts.push(v.includes('"') ? `${k}='${v.replace(/&/g, '&amp;').replace(/'/g, '&#39;')}'` : `${k}="${escapeAttr(v)}"`);
+ }
return `<${tag} ${parts.join(' ')}>${tag === 'img' ? '' : `</${tag}>`}`;
}
diff --git a/packages/openfilm/src/film-doc.test.mjs b/packages/openfilm/src/film-doc.test.mjs
index a04f198..0eb484c 100644
--- a/packages/openfilm/src/film-doc.test.mjs
+++ b/packages/openfilm/src/film-doc.test.mjs
@@ -344,3 +344,12 @@ test('an override\'s style takes CSS properties in camelCase and custom properti
assert.match(problems(page(bad)), /style has to be at most 24 properties, camelCase or custom/, JSON.stringify(bad));
}
});
+
+test('an attribute holding JSON (Studio\'s data-props) is written in single quotes, as overrides are, and read back as it was', () => {
+ const list = JSON.stringify([{ name: 'It\'s "new" & <bold>', type: 'text', at: 'h1' }]);
+ const html = filmHtml(film({ src: 'a.html', id: 'a', attrs: { 'data-props': list, 'data-link': 'a' } }));
+ assert.match(html, /data-props='\[\{"name":"It&#39;s \\"new\\" &amp; <bold>","type":"text","at":"h1"\}\]' data-link="a"/);
+ const back = readFilmFile(html);
+ assert.deepEqual(back.problems, []);
+ assert.equal(back.value.tracks[0].clips[0].attrs['data-props'], list);
+});
diff --git a/packages/openfilm/src/host.d.mts b/packages/openfilm/src/host.d.mts
index 3b1c5b1..008f50a 100644
--- a/packages/openfilm/src/host.d.mts
+++ b/packages/openfilm/src/host.d.mts
@@ -21,7 +21,7 @@ export interface FilmMeta { duration: number | null; width: number; height: numb
/** One sound of the film as the built-in timeline plays it: `src` a path on the film's origin, placed at film second `at`, its source seconds [from, to). */
export interface FilmSound { clip: string; src: string; at: number; from: number; to?: number; volume: number; speed: number }
export declare class FilmPage {
- static open(browser: Browser, origin: string, entry: string, opts?: { scale?: number; transparent?: boolean; black?: boolean; readyMs?: number; offline?: boolean; network?: PageNetwork; waitMs?: number }): Promise<FilmPage>;
+ static open(browser: Browser, origin: string, entry: string, opts?: { scale?: number; size?: { w: number; h: number } | null; transparent?: boolean; black?: boolean; readyMs?: number; offline?: boolean; network?: PageNetwork; waitMs?: number }): Promise<FilmPage>;
page: Page;
meta: FilmMeta;
problems: Array<{ kind: string; message: string }>;
diff --git a/packages/openfilm/src/host.mjs b/packages/openfilm/src/host.mjs
index 800778f..050772d 100644
--- a/packages/openfilm/src/host.mjs
+++ b/packages/openfilm/src/host.mjs
@@ -343,14 +343,16 @@ const stuck = async (/** @type {import('playwright-core').Page} */ page) =>
/** One web page in one browser tab. */
export class FilmPage {
- static async open(browser, origin, entry, { scale = 1, transparent = false, black = false, offline = false, network = {}, waitMs = 10_000, readyMs = READY_MS } = {}) {
+ static async open(browser, origin, entry, { scale = 1, size = null, transparent = false, black = false, offline = false, network = {}, waitMs = 10_000, readyMs = READY_MS } = {}) {
const film = new FilmPage();
film.problems = [];
film.browser = browser;
film.origin = origin;
film.entry = entry;
film.scale = scale;
- film.context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, deviceScaleFactor: scale });
+ /* `size`: a page clip's (SPEC §1), what a page without a size of its own is laid out at, from its first layout */
+ const laid = size?.w > 0 && size?.h > 0 ? { width: Math.round(size.w), height: Math.round(size.h) } : { width: 1920, height: 1080 };
+ film.context = await browser.newContext({ viewport: laid, deviceScaleFactor: scale });
film.page = await film.context.newPage();
const problems = film.problems;
film.page.on('pageerror', (e) => problems.push({ kind: 'error', message: e.message }));
@@ -403,17 +405,17 @@ export class FilmPage {
throw new FrameError(`window.film with a frame() function did not appear within ${waitMs / 1000} s${failed()}`);
}
/* a ready that never comes (a file that never loads, a loop that never ends) is said, rather than waited on for ever */
- film.meta = await whileMoving(film.page, film.page.evaluate(async () => {
+ film.meta = await whileMoving(film.page, film.page.evaluate(async (laid) => {
const a = window.film;
await (typeof a.ready === 'function' ? a.ready() : a.ready);
await document.fonts?.ready;
- /* a page without a size of its own, opened on its own, is 1920 × 1080 (inside a film it is the stage's); one
- without a duration has no end (null) */
+ /* a page without a size of its own, opened on its own, is 1920 × 1080, or its clip's `size` (inside a film it
+ is the stage's); one without a duration has no end (null) */
const sized = a.width != null || a.height != null;
- return { duration: a.duration ?? null, width: sized ? a.width : 1920, height: sized ? a.height : 1080, sized,
+ return { duration: a.duration ?? null, width: sized ? a.width : laid.width, height: sized ? a.height : laid.height, sized,
/* an edit's sound, from the built-in timeline (a single page has none) */
sounds: window.__filmSounds?.() ?? [] };
- }), readyMs, `film.ready did not finish within ${readyMs / 1000} s`).catch(async (e) => {
+ }, laid), readyMs, `film.ready did not finish within ${readyMs / 1000} s`).catch(async (e) => {
const late = e instanceof FrameError ? await stuck(film.page) : '';
await film.context.close();
if (e instanceof FrameError) throw new FrameError(`${entry.startsWith('__film/') ? '' : `${entry}: `}${e.message}${late}${failed(e.message)}`);
diff --git a/packages/openfilm/src/locations.mjs b/packages/openfilm/src/locations.mjs
index 9da9e99..093d4a7 100644
--- a/packages/openfilm/src/locations.mjs
+++ b/packages/openfilm/src/locations.mjs
@@ -18,8 +18,34 @@ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
/** Studio's own home (its settings and keys, not the person's work): OPENFILM_HOME, else ~/.openfilm. */
export const studioHomeDir = () => process.env.OPENFILM_HOME || join(homedir(), '.openfilm');
-/** The Studio home whose prefs.json says where the library is: OPENFILM_SHARED_HOME, else Studio's own. */
-const choiceHome = () => process.env.OPENFILM_SHARED_HOME || studioHomeDir();
+/**
+ * The Studio home whose prefs.json holds what every OpenFilm on this computer shares (where the library is, the skills
+ * turned off): OPENFILM_SHARED_HOME, else Studio's own.
+ */
+export const sharedHome = () => process.env.OPENFILM_SHARED_HOME || studioHomeDir();
+
+/** One value of the shared prefs.json (`home`: the home that holds it), or undefined. @param {string} key */
+export function sharedPref(key, home = sharedHome()) {
+ try {
+ const raw = JSON.parse(readFileSync(join(home, 'prefs.json'), 'utf8'));
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw[key] : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Keep one value in the shared prefs.json. The file is shared with every OpenFilm on this computer, older or newer:
+ * what this one does not know of it is written back as it was. @param {string} key @param {unknown} value
+ */
+export function setSharedPref(key, value, home = sharedHome()) {
+ const at = join(home, 'prefs.json');
+ let kept = {};
+ try { const raw = JSON.parse(readFileSync(at, 'utf8')); if (raw && typeof raw === 'object' && !Array.isArray(raw)) kept = raw; } catch { /* none yet */ }
+ mkdirSync(home, { recursive: true });
+ writeFileSync(`${at}.${process.pid}.tmp`, `${JSON.stringify({ ...kept, [key]: value }, null, 2)}\n`);
+ renameSync(`${at}.${process.pid}.tmp`, at);
+}
/** Where new projects go unless the person chose: OPENFILM_LIBRARY, else ~/Movies/OpenFilm/Projects on macOS, ~/Videos/OpenFilm/Projects elsewhere. */
export const libraryDefault = () => process.env.OPENFILM_LIBRARY
@@ -46,29 +72,18 @@ export const LOCATION_KEYS = /** @type {const} */ ({ projects: 'projectsFolder'
/** A folder the person chose, as kept in prefs.json: an absolute path, or null (none chosen, or not one). */
export function chosenFolder(/** @type {'projectsFolder'} */ key) {
- try {
- const value = JSON.parse(readFileSync(join(choiceHome(), 'prefs.json'), 'utf8'))?.[key];
- return typeof value === 'string' && isAbsolute(value) ? resolve(value) : null;
- } catch {
- return null;
- }
+ const value = sharedPref(key);
+ return typeof value === 'string' && isAbsolute(value) ? resolve(value) : null;
}
/**
- * Keep a folder the person chose (null: back to the default) in the prefs.json that holds it. The file is shared with
- * every OpenFilm on this computer, older or newer: what this one does not know of it is written back as it was.
+ * Keep a folder the person chose (null: back to the default) in the shared prefs.json.
* @param {'projectsFolder'} key @param {string | null} value
*/
export function chooseFolder(key, value) {
- const at = join(choiceHome(), 'prefs.json');
- let kept = {};
- try { const raw = JSON.parse(readFileSync(at, 'utf8')); if (raw && typeof raw === 'object' && !Array.isArray(raw)) kept = raw; } catch { /* none yet */ }
- mkdirSync(choiceHome(), { recursive: true });
- writeFileSync(`${at}.${process.pid}.tmp`, `${JSON.stringify({ ...kept, [key]: value }, null, 2)}\n`);
- renameSync(`${at}.${process.pid}.tmp`, at);
+ setSharedPref(key, value);
}
-/** Where new projects go: the folder the person chose, else the default. */
export const libraryRoot = () => chosenFolder('projectsFolder') ?? libraryDefault();
/**
@@ -120,7 +135,7 @@ export function usableFolder(value) {
if (typeof value !== 'string' || !isAbsolute(value)) throw new Error('Choose a folder by its full path.');
const path = resolve(value);
if (dirname(path) === path) throw new Error('Choose a folder on that disk, not the disk itself.');
- for (const home of new Set([resolve(studioHomeDir()), resolve(choiceHome())])) {
+ for (const home of new Set([resolve(studioHomeDir()), resolve(sharedHome())])) {
if (path === home || path.startsWith(home + sep)) throw new Error('OpenFilm keeps its own settings there: choose another folder.');
}
try {
diff --git a/packages/openfilm/src/shared.d.mts b/packages/openfilm/src/shared.d.mts
index 416d63b..e32718f 100644
--- a/packages/openfilm/src/shared.d.mts
+++ b/packages/openfilm/src/shared.d.mts
@@ -3,6 +3,8 @@ export interface MixFade { in: number; out: number; length: number; skip: number
export interface MixClip { file: string; at: number; from: number; to?: number; volume: number; speed?: number; fade?: MixFade }
export declare function audioClips(root: string, entry: string, clips: Array<{ src: string; at?: number; from?: number; to?: number; volume?: number; speed?: number; fade?: readonly [number, number] }> | undefined, from?: number): MixClip[];
export declare function fadeFilter(fade: MixFade | undefined): string;
+/** The atempo filter chain for a playback speed, the pitch kept (each stage takes 0.5–2); empty at 1. */
+export declare function tempo(speed: number): string;
export declare function mix(clips: MixClip[], duration: number, file: string, codec?: string[]): Promise<void>;
/** A mix's inputs and filter graph: a file used by several clips is one input, split. */
export declare function mixGraph(clips: MixClip[], duration: number): { inputs: string[]; filter: string };
diff --git a/packages/openfilm/src/shared.mjs b/packages/openfilm/src/shared.mjs
index 19a65e5..d99e0d3 100644
--- a/packages/openfilm/src/shared.mjs
+++ b/packages/openfilm/src/shared.mjs
@@ -227,7 +227,7 @@ export function hasAudio(file) {
}
/** atempo chain for a playback rate (pitch kept); each stage takes 0.5–2. */
-function tempo(speed) {
+export function tempo(speed) {
const out = [];
let s = speed;
while (s > 2) { out.push('atempo=2'); s /= 2; }
diff --git a/packages/openfilm/src/skills-cli.mjs b/packages/openfilm/src/skills-cli.mjs
index 719e128..85b65f2 100644
--- a/packages/openfilm/src/skills-cli.mjs
+++ b/packages/openfilm/src/skills-cli.mjs
@@ -13,7 +13,7 @@ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from '
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { FILM_FILE } from './film-doc.mjs';
-import { addSkills, findSkill, folderSize, holdsSkills, listSkills, migrateMySkills, mySkillsDir, readSkill, removeSkill, skillText, skillsIn, PROJECT_SKILLS } from './skills.mjs';
+import { addSkills, findSkill, folderSize, holdsSkills, migrateMySkills, mySkillsDir, readSkill, removeSkill, skillText, skillsIn, usableSkills, PROJECT_SKILLS } from './skills.mjs';
/** The project around a folder (the nearest film.html above), or null. @param {string} from */
export function projectAround(from) {
@@ -25,13 +25,17 @@ const SOURCE = { project: 'this project', mine: 'yours', official: 'official' };
/** a path as the person reads it: from the current folder when it is under it */
const shown = (/** @type {string} */ p) => { const r = relative(process.cwd(), p); return r && !r.startsWith('..') ? r : p; };
-/** `openfilm skills`: every skill the project around here (if any) can be made with. @param {string} run */
+/**
+ * `openfilm skills`: the skills the project around here (if any) can be made with: its own, the person's and the
+ * official ones they installed, none they turned off (usableSkills).
+ * @param {string} run
+ */
export function skillsCommand(run, { cwd = process.cwd() } = {}) {
migrateMySkills();
const project = projectAround(cwd);
- const skills = listSkills({ project });
+ const skills = usableSkills({ project });
if (!skills.length) {
- return { ok: true, lines: [`No skills yet. \`${run} skill add <GitHub address or folder>\` adds one to yours (${shown(mySkillsDir())}).`] };
+ return { ok: true, lines: [`No skills installed. Install OpenFilm's in Studio's Skills, or \`${run} skill add <GitHub address or folder>\` adds one to yours (${shown(mySkillsDir())}).`] };
}
const width = Math.min(28, Math.max(...skills.map((s) => s.name.length)));
return {
diff --git a/packages/openfilm/src/skills.mjs b/packages/openfilm/src/skills.mjs
index 7739185..11d1582 100644
--- a/packages/openfilm/src/skills.mjs
+++ b/packages/openfilm/src/skills.mjs
@@ -26,7 +26,7 @@ import { fileURLToPath } from 'node:url';
import { randomUUID } from 'node:crypto';
import { moveToTrash } from '../studio/server/trash.mjs';
import { pictureType } from '../studio/server/cover.mjs';
-import { libraryDefault } from './locations.mjs';
+import { libraryDefault, setSharedPref, sharedPref } from './locations.mjs';
const mkdirSyncSafe = (/** @type {string} */ dir) => mkdirSync(dir, { recursive: true });
/** a folder moved to another place: renamed, else (another disk) copied and then removed */
@@ -243,6 +243,53 @@ export function listSkills({ project = null, mine = mySkillsDir(), official = of
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
+/**
+ * Which skills agents get. The official ones are a catalog: one is installed to be used (`skillsInstalled`); the
+ * person's own and a project's are theirs already. Any of them can be turned off (`skillsOff`) and stays where it is,
+ * offered to no agent until it is turned on again. Both are kept in the shared prefs.json, so every OpenFilm on this
+ * computer agrees; `home`: the Studio home that holds it.
+ */
+const namesIn = (/** @type {unknown} */ value) => (Array.isArray(value) ? [...new Set(value.filter((n) => typeof n === 'string' && SKILL_NAME.test(n)))].sort() : []);
+
+/** The official skills the person installed, by name. @param {string} [home] @returns {string[]} */
+export function skillsInstalled(home) {
+ return namesIn(sharedPref('skillsInstalled', home));
+}
+
+/** The skills the person turned off, by name. @param {string} [home] @returns {string[]} */
+export function skillsOff(home) {
+ return namesIn(sharedPref('skillsOff', home));
+}
+
+/** @param {'skillsInstalled' | 'skillsOff'} key @param {string} name @param {boolean} present @param {string} [home] */
+function keepName(key, name, present, home) {
+ if (!SKILL_NAME.test(name)) throw new Error(`"${name}" is not a skill's name.`);
+ const names = new Set(namesIn(sharedPref(key, home)));
+ if (present) names.add(name); else names.delete(name);
+ setSharedPref(key, [...names].sort(), home);
+}
+
+/** Turn a skill on or off, by name. @param {string} name @param {boolean} on @param {string} [home] */
+export function setSkillOn(name, on, home) {
+ keepName('skillsOff', name, !on, home);
+}
+
+/** Install an official skill (it starts on), or uninstall it. @param {string} name @param {boolean} installed @param {string} [home] */
+export function setSkillInstalled(name, installed, home) {
+ keepName('skillsInstalled', name, installed, home);
+ if (installed) keepName('skillsOff', name, false, home);
+}
+
+/**
+ * The skills agents get for a project: listSkills's, but the official ones not installed and any turned off.
+ * @param {Parameters<typeof listSkills>[0] & { home?: string }} [where]
+ */
+export function usableSkills({ home, ...where } = {}) {
+ const installed = new Set(skillsInstalled(home));
+ const off = new Set(skillsOff(home));
+ return listSkills(where).filter((s) => (s.source !== 'official' || installed.has(s.name)) && !off.has(s.name));
+}
+
/** One skill by name, as listSkills finds it, or null. @param {string} name @param {Parameters<typeof listSkills>[0]} [where] */
export function findSkill(name, where) {
return listSkills(where).find((s) => s.name === name) ?? null;
diff --git a/packages/openfilm/src/skills.test.mjs b/packages/openfilm/src/skills.test.mjs
index 7f79482..7dd40e8 100644
--- a/packages/openfilm/src/skills.test.mjs
+++ b/packages/openfilm/src/skills.test.mjs
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { cpSync, mkdirSync, mkdtempSync, writeFileSync, existsSync, readFileSync, symlinkSync, lstatSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { addSkills, findSkill, listSkills, migrateMySkills, mySkillsDir, parseSkillFile, readSkill, removeSkill, setSkillCover, skillOrigins, skillText } from './skills.mjs';
+import { addSkills, findSkill, listSkills, migrateMySkills, mySkillsDir, parseSkillFile, readSkill, removeSkill, setSkillCover, setSkillInstalled, setSkillOn, skillOrigins, skillText } from './skills.mjs';
import { commitSkills, discardSkills, previewFolder, previewSkills, skillCommand, skillsCommand } from './skills-cli.mjs';
const skill = (dir, name, description, body = 'How to make it.', extra = {}) => {
@@ -223,6 +223,8 @@ test('openfilm skills and skill: the list, one printed whole, one added from an
skill(join(film, 'skills', 'brand'), 'brand', 'This film\'s brand');
const before = process.env.OPENFILM_SKILLS;
const beforeHome = process.env.OPENFILM_HOME;
+ const beforeShared = process.env.OPENFILM_SHARED_HOME;
+ delete process.env.OPENFILM_SHARED_HOME;
process.env.OPENFILM_SKILLS = join(home, 'skills');
/* the skills kept in Studio's home before, moved as the commands run: a scratch home, never the person's */
process.env.OPENFILM_HOME = join(root, 'studio-home');
@@ -230,10 +232,15 @@ test('openfilm skills and skill: the list, one printed whole, one added from an
const listed = skillsCommand('openfilm', { cwd: film });
assert.ok(listed.lines.some((l) => /brand\s+this project/.test(l)));
assert.ok(listed.lines.some((l) => l.includes('This film\'s brand')));
- /* outside a project: none of this film's, only what comes with OpenFilm */
+ /* outside a project: none of this film's; OpenFilm's own once installed, and not while off */
+ assert.match(skillsCommand('openfilm', { cwd: root }).lines[0], /^No skills installed\./);
+ setSkillInstalled('replicate', true);
const outside = skillsCommand('openfilm', { cwd: root }).lines;
assert.match(outside[0], /^Skills\. /);
assert.ok(!outside.some((l) => /this project/.test(l)) && outside.some((l) => /replicate\s+official/.test(l)));
+ setSkillOn('replicate', false);
+ assert.ok(!skillsCommand('openfilm', { cwd: root }).lines.some((l) => /replicate/.test(l)), 'off: offered to no agent');
+ setSkillOn('replicate', true);
const printed = await skillCommand(['brand'], 'openfilm', { cwd: film });
assert.ok(printed.ok);
@@ -253,6 +260,7 @@ test('openfilm skills and skill: the list, one printed whole, one added from an
} finally {
if (before === undefined) delete process.env.OPENFILM_SKILLS; else process.env.OPENFILM_SKILLS = before;
if (beforeHome === undefined) delete process.env.OPENFILM_HOME; else process.env.OPENFILM_HOME = beforeHome;
+ if (beforeShared !== undefined) process.env.OPENFILM_SHARED_HOME = beforeShared;
}
});
diff --git a/packages/openfilm/studio/server/bridge.js b/packages/openfilm/studio/server/bridge.js
index 4acb679..e881a58 100644
--- a/packages/openfilm/studio/server/bridge.js
+++ b/packages/openfilm/studio/server/bridge.js
@@ -10,6 +10,7 @@
* { type: 'update', film, head, seq } film.html changed: change the film in place if it can be
* { type: 'renders', list } stretches rendered for the preview to play in their place: [{ a, b, src }]
* { type: 'preview', clip, overrides } show a tweak on a page, not kept (null: stop showing)
+ * { type: 'overrides', list } a page on its own: its clip's changes (SPEC §1), applied after each frame
* { type: 'pick', x, y, seq } what is under this stage point
* film → { source: 'openfilm-film', type: 'ready', duration, width, height, sounds, spans, origin }
* { type: 'seeked', t, seq } the frame at t is on screen
@@ -43,6 +44,17 @@
});
const facts = (f) => ({ duration: f.duration, width: f.width, height: f.height, sounds: window.__filmSounds?.() ?? [], spans: window.__filmSpans?.() ?? [] });
const editor = () => window.__filmEditor;
+ /* a page on its own played as a clip had it (a clip of Saved): its changes, after each frame, as the film's
+ timeline applies them (src/overrides.mjs); what they changed is remembered, so the page's own look comes back */
+ let tweaks = null;
+ let tweaker = null;
+ const tweakState = { win: window, touched: new Map(), found: [] };
+ const drawn = async (f, t) => {
+ await f.frame(t);
+ if (!tweaks) return;
+ tweaker ??= import(new URL('__film/overrides.mjs', location.href).href).then((m) => m.override);
+ (await tweaker)(tweakState, tweaks);
+ };
/* the film once loaded, or null: one that fails to load (a clip with no length, a missing file) says why once, here,
and draws and answers nothing after — a page error for each later message would only repeat it */
@@ -73,7 +85,7 @@
video must not stop the picture. */
const watch = editor()?.watch;
let timer;
- await Promise.race([watch ? watch(t) : f.frame(t), new Promise((done) => { timer = setTimeout(done, behind ? BEHIND_WAIT_MS : FRAME_WAIT_MS); })]);
+ await Promise.race([watch ? watch(t) : drawn(f, t), new Promise((done) => { timer = setTimeout(done, behind ? BEHIND_WAIT_MS : FRAME_WAIT_MS); })]);
clearTimeout(timer);
post({ type: 'seeked', t, seq });
} catch (e) { fail(e); }
@@ -121,7 +133,7 @@
const watch = editor()?.watch;
const play = { rate: line.rate, now: Math.min(lineAt(now), end) };
let timer;
- await Promise.race([watch ? watch(t, play) : up.frame(t), new Promise((done) => { timer = setTimeout(done, FRAME_WAIT_MS); })]);
+ await Promise.race([watch ? watch(t, play) : drawn(up, t), new Promise((done) => { timer = setTimeout(done, FRAME_WAIT_MS); })]);
clearTimeout(timer);
} catch (e) { fail(e); }
drawing = false;
@@ -160,6 +172,8 @@
if (e.origin !== EDITOR || e.data?.source !== 'openfilm-studio') return;
const m = e.data;
if (m.type === 'clock') { post({ type: 'clock', ping: m.ping, now: clock() }); return; }
+ /* before the next frame is drawn: the one asked for after them shows them */
+ if (m.type === 'overrides') { if (!editor()) tweaks = Array.isArray(m.list) && m.list.length ? m.list : null; return; }
if (m.type === 'seek') { stop(); next = m; asked = m.t; draw(); return; }
if (m.type === 'play') {
const fps = Number(m.fps);
diff --git a/packages/openfilm/studio/server/derived.mjs b/packages/openfilm/studio/server/derived.mjs
index f58ea08..2d529ab 100644
--- a/packages/openfilm/studio/server/derived.mjs
+++ b/packages/openfilm/studio/server/derived.mjs
@@ -12,6 +12,7 @@ import { createHash } from 'node:crypto';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rename, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
+import { tempo } from '../../src/shared.mjs';
import { readable } from './files.mjs';
import { TOOL_DIR } from './projects.mjs';
import { writeAtomic } from './atomic.mjs';
@@ -154,18 +155,24 @@ const COMPACT = /\.(mp3|m4a|aac|ogg|oga|opus)$/i;
const COMPACT_BYTES = 16 << 20;
/** @type {Map<string, Promise<string | null>>} copies being made, by where they go */
const makingSound = new Map();
+/** The speeds a sound is made at: a clip's (SPEED_MIN to SPEED_MAX) by the viewer's (0.25× to 2×), and some room. */
+export const SOUND_SPEED = { min: 1 / 16, max: 16 };
/**
* The sound of a media file as the editor plays it, small: a compressed sound file of up to COMPACT_BYTES is its
* own; any other (a video, a WAV, a long recording) gets a copy of its sound in `.film/cache/audio/`, AAC in .m4a:
- * the file's own AAC as it is, any other sound encoded at 128 kb/s, stereo at most. Made once per version of the
- * file; returns the path to play, or null when there is no sound in it. Exports mix from the files themselves.
- * @param {string} root @param {string} rel
+ * the file's own AAC as it is, any other sound encoded at 128 kb/s, stereo at most. At another `speed` it is stretched
+ * to it with its pitch kept, by the same atempo filter exports use, so the editor plays it as the export has it (a
+ * sound sped up as a tape is would be heard higher). Made once per version of the file and speed; returns the path to
+ * play, or null when there is no sound in it. Exports mix from the files themselves.
+ * @param {string} root @param {string} rel @param {number} [speed]
*/
-export async function soundOf(root, rel) {
+export async function soundOf(root, rel, speed = 1) {
+ if (!(speed >= SOUND_SPEED.min && speed <= SOUND_SPEED.max)) throw new MediaError('speed: from 1/16 to 16', 400);
+ const at = Math.round(speed * 1e4) / 1e4;
const { abs, key } = await source(root, rel);
- if (COMPACT.test(rel) && (await stat(abs)).size <= COMPACT_BYTES) return abs;
- const out = join(root, TOOL_DIR, 'cache', 'audio', `${key}.m4a`);
+ if (at === 1 && COMPACT.test(rel) && (await stat(abs)).size <= COMPACT_BYTES) return abs;
+ const out = join(root, TOOL_DIR, 'cache', 'audio', at === 1 ? `${key}.m4a` : `${key}-x${at}.m4a`);
if (existsSync(out)) return out;
let made = makingSound.get(out);
if (!made) {
@@ -175,7 +182,9 @@ export async function soundOf(root, rel) {
const stream = info.streams?.[0] ?? {};
const channels = Number(stream.channels) || 2;
/* AAC is what a browser decodes everywhere: kept as it is when it is that already (no loss, no time) */
- const codec = stream.codec_name === 'aac' && channels <= 2 ? ['-c:a', 'copy'] : ['-c:a', 'aac', '-b:a', '128k', '-ac', String(Math.min(2, channels))];
+ const codec = at === 1 && stream.codec_name === 'aac' && channels <= 2
+ ? ['-c:a', 'copy']
+ : [...(at === 1 ? [] : ['-af', tempo(at)]), '-c:a', 'aac', '-b:a', '128k', '-ac', String(Math.min(2, channels))];
await mkdir(join(root, TOOL_DIR, 'cache', 'audio'), { recursive: true });
const part = `${out}.part`;
try {
diff --git a/packages/openfilm/studio/server/derived.test.mjs b/packages/openfilm/studio/server/derived.test.mjs
index 9cda345..4c0f28e 100644
--- a/packages/openfilm/studio/server/derived.test.mjs
+++ b/packages/openfilm/studio/server/derived.test.mjs
@@ -125,3 +125,29 @@ test('a file\'s sound for the editor is small and in step: a video\'s AAC kept a
assert.deepEqual(readdirSync(join(root, '.film', 'cache', 'audio')).sort(), made, 'asked again: the copy made');
await assert.rejects(soundOf(root, 'assets/none.mp4'), (e) => e instanceof MediaError && e.status === 404);
});
+
+/** A tone's frequency (Hz) and length (s), from its zero crossings. @param {string} file */
+function toneOf(file) {
+ const pcm = execFileSync('ffmpeg', ['-v', 'error', '-i', file, '-ac', '1', '-ar', '48000', '-f', 's16le', '-'], { maxBuffer: 1 << 28 });
+ const samples = new Int16Array(pcm.buffer, pcm.byteOffset, Math.floor(pcm.length / 2));
+ let ups = 0;
+ for (let i = 1; i < samples.length; i++) if (samples[i - 1] < 0 && samples[i] >= 0) ups++;
+ const seconds = samples.length / 48000;
+ return { hz: ups / seconds, seconds };
+}
+
+test('a sound played at another speed is stretched to it with its pitch kept, once per speed', { skip: !hasFfmpeg && 'no ffmpeg' }, async () => {
+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=6', '-b:a', '128k', join(root, 'assets', 'tone.mp3')]);
+ const own = String(await soundOf(root, 'assets/tone.mp3'));
+ assert.equal(own, join(root, 'assets', 'tone.mp3'), 'at 1× a small sound is played as it is');
+ for (const speed of [1.5, 0.5, 4]) {
+ const copy = String(await soundOf(root, 'assets/tone.mp3', speed));
+ assert.match(copy, /-x[\d.]+\.m4a$/, `${speed}×: a copy of its own`);
+ const tone = toneOf(copy);
+ assert.ok(Math.abs(tone.hz - 440) < 440 * 0.03, `${speed}×: still 440 Hz, not ${Math.round(tone.hz)}`);
+ assert.ok(Math.abs(tone.seconds - 6 / speed) < 0.1, `${speed}×: ${6 / speed} s long, not ${tone.seconds}`);
+ assert.equal(String(await soundOf(root, 'assets/tone.mp3', speed)), copy, 'asked again: the copy made');
+ }
+ await assert.rejects(soundOf(root, 'assets/tone.mp3', 0), (e) => e instanceof MediaError && e.status === 400);
+ await assert.rejects(soundOf(root, 'assets/tone.mp3', 32), (e) => e instanceof MediaError && e.status === 400);
+});
diff --git a/packages/openfilm/studio/server/film.mjs b/packages/openfilm/studio/server/film.mjs
index f303fff..1911e48 100644
--- a/packages/openfilm/studio/server/film.mjs
+++ b/packages/openfilm/studio/server/film.mjs
@@ -44,14 +44,18 @@ export async function readProjectFilm(root) {
}
/**
- * A clip's overrides (SPEC §1), by its id, as film.html has them now: what its thumbnails are drawn with. Null when it
- * has none, or no clip has that id.
+ * How a page clip is drawn, by its id, as film.html has it now: its overrides (SPEC §1, null when none) and the size
+ * its page is laid out at (its `size`, null when it has none). What its thumbnails are drawn with; null when no clip
+ * has that id.
* @param {string} root @param {string} id
+ * @returns {Promise<{ overrides: object[] | null, size: { w: number, h: number } | null } | null>}
*/
-export async function clipOverrides(root, id) {
+export async function pageClipLook(root, id) {
const { value } = await readProjectFilm(root);
for (const track of value?.tracks ?? []) {
- for (const clip of track.clips ?? []) if (clip.id === id) return clip.overrides?.length ? clip.overrides : null;
+ for (const clip of track.clips ?? []) {
+ if (clip.id === id) return { overrides: clip.overrides?.length ? clip.overrides : null, size: clip.size?.w && clip.size?.h ? clip.size : null };
+ }
}
return null;
}
diff --git a/packages/openfilm/studio/server/ops.mjs b/packages/openfilm/studio/server/ops.mjs
index 33a3041..1f494e6 100644
--- a/packages/openfilm/studio/server/ops.mjs
+++ b/packages/openfilm/studio/server/ops.mjs
@@ -304,12 +304,13 @@ function setField(/** @type {Clip} */ clip, /** @type {string} */ prop, /** @typ
else delete raw.overrides;
return;
}
- if (prop === 'link') {
- /* linked clips (a video and the sound taken off it) share a `data-link`: an attribute the film keeps and gives no
- meaning, Studio's own (SPEC §1) */
+ if (prop === 'link' || prop === 'props') {
+ /* Studio's own attributes, which the film keeps and gives no meaning (SPEC §1): linked clips (a video and the sound
+ taken off it) share a `data-link`; a page clip's component properties are its `data-props` (a JSON list) */
+ const name = prop === 'link' ? 'data-link' : 'data-props';
const attrs = /** @type {Record<string, string>} */ ({ ...(/** @type {Record<string, string> | undefined} */ (raw.attrs) ?? {}) });
- if (typeof v === 'string' && v) attrs['data-link'] = v;
- else delete attrs['data-link'];
+ if (typeof v === 'string' && v) attrs[name] = v;
+ else delete attrs[name];
if (Object.keys(attrs).length) raw.attrs = attrs;
else delete raw.attrs;
return;
diff --git a/packages/openfilm/studio/server/ops.test.mjs b/packages/openfilm/studio/server/ops.test.mjs
index a65bbc5..134209f 100644
--- a/packages/openfilm/studio/server/ops.test.mjs
+++ b/packages/openfilm/studio/server/ops.test.mjs
@@ -86,6 +86,16 @@ test('links: `link` writes data-link among the attributes a clip keeps, and take
assert.deepEqual(split.tracks[1].clips.map((c) => [c.id, c.attrs?.['data-link']]), [['v', 'v'], ['v-b', 'v-b']]);
});
+test('component properties: `props` writes data-props beside a link, takes it away, and a copy of the clip has them too', () => {
+ const list = JSON.stringify([{ name: 'Title', type: 'text', at: '#title' }]);
+ const f = applyOps(film(), [{ op: 'props', edits: [{ clip: 'a', prop: 'props', value: list }, { clip: 'a', prop: 'link', value: 'a' }] }]);
+ assert.deepEqual(f.tracks[0].clips[0].attrs, { 'data-props': list, 'data-link': 'a' });
+ const copy = applyOps(structuredClone(f), [{ op: 'insert', from: 'a', at: 20, track: 0, link: null }]);
+ assert.equal(copy.tracks[0].clips.at(-1).attrs?.['data-props'], list, 'every clip of the page offers the same properties');
+ const gone = applyOps(structuredClone(f), [{ op: 'props', edits: [{ clip: 'a', prop: 'props', value: null }] }]);
+ assert.deepEqual(gone.tracks[0].clips[0].attrs, { 'data-link': 'a' });
+});
+
test('props: clips that moved in time are written in the order they play', () => {
const f = applyOps(film(), [{ op: 'props', edits: [{ clip: 'a', prop: 'at', value: 8 }] }]);
assert.deepEqual(ids(f)[0], ['b', 'a']);
diff --git a/packages/openfilm/studio/server/pageframes.mjs b/packages/openfilm/studio/server/pageframes.mjs
index 9db15cf..8941d6d 100644
--- a/packages/openfilm/studio/server/pageframes.mjs
+++ b/packages/openfilm/studio/server/pageframes.mjs
@@ -56,11 +56,13 @@ export const FILM_PAGE = FILM_FILE;
/**
* The page `rel` of the folder served at `base` (its film-origin URL), drawn at `ms`, `width` px wide, as JPEG.
* `ms` past the page's end draws its last frame; `ms` < 0 draws the middle (its poster). `overrides`: a page clip's
- * (SPEC §1), drawn with it, so its pictures on the timeline show what was changed in it.
+ * (SPEC §1), drawn with it, so its pictures on the timeline show what was changed in it. `size`: a page clip's, the
+ * CSS pixels a page without a size of its own is laid out at (SPEC §1), as the film lays it out; without one it is
+ * 1920 × 1080, as a page opened on its own.
* @param {string} root @param {string} base @param {string} rel @param {number} ms @param {number} width
- * @param {object[] | null} [overrides]
+ * @param {object[] | null} [overrides] @param {{ w: number, h: number } | null} [size]
*/
-export async function pageFrame(root, base, rel, ms, width, overrides = null) {
+export async function pageFrame(root, base, rel, ms, width, overrides = null, size = null) {
const w = Math.max(32, Math.min(960, Math.round(width / 2) * 2 || 160));
/* `rel` is the request's: a page of the project only, never one reached by `../` or a link out of the folder */
const page = inProject(root, rel);
@@ -68,7 +70,8 @@ export async function pageFrame(root, base, rel, ms, width, overrides = null) {
if (!info?.isFile()) throw new PageFrameError(`${rel} is not there`);
/* `black`: how frames are drawn (frames drawn on white before are not reused) */
const tweaks = overrides?.some((o) => o && typeof o === 'object' && 'at' in o) ? JSON.stringify(overrides) : '';
- const key = createHash('sha256').update(`black\0${rel}\0${Math.round(ms)}\0${w}${tweaks ? `\0${tweaks}` : ''}`).digest('hex').slice(0, 24);
+ const laid = size ? `${Math.round(size.w)}x${Math.round(size.h)}` : '';
+ const key = createHash('sha256').update(`black\0${rel}\0${Math.round(ms)}\0${w}${tweaks ? `\0${tweaks}` : ''}${laid ? `\0${laid}` : ''}`).digest('hex').slice(0, 24);
const dir = join(root, TOOL_DIR, 'cache', 'pageframes');
const file = join(dir, `${key}.jpg`);
/* a frame is good while every file the page loaded to draw it is as it was then: the page, and its styles, code,
@@ -94,7 +97,7 @@ export async function pageFrame(root, base, rel, ms, width, overrides = null) {
if (rel === FILM_PAGE) await filmCopies(root, base, info);
/* a page drawn with tweaks is one of its own: the page kept open for another clip of the same file has none */
const drawn = tweaks ? `${version}:${createHash('sha256').update(tweaks).digest('hex').slice(0, 12)}` : version;
- const { jpeg, duration, loaded } = await draw(pageUrl(base, rel), ms, w, drawn, base, tweaks ? overrides : null).catch((e) => {
+ const { jpeg, duration, loaded } = await draw(pageUrl(base, rel), ms, w, drawn, base, tweaks ? overrides : null, laid ? size : null).catch((e) => {
failures.set(id, { error: e, at: Date.now() });
if (failures.size > 500) failures.delete(failures.keys().next().value ?? '');
throw e;
@@ -230,8 +233,8 @@ async function closeBrowser() {
* Draw `url` at `ms`, `w` px wide. `loaded`: the project's files the page (and every page inside it) loaded, project
* relative (`base`: where the project is served), so the frame is known stale when one of them changes.
*/
-function draw(/** @type {string} */ url, /** @type {number} */ ms, /** @type {number} */ w, /** @type {string} */ version, /** @type {string} */ base, /** @type {object[] | null} */ overrides = null) {
- return withPage(url, w, version, async (page) => {
+function draw(/** @type {string} */ url, /** @type {number} */ ms, /** @type {number} */ w, /** @type {string} */ version, /** @type {string} */ base, /** @type {object[] | null} */ overrides = null, /** @type {{ w: number, h: number } | null} */ size = null) {
+ return withPage(url, w, version, size, async (page) => {
const duration = lengthOf(page);
const end = duration != null ? Math.max(0, duration - 1e-3) : Infinity;
/* a poster: the fullest of a few moments around the middle (a page's middle is often a scene's first, faded-in
@@ -285,7 +288,7 @@ export async function pageFacts(root, base, rel) {
const file = inProject(root, rel);
const info = file ? await stat(file).catch(() => null) : null;
if (!info?.isFile()) throw new PageFrameError(`${rel} is not there`);
- return withPage(pageUrl(base, rel), POSTER_W, `${info.mtimeMs}:${info.size}`, async (page) => {
+ return withPage(pageUrl(base, rel), POSTER_W, `${info.mtimeMs}:${info.size}`, null, async (page) => {
const duration = lengthOf(page);
return { ...(duration != null ? { duration } : {}), width: page.meta.width, height: page.meta.height, ...(page.meta.sized ? {} : { reflows: true }) };
});
@@ -298,12 +301,13 @@ const lengthOf = (/** @type {FilmPage} */ page) => {
};
/**
- * `use` the page kept for `url` at `w` px and `version`, one at a time. A page that failed, or never finished a frame,
- * is not kept: the next request opens it fresh.
- * @template T @param {string} url @param {number} w @param {string} version @param {(page: FilmPage) => Promise<T>} use
+ * `use` the page kept for `url` at `w` px and `version` (laid out at `size`, see pageFrame), one at a time. A page that
+ * failed, or never finished a frame, is not kept: the next request opens it fresh.
+ * @template T @param {string} url @param {number} w @param {string} version @param {{ w: number, h: number } | null} size
+ * @param {(page: FilmPage) => Promise<T>} use
* @returns {Promise<T>}
*/
-function withPage(url, w, version, use) {
+function withPage(url, w, version, size, use) {
const job = queue.then(async () => {
if (idle) clearTimeout(idle);
/** @type {NodeJS.Timeout | undefined} */
@@ -311,13 +315,13 @@ function withPage(url, w, version, use) {
const late = new Promise((_, fail) => {
timer = setTimeout(() => { void closeBrowser(); fail(new Error(`drawing ${url.split('/').pop()} took over ${JOB_MS / 1000} s`)); }, JOB_MS);
});
- const work = pageFor(url, w, version).then(use);
+ const work = pageFor(url, w, version, size).then(use);
/* given up on, it fails later (its browser closed): heard, so it cannot end the process */
work.catch(() => {});
try {
return await Promise.race([work, late]);
} catch (e) {
- forget(url, w, version);
+ forget(url, w, version, size);
throw e;
} finally {
clearTimeout(timer);
@@ -329,20 +333,23 @@ function withPage(url, w, version, use) {
return job;
}
+/** The key a page is kept by. @param {string} url @param {number} w @param {string} version @param {{ w: number, h: number } | null} size */
+const keyOf = (url, w, version, size) => `${url}@${w}${size ? `:${size.w}x${size.h}` : ''}#${version}`;
+
/** Close the page kept for `url` at `w` px and `version`, if one is. */
-function forget(/** @type {string} */ url, /** @type {number} */ w, /** @type {string} */ version) {
- const key = `${url}@${w}#${version}`;
+function forget(/** @type {string} */ url, /** @type {number} */ w, /** @type {string} */ version, /** @type {{ w: number, h: number } | null} */ size) {
+ const key = keyOf(url, w, version, size);
const page = open.get(key);
open.delete(key);
void page?.then((p) => p.close(), () => {});
}
/**
- * An open page for `url` at about `w` px wide: kept open while its file is the same `version`, the least recently
- * used one closed past KEEP_PAGES.
+ * An open page for `url` at about `w` px wide (laid out at `size` when it has no size of its own): kept open while its
+ * file is the same `version`, the least recently used one closed past KEEP_PAGES.
*/
-async function pageFor(/** @type {string} */ url, /** @type {number} */ w, /** @type {string} */ version) {
- const key = `${url}@${w}#${version}`;
+async function pageFor(/** @type {string} */ url, /** @type {number} */ w, /** @type {string} */ version, /** @type {{ w: number, h: number } | null} */ size) {
+ const key = keyOf(url, w, version, size);
const known = open.get(key);
if (known) {
open.delete(key);
@@ -354,9 +361,10 @@ async function pageFor(/** @type {string} */ url, /** @type {number} */ w, /** @
/* a browser that could not start (not downloaded yet on a first run) is tried again next time, not kept */
browser ??= launch().catch((e) => { browser = null; throw e; });
const origin = new URL(url).origin;
- /* a page is 1920 wide unless it says otherwise; the device scale makes the capture `w` px without a resize */
+ /* a page is 1920 wide (or its clip's size) unless it says otherwise; the device scale makes the capture `w` px
+ without a resize */
/* on black, as the film shows a page with nothing below it (white, the browser's default, hid a white title) */
- const opening = (async () => FilmPage.open(await /** @type {Promise<import('playwright-core').Browser>} */ (browser), origin, url, { scale: w / 1920, black: true, waitMs: 15_000, readyMs: FRAME_MS }))();
+ const opening = (async () => FilmPage.open(await /** @type {Promise<import('playwright-core').Browser>} */ (browser), origin, url, { scale: w / (size?.w ?? 1920), ...(size ? { size } : {}), black: true, waitMs: 15_000, readyMs: FRAME_MS }))();
open.set(key, opening);
opening.catch((e) => {
open.delete(key);
diff --git a/packages/openfilm/studio/server/pageframes.test.mjs b/packages/openfilm/studio/server/pageframes.test.mjs
index f0fde23..551a6d0 100644
--- a/packages/openfilm/studio/server/pageframes.test.mjs
+++ b/packages/openfilm/studio/server/pageframes.test.mjs
@@ -125,6 +125,26 @@ test('a page clip\'s thumbnail shows the changes made in it (its overrides): ano
assert.ok(!(await frame(true)).equals(moved), 'changed again: drawn again');
});
+/** A JPEG's width and height, from its frame header. @param {Buffer} jpeg */
+function jpegSize(jpeg) {
+ for (let i = 2; i + 9 < jpeg.length;) {
+ const marker = jpeg[i + 1];
+ if (marker >= 0xc0 && marker <= 0xc3) return { w: jpeg.readUInt16BE(i + 7), h: jpeg.readUInt16BE(i + 5) };
+ i += 2 + jpeg.readUInt16BE(i + 2);
+ }
+ return null;
+}
+
+test('a page clip with a size is drawn laid out at it, as the film lays it out: a portrait page is a portrait picture', async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Portrait') } })).json();
+ /* a page with no size of its own: laid out at what it is given, its box half of the width it gets */
+ writeFileSync(join(project.path, 'p.html'), '<!doctype html><body style="margin:0;background:#fff"><div style="width:50vw;height:100vh;background:#f00"></div><script>window.film = { duration: 2, frame() {} };</script></body>');
+ writeFileSync(join(project.path, 'film.html'), filmHtml({ tracks: [{ clips: [{ id: 'p', src: 'p.html', size: { w: 1080, h: 1920 } }] }] }));
+ const frame = async (clip) => Buffer.from(await (await api(`/api/projects/${project.id}/media?what=frame&path=p.html&ms=500&w=160${clip ? '&clip=p' : ''}`)).arrayBuffer());
+ assert.deepEqual(jpegSize(await frame(true)), { w: 160, h: 284 }, 'the clip: 1080 × 1920');
+ assert.deepEqual(jpegSize(await frame(false)), { w: 160, h: 90 }, 'the page on its own: 1920 × 1080');
+});
+
test('a page that never gets ready (a loop that never ends) fails in its own time, and the pages after it are drawn', async () => {
const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Stuck') } })).json();
writeFileSync(join(project.path, 'loop.html'), '<!doctype html><body><script>window.film = { duration: 2, ready: new Promise(() => setTimeout(() => { for (;;) {} }, 100)), frame() {} };</script></body>');
diff --git a/packages/openfilm/studio/server/pages.mjs b/packages/openfilm/studio/server/pages.mjs
index 9b1013a..23b161d 100644
--- a/packages/openfilm/studio/server/pages.mjs
+++ b/packages/openfilm/studio/server/pages.mjs
@@ -16,7 +16,8 @@
* Pages get the host flag (the film's clock, see src/host.mjs) before any of their scripts, as `look` and `render`
* give it, so a film draws here exactly as it renders. Everything may be read by the editor's origin (its sound mixer
* fetches the media), which frames the pages. A media file asked for with `?film-sound` is its sound,
- * small (derived.mjs soundOf): what the mixer plays, never the whole of a video; 204 when it has none.
+ * small (derived.mjs soundOf): what the mixer plays, never the whole of a video; 204 when it has none. With
+ * `&speed=…` it is stretched to that speed, its pitch kept.
*/
import { execFile } from 'node:child_process';
import { createHash, createHmac } from 'node:crypto';
@@ -31,7 +32,7 @@ import { readPrefs } from './prefs.mjs';
import { readyProxy } from './proxies.mjs';
import { madeCopy } from '../../src/seekable.mjs';
import { isPreviewKey, previewDir } from './preview-cache.mjs';
-import { soundOf } from './derived.mjs';
+import { SOUND_SPEED, soundOf } from './derived.mjs';
const BRIDGE = readFileSync(new URL('./bridge.js', import.meta.url), 'utf8');
@@ -178,7 +179,10 @@ export async function startPages({ port, editorOrigin, secret, projects }) {
if (!servable(entry.root, plain)) { res.writeHead(404, headers).end('not found'); return; }
if (url.searchParams.has('film-sound')) {
/* waited for while it is made (a few seconds for a long recording): the mixer plays the film without it meanwhile */
- const file = await soundOf(entry.root, plain.replace(/^\/+/, '')).catch((/** @type {any} */ e) => (e?.status === 404 ? undefined : null));
+ /* `speed`: stretched to it, its pitch kept (the clip's speed by the viewer's) */
+ const speed = Number(url.searchParams.get('speed') ?? 1);
+ if (!(speed >= SOUND_SPEED.min && speed <= SOUND_SPEED.max)) { res.writeHead(400, headers).end('speed: from 1/16 to 16'); return; }
+ const file = await soundOf(entry.root, plain.replace(/^\/+/, ''), speed).catch((/** @type {any} */ e) => (e?.status === 404 ? undefined : null));
if (file === undefined) { res.writeHead(404, headers).end('not found'); return; }
if (!file) { res.writeHead(204, headers).end(); return; }
if (!folderFiles(dirname(file), { headers: policy() })(req, res, `/${basename(file)}`, url.searchParams)) res.writeHead(403, headers).end();
diff --git a/packages/openfilm/studio/server/projects.mjs b/packages/openfilm/studio/server/projects.mjs
index 9f3e081..2f1d2d4 100644
--- a/packages/openfilm/studio/server/projects.mjs
+++ b/packages/openfilm/studio/server/projects.mjs
@@ -69,6 +69,16 @@ export { libraryRoot };
* @typedef {{ recent: Recent[], folders: ProjectFolder[] }} StudioState
*/
+/* One change of the list at a time in this Studio: each reads the list and writes it back, so two at once (several
+ projects deleted together, a project made while another is deleted) would each write over the other's change. */
+let stateTurn = Promise.resolve();
+/** @template T @param {() => Promise<T>} change @returns {Promise<T>} */
+function exclusive(change) {
+ const run = stateTurn.then(change, change);
+ stateTurn = run.then(() => {}, () => {});
+ return run;
+}
+
/** The list of projects and the person's preferences, read fresh each time (another Studio command may have written). */
export async function readState() {
try {
@@ -144,14 +154,16 @@ export async function openProject(path, { create = true } = {}) {
refuse(folder);
await writeFile(join(folder, TOOL_DIR, '.gitignore'), '*\n');
if (!existsSync(join(folder, FILM_FILE))) await writeFile(join(folder, FILM_FILE), filmHtml(EMPTY_FILM), { flag: 'wx' }).catch(() => {});
- const state = await readState();
- const id = await folderId(folder, state);
- /* reopened: it stays in its folder of the list */
- const listed = state.recent.find((r) => r.id === id)?.folderId;
- const entry = { id, path: folder, openedAt: Date.now(), ...(listed ? { folderId: listed } : {}) };
- state.recent = [entry, ...state.recent.filter((r) => r.id !== id && r.path !== folder)];
- await writeState(state);
- return describe(entry);
+ return exclusive(async () => {
+ const state = await readState();
+ const id = await folderId(folder, state);
+ /* reopened: it stays in its folder of the list */
+ const listed = state.recent.find((r) => r.id === id)?.folderId;
+ const entry = { id, path: folder, openedAt: Date.now(), ...(listed ? { folderId: listed } : {}) };
+ state.recent = [entry, ...state.recent.filter((r) => r.id !== id && r.path !== folder)];
+ await writeState(state);
+ return describe(entry);
+ });
}
/** A new project in the library: "Untitled", "Untitled 2", … never an existing folder. */
@@ -235,11 +247,13 @@ async function followLibrary(state) {
/** Every project of the library and the ones opened from elsewhere, most recent first; one whose folder is gone says so (`missing`). */
export async function listProjects() {
- const state = await readState();
- if (await followLibrary(state)) await writeState(state);
- const folders = new Set(state.folders.map((f) => f.id));
- /* a project in a folder that was deleted is back at the top level */
- return state.recent.map((r) => describe(r.folderId && !folders.has(r.folderId) ? { ...r, folderId: undefined } : r));
+ return exclusive(async () => {
+ const state = await readState();
+ if (await followLibrary(state)) await writeState(state);
+ const folders = new Set(state.folders.map((f) => f.id));
+ /* a project in a folder that was deleted is back at the top level */
+ return state.recent.map((r) => describe(r.folderId && !folders.has(r.folderId) ? { ...r, folderId: undefined } : r));
+ });
}
/* ── folders of the Projects list: only a way to group the list, kept in studio.json; nothing moves on disk ── */
@@ -258,23 +272,46 @@ export async function listFolders() {
/** A new folder in the list: at the top level, or in the folder `parentId`. */
export async function createFolder(/** @type {unknown} */ name, /** @type {unknown} */ parentId = null) {
- const state = await readState();
- const parent = typeof parentId === 'string' && parentId ? parentId : null;
- if (parent && !state.folders.some((f) => f.id === parent)) throw new ProjectError('no such folder', 404);
- const folder = { id: newId(), name: listFolderName(name), createdAt: Date.now(), ...(parent ? { parentId: parent } : {}) };
- state.folders.push(folder);
- await writeState(state);
- return folder;
+ return exclusive(async () => {
+ const state = await readState();
+ const parent = typeof parentId === 'string' && parentId ? parentId : null;
+ if (parent && !state.folders.some((f) => f.id === parent)) throw new ProjectError('no such folder', 404);
+ const folder = { id: newId(), name: listFolderName(name), createdAt: Date.now(), ...(parent ? { parentId: parent } : {}) };
+ state.folders.push(folder);
+ await writeState(state);
+ return folder;
+ });
}
/** Rename a folder of the list. */
export async function renameFolder(/** @type {string} */ id, /** @type {unknown} */ name) {
- const state = await readState();
- const folder = state.folders.find((f) => f.id === id);
- if (!folder) throw new ProjectError('no such folder', 404);
- folder.name = listFolderName(name);
- await writeState(state);
- return folder;
+ return exclusive(async () => {
+ const state = await readState();
+ const folder = state.folders.find((f) => f.id === id);
+ if (!folder) throw new ProjectError('no such folder', 404);
+ folder.name = listFolderName(name);
+ await writeState(state);
+ return folder;
+ });
+}
+
+/**
+ * Move a folder of the list into another (null: the top level), with what is in it. Never into itself or a folder
+ * inside it.
+ * @param {string} id @param {string | null} parentId
+ */
+export async function moveFolder(id, parentId) {
+ return exclusive(async () => {
+ const state = await readState();
+ const folder = state.folders.find((f) => f.id === id);
+ if (!folder) throw new ProjectError('no such folder', 404);
+ if (parentId != null && !state.folders.some((f) => f.id === parentId)) throw new ProjectError('no such folder', 404);
+ if (parentId != null && folderTree(state.folders, id).has(parentId)) throw new ProjectError('a folder cannot go inside itself', 400, 'inside-itself');
+ if (parentId) folder.parentId = parentId;
+ else delete folder.parentId;
+ await writeState(state);
+ return folder;
+ });
}
/** A folder and every folder inside it, at any depth: their ids. @param {ProjectFolder[]} folders @param {string} id */
@@ -292,26 +329,30 @@ export function folderTree(folders, id) {
* the projects that were in them (deleting a folder deletes them too: the caller deletes each, see deleteProject).
*/
export async function deleteFolder(/** @type {string} */ id) {
- const state = await readState();
- if (!state.folders.some((f) => f.id === id)) throw new ProjectError('no such folder', 404);
- const gone = folderTree(state.folders, id);
- state.folders = state.folders.filter((f) => !gone.has(f.id));
- const inside = state.recent.filter((r) => r.folderId && gone.has(r.folderId));
- for (const r of inside) delete r.folderId;
- await writeState(state);
- return inside.map((r) => r.id);
+ return exclusive(async () => {
+ const state = await readState();
+ if (!state.folders.some((f) => f.id === id)) throw new ProjectError('no such folder', 404);
+ const gone = folderTree(state.folders, id);
+ state.folders = state.folders.filter((f) => !gone.has(f.id));
+ const inside = state.recent.filter((r) => r.folderId && gone.has(r.folderId));
+ for (const r of inside) delete r.folderId;
+ await writeState(state);
+ return inside.map((r) => r.id);
+ });
}
/** Put a project in a folder of the list, or (null) back at the top level. */
export async function moveProjectToFolder(/** @type {string} */ id, /** @type {string | null} */ folderId) {
- const state = await readState();
- const entry = state.recent.find((r) => r.id === id);
- if (!entry) throw new ProjectError('no such project', 404);
- if (folderId != null && !state.folders.some((f) => f.id === folderId)) throw new ProjectError('no such folder', 404);
- if (folderId) entry.folderId = folderId;
- else delete entry.folderId;
- await writeState(state);
- return describe(entry);
+ return exclusive(async () => {
+ const state = await readState();
+ const entry = state.recent.find((r) => r.id === id);
+ if (!entry) throw new ProjectError('no such project', 404);
+ if (folderId != null && !state.folders.some((f) => f.id === folderId)) throw new ProjectError('no such folder', 404);
+ if (folderId) entry.folderId = folderId;
+ else delete entry.folderId;
+ await writeState(state);
+ return describe(entry);
+ });
}
/** The project with this id, or a 404. */
@@ -326,13 +367,15 @@ export async function projectById(/** @type {string} */ id) {
* `openProject` makes a project the CLI opens, so `openfilm open` alone comes back to it.
*/
export async function markOpened(/** @type {string} */ id) {
- const state = await readState();
- const entry = state.recent.find((r) => r.id === id);
- if (!entry) throw new ProjectError('no such project', 404);
- entry.openedAt = Date.now();
- state.recent = [entry, ...state.recent.filter((r) => r !== entry)];
- await writeState(state);
- return describe(entry);
+ return exclusive(async () => {
+ const state = await readState();
+ const entry = state.recent.find((r) => r.id === id);
+ if (!entry) throw new ProjectError('no such project', 404);
+ entry.openedAt = Date.now();
+ state.recent = [entry, ...state.recent.filter((r) => r !== entry)];
+ await writeState(state);
+ return describe(entry);
+ });
}
/**
@@ -342,41 +385,45 @@ export async function markOpened(/** @type {string} */ id) {
* @param {string} id @param {string} path
*/
export async function locateProject(id, path) {
- const state = await readState();
- const entry = state.recent.find((r) => r.id === id);
- if (!entry) throw new ProjectError('no such project', 404);
- const asked = resolve(path);
- refuse(asked);
- if (!existsSync(asked) || !statSync(asked).isDirectory()) throw new ProjectError('That folder does not exist.', 404, 'not-found');
- const folder = realpathSync(asked);
- refuse(folder);
- if (!existsSync(join(folder, FILM_FILE))) throw new ProjectError('There is no film.html in that folder.', 409, 'no-film');
- const other = state.recent.find((r) => r.id !== id && (r.path === folder || sameFolder(r.path, folder)));
- if (other) throw new ProjectError(`That folder is already in the list, as “${basename(other.path)}”.`, 409, 'listed');
- await mkdir(join(folder, TOOL_DIR), { recursive: true });
- await writeFile(join(folder, TOOL_DIR, '.gitignore'), '*\n');
- /* the folder carries the project's id: a copy made of it later is told apart from it (folderId) */
- let had = '';
- try { had = (await readFile(join(folder, TOOL_DIR, 'id'), 'utf8')).trim(); } catch { /* none yet */ }
- if (had !== id) await writeFile(join(folder, TOOL_DIR, 'id'), `${id}\n`);
- entry.path = folder;
- await writeState(state);
- return describe(entry);
+ return exclusive(async () => {
+ const state = await readState();
+ const entry = state.recent.find((r) => r.id === id);
+ if (!entry) throw new ProjectError('no such project', 404);
+ const asked = resolve(path);
+ refuse(asked);
+ if (!existsSync(asked) || !statSync(asked).isDirectory()) throw new ProjectError('That folder does not exist.', 404, 'not-found');
+ const folder = realpathSync(asked);
+ refuse(folder);
+ if (!existsSync(join(folder, FILM_FILE))) throw new ProjectError('There is no film.html in that folder.', 409, 'no-film');
+ const other = state.recent.find((r) => r.id !== id && (r.path === folder || sameFolder(r.path, folder)));
+ if (other) throw new ProjectError(`That folder is already in the list, as “${basename(other.path)}”.`, 409, 'listed');
+ await mkdir(join(folder, TOOL_DIR), { recursive: true });
+ await writeFile(join(folder, TOOL_DIR, '.gitignore'), '*\n');
+ /* the folder carries the project's id: a copy made of it later is told apart from it (folderId) */
+ let had = '';
+ try { had = (await readFile(join(folder, TOOL_DIR, 'id'), 'utf8')).trim(); } catch { /* none yet */ }
+ if (had !== id) await writeFile(join(folder, TOOL_DIR, 'id'), `${id}\n`);
+ entry.path = folder;
+ await writeState(state);
+ return describe(entry);
+ });
}
/** Rename a project: its folder is renamed beside itself (the project's name is its folder's name). */
export async function renameProject(/** @type {string} */ id, /** @type {string} */ name) {
- const state = await readState();
- const entry = state.recent.find((r) => r.id === id);
- if (!entry) throw new ProjectError('no such project', 404);
- const to = join(dirname(entry.path), folderName(name));
- if (to === entry.path) return describe(entry);
- /* taken: retrying can't help, so it says so; the same folder in another case (on a disk that ignores it) is not */
- if (existsSync(to) && !sameFolder(to, entry.path)) throw new ProjectError(`the name "${basename(to)}" is taken: there is already a folder by that name beside this project`, 409);
- await rename(entry.path, to);
- entry.path = to;
- await writeState(state);
- return describe(entry);
+ return exclusive(async () => {
+ const state = await readState();
+ const entry = state.recent.find((r) => r.id === id);
+ if (!entry) throw new ProjectError('no such project', 404);
+ const to = join(dirname(entry.path), folderName(name));
+ if (to === entry.path) return describe(entry);
+ /* taken: retrying can't help, so it says so; the same folder in another case (on a disk that ignores it) is not */
+ if (existsSync(to) && !sameFolder(to, entry.path)) throw new ProjectError(`the name "${basename(to)}" is taken: there is already a folder by that name beside this project`, 409);
+ await rename(entry.path, to);
+ entry.path = to;
+ await writeState(state);
+ return describe(entry);
+ });
}
/**
@@ -392,9 +439,11 @@ export async function deleteProject(/** @type {string} */ id) {
/** Take a project off the list. Its folder stays as it is. */
export async function forgetProject(/** @type {string} */ id) {
- const state = await readState();
- state.recent = state.recent.filter((r) => r.id !== id);
- await writeState(state);
+ return exclusive(async () => {
+ const state = await readState();
+ state.recent = state.recent.filter((r) => r.id !== id);
+ await writeState(state);
+ });
}
/**
@@ -413,34 +462,36 @@ export async function moveLibrary(to, { move = false, choose }) {
let moved = 0;
if (!move || resolve(from) === resolve(into) || !existsSync(from)) return { moved, failed };
await mkdir(into, { recursive: true });
- const state = await readState();
- const realFrom = realpathSync(from);
- for (const folder of libraryProjects(from)) {
- let target = join(into, basename(folder));
- for (let n = 2; existsSync(target); n++) target = join(into, `${basename(folder)} ${n}`);
- try {
+ return exclusive(async () => {
+ const state = await readState();
+ const realFrom = realpathSync(from);
+ for (const folder of libraryProjects(from)) {
+ let target = join(into, basename(folder));
+ for (let n = 2; existsSync(target); n++) target = join(into, `${basename(folder)} ${n}`);
try {
- await rename(folder, target);
- } catch (e) {
- if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EXDEV') throw e;
try {
- await cp(folder, target, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });
- } catch (copying) {
- /* half a copy is no project: it goes, the original stays */
- if (existsSync(target)) await moveToTrash(target).catch(() => {});
- throw copying;
+ await rename(folder, target);
+ } catch (e) {
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EXDEV') throw e;
+ try {
+ await cp(folder, target, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });
+ } catch (copying) {
+ /* half a copy is no project: it goes, the original stays */
+ if (existsSync(target)) await moveToTrash(target).catch(() => {});
+ throw copying;
+ }
+ await moveToTrash(folder);
}
- await moveToTrash(folder);
+ } catch (e) {
+ failed.push({ name: basename(folder), error: /** @type {Error} */ (e).message });
+ continue;
}
- } catch (e) {
- failed.push({ name: basename(folder), error: /** @type {Error} */ (e).message });
- continue;
+ moved++;
+ const real = realpathSync(target);
+ const was = join(realFrom, basename(folder));
+ for (const r of state.recent) if (r.path === folder || r.path === was) r.path = real;
}
- moved++;
- const real = realpathSync(target);
- const was = join(realFrom, basename(folder));
- for (const r of state.recent) if (r.path === folder || r.path === was) r.path = real;
- }
- await writeState(state);
- return { moved, failed };
+ await writeState(state);
+ return { moved, failed };
+ });
}
diff --git a/packages/openfilm/studio/server/projects.test.mjs b/packages/openfilm/studio/server/projects.test.mjs
index 98ab27c..0f715b1 100644
--- a/packages/openfilm/studio/server/projects.test.mjs
+++ b/packages/openfilm/studio/server/projects.test.mjs
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
-import { createProject, forgetProject, listProjects, locateProject, moveLibrary, openProject, projectById, renameProject, ProjectError } from './projects.mjs';
+import { createFolder, createProject, forgetProject, listFolders, listProjects, locateProject, moveFolder, moveLibrary, openProject, projectById, renameProject, ProjectError } from './projects.mjs';
import { chooseFolder } from '../../src/locations.mjs';
import { readFilmFile } from '../../src/film-doc.mjs';
@@ -239,3 +239,26 @@ test('a listed project moved into the library outside Studio is the same project
assert.equal(listed[0].path, join(realpathSync(scratch), 'library', 'Trip'));
assert.equal(listed[0].missing, false);
});
+
+test('changes to the list made at the same moment all hold: projects made while others are taken off stay on it', async () => {
+ const old = await Promise.all(['One', 'Two', 'Three'].map((name) => createProject(name)));
+ const [made] = await Promise.all([
+ Promise.all(['Four', 'Five', 'Six'].map((name) => createProject(name))),
+ ...old.map((p) => forgetProject(p.id)),
+ ]);
+ const ids = (await listProjects()).map((p) => p.id);
+ for (const p of made) assert.ok(ids.includes(p.id), `${p.name} stays on the list`);
+});
+
+test('a folder moves into another with what it holds, back to the top level, and never inside itself', async () => {
+ const a = await createFolder('A');
+ const b = await createFolder('B', a.id);
+ const c = await createFolder('C');
+ assert.equal((await moveFolder(c.id, b.id)).parentId, b.id);
+ /* into itself, or a folder inside it: refused */
+ await assert.rejects(moveFolder(a.id, c.id), (e) => e instanceof ProjectError && e.code === 'inside-itself');
+ await assert.rejects(moveFolder(a.id, a.id), (e) => e instanceof ProjectError && e.code === 'inside-itself');
+ assert.equal((await moveFolder(c.id, null)).parentId, undefined);
+ assert.deepEqual((await listFolders()).map((f) => [f.name, f.parentId ?? null]), [['A', null], ['B', a.id], ['C', null]]);
+ await assert.rejects(moveFolder('nope', null), (e) => e instanceof ProjectError && e.status === 404);
+});
diff --git a/packages/openfilm/studio/server/saved.mjs b/packages/openfilm/studio/server/saved.mjs
index d44ec71..da12711 100644
--- a/packages/openfilm/studio/server/saved.mjs
+++ b/packages/openfilm/studio/server/saved.mjs
@@ -5,9 +5,9 @@
* a project, and what Studio saves from a film, each as a folder of its own holding what it needs (a bundle):
*
* <bundle>/saved.json { version, savedAt, kind: 'clip' | 'group' | 'page', clip | clips | path, durationMs?, w?,
- * h?, template? } a clip as the film has it (its place, its look, the changes made in its
- * page; no time, no id), clips saved together (each one's track from the top one they had
- * and `at` seconds from the first), or a page of a project with what it loads
+ * h? } a clip as the film has it (its place, its look, the changes made in its page, the
+ * properties it offers; no time, no id), clips saved together (each one's track from the top
+ * one they had and `at` seconds from the first), or a page of a project with what it loads
* <bundle>/files/… the clip's file and what it loads (closure.mjs), at the places they had in its project, so a
* page's own references still find what they name
* <bundle>/poster.jpg its picture, when one could be drawn
@@ -16,7 +16,8 @@
* The API names what is in the library from `saved/` (LIBRARY), as a project's media is named from `assets/`, so the
* media pane shows both the same way. Used in a project, a thing is a copy: a file is imported into its assets/ as one
* from the computer is (the same bytes there already are that file), a bundle's files go to `saved/<its place>/` there
- * once (taken again, what is there is used). Changing one never changes the other.
+ * once (taken again, what is there is used). Changing one never changes the other. A page clip saved with
+ * properties (its `data-props`, lib/component-props) is a component: every clip taken from it offers them.
*/
import { existsSync, createReadStream } from 'node:fs';
import { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
@@ -40,8 +41,6 @@ const VERSION = 2;
export const LIBRARY = 'saved';
/** The file that makes a folder of the library a bundle. */
const BUNDLE = 'saved.json';
-/** A page whose own CSS sets custom properties on :root (or html): the inspector offers them as its template's controls. */
-const ROOT_VARS = /(?::root|\bhtml)\s*(?:,[^{]*)?\{[^}]*--[\w-]+\s*:/i;
/** The library's folder, made when it is not there yet. */
export async function libraryRoot() {
@@ -114,15 +113,27 @@ const mainOf = (/** @type {any} */ item) => (item.kind === 'clip' ? item.clip.sr
/** A bundle as the listing shows it. @param {string} rel @param {any} item */
function bundleEntry(rel, item) {
const kind = kindOf(mainOf(item));
+ /* a page saved, or a page clip: where its page is in the library, and how its clip had it (its size, the changes
+ made in it), so the media pane's viewer plays it as the film did */
+ const clip = item.kind === 'clip' && kind === 'page' ? item.clip : null;
+ const size = clip?.size?.w > 0 && clip?.size?.h > 0 ? { w: clip.size.w, h: clip.size.h } : null;
+ /* a component: how many properties it offers (its clip's data-props) */
+ const props = (() => {
+ try { const list = JSON.parse(item.kind === 'clip' ? item.clip.attrs?.['data-props'] ?? '[]' : '[]'); return Array.isArray(list) ? list.length : 0; } catch { return 0; }
+ })();
+ const overrides = Array.isArray(clip?.overrides) && clip.overrides.some((/** @type {any} */ o) => o && typeof o === 'object' && 'at' in o) ? clip.overrides : null;
const num = (/** @type {unknown} */ v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.round(v) : undefined);
const savedAt = Date.parse(item.savedAt) || 0;
const saved = {
kind: item.kind,
...(item.kind === 'group' ? { count: item.clips.length } : {}),
- ...(item.template === true ? { template: true } : {}),
+ ...(props ? { props } : {}),
...(num(item.durationMs) ? { durationMs: num(item.durationMs) } : {}),
...(num(item.w) ? { w: num(item.w) } : {}),
...(num(item.h) ? { h: num(item.h) } : {}),
+ ...(kind === 'page' && item.kind !== 'group' ? { page: `${rel}/files/${mainOf(item)}` } : {}),
+ ...(size ? { size } : {}),
+ ...(overrides ? { overrides } : {}),
};
return { path: libraryPath(rel), kind: kind === 'page' ? 'page' : kind, size: 0, mtime: savedAt, added: savedAt, saved };
}
@@ -177,16 +188,14 @@ async function keep(root, files, about, name, into, poster) {
const folder = freeName(parent, cleanName(name) || 'Saved');
const dir = join(parent, folder);
await mkdir(join(dir, 'files'), { recursive: true });
- let template = false;
for (const rel of files) {
const to = join(dir, 'files', rel);
await mkdir(dirname(to), { recursive: true });
await copyFile(join(root, rel), to);
- if (!template && /\.(html?|css)$/i.test(rel)) template = ROOT_VARS.test(await readFile(to, 'utf8').catch(() => ''));
}
const picture = poster ? await poster().catch(() => null) : null;
if (picture) await writeFile(join(dir, 'poster.jpg'), picture);
- await writeFile(join(dir, BUNDLE), `${JSON.stringify({ version: VERSION, ...about, savedAt: new Date().toISOString(), ...(template ? { template: true } : {}) }, null, 2)}\n`);
+ await writeFile(join(dir, BUNDLE), `${JSON.stringify({ version: VERSION, ...about, savedAt: new Date().toISOString() }, null, 2)}\n`);
return libraryPath(into ? `${into}/${folder}` : folder);
}
diff --git a/packages/openfilm/studio/server/saved.test.mjs b/packages/openfilm/studio/server/saved.test.mjs
index f4ebde7..d07f432 100644
--- a/packages/openfilm/studio/server/saved.test.mjs
+++ b/packages/openfilm/studio/server/saved.test.mjs
@@ -31,7 +31,7 @@ function project() {
writeFileSync(join(root, 'assets', 'v.mp4'), 'mp4');
writeFileSync(join(root, 'film.html'), `<meta name="viewport" content="width=1920, height=1080">
<section>
- <iframe id="title" src="pages/title.html" at="5" style="left: 10px; top: 20px; width: 400px; height: 200px" overrides='[{"at":"#t","text":"Hello","style":{"--accent":"#00ff00"}}]' data-link="T"></iframe>
+ <iframe id="title" src="pages/title.html" at="5" size="1080x1920" style="left: 10px; top: 20px; width: 400px; height: 200px" overrides='[{"at":"#t","text":"Hello","style":{"--accent":"#00ff00"}}]' data-link="T" data-props='[{"name":"Title","type":"text","at":"#t"}]'></iframe>
</section>
<section>
<video id="v" src="assets/v.mp4#t=0,4" at="3" data-link="L"></video>
@@ -55,10 +55,9 @@ test('a saved clip is a folder of the library named as the person reads it, with
assert.equal(kept.kind, 'clip');
assert.equal(kept.clip.at, undefined, 'no place in time: it gets one where it is put');
assert.equal(kept.clip.id, undefined);
- assert.equal(kept.clip.attrs, undefined, 'a link to clips of the film it came from is not kept');
+ assert.deepEqual(kept.clip.attrs, { 'data-props': '[{"name":"Title","type":"text","at":"#t"}]' }, 'its properties kept (a component); a link to clips of the film it came from not');
assert.deepEqual(kept.clip.overrides, [{ at: '#t', text: 'Hello', style: { '--accent': '#00ff00' } }]);
assert.deepEqual(kept.clip.box, { x: 10, y: 20, w: 400, h: 200 });
- assert.equal(kept.template, true, 'its CSS sets custom properties on :root');
assert.equal(await saveClip(root, 'title', { name: 'Lower third' }), 'saved/Lower third 2', 'a name taken gets a number');
await assert.rejects(saveClip(root, 'nope'), /not in the film/);
});
@@ -75,7 +74,11 @@ test('the library lists files of any kind and folders as a project\'s media, a b
assert.deepEqual(folders, ['saved/Logos']);
assert.deepEqual(pages, []);
assert.deepEqual(files.map((f) => [f.path, f.kind]), [['saved/Logos/acme.svg', 'image'], ['saved/Logos/Lower third', 'page'], ['saved/notes.pdf', 'other']]);
- assert.deepEqual(files[1].saved, { kind: 'clip', template: true, durationMs: 2000, w: 400, h: 200 });
+ /* its page where the library has it, laid out and changed as its clip had it: the viewer plays it as the film did */
+ assert.deepEqual(files[1].saved, {
+ kind: 'clip', props: 1, durationMs: 2000, w: 400, h: 200, page: 'Logos/Lower third/files/pages/title.html',
+ size: { w: 1080, h: 1920 }, overrides: [{ at: '#t', text: 'Hello', style: { '--accent': '#00ff00' } }],
+ });
});
test('a bundle moves and is renamed as a folder; taken into a project, its files go under saved/ there once, its page still finding them', async () => {
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index 89e4c2a..c4a693f 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -21,7 +21,7 @@ import { pipeline } from 'node:stream';
import { mkdir, readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
-import { EditError, clipOverrides, editProjectFilm, readProjectFilm } from './film.mjs';
+import { EditError, editProjectFilm, pageClipLook, readProjectFilm } from './film.mjs';
import { FileError, bringIn, collect, extractAudio, freezeFrame, importFile, inside, listFiles, makeFolder, moveCheck, moveFile, readable, relink, trashFile } from './files.mjs';
import { ExportError, createExports, draftApps, exportCapabilities, exportsRoot, projectSizes } from './exports.mjs';
import { MediaError, frame, loudness, poster, probe, waveform } from './derived.mjs';
@@ -30,7 +30,7 @@ import { ownHost, startPages } from './pages.mjs';
import { HttpError, cookie, json, readJson } from './http.mjs';
import { acceptWebSocket } from './websocket.mjs';
import {
- ProjectError, createFolder, createProject, deleteFolder, deleteProject, libraryRoot, listFolders, listProjects, locateProject, markOpened, moveLibrary,
+ ProjectError, createFolder, createProject, deleteFolder, deleteProject, libraryRoot, listFolders, listProjects, locateProject, markOpened, moveFolder, moveLibrary,
moveProjectToFolder, openProject, projectById, renameFolder, renameProject, studioHome, studioKey, TOOL_DIR,
} from './projects.mjs';
import { FetchError, createFetches, fetchFilm, parseRepoUrl } from './fetch-repo.mjs';
@@ -49,7 +49,8 @@ import { FILM_PAGE, PageFrameError, closePageFrames, filmPoster, pageFacts, page
import { COVER_FRAME_W, CoverError, clearCover, readCover, readCoverBody, setCover, setCoverFromFile } from './cover.mjs';
import { SavedError, bundlePoster, libraryPath, libraryRel, libraryRoot as savedLibrary, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';
import { FILM_FILE, clipKind, isPage } from '../../src/film-doc.mjs';
-import { listSkills, setSkillCover, skillOrigins } from '../../src/skills.mjs';
+import { moveToTrash } from './trash.mjs';
+import { listSkills, removeSkill, setSkillCover, setSkillInstalled, setSkillOn, skillOrigins, skillsInstalled, skillsOff } from '../../src/skills.mjs';
import { providersRoute } from './providers/index.mjs';
import { captionRoutes } from './captions.mjs';
import { projectSettingsRoute } from './project-settings.mjs';
@@ -319,7 +320,9 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const rel = (/** @type {unknown} */ path) => { try { return libraryRel(path); } catch (e) { throw new HttpError(400, /** @type {Error} */ (e).message); } };
const at = url.searchParams.get('path') ?? '';
if (sub === 'files') {
- if (req.method === 'GET') return json(res, 200, await listLibrary());
+ /* `folder`: the library as the film's origin serves it, so a saved page plays in the media pane's viewer as a
+ project's does */
+ if (req.method === 'GET') return json(res, 200, { ...await listLibrary(), folder: pages.folderUrl({ id: SAVED_ORIGIN_ID, path: lib }) });
if (req.method === 'PUT') return json(res, 200, { path: libraryPath((await importFile(lib, rel(at), req)).path) });
if (req.method === 'PATCH') {
const { from, to } = /** @type {{ from?: unknown, to?: unknown }} */ (await readJson(req) ?? {});
@@ -432,6 +435,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const project = id ? (await listProjects()).find((p) => p.id === id && !p.missing) : null;
const skills = listSkills({ project: project?.path ?? null });
const origins = skillOrigins();
+ const off = new Set(skillsOff());
+ const installed = new Set(skillsInstalled());
const media = (/** @type {string} */ name, /** @type {'cover' | 'preview'} */ which) => `/api/skills/${encodeURIComponent(name)}/${which}${id ? `?project=${encodeURIComponent(id)}` : ''}`;
return json(res, 200, {
skills: skills.map((k) => ({
@@ -441,9 +446,40 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
...(k.cover ? { cover: `${media(k.name, 'cover')}${id ? '&' : '?'}v=${encodeURIComponent(k.cover)}` } : {}), ...(k.preview ? { preview: media(k.name, 'preview') } : {}),
/* the person's own: where it came from (none kept: made where it is) */
...(k.source === 'mine' ? { origin: origins[basename(k.folder)] ?? { from: 'made' } } : {}),
+ /* an official one is installed to be used; the person's own and a project's are theirs already */
+ installed: k.source !== 'official' || installed.has(k.name),
+ /* turned off: offered to no agent until it is turned on again */
+ ...(off.has(k.name) ? { off: true } : {}),
})),
});
}
+ /* an official skill installed or uninstalled (PUT { installed }) */
+ if (parts[0] === 'skills' && parts.length === 3 && parts[2] === 'installed' && req.method === 'PUT') {
+ const installed = (await readJson(req))?.installed;
+ if (typeof installed !== 'boolean') throw new HttpError(400, 'installed: true or false');
+ const skill = listSkills().find((k) => k.name === decodeURIComponent(parts[1]));
+ if (!skill || skill.source !== 'official') throw new HttpError(404, 'no such official skill');
+ setSkillInstalled(skill.name, installed);
+ return json(res, 200, { installed });
+ }
+ /* one of the person's own skills, or a project's, moved to the trash (an official one is uninstalled instead) */
+ if (parts[0] === 'skills' && parts.length === 2 && req.method === 'DELETE') {
+ const id = url.searchParams.get('project');
+ const project = id ? (await listProjects()).find((p) => p.id === id && !p.missing) : null;
+ const skill = listSkills({ project: project?.path ?? null }).find((k) => k.name === decodeURIComponent(parts[1]));
+ if (!skill) throw new HttpError(404, 'no such skill');
+ if (skill.source === 'official') throw new HttpError(400, 'An official skill is uninstalled, not removed.');
+ if (skill.source === 'mine') await removeSkill(skill.name);
+ else await moveToTrash(skill.folder);
+ return json(res, 200, {});
+ }
+ /* a skill turned on or off, by name, for every project (PUT { on }) */
+ if (parts[0] === 'skills' && parts.length === 3 && parts[2] === 'on' && req.method === 'PUT') {
+ const on = (await readJson(req))?.on;
+ if (typeof on !== 'boolean') throw new HttpError(400, 'on: true or false');
+ try { setSkillOn(decodeURIComponent(parts[1]), on); } catch (e) { throw new HttpError(400, e instanceof Error ? e.message : String(e)); }
+ return json(res, 200, { on });
+ }
/* Only the person's own skill can be changed; a project override must not edit a hidden personal skill. */
if (parts[0] === 'skills' && parts.length === 3 && parts[2] === 'cover' && (req.method === 'PUT' || req.method === 'DELETE')) {
const id = url.searchParams.get('project');
@@ -492,7 +528,12 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const { name, parentId } = /** @type {{ name?: string, parentId?: string | null }} */ (await readJson(req));
return json(res, 200, { folder: await createFolder(name, parentId) });
}
- if (parts.length === 3 && req.method === 'PATCH') return json(res, 200, { folder: await renameFolder(parts[2], /** @type {{ name?: string }} */ (await readJson(req)).name) });
+ if (parts.length === 3 && req.method === 'PATCH') {
+ const body = /** @type {{ name?: string, parentId?: string | null }} */ (await readJson(req));
+ /* { parentId }: moved into another folder (null: the top level); else { name }: renamed */
+ if (Object.hasOwn(body ?? {}, 'parentId')) return json(res, 200, { folder: await moveFolder(parts[2], body.parentId || null) });
+ return json(res, 200, { folder: await renameFolder(parts[2], body.name) });
+ }
if (parts.length === 3 && req.method === 'DELETE') return json(res, 200, { projects: await deleteFolder(parts[2]) });
}
if (parts.length === 3 && parts[2] === 'folder' && req.method === 'PUT') {
@@ -555,6 +596,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/* its files are being written, and its chat is mid-turn: stopped first, by the person */
if (agentIn(project.path)) throw new HttpError(409, 'An agent is running in this project: stop it first, then delete the project.', { code: 'agent-running' });
await deleteProject(project.id);
+ /* every page showing it leaves it (with tabs, its tab closes) */
+ watchers.emit(project.path, { type: 'gone' });
return json(res, 200, {});
}
}
@@ -796,9 +839,9 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/* a web page has no file to cut a frame from: it is drawn, as an export draws it (pageframes.mjs); a page clip's
frame (`clip`, its id) with the person's changes in it, as the film shows them */
const clipId = what === 'frame' ? url.searchParams.get('clip') : null;
- const tweaks = clipId && isPage(at) ? await clipOverrides(project.path, clipId) : null;
+ const look = clipId && isPage(at) ? await pageClipLook(project.path, clipId) : null;
const page = isPage(at) && (what === 'poster' || what === 'frame')
- ? () => pageFrame(project.path, pages.folderUrl(project), at, what === 'poster' ? -1 : Number(url.searchParams.get('ms')), what === 'poster' ? 480 : Number(url.searchParams.get('w')), tweaks).catch((e) => {
+ ? () => pageFrame(project.path, pages.folderUrl(project), at, what === 'poster' ? -1 : Number(url.searchParams.get('ms')), what === 'poster' ? 480 : Number(url.searchParams.get('w')), look?.overrides ?? null, look?.size ?? null).catch((e) => {
throw new HttpError(e instanceof PageFrameError ? 404 : 422, String(e?.message ?? e));
})
: null;
@@ -1099,6 +1142,9 @@ export function opener(target, platform = process.platform) {
return platform === 'darwin' ? ['open', target] : ['xdg-open', target];
}
+/** What Saved is served by on the film's origin (pages.mjs): no project's id has a NUL in it. */
+const SAVED_ORIGIN_ID = '\0saved';
+
/**
* What saved.mjs answers, its refusals as the HTTP errors they are.
* @template T @param {() => Promise<T>} fn @returns {Promise<T>}
@@ -1114,14 +1160,16 @@ async function savedCall(fn) {
* A saved clip's picture, from the middle of what it shows: a page drawn with the changes made in it, a video's frame,
* a still's own; a sound has none.
* @param {string} root @param {string} base the project's folder as the pages are served (pageframes.mjs)
- * @param {{ src: string, time?: unknown, overrides?: unknown }} clip @param {number} durationMs
+ * @param {{ src: string, time?: unknown, overrides?: unknown, size?: unknown }} clip @param {number} durationMs
* @returns {Promise<Buffer | null>}
*/
async function clipPoster(root, base, clip, durationMs) {
const kind = clipKind(clip.src);
const from = Array.isArray(clip.time) && typeof clip.time[0] === 'number' ? clip.time[0] * 1000 : 0;
const ms = durationMs > 0 ? from + durationMs / 2 : -1;
- if (kind === 'page') return pageFrame(root, base, clip.src, ms, 480, Array.isArray(clip.overrides) ? clip.overrides : null);
+ /* laid out at the clip's size, as the film lays it out (a page without one of its own is the clip's `size`) */
+ const size = /** @type {{ w?: number, h?: number } | undefined} */ (clip.size);
+ if (kind === 'page') return pageFrame(root, base, clip.src, ms, 480, Array.isArray(clip.overrides) ? clip.overrides : null, size?.w && size?.h ? { w: size.w, h: size.h } : null);
if (kind === 'video') return frame(root, clip.src, Math.max(0, ms), 480);
if (kind === 'still') return poster(root, clip.src);
return null;
diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjs
index 1d0e01c..d0520f9 100644
--- a/packages/openfilm/studio/server/server.test.mjs
+++ b/packages/openfilm/studio/server/server.test.mjs
@@ -913,3 +913,16 @@ test('Settings moves the library: how many projects it holds, then the folder an
assert.equal(back.locations.projects.chosen, false);
assert.ok(existsSync(join(back.locations.projects.path, 'To move', 'film.html')), 'and back to the default');
});
+
+test('a project deleted: every page showing it is told it is gone; several deleted at once all leave the list', async () => {
+ const made = [];
+ for (const name of ['Gone one', 'Gone two', 'Gone three']) made.push((await (await api('/api/projects', { method: 'POST', body: { name } })).json()).project);
+ const told = collect(`/api/projects/${made[0].id}/events`, (events) => events.some((e) => e.type === 'gone'));
+ await new Promise((r) => setTimeout(r, 300));
+ /* deleted together, as the Projects window does: none comes back */
+ const answers = await Promise.all(made.map((p) => api(`/api/projects/${p.id}`, { method: 'DELETE' })));
+ assert.deepEqual(answers.map((r) => r.status), [200, 200, 200]);
+ assert.ok((await told).some((e) => e.type === 'gone'));
+ const { projects } = await (await api('/api/projects')).json();
+ assert.deepEqual(projects.filter((p) => made.some((m) => m.id === p.id)), []);
+});
diff --git a/packages/openfilm/studio/server/skill-covers.test.mjs b/packages/openfilm/studio/server/skill-covers.test.mjs
index 1da7c1c..6efacc3 100644
--- a/packages/openfilm/studio/server/skill-covers.test.mjs
+++ b/packages/openfilm/studio/server/skill-covers.test.mjs
@@ -1,9 +1,10 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { addSkills } from '../../src/skills.mjs';
+import { skillsCommand } from '../../src/skills-cli.mjs';
import { startStudio } from './server.mjs';
test('a replacement skill cover has a new gallery URL and serves the chosen bytes', async (t) => {
@@ -72,3 +73,61 @@ test('a replacement skill cover has a new gallery URL and serves the chosen byte
writeFileSync(join(project.path, 'skills', 'covered', 'SKILL.md'), '---\nname: covered\n---\nProject steps.');
assert.equal((await api(`${endpoint}?project=${project.id}`, { method: 'DELETE' })).status, 403);
});
+
+test('skills: turned off and on, an official one installed and uninstalled, one of the person\'s removed to the trash', async (t) => {
+ const root = mkdtempSync(join(tmpdir(), 'of-skill-off-'));
+ const variables = { OPENFILM_HOME: join(root, 'home'), OPENFILM_LIBRARY: join(root, 'library'), OPENFILM_SKILLS: join(root, 'mine'), OPENFILM_TRASH_DIR: join(root, 'trash') };
+ const previous = Object.fromEntries([...Object.keys(variables), 'OPENFILM_SHARED_HOME'].map((key) => [key, process.env[key]]));
+ Object.assign(process.env, variables);
+ delete process.env.OPENFILM_SHARED_HOME;
+ mkdirSync(variables.OPENFILM_TRASH_DIR);
+ t.after(() => {
+ for (const [key, value] of Object.entries(previous)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; }
+ rmSync(root, { recursive: true, force: true });
+ });
+ const source = join(root, 'source');
+ mkdirSync(source);
+ writeFileSync(join(source, 'SKILL.md'), '---\nname: quiet\ndescription: One to turn off\n---\nSteps.');
+ await addSkills(source);
+ mkdirSync(variables.OPENFILM_HOME, { recursive: true });
+ writeFileSync(join(variables.OPENFILM_HOME, 'prefs.json'), '{"projectsFolder":null,"kept":"as it was"}');
+ const studio = await startStudio({ port: 0, openBrowser: () => {} });
+ t.after(() => studio.close());
+ const api = (path, { method = 'GET', body } = {}) => fetch(studio.origin + path, {
+ method, headers: { 'x-studio-key': studio.key, ...(body ? { 'content-type': 'application/json' } : {}) },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const listed = async () => (await (await api('/api/skills')).json()).skills.find((s) => s.name === 'quiet');
+ const command = () => skillsCommand('openfilm', { cwd: root }).lines.join('\n');
+ assert.equal((await listed()).off, undefined);
+ assert.match(command(), /quiet/);
+
+ assert.equal((await api('/api/skills/quiet/on', { method: 'PUT', body: { on: false } })).status, 200);
+ assert.equal((await listed()).off, true, 'still in the gallery, to turn on again');
+ assert.doesNotMatch(command(), /quiet/, 'offered to no agent');
+ assert.equal(JSON.parse(readFileSync(join(variables.OPENFILM_HOME, 'prefs.json'), 'utf8')).kept, 'as it was', 'the rest of prefs.json kept');
+
+ assert.equal((await api('/api/skills/quiet/on', { method: 'PUT', body: { on: true } })).status, 200);
+ assert.equal((await listed()).off, undefined);
+ assert.match(command(), /quiet/);
+ assert.equal((await api('/api/skills/quiet/on', { method: 'PUT', body: { on: 'yes' } })).status, 400);
+ assert.equal((await api('/api/skills/..%2Fx/on', { method: 'PUT', body: { on: false } })).status, 400);
+ assert.equal((await listed()).installed, true, 'the person\'s own is theirs already');
+
+ /* an official one: in the catalog, used once installed */
+ const replicate = async () => (await (await api('/api/skills')).json()).skills.find((s) => s.name === 'replicate');
+ assert.equal((await replicate()).installed, false);
+ assert.doesNotMatch(command(), /replicate/);
+ assert.equal((await api('/api/skills/replicate/installed', { method: 'PUT', body: { installed: true } })).status, 200);
+ assert.equal((await replicate()).installed, true);
+ assert.match(command(), /replicate/);
+ assert.equal((await api('/api/skills/replicate', { method: 'DELETE' })).status, 400, 'uninstalled, not removed');
+ assert.equal((await api('/api/skills/replicate/installed', { method: 'PUT', body: { installed: false } })).status, 200);
+ assert.doesNotMatch(command(), /replicate/);
+ assert.equal((await api('/api/skills/quiet/installed', { method: 'PUT', body: { installed: false } })).status, 404, 'only an official one');
+
+ /* one of the person's own removed: to the trash */
+ assert.equal((await api('/api/skills/quiet', { method: 'DELETE' })).status, 200);
+ assert.equal(await listed(), undefined);
+ assert.ok(existsSync(join(variables.OPENFILM_TRASH_DIR, 'quiet')) || readdirSync(variables.OPENFILM_TRASH_DIR).length > 0, 'in the trash');
+});
diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.js
index 9c4f541..916be1e 100644
--- a/packages/openfilm/studio/server/stage.js
+++ b/packages/openfilm/studio/server/stage.js
@@ -621,6 +621,32 @@
return hit;
};
+ /**
+ * The picture a layer draws, when it is one a file can be put in place of: an <img> (what it shows now, the file an
+ * override's `content` puts there before its own), or a box painted with one image (`bg`). A box that holds one
+ * <img> filling most of it (a frame around a photo, what a click on it takes first) has that picture: `at` / `n`
+ * name the <img>, where the file goes. `changed`: the clip has put another file there.
+ */
+ const pictureOf = (c, el) => {
+ const url = (v) => /^url\("?([^"]*)"?\)$/.exec(v ?? '')?.[1] ?? null;
+ const changed = (target, key) => overrideOf(c, target)?.style?.[key] != null;
+ const imgOf = (img) => {
+ const src = url(css(img).content) ?? (img.currentSrc || img.src);
+ return src ? { kind: 'img', src, changed: changed(img, 'content') } : null;
+ };
+ if (el.localName.toLowerCase() === 'img') return imgOf(el);
+ const painted = url(css(el).backgroundImage);
+ if (painted) return { kind: 'bg', src: painted, changed: changed(el, 'backgroundImage') };
+ const imgs = [...el.querySelectorAll('img')].filter((img) => !img.closest('svg'));
+ if (imgs.length !== 1) return null;
+ const box = el.getBoundingClientRect();
+ const pic = imgs[0].getBoundingClientRect();
+ const w = Math.max(0, Math.min(box.right, pic.right) - Math.max(box.left, pic.left));
+ const h = Math.max(0, Math.min(box.bottom, pic.bottom) - Math.max(box.top, pic.top));
+ if (!(box.width * box.height > 0) || w * h < 0.6 * box.width * box.height) return null;
+ const inner = imgOf(imgs[0]);
+ return inner ? { ...inner, ...targetOf(imgs[0]) } : null;
+ };
/** What the editor gets of a layer: who it is, and where it is on the stage now. */
const describe = (c, el, kind = kindOf(el) ?? (isGroup(el) ? 'box' : null)) => {
if (!kind) return null;
@@ -632,6 +658,7 @@
? { cx: rect.left + rect.width / 2, cy: rect.top + rect.height / 2, w: rect.width, h: rect.height, r: 0 }
: measureFrame(el, g.s, totalTurn(el));
const words = kind === 'text' ? textOf(el) : '';
+ const picture = kind === 'image' || kind === 'box' ? pictureOf(c, el) : null;
const where = locOf(el);
const turn = clipTurn(M);
return {
@@ -643,6 +670,7 @@
...(similarOf(el) ? { similar: similarOf(el) } : {}),
label: labelOf(el, kind),
...(words ? { text: { value: words, shape: 'value' } } : {}),
+ ...(picture ? { picture } : {}),
style: styleOf(el, kind),
parents: parentsOf(el),
override: overrideOf(c, el),
@@ -1540,7 +1568,7 @@
textStart: startText,
textFinish({ commit }) { finishText(Boolean(commit)); return true; },
/**
- * A page clip's template controls, what the inspector offers to change in it without opening the page: the CSS
+ * What a page clip shows that it can change without opening the page (its properties are made of these): the CSS
* custom properties its stylesheets set on `:root` (or `html`), each with its value now; its words, each layer of
* text with its selector and its words now; and its pictures, each <img> and each box painted with one image, with
* the address drawn now. Null when the clip is not a page on the picture now.
diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjs
index be4c1f1..8ca3cb3 100644
--- a/packages/openfilm/studio/server/stage.test.mjs
+++ b/packages/openfilm/studio/server/stage.test.mjs
@@ -378,3 +378,39 @@ test('more words leave the others where they are: previewed, and typed in place'
await stage.close();
}
});
+
+test('a picture inside a page says what it draws: an <img>, a box painted with one, a frame holding one <img>, and a file put there', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-picture-'));
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==', 'base64');
+ for (const name of ['a.png', 'b.png', 'c.png']) writeFileSync(join(dir, name), png);
+ writeFileSync(join(dir, 'p.html'), `<!doctype html><body style="margin:0">
+<img id="solo" src="a.png" style="position:absolute;left:10px;top:10px;width:60px;height:40px">
+<div id="painted" style="position:absolute;left:90px;top:10px;width:60px;height:40px;background:url(b.png) center/cover"></div>
+<div id="frame" style="position:absolute;left:170px;top:10px;width:60px;height:40px;background:#222"><img src="a.png" style="width:100%;height:100%;object-fit:cover"></div>
+<div id="pair" style="position:absolute;left:10px;top:100px;width:140px;height:60px;background:#222"><img src="a.png" style="width:70px;height:60px"><img src="b.png" style="width:70px;height:60px"></div>
+<script>window.film={duration:2,frame(){}}</script></body>`);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'p', src: 'p.html', overrides: [{ at: '#frame > img', style: { content: 'url("c.png")' } }] }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const solo = await stage.ask('hit', { x: 40, y: 30, detail: true });
+ assert.equal(solo?.picture?.kind, 'img');
+ assert.match(solo.picture.src, /\/a\.png$/);
+ assert.equal(solo.picture.changed, false);
+ assert.equal(solo.picture.at, undefined, 'its own picture: the file goes on it');
+ const painted = await stage.ask('hit', { x: 120, y: 30, detail: true });
+ assert.equal(painted?.picture?.kind, 'bg');
+ assert.match(painted.picture.src, /\/b\.png$/);
+ /* a frame around a photo (what a click takes first when something else is in it): its picture is the <img> in it,
+ which the file was put on */
+ const frame = await stage.ask('layer', { clip: 'p', loc: '#frame', any: true });
+ assert.equal(frame?.kind, 'box');
+ assert.equal(frame?.picture?.kind, 'img');
+ assert.equal(frame.picture.at, '#frame > img');
+ assert.match(frame.picture.src, /\/c\.png$/, 'the file put there, not its own');
+ assert.equal(frame.picture.changed, true);
+ const pair = await stage.ask('layer', { clip: 'p', loc: '#pair', any: true });
+ assert.ok(pair && !pair.picture, 'a box of two pictures is no one picture');
+ } finally {
+ await stage.close();
+ }
+});
diff --git a/packages/openfilm/studio/server/watch.mjs b/packages/openfilm/studio/server/watch.mjs
index 9c4553d..eb99c39 100644
--- a/packages/openfilm/studio/server/watch.mjs
+++ b/packages/openfilm/studio/server/watch.mjs
@@ -4,7 +4,7 @@
* file (`files`: a page, a picture, a sound). One watcher per open project, shared by every page showing it, closed when
* the last one leaves. Studio's own folders and the usual build and dependency folders are not watched.
*/
-import { readdirSync, watch } from 'node:fs';
+import { existsSync, readdirSync, watch } from 'node:fs';
import { join } from 'node:path';
import { readProjectFilm } from './film.mjs';
import { FILM_FILE } from '../../src/film-doc.mjs';
@@ -13,6 +13,8 @@ import { FILM_FILE } from '../../src/film-doc.mjs';
const IGNORED = /^(\.[^/\\]+|node_modules|dist|build)([/\\]|$)/;
/** How long changes are gathered before one event: an agent writes a file in several chunks, and often several files. */
const SETTLE_MS = 120;
+/** How long a folder that went is looked at again before its pages are told it is gone. */
+const GONE_RECHECK_MS = 400;
/* Studio's own half-written files (a file written whole through a random-named sibling, atomic.mjs; an import
streaming in, files.mjs): only the result is a change */
@@ -26,7 +28,8 @@ const WRITING = /(^|[/\\])([^/\\]+\.[0-9a-f-]{8,}\.tmp|\.\d+\.\d+\.importing)$/;
* `project`: the project renamed, as it is now.
* @typedef {{ type: 'film', rev: string } | { type: 'files', paths?: string[] } | { type: 'history' } | { type: 'export', job: object }
* | { type: 'history-progress', op: string, phase: string, done: number, total: number } | { type: 'project', project: object }
- * | { type: 'ask', ask: object } | { type: 'asked', id: string } | { type: 'notice', notice: object }} FolderEvent
+ * | { type: 'ask', ask: object } | { type: 'asked', id: string } | { type: 'notice', notice: object }
+ * | { type: 'gone' }} FolderEvent `gone`: the project was deleted, or its folder is not there any more
*/
/**
@@ -45,6 +48,14 @@ export function watchFolder(root, send) {
const flush = async () => {
timer = null;
+ if (closed) return;
+ /* the folder itself went (deleted, or moved away outside Studio): its pages leave the project. Looked at again a
+ moment later: a rename in Studio moves its pages to the new folder (createWatchers `move`), closing this */
+ if (!existsSync(root)) {
+ await new Promise((done) => setTimeout(done, GONE_RECHECK_MS));
+ if (!closed && !existsSync(root)) send({ type: 'gone' });
+ return;
+ }
const kinds = [...pending];
const changed = paths;
pending.clear();
diff --git a/packages/openfilm/studio/server/watch.test.mjs b/packages/openfilm/studio/server/watch.test.mjs
index afde3e7..23dc9de 100644
--- a/packages/openfilm/studio/server/watch.test.mjs
+++ b/packages/openfilm/studio/server/watch.test.mjs
@@ -152,3 +152,26 @@ test('moving into an already watched path preserves both subscriptions', () => {
rmSync(scratch, { recursive: true, force: true });
}
});
+
+test("a watched project's folder that goes is said gone; one renamed in Studio (moved) is not", async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-watch-gone-'));
+ writeFileSync(join(root, 'film.html'), '{"stage":{"w":1,"h":1},"tracks":[]}');
+ const watchers = createWatchers();
+ const seen = [];
+ const stop = watchers.subscribe(root, (e) => seen.push(e));
+ try {
+ await settle(600);
+ /* renamed by Studio: the watch follows it, and nothing is gone */
+ const renamed = `${root}-renamed`;
+ renameSync(root, renamed);
+ watchers.move(root, renamed);
+ await settle(900);
+ assert.ok(!seen.some((e) => e.type === 'gone'), JSON.stringify(seen));
+ /* deleted (or moved away outside Studio) */
+ rmSync(renamed, { recursive: true, force: true });
+ await settle(1200);
+ assert.ok(seen.some((e) => e.type === 'gone'), JSON.stringify(seen));
+ } finally {
+ stop();
+ }
+});
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index 1a4e767..bd75b88 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -198,7 +198,9 @@ export type StudioNotice = { id: string; kind: 'balance'; provider: string; prov
export type FolderEvent = { type: 'film'; rev: string } | { type: 'files'; paths?: string[] } | { type: 'history' } | { type: 'export'; job: ExportJob } | { type: 'open'; to: string }
| { type: 'history-progress'; op: string; phase: string; done: number; total: number }
- | { type: 'ask'; ask: SpendAsk } | { type: 'asked'; id: string } | { type: 'notice'; notice: StudioNotice } | { type: 'project'; project: Project };
+ | { type: 'ask'; ask: SpendAsk } | { type: 'asked'; id: string } | { type: 'notice'; notice: StudioNotice } | { type: 'project'; project: Project }
+ /* the project was deleted, or its folder is not there any more: its pages leave it */
+ | { type: 'gone' };
/**
* Listen to a stream of events (a WebSocket: a browser's six HTTP connections to Studio stay free for the page's
@@ -208,7 +210,7 @@ export type FolderEvent = { type: 'film'; rev: string } | { type: 'files'; paths
* version (lib/studio-version); the page's own one does. It also tells Studio whether the page is in sight, so
* `openfilm open` opens a browser when no page is (a tab behind others, a minimized window).
*/
-export function listen(path: string, on: (event: FolderEvent) => void, { onBack, watch = false }: { onBack?: () => void; watch?: boolean } = {}): () => void {
+export function listen(path: string, on: (event: FolderEvent) => void, { onBack, watch = false, gone }: { onBack?: () => void; watch?: boolean; gone?: () => Promise<boolean> } = {}): () => void {
const inSight = () => document.visibilityState === 'visible';
const url = () => `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/api/${path}${watch ? `?visible=${inSight() ? 1 : 0}` : ''}`;
const tell = () => { if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ visible: inSight() })); };
@@ -246,6 +248,16 @@ export function listen(path: string, on: (event: FolderEvent) => void, { onBack,
/* soon at first, then every second: Studio restarting (`openfilm open` starts it afresh) is back within one
or two, and waits a few for the pages before it */
again = setTimeout(connect, Math.min(1000, 250 * 2 ** tries++));
+ /* refused again and again while Studio answers: what it streams may be gone (a project deleted, its folder
+ moved away), which reconnecting can't change; asked, and if so said once and left */
+ if (gone && (tries === 3 || tries % 20 === 0)) {
+ void gone().then((yes) => {
+ if (!yes || stopped) return;
+ stopped = true;
+ if (again) clearTimeout(again);
+ on({ type: 'gone' });
+ }, () => {});
+ }
};
};
connect();
@@ -299,7 +311,11 @@ export function projectEvents(id: string, on: (event: FolderEvent) => void): ()
for (const fn of [...listeners]) fn(event);
};
/* back after Studio was away: the film, the files and the history may all have changed meanwhile */
- const stop = listen(`${p(id)}/events`, tell, { onBack: () => { tell({ type: 'film', rev: '' }); tell({ type: 'files' }); tell({ type: 'history' }); } });
+ const stop = listen(`${p(id)}/events`, tell, {
+ onBack: () => { tell({ type: 'film', rev: '' }); tell({ type: 'files' }); tell({ type: 'history' }); },
+ /* the project off the list, or its folder missing: gone (a list that can't be read says nothing) */
+ gone: () => call<{ projects: Project[] }>('projects').then((r) => { const found = r.projects.find((x) => x.id === id); return !found || Boolean(found.missing); }),
+ });
stream = { stop, listeners };
streams.set(id, stream);
}
diff --git a/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx b/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx
index fec2a68..3cc248a 100644
--- a/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx
+++ b/packages/openfilm/studio/ui/src/components/ExamplesGallery.tsx
@@ -3,27 +3,23 @@
*
* · start the projects window's "Examples": the examples only; one is started from (copied into a new project)
* · reference the Community, over a film, from the app's chat (lib/host.ts `onCommand` `show-examples`): two views
- * switched in its title row, Skills first (one is named in the message being written; one of the
- * person's own added), then Examples (one, or a part of it, a segment or a stretch dragged on its strip,
- * is pointed at in the message; starting from one is still there)
+ * switched in its title row, Skills first (SkillsLibrary: those installed, and OpenFilm's to install),
+ * then Examples (one, or a part of it, a segment or a stretch dragged on its strip, is pointed at in the
+ * message; starting from one is still there)
*
- * Examples: the first wide, the others in a grid. Skills: the person's own first, then this project's, then OpenFilm's
- * by kind (ways of working, then looks, each in its openfilm.json `order`), narrowed by a row of filters that stays at
- * the top, beside adding one. Example cards are posters that play their preview under the pointer; skills show their
- * own title and summary (openfilm.json, in the language shown) rather than the words written for the agent. One opened
- * is a page of two columns: its picture or preview on the left, what it is and what to do with it on the right. The
- * title row is the projects window's own, so switching views moves nothing. Esc goes back from a page, else closes.
+ * Examples: the first wide, the others in a grid; cards are posters that play their preview under the pointer. One
+ * opened, an example or a skill, is a page of two columns in place of the list: its preview on the left, what it is
+ * and what to do with it on the right; Back (or Esc) returns to the list as it was. The title row is the projects
+ * window's own, so switching views moves nothing.
*/
import React from 'react';
import { createPortal } from 'react-dom';
-import {
- ArrowLeft, Check, Clapperboard, Copy, ExternalLink, Film, Folder, GitBranch, Info, Layers, MonitorPlay, Music, PenLine,
- PictureInPicture2, Play, Plus, Presentation, Scissors, Search, Shapes, Sparkles, Wand2, X, Github, type LucideIcon,
-} from 'lucide-react';
-import { useLanguage, useT } from '@/i18n';
+import { ArrowLeft, Clapperboard, ExternalLink, Play, X } from 'lucide-react';
+import { useT } from '@/i18n';
import { studioHost, type CommunityItem } from '@/lib/host';
import { seenExamples, seenSkills, sourcesApi, watchSkills, type Example, type SkillEntry } from '@/lib/project-sources';
import { GitHubDialog } from './ProjectSources';
+import { SkillsLibrary } from './SkillsLibrary';
export type ExamplesMode = 'start' | 'reference';
/** A part of an example picked to point at: none for the whole film. */
@@ -31,25 +27,7 @@ export type ExamplePart = { from: number; to: number; segment?: string } | null;
type Opened = { kind: 'example'; example: Example } | { kind: 'skill'; skill: SkillEntry };
-/** The skills' filters: all of them, or one group. */
-type SkillGroup = 'mine' | 'project' | 'workflow' | 'style';
-type SkillFilter = 'all' | SkillGroup;
-
-const byOrder = (a: SkillEntry, b: SkillEntry) => (a.order ?? 999) - (b.order ?? 999) || a.name.localeCompare(b.name);
-
const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
-/** words in the language shown, else its family's, else English, else any */
-const inLanguage = (words: Record<string, string> | undefined, lang: string) =>
- (words ? words[lang] ?? words[lang.split('-')[0]!] ?? words.en ?? Object.values(words)[0] : undefined);
-
-/** A skill as people see it: its title and summary in the language shown, else its name and the agent's description. */
-function useSkillWords() {
- const lang = useLanguage();
- return (skill: SkillEntry) => ({
- title: inLanguage(skill.shown?.title, lang) ?? skill.name,
- summary: inLanguage(skill.shown?.summary, lang) ?? skill.description,
- });
-}
/** Two titles in the title row, the one shown bright (the projects window's switch is the same). */
export function TitleSwitch<T extends string>({ items, value, onChange }: { items: Array<{ id: T; label: string }>; value: T; onChange: (id: T) => void }) {
@@ -65,7 +43,7 @@ export function TitleSwitch<T extends string>({ items, value, onChange }: { item
);
}
-export function ExamplesGallery({ mode, projectId = null, heading, initial, onClose, onStart, onReference, onUseSkill }: {
+export function ExamplesGallery({ mode, projectId = null, heading, initial, onClose, onStart, onReference, onTrySkill }: {
mode: ExamplesMode;
/** open on this skill's or example's page (a pill of one clicked in the chat) */
initial?: CommunityItem;
@@ -76,7 +54,8 @@ export function ExamplesGallery({ mode, projectId = null, heading, initial, onCl
onClose?: () => void;
onStart: (example: Example) => void;
onReference?: (example: Example, part: ExamplePart) => void;
- onUseSkill?: (skill: SkillEntry) => void;
+ /** Try now on a skill: a new conversation in the app's chat with it named */
+ onTrySkill?: (skill: SkillEntry) => void;
}) {
const t = useT();
/* the Community (over a film) opens on its skills; the projects window shows the examples only */
@@ -101,7 +80,6 @@ export function ExamplesGallery({ mode, projectId = null, heading, initial, onCl
if (example) setOpened({ kind: 'example', example });
}
}, [skills, examples]);
- const [filter, setFilter] = React.useState<SkillFilter>('all');
React.useEffect(() => {
let alive = true;
@@ -119,28 +97,25 @@ export function ExamplesGallery({ mode, projectId = null, heading, initial, onCl
return () => window.removeEventListener('keydown', onKey, true);
}, [opened, onClose]);
+ /* a page opened starts at its top; Back returns to the list where it was left */
+ const scroller = React.useRef<HTMLDivElement>(null);
+ const listTop = React.useRef(0);
+ const wasOpen = React.useRef(false);
+ React.useLayoutEffect(() => {
+ const el = scroller.current;
+ const open = opened != null;
+ if (!el || open === wasOpen.current) return;
+ if (open) { listTop.current = el.scrollTop; el.scrollTop = 0; } else el.scrollTop = listTop.current;
+ wasOpen.current = open;
+ }, [opened]);
+
const kindLabel = (c: string) => { const key = `gallery.cat.${c}`; const label = t(key); return label === key ? c : label; };
const show = (next: 'skills' | 'examples') => { setView(next); setOpened(null); };
let body: React.ReactNode;
- if (opened?.kind === 'example') {
- body = <ExampleDetail example={opened.example} mode={mode} onStart={onStart} onReference={onReference} categoryLabel={kindLabel} />;
- } else if (opened?.kind === 'skill') {
- const selected = opened.skill;
- body = <SkillDetail key={`${selected.source}:${selected.name}`} skill={selected} projectId={projectId} mode={mode} onUse={onUseSkill} onCoverChanged={(cover) => {
- const update = (skill: SkillEntry) => skill.source === 'mine' && skill.name === selected.name ? { ...skill, cover: cover ?? undefined } : skill;
- setSkills((list) => list.map(update));
- setOpened((current) => current?.kind === 'skill' ? { ...current, skill: update(current.skill) } : current);
- }} />;
- } else if (view === 'skills') {
- const official = skills.filter((k) => k.source === 'official').sort(byOrder);
- const groups: Array<{ id: SkillGroup; items: SkillEntry[] }> = [
- { id: 'workflow', items: official.filter((k) => k.kind !== 'style') },
- { id: 'style', items: official.filter((k) => k.kind === 'style') },
- { id: 'project', items: skills.filter((k) => k.source === 'project').sort(byOrder) },
- { id: 'mine', items: skills.filter((k) => k.source === 'mine').sort(byOrder) },
- ].filter((g) => g.id !== 'project' || g.items.length) as Array<{ id: SkillGroup; items: SkillEntry[] }>;
- body = <SkillsView groups={groups} filter={filter === 'all' || groups.some((g) => g.id === filter) ? filter : 'all'} onFilter={setFilter} onOpen={(k) => setOpened({ kind: 'skill', skill: k })} />;
+ if (view === 'skills') {
+ body = <SkillsLibrary skills={skills} setSkills={setSkills} projectId={projectId} opened={opened?.kind === 'skill' ? opened.skill : null}
+ onOpen={(skill) => setOpened({ kind: 'skill', skill })} onBack={() => setOpened(null)} {...(onTrySkill ? { onTry: onTrySkill } : {})} />;
} else if (examples == null) {
body = <Empty text={t('gallery.loading')} />;
} else if (!examples.length) {
@@ -159,13 +134,22 @@ export function ExamplesGallery({ mode, projectId = null, heading, initial, onCl
</Body>
);
}
+ /* an example opened: its page in place of the list, the list kept (hidden) so Back finds it where it was */
+ if (opened?.kind === 'example') {
+ body = (
+ <>
+ <ExampleDetail example={opened.example} mode={mode} onStart={onStart} onReference={onReference} categoryLabel={kindLabel} />
+ <div hidden>{body}</div>
+ </>
+ );
+ }
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
{/* the same row as the projects' (ProjectsView): switching between them moves nothing */}
<header className="flex shrink-0 flex-col px-6 pb-4 pt-5">
<div className="flex min-h-8 items-center gap-1">
- {/* an opened one has its way back here, where the switch was */}
+ {/* an example or a skill opened has its way back here, where the switch was */}
{opened ? (
<button type="button" onClick={() => setOpened(null)} className="mr-auto flex h-8 items-center gap-1.5 rounded-lg pl-1 pr-2.5 text-[13.5px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
<ArrowLeft size={16} strokeWidth={1.75} />{t('gallery.back')}
@@ -179,7 +163,7 @@ export function ExamplesGallery({ mode, projectId = null, heading, initial, onCl
) : null}
</div>
</header>
- <div className="min-h-0 min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">{body}</div>
+ <div ref={scroller} className="min-h-0 min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">{body}</div>
</div>
);
}
@@ -194,115 +178,6 @@ function Body({ note, children }: { note?: string; children: React.ReactNode })
);
}
-const GROUP_LABEL: Record<SkillGroup, string> = { mine: 'gallery.mine', project: 'gallery.project', workflow: 'gallery.workflow', style: 'gallery.style' };
-
-/**
- * The skills: filters on the left (all of OpenFilm's, its workflows, its looks; this project's; the person's own),
- * adding one and a search on the right, all in a row that stays at the top; then the cards. "All" shows OpenFilm's
- * under their kinds; the person's own are their own filter. What skills are for is a note behind the (i).
- */
-function SkillsView({ groups, filter, onFilter, onOpen }: {
- groups: Array<{ id: SkillGroup; items: SkillEntry[] }>; filter: SkillFilter; onFilter: (f: SkillFilter) => void; onOpen: (k: SkillEntry) => void;
-}) {
- const t = useT();
- const words = useSkillWords();
- const [query, setQuery] = React.useState('');
- const q = query.trim().toLowerCase();
- const matches = (k: SkillEntry) => !q || [words(k).title, words(k).summary, k.name].some((w) => w?.toLowerCase().includes(q));
- const shown = (filter === 'all' ? groups.filter((g) => g.id === 'workflow' || g.id === 'style') : groups.filter((g) => g.id === filter))
- .map((g) => ({ ...g, items: g.items.filter(matches) }));
- const chip = (id: SkillFilter, label: string, count?: number) => (
- <button key={id} type="button" role="tab" aria-selected={filter === id} onClick={() => onFilter(id)}
- className={`flex h-8 shrink-0 items-center gap-1.5 rounded-[8px] px-3 text-[13px] transition ${filter === id ? 'bg-[var(--bg-hover)] font-medium text-[var(--text)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>
- {label}{count ? <span className="text-[var(--text-faint)]">{count}</span> : null}
- </button>
- );
- const own = groups.filter((g) => g.id === 'project' || g.id === 'mine');
- return (
- <div className="pb-10">
- <div className="sticky top-0 z-[1] flex items-center gap-1 bg-[var(--app-content-bg)] px-6 pb-4">
- <div role="tablist" className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">
- {chip('all', t('gallery.all'))}
- {chip('workflow', t('gallery.workflow'))}
- {chip('style', t('gallery.style'))}
- <span className="mx-2 h-4 w-px shrink-0 bg-[var(--border-strong)]" />
- {own.map((g) => chip(g.id, t(GROUP_LABEL[g.id]), g.items.length))}
- <AboutSkills />
- </div>
- {studioHost?.skills ? (
- <button type="button" onClick={() => studioHost?.skills?.add()}
- className="flex h-9 shrink-0 items-center gap-1.5 rounded-[9px] border border-[var(--border)] px-3 text-[13px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={14} />{t('gallery.addSkill')}</button>
- ) : null}
- <label className="ml-2 flex h-9 w-[260px] shrink-0 items-center gap-2 rounded-[9px] bg-[var(--surface-2)] px-3 text-[var(--text-faint)] ring-1 ring-[var(--border)] focus-within:ring-[var(--border-strong)]">
- <Search size={14} strokeWidth={1.75} />
- <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('gallery.search')}
- className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />
- {query ? <button type="button" aria-label={t('project.close')} onClick={() => setQuery('')} className="hover:text-[var(--text)]"><X size={13} /></button> : null}
- </label>
- </div>
- <div className="px-6">
- {shown.map((g, i) => (
- <section key={g.id} className={i ? 'mt-10' : ''}>
- {filter === 'all' && g.items.length ? <h3 className="mb-4 text-[15px] font-semibold text-[var(--text)]">{t(GROUP_LABEL[g.id])}</h3> : null}
- {g.items.length ? <Grid>{g.items.map((k) => <SkillCard key={`${k.source}:${k.name}`} skill={k} onOpen={() => onOpen(k)} />)}</Grid>
- : q ? <Empty text={t('gallery.noMatch')} /> : g.id === 'mine' ? <NoSkills /> : null}
- </section>
- ))}
- </div>
- </div>
- );
-}
-
-/** What skills are for, behind an (i) at the end of the filters: shown while the pointer or focus is on it. */
-function AboutSkills() {
- const t = useT();
- const [open, setOpen] = React.useState(false);
- return (
- <span className="relative ml-1 flex shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
- <button type="button" aria-label={t('gallery.aboutSkills')} aria-expanded={open} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}
- className="flex h-8 w-8 items-center justify-center rounded-[8px] text-[var(--text-faint)] transition hover:text-[var(--text)]">
- <Info size={15} strokeWidth={1.75} />
- </button>
- {open ? (
- <span role="tooltip" className="fixed z-[10060] mt-9 w-[400px] whitespace-pre-line rounded-[10px] border border-[var(--border-strong)] bg-[var(--dock-pane)] px-4 py-3.5 text-[12.5px] leading-[20px] text-[var(--text-muted)] shadow-[0_12px_32px_rgba(0,0,0,0.35)]">
- {t('gallery.skillKinds')}
- </span>
- ) : null}
- </span>
- );
-}
-
-/** None of the person's skills yet: what theirs are for, and how to get one. */
-function NoSkills() {
- const t = useT();
- return (
- <div className="flex flex-col items-center rounded-[12px] border border-dashed border-[var(--border-strong)] px-6 py-12 text-center">
- <Sparkles size={22} strokeWidth={1.5} className="text-[var(--text-faint)]" />
- <p className="mt-3 max-w-[520px] text-[13px] leading-[20px] text-[var(--text-muted)]">{t('gallery.noSkills')}</p>
- {studioHost?.skills ? (
- <button type="button" onClick={() => studioHost?.skills?.add()}
- className="mt-4 flex h-9 items-center gap-1.5 rounded-[9px] border border-[var(--border)] px-3.5 text-[13px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={14} />{t('gallery.addSkill')}</button>
- ) : null}
- </div>
- );
-}
-
-/** Where one of the person's skills came from, as a short line: GitHub · owner/repo, a folder's name, or made here. */
-function Origin({ skill }: { skill: SkillEntry }) {
- const t = useT();
- const o = skill.origin;
- if (!o) return null;
- let icon = <Wand2 size={12} />, text = t('gallery.made');
- if (o.from === 'link') {
- icon = <GitBranch size={12} />;
- try { const u = new URL(o.address); text = `${u.hostname.replace(/^www\./, '').replace(/\.com$/, '').replace(/^github$/, 'GitHub').replace(/^gitlab$/, 'GitLab')} · ${u.pathname.split('/').filter(Boolean).slice(0, 2).join('/')}`; } catch { text = o.address; }
- } else if (o.from === 'folder') {
- icon = <Folder size={12} />;
- text = `${t('gallery.fromFolder')} · ${o.address.split(/[\\/]/).filter(Boolean).pop() ?? o.address}`;
- }
- return <div title={o.from === 'made' ? undefined : o.address} className="mt-2 flex min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--text-faint)]">{icon}<span className="truncate">{text}</span></div>;
-}
-
function Empty({ text }: { text: string }) {
return <p className="py-14 text-center text-[13px] text-[var(--text-muted)]">{text}</p>;
}
@@ -366,134 +241,6 @@ function ExampleCard({ example, label, onOpen }: { example: Example; label: stri
);
}
-const ICONS: Record<string, LucideIcon> = {
- copy: Copy, scissors: Scissors, monitor: MonitorPlay, shapes: Shapes, pip: PictureInPicture2, pen: PenLine, film: Film,
- music: Music, presentation: Presentation, layers: Layers,
-};
-/** each mark its own color, so the covers tell apart at a glance */
-const HUES: Record<string, number> = { copy: 212, scissors: 18, monitor: 188, shapes: 262, pip: 328, pen: 42, film: 28, music: 286, presentation: 228, layers: 6 };
-
-/** A skill's picture: its cover, else its preview's first frame, else a tile of its mark and title in its own color. */
-function SkillCover({ skill, title, big = false, playing = false }: { skill: SkillEntry; title: string; big?: boolean; playing?: boolean }) {
- const [failed, setFailed] = React.useState(false);
- if (skill.cover && !failed) {
- return (
- <>
- <img src={skill.cover} alt="" loading="lazy" draggable={false} onError={() => setFailed(true)} className="absolute inset-0 h-full w-full object-cover" />
- {playing && skill.preview ? <video src={skill.preview} autoPlay muted loop playsInline className="absolute inset-0 h-full w-full object-cover" /> : null}
- </>
- );
- }
- const Mark = ICONS[skill.icon ?? ''] ?? Sparkles;
- const hue = HUES[skill.icon ?? ''] ?? 220;
- return (
- <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 px-6 text-center"
- style={{ background: `radial-gradient(110% 90% at 25% 0%, hsl(${hue} 70% 55% / 0.22), transparent 62%), radial-gradient(90% 80% at 100% 100%, hsl(${hue} 70% 50% / 0.12), transparent 60%), var(--surface-2)` }}>
- <span className={`flex items-center justify-center rounded-[14px] ${big ? 'h-16 w-16' : 'h-14 w-14'}`}
- style={{ background: `hsl(${hue} 70% 55% / 0.16)`, color: `hsl(${hue} 80% 72%)`, boxShadow: `0 0 0 1px hsl(${hue} 70% 60% / 0.28)` }}>
- <Mark size={big ? 28 : 24} strokeWidth={1.6} />
- </span>
- {/* a card has its title under it; the page's big picture carries it */}
- {big ? <span className="line-clamp-2 text-[22px] font-semibold tracking-[-0.01em] text-[var(--text)]">{title}</span> : null}
- </div>
- );
-}
-
-function SkillCard({ skill, onOpen }: { skill: SkillEntry; onOpen: () => void }) {
- const words = useSkillWords()(skill);
- const [hover, setHover] = React.useState(false);
- return (
- <button type="button" onClick={onOpen} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} className="group flex min-w-0 flex-col text-left outline-none">
- <div className="relative aspect-video w-full overflow-hidden rounded-[12px] ring-1 ring-[var(--border)] transition group-hover:ring-[var(--border-strong)] group-focus-visible:ring-2 group-focus-visible:ring-[var(--text-muted)]">
- <SkillCover key={skill.cover ?? ''} skill={skill} title={words.title} playing={hover} />
- </div>
- <div className="mt-3 truncate text-[14.5px] font-semibold tracking-[-0.005em] text-[var(--text)]">{words.title}</div>
- {words.summary ? <div className="mt-1 line-clamp-2 text-[12.5px] leading-[18px] text-[var(--text-muted)]">{words.summary}</div> : null}
- <Origin skill={skill} />
- </button>
- );
-}
-
-/**
- * A skill on its own: its preview (or picture) large on the left; on the right its title, kind and version, who it is
- * for and what it does, what the agent reads, and using it, at the bottom.
- */
-function SkillDetail({ skill, projectId, mode, onUse, onCoverChanged }: {
- skill: SkillEntry; projectId: string | null; mode: ExamplesMode; onUse?: (skill: SkillEntry) => void; onCoverChanged: (cover: string | null) => void;
-}) {
- const t = useT();
- const lang = useLanguage();
- const words = useSkillWords()(skill);
- const details = inLanguage(skill.shown?.details, lang);
- const group: SkillGroup = skill.source === 'official' ? (skill.kind === 'style' ? 'style' : 'workflow') : skill.source;
- const source = skill.repository ?? (skill.origin?.from === 'link' ? skill.origin.address : undefined);
- const [busy, setBusy] = React.useState(false);
- const [error, setError] = React.useState<string | null>(null);
- const coverInput = React.useRef<HTMLInputElement>(null);
- const changeCover = async (file: File | null) => {
- setBusy(true);
- setError(null);
- try {
- let cover: string | null = null;
- if (file) {
- if (file.size > 5 * 1024 * 1024 || !['image/png', 'image/jpeg', 'image/webp'].includes(file.type)) throw new Error(t('gallery.coverInvalid'));
- cover = await new Promise<string>((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => resolve(String(reader.result));
- reader.onerror = () => reject(new Error(t('gallery.coverInvalid')));
- reader.readAsDataURL(file);
- });
- const image = new Image();
- image.src = cover;
- await image.decode().catch(() => { throw new Error(t('gallery.coverInvalid')); });
- }
- onCoverChanged(await sourcesApi.setSkillCover(skill.name, cover, projectId));
- } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
- finally { setBusy(false); }
- };
- return (
- <div className="grid h-full min-h-0 grid-cols-[minmax(0,1.65fr)_minmax(320px,1fr)] border-t border-[var(--border)]">
- <div className="flex min-h-0 flex-col items-center justify-center gap-4 bg-[color-mix(in_srgb,var(--bg)_55%,transparent)] p-8">
- <div className="relative aspect-video w-full overflow-hidden rounded-[12px] bg-black ring-1 ring-[var(--border)]">
- {skill.preview ? <video src={skill.preview} poster={skill.cover} autoPlay muted loop controls playsInline className="absolute inset-0 h-full w-full object-contain" />
- : <SkillCover key={skill.cover ?? ''} skill={skill} title={words.title} big />}
- </div>
- {skill.source === 'mine' ? <div className="flex flex-wrap items-center justify-center gap-3 text-[12px] text-[var(--text-muted)]">
- <button type="button" disabled={busy} onClick={() => coverInput.current?.click()} className="h-9 rounded-[9px] px-3 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40">{t(skill.cover ? 'gallery.changeCover' : 'gallery.chooseCover')}</button>
- <input ref={coverInput} type="file" accept="image/png,image/jpeg,image/webp" aria-label={t(skill.cover ? 'gallery.changeCover' : 'gallery.chooseCover')} disabled={busy} hidden
- onChange={(e) => { const file = e.target.files?.[0]; e.target.value = ''; if (file) void changeCover(file); }} />
- {skill.cover ? <button type="button" disabled={busy} onClick={() => void changeCover(null)} className="h-9 rounded-[9px] px-3 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40">{t('gallery.removeCover')}</button> : null}
- {busy ? <span role="status">{t('gallery.coverSaving')}</span> : null}
- </div> : null}
- {error ? <p role="alert" className="text-[12px] text-[var(--warn)]">{error}</p> : null}
- </div>
- <div className="flex min-h-0 flex-col border-l border-[var(--border)]">
- <div className="min-h-0 flex-1 overflow-y-auto px-7 pt-7">
- <h2 className="text-[22px] font-semibold leading-tight tracking-[-0.015em] text-[var(--text)]">{words.title}</h2>
- <div className="mt-2.5 flex items-center gap-2 text-[12px] text-[var(--text-muted)]">
- <span>{t(GROUP_LABEL[group])}</span>
- {skill.version ? <span className="rounded-[5px] border border-[var(--border)] px-1.5 py-[1px] font-mono text-[10.5px] text-[var(--text-dim)]">v{skill.version}</span> : null}
- {/* its source: OpenFilm's repository, or the address one of the person's came from */}
- {source ? (
- <a href={source} target="_blank" rel="noreferrer" title={source} aria-label={t('gallery.viewSource')}
- className="flex h-6 w-6 items-center justify-center rounded-[6px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><Github size={14} strokeWidth={1.75} /></a>
- ) : null}
- </div>
- <Origin skill={skill} />
- {words.summary ? <p className="mt-5 text-[14px] leading-[22px] text-[var(--text)]">{words.summary}</p> : null}
- {details ? details.split('\n').map((line) => <p key={line} className="mt-3 text-[13.5px] leading-[22px] text-[var(--text-muted)]">{line}</p>) : null}
- </div>
- <div className="shrink-0 px-7 pb-7 pt-4">
- {mode === 'reference' && onUse ? (
- <button type="button" onClick={() => onUse(skill)}
- className="flex h-11 w-full items-center justify-center gap-1.5 rounded-[10px] bg-[var(--text)] text-[14px] font-medium text-[var(--bg)] transition hover:opacity-90"><Check size={15} />{t('gallery.useSkill')}</button>
- ) : null}
- </div>
- </div>
- </div>
- );
-}
-
/**
* An example on its own: its preview with sound, its parts on a strip (one picked by a click, a stretch by dragging
* across them; none: the whole film), and what to do with it.
@@ -611,7 +358,7 @@ export function ExamplesDialog({ projectId, open, onClose, onStarted }: { projec
onClose={onClose}
onStart={setStarting}
onReference={reference}
- onUseSkill={(skill) => { studioHost?.useSkill?.({ name: skill.name, description: skill.description }); onClose(); }}
+ onTrySkill={(skill) => { studioHost?.useSkill?.({ name: skill.name, description: skill.description, newConversation: true }); onClose(); }}
/>
</div>
{starting ? (
diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
index 6d2d00c..9a1b7a4 100644
--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
@@ -18,7 +18,7 @@ import * as React from 'react';
import {
AlignCenterHorizontal, AlignCenterVertical, AlignEndHorizontal, AlignEndVertical, AlignHorizontalDistributeCenter,
AlignStartHorizontal, AlignStartVertical, AlignVerticalDistributeCenter, ArrowRightToLine, AudioLines, Captions,
- Check, ChevronRight, CircleAlert, Clapperboard, Copy, Film, Gauge, Image as ImageIcon, Link2, Maximize2, MousePointerClick,
+ Check, ChevronRight, CircleAlert, Clapperboard, Copy, Diamond, Film, Gauge, Image as ImageIcon, Link2, Maximize2, MousePointerClick,
Lock, MoveHorizontal, Music, Replace, RotateCcw, Scissors, Shapes, Sparkles, Square, Type, Unlink2, Video, Volume2, X,
} from 'lucide-react';
@@ -40,9 +40,9 @@ import { editsForMoves } from '@/lib/timeline-drag';
import { useTimelinePrefs } from '@/lib/timeline-prefs';
import { formatTimecode, FRAME_RATES, timecodeFps, useTimecodeFps } from '@/lib/timecode';
import { MenuSelect } from './MenuSelect';
-import { CANVAS_SIDE, canvasSide } from '@/lib/canvas-fit';
+import { CANVAS_SIDE, canvasSide, originalShape, shaped } from '@/lib/canvas-fit';
import { filmFrameOf, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';
-import { CANVAS_RATIOS, canvasRatioLabel, shaped } from './FramePicker';
+import { CANVAS_RATIOS, canvasRatioLabel } from './FramePicker';
import { declared, withDeclarations, type ClipLook } from '@/lib/clip-look';
import { PANE_BAR, PANE_BTN, PANE_ICON, PANE_TITLE } from './dock-pane-bar';
import { Tooltip } from './Tooltip';
@@ -60,7 +60,10 @@ import type { MaskSession } from '@/lib/stage-mask';
import type { MaskShape } from '@/lib/clip-mask';
import type { FadeMs } from '@/lib/clip-fade';
import type { FoundKind } from '@/lib/transitions';
-import { TemplateSection, type TemplateHost } from './TemplateSection';
+import { PictureInput, PropertiesSection, type PropsHost } from './PropertiesSection';
+import { propOf, withProp, withoutProp, type ComponentProp } from '@/lib/component-props';
+import { layerTarget } from '@/lib/stage-layers';
+import type { StagePictureActions } from './stage-menu';
/** A change of a layer's words (kept as its `text` override). `expect` is what it said before: painted back on refusal. */
export type StageTextEdit = {
@@ -87,7 +90,7 @@ export type FilmSummary = {
durationMs: number;
tracks: number;
clips: number;
- /** Nothing made yet: the stage itself may change shape (see FramePicker). */
+ /** Nothing made yet: the stage itself may change shape. */
empty: boolean;
/** Each track's name (P1, V2, A1; see filmTrackBadges), by its place in film.html. */
badges?: readonly string[];
@@ -168,6 +171,7 @@ export const FilmInspector = React.memo(function FilmInspector({
onCanvas,
onCanvasPreview,
canvasDraft,
+ canvasOriginal,
layers,
onEditLayers,
onPlaceLayers,
@@ -175,7 +179,9 @@ export const FilmInspector = React.memo(function FilmInspector({
rate,
fades,
transition,
- templateOf,
+ propsHostOf,
+ pictures,
+ layerProps,
}: {
element: StageElement | null;
/** The clips selected on the timeline. A layer picked on the picture wins: one selection at a time. */
@@ -240,6 +246,8 @@ export const FilmInspector = React.memo(function FilmInspector({
onCanvasPreview?: (size: { w: number; h: number } | null) => void;
/** That size, while it is shown. */
canvasDraft?: { w: number; h: number } | null;
+ /** The first picture's own size: the canvas's "Original" shape. None: nothing to fit to yet. */
+ canvasOriginal?: { w: number; h: number } | null;
/** Several layers selected on the picture, and how to write them at once. */
layers?: readonly StageElement[];
onEditLayers?: (list: LayerEdit[]) => Promise<string | null>;
@@ -253,8 +261,12 @@ export const FilmInspector = React.memo(function FilmInspector({
fades?: ReadonlyMap<string, FadeMs>;
/** The transition picked on the timeline (no clip selected): its kind and length, made longer or taken away here. */
transition?: TransitionPick | null;
- /** A page clip's template controls (TemplateSection): read from its page, written as its overrides. */
- templateOf?: (block: TimelineBlock) => TemplateHost | null;
+ /** A page clip's properties (PropertiesSection): read from its page, written as its overrides and its data-props. */
+ propsHostOf?: (block: TimelineBlock) => PropsHost | null;
+ /** Another file in the place of a picture inside a page (a layer's Picture section). */
+ pictures?: StagePictureActions;
+ /** A layer made a property of its clip (◇ beside its words, its picture, its showing). */
+ layerProps?: LayerPropsActions;
}) {
const t = useT();
useCommitBeforeLeaving();
@@ -306,6 +318,8 @@ export const FilmInspector = React.memo(function FilmInspector({
onSelectParent={onSelectParent}
onSelectClip={onSelectClip}
{...(onEditMask ? { onEditMask } : {})}
+ {...(pictures ? { pictures } : {})}
+ {...(layerProps ? { layerProps } : {})}
/>
) : clip ? (
<ClipPanel
@@ -326,7 +340,7 @@ export const FilmInspector = React.memo(function FilmInspector({
badges={film?.badges}
stage={stageSize}
{...(fades ? { fades } : {})}
- {...(templateOf ? { templateOf } : {})}
+ {...(propsHostOf ? { propsHostOf } : {})}
/>
) : many ? (
<MultiClipPanel
@@ -342,7 +356,7 @@ export const FilmInspector = React.memo(function FilmInspector({
) : geometry?.kind === 'group' && geometry.group ? (
<GroupPanel geometry={geometry} group={geometry.group} layers={layers} onEditLayers={onEditLayers} {...(onPlaceLayers ? { onPlace: onPlaceLayers } : {})} t={t} />
) : (
- <FilmPanel t={t} stage={stageSize} draft={canvasDraft} film={film ?? null} onCanvas={onCanvas} onCanvasPreview={onCanvasPreview} rate={rate ?? null} />
+ <FilmPanel t={t} stage={stageSize} draft={canvasDraft} film={film ?? null} onCanvas={onCanvas} onCanvasPreview={onCanvasPreview} original={canvasOriginal ?? null} rate={rate ?? null} />
)}
</div>
</fieldset>
@@ -389,12 +403,12 @@ function RedesignHint({ t, stage }: { t: T; stage: { w: number; h: number } }) {
}
/**
- * The film itself: its name, its stage and shape, how long it is, what is in it. The shape changes as the
- * player's ratio button changes it (FramePicker): the canvas itself, at any time, as an image editor's canvas size
- * (what is on it stays as it is, centered); laying the film out again for it is the agent's (RedesignHint).
+ * The film itself: its name, its stage and shape, how long it is, what is in it. Picking a shape changes the canvas
+ * itself, at any time, as an image editor's canvas size: the film is scaled whole into it, centered; laying the film
+ * out again for it is the agent's (RedesignHint). "Original" takes the shape of the first picture.
*/
function FilmPanel({
- t, stage: kept, draft, film, onCanvas, onCanvasPreview, rate,
+ t, stage: kept, draft, film, onCanvas, onCanvasPreview, original, rate,
}: {
t: T;
stage: { w: number; h: number };
@@ -403,6 +417,7 @@ function FilmPanel({
film: FilmSummary | null;
onCanvas?: (next: FilmFrameId, size?: { w: number; h: number }) => void;
onCanvasPreview?: (size: { w: number; h: number } | null) => void;
+ original: { w: number; h: number } | null;
rate: { fps: number; fromFootage: boolean; onChange: (fps: number) => void } | null;
}) {
const canvas = Boolean(onCanvas);
@@ -410,6 +425,7 @@ function FilmPanel({
const stage = draft ?? kept;
const placed = Boolean(film && !film.empty);
const preset = CANVAS_RATIOS.find((r) => shaped(stage, filmFrameRatio(r.id, stage)));
+ const { frame: fit, current: isFit } = originalShape(stage, original);
const setSize = (w: number, h: number) => {
const size = { w, h };
if (size.w === kept.w && size.h === kept.h) { onCanvasPreview?.(null); return; }
@@ -432,13 +448,20 @@ function FilmPanel({
{canvas ? (
<MenuSelect
label={t('inspector.stageShape')}
- value={preset?.id ?? 'custom'}
+ value={isFit ? 'original' : preset?.id ?? 'custom'}
groups={[
- { choices: preset ? [] : [{ value: 'custom', label: t('viewer.frameCustom') }] },
+ {
+ choices: [
+ ...(fit ? [{ value: 'original', label: t('viewer.ratioOriginal') }] : []),
+ ...(preset || isFit ? [] : [{ value: 'custom', label: t('viewer.frameCustom') }]),
+ ],
+ },
{ choices: CANVAS_RATIOS.filter((r) => r.group === 'wide').map((r) => ({ value: r.id, label: canvasRatioLabel(t, r) })) },
{ choices: CANVAS_RATIOS.filter((r) => r.group === 'tall').map((r) => ({ value: r.id, label: canvasRatioLabel(t, r) })) },
].filter((g) => g.choices.length)}
- onPick={(id) => { if (id !== 'custom') onCanvas?.(id as FilmFrameId); }}
+ onPick={(id) => {
+ if (id === 'original') { if (fit) onCanvas?.(fit); } else if (id !== 'custom') onCanvas?.(id as FilmFrameId);
+ }}
/>
) : null}
<Row>
@@ -749,7 +772,7 @@ type Scope = 'one' | 'all' | 'similar';
function LayerPanel({
element, geometry, inlineTextFailure, onEditStyle, onEditSimilar, countSimilar, onPreviewStyle, onEditText, onPreviewText,
- onEditOverride, onPreviewOverride, onSelectParent, onSelectClip, onEditMask,
+ onEditOverride, onPreviewOverride, onSelectParent, onSelectClip, onEditMask, pictures, layerProps,
}: {
element: StageElement;
geometry?: StageGeometry | null;
@@ -772,6 +795,8 @@ function LayerPanel({
onSelectParent?: (loc: string, clipLoc?: string) => void;
onSelectClip?: (clipLoc: string) => void;
onEditMask?: (session: MaskSession | null) => void;
+ pictures?: StagePictureActions;
+ layerProps?: LayerPropsActions;
}) {
const t = useT();
const [refusal, setRefusalState] = React.useState<string | null>(null);
@@ -970,6 +995,7 @@ function LayerPanel({
{element.text ? (
<TextSection
text={element.text}
+ {...(layerProps ? { aside: <PropButton element={element} type="text" actions={layerProps} t={t} /> } : {})}
shared={copies}
onEditText={onEditText}
onPreviewText={onPreviewText}
@@ -977,6 +1003,32 @@ function LayerPanel({
/>
) : null}
+ {/* a picture: another file in its place, from the project or this computer, or dropped from the media pane */}
+ {element.picture && pictures ? (
+ <Section
+ id="picture"
+ title={t('inspector.picture')}
+ aside={(
+ <span className="flex items-center">
+ {element.picture.changed ? (
+ <SectionAction label={t('stageMenu.pictureOwn')} onClick={() => pictures.put(element, null)}>
+ <RotateCcw size={11} />
+ </SectionAction>
+ ) : null}
+ {layerProps ? <PropButton element={element} type="image" actions={layerProps} t={t} /> : null}
+ </span>
+ )}
+ >
+ <PictureInput
+ src={element.picture.src}
+ host={{ pictures: pictures.pictures, ...(pictures.pickFromComputer ? { pickPicture: pictures.pickFromComputer } : {}) }}
+ label={t('inspector.picture')}
+ onPick={(path) => pictures.put(element, path)}
+ t={t}
+ />
+ </Section>
+ ) : null}
+
{canMove ? (
<Section
id="position"
@@ -1094,7 +1146,12 @@ function LayerPanel({
/>
{/* in this order: appearance, fill, stroke, effects; then the picture's color adjustments */}
- <AppearanceSection look={look} t={t} radius={kind === 'box' || kind === 'image' || textFilled} />
+ <AppearanceSection
+ look={look}
+ t={t}
+ radius={kind === 'box' || kind === 'image' || textFilled}
+ {...(layerProps ? { aside: <PropButton element={element} type="boolean" actions={layerProps} t={t} /> } : {})}
+ />
<FillSection
look={look}
t={t}
@@ -1136,10 +1193,54 @@ function LayerPanel({
/**
* The words themselves, saved on blur — painted as they are typed, written once.
*/
+/** Making a layer a property of its clip, and no longer: the inspector's ◇ (lib/component-props). */
+export interface LayerPropsActions {
+ /** The properties of the layer's clip now. */
+ list: (element: StageElement) => ComponentProp[];
+ /** Write them. */
+ save: (element: StageElement, next: readonly ComponentProp[]) => void;
+}
+
+/**
+ * ◇ beside the layer's words, its picture or its showing: makes it a property of the clip (named from what it is, renamed
+ * in the clip's Properties), or, filled when it is one, takes the property away.
+ */
+function PropButton({ element, type, actions, t }: {
+ element: StageElement; type: 'text' | 'image' | 'boolean'; actions: LayerPropsActions; t: T;
+}) {
+ const list = actions.list(element);
+ const picture = element.picture;
+ /* a frame holding one picture: the property is its <img>'s */
+ const own = layerTarget(element);
+ const target = type === 'image' && picture?.at ? { at: picture.at, ...(picture.n ? { n: picture.n } : {}) } : own;
+ if (!target || (type === 'image' && !picture)) return null;
+ const bound = propOf(list, type, target);
+ const words = element.text?.value.replace(/\s+/g, ' ').trim() ?? '';
+ const file = picture ? decodeURIComponent(picture.src.split(/[?#]/)[0]!.split('/').pop() ?? '').replace(/\.[^.]+$/, '') : '';
+ const name = type === 'text' ? (words.length > 24 ? `${words.slice(0, 24)}…` : words) || t('inspector.propText')
+ : type === 'image' ? file || t('inspector.picture')
+ /* a layer named by its tag alone (div) is named by its picture, else its kind */
+ : t('inspector.propShowName').replace('{name}', element.label && element.label !== element.tag ? element.label
+ : file || (element.kind === 'clip' ? element.label : layerKindLabel(t, element.kind)));
+ const label = bound
+ ? t('inspector.propBound').replace('{name}', bound.name)
+ : t(type === 'text' ? 'inspector.propMakeText' : type === 'image' ? 'inspector.propMakePicture' : 'inspector.propMakeShow');
+ const make = (): ComponentProp => (type === 'image'
+ ? { name, type, kind: picture!.kind, ...target }
+ : { name, type, ...target });
+ return (
+ <SectionAction label={label} onClick={() => actions.save(element, bound ? withoutProp(list, bound.name) : withProp(list, make()))}>
+ <Diamond size={11} className={bound ? 'fill-[var(--accent)] text-[var(--accent)]' : ''} />
+ </SectionAction>
+ );
+}
+
function TextSection({
- text, shared, onEditText, onPreviewText, onRefused,
+ text, shared, onEditText, onPreviewText, onRefused, aside,
}: {
text: NonNullable<StageElement['text']>;
+ /** Beside the title: making the words a property of the clip. */
+ aside?: React.ReactNode;
/** How many copies share these words: changing them changes all, and the panel says so. */
shared: number;
onEditText: (edit: StageTextEdit) => Promise<StageEditFailure | null>;
@@ -1189,9 +1290,14 @@ function TextSection({
<Section
id="text"
title={t('inspector.content')}
- aside={shared ? (
- <span className="text-[10.5px] text-[var(--text-faint)]">
- {t('inspector.mapTextShared').replace('{n}', String(shared))}
+ aside={shared || aside ? (
+ <span className="flex items-center gap-1.5">
+ {shared ? (
+ <span className="text-[10.5px] text-[var(--text-faint)]">
+ {t('inspector.mapTextShared').replace('{n}', String(shared))}
+ </span>
+ ) : null}
+ {aside}
</span>
) : null}
>
@@ -1376,10 +1482,10 @@ function clipsLook(
*/
function ClipPanel({
block, onMain, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, replaceEntries, clipLookOf, onPreviewLook, onStartCrop, onEditMask, maskAsk, onMaskAsked, fades,
- templateOf,
+ propsHostOf,
}: {
fades?: ReadonlyMap<string, FadeMs>;
- templateOf?: (block: TimelineBlock) => TemplateHost | null;
+ propsHostOf?: (block: TimelineBlock) => PropsHost | null;
replaceEntries?: (block: TimelineBlock) => ContextMenuEntry[];
block: TimelineBlock;
/** On the main track, where the magnet acts. */
@@ -1425,10 +1531,10 @@ function ClipPanel({
const at = parseFilmDocLoc(loc ?? '');
const badge = at ? badges?.[at.track] : undefined;
/* the same host while the same clip is in hand: the section reads the page again when its overrides change */
- const template = React.useMemo(
- () => (block.kind === 'mg' && docLoc && templateOf ? templateOf(block) : null),
+ const propsHost = React.useMemo(
+ () => (block.kind === 'mg' && docLoc && propsHostOf ? propsHostOf(block) : null),
// eslint-disable-next-line react-hooks/exhaustive-deps
- [templateOf, block.clipId, block.kind, docLoc],
+ [propsHostOf, block.clipId, block.kind, docLoc],
);
return (
@@ -1450,9 +1556,9 @@ function ClipPanel({
</p>
) : (
<>
- {/* a page's own controls first: what a template is used for */}
- {template ? (
- <TemplateSection host={template} commit={(next) => commit([{ loc: loc!, prop: 'overrides', value: next as unknown as Record<string, unknown> | null }])} />
+ {/* a page's properties first: what it offers to change */}
+ {propsHost ? (
+ <PropertiesSection host={propsHost} commit={(next) => commit([{ loc: loc!, prop: 'overrides', value: next as unknown as Record<string, unknown> | null }])} />
) : null}
{picture && own && geo ? (
<ClipPositionSection
diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
index 99dae36..90f179d 100644
--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
@@ -80,9 +80,10 @@ import type { StageBox } from '@/lib/host';
import { samePictureMarks, type PictureMarks } from '@/lib/chat-marks';
import { distributeShifts } from '@/lib/selection-toolbar';
import { trackLockedAt } from '@/lib/track-lock';
+import { peekResourceDrag, readResourceDragData, RESOURCE_DRAG_TYPE } from '@/lib/resource-drag';
import {
compactScale, type NodeOverride, type StageElement, type StageElementStyle, type StageGeometry, type StageNodeKind,
- type StageNodeParent,
+ type StageNodeParent, type StagePicture,
} from '@/lib/stage-types';
export type { LayerGeometry } from '@/lib/stage-gesture';
@@ -135,6 +136,8 @@ export interface StageLayer {
similar?: string;
label: string;
text?: { value: string; shape: 'children' | 'prop' | 'value' };
+ /** the picture it draws, when a file can be put in its place (studio/server/stage.js pictureOf) */
+ picture?: StagePicture;
style: StageElementStyle;
parents: StageNodeParent[];
override: NodeOverride | null;
@@ -417,6 +420,8 @@ interface FilmStageSelectProps {
onStartMask?: (shape: MaskShape | 'none', clipLoc: string) => void;
/** A layer pointed at from elsewhere (a row of the Layers panel), outlined as the one under the pointer is. */
pointLayer?: { clipId: string; loc: string } | null;
+ /** A picture of the project dropped on a picture inside a page (an <img>, a box painted with one): put in its place. */
+ onDropPicture?: (element: StageElement, path: string) => void;
/**
* The picture has the keyboard: the arrow keys move what is in hand (1 px, ⇧ 10). Without it they are the
* playhead's, whatever is in hand.
@@ -427,7 +432,7 @@ interface FilmStageSelectProps {
function FilmStageSelectImpl({
previewRef, stage, doc, spans, timeMs, playing, onPause, onSelectElement, onEditClip, linkedLocs, onSelectClips, selectRequest,
clipPreviewRef, lookPreviewRef, controlRef, onTransformLayer, onTransformLayers, onEditTextInline, onGeometry, menuFor, recoveryMenu,
- onRegion, regionHint, flashBox, chat, onHoverLayer, selectionBar = false, onRefer, onStartMask, pointLayer, arrowsMove = true,
+ onRegion, regionHint, flashBox, chat, onHoverLayer, selectionBar = false, onRefer, onStartMask, pointLayer, arrowsMove = true, onDropPicture,
}: FilmStageSelectProps) {
const arrowsMoveRef = React.useRef(arrowsMove);
arrowsMoveRef.current = arrowsMove;
@@ -606,6 +611,7 @@ function FilmStageSelectImpl({
...(clipLocOf(docRef.current, layer.clip) ? { clipLoc: clipLocOf(docRef.current, layer.clip) } : {}),
clipKind: 'mg',
...(layer.text ? { text: { loc: layer.loc, value: layer.text.value, shape: layer.text.shape } } : {}),
+ ...(layer.picture ? { picture: layer.picture } : {}),
tag: layer.tag,
...(layer.similar ? { similar: layer.similar } : {}),
style: layer.style,
@@ -1469,6 +1475,42 @@ function FilmStageSelectImpl({
});
return () => { live = false; };
}, [pointClip, pointLoc, ask]);
+ /* ── a picture of the media pane dragged over the picture: the picture inside a page under it takes its place ── */
+ const [dropOn, setDropOn] = React.useState<StageLayer | null>(null);
+ const dropOnRef = React.useRef(dropOn);
+ dropOnRef.current = dropOn;
+ const dropQueue = React.useMemo(() => new Latest<{ x: number; y: number } | null>(async (p) => {
+ if (!p) { setDropOn(null); return; }
+ const layer = await ask<StageLayer>('hit', { ...p, detail: true });
+ const fits = layer?.picture && !layer.locked && !lockedClip(clipLocOf(docRef.current, layer.clip)) ? layer : null;
+ setDropOn((cur) => (fits && cur && cur.handle === fits.handle ? cur : fits));
+ }), [ask]); // eslint-disable-line react-hooks/exhaustive-deps
+ /** A picture of the project is being dragged (not a thing of Saved: it is brought in only where it lands as a clip). */
+ const draggingPicture = (e: React.DragEvent) => {
+ if (!onDropPicture || !e.dataTransfer.types.includes(RESOURCE_DRAG_TYPE)) return false;
+ const item = peekResourceDrag();
+ return !item || (item.kind === 'image' && !item.saved);
+ };
+ const pictureDrag = {
+ onDragOver: (e: React.DragEvent) => {
+ if (!draggingPicture(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = dropOnRef.current ? 'copy' : 'none';
+ const p = local(e);
+ const vs = viewScaleNow();
+ dropQueue.push({ x: p.x / vs, y: p.y / vs });
+ },
+ onDragLeave: (e: React.DragEvent) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) dropQueue.push(null); },
+ onDrop: (e: React.DragEvent) => {
+ const target = dropOnRef.current;
+ dropQueue.push(null);
+ if (!draggingPicture(e)) return;
+ e.preventDefault();
+ const file = readResourceDragData(e.dataTransfer);
+ if (!target || !file || file.saved || file.kind !== 'image') return;
+ onDropPicture?.(elementOf(target), file.path);
+ },
+ };
/* the layer under the pointer, told to the app: asked of the stage once each time it is another one */
const hoverHandle = hover && !hover.clip ? hover.handle : null;
React.useEffect(() => {
@@ -2404,15 +2446,21 @@ function FilmStageSelectImpl({
const tools: SelectionToolEntry[] = [];
const fromMenu = (id: string, icon?: React.ReactNode) => {
const item = find(id);
- if (!item || item.submenu) return;
+ if (!item) return;
+ /* an item with a submenu (Replace picture): its list hangs from the button */
+ const sub = item.submenu;
tools.push({
id, label: item.label, icon: icon ?? item.icon,
...(item.shortcut ? { shortcut: item.shortcut } : {}), ...(item.hint ? { hint: item.hint } : {}),
- ...(item.disabled ? { disabled: true } : {}), ...(item.danger ? { danger: true } : {}),
- onSelect: () => item.onSelect?.(),
+ ...(item.disabled || (sub && !sub.length) ? { disabled: true } : {}), ...(item.danger ? { danger: true } : {}),
+ onSelect: (button) => {
+ if (!sub) { item.onSelect?.(); return; }
+ const r = button.getBoundingClientRect();
+ openMenuAt({ x: r.left, y: r.bottom + 4 }, sub);
+ },
});
};
- if (barKind === 'layer') for (const id of ['edit-text', 'front', 'back', 'hide', 'reset']) fromMenu(id);
+ if (barKind === 'layer') for (const id of ['edit-text', 'replace-picture', 'front', 'back', 'hide', 'reset']) fromMenu(id);
if (barKind === 'clip') {
if (heldEl?.clipKind === 'video' && onEditClip) tools.push({ id: 'crop', label: t('selectionBar.crop'), icon: <CropIcon size={14} />, shortcut: 'C', onSelect: () => { startCrop(); } });
if (onStartMask && heldEl?.clipLoc) {
@@ -2772,6 +2820,7 @@ function FilmStageSelectImpl({
style={{ touchAction: 'none', pointerEvents: editingText != null ? 'none' : undefined, ...(modAt || regionDraft ? { cursor: 'crosshair' } : {}) }}
onDoubleClick={onStageDoubleClick}
onContextMenu={onStageContextMenu}
+ {...pictureDrag}
onClick={(e) => e.stopPropagation()}
onPointerDown={pressDown}
onPointerMove={(e) => {
@@ -2935,6 +2984,8 @@ function FilmStageSelectImpl({
<Box key={h.clip ?? `${h.handle}:${i}`} rect={scaleBox(h.rect, vsNow)} frame={h.frame && scaleFrame(h.frame, vsNow)} tone="hover" />
)) : null}
{draftRect ? <Box rect={draftRect} tone="draft" /> : null}
+ {/* the picture a dragged file would take the place of */}
+ {dropOn ? <Box rect={scaleBox(dropOn.rect, vsNow)} frame={dropOn.frame && scaleFrame(dropOn.frame, vsNow)} tone="region" /> : null}
{regionDraft ? <Box rect={boxOfDrag(regionDraft)} tone="region" /> : null}
{flash ? <Box rect={scaleBox({ left: flash.box.x, top: flash.box.y, width: flash.box.w, height: flash.box.h }, vsNow)} tone="region" fading={flash.fading} /> : null}
{chatClip?.box ? <MgOutline t={chatClip.t} box={chatClip.box} viewScale={vsNow} color={CHAT_TONE} /> : null}
@@ -3058,6 +3109,7 @@ export const FilmStageSelect = React.memo(FilmStageSelectImpl, (a, b) => (
&& a.onStartMask === b.onStartMask
&& a.pointLayer?.clipId === b.pointLayer?.clipId
&& a.pointLayer?.loc === b.pointLayer?.loc
+ && a.onDropPicture === b.onDropPicture
));
function sameLocs(a: readonly string[] | undefined, b: readonly string[] | undefined): boolean {
diff --git a/packages/openfilm/studio/ui/src/components/FramePicker.tsx b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
index 5b5416e..435d961 100644
--- a/packages/openfilm/studio/ui/src/components/FramePicker.tsx
+++ b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
@@ -1,14 +1,11 @@
/**
- * The aspect ratio button beside the picture: the film's canvas (its stage in film.html). Picking a shape changes the
- * canvas itself (`onCanvas`): the film is scaled whole into it, centered, until the agent lays it
- * out again. A delivery frame (bars or a crop around the film) is the export's. Any other size is typed in the
- * inspector.
+ * The canvas's shapes (the inspector's Stage menu) and a ratio typed by hand (the export's delivery frame). Picking a
+ * shape changes the canvas itself: the film is scaled whole into it, centered, until the agent lays it out again.
*/
import * as React from 'react';
-import { Check, Proportions } from 'lucide-react';
+import { Check } from 'lucide-react';
import { useT } from '@/i18n';
-import { customFilmFrame, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';
-import { Tooltip } from './Tooltip';
+import { customFilmFrame, type FilmFrameId } from '@/lib/film-frame';
/** The shapes a canvas is offered in: landscape, then portrait. */
export const CANVAS_RATIOS: { group: 'wide' | 'tall'; id: FilmFrameId; phone?: true }[] = [
@@ -30,81 +27,6 @@ export function canvasRatioLabel(t: (key: string) => string, item: { id: FilmFra
return item.phone ? t('viewer.ratioPhone') : item.id;
}
-/** Whether the stage has this ratio: its width within 2 px of it (a size made from a ratio is rounded to even px). */
-export const shaped = (stage: { w: number; h: number }, ratio: number) => Math.abs(stage.w - stage.h * ratio) <= 2;
-
-export function FramePicker({
- stage, original, busy, onCanvas,
-}: {
- stage: { w: number; h: number };
- /** The first picture's own size: "Original" takes its shape. None: nothing to fit to yet. */
- original?: { w: number; h: number } | null;
- /** The canvas change is being written: no second one meanwhile (two requests would race for one file). */
- busy?: boolean;
- /** Change the film's canvas to this shape (the editor works out its size and fits the film into it). */
- onCanvas: (next: FilmFrameId) => void;
-}): React.ReactElement {
- const t = useT();
- const [open, setOpen] = React.useState(false);
- const box = React.useRef<HTMLDivElement | null>(null);
- const fit = original ? customFilmFrame(original.w, original.h) : null;
- const preset = CANVAS_RATIOS.find((r) => shaped(stage, filmFrameRatio(r.id, stage)));
- const isFit = Boolean(original && shaped(stage, original.w / original.h));
-
- React.useEffect(() => {
- if (!open) return undefined;
- const away = (e: MouseEvent): void => {
- if (!box.current?.contains(e.target as Node)) setOpen(false);
- };
- window.addEventListener('mousedown', away);
- return () => window.removeEventListener('mousedown', away);
- }, [open]);
-
- const pick = (id: FilmFrameId) => { setOpen(false); onCanvas(id); };
- const row = 'flex w-full items-center gap-2.5 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:pointer-events-none disabled:opacity-40';
- const tick = (on: boolean) => <span className="flex w-3.5 shrink-0 justify-center">{on ? <Check size={13} className="text-[var(--accent)]" /> : null}</span>;
- const item = (r: (typeof CANVAS_RATIOS)[number]) => (
- <button key={r.id} type="button" disabled={busy} onClick={() => pick(r.id)} onMouseDown={(e) => e.preventDefault()} className={row}>
- {tick(!isFit && preset?.id === r.id)}
- <span className="flex-1">{canvasRatioLabel(t, r)}</span>
- </button>
- );
-
- return (
- <div ref={box} className="relative flex items-center">
- <Tooltip label={t('viewer.canvas')}>
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- /* no focus on click: the next Space would land on this button instead of playing */
- onMouseDown={(e) => e.preventDefault()}
- className={`flex h-[22px] items-center gap-1 rounded-md px-1.5 text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${
- busy ? 'opacity-50' : ''
- }`}
- aria-label={t('viewer.canvas')}
- aria-expanded={open}
- >
- <Proportions size={14} />
- {/* the ratio is printed on the button: "this film is vertical" must be visible without opening it */}
- <span className="text-[12px] leading-none tabular-nums">{preset ? preset.id : `${stage.w}×${stage.h}`}</span>
- </button>
- </Tooltip>
- {open ? (
- <div className="absolute bottom-[28px] right-0 z-50 max-h-[min(520px,75vh)] w-[180px] overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface)] p-1 shadow-[var(--shadow-lg)]">
- <button type="button" disabled={busy || !fit} onClick={() => fit && pick(fit)} onMouseDown={(e) => e.preventDefault()} className={row}>
- {tick(isFit)}
- <span className="flex-1">{t('viewer.ratioOriginal')}</span>
- </button>
- <div className="mx-1 my-1 h-px bg-[var(--border)]" />
- {CANVAS_RATIOS.filter((r) => r.group === 'wide').map(item)}
- <div className="mx-1 my-1 h-px bg-[var(--border)]" />
- {CANVAS_RATIOS.filter((r) => r.group === 'tall').map(item)}
- </div>
- ) : null}
- </div>
- );
-}
-
/**
* A ratio of the person's own, typed as width and height ("2.39" by "1", "5" by "4"), from 1:4 to 4:1: Enter or the
* check puts it in use. Starts from the frame in use.
diff --git a/packages/openfilm/studio/ui/src/components/Launcher.tsx b/packages/openfilm/studio/ui/src/components/Launcher.tsx
index 67b0761..c99a1d2 100644
--- a/packages/openfilm/studio/ui/src/components/Launcher.tsx
+++ b/packages/openfilm/studio/ui/src/components/Launcher.tsx
@@ -1,11 +1,13 @@
/**
* The window of an app with tabs (lib/host.ts `tabs`) when no tab is open: an empty window (its top bar still drags
* it) and the projects window over it, as `+` opens it, only with nothing behind to close it to. The project picked
- * opens in its tab.
+ * opens in its tab. Shown while tabs are open too (a tab's page that could not load), its top bar has them, so they
+ * can always be reached.
*/
import { BrandLogo } from './BrandLogo';
import { ProjectsPopover } from './ProjectsLibrary';
import { SettingsModal } from './settings/SettingsModal';
+import { TabStrip, useHostTabs } from './TabStrip';
import { useSettings } from './settings/use-settings';
import { Tooltip } from './Tooltip';
import { useT } from '@/i18n';
@@ -13,6 +15,7 @@ import { useT } from '@/i18n';
export function Launcher({ onOpen }: { onOpen: (projectId: string) => void }) {
const t = useT();
const [settings, setSettings] = useSettings();
+ const { tabs } = useHostTabs();
return (
<div className="workspace-shell flex flex-col bg-[var(--dock-shell)]">
<div data-titlebar className="relative flex h-8 min-w-0 shrink-0 items-center gap-1 px-[6px]">
@@ -23,6 +26,7 @@ export function Launcher({ onOpen }: { onOpen: (projectId: string) => void }) {
<BrandLogo size={15} />
</button>
</Tooltip>
+ {tabs.length ? <TabStrip /> : null}
</div>
<ProjectsPopover open currentProjectId="" onOpen={onOpen} onCurrentRemoved={() => {}} />
<SettingsModal open={settings !== null} section={settings ?? undefined} onClose={() => setSettings(null)} />
diff --git a/packages/openfilm/studio/ui/src/components/MediaPool.tsx b/packages/openfilm/studio/ui/src/components/MediaPool.tsx
index b407a43..3458193 100644
--- a/packages/openfilm/studio/ui/src/components/MediaPool.tsx
+++ b/packages/openfilm/studio/ui/src/components/MediaPool.tsx
@@ -20,7 +20,7 @@ import {
Bookmark,
BookmarkPlus,
Layers,
- LayoutTemplate,
+ Component as ComponentIcon,
ChevronRight,
Clapperboard,
Copy,
@@ -1013,7 +1013,7 @@ export function MediaPool({
onPress={(e) => press(item, e)}
typeText={item.file.bundle ? t(`saved.kind_${item.file.bundle.kind}`) : item.file.kind === 'mg' ? t('assets.kindPage') : extOf(item.file.name).toUpperCase()}
library={inSaved}
- {...(item.file.bundle?.template ? { templateMark: t('saved.template') } : {})}
+ {...(item.file.bundle?.props ? { componentMark: t('saved.component') } : {})}
onMenu={(e) => menuFor(item, e)}
onRename={(name) => void rename(item.file.path, name, false)}
onCancelRename={() => setRenaming(null)}
@@ -1252,8 +1252,8 @@ function FileTile(p: {
row?: boolean;
/** In Saved: a drag of it says its place there (its files are brought into the project as it lands). */
library?: boolean;
- /** A bundle of Saved whose page has custom properties: the word that marks it a template. */
- templateMark?: string;
+ /** A bundle of Saved that offers properties: the word that marks it a component. */
+ componentMark?: string;
}) {
const bundle = p.file.bundle;
return (
@@ -1321,9 +1321,9 @@ function FileTile(p: {
) : p.file.proxy && p.file.proxy.state !== 'failed' ? (
<span className="absolute inset-x-0 bottom-0 z-10 h-1" title={p.proxyLabel}><UploadBar ratio={p.file.proxy.state === 'making' ? p.file.proxy.ratio ?? 0 : -1} /></span>
) : null}
- {/* a bundle of Saved: a template, and how many clips a group holds */}
- {p.templateMark ? (
- <span className="absolute left-1 top-1 z-10 flex items-center gap-0.5 rounded bg-black/65 px-1 text-[9.5px] font-semibold leading-[15px] text-white/90"><LayoutTemplate size={9} />{p.templateMark}</span>
+ {/* a bundle of Saved: a component, and how many clips a group holds */}
+ {p.componentMark ? (
+ <span className="absolute left-1 top-1 z-10 flex items-center gap-0.5 rounded bg-black/65 px-1 text-[9.5px] font-semibold leading-[15px] text-white/90"><ComponentIcon size={9} />{p.componentMark}</span>
) : null}
{bundle?.kind === 'group' && bundle.count ? (
<span className="absolute bottom-1 left-1 z-10 flex items-center gap-0.5 rounded bg-black/65 px-1 text-[10.5px] tabular-nums leading-[16px] text-white"><Layers size={10} />{bundle.count}</span>
diff --git a/packages/openfilm/studio/ui/src/components/PlaybackMenu.tsx b/packages/openfilm/studio/ui/src/components/PlaybackMenu.tsx
new file mode 100644
index 0000000..9724cc0
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/PlaybackMenu.tsx
@@ -0,0 +1,113 @@
+import React from 'react';
+import { createPortal } from 'react-dom';
+import { Captions, Repeat, Settings2 } from 'lucide-react';
+import { useT } from '@/i18n';
+import { useKeyHint } from '@/lib/keymap-store';
+import { Tooltip } from './Tooltip';
+
+/** The speeds the viewer plays at (the player plays forward only, from 0.25× to 2×). */
+export const PLAYBACK_SPEEDS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] as const;
+
+export type PlaybackSettings = {
+ /** Loop playback (⇧L): of the range marked (`ranged`), else of the whole film. */
+ loop: boolean;
+ ranged: boolean;
+ onLoop: () => void;
+ speed: number;
+ onSpeed: (speed: number) => void;
+ /** Subtitles on the picture, when the film has any. */
+ captions?: { on: boolean; onToggle: () => void } | null;
+};
+
+/**
+ * The viewer's playback settings: loop, subtitles on the picture, and the speed. What is not the default shows on the
+ * button itself (the loop icon, "1.5×"), so it is seen without opening the menu. Nothing here takes focus on click:
+ * the next Space still plays.
+ */
+export function PlaybackMenu({ className, disabled, settings }: {
+ className?: string;
+ disabled?: boolean;
+ settings: PlaybackSettings;
+}) {
+ const t = useT();
+ const keyHint = useKeyHint();
+ const button = React.useRef<HTMLButtonElement>(null);
+ const panel = React.useRef<HTMLDivElement>(null);
+ const [anchor, setAnchor] = React.useState<{ right: number; bottom: number } | null>(null);
+ const id = React.useId();
+ React.useEffect(() => {
+ if (!anchor) return;
+ const outside = (event: PointerEvent) => {
+ if (!panel.current?.contains(event.target as Node) && !button.current?.contains(event.target as Node)) setAnchor(null);
+ };
+ const close = () => setAnchor(null);
+ const escape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') { event.stopPropagation(); close(); }
+ };
+ /* capture phase: the picture, the timeline and inputs each stop pointerdown, so it never bubbles to window.
+ A click into the preview iframe sends no event at all, only a window blur — that counts as "elsewhere" too. */
+ window.addEventListener('pointerdown', outside, true);
+ window.addEventListener('keydown', escape, true);
+ window.addEventListener('resize', close);
+ window.addEventListener('blur', close);
+ return () => {
+ window.removeEventListener('pointerdown', outside, true);
+ window.removeEventListener('keydown', escape, true);
+ window.removeEventListener('resize', close);
+ window.removeEventListener('blur', close);
+ };
+ }, [anchor]);
+
+ const { loop, ranged, onLoop, speed, onSpeed, captions } = settings;
+ const loopLabel = t(ranged ? 'viewer.loopRange' : 'viewer.loopFilm');
+ const speedText = (s: number) => `${s}×`;
+ const keep = (e: React.MouseEvent) => e.preventDefault();
+ const toggle = (key: string, label: string, checked: boolean, change: () => void, Icon: typeof Repeat, hint?: string) => (
+ <button key={key} type="button" role="switch" aria-checked={checked} onClick={change} onMouseDown={keep}
+ data-playback={key}
+ className="flex w-full items-center gap-2.5 rounded-[7px] px-2 py-1.5 text-[12px] text-[var(--text)] hover:bg-[var(--bg-hover)] focus-visible:outline focus-visible:outline-[var(--border-strong)]">
+ <Icon size={14} aria-hidden className="shrink-0 text-[var(--text-muted)]" />
+ <span className="flex-1 text-left">{label}</span>
+ {hint ? <span className="text-[11px] text-[var(--text-faint)]">{hint}</span> : null}
+ <span aria-hidden className={`relative h-[18px] w-[30px] shrink-0 rounded-full transition-colors ${checked ? 'bg-[var(--text)]' : 'bg-[var(--surface-2)] ring-1 ring-inset ring-[var(--border)]'}`}>
+ <span className={`absolute top-[3px] h-3 w-3 rounded-full transition-all ${checked ? 'left-[15px] bg-[var(--bg)]' : 'left-[3px] bg-[var(--text-faint)]'}`} />
+ </span>
+ </button>
+ );
+
+ return <>
+ <Tooltip label={t('viewer.playback')}>
+ <button ref={button} type="button" disabled={disabled} className={className} aria-label={t('viewer.playback')}
+ aria-haspopup="dialog" aria-expanded={!!anchor} aria-controls={anchor ? id : undefined}
+ data-viewer-loop={loop ? '1' : '0'} data-viewer-speed={speed}
+ /* no focus on click: the next Space would land on this button instead of playing */
+ onMouseDown={keep}
+ onClick={() => {
+ const rect = button.current!.getBoundingClientRect();
+ setAnchor((current) => current ? null : { right: Math.max(12, window.innerWidth - rect.right), bottom: window.innerHeight - rect.top + 6 });
+ }}>
+ {loop ? <Repeat size={14} className="text-[var(--accent)]" aria-hidden /> : null}
+ {speed !== 1 ? <span className="text-[12px] leading-none tabular-nums">{speedText(speed)}</span> : null}
+ {!loop && speed === 1 ? <Settings2 size={14} aria-hidden /> : null}
+ </button>
+ </Tooltip>
+ {anchor && createPortal(<div ref={panel} id={id} role="dialog" aria-label={t('viewer.playback')}
+ style={anchor} className="fixed z-[110] w-56 rounded-[14px] border border-[var(--border)] bg-[var(--surface)] p-1.5 shadow-[0_18px_48px_-12px_rgba(0,0,0,0.45),0_2px_8px_rgba(0,0,0,0.12)]">
+ <div className="px-2 pb-1 pt-1 text-[11px] font-medium text-[var(--text-faint)]">{t('viewer.playback')}</div>
+ {toggle('loop', loopLabel, loop, onLoop, Repeat, keyHint('loop'))}
+ {captions ? toggle('captions', t('viewer.subtitles'), captions.on, captions.onToggle, Captions) : null}
+ <div className="mx-1 my-1 h-px bg-[var(--border)]" />
+ <div className="px-2 pb-1.5 pt-1 text-[11px] font-medium text-[var(--text-faint)]">{t('viewer.speed')}</div>
+ <div role="radiogroup" aria-label={t('viewer.speed')} className="grid grid-cols-4 gap-1 px-1 pb-1">
+ {PLAYBACK_SPEEDS.map((s) => (
+ <button key={s} type="button" role="radio" aria-checked={s === speed} onClick={() => onSpeed(s)} onMouseDown={keep}
+ className={`h-7 rounded-[6px] text-[12px] tabular-nums transition focus-visible:outline focus-visible:outline-[var(--border-strong)] ${
+ s === speed ? 'bg-[var(--text)] font-medium text-[var(--bg)]' : 'text-[var(--text)] hover:bg-[var(--bg-hover)]'
+ }`}>
+ {speedText(s)}
+ </button>
+ ))}
+ </div>
+ </div>, document.body)}
+ </>;
+}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 2063a2d..e91ddab 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -7,7 +7,7 @@
* are written one at a time (see editor/use-film.ts); the agent's writes come in through the folder's events.
*/
import * as React from 'react';
-import { BookmarkPlus, ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, Share, TriangleAlert } from 'lucide-react';
+import { BookmarkPlus, ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert, Upload } from 'lucide-react';
import { applyOps } from '../../../server/ops.mjs';
import { api, ApiError, PREFS_EVENT, projectEvents, type Clip, type Film, type Listing, type Op, type ProjectFilm, type ProjectSettings } from '@/api';
import { useT } from '@/i18n';
@@ -86,7 +86,6 @@ import { ProjectMenu } from './ProjectMenu';
import { ProjectHistoryButton, ProjectHistoryControls } from './ProjectHistoryControls';
import { useProjectHistory } from './use-project-history';
import { ProjectsPopover } from './ProjectsLibrary';
-import { FramePicker } from './FramePicker';
import { FilmFullscreenBar, useFullscreenKeys } from './FilmFullscreenBar';
import { ViewerBar } from './ViewerBar';
import { LiveTime, type PlaybackClock } from './LiveTime';
@@ -98,11 +97,13 @@ import { ExportTray, type ExportTrayHandle } from './export/ExportTray';
import { FilmStageSelect, type FilmStageControl, type LayerGeometry, type StageClipEdit, type StagePick } from './FilmStageSelect';
import { openSection } from './inspector-fields';
import { FontScopeContext, type FontScope } from '@/lib/use-fonts';
-import { stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuContext } from './stage-menu';
+import { stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuContext, type StagePictureActions } from './stage-menu';
import type { StageEditFailure, StageTextEdit } from './FilmInspector';
import { layerTarget, pageClipOf, recoverLayer } from '@/lib/stage-layers';
-import type { TemplateControls } from '@/lib/template-controls';
-import type { TemplateHost } from './TemplateSection';
+import { pictureStyle, relativeTo, type TemplateControls } from '@/lib/template-controls';
+import { propsAttr, propsOf, type ComponentProp } from '@/lib/component-props';
+import type { PropsHost } from './PropertiesSection';
+import type { LayerPropsActions } from './FilmInspector';
import { SAVED, refreshSaved, savedActions, savedSources, useSavedListing } from '@/lib/saved';
import { batchMap } from '@/lib/batch-map';
import { groupInsertAt, groupInsertOps } from '@/lib/saved-insert';
@@ -115,6 +116,8 @@ import { usePreviewPrefs } from '@/lib/preview-prefs';
import { isTypingTarget } from './typing-target';
const PANE = 'relative flex min-h-0 min-w-0 flex-col overflow-hidden rounded-[7px]';
+/** The files a picture inside a page can be replaced with. */
+const PICTURE_FILE = /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i;
/* ⌘ is the modifier on a Mac, Ctrl elsewhere (the editor's keys, lib/timeline-keys) */
const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
/** Which the media pane shows, the project's media or Saved: kept while Studio is open, across projects. */
@@ -200,6 +203,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const t = useT();
const toast = useToast();
const keyHint = useKeyHint();
+ /* the latest onLeave, for the folder's events (subscribed once per project) */
+ const leaveRef = React.useRef(onLeave);
+ leaveRef.current = onLeave;
/* how many times the project's files changed since it opened (see the folder events below) */
const [filesTick, setFilesTick] = React.useState(0);
const [loaded, setLoaded] = React.useState<ProjectFilm | null>(null);
@@ -215,7 +221,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* ── the project, its film and its files ── */
React.useEffect(() => {
- api.film(projectId).then(setLoaded, (e: Error) => setFailure(e.message));
+ /* a project the list no longer has (deleted meanwhile, a tab of it opened again): gone, so this page leaves it */
+ api.film(projectId).then(setLoaded, (e: Error) => { if (e instanceof ApiError && e.status === 404) leaveRef.current(); else setFailure(e.message); });
void api.opened(projectId).catch(() => {});
const loadFiles = () => api.files(projectId).then(setRawListing, () => {});
void loadFiles();
@@ -223,6 +230,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* a picture that could not be drawn is tried again whenever the folder changes: the missing file arrived, or
the clip that named it is gone from film.html now that the edit is written */
if (previewErrorRef.current && (event.type === 'film' || event.type === 'files')) { preview.current?.reload?.(); }
+ /* deleted (here, in another tab, by an agent), or its folder gone: this page leaves it (with tabs, its tab closes) */
+ if (event.type === 'gone') { leaveRef.current(); return; }
/* renamed from another tab, or the projects list */
if (event.type === 'project') { setLoaded((l) => (l ? { ...l, project: event.project } : l)); return; }
if (event.type !== 'files') return;
@@ -323,6 +332,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
pageSurface: (f) => `${folder}${f.path.split('/').map(encodeURIComponent).join('/')}`,
};
}, [projectId, folder, filesTick]);
+ /* for the pictures' thumbnails in a menu built after the render that made it */
+ const mediaSourcesRef = React.useRef(mediaSources);
+ mediaSourcesRef.current = mediaSources;
/*
* proxies (studio/server/proxies.mjs): asked for the project's heavy footage whenever its files change or the
* preferences do, followed while they are made. One ready for footage on the film, or other preferences, load the
@@ -383,6 +395,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const [loop, setLoop] = React.useState(false);
const loopRef = React.useRef(loop);
loopRef.current = loop;
+ /* the speed picked in the viewer's playback settings: what plays once a J/K/L shuttle is let go */
+ const speedRef = React.useRef(1);
/* the range marked (set below, with the timeline's): what loops */
const rangeNowRef = React.useRef<FilmRange | null>(null);
const clock = React.useMemo<PlaybackClock>(() => ({
@@ -452,11 +466,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {
alone is sought along at that rate, silent, as a scrub is (the player plays forward only, at most 2×) ── */
const shuttleRateRef = React.useRef(0);
const shuttleFrame = React.useRef(0);
- /** The shuttle let go: the player back at 1× if the shuttle changed its rate. */
+ /** The shuttle let go: the player back at the speed picked if the shuttle changed its rate. */
const stopShuttle = React.useCallback(() => {
if (shuttleFrame.current) cancelAnimationFrame(shuttleFrame.current);
shuttleFrame.current = 0;
- if (shuttleRateRef.current !== 0 && player.current.rate !== 1) { player.current.setRate(1); setRateState(1); }
+ if (shuttleRateRef.current !== 0 && player.current.rate !== speedRef.current) {
+ player.current.setRate(speedRef.current);
+ setRateState(player.current.rate);
+ }
shuttleRateRef.current = 0;
}, []);
const pause = React.useCallback(() => {
@@ -1500,7 +1517,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
if (!failed && (patch === null || patch.style)) {
window.setTimeout(() => {
void stageControl.current?.describe(element).then((fresh) => {
- if (fresh) setStageElement((el) => (el?.loc === element.loc ? { ...el, style: fresh.style } : el));
+ if (fresh) setStageElement((el) => (el?.loc === element.loc ? { ...el, style: fresh.style, ...(fresh.picture ? { picture: fresh.picture } : {}) } : el));
});
}, 120);
}
@@ -1652,16 +1669,59 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const startStageCrop = React.useCallback(() => { stageControl.current?.startCrop(); }, []);
const editStageMask = React.useCallback((session: MaskSession | null) => { stageControl.current?.editMask(session); }, []);
const pageChangesOf = usePageChanges(preview, filmRef);
- /* a page clip's template controls (components/TemplateSection): read from its page on the picture, previewed there,
- written as its overrides by the inspector */
- /* the project's files as listed now, for the Template section's pictures (its host outlives a render) */
+ /* the project's files as listed now, for the pictures a picture is replaced with (a host outlives a render) */
const listingRef = React.useRef(listing);
listingRef.current = listing;
- const templateOf = React.useCallback((block: TimelineBlock): TemplateHost | null => {
+ /* another file in the place of a picture inside a page (an <img>, a box painted with one image): the clip's override,
+ the file named from the page's folder, as a picture property writes it */
+ const putLayerPicture = React.useCallback((element: StageElement, path: string | null) => {
+ const doc = filmRef.current as unknown as FilmDoc | null;
+ const found = doc ? pageClipOf(doc, element) : null;
+ const picture = element.picture;
+ if (!found || !picture) { toast.show(t('timeline.editFail')); return; }
+ const style = pictureStyle(picture.kind, path == null ? null : relativeTo(found.clip.src, path));
+ /* a box holding one picture: the file goes on its <img> */
+ const target: StageElement = picture.at
+ ? { ...element, loc: picture.n ? `${picture.at}#${picture.n}` : picture.at, ...(picture.n ? { instance: picture.n } : { instance: undefined }), override: null }
+ : element;
+ void editStageOverrideRef.current(target, { style }).then((failed) => {
+ if (failed) { toast.show(failed); return; }
+ /* the layer in hand shows the picture now on it once the page has it */
+ window.setTimeout(() => {
+ void stageControl.current?.describe(element).then((fresh) => {
+ if (fresh) setStageElement((el) => (el?.loc === element.loc ? { ...el, ...(fresh.picture ? { picture: fresh.picture } : {}) } : el));
+ });
+ }, 150);
+ });
+ }, [t]); // eslint-disable-line react-hooks/exhaustive-deps
+ const pictureActions = React.useMemo<StagePictureActions>(() => ({
+ pictures: () => (listingRef.current?.files ?? []).filter((f) => PICTURE_FILE.test(f.path)).map((f) => ({ path: f.path, name: f.path.split('/').pop() ?? f.path, url: mediaSourcesRef.current.file(f) })),
+ pickFromComputer: () => pickReplacement('picture'),
+ put: putLayerPicture,
+ }), [pickReplacement, putLayerPicture]);
+ /* a page clip's component properties (lib/component-props): its data-props, read and written by its id */
+ const clipPropsOf = React.useCallback((clipId: string | undefined): ComponentProp[] => (
+ clipId ? propsOf(filmRef.current?.tracks.flatMap((tr) => tr.clips).find((c) => c.id === clipId)) : []
+ ), []);
+ const writeClipProps = React.useCallback((clipId: string | undefined, next: readonly ComponentProp[]) => {
+ const loc = blocksRef.current.find((b) => b.clipId === clipId)?.loc;
+ if (!loc) { toast.show(t('timeline.editFail')); return; }
+ void editBlocks([{ loc, prop: 'props', value: propsAttr(next) }]).then((failed) => { if (failed) toast.show(failed); });
+ }, [editBlocks, t]); // eslint-disable-line react-hooks/exhaustive-deps
+ /* a layer made a property of its clip (the inspector's ◇), or no longer one */
+ const layerProps = React.useMemo<LayerPropsActions>(() => ({
+ list: (element) => clipPropsOf(element.clipId),
+ save: (element, next) => writeClipProps(element.clipId, next),
+ }), [clipPropsOf, writeClipProps]);
+ /* a page clip's Properties (components/PropertiesSection): what its page shows read on the picture, previewed there,
+ filled in as its overrides by the inspector */
+ const propsHostOf = React.useCallback((block: TimelineBlock): PropsHost | null => {
const clip = block.clipId;
if (!clip) return null;
return {
read: () => askStage<TemplateControls>('controls', { clip }),
+ props: () => clipPropsOf(clip),
+ setProps: (next) => writeClipProps(clip, next),
overrides: () => {
const at = parseFilmDocLoc(blocksRef.current.find((b) => b.clipId === clip)?.loc ?? '');
return (at ? filmRef.current?.tracks[at.track]?.clips[at.clip]?.overrides : undefined) as readonly FilmOverride[] | undefined;
@@ -1670,10 +1730,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {
void (patch ? askStage('tweak', { clip, at: target.at, ...(target.n ? { n: target.n } : {}), patch }) : askStage('release', { clip }));
},
page: block.src ?? '',
- pictures: () => (listingRef.current?.files ?? []).filter((f) => /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i.test(f.path)).map((f) => ({ path: f.path, name: f.path.split('/').pop() ?? f.path })),
+ pictures: pictureActions.pictures,
pickPicture: () => pickReplacement('picture'),
+ point: (target) => setPointedLayer(target ? { clipId: clip, loc: target.n ? `${target.at}#${target.n}` : target.at } : null),
};
- }, [askStage, pickReplacement]);
+ }, [askStage, pickReplacement, pictureActions, clipPropsOf, writeClipProps]);
/* a clip's own CSS as film.html has it, and the look the player measured (the Inspector's Look section) */
const clipLookOf = React.useCallback((clipLoc: string) => {
const at = parseFilmDocLoc(clipLoc);
@@ -1698,6 +1759,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
selectParent: selectStageParent,
selectClip: selectStageClip,
notify: (message) => toast.show(message),
+ picture: pictureActions,
clip: {
isLocked: (clipLoc) => Boolean(timelineTracks.find((tr) => tr.blocks.some((b) => b.loc === clipLoc))?.locked),
canSplit: (clipLoc) => { const b = blockAt(clipLoc); const now = timeRef.current; return !!b && now > b.startMs + 100 && now < b.endMs - 100; },
@@ -1728,7 +1790,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
exportClip: (clipId) => openClipExportRef.current(clipId),
remove: (clipLoc) => { const b = blockAt(clipLoc); if (b) { void removeBlocks(withLinkedBlocks(b)); setStageElement(null); } },
},
- }, t), [editStageOverrides, selectStageParent, selectStageClip, splitBlocks, copyBlocks, clipboard, timelineTracks, pasteAt, editBlocks, removeBlocks, t, toast]); // eslint-disable-line react-hooks/exhaustive-deps
+ }, t), [editStageOverrides, selectStageParent, selectStageClip, splitBlocks, copyBlocks, clipboard, timelineTracks, pasteAt, editBlocks, removeBlocks, t, toast, pictureActions]); // eslint-disable-line react-hooks/exhaustive-deps
/*
* "Reference in chat", first on the menus of a clip, a layer and a track, when the app around Studio has a chat.
* The references are made when it is chosen: a layer right-clicked is measured just after its menu opens. ⌘L does
@@ -2253,6 +2315,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const [volume, setVolumeState] = React.useState(1);
const [muted, setMutedState] = React.useState(false);
const [rate, setRateState] = React.useState(1);
+ /** Play at this speed from now on (the viewer's playback settings, the full-screen player's). */
+ const setSpeed = React.useCallback((speed: number) => {
+ player.current.setRate(speed);
+ speedRef.current = player.current.rate;
+ setRateState(player.current.rate);
+ }, []);
/* full screen only: elsewhere K, M, C and F are the editor's keys */
useFullscreenKeys({
enabled: fullscreen,
@@ -2671,7 +2739,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
else if (totalMs > 0) setExportOpen(true);
else toast.show(t('project.filmNotReady'));
}}>
- <Share size={16} />
+ <Upload size={16} />
</button>
</Tooltip>
{/* in an app's tabs these are in the tab's menu */}
@@ -2770,7 +2838,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
}} />
{pickedMedia ? (
<div className="absolute inset-x-0 bottom-0 top-8 z-20">
- <SourcePreview file={pickedSaved && pickedMedia.bundle ? { ...pickedMedia, kind: 'image' } : pickedMedia} sources={pickedSaved ? savedSources : mediaSources} onClose={() => pickMedia(null)} onPlace={placeFromSource} />
+ {/* a bundle of Saved plays its page as its clip had it; any other bundle shows its picture */}
+ <SourcePreview file={pickedSaved && pickedMedia.bundle && !pickedMedia.bundle.page ? { ...pickedMedia, kind: 'image' } : pickedMedia} sources={pickedSaved ? savedSources : mediaSources} onClose={() => pickMedia(null)} onPlace={placeFromSource} />
</div>
) : null}
{dropped?.length || undone.length ? (
@@ -2836,7 +2905,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
selectionBar={barAt === 'stage'}
{...(studioHost?.refer ? { onRefer: referFromStage } : {})}
onStartMask={openMaskSection}
- pointLayer={layersShown ? pointedLayer : null}
+ pointLayer={pointedLayer}
+ onDropPicture={putLayerPicture}
arrowsMove={viewerFocus}
/>
) : null}
@@ -2887,7 +2957,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onScrubCommit={(ms) => seek(ms)}
onVolume={(v) => { player.current.setVolume(v); setVolumeState(player.current.volume); setMutedState(player.current.muted); }}
onToggleMute={() => { player.current.setMuted(!player.current.muted); setMutedState(player.current.muted); }}
- onRate={(r) => { player.current.setRate(r); setRateState(player.current.rate); }}
+ onRate={setSpeed}
onExit={toggleFullscreen}
captionsOn={subs.count ? captionsOn : undefined}
onToggleCaptions={() => setCaptionsOn((v) => !v)}
@@ -2910,10 +2980,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {
totalMs={totalMs}
playing={playing}
onPlayPause={toggle}
- loop={{ on: loop, ranged: Boolean(markedRange), onToggle: () => setLoop((on) => !on) }}
- frame={value ? (
- <FramePicker stage={stage} original={originalSize} onCanvas={changeCanvas} />
- ) : null}
+ playback={{
+ loop,
+ ranged: Boolean(markedRange),
+ onLoop: () => setLoop((on) => !on),
+ speed: rate,
+ onSpeed: setSpeed,
+ captions: subs.count ? { on: captionsOn, onToggle: () => setCaptionsOn((v) => !v) } : null,
+ }}
onFullscreen={toggleFullscreen}
/>
</div>
@@ -2952,7 +3026,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onSelectClip={selectStageClip}
onPreviewClip={previewClip}
pageChangesOf={pageChangesOf}
- templateOf={templateOf}
+ propsHostOf={propsHostOf}
+ layerProps={layerProps}
+ pictures={pictureActions}
replaceEntries={tools.replaceEntries}
clipLookOf={clipLookOf}
onPreviewLook={previewLook}
@@ -2965,6 +3041,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onCanvas={changeCanvas}
onCanvasPreview={previewCanvas}
canvasDraft={canvasDraft}
+ canvasOriginal={originalSize}
onEditLayers={editStageOverrides}
onPlaceLayers={(to) => stageControl.current?.placeLayers(to)}
locked={inspectorLocked}
@@ -3057,7 +3134,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
</div>
<ProjectHistoryControls projectId={projectId} history={history} open={historyOpen} anchor={historyAnchor} onClose={() => setHistoryOpen(false)} />
- <ProjectsPopover open={projectsOpen} currentProjectId={projectId} onOpen={(id) => { setProjectsOpen(false); onProject(id); }} onCurrentRemoved={onLeave} onClose={() => setProjectsOpen(false)} />
+ <ProjectsPopover open={projectsOpen} currentProjectId={projectId} onOpen={(id) => { if (!studioHost?.tabs) setProjectsOpen(false); onProject(id); }} onCurrentRemoved={onLeave} onClose={() => setProjectsOpen(false)} />
{examplesOpen ? (
<ExamplesDialog projectId={projectId} open={examplesOpen === true ? undefined : examplesOpen} onClose={() => setExamplesOpen(false)}
/* a film started from an example: in a tab of its own where there are tabs, else here */
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
index 435b7da..19c04cd 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
@@ -21,6 +21,7 @@ import { Loader2 } from 'lucide-react';
import { api, ApiError, LIBRARY_EVENT } from '@/api';
import { useT } from '@/i18n';
import { folderApi, folderCounts, folderTrail, type ProjectFolder } from '@/lib/project-folders';
+import { stillThere } from '@/lib/project-delete';
import { studioHost } from '@/lib/host';
import { SourceError, sourcesApi } from '@/lib/project-sources';
import { LIST_WAIT_MS, within } from '@/lib/projects-page';
@@ -71,6 +72,14 @@ function useProjectLibrary(open: boolean) {
return () => { alive = false; };
}, [open, tries]);
const retryLoad = React.useCallback(() => setTries((n) => n + 1), []);
+ /* shown again (the app's projects page when the last tab closes, a window brought back): read afresh, as it may
+ have changed meanwhile */
+ React.useEffect(() => {
+ if (!open) return undefined;
+ const back = () => { if (document.visibilityState === 'visible') retryLoad(); };
+ document.addEventListener('visibilitychange', back);
+ return () => document.removeEventListener('visibilitychange', back);
+ }, [open, retryLoad]);
const reloadFolders = React.useCallback(() => {
void folderApi.list().then(setFolders, () => {});
@@ -117,8 +126,13 @@ function useProjectLibrary(open: boolean) {
const drop = new Set(ids);
setProjects((list) => list.filter((p) => !drop.has(p.id)));
/* null: deleted; else why not ('agent-running': an agent started in it since the list was read) */
- const results = await Promise.all(ids.map((id) => api.forget(id).then(() => null, (e: unknown) => ({ id, working: e instanceof ApiError && e.body.code === 'agent-running' }))));
- const failed = results.filter((r): r is { id: string; working: boolean } => r !== null);
+ /* `lost`: no answer came (the request was cut off, as when the page showing one of them leaves it) */
+ const results = await Promise.all(ids.map((id) => api.forget(id).then(() => null, (e: unknown) => ({
+ id, working: e instanceof ApiError && e.body.code === 'agent-running', lost: !(e instanceof ApiError),
+ }))));
+ /* the ones still on the list (lib/project-delete): one gone already, or whose lost answer was a delete, was deleted */
+ const failed = await stillThere(results.filter((r): r is { id: string; working: boolean; lost: boolean } => r !== null),
+ () => api.projects().then((list) => list.map((p) => p.id)));
if (failed.length) {
const back = new Set(failed.map((f) => f.id));
setProjects((list) => [...list, ...before.filter((p) => back.has(p.id)).map((p) => (failed.find((f) => f.id === p.id)?.working ? { ...p, working: true } : p))]);
@@ -139,6 +153,15 @@ function useProjectLibrary(open: boolean) {
}
}
+ /** A folder into another (null: the top level), with what it holds. */
+ function moveFolder(id: string, parentId: string | null) {
+ setFolders((list) => list.map((f) => (f.id === id ? { ...f, parentId: parentId ?? undefined } : f)));
+ folderApi.moveFolder(id, parentId).then(
+ (folder) => setFolders((list) => list.map((f) => (f.id === id ? folder : f))),
+ () => reloadFolders(),
+ );
+ }
+
function renameFolder(id: string, name: string) {
setFolders((list) => list.map((f) => (f.id === id ? { ...f, name } : f)));
folderApi.rename(id, name).then(
@@ -179,6 +202,9 @@ function useProjectLibrary(open: boolean) {
const renamed = await api.rename(id, name);
/* the server cleans the name for the file system: show what the folder is really called */
setProjects((list) => list.map((p) => (p.id === id ? { ...p, ...renamed } : p)));
+ /* its tab says the new name, also while that tab has no page to say it */
+ const tab = (await studioHost?.tabs?.list().catch(() => null))?.tabs.find((x) => x.projectId === id);
+ if (tab) void studioHost?.tabs?.retitle?.(tab.id, renamed.name);
} catch (e) {
setProjects(before);
/* a name that is taken: retrying can't help, so the message says what to do instead */
@@ -188,13 +214,16 @@ function useProjectLibrary(open: boolean) {
}
}
- return { projects, folders, loaded, loadFailed, retryLoad, error, flash, reload: reloadFolders, agentRunning, workingIn, deleteProjects, renameProject, createFolder, renameFolder, moveProject, deleteFolder, coverChanged };
+ return { projects, folders, loaded, loadFailed, retryLoad, error, flash, reload: reloadFolders, agentRunning, workingIn, deleteProjects, renameProject, createFolder, renameFolder, moveFolder, moveProject, deleteFolder, coverChanged };
}
/** The launcher's two views: the person's projects, and the examples to start from (ExamplesGallery). */
export type LauncherView = 'projects' | 'examples';
/** The switch between them, in the title row (the Community's is the same). */
+/** How long the projects window waits for the tab it opened to cover it before it closes anyway. */
+const COVER_WAIT_MS = 4000;
+
export function LauncherSwitch({ view, onView }: { view: LauncherView; onView: (view: LauncherView) => void }) {
const t = useT();
return <TitleSwitch items={[{ id: 'projects' as const, label: t('launcher.projects') }, { id: 'examples' as const, label: t('launcher.examples') }]} value={view} onChange={onView} />;
@@ -248,9 +277,23 @@ export function ProjectsPopover({
const go = (projectId: string, kind: 'creating' | 'opening') => {
/* the project already open: nowhere to go, and an "Opening" that would never end */
if (projectId === currentProjectId) { close(); return; }
+ /* with tabs it opens in its own tab, not this page: this window stays until that tab covers it (closed first, the
+ page behind would show for a moment), then it is done here; a few seconds at most */
+ const tabs = studioHost?.tabs;
+ if (tabs) {
+ setBusy(kind);
+ let stop = () => {};
+ const timer = setTimeout(() => done(), COVER_WAIT_MS);
+ const done = () => { stop(); clearTimeout(timer); setBusy(null); close(); };
+ stop = tabs.onCovered?.(done) ?? (() => {});
+ onOpen(projectId);
+ return;
+ }
setBusy(kind);
onOpen(projectId);
};
+ /* closed: nothing in progress shows when it opens again */
+ React.useEffect(() => { if (!open) setBusy(null); }, [open]);
/* another project opened: done */
const latestClose = React.useRef(close);
latestClose.current = close;
@@ -416,6 +459,7 @@ export function ProjectsPopover({
});
}}
onMoveToFolder={lib.moveProject}
+ onMoveFolder={lib.moveFolder}
onClose={onClose}
/>
</ProjectCoverContext.Provider>
@@ -462,6 +506,8 @@ export function ProjectsPopover({
setPendingDelete(null);
if (!ids) return;
void lib.deleteProjects(ids).then((deleted) => {
+ /* their tabs close together, this page's own among them */
+ if (deleted.size) void studioHost?.tabs?.gone?.([...deleted]);
if (deleted.has(currentProjectId)) onCurrentRemoved();
});
}}
@@ -510,6 +556,7 @@ export function ProjectsPopover({
setPendingFolder(null);
if (!folder) return;
void lib.deleteFolder(folder).then((deleted) => {
+ if (deleted.size) void studioHost?.tabs?.gone?.([...deleted]);
if (deleted.has(currentProjectId)) onCurrentRemoved();
});
}}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
index 91f04f9..e972d10 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
@@ -7,25 +7,7 @@
import React from 'react';
import { createPortal } from 'react-dom';
import {
- ArrowLeft,
- Check,
- ChevronDown,
- Clock3,
- Folder,
- FolderOpen,
- FolderPlus,
- FolderSearch,
- Github,
- LayoutGrid,
- List,
- MoreHorizontal,
- Pencil,
- Plus,
- Search,
- SlidersHorizontal,
- Trash2,
- Video,
- X,
+ ArrowLeft, Check, ChevronDown, ChevronRight, Clock3, Folder, FolderInput, FolderOpen, FolderPlus, FolderSearch, Github, LayoutGrid, List, MoreHorizontal, Pencil, Plus, Search, SlidersHorizontal, Trash2, Video, X,
} from 'lucide-react';
import type { Example } from '@/lib/project-sources';
import { ExamplesSection } from './ProjectSources';
@@ -66,6 +48,7 @@ export function ProjectsView({
onRenameFolder,
onDeleteFolder,
onMoveToFolder,
+ onMoveFolder,
onClose,
heading,
}: {
@@ -101,6 +84,8 @@ export function ProjectsView({
onDeleteFolder: (folder: ProjectFolder) => void;
/** Put a project in a folder, or (null) in none. */
onMoveToFolder: (projectId: string, folderId: string | null) => void;
+ /** a folder into another (null: the top level) */
+ onMoveFolder: (folderId: string, parentId: string | null) => void;
/** Missing: no close button (Studio has no project to go back to). */
onClose?: () => void;
/** The title row's left, in place of "Projects" (the launcher's switch between the projects and the examples). */
@@ -117,7 +102,8 @@ export function ProjectsView({
const [renamingId, setRenamingId] = React.useState<string | null>(null);
/* folders: the one being looked at (null = all), the project a folder is being picked for, the folder being named */
const [folderId, setFolderId] = React.useState<string | null>(null);
- const [moving, setMoving] = React.useState<LibraryProject | null>(null);
+ /* what the folder picker moves: a project, or a folder of the list */
+ const [moving, setMoving] = React.useState<{ project: LibraryProject } | { folder: ProjectFolder } | null>(null);
const [renamingFolderId, setRenamingFolderId] = React.useState<string | null>(null);
/* the folder looked at was deleted (here or elsewhere): back to all */
React.useEffect(() => {
@@ -156,6 +142,7 @@ export function ProjectsView({
},
onCancelRename: () => setRenamingFolderId(null),
onDelete: () => onDeleteFolder(folder),
+ onMove: () => setMoving({ folder }),
};
}
@@ -240,7 +227,7 @@ export function ProjectsView({
},
onCancelRename: () => setRenamingId((current) => (current === project.id ? null : current)),
onStartSelect: () => startSelecting(project),
- onMoveToFolder: () => setMoving(project),
+ onMoveToFolder: () => setMoving({ project }),
onLocate: () => onLocate(project),
onDelete: () => onDelete([project.id]),
};
@@ -263,6 +250,7 @@ export function ProjectsView({
onGo={setFolderId}
onRename={(name) => onRenameFolder(currentFolder.id, name)}
onDelete={() => onDeleteFolder(currentFolder)}
+ onMove={() => setMoving({ folder: currentFolder })}
/>
) : (
heading ?? <h2 className="mr-auto text-[17px] font-semibold tracking-[-0.01em] text-[var(--text)]">{t('nav.projects')}</h2>
@@ -379,19 +367,19 @@ export function ProjectsView({
{moving ? (
<FolderPicker
- title={titleOf(moving, t)}
+ title={'project' in moving ? titleOf(moving.project, t) : moving.folder.name}
folders={folders}
- counts={counts}
- current={moving.folderId && folders.some((f) => f.id === moving.folderId) ? moving.folderId : null}
- onPick={(fid) => {
- onMoveToFolder(moving.id, fid);
- setMoving(null);
- }}
- onCreate={async (name) => {
- const created = await onCreateFolder(name);
- if (created) onMoveToFolder(moving.id, created.id);
+ current={'project' in moving
+ ? (moving.project.folderId && folders.some((f) => f.id === moving.project.folderId) ? moving.project.folderId : null)
+ : parentOf(moving.folder, folders)}
+ /* a folder never goes into itself or a folder inside it */
+ exclude={'folder' in moving ? new Set([moving.folder.id, ...folders.filter((f) => folderTrail(folders, f.id).some((up) => up.id === moving.folder.id)).map((f) => f.id)]) : new Set()}
+ onMove={(fid) => {
+ if ('project' in moving) onMoveToFolder(moving.project.id, fid);
+ else onMoveFolder(moving.folder.id, fid);
setMoving(null);
}}
+ onCreate={(name, parentId) => onCreateFolder(name, parentId)}
onClose={() => setMoving(null)}
/>
) : null}
@@ -681,13 +669,13 @@ function ProjectCard({
<button
type="button"
onClick={open}
- className={`relative block aspect-video w-full overflow-hidden rounded-lg bg-[var(--surface-2)] text-left ring-1 transition duration-200 hover:brightness-[1.04] ${
- selected ? 'ring-2 ring-[var(--accent)]' : 'ring-[var(--border)]'
- }`}
+ className="relative block aspect-video w-full overflow-hidden rounded-lg bg-[var(--surface-2)] text-left ring-1 ring-[var(--border)] transition duration-200 hover:brightness-[1.04]"
aria-label={title}
aria-pressed={selecting ? selected : undefined}
>
<PosterMedia project={project} shade />
+ {/* chosen: an outline drawn inside the card, over its picture, so the list's edge never cuts it */}
+ {selected ? <span aria-hidden className="pointer-events-none absolute inset-0 z-[1] rounded-lg ring-2 ring-inset ring-[var(--accent)]" /> : null}
{project.missing ? <span aria-hidden className="absolute inset-0 bg-black/45" /> : null}
{project.duration && !project.missing ? (
<div className="absolute bottom-2 right-2 text-[10.5px] font-medium text-white/80">
@@ -814,12 +802,11 @@ function ProjectListRow({
<button
type="button"
onClick={open}
- className={`relative block aspect-video w-28 overflow-hidden rounded-md bg-[var(--surface-2)] ring-1 sm:w-36 ${
- selected ? 'ring-2 ring-[var(--accent)]' : 'ring-[var(--border)]'
- }`}
+ className="relative block aspect-video w-28 overflow-hidden rounded-md bg-[var(--surface-2)] ring-1 ring-[var(--border)] sm:w-36"
aria-label={title}
>
<PosterMedia project={project} />
+ {selected ? <span aria-hidden className="pointer-events-none absolute inset-0 z-[1] rounded-md ring-2 ring-inset ring-[var(--accent)]" /> : null}
</button>
<SelectToggle selecting={selecting} selected={selected} onToggle={onToggleSelect} label={t('library.toggleSelect')} />
</div>
@@ -888,6 +875,7 @@ interface FolderItemProps {
onCommitRename: (name: string) => void;
onCancelRename: () => void;
onDelete: () => void;
+ onMove: () => void;
}
/**
@@ -928,6 +916,7 @@ function FolderCard({
onCommitRename,
onCancelRename,
onDelete,
+ onMove,
}: FolderItemProps) {
const t = useT();
const language = useLanguage();
@@ -982,7 +971,7 @@ function FolderCard({
{formatDate(folder.createdAt, language)}
</button>
</div>
- <FolderMenu onRename={onStartRename} onDelete={onDelete} />
+ <FolderMenu onRename={onStartRename} onMove={onMove} onDelete={onDelete} />
</div>
<span className="sr-only">{t('projects.folderAll')}</span>
</article>
@@ -1020,6 +1009,7 @@ function FolderListRow({
onCommitRename,
onCancelRename,
onDelete,
+ onMove,
}: FolderItemProps) {
const t = useT();
const language = useLanguage();
@@ -1057,13 +1047,13 @@ function FolderListRow({
{formatDate(folder.createdAt, language)}
</p>
</div>
- <FolderMenu onRename={onStartRename} onDelete={onDelete} />
+ <FolderMenu onRename={onStartRename} onMove={onMove} onDelete={onDelete} />
</div>
);
}
/** A folder's "…": rename, delete. The project card's menu, in looks and placement (see ProjectMenu). */
-function FolderMenu({ onRename, onDelete }: { onRename: () => void; onDelete: () => void }) {
+function FolderMenu({ onRename, onMove, onDelete }: { onRename: () => void; onMove: () => void; onDelete: () => void }) {
const t = useT();
const [anchor, setAnchor] = React.useState<{ x: number; y: number; top: number } | null>(null);
const button = React.useRef<HTMLButtonElement>(null);
@@ -1094,6 +1084,7 @@ function FolderMenu({ onRename, onDelete }: { onRename: () => void; onDelete: ()
onClose={() => setAnchor(null)}
items={[
{ id: 'rename', icon: <Pencil size={14} />, label: t('projects.renameFolder'), onSelect: onRename },
+ { id: 'move', icon: <FolderInput size={14} />, label: t('projects.moveTo'), onSelect: onMove },
{ id: 'sep', separator: true },
{ id: 'delete', icon: <Trash2 size={14} />, label: t('projects.deleteFolder'), danger: true, onSelect: onDelete },
]}
@@ -1114,6 +1105,7 @@ function FolderCrumb({
onGo,
onRename,
onDelete,
+ onMove,
}: {
folder: ProjectFolder;
/** the folders it is in, the outermost first */
@@ -1123,6 +1115,7 @@ function FolderCrumb({
onGo: (folderId: string | null) => void;
onRename: (name: string) => void;
onDelete: () => void;
+ onMove: () => void;
}) {
const t = useT();
const [renaming, setRenaming] = React.useState(false);
@@ -1163,7 +1156,7 @@ function FolderCrumb({
</button>
)}
<span className="shrink-0 text-[12.5px] font-normal tabular-nums text-[var(--text-faint)]">{count}</span>
- <FolderMenu onRename={() => setRenaming(true)} onDelete={onDelete} />
+ <FolderMenu onRename={() => setRenaming(true)} onMove={onMove} onDelete={onDelete} />
</h2>
);
}
@@ -1216,41 +1209,38 @@ function InlineNameInput({
}
/**
- * Pick a folder for a project: a small centered card, "Move to folder" and the project's name on top, then the places
- * it can go (each a tinted folder tile, the name and how many it holds; the current one ticked), "No folder" first and
- * a new folder last (named, then the project goes straight in). A pick moves it and closes.
+ * Where a project, or a folder of the list, goes: the folders as a tree, as a file browser shows them. "Projects" (no
+ * folder) at the top and each folder under the one it is in, opened and closed by its arrow. A click picks a place and
+ * a double click (or Move, or Enter) moves it there; the place it is in now is marked and cannot be picked. New folder
+ * makes one inside the place picked, named in the tree, and picks it. A folder never offers itself or what is in it
+ * (`exclude`).
*/
function FolderPicker({
title,
folders,
- counts,
current,
- onPick,
+ exclude,
+ onMove,
onCreate,
onClose,
}: {
title: string;
folders: ProjectFolder[];
- counts: Record<string, number>;
current: string | null;
- onPick: (folderId: string | null) => void;
- onCreate: (name: string) => void | Promise<void>;
+ exclude: ReadonlySet<string>;
+ onMove: (folderId: string | null) => void;
+ onCreate: (name: string, parentId: string | null) => Promise<ProjectFolder | null>;
onClose: () => void;
}) {
const t = useT();
- const [creating, setCreating] = React.useState(false);
- const tree = React.useMemo(() => {
- const out: { folder: ProjectFolder; depth: number }[] = [];
- const walk = (parent: string | null, depth: number) => {
- for (const f of folders) {
- if (parentOf(f, folders) !== parent || out.some((o) => o.folder.id === f.id)) continue;
- out.push({ folder: f, depth });
- walk(f.id, depth + 1);
- }
- };
- walk(null, 0);
- return out;
- }, [folders]);
+ /* null is the project list itself (no folder) */
+ const [picked, setPicked] = React.useState<string | null>(current);
+ const [shut, setShut] = React.useState<ReadonlySet<string>>(new Set());
+ /* a new folder being named, inside this place (undefined: none) */
+ const [naming, setNaming] = React.useState<string | null | undefined>(undefined);
+ const children = React.useCallback((parent: string | null) => folders
+ .filter((f) => parentOf(f, folders) === parent && !exclude.has(f.id))
+ .sort((a, b) => a.name.localeCompare(b.name)), [folders, exclude]);
React.useEffect(() => {
/* this Escape closes the picker, not the popover under it */
const onKey = (event: KeyboardEvent) => {
@@ -1262,94 +1252,118 @@ function FolderPicker({
return () => window.removeEventListener('keydown', onKey, true);
}, [onClose]);
- const row = (selected: boolean) =>
- `group flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition ${
- selected ? 'bg-[var(--bg-active)]' : 'hover:bg-[var(--bg-hover)]'
- }`;
- const tile = 'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg';
+ const canMove = picked !== current;
+ const move = (to: string | null) => { if (to !== current) onMove(to); };
+ const toggle = (id: string) => setShut((was) => { const next = new Set(was); if (next.has(id)) next.delete(id); else next.add(id); return next; });
+ const startNew = () => {
+ setNaming(picked);
+ if (picked) setShut((was) => { const next = new Set(was); next.delete(picked); return next; });
+ };
+ const named = async (name: string) => {
+ const parent = naming ?? null;
+ setNaming(undefined);
+ if (!name) return;
+ const made = await onCreate(name, parent);
+ if (made) setPicked(made.id);
+ };
+
+ /* a place: its arrow (when it holds folders), its icon, its name, and "Here now" on the place it is in */
+ const place = (id: string | null, depth: number, icon: React.ReactNode, label: string): React.ReactNode => {
+ const kids = children(id);
+ const open = id === null || !shut.has(id);
+ const isPicked = picked === id;
+ const here = current === id;
+ return (
+ <React.Fragment key={id ?? 'top'}>
+ <div
+ role="treeitem"
+ aria-selected={isPicked}
+ aria-expanded={kids.length ? open : undefined}
+ onClick={() => setPicked(id)}
+ onDoubleClick={() => move(id)}
+ style={{ paddingLeft: 6 + depth * 18 }}
+ className={`flex h-8 cursor-default select-none items-center gap-1.5 rounded-md pr-2.5 text-[13px] ${
+ isPicked ? 'bg-[var(--accent)] text-[var(--on-accent)]' : 'text-[var(--text)] hover:bg-[var(--bg-hover)]'
+ }`}
+ >
+ {kids.length && id !== null ? (
+ <button type="button" aria-label={label} onClick={(event) => { event.stopPropagation(); toggle(id); }}
+ className="flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-70 hover:opacity-100">
+ <ChevronRight size={13} className={`transition-transform ${open ? 'rotate-90' : ''}`} />
+ </button>
+ ) : <span className="w-4 shrink-0" />}
+ <span className={`shrink-0 ${isPicked ? '' : 'text-[var(--text-dim)]'}`}>{icon}</span>
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {here ? <span className={`shrink-0 text-[11.5px] ${isPicked ? 'opacity-80' : 'text-[var(--text-faint)]'}`}>{t('projects.hereNow')}</span> : null}
+ </div>
+ {open ? (
+ <>
+ {naming === id ? (
+ <div className="flex h-8 items-center gap-1.5 pr-2.5" style={{ paddingLeft: 6 + (depth + 1) * 18 }}>
+ <span className="w-4 shrink-0" />
+ <Folder size={15} strokeWidth={1.7} className="shrink-0 text-[var(--text-dim)]" />
+ <InlineNameInput
+ initial=""
+ placeholder={t('projects.newFolderName')}
+ onCommit={(name) => void named(name)}
+ onCancel={() => setNaming(undefined)}
+ className="h-6 min-w-0 flex-1 rounded border border-[var(--text)] bg-[var(--surface)] px-1.5 text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]"
+ />
+ </div>
+ ) : null}
+ {kids.map((f) => place(f.id, depth + 1, <Folder size={15} strokeWidth={1.7} />, f.name))}
+ </>
+ ) : null}
+ </React.Fragment>
+ );
+ };
return createPortal(
<div
role="dialog"
aria-modal
- className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/35 p-4 backdrop-blur-[2px]"
+ aria-label={t('projects.moveToTitle').replace('{name}', title)}
+ className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/35 p-4"
onMouseDown={(event) => {
if (event.target === event.currentTarget) onClose();
}}
>
<div
- className="w-full max-w-[360px] overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"
+ className="flex w-full max-w-[460px] flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"
style={{ animation: 'openfilm-pop 0.16s ease-out both' }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && naming === undefined && canMove && !(event.target instanceof HTMLInputElement)) { event.preventDefault(); move(picked); }
+ }}
>
- <div className="flex items-start gap-3 px-5 pb-3 pt-5">
+ <div className="flex items-start gap-3 px-5 pb-3 pt-4">
<div className="min-w-0 flex-1">
- <p className="text-[15px] font-semibold text-[var(--text)]">{t('projects.moveToFolder')}</p>
- <p className="mt-0.5 truncate text-[12.5px] text-[var(--text-muted)]">{title}</p>
+ <p className="truncate text-[15px] font-semibold text-[var(--text)]">{t('projects.moveToTitle').replace('{name}', title)}</p>
+ <p className="mt-0.5 text-[12.5px] text-[var(--text-muted)]">{t('projects.moveHint')}</p>
</div>
<button
type="button"
onClick={onClose}
aria-label={t('confirm.cancel')}
- className="-mr-1.5 -mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
+ className="-mr-1.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
>
<X size={15} />
</button>
</div>
- <div className="max-h-[52vh] overflow-y-auto px-2.5 pb-1">
- <button type="button" onClick={() => onPick(null)} className={row(current === null)}>
- <span className={`${tile} border border-dashed border-[var(--border-strong)] text-[var(--text-faint)]`}>
- <FolderOpen size={16} strokeWidth={1.7} />
- </span>
- <span className="min-w-0 flex-1 truncate text-[13.5px] text-[var(--text)]">{t('projects.noFolder')}</span>
- {current === null ? <Check size={15} className="shrink-0 text-[var(--text)]" /> : null}
- </button>
- {/* as a tree: each folder under the one it is in, a step in */}
- {tree.map(({ folder, depth }) => (
- <button key={folder.id} type="button" onClick={() => onPick(folder.id)} className={row(current === folder.id)} style={{ paddingLeft: 10 + depth * 18 }}>
- <span className={`${tile} bg-[var(--surface-3)] text-[var(--text-dim)]`}>
- <Folder size={16} strokeWidth={1.7} />
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-[13.5px] text-[var(--text)]">{folder.name}</span>
- <span className="block text-[11.5px] tabular-nums text-[var(--text-faint)]">
- {counts[folder.id] ?? 0}
- </span>
- </span>
- {current === folder.id ? <Check size={15} className="shrink-0 text-[var(--text)]" /> : null}
- </button>
- ))}
+ <div role="tree" tabIndex={0} className="mx-5 h-[260px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--bg)] p-1 outline-none">
+ {place(null, 0, <LayoutGrid size={15} strokeWidth={1.7} />, t('nav.projects'))}
</div>
- <div className="border-t border-[var(--border-soft)] p-2.5">
- {creating ? (
- <div className="flex items-center gap-3 px-2.5 py-1.5">
- <span className={`${tile} bg-[var(--brand-wind-from)]/15 text-[var(--brand-wind-from)]`}>
- <FolderPlus size={16} strokeWidth={1.7} />
- </span>
- <InlineNameInput
- initial=""
- placeholder={t('projects.folderNamePlaceholder')}
- onCommit={(name) => {
- setCreating(false);
- if (name) void onCreate(name);
- }}
- onCancel={() => setCreating(false)}
- className="h-8 min-w-0 flex-1 rounded-lg border border-[var(--text)] bg-[var(--surface)] px-2.5 text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]"
- />
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setCreating(true)}
- className="flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition hover:bg-[var(--bg-hover)]"
- >
- <span className={`${tile} bg-[var(--brand-wind-from)]/15 text-[var(--brand-wind-from)]`}>
- <FolderPlus size={16} strokeWidth={1.7} />
- </span>
- <span className="text-[13.5px] text-[var(--text)]">{t('projects.newFolder')}</span>
- </button>
- )}
+ <div className="flex items-center gap-2 px-5 py-4">
+ <button type="button" onClick={startNew}
+ className="flex h-8 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]">
+ <FolderPlus size={14} strokeWidth={1.8} />{t('projects.newFolder')}
+ </button>
+ <span className="flex-1" />
+ <button type="button" onClick={onClose}
+ className="h-8 rounded-lg border border-[var(--border)] px-3 text-[12.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]">{t('confirm.cancel')}</button>
+ <button type="button" disabled={!canMove} onClick={() => move(picked)}
+ className="h-8 rounded-lg bg-[var(--text)] px-4 text-[12.5px] font-medium text-[var(--bg)] transition hover:opacity-90 disabled:opacity-40">{t('projects.move')}</button>
</div>
</div>
</div>,
diff --git a/packages/openfilm/studio/ui/src/components/PropertiesSection.tsx b/packages/openfilm/studio/ui/src/components/PropertiesSection.tsx
new file mode 100644
index 0000000..2820ea4
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/PropertiesSection.tsx
@@ -0,0 +1,418 @@
+/**
+ * A page clip's Properties: what its page offers to change, each a property the person made of one of its layers (its
+ * words, its picture, whether it shows) or of one of its CSS variables (lib/component-props), as a design tool's
+ * component offers its properties. Only those, none worked out on their own. Each field paints first and writes when
+ * let go, as every inspector field does; what a clip fills in is an override, and a property can go back to its
+ * default. Its name is the person's: renamed with a double-click, removed from its menu. A pointer on a row outlines
+ * its layer on the picture.
+ */
+import * as React from 'react';
+import { HardDriveUpload, ImageIcon, Plus, RotateCcw } from 'lucide-react';
+
+import { useT } from '@/i18n';
+import type { FilmOverride } from '@/lib/film';
+import {
+ ROOT, fieldOf, isFontVar, labelOf, relativeTo, valueOf, type TemplateControls, type VarField,
+} from '@/lib/template-controls';
+import {
+ propOf, propValue, renamedProp, withProp, withPropValue, withPropsReset, withoutProp, type ComponentProp, type PropValue,
+} from '@/lib/component-props';
+import { joinFontFamily, splitFontFamily } from '@/lib/font-styles';
+import { readResourceDragData, RESOURCE_DRAG_TYPE } from '@/lib/resource-drag';
+import { ColorField, FIELD, INPUT, NumField, Section, SectionAction } from './inspector-fields';
+import { FontFamilyPicker } from './FontFamilyPicker';
+import { ContextMenu, type ContextMenuEntry } from './ContextMenu';
+import { pictureThumb } from './stage-menu';
+import { Tooltip } from './Tooltip';
+
+type T = ReturnType<typeof useT>;
+
+/** What the section needs of the clip: its page as it is on the picture, its overrides and properties, the picture. */
+export interface PropsHost {
+ /** What the page shows now (its variables, words and pictures); null when the clip is not on the picture now. */
+ read: () => Promise<TemplateControls | null>;
+ overrides: () => readonly FilmOverride[] | undefined;
+ /** The clip's properties (its data-props). */
+ props: () => readonly ComponentProp[];
+ /** Write the clip's properties. */
+ setProps: (next: readonly ComponentProp[]) => void;
+ /** Paints a change without writing it; null takes it back. */
+ preview: (target: { at: string; n?: number }, patch: { style?: Record<string, string>; text?: string } | null) => void;
+ /** The page's file, by its place in the project: a picture put in is named from its folder. */
+ page: string;
+ /** The project's pictures, by their place in the project, each with where its thumbnail is read from. */
+ pictures: () => Array<{ path: string; name: string; url?: string }>;
+ /** One from this computer, brought into the project: its place there (null: none picked). */
+ pickPicture?: () => Promise<string | null>;
+ /** Outline a layer of the page on the picture (a row pointed at); null: none. */
+ point?: (target: { at: string; n?: number } | null) => void;
+}
+
+const PICTURE = /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i;
+
+/* a page clip off the picture is read again now and then: the playhead may come to it */
+const OFF_PICTURE_EVERY_MS = 1500;
+
+const isNamedColor = (v: string) => typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('color', v);
+
+const sameAt = (a: { at: string; n?: number }, b: { at: string; n?: number }) => a.at === b.at && (a.n ?? null) === (b.n ?? null);
+
+export function PropertiesSection({ host, commit }: {
+ host: PropsHost;
+ /** Writes the clip's next overrides (null: none left). */
+ commit: (next: FilmOverride[] | null) => void;
+}) {
+ const t = useT();
+ const [controls, setControls] = React.useState<TemplateControls | null | undefined>(undefined);
+ const [menu, setMenu] = React.useState<{ x: number; y: number; items: ContextMenuEntry[] } | null>(null);
+ const [renaming, setRenaming] = React.useState<string | null>(null);
+ const overrides = host.overrides();
+ const props = host.props();
+ const kept = JSON.stringify(overrides ?? []);
+ React.useEffect(() => {
+ let live = true;
+ let timer = 0;
+ const read = () => {
+ void host.read().catch(() => null).then((next) => {
+ if (!live) return;
+ setControls((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
+ if (!next) timer = window.setTimeout(read, OFF_PICTURE_EVERY_MS);
+ });
+ };
+ /* the picture shows a written change a moment after it is kept */
+ timer = window.setTimeout(read, 120);
+ return () => { live = false; window.clearTimeout(timer); };
+ }, [host, kept]);
+ /* nothing stays outlined once the section goes (another clip in hand) */
+ React.useEffect(() => () => { host.point?.(null); }, [host]);
+
+ const set = (prop: ComponentProp, value: PropValue | null) => commit(withPropValue(overrides, prop, value));
+ const changed = props.filter((p) => propValue(overrides, p) != null);
+ /* the page's variables not offered yet: what the + offers */
+ const vars = (controls?.vars ?? []).filter((v) => !propOf(props, 'var', v.name));
+ const add = (e: React.MouseEvent<HTMLButtonElement>) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setMenu({
+ x: r.left, y: r.bottom + 4,
+ items: vars.length
+ ? vars.map((v) => ({ id: `var:${v.name}`, label: labelOf(v.name), hint: v.name, onSelect: () => host.setProps(withProp(props, { name: labelOf(v.name), type: 'var', var: v.name })) }))
+ : [{ id: 'no-vars', label: t('inspector.propsNoVars'), disabled: true, onSelect: () => {} }],
+ });
+ };
+ const rowMenu = (e: React.MouseEvent, prop: ComponentProp) => {
+ e.preventDefault();
+ setMenu({
+ x: e.clientX, y: e.clientY,
+ items: [
+ { id: 'rename', label: t('inspector.propRename'), onSelect: () => setRenaming(prop.name) },
+ { id: 'remove', label: t('inspector.propRemove'), onSelect: () => host.setProps(withoutProp(props, prop.name)) },
+ ],
+ });
+ };
+ const pointing = (prop: ComponentProp) => {
+ const target = prop.type === 'var' ? null : { at: prop.at, ...(prop.n ? { n: prop.n } : {}) };
+ return target ? {
+ onPointerEnter: () => host.point?.(target),
+ onPointerLeave: () => host.point?.(null),
+ onFocus: () => host.point?.(target),
+ onBlur: () => host.point?.(null),
+ } : {};
+ };
+
+ const field = (prop: ComponentProp): React.ReactNode => {
+ const value = propValue(overrides, prop);
+ switch (prop.type) {
+ case 'text': {
+ const own = controls?.texts.find((x) => sameAt(x, prop))?.value ?? '';
+ const target = { at: prop.at, ...(prop.n ? { n: prop.n } : {}) };
+ return (
+ <WordsInput
+ label={prop.name}
+ value={typeof value === 'string' ? value : own}
+ onCommit={(next) => set(prop, next === own ? null : next)}
+ onPreview={(next) => host.preview(target, next == null ? null : { text: next })}
+ />
+ );
+ }
+ case 'image': {
+ const own = controls?.images?.find((x) => sameAt(x, prop))?.src ?? '';
+ /* what it draws now: the picture put in, read from the page's folder, else the page's own */
+ const src = typeof value === 'string' && controls?.page ? new URL(value, controls.page).href : own;
+ return <PictureInput src={src} host={host} label={prop.name} onPick={(path) => set(prop, relativeTo(host.page, path))} t={t} />;
+ }
+ case 'boolean':
+ return <Switch label={prop.name} on={value !== false} onChange={(on) => set(prop, on ? null : false)} />;
+ case 'var': {
+ const own = controls?.vars.find((v) => v.name === prop.var)?.value ?? '';
+ const now = typeof value === 'string' ? value : own;
+ const paint = (next: string | null) => host.preview({ at: ROOT }, next == null ? null : { style: { [prop.var]: next } });
+ return isFontVar(prop.var, now)
+ ? <FontInput label={prop.name} value={now} onCommit={(next) => set(prop, next)} onPreview={paint} />
+ : <VarInput name={prop.name} field={fieldOf(now, isNamedColor)} onCommit={(next) => set(prop, next)} onPreview={paint} />;
+ }
+ }
+ };
+
+ return (
+ <Section
+ id="properties"
+ title={t('inspector.props')}
+ aside={(
+ <span className="flex items-center">
+ {changed.length ? (
+ <SectionAction label={t('inspector.propsResetAll')} onClick={() => commit(withPropsReset(overrides, props))}><RotateCcw size={11} /></SectionAction>
+ ) : null}
+ <Tooltip label={t('inspector.propsAdd')}>
+ <button type="button" aria-label={t('inspector.propsAdd')} onClick={add} className="flex h-5 w-5 items-center justify-center rounded-[4px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
+ <Plus size={12} />
+ </button>
+ </Tooltip>
+ </span>
+ )}
+ >
+ {!props.length ? (
+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.propsEmpty')}</p>
+ ) : props.map((prop) => (
+ <div key={prop.name} {...pointing(prop)} onContextMenu={(e) => rowMenu(e, prop)}>
+ <Line
+ label={renaming === prop.name ? (
+ <NameInput
+ value={prop.name}
+ onDone={(next) => { setRenaming(null); host.setProps(renamedProp(props, prop.name, next)); }}
+ onCancel={() => setRenaming(null)}
+ />
+ ) : prop.name}
+ title={t('inspector.propRenameHint')}
+ onRename={() => setRenaming(prop.name)}
+ changed={propValue(overrides, prop) != null}
+ onReset={() => set(prop, null)}
+ t={t}
+ >
+ {field(prop)}
+ </Line>
+ </div>
+ ))}
+ {!controls && props.length ? (
+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.templateOffPicture')}</p>
+ ) : null}
+ {menu ? <ContextMenu x={menu.x} y={menu.y} items={menu.items} onClose={() => setMenu(null)} /> : null}
+ </Section>
+ );
+}
+
+/** A property's name typed anew: kept on Enter or when left, Esc gives up. */
+function NameInput({ value, onDone, onCancel }: { value: string; onDone: (next: string) => void; onCancel: () => void }) {
+ const [raw, setRaw] = React.useState(value);
+ const done = React.useRef(false);
+ return (
+ <input
+ autoFocus
+ value={raw}
+ spellCheck={false}
+ onFocus={(e) => e.currentTarget.select()}
+ onChange={(e) => setRaw(e.target.value)}
+ onBlur={() => { if (!done.current) { done.current = true; onDone(raw); } }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.nativeEvent.isComposing) { done.current = true; onDone(raw); }
+ if (e.key === 'Escape') { done.current = true; onCancel(); }
+ }}
+ className="h-5 w-full min-w-0 rounded-[4px] bg-[var(--bg)] px-1 text-[11px] text-[var(--text)] outline-none ring-1 ring-[var(--accent)]"
+ />
+ );
+}
+
+/** Shown or not: a switch. */
+function Switch({ label, on, onChange }: { label: string; on: boolean; onChange: (on: boolean) => void }) {
+ return (
+ <button type="button" role="switch" aria-checked={on} aria-label={label} onClick={() => onChange(!on)} className="flex h-6 items-center">
+ <span aria-hidden className={`relative h-[16px] w-[28px] shrink-0 rounded-full transition-colors ${on ? 'bg-[var(--text)]' : 'bg-[var(--surface-2)] ring-1 ring-inset ring-[var(--border)]'}`}>
+ <span className={`absolute top-[3px] h-2.5 w-2.5 rounded-full transition-all ${on ? 'left-[15px] bg-[var(--bg)]' : 'left-[3px] bg-[var(--text-faint)]'}`} />
+ </span>
+ </button>
+ );
+}
+
+/** A picture: its thumbnail and name; clicked, the project's pictures and one from this computer; a picture dropped. */
+export function PictureInput({ src, host, label, onPick, t }: {
+ src: string; host: Pick<PropsHost, 'pictures' | 'pickPicture'>; label: string; onPick: (path: string) => void; t: T;
+}) {
+ const [menu, setMenu] = React.useState<{ x: number; y: number } | null>(null);
+ const [over, setOver] = React.useState(false);
+ const name = decodeURIComponent(src.split(/[?#]/)[0]!.split('/').pop() ?? '');
+ const entries = (): ContextMenuEntry[] => {
+ const list = host.pictures().slice(0, 40);
+ const pick = host.pickPicture;
+ return [
+ ...list.map((f) => ({ id: `pic:${f.path}`, label: f.name, icon: pictureThumb(f.url), onSelect: () => onPick(f.path) })),
+ ...(pick ? [
+ ...(list.length ? [{ id: 'pic-sep', separator: true as const }] : []),
+ { id: 'pic-computer', label: t('inspector.templatePictureComputer'), icon: <HardDriveUpload size={14} />, onSelect: () => { void pick().then((path) => { if (path && PICTURE.test(path)) onPick(path); }); } },
+ ] : []),
+ ];
+ };
+ return (
+ <>
+ <button
+ type="button"
+ aria-label={`${label}: ${t('inspector.templatePictureReplace')}`}
+ title={t('inspector.templatePictureReplace')}
+ onClick={(e) => { const r = e.currentTarget.getBoundingClientRect(); setMenu({ x: r.left, y: r.bottom + 4 }); }}
+ onDragOver={(e) => { if (e.dataTransfer.types.includes(RESOURCE_DRAG_TYPE)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; setOver(true); } }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ setOver(false);
+ const file = readResourceDragData(e.dataTransfer);
+ if (!file || file.saved || !PICTURE.test(file.path)) return;
+ e.preventDefault();
+ onPick(file.path);
+ }}
+ className={`${FIELD} gap-1.5 px-1 text-left ${over ? 'ring-[1.5px] ring-[var(--accent)]' : ''}`}
+ >
+ <span className="flex h-[18px] w-[28px] shrink-0 items-center justify-center overflow-hidden rounded-[3px] bg-[var(--bg-hover)]">
+ {src ? <img src={src} alt="" className="h-full w-full object-cover" draggable={false} /> : <ImageIcon size={12} />}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[11px] text-[var(--text)]">{name}</span>
+ </button>
+ {menu ? <ContextMenu x={menu.x} y={menu.y} items={entries()} onClose={() => setMenu(null)} /> : null}
+ </>
+ );
+}
+
+/** A custom property that names a font: the font picker over its first family, the fallbacks after it kept. */
+function FontInput({ label, value, onCommit, onPreview }: {
+ label: string; value: string; onCommit: (value: string) => void; onPreview: (value: string | null) => void;
+}) {
+ const [family, rest] = splitFontFamily(value);
+ return (
+ <FontFamilyPicker
+ label={label}
+ value={family}
+ sample=""
+ onPreview={(next) => onPreview(joinFontFamily(next, rest))}
+ onRevert={() => onPreview(null)}
+ onCommit={(next) => onCommit(joinFontFamily(next, rest))}
+ className={FIELD}
+ />
+ );
+}
+
+/** A property: its name on the left (a double-click renames it), its field, and going back to its default. */
+function Line({ label, title, changed, onReset, onRename, t, children }: {
+ label: React.ReactNode; title: string; changed: boolean; onReset: () => void; onRename: () => void; t: T; children: React.ReactNode;
+}) {
+ const reset = changed ? (
+ <SectionAction label={t('inspector.propReset')} onClick={onReset}><RotateCcw size={11} /></SectionAction>
+ ) : <span className="w-5" />;
+ const name = (
+ <span className="min-w-0 truncate text-[11px] text-[var(--text-muted)]" title={title} onDoubleClick={onRename}>
+ {changed ? <span aria-hidden className="mr-1 inline-block h-1.5 w-1.5 rounded-full bg-[var(--accent)] align-middle" /> : null}
+ {label}
+ </span>
+ );
+ return (
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_20px] items-center gap-1.5">
+ {name}
+ <div className="min-w-0">{children}</div>
+ {reset}
+ </div>
+ );
+}
+
+/** A custom property's field by its kind: a color, a number with its unit, or words. */
+function VarInput({ name, field, onCommit, onPreview }: {
+ name: string;
+ field: VarField;
+ onCommit: (value: string) => void;
+ onPreview: (value: string | null) => void;
+}) {
+ const label = labelOf(name);
+ if (field.kind === 'color') {
+ return <ColorField label={label} value={field.value} onCommit={onCommit} onPreview={onPreview} />;
+ }
+ if (field.kind === 'number') {
+ const step = Number.isInteger(field.value) && Math.abs(field.value) >= 2 ? 1 : 0.1;
+ return (
+ <NumField
+ label={label}
+ bare
+ value={field.value}
+ step={step}
+ {...(field.unit ? { unit: field.unit } : {})}
+ onCommit={(n) => onCommit(valueOf({ ...field, value: n }))}
+ onPreview={(n) => onPreview(valueOf({ ...field, value: n }))}
+ onRevert={() => onPreview(null)}
+ />
+ );
+ }
+ return (
+ <TypedInput
+ label={label}
+ value={field.value}
+ onCommit={(v) => onCommit(valueOf({ ...field, value: v }))}
+ />
+ );
+}
+
+/** One line typed and kept when left or on Enter; Esc gives up. */
+function TypedInput({ label, value, onCommit }: { label: string; value: string; onCommit: (value: string) => void }) {
+ const [raw, setRaw] = React.useState(value);
+ React.useEffect(() => setRaw(value), [value]);
+ const cancelled = React.useRef(false);
+ return (
+ <div className={FIELD}>
+ <input
+ aria-label={label}
+ value={raw}
+ spellCheck={false}
+ onChange={(e) => setRaw(e.target.value)}
+ onBlur={() => {
+ if (cancelled.current) { cancelled.current = false; return; }
+ if (raw.trim() && raw !== value) onCommit(raw);
+ else setRaw(value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.nativeEvent.isComposing) (e.target as HTMLInputElement).blur();
+ if (e.key === 'Escape') { cancelled.current = true; setRaw(value); (e.target as HTMLInputElement).blur(); }
+ }}
+ className={`${INPUT} pl-2`}
+ />
+ </div>
+ );
+}
+
+/** A layer's words: the picture follows as they are typed, kept when left or on Enter (Shift+Enter: a new line). */
+function WordsInput({ label, value, onCommit, onPreview }: {
+ label: string;
+ value: string;
+ onCommit: (value: string) => void;
+ onPreview: (value: string | null) => void;
+}) {
+ const [raw, setRaw] = React.useState(value);
+ const typing = React.useRef(false);
+ React.useEffect(() => { if (!typing.current) setRaw(value); }, [value]);
+ const cancelled = React.useRef(false);
+ return (
+ <textarea
+ aria-label={label}
+ value={raw}
+ rows={Math.min(4, Math.max(1, raw.split('\n').length))}
+ onChange={(e) => { typing.current = true; setRaw(e.target.value); onPreview(e.target.value); }}
+ onBlur={() => {
+ typing.current = false;
+ if (cancelled.current) { cancelled.current = false; return; }
+ if (raw !== value) onCommit(raw);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); (e.target as HTMLTextAreaElement).blur(); }
+ if (e.key === 'Escape') {
+ cancelled.current = true;
+ typing.current = false;
+ setRaw(value);
+ onPreview(null);
+ (e.target as HTMLTextAreaElement).blur();
+ }
+ }}
+ className="w-full resize-none rounded-[5px] bg-[var(--fill-tsp)] px-2 py-1 text-[11.5px] leading-[1.5] text-[var(--text)] outline-none ring-1 ring-inset ring-transparent transition hover:ring-[var(--border)] focus:bg-[var(--bg)] focus:ring-[1.5px] focus:ring-[var(--accent)]"
+ />
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/SkillsLibrary.tsx b/packages/openfilm/studio/ui/src/components/SkillsLibrary.tsx
new file mode 100644
index 0000000..1c9c251
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/SkillsLibrary.tsx
@@ -0,0 +1,504 @@
+/**
+ * Skills: what an agent can take up when making a film. Two views, switched in their own row:
+ *
+ * · Installed what agents get, the person's own first, then the official ones they installed, then this project's,
+ * then each agent's own (those the person installed in Codex, Claude Code…, off until let in). Each is a
+ * row with its switch: on, an agent takes it up whenever it fits; off, it stays here and no agent gets it.
+ * · Discover OpenFilm's official skills, a catalog: one is installed to be used (it starts on).
+ *
+ * One opened is a page in place of the list, as an example is (the gallery's Back returns to the list as it was): its
+ * preview or picture on the left; on the right its title and switch, what it is for, and what to do with it: Install,
+ * or Try now (a new conversation with the skill named in its message), and uninstalling it (an official one) or moving
+ * it to the trash (the person's own, a project's). Adding one (a link, a folder, made with the agent) is the app's own
+ * dialog.
+ */
+import React from 'react';
+import {
+ Blocks, Check, Copy, Film, Folder, GitBranch, Github, Info, Layers, MessageSquarePlus, MonitorPlay,
+ MoreHorizontal, Music, PenLine, PictureInPicture2, Plus, Presentation, Scissors, Search, Shapes, Sparkles, Trash2, Wand2, X,
+ type LucideIcon,
+} from 'lucide-react';
+import { useLanguage, useT } from '@/i18n';
+import { studioHost, type HostAgentId } from '@/lib/host';
+import { sourcesApi, type SkillEntry } from '@/lib/project-sources';
+import { ConfirmDialog } from './ConfirmDialog';
+import { ContextMenu, type ContextMenuEntry } from './ContextMenu';
+import { SettingsSwitch } from './settings/ui';
+
+export type SkillsView = 'installed' | 'discover';
+type Kind = 'all' | 'workflow' | 'style';
+/** One of an agent's own skills (Settings → Agents lets the same in). */
+type AgentSkill = { name: string; description: string; allowed: boolean };
+type AgentGroup = { id: HostAgentId; name: string; skills: AgentSkill[] };
+
+export const byOrder = (a: SkillEntry, b: SkillEntry) => (a.order ?? 999) - (b.order ?? 999) || a.name.localeCompare(b.name);
+/** words in the language shown, else its family's, else English, else any */
+export const inLanguage = (words: Record<string, string> | undefined, lang: string) =>
+ (words ? words[lang] ?? words[lang.split('-')[0]!] ?? words.en ?? Object.values(words)[0] : undefined);
+
+/** A skill as people see it: its title and summary in the language shown, else its name and the agent's description. */
+export function useSkillWords() {
+ const lang = useLanguage();
+ return (skill: SkillEntry) => ({
+ title: inLanguage(skill.shown?.title, lang) ?? skill.name,
+ summary: inLanguage(skill.shown?.summary, lang) ?? skill.description,
+ });
+}
+
+/** An official one not installed is in the catalog only; the person's own and a project's are installed already. */
+const installedOf = (skill: SkillEntry) => skill.installed !== false;
+
+export function SkillsLibrary({ skills, setSkills, projectId, opened, onOpen, onBack, onTry }: {
+ skills: SkillEntry[];
+ setSkills: React.Dispatch<React.SetStateAction<SkillEntry[]>>;
+ projectId: string | null;
+ /** the skill whose page is open (the gallery keeps it: its Back and Esc return to the list) */
+ opened: SkillEntry | null;
+ onOpen: (skill: SkillEntry) => void;
+ /** back to the list (the skill opened was removed) */
+ onBack: () => void;
+ /** Try now: a new conversation with the skill named (none: Studio without the app's chat) */
+ onTry?: (skill: SkillEntry) => void;
+}) {
+ const t = useT();
+ const words = useSkillWords();
+ const [view, setView] = React.useState<SkillsView>(() => (skills.some(installedOf) ? 'installed' : 'discover'));
+ const [kind, setKind] = React.useState<Kind>('all');
+ const [query, setQuery] = React.useState('');
+ const [removing, setRemoving] = React.useState<SkillEntry | null>(null);
+ const agents = useAgentSkills();
+
+ /* each change shown at once, then the list read again (watchSkills) */
+ const patch = (name: string, change: (k: SkillEntry) => SkillEntry) => setSkills((list) => list.map((k) => (k.name === name ? change(k) : k)));
+ const reload = () => { void sourcesApi.skills(projectId).then(setSkills); };
+ const turn = (skill: SkillEntry, on: boolean) => {
+ patch(skill.name, (k) => { const { off: _was, ...rest } = k; return on ? rest : { ...rest, off: true }; });
+ void sourcesApi.setSkillOn(skill.name, on).catch(reload);
+ };
+ const install = (skill: SkillEntry, installed: boolean) => {
+ patch(skill.name, (k) => { const { off: _was, ...rest } = k; return { ...rest, installed }; });
+ void sourcesApi.setSkillInstalled(skill.name, installed).catch(reload);
+ };
+ const remove = (skill: SkillEntry) => {
+ if (skill.source === 'official') { install(skill, false); return; }
+ setRemoving(skill);
+ };
+
+ const q = query.trim().toLowerCase();
+ const matches = (k: SkillEntry) => !q || [words(k).title, words(k).summary, k.name].some((w) => w?.toLowerCase().includes(q));
+ const installed = skills.filter(installedOf).filter(matches);
+ const groups = [
+ { id: 'mine', label: t('gallery.mine'), hint: t('gallery.mineHint'), items: installed.filter((k) => k.source === 'mine').sort(byOrder) },
+ { id: 'official', label: t('gallery.fromOpenFilm'), hint: t('gallery.officialHint'), items: installed.filter((k) => k.source === 'official').sort(byOrder) },
+ { id: 'project', label: t('gallery.project'), hint: t('gallery.projectHint'), items: installed.filter((k) => k.source === 'project').sort(byOrder) },
+ ];
+ const catalog = skills.filter((k) => k.source === 'official' && (kind === 'all' || (kind === 'style') === (k.kind === 'style')) && matches(k)).sort(byOrder);
+ const count = skills.filter(installedOf).length + agents.groups.reduce((n, g) => n + g.skills.filter((s) => s.allowed).length, 0);
+
+ const chip = (selected: boolean, label: React.ReactNode, onClick: () => void, key: string) => (
+ <button key={key} type="button" role="tab" aria-selected={selected} onClick={onClick}
+ className={`flex h-8 shrink-0 items-center gap-1.5 rounded-[8px] px-3 text-[13px] transition ${selected ? 'bg-[var(--bg-hover)] font-medium text-[var(--text)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>
+ {label}
+ </button>
+ );
+
+ const confirm = (
+ <ConfirmDialog open={removing != null} danger
+ title={t('gallery.removeTitle').replace('{name}', removing ? words(removing).title : '')}
+ description={t('gallery.removeHint')} confirmLabel={t('gallery.remove')}
+ onCancel={() => setRemoving(null)}
+ onConfirm={() => {
+ const skill = removing;
+ setRemoving(null);
+ if (!skill) return;
+ if (opened?.name === skill.name) onBack();
+ setSkills((list) => list.filter((k) => !(k.source === skill.source && k.name === skill.name)));
+ void sourcesApi.removeSkill(skill.name, projectId).finally(reload);
+ }} />
+ );
+
+ return (
+ <>
+ {/* one opened: its page in place of the list; the list stays, hidden, so Back finds it as it was (its view, its
+ search, where it was scrolled to) */}
+ {opened ? (
+ <SkillPage key={`${opened.source}:${opened.name}`} skill={skills.find((k) => k.source === opened.source && k.name === opened.name) ?? opened}
+ projectId={projectId} onTurn={(on) => turn(opened, on)} onInstall={(on) => install(opened, on)}
+ onRemove={() => remove(opened)} onTry={onTry}
+ onCoverChanged={(cover) => patch(opened.name, (k) => (k.source === 'mine' ? { ...k, cover: cover ?? undefined } : k))} />
+ ) : null}
+ <div className="pb-10" hidden={Boolean(opened)}>
+ <div className="sticky top-0 z-[1] flex items-center gap-1 bg-[var(--app-content-bg)] px-6 pb-4">
+ <div role="tablist" className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">
+ {chip(view === 'installed', <>{t('gallery.installed')}{count ? <span className="text-[var(--text-faint)]">{count}</span> : null}</>, () => setView('installed'), 'installed')}
+ {chip(view === 'discover', t('gallery.discover'), () => setView('discover'), 'discover')}
+ {view === 'discover' ? (
+ <>
+ <span className="mx-2 h-4 w-px shrink-0 bg-[var(--border-strong)]" />
+ {chip(kind === 'all', t('gallery.all'), () => setKind('all'), 'all')}
+ {chip(kind === 'workflow', t('gallery.workflow'), () => setKind('workflow'), 'workflow')}
+ {chip(kind === 'style', t('gallery.style'), () => setKind('style'), 'style')}
+ </>
+ ) : null}
+ <AboutSkills />
+ </div>
+ {studioHost?.skills ? (
+ <button type="button" onClick={() => studioHost?.skills?.add()}
+ className="flex h-9 shrink-0 items-center gap-1.5 rounded-[9px] border border-[var(--border)] px-3 text-[13px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={14} />{t('gallery.addSkill')}</button>
+ ) : null}
+ <label className="ml-2 flex h-9 w-[240px] shrink-0 items-center gap-2 rounded-[9px] bg-[var(--surface-2)] px-3 text-[var(--text-faint)] ring-1 ring-[var(--border)] focus-within:ring-[var(--border-strong)]">
+ <Search size={14} strokeWidth={1.75} />
+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('gallery.search')}
+ className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />
+ {query ? <button type="button" aria-label={t('project.close')} onClick={() => setQuery('')} className="hover:text-[var(--text)]"><X size={13} /></button> : null}
+ </label>
+ </div>
+
+ <div className="px-6">
+ {view === 'installed' ? (
+ <div className="mx-auto flex max-w-[880px] flex-col gap-8">
+ {groups.map((g) => (g.id === 'project' && !g.items.length) || (q && !g.items.length) ? null : (
+ <section key={g.id}>
+ <GroupHead label={g.label} hint={g.hint} />
+ {g.items.length ? g.items.map((k) => (
+ <SkillRow key={`${k.source}:${k.name}`} skill={k} onOpen={() => onOpen(k)} onTurn={(on) => turn(k, on)}
+ menu={rowMenu(k)} />
+ )) : g.id === 'mine' ? <NoSkills /> : (
+ <p className="px-2 py-3 text-[12.5px] text-[var(--text-muted)]">
+ {t('gallery.noneInstalled')}{' '}
+ <button type="button" onClick={() => setView('discover')} className="font-medium text-[var(--text)] underline-offset-2 hover:underline">{t('gallery.discover')}</button>
+ </p>
+ )}
+ </section>
+ ))}
+ {agents.groups.map((g) => {
+ const items = g.skills.filter((s) => !q || [s.name, s.description].some((w) => w.toLowerCase().includes(q)));
+ return items.length ? (
+ <section key={g.id}>
+ <GroupHead label={t('gallery.fromAgent').replace('{name}', g.name)} hint={t('gallery.agentHint')} />
+ {items.map((s) => <AgentSkillRow key={s.name} skill={s} onTurn={(on) => agents.allow(g.id, s.name, on)} />)}
+ </section>
+ ) : null;
+ })}
+ </div>
+ ) : catalog.length ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(240px,1fr))] gap-x-6 gap-y-8">
+ {catalog.map((k) => <CatalogCard key={k.name} skill={k} onOpen={() => onOpen(k)} onInstall={() => install(k, true)} />)}
+ </div>
+ ) : <p className="py-14 text-center text-[13px] text-[var(--text-muted)]">{t('gallery.noMatch')}</p>}
+ </div>
+
+ </div>
+ {confirm}
+ </>
+ );
+
+ function rowMenu(k: SkillEntry): ContextMenuEntry[] {
+ return [
+ ...(onTry ? [{ id: 'try', icon: <MessageSquarePlus size={14} />, label: t('gallery.tryNow'), disabled: Boolean(k.off), onSelect: () => onTry(k) }] : []),
+ { id: 'open', icon: <Info size={14} />, label: t('gallery.details'), onSelect: () => onOpen(k) },
+ { id: 'sep', separator: true },
+ { id: 'remove', icon: <Trash2 size={14} />, label: t(k.source === 'official' ? 'gallery.uninstall' : 'gallery.remove'), danger: true, onSelect: () => remove(k) },
+ ];
+ }
+}
+
+/** The skills each of the person's agents has of its own, for the agents that can be told which to leave out. */
+function useAgentSkills() {
+ const [groups, setGroups] = React.useState<AgentGroup[]>([]);
+ const host = studioHost?.agents;
+ const read = React.useCallback(async () => {
+ if (!host?.skills) return;
+ const agents = (await host.list().catch(() => [])).filter((a) => a.status === 'ready' && a.shown);
+ const read = await Promise.all(agents.map(async (a) => {
+ const own = await host.skills!(a.id).catch(() => null);
+ return own?.filtered && own.skills.length ? { id: a.id, name: a.name, skills: own.skills } : null;
+ }));
+ setGroups(read.filter((g): g is AgentGroup => g != null));
+ }, [host]);
+ React.useEffect(() => { void read(); }, [read]);
+ const allow = (id: HostAgentId, name: string, allowed: boolean) => {
+ setGroups((list) => list.map((g) => (g.id === id ? { ...g, skills: g.skills.map((s) => (s.name === name ? { ...s, allowed } : s)) } : g)));
+ void host?.allowSkill?.(id, name, allowed)?.catch(() => {}).finally(() => { void read(); });
+ };
+ return { groups, allow };
+}
+
+function GroupHead({ label, hint }: { label: string; hint: string }) {
+ return (
+ <div className="mb-1 flex items-baseline gap-3 px-2">
+ <h3 className="text-[14px] font-semibold text-[var(--text)]">{label}</h3>
+ <span className="truncate text-[12px] text-[var(--text-faint)]">{hint}</span>
+ </div>
+ );
+}
+
+/** An installed skill: its picture, title and what it does (or where it came from), its switch and its menu. */
+function SkillRow({ skill, onOpen, onTurn, menu }: { skill: SkillEntry; onOpen: () => void; onTurn: (on: boolean) => void; menu: ContextMenuEntry[] }) {
+ const t = useT();
+ const w = useSkillWords()(skill);
+ return (
+ <div role="button" tabIndex={0} onClick={onOpen} onKeyDown={(e) => { if (e.key === 'Enter' && e.target === e.currentTarget) onOpen(); }}
+ className="group flex cursor-pointer items-center gap-3.5 rounded-[10px] px-2 py-2 outline-none transition hover:bg-[var(--bg-hover)] focus-visible:bg-[var(--bg-hover)]">
+ <div className={`relative h-[46px] w-[82px] shrink-0 overflow-hidden rounded-[7px] ring-1 ring-[var(--border)] transition-opacity ${skill.off ? 'opacity-45' : ''}`}>
+ <SkillCover key={skill.cover ?? ''} skill={skill} title={w.title} small />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className={`truncate text-[13.5px] font-medium ${skill.off ? 'text-[var(--text-muted)]' : 'text-[var(--text)]'}`}>{w.title}</div>
+ <div className="truncate text-[12px] text-[var(--text-muted)]">{skill.off ? t('gallery.offLine') : w.summary}</div>
+ </div>
+ <span onClick={(e) => e.stopPropagation()} className="flex shrink-0 items-center gap-1">
+ <SettingsSwitch checked={!skill.off} onChange={onTurn} label={t(skill.off ? 'gallery.turnOn' : 'gallery.turnOff').replace('{name}', w.title)} />
+ <MoreMenu items={menu} />
+ </span>
+ </div>
+ );
+}
+
+/** One of an agent's own skills: its name and description, and whether OpenFilm lets it in. */
+function AgentSkillRow({ skill, onTurn }: { skill: AgentSkill; onTurn: (on: boolean) => void }) {
+ const t = useT();
+ return (
+ <div className="flex items-center gap-3.5 rounded-[10px] px-2 py-2">
+ <div className={`flex h-[46px] w-[82px] shrink-0 items-center justify-center rounded-[7px] bg-[var(--surface-2)] text-[var(--text-faint)] ring-1 ring-[var(--border)] ${skill.allowed ? '' : 'opacity-45'}`}>
+ <Blocks size={16} strokeWidth={1.6} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className={`truncate font-mono text-[13px] ${skill.allowed ? 'text-[var(--text)]' : 'text-[var(--text-muted)]'}`}>{skill.name}</div>
+ {skill.description ? <div className="truncate text-[12px] text-[var(--text-muted)]" title={skill.description}>{skill.description}</div> : null}
+ </div>
+ <span className="flex shrink-0 items-center gap-1">
+ <SettingsSwitch checked={skill.allowed} onChange={onTurn} label={t(skill.allowed ? 'gallery.turnOff' : 'gallery.turnOn').replace('{name}', skill.name)} />
+ <span className="w-[26px]" />
+ </span>
+ </div>
+ );
+}
+
+/** One of OpenFilm's in the catalog: its picture (its preview under the pointer), title, summary, and Install. */
+function CatalogCard({ skill, onOpen, onInstall }: { skill: SkillEntry; onOpen: () => void; onInstall: () => void }) {
+ const t = useT();
+ const w = useSkillWords()(skill);
+ const [hover, setHover] = React.useState(false);
+ return (
+ <div className="flex min-w-0 flex-col">
+ <button type="button" onClick={onOpen} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} className="group flex min-w-0 flex-col text-left outline-none">
+ <div className="relative aspect-video w-full overflow-hidden rounded-[12px] ring-1 ring-[var(--border)] transition group-hover:ring-[var(--border-strong)] group-focus-visible:ring-2 group-focus-visible:ring-[var(--text-muted)]">
+ <SkillCover key={skill.cover ?? ''} skill={skill} title={w.title} playing={hover} />
+ </div>
+ </button>
+ <div className="mt-3 flex min-w-0 items-start gap-3">
+ <button type="button" tabIndex={-1} onClick={onOpen} className="min-w-0 flex-1 text-left">
+ <div className="truncate text-[14.5px] font-semibold tracking-[-0.005em] text-[var(--text)]">{w.title}</div>
+ {w.summary ? <div className="mt-1 line-clamp-2 text-[12.5px] leading-[18px] text-[var(--text-muted)]">{w.summary}</div> : null}
+ </button>
+ {installedOf(skill) ? (
+ <span className="flex h-8 shrink-0 items-center gap-1 px-1 text-[12.5px] text-[var(--text-faint)]"><Check size={13} />{t('gallery.installedOne')}</span>
+ ) : (
+ <button type="button" onClick={onInstall}
+ className="h-8 shrink-0 rounded-[8px] border border-[var(--border)] px-3 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)]">{t('gallery.install')}</button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** A "…" that opens its menu under it. */
+function MoreMenu({ items }: { items: ContextMenuEntry[] }) {
+ const t = useT();
+ const [anchor, setAnchor] = React.useState<{ x: number; y: number; top: number } | null>(null);
+ const button = React.useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button ref={button} type="button" aria-label={t('gallery.more')} aria-expanded={anchor != null} aria-haspopup="menu"
+ onClick={(e) => {
+ e.stopPropagation();
+ const box = e.currentTarget.getBoundingClientRect();
+ setAnchor((cur) => (cur ? null : { x: box.right, y: box.bottom + 4, top: box.top - 4 }));
+ }}
+ className="flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-md text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
+ <MoreHorizontal size={15} />
+ </button>
+ {anchor ? <ContextMenu x={anchor.x} y={anchor.y} flipTo={anchor.top} align="end" trigger={button} onClose={() => setAnchor(null)} items={items} /> : null}
+ </>
+ );
+}
+
+/**
+ * A skill on its own, in place of the list: its preview (or picture) large on the left; on the right its title and
+ * switch, kind and version, where it came from, who it is for and what it does, and at the bottom installing it or
+ * Try now, then uninstalling it (an official one) or moving it to the trash (the person's own, a project's).
+ */
+function SkillPage({ skill, projectId, onTurn, onInstall, onRemove, onTry, onCoverChanged }: {
+ skill: SkillEntry; projectId: string | null; onTurn: (on: boolean) => void; onInstall: (on: boolean) => void;
+ onRemove: () => void; onTry?: (skill: SkillEntry) => void; onCoverChanged: (cover: string | null) => void;
+}) {
+ const t = useT();
+ const lang = useLanguage();
+ const words = useSkillWords()(skill);
+ const details = inLanguage(skill.shown?.details, lang);
+ const installed = installedOf(skill);
+ const group = skill.source === 'official' ? (skill.kind === 'style' ? 'gallery.style' : 'gallery.workflow') : skill.source === 'mine' ? 'gallery.mine' : 'gallery.project';
+ const source = skill.repository ?? (skill.origin?.from === 'link' ? skill.origin.address : undefined);
+ const [busy, setBusy] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+ const coverInput = React.useRef<HTMLInputElement>(null);
+ const changeCover = async (file: File | null) => {
+ setBusy(true);
+ setError(null);
+ try {
+ let cover: string | null = null;
+ if (file) {
+ if (file.size > 5 * 1024 * 1024 || !['image/png', 'image/jpeg', 'image/webp'].includes(file.type)) throw new Error(t('gallery.coverInvalid'));
+ cover = await new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result));
+ reader.onerror = () => reject(new Error(t('gallery.coverInvalid')));
+ reader.readAsDataURL(file);
+ });
+ const image = new Image();
+ image.src = cover;
+ await image.decode().catch(() => { throw new Error(t('gallery.coverInvalid')); });
+ }
+ onCoverChanged(await sourcesApi.setSkillCover(skill.name, cover, projectId));
+ } catch (e) { setError(e instanceof Error ? e.message : String(e)); }
+ finally { setBusy(false); }
+ };
+ return (
+ <div className="grid h-full min-h-0 grid-cols-[minmax(0,1.65fr)_minmax(320px,1fr)] border-t border-[var(--border)]">
+ <div className="flex min-h-0 flex-col items-center justify-center gap-4 bg-[color-mix(in_srgb,var(--bg)_55%,transparent)] p-8">
+ <div className="relative aspect-video w-full overflow-hidden rounded-[12px] bg-black ring-1 ring-[var(--border)]">
+ {skill.preview ? <video src={skill.preview} poster={skill.cover} autoPlay muted loop controls playsInline className="absolute inset-0 h-full w-full object-contain" />
+ : <SkillCover key={skill.cover ?? ''} skill={skill} title={words.title} big />}
+ </div>
+ {skill.source === 'mine' ? <div className="flex flex-wrap items-center justify-center gap-3 text-[12px] text-[var(--text-muted)]">
+ <button type="button" disabled={busy} onClick={() => coverInput.current?.click()} className="h-9 rounded-[9px] px-3 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40">{t(skill.cover ? 'gallery.changeCover' : 'gallery.chooseCover')}</button>
+ <input ref={coverInput} type="file" accept="image/png,image/jpeg,image/webp" aria-label={t(skill.cover ? 'gallery.changeCover' : 'gallery.chooseCover')} disabled={busy} hidden
+ onChange={(e) => { const file = e.target.files?.[0]; e.target.value = ''; if (file) void changeCover(file); }} />
+ {skill.cover ? <button type="button" disabled={busy} onClick={() => void changeCover(null)} className="h-9 rounded-[9px] px-3 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40">{t('gallery.removeCover')}</button> : null}
+ {busy ? <span role="status">{t('gallery.coverSaving')}</span> : null}
+ </div> : null}
+ {error ? <p role="alert" className="text-[12px] text-[var(--warn)]">{error}</p> : null}
+ </div>
+ <div className="flex min-h-0 flex-col border-l border-[var(--border)]">
+ <div className="min-h-0 flex-1 overflow-y-auto px-7 pt-7">
+ <div className="flex items-start gap-3">
+ <h2 className="min-w-0 flex-1 text-[22px] font-semibold leading-tight tracking-[-0.015em] text-[var(--text)]">{words.title}</h2>
+ {installed ? <SettingsSwitch checked={!skill.off} onChange={onTurn} label={t(skill.off ? 'gallery.turnOn' : 'gallery.turnOff').replace('{name}', words.title)} /> : null}
+ </div>
+ {skill.off ? <p className="mt-2 text-[12.5px] text-[var(--text-muted)]">{t('gallery.skillOff')}</p> : null}
+ <div className="mt-2.5 flex items-center gap-2 text-[12px] text-[var(--text-muted)]">
+ <span>{t(group)}</span>
+ {skill.version ? <span className="rounded-[5px] border border-[var(--border)] px-1.5 py-[1px] font-mono text-[10.5px] text-[var(--text-dim)]">v{skill.version}</span> : null}
+ {/* its source: OpenFilm's repository, or the address one of the person's came from */}
+ {source ? (
+ <a href={source} target="_blank" rel="noreferrer" title={source} aria-label={t('gallery.viewSource')}
+ className="flex h-6 w-6 items-center justify-center rounded-[6px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"><Github size={14} strokeWidth={1.75} /></a>
+ ) : null}
+ </div>
+ <Origin skill={skill} />
+ {words.summary ? <p className="mt-5 text-[14px] leading-[22px] text-[var(--text)]">{words.summary}</p> : null}
+ {details ? details.split('\n').map((line) => <p key={line} className="mt-3 text-[13.5px] leading-[22px] text-[var(--text-muted)]">{line}</p>) : null}
+ </div>
+ <div className="shrink-0 px-7 pb-7 pt-4">
+ {!installed ? (
+ <button type="button" onClick={() => onInstall(true)}
+ className="flex h-11 w-full items-center justify-center gap-1.5 rounded-[10px] bg-[var(--text)] text-[14px] font-medium text-[var(--bg)] transition hover:opacity-90"><Plus size={15} />{t('gallery.install')}</button>
+ ) : onTry ? (
+ <button type="button" onClick={() => onTry(skill)} disabled={skill.off} title={skill.off ? t('gallery.tryOff') : undefined}
+ className="flex h-11 w-full items-center justify-center gap-1.5 rounded-[10px] bg-[var(--text)] text-[14px] font-medium text-[var(--bg)] transition hover:opacity-90 disabled:opacity-40"><MessageSquarePlus size={15} />{t('gallery.tryNow')}</button>
+ ) : null}
+ {installed ? (
+ <button type="button" onClick={onRemove}
+ className="mt-2 flex h-10 w-full items-center justify-center gap-1.5 rounded-[10px] text-[13px] text-[var(--text-muted)] transition hover:bg-[color-mix(in_srgb,var(--err)_12%,transparent)] hover:text-[var(--err)]">
+ <Trash2 size={14} />{t(skill.source === 'official' ? 'gallery.uninstall' : 'gallery.remove')}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** What skills are for, behind the (i). */
+function AboutSkills() {
+ const t = useT();
+ const [open, setOpen] = React.useState(false);
+ return (
+ <span className="relative ml-1 flex shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
+ <button type="button" aria-label={t('gallery.aboutSkills')} aria-expanded={open} onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}
+ className="flex h-8 w-8 items-center justify-center rounded-[8px] text-[var(--text-faint)] transition hover:text-[var(--text)]">
+ <Info size={15} strokeWidth={1.75} />
+ </button>
+ {open ? (
+ <span role="tooltip" className="fixed z-[10060] mt-9 w-[400px] whitespace-pre-line rounded-[10px] border border-[var(--border-strong)] bg-[var(--dock-pane)] px-4 py-3.5 text-[12.5px] leading-[20px] text-[var(--text-muted)] shadow-[0_12px_32px_rgba(0,0,0,0.35)]">
+ {t('gallery.skillKinds')}
+ </span>
+ ) : null}
+ </span>
+ );
+}
+
+/** None of the person's skills yet: what theirs are for, and how to get one. */
+function NoSkills() {
+ const t = useT();
+ return (
+ <div className="mt-1 flex items-center gap-4 rounded-[12px] border border-dashed border-[var(--border-strong)] px-5 py-4">
+ <Sparkles size={18} strokeWidth={1.5} className="shrink-0 text-[var(--text-faint)]" />
+ <p className="min-w-0 flex-1 text-[12.5px] leading-[19px] text-[var(--text-muted)]">{t('gallery.noSkills')}</p>
+ {studioHost?.skills ? (
+ <button type="button" onClick={() => studioHost?.skills?.add()}
+ className="flex h-8 shrink-0 items-center gap-1.5 rounded-[8px] border border-[var(--border)] px-3 text-[12.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)]"><Plus size={13} />{t('gallery.addSkill')}</button>
+ ) : null}
+ </div>
+ );
+}
+
+/** Where one of the person's skills came from, as a short line: GitHub · owner/repo, a folder's name, or made here. */
+function Origin({ skill }: { skill: SkillEntry }) {
+ const t = useT();
+ const o = skill.origin;
+ if (!o) return null;
+ let icon = <Wand2 size={12} />, text = t('gallery.made');
+ if (o.from === 'link') {
+ icon = <GitBranch size={12} />;
+ try { const u = new URL(o.address); text = `${u.hostname.replace(/^www\./, '').replace(/\.com$/, '').replace(/^github$/, 'GitHub').replace(/^gitlab$/, 'GitLab')} · ${u.pathname.split('/').filter(Boolean).slice(0, 2).join('/')}`; } catch { text = o.address; }
+ } else if (o.from === 'folder') {
+ icon = <Folder size={12} />;
+ text = `${t('gallery.fromFolder')} · ${o.address.split(/[\\/]/).filter(Boolean).pop() ?? o.address}`;
+ }
+ return <div title={o.from === 'made' ? undefined : o.address} className="mt-2 flex min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--text-faint)]">{icon}<span className="truncate">{text}</span></div>;
+}
+
+const ICONS: Record<string, LucideIcon> = {
+ copy: Copy, scissors: Scissors, monitor: MonitorPlay, shapes: Shapes, pip: PictureInPicture2, pen: PenLine, film: Film,
+ music: Music, presentation: Presentation, layers: Layers,
+};
+/** each mark its own color, so the covers tell apart at a glance */
+const HUES: Record<string, number> = { copy: 212, scissors: 18, monitor: 188, shapes: 262, pip: 328, pen: 42, film: 28, music: 286, presentation: 228, layers: 6 };
+
+/** A skill's picture: its cover, else its preview's first frame, else a tile of its mark in its own color. */
+function SkillCover({ skill, title, small = false, big = false, playing = false }: { skill: SkillEntry; title: string; small?: boolean; big?: boolean; playing?: boolean }) {
+ const [failed, setFailed] = React.useState(false);
+ if (skill.cover && !failed) {
+ return (
+ <>
+ <img src={skill.cover} alt="" loading="lazy" draggable={false} onError={() => setFailed(true)} className="absolute inset-0 h-full w-full object-cover" />
+ {playing && skill.preview ? <video src={skill.preview} autoPlay muted loop playsInline className="absolute inset-0 h-full w-full object-cover" /> : null}
+ </>
+ );
+ }
+ const Mark = ICONS[skill.icon ?? ''] ?? Sparkles;
+ const hue = HUES[skill.icon ?? ''] ?? 220;
+ return (
+ <div aria-label={title} className="absolute inset-0 flex flex-col items-center justify-center gap-3 px-6 text-center"
+ style={{ background: `radial-gradient(110% 90% at 25% 0%, hsl(${hue} 70% 55% / 0.22), transparent 62%), radial-gradient(90% 80% at 100% 100%, hsl(${hue} 70% 50% / 0.12), transparent 60%), var(--surface-2)` }}>
+ <span className={`flex items-center justify-center ${small ? 'h-7 w-7 rounded-[8px]' : big ? 'h-16 w-16 rounded-[14px]' : 'h-14 w-14 rounded-[14px]'}`}
+ style={{ background: `hsl(${hue} 70% 55% / 0.16)`, color: `hsl(${hue} 80% 72%)`, boxShadow: `0 0 0 1px hsl(${hue} 70% 60% / 0.28)` }}>
+ <Mark size={small ? 14 : big ? 28 : 24} strokeWidth={1.6} />
+ </span>
+ {/* a card has its title under it; the page's big picture carries it */}
+ {big ? <span className="line-clamp-2 text-[22px] font-semibold tracking-[-0.01em] text-[var(--text)]">{title}</span> : null}
+ </div>
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
index 16657e1..fb01df2 100644
--- a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
+++ b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
@@ -139,7 +139,7 @@ function SourceBar({ time, duration, playing, onToggle, onSeek, disabled, marks,
onPlayPause={onToggle}
onFullscreen={onFullscreen}
/* the part marked with I and O, while there is one (`,` and `.` put it on the film) */
- frame={marked ? <span data-source-range="" className="shrink-0 text-[11px] tabular-nums text-[var(--accent)]">{marked}</span> : undefined}
+ extra={marked ? <span data-source-range="" className="shrink-0 text-[11px] tabular-nums text-[var(--accent)]">{marked}</span> : undefined}
/>
</div>
);
@@ -287,6 +287,7 @@ const CLOCK_PINGS = 5;
* the editor's origin it could reach the editor), with Studio's bridge in it, driven by messages. Still, it is told the
* moment to draw (seek t → frame(t)); playing, the line it plays on, and it draws its own frames from it, on the
* project's frame grid (studio/server/bridge.js `play`): no message a frame, so a busy editor does not hold the picture.
+ * A page clip of Saved plays as the film had it: laid out at its clip's size, with the changes made in it.
*/
function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
const t = useT();
@@ -295,6 +296,9 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
const boxRef = React.useRef<HTMLDivElement>(null);
const seq = React.useRef(0);
const surface = sources.pageSurface?.(file) ?? null;
+ /* what a page without a size of its own is laid out at: its clip's size, else 1920 × 1080 as a page on its own */
+ const laid = file.bundle?.size ?? { w: 1920, h: 1080 };
+ const overrides = file.bundle?.overrides ?? null;
const origin = React.useMemo(() => {
try { return surface ? new URL(surface, window.location.href).origin : null; } catch { return null; }
}, [surface]);
@@ -348,7 +352,8 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
}
if (data.type !== 'ready') return;
const num = (v: unknown, fallback: number) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback);
- setSize({ w: num(data.width, 1920), h: num(data.height, 1080), duration: num(data.duration, 0) });
+ setSize({ w: num(data.width, laid.w), h: num(data.height, laid.h), duration: num(data.duration, 0) });
+ if (overrides) post({ type: 'overrides', list: overrides });
/* where its clock is: first by where each clock started, then by pings */
clock.current = Number(data.origin) > 0 ? { offset: performance.timeOrigin - Number(data.origin), rtt: Infinity } : null;
for (let i = 0; i < CLOCK_PINGS; i++) setTimeout(() => post({ type: 'clock', ping: performance.now() }), 40 * i);
@@ -356,7 +361,7 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
};
window.addEventListener('message', onMessage);
return () => window.removeEventListener('message', onMessage);
- }, [draw, origin, post, tellPlay]);
+ }, [draw, origin, post, tellPlay, laid.w, laid.h, overrides]);
React.useEffect(() => {
const box = boxRef.current;
@@ -439,7 +444,7 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
src={surface}
title={file.name}
className="pointer-events-none absolute left-0 top-0 origin-top-left border-0"
- style={{ width: size?.w ?? 1920, height: size?.h ?? 1080, transform: `scale(${scale})` }}
+ style={{ width: size?.w ?? laid.w, height: size?.h ?? laid.h, transform: `scale(${scale})` }}
/>
</div>
)}
diff --git a/packages/openfilm/studio/ui/src/components/TemplateSection.tsx b/packages/openfilm/studio/ui/src/components/TemplateSection.tsx
deleted file mode 100644
index 9fa0730..0000000
--- a/packages/openfilm/studio/ui/src/components/TemplateSection.tsx
+++ /dev/null
@@ -1,329 +0,0 @@
-/**
- * The inspector's Template section for a page clip: the page's custom properties, its words and its pictures, changed
- * here without opening the page, as a motion graphics template is filled in (lib/template-controls). Each field paints
- * first and writes when let go, as every inspector field does; each change is an override of the clip, and a field
- * changed from the page's own value can go back to it. A custom property that names a font gets the font picker; a
- * picture is replaced by a picture of the project (picked from a menu, or dropped from the media pane) or one from this
- * computer.
- */
-import * as React from 'react';
-import { HardDriveUpload, ImageIcon, RotateCcw } from 'lucide-react';
-
-import { useT } from '@/i18n';
-import type { FilmOverride } from '@/lib/film';
-import {
- ROOT, changedImage, changedText, changedVar, fieldOf, isFontVar, labelOf, relativeTo, valueOf, withImage, withText, withVar,
- type TemplateControls, type TemplateImage, type VarField,
-} from '@/lib/template-controls';
-import { joinFontFamily, splitFontFamily } from '@/lib/font-styles';
-import { readResourceDragData, RESOURCE_DRAG_TYPE } from '@/lib/resource-drag';
-import { ColorField, FIELD, INPUT, NumField, Section, SectionAction } from './inspector-fields';
-import { FontFamilyPicker } from './FontFamilyPicker';
-import { ContextMenu, type ContextMenuEntry } from './ContextMenu';
-
-type T = ReturnType<typeof useT>;
-
-/** What the section needs of the clip: its controls as the page has them, its overrides, and the picture. */
-export interface TemplateHost {
- /** Null when the clip is not on the picture now (the page is read where it is drawn). */
- read: () => Promise<TemplateControls | null>;
- overrides: () => readonly FilmOverride[] | undefined;
- /** Paints a change without writing it; null takes it back. */
- preview: (target: { at: string; n?: number }, patch: { style?: Record<string, string>; text?: string } | null) => void;
- /** The page's file, by its place in the project: a picture put in is named from its folder. */
- page: string;
- /** The project's pictures, by their place in the project. */
- pictures: () => Array<{ path: string; name: string }>;
- /** One from this computer, brought into the project: its place there (null: none picked). */
- pickPicture?: () => Promise<string | null>;
-}
-
-const PICTURE = /\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i;
-
-/* a page clip off the picture is read again now and then: the playhead may come to it */
-const OFF_PICTURE_EVERY_MS = 1500;
-
-const isNamedColor = (v: string) => typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('color', v);
-
-export function TemplateSection({ host, commit }: {
- host: TemplateHost;
- /** Writes the clip's next overrides (null: none left). */
- commit: (next: FilmOverride[] | null) => void;
-}) {
- const t = useT();
- const [controls, setControls] = React.useState<TemplateControls | null | undefined>(undefined);
- const overrides = host.overrides();
- const kept = JSON.stringify(overrides ?? []);
- React.useEffect(() => {
- let live = true;
- let timer = 0;
- const read = () => {
- void host.read().catch(() => null).then((next) => {
- if (!live) return;
- setControls((prev) => (JSON.stringify(prev) === JSON.stringify(next) ? prev : next));
- if (!next) timer = window.setTimeout(read, OFF_PICTURE_EVERY_MS);
- });
- };
- /* the picture shows a written change a moment after it is kept */
- timer = window.setTimeout(read, 120);
- return () => { live = false; window.clearTimeout(timer); };
- }, [host, kept]);
-
- if (controls === undefined) return null;
- if (controls && !controls.vars.length && !controls.texts.length && !controls.images?.length) return null;
- const setVar = (name: string, value: string | null) => commit(withVar(overrides, name, value));
- const setText = (at: string, n: number | undefined, value: string | null) => commit(withText(overrides, at, n, value));
- const setImage = (image: TemplateImage, path: string | null) => commit(withImage(overrides, image, path == null ? null : relativeTo(host.page, path)));
-
- return (
- <Section id="template" title={t('inspector.template')}>
- {!controls ? (
- <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.templateOffPicture')}</p>
- ) : (
- <>
- {controls.vars.map(({ name, value }) => (
- <Line key={name} label={labelOf(name)} title={name} changed={changedVar(overrides, name) != null} onReset={() => setVar(name, null)} t={t}>
- {isFontVar(name, value) ? (
- <FontInput
- label={labelOf(name)}
- value={value}
- onCommit={(next) => setVar(name, next)}
- onPreview={(next) => host.preview({ at: ROOT }, next == null ? null : { style: { [name]: next } })}
- />
- ) : (
- <VarInput
- name={name}
- field={fieldOf(value, isNamedColor)}
- onCommit={(next) => setVar(name, next)}
- onPreview={(next) => host.preview({ at: ROOT }, next == null ? null : { style: { [name]: next } })}
- />
- )}
- </Line>
- ))}
- {controls.texts.map(({ at, n, label, value }, i) => (
- <Line
- key={`${at}#${n ?? 0}`}
- label={label || `${t('inspector.templateText')} ${i + 1}`}
- title={n ? `${at} (${n})` : at}
- changed={changedText(overrides, at, n) != null}
- onReset={() => setText(at, n, null)}
- t={t}
- wide
- >
- <WordsInput
- value={value}
- label={label || `${t('inspector.templateText')} ${i + 1}`}
- onCommit={(next) => setText(at, n, next)}
- onPreview={(next) => host.preview({ at, ...(n ? { n } : {}) }, next == null ? null : { text: next })}
- />
- </Line>
- ))}
- {(controls.images ?? []).map((image, i) => {
- const label = image.label || `${t('inspector.templatePicture')} ${i + 1}`;
- const put = changedImage(overrides, image);
- /* what it draws now: the picture put in, read from the page's folder, else the page's own */
- const src = put != null && controls.page ? new URL(put, controls.page).href : image.src;
- return (
- <Line key={`${image.at}#${image.n ?? 0}`} label={label} title={image.n ? `${image.at} (${image.n})` : image.at} changed={put != null} onReset={() => setImage(image, null)} t={t}>
- <PictureInput src={src} host={host} label={label} onPick={(path) => setImage(image, path)} t={t} />
- </Line>
- );
- })}
- </>
- )}
- </Section>
- );
-}
-
-/** A picture: its thumbnail and name; clicked, the project's pictures and one from this computer; a picture dropped. */
-function PictureInput({ src, host, label, onPick, t }: {
- src: string; host: TemplateHost; label: string; onPick: (path: string) => void; t: T;
-}) {
- const [menu, setMenu] = React.useState<{ x: number; y: number } | null>(null);
- const [over, setOver] = React.useState(false);
- const name = decodeURIComponent(src.split(/[?#]/)[0]!.split('/').pop() ?? '');
- const entries = (): ContextMenuEntry[] => {
- const list = host.pictures().slice(0, 40);
- const pick = host.pickPicture;
- return [
- ...list.map((f) => ({ id: `pic:${f.path}`, label: f.name, onSelect: () => onPick(f.path) })),
- ...(pick ? [
- ...(list.length ? [{ id: 'pic-sep', separator: true as const }] : []),
- { id: 'pic-computer', label: t('inspector.templatePictureComputer'), icon: <HardDriveUpload size={14} />, onSelect: () => { void pick().then((path) => { if (path && PICTURE.test(path)) onPick(path); }); } },
- ] : []),
- ];
- };
- return (
- <>
- <button
- type="button"
- aria-label={`${label}: ${t('inspector.templatePictureReplace')}`}
- title={t('inspector.templatePictureReplace')}
- onClick={(e) => { const r = e.currentTarget.getBoundingClientRect(); setMenu({ x: r.left, y: r.bottom + 4 }); }}
- onDragOver={(e) => { if (e.dataTransfer.types.includes(RESOURCE_DRAG_TYPE)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; setOver(true); } }}
- onDragLeave={() => setOver(false)}
- onDrop={(e) => {
- setOver(false);
- const file = readResourceDragData(e.dataTransfer);
- if (!file || file.saved || !PICTURE.test(file.path)) return;
- e.preventDefault();
- onPick(file.path);
- }}
- className={`${FIELD} gap-1.5 px-1 text-left ${over ? 'ring-[1.5px] ring-[var(--accent)]' : ''}`}
- >
- <span className="flex h-[18px] w-[28px] shrink-0 items-center justify-center overflow-hidden rounded-[3px] bg-[var(--bg-hover)]">
- {src ? <img src={src} alt="" className="h-full w-full object-cover" draggable={false} /> : <ImageIcon size={12} />}
- </span>
- <span className="min-w-0 flex-1 truncate text-[11px] text-[var(--text)]">{name}</span>
- </button>
- {menu ? <ContextMenu x={menu.x} y={menu.y} items={entries()} onClose={() => setMenu(null)} /> : null}
- </>
- );
-}
-
-/** A custom property that names a font: the font picker over its first family, the fallbacks after it kept. */
-function FontInput({ label, value, onCommit, onPreview }: {
- label: string; value: string; onCommit: (value: string) => void; onPreview: (value: string | null) => void;
-}) {
- const [family, rest] = splitFontFamily(value);
- return (
- <FontFamilyPicker
- label={label}
- value={family}
- sample=""
- onPreview={(next) => onPreview(joinFontFamily(next, rest))}
- onRevert={() => onPreview(null)}
- onCommit={(next) => onCommit(joinFontFamily(next, rest))}
- className={FIELD}
- />
- );
-}
-
-/** A control: its name on the left (words above their box), its field, and going back to the page's own value. */
-function Line({ label, title, changed, onReset, wide = false, t, children }: {
- label: string; title: string; changed: boolean; onReset: () => void; wide?: boolean; t: T; children: React.ReactNode;
-}) {
- const reset = changed ? (
- <SectionAction label={t('inspector.templateReset')} onClick={onReset}><RotateCcw size={11} /></SectionAction>
- ) : <span className="w-5" />;
- const name = (
- <span className="min-w-0 truncate text-[11px] text-[var(--text-muted)]" title={title}>
- {changed ? <span aria-hidden className="mr-1 inline-block h-1.5 w-1.5 rounded-full bg-[var(--accent)] align-middle" /> : null}
- {label}
- </span>
- );
- if (wide) {
- return (
- <div className="flex flex-col gap-1">
- <div className="flex h-5 items-center justify-between gap-2">{name}{reset}</div>
- {children}
- </div>
- );
- }
- return (
- <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1.5fr)_20px] items-center gap-1.5">
- {name}
- <div className="min-w-0">{children}</div>
- {reset}
- </div>
- );
-}
-
-/** A custom property's field by its kind: a color, a number with its unit, or words. */
-function VarInput({ name, field, onCommit, onPreview }: {
- name: string;
- field: VarField;
- onCommit: (value: string) => void;
- onPreview: (value: string | null) => void;
-}) {
- const label = labelOf(name);
- if (field.kind === 'color') {
- return <ColorField label={label} value={field.value} onCommit={onCommit} onPreview={onPreview} />;
- }
- if (field.kind === 'number') {
- const step = Number.isInteger(field.value) && Math.abs(field.value) >= 2 ? 1 : 0.1;
- return (
- <NumField
- label={label}
- bare
- value={field.value}
- step={step}
- {...(field.unit ? { unit: field.unit } : {})}
- onCommit={(n) => onCommit(valueOf({ ...field, value: n }))}
- onPreview={(n) => onPreview(valueOf({ ...field, value: n }))}
- onRevert={() => onPreview(null)}
- />
- );
- }
- return (
- <TypedInput
- label={label}
- value={field.value}
- onCommit={(v) => onCommit(valueOf({ ...field, value: v }))}
- />
- );
-}
-
-/** One line typed and kept when left or on Enter; Esc gives up. */
-function TypedInput({ label, value, onCommit }: { label: string; value: string; onCommit: (value: string) => void }) {
- const [raw, setRaw] = React.useState(value);
- React.useEffect(() => setRaw(value), [value]);
- const cancelled = React.useRef(false);
- return (
- <div className={FIELD}>
- <input
- aria-label={label}
- value={raw}
- spellCheck={false}
- onChange={(e) => setRaw(e.target.value)}
- onBlur={() => {
- if (cancelled.current) { cancelled.current = false; return; }
- if (raw.trim() && raw !== value) onCommit(raw);
- else setRaw(value);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' && !e.nativeEvent.isComposing) (e.target as HTMLInputElement).blur();
- if (e.key === 'Escape') { cancelled.current = true; setRaw(value); (e.target as HTMLInputElement).blur(); }
- }}
- className={`${INPUT} pl-2`}
- />
- </div>
- );
-}
-
-/** A layer's words: the picture follows as they are typed, kept when left or on Enter (Shift+Enter: a new line). */
-function WordsInput({ label, value, onCommit, onPreview }: {
- label: string;
- value: string;
- onCommit: (value: string) => void;
- onPreview: (value: string | null) => void;
-}) {
- const [raw, setRaw] = React.useState(value);
- const typing = React.useRef(false);
- React.useEffect(() => { if (!typing.current) setRaw(value); }, [value]);
- const cancelled = React.useRef(false);
- return (
- <textarea
- aria-label={label}
- value={raw}
- rows={Math.min(4, Math.max(1, raw.split('\n').length))}
- onChange={(e) => { typing.current = true; setRaw(e.target.value); onPreview(e.target.value); }}
- onBlur={() => {
- typing.current = false;
- if (cancelled.current) { cancelled.current = false; return; }
- if (raw !== value) onCommit(raw);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); (e.target as HTMLTextAreaElement).blur(); }
- if (e.key === 'Escape') {
- cancelled.current = true;
- typing.current = false;
- setRaw(value);
- onPreview(null);
- (e.target as HTMLTextAreaElement).blur();
- }
- }}
- className="w-full resize-none rounded-[5px] bg-[var(--fill-tsp)] px-2 py-1 text-[11.5px] leading-[1.5] text-[var(--text)] outline-none ring-1 ring-inset ring-transparent transition hover:ring-[var(--border)] focus:bg-[var(--bg)] focus:ring-[1.5px] focus:ring-[var(--accent)]"
- />
- );
-}
diff --git a/packages/openfilm/studio/ui/src/components/ViewerBar.tsx b/packages/openfilm/studio/ui/src/components/ViewerBar.tsx
index 3858af7..e4a1f8c 100644
--- a/packages/openfilm/studio/ui/src/components/ViewerBar.tsx
+++ b/packages/openfilm/studio/ui/src/components/ViewerBar.tsx
@@ -1,13 +1,14 @@
/**
- * The transport bar under the picture: the timecode on the left, play in the center, the frame picker and full screen
- * on the right. As tall (32px) as the pane bar above the picture, so the picture sits evenly between two equal edges.
+ * The transport bar under the picture: the timecode on the left, play in the center, the playback settings and full
+ * screen on the right. As tall (32px) as the pane bar above the picture, so the picture sits evenly between two equal edges.
*/
-import React from 'react';
-import { Expand, Pause, Play, Repeat } from 'lucide-react';
+import type React from 'react';
+import { Expand, Pause, Play } from 'lucide-react';
import { useT } from '@/i18n';
import { formatTimecode, useTimecodeFps } from '@/lib/timecode';
import { PANE_BTN, PANE_ICON } from './dock-pane-bar';
import { LiveText, type PlaybackClock } from './LiveTime';
+import { PlaybackMenu, type PlaybackSettings } from './PlaybackMenu';
import { Tooltip } from './Tooltip';
import { useKeyHint } from '@/lib/keymap-store';
@@ -20,9 +21,9 @@ export function ViewerBar({
totalMs,
playing,
onPlayPause,
- frame,
onFullscreen,
- loop,
+ playback,
+ extra,
}: {
timeMs: number;
/** The time on the clock (playing, scrubbing): only the timecode follows it, the rest of the bar stays still. */
@@ -30,12 +31,12 @@ export function ViewerBar({
totalMs: number;
playing: boolean;
onPlayPause: () => void;
- /** The FramePicker, when the film can be framed (not read-only). */
- frame?: React.ReactNode;
/** Full screen; the button is disabled while the film has no length. */
onFullscreen?: () => void;
- /** Loop playback (⇧L): of the range marked, else of the whole film. Without it there is no loop button. */
- loop?: { on: boolean; ranged: boolean; onToggle: () => void } | null;
+ /** Loop, subtitles and speed (see PlaybackMenu). Without it there is no settings button. */
+ playback?: PlaybackSettings | null;
+ /** Shown before the buttons on the right (the source viewer: the part marked). */
+ extra?: React.ReactNode;
}) {
const t = useT();
const keyHint = useKeyHint();
@@ -70,23 +71,14 @@ export function ViewerBar({
</button>
</Tooltip>
<span className="flex items-center justify-end gap-1">
- {loop ? (
- <Tooltip label={t(loop.ranged ? 'viewer.loopRange' : 'viewer.loopFilm')} shortcut={keyHint('loop')}>
- <button
- type="button"
- onClick={loop.onToggle}
- onMouseDown={(e) => e.preventDefault()}
- disabled={!playable}
- aria-pressed={loop.on}
- aria-label={t(loop.ranged ? 'viewer.loopRange' : 'viewer.loopFilm')}
- data-viewer-loop={loop.on ? '1' : '0'}
- className={`${VIEW_BTN} disabled:pointer-events-none disabled:opacity-30 ${loop.on ? '!text-[var(--accent)]' : ''}`}
- >
- <Repeat size={PANE_ICON} />
- </button>
- </Tooltip>
+ {extra}
+ {playback ? (
+ <PlaybackMenu
+ settings={playback}
+ disabled={!playable}
+ className={`${VIEW_BTN} !w-auto min-w-[22px] gap-1 px-1 disabled:pointer-events-none disabled:opacity-30`}
+ />
) : null}
- {frame}
{onFullscreen ? (
<Tooltip label={t('viewer.fullscreen')}>
<button
diff --git a/packages/openfilm/studio/ui/src/components/inspector-look.tsx b/packages/openfilm/studio/ui/src/components/inspector-look.tsx
index 622ff73..a9895bf 100644
--- a/packages/openfilm/studio/ui/src/components/inspector-look.tsx
+++ b/packages/openfilm/studio/ui/src/components/inspector-look.tsx
@@ -615,7 +615,7 @@ function usePreviewed(look: Look) {
return { before, remember, restore, preview, commit };
}
-export function AppearanceSection({ look, t, children, radius = false }: { look: Look; t: T; children?: React.ReactNode; radius?: boolean }) {
+export function AppearanceSection({ look, t, children, radius = false, aside }: { look: Look; t: T; children?: React.ReactNode; radius?: boolean; aside?: React.ReactNode }) {
const previewed = usePreviewed(look);
const opacity = look.common((read) => {
const v = Number(read('opacity') ?? 1);
@@ -628,7 +628,7 @@ export function AppearanceSection({ look, t, children, radius = false }: { look:
return { opacity: n >= 100 ? null : String(Math.round(n * 10) / 1000) };
};
return (
- <Section id="appearance" title={t('inspector.appearance')}>
+ <Section id="appearance" title={t('inspector.appearance')} {...(aside ? { aside } : {})}>
<SliderField
label={t('inspector.opacity')}
value={opacity}
diff --git a/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx
index 8dbd5f0..82dfa53 100644
--- a/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/ShortcutsSection.tsx
@@ -261,7 +261,7 @@ export function ShortcutsSection() {
<SettingsSelect<SchemeId> label={t('settings.shortcuts.scheme')} value={draft.scheme} options={schemeOptions} onChange={chooseScheme} width={200} />
</div>
{notice ? <p role="status" className="mb-3 text-[13.5px] leading-relaxed text-[var(--text-muted)]">{notice}</p> : null}
- <div className="@container rounded-[12px] bg-[var(--fill-tsp)] px-5 py-3">
+ <div className="@container">
<div className="grid grid-cols-1 gap-x-8 @xl:grid-cols-2">
{columns(actionRows).map((rows, i) => (
<div key={i} className={`flex flex-col ${i === 1 ? '@xl:border-l @xl:border-[var(--border)] @xl:pl-8' : ''}`}>{rows.map(renderRow)}</div>
diff --git a/packages/openfilm/studio/ui/src/components/stage-menu.tsx b/packages/openfilm/studio/ui/src/components/stage-menu.tsx
index 6a66d37..5d0bdcb 100644
--- a/packages/openfilm/studio/ui/src/components/stage-menu.tsx
+++ b/packages/openfilm/studio/ui/src/components/stage-menu.tsx
@@ -6,9 +6,10 @@
*
* Layer changes are overrides (the editor writes film.html); the clip's actions are the editor's, passed in.
*/
+import type * as React from 'react';
import {
- BringToFront, ClipboardPaste, Copy as CopyIcon, CopyPlus, CornerLeftUp, Download, Eye, EyeOff, Layers, Lock,
- RotateCcw, Scissors, SendToBack, Trash2, Type as TypeIcon, Unlock,
+ BringToFront, ClipboardPaste, Copy as CopyIcon, CopyPlus, CornerLeftUp, Download, Eye, EyeOff, HardDriveUpload, ImageIcon,
+ ImageUp, Layers, Lock, RotateCcw, Scissors, SendToBack, Trash2, Type as TypeIcon, Unlock,
} from 'lucide-react';
import type { ContextMenuEntry } from '@/components/ContextMenu';
@@ -83,6 +84,46 @@ export interface StageMenuActions {
notify?(message: string): void;
/** The whole clip's actions; without them a clip's menu is empty. */
clip?: StageClipActions;
+ /** Another file in a picture's place; without it a picture has no Replace. */
+ picture?: StagePictureActions;
+}
+
+/** Replacing the picture a layer draws (an <img>, a box painted with one image): written as the clip's override. */
+export interface StagePictureActions {
+ /** The project's pictures, by their place in the project, each with where its thumbnail is read from. */
+ pictures(): Array<{ path: string; name: string; url?: string }>;
+ /** One from this computer, brought into the project: its place there (null: none picked). */
+ pickFromComputer?(): Promise<string | null>;
+ /** `path` (in the project) drawn in the layer's place; null: its own again. */
+ put(element: StageElement, path: string | null): void;
+}
+
+/** A picture's thumbnail in a menu, where its icon goes: wider than an icon, so the pictures read apart. */
+export function pictureThumb(url: string | undefined): React.ReactNode {
+ return url
+ ? <img src={url} alt="" draggable={false} loading="lazy" className="h-[14px] w-[22px] shrink-0 rounded-[2px] object-cover" />
+ : <ImageIcon size={14} />;
+}
+
+/** The pictures a layer's Replace offers: the project's, one from this computer, and its own again once replaced. */
+export function replacePictureEntries(el: StageElement, actions: StagePictureActions, t: (path: string) => string): ContextMenuEntry[] {
+ const picture = el.picture;
+ if (!picture) return [];
+ const list = actions.pictures().slice(0, 40);
+ const pick = actions.pickFromComputer;
+ const out: ContextMenuEntry[] = list.map((f) => ({ id: `picture:${f.path}`, label: f.name, icon: pictureThumb(f.url), onSelect: () => actions.put(el, f.path) }));
+ if (pick) {
+ if (out.length) out.push({ id: 'picture-sep', separator: true });
+ out.push({
+ id: 'picture-computer', label: t('inspector.templatePictureComputer'), icon: <HardDriveUpload size={14} />,
+ onSelect: () => { void pick().then((path) => { if (path) actions.put(el, path); }); },
+ });
+ }
+ if (picture.changed) {
+ out.push({ id: 'picture-own-sep', separator: true });
+ out.push({ id: 'picture-own', label: t('stageMenu.pictureOwn'), icon: <RotateCcw size={14} />, onSelect: () => actions.put(el, null) });
+ }
+ return out;
}
type T = (path: string) => string;
@@ -172,6 +213,9 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stag
if (ctx.editText) {
m.push({ id: 'edit-text', label: t('stageMenu.editText'), icon: <TypeIcon size={14} />, shortcut: '↵', disabled: locked, hint: t('stageMenu.lockedHint'), onSelect: ctx.editText });
}
+ if (el.picture && actions.picture) {
+ m.push({ id: 'replace-picture', label: t('stageMenu.replacePicture'), icon: <ImageUp size={14} />, disabled: locked, hint: t('stageMenu.lockedHint'), submenu: replacePictureEntries(el, actions.picture, t) });
+ }
m.sep();
/* restacking writes z-index overrides where the layer meets what it overlaps (stage.js arrange), in one write; the
page stays as written. When there is nothing to do, it says why instead of doing nothing silently */
diff --git a/packages/openfilm/studio/ui/src/editor/player.test.ts b/packages/openfilm/studio/ui/src/editor/player.test.ts
index 511656d..1ca19a1 100644
--- a/packages/openfilm/studio/ui/src/editor/player.test.ts
+++ b/packages/openfilm/studio/ui/src/editor/player.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { anchorTime, EASE_STEP, easedLead, fadeSteps, JUMP, soundsDue } from './player.ts';
+import { anchorTime, EASE_STEP, easedLead, fadeSteps, JUMP, soundsDue, soundSpeed, stretchedSpan } from './player.ts';
test('a sound\'s fades as ramps: where it is now, then each corner after it', () => {
/* 4 s long, 1 s in, 2 s out */
@@ -39,3 +39,17 @@ test('sounds are started a few seconds ahead of the film, each once, solo leavin
/* a sound of a faster clip lasts less on the film */
assert.deepEqual(soundsDue([{ ...s(0, 4, 'e'), speed: 2 }], 2.5, 3, new Set(), null), []);
});
+
+test('a sound at another speed is played from a copy stretched to it: where to start in it and for how long', () => {
+ /* a clip at 2× of the file's seconds 10–20, at film second 4: 5 film seconds long */
+ const s = { src: 'a.wav', at: 4, from: 10, to: 20, volume: 1, speed: 2 };
+ assert.equal(soundSpeed(2, 1), 2);
+ assert.equal(soundSpeed(2, 0.75), 1.5);
+ assert.equal(soundSpeed(1, 1 / 3), 0.3333);
+ /* from its start, the viewer at 1×: the 2× copy from 10 / 2, all 10 file seconds as 5 */
+ assert.deepEqual(stretchedSpan(s, 4, 2), { offset: 5, duration: 5 });
+ /* the film started 1 s into it, the viewer at 1.5× (the copy at 3×): file second 12, 8 file seconds left */
+ assert.deepEqual(stretchedSpan(s, 5, 3), { offset: 4, duration: 8 / 3 });
+ /* at 1× of a 1× clip it is the file itself */
+ assert.deepEqual(stretchedSpan({ ...s, speed: 1, to: 15 }, 6, 1), { offset: 12, duration: 3 });
+});
diff --git a/packages/openfilm/studio/ui/src/editor/player.ts b/packages/openfilm/studio/ui/src/editor/player.ts
index a597af0..5d5ab04 100644
--- a/packages/openfilm/studio/ui/src/editor/player.ts
+++ b/packages/openfilm/studio/ui/src/editor/player.ts
@@ -10,8 +10,10 @@
*
* `sounds` is the timeline's own list (src/timeline.mjs `__filmSounds`): each sound clip's sound and each video's own,
* already placed and cut to its clip, with its volume and speed. Each file's sound is fetched small (`?film-sound`, see
- * studio/server/pages.mjs): a video's is a copy of its sound alone, never the whole video. A sound not here yet (its
- * copy still being made) is silent until it is, then joins where the film is. Sounds are started a few seconds ahead of
+ * studio/server/pages.mjs): a video's is a copy of its sound alone, never the whole video. A sound played faster or
+ * slower (its clip's speed by the viewer's) is fetched stretched to that speed with its pitch kept (`&speed=`, the
+ * atempo filter exports use) and played as it is: never sped up as a tape is, which would be heard higher. A sound not
+ * here yet (its copy still being made) is silent until it is, then joins where the film is. Sounds are started a few seconds ahead of
* the film, not all at once: a film of hundreds of sounds starts as quickly as one of a few.
*
* Every sound goes through one mix, metered (`levels`: the audio meters read it while the film plays, nothing reads it
@@ -82,6 +84,26 @@ export type MixSamples = [Float32Array<ArrayBuffer>, Float32Array<ArrayBuffer>];
/** A sound's length on the film (s). */
const lengthOf = (s: Sound) => (s.to - s.from) / s.speed;
+/** The speed a sound's file is played at: its clip's by the viewer's, to 4 places (the copy made for it, see soundOf). */
+export function soundSpeed(speed: number, rate: number): number {
+ return Math.round(speed * rate * 1e4) / 1e4;
+}
+
+/**
+ * Where to start in a copy of the sound stretched to `speed` (soundSpeed) and how long to play it (its own seconds),
+ * for the sound heard from film second `startFilm` to its end: the copy's second is `speed` of the file's.
+ */
+export function stretchedSpan(s: Sound, startFilm: number, speed: number): { offset: number; duration: number } {
+ const end = s.at + lengthOf(s);
+ return {
+ offset: (s.from + (startFilm - s.at) * s.speed) / speed,
+ duration: ((end - startFilm) * s.speed) / speed,
+ };
+}
+
+/** A decoded sound's place: its file, at a speed. */
+const bufferKey = (src: string, speed: number) => `${speed}|${src}`;
+
/** How far film time `t` is from a sound: 0 while it plays, else until it starts; one already past after all those. */
function awayFrom(s: Sound, t: number) {
const end = s.at + lengthOf(s);
@@ -103,7 +125,8 @@ export function soundsDue(sounds: readonly Sound[], from: number, until: number,
export class Player {
private ctx: AudioContext | null = null;
- /** each file's decoded sound, and the version of the file it was decoded from (undefined: not known then) */
+ /** each file's decoded sound at a speed (bufferKey), and the version of the file it was decoded from (undefined: not
+ known then) */
private buffers = new Map<string, { version: number | undefined; buffer: Promise<AudioBuffer | null> }>();
private origin = '';
private versionOf: (src: string) => number | undefined = () => undefined;
@@ -157,15 +180,22 @@ export class Player {
if (this.fetchSounds() && this.playing) this.restart();
}
- /** Fetches the sounds not decoded yet, or decoded from an older version; says whether there were any. */
+ /**
+ * Fetches the sounds not decoded yet at the speed they play at now, or decoded from an older version; says whether
+ * there were any. Those at no speed played now or at 1× are let go (a long sound decoded is tens of MB).
+ */
private fetchSounds(): boolean {
if (!this.origin) return false;
const ctx = this.context();
let fetched = false;
const t = this.time();
+ const kept = new Set(this.sounds.flatMap((s) => [bufferKey(s.src, soundSpeed(s.speed, this.rate)), bufferKey(s.src, soundSpeed(s.speed, 1))]));
+ for (const key of [...this.buffers.keys()]) if (!kept.has(key)) this.buffers.delete(key);
for (const s of [...this.sounds].sort((a, b) => awayFrom(a, t) - awayFrom(b, t))) {
const version = this.versionOf(s.src);
- const had = this.buffers.get(s.src);
+ const speed = soundSpeed(s.speed, this.rate);
+ const key = bufferKey(s.src, speed);
+ const had = this.buffers.get(key);
/* a version not known on one side is taken as the same: the file was not seen to change */
if (had && (had.version === version || had.version === undefined || version === undefined)) {
had.version ??= version;
@@ -173,9 +203,10 @@ export class Player {
}
const url = new URL(s.src, this.origin);
url.searchParams.set('film-sound', '1');
+ if (speed !== 1) url.searchParams.set('speed', String(speed));
/* past the browser's cache, which keeps the old file under the same address */
if (version !== undefined) url.searchParams.set('v', String(version));
- this.buffers.set(s.src, { version, buffer: this.slot(s.src)
+ this.buffers.set(key, { version, buffer: this.slot(s.src)
.then((done) => fetch(url)
/* 204: there is no sound in it */
.then((r) => (r.status === 204 ? null : r.ok ? r.arrayBuffer() : Promise.reject(new Error(String(r.status)))))
@@ -284,10 +315,13 @@ export class Player {
if (this.master) this.master.gain.value = muted ? 0 : this.volume;
}
- /** Play faster or slower (pitch moves with it); playing goes on from where it is. */
+ /** Play faster or slower, the pitch kept (each sound at that speed is fetched); playing goes on from where it is. */
setRate(rate: number) {
const t = this.time();
- this.rate = Math.max(0.25, Math.min(2, rate));
+ const next = Math.max(0.25, Math.min(2, rate));
+ if (next === this.rate) return;
+ this.rate = next;
+ this.fetchSounds();
if (this.playing) this.restart(t);
}
@@ -382,7 +416,7 @@ export class Player {
for (const i of soundsDue(this.sounds, now, now + AHEAD * this.rate, this.started, this.heard)) {
this.started.add(i);
const s = this.sounds[i];
- void this.buffers.get(s.src)?.buffer.then((buffer) => {
+ void this.buffers.get(bufferKey(s.src, soundSpeed(s.speed, this.rate)))?.buffer.then((buffer) => {
if (!buffer || !this.playing || this.heardLine !== heard) return;
this.schedule(buffer, s, heard);
});
@@ -401,10 +435,10 @@ export class Player {
const startFilm = Math.max(s.at, heard.t + Math.max(0, soonest - heard.at) * r);
if (startFilm >= end) return;
const when = Math.max(soonest, ctxAt(startFilm));
- const offset = s.from + (startFilm - s.at) * s.speed;
+ /* the buffer is the sound stretched to this speed already: played as it is, its pitch is the file's */
+ const span = stretchedSpan(s, startFilm, soundSpeed(s.speed, r));
const source = ctx.createBufferSource();
source.buffer = buffer;
- source.playbackRate.value = s.speed * r;
const gain = ctx.createGain();
if (s.fade) {
/* its fades as ramps on the audio clock, sample-accurate: from where it starts, each corner at its own moment */
@@ -413,7 +447,7 @@ export class Player {
for (const [u, g] of rest) gain.gain.linearRampToValueAtTime(s.volume * g, Math.max(when, ctxAt(s.at + u)));
} else gain.gain.value = s.volume;
source.connect(gain).connect(this.mix ?? ctx.destination);
- source.start(when, offset, (end - startFilm) * s.speed);
+ source.start(when, span.offset, span.duration);
source.onended = () => {
const i = this.playingNodes.indexOf(source);
if (i >= 0) this.playingNodes.splice(i, 1);
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 1519c26..7d3e08d 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -47,7 +47,29 @@ export const en = {
partsHint: 'Click a part, or drag across the strip for a stretch.',
viewSource: 'View on GitHub',
back: 'Back',
- useSkill: 'Use this skill',
+ installed: 'Installed',
+ discover: 'Discover',
+ mineHint: 'In your Skills folder',
+ fromOpenFilm: 'From OpenFilm',
+ officialHint: 'Installed from Discover',
+ projectHint: 'Kept with this film',
+ noneInstalled: 'None installed yet. Find OpenFilm\'s in',
+ fromAgent: 'From {name}',
+ agentHint: 'Your agent\'s own. Off until you turn one on.',
+ removeTitle: 'Move “{name}” to the trash?',
+ removeHint: 'Agents stop using it. You can put it back from the trash.',
+ remove: 'Move to trash',
+ tryNow: 'Try now',
+ tryOff: 'Turn it on to try it',
+ details: 'Details',
+ uninstall: 'Uninstall',
+ offLine: 'Off. Agents won\'t use it.',
+ installedOne: 'Installed',
+ install: 'Install',
+ more: 'More',
+ turnOn: 'Turn on {name}',
+ turnOff: 'Turn off {name}',
+ skillOff: 'Off. Agents aren\'t offered it until you turn it on again.',
mine: 'Yours',
project: 'This project',
addSkill: 'Add a skill',
@@ -162,6 +184,12 @@ export const en = {
deleteFolderHintOne: 'Deletes the folder and moves the project inside it to the Trash, where you can take it back.',
deleteFolderHintEmpty: 'Deletes the folder. There are no projects in it.',
renameTaken: '“{name}” is taken: there is already a folder with that name. Choose another.',
+ moveToTitle: 'Move “{name}”',
+ moveHint: 'Choose where it goes.',
+ move: 'Move',
+ moveTo: 'Move to…',
+ hereNow: 'Here now',
+ newFolderName: 'New folder name',
moveToFolder: 'Move to folder',
changeCover: 'Change cover…',
restoreCover: 'Use the automatic cover',
@@ -169,7 +197,6 @@ export const en = {
setAsCover: 'Set as project cover',
coverSet: 'Cover set',
coverFailed: 'Couldn’t use that as the cover.',
- noFolder: 'No folder',
folderEmpty: 'This folder is empty',
creating: 'Creating project',
opening: 'Opening project',
@@ -699,6 +726,8 @@ export const en = {
hideAll: "Hide",
showAll: "Show",
editText: "Edit text",
+ replacePicture: 'Replace picture',
+ pictureOwn: 'Back to its own picture',
duplicate: "Duplicate",
front: "Bring to front",
back: "Send to back",
@@ -776,7 +805,7 @@ export const en = {
failed: 'Could not add to Saved: {error}',
emptyTitle: 'Nothing in Saved yet',
emptyBody: 'Saved is yours in every project. Upload files of any kind or drop them here, or right-click a clip on the timeline and choose Add to Saved.',
- template: 'Template',
+ component: 'Component',
kind_clip: 'Clip',
kind_group: 'Clips',
kind_page: 'Page',
@@ -884,8 +913,10 @@ export const en = {
frameCustomH: 'Height',
frameCustomApply: 'Use this ratio',
frameCustomRange: 'From 1:4 to 4:1',
- canvas: 'Aspect ratio',
fullscreen: 'Full screen',
+ playback: 'Playback',
+ speed: 'Speed',
+ subtitles: 'Subtitles',
},
inspector: {
fades: 'Fades',
@@ -968,11 +999,23 @@ export const en = {
sound: 'Sound',
gainDb: 'Volume',
pageChanges: 'Changes inside the page',
- template: 'Template',
- templateOffPicture: 'Move the playhead onto this clip to see what its page lets you change.',
- templateText: 'Text',
- templateReset: 'Back to the page’s own',
- templatePicture: 'Picture',
+ templateOffPicture: 'Move the playhead onto this clip to see its values.',
+ props: 'Properties',
+ propsEmpty: 'Select a layer of this page and click ◇ beside its words, its picture or its appearance to make it a property.',
+ propsAdd: 'Add a property from the page’s variables',
+ propsNoVars: 'This page has no variables',
+ propsResetAll: 'Reset all',
+ propReset: 'Back to the default',
+ propRename: 'Rename',
+ propRenameHint: 'Double-click to rename; right-click for more',
+ propRemove: 'Remove property',
+ propText: 'Text',
+ propShowName: 'Show {name}',
+ propBound: 'Property “{name}”: click to remove it',
+ propMakeText: 'Make the words a property',
+ propMakePicture: 'Make the picture a property',
+ propMakeShow: 'Make showing it a property',
+ picture: 'Picture',
templatePictureReplace: 'Replace picture',
templatePictureComputer: 'From this computer…',
pageChangeLost: 'No longer in the page',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index f3e824e..706c610 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -46,7 +46,29 @@ export const es: Words = {
partsHint: 'Haz clic en una parte o arrastra sobre la barra para un tramo.',
viewSource: 'Ver en GitHub',
back: 'Atrás',
- useSkill: 'Usar esta skill',
+ installed: 'Instaladas',
+ discover: 'Descubrir',
+ mineHint: 'En tu carpeta Skills',
+ fromOpenFilm: 'De OpenFilm',
+ officialHint: 'Instaladas desde Descubrir',
+ projectHint: 'Guardadas con esta película',
+ noneInstalled: 'Aún no hay ninguna. Encuentra las de OpenFilm en',
+ fromAgent: 'De {name}',
+ agentHint: 'Las de tu agente. Desactivadas hasta que actives una.',
+ removeTitle: '¿Mover «{name}» a la papelera?',
+ removeHint: 'Los agentes dejarán de usarla. Puedes recuperarla de la papelera.',
+ remove: 'Mover a la papelera',
+ tryNow: 'Probar',
+ tryOff: 'Actívala para probarla',
+ details: 'Detalles',
+ uninstall: 'Desinstalar',
+ offLine: 'Desactivada. Los agentes no la usan.',
+ installedOne: 'Instalada',
+ install: 'Instalar',
+ more: 'Más',
+ turnOn: 'Activar {name}',
+ turnOff: 'Desactivar {name}',
+ skillOff: 'Desactivada. Ningún agente la usará hasta que la vuelvas a activar.',
mine: 'Tuya',
project: 'Este proyecto',
addSkill: 'Añadir una skill',
@@ -161,6 +183,12 @@ export const es: Words = {
deleteFolderHintOne: 'Elimina la carpeta y mueve el proyecto que contiene a la Papelera, desde donde puedes recuperarlo.',
deleteFolderHintEmpty: 'Elimina la carpeta. No contiene ningún proyecto.',
renameTaken: '“{name}” ya está en uso: ya hay una carpeta con ese nombre. Elige otro.',
+ moveToTitle: 'Mover «{name}»',
+ moveHint: 'Elige adónde va.',
+ move: 'Mover',
+ moveTo: 'Mover a…',
+ hereNow: 'Aquí ahora',
+ newFolderName: 'Nombre de la carpeta nueva',
moveToFolder: 'Mover a carpeta',
changeCover: 'Cambiar portada…',
restoreCover: 'Usar la portada automática',
@@ -168,7 +196,6 @@ export const es: Words = {
setAsCover: 'Usar como portada del proyecto',
coverSet: 'Portada establecida',
coverFailed: 'No se pudo usar como portada.',
- noFolder: 'Sin carpeta',
folderEmpty: 'Esta carpeta está vacía',
creating: 'Creando proyecto',
opening: 'Abriendo proyecto',
@@ -698,6 +725,8 @@ export const es: Words = {
hideAll: 'Ocultar',
showAll: 'Mostrar',
editText: 'Editar texto',
+ replacePicture: 'Reemplazar imagen',
+ pictureOwn: 'Volver a su imagen',
duplicate: 'Duplicar',
front: 'Traer al frente',
back: 'Enviar al fondo',
@@ -775,7 +804,7 @@ export const es: Words = {
failed: 'No se pudo añadir a Guardados: {error}',
emptyTitle: 'Aún no hay nada en Guardados',
emptyBody: 'Guardados es tuyo en todos los proyectos. Sube o suelta aquí archivos de cualquier tipo, o haz clic derecho en un clip de la línea de tiempo y elige Añadir a Guardados.',
- template: 'Plantilla',
+ component: 'Componente',
kind_clip: 'Clip',
kind_group: 'Clips',
kind_page: 'Página',
@@ -883,8 +912,10 @@ export const es: Words = {
frameCustomH: 'Alto',
frameCustomApply: 'Usar esta proporción',
frameCustomRange: 'De 1:4 a 4:1',
- canvas: 'Relación de aspecto',
fullscreen: 'Pantalla completa',
+ playback: 'Reproducción',
+ speed: 'Velocidad',
+ subtitles: 'Subtítulos',
},
inspector: {
fades: 'Fundidos',
@@ -967,11 +998,23 @@ export const es: Words = {
sound: 'Sonido',
gainDb: 'Volumen',
pageChanges: 'Cambios dentro de la página',
- template: 'Plantilla',
- templateOffPicture: 'Lleva el cabezal a este clip para ver qué permite cambiar su página.',
- templateText: 'Texto',
- templateReset: 'Volver al valor de la página',
- templatePicture: 'Imagen',
+ templateOffPicture: 'Lleva el cabezal a este clip para ver sus valores.',
+ props: 'Propiedades',
+ propsEmpty: 'Selecciona una capa de esta página y pulsa ◇ junto a su texto, su imagen o su apariencia para hacerla una propiedad.',
+ propsAdd: 'Añadir una propiedad de las variables de la página',
+ propsNoVars: 'Esta página no tiene variables',
+ propsResetAll: 'Restablecer todo',
+ propReset: 'Volver al valor predeterminado',
+ propRename: 'Renombrar',
+ propRenameHint: 'Doble clic para renombrar; clic derecho para más',
+ propRemove: 'Quitar propiedad',
+ propText: 'Texto',
+ propShowName: 'Mostrar {name}',
+ propBound: 'Propiedad «{name}»: haz clic para quitarla',
+ propMakeText: 'Hacer del texto una propiedad',
+ propMakePicture: 'Hacer de la imagen una propiedad',
+ propMakeShow: 'Hacer de mostrar u ocultar una propiedad',
+ picture: 'Imagen',
templatePictureReplace: 'Reemplazar imagen',
templatePictureComputer: 'Desde este ordenador…',
pageChangeLost: 'Ya no está en la página',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 05d1e57..9fabea1 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -46,7 +46,29 @@ export const ja: Words = {
partsHint: 'パートをクリックするか、バーの上をドラッグして範囲を選びます。',
viewSource: 'GitHub で見る',
back: '戻る',
- useSkill: 'このスキルを使う',
+ installed: 'インストール済み',
+ discover: '見つける',
+ mineHint: 'あなたの Skills フォルダ',
+ fromOpenFilm: 'OpenFilm から',
+ officialHint: '「見つける」からインストール',
+ projectHint: 'この作品と一緒に保存',
+ noneInstalled: 'まだありません。OpenFilm のスキルはこちら:',
+ fromAgent: '{name} から',
+ agentHint: 'エージェント自身のもの。オンにしたものだけ使います。',
+ removeTitle: '「{name}」をゴミ箱に移動しますか?',
+ removeHint: 'エージェントは使わなくなります。ゴミ箱から戻せます。',
+ remove: 'ゴミ箱に移動',
+ tryNow: '試す',
+ tryOff: 'オンにすると試せます',
+ details: '詳細',
+ uninstall: 'アンインストール',
+ offLine: 'オフ。エージェントは使いません。',
+ installedOne: 'インストール済み',
+ install: 'インストール',
+ more: 'その他',
+ turnOn: '{name} をオンにする',
+ turnOff: '{name} をオフにする',
+ skillOff: 'オフです。オンに戻すまで、エージェントはこのスキルを使いません。',
mine: '自分の',
project: 'このプロジェクト',
addSkill: 'スキルを追加',
@@ -161,6 +183,12 @@ export const ja: Words = {
deleteFolderHintOne: 'フォルダーを削除し、中のプロジェクトをゴミ箱に移動します。ゴミ箱から元に戻せます。',
deleteFolderHintEmpty: 'フォルダーを削除します。中にプロジェクトはありません。',
renameTaken: '「{name}」は使用されています。同じ名前のフォルダーがすでにあります。別の名前を選んでください。',
+ moveToTitle: '「{name}」を移動',
+ moveHint: '移動先を選んでください。',
+ move: '移動',
+ moveTo: '移動…',
+ hereNow: '現在の場所',
+ newFolderName: '新しいフォルダ名',
moveToFolder: 'フォルダーへ移動',
changeCover: 'カバーを変更…',
restoreCover: '自動のカバーに戻す',
@@ -168,7 +196,6 @@ export const ja: Words = {
setAsCover: 'プロジェクトのカバーにする',
coverSet: 'カバーを設定しました',
coverFailed: 'カバーにできませんでした。',
- noFolder: 'フォルダーなし',
folderEmpty: 'このフォルダーは空です',
creating: 'プロジェクトを作成中',
opening: 'プロジェクトを開いています',
@@ -698,6 +725,8 @@ export const ja: Words = {
hideAll: '非表示',
showAll: '表示',
editText: 'テキストを編集',
+ replacePicture: '画像を置き換え',
+ pictureOwn: '元の画像に戻す',
duplicate: '複製',
front: '最前面へ',
back: '最背面へ',
@@ -775,7 +804,7 @@ export const ja: Words = {
failed: 'コレクションに追加できませんでした:{error}',
emptyTitle: 'コレクションはまだ空です',
emptyBody: 'コレクションはどのプロジェクトでも使えます。どんなファイルでもアップロードやドロップで追加でき、タイムラインのクリップを右クリックして「コレクションに追加」も選べます。',
- template: 'テンプレート',
+ component: 'コンポーネント',
kind_clip: 'クリップ',
kind_group: 'クリップ群',
kind_page: 'ページ',
@@ -883,8 +912,10 @@ export const ja: Words = {
frameCustomH: '高さ',
frameCustomApply: 'この比率を使う',
frameCustomRange: '1:4 から 4:1 まで',
- canvas: 'アスペクト比',
fullscreen: '全画面表示',
+ playback: '再生設定',
+ speed: '再生速度',
+ subtitles: '字幕を表示',
},
inspector: {
fades: 'フェード',
@@ -967,11 +998,23 @@ export const ja: Words = {
sound: 'サウンド',
gainDb: '音量',
pageChanges: 'ページ内の変更',
- template: 'テンプレート',
- templateOffPicture: '再生ヘッドをこのクリップに合わせると、ページで変えられる項目が表示されます。',
- templateText: 'テキスト',
- templateReset: 'ページの元の値に戻す',
- templatePicture: '画像',
+ templateOffPicture: '再生ヘッドをこのクリップに合わせると、今の値が表示されます。',
+ props: 'プロパティ',
+ propsEmpty: 'このページのレイヤーを選び、テキスト・画像・外観の横の ◇ を押すとプロパティになります。',
+ propsAdd: 'ページの変数からプロパティを追加',
+ propsNoVars: 'このページに変数はありません',
+ propsResetAll: 'すべて元に戻す',
+ propReset: 'デフォルトに戻す',
+ propRename: '名前を変更',
+ propRenameHint: 'ダブルクリックで名前を変更、右クリックでその他',
+ propRemove: 'プロパティを削除',
+ propText: 'テキスト',
+ propShowName: '{name}を表示',
+ propBound: 'プロパティ「{name}」:クリックで削除',
+ propMakeText: 'テキストをプロパティにする',
+ propMakePicture: '画像をプロパティにする',
+ propMakeShow: '表示/非表示をプロパティにする',
+ picture: '画像',
templatePictureReplace: '画像を置き換え',
templatePictureComputer: 'このコンピュータから…',
pageChangeLost: 'ページ内にもうありません',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 7e32999..e753573 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -46,7 +46,29 @@ export const ko: Words = {
partsHint: '구간을 클릭하거나 막대 위를 드래그해 범위를 고르세요.',
viewSource: 'GitHub에서 보기',
back: '뒤로',
- useSkill: '이 스킬 사용',
+ installed: '설치됨',
+ discover: '찾아보기',
+ mineHint: '내 Skills 폴더',
+ fromOpenFilm: 'OpenFilm 제공',
+ officialHint: '찾아보기에서 설치',
+ projectHint: '이 영상과 함께 저장',
+ noneInstalled: '아직 설치한 스킬이 없습니다. OpenFilm 스킬 보기:',
+ fromAgent: '{name} 제공',
+ agentHint: '에이전트 자체 스킬. 켠 것만 사용합니다.',
+ removeTitle: '「{name}」을(를) 휴지통으로 옮길까요?',
+ removeHint: '에이전트가 더 이상 쓰지 않습니다. 휴지통에서 되돌릴 수 있습니다.',
+ remove: '휴지통으로 이동',
+ tryNow: '사용해 보기',
+ tryOff: '켜야 사용해 볼 수 있습니다',
+ details: '자세히',
+ uninstall: '제거',
+ offLine: '꺼짐. 에이전트가 쓰지 않습니다.',
+ installedOne: '설치됨',
+ install: '설치',
+ more: '더 보기',
+ turnOn: '{name} 켜기',
+ turnOff: '{name} 끄기',
+ skillOff: '꺼져 있습니다. 다시 켜기 전까지 에이전트는 이 스킬을 쓰지 않습니다.',
mine: '내 스킬',
project: '이 프로젝트',
addSkill: '스킬 추가',
@@ -161,6 +183,12 @@ export const ko: Words = {
deleteFolderHintOne: '폴더를 삭제하고 안에 있는 프로젝트를 휴지통으로 옮깁니다. 휴지통에서 되살릴 수 있습니다.',
deleteFolderHintEmpty: '폴더를 삭제합니다. 폴더 안에 프로젝트가 없습니다.',
renameTaken: '“{name}”은(는) 이미 사용 중인 폴더 이름입니다. 다른 이름을 선택하세요.',
+ moveToTitle: '「{name}」 이동',
+ moveHint: '옮길 위치를 고르세요.',
+ move: '이동',
+ moveTo: '이동…',
+ hereNow: '현재 위치',
+ newFolderName: '새 폴더 이름',
moveToFolder: '폴더로 이동',
changeCover: '커버 변경…',
restoreCover: '자동 커버로 되돌리기',
@@ -168,7 +196,6 @@ export const ko: Words = {
setAsCover: '프로젝트 커버로 설정',
coverSet: '커버를 설정했습니다',
coverFailed: '커버로 사용할 수 없습니다.',
- noFolder: '폴더 없음',
folderEmpty: '이 폴더는 비어 있습니다',
creating: '프로젝트 만드는 중',
opening: '프로젝트 여는 중',
@@ -698,6 +725,8 @@ export const ko: Words = {
hideAll: '숨기기',
showAll: '표시',
editText: '텍스트 편집',
+ replacePicture: '이미지 바꾸기',
+ pictureOwn: '원래 이미지로',
duplicate: '복제',
front: '맨 앞으로 가져오기',
back: '맨 뒤로 보내기',
@@ -775,7 +804,7 @@ export const ko: Words = {
failed: '보관함에 추가하지 못했습니다: {error}',
emptyTitle: '보관함이 아직 비어 있습니다',
emptyBody: '보관함은 모든 프로젝트에서 쓸 수 있습니다. 어떤 파일이든 업로드하거나 끌어다 놓고, 타임라인의 클립을 오른쪽 클릭해 보관함에 추가할 수도 있습니다.',
- template: '템플릿',
+ component: '컴포넌트',
kind_clip: '클립',
kind_group: '클립 묶음',
kind_page: '페이지',
@@ -883,8 +912,10 @@ export const ko: Words = {
frameCustomH: '높이',
frameCustomApply: '이 비율 사용',
frameCustomRange: '1:4부터 4:1까지',
- canvas: '화면 비율',
fullscreen: '전체 화면',
+ playback: '재생 설정',
+ speed: '재생 속도',
+ subtitles: '자막 표시',
},
inspector: {
fades: '페이드',
@@ -967,11 +998,23 @@ export const ko: Words = {
sound: '사운드',
gainDb: '볼륨',
pageChanges: '페이지 안의 변경 사항',
- template: '템플릿',
- templateOffPicture: '재생 헤드를 이 클립 위로 옮기면 페이지에서 바꿀 수 있는 항목이 보입니다.',
- templateText: '텍스트',
- templateReset: '페이지 원래 값으로',
- templatePicture: '이미지',
+ templateOffPicture: '재생 헤드를 이 클립 위로 옮기면 지금 값이 보입니다.',
+ props: '속성',
+ propsEmpty: '이 페이지에서 레이어를 선택하고 텍스트, 이미지, 모양 옆의 ◇를 누르면 속성이 됩니다.',
+ propsAdd: '페이지 변수에서 속성 추가',
+ propsNoVars: '이 페이지에는 변수가 없습니다',
+ propsResetAll: '모두 되돌리기',
+ propReset: '기본값으로',
+ propRename: '이름 바꾸기',
+ propRenameHint: '더블클릭으로 이름 바꾸기, 오른쪽 클릭으로 더 보기',
+ propRemove: '속성 제거',
+ propText: '텍스트',
+ propShowName: '{name} 표시',
+ propBound: '속성 “{name}”: 클릭하면 제거',
+ propMakeText: '텍스트를 속성으로',
+ propMakePicture: '이미지를 속성으로',
+ propMakeShow: '표시/숨기기를 속성으로',
+ picture: '이미지',
templatePictureReplace: '이미지 바꾸기',
templatePictureComputer: '이 컴퓨터에서…',
pageChangeLost: '더 이상 페이지에 없음',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index b4e0c00..13be802 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -47,7 +47,29 @@ export const zhCN: Words = {
partsHint: '点一段,或者在条上拖出一段。',
viewSource: '在 GitHub 上查看',
back: '返回',
- useSkill: '使用这个 skill',
+ installed: '已安装',
+ discover: '发现',
+ mineHint: '在你的 Skills 文件夹里',
+ fromOpenFilm: '来自 OpenFilm',
+ officialHint: '从“发现”安装',
+ projectHint: '随这部片子保存',
+ noneInstalled: '还没有安装。去这里找 OpenFilm 的:',
+ fromAgent: '来自 {name}',
+ agentHint: '智能体自己的,开启后才会用。',
+ removeTitle: '把「{name}」移到废纸篓?',
+ removeHint: '智能体不会再用它。需要时可以从废纸篓放回来。',
+ remove: '移到废纸篓',
+ tryNow: '试一试',
+ tryOff: '开启后才能试',
+ details: '详情',
+ uninstall: '卸载',
+ offLine: '已关闭,智能体不会用它。',
+ installedOne: '已安装',
+ install: '安装',
+ more: '更多',
+ turnOn: '开启 {name}',
+ turnOff: '关闭 {name}',
+ skillOff: '已关闭。重新开启前,智能体不会用到它。',
mine: '我的',
project: '本项目',
addSkill: '添加 skill',
@@ -162,6 +184,12 @@ export const zhCN: Words = {
deleteFolderHintOne: '删除此文件夹,并将其中的项目移到废纸篓,你可以从那里找回。',
deleteFolderHintEmpty: '删除此文件夹。其中没有项目。',
renameTaken: '“{name}”已被占用:已有同名文件夹。请换一个名称。',
+ moveToTitle: '移动「{name}」',
+ moveHint: '选择要放到哪里。',
+ move: '移动',
+ moveTo: '移到…',
+ hereNow: '当前位置',
+ newFolderName: '新文件夹名称',
moveToFolder: '移到文件夹',
changeCover: '更换封面…',
restoreCover: '恢复自动封面',
@@ -169,7 +197,6 @@ export const zhCN: Words = {
setAsCover: '设为项目封面',
coverSet: '已设为封面',
coverFailed: '无法用它做封面。',
- noFolder: '无文件夹',
folderEmpty: '此文件夹为空',
creating: '正在创建项目',
opening: '正在打开项目',
@@ -699,6 +726,8 @@ export const zhCN: Words = {
hideAll: '隐藏',
showAll: '显示',
editText: '编辑文字',
+ replacePicture: '替换图片',
+ pictureOwn: '换回原图',
duplicate: '创建副本',
front: '置于顶层',
back: '置于底层',
@@ -776,7 +805,7 @@ export const zhCN: Words = {
failed: '收藏失败:{error}',
emptyTitle: '收藏里还没有东西',
emptyBody: '收藏在所有项目里都能用。可以上传或拖入任何文件,也可以在时间轴的片段上右键选「收藏」。',
- template: '模板',
+ component: '组件',
kind_clip: '片段',
kind_group: '片段组',
kind_page: '页面',
@@ -884,8 +913,10 @@ export const zhCN: Words = {
frameCustomH: '高',
frameCustomApply: '使用这个比例',
frameCustomRange: '范围 1:4 到 4:1',
- canvas: '画面比例',
fullscreen: '全屏',
+ playback: '播放设置',
+ speed: '播放速度',
+ subtitles: '显示字幕',
},
inspector: {
fades: '淡入淡出',
@@ -968,11 +999,23 @@ export const zhCN: Words = {
sound: '声音',
gainDb: '音量',
pageChanges: '页面内的修改',
- template: '模板参数',
- templateOffPicture: '把播放头移到这个片段上,就能看到它的页面可以改哪些参数。',
- templateText: '文字',
- templateReset: '恢复页面原值',
- templatePicture: '图片',
+ templateOffPicture: '把播放头移到这个片段上,就能看到它现在的值。',
+ props: '属性',
+ propsEmpty: '在这个页面里选中一层,点它的文字、图片或外观旁的 ◇,就能把它设为属性。',
+ propsAdd: '从页面的变量添加属性',
+ propsNoVars: '这个页面没有变量',
+ propsResetAll: '全部恢复',
+ propReset: '恢复默认',
+ propRename: '重命名',
+ propRenameHint: '双击重命名,右键查看更多',
+ propRemove: '移除属性',
+ propText: '文字',
+ propShowName: '显示{name}',
+ propBound: '属性“{name}”:点击移除',
+ propMakeText: '把文字设为属性',
+ propMakePicture: '把图片设为属性',
+ propMakeShow: '把显示/隐藏设为属性',
+ picture: '图片',
templatePictureReplace: '替换图片',
templatePictureComputer: '从这台电脑选择…',
pageChangeLost: '已不在页面中',
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
index 5ae45e2..308a551 100644
--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { canvasFor, canvasSide, fitToCanvas } from './canvas-fit.ts';
+import { canvasFor, canvasSide, fitToCanvas, originalShape } from './canvas-fit.ts';
const wide = { w: 1920, h: 1080 }, tall = { w: 1080, h: 1440 }, cinema = { w: 2538, h: 1080 };
const boxOf = (out: ReturnType<typeof fitToCanvas>, id: string) => out.find((c) => c.id === id)?.box;
@@ -58,3 +58,12 @@ test('a canvas side typed or dragged stays in reason: 16 to 8192 px, even, at mo
assert.equal(canvasSide(9000, 4000), 8192);
assert.equal(canvasSide(2, 40), 16);
});
+
+test('Original is the first picture\'s shape, current when the stage has it', () => {
+ assert.deepEqual(originalShape(wide, { w: 3840, h: 2160 }), { frame: '3840:2160', current: true });
+ assert.deepEqual(originalShape(tall, { w: 1080, h: 1920 }), { frame: '1080:1920', current: false });
+ assert.deepEqual(canvasFor(wide, originalShape(wide, { w: 1080, h: 1920 }).frame!), { w: 1080, h: 1920 });
+ /* nothing to fit to, or a shape past 1:4 / 4:1: no Original */
+ assert.deepEqual(originalShape(wide, null), { frame: null, current: false });
+ assert.deepEqual(originalShape(wide, { w: 5000, h: 1000 }), { frame: null, current: false });
+});
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
index 357dba9..82a3863 100644
--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
@@ -11,7 +11,7 @@
* given the old canvas as its `size`, so it is scaled as a video is rather than laid out again in the new shape.
*/
import { pictureRect } from '../../../../src/film-doc.mjs';
-import { frameRatioOf, type FilmFrameId } from './film-frame.ts';
+import { customFilmFrame, frameRatioOf, type FilmFrameId } from './film-frame.ts';
import type { FilmBox, FilmSrcKind } from './film.ts';
type Size = { w: number; h: number };
@@ -86,3 +86,15 @@ export function fitToCanvas(clips: readonly CanvasClip[], from: Size, to: Size):
}
return out;
}
+
+/** Whether the stage has this ratio: its width within 2 px of it (a size made from a ratio is rounded to even px). */
+export const shaped = (stage: Size, ratio: number) => Math.abs(stage.w - stage.h * ratio) <= 2;
+
+/**
+ * The canvas's "Original" shape: the first picture's own (`original`), when there is one and it is between 1:4 and
+ * 4:1; and whether the stage has it now.
+ */
+export function originalShape(stage: Size, original: Size | null): { frame: FilmFrameId | null; current: boolean } {
+ const frame = original ? customFilmFrame(original.w, original.h) : null;
+ return { frame, current: Boolean(frame && original && shaped(stage, original.w / original.h)) };
+}
diff --git a/packages/openfilm/studio/ui/src/lib/component-props.test.ts b/packages/openfilm/studio/ui/src/lib/component-props.test.ts
new file mode 100644
index 0000000..35f83cc
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/component-props.test.ts
@@ -0,0 +1,56 @@
+import { test as it } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ freshName, propOf, propValue, propsAttr, propsOf, renamedProp, withProp, withPropValue, withPropsReset, withoutProp,
+ type ComponentProp,
+} from './component-props.ts';
+
+const title: ComponentProp = { name: 'Title', type: 'text', at: '#title' };
+const photo: ComponentProp = { name: 'Photo', type: 'image', at: '.picture > img', kind: 'img' };
+const logo: ComponentProp = { name: 'Show logo', type: 'boolean', at: '#logo' };
+const accent: ComponentProp = { name: 'Accent', type: 'var', var: '--accent' };
+
+it('a clip\'s properties are read from its data-props, anything not one left out', () => {
+ const attrs = { 'data-props': JSON.stringify([title, photo, { name: 'Bad', type: 'image', at: '#x' }, { name: 'Title', type: 'text', at: '#again' }, logo, accent, 'no']) };
+ assert.deepEqual(propsOf({ attrs }), [title, photo, logo, accent]);
+ assert.deepEqual(propsOf({ attrs: { 'data-props': '{oops' } }), []);
+ assert.deepEqual(propsOf({}), []);
+ assert.equal(propsAttr([]), null, 'none left: the attribute goes');
+ assert.deepEqual(JSON.parse(propsAttr([title])!), [title]);
+});
+
+it('a property is made of one thing once: made again it is replaced, its name kept unique; renamed and removed by name', () => {
+ let list = withProp([], title);
+ list = withProp(list, { name: 'Title', type: 'text', at: '#subtitle' });
+ assert.deepEqual(list.map((p) => p.name), ['Title', 'Title 2']);
+ list = withProp(list, { name: 'Headline', type: 'text', at: '#title' });
+ assert.deepEqual(list.map((p) => p.name), ['Title 2', 'Headline'], 'the same layer\'s words: one property');
+ assert.equal(propOf(list, 'text', { at: '#title' })?.name, 'Headline');
+ assert.equal(propOf(list, 'boolean', { at: '#title' }), null, 'its showing is another property');
+ assert.deepEqual(renamedProp(list, 'Headline', 'Title 2').map((p) => p.name), ['Title 2', 'Headline'], 'a name taken: as it was');
+ assert.deepEqual(renamedProp(list, 'Headline', ' Name ').map((p) => p.name), ['Title 2', 'Name']);
+ assert.deepEqual(withoutProp(list, 'Title 2').map((p) => p.name), ['Headline']);
+ assert.equal(freshName([title], ''), 'Property');
+});
+
+it('each property is filled in as an override, and back at its default leaves none', () => {
+ let o = withPropValue(undefined, title, 'Hello') ?? undefined;
+ o = withPropValue(o, photo, '../assets/new.png') ?? undefined;
+ o = withPropValue(o, logo, false) ?? undefined;
+ o = withPropValue(o, accent, '#00ff00') ?? undefined;
+ assert.deepEqual(o, [
+ { at: '#title', text: 'Hello' },
+ { at: '.picture > img', style: { content: 'url("../assets/new.png")' } },
+ { at: '#logo', style: { visibility: 'hidden' } },
+ { at: ':root', style: { '--accent': '#00ff00' } },
+ ]);
+ assert.equal(propValue(o, title), 'Hello');
+ assert.equal(propValue(o, photo), '../assets/new.png');
+ assert.equal(propValue(o, logo), false);
+ assert.equal(propValue(o, accent), '#00ff00');
+ assert.equal(propValue(withPropValue(o, logo, true) ?? undefined, logo), null, 'shown again: its default');
+ /* a move made on the picture is not a property: Reset all leaves it */
+ const moved = [...o!, { at: '#other', t: [10, 0] as [number, number] }];
+ assert.deepEqual(withPropsReset(moved, [title, photo, logo, accent]), [{ at: '#other', t: [10, 0] }]);
+ assert.equal(withPropsReset(o, [title, photo, logo, accent]), null);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/component-props.ts b/packages/openfilm/studio/ui/src/lib/component-props.ts
new file mode 100644
index 0000000..8e71c49
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/component-props.ts
@@ -0,0 +1,128 @@
+/**
+ * A page clip's component properties: the few things of its page the person chose to offer for change, each named, as
+ * a design tool's component offers its properties. A property is made from a layer in the page (its words, its
+ * picture, whether it shows) or from one of the page's CSS variables; every clip of the page (a copy, one taken from
+ * Saved) offers the same ones, and each fills them in its own way.
+ *
+ * Where they are kept: the clip's `data-props`, a JSON list (an attribute the film keeps and gives no meaning, SPEC §1).
+ * What each clip fills in is an override, as any change made on the picture is: words as a `text` entry, a picture
+ * as the CSS that draws another file in its place, hidden as `visibility: hidden`, a variable in the `:root` entry's
+ * style. A property at its default has no override. The page itself is never written.
+ *
+ * Pure: no React, no DOM, so `node --test` runs it.
+ */
+
+import type { FilmOverride } from './film.ts';
+import { nextOverrides, overrideOf } from './film-overrides.ts';
+import { changedImage, changedText, changedVar, withImage, withText, withVar } from './template-controls.ts';
+
+/** Where the properties are kept on the clip. */
+export const PROPS_ATTR = 'data-props';
+
+/** Which layer: the CSS selector in the page and which match (none: every match). */
+type Target = { at: string; n?: number };
+
+export type ComponentProp =
+ | ({ name: string; type: 'text' } & Target)
+ | ({ name: string; type: 'image'; kind: 'img' | 'bg' } & Target)
+ | ({ name: string; type: 'boolean' } & Target)
+ | { name: string; type: 'var'; var: string };
+
+export type ComponentPropType = ComponentProp['type'];
+
+/** The value a property is set to: words, a file's place from the page's folder, shown or not, a CSS value. */
+export type PropValue = string | boolean;
+
+const isTarget = (o: Record<string, unknown>): boolean => typeof o.at === 'string' && o.at !== '' && (o.n === undefined || (Number.isInteger(o.n) && Number(o.n) > 0));
+
+/** The clip's properties, as its `data-props` lists them (anything not one left out). */
+export function propsOf(clip: { attrs?: Record<string, string> } | null | undefined): ComponentProp[] {
+ const raw = clip?.attrs?.[PROPS_ATTR];
+ if (!raw) return [];
+ let list: unknown;
+ try { list = JSON.parse(raw); } catch { return []; }
+ if (!Array.isArray(list)) return [];
+ const out: ComponentProp[] = [];
+ for (const item of list) {
+ if (!item || typeof item !== 'object') continue;
+ const o = item as Record<string, unknown>;
+ if (typeof o.name !== 'string' || !o.name.trim() || out.some((p) => p.name === o.name)) continue;
+ const at = { at: o.at as string, ...(o.n !== undefined ? { n: o.n as number } : {}) };
+ if ((o.type === 'text' || o.type === 'boolean') && isTarget(o)) out.push({ name: o.name, type: o.type, ...at });
+ else if (o.type === 'image' && isTarget(o) && (o.kind === 'img' || o.kind === 'bg')) out.push({ name: o.name, type: 'image', kind: o.kind, ...at });
+ else if (o.type === 'var' && typeof o.var === 'string' && o.var.startsWith('--')) out.push({ name: o.name, type: 'var', var: o.var });
+ }
+ return out;
+}
+
+/** The properties as `data-props` keeps them; null when there are none (the attribute goes). */
+export function propsAttr(list: readonly ComponentProp[]): string | null {
+ return list.length ? JSON.stringify(list) : null;
+}
+
+/** A name not taken among `list`: `base`, else `base 2`, `base 3`… */
+export function freshName(list: readonly ComponentProp[], base: string): string {
+ const name = base.trim().slice(0, 40) || 'Property';
+ for (let i = 1; ; i++) {
+ const candidate = i === 1 ? name : `${name} ${i}`;
+ if (!list.some((p) => p.name === candidate)) return candidate;
+ }
+}
+
+const sameTarget = (a: Target, b: Target) => a.at === b.at && (a.n ?? null) === (b.n ?? null);
+
+/** The property made of this layer's words / picture / showing, or of this variable, when there is one. */
+export function propOf(list: readonly ComponentProp[], type: ComponentPropType, of: Target | string): ComponentProp | null {
+ return list.find((p) => p.type === type && (p.type === 'var' ? p.var === of : typeof of !== 'string' && sameTarget(p, of))) ?? null;
+}
+
+/** The list with `prop` added; one of the same type made of the same thing is replaced (its name kept unique). */
+export function withProp(list: readonly ComponentProp[], prop: ComponentProp): ComponentProp[] {
+ const of = prop.type === 'var' ? prop.var : { at: prop.at, ...(prop.n !== undefined ? { n: prop.n } : {}) };
+ const rest = list.filter((p) => p !== propOf(list, prop.type, of));
+ return [...rest, { ...prop, name: freshName(rest, prop.name) }];
+}
+
+/** The list without the property named `name`. */
+export function withoutProp(list: readonly ComponentProp[], name: string): ComponentProp[] {
+ return list.filter((p) => p.name !== name);
+}
+
+/** The list with a property renamed; a name taken or empty leaves it as it was. */
+export function renamedProp(list: readonly ComponentProp[], name: string, next: string): ComponentProp[] {
+ const to = next.trim().slice(0, 40);
+ if (!to || to === name || list.some((p) => p.name === to)) return [...list];
+ return list.map((p) => (p.name === name ? { ...p, name: to } : p));
+}
+
+const targetOf = (p: Exclude<ComponentProp, { type: 'var' }>): Target => ({ at: p.at, ...(p.n !== undefined ? { n: p.n } : {}) });
+
+/**
+ * What the clip set a property to (its override), or null at its default: words, a file's place from the page's folder,
+ * `false` for a layer hidden, a CSS value.
+ */
+export function propValue(overrides: readonly FilmOverride[] | undefined, prop: ComponentProp): PropValue | null {
+ switch (prop.type) {
+ case 'text': return changedText(overrides, prop.at, prop.n);
+ case 'image': return changedImage(overrides, { ...targetOf(prop), kind: prop.kind });
+ case 'boolean': return overrideOf(overrides, targetOf(prop))?.style?.visibility === 'hidden' ? false : null;
+ case 'var': return changedVar(overrides, prop.var);
+ }
+}
+
+/** The clip's next overrides with a property set (null: back to its default). Null when none is left. */
+export function withPropValue(overrides: readonly FilmOverride[] | undefined, prop: ComponentProp, value: PropValue | null): FilmOverride[] | null {
+ switch (prop.type) {
+ case 'text': return withText(overrides, prop.at, prop.n, typeof value === 'string' ? value : null);
+ case 'image': return withImage(overrides, { ...targetOf(prop), kind: prop.kind }, typeof value === 'string' ? value : null);
+ case 'boolean': return nextOverrides(overrides, targetOf(prop), { style: { visibility: value === false ? 'hidden' : null } });
+ case 'var': return withVar(overrides, prop.var, typeof value === 'string' ? value : null);
+ }
+}
+
+/** The clip's next overrides with every property back to its default (its other changes, moves and fades, stay). */
+export function withPropsReset(overrides: readonly FilmOverride[] | undefined, list: readonly ComponentProp[]): FilmOverride[] | null {
+ let next: readonly FilmOverride[] | undefined = overrides;
+ for (const p of list) if (propValue(next, p) != null) next = withPropValue(next, p, null) ?? undefined;
+ return next?.length ? [...next] : null;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index 21d890f..4fff05a 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -70,10 +70,10 @@ export interface StudioHost {
onChange: (listener: (state: { open: boolean; width: number; assets?: { open: boolean; bottom: number } }) => void) => void;
};
/**
- * The app's chat names a skill in the message being written: the examples (opened from the chat, `show-examples`)
- * call this for a skill picked in them.
+ * The app's chat names a skill in the message being written: the skills (opened from the chat, `show-examples`)
+ * call this for one tried there, `newConversation` true (Try now: a new conversation with it named).
*/
- useSkill?: (skill: { name: string; description: string }) => void;
+ useSkill?: (skill: { name: string; description: string; newConversation?: boolean }) => void;
/** The person's own skills, where the app keeps them: one added, the app's own way (from a link, a folder, or made
with the agent). The Community's skills offer it. */
skills?: { add: () => void };
@@ -167,10 +167,14 @@ export interface StudioHost {
open: (projectId: string) => void;
move: (id: string, index: number) => void;
report: (state: { title?: string; exporting?: number | null; gone?: boolean }) => void;
+ /** projects this page deleted: their tabs close together, none of them to be opened again */
+ gone?: (projectIds: string[]) => Promise<unknown>;
/** another tab's title, its project renamed from this page's tabs (its page may be gone, and cannot say it) */
retitle?: (id: string, title: string) => Promise<unknown>;
openRequest: (to: string) => void;
onPick: (listener: () => void) => () => void;
+ /** another page shown in front of this one (a tab it opened, ready): what it showed meanwhile can go */
+ onCovered?: (listener: () => void) => () => void;
};
/**
diff --git a/packages/openfilm/studio/ui/src/lib/project-delete.test.ts b/packages/openfilm/studio/ui/src/lib/project-delete.test.ts
new file mode 100644
index 0000000..42a8208
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/project-delete.test.ts
@@ -0,0 +1,20 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { stillThere } from './project-delete.ts';
+
+const now = () => Promise.resolve();
+
+test('a delete whose answer was lost counts once the project leaves the list; one refused stays', async () => {
+ /* the open project's request was cut off, the server still moving it: gone at the second look */
+ const lists = [['a', 'b'], ['b']];
+ const left = await stillThere([{ id: 'a', lost: true }, { id: 'b', lost: false }], async () => lists.shift() ?? ['b'], { wait: now });
+ assert.deepEqual(left.map((f) => f.id), ['b']);
+});
+
+test('a project already gone was deleted; an unreadable list changes nothing; a lost one still there after the tries stays', async () => {
+ assert.deepEqual(await stillThere([{ id: 'a', lost: false }], async () => [], { wait: now }), []);
+ assert.deepEqual((await stillThere([{ id: 'a', lost: false }], () => Promise.reject(new Error('down')), { wait: now })).map((f) => f.id), ['a']);
+ let reads = 0;
+ const left = await stillThere([{ id: 'a', lost: true }], async () => { reads += 1; return ['a']; }, { tries: 3, wait: now });
+ assert.deepEqual([left.map((f) => f.id), reads], [['a'], 3]);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/project-delete.ts b/packages/openfilm/studio/ui/src/lib/project-delete.ts
new file mode 100644
index 0000000..bd2846a
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/project-delete.ts
@@ -0,0 +1,20 @@
+/**
+ * Which of the projects whose delete seemed to fail are still there, by the list read again (`list`): one gone already
+ * was deleted, and one whose answer was lost (`lost`: the request was cut off, as when the page showing it leaves
+ * it) may still be on its way to the Trash, so the list is read again a few times (`wait` between) before it counts.
+ * A list that cannot be read changes nothing.
+ */
+export async function stillThere<F extends { id: string; lost: boolean }>(
+ failed: readonly F[],
+ list: () => Promise<readonly string[]>,
+ { tries = 6, wait = () => new Promise<void>((done) => setTimeout(done, 500)) }: { tries?: number; wait?: () => Promise<void> } = {},
+): Promise<F[]> {
+ let left = [...failed];
+ for (let i = 0; left.length && i < tries; i++) {
+ if (i) await wait();
+ const ids = await list().then((l) => new Set(l), () => null);
+ if (ids) left = left.filter((f) => ids.has(f.id));
+ if (!left.some((f) => f.lost)) break;
+ }
+ return left;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/project-folders.ts b/packages/openfilm/studio/ui/src/lib/project-folders.ts
index 4309812..8f548b6 100644
--- a/packages/openfilm/studio/ui/src/lib/project-folders.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-folders.ts
@@ -41,6 +41,8 @@ export const folderApi = {
/** takes the folder off the list; resolves to the ids of the projects that were in it */
remove: (id: string) => call<{ projects: string[] }>(`folders/${encodeURIComponent(id)}`, 'DELETE').then((r) => r.projects),
move: (projectId: string, folderId: string | null) => call<object>(`${encodeURIComponent(projectId)}/folder`, 'PUT', { folderId }),
+ /** a folder into another (null: the top level), with what it holds */
+ moveFolder: (id: string, parentId: string | null) => call<{ folder: ProjectFolder }>(`folders/${encodeURIComponent(id)}`, 'PATCH', { parentId }).then((r) => r.folder),
};
/**
diff --git a/packages/openfilm/studio/ui/src/lib/project-sources.ts b/packages/openfilm/studio/ui/src/lib/project-sources.ts
index 968a32a..1c7eaea 100644
--- a/packages/openfilm/studio/ui/src/lib/project-sources.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-sources.ts
@@ -53,6 +53,10 @@ export type SkillEntry = {
repository?: string;
/** the person's own: where it came from (a link, a folder), or made where it is */
origin?: { from: 'link' | 'folder'; address: string } | { from: 'made' };
+ /** an official one: installed to be used (the person's own and a project's are installed already) */
+ installed?: boolean;
+ /** turned off: offered to no agent until it is turned on again */
+ off?: true;
};
/** an example film's part, as its index names it (`S2-Hook`), from and to in seconds */
export type ExampleSegment = { title: string; from: number; to: number };
@@ -121,6 +125,26 @@ export const sourcesApi = {
for (const [key, skills] of seen.skills) seen.skills.set(key, skills.map((skill) => skill.source === 'mine' && skill.name === name ? { ...skill, cover: result.cover ?? undefined } : skill));
return result.cover;
},
+ /** a skill turned on or off for every project; whoever lists skills (the gallery, the desktop's chat) reads them again */
+ setSkillOn: async (name: string, on: boolean): Promise<void> => {
+ await call<{ on: boolean }>(`skills/${encodeURIComponent(name)}/on`, 'PUT', { on });
+ for (const [key, skills] of seen.skills) seen.skills.set(key, skills.map((skill) => {
+ if (skill.name !== name) return skill;
+ const { off: _was, ...rest } = skill;
+ return on ? rest : { ...rest, off: true as const };
+ }));
+ window.dispatchEvent(new Event(SKILLS_CHANGED));
+ },
+ /** an official skill installed (it starts on) or uninstalled; whoever lists skills reads them again */
+ setSkillInstalled: async (name: string, installed: boolean): Promise<void> => {
+ await call<{ installed: boolean }>(`skills/${encodeURIComponent(name)}/installed`, 'PUT', { installed });
+ window.dispatchEvent(new Event(SKILLS_CHANGED));
+ },
+ /** one of the person's own skills, or a project's, moved to the trash */
+ removeSkill: async (name: string, projectId?: string | null): Promise<void> => {
+ await call<object>(`skills/${encodeURIComponent(name)}${projectId ? `?project=${encodeURIComponent(projectId)}` : ''}`, 'DELETE');
+ window.dispatchEvent(new Event(SKILLS_CHANGED));
+ },
/** asked as Studio opens, so a gallery opened later shows its examples and skills at once */
preload: () => { void sourcesApi.examples(); void sourcesApi.skills(null); },
locate: (id: string, path: string) => call<{ project: { id: string } }>(`projects/${encodeURIComponent(id)}/locate`, 'POST', { path }).then((r) => r.project),
diff --git a/packages/openfilm/studio/ui/src/lib/saved.ts b/packages/openfilm/studio/ui/src/lib/saved.ts
index 956fd6a..ce6ce1e 100644
--- a/packages/openfilm/studio/ui/src/lib/saved.ts
+++ b/packages/openfilm/studio/ui/src/lib/saved.ts
@@ -16,6 +16,8 @@ export const SAVED = 'saved';
let version = 0;
const listeners = new Set<() => void>();
+/** The library as the film's origin serves it (its listing says), where a saved page plays: '' until it is read. */
+let folder = '';
/** Read the library again (something was put in it, or may have been). */
export function refreshSaved(): void {
@@ -27,11 +29,16 @@ const enc = (path: string) => encodeURIComponent(path);
const media = (what: string, path: string, v: number) => `/api/saved/media?what=${what}&path=${enc(path)}&v=${v}`;
/** Where the library's pictures, sounds and bytes come from. A bundle is pictured by its poster. */
+/** A page of the library, at its place there (from its top), on the film's origin; none before the listing is read. */
+const pageAt = (rel: string) => (folder ? `${folder}${rel.split('/').map(encodeURIComponent).join('/')}` : undefined);
+
export const savedSources: MediaSources = {
file: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : `/api/saved/file?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}`),
poster: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : f.kind === 'video' ? media('poster', f.path, Math.round(f.mtimeMs)) : undefined),
wave: (f) => media('wave', f.path, Math.round(f.mtimeMs)),
pagePoster: (f) => (f.bundle ? `/api/saved/poster?path=${enc(f.path)}&v=${Math.round(f.mtimeMs)}` : undefined),
+ /* a page saved, or a page clip: its page, played as a project's is; a page put in the library as a file: itself */
+ pageSurface: (f) => (f.bundle ? (f.bundle.page ? pageAt(f.bundle.page) : undefined) : pageAt(f.path.slice(SAVED.length + 1))),
};
/** The library as the media pane lists it, once read (null before, or while `on` is false). */
@@ -46,7 +53,11 @@ export function useSavedListing(on: boolean): MediaListing | null {
React.useEffect(() => {
if (!on) return undefined;
let live = true;
- void fetch('/api/saved/files', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null), () => null).then((body) => { if (live && body) setRaw(body); });
+ void fetch('/api/saved/files', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null), () => null).then((body) => {
+ if (!live || !body) return;
+ if (typeof body.folder === 'string') folder = body.folder;
+ setRaw(body);
+ });
return () => { live = false; };
}, [on, seen]);
/* the window back: its folder may have been changed from the file manager */
diff --git a/packages/openfilm/studio/ui/src/lib/stage-types.ts b/packages/openfilm/studio/ui/src/lib/stage-types.ts
index 19981c9..7a6b717 100644
--- a/packages/openfilm/studio/ui/src/lib/stage-types.ts
+++ b/packages/openfilm/studio/ui/src/lib/stage-types.ts
@@ -48,6 +48,13 @@ export interface NodeOverride {
*/
export type OverridePivot = { hx: -1 | 0 | 1; hy: -1 | 0 | 1 };
+/**
+ * The picture a layer draws, when another file can be put in its place: an <img> (`img`), or a box painted with one
+ * image (`bg`). `src` is the address it draws now (on the film's origin): a file put in its place, else its own;
+ * `changed`: a file was put there. A box holding one <img> that fills it has that one's: `at` / `n` name the <img>.
+ */
+export type StagePicture = { kind: 'img' | 'bg'; src: string; changed?: boolean; at?: string; n?: number };
+
/** What is selected on the stage: a whole clip, or a layer inside one. */
export type StageElement = {
kind: 'clip' | StageNodeKind;
@@ -68,6 +75,8 @@ export type StageElement = {
* they are held (`value`: worked out, not written as one piece).
*/
text?: { loc: string; value: string; shape: 'children' | 'prop' | 'value' };
+ /** The picture it draws, when another file can be put in its place. */
+ picture?: StagePicture;
/** Attributes written as literals (`fill`, `strokeWidth`, `src`): the only ones the panel can change. */
attrs?: Record<string, string>;
/** Outer layers, nearest first. */
diff --git a/packages/openfilm/studio/ui/src/lib/template-controls.test.ts b/packages/openfilm/studio/ui/src/lib/template-controls.test.ts
index e783913..abe4ffe 100644
--- a/packages/openfilm/studio/ui/src/lib/template-controls.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/template-controls.test.ts
@@ -1,7 +1,7 @@
import { test as it } from 'node:test';
import assert from 'node:assert/strict';
import type { FilmOverride } from './film.ts';
-import { changedImage, changedText, changedVar, cssUrl, fieldOf, isFontVar, labelOf, relativeTo, urlOf, valueOf, withImage, withText, withVar } from './template-controls.ts';
+import { changedImage, changedText, changedVar, cssUrl, fieldOf, isFontVar, labelOf, pictureStyle, relativeTo, urlOf, valueOf, withImage, withText, withVar } from './template-controls.ts';
it('a custom property is changed as a color, a number with its unit, words, or as typed', () => {
assert.deepEqual(fieldOf('#ff5746'), { kind: 'color', value: '#ff5746' });
@@ -97,3 +97,11 @@ it('a custom property that names a font gets the font picker', () => {
assert.equal(isFontVar('--font-color', '#fff'), false);
assert.equal(isFontVar('--accent', 'Inter'), false);
});
+
+it('a picture on the picture is replaced by the same style the Content section writes: an <img> by content, a box by its background', () => {
+ assert.deepEqual(pictureStyle('img', '../assets/new.png'), { content: 'url("../assets/new.png")' });
+ assert.deepEqual(pictureStyle('bg', 'bg.jpg'), { backgroundImage: 'url("bg.jpg")' });
+ assert.deepEqual(pictureStyle('img', null), { content: null }, 'its own again');
+ const logo = { at: '#logo', kind: 'img' as const };
+ assert.equal(changedImage([{ at: '#logo', style: pictureStyle('img', 'x.png') as Record<string, string> }], logo), 'x.png');
+});
diff --git a/packages/openfilm/studio/ui/src/lib/template-controls.ts b/packages/openfilm/studio/ui/src/lib/template-controls.ts
index 3f57a4b..beb4429 100644
--- a/packages/openfilm/studio/ui/src/lib/template-controls.ts
+++ b/packages/openfilm/studio/ui/src/lib/template-controls.ts
@@ -1,13 +1,12 @@
/**
- * A page clip's template controls: what the inspector offers to change in a page without opening it, as a motion
- * graphics template has. Read from the page as it is on the picture (studio/server/stage.js `controls`): the CSS custom
- * properties its stylesheets set on `:root`, its words, and its pictures. Each change is an override of the clip, as any
- * change made on the picture is: a custom property in the style of the `:root` entry (the host sets it with priority,
- * so it wins over the page's own), words as a `text` entry, a picture as the CSS that draws another file in its place
- * (`content: url()` for an <img>, `background-image` for a box painted with one). Nothing for an agent to learn: a page
- * that keeps its colors and sizes in custom properties is a template already.
+ * What a page shows that a clip can change without opening it, read from the page as it is on the picture
+ * (studio/server/stage.js `controls`): the CSS custom properties its stylesheets set on `:root`, its words, and its
+ * pictures. The clip's properties (lib/component-props) are made of them. Each change is an override of the clip, as
+ * any change made on the picture is: a custom property in the style of the `:root` entry (the host sets it with
+ * priority, so it wins over the page's own), words as a `text` entry, a picture as the CSS that draws another file in
+ * its place (`content: url()` for an <img>, `background-image` for a box painted with one).
*
- * Pure: no React, no DOM, so `node --test` runs it (src/template-controls.test.mjs).
+ * Pure: no React, no DOM, so `node --test` runs it.
*/
import type { FilmOverride } from './film.ts';
@@ -121,6 +120,11 @@ export function changedImage(overrides: readonly FilmOverride[] | undefined, ima
return v == null ? null : urlOf(String(v));
}
+/** The style that draws another file in a picture's place (`path` from the page's folder), or its own again (null). */
+export function pictureStyle(kind: TemplateImage['kind'], path: string | null): Record<string, string | null> {
+ return { [imageKey(kind)]: path == null ? null : cssUrl(path) };
+}
+
/** The next overrides with another file drawn in a picture's place (`path` from the page's folder; null: the page's own). */
export function withImage(overrides: readonly FilmOverride[] | undefined, image: Pick<TemplateImage, 'at' | 'n' | 'kind'>, path: string | null): FilmOverride[] | null {
return nextOverrides(overrides, { at: image.at, ...(image.n != null ? { n: image.n } : {}) }, { style: { [imageKey(image.kind)]: path == null ? null : cssUrl(path) } });
diff --git a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts b/packages/openfilm/studio/ui/src/lib/workspace-resources.ts
index 96919c7..3bba505 100644
--- a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts
+++ b/packages/openfilm/studio/ui/src/lib/workspace-resources.ts
@@ -7,6 +7,7 @@
* `mediaListingOf`, and turns the pane's callbacks into `PUT/PATCH/DELETE files` and `POST folders`.
*/
import { clipKind } from '../../../../src/film-doc.mjs';
+import type { FilmOverride } from './film.ts';
import { mediaFetch } from './media-queue.ts';
export type WorkspaceResourceKind = 'video' | 'image' | 'audio' | 'mg' | 'other';
@@ -45,8 +46,19 @@ export interface WorkspaceResource {
bundle?: SavedBundle;
}
-/** What a bundle of Saved is: a clip, a group of `count` clips, or a page; `template`: its page has custom properties. */
-export interface SavedBundle { kind: 'clip' | 'group' | 'page'; count?: number; template?: boolean }
+/**
+ * What a bundle of Saved is: a clip, a group of `count` clips, or a page; `props`: a component, the properties it offers.
+ * A page, or a clip of one: `page`, where its page is in the library (from its top); a clip's `size` (what its page is
+ * laid out at) and `overrides` (the changes made in it), so it plays as the film had it.
+ */
+export interface SavedBundle {
+ kind: 'clip' | 'group' | 'page';
+ count?: number;
+ props?: number;
+ page?: string;
+ size?: { w: number; h: number };
+ overrides?: readonly FilmOverride[];
+}
export interface MediaProxy { state: 'waiting' | 'making' | 'ready' | 'failed'; ratio?: number }
@@ -160,7 +172,14 @@ export function mediaListingOf(
addedMs: f.added ?? f.mtime,
/* a bundle of Saved says its own length and size (it is no file to probe) */
...(f.saved ? {
- bundle: { kind: f.saved.kind, ...(f.saved.count ? { count: f.saved.count } : {}), ...(f.saved.template ? { template: true } : {}) },
+ bundle: {
+ kind: f.saved.kind,
+ ...(f.saved.count ? { count: f.saved.count } : {}),
+ ...(f.saved.props ? { props: f.saved.props } : {}),
+ ...(f.saved.page ? { page: f.saved.page } : {}),
+ ...(f.saved.size ? { size: f.saved.size } : {}),
+ ...(f.saved.overrides ? { overrides: f.saved.overrides } : {}),
+ },
...(f.saved.durationMs ? { durationMs: f.saved.durationMs } : {}),
...(f.saved.w ? { w: f.saved.w } : {}),
...(f.saved.h ? { h: f.saved.h } : {}),