feat: initial conversational flow (#37)
* chore: only set visibility for container particles * create reusable controls indicator for reply or new * compress the size of top bar * refactor: restructure state, routing, and more * introduce stream compose flow * feat: compose new stream full flow * implement stream player * fix: prevent redirect for signed object urls * fix: implement stream playback cleaner structure * refactor: layout file name * feat: show stream name in breadcrumbs * chore: tweak padding * chore: adjust position of audio bars * feat: show latest particle preview in stream list * fix: remove console log * refactor: reorder classes * fix: avoid passing in updated_at to firestore particle * refactor: extract properties for container particles to flat fields in firestore * make the stream previews look alive * feat: show audio bars during audio clip playback * feat: order streams by last child creation * feat: playback where I left off * chore: remove unused store * fix: recording mode not using shared state * chore: clean unused variable * remove unused imports * fix: improve controls indicator immersion * feat: show playback progress in bar & auto-play text * feat: auto-exit stream on playback completion * fix: jittery media playback progress * fix: navigate during state change is invalid with react router * fix: buggy exit progress when changing clips * feat: add app icon * update package.json info * feat: only show streams visible to me * feat: show seen indicator on particles * fix: prevent unnecessary effects * fix: play new particle after playback is ended * use contols indicator for exit timer
This commit was merged in pull request #37.
This commit is contained in:
@@ -1,20 +1,23 @@
|
||||
import { Particle } from "@/api/types";
|
||||
import { useParticleChildren } from "@/hooks/use-particle-children";
|
||||
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
||||
import { parseParticlePath, type ParticlePath } from "@/lib/particle-path";
|
||||
import { ComposeOverlay } from "@/features/compose/compose-overlay";
|
||||
|
||||
interface FolderViewProps {
|
||||
folderParticle: Particle;
|
||||
networkId: string;
|
||||
particleSegments: string[];
|
||||
path: ParticlePath;
|
||||
}
|
||||
|
||||
export function FolderView({ networkId, particleSegments, folderParticle }: FolderViewProps) {
|
||||
const { children, error, isLoading } = useParticleChildren(networkId, particleSegments);
|
||||
export function FolderView({ path, folderParticle }: FolderViewProps) {
|
||||
const { children, error, isLoading } = useLiveParticleChildren(path);
|
||||
const { networkId } = parseParticlePath(path);
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Folder view — {networkId}/{particleSegments.join("/")}
|
||||
Folder view — {folderParticle.id}
|
||||
</p>
|
||||
<ComposeOverlay networkId={networkId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,43 +1,257 @@
|
||||
import { useParticleChildren } from "@/hooks/use-particle-children";
|
||||
import { useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
Radio,
|
||||
MessageSquare,
|
||||
Video,
|
||||
Mic,
|
||||
Image,
|
||||
FileText,
|
||||
CircleCheck,
|
||||
StickyNote,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useLiveParticleChildren, useLiveLatestChild } from "@/hooks/use-particle";
|
||||
import { useAuthStore } from "@/stores/auth-store";
|
||||
import {
|
||||
parseParticlePath,
|
||||
particlePath,
|
||||
type ParticlePath,
|
||||
} from "@/lib/particle-path";
|
||||
import { getInitials } from "@/lib/utils";
|
||||
import { formatDistanceToNow } from "@/lib/time-utils";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Small } from "@/components/ui/typography";
|
||||
import type { Particle, StreamProperties } from "@/api/types";
|
||||
|
||||
function getParticleTypeIcon(particle: Particle): LucideIcon {
|
||||
switch (particle.type) {
|
||||
case "text":
|
||||
return MessageSquare;
|
||||
case "media": {
|
||||
const mime = particle.properties.mime_type;
|
||||
if (mime.startsWith("video/")) return Video;
|
||||
if (mime.startsWith("audio/")) return Mic;
|
||||
if (mime.startsWith("image/")) return Image;
|
||||
return Video;
|
||||
}
|
||||
case "file":
|
||||
return FileText;
|
||||
case "quest":
|
||||
return CircleCheck;
|
||||
case "paper":
|
||||
return StickyNote;
|
||||
default:
|
||||
return Radio;
|
||||
}
|
||||
}
|
||||
|
||||
function getMessagePreview(particle: Particle): string {
|
||||
switch (particle.type) {
|
||||
case "text":
|
||||
return particle.properties.content;
|
||||
case "media": {
|
||||
const mime = particle.properties.mime_type;
|
||||
if (mime.startsWith("video/")) return "Video clip";
|
||||
if (mime.startsWith("audio/")) return "Voice note";
|
||||
if (mime.startsWith("image/")) return "Photo";
|
||||
return "Media";
|
||||
}
|
||||
case "file":
|
||||
return particle.properties.filename;
|
||||
case "quest":
|
||||
return particle.properties.title;
|
||||
case "paper":
|
||||
return particle.properties.title;
|
||||
default:
|
||||
return particle.type;
|
||||
}
|
||||
}
|
||||
|
||||
function StreamRow({
|
||||
particle,
|
||||
networkId,
|
||||
onClick,
|
||||
}: {
|
||||
particle: Particle & { type: "stream"; properties: StreamProperties };
|
||||
networkId: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const streamPath = particlePath(networkId, [particle.id]);
|
||||
const { latestChild } = useLiveLatestChild(streamPath);
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const userId = user?.id ?? "";
|
||||
const userEmail = user?.email ?? "";
|
||||
|
||||
const isDM =
|
||||
particle.visible_to.length === 2 &&
|
||||
particle.visible_to.every((v) => v.startsWith("human:"));
|
||||
|
||||
const initials = useMemo(() => {
|
||||
if (isDM) {
|
||||
const otherEntry = particle.visible_to.find(
|
||||
(v) => v !== `human:${userEmail}`,
|
||||
);
|
||||
if (otherEntry) {
|
||||
const otherEmail = otherEntry.replace("human:", "");
|
||||
return getInitials(otherEmail);
|
||||
}
|
||||
}
|
||||
return particle.properties.name.slice(0, 2).toUpperCase();
|
||||
}, [isDM, particle.visible_to, particle.properties.name, userEmail]);
|
||||
|
||||
const isUnseen = useMemo(() => {
|
||||
if (!latestChild) return false;
|
||||
const latestChildTimestamp = latestChild.created_at.getTime();
|
||||
const userPlaybackPosition =
|
||||
particle.playback_markers?.[userId]?.getTime() ?? 0;
|
||||
return latestChildTimestamp > userPlaybackPosition;
|
||||
}, [latestChild, particle.playback_markers, userId]);
|
||||
|
||||
const senderPrefix = useMemo(() => {
|
||||
if (!latestChild) return null;
|
||||
const isCurrentUser = latestChild.created_by_email === userEmail;
|
||||
if (isDM) {
|
||||
return isCurrentUser ? "You: " : null;
|
||||
}
|
||||
// Group stream
|
||||
if (isCurrentUser) return "You: ";
|
||||
const emailPrefix = latestChild.created_by_email.split("@")[0];
|
||||
const capitalized =
|
||||
emailPrefix.charAt(0).toUpperCase() + emailPrefix.slice(1);
|
||||
return `${capitalized}: `;
|
||||
}, [latestChild, userEmail, isDM]);
|
||||
|
||||
const subtitle = latestChild
|
||||
? getMessagePreview(latestChild)
|
||||
: particle.properties.status;
|
||||
|
||||
const TypeIcon = latestChild ? getParticleTypeIcon(latestChild) : Radio;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-accent"
|
||||
>
|
||||
<Avatar
|
||||
className={cn(isUnseen && "ring-2 ring-primary")}
|
||||
>
|
||||
<AvatarFallback className="bg-primary/10 text-primary font-medium">
|
||||
{initials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-sm",
|
||||
isUnseen
|
||||
? "font-semibold text-foreground"
|
||||
: "font-medium text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{particle.properties.name}
|
||||
</p>
|
||||
{latestChild && (
|
||||
<Small
|
||||
className={cn(
|
||||
"shrink-0",
|
||||
isUnseen ? "text-primary" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{formatDistanceToNow(latestChild.created_at.toISOString())}
|
||||
</Small>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<TypeIcon
|
||||
className={cn(
|
||||
"size-3.5 shrink-0",
|
||||
isUnseen ? "text-foreground" : "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
<Small
|
||||
className={cn(
|
||||
"truncate",
|
||||
isUnseen
|
||||
? "text-foreground font-medium"
|
||||
: "text-muted-foreground font-normal",
|
||||
)}
|
||||
>
|
||||
{senderPrefix && (
|
||||
<span className="text-muted-foreground">{senderPrefix}</span>
|
||||
)}
|
||||
{subtitle}
|
||||
</Small>
|
||||
</div>
|
||||
</div>
|
||||
{isUnseen && (
|
||||
<span className="size-2 shrink-0 rounded-full bg-primary" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Generates the scopes for filtering particles to those that the user has access to
|
||||
function useVisibilityScopes(
|
||||
userEmail?: string,
|
||||
networkId?: string,
|
||||
) {
|
||||
return useMemo(() => {
|
||||
let scopes: string[] = [];
|
||||
if (userEmail) {
|
||||
scopes.push(`human:${userEmail}`);
|
||||
}
|
||||
if (networkId) {
|
||||
scopes.push(`network:${networkId}`);
|
||||
}
|
||||
return scopes;
|
||||
}, [userEmail, networkId]);
|
||||
}
|
||||
|
||||
interface ParticleListViewProps {
|
||||
networkId: string;
|
||||
particleSegments: string[];
|
||||
path: ParticlePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grid/list of child particles for a container (folder, stream root, or network root).
|
||||
* List of stream particles for a container (network root, folder, etc.).
|
||||
*/
|
||||
export function ParticleListView({ networkId, particleSegments }: ParticleListViewProps) {
|
||||
const { children, isLoading } = useParticleChildren(networkId, particleSegments);
|
||||
export function ParticleListView({ path }: ParticleListViewProps) {
|
||||
const { networkId } = parseParticlePath(path);
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const visibilityScopes = useVisibilityScopes(user?.email, networkId);
|
||||
|
||||
const { children, isLoading } = useLiveParticleChildren(path, "last_child_created_at", "desc", visibilityScopes);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const streams = useMemo(
|
||||
() => children.filter((c) => c.type === "stream"),
|
||||
[children],
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">Loading particles...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (children.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">No particles yet</p>
|
||||
</div>
|
||||
);
|
||||
return <Progress />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 p-4">
|
||||
{children.map((child) => (
|
||||
<div
|
||||
key={child.id}
|
||||
className="rounded-lg border p-3 text-sm"
|
||||
>
|
||||
<p className="font-medium">{child.id}</p>
|
||||
<p className="text-muted-foreground text-xs">{child.type}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<ScrollArea className="h-full">
|
||||
<div className="py-1">
|
||||
{streams.map((stream, index) => (
|
||||
<div key={stream.id}>
|
||||
<StreamRow
|
||||
particle={stream}
|
||||
networkId={networkId}
|
||||
onClick={() => navigate(`/${networkId}/${stream.id}`)}
|
||||
/>
|
||||
{index < streams.length - 1 && <Separator className="mx-4" />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Particle } from "@/api/types";
|
||||
import { apiClient } from "@/api/client";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
Video,
|
||||
Mic,
|
||||
ScrollText,
|
||||
BookOpen,
|
||||
FileIcon,
|
||||
FolderIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
export function ParticlePreview({ particle }: { particle: Particle }) {
|
||||
switch (particle.type) {
|
||||
case "text":
|
||||
return <TextPreview particle={particle} />;
|
||||
case "media":
|
||||
return <MediaPreview particle={particle} />;
|
||||
case "quest":
|
||||
return <QuestPreview particle={particle} />;
|
||||
case "paper":
|
||||
return <PaperPreview particle={particle} />;
|
||||
case "file":
|
||||
return <FilePreview particle={particle} />;
|
||||
case "folder":
|
||||
return <FolderPreview particle={particle} />;
|
||||
default:
|
||||
return <EmptyPreview />;
|
||||
}
|
||||
}
|
||||
|
||||
function TextPreview({ particle }: { particle: Extract<Particle, { type: "text" }> }) {
|
||||
const truncated =
|
||||
particle.properties.content.length > 30
|
||||
? particle.properties.content.slice(0, 30) + "..."
|
||||
: particle.properties.content;
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center p-4">
|
||||
<p className="line-clamp-4 text-center text-4xl leading-relaxed">
|
||||
{truncated}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MediaPreview({ particle }: { particle: Extract<Particle, { type: "media" }> }) {
|
||||
const { mime_type, duration_ms } = particle.properties;
|
||||
const isVideo = mime_type.startsWith("video");
|
||||
const durationSec = Math.round(duration_ms / 1000);
|
||||
const durationLabel = `${Math.floor(durationSec / 60)}:${String(durationSec % 60).padStart(2, "0")}`;
|
||||
|
||||
if (isVideo) {
|
||||
return <VideoThumbnail particleId={particle.id} duration={durationLabel} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-black/90">
|
||||
<Mic className="h-8 w-8 text-white/60" />
|
||||
<span className="font-mono text-xs text-white/50">{durationLabel}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VideoThumbnail({
|
||||
particleId,
|
||||
duration,
|
||||
}: {
|
||||
particleId: string;
|
||||
duration: string;
|
||||
}) {
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
apiClient
|
||||
.getParticleDownloadUrl(particleId)
|
||||
.then((downloadUrl) => {
|
||||
if (!cancelled) setUrl(downloadUrl);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [particleId]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-black/80">
|
||||
<Video className="h-8 w-8 text-white/40" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!url) {
|
||||
return <Skeleton className="h-full w-full rounded-none" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full bg-black">
|
||||
<video
|
||||
src={url}
|
||||
preload="metadata"
|
||||
muted
|
||||
playsInline
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
<span className="absolute right-1.5 bottom-1.5 rounded bg-black/70 px-1.5 py-0.5 font-mono text-[10px] text-white/80">
|
||||
{duration}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestPreview({ particle }: { particle: Extract<Particle, { type: "quest" }> }) {
|
||||
const { title, status } = particle.properties;
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-amber-500/10 p-4">
|
||||
<ScrollText className="h-6 w-6 text-amber-600/70 dark:text-amber-400/70" />
|
||||
<p className="line-clamp-2 text-center text-sm font-medium">
|
||||
{title}
|
||||
</p>
|
||||
{status && (
|
||||
<span className="text-muted-foreground text-[10px] uppercase tracking-wide">
|
||||
{status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PaperPreview({ particle }: { particle: Extract<Particle, { type: "paper" }> }) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-blue-500/10 p-4">
|
||||
<BookOpen className="h-6 w-6 text-blue-600/70 dark:text-blue-400/70" />
|
||||
<p className="line-clamp-2 text-center text-sm font-medium">
|
||||
{particle.properties.title}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FilePreview({ particle }: { particle: Extract<Particle, { type: "file" }> }) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-emerald-500/10 p-4">
|
||||
<FileIcon className="h-6 w-6 text-emerald-600/70 dark:text-emerald-400/70" />
|
||||
<p className="text-muted-foreground line-clamp-1 text-center text-xs">
|
||||
{particle.properties.filename}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FolderPreview({ particle }: { particle: Extract<Particle, { type: "folder" }> }) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-orange-500/10 p-4">
|
||||
<FolderIcon className="h-6 w-6 text-orange-600/70 dark:text-orange-400/70" />
|
||||
<p className="text-muted-foreground line-clamp-1 text-center text-xs">
|
||||
{particle.properties.name}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyPreview() {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-xs italic">No messages yet</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +1,22 @@
|
||||
import { useParticle } from "@/hooks/use-particle";
|
||||
import { StreamView } from "./stream-view";
|
||||
import { FolderView } from "./folder-view";
|
||||
import { ParticleListView } from "./particle-list-view";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useLiveParticle } from "@/hooks/use-particle";
|
||||
import { particlePath } from "@/lib/particle-path";
|
||||
import { isContainerType } from "@/api/types";
|
||||
|
||||
interface ParticleViewResolverProps {
|
||||
networkId: string;
|
||||
particleSegments: string[];
|
||||
}
|
||||
import { StreamView } from "@/features/particles/stream-view";
|
||||
import { FolderView } from "@/features/particles/folder-view";
|
||||
import { ParticleListView } from "@/features/particles/particle-list-view";
|
||||
|
||||
/**
|
||||
* Resolves a particle by its path segments and renders the appropriate view
|
||||
* based on particle type (e.g. stream would show clips in story mode, folder would list files, etc.)
|
||||
* Route-level component for /:networkId/*.
|
||||
* Reads params from the router, resolves the particle, and renders
|
||||
* the appropriate view based on particle type.
|
||||
*/
|
||||
export function ParticleViewResolver({ networkId, particleSegments }: ParticleViewResolverProps) {
|
||||
const { particle, isLoading, error } = useParticle(networkId, particleSegments);
|
||||
export default function ParticleViewResolver() {
|
||||
const { networkId, "*": rest } = useParams();
|
||||
const segments = (rest ?? "").split("/").filter(Boolean);
|
||||
const path = particlePath(networkId!, segments); // path of current container particle
|
||||
|
||||
const { particle, isLoading, error } = useLiveParticle(path);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -32,12 +34,11 @@ export function ParticleViewResolver({ networkId, particleSegments }: ParticleVi
|
||||
);
|
||||
}
|
||||
|
||||
// While the hook is stubbed, particle will be null — show a placeholder
|
||||
if (!particle) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Particle: {particleSegments.join(" / ")}
|
||||
Particle: {segments.join(" / ")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
@@ -45,15 +46,13 @@ export function ParticleViewResolver({ networkId, particleSegments }: ParticleVi
|
||||
|
||||
switch (particle.type) {
|
||||
case "stream":
|
||||
return <StreamView streamParticle={particle} networkId={networkId} particleSegments={particleSegments} />;
|
||||
return <StreamView streamParticle={particle} path={path} />;
|
||||
case "folder":
|
||||
return <FolderView folderParticle={particle} networkId={networkId} particleSegments={particleSegments} />;
|
||||
return <FolderView folderParticle={particle} path={path} />;
|
||||
default:
|
||||
// For container types we haven't built a view for, fall back to list
|
||||
if (isContainerType(particle.type)) {
|
||||
return <ParticleListView networkId={networkId} particleSegments={particleSegments} />;
|
||||
return <ParticleListView path={path} />;
|
||||
}
|
||||
// Leaf particle — placeholder
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
|
||||
@@ -1,36 +1,432 @@
|
||||
import { Particle } from "@/api/types";
|
||||
import { useParticleChildren } from "@/hooks/use-particle-children";
|
||||
import { useState, useEffect, useEffectEvent, useCallback, useReducer, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuthStore } from "@/stores/auth-store";
|
||||
import type { Particle } from "@/api/types";
|
||||
import { useLiveParticleChildren } from "@/hooks/use-particle";
|
||||
import { parseParticlePath, toFirestoreDocPath, type ParticlePath } from "@/lib/particle-path";
|
||||
import { ComposeOverlay } from "@/features/compose/compose-overlay";
|
||||
import { PlaybackPageIndicator } from "@/features/playback/playback-page-indicator";
|
||||
import { MediaParticleView } from "@/features/playback/media-particle-view";
|
||||
import { TextParticleView } from "@/features/playback/text-particle-view";
|
||||
import { FallbackParticleView } from "@/features/playback/fallback-particle-view";
|
||||
import { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar";
|
||||
import ControlsIndicator from "@/features/compose/controls-indicator";
|
||||
import { updateStreamPlaybackMarker } from "@/lib/firestore-particles";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useNetwork } from "@/hooks/use-networks";
|
||||
|
||||
interface StreamViewProps {
|
||||
streamParticle: Particle;
|
||||
networkId: string;
|
||||
particleSegments: string[];
|
||||
// --- Playback reducer ---
|
||||
|
||||
type PlaybackStatus = "idle" | "playing" | "ended";
|
||||
|
||||
interface PlaybackState {
|
||||
currentIndex: number;
|
||||
status: PlaybackStatus;
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
export function StreamView({ networkId, particleSegments, streamParticle }: StreamViewProps) {
|
||||
const { children, error, isLoading } = useParticleChildren(networkId, particleSegments);
|
||||
type PlaybackAction =
|
||||
| { type: "INIT"; particleCount: number, initialIndex?: 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: action.initialIndex ?? 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.status === "ended" && state.currentIndex < action.particleCount - 1) {
|
||||
// New particle appended — resume and advance to it
|
||||
return { ...state, currentIndex: state.currentIndex + 1, status: "playing", paused: false };
|
||||
}
|
||||
if (state.currentIndex >= action.particleCount) {
|
||||
return { ...state, currentIndex: action.particleCount - 1 };
|
||||
}
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
const initialState: PlaybackState = {
|
||||
currentIndex: 0,
|
||||
status: "idle",
|
||||
paused: false,
|
||||
};
|
||||
|
||||
// --- Exit countdown hook ---
|
||||
|
||||
const EXIT_DELAY_MS = 5000;
|
||||
const EXIT_TICK_MS = 100;
|
||||
|
||||
function useExitCountdown(
|
||||
status: PlaybackStatus,
|
||||
composeActive: boolean,
|
||||
onExit: () => void,
|
||||
) {
|
||||
const [remainingMs, setRemainingMs] = useState<number | null>(null);
|
||||
|
||||
const handleExit = useEffectEvent(() => {
|
||||
onExit();
|
||||
});
|
||||
|
||||
// Start/cancel countdown based on playback status
|
||||
useEffect(() => {
|
||||
if (status === "ended") {
|
||||
setRemainingMs(EXIT_DELAY_MS);
|
||||
} else {
|
||||
setRemainingMs(null);
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
// Tick the countdown down (pauses when compose is active)
|
||||
useEffect(() => {
|
||||
if (remainingMs === null || remainingMs <= 0 || composeActive) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setRemainingMs((prev) => {
|
||||
if (prev === null) return null;
|
||||
const next = prev - EXIT_TICK_MS;
|
||||
return next <= 0 ? 0 : next;
|
||||
});
|
||||
}, EXIT_TICK_MS);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [remainingMs !== null && remainingMs > 0, composeActive]);
|
||||
|
||||
// Navigate once countdown hits zero
|
||||
useEffect(() => {
|
||||
if (remainingMs !== null && remainingMs <= 0) {
|
||||
handleExit();
|
||||
}
|
||||
}, [remainingMs]);
|
||||
|
||||
return remainingMs;
|
||||
}
|
||||
|
||||
// --- StreamView ---
|
||||
|
||||
interface StreamViewProps {
|
||||
streamParticle: Particle & { type: "stream" };
|
||||
path: ParticlePath;
|
||||
}
|
||||
|
||||
export function StreamView({ path, streamParticle }: StreamViewProps) {
|
||||
const { networkId } = parseParticlePath(path);
|
||||
const navigate = useNavigate();
|
||||
const { children } = useLiveParticleChildren(path, "created_at", "asc");
|
||||
|
||||
const [state, dispatch] = useReducer(playbackReducer, initialState);
|
||||
const [composeActive, setComposeActive] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const hasInitializedRef = useRef<string | null>(null);
|
||||
|
||||
const handleExitNavigate = useCallback(() => {
|
||||
navigate(`/${networkId}`);
|
||||
}, [navigate, networkId]);
|
||||
|
||||
const exitRemainingMs = useExitCountdown(
|
||||
state.status,
|
||||
composeActive,
|
||||
handleExitNavigate,
|
||||
);
|
||||
|
||||
const userId = useAuthStore((s) => s.user?.id);
|
||||
|
||||
// Reset progress when particle changes
|
||||
useEffect(() => {
|
||||
setProgress(0);
|
||||
}, [state.currentIndex]);
|
||||
|
||||
// Init playback once per stream entry, only after children have loaded
|
||||
useEffect(() => {
|
||||
if (children.length === 0) return;
|
||||
if (hasInitializedRef.current === streamParticle.id) return;
|
||||
hasInitializedRef.current = streamParticle.id;
|
||||
|
||||
const playbackPosition = streamParticle.playback_markers?.[userId ?? ""];
|
||||
let initialIndex = 0;
|
||||
|
||||
if (playbackPosition) {
|
||||
const foundIndex = children.findIndex(
|
||||
(c) => c.created_at.getTime() === playbackPosition.getTime(),
|
||||
);
|
||||
if (foundIndex !== -1) {
|
||||
initialIndex = foundIndex;
|
||||
}
|
||||
}
|
||||
|
||||
dispatch({ type: "INIT", particleCount: children.length, initialIndex });
|
||||
}, [streamParticle.id, userId, children]);
|
||||
|
||||
// Sync on subsequent changes (new particle appended, removed, etc.)
|
||||
useEffect(() => {
|
||||
if (hasInitializedRef.current !== streamParticle.id) return;
|
||||
dispatch({ type: "SYNC_PARTICLES", particleCount: children.length });
|
||||
}, [children.length, streamParticle.id]);
|
||||
|
||||
// Pause/resume playback when compose overlay opens/closes
|
||||
useEffect(() => {
|
||||
if (composeActive) dispatch({ type: "PAUSE" });
|
||||
else dispatch({ type: "RESUME" });
|
||||
}, [composeActive]);
|
||||
|
||||
const next = useCallback(() => {
|
||||
dispatch({ type: "NEXT", particleCount: children.length });
|
||||
}, [children.length]);
|
||||
|
||||
const prev = useCallback(() => {
|
||||
dispatch({ type: "PREV" });
|
||||
}, []);
|
||||
|
||||
const goTo = useCallback(
|
||||
(index: number) => {
|
||||
dispatch({ type: "GO_TO", index, particleCount: children.length });
|
||||
},
|
||||
[children.length],
|
||||
);
|
||||
|
||||
// Click-to-navigate: left 30% = prev, right 70% = next
|
||||
const handlePlaybackClick = useCallback(
|
||||
(e: React.MouseEvent<HTMLDivElement>) => {
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const x = (e.clientX - rect.left) / rect.width;
|
||||
if (x < 0.3) prev();
|
||||
else if (x > 0.7) next();
|
||||
},
|
||||
[prev, next],
|
||||
);
|
||||
|
||||
// Playback keyboard: arrows, escape
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (composeActive) return;
|
||||
|
||||
const target = e.target as HTMLElement;
|
||||
if (
|
||||
target.tagName === "INPUT" ||
|
||||
target.tagName === "TEXTAREA" ||
|
||||
target.isContentEditable
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (e.key) {
|
||||
case "ArrowRight":
|
||||
case "ArrowDown":
|
||||
e.preventDefault();
|
||||
next();
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
case "ArrowUp":
|
||||
e.preventDefault();
|
||||
prev();
|
||||
break;
|
||||
case "Escape":
|
||||
e.preventDefault();
|
||||
navigate(`/${networkId}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
},
|
||||
[composeActive, next, prev, navigate, networkId],
|
||||
);
|
||||
|
||||
const currentParticle = children[state.currentIndex] ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!userId || !currentParticle) return;
|
||||
|
||||
const streamDocPath = toFirestoreDocPath(path);
|
||||
updateStreamPlaybackMarker(streamDocPath, userId, currentParticle.created_at);
|
||||
}, [currentParticle?.id, path])
|
||||
|
||||
// Author info from current particle
|
||||
const authorEmail = currentParticle?.created_by_email ?? "";
|
||||
const authorInitials = authorEmail.split("@")[0]?.slice(0, 2).toUpperCase() ?? "";
|
||||
|
||||
if (children.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 bg-black text-white">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
No particles in this stream yet
|
||||
</p>
|
||||
<ControlsIndicator type="reply" />
|
||||
<ComposeOverlay
|
||||
networkId={networkId!}
|
||||
targetPath={path}
|
||||
onActiveChange={setComposeActive}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Render particle content inline (replaces ParticleRenderer)
|
||||
function renderParticle(particle: Particle) {
|
||||
switch (particle.type) {
|
||||
case "media":
|
||||
return (
|
||||
<MediaParticleView
|
||||
key={particle.id}
|
||||
particle={particle}
|
||||
paused={state.paused}
|
||||
onEnded={next}
|
||||
onProgress={setProgress}
|
||||
/>
|
||||
);
|
||||
case "text":
|
||||
return (
|
||||
<TextParticleView
|
||||
key={particle.id}
|
||||
particle={particle}
|
||||
paused={state.paused}
|
||||
onEnded={next}
|
||||
onProgress={setProgress}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return <FallbackParticleView particle={particle} />;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Stream view — {networkId}/{particleSegments.join("/")}
|
||||
</p>
|
||||
<div className="relative flex h-full flex-col bg-black text-white">
|
||||
{/* Progress indicator */}
|
||||
<div className="z-10 absolute left-0 right-0">
|
||||
<PlaybackPageIndicator
|
||||
total={children.length}
|
||||
current={state.currentIndex}
|
||||
progress={progress}
|
||||
onGoTo={goTo}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isLoading && <p className="text-muted-foreground text-sm">Loading stream data...</p>}
|
||||
{error && <p className="text-destructive text-sm">Failed to load stream data</p>}
|
||||
|
||||
{!isLoading && !error && (
|
||||
<div className="mt-4">
|
||||
<p className="text-sm font-medium">Stream Children:</p>
|
||||
<ul className="list-disc list-inside">
|
||||
{children.map((child) => (
|
||||
<li key={child.id} className="text-sm">
|
||||
{child.id} ({child.type})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{/* Author overlay */}
|
||||
{currentParticle && (
|
||||
<div className="absolute top-5 left-1/2 transform -translate-x-1/2 z-10 flex items-center justify-center gap-2 bg-black/30 backdrop-blur-sm p-1 pr-2 rounded-full">
|
||||
<Avatar size="sm">
|
||||
<AvatarFallback className="bg-white/20 text-[10px] font-medium text-white">
|
||||
{authorInitials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-xs text-white/70">
|
||||
{authorEmail.split("@")[0]}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main playback area */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{currentParticle && (
|
||||
<div
|
||||
className="relative flex h-full w-full cursor-pointer items-center justify-center"
|
||||
onClick={handlePlaybackClick}
|
||||
>
|
||||
{renderParticle(currentParticle)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ComposeOverlay
|
||||
networkId={networkId!}
|
||||
targetPath={path}
|
||||
onActiveChange={setComposeActive}
|
||||
/>
|
||||
|
||||
{/* Bottom overlay: stream info + reply */}
|
||||
<div className="absolute right-0 left-0 bottom-0 z-10">
|
||||
<ControlsIndicator type={"reply"}>
|
||||
<div className="flex items-center gap-1 text-xs text-white/70">
|
||||
Seen by
|
||||
<SeenIndicator stream={streamParticle} currentParticle={currentParticle} networkId={networkId} />
|
||||
{/* Exit countdown */}
|
||||
{exitRemainingMs !== null && (
|
||||
<span>
|
||||
Closing in {Math.ceil(exitRemainingMs / 1000)}s
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</ControlsIndicator>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Shows a list of avatars of users who have seen the current particle, based on playback markers in the stream particle.
|
||||
const SeenIndicator = ({ stream, currentParticle, networkId }: { stream: Particle & { type: "stream" }, currentParticle: Particle, networkId: string }) => {
|
||||
const network = useNetwork(networkId);
|
||||
const playbackMarkers = stream.playback_markers ?? {};
|
||||
|
||||
const seenUserIds = Object.entries(playbackMarkers)
|
||||
.filter(([_, timestamp]) => timestamp.getTime() >= currentParticle.created_at.getTime())
|
||||
.map(([userId, _]) => userId);
|
||||
|
||||
const seenUserEmails = seenUserIds
|
||||
.map((userId) => network?.humans?.find((h) => h.id === userId)?.email)
|
||||
.filter((email): email is string => !!email);
|
||||
|
||||
if (seenUserIds.length === 0) return null;
|
||||
|
||||
return (
|
||||
<AvatarGroup>
|
||||
{seenUserEmails.map((email) => (
|
||||
<Tooltip key={email}>
|
||||
<TooltipTrigger asChild>
|
||||
<Avatar size="sm">
|
||||
<AvatarFallback>
|
||||
{email.split("@")[0].slice(0, 2)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>Seen by {email.split("@")[0]}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</AvatarGroup>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user