fix: implement stream playback cleaner structure

This commit is contained in:
talksik
2026-03-18 17:13:41 -07:00
parent 80b21ce58a
commit 69d6ec2ca2
18 changed files with 461 additions and 447 deletions
+7 -4
View File
@@ -44,9 +44,11 @@ class ApiClient {
path: string, path: string,
body?: unknown, body?: unknown,
): Promise<Response> { ): Promise<Response> {
const headers: Record<string, string> = { const headers: Record<string, string> = {};
"Content-Type": "application/json",
}; if (body) {
headers["Content-Type"] = "application/json";
}
const token = this.config.getToken(); const token = this.config.getToken();
if (token) { if (token) {
@@ -115,7 +117,8 @@ class ApiClient {
"GET", "GET",
`/particles/${objectId}/download`, `/particles/${objectId}/download`,
); );
return response.url; const data = await response.json();
return data.url;
} }
// --- Depot --- // --- Depot ---
+229 -20
View File
@@ -1,38 +1,164 @@
import { useComposeStore } from "@/stores/compose-store"; import { useCallback, useEffect, useRef, useState } from "react";
import { useAuthStore } from "@/stores/auth-store"; import { useAuthStore } from "@/stores/auth-store";
import { useCreateParticle } from "@/hooks/use-create-particle"; import { useCreateParticle } from "@/hooks/use-create-particle";
import { useRecordingMode } from "@/hooks/use-recording-mode";
import { useRecorder } from "@/features/compose/use-recorder";
import { particlePath, toFirestoreChildrenPath } from "@/lib/particle-path"; import { particlePath, toFirestoreChildrenPath } from "@/lib/particle-path";
import type { ParticlePath } from "@/lib/particle-path";
import { RecordingOverlay } from "@/features/compose/recording-overlay"; import { RecordingOverlay } from "@/features/compose/recording-overlay";
import { TextComposeStep } from "@/features/compose/text-compose-step"; import { TextComposeStep } from "@/features/compose/text-compose-step";
import { ConfigureStreamStep } from "@/features/compose/configure-stream-step"; import { ConfigureStreamStep } from "@/features/compose/configure-stream-step";
import { useCallback } from "react"; import { apiClient } from "@/api/client";
type ComposeStep = "idle" | "recording" | "reviewing" | "typing" | "configuring";
interface ComposeOverlayProps {
networkId: string;
targetPath?: ParticlePath;
onActiveChange?: (active: boolean) => void;
}
/** /**
* Renders the current compose step as a fullscreen overlay. * Self-contained compose overlay. Each consumer renders its own instance
* Returns null when idle — zero cost when not composing. * with props that determine the mode (new stream vs. reply).
*/ */
export function ComposeOverlay() { export function ComposeOverlay({
const step = useComposeStore((s) => s.step); networkId,
const cancel = useComposeStore((s) => s.cancel); targetPath,
const textContent = useComposeStore((s) => s.textContent); onActiveChange,
const setTextContent = useComposeStore((s) => s.setTextContent); }: ComposeOverlayProps) {
const advanceToConfigure = useComposeStore((s) => s.advanceToConfigure); const [step, setStep] = useState<ComposeStep>("idle");
const networkId = useComposeStore((s) => s.networkId); const [error, setError] = useState<string | null>(null);
const mediaStream = useComposeStore((s) => s.mediaStream); const [textContent, setTextContent] = useState("");
const recordingMode = useComposeStore((s) => s.recordingMode); const [mediaStream, setMediaStream] = useState<MediaStream | null>(null);
const reviewBlob = useComposeStore((s) => s.reviewBlob); const [reviewBlob, setReviewBlob] = useState<Blob | null>(null);
const error = useComposeStore((s) => s.error); const [reviewDurationMs, setReviewDurationMs] = useState(0);
const [reviewMimeType, setReviewMimeType] = useState<string | null>(null);
const [recordingMode] = useRecordingMode();
const userEmail = useAuthStore((s) => s.user?.email); const userEmail = useAuthStore((s) => s.user?.email);
const createParticle = useCreateParticle(); const createParticle = useCreateParticle();
// Refs to avoid stale closures in keyboard handler
const stepRef = useRef(step);
stepRef.current = step;
// Notify parent when active state changes
useEffect(() => {
onActiveChange?.(step !== "idle");
}, [step, onActiveChange]);
const cancel = useCallback(() => {
setStep("idle");
setError(null);
setTextContent("");
setMediaStream(null);
setReviewBlob(null);
setReviewDurationMs(0);
setReviewMimeType(null);
}, []);
const { startRecording, stopRecording, cancelRecording } = useRecorder({
mode: recordingMode,
onStreamReady: (stream) => setMediaStream(stream),
onStreamCleanup: () => setMediaStream(null),
onFinish: (blob, durationMs, mimeType) => {
setStep("reviewing");
setReviewBlob(blob);
setReviewDurationMs(durationMs);
setReviewMimeType(mimeType);
},
onError: (message) => setError(message),
});
// --- Submission ---
const uploadMedia = useCallback(
async (blob: Blob, mimeType: string) => {
const ext = "webm";
const fileName = `recording-${Date.now()}.${ext}`;
const { object_id, upload_url, upload_headers } =
await apiClient.prepareUpload({
network_id: networkId,
name: fileName,
content_type: mimeType,
content_length: blob.size,
});
await fetch(upload_url, {
method: "PUT",
headers: upload_headers,
body: blob,
});
await apiClient.confirmUpload(object_id);
return { object_id, size_bytes: blob.size };
},
[networkId],
);
const createChildParticle = useCallback(
async (collectionPath: string) => {
if (!userEmail) return;
if (textContent.trim()) {
await createParticle.mutateAsync({
collectionPath,
type: "text",
properties: { content: textContent },
createdByEmail: userEmail,
});
} else if (reviewBlob && reviewMimeType) {
const { object_id, size_bytes } = await uploadMedia(
reviewBlob,
reviewMimeType,
);
await createParticle.mutateAsync({
collectionPath,
type: "media",
properties: {
object_id,
mime_type: reviewMimeType,
duration_ms: reviewDurationMs,
size_bytes,
},
createdByEmail: userEmail,
});
}
},
[
userEmail,
textContent,
reviewBlob,
reviewMimeType,
reviewDurationMs,
createParticle,
uploadMedia,
],
);
// Reply mode: create particle directly under targetPath
const submitReply = useCallback(async () => {
if (!targetPath || !userEmail) return;
const collectionPath = toFirestoreChildrenPath(targetPath);
await createChildParticle(collectionPath);
cancel();
}, [targetPath, userEmail, createChildParticle, cancel]);
const submitReplyRef = useRef(submitReply);
submitReplyRef.current = submitReply;
// New stream mode: create stream + first child
const handleStreamSubmit = useCallback( const handleStreamSubmit = useCallback(
async (streamName: string, visibleTo: string[]) => { async (streamName: string, visibleTo: string[]) => {
if (!networkId || !userEmail) return; if (!userEmail) return;
const collectionPath = toFirestoreChildrenPath(particlePath(networkId)); const collectionPath = toFirestoreChildrenPath(particlePath(networkId));
await createParticle.mutateAsync({ const streamId = await createParticle.mutateAsync({
collectionPath, collectionPath,
type: "stream", type: "stream",
properties: { properties: {
@@ -43,13 +169,96 @@ export function ComposeOverlay() {
createdByEmail: userEmail, createdByEmail: userEmail,
}); });
const streamChildrenPath = toFirestoreChildrenPath(
particlePath(networkId, [streamId]),
);
await createChildParticle(streamChildrenPath);
cancel(); cancel();
}, },
[networkId, userEmail, createParticle, cancel], [networkId, userEmail, createParticle, createChildParticle, cancel],
); );
// --- Keyboard handling ---
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const currentStep = stepRef.current;
if (currentStep === "typing" || currentStep === "configuring") return;
const target = e.target as HTMLElement;
if (
target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable
) {
return;
}
switch (currentStep) {
case "idle": {
if (e.key === "`" && !e.repeat) {
e.preventDefault();
setStep("recording");
startRecording();
} else if (e.key === "t" || e.key === "T") {
e.preventDefault();
setStep("typing");
}
break;
}
case "recording": {
if (e.key === "q" || e.key === "Q" || e.key === "Escape") {
e.preventDefault();
cancelRecording();
cancel();
}
break;
}
case "reviewing": {
if (e.key === "q" || e.key === "Q" || e.key === "Escape") {
e.preventDefault();
cancelRecording();
cancel();
} else if (e.key === "Enter") {
e.preventDefault();
if (targetPath) {
submitReplyRef.current();
} else {
setStep("configuring");
}
}
break;
}
}
};
const handleKeyUp = (e: KeyboardEvent) => {
if (stepRef.current === "recording" && e.key === "`") {
e.preventDefault();
stopRecording();
}
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
}, [targetPath, startRecording, stopRecording, cancelRecording, cancel]);
// --- Render ---
if (step === "idle") return null; if (step === "idle") return null;
const handleTextAdvance = targetPath
? submitReply
: () => setStep("configuring");
return ( return (
<> <>
{(step === "recording" || step === "reviewing") && ( {(step === "recording" || step === "reviewing") && (
@@ -66,11 +275,11 @@ export function ComposeOverlay() {
<TextComposeStep <TextComposeStep
textContent={textContent} textContent={textContent}
onTextChange={setTextContent} onTextChange={setTextContent}
onAdvance={advanceToConfigure} onAdvance={handleTextAdvance}
onCancel={cancel} onCancel={cancel}
/> />
)} )}
{step === "configuring" && ( {!targetPath && step === "configuring" && (
<ConfigureStreamStep <ConfigureStreamStep
networkId={networkId} networkId={networkId}
onCancel={cancel} onCancel={cancel}
@@ -1,5 +1,5 @@
import { Video, Mic } from "lucide-react"; import { Video, Mic } from "lucide-react";
import { useComposeStore } from "@/stores/compose-store"; import { useRecordingMode } from "@/hooks/use-recording-mode";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -7,8 +7,7 @@ interface ControlsIndicatorProps {
type: "reply" | "new"; type: "reply" | "new";
} }
export default function ControlsIndicator({ type }: ControlsIndicatorProps) { export default function ControlsIndicator({ type }: ControlsIndicatorProps) {
const recordingMode = useComposeStore((s) => s.recordingMode); const [recordingMode, setRecordingMode] = useRecordingMode();
const setRecordingMode = useComposeStore((s) => s.setRecordingMode);
return ( return (
<div className="flex items-center gap-2 text-xs"> <div className="flex items-center gap-2 text-xs">
@@ -23,7 +22,7 @@ export default function ControlsIndicator({ type }: ControlsIndicatorProps) {
} }
variant="secondary" variant="secondary"
className={cn( className={cn(
"text-xs", "text-xs rounded-full",
"text-muted-foreground hover:text-white/90", "text-muted-foreground hover:text-white/90",
)} )}
> >
@@ -1,10 +1,10 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import type { ComposeStep, RecordingMode } from "@/stores/compose-store"; import type { RecordingMode } from "@/hooks/use-recording-mode";
import { AudioLevelBars } from "@/components/audio/audio-level-bars"; import { AudioLevelBars } from "@/components/audio/audio-level-bars";
import { useAudioSource } from "@/components/audio/use-audio-source"; import { useAudioSource } from "@/components/audio/use-audio-source";
interface RecordingOverlayProps { interface RecordingOverlayProps {
step: ComposeStep; step: "recording" | "reviewing";
mediaStream: MediaStream | null; mediaStream: MediaStream | null;
recordingMode: RecordingMode; recordingMode: RecordingMode;
reviewBlob: Blob | null; reviewBlob: Blob | null;
@@ -1,110 +0,0 @@
import { useEffect, useCallback } from "react";
import { useComposeStore } from "@/stores/compose-store";
import { useRecorder } from "@/features/compose/use-recorder";
import { useParams } from "react-router-dom";
/**
* Global keyboard handler for the compose flow.
*
* Handles keys for idle, recording, and reviewing steps.
* The typing and configuring steps handle their own keyboard
* events via focused elements — this hook ignores those steps.
*/
export function useComposeKeyboard() {
const networkId = useParams()["networkId"];
const recordingMode = useComposeStore((s) => s.recordingMode);
const setMediaStream = useComposeStore((s) => s.setMediaStream);
const finishRecording = useComposeStore((s) => s.finishRecording);
const setError = useComposeStore((s) => s.setError);
const beginRecording = useComposeStore((s) => s.startRecording);
const beginTyping = useComposeStore((s) => s.startTyping);
const cancel = useComposeStore((s) => s.cancel);
const advanceToConfigure = useComposeStore((s) => s.advanceToConfigure);
const { startRecording, stopRecording, cancelRecording } = useRecorder({
mode: recordingMode,
onStreamReady: (stream) => setMediaStream(stream),
onStreamCleanup: () => setMediaStream(null),
onFinish: (blob, durationMs) => finishRecording(blob, durationMs),
onError: (message) => setError(message),
});
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
const { step } = useComposeStore.getState();
// Typing and configuring steps own their focused keyboard events
if (step === "typing" || step === "configuring") return;
// Don't intercept if the user is typing in an unrelated input
const target = e.target as HTMLElement;
if (
target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.isContentEditable
) {
return;
}
switch (step) {
case "idle": {
if (!networkId) return;
if (e.key === "`" && !e.repeat) {
e.preventDefault();
beginRecording(networkId);
startRecording();
} else if (e.key === "t" || e.key === "T") {
e.preventDefault();
beginTyping(networkId);
}
break;
}
case "recording": {
if (e.key === "q" || e.key === "Q" || e.key === "Escape") {
e.preventDefault();
cancelRecording();
cancel();
}
break;
}
case "reviewing": {
if (e.key === "q" || e.key === "Q" || e.key === "Escape") {
e.preventDefault();
cancelRecording();
cancel();
} else if (e.key === "Enter") {
e.preventDefault();
advanceToConfigure();
}
break;
}
}
},
[networkId, startRecording, cancelRecording, beginRecording, beginTyping, cancel, advanceToConfigure],
);
const handleKeyUp = useCallback(
(e: KeyboardEvent) => {
const { step } = useComposeStore.getState();
if (step === "recording" && e.key === "`") {
e.preventDefault();
stopRecording();
// finishRecording is called by the MediaRecorder onstop handler
// once the blob is ready — no need to call it here.
}
},
[stopRecording],
);
useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
}, [handleKeyDown, handleKeyUp]);
}
+3 -3
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef } from "react"; import { useCallback, useEffect, useRef } from "react";
import type { RecordingMode } from "@/stores/compose-store"; import type { RecordingMode } from "@/hooks/use-recording-mode";
const VIDEO_PREFERRED_MIME = "video/webm;codecs=vp9,opus"; const VIDEO_PREFERRED_MIME = "video/webm;codecs=vp9,opus";
const VIDEO_FALLBACK_MIME = "video/webm"; const VIDEO_FALLBACK_MIME = "video/webm";
@@ -21,7 +21,7 @@ interface UseRecorderOptions {
mode: RecordingMode; mode: RecordingMode;
onStreamReady: (stream: MediaStream) => void; onStreamReady: (stream: MediaStream) => void;
onStreamCleanup: () => void; onStreamCleanup: () => void;
onFinish: (blob: Blob, durationMs: number) => void; onFinish: (blob: Blob, durationMs: number, mimeType: string) => void;
onError: (message: string) => void; onError: (message: string) => void;
} }
@@ -86,7 +86,7 @@ export function useRecorder({
stopTracks(); stopTracks();
if (blob.size > 0) { if (blob.size > 0) {
onFinishRef.current(blob, durationMs); onFinishRef.current(blob, durationMs, mime);
} }
}; };
-2
View File
@@ -12,7 +12,6 @@ import {
} from "@/components/ui/breadcrumb"; } from "@/components/ui/breadcrumb";
import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useNetworks } from "@/hooks/use-networks"; import { useNetworks } from "@/hooks/use-networks";
import { ComposeOverlay } from "@/features/compose/compose-overlay";
function NetworkBreadcrumbContent({ networkId }: { networkId: string }) { function NetworkBreadcrumbContent({ networkId }: { networkId: string }) {
const { data: networks } = useNetworks(); const { data: networks } = useNetworks();
@@ -123,7 +122,6 @@ export default function LayoutWithPath() {
<TopBar /> <TopBar />
<div className="relative flex-1 overflow-hidden"> <div className="relative flex-1 overflow-hidden">
<Outlet /> <Outlet />
<ComposeOverlay />
</div> </div>
</div> </div>
); );
+7 -3
View File
@@ -1,7 +1,8 @@
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { particlePath } from "@/lib/particle-path"; import { particlePath } from "@/lib/particle-path";
import { ParticleListView } from "@/features/particles/particle-list-view"; import { ParticleListView } from "@/features/particles/particle-list-view";
import { useComposeKeyboard } from "@/features/compose/use-compose-keyboard"; import ControlsIndicator from "@/features/compose/controls-indicator";
import { ComposeOverlay } from "./compose/compose-overlay";
/** /**
* Route-level component for /:networkId (index). * Route-level component for /:networkId (index).
@@ -10,9 +11,12 @@ import { useComposeKeyboard } from "@/features/compose/use-compose-keyboard";
export default function NetworkRoot() { export default function NetworkRoot() {
const { networkId } = useParams(); const { networkId } = useParams();
const path = particlePath(networkId!, []); const path = particlePath(networkId!, []);
useComposeKeyboard();
return ( return (
<ParticleListView path={path} /> <>
<ParticleListView path={path} />
<ControlsIndicator type={"new"} />
<ComposeOverlay networkId={networkId!} />
</>
); );
} }
+4 -3
View File
@@ -1,7 +1,7 @@
import { Particle } from "@/api/types"; import { Particle } from "@/api/types";
import { useLiveParticleChildren } from "@/hooks/use-particle"; import { useLiveParticleChildren } from "@/hooks/use-particle";
import type { ParticlePath } from "@/lib/particle-path"; import { parseParticlePath, type ParticlePath } from "@/lib/particle-path";
import { useComposeKeyboard } from "@/features/compose/use-compose-keyboard"; import { ComposeOverlay } from "@/features/compose/compose-overlay";
interface FolderViewProps { interface FolderViewProps {
folderParticle: Particle; folderParticle: Particle;
@@ -9,14 +9,15 @@ interface FolderViewProps {
} }
export function FolderView({ path, folderParticle }: FolderViewProps) { export function FolderView({ path, folderParticle }: FolderViewProps) {
useComposeKeyboard();
const { children, error, isLoading } = useLiveParticleChildren(path); const { children, error, isLoading } = useLiveParticleChildren(path);
const { networkId } = parseParticlePath(path);
return ( return (
<div className="flex h-full items-center justify-center"> <div className="flex h-full items-center justify-center">
<p className="text-muted-foreground text-sm"> <p className="text-muted-foreground text-sm">
Folder view {folderParticle.id} Folder view {folderParticle.id}
</p> </p>
<ComposeOverlay networkId={networkId} />
</div> </div>
); );
} }
@@ -1,5 +1,4 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { useComposeKeyboard } from "@/features/compose/use-compose-keyboard";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Radio } from "lucide-react"; import { Radio } from "lucide-react";
import { useLiveParticleChildren } from "@/hooks/use-particle"; import { useLiveParticleChildren } from "@/hooks/use-particle";
@@ -9,7 +8,6 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { Small } from "@/components/ui/typography"; import { Small } from "@/components/ui/typography";
import ControlsIndicator from "@/features/compose/controls-indicator";
import type { Particle, StreamProperties } from "@/api/types"; import type { Particle, StreamProperties } from "@/api/types";
function StreamRow({ function StreamRow({
@@ -55,7 +53,6 @@ interface ParticleListViewProps {
* List of stream particles for a container (network root, folder, etc.). * List of stream particles for a container (network root, folder, etc.).
*/ */
export function ParticleListView({ path }: ParticleListViewProps) { export function ParticleListView({ path }: ParticleListViewProps) {
useComposeKeyboard();
const { children, isLoading } = useLiveParticleChildren(path); const { children, isLoading } = useLiveParticleChildren(path);
const { networkId } = parseParticlePath(path); const { networkId } = parseParticlePath(path);
const navigate = useNavigate(); const navigate = useNavigate();
@@ -69,14 +66,6 @@ export function ParticleListView({ path }: ParticleListViewProps) {
return <Progress />; return <Progress />;
} }
if (streams.length === 0) {
return (
<div className="flex flex-col h-full items-center justify-center gap-2">
<ControlsIndicator type={"new"} />
</div>
);
}
return ( return (
<ScrollArea className="h-full"> <ScrollArea className="h-full">
<div className="py-1"> <div className="py-1">
+138 -47
View File
@@ -1,16 +1,93 @@
import { useEffect, useCallback } from "react"; import { useState, useEffect, useCallback, useReducer } from "react";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import type { Particle } from "@/api/types"; import type { Particle } from "@/api/types";
import { useLiveParticleChildren } from "@/hooks/use-particle"; import { useLiveParticleChildren } from "@/hooks/use-particle";
import type { ParticlePath } from "@/lib/particle-path"; import type { ParticlePath } from "@/lib/particle-path";
import { usePlaybackStore } from "@/stores/playback-store"; import { ComposeOverlay } from "@/features/compose/compose-overlay";
import { useComposeStore } from "@/stores/compose-store";
import { useComposeKeyboard } from "@/features/compose/use-compose-keyboard";
import { PlaybackPageIndicator } from "@/features/playback/playback-page-indicator"; import { PlaybackPageIndicator } from "@/features/playback/playback-page-indicator";
import { ParticleRenderer } from "@/features/playback/particle-renderer"; import { ParticleRenderer } from "@/features/playback/particle-renderer";
import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import ControlsIndicator from "@/features/compose/controls-indicator"; import ControlsIndicator from "@/features/compose/controls-indicator";
// --- Playback reducer ---
type PlaybackStatus = "idle" | "playing" | "ended";
interface PlaybackState {
currentIndex: number;
status: PlaybackStatus;
paused: boolean;
}
type PlaybackAction =
| { type: "INIT"; particleCount: number }
| { type: "NEXT"; particleCount: number }
| { type: "PREV" }
| { type: "GO_TO"; index: number; particleCount: number }
| { type: "PAUSE" }
| { type: "RESUME" }
| { type: "SYNC_PARTICLES"; particleCount: number };
function playbackReducer(
state: PlaybackState,
action: PlaybackAction,
): PlaybackState {
switch (action.type) {
case "INIT":
return {
currentIndex: 0,
status: action.particleCount > 0 ? "playing" : "idle",
paused: false,
};
case "NEXT":
if (state.currentIndex < action.particleCount - 1) {
return { ...state, currentIndex: state.currentIndex + 1, paused: false };
}
return { ...state, status: "ended", paused: false };
case "PREV":
if (state.currentIndex > 0) {
return {
...state,
currentIndex: state.currentIndex - 1,
status: "playing",
paused: false,
};
}
return state;
case "GO_TO":
if (action.index >= 0 && action.index < action.particleCount) {
return {
...state,
currentIndex: action.index,
status: "playing",
paused: false,
};
}
return state;
case "PAUSE":
return { ...state, paused: true };
case "RESUME":
return { ...state, paused: false };
case "SYNC_PARTICLES":
// Clamp index if particles were removed; don't reset position
if (action.particleCount === 0) {
return { currentIndex: 0, status: "idle", paused: state.paused };
}
if (state.currentIndex >= action.particleCount) {
return { ...state, currentIndex: action.particleCount - 1 };
}
return state;
}
}
const initialState: PlaybackState = {
currentIndex: 0,
status: "idle",
paused: false,
};
// --- StreamView ---
interface StreamViewProps { interface StreamViewProps {
streamParticle: Particle; streamParticle: Particle;
path: ParticlePath; path: ParticlePath;
@@ -21,44 +98,44 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const { children } = useLiveParticleChildren(path); const { children } = useLiveParticleChildren(path);
const status = usePlaybackStore((s) => s.status); const [state, dispatch] = useReducer(playbackReducer, initialState);
const currentIndex = usePlaybackStore((s) => s.currentIndex); const [composeActive, setComposeActive] = useState(false);
const particles = usePlaybackStore((s) => s.particles);
const initStream = usePlaybackStore((s) => s.initStream);
const goTo = usePlaybackStore((s) => s.goTo);
const next = usePlaybackStore((s) => s.next);
const prev = usePlaybackStore((s) => s.prev);
const pause = usePlaybackStore((s) => s.pause);
const resume = usePlaybackStore((s) => s.resume);
const reset = usePlaybackStore((s) => s.reset);
// Compose keyboard (backtick, t, q, escape-during-compose) // Init playback when the stream particle changes
useComposeKeyboard();
// Init playback when children change
useEffect(() => { useEffect(() => {
if (children.length > 0) { dispatch({ type: "INIT", particleCount: children.length });
initStream(streamParticle.id, children, 0); }, [streamParticle.id]);
}
return () => reset(); // Sync when children list changes (e.g. new particle appended via Firestore)
}, [children, streamParticle.id, initStream, reset]); useEffect(() => {
dispatch({ type: "SYNC_PARTICLES", particleCount: children.length });
}, [children.length]);
// Pause/resume playback when compose overlay opens/closes // Pause/resume playback when compose overlay opens/closes
useEffect(() => { useEffect(() => {
return useComposeStore.subscribe((state) => { if (composeActive) dispatch({ type: "PAUSE" });
if (state.step !== "idle") { else dispatch({ type: "RESUME" });
pause(); }, [composeActive]);
} else {
resume(); const next = useCallback(() => {
} dispatch({ type: "NEXT", particleCount: children.length });
}); }, [children.length]);
}, [pause, resume]);
const prev = useCallback(() => {
dispatch({ type: "PREV" });
}, []);
const goTo = useCallback(
(index: number) => {
dispatch({ type: "GO_TO", index, particleCount: children.length });
},
[children.length],
);
// Playback keyboard: arrows, escape // Playback keyboard: arrows, escape
const handleKeyDown = useCallback( const handleKeyDown = useCallback(
(e: KeyboardEvent) => { (e: KeyboardEvent) => {
const composeStep = useComposeStore.getState().step; if (composeActive) return;
if (composeStep !== "idle") return;
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
if ( if (
@@ -86,7 +163,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
break; break;
} }
}, },
[next, prev, navigate, networkId], [composeActive, next, prev, navigate, networkId],
); );
useEffect(() => { useEffect(() => {
@@ -94,7 +171,7 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
return () => window.removeEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown);
}, [handleKeyDown]); }, [handleKeyDown]);
const currentParticle = particles[currentIndex] ?? null; const currentParticle = children[state.currentIndex] ?? null;
// Stream name from properties (narrowed to stream type) // Stream name from properties (narrowed to stream type)
const streamName = const streamName =
@@ -113,6 +190,11 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
No particles in this stream yet No particles in this stream yet
</p> </p>
<ControlsIndicator type="reply" /> <ControlsIndicator type="reply" />
<ComposeOverlay
networkId={networkId!}
targetPath={path}
onActiveChange={setComposeActive}
/>
</div> </div>
); );
} }
@@ -120,10 +202,10 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
return ( return (
<div className="relative flex h-full flex-col bg-black text-white"> <div className="relative flex h-full flex-col bg-black text-white">
{/* Progress indicator */} {/* Progress indicator */}
<div className="z-10 pt-1"> <div className="z-10 absolute left-0 right-0">
<PlaybackPageIndicator <PlaybackPageIndicator
total={particles.length} total={children.length}
current={currentIndex} current={state.currentIndex}
onGoTo={goTo} onGoTo={goTo}
/> />
</div> </div>
@@ -144,18 +226,27 @@ export function StreamView({ path, streamParticle }: StreamViewProps) {
{/* Main playback area */} {/* Main playback area */}
<div className="flex-1 overflow-hidden"> <div className="flex-1 overflow-hidden">
{currentParticle && status !== "ended" ? ( {currentParticle && (
<ParticleRenderer particle={currentParticle} /> <ParticleRenderer
) : ( particle={currentParticle}
<div className="flex h-full items-center justify-center"> paused={state.paused}
<p className="text-muted-foreground text-sm">End of stream</p> onNext={next}
</div> onPrev={prev}
/>
)} )}
</div> </div>
{/* Stream name overlay */} <ComposeOverlay
<div className="z-10 flex items-center justify-center pb-3 pt-1"> networkId={networkId!}
<span className="text-sm font-medium text-white/60">{streamName}</span> targetPath={path}
onActiveChange={setComposeActive}
/>
{/* Bottom overlay: stream info + reply */}
<div className="absolute right-0 bottom-0 z-10 flex justify-center p-2">
<div className="flex w-full items-center gap-2.5 rounded-full bg-black/30 px-2 py-2 backdrop-blur-sm">
<ControlsIndicator type={"reply"} />
</div>
</div> </div>
</div> </div>
); );
@@ -1,13 +1,14 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import type { Particle } from "@/api/types"; import type { Particle } from "@/api/types";
import { apiClient } from "@/api/client"; import { useDownloadUrl } from "@/hooks/use-download-url";
import { usePlaybackStore } from "@/stores/playback-store";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
type MediaParticle = Extract<Particle, { type: "media" }>; type MediaParticle = Extract<Particle, { type: "media" }>;
interface MediaParticleViewProps { interface MediaParticleViewProps {
particle: MediaParticle; particle: MediaParticle;
paused: boolean;
onEnded: () => void;
} }
function formatTime(ms: number): string { function formatTime(ms: number): string {
@@ -35,14 +36,10 @@ function DurationPill({
export function MediaParticleView({ export function MediaParticleView({
particle, particle,
paused,
onEnded,
}: MediaParticleViewProps) { }: MediaParticleViewProps) {
const cachedUrl = usePlaybackStore( const { data: url, error } = useDownloadUrl(particle.properties.object_id);
(s) => s.downloadUrlCache[particle.id],
);
const cacheDownloadUrl = usePlaybackStore((s) => s.cacheDownloadUrl);
const next = usePlaybackStore((s) => s.next);
const paused = usePlaybackStore((s) => s.paused);
const [error, setError] = useState<string | null>(null);
const videoRef = useRef<HTMLVideoElement>(null); const videoRef = useRef<HTMLVideoElement>(null);
const audioRef = useRef<HTMLAudioElement>(null); const audioRef = useRef<HTMLAudioElement>(null);
@@ -50,25 +47,6 @@ export function MediaParticleView({
const isAudio = particle.properties.mime_type?.startsWith("audio/"); const isAudio = particle.properties.mime_type?.startsWith("audio/");
useEffect(() => {
if (cachedUrl) return;
let cancelled = false;
apiClient
.getParticleDownloadUrl(particle.properties.object_id)
.then((downloadUrl) => {
if (cancelled) return;
cacheDownloadUrl(particle.id, downloadUrl);
})
.catch(() => {
if (!cancelled) setError("Failed to load media");
});
return () => {
cancelled = true;
};
}, [particle.id, particle.properties.object_id, cacheDownloadUrl]);
useEffect(() => { useEffect(() => {
const el = isAudio ? audioRef.current : videoRef.current; const el = isAudio ? audioRef.current : videoRef.current;
if (!el) return; if (!el) return;
@@ -80,17 +58,17 @@ export function MediaParticleView({
console.warn("Playback failed", { particleId: particle.id }); console.warn("Playback failed", { particleId: particle.id });
}); });
} }
}, [paused]); }, [paused, isAudio, particle.id]);
if (error) { if (error) {
return ( return (
<div className="text-muted-foreground flex items-center justify-center text-sm"> <div className="text-muted-foreground flex items-center justify-center text-sm">
{error} Failed to load media
</div> </div>
); );
} }
if (!cachedUrl) { if (!url) {
return <Skeleton className="h-full w-full rounded-none" />; return <Skeleton className="h-full w-full rounded-none" />;
} }
@@ -100,9 +78,9 @@ export function MediaParticleView({
<audio <audio
ref={audioRef} ref={audioRef}
crossOrigin="anonymous" crossOrigin="anonymous"
src={cachedUrl} src={url}
autoPlay autoPlay
onEnded={next} onEnded={onEnded}
onTimeUpdate={(e) => { onTimeUpdate={(e) => {
setCurrentTimeMs(e.currentTarget.currentTime * 1000); setCurrentTimeMs(e.currentTarget.currentTime * 1000);
}} }}
@@ -120,10 +98,10 @@ export function MediaParticleView({
<div className="relative h-full w-full"> <div className="relative h-full w-full">
<video <video
ref={videoRef} ref={videoRef}
src={cachedUrl} src={url}
autoPlay autoPlay
playsInline playsInline
onEnded={next} onEnded={onEnded}
onTimeUpdate={(e) => { onTimeUpdate={(e) => {
setCurrentTimeMs(e.currentTarget.currentTime * 1000); setCurrentTimeMs(e.currentTarget.currentTime * 1000);
}} }}
+26 -9
View File
@@ -1,24 +1,26 @@
import type { Particle } from "@/api/types"; import type { Particle } from "@/api/types";
import { usePlaybackStore } from "@/stores/playback-store";
import { MediaParticleView } from "./media-particle-view"; import { MediaParticleView } from "./media-particle-view";
import { TextParticleView } from "./text-particle-view"; import { TextParticleView } from "./text-particle-view";
import { FallbackParticleView } from "./fallback-particle-view"; import { FallbackParticleView } from "./fallback-particle-view";
interface ParticleRendererProps { interface ParticleRendererProps {
particle: Particle; particle: Particle;
paused: boolean;
onNext: () => void;
onPrev: () => void;
} }
export function ParticleRenderer({ export function ParticleRenderer({
particle, particle,
paused,
onNext,
onPrev,
}: ParticleRendererProps) { }: ParticleRendererProps) {
const next = usePlaybackStore((s) => s.next);
const prev = usePlaybackStore((s) => s.prev);
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => { const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect(); const rect = e.currentTarget.getBoundingClientRect();
const x = (e.clientX - rect.left) / rect.width; const x = (e.clientX - rect.left) / rect.width;
if (x < 0.3) prev(); if (x < 0.3) onPrev();
else if (x > 0.7) next(); else if (x > 0.7) onNext();
}; };
return ( return (
@@ -26,15 +28,30 @@ export function ParticleRenderer({
className="relative flex h-full w-full cursor-pointer items-center justify-center" className="relative flex h-full w-full cursor-pointer items-center justify-center"
onClick={handleClick} onClick={handleClick}
> >
<ParticleContent particle={particle} /> <ParticleContent particle={particle} paused={paused} onEnded={onNext} />
</div> </div>
); );
} }
function ParticleContent({ particle }: { particle: Particle }) { function ParticleContent({
particle,
paused,
onEnded,
}: {
particle: Particle;
paused: boolean;
onEnded: () => void;
}) {
switch (particle.type) { switch (particle.type) {
case "media": case "media":
return <MediaParticleView key={particle.id} particle={particle} />; return (
<MediaParticleView
key={particle.id}
particle={particle}
paused={paused}
onEnded={onEnded}
/>
);
case "text": case "text":
return <TextParticleView particle={particle} />; return <TextParticleView particle={particle} />;
default: default:
+9
View File
@@ -0,0 +1,9 @@
import { useQuery } from "@tanstack/react-query";
import { apiClient } from "@/api/client";
export function useDownloadUrl(objectId: string) {
return useQuery({
queryKey: ["download-url", objectId],
queryFn: () => apiClient.getParticleDownloadUrl(objectId),
});
}
+19
View File
@@ -0,0 +1,19 @@
import { useState, useCallback } from "react";
export type RecordingMode = "video" | "audio";
const KEY = "llink:recording-mode";
export function useRecordingMode(): [RecordingMode, (mode: RecordingMode) => void] {
const [mode, setModeState] = useState<RecordingMode>(() => {
const stored = localStorage.getItem(KEY);
return stored === "audio" ? "audio" : "video";
});
const setMode = useCallback((m: RecordingMode) => {
localStorage.setItem(KEY, m);
setModeState(m);
}, []);
return [mode, setMode];
}
+1
View File
@@ -87,6 +87,7 @@ export function subscribeToParticleChildren(
); );
} }
// This creates a new particle document with the given properties and returns its ID.
export async function createParticle<T extends ParticleType>( export async function createParticle<T extends ParticleType>(
collectionPath: string, collectionPath: string,
type: T, type: T,
-106
View File
@@ -1,106 +0,0 @@
import { create } from "zustand";
export type ComposeStep =
| "idle"
| "recording"
| "reviewing"
| "typing"
| "configuring";
export type RecordingMode = "video" | "audio";
const RECORDING_MODE_KEY = "llink:recording-mode";
function loadRecordingMode(): RecordingMode {
const stored = localStorage.getItem(RECORDING_MODE_KEY);
return stored === "audio" ? "audio" : "video";
}
interface ComposeState {
// Flow
step: ComposeStep;
networkId: string | null;
error: string | null;
// Text compose
textContent: string;
// Recording
recordingMode: RecordingMode;
mediaStream: MediaStream | null;
reviewBlob: Blob | null;
reviewDurationMs: number;
// Transitions
startRecording: (networkId: string) => void;
finishRecording: (blob: Blob, durationMs: number) => void;
startTyping: (networkId: string) => void;
advanceToConfigure: () => void;
setTextContent: (text: string) => void;
cancel: () => void;
// Recording helpers (called by useRecorder)
setMediaStream: (stream: MediaStream | null) => void;
setRecordingMode: (mode: RecordingMode) => void;
setError: (error: string) => void;
}
export const useComposeStore = create<ComposeState>((set, get) => ({
step: "idle",
networkId: null,
error: null,
textContent: "",
recordingMode: loadRecordingMode(),
mediaStream: null,
reviewBlob: null,
reviewDurationMs: 0,
startRecording: (networkId) => {
if (get().step !== "idle") return;
set({
step: "recording",
networkId,
error: null,
reviewBlob: null,
reviewDurationMs: 0,
});
},
finishRecording: (blob, durationMs) => {
if (get().step !== "recording") return;
set({ step: "reviewing", reviewBlob: blob, reviewDurationMs: durationMs });
},
startTyping: (networkId) => {
if (get().step !== "idle") return;
set({ step: "typing", networkId, textContent: "", error: null });
},
advanceToConfigure: () => {
const { step } = get();
if (step !== "reviewing" && step !== "typing") return;
set({ step: "configuring" });
},
setTextContent: (textContent) => set({ textContent }),
cancel: () =>
set({
step: "idle",
networkId: null,
error: null,
textContent: "",
mediaStream: null,
reviewBlob: null,
reviewDurationMs: 0,
}),
setMediaStream: (mediaStream) => set({ mediaStream }),
setRecordingMode: (mode) => {
localStorage.setItem(RECORDING_MODE_KEY, mode);
set({ recordingMode: mode });
},
setError: (error) => set({ error }),
}));
-88
View File
@@ -1,88 +0,0 @@
import { create } from "zustand";
import type { Particle } from "@/api/types";
type PlaybackStatus = "idle" | "playing" | "ended";
interface PlaybackState {
streamId: string | null;
particles: Particle[];
currentIndex: number;
status: PlaybackStatus;
paused: boolean;
downloadUrlCache: Record<string, string>;
initStream: (
streamId: string,
particles: Particle[],
startIndex: number,
) => void;
next: () => void;
prev: () => void;
goTo: (index: number) => void;
pause: () => void;
resume: () => void;
cacheDownloadUrl: (particleId: string, url: string) => void;
reset: () => void;
}
export const usePlaybackStore = create<PlaybackState>((set, get) => ({
streamId: null,
particles: [],
currentIndex: 0,
status: "idle",
paused: false,
downloadUrlCache: {},
initStream: (streamId, particles, startIndex) => {
set({
streamId,
particles,
currentIndex: startIndex,
status: particles.length > 0 ? "playing" : "ended",
downloadUrlCache: {},
});
},
next: () => {
const { currentIndex, particles } = get();
if (currentIndex < particles.length - 1) {
set({ currentIndex: currentIndex + 1, paused: false });
} else {
set({ status: "ended", paused: false });
}
},
prev: () => {
const { currentIndex } = get();
if (currentIndex > 0) {
set({ currentIndex: currentIndex - 1, status: "playing", paused: false });
}
},
goTo: (index) => {
const { particles } = get();
if (index >= 0 && index < particles.length) {
set({ currentIndex: index, status: "playing", paused: false });
}
},
pause: () => set({ paused: true }),
resume: () => set({ paused: false }),
cacheDownloadUrl: (particleId, url) => {
set({
downloadUrlCache: { ...get().downloadUrlCache, [particleId]: url },
});
},
reset: () => {
set({
streamId: null,
particles: [],
currentIndex: 0,
status: "idle",
paused: false,
downloadUrlCache: {},
});
},
}));