Branchwell

AI Resource Pro / portrait-video · airesourcepro.com / src / components / TikTokCaptions.tsx

1import React, { useCallback, useEffect, useState } from "react";
2import {
3 Sequence,
4 staticFile,
5 useCurrentFrame,
6 useVideoConfig,
7 continueRender,
8 delayRender,
9 spring,
10 interpolate,
11} from "remotion";
12import { createTikTokStyleCaptions } from "@remotion/captions";
13import type { Caption } from "@remotion/captions";
14import { fontFamily } from "../fonts";
15
16interface TikTokCaptionsProps {
17 captionsFile: string;
18 highlightColor?: string;
19 audioStartFrame?: number;
20}
21
22export const TikTokCaptions: React.FC<TikTokCaptionsProps> = ({
23 captionsFile,
24 highlightColor = "#43ACE9",
25 audioStartFrame = 0,
26}) => {
27 const [pages, setPages] = useState<
28 ReturnType<typeof createTikTokStyleCaptions>["pages"]
29 >([]);
30 const [handle] = useState(() => delayRender());
31 const { fps } = useVideoConfig();
32 const frame = useCurrentFrame();
33
34 const fetchCaptions = useCallback(async () => {
35 const res = await fetch(staticFile(captionsFile));
36 const captions: Caption[] = await res.json();
37 const { pages: rawPages } = createTikTokStyleCaptions({
38 captions,
39 combineTokensWithinMilliseconds: 100,
40 });
41
42 // Split pages that would exceed 2 lines - word-aware splitting
43 const maxWordsPerPage = 4; // ~2 lines worth of words
44 const splitPages = rawPages.flatMap(page => {
45 if (!page.tokens || page.tokens.length === 0) return [page];
46
47 // If page has 6 or fewer words, keep it as-is
48 if (page.tokens.length <= maxWordsPerPage) {
49 return [page];
50 }
51
52 // Split into smaller pages by word count
53 const result: typeof rawPages = [];
54 let currentTokens: typeof page.tokens = [];
55
56 for (const token of page.tokens) {
57 if (!token || !token.text) continue;
58
59 currentTokens.push(token);
60
61 // Create new page when we reach max words
62 if (currentTokens.length >= maxWordsPerPage) {
63 const firstToken = currentTokens[0];
64 const lastToken = currentTokens[currentTokens.length - 1];
65 if (firstToken && lastToken && firstToken.fromMs !== undefined && lastToken.toMs !== undefined) {
66 result.push({
67 tokens: currentTokens,
68 text: currentTokens.map(t => t.text).join(' '),
69 startMs: firstToken.fromMs,
70 durationMs: lastToken.toMs - firstToken.fromMs,
71 });
72 }
73 currentTokens = [];
74 }
75 }
76
77 // Add remaining tokens
78 if (currentTokens.length > 0) {
79 const firstToken = currentTokens[0];
80 const lastToken = currentTokens[currentTokens.length - 1];
81 if (firstToken && lastToken && firstToken.fromMs !== undefined && lastToken.toMs !== undefined) {
82 result.push({
83 tokens: currentTokens,
84 text: currentTokens.map(t => t.text).join(' '),
85 startMs: firstToken.fromMs,
86 durationMs: lastToken.toMs - firstToken.fromMs,
87 });
88 }
89 }
90
91 return result.length > 0 ? result : [page];
92 });
93
94 setPages(splitPages);
95 continueRender(handle);
96 }, [captionsFile, handle]);
97
98 useEffect(() => {
99 fetchCaptions();
100 }, [fetchCaptions]);
101
102 return (
103 <>
104 {pages.map((page, i) => {
105 const startFrame = Math.floor((page.startMs / 1000) * fps) + audioStartFrame;
106 const durationFrames = Math.ceil((page.durationMs / 1000) * fps);
107
108 return (
109 <Sequence key={i} from={startFrame} durationInFrames={durationFrames}>
110 <div
111 style={{
112 position: "absolute",
113 top: "52%",
114 left: 0,
115 right: 0,
116 display: "flex",
117 justifyContent: "center",
118 alignItems: "center",
119 }}
120 >
121 <div
122 style={{
123 textAlign: "center",
124 maxWidth: "78%",
125 fontFamily,
126 fontWeight: 900,
127 fontSize: 68,
128 lineHeight: 1.3,
129 textShadow:
130 "0 2px 8px rgba(0,0,0,0.9), 0 0 20px rgba(0,0,0,0.5)",
131 wordWrap: "break-word",
132 overflowWrap: "break-word",
133 whiteSpace: "normal",
134 overflow: "visible",
135 }}
136 >
137 {page.tokens.map((token, j) => {
138 const wordStartFrame =
139 Math.floor((token.fromMs / 1000) * fps) + audioStartFrame;
140 const wordEndFrame =
141 Math.ceil((token.toMs / 1000) * fps) + audioStartFrame;
142 const isActive =
143 frame >= wordStartFrame &&
144 frame < wordEndFrame;
145 const activeScale = isActive
146 ? spring({
147 frame: frame - wordStartFrame,
148 fps,
149 config: { damping: 10, stiffness: 200 },
150 })
151 : 0;
152 const scale = interpolate(activeScale, [0, 1], [1, 1.15]);
153 return (
154 <span
155 key={j}
156 style={{
157 color: isActive ? highlightColor : "#ffffff",
158 WebkitTextStroke: "4px #000000",
159 paintOrder: "stroke fill",
160 transform: `scale(${scale})`,
161 display: "inline-block",
162 marginRight: j < page.tokens.length - 1 ? "0.3em" : "0",
163 }}
164 >
165 {token.text}
166 </span>
167 );
168 })}
169 </div>
170 </div>
171 </Sequence>
172 );
173 })}
174 </>
175 );
176};