Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Improve uploading context (#1051)
Oscar Beaumontfdb412f46a9d
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsxindex b294f513a..e83dd11aa 100644--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx@@ -24,7 +24,7 @@ import { CapPagination } from "./components/CapPagination";import { EmptyCapState } from "./components/EmptyCapState";import type { FolderDataType } from "./components/Folder";import Folder from "./components/Folder";-import { useUploadingContext } from "./UploadingContext";+import { useUploadingContext, useUploadingStatus } from "./UploadingContext";export type VideoData = {id: Video.VideoId;@@ -74,7 +74,6 @@ export const Caps = ({const previousCountRef = useRef<number>(0);const [selectedCaps, setSelectedCaps] = useState<Video.VideoId[]>([]);const [isDraggingCap, setIsDraggingCap] = useState(false);- const { uploadStatus } = useUploadingContext();const anyCapSelected = selectedCaps.length > 0;@@ -258,10 +257,7 @@ export const Caps = ({onError: () => toast.error("Failed to delete cap"),});- const isUploading = uploadStatus !== undefined;- const uploadingCapId =- uploadStatus && "capId" in uploadStatus ? uploadStatus.capId : undefined;-+ const [isUploading, uploadingCapId] = useUploadingStatus();const visibleVideos = useMemo(() =>isUploading && uploadingCapIddiff --git a/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx b/apps/web/app/(org)/dashboard/caps/UploadingContext.tsxindex 18def19ad..a24220c15 100644--- a/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx+++ b/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx@@ -1,13 +1,10 @@"use client";+import { useStore } from "@tanstack/react-store";+import { Store } from "@tanstack/store";import type React from "react";import { createContext, useContext, useEffect, useState } from "react";-interface UploadingContextType {- uploadStatus: UploadStatus | undefined;- setUploadStatus: (state: UploadStatus | undefined) => void;-}-export type UploadStatus =| {status: "parsing";@@ -32,6 +29,11 @@ export type UploadStatus =thumbnailUrl: string | undefined;};+interface UploadingContextType {+ uploadingStore: Store<{ uploadStatus?: UploadStatus }>;+ setUploadStatus: (state: UploadStatus | undefined) => void;+}+const UploadingContext = createContext<UploadingContextType | undefined>(undefined,);@@ -45,13 +47,52 @@ export function useUploadingContext() {return context;}+export function useUploadingStatus() {+ const { uploadingStore } = useUploadingContext();+ return useStore(+ uploadingStore,+ (s) =>+ [+ s.uploadStatus !== undefined,+ s.uploadStatus && "capId" in s.uploadStatus+ ? s.uploadStatus.capId+ : null,+ ] as const,+ );+}+export function UploadingProvider({ children }: { children: React.ReactNode }) {- const [state, setState] = useState<UploadStatus>();+ const [uploadingStore] = useState<Store<{ uploadStatus?: UploadStatus }>>(+ () => new Store({}),+ );++ return (+ <UploadingContext.Provider+ value={{+ uploadingStore,+ setUploadStatus: (status: UploadStatus | undefined) => {+ uploadingStore.setState((state) => ({+ ...state,+ uploadStatus: status,+ }));+ },+ }}+ >+ {children}++ <ForbidLeaveWhenUploading />+ </UploadingContext.Provider>+ );+}++// Separated to prevent rerendering whole tree+function ForbidLeaveWhenUploading() {+ const { uploadingStore } = useUploadingContext();+ const uploadStatus = useStore(uploadingStore, (state) => state.uploadStatus);- // Prevent the user closing the tab while uploadinguseEffect(() => {const handleBeforeUnload = (e: BeforeUnloadEvent) => {- if (state?.status) {+ if (uploadStatus?.status) {e.preventDefault();// Chrome requires returnValue to be sete.returnValue = "";@@ -61,16 +102,7 @@ export function UploadingProvider({ children }: { children: React.ReactNode }) {window.addEventListener("beforeunload", handleBeforeUnload);return () => window.removeEventListener("beforeunload", handleBeforeUnload);- }, [state]);+ }, [uploadStatus]);- return (- <UploadingContext.Provider- value={{- uploadStatus: state,- setUploadStatus: setState,- }}- >- {children}- </UploadingContext.Provider>- );+ return null;}diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsxindex 8969b420f..160bbd970 100644--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx@@ -452,7 +452,6 @@ export const CapCard = ({"transition-opacity duration-200",uploadProgress && "opacity-30",)}- userId={cap.ownerId}videoId={cap.id}alt={`${cap.name} Thumbnail`}/>diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsxindex 5ca9cc12f..80931b4c3 100644--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx@@ -5,6 +5,8 @@ import { userIsPro } from "@cap/utils";import type { Folder } from "@cap/web-domain";import { faUpload } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { type QueryClient, useQueryClient } from "@tanstack/react-query";+import { useStore } from "@tanstack/react-store";import { useRouter } from "next/navigation";import { useRef, useState } from "react";import { toast } from "sonner";@@ -15,6 +17,7 @@ import {useUploadingContext,} from "@/app/(org)/dashboard/caps/UploadingContext";import { UpgradeModal } from "@/components/UpgradeModal";+import { imageUrlQuery } from "@/components/VideoThumbnail";export const UploadCapButton = ({size = "md",@@ -26,9 +29,11 @@ export const UploadCapButton = ({}) => {const { user } = useDashboardContext();const inputRef = useRef<HTMLInputElement>(null);- const { uploadStatus, setUploadStatus } = useUploadingContext();+ const { uploadingStore, setUploadStatus } = useUploadingContext();+ const isUploading = useStore(uploadingStore, (s) => !!s.uploadStatus);const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);const router = useRouter();+ const queryClient = useQueryClient();const handleClick = () => {if (!user) return;@@ -47,13 +52,16 @@ export const UploadCapButton = ({const file = e.target.files?.[0];if (!file || !user) return;- const ok = await legacyUploadCap(file, folderId, setUploadStatus);+ const ok = await legacyUploadCap(+ file,+ folderId,+ setUploadStatus,+ queryClient,+ );if (ok) router.refresh();if (inputRef.current) inputRef.current.value = "";};- const isUploading = !!uploadStatus;-return (<><Button@@ -86,6 +94,7 @@ async function legacyUploadCap(file: File,folderId: Folder.FolderId | undefined,setUploadStatus: (state: UploadStatus | undefined) => void,+ queryClient: QueryClient,) {const parser = await import("@remotion/media-parser");const webcodecs = await import("@remotion/webcodecs");@@ -476,6 +485,7 @@ async function legacyUploadCap(xhr.onload = () => {if (xhr.status >= 200 && xhr.status < 300) {resolve();+ queryClient.refetchQueries(imageUrlQuery(uploadId));} else {reject(new Error(`Screenshot upload failed with status ${xhr.status}`),diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadPlaceholderCard.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadPlaceholderCard.tsxindex dd6966490..5f004dff5 100644--- a/apps/web/app/(org)/dashboard/caps/components/UploadPlaceholderCard.tsx+++ b/apps/web/app/(org)/dashboard/caps/components/UploadPlaceholderCard.tsx@@ -2,12 +2,14 @@import { LogoSpinner } from "@cap/ui";import { calculateStrokeDashoffset, getProgressCircleConfig } from "@cap/utils";+import { useStore } from "@tanstack/react-store";import { type UploadStatus, useUploadingContext } from "../UploadingContext";const { circumference } = getProgressCircleConfig();export const UploadPlaceholderCard = () => {- const { uploadStatus } = useUploadingContext();+ const { uploadingStore } = useUploadingContext();+ const uploadStatus = useStore(uploadingStore, (s) => s.uploadStatus);const strokeDashoffset = calculateStrokeDashoffset(uploadStatus &&(uploadStatus.status === "converting" ||diff --git a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsxindex 90563e357..07ad8214e 100644--- a/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx+++ b/apps/web/app/(org)/dashboard/folder/[id]/components/FolderVideosSection.tsx@@ -2,6 +2,7 @@import type { Video } from "@cap/web-domain";import { useQuery } from "@tanstack/react-query";+import { useStore } from "@tanstack/react-store";import { Effect, Exit } from "effect";import { useRouter } from "next/navigation";import { useMemo, useRef, useState } from "react";@@ -13,7 +14,10 @@ import type { VideoData } from "../../../caps/Caps";import { CapCard } from "../../../caps/components/CapCard/CapCard";import { SelectedCapsBar } from "../../../caps/components/SelectedCapsBar";import { UploadPlaceholderCard } from "../../../caps/components/UploadPlaceholderCard";-import { useUploadingContext } from "../../../caps/UploadingContext";+import {+ useUploadingContext,+ useUploadingStatus,+} from "../../../caps/UploadingContext";interface FolderVideosSectionProps {initialVideos: VideoData;@@ -27,13 +31,8 @@ export default function FolderVideosSection({cardType = "default",}: FolderVideosSectionProps) {const router = useRouter();- const { uploadStatus } = useUploadingContext();const { user } = useDashboardContext();- const isUploading = uploadStatus !== undefined;- const uploadingCapId =- uploadStatus && "capId" in uploadStatus ? uploadStatus.capId : null;-const [selectedCaps, setSelectedCaps] = useState<Video.VideoId[]>([]);const previousCountRef = useRef<number>(0);@@ -159,6 +158,7 @@ export default function FolderVideosSection({refetchOnMount: true,});+ const [isUploading, uploadingCapId] = useUploadingStatus();const visibleVideos = useMemo(() =>isUploading && uploadingCapIddiff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/VideoCard.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/VideoCard.tsxindex b1fe3b05b..8adc2a307 100644--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/VideoCard.tsx+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/VideoCard.tsx@@ -100,7 +100,6 @@ const VideoCard: React.FC<VideoCardProps> = memo(><VideoThumbnailimageClass="w-full h-full transition-all duration-200 group-hover:scale-105"- userId={video.ownerId}videoId={video.id}alt={`${video.name} Thumbnail`}objectFit="cover"diff --git a/apps/web/app/api/thumbnail/route.ts b/apps/web/app/api/thumbnail/route.tsindex fa645c74b..de2c5a8a1 100644--- a/apps/web/app/api/thumbnail/route.ts+++ b/apps/web/app/api/thumbnail/route.ts@@ -10,11 +10,10 @@ export const revalidate = 0;export async function GET(request: NextRequest) {const { searchParams } = request.nextUrl;- const userId = searchParams.get("userId");const videoId = searchParams.get("videoId");const origin = request.headers.get("origin") as string;- if (!userId || !videoId) {+ if (!videoId)return new Response(JSON.stringify({error: true,@@ -25,9 +24,8 @@ export async function GET(request: NextRequest) {headers: getHeaders(origin),},);- }- const query = await db()+ const [query] = await db().select({video: videos,bucket: s3Buckets,@@ -36,29 +34,17 @@ export async function GET(request: NextRequest) {.leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id)).where(eq(videos.id, Video.VideoId.make(videoId)));- if (query.length === 0) {- return new Response(- JSON.stringify({ error: true, message: "Video does not exist" }),- {- status: 401,- headers: getHeaders(origin),- },- );- }-- const result = query[0];- if (!result?.video) {+ if (!query)return new Response(JSON.stringify({ error: true, message: "Video not found" }),{- status: 401,+ status: 404,headers: getHeaders(origin),},);- }- const prefix = `${userId}/${videoId}/`;- const bucketProvider = await createBucketProvider(result.bucket);+ const prefix = `${query.video.ownerId}/${query.video.id}/`;+ const bucketProvider = await createBucketProvider(query.bucket);try {const listResponse = await bucketProvider.listObjects({@@ -66,11 +52,11 @@ export async function GET(request: NextRequest) {});const contents = listResponse.Contents || [];- const thumbnailKey = contents.find((item: any) =>+ const thumbnailKey = contents.find((item) =>item.Key?.endsWith("screen-capture.jpg"),)?.Key;- if (!thumbnailKey) {+ if (!thumbnailKey)return new Response(JSON.stringify({error: true,@@ -81,7 +67,6 @@ export async function GET(request: NextRequest) {headers: getHeaders(origin),},);- }const thumbnailUrl = await bucketProvider.getSignedObjectUrl(thumbnailKey);diff --git a/apps/web/components/VideoThumbnail.tsx b/apps/web/components/VideoThumbnail.tsxindex e57697667..965e6ae52 100644--- a/apps/web/components/VideoThumbnail.tsx+++ b/apps/web/components/VideoThumbnail.tsx@@ -1,13 +1,11 @@import { LogoSpinner } from "@cap/ui";-import { useQuery } from "@tanstack/react-query";+import { queryOptions, useQuery } from "@tanstack/react-query";import clsx from "clsx";import moment from "moment";import Image from "next/image";import { memo, useEffect, useRef, useState } from "react";-import { useUploadingContext } from "@/app/(org)/dashboard/caps/UploadingContext";interface VideoThumbnailProps {- userId: string;videoId: string;alt: string;imageClass?: string;@@ -43,9 +41,20 @@ function generateRandomGrayScaleColor() {return `rgb(${grayScaleValue}, ${grayScaleValue}, ${grayScaleValue})`;}+export const imageUrlQuery = (videoId: string) =>+ queryOptions({+ queryKey: ["thumbnail", videoId],+ queryFn: async () => {+ const response = await fetch(`/api/thumbnail?videoId=${videoId}`);+ if (response.ok) {+ const data = await response.json();+ return data.screen;+ } else throw new Error("Failed to fetch pre-signed URLs");+ },+ });+export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(({- userId,videoId,alt,imageClass,@@ -53,31 +62,9 @@ export const VideoThumbnail: React.FC<VideoThumbnailProps> = memo(containerClass,videoDuration,}) => {- const imageUrl = useQuery({- queryKey: ["thumbnail", userId, videoId],- queryFn: async () => {- const cacheBuster = new Date().getTime();- const response = await fetch(- `/api/thumbnail?userId=${userId}&videoId=${videoId}&t=${cacheBuster}`,- );- if (response.ok) {- const data = await response.json();- return data.screen;- } else {- throw new Error("Failed to fetch pre-signed URLs");- }- },- });+ const imageUrl = useQuery(imageUrlQuery(videoId));const imageRef = useRef<HTMLImageElement>(null);- const { uploadStatus } = useUploadingContext();-- const uploadingCapId =- uploadStatus && "capId" in uploadStatus ? uploadStatus.capId : null;- useEffect(() => {- imageUrl.refetch();- }, [imageUrl.refetch, uploadingCapId]);-const randomGradient = `linear-gradient(to right, ${generateRandomGrayScaleColor()}, ${generateRandomGrayScaleColor()})`;const [imageStatus, setImageStatus] = useState<diff --git a/apps/web/package.json b/apps/web/package.jsonindex 92358d25c..001cfc149 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -66,6 +66,7 @@"@tanstack/react-query": "^5.90.1","@tanstack/react-query-devtools": "^5.90.1","@tanstack/react-store": "^0.7.7",+ "@tanstack/store": "^0.7.7","@ts-rest/core": "^3.52.1","@uidotdev/usehooks": "^2.4.1","@vercel/functions": "^3.1.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c7ca15212..e110e46b8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -588,6 +588,9 @@ importers:'@tanstack/react-store':specifier: ^0.7.7+ '@tanstack/store':+ specifier: ^0.7.7+ version: 0.7.7'@ts-rest/core':specifier: ^3.52.1version: 3.52.1(@types/[email protected])([email protected])@@ -23057,8 +23060,8 @@ snapshots:eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 4.6.2([email protected]([email protected]))@@ -23086,33 +23089,33 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.0([email protected])- eslint: 9.30.1([email protected])+ eslint: 8.57.1get-tsconfig: 4.10.0is-bun-module: 2.0.0stable-hash: 0.0.5tinyglobby: 0.2.13unrs-resolver: 1.7.2optionalDependencies:- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])transitivePeerDependencies:- supports-colordependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.0([email protected])- eslint: 8.57.1+ eslint: 9.30.1([email protected])get-tsconfig: 4.10.0is-bun-module: 2.0.0stable-hash: 0.0.5tinyglobby: 0.2.13unrs-resolver: 1.7.2optionalDependencies:- eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])+ eslint-plugin-import: 2.31.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -23127,14 +23130,14 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -23178,7 +23181,7 @@ snapshots:- eslint-import-resolver-webpack- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.8@@ -23189,7 +23192,7 @@ snapshots:doctrine: 2.1.0eslint: 9.30.1([email protected])eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3