Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Refactor of Share.tsx + Cap AI loading state fixes (#588)

Richie McIlroy7c06c65a5c87
diff --git a/apps/web/app/api/video/status/route.ts b/apps/web/app/api/video/status/route.ts
index 5c93716d3..49c5c3893 100644
--- a/apps/web/app/api/video/status/route.ts
+++ b/apps/web/app/api/video/status/route.ts
@@ -34,11 +34,9 @@ export async function GET(request: NextRequest) {
const video = result[0];
const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {};
- // Trigger transcription if it hasn't started yet
- if (!video.transcriptionStatus || video.transcriptionStatus === "ERROR") {
+ if (!video.transcriptionStatus) {
console.log(`[Status API] Transcription not started for video ${videoId}, triggering transcription`);
try {
- // Trigger transcription in the background
transcribeVideo(videoId, video.ownerId).catch(error => {
console.error(`[Status API] Error starting transcription for video ${videoId}:`, error);
});
@@ -52,9 +50,28 @@ export async function GET(request: NextRequest) {
}, { status: 200 });
} catch (error) {
console.error(`[Status API] Error triggering transcription for video ${videoId}:`, error);
+ return Response.json({
+ transcriptionStatus: "ERROR",
+ aiProcessing: false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ error: "Failed to start transcription"
+ }, { status: 500 });
}
}
+ if (video.transcriptionStatus === "ERROR") {
+ return Response.json({
+ transcriptionStatus: "ERROR",
+ aiProcessing: false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ error: "Transcription failed"
+ }, { status: 200 });
+ }
+
if (metadata.aiProcessing) {
const updatedAtTime = new Date(video.updatedAt).getTime();
const currentTime = new Date().getTime();
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index cde1a0a3d..fa2492421 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -4,7 +4,8 @@ import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { Logo } from "@cap/ui";
-import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useMemo, useRef } from "react";
import { ShareHeader } from "./_components/ShareHeader";
import { ShareVideo } from "./_components/ShareVideo";
import { Sidebar } from "./_components/Sidebar";
@@ -52,6 +53,104 @@ interface ShareProps {
aiUiEnabled: boolean;
}
+interface VideoStatusResponse {
+ transcriptionStatus?: "PROCESSING" | "COMPLETE" | "ERROR" | null;
+ aiProcessing?: boolean;
+ aiTitle?: string | null;
+ summary?: string | null;
+ chapters?: { title: string; start: number }[] | null;
+}
+
+const useVideoStatus = (
+ videoId: string,
+ aiGenerationEnabled: boolean,
+ initialData?: {
+ transcriptionStatus?: string | null;
+ aiData?: {
+ title?: string | null;
+ summary?: string | null;
+ chapters?: { title: string; start: number }[] | null;
+ processing?: boolean;
+ } | null;
+ }
+) => {
+ return useQuery({
+ queryKey: ["videoStatus", videoId],
+ queryFn: async (): Promise<VideoStatusResponse> => {
+ const res = await fetch(`/api/video/status?videoId=${videoId}`);
+ if (!res.ok) {
+ throw new Error(`HTTP ${res.status}: ${res.statusText}`);
+ }
+ return res.json();
+ },
+ initialData: initialData
+ ? {
+ transcriptionStatus: initialData.transcriptionStatus as
+ | "PROCESSING"
+ | "COMPLETE"
+ | "ERROR"
+ | null,
+ aiProcessing: initialData.aiData?.processing || false,
+ aiTitle: initialData.aiData?.title || null,
+ summary: initialData.aiData?.summary || null,
+ chapters: initialData.aiData?.chapters || null,
+ }
+ : undefined,
+ refetchInterval: (query) => {
+ const data = query.state.data;
+ if (!data) return 2000;
+
+ const shouldContinuePolling = () => {
+ if (
+ !data.transcriptionStatus ||
+ data.transcriptionStatus === "PROCESSING"
+ ) {
+ return true;
+ }
+
+ if (data.transcriptionStatus === "ERROR") {
+ return false;
+ }
+
+ if (data.transcriptionStatus === "COMPLETE") {
+ if (!aiGenerationEnabled) {
+ return false;
+ }
+
+ if (data.aiProcessing) {
+ return true;
+ }
+
+ if (!data.summary && !data.chapters) {
+ return true;
+ }
+
+ return false;
+ }
+
+ return false;
+ };
+
+ return shouldContinuePolling() ? 2000 : false;
+ },
+ refetchIntervalInBackground: false,
+ staleTime: 1000,
+ });
+};
+
+const useVideoAnalytics = (videoId: string, initialCount: number) => {
+ return useQuery({
+ queryKey: ["videoAnalytics", videoId],
+ queryFn: async () => {
+ const result = await getVideoAnalytics(videoId);
+ return result.count || 0;
+ },
+ initialData: initialCount,
+ staleTime: 30000,
+ refetchOnWindowFocus: false,
+ });
+};
+
export const Share: React.FC<ShareProps> = ({
data,
user,
@@ -64,41 +163,62 @@ export const Share: React.FC<ShareProps> = ({
aiGenerationEnabled,
aiUiEnabled,
}) => {
- const [analytics, setAnalytics] = useState(initialAnalytics);
const effectiveDate: Date = data.metadata?.customCreatedAt
? new Date(data.metadata.customCreatedAt)
: data.createdAt;
const videoRef = useRef<HTMLVideoElement>(null);
- const [transcriptionStatus, setTranscriptionStatus] = useState<string | null>(
- data.transcriptionStatus || null
+
+ const { data: videoStatus } = useVideoStatus(data.id, aiGenerationEnabled, {
+ transcriptionStatus: data.transcriptionStatus,
+ aiData: initialAiData,
+ });
+
+ const { data: viewCount } = useVideoAnalytics(
+ data.id,
+ initialAnalytics.views
);
- const [aiData, setAiData] = useState<{
- title?: string | null;
- summary?: string | null;
- chapters?: { title: string; start: number }[] | null;
- processing?: boolean;
- } | null>(initialAiData || null);
+ const analytics = useMemo(
+ () => ({
+ views: viewCount || 0,
+ comments: comments.filter((c) => c.type === "text").length,
+ reactions: comments.filter((c) => c.type === "emoji").length,
+ }),
+ [viewCount, comments]
+ );
+
+ const transcriptionStatus =
+ videoStatus?.transcriptionStatus || data.transcriptionStatus;
+
+ const aiData = useMemo(
+ () => ({
+ title: videoStatus?.aiTitle || null,
+ summary: videoStatus?.summary || null,
+ chapters: videoStatus?.chapters || null,
+ processing: videoStatus?.aiProcessing || false,
+ }),
+ [videoStatus]
+ );
const shouldShowLoading = () => {
if (!aiGenerationEnabled) {
return false;
}
- if (
- !transcriptionStatus ||
- transcriptionStatus === "PROCESSING" ||
- transcriptionStatus === "ERROR"
- ) {
+ if (!transcriptionStatus || transcriptionStatus === "PROCESSING") {
return true;
}
+ if (transcriptionStatus === "ERROR") {
+ return false;
+ }
+
if (transcriptionStatus === "COMPLETE") {
- if (!initialAiData || initialAiData.processing === true) {
+ if (aiData.processing === true) {
return true;
}
- if (!initialAiData.summary && !initialAiData.chapters) {
+ if (!aiData.summary && !aiData.chapters) {
return true;
}
}
@@ -106,123 +226,7 @@ export const Share: React.FC<ShareProps> = ({
return false;
};
- const [aiLoading, setAiLoading] = useState(shouldShowLoading());
-
- const aiDataRef = useRef(aiData);
- useEffect(() => {
- aiDataRef.current = aiData;
- }, [aiData]);
-
- useEffect(() => {
- let active = true;
- let pollInterval: NodeJS.Timeout | null = null;
- let pollCount = 0;
- const MAX_POLLS = 300;
- const POLL_INTERVAL = 2000;
-
- const shouldPoll = () => {
- if (pollCount >= MAX_POLLS) {
- return false;
- }
-
- if (!transcriptionStatus || transcriptionStatus === "PROCESSING") {
- return true;
- }
-
- if (transcriptionStatus === "ERROR") {
- return true;
- }
-
- if (transcriptionStatus === "COMPLETE") {
- if (!aiGenerationEnabled) {
- return false;
- }
-
- const currentAiData = aiDataRef.current;
-
- if (!currentAiData || currentAiData.processing) {
- return true;
- }
-
- if (!currentAiData.summary && !currentAiData.chapters) {
- return true;
- }
-
- return false;
- }
-
- return false;
- };
-
- const pollStatus = async () => {
- if (!active) return;
-
- pollCount++;
-
- try {
- const res = await fetch(`/api/video/status?videoId=${data.id}`);
- if (!res.ok) {
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
- }
-
- const json = await res.json();
-
- if (!active) return;
-
- if (
- json.transcriptionStatus &&
- json.transcriptionStatus !== transcriptionStatus
- ) {
- setTranscriptionStatus(json.transcriptionStatus);
- }
-
- const hasAiData = json.summary || json.chapters || json.aiTitle;
- if (hasAiData) {
- const newAiData = {
- title: json.aiTitle || null,
- summary: json.summary || null,
- chapters: json.chapters || null,
- processing: json.aiProcessing || false,
- };
- setAiData(newAiData);
- setAiLoading(json.aiProcessing || false);
- } else if (json.aiProcessing) {
- setAiData((prev) => ({ ...prev, processing: true }));
- setAiLoading(true);
- } else if (
- json.transcriptionStatus === "COMPLETE" &&
- !json.aiProcessing
- ) {
- setAiData((prev) => ({ ...prev, processing: false }));
- }
-
- if (!shouldPoll()) {
- if (pollInterval) {
- clearInterval(pollInterval);
- pollInterval = null;
- }
- setAiLoading(false);
- }
- } catch (err) {
- console.error("[Share] Error polling video status:", err);
- }
- };
-
- if (shouldPoll()) {
- pollStatus();
-
- pollInterval = setInterval(pollStatus, POLL_INTERVAL);
- } else {
- setAiLoading(false);
- }
-
- return () => {
- active = false;
- if (pollInterval) {
- clearInterval(pollInterval);
- }
- };
- }, [data.id, transcriptionStatus]);
+ const aiLoading = shouldShowLoading();
const handleSeek = (time: number) => {
if (videoRef.current) {
@@ -230,36 +234,15 @@ export const Share: React.FC<ShareProps> = ({
}
};
- useEffect(() => {
- const fetchViewCount = async () => {
- try {
- const result = await getVideoAnalytics(data.id);
-
- setAnalytics((prev) => ({
- ...prev,
- views: result.count || 0,
- }));
- } catch (error) {
- console.error("Error fetching view count:", error);
- }
- };
-
- fetchViewCount();
- }, [data.id]);
-
- useEffect(() => {
- setAnalytics((prev) => ({
- ...prev,
- comments: comments.filter((c) => c.type === "text").length,
- reactions: comments.filter((c) => c.type === "emoji").length,
- }));
- }, [comments]);
-
const headerData =
aiData && aiData.title && !aiData.processing
? { ...data, name: aiData.title, createdAt: effectiveDate }
: { ...data, createdAt: effectiveDate };
+ console.log("aiLoading", aiLoading);
+ console.log("transcriptionStatus", transcriptionStatus);
+ console.log("aiData", aiData);
+
return (
<>
<div className="container flex-1 px-4 py-4 mx-auto">
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3f2224203..e9595fd2a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -449,7 +449,7 @@ importers:
'@hono/zod-validator':
specifier: ^0.4.3
'@hookform/resolvers':
specifier: ^3.3.2
@@ -494,9 +494,9 @@ importers:
version: 3.5.0
'@t3-oss/env-nextjs':
specifier: ^0.12.0
'@tanstack/react-query':
- specifier: ^5.51.11
+ specifier: ^5.75.4
version: 5.75.4([email protected])
'@tanstack/react-store':
specifier: ^0.5.5
@@ -506,7 +506,7 @@ importers:
version: 0.5.5
'@ts-rest/core':
specifier: ^3.52.1
- version: 3.52.1(@types/[email protected])([email protected])
+ version: 3.52.1(@types/[email protected])([email protected])
'@types/js-cookie':
specifier: ^3.0.6
version: 3.0.6
@@ -536,7 +536,7 @@ importers:
version: 0.43.1(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])([email protected])
dub:
specifier: ^0.33.1
- version: 0.33.1([email protected])
+ version: 0.33.1([email protected])
file-saver:
specifier: ^2.0.5
version: 2.0.5
@@ -643,8 +643,8 @@ importers:
specifier: ^8.17.3
version: 8.22.0
zod:
- specifier: ^3.24.2
- version: 3.24.4
+ specifier: ^3.24.4
+ version: 3.25.20
devDependencies:
'@types/file-saver':
specifier: ^2.0.7
@@ -5025,10 +5025,10 @@ packages:
react-dom:
optional: true
- '@storybook/[email protected]':
- resolution: {integrity: sha512-xyE9Wyz/gc+TEsGSc9BIM0V5Y1RQgEUBEsUdBmC/7rV2JGwzjG31H7JaWgC/3q3rG2kUr24vjLAEsRDEIMeGhA==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-N4RdEjLptun71RH/h4vQA551SKRtr+gyQGx5sVCyamdE52QRPnDOyoM5Kj1IOqTtqLPjYV4D7c0WV2mDIDYazg==}
peerDependencies:
- storybook: ^9.1.0-alpha.0
+ storybook: ^9.1.0-alpha.2
vite: ^5.0.0 || ^6.0.0
'@storybook/[email protected]':
@@ -5044,10 +5044,10 @@ packages:
peerDependencies:
storybook: ^8.6.12
- '@storybook/[email protected]':
- resolution: {integrity: sha512-8WDOzqago5Dt41cNjzyISYUAqzA22HPXc0SU8kb9JS1oYyOADbX2dvwngxybdcGRPxK0EMcgnZub96qKD4f+/g==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-h2zb2J9lst1QMphSDpv3exNyw8fq4w8krV0aNJ+42E/GfHs11jI2zO4aamMCacWl0wSHSDeJaVxFUgXbZbLGcA==}
peerDependencies:
- storybook: ^9.1.0-alpha.0
+ storybook: ^9.1.0-alpha.2
'@storybook/[email protected]':
resolution: {integrity: sha512-bOmTNJE4FM6+3/1hPQVgha8cLxX2Nyi/4Z+tYq0pCDEyQqGRTD2KXre9XsSCnziRaGxiW80OrKkmqWY8Otuu4A==}
@@ -14790,10 +14790,10 @@ snapshots:
hono: 4.7.8
valibot: 1.0.0-rc.1([email protected])
dependencies:
hono: 4.7.8
- zod: 3.24.4
+ zod: 3.25.20
dependencies:
@@ -15328,8 +15328,8 @@ snapshots:
express-rate-limit: 7.5.0([email protected])
pkce-challenge: 4.1.0
raw-body: 3.0.0
- zod: 3.24.4
- zod-to-json-schema: 3.24.3([email protected])
+ zod: 3.25.20
+ zod-to-json-schema: 3.24.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -15471,7 +15471,7 @@ snapshots:
unixify: 1.0.0
urlpattern-polyfill: 8.0.2
yargs: 17.7.2
- zod: 3.24.4
+ zod: 3.25.20
transitivePeerDependencies:
- encoding
- rollup
@@ -17834,9 +17834,9 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
- '@storybook/csf-plugin': 9.1.0-alpha.0([email protected]([email protected]))
+ '@storybook/csf-plugin': 9.1.0-alpha.2([email protected]([email protected]))
storybook: 8.6.12([email protected])
ts-dedent: 2.2.0
@@ -17867,7 +17867,7 @@ snapshots:
storybook: 8.6.12([email protected])
unplugin: 1.16.1
dependencies:
storybook: 8.6.12([email protected])
unplugin: 1.16.1
@@ -17951,6 +17951,12 @@ snapshots:
valibot: 1.0.0-rc.1([email protected])
zod: 3.24.4
+ optionalDependencies:
+ typescript: 5.8.3
+ valibot: 1.0.0-rc.1([email protected])
+ zod: 3.25.20
+
dependencies:
@@ -17959,6 +17965,14 @@ snapshots:
valibot: 1.0.0-rc.1([email protected])
zod: 3.24.4
+ dependencies:
+ optionalDependencies:
+ typescript: 5.8.3
+ valibot: 1.0.0-rc.1([email protected])
+ zod: 3.25.20
+
dependencies:
lodash.castarray: 4.4.0
@@ -18254,10 +18268,10 @@ snapshots:
'@total-typescript/[email protected]': {}
optionalDependencies:
'@types/node': 20.17.43
- zod: 3.24.4
+ zod: 3.25.20
optionalDependencies:
@@ -20408,9 +20422,9 @@ snapshots:
'@planetscale/database': 1.19.0
mysql2: 3.14.1
dependencies:
- zod: 3.24.4
+ zod: 3.25.20
dependencies:
@@ -20847,7 +20861,7 @@ snapshots:
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]))([email protected])
eslint-plugin-jsx-a11y: 6.10.2([email protected])
eslint-plugin-react: 7.37.5([email protected])
eslint-plugin-react-hooks: 4.6.2([email protected])
@@ -20886,7 +20900,7 @@ snapshots:
tinyglobby: 0.2.13
unrs-resolver: 1.7.2
optionalDependencies:
transitivePeerDependencies:
- supports-color
@@ -20905,6 +20919,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ debug: 3.2.7
+ optionalDependencies:
+ '@typescript-eslint/parser': 5.62.0([email protected])([email protected])
+ eslint: 8.57.1
+ eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]))([email protected])
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
debug: 3.2.7
@@ -20927,6 +20952,35 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@rtsao/scc': 1.1.0
+ array-includes: 3.1.8
+ array.prototype.findlastindex: 1.2.6
+ array.prototype.flat: 1.3.3
+ array.prototype.flatmap: 1.3.3
+ debug: 3.2.7
+ doctrine: 2.1.0
+ eslint: 8.57.1
+ eslint-import-resolver-node: 0.3.9
+ hasown: 2.0.2
+ is-core-module: 2.16.1
+ is-glob: 4.0.3
+ minimatch: 3.1.2
+ object.fromentries: 2.0.8
+ object.groupby: 1.0.3
+ object.values: 1.2.1
+ semver: 6.3.1
+ string.prototype.trimend: 1.0.9
+ tsconfig-paths: 3.15.0
+ optionalDependencies:
+ '@typescript-eslint/parser': 5.62.0([email protected])([email protected])
+ transitivePeerDependencies:
+ - eslint-import-resolver-typescript
+ - eslint-import-resolver-webpack
+ - supports-color
+
dependencies:
'@rtsao/scc': 1.1.0
@@ -26204,7 +26258,7 @@ snapshots:
dependencies:
'@storybook/types': 9.0.0-alpha.1([email protected]([email protected]))
magic-string: 0.30.17
solid-js: 1.9.6
@@ -27378,7 +27432,7 @@ snapshots:
unenv: 1.10.0
- zod: 3.24.4
+ zod: 3.25.20
transitivePeerDependencies:
- '@azure/app-configuration'
- '@azure/cosmos'
@@ -27871,9 +27925,9 @@ snapshots:
dependencies:
zod: 3.24.2
dependencies:
- zod: 3.24.4
+ zod: 3.25.20