Skip to content

🎥 Make videos programmatically with React

Add caption style selection to Studio transcription

Igor Samokhovets15806b71e54c
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index d75d69d400..c6b62a2d94 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1,11 +1,13 @@
import {
CodemodsInternals,
- applyCodemodChanges,
- addComposition as addCompositionCodemod,
addCanvasCaptureComposition,
+ addComposition as addCompositionCodemod,
addEffect as addEffectCodemod,
addElement,
addFolder as addFolderCodemod,
+ applyCodemodChanges,
+ canPrecomposeJsxNodes,
+ canWrapNode,
createElement,
deleteComposition as deleteCompositionCodemod,
deleteEffects as deleteEffectsCodemod,
@@ -14,13 +16,10 @@ import {
duplicateComposition as duplicateCompositionCodemod,
duplicateEffects as duplicateEffectsCodemod,
duplicateNodes as duplicateNodesCodemod,
- canWrapNode,
- wrapNode as wrapNodeCodemod,
getNodeProps,
- canPrecomposeJsxNodes,
- precomposeJsxNodes as precomposeJsxNodesCodemod,
moveComposition as moveCompositionCodemod,
moveFolder as moveFolderCodemod,
+ precomposeJsxNodes as precomposeJsxNodesCodemod,
renameComposition as renameCompositionCodemod,
renameFolder as renameFolderCodemod,
reorderEffect as reorderEffectCodemod,
@@ -34,6 +33,7 @@ import {
updateEffectProps as updateEffectPropsCodemod,
updateNodeKeyframes,
updateNodeProps,
+ wrapNode as wrapNodeCodemod,
type CodemodFileChange,
type CodemodNodeResult,
type CompositionDestination,
@@ -56,18 +56,18 @@ import {
type BrowserStudioOperations,
type BrowserStudioPackageInstallationOperations,
type CompositionEditResponse,
- type CompositionDestination as StudioCompositionDestination,
type ElementInstallExpectedFileState,
type EventSourceEvent,
- type InsertElementResponse,
type InsertCompositionElementRequest,
+ type InsertElementResponse,
type NewCompositionOptions,
type SequenceNodePathRemapping,
+ type CompositionDestination as StudioCompositionDestination,
type SubscribeToSequencePropsRequest,
type SubscribeToSequencePropsResponse,
type SymbolicatedStackFrame,
- type UnsubscribeFromSequencePropsRequest,
type UndoRedoNavigation,
+ type UnsubscribeFromSequencePropsRequest,
} from '@remotion/studio-shared';
import type {
InteractivitySchema,
@@ -457,6 +457,14 @@ const getElementInstallPlanForProject = async ({
}: Parameters<BrowserStudioOperations['prepareElementInstall']>[0] & {
project: VirtualProject;
}) => {
+ if (
+ destination.type === 'selected-media' &&
+ (element.isCaptionStyle !== true ||
+ element.installationMode !== 'component-owned-sequence')
+ ) {
+ throw new Error('The Element must be a component-owned caption style');
+ }
+
const componentName =
StudioProtocolInternals.getElementComponentNameFromSourceCode(
element.sourceCode,
@@ -2280,6 +2288,7 @@ export const createBrowserStudioOperations = ({
readFileContents: (candidate) => project.files[candidate] ?? null,
});
const result = insertBasicCaptionsCodemod({
+ element: null,
input: project.files[absolutePath],
nodePath,
captions,
@@ -2447,6 +2456,7 @@ export const createBrowserStudioOperations = ({
...value.payload.element,
durationInFrames: value.payload.element.durationInFrames ?? null,
installationMode: value.payload.element.installationMode ?? null,
+ isCaptionStyle: value.payload.element.isCaptionStyle ?? false,
},
sourceOrigin: value.sourceOrigin,
};
@@ -2482,6 +2492,17 @@ export const createBrowserStudioOperations = ({
),
insertElement: async (request) => {
try {
+ if (
+ request.captionTarget !== null &&
+ (request.element.isCaptionStyle !== true ||
+ request.element.installationMode !== 'component-owned-sequence' ||
+ request.newComposition !== null ||
+ request.compositionFile !== null ||
+ request.compositionId !== null)
+ ) {
+ throw new Error('Invalid caption style installation target');
+ }
+
StudioProtocolInternals.assertElementAssets(request.element.assets);
StudioProtocolInternals.assertElementAssetReferences(request.element);
const {element} = request;
@@ -2545,11 +2566,17 @@ export const createBrowserStudioOperations = ({
const plan = await getElementInstallPlanForProject({
installationName: request.installationName,
- destination: {
- type: 'current-composition',
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
- },
+ destination:
+ request.captionTarget === null
+ ? {
+ type: 'current-composition',
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ }
+ : {
+ type: 'selected-media',
+ compositionFile: request.captionTarget.fileName,
+ },
element,
project,
});
@@ -2659,47 +2686,88 @@ export const createBrowserStudioOperations = ({
request.element.dependencies,
);
const durationInFrames = request.element.durationInFrames ?? null;
- const insertion = await insertIntoProject({
- project,
- request: {
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
- element: {
- componentName: plan.componentName,
- importName: plan.componentName,
- importPath: plan.importPath,
- position: componentOwnsSequence ? request.position : null,
- props: [
- ...Object.entries(request.element.initialProps ?? {}).map(
- ([name, value]) => ({name, value}),
- ),
- ...(componentOwnsSequence && durationInFrames !== null
- ? [
- {
- name: 'durationInFrames',
- value: durationInFrames,
- },
- ]
- : []),
- ...(componentOwnsSequence
- ? [{name: 'name', value: request.element.displayName}]
- : []),
- ],
- type: 'component',
- },
- from: componentOwnsSequence ? request.from : null,
- premountFor: request.premountFor,
- },
- wrapInSequence: componentOwnsSequence
- ? null
- : {
- dimensions: request.element.dimensions,
- durationInFrames,
- from: request.from,
- name: request.element.displayName,
- position: request.position,
- },
- });
+ const insertion =
+ request.captionTarget === null
+ ? await insertIntoProject({
+ project,
+ request: {
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ element: {
+ componentName: plan.componentName,
+ importName: plan.componentName,
+ importPath: plan.importPath,
+ position: componentOwnsSequence ? request.position : null,
+ props: [
+ ...Object.entries(request.element.initialProps ?? {}).map(
+ ([name, value]) => ({name, value}),
+ ),
+ ...(componentOwnsSequence && durationInFrames !== null
+ ? [
+ {
+ name: 'durationInFrames',
+ value: durationInFrames,
+ },
+ ]
+ : []),
+ ...(componentOwnsSequence
+ ? [{name: 'name', value: request.element.displayName}]
+ : []),
+ ],
+ type: 'component',
+ },
+ from: componentOwnsSequence ? request.from : null,
+ premountFor: request.premountFor,
+ },
+ wrapInSequence: componentOwnsSequence
+ ? null
+ : {
+ dimensions: request.element.dimensions,
+ durationInFrames,
+ from: request.from,
+ name: request.element.displayName,
+ position: request.position,
+ },
+ })
+ : (() => {
+ const filePath = findProjectFile({
+ filePath: request.captionTarget.fileName,
+ project,
+ });
+ const result = insertBasicCaptionsCodemod({
+ ...request.captionTarget,
+ input: project.files[filePath],
+ importPath: plan.importPath,
+ element: {
+ componentName: plan.componentName,
+ initialProps: {
+ ...element.initialProps,
+ ...(element.dimensions === null
+ ? {}
+ : {
+ style: {
+ ...element.dimensions,
+ ...(typeof element.initialProps?.style ===
+ 'object'
+ ? element.initialProps.style
+ : {}),
+ },
+ }),
+ },
+ },
+ });
+ return {
+ filePath,
+ nodePathRemappings: result.nodePathRemappings,
+ changes: [
+ {
+ filePath,
+ previousContents: project.files[filePath],
+ nextContents: result.output,
+ },
+ ],
+ };
+ })();
const projectWithElement = applyCodemodChanges(project, [
...insertion.changes,
{
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 1b60212911..9225067ff2 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -66,6 +66,7 @@ test('consumes an initial Element payload only once', () => {
...payload.element,
durationInFrames: 60,
installationMode: 'wrapped',
+ isCaptionStyle: false,
},
sourceOrigin: 'https://elements.example.test',
});
diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
index 5cc7fcc9ca..ead82fd308 100644
--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts
@@ -524,6 +524,7 @@ test('imports an Element with pinned Remotion dependencies as one undoable mutat
logoSrc: staticFileRef('elements/lower-third.bin'),
},
installationMode: 'wrapped' as const,
+ isCaptionStyle: false,
slug: 'titles/lower-third',
sourceCode: `import {Rect} from '@remotion/shapes';
import {Img} from 'remotion';
@@ -577,6 +578,7 @@ export const LowerThird = ({logoSrc}: {logoSrc: string}) => <>
expectedFileState: preflight.plan.expectedFileState,
from: 12,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 24, y: 48},
undoRedoNavigation: null,
@@ -640,6 +642,7 @@ export const LowerThird = ({logoSrc}: {logoSrc: string}) => <>
expectedFileState: null,
from: null,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -682,6 +685,7 @@ export const LowerThird = ({logoSrc}: {logoSrc: string}) => <>
(
await operations.insertElement({
...installRequest,
+ captionTarget: null,
overwriteExisting: true,
})
).success,
@@ -729,12 +733,14 @@ const makeElementAssetFixture = () => {
durationInFrames: 30,
initialProps: null,
installationMode: 'wrapped',
+ isCaptionStyle: false,
slug: 'asset-element',
sourceCode: 'export const AssetElement = () => <div />;',
},
expectedFileState: null,
from: null,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -857,6 +863,7 @@ test('installs an Element into a new composition as one undoable mutation', asyn
durationInFrames: 90,
initialProps: null,
installationMode: 'wrapped' as const,
+ isCaptionStyle: false,
slug: 'browser-element',
sourceCode: 'export const BrowserElement = () => <div />;\n',
} satisfies ElementDragData['element'];
@@ -877,6 +884,7 @@ test('installs an Element into a new composition as one undoable mutation', asyn
expectedFileState: preflight.plan.expectedFileState,
from: null,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: {
@@ -973,6 +981,7 @@ test('installs component-owned Element timing and initial props', async () => {
width: 640,
},
installationMode: 'component-owned-sequence' as const,
+ isCaptionStyle: false,
slug: 'captions',
sourceCode: 'export const Captions = () => <div />;\n',
} satisfies ElementDragData['element'];
@@ -997,6 +1006,7 @@ test('installs component-owned Element timing and initial props', async () => {
expectedFileState: preflight.plan.expectedFileState,
from: 30,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 24, y: 48},
undoRedoNavigation: null,
@@ -1081,12 +1091,14 @@ test('rejects contradictory component-owned Element initial props', async () =>
durationInFrames: 90,
initialProps,
installationMode: 'component-owned-sequence',
+ isCaptionStyle: false,
slug: 'captions',
sourceCode: 'export const Captions = () => <div />;\n',
},
expectedFileState: null,
from: 30,
premountFor: null,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 24, y: 48},
undoRedoNavigation: null,
diff --git a/packages/codemods/src/insert-basic-captions.ts b/packages/codemods/src/insert-basic-captions.ts
index 74dccbe33b..42e541da00 100644
--- a/packages/codemods/src/insert-basic-captions.ts
+++ b/packages/codemods/src/insert-basic-captions.ts
@@ -1,15 +1,21 @@
import type {JSXElement, JSXFragment} from '@babel/types';
+import type {ElementInitialProps} from '@remotion/studio-protocol';
import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
+import {buildJsxElement} from './build-jsx-element';
import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
import {
captureJsxNodePaths,
getNodePathRemappings,
} from './get-node-path-remappings';
-import {indentInsertedJsx} from './print-jsx';
+import {createElementFromInsertable} from './insertable-element';
+import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
-import {ensureNamedImport, getImportedName} from './sequence-props/imports';
+import {
+ ensureOfficialNamedImport,
+ getImportedName,
+} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
import {
applySourceEdits,
@@ -30,6 +36,7 @@ export const insertBasicCaptions = ({
input,
nodePath,
captions,
+ element,
durationInFrames,
premountFor,
importPath = './basic-captions.element',
@@ -37,6 +44,10 @@ export const insertBasicCaptions = ({
}: {
input: string;
nodePath: SequenceNodePath;
+ element: {
+ componentName: string;
+ initialProps: ElementInitialProps | null;
+ } | null;
captions: {
text: string;
startMs: number;
@@ -98,33 +109,30 @@ export const insertBasicCaptions = ({
throw new Error('The selected element is not a Remotion Video or Audio');
}
- let localName = 'BasicCaptions';
- let suffix = 1;
- while (new RegExp(`\\b${localName}\\b`).test(input)) {
- localName = `BasicCaptions${suffix++}`;
- }
-
- const captionsLocalName = ensureNamedImport({
+ const componentName = element?.componentName ?? 'BasicCaptions';
+ const captionsLocalName = ensureOfficialNamedImport({
ast,
- importedName: 'BasicCaptions',
- localName,
+ importedName: componentName,
+ preferredLocalName: componentName,
sourcePath: importPath,
});
- const copiedAttributes = media.openingElement.attributes
- .filter(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- [
- 'from',
- 'durationInFrames',
- 'trimBefore',
- 'playbackRate',
- 'premountFor',
- 'postmountFor',
- ].includes(attribute.name.name),
- )
- .map((attribute) => recast.print(attribute).code);
+ const timingProps = [
+ 'from',
+ 'durationInFrames',
+ 'trimBefore',
+ 'playbackRate',
+ 'premountFor',
+ 'postmountFor',
+ ];
+ const mediaAttributes = media.openingElement.attributes.filter(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ timingProps.includes(attribute.name.name),
+ );
+ const copiedAttributes = mediaAttributes.map(
+ (attribute) => recast.print(attribute).code,
+ );
if (
Number.isFinite(durationInFrames) &&
durationInFrames !== null &&
@@ -142,81 +150,135 @@ export const insertBasicCaptions = ({
copiedAttributes.push(`premountFor={${premountFor}}`);
}
- const formattingConfig = getSourceFormattingConfig({
- input,
- prettierConfigOverride,
- });
- const trailingComma =
- prettierConfigOverride?.trailingComma !== 'none' &&
- prettierConfigOverride?.trailingComma !== false;
- const singleLineElement = `<${captionsLocalName} captions={[]}${copiedAttributes.length === 0 ? '' : ` ${copiedAttributes.join(' ')}`} />`;
- const captionLines = captions.flatMap((caption, captionIndex) => {
- const doubleQuotedText = JSON.stringify(caption.text);
- const singleQuotedText = `'${doubleQuotedText
- .slice(1, -1)
- .replaceAll('\\"', '"')
- .replaceAll("'", "\\'")}'`;
- const singleQuotes = caption.text.match(/'/g)?.length ?? 0;
- const doubleQuotes = caption.text.match(/"/g)?.length ?? 0;
- const text =
- singleQuotes === doubleQuotes
- ? formattingConfig.quote === 'single'
- ? singleQuotedText
- : doubleQuotedText
- : singleQuotes < doubleQuotes
- ? singleQuotedText
- : doubleQuotedText;
- const properties = [
- `text: ${text}`,
- `startMs: ${JSON.stringify(caption.startMs)}`,
- `endMs: ${JSON.stringify(caption.endMs)}`,
- `timestampMs: ${JSON.stringify(caption.timestampMs)}`,
- `confidence: ${JSON.stringify(caption.confidence)}`,
- ...(caption.pageBreakAfter === undefined
- ? []
- : [`pageBreakAfter: ${caption.pageBreakAfter}`]),
- ];
- return [
- '{',
- ...properties.map((property, propertyIndex) =>
+ let elementSource: string;
+ if (element === null) {
+ const formattingConfig = getSourceFormattingConfig({
+ input,
+ prettierConfigOverride,
+ });
+ const trailingComma =
+ prettierConfigOverride?.trailingComma !== 'none' &&
+ prettierConfigOverride?.trailingComma !== false;
+ const singleLineElement = `<${captionsLocalName} captions={[]}${copiedAttributes.length === 0 ? '' : ` ${copiedAttributes.join(' ')}`} />`;
+ const captionLines = captions.flatMap((caption, captionIndex) => {
+ const doubleQuotedText = JSON.stringify(caption.text);
+ const singleQuotedText = `'${doubleQuotedText
+ .slice(1, -1)
+ .replaceAll('\\"', '"')
+ .replaceAll("'", "\\'")}'`;
+ const singleQuotes = caption.text.match(/'/g)?.length ?? 0;
+ const doubleQuotes = caption.text.match(/"/g)?.length ?? 0;
+ const text =
+ singleQuotes === doubleQuotes
+ ? formattingConfig.quote === 'single'
+ ? singleQuotedText
+ : doubleQuotedText
+ : singleQuotes < doubleQuotes
+ ? singleQuotedText
+ : doubleQuotedText;
+ const properties = [
+ `text: ${text}`,
+ `startMs: ${JSON.stringify(caption.startMs)}`,
+ `endMs: ${JSON.stringify(caption.endMs)}`,
+ `timestampMs: ${JSON.stringify(caption.timestampMs)}`,
+ `confidence: ${JSON.stringify(caption.confidence)}`,
+ ...(caption.pageBreakAfter === undefined
+ ? []
+ : [`pageBreakAfter: ${caption.pageBreakAfter}`]),
+ ];
+ return [
+ '{',
+ ...properties.map((property, propertyIndex) =>
+ indentInsertedJsx({
+ indent: formattingConfig.indentationUnit,
+ insertion: `${property}${
+ propertyIndex < properties.length - 1 || trailingComma ? ',' : ''
+ }`,
+ }),
+ ),
+ `}${captionIndex < captions.length - 1 || trailingComma ? ',' : ''}`,
+ ].map((line) =>
indentInsertedJsx({
indent: formattingConfig.indentationUnit,
- insertion: `${property}${
- propertyIndex < properties.length - 1 || trailingComma ? ',' : ''
- }`,
+ insertion: line,
}),
- ),
- `}${captionIndex < captions.length - 1 || trailingComma ? ',' : ''}`,
- ].map((line) =>
- indentInsertedJsx({
- indent: formattingConfig.indentationUnit,
- insertion: line,
+ );
+ });
+ const multilineElementLines = [
+ `<${captionsLocalName}`,
+ 'captions={[',
+ ...captionLines,
+ ']}',
+ ...copiedAttributes,
+ '/>',
+ ];
+ elementSource =
+ captions.length === 0 &&
+ !singleLineElement.includes('\n') &&
+ singleLineElement.length <= formattingConfig.printWidth
+ ? singleLineElement
+ : multilineElementLines
+ .map((line, index) =>
+ index === 0 || index === multilineElementLines.length - 1
+ ? line
+ : indentInsertedJsx({
+ indent: formattingConfig.indentationUnit,
+ insertion: line,
+ }),
+ )
+ .join(formattingConfig.endOfLine);
+ } else {
+ const jsx = buildJsxElement({
+ ast,
+ element: createElementFromInsertable({
+ element: {
+ type: 'component',
+ componentName: captionsLocalName,
+ importName: componentName,
+ importPath,
+ position: null,
+ props: [
+ ...Object.entries(element.initialProps ?? {})
+ .filter(
+ ([name]) => name !== 'captions' && !timingProps.includes(name),
+ )
+ .map(([name, value]) => ({name, value})),
+ {name: 'captions', value: captions},
+ ...(durationInFrames !== null && Number.isFinite(durationInFrames)
+ ? [{name: 'durationInFrames', value: durationInFrames}]
+ : []),
+ ],
+ },
+ from: null,
+ premountFor,
+ wrapInSequence: null,
}),
+ });
+ const copiedNames = new Set(
+ mediaAttributes.map((attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier'
+ ? attribute.name.name
+ : null,
+ ),
);
- });
- const multilineElementLines = [
- `<${captionsLocalName}`,
- 'captions={[',
- ...captionLines,
- ']}',
- ...copiedAttributes,
- '/>',
- ];
- const elementSource =
- captions.length === 0 &&
- !singleLineElement.includes('\n') &&
- singleLineElement.length <= formattingConfig.printWidth
- ? singleLineElement
- : multilineElementLines
- .map((line, index) =>
- index === 0 || index === multilineElementLines.length - 1
- ? line
- : indentInsertedJsx({
- indent: formattingConfig.indentationUnit,
- insertion: line,
- }),
- )
- .join(formattingConfig.endOfLine);
+ jsx.openingElement.attributes = (
+ jsx.openingElement.attributes ?? []
+ ).filter(
+ (attribute) =>
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier' ||
+ !copiedNames.has(attribute.name.name),
+ );
+ jsx.openingElement.attributes.push(...(mediaAttributes as never[]));
+ elementSource = printInsertedJsx({
+ element: jsx,
+ input,
+ prettierConfigOverride,
+ compactLiteralProps: true,
+ });
+ }
+
const parsedElement = parseAst(`const element = (${elementSource});`).program
.body[0];
if (
diff --git a/packages/codemods/src/test/insert-basic-captions.test.ts b/packages/codemods/src/test/insert-basic-captions.test.ts
index fba9758db4..c33806fce9 100644
--- a/packages/codemods/src/test/insert-basic-captions.test.ts
+++ b/packages/codemods/src/test/insert-basic-captions.test.ts
@@ -31,6 +31,7 @@ export const Comp = () => (
);
`;
const {output} = insertBasicCaptions({
+ element: null,
input,
nodePath: lineContainingToNodePath(input, '<Video'),
captions,
@@ -83,6 +84,7 @@ test('uses the source whitespace and configured trailing comma style', () => {
'',
].join('\r\n');
const {output} = insertBasicCaptions({
+ element: null,
input,
nodePath: lineContainingToNodePath(input, '<Video'),
captions: [
diff --git a/packages/docs/docs/studio-protocol/create-element-payload.mdx b/packages/docs/docs/studio-protocol/create-element-payload.mdx
index 10e51c0dfb..7a9f8b3c4b 100644
--- a/packages/docs/docs/studio-protocol/create-element-payload.mdx
+++ b/packages/docs/docs/studio-protocol/create-element-payload.mdx
@@ -117,6 +117,14 @@ With `'component-owned-sequence'`, Studio puts timing, name, and absolute positi
See [Design it for composition](/elements/guidelines#design-it-for-composition) for guidance on choosing a mode and wiring the component.
+### isCaptionStyle?<AvailableFrom v="4.0.534" />
+
+Set to `true` to let the Element be selected in the Styles tab when generating captions for a video or audio element. The default is `false`.
+
+Caption styles must use `installationMode: 'component-owned-sequence'`, accept a `captions` prop containing [`Caption[]`](/docs/captions/caption), and expose it through [`Interactive.captionsSchema`](/docs/interactivity-schema#interactivecaptionsschema). Use [`Interactive.withSchema()`](/docs/interactive-with-schema) with `wrapInSequence: true` to support `from`, `durationInFrames`, `trimBefore`, `playbackRate`, `premountFor`, and `postmountFor`.
+
+Studio replaces preview captions with the generated transcript and copies timing from the selected media. Other initial props are preserved. Choosing a style does not install it; Studio installs its source, dependencies, and assets after transcription, with your permission. The flag describes compatibility, not trust: an Element can execute arbitrary code.
+
## Return value
A `StudioElementPayload`. Asset-free payloads use version `1`; payloads with assets use version `2`. Pass the returned object unchanged to a transport API instead of serializing it manually.
diff --git a/packages/docs/elements/captions/index.mdx b/packages/docs/elements/captions/index.mdx
index 1f0cf8670f..211c926e37 100644
--- a/packages/docs/elements/captions/index.mdx
+++ b/packages/docs/elements/captions/index.mdx
@@ -15,7 +15,10 @@ import {ElementLibrary} from '@site/src/components/Elements/ElementLibrary';
<Step>1</Step> Select a video or audio.<br/>
<Step>2</Step> Click <kbd>Generate captions</kbd> in the inspector.<br/>
-<Step>3</Step> Confirm installation and generate captions. <br/>
+<Step>3</Step> In the <kbd>Styles</kbd> tab, keep Simple captions or choose a caption Element.<br/>
+<Step>4</Step> For a selected Element, allow installing its code, then click <kbd>Generate captions</kbd>.<br/>
+
+Style selection is available from <AvailableFrom v="4.0.534" inline />. Simple captions works without loading the Element library.
### Importing captions into Studio<AvailableFrom v="4.0.521" />
diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.ts
index 3f9a978089..d2d62349b7 100644
--- a/packages/docs/src/components/Elements/element-definitions.ts
+++ b/packages/docs/src/components/Elements/element-definitions.ts
@@ -1,11 +1,11 @@
import {ding, mouseClick} from '@remotion/sfx';
-import {staticFileRef} from '@remotion/studio-protocol';
import type {
ElementAsset,
ElementDependency,
ElementInitialProps,
ElementInstallationMode,
} from '@remotion/studio-protocol';
+import {staticFileRef} from '@remotion/studio-protocol';
import type {ComponentType} from 'react';
import {MirroredAudioSpectrum} from '../../../elements/audio/mirrored-spectrum/mirrored-spectrum';
import {AudioOscilloscope} from '../../../elements/audio/oscilloscope/audio-oscilloscope';
@@ -105,6 +105,7 @@ export type ElementDefinition = {
readonly safeArea: number;
readonly slug: string;
readonly installationMode: ElementInstallationMode;
+ readonly isCaptionStyle: boolean;
readonly width: number;
};
@@ -130,6 +131,7 @@ const youtubeSubscribeNudgeAssets = {
const elementImplementations = [
{
slug: 'audio/oscilloscope',
+ isCaptionStyle: false,
assets: [audioOscilloscopeAudio],
installationProps: {
src: staticFileRef(audioOscilloscopeAudio.path),
@@ -162,6 +164,7 @@ const elementImplementations = [
},
{
slug: 'audio/waveform-progress',
+ isCaptionStyle: false,
assets: [audioOscilloscopeAudio],
installationProps: {
src: staticFileRef(audioOscilloscopeAudio.path),
@@ -194,6 +197,7 @@ const elementImplementations = [
},
{
slug: 'audio/mirrored-spectrum',
+ isCaptionStyle: false,
assets: [audioOscilloscopeAudio],
installationProps: {
src: staticFileRef(audioOscilloscopeAudio.path),
@@ -226,6 +230,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/notebook-paper',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: NotebookPaper,
@@ -253,6 +258,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/paper-texture',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: PaperTexture,
@@ -281,6 +287,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/rotating-starburst',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: RotatingStarburst,
@@ -308,6 +315,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/moving-waves',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: MovingWaves,
@@ -335,6 +343,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/moving-zigzags',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: MovingZigzags,
@@ -362,6 +371,7 @@ const elementImplementations = [
},
{
slug: 'backgrounds/liquid-contours',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: LiquidContours,
@@ -390,6 +400,7 @@ const elementImplementations = [
},
{
slug: 'captions/basic-captions',
+ isCaptionStyle: true,
assets: [],
installationProps: null,
component: BasicCaptions,
@@ -418,6 +429,7 @@ const elementImplementations = [
},
{
slug: 'captions/rounded-captions',
+ isCaptionStyle: true,
assets: [],
installationProps: null,
component: RoundedCaptions,
@@ -451,6 +463,7 @@ const elementImplementations = [
},
{
slug: 'captions/moving-pill-captions',
+ isCaptionStyle: true,
assets: [],
installationProps: null,
component: MovingPillCaptions,
@@ -483,6 +496,7 @@ const elementImplementations = [
},
{
slug: 'captions/popping-word-captions',
+ isCaptionStyle: true,
assets: [],
installationProps: null,
component: PoppingWordCaptions,
@@ -514,6 +528,7 @@ const elementImplementations = [
},
{
slug: 'captions/word-highlight-captions',
+ isCaptionStyle: true,
assets: [],
installationProps: null,
component: WordHighlightCaptions,
@@ -545,6 +560,7 @@ const elementImplementations = [
},
{
slug: 'commerce/product-collection',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: ProductCollection,
@@ -572,6 +588,7 @@ const elementImplementations = [
},
{
slug: 'commerce/product-discount-callout',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: ProductDiscountCallout,
@@ -602,6 +619,7 @@ const elementImplementations = [
},
{
slug: 'commerce/shine',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: Shine,
@@ -627,6 +645,7 @@ const elementImplementations = [
},
{
slug: 'commerce/tear',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: Tear,
@@ -652,6 +671,7 @@ const elementImplementations = [
},
{
slug: 'data/horizontal-bar-chart',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: HorizontalBarChart,
@@ -679,6 +699,7 @@ const elementImplementations = [
},
{
slug: 'data/line-chart',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: LineChart,
@@ -704,6 +725,7 @@ const elementImplementations = [
},
{
slug: 'data/number-counter',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: NumberCounter,
@@ -737,6 +759,7 @@ const elementImplementations = [
},
{
slug: 'data/pie-chart',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: PieChart,
@@ -763,6 +786,7 @@ const elementImplementations = [
},
{
slug: 'data/vertical-bar-chart',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: VerticalBarChart,
@@ -791,6 +815,7 @@ const elementImplementations = [
},
{
slug: 'layouts/picture-in-picture-transition',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: PictureInPictureTransition,
@@ -819,6 +844,7 @@ const elementImplementations = [
},
{
slug: 'layouts/slide-to-split-screen',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: SlideToSplitScreen,
@@ -847,6 +873,7 @@ const elementImplementations = [
},
{
slug: 'maps/map-flyover',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: MapFlyover,
@@ -876,6 +903,7 @@ const elementImplementations = [
},
{
slug: 'maps/watercolor-map',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: WatercolorMap,
@@ -907,6 +935,7 @@ const elementImplementations = [
},
{
slug: 'overlays/location-lower-third',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: LocationLowerThird,
@@ -934,6 +963,7 @@ const elementImplementations = [
},
{
slug: 'overlays/name-lower-third',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: NameLowerThird,
@@ -962,6 +992,7 @@ const elementImplementations = [
},
{
slug: 'overlays/social-safe-zones',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: SocialSafeZones,
@@ -990,6 +1021,7 @@ const elementImplementations = [
},
{
slug: 'text/news-article-highlight',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: NewsArticleHighlight,
@@ -1017,6 +1049,7 @@ const elementImplementations = [
},
{
slug: 'storytelling/speed-lines',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: SpeedLines,
@@ -1044,6 +1077,7 @@ const elementImplementations = [
},
{
slug: 'storytelling/on-screen-messages',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: OnScreenMessages,
@@ -1072,6 +1106,7 @@ const elementImplementations = [
},
{
slug: 'storytelling/polaroid-pictures',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: PolaroidPictures,
@@ -1100,6 +1135,7 @@ const elementImplementations = [
},
{
slug: 'text/circle-marker',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: CircleMarker,
@@ -1131,6 +1167,7 @@ const elementImplementations = [
},
{
slug: 'text/crossed-off',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: CrossedOffText,
@@ -1160,6 +1197,7 @@ const elementImplementations = [
},
{
slug: 'text/spinning-text-wheel',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: SpinningTextWheel,
@@ -1188,6 +1226,7 @@ const elementImplementations = [
},
{
slug: 'text/strike-through',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: StrikeThroughText,
@@ -1219,6 +1258,7 @@ const elementImplementations = [
},
{
slug: 'text/text-marker',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: TextMarker,
@@ -1248,6 +1288,7 @@ const elementImplementations = [
},
{
slug: 'youtube/youtube-comment-highlight',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: YouTubeCommentHighlight,
@@ -1275,6 +1316,7 @@ const elementImplementations = [
},
{
slug: 'youtube/youtube-end-card',
+ isCaptionStyle: false,
assets: [],
installationProps: null,
component: YouTubeEndCard,
@@ -1303,6 +1345,7 @@ const elementImplementations = [
},
{
slug: 'youtube/youtube-subscribe-nudge',
+ isCaptionStyle: false,
assets: [
youtubeSubscribeNudgeAssets.click,
youtubeSubscribeNudgeAssets.ding,
diff --git a/packages/docs/src/components/Elements/element-drag-data.ts b/packages/docs/src/components/Elements/element-drag-data.ts
index 323b9f9843..2dd099bd12 100644
--- a/packages/docs/src/components/Elements/element-drag-data.ts
+++ b/packages/docs/src/components/Elements/element-drag-data.ts
@@ -33,6 +33,7 @@ export const createElementPayloadFromDefinition = ({
? definition.initialProps
: {...definition.initialProps, ...definition.installationProps},
installationMode: definition.installationMode,
+ isCaptionStyle: definition.isCaptionStyle,
slug: definition.slug,
sourceCode,
});
diff --git a/packages/studio-protocol/src/drag-data.ts b/packages/studio-protocol/src/drag-data.ts
index 89eb56da8d..5ba311106a 100644
--- a/packages/studio-protocol/src/drag-data.ts
+++ b/packages/studio-protocol/src/drag-data.ts
@@ -244,6 +244,7 @@ export const makeDragData = ((
slug: input.slug,
sourceCode: input.sourceCode,
installationMode: input.installationMode,
+ isCaptionStyle: input.isCaptionStyle,
}),
{
type: input.type,
diff --git a/packages/studio-protocol/src/element-drag-data.ts b/packages/studio-protocol/src/element-drag-data.ts
index 88cf38e20b..bf649da5c2 100644
--- a/packages/studio-protocol/src/element-drag-data.ts
+++ b/packages/studio-protocol/src/element-drag-data.ts
@@ -57,6 +57,7 @@ export type ElementDragData = {
durationInFrames?: number;
initialProps: ElementInitialProps | null;
installationMode?: ElementInstallationMode;
+ isCaptionStyle?: boolean;
slug: string;
displayName: string;
sourceCode: string;
@@ -427,6 +428,7 @@ export const makeElementDragData = ({
slug,
sourceCode,
installationMode,
+ isCaptionStyle,
}: Omit<ElementDragData['element'], 'dependencies'> & {
dependencies: ElementDependency[];
}): ElementDragData => {
@@ -453,6 +455,7 @@ export const makeElementDragData = ({
...(durationInFrames === undefined ? {} : {durationInFrames}),
initialProps,
...(installationMode === undefined ? {} : {installationMode}),
+ ...(isCaptionStyle === undefined ? {} : {isCaptionStyle}),
slug,
sourceCode,
},
@@ -468,6 +471,7 @@ const elementDragDataSchema = z.object({
durationInFrames: z.optional(durationSchema),
initialProps: z.optional(z.nullable(elementInitialPropsSchema)),
installationMode: z.optional(elementInstallationModeSchema),
+ isCaptionStyle: z.optional(z.boolean()),
slug: slugSchema,
displayName: z.string().check(z.minLength(1), z.maxLength(119)),
sourceCode: z
@@ -531,6 +535,7 @@ export const parseElementDragData = (value: string): ElementDragData | null => {
slug: parsed.data.element.slug,
sourceCode: parsed.data.element.sourceCode,
installationMode: parsed.data.element.installationMode,
+ isCaptionStyle: parsed.data.element.isCaptionStyle,
});
return result.version === parsed.data.version ? result : null;
} catch {
diff --git a/packages/studio-protocol/src/element-payload.ts b/packages/studio-protocol/src/element-payload.ts
index 2ed697ed89..b129791a6e 100644
--- a/packages/studio-protocol/src/element-payload.ts
+++ b/packages/studio-protocol/src/element-payload.ts
@@ -29,6 +29,7 @@ export type CreateElementPayloadInput = {
readonly durationInFrames: number;
readonly initialProps?: ElementInitialProps | null;
readonly installationMode?: ElementInstallationMode;
+ readonly isCaptionStyle?: boolean;
};
export type StudioElementPayload = ElementDragData & {
@@ -94,6 +95,22 @@ const assertCreateElementPayloadInput = (
);
}
+ if (
+ input.isCaptionStyle !== undefined &&
+ typeof input.isCaptionStyle !== 'boolean'
+ ) {
+ throw new TypeError('isCaptionStyle must be a boolean');
+ }
+
+ if (
+ input.isCaptionStyle &&
+ input.installationMode !== 'component-owned-sequence'
+ ) {
+ throw new TypeError(
+ 'Caption styles must use component-owned-sequence installation',
+ );
+ }
+
const initialProps = input.initialProps ?? null;
if (!isElementInitialProps(initialProps)) {
throw new TypeError(
@@ -128,6 +145,7 @@ export const createElementPayload = (
slug: input.slug,
sourceCode: input.sourceCode,
installationMode: input.installationMode ?? 'wrapped',
+ isCaptionStyle: input.isCaptionStyle,
});
const payload: StudioElementPayload = {
...constructed.data,
diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.ts
index ce55d4c45d..6ff7f79ded 100644
--- a/packages/studio-protocol/src/install-in-studio.ts
+++ b/packages/studio-protocol/src/install-in-studio.ts
@@ -99,7 +99,7 @@ const installInStudioResultSchema = z.union([
}),
z.object({
success: z.literal(false),
- code: z.literal('no-installable-target'),
+ code: z.enum(['no-installable-target', 'request-rejected']),
message: z.string(),
}),
]);
diff --git a/packages/studio-server/src/preview-server/routes/element-install-plan.ts b/packages/studio-server/src/preview-server/routes/element-install-plan.ts
index 43eea0ac90..49adaead49 100644
--- a/packages/studio-server/src/preview-server/routes/element-install-plan.ts
+++ b/packages/studio-server/src/preview-server/routes/element-install-plan.ts
@@ -118,6 +118,13 @@ export const getElementInstallPlan = async ({
remotionRoot: string;
}) => {
validateElementForInstallation(element);
+ if (
+ destination.type === 'selected-media' &&
+ (element.isCaptionStyle !== true ||
+ element.installationMode !== 'component-owned-sequence')
+ ) {
+ throw new Error('The Element must be a component-owned caption style');
+ }
const componentName =
StudioProtocolInternals.getElementComponentNameFromSourceCode(
diff --git a/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
index 2a950bd4ec..b51b93991f 100644
--- a/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
@@ -69,6 +69,7 @@ export const insertBasicCaptionsHandler: ApiHandler<
},
});
const {output, logLine, nodePathRemappings} = insertBasicCaptions({
+ element: null,
input: fileContents,
nodePath,
captions,
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 022cf60118..48a4fc1735 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -7,6 +7,7 @@ import {
writeFileSync,
} from 'node:fs';
import path from 'node:path';
+import {CodemodsInternals} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
import type {
@@ -72,6 +73,7 @@ export const insertElementHandler: ApiHandler<
input: {
compositionFile,
compositionId,
+ captionTarget,
element,
installationName,
expectedFileState,
@@ -89,6 +91,17 @@ export const insertElementHandler: ApiHandler<
}) => {
let resolvedAssets: Array<{contents: Uint8Array; path: string}>;
try {
+ if (
+ captionTarget !== null &&
+ (element.isCaptionStyle !== true ||
+ element.installationMode !== 'component-owned-sequence' ||
+ newComposition !== null ||
+ compositionFile !== null ||
+ compositionId !== null)
+ ) {
+ throw new Error('Invalid caption style installation target');
+ }
+
StudioProtocolInternals.assertElementAssets(element.assets);
StudioProtocolInternals.assertElementAssetReferences(element);
resolvedAssets = await StudioProtocolInternals.resolveElementAssets({
@@ -246,16 +259,21 @@ export const insertElementHandler: ApiHandler<
}
const installDestination =
- newComposition === null
+ captionTarget !== null
? {
- type: 'current-composition' as const,
- compositionFile,
- compositionId,
+ type: 'selected-media' as const,
+ compositionFile: captionTarget.fileName,
}
- : {
- type: 'new-composition' as const,
- compositionFile,
- };
+ : newComposition === null
+ ? {
+ type: 'current-composition' as const,
+ compositionFile,
+ compositionId,
+ }
+ : {
+ type: 'new-composition' as const,
+ compositionFile,
+ };
const plan = await getElementInstallPlan({
installationName,
destination: installDestination,
@@ -366,10 +384,25 @@ export const insertElementHandler: ApiHandler<
position,
},
};
- const inserted = await insertJsxElementIntoComposition({
- ...insertionInput,
- sourceFileOverrides,
- });
+ const inserted =
+ captionTarget === null
+ ? await insertJsxElementIntoComposition({
+ ...insertionInput,
+ compositionFile,
+ compositionId,
+ sourceFileOverrides,
+ })
+ : (() => {
+ const fileName = plan.safePaths.compositionFileName;
+ const oldContents = readFileSync(fileName, 'utf-8');
+ const result = CodemodsInternals.insertBasicCaptions({
+ ...captionTarget,
+ input: oldContents,
+ importPath: plan.importPath,
+ element: {componentName: plan.componentName, initialProps},
+ });
+ return {...result, fileName, oldContents};
+ })();
if (
compositionCreation !== null &&
inserted.fileName !== compositionCreation.componentFilePath
diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
index 873bcd5be5..669c10165c 100644
--- a/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-install.ts
@@ -44,6 +44,7 @@ const deliverElementInstall = ({
durationInFrames: element.durationInFrames ?? null,
initialProps: element.initialProps ?? null,
installationMode: element.installationMode ?? null,
+ isCaptionStyle: element.isCaptionStyle ?? false,
},
from: null,
position: null,
diff --git a/packages/studio-server/src/test/insert-basic-captions.test.ts b/packages/studio-server/src/test/insert-basic-captions.test.ts
index 638aa3eb6b..74b184e515 100644
--- a/packages/studio-server/src/test/insert-basic-captions.test.ts
+++ b/packages/studio-server/src/test/insert-basic-captions.test.ts
@@ -131,6 +131,7 @@ test('wraps a root Audio in a fragment when adding captions', () => {
const input = `import {Audio} from 'remotion';
export const Comp = () => <Audio src="voice.mp3" />;`;
const {output} = insertBasicCaptions({
+ element: null,
input,
nodePath: lineContainingToNodePath(input, '<Audio'),
captions: [
@@ -182,6 +183,7 @@ export const Comp = () => <Audio src="voice.mp3" />;`;
},
];
const first = insertBasicCaptions({
+ element: null,
input,
nodePath: lineContainingToNodePath(input, '<Audio'),
captions,
@@ -190,6 +192,7 @@ export const Comp = () => <Audio src="voice.mp3" />;`;
importPath: localElement.importPath,
});
const second = insertBasicCaptions({
+ element: null,
input: first.output,
nodePath: lineContainingToNodePath(first.output, '<Audio'),
captions,
diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.ts
index 58d59a4c10..3f6c45d85a 100644
--- a/packages/studio-server/src/test/insert-element.test.ts
+++ b/packages/studio-server/src/test/insert-element.test.ts
@@ -78,12 +78,16 @@ const element: InsertElementRequest['element'] = {
durationInFrames: 72,
initialProps: null,
installationMode: null,
+ isCaptionStyle: false,
displayName: 'Lower Third',
slug: 'overlays/lower-third',
sourceCode: incomingElementSource,
};
-type InsertElementTestRequest = Omit<InsertElementRequest, 'premountFor'> & {
+type InsertElementTestRequest = Omit<
+ Extract<InsertElementRequest, {captionTarget: null}>,
+ 'premountFor'
+> & {
premountFor?: number | null;
};
@@ -157,6 +161,7 @@ const makeFixture = () => {
element,
expectedFileState,
from: null,
+ captionTarget: null,
overwriteExisting,
position: null,
undoRedoNavigation: null,
@@ -293,6 +298,7 @@ export const LowerThird = ({logoSrc, ...props}: {logoSrc: string} & SequenceProp
element: assetElement,
expectedFileState: null,
from: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -398,6 +404,7 @@ test('rejects oversized mixed Element assets before writing any files, regardles
element: {...element, assets: orderedAssets},
expectedFileState: null,
from: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -472,6 +479,7 @@ test('invalidates a new-composition install after an external component edit', a
element,
expectedFileState: {exists: false},
from: null,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -580,9 +588,11 @@ test('installs structured initial props on a component-owned Sequence', async ()
...element,
initialProps: structuredInitialProps,
installationMode: 'component-owned-sequence',
+ isCaptionStyle: false,
},
expectedFileState: null,
from: 30,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 120, y: 80},
undoRedoNavigation: null,
@@ -638,9 +648,11 @@ test('rejects contradictory component-owned installation props', async () => {
...element,
initialProps,
installationMode: 'component-owned-sequence',
+ isCaptionStyle: false,
},
expectedFileState: null,
from: 30,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 120, y: 80},
undoRedoNavigation: null,
@@ -670,6 +682,7 @@ test('keeps wrapped installation and passes initial props to its child', async (
},
expectedFileState: null,
from: 12,
+ captionTarget: null,
overwriteExisting: false,
position: {x: 40, y: 50},
undoRedoNavigation: null,
@@ -701,6 +714,7 @@ test('materializes independent props for two component-owned copies', async () =
...element,
initialProps: structuredInitialProps,
installationMode: 'component-owned-sequence' as const,
+ isCaptionStyle: false,
};
const first = await fixture.callHandlerWithInput({
installationName: null,
@@ -709,6 +723,7 @@ test('materializes independent props for two component-owned copies', async () =
element: componentOwnedElement,
expectedFileState: null,
from: 0,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -722,6 +737,7 @@ test('materializes independent props for two component-owned copies', async () =
element: componentOwnedElement,
expectedFileState: {exists: false},
from: 30,
+ captionTarget: null,
overwriteExisting: false,
position: null,
undoRedoNavigation: null,
@@ -766,6 +782,7 @@ test('installs independent named copies into the same and another composition',
expectedFileState: {exists: false},
from: null,
position: null,
+ captionTarget: null,
overwriteExisting: false,
undoRedoNavigation: null,
newComposition: null,
@@ -896,6 +913,7 @@ test.each(['../outside', 'nested/name', 'Uppercase', '', 'name.element.tsx'])(
expectedFileState: null,
from: null,
position: null,
+ captionTarget: null,
overwriteExisting: false,
undoRedoNavigation: null,
newComposition: null,
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 038b24e6b5..d1ad394d6e 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -16,10 +16,10 @@ import type {
_InternalTypes,
CannotUpdateSequenceReason,
CanUpdateEffectPropsResponse,
+ CanUpdateSequencePropSource,
CanUpdateSequencePropsResponseFalse,
CanUpdateSequencePropsResponseTrue,
CanUpdateSequencePropStatus,
- CanUpdateSequencePropSource,
ExtrapolateType,
InteractivitySchema,
InterpolateOutputOption,
@@ -102,6 +102,7 @@ export type InstallableElement = {
durationInFrames: number | null;
initialProps: Readonly<Record<string, ComponentPropValue>> | null;
installationMode: ElementInstallationMode | null;
+ isCaptionStyle: boolean;
slug: string;
displayName: string;
sourceCode: string;
@@ -1175,6 +1176,10 @@ export type ElementInstallExpectedFileState =
};
export type ElementInstallDestination =
+ | {
+ type: 'selected-media';
+ compositionFile: string;
+ }
| {
type: 'current-composition';
compositionFile: string;
@@ -1208,8 +1213,6 @@ export type PrepareElementInstallResponse =
export type InsertElementRequest = {
installationName: string | null;
- compositionFile: string;
- compositionId: string;
element: InstallableElement;
expectedFileState: ElementInstallExpectedFileState | null;
from: number | null;
@@ -1217,11 +1220,23 @@ export type InsertElementRequest = {
position: InsertableCompositionElementPosition | null;
overwriteExisting: boolean;
undoRedoNavigation: UndoRedoNavigation | null;
- newComposition: {
- options: NewCompositionOptions;
- symbolicatedStack: SymbolicatedStackFrame | null;
- } | null;
-};
+} & (
+ | {
+ captionTarget: InsertBasicCaptionsRequest;
+ compositionFile: null;
+ compositionId: null;
+ newComposition: null;
+ }
+ | {
+ captionTarget: null;
+ compositionFile: string;
+ compositionId: string;
+ newComposition: {
+ options: NewCompositionOptions;
+ symbolicatedStack: SymbolicatedStackFrame | null;
+ } | null;
+ }
+);
export type InsertElementFileConflict = {
filePath: string;
diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsx
index b64d46463a..e892b12b3b 100644
--- a/packages/studio/src/components/CurrentAsset.tsx
+++ b/packages/studio/src/components/CurrentAsset.tsx
@@ -364,6 +364,7 @@ export const AssetInfo: React.FC<{
setSelectedModal({
type: 'transcribe',
+ captionStyle: null,
src,
displayName: fileName,
audioStreamIndex: null,
diff --git a/packages/studio/src/components/ElementInstallRequestHandler.tsx b/packages/studio/src/components/ElementInstallRequestHandler.tsx
index d378b736e6..22a34ce483 100644
--- a/packages/studio/src/components/ElementInstallRequestHandler.tsx
+++ b/packages/studio/src/components/ElementInstallRequestHandler.tsx
@@ -35,6 +35,8 @@ export const ElementInstallRequestHandler: FC = () => {
const config = Internals.useUnsafeVideoConfig();
const {setSelectedModal} = useContext(SetSelectedModalContext);
const selectedModal = useContext(SelectedModalContext);
+ const selectedModalRef = useRef(selectedModal);
+ selectedModalRef.current = selectedModal;
const showingExperimentalNotice =
selectedModal?.type === 'browser-studio-experimental-notice';
const {previewServerState, subscribeToEvent} = useContext(
@@ -163,6 +165,23 @@ export const ElementInstallRequestHandler: FC = () => {
return;
}
+ const modal = selectedModalRef.current;
+ if (
+ modal?.type === 'transcribe' &&
+ modal.target !== null &&
+ (payload.element.isCaptionStyle !== true ||
+ payload.element.installationMode !== 'component-owned-sequence')
+ ) {
+ responsePort.postMessage({
+ success: false,
+ code: 'request-rejected',
+ message: 'This Element is not a caption style',
+ } satisfies InstallInStudioResult);
+ window.setTimeout(() => responsePort.close(), 1000);
+ showNotification('This Element is not a caption style', 4000);
+ return;
+ }
+
const request: ElementInstallRequest | null = canInstallElement
? {
clientId: previewServerClientId,
@@ -174,6 +193,7 @@ export const ElementInstallRequestHandler: FC = () => {
durationInFrames: payload.element.durationInFrames ?? null,
initialProps: payload.element.initialProps ?? null,
installationMode: payload.element.installationMode ?? null,
+ isCaptionStyle: payload.element.isCaptionStyle ?? false,
},
from: null,
id: crypto.randomUUID(),
@@ -221,6 +241,24 @@ export const ElementInstallRequestHandler: FC = () => {
useEffect(() => {
return subscribeToElementInstallRequests((request) => {
+ const modal = selectedModalRef.current;
+ if (modal?.type === 'transcribe' && modal.target !== null) {
+ if (
+ request.element.isCaptionStyle !== true ||
+ request.element.installationMode !== 'component-owned-sequence'
+ ) {
+ showNotification('This Element is not a caption style', 4000);
+ return;
+ }
+
+ setSelectedModal((current) =>
+ current?.type === 'transcribe' && current.target !== null
+ ? {...current, captionStyle: request}
+ : current,
+ );
+ return;
+ }
+
const shouldAddCompositionDefaults =
request.source.type !== 'drag-and-drop' &&
request.compositionFile !== null &&
@@ -245,7 +283,7 @@ export const ElementInstallRequestHandler: FC = () => {
: request;
setPendingRequests((requests) => [...requests, requestWithDefaults]);
});
- }, [config]);
+ }, [config, setSelectedModal]);
useEffect(() => {
if (!canInstallElement || showingExperimentalNotice) {
diff --git a/packages/studio/src/components/ElementLibraryFrame.tsx b/packages/studio/src/components/ElementLibraryFrame.tsx
new file mode 100644
index 0000000000..12922d3390
--- /dev/null
+++ b/packages/studio/src/components/ElementLibraryFrame.tsx
@@ -0,0 +1,76 @@
+import React, {useLayoutEffect, useRef, useState} from 'react';
+import {Spinner} from './Spinner';
+
+const contentStyle: React.CSSProperties = {
+ flex: 1,
+ minHeight: 0,
+ position: 'relative',
+};
+
+const iframeStyle: React.CSSProperties = {
+ border: 0,
+ colorScheme: 'dark',
+ height: '100%',
+ inset: 0,
+ position: 'absolute',
+ width: '100%',
+};
+
+const loadingStyle: React.CSSProperties = {
+ alignItems: 'center',
+ display: 'flex',
+ inset: 0,
+ justifyContent: 'center',
+ position: 'absolute',
+};
+
+export const ElementLibraryFrame: React.FC<{
+ readonly name: string;
+ readonly url: string;
+}> = ({name, url}) => {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [isLoaded, setIsLoaded] = useState(false);
+
+ useLayoutEffect(() => {
+ const iframe = iframeRef.current;
+ if (iframe === null) {
+ return;
+ }
+
+ setIsLoaded(false);
+ const onLoad = () => setIsLoaded(true);
+ iframe.addEventListener('load', onLoad);
+
+ // Studio is cross-origin isolated. A credentialless iframe may embed a
+ // library that does not set Cross-Origin-Resource-Policy headers.
+ iframe.setAttribute('credentialless', '');
+ const iframeUrl = new URL(url);
+ iframeUrl.searchParams.set('remotion-studio', 'true');
+ iframeUrl.searchParams.set('docusaurus-theme', 'dark');
+ iframe.src = iframeUrl.toString();
+
+ return () => {
+ iframe.removeEventListener('load', onLoad);
+ };
+ }, [url]);
+
+ return (
+ <div style={contentStyle}>
+ <iframe
+ ref={iframeRef}
+ allow="local-network-access; loopback-network"
+ data-remotion-element-library=""
+ style={{
+ ...iframeStyle,
+ visibility: isLoaded ? 'visible' : 'hidden',
+ }}
+ aria-label={`${name} library`}
+ />
+ {isLoaded ? null : (
+ <div style={loadingStyle} role="status" aria-label={`Loading ${name}`}>
+ <Spinner duration={0.5} size={24} />
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/ElementLibraryModal.tsx b/packages/studio/src/components/ElementLibraryModal.tsx
index abd6ca20ad..7c2af495e0 100644
--- a/packages/studio/src/components/ElementLibraryModal.tsx
+++ b/packages/studio/src/components/ElementLibraryModal.tsx
@@ -1,10 +1,4 @@
-import React, {
- useCallback,
- useContext,
- useLayoutEffect,
- useRef,
- useState,
-} from 'react';
+import React, {useCallback, useContext} from 'react';
import {GearIcon} from '../icons/gear';
import {
type ElementInstallModalState,
@@ -12,12 +6,12 @@ import {
} from '../state/modals';
import {ActionTooltip} from './ActionTooltip';
import {ElementInstallConfirmation} from './ElementInstallConfirmation';
+import {ElementLibraryFrame} from './ElementLibraryFrame';
import type {RenderInlineAction} from './InlineAction';
import {InlineAction} from './InlineAction';
import {getMaxModalHeight, getMaxModalWidth} from './ModalContainer';
import {ModalHeader} from './ModalHeader';
import {DismissableModal} from './NewComposition/DismissableModal';
-import {Spinner} from './Spinner';
const panelStyle: React.CSSProperties = {
display: 'flex',
@@ -27,36 +21,11 @@ const panelStyle: React.CSSProperties = {
width: getMaxModalWidth(1400),
};
-const contentStyle: React.CSSProperties = {
- flex: 1,
- minHeight: 0,
- position: 'relative',
-};
-
-const iframeStyle: React.CSSProperties = {
- border: 0,
- colorScheme: 'dark',
- height: '100%',
- inset: 0,
- position: 'absolute',
- width: '100%',
-};
-
-const loadingStyle: React.CSSProperties = {
- alignItems: 'center',
- display: 'flex',
- inset: 0,
- justifyContent: 'center',
- position: 'absolute',
-};
-
export const ElementLibraryModal: React.FC<{
readonly name: string;
readonly url: string;
readonly installState: ElementInstallModalState | null;
}> = ({name, url, installState}) => {
- const iframeRef = useRef<HTMLIFrameElement>(null);
- const [isLoaded, setIsLoaded] = useState(false);
const {setSelectedModal} = useContext(SetSelectedModalContext);
const openElementSettings = useCallback(() => {
setSelectedModal({
@@ -71,29 +40,6 @@ export const ElementLibraryModal: React.FC<{
return <GearIcon color={color} height={16} width={16} />;
}, []);
- useLayoutEffect(() => {
- const iframe = iframeRef.current;
- if (iframe === null) {
- return;
- }
-
- setIsLoaded(false);
- const onLoad = () => setIsLoaded(true);
- iframe.addEventListener('load', onLoad);
-
- // Studio is cross-origin isolated. A credentialless iframe may embed a
- // library that does not set Cross-Origin-Resource-Policy headers.
- iframe.setAttribute('credentialless', '');
- const iframeUrl = new URL(url);
- iframeUrl.searchParams.set('remotion-studio', 'true');
- iframeUrl.searchParams.set('docusaurus-theme', 'dark');
- iframe.src = iframeUrl.toString();
-
- return () => {
- iframe.removeEventListener('load', onLoad);
- };
- }, [url]);
-
return (
<DismissableModal panelStyle={panelStyle}>
<ModalHeader
@@ -114,27 +60,7 @@ export const ElementLibraryModal: React.FC<{
</ActionTooltip>
}
/>
- <div style={contentStyle}>
- <iframe
- ref={iframeRef}
- allow="local-network-access; loopback-network"
- data-remotion-element-library=""
- style={{
- ...iframeStyle,
- visibility: isLoaded ? 'visible' : 'hidden',
- }}
- aria-label={`${name} library`}
- />
- {isLoaded ? null : (
- <div
- style={loadingStyle}
- role="status"
- aria-label={`Loading ${name}`}
- >
- <Spinner duration={0.5} size={24} />
- </div>
- )}
- </div>
+ <ElementLibraryFrame name={name} url={url} />
{installState === null ? null : (
<ElementInstallConfirmation state={installState} />
)}
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index 64e5001a98..af85af3230 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -185,6 +185,7 @@ const SequenceSourceQuickActions: React.FC<{
const nodePath = selection.nodePathInfo.sequenceSubscriptionKey;
setSelectedModal({
type: 'transcribe',
+ captionStyle: null,
src: mediaSequence.src,
displayName: getMediaFileName(
mediaSequence.src,
diff --git a/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx b/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
index b438902a3b..167459456b 100644
--- a/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
+++ b/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
@@ -13,6 +13,7 @@ import {writeStaticFile} from '../../api/write-static-file';
import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {installRequiredPackages} from '../../helpers/install-required-package';
import {callApi} from '../call-api';
+import {installElement, prepareElementInstall} from '../element-install-api';
import {resampleMediaTo16Khz} from '../Transcription/resample-media-to-16-khz';
import type {CaptionJob} from './caption-job-types';
import {RenderQueueContext} from './context';
@@ -121,6 +122,86 @@ export const CaptionQueueProcessor: React.FC = () => {
contents: JSON.stringify(captions, null, 2),
filePath: job.outName,
});
+ } else if (job.captionStyle !== null) {
+ const {element} = job.captionStyle;
+ updateCaptionJobProgress(job.id, {
+ message: `Adding ${element.displayName}...`,
+ value: 0.95,
+ });
+ const hash = await crypto.subtle.digest(
+ 'SHA-256',
+ new TextEncoder().encode(element.sourceCode),
+ );
+ const sourceHash = Array.from(new Uint8Array(hash), (byte) =>
+ byte.toString(16).padStart(2, '0'),
+ ).join('');
+ const baseName = element.slug.split('/').at(-1);
+ let installed = false;
+ for (let index = 0; index < 1000; index++) {
+ signal.throwIfAborted();
+ const installationName = `${baseName}${index === 0 ? '' : `-${index + 1}`}`;
+ const preflight = await prepareElementInstall({
+ installationName,
+ destination: {
+ type: 'selected-media',
+ compositionFile: job.target.fileName,
+ },
+ element,
+ });
+ if (!preflight.success) {
+ throw new Error(preflight.reason);
+ }
+
+ const {expectedFileState} = preflight.plan;
+ if (
+ expectedFileState.exists &&
+ expectedFileState.sourceHash !== sourceHash
+ ) {
+ continue;
+ }
+
+ if (getBrowserStudioOperations() === null) {
+ await installRequiredPackages(element.dependencies);
+ }
+
+ signal.throwIfAborted();
+ const response = await installElement({
+ installationName,
+ compositionFile: null,
+ compositionId: null,
+ captionTarget: {
+ fileName: job.target.fileName,
+ nodePath: job.target.nodePath.nodePath,
+ durationInFrames: job.target.durationInFrames,
+ premountFor: job.target.premountFor,
+ captions,
+ },
+ element,
+ expectedFileState,
+ from: null,
+ premountFor: job.target.premountFor,
+ position: null,
+ overwriteExisting: expectedFileState.exists,
+ undoRedoNavigation: null,
+ newComposition: null,
+ });
+ if (!response.success) {
+ throw new Error(
+ response.type === 'error'
+ ? response.reason
+ : `Element file changed: ${response.conflict.filePath}`,
+ );
+ }
+
+ installed = true;
+ break;
+ }
+
+ if (!installed) {
+ throw new Error(
+ 'Could not find an available filename for the caption style',
+ );
+ }
} else {
updateCaptionJobProgress(job.id, {
message: 'Adding Basic captions...',
diff --git a/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx b/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
index 3312565e43..3ac629c279 100644
--- a/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
+++ b/packages/studio/src/components/RenderQueue/RenderQueueRepeat.tsx
@@ -30,6 +30,7 @@ export const RenderQueueRepeatItem: React.FC<{
if (job.type === 'caption') {
setSelectedModal({
type: 'transcribe',
+ captionStyle: job.captionStyle,
src: job.src,
displayName: job.displayName,
audioStreamIndex: job.audioStreamIndex,
diff --git a/packages/studio/src/components/RenderQueue/caption-job-types.ts b/packages/studio/src/components/RenderQueue/caption-job-types.ts
index 9cf8c8fb72..d6fb9834d2 100644
--- a/packages/studio/src/components/RenderQueue/caption-job-types.ts
+++ b/packages/studio/src/components/RenderQueue/caption-job-types.ts
@@ -1,3 +1,4 @@
+import type {ElementInstallRequest} from '@remotion/studio-shared';
import type {
WhisperWebGpuModel,
WhisperWebGpuTask,
@@ -20,6 +21,7 @@ type CaptionJobStatus =
};
export type AddCaptionJobParams = {
+ captionStyle: ElementInstallRequest | null;
src: string;
displayName: string;
audioStreamIndex: number | null;
diff --git a/packages/studio/src/components/Transcription/TranscriptionModal.tsx b/packages/studio/src/components/Transcription/TranscriptionModal.tsx
index 5e0cd8aa56..2a22b558c8 100644
--- a/packages/studio/src/components/Transcription/TranscriptionModal.tsx
+++ b/packages/studio/src/components/Transcription/TranscriptionModal.tsx
@@ -16,6 +16,7 @@ import React, {
import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {BLUE_DISABLED, LIGHT_TEXT, WHITE} from '../../helpers/colors';
import {getFileManagerName} from '../../helpers/get-file-manager-name';
+import {BrowseElementsIcon} from '../../icons/browse-elements';
import {Checkmark} from '../../icons/Checkmark';
import {ExpandedFolderIconSolid} from '../../icons/folder';
import {GearIcon} from '../../icons/gear';
@@ -26,10 +27,12 @@ import {SetSelectedModalContext} from '../../state/modals';
import {SidebarContext} from '../../state/sidebar';
import {Button} from '../Button';
import {Checkbox} from '../Checkbox';
+import {ElementLibraryFrame} from '../ElementLibraryFrame';
import type {RenderInlineAction} from '../InlineAction';
import {InlineAction} from '../InlineAction';
import {Spacing} from '../layout';
import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';
+import {getMaxModalHeight, getMaxModalWidth} from '../ModalContainer';
import {ModalHeader} from '../ModalHeader';
import type {ComboboxValue} from '../NewComposition/ComboBox';
import {Combobox} from '../NewComposition/ComboBox';
@@ -57,6 +60,7 @@ import {
import {RenderModalHr} from '../RenderModal/RenderModalHr';
import {openInFileExplorer} from '../RenderQueue/actions';
import {RenderQueueContext} from '../RenderQueue/context';
+import {useSettings} from '../SettingsContext';
import {VerticalTab} from '../Tabs/vertical';
import {useModelCacheStatus} from '../use-model-cache-status';
import {useStaticFiles} from '../use-static-files';
@@ -80,7 +84,7 @@ const DEFAULT_REPETITION_PENALTY = 1;
const DEFAULT_NO_REPEAT_NGRAM_SIZE = 0;
const MAX_CHUNK_LENGTH_IN_SECONDS = 30;
-type Tab = 'transcribe' | 'advanced' | 'models';
+type Tab = 'transcribe' | 'advanced' | 'models' | 'styles';
type SupportState =
| {type: 'checking'}
@@ -702,11 +706,41 @@ const AdvancedSettings: React.FC<{
export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
audioStreamIndex,
+ captionStyle,
displayName,
requestInit,
src,
target,
}) => {
+ const [acceptedCaptionStyleId, setAcceptedCaptionStyleId] = useState<
+ string | null
+ >(null);
+ const [libraryUrl, setLibraryUrl] = useState(
+ 'https://www.remotion.dev/elements/captions',
+ );
+ const {studioRuntimeConfig} = useSettings();
+ const libraryOptions: ComboboxValue[] = [
+ {
+ url: 'https://www.remotion.dev/elements/captions',
+ displayName: 'Remotion captions',
+ },
+ ...(studioRuntimeConfig?.elementLibraries ?? []).filter(
+ ({url}) =>
+ url !== 'https://www.remotion.dev/elements' &&
+ url !== 'https://www.remotion.dev/elements/captions',
+ ),
+ ].map(({url, displayName: libraryName}) => ({
+ type: 'item',
+ id: url,
+ value: url,
+ label: libraryName ?? new URL(url).host,
+ leftItem: url === libraryUrl ? <Checkmark /> : null,
+ keyHint: null,
+ quickSwitcherLabel: null,
+ subMenu: null,
+ disabled: false,
+ onClick: () => setLibraryUrl(url),
+ }));
const [tab, setTab] = useState<Tab>('transcribe');
const isModelCached = useCallback(
(model: WhisperWebGpuModel) => isWhisperModelCached({model}),
@@ -809,13 +843,17 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
supportState.type === 'supported' &&
outputValidationMessage === null &&
chunkValidationMessage === null &&
- decodingValidationMessage === null;
+ decodingValidationMessage === null &&
+ (captionStyle === null || acceptedCaptionStyleId === captionStyle.id);
const transcribeDisabledReason =
supportState.type === 'checking'
? 'Checking WebGPU support'
: supportState.type === 'unsupported'
? supportState.message
- : (outputValidationMessage ??
+ : ((captionStyle !== null && acceptedCaptionStyleId !== captionStyle.id
+ ? 'Allow installing the selected caption style first'
+ : null) ??
+ outputValidationMessage ??
chunkValidationMessage ??
decodingValidationMessage ??
undefined);
@@ -838,11 +876,15 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
}
addCaptionJob({
+ captionStyle,
src,
displayName,
audioStreamIndex,
requestInit,
- outName: target === null ? outName : 'Basic captions',
+ outName:
+ target === null
+ ? outName
+ : (captionStyle?.element.displayName ?? 'Simple captions'),
target,
model: selectedModel,
language: modelInfo.multilingual ? selectedLanguage : null,
@@ -864,6 +906,7 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
addCaptionJob,
audioStreamIndex,
canTranscribe,
+ captionStyle,
chunkLengthInSeconds,
displayName,
doSample,
@@ -889,8 +932,61 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
return (
<DismissableModal ariaLabel={title}>
- <div style={transcriptionModalStyle}>
+ <div
+ style={{
+ ...transcriptionModalStyle,
+ ...(tab === 'styles'
+ ? {height: getMaxModalHeight(850), width: getMaxModalWidth(1200)}
+ : {}),
+ }}
+ >
<ModalHeader title={title} />
+ {captionStyle === null ? null : (
+ <div
+ style={{
+ padding: '8px 16px',
+ maxHeight: 160,
+ overflowY: 'auto',
+ flexShrink: 0,
+ }}
+ >
+ <div style={{fontSize: 13}}>
+ {captionStyle.element.displayName} from{' '}
+ {'origin' in captionStyle.source
+ ? (captionStyle.source.origin ?? 'an unverified source')
+ : 'an unverified drag-and-drop payload'}
+ </div>
+ <div style={{fontSize: 13}}>
+ Dependencies:{' '}
+ {captionStyle.element.dependencies
+ .map(({name, version}) =>
+ version === null ? name : `${name}@${version}`,
+ )
+ .join(', ') || 'None'}
+ . This style can execute arbitrary code.
+ </div>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 8,
+ fontSize: 13,
+ }}
+ >
+ <Checkbox
+ checked={acceptedCaptionStyleId === captionStyle.id}
+ onChange={(event) =>
+ setAcceptedCaptionStyleId(
+ event.target.checked ? captionStyle.id : null,
+ )
+ }
+ inputId="allow-caption-style"
+ name="allow-caption-style"
+ />
+ Allow installing this style and running its code
+ </label>
+ </div>
+ )}
<div style={container}>
<div style={flexer} />
<Button
@@ -922,6 +1018,20 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
>
Transcribe
</VerticalTab>
+ {target === null ? null : (
+ <VerticalTab
+ style={horizontalTab}
+ selected={tab === 'styles'}
+ onClick={() => setTab('styles')}
+ renderIcon={(color) => (
+ <div style={iconContainer}>
+ <BrowseElementsIcon color={color} style={icon} />
+ </div>
+ )}
+ >
+ Styles
+ </VerticalTab>
+ )}
<VerticalTab
style={horizontalTab}
selected={tab === 'models'}
@@ -996,6 +1106,43 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
validationMessage={chunkValidationMessage}
/>
</div>
+ {tab === 'styles' && target !== null ? (
+ <div
+ style={{
+ ...optionsPanel,
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}
+ >
+ <div style={{padding: 16}}>
+ <div style={{fontSize: 13, marginBottom: 8}} role="status">
+ Selected style:{' '}
+ {captionStyle?.element.displayName ?? 'Simple captions'}
+ </div>
+ <Button
+ onClick={() =>
+ setSelectedModal((modal) =>
+ modal?.type === 'transcribe'
+ ? {...modal, captionStyle: null}
+ : modal,
+ )
+ }
+ disabled={captionStyle === null}
+ >
+ Use Simple captions
+ </Button>
+ {libraryOptions.length > 1 ? (
+ <Combobox
+ values={libraryOptions}
+ selectedId={libraryUrl}
+ aria-label="Caption style library"
+ style={{marginTop: 8}}
+ />
+ ) : null}
+ </div>
+ <ElementLibraryFrame name="Caption styles" url={libraryUrl} />
+ </div>
+ ) : null}
<Models
description={
'Models are downloaded automatically when needed.\nYou can also manage the browser cache here.'
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index 9765df88c1..d9f3365116 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -607,6 +607,7 @@ export const WebMcp: FC = () => {
}
const jobId = addCaptionJob({
+ captionStyle: null,
audioStreamIndex: null,
chunkLengthInSeconds,
displayName,
diff --git a/packages/studio/src/components/handle-drop.ts b/packages/studio/src/components/handle-drop.ts
index e7232b0971..01edc367bf 100644
--- a/packages/studio/src/components/handle-drop.ts
+++ b/packages/studio/src/components/handle-drop.ts
@@ -142,6 +142,7 @@ export const handleDrop = async ({
durationInFrames: element.element.durationInFrames ?? null,
initialProps: element.element.initialProps ?? null,
installationMode: element.element.installationMode ?? null,
+ isCaptionStyle: element.element.isCaptionStyle ?? false,
},
from,
position: getElementPositionForDrop({
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 47651c971f..5a30c11440 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -1375,6 +1375,7 @@ export const insertElement = async ({
}
const response = await installElement({
+ captionTarget: null,
installationName,
compositionFile,
compositionId,
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index 8ac9ce2047..f69fe08472 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -160,6 +160,7 @@ export type AssetSelectionModalState = {
export type TranscriptionModalState = {
type: 'transcribe';
+ captionStyle: ElementInstallRequest | null;
src: string;
displayName: string;
audioStreamIndex: number | null;
diff --git a/packages/studio/src/test/caption-queue-processor.test.tsx b/packages/studio/src/test/caption-queue-processor.test.tsx
index 1cf16c4581..eb70eb6dd2 100644
--- a/packages/studio/src/test/caption-queue-processor.test.tsx
+++ b/packages/studio/src/test/caption-queue-processor.test.tsx
@@ -235,6 +235,7 @@ test('downloads a model in the queued job before transcribing', async () => {
let jobId = '';
act(() => {
jobId = getContext().addCaptionJob({
+ captionStyle: null,
displayName: 'interview.wav',
audioStreamIndex: 2,
requestInit: {
@@ -372,6 +373,7 @@ test('downloads a model in the queued job before transcribing', async () => {
let inlineJobId = '';
act(() => {
inlineJobId = getContext().addCaptionJob({
+ captionStyle: null,
displayName: 'clip.mp4',
audioStreamIndex: null,
requestInit: null,
diff --git a/packages/studio/src/test/queue-job-errors.test.tsx b/packages/studio/src/test/queue-job-errors.test.tsx
index a3ca0fbf7c..298df33be2 100644
--- a/packages/studio/src/test/queue-job-errors.test.tsx
+++ b/packages/studio/src/test/queue-job-errors.test.tsx
@@ -33,6 +33,7 @@ afterEach(() => {
});
const captionJob: CaptionJob = {
+ captionStyle: null,
id: 'caption-job',
type: 'caption',
startedAt: 0,
diff --git a/packages/studio/src/test/render-queue-scheduler.test.tsx b/packages/studio/src/test/render-queue-scheduler.test.tsx
index bae68d360d..323c0e1978 100644
--- a/packages/studio/src/test/render-queue-scheduler.test.tsx
+++ b/packages/studio/src/test/render-queue-scheduler.test.tsx
@@ -25,6 +25,7 @@ const compositionRef: CompositionRef = {
};
const makeCaptionParams = (displayName: string): AddCaptionJobParams => ({
+ captionStyle: null,
src: `/${displayName}`,
displayName,
audioStreamIndex: null,
diff --git a/packages/studio/src/test/renders-tab-caption-jobs.test.tsx b/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
index 1f1dfcb9c7..bb7add09a5 100644
--- a/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
+++ b/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
@@ -46,6 +46,7 @@ const renderWithCaptionJob = (job: CaptionJob) => {
};
const baseJob = {
+ captionStyle: null,
id: 'caption-job',
type: 'caption',
startedAt: 0,
diff --git a/packages/studio/src/test/transcription-modal.test.tsx b/packages/studio/src/test/transcription-modal.test.tsx
index 652f5a0260..1cda7f8b18 100644
--- a/packages/studio/src/test/transcription-modal.test.tsx
+++ b/packages/studio/src/test/transcription-modal.test.tsx
@@ -8,6 +8,7 @@ import {
waitFor,
} from '@testing-library/react';
import type {AddCaptionJobParams} from '../components/RenderQueue/caption-job-types';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
const selectComboboxItem = async (
combobox: HTMLElement,
@@ -99,6 +100,7 @@ test('serializes transcription modal settings into caption jobs', async () => {
});
try {
+ const {SettingsProvider} = await import('../components/SettingsContext');
const {TranscriptionModal} =
await import('../components/Transcription/TranscriptionModal');
const {RenderQueueContext} =
@@ -114,44 +116,56 @@ test('serializes transcription modal settings into caption jobs', async () => {
} as const;
render(
- <SetSelectedModalContext.Provider
- value={{setSelectedModal: () => undefined}}
+ <StudioServerConnectionCtx.Provider
+ value={{
+ previewServerState: {type: 'init'},
+ configFileChangeRevision: 0,
+ restartRequired: false,
+ subscribeToEvent: () => () => undefined,
+ }}
>
- <SidebarContext.Provider
- value={{
- rightSidebarTemporaryExpansion: false,
- setRightSidebarTemporaryExpansion: () => undefined,
- sidebarCollapsedDuringDrag: null,
- sidebarCollapsedStateLeft: 'collapsed',
- sidebarCollapsedStateRight: 'collapsed',
- setSidebarCollapsedDuringDrag: () => undefined,
- setSidebarCollapsedState: () => undefined,
- }}
- >
- <RenderQueueContext.Provider
- value={
- {
- captionJobs: [],
- addCaptionJob: (params: AddCaptionJobParams) => {
- submittedJobs.push(params);
- return `caption-job-${submittedJobs.length}`;
- },
- } as never
- }
+ <SettingsProvider>
+ <SetSelectedModalContext.Provider
+ value={{setSelectedModal: () => undefined}}
>
- <StaticFilesProvider>
- <TranscriptionModal
- type="transcribe"
- audioStreamIndex={2}
- displayName="interview.wav"
- requestInit={requestInit}
- src="/media/interview.wav"
- target={null}
- />
- </StaticFilesProvider>
- </RenderQueueContext.Provider>
- </SidebarContext.Provider>
- </SetSelectedModalContext.Provider>,
+ <SidebarContext.Provider
+ value={{
+ rightSidebarTemporaryExpansion: false,
+ setRightSidebarTemporaryExpansion: () => undefined,
+ sidebarCollapsedDuringDrag: null,
+ sidebarCollapsedStateLeft: 'collapsed',
+ sidebarCollapsedStateRight: 'collapsed',
+ setSidebarCollapsedDuringDrag: () => undefined,
+ setSidebarCollapsedState: () => undefined,
+ }}
+ >
+ <RenderQueueContext.Provider
+ value={
+ {
+ captionJobs: [],
+ addCaptionJob: (params: AddCaptionJobParams) => {
+ submittedJobs.push(params);
+ return `caption-job-${submittedJobs.length}`;
+ },
+ } as never
+ }
+ >
+ <StaticFilesProvider>
+ <TranscriptionModal
+ type="transcribe"
+ captionStyle={null}
+ audioStreamIndex={2}
+ displayName="interview.wav"
+ requestInit={requestInit}
+ src="/media/interview.wav"
+ target={null}
+ />
+ </StaticFilesProvider>
+ </RenderQueueContext.Provider>
+ </SidebarContext.Provider>
+ </SetSelectedModalContext.Provider>
+ </SettingsProvider>
+ </StudioServerConnectionCtx.Provider>,
);
screen.getByRole('dialog', {
@@ -283,6 +297,7 @@ test('serializes transcription modal settings into caption jobs', async () => {
fireEvent.click(submit);
const commonJob = {
+ captionStyle: null,
audioStreamIndex: 2,
chunkLengthInSeconds: 22,
displayName: 'interview.wav',
diff --git a/packages/studio/src/test/whisper-webgpu-capability.test.tsx b/packages/studio/src/test/whisper-webgpu-capability.test.tsx
index 305ff0a608..393ea05dfb 100644
--- a/packages/studio/src/test/whisper-webgpu-capability.test.tsx
+++ b/packages/studio/src/test/whisper-webgpu-capability.test.tsx
@@ -1,6 +1,7 @@
import {afterEach, expect, spyOn, test} from 'bun:test';
import {cleanup, fireEvent, render, waitFor} from '@testing-library/react';
import {ModalsProvider} from '../components/ModalsProvider';
+import {SettingsProvider} from '../components/SettingsContext';
import {TranscriptionModalWithOptionalWhisper} from '../components/Transcription/TranscriptionModalWithOptionalWhisper';
import {
isWhisperWebGpuInstalled,
@@ -8,6 +9,7 @@ import {
} from '../components/Transcription/whisper-webgpu-capability';
import {VIDEO_MATTING_PACKAGE} from '../components/VideoMatting/video-matting-capability';
import {VideoMattingModalWithOptionalPackage} from '../components/VideoMatting/VideoMattingModalWithOptionalPackage';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
import {
TRANSFORMERS_PACKAGE,
withRequiredAuxiliaryPackages,
@@ -76,18 +78,30 @@ test('opens transcription after installing Whisper without restarting', async ()
);
try {
const {container, getByRole, getByText} = render(
- <ModalsProvider>
- <TranscriptionModalWithOptionalWhisper
- state={{
- type: 'transcribe',
- src: '/voice.wav',
- displayName: 'voice.wav',
- audioStreamIndex: null,
- requestInit: null,
- target: null,
- }}
- />
- </ModalsProvider>,
+ <StudioServerConnectionCtx.Provider
+ value={{
+ previewServerState: {type: 'init'},
+ configFileChangeRevision: 0,
+ restartRequired: false,
+ subscribeToEvent: () => () => undefined,
+ }}
+ >
+ <SettingsProvider>
+ <ModalsProvider>
+ <TranscriptionModalWithOptionalWhisper
+ state={{
+ type: 'transcribe',
+ captionStyle: null,
+ src: '/voice.wav',
+ displayName: 'voice.wav',
+ audioStreamIndex: null,
+ requestInit: null,
+ target: null,
+ }}
+ />
+ </ModalsProvider>
+ </SettingsProvider>
+ </StudioServerConnectionCtx.Provider>,
);
fireEvent.click(getByRole('button', {name: 'Install packages'}));