Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): integrate timeline view into share page
Richie McIlroy6340ce0aa063
diff --git a/apps/web/__tests__/unit/share-stage-identity.test.ts b/apps/web/__tests__/unit/share-stage-identity.test.tsnew file mode 100644index 000000000..aa000167c--- /dev/null+++ b/apps/web/__tests__/unit/share-stage-identity.test.ts@@ -0,0 +1,265 @@+// @vitest-environment jsdom++import {+ act,+ type ComponentProps,+ createElement,+ type ReactNode,+ type Ref,+} from "react";+import { createRoot } from "react-dom/client";+import {+ afterAll,+ afterEach,+ beforeAll,+ describe,+ expect,+ it,+ vi,+} from "vitest";+import { Share } from "@/app/s/[videoId]/Share";++vi.mock("motion/react", async () => {+ const { createElement } = await import("react");+ type MotionProps = Record<string, unknown> & { children?: ReactNode };+ const strip = (props: MotionProps) => {+ const {+ layout: _layout,+ layoutId: _layoutId,+ initial: _initial,+ animate: _animate,+ exit: _exit,+ transition: _transition,+ onLayoutAnimationStart: _onLayoutAnimationStart,+ onLayoutAnimationComplete: _onLayoutAnimationComplete,+ children,+ ...rest+ } = props;+ return { children, rest };+ };+ const host =+ (tag: string) =>+ (props: MotionProps): ReactNode => {+ const { children, rest } = strip(props);+ return createElement(tag, rest, children);+ };+ return {+ AnimatePresence: ({ children }: { children?: ReactNode }) => children,+ useReducedMotion: () => false,+ motion: { div: host("div"), span: host("span") },+ };+});++vi.mock("next/dynamic", async () => {+ const { createElement } = await import("react");+ return {+ default: () => () => createElement("div", { "data-timeline-view": "" }),+ };+});++vi.mock("next/image", async () => {+ const { createElement } = await import("react");+ return {+ default: ({ alt }: { alt?: string }) => createElement("img", { alt }),+ };+});++vi.mock("next/navigation", () => ({+ useSearchParams: () => new URLSearchParams(),+ useRouter: () => ({ refresh: () => undefined }),+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: undefined }),+}));++vi.mock("@/actions/videos/get-status", () => ({+ getVideoStatus: async () => ({}),+}));++vi.mock("@/app/s/[videoId]/_components/CaptionContext", () => ({+ CaptionProvider: ({ children }: { children?: ReactNode }) => children,+}));++vi.mock("@/app/s/[videoId]/_components/ShareVideo", async () => {+ const { createElement } = await import("react");+ return {+ ShareVideo: ({ ref }: { ref?: Ref<HTMLVideoElement> }) =>+ createElement("video", { ref, "data-share-video": "" }),+ };+});++vi.mock("@/app/s/[videoId]/_components/Sidebar", async () => {+ const { createElement } = await import("react");+ return { Sidebar: () => createElement("div", { "data-sidebar": "" }) };+});++vi.mock("@/app/s/[videoId]/_components/Toolbar", async () => {+ const { createElement } = await import("react");+ return { Toolbar: () => createElement("div", { "data-toolbar": "" }) };+});++vi.mock("@/app/s/[videoId]/_components/SummaryChapters", async () => {+ const { createElement } = await import("react");+ return { default: () => createElement("div", { "data-summary": "" }) };+});++const actEnvironment = globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT?: boolean;+};++type ShareComponentProps = ComponentProps<typeof Share>;++const createProps = (+ overrides: Partial<ShareComponentProps> = {},+): ShareComponentProps => ({+ data: {+ id: "video-id",+ name: "Test video",+ orgId: "org-id",+ owner: { id: "owner-id", isPro: false },+ duration: 60,+ metadata: null,+ createdAt: new Date(),+ isScreenshot: false,+ transcriptionStatus: null,+ source: { type: "desktopMP4" },+ orgSettings: null,+ } as unknown as ShareComponentProps["data"],+ comments: [],+ views: 0,+ customDomain: null,+ domainVerified: false,+ // Matching the owner short-circuits the view-tracking beacon, which has no+ // business firing from a layout test.+ viewerId: "owner-id",+ isEditProcessing: false,+ aiGenerationAvailable: false,+ transcriptionGenerationAvailable: false,+ ...overrides,+});++const findButton = (container: HTMLElement, label: string) =>+ Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent === label,+ );++/** The stage wrapper is three levels above the `<video>`: player -> inset box -> card -> stage. */+const stageOf = (video: Element | null) =>+ video?.parentElement?.parentElement?.parentElement ?? null;++describe("Share view toggle", () => {+ beforeAll(() => {+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;+ });++ afterEach(() => {+ document.body.replaceChildren();+ window.history.replaceState(window.history.state, "", "/s/video-id");+ });++ afterAll(() => {+ delete actEnvironment.IS_REACT_ACT_ENVIRONMENT;+ });++ it("keeps the same stage and video element across view changes", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(createElement(Share, createProps()));+ });++ const video = container.querySelector("[data-share-video]");+ const stage = stageOf(video);+ expect(video).not.toBeNull();+ expect(stage).not.toBeNull();+ expect(container.querySelector("[data-sidebar]")).not.toBeNull();+ expect(container.querySelector("[data-toolbar]")).not.toBeNull();++ await act(async () => {+ findButton(container, "Timeline")?.click();+ });++ // The whole point of the grid refactor: the player is moved, never rebuilt.+ expect(container.querySelector("[data-share-video]")).toBe(video);+ expect(stageOf(container.querySelector("[data-share-video]"))).toBe(stage);+ expect(container.querySelector("[data-timeline-view]")).not.toBeNull();+ expect(container.querySelector("[data-sidebar]")).toBeNull();+ expect(container.querySelector("[data-toolbar]")).toBeNull();+ expect(window.location.search).toBe("?view=timeline");++ await act(async () => {+ findButton(container, "Player")?.click();+ });++ expect(container.querySelector("[data-share-video]")).toBe(video);+ expect(stageOf(container.querySelector("[data-share-video]"))).toBe(stage);+ expect(container.querySelector("[data-sidebar]")).not.toBeNull();+ expect(container.querySelector("[data-timeline-view]")).toBeNull();+ expect(window.location.search).toBe("");++ await act(async () => {+ root.unmount();+ });+ });++ it("starts on the timeline when the server resolves ?view=timeline", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ createElement(Share, createProps({ initialView: "timeline" })),+ );+ });++ expect(container.querySelector("[data-timeline-view]")).not.toBeNull();+ expect(container.querySelector("[data-share-video]")).not.toBeNull();+ expect(container.querySelector("[data-sidebar]")).toBeNull();++ await act(async () => {+ root.unmount();+ });+ });++ it("hides the toggle for screenshots", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ createElement(+ Share,+ createProps({+ data: {+ id: "video-id",+ name: "Test screenshot",+ orgId: "org-id",+ owner: { id: "owner-id", isPro: false },+ duration: null,+ metadata: null,+ createdAt: new Date(),+ isScreenshot: true,+ transcriptionStatus: null,+ source: { type: "desktopMP4" },+ orgSettings: null,+ } as unknown as ShareComponentProps["data"],+ initialView: "timeline",+ screenshotImageUrl: "https://example.com/shot.png",+ }),+ ),+ );+ });++ expect(findButton(container, "Timeline")).toBeUndefined();+ expect(container.querySelector("[data-timeline-view]")).toBeNull();++ await act(async () => {+ root.unmount();+ });+ });+});diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsxindex f2b39515d..3f9277643 100644--- a/apps/web/app/s/[videoId]/Share.tsx+++ b/apps/web/app/s/[videoId]/Share.tsx@@ -4,9 +4,13 @@ import type { comments as commentsSchema } from "@cap/database/schema";import type { ViewerSettingKey } from "@cap/web-backend";import type { ImageUpload, Video } from "@cap/web-domain";import { useQuery } from "@tanstack/react-query";+import clsx from "clsx";+import { AnimatePresence, motion, useReducedMotion } from "motion/react";+import dynamic from "next/dynamic";import Image from "next/image";import { useSearchParams } from "next/navigation";import {+ Suspense,startTransition,use,useCallback,@@ -21,13 +25,32 @@ import {type VideoStatusResult,} from "@/actions/videos/get-status";import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";+import { SignedImageUrl } from "@/components/SignedImageUrl";import { CaptionProvider } from "./_components/CaptionContext";+import { PlaybackProvider } from "./_components/playback/PlaybackContext";import { ShareVideo } from "./_components/ShareVideo";+import { type ShareView, ShareViewToggle } from "./_components/ShareViewToggle";import { Sidebar } from "./_components/Sidebar";import SummaryChapters from "./_components/SummaryChapters";import { Toolbar } from "./_components/Toolbar";+import { formatTimeAgo } from "./_components/tabs/Activity/utils";+import { TimelineSkeleton } from "./_components/timeline/TimelineSkeleton";+import type { FilmstripSource } from "./_components/timeline/useFilmstripFrames";import type { VideoData } from "./types";+const importTimelineView = () => import("./_components/timeline/TimelineView");+const TimelineView = dynamic(importTimelineView, { ssr: false });++/** Whether the viewer last left the comments rail collapsed. */+const RAIL_COLLAPSED_KEY = "cap_share_rail_collapsed";++/**+ * The interactive walkthrough behind the header's "How does this work?".+ * Relative, so a custom domain or a self-hosted deployment links at its own+ * copy of the post rather than back at cap.so.+ */+const TIMELINE_GUIDE_URL = "/blog/timeline-view";+type CommentWithAuthor = typeof commentsSchema.$inferSelect & {authorName: string | null;authorImage: ImageUpload.ImageUrl | null;@@ -170,6 +193,16 @@ interface ShareProps {} | null;aiGenerationAvailable: boolean;transcriptionGenerationAvailable: boolean;+ /** Server-resolved `?view=` so the first paint already has the right layout. */+ initialView?: ShareView;+ canRecordMedia?: boolean;+ viewerSignedIn?: boolean;+ /**+ * The page header. Passed in rather than rendered above `Share` so the+ * timeline view can swap it for a slim bar without the page owning which+ * view is active.+ */+ header?: React.ReactNode;}const useVideoStatus = (@@ -287,6 +320,10 @@ export const Share = ({defaultPlaybackSpeed,aiGenerationAvailable,transcriptionGenerationAvailable,+ initialView = "classic",+ canRecordMedia = false,+ viewerSignedIn = false,+ header,}: ShareProps) => {const isScreenshot = data.isScreenshot === true;const effectiveDate: Date = data.metadata?.customCreatedAt@@ -294,6 +331,7 @@ export const Share = ({: data.createdAt;const playerRef = useRef<HTMLVideoElement | null>(null);+ const stageRef = useRef<HTMLDivElement | null>(null);const activityRef = useRef<{ scrollToBottom: () => void }>(null);const initialComments: CommentType[] =comments instanceof Promise ? use(comments) : comments;@@ -516,141 +554,613 @@ export const Share = ({}, 100);}, []);+ const reduceMotion = useReducedMotion() ?? false;+ const [selectedView, setSelectedView] = useState<ShareView>(initialView);+ // Screenshots have no timeline to show, and a comments-disabled video has+ // nothing to branch — both stay on the classic layout even if someone+ // hand-writes `?view=timeline`.+ const timelineAvailable = !isScreenshot && !areCommentStampsDisabled;++ // Where the timeline's filmstrip frames come from. Mirrors the source split+ // in `ShareVideo`: instant recordings have a result.mp4 a bare <video> can+ // seek; everything else is an HLS playlist. A still-uploading segments+ // source gets no strip — its playlist is in flux and not worth hammering.+ const filmstripSource = useMemo<FilmstripSource | null>(() => {+ if (isScreenshot) return null;+ const sourceType = data.source.type;+ if (sourceType === "desktopMP4" || sourceType === "webMP4") {+ return {+ src: `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=mp4`,+ kind: "native",+ };+ }+ if (sourceType === "desktopSegments") {+ if (data.hasActiveUpload) return null;+ return {+ src: `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=segments-master`,+ kind: "hls",+ };+ }+ return {+ src: `/api/playlist?userId=${data.owner.id}&videoId=${data.id}&videoType=video`,+ kind: "hls",+ };+ }, [+ isScreenshot,+ data.source.type,+ data.owner.id,+ data.id,+ data.hasActiveUpload,+ ]);+ // The theater block hugs the video: width-driven height from the real+ // aspect ratio, capped so the deck below stays reachable without scrolling.+ const stageAspect =+ data.width && data.height && data.width > 0 && data.height > 0+ ? data.width / data.height+ : 16 / 9;++ const view: ShareView = timelineAvailable ? selectedView : "classic";+ const [morphing, setMorphing] = useState(false);+ const [stageFullscreen, setStageFullscreen] = useState(false);+ const [timelineRecording, setTimelineRecording] = useState(false);+ // The deck row the player's control bar portals into while the timeline is+ // up. Null until the lazily-loaded deck mounts; the bar stays on the video+ // (and returns there for fullscreen, which hides the deck).+ const [controlsSlot, setControlsSlot] = useState<HTMLElement | null>(null);++ const setViewAndUrl = useCallback((next: ShareView) => {+ setSelectedView(next);+ if (typeof window === "undefined") return;+ const url = new URL(window.location.href);+ if (next === "timeline") url.searchParams.set("view", "timeline");+ else url.searchParams.delete("view");+ // replaceState, not router.replace: the view is a presentation detail and+ // a Next navigation here would re-render the tree and remount the player.+ window.history.replaceState(+ window.history.state,+ "",+ `${url.pathname}${url.search}${url.hash}`,+ );+ }, []);++ const prefetchTimeline = useCallback(() => {+ void importTimelineView();+ }, []);++ // A toggle mid-fullscreen would rip the video out of the fullscreen element,+ // so disable it for as long as the stage owns the screen.+ useEffect(() => {+ const syncFullscreen = () => {+ const active = document.fullscreenElement;+ // `contains` is inclusive, so this also covers the stage itself.+ setStageFullscreen(Boolean(active && stageRef.current?.contains(active)));+ };+ syncFullscreen();+ document.addEventListener("fullscreenchange", syncFullscreen);+ return () =>+ document.removeEventListener("fullscreenchange", syncFullscreen);+ }, []);++ // T flips Player/Timeline, under the same guards as the toggle itself.+ useEffect(() => {+ if (!timelineAvailable) return;++ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "t" && event.key !== "T") return;+ if (event.metaKey || event.ctrlKey || event.altKey) return;+ const target = event.target as HTMLElement | null;+ if (+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ target?.isContentEditable+ ) {+ return;+ }+ if (stageFullscreen || timelineRecording) return;+ event.preventDefault();+ setViewAndUrl(view === "timeline" ? "classic" : "timeline");+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [+ timelineAvailable,+ stageFullscreen,+ timelineRecording,+ view,+ setViewAndUrl,+ ]);++ const showRail = view === "classic" && !allSettingsDisabled;+ const [railCollapsed, setRailCollapsed] = useState(false);++ // Read after mount, not during render: the server has no idea what the+ // viewer collapsed last time, and guessing would hydrate the wrong width.+ useEffect(() => {+ try {+ setRailCollapsed(+ window.localStorage.getItem(RAIL_COLLAPSED_KEY) === "true",+ );+ } catch {+ /* private mode; the default (open) is fine */+ }+ }, []);++ const toggleRail = useCallback(() => {+ // Persist outside the updater: React may invoke updater functions more+ // than once, and localStorage writes don't belong in render-adjacent code.+ const next = !railCollapsed;+ setRailCollapsed(next);+ try {+ window.localStorage.setItem(RAIL_COLLAPSED_KEY, String(next));+ } catch {+ /* not worth failing the toggle over */+ }+ }, [railCollapsed]);+return (<CaptionProvidervideoId={data.id}transcriptionStatus={transcriptionStatus}>- <div className="mt-4">- <div className="flex flex-col gap-4 lg:flex-row">- <div className="flex-1">- <div className="overflow-visible relative bg-white rounded-2xl border aspect-video border-gray-5">+ <PlaybackProvider+ videoRef={playerRef}+ stageRef={stageRef}+ fallbackDuration={data.duration}+ >+ {/*+ * The page bar. It spans the video column AND the comments rail, so+ * the rail hangs beneath it the way Loom's panel hangs beneath its+ * top bar. Hidden (never unmounted) in timeline view, which carries+ * its own slim title row: the header owns dialogs and the inline+ * title editor, and toggling views must not discard them.+ */}+ <div+ className={clsx(+ "shrink-0 border-b border-gray-5 bg-white px-4 lg:px-8",+ view === "timeline" && "hidden",+ )}+ >+ {header}+ </div>++ {/*+ * The two-pane shell. On desktop the page itself no longer scrolls+ * (see `page.tsx`): the video column scrolls inside the left pane and+ * the comments rail runs the full height beside it.+ * Phones stack the two and scroll the document as normal.+ */}+ <div className="flex flex-col flex-1 min-h-0 lg:flex-row">+ <div className="flex flex-col flex-1 min-w-0 lg:overflow-y-auto">+ {/* Gutters live here rather than on the page, so the rail can sit+ flush against the viewport edge while the video stays centred+ inside what's left. */}+ <div className="flex flex-col flex-1 px-4 mx-auto w-full max-w-[80rem] lg:px-8">+ {/*+ * Classic: a normal page section with bottom padding. Timeline: the+ * card sizes itself to the video's aspect ratio (viewport-capped)+ * and floats in the middle of the leftover viewport — the page above+ * keeps this wrapper in a flex column, so flex-1 + justify-center is+ * all the vertical centring takes. (Desktop only; small screens keep+ * natural flow.)+ */}<div- className={- isScreenshot- ? "absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl"- : "absolute inset-x-3 top-1/2 aspect-video -translate-y-1/2 overflow-visible rounded-xl"- }+ className={clsx(+ view === "timeline"+ ? "mt-2 pb-6 lg:mt-0 lg:pb-0 lg:flex lg:flex-1 lg:flex-col lg:justify-center"+ : "mt-4 pb-8",+ )}>- {isScreenshot ? (- <ScreenshotImage src={screenshotImageUrl} alt={data.name} />- ) : (- <ShareVideo- data={{ ...data, transcriptionStatus }}- comments={comments}- areChaptersDisabled={areChaptersDisabled}- areCaptionsDisabled={areCaptionsDisabled}- areCommentStampsDisabled={areCommentStampsDisabled}- areReactionStampsDisabled={areReactionStampsDisabled}- chapters={aiData?.chapters || []}- aiGenerationStatus={aiData?.aiGenerationStatus}- canRetryProcessing={viewerId === data.owner.id}- canFinalizeDesktopSegments={viewerId === data.owner.id}- showPlaybackStatusBadge={viewerId === data.owner.id}- isEditProcessing={isEditProcessing}- recordingStopped={recordingStopped}- defaultPlaybackSpeed={defaultPlaybackSpeed}- ref={playerRef}- />+ {timelineAvailable && view === "timeline" && (+ // The top edge of the player card. It sits flush on the grid+ // below (which carries the bottom corners and the rest of the+ // border), so the two read as one contained, rounded unit,+ // centred at the same width. Classic view's toggle lives under+ // the player instead.+ <div className="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-3 rounded-t-xl border border-b-0 border-gray-5 bg-white px-5">+ <div className="flex min-w-0 items-center gap-3">+ <SignedImageUrl+ image={data.owner.image}+ name={data.owner.name ?? "Someone"}+ className="size-8 shrink-0 rounded-full"+ letterClass="text-xs font-medium"+ />+ <div className="min-w-0">+ <p className="truncate text-sm font-medium leading-tight text-gray-12">+ {videoStatus?.name ?? data.name}+ </p>+ <p className="truncate text-xs leading-tight text-gray-10">+ {data.owner.name ?? "Someone"}+ {" · "}+ {formatTimeAgo(effectiveDate)}+ </p>+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {/* New surface, so it carries its own explainer. Opens in a+ tab of its own: leaving the page would drop playback and+ anything half-typed in the composer. */}+ <a+ href={TIMELINE_GUIDE_URL}+ target="_blank"+ rel="noreferrer"+ title="How does the timeline work?"+ className="flex h-7 shrink-0 items-center gap-1.5 rounded-full border border-gray-5 bg-white px-2 text-xs font-medium text-gray-11 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9 md:px-2.5"+ >+ <svg+ viewBox="0 0 16 16"+ className="size-3.5 shrink-0 fill-current"+ aria-hidden+ >+ <title>How does this work?</title>+ <path d="M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13Zm0 1.2a5.3 5.3 0 1 1 0 10.6A5.3 5.3 0 0 1 8 2.7Zm0 1.6c-1.2 0-2.1.7-2.4 1.8a.6.6 0 0 0 1.15.34c.16-.55.6-.94 1.25-.94.7 0 1.2.44 1.2 1.03 0 .45-.2.73-.78 1.14-.66.47-.99.94-.96 1.72a.6.6 0 0 0 1.2-.04c-.02-.35.1-.53.53-.83.75-.53 1.21-1.08 1.21-2 0-1.25-1.02-2.22-2.4-2.22Zm0 6.05a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z" />+ </svg>+ <span className="hidden md:inline">+ How does this work?+ </span>+ </a>+ <ShareViewToggle+ view={view}+ onChange={setViewAndUrl}+ // Fullscreen: a morph would rip the video out of the+ // fullscreen element. Recording: leaving the timeline+ // unmounts the recorder and silently discards the take.+ disabled={stageFullscreen || timelineRecording}+ prefetch={prefetchTimeline}+ />+ </div>+ </div>)}- </div>- </div>- <div className="mt-4 lg:hidden">- <Toolbar- onOptimisticComment={handleOptimisticComment}- onCommentSuccess={handleCommentSuccess}- disableComments={areCommentStampsDisabled}- disableReactions={areReactionStampsDisabled}- data={data}- />- </div>- </div>- {!allSettingsDisabled && (- <div className="flex flex-col lg:w-80">- <Sidebar- data={{- ...data,- createdAt: effectiveDate,- transcriptionStatus,- }}- videoSettings={videoSettings}- commentsData={commentsData}- setCommentsData={setCommentsData}- optimisticComments={optimisticComments}- setOptimisticComments={setOptimisticComments}- handleCommentSuccess={handleCommentSuccess}- views={views}- onSeek={isScreenshot ? undefined : handleSeek}- isScreenshot={isScreenshot}- videoId={data.id}- aiData={aiData}- aiGenerationEnabled={aiGenerationAvailable}- recordingStopped={recordingStopped}- ref={activityRef}- />- </div>- )}- </div>+ {/*+ * One grid, two arrangements. The stage below is a single JSX node+ * at a single tree position in both views. Only its grid placement+ * and its siblings change, because remounting it would tear down+ * the media-chrome store inside the player and restart playback.+ */}+ <div+ className={clsx(+ "grid relative",+ // In timeline view the grid is the body of the player card:+ // contained, centred, bottom corners rounded (the title row+ // above carries the top ones). Background clips to the radius+ // on its own, so no overflow-clip — the shelf's cards must+ // escape.+ view === "timeline"+ ? "mx-auto w-full max-w-6xl gap-0 rounded-b-xl border border-t-0 border-gray-5 bg-white"+ : "gap-4",+ // One column in both views: the comments rail left the grid to+ // become a full-height pane beside it.+ "lg:grid-cols-1",+ )}+ >+ <motion.div+ ref={stageRef}+ layout+ data-morphing={morphing ? "" : undefined}+ onLayoutAnimationStart={() => setMorphing(true)}+ onLayoutAnimationComplete={() => setMorphing(false)}+ transition={+ reduceMotion+ ? { duration: 0 }+ : {+ type: "spring",+ stiffness: 260,+ damping: 32,+ mass: 0.9,+ }+ }+ className={clsx(+ "min-w-0",+ // Contained card, not full-bleed: the unit keeps the page's+ // gutters and sits centred with everything else.+ view === "timeline"+ ? "lg:col-span-full lg:row-start-1"+ : "lg:col-start-1 lg:row-start-1",+ )}+ >+ {/*+ * Classic: a white page card holding the video. Timeline: the+ * screen at the top of the card, edge to edge and squared off,+ * with the light chrome (strip, comments, controls) below it.+ */}+ <div+ className={clsx(+ "overflow-visible relative transition-[border-radius] duration-300",+ // Timeline: the screen, sized by the video's own aspect ratio+ // (style below), so a landscape recording meets the strip+ // with no bar of black under it. It stays dark — the screen+ // is the one part of the card that isn't chrome, same as the+ // black box classic view paints inside its white card. The+ // colour is the player's dark `--background` token spelled+ // out (a `dark` class here would restyle every overlay+ // inside the stage).+ // The 340px budget covers the card's own chrome (title row,+ // strip, shelf, bar) plus page margins, so the centred card+ // always fits the viewport — justify-center clips at the+ // top if its content overflows.+ // The 280px floor is desktop-only: on a phone it would beat+ // the aspect ratio and letterbox the video away from the+ // strip. The 65svh cap keeps a portrait video from pushing+ // the deck below the fold; the video pillarboxes inside.+ view === "timeline"+ ? "rounded-none bg-[hsl(224,71.4%,4.1%)] w-full max-h-[65svh] lg:min-h-[280px] lg:max-h-[calc(100vh-340px)]"+ : "rounded-2xl border border-gray-5 bg-white aspect-video",+ )}+ style={+ view === "timeline"+ ? { aspectRatio: String(stageAspect) }+ : undefined+ }+ >+ <div+ className={+ isScreenshot+ ? "absolute inset-3 w-[calc(100%-1.5rem)] h-[calc(100%-1.5rem)] overflow-visible rounded-xl"+ : view === "timeline"+ ? "absolute inset-0 overflow-visible"+ : "absolute inset-x-3 top-1/2 aspect-video -translate-y-1/2 overflow-visible rounded-xl"+ }+ >+ {isScreenshot ? (+ <ScreenshotImage+ src={screenshotImageUrl}+ alt={data.name}+ />+ ) : (+ <ShareVideo+ data={{ ...data, transcriptionStatus }}+ comments={comments}+ areChaptersDisabled={areChaptersDisabled}+ areCaptionsDisabled={areCaptionsDisabled}+ // The deck under the video owns seeking, the clock and+ // comments in timeline view; duplicating them inside the+ // video reads as two players. Fullscreen hides the deck,+ // so the in-video versions come back for its duration.+ externalTimeline={+ view === "timeline" && !stageFullscreen+ }+ controlsPortalEl={+ view === "timeline" && !stageFullscreen+ ? controlsSlot+ : null+ }+ areCommentStampsDisabled={+ areCommentStampsDisabled ||+ (view === "timeline" && !stageFullscreen)+ }+ areReactionStampsDisabled={+ areReactionStampsDisabled ||+ (view === "timeline" && !stageFullscreen)+ }+ chapters={aiData?.chapters ?? undefined}+ aiGenerationStatus={aiData?.aiGenerationStatus}+ canRetryProcessing={viewerId === data.owner.id}+ canFinalizeDesktopSegments={+ viewerId === data.owner.id+ }+ showPlaybackStatusBadge={viewerId === data.owner.id}+ isEditProcessing={isEditProcessing}+ recordingStopped={recordingStopped}+ defaultPlaybackSpeed={defaultPlaybackSpeed}+ ref={playerRef}+ />+ )}+ </div>+ </div>+ </motion.div>- <div className="hidden mt-4 lg:block">- <div>- <Toolbar- onOptimisticComment={handleOptimisticComment}- onCommentSuccess={handleCommentSuccess}- disableComments={areCommentStampsDisabled}- disableReactions={areReactionStampsDisabled}- data={data}- />- </div>- </div>+ <AnimatePresence mode="popLayout" initial={false}>+ {view === "classic" ? (+ <motion.div+ key="toolbar"+ className="lg:col-span-full lg:row-start-2"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: reduceMotion ? 0 : 0.14 }}+ >+ {/*+ * The view toggle sits to the left under the player; the+ * absolute placement (desktop) keeps the toolbar pill+ * centred rather than pushed aside.+ */}+ <div className="relative">+ {timelineAvailable && (+ <div className="mb-3 flex justify-start lg:absolute lg:left-0 lg:top-1/2 lg:mb-0 lg:-translate-y-1/2">+ <ShareViewToggle+ view={view}+ onChange={setViewAndUrl}+ disabled={stageFullscreen || timelineRecording}+ prefetch={prefetchTimeline}+ />+ </div>+ )}+ <Toolbar+ onOptimisticComment={handleOptimisticComment}+ onCommentSuccess={handleCommentSuccess}+ disableComments={areCommentStampsDisabled}+ disableReactions={areReactionStampsDisabled}+ data={data}+ />+ </div>+ </motion.div>+ ) : (+ // The band runs its own enter/exit; this wrapper only exists+ // to give popLayout a motion child to pop out of the grid.+ <motion.div+ key="timeline"+ className="lg:col-span-full lg:row-start-2"+ >+ <Suspense fallback={<TimelineSkeleton />}>+ <TimelineView+ comments={optimisticComments}+ videoId={data.id}+ chapters={aiData?.chapters ?? undefined}+ transcriptionStatus={transcriptionStatus}+ filmstripSource={filmstripSource}+ onOptimisticComment={handleOptimisticComment}+ onCommentSuccess={handleCommentSuccess}+ canRecordMedia={canRecordMedia}+ viewerSignedIn={viewerSignedIn}+ disableReactions={areReactionStampsDisabled}+ onRecordingActiveChange={setTimelineRecording}+ onControlsSlotChange={setControlsSlot}+ />+ </Suspense>+ </motion.div>+ )}+ </AnimatePresence>- <div className="hidden mt-4 lg:block">- {!isScreenshot && aiLoading && (- <div className="p-4 animate-pulse new-card-style">- <div className="space-y-6">- <div>- <div className="mb-3 w-24 h-6 bg-gray-200 rounded"></div>- <div className="mb-4 w-32 h-3 bg-gray-100 rounded"></div>- <div className="space-y-3">- <div className="w-full h-4 bg-gray-200 rounded"></div>- <div className="w-5/6 h-4 bg-gray-200 rounded"></div>- <div className="w-4/5 h-4 bg-gray-200 rounded"></div>- <div className="w-full h-4 bg-gray-200 rounded"></div>- <div className="w-3/4 h-4 bg-gray-200 rounded"></div>- </div>- </div>+ <AnimatePresence mode="popLayout" initial={false}>+ {view === "classic" && (+ <motion.div+ key="summary"+ className="hidden lg:block lg:col-span-full lg:row-start-3"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: reduceMotion ? 0 : 0.14 }}+ >+ {!isScreenshot && aiLoading && (+ <div className="p-4 animate-pulse new-card-style">+ <div className="space-y-6">+ <div>+ <div className="mb-3 w-24 h-6 bg-gray-200 rounded"></div>+ <div className="mb-4 w-32 h-3 bg-gray-100 rounded"></div>+ <div className="space-y-3">+ <div className="w-full h-4 bg-gray-200 rounded"></div>+ <div className="w-5/6 h-4 bg-gray-200 rounded"></div>+ <div className="w-4/5 h-4 bg-gray-200 rounded"></div>+ <div className="w-full h-4 bg-gray-200 rounded"></div>+ <div className="w-3/4 h-4 bg-gray-200 rounded"></div>+ </div>+ </div>- <div>- <div className="mb-4 w-24 h-6 bg-gray-200 rounded"></div>- <div className="space-y-2">- {[1, 2, 3, 4].map((i) => (- <div key={i} className="flex items-center p-2">- <div className="mr-3 w-12 h-4 bg-gray-200 rounded"></div>- <div className="flex-1 h-4 bg-gray-200 rounded"></div>- </div>- ))}- </div>+ <div>+ <div className="mb-4 w-24 h-6 bg-gray-200 rounded"></div>+ <div className="space-y-2">+ {[1, 2, 3, 4].map((i) => (+ <div+ key={i}+ className="flex items-center p-2"+ >+ <div className="mr-3 w-12 h-4 bg-gray-200 rounded"></div>+ <div className="flex-1 h-4 bg-gray-200 rounded"></div>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ )}++ {!isScreenshot && (+ <SummaryChapters+ isSummaryDisabled={isSummaryDisabled}+ areChaptersDisabled={areChaptersDisabled}+ handleSeek={handleSeek}+ aiData={aiData}+ aiLoading={aiLoading}+ />+ )}+ </motion.div>+ )}+ </AnimatePresence></div></div></div>+ </div>++ {/*+ * The comments rail. Full height, flush to the viewport edge and+ * scrolling independently of the video column — the panel is the+ * one part of this page whose usefulness is measured in vertical+ * space. Collapsing animates the width away; the pane stays mounted+ * so the open tab and scroll position survive the round trip.+ */}+ {showRail && (+ <aside+ className={clsx(+ "shrink-0 px-4 pb-8 lg:p-0 lg:h-full lg:border-l lg:border-gray-5 lg:bg-white lg:overflow-hidden",+ reduceMotion+ ? undefined+ : "lg:transition-[width] lg:duration-300 lg:ease-out",+ railCollapsed ? "lg:w-0" : "lg:w-[22rem] xl:w-[24rem]",+ )}+ >+ {/* Hidden rather than merely clipped while collapsed, so the+ panel's inputs leave the tab order. Scoped to lg: the+ stored preference is a desktop one and the phone layout+ shows the panel regardless. */}+ <div+ className={clsx(+ "lg:h-full lg:w-[22rem] xl:w-[24rem]",+ railCollapsed && "lg:invisible",+ )}+ >+ <Sidebar+ data={{+ ...data,+ createdAt: effectiveDate,+ transcriptionStatus,+ }}+ videoSettings={videoSettings}+ commentsData={commentsData}+ setCommentsData={setCommentsData}+ optimisticComments={optimisticComments}+ setOptimisticComments={setOptimisticComments}+ handleCommentSuccess={handleCommentSuccess}+ views={views}+ onSeek={isScreenshot ? undefined : handleSeek}+ isScreenshot={isScreenshot}+ videoId={data.id}+ aiData={aiData}+ aiGenerationEnabled={aiGenerationAvailable}+ recordingStopped={recordingStopped}+ canRecordMedia={canRecordMedia}+ onCollapse={toggleRail}+ ref={activityRef}+ />+ </div>+ </aside>)}- {!isScreenshot && (- <SummaryChapters- isSummaryDisabled={isSummaryDisabled}- areChaptersDisabled={areChaptersDisabled}- handleSeek={handleSeek}- aiData={aiData}- aiLoading={aiLoading}- />+ {/* Only handle back to the panel once it's away. Sits on the edge+ it collapsed into, so the gesture reverses itself. */}+ {showRail && railCollapsed && (+ <button+ type="button"+ onClick={toggleRail}+ aria-label="Show comments"+ title="Show comments"+ className="hidden fixed right-0 top-1/2 z-30 items-center justify-center -translate-y-1/2 rounded-l-lg border border-r-0 border-gray-5 bg-white h-16 w-6 text-gray-10 shadow-sm transition-colors hover:text-gray-12 lg:flex"+ >+ <ChevronGlyph direction="left" />+ </button>)}</div>- </div>+ </PlaybackProvider></CaptionProvider>);};+function ChevronGlyph({ direction }: { direction: "left" | "right" }) {+ return (+ <svg+ viewBox="0 0 16 16"+ className={clsx(+ "size-4 fill-current",+ direction === "right" && "rotate-180",+ )}+ aria-hidden+ >+ <title>{direction === "left" ? "Expand" : "Collapse"}</title>+ <path d="M10.3 3.3a.6.6 0 0 1 0 .85L6.45 8l3.85 3.85a.6.6 0 1 1-.85.85l-4.27-4.27a.6.6 0 0 1 0-.86L9.45 3.3a.6.6 0 0 1 .85 0Z" />+ </svg>+ );+}+function ScreenshotImage({ src, alt }: { src?: string | null; alt: string }) {if (!src) {return (diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsxindex e3c5bac13..89a989144 100644--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx@@ -2,7 +2,7 @@ import type { comments as commentsSchema } from "@cap/database/schema";import { classNames } from "@cap/utils";import type { ImageUpload, Video } from "@cap/web-domain";import clsx from "clsx";-import { AnimatePresence, motion } from "framer-motion";+import { AnimatePresence, motion } from "motion/react";import { forwardRef, Suspense, useState } from "react";import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data";import { useCurrentUser } from "@/app/Layout/AuthContext";@@ -48,6 +48,11 @@ interface SidebarProps {/** The owner just stopped this recording and landed here from the desktop* app — surface the transcript, which is the thing appearing live. */recordingStopped?: boolean;+ /** Owner is on Pro and the viewer is signed in; the composer's record+ * buttons ride on the same gate the timeline's do. */+ canRecordMedia?: boolean;+ /** Supplied on desktop, where the rail can be folded away. */+ onCollapse?: () => void;}const TabContent = motion.div;@@ -72,7 +77,7 @@ const tabVariants = {const tabTransition = {x: { type: "spring", stiffness: 300, damping: 30 },opacity: { duration: 0.2 },-};+} as const;export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>((@@ -90,6 +95,8 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(aiGenerationEnabled = false,isScreenshot = false,recordingStopped = false,+ canRecordMedia = false,+ onCollapse,},ref,) => {@@ -183,6 +190,8 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(isOwner={isOwner}onSeek={onSeek}videoId={data.id}+ ownerName={data.owner.name}+ canRecordMedia={canRecordMedia && !isScreenshot}/></Suspense>);@@ -208,8 +217,10 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>(const allTabsDisabled = tabs.every((tab) => tab.disabled);+ // Desktop: a flush pane that fills its rail, so the comment list gets the+ // viewport's height rather than the video's. Phones keep the card.return (- <div className="bg-white rounded-2xl border border-gray-5 overflow-hidden h-[calc(100vh-16rem)] lg:h-full flex flex-col lg:aspect-video">+ <div className="bg-white rounded-2xl border border-gray-5 overflow-hidden h-[70svh] flex flex-col lg:h-full lg:rounded-none lg:border-0"><div className="flex-none"><divclassName={clsx(@@ -252,6 +263,24 @@ export const Sidebar = forwardRef<{ scrollToBottom: () => void }, SidebarProps>()}</button>))}+ {onCollapse && (+ <button+ type="button"+ onClick={onCollapse}+ aria-label="Hide comments"+ title="Hide comments"+ className="hidden shrink-0 items-center justify-center px-3 text-gray-9 transition-colors hover:bg-gray-1 hover:text-gray-12 lg:flex"+ >+ <svg+ viewBox="0 0 16 16"+ className="size-4 fill-current"+ aria-hidden+ >+ <title>Hide comments</title>+ <path d="M5.7 3.3a.6.6 0 0 0 0 .85L9.55 8 5.7 11.85a.6.6 0 1 0 .85.85l4.27-4.27a.6.6 0 0 0 0-.86L6.55 3.3a.6.6 0 0 0-.85 0Z" />+ </svg>+ </button>+ )}</div></div><div className="flex-1 min-h-0">diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex a419164ed..954e55cfe 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -97,32 +97,35 @@ const hasRecordingStoppedParam = (searchParams: ShareVideoSearchParams) => {// Helper function to fetch shared spaces data for a videoasync function getSharedSpacesForVideo(videoId: Video.VideoId) {- // Fetch space-level sharing- const spaceSharing = await db()- .select({- id: spaces.id,- name: spaces.name,- organizationId: spaces.organizationId,- iconUrl: spaces.iconUrl,- settings: spaces.settings,- hasPassword: sql`${spaces.password} IS NOT NULL`.mapWith(Boolean),- })- .from(spaceVideos)- .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))- .innerJoin(organizations, eq(spaces.organizationId, organizations.id))- .where(eq(spaceVideos.videoId, videoId));-- // Fetch organization-level sharing- const orgSharing = await db()- .select({- id: organizations.id,- name: organizations.name,- organizationId: organizations.id,- iconUrl: organizations.iconUrl,- })- .from(sharedVideos)- .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))- .where(eq(sharedVideos.videoId, videoId));+ // Space-level and organization-level sharing are independent queries.+ const [spaceSharing, orgSharing] = await Promise.all([+ db()+ .select({+ id: spaces.id,+ name: spaces.name,+ organizationId: spaces.organizationId,+ iconUrl: spaces.iconUrl,+ settings: spaces.settings,+ hasPassword: sql`${spaces.password} IS NOT NULL`.mapWith(Boolean),+ })+ .from(spaceVideos)+ .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))+ .innerJoin(organizations, eq(spaces.organizationId, organizations.id))+ .where(eq(spaceVideos.videoId, videoId)),+ db()+ .select({+ id: organizations.id,+ name: organizations.name,+ organizationId: organizations.id,+ iconUrl: organizations.iconUrl,+ })+ .from(sharedVideos)+ .innerJoin(+ organizations,+ eq(sharedVideos.organizationId, organizations.id),+ )+ .where(eq(sharedVideos.videoId, videoId)),+ ]);const sharedSpaces: Array<{id: string;@@ -386,7 +389,17 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {Effect.succeed({ needsPassword: true } as const),),Effect.map((data) => (- <div key={videoId} className="flex flex-col min-h-screen bg-gray-2">+ // overflow-x-clip: the timeline view's theater strip breaks out to+ // 100vw, which overshoots by the scrollbar width on OSes with classic+ // scrollbars; clipping here keeps the page from gaining a horizontal+ // scroll without creating a new scroll container.+ // Desktop pins the page to the viewport so the comments rail can run+ // full height and the video column scrolls on its own; phones keep+ // ordinary document flow.+ <div+ key={videoId}+ className="flex overflow-x-clip flex-col min-h-screen bg-gray-2 lg:h-screen lg:min-h-0 lg:overflow-hidden"+ ><PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />{!data.needsPassword && (<AuthorizedContent video={data.video} searchParams={searchParams} />@@ -474,34 +487,27 @@ async function AuthorizedContent({);const recordingStopped = hasRecordingStoppedParam(searchParams);- // Fetch spaces data for the sharing dialog- let spacesData = null;- if (user) {- try {- const dashboardData = await getDashboardData(user);- spacesData = dashboardData.spacesData;- } catch (error) {- console.error("Failed to fetch spaces data for sharing dialog:", error);- spacesData = [];- }- }+ // Everything below is an independent round trip (DB or storage); each is+ // started here and awaited together further down, so the page pays for the+ // slowest one instead of the sum of all of them.+ const spacesDataPromise: Promise<+ Awaited<ReturnType<typeof getDashboardData>>["spacesData"] | null+ > = user+ ? getDashboardData(user).then(+ (dashboardData) => dashboardData.spacesData,+ (error) => {+ console.error(+ "Failed to fetch spaces data for sharing dialog:",+ error,+ );+ return [];+ },+ )+ : Promise.resolve(null);- // Fetch shared spaces data for this video- const sharedSpaces = await getSharedSpacesForVideo(videoId);- const rules = resolveEffectiveVideoRules({- videoSettings: video.videoSettings,- organizationSettings: video.orgSettings,- spaces: sharedSpaces.filter((space) => space.id !== space.organizationId),- });- const env = serverEnv();- const transcriptionGenerationAvailable =- !video.isScreenshot &&- Boolean(env.ASSEMBLY_API_KEY) &&- !rules.settings.disableTranscript;- const aiProviderAvailable = Boolean(env.GROQ_API_KEY || env.OPENAI_API_KEY);+ const sharedSpacesPromise = getSharedSpacesForVideo(videoId);- let aiGenerationEnabled = false;- const videoOwnerQuery = await db()+ const aiGenerationEnabledPromise = db().select({email: users.email,stripeSubscriptionStatus: users.stripeSubscriptionStatus,@@ -509,49 +515,17 @@ async function AuthorizedContent({}).from(users).where(eq(users.id, video.owner.id))- .limit(1);-- if (videoOwnerQuery.length > 0 && videoOwnerQuery[0]) {- const videoOwner = videoOwnerQuery[0];- aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);- }-- if (- transcriptionGenerationAvailable &&- !hasActiveUpload &&- video.transcriptionStatus !== "COMPLETE" &&- video.transcriptionStatus !== "PROCESSING" &&- video.transcriptionStatus !== "SKIPPED" &&- video.transcriptionStatus !== "NO_AUDIO" &&- video.transcriptionStatus !== "ERROR"- ) {- console.log("[ShareVideoPage] Starting transcription for video:", videoId);- transcribeVideo(videoId, video.owner.id, aiGenerationEnabled).catch(- (error) => {- console.error(- `[ShareVideoPage] Error transcribing video ${videoId}:`,- error,- );- },+ .limit(1)+ .then((videoOwnerQuery) =>+ videoOwnerQuery[0] ? isAiGenerationEnabled(videoOwnerQuery[0]) : false,);- }- const currentMetadata = (video.metadata as VideoMetadata) || {};- const metadata = currentMetadata;- const aiGenerationStatus = metadata.aiGenerationStatus || null;-- const initialAiData = {- title: metadata.aiTitle || null,- summary: metadata.summary || null,- chapters: metadata.chapters || null,- aiGenerationStatus,- };-- const screenshotImageUrl = video.isScreenshot- ? await Effect.flatMap(Videos, (videos) =>- videos.getThumbnailURL(videoId),- ).pipe(Effect.map(Option.getOrNull), runPromise)- : null;+ const screenshotImageUrlPromise = video.isScreenshot+ ? Effect.flatMap(Videos, (videos) => videos.getThumbnailURL(videoId)).pipe(+ Effect.map(Option.getOrNull),+ runPromise,+ )+ : Promise.resolve(null);const customDomainPromise = (async () => {if (!user) {@@ -664,6 +638,9 @@ async function AuthorizedContent({createdAt: comments.createdAt,updatedAt: comments.updatedAt,parentCommentId: comments.parentCommentId,+ mediaKey: comments.mediaKey,+ mediaDuration: comments.mediaDuration,+ mediaMeta: comments.mediaMeta,authorName: users.name,authorImage: users.image,})@@ -698,19 +675,7 @@ async function AuthorizedContent({const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);- const [- membersList,- userOrganizations,- sharedOrganizations,- { customDomain, domainVerified },- ] = await Promise.all([- membersListPromise,- userOrganizationsPromise,- sharedOrganizationsPromise,- customDomainPromise,- ]);-- const canManageSharePageBranding = await (async () => {+ const canManageSharePageBrandingPromise = (async () => {if (!userId) return false;const [organizationAccess] = await db()@@ -745,6 +710,102 @@ async function AuthorizedContent({);})();+ const isVideoDownloadReady =+ !hasActiveUpload && video.source?.type !== "desktopSegments";++ const canDownloadVideoPromise =+ userId && isVideoDownloadReady+ ? canUserDownloadVideo({+ userId,+ ownerId: video.owner.id,+ videoId,+ })+ : Promise.resolve(false);++ const videoHasEditsPromise = canDownloadVideoPromise.then((canDownload) => {+ if (!canDownload || video.isScreenshot) return false;+ return db()+ .select({ editSpec: videoEdits.editSpec })+ .from(videoEdits)+ .where(eq(videoEdits.videoId, videoId))+ .then(([videoEditRow]) =>+ videoEditRow+ ? !areEditSpecsEquivalent(+ videoEditRow.editSpec,+ createIdentityEditSpec(videoEditRow.editSpec.sourceDuration),+ )+ : false,+ );+ });++ const [+ spacesData,+ sharedSpaces,+ aiGenerationEnabled,+ screenshotImageUrl,+ membersList,+ userOrganizations,+ sharedOrganizations,+ { customDomain, domainVerified },+ canManageSharePageBranding,+ canDownloadVideo,+ videoHasEdits,+ ] = await Promise.all([+ spacesDataPromise,+ sharedSpacesPromise,+ aiGenerationEnabledPromise,+ screenshotImageUrlPromise,+ membersListPromise,+ userOrganizationsPromise,+ sharedOrganizationsPromise,+ customDomainPromise,+ canManageSharePageBrandingPromise,+ canDownloadVideoPromise,+ videoHasEditsPromise,+ ]);++ const rules = resolveEffectiveVideoRules({+ videoSettings: video.videoSettings,+ organizationSettings: video.orgSettings,+ spaces: sharedSpaces.filter((space) => space.id !== space.organizationId),+ });+ const env = serverEnv();+ const transcriptionGenerationAvailable =+ !video.isScreenshot &&+ Boolean(env.ASSEMBLY_API_KEY) &&+ !rules.settings.disableTranscript;+ const aiProviderAvailable = Boolean(env.GROQ_API_KEY || env.OPENAI_API_KEY);++ if (+ transcriptionGenerationAvailable &&+ !hasActiveUpload &&+ video.transcriptionStatus !== "COMPLETE" &&+ video.transcriptionStatus !== "PROCESSING" &&+ video.transcriptionStatus !== "SKIPPED" &&+ video.transcriptionStatus !== "NO_AUDIO" &&+ video.transcriptionStatus !== "ERROR"+ ) {+ console.log("[ShareVideoPage] Starting transcription for video:", videoId);+ transcribeVideo(videoId, video.owner.id, aiGenerationEnabled).catch(+ (error) => {+ console.error(+ `[ShareVideoPage] Error transcribing video ${videoId}:`,+ error,+ );+ },+ );+ }++ const metadata = (video.metadata as VideoMetadata) || {};+ const aiGenerationStatus = metadata.aiGenerationStatus || null;++ const initialAiData = {+ title: metadata.aiTitle || null,+ summary: metadata.summary || null,+ chapters: metadata.chapters || null,+ aiGenerationStatus,+ };+const videoWithOrganizationInfo = await Effect.gen(function* () {const imageUploads = yield* ImageUploads;@@ -792,57 +853,49 @@ async function AuthorizedContent({video.orgSettings?.defaultPlaybackSpeed,);- const isVideoDownloadReady =- !hasActiveUpload && video.source?.type !== "desktopSegments";-- const canDownloadVideo =- userId && isVideoDownloadReady- ? await canUserDownloadVideo({- userId,- ownerId: video.owner.id,- videoId,- })- : false;-- let videoHasEdits = false;- if (canDownloadVideo && !video.isScreenshot) {- const [videoEditRow] = await db()- .select({ editSpec: videoEdits.editSpec })- .from(videoEdits)- .where(eq(videoEdits.videoId, videoId));-- videoHasEdits = videoEditRow- ? !areEditSpecsEquivalent(- videoEditRow.editSpec,- createIdentityEditSpec(videoEditRow.editSpec.sourceDuration),- )- : false;- }-+ const initialShareView =+ optionFromTOrFirst(searchParams.view).pipe(Option.getOrNull) ===+ "timeline" && !video.isScreenshot+ ? ("timeline" as const)+ : ("classic" as const);+ // Recording media comments rides on the VIDEO OWNER's Pro plan; the+ // upload/create paths re-check server-side via canUseMediaComments.+ const canRecordMedia = Boolean(user) && videoWithOrganizationInfo.owner.isPro;++ // Bottom padding lives in Share (classic view only): the timeline view's+ // theater strip must end flush with the viewport, and Share is the one that+ // knows which view is active. Gutters moved into Share too — the comments+ // rail is flush to the viewport edge, so only the video column is centred+ // in a container.return (- <div className="container flex-1 px-4 pb-8 mx-auto">- <ShareHeader- data={{- ...videoWithOrganizationInfo,- createdAt: video.metadata?.customCreatedAt- ? new Date(video.metadata.customCreatedAt)- : video.createdAt,- }}- customDomain={customDomain}- domainVerified={domainVerified}- sharedOrganizations={- videoWithOrganizationInfo.sharedOrganizations || []- }- sharedSpaces={sharedSpaces}- userOrganizations={userOrganizations}- spacesData={spacesData}- branding={getSharePageBranding(videoWithOrganizationInfo)}- canManageSharePageBranding={canManageSharePageBranding}- canDownload={canDownloadVideo}- hasEdits={videoHasEdits}- />-+ <div className="flex flex-col flex-1 min-h-0"><Share+ header={+ <ShareHeader+ data={{+ ...videoWithOrganizationInfo,+ createdAt: video.metadata?.customCreatedAt+ ? new Date(video.metadata.customCreatedAt)+ : video.createdAt,+ }}+ customDomain={customDomain}+ domainVerified={domainVerified}+ sharedOrganizations={+ videoWithOrganizationInfo.sharedOrganizations || []+ }+ sharedSpaces={sharedSpaces}+ userOrganizations={userOrganizations}+ spacesData={spacesData}+ branding={getSharePageBranding(videoWithOrganizationInfo)}+ canManageSharePageBranding={canManageSharePageBranding}+ canDownload={canDownloadVideo}+ hasEdits={videoHasEdits}+ // Caught separately from the copy the sidebar consumes: the+ // header renders for everyone, and a failed count is worth+ // less than the header it would otherwise take down.+ views={viewsPromise.catch(() => null)}+ />+ }data={videoWithOrganizationInfo}screenshotImageUrl={screenshotImageUrl}videoSettings={videoWithOrganizationInfo.settings}@@ -852,6 +905,9 @@ async function AuthorizedContent({domainVerified={domainVerified}userOrganizations={userOrganizations}viewerId={user?.id ?? null}+ viewerSignedIn={user !== null}+ initialView={initialShareView}+ canRecordMedia={canRecordMedia}isEditProcessing={isEditProcessing}recordingStopped={recordingStopped}defaultPlaybackSpeed={defaultPlaybackSpeed}