🎥 Make videos programmatically with React
`@remotion/studio`: Import captions from public folder
JonnyBurgerf0b478335c71
diff --git a/packages/studio/src/components/CaptionInspector.tsx b/packages/studio/src/components/CaptionInspector.tsxindex 162ca36fca..ae453b4ac9 100644--- a/packages/studio/src/components/CaptionInspector.tsx+++ b/packages/studio/src/components/CaptionInspector.tsx@@ -2,6 +2,7 @@ import type {Caption} from '@remotion/captions';import React, {useCallback, useRef, useState} from 'react';import {CURRENT_COLOR, LIGHT_TEXT} from '../helpers/colors';import {UploadIcon} from '../icons/upload';+import {SetSelectedModalContext} from '../state/modals';import {Button} from './Button';import {CaptionTextEditor} from './CaptionTextEditor';import {CollapsibleInspectorSectionHeader} from './InspectorPanel/CollapsibleInspectorSectionHeader';@@ -46,12 +47,17 @@ export const CaptionInspector: React.FC<{}) => {const fileInput = useRef<HTMLInputElement>(null);const [isImporting, setIsImporting] = useState(false);+ const {setSelectedModal} = React.useContext(SetSelectedModalContext);const importCaptions = useCallback(- async (event: React.ChangeEvent<HTMLInputElement>) => {- const file = event.currentTarget.files?.[0];- event.currentTarget.value = '';- if (!file || onReplaceCaptions === null) {+ async ({+ fileName,+ contents,+ }: {+ fileName: string;+ contents: Promise<string>;+ }) => {+ if (onReplaceCaptions === null) {return;}@@ -59,13 +65,13 @@ export const CaptionInspector: React.FC<{try {onReplaceCaptions(parseCaptionFile({- fileName: file.name,- contents: await file.text(),+ fileName,+ contents: await contents,}),);} catch (error) {showNotification(- `Could not import ${file.name}: ${error instanceof Error ? error.message : String(error)}`,+ `Could not import ${fileName}: ${error instanceof Error ? error.message : String(error)}`,5000,);} finally {@@ -75,6 +81,40 @@ export const CaptionInspector: React.FC<{[onReplaceCaptions],);+ const onFileSelected = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ const file = event.currentTarget.files?.[0];+ event.currentTarget.value = '';+ if (!file) {+ return;+ }++ importCaptions({fileName: file.name, contents: file.text()}).catch(+ () => undefined,+ );+ },+ [importCaptions],+ );++ const openCaptionSelection = useCallback(() => {+ setSelectedModal({+ type: 'quick-switcher',+ mode: 'assets',+ invocationTimestamp: Date.now(),+ assetSelection: {+ initialQuery: 'type:json',+ onSelectFile: () => fileInput.current?.click(),+ onSelected: (asset) => {+ return importCaptions({+ fileName: asset.name,+ contents: fetch(asset.src).then((response) => response.text()),+ }).catch(() => undefined);+ },+ },+ compositionSelection: null,+ });+ }, [importCaptions, setSelectedModal]);+return (<><InspectorSectionHeader>@@ -88,7 +128,7 @@ export const CaptionInspector: React.FC<{accept=".json"aria-label="Import captions file"hidden- onChange={importCaptions}+ onChange={onFileSelected}type="file"/><Button@@ -98,7 +138,7 @@ export const CaptionInspector: React.FC<{gap: 4,}}disabled={isImporting}- onClick={() => fileInput.current?.click()}+ onClick={openCaptionSelection}size="condensed"title={importTooltip}>diff --git a/packages/studio/src/test/caption-inspector-import.test.tsx b/packages/studio/src/test/caption-inspector-import.test.tsxnew file mode 100644index 0000000000..24ca88fe72--- /dev/null+++ b/packages/studio/src/test/caption-inspector-import.test.tsx@@ -0,0 +1,86 @@+import {afterEach, expect, test} from 'bun:test';+import type {Caption} from '@remotion/captions';+import {act, cleanup, fireEvent, render, screen} from '@testing-library/react';+import {CaptionInspector} from '../components/CaptionInspector';+import {SetSelectedModalContext, type ModalState} from '../state/modals';++afterEach(cleanup);++test('imports captions from a JSON file in the public folder', async () => {+ let selectedModal: ModalState | null = null;+ const importResult: {captions: Caption[] | null} = {captions: null};+ const previousFetch = globalThis.fetch;+ globalThis.fetch = ((input) => {+ expect(input).toBe('/captions.json');+ return Promise.resolve(+ new Response(+ JSON.stringify([+ {+ text: 'From public folder',+ startMs: 0,+ endMs: 1000,+ timestampMs: null,+ confidence: null,+ },+ ]),+ ),+ );+ }) as typeof fetch;++ try {+ render(+ <SetSelectedModalContext.Provider+ value={{+ setSelectedModal: (update) => {+ selectedModal =+ typeof update === 'function' ? update(selectedModal) : update;+ },+ }}+ >+ <CaptionInspector+ captions={[]}+ expanded={false}+ onTextChange={() => undefined}+ onTextSave={null}+ onTextCancel={null}+ onReplaceCaptions={(captions) => {+ importResult.captions = captions;+ }}+ onToggle={() => undefined}+ readOnly={false}+ readOnlyTitle={null}+ />+ </SetSelectedModalContext.Provider>,+ );++ fireEvent.click(screen.getByRole('button', {name: 'Import'}));+ const modal = selectedModal as ModalState | null;+ if (modal?.type !== 'quick-switcher' || modal.assetSelection === null) {+ throw new Error('Expected asset Quick Switcher to open');+ }++ const {assetSelection} = modal;++ expect(assetSelection.initialQuery).toBe('type:json');+ await act(async () => {+ await (assetSelection.onSelected({+ lastModified: 0,+ name: 'captions.json',+ sizeInBytes: 1,+ src: '/captions.json',+ }) as unknown as Promise<void>);+ });++ expect(importResult.captions).toEqual([+ {+ text: 'From public folder',+ startMs: 0,+ endMs: 1000,+ timestampMs: null,+ confidence: null,+ },+ ]);+ } finally {+ globalThis.fetch = previousFetch;+ }+});