4 Commits

Author SHA1 Message Date
Arjun Patel 62323e42b2 nit 2026-06-20 14:34:40 -07:00
Arjun Patel dfcba82aa4 ignore emacs project.el 2026-06-20 14:27:45 -07:00
Arjun Patel bde093fb21 fix: sidebar padding glitchy
Long markdown content would make each chat row expand and remove the padding in the sidebar
2026-06-20 13:30:07 -07:00
Arjun Patel 5118790353 fix: avatar showing blank when switching 2026-06-20 13:07:41 -07:00
11 changed files with 102 additions and 576 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "Flowy.llink",
"productName": "Flowy.llink",
"version": "1.8.0",
"version": "1.7.1",
"description": "Flowy.llink is a video messaging app for teams",
"main": ".vite/build/main.js",
"private": true,
+1 -6
View File
@@ -6,12 +6,8 @@ import { cn } from '@/lib/utils';
function ScrollArea({
className,
children,
viewportRef,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
/** Ref to the scrollable viewport, e.g. for scroll anchoring or observers. */
viewportRef?: React.Ref<HTMLDivElement>;
}) {
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
@@ -19,7 +15,6 @@ function ScrollArea({
{...props}
>
<ScrollAreaPrimitive.Viewport
ref={viewportRef}
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&>div]:!w-full"
>
@@ -7,10 +7,6 @@ import { useObjectUrl } from '@/hooks/use-object-url';
import { AttachmentStrip } from '@/features/compose/attachment-strip';
import type { PendingAttachment } from '@/features/compose/attachment-strip';
import { cn } from '@/lib/utils';
import {
RECORDING_MAX_DURATION_SECONDS,
RECORDING_WARNING_SECONDS,
} from '@/lib/constants';
import { Button } from '@/components/ui/button';
import { KeyHint } from '@/components/key-hint';
import { useComposeIntentStore } from '@/stores/compose-intent-store';
@@ -38,50 +34,16 @@ interface RecordingOverlayProps {
objectFit?: 'cover' | 'contain';
}
const WARNING_AT_SECONDS =
RECORDING_MAX_DURATION_SECONDS - RECORDING_WARNING_SECONDS;
/**
* Tracks elapsed recording time and drives the time-limit UI. Keeps the
* recorder itself unaware of limits: when the cap is reached it dispatches the
* standard `stop` intent (the same path as releasing the ` key), which finishes
* the recording into the review step.
*/
function useRecordingCountdown(active: boolean) {
function RecordingTimer() {
const [elapsed, setElapsed] = useState(0);
const requestIntent = useComposeIntentStore((s) => s.request);
useEffect(() => {
if (!active) return;
const start = Date.now();
let stopped = false;
// Tick faster than 1s so the auto-stop lands within ~250ms of the cap, but
// only re-render when the whole-second value actually changes.
const interval = setInterval(() => {
const seconds = Math.floor((Date.now() - start) / 1000);
setElapsed((prev) => (prev === seconds ? prev : seconds));
if (seconds >= RECORDING_MAX_DURATION_SECONDS && !stopped) {
stopped = true;
requestIntent('stop');
}
}, 250);
return () => {
clearInterval(interval);
setElapsed(0);
};
}, [active, requestIntent]);
setElapsed((prev) => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return { elapsed, isWarning: elapsed >= WARNING_AT_SECONDS };
}
function RecordingTimer({
elapsed,
isWarning,
}: {
elapsed: number;
isWarning: boolean;
}) {
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
const display = `${minutes}:${seconds.toString().padStart(2, '0')}`;
@@ -89,14 +51,7 @@ function RecordingTimer({
return (
<div className="flex items-center gap-2">
<span className="h-2.5 w-2.5 animate-pulse rounded-full bg-red-500" />
<span
className={cn(
'font-mono text-sm text-white/80',
isWarning && 'text-red-400',
)}
>
{display}
</span>
<span className="font-mono text-sm text-white/80">{display}</span>
</div>
);
}
@@ -182,31 +137,14 @@ export function RecordingOverlay({
const isLoading = isRecording && !mediaStream;
const requestIntent = useComposeIntentStore((s) => s.request);
const { elapsed, isWarning } = useRecordingCountdown(
isRecording && !isLoading,
);
return (
<div
className={cn(
'absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/90',
isReviewing && isDragging && 'ring-2 ring-inset ring-white/30',
isRecording && isWarning && 'record-warning-glow',
)}
{...(isReviewing ? dropZoneProps : {})}
>
{/* Top progress bar: fills over the recording duration, red in warning */}
{isRecording && !isLoading && (
<div className="absolute inset-x-0 top-0 z-20 h-1 bg-white/10">
<div
className={cn(
'h-full w-full origin-left record-progress',
isWarning ? 'bg-red-500' : 'bg-white/80',
)}
style={{ animationDuration: `${RECORDING_MAX_DURATION_SECONDS}s` }}
/>
</div>
)}
{/* Loading state */}
{isLoading && (
<div className="z-10 flex flex-col items-center gap-2">
@@ -247,7 +185,7 @@ export function RecordingOverlay({
{/* Top center: recording indicator */}
<div className="absolute top-8 z-10">
{isRecording && !isLoading ? (
<RecordingTimer elapsed={elapsed} isWarning={isWarning} />
<RecordingTimer />
) : isReviewing ? (
<div className="flex items-center gap-2">
<span className="text-sm text-white/80">Review recording</span>
@@ -7,87 +7,58 @@ import {
import type { HumanPresence } from '@/hooks/use-presence-positions';
const MAX_VISIBLE_AVATARS = 3;
const VISIBLE_SEGMENTS = 10;
const PAGE_SIZE = 10;
interface PlaybackPageIndicatorProps {
/** Number of particles currently loaded in the window. */
loadedCount: number;
total: number;
current: number;
progress: number;
onGoTo: (index: number) => void;
presenceBySegment?: Map<number, HumanPresence[]>;
/** Set of humanIds currently online in the stream channel. */
onlineHumanIds?: Set<string>;
/** More (older) particles exist before the loaded window. */
hasMoreOlder?: boolean;
/** Pull in older history when scrubbing past the oldest loaded segment. */
onLoadOlder?: () => void;
/** Render only avatars or only tracks. Omit to render both. */
layer?: 'avatars' | 'tracks';
}
/**
* A streaming, count-free progress scrubber. The stream is paginated, so the
* true particle count is unknown — instead this shows a sliding window of
* segments around the current position. Segments map to the loaded particles
* (newest on the right); the edge stubs scrub within the window and pull in
* older history when you reach the oldest loaded segment.
*/
export function PlaybackPageIndicator({
loadedCount,
total,
current,
progress,
onGoTo,
presenceBySegment,
onlineHumanIds,
hasMoreOlder,
onLoadOlder,
layer,
}: PlaybackPageIndicatorProps) {
if (loadedCount === 0) return null;
if (total === 0) return null;
const showAvatars = layer !== 'tracks';
const showTracks = layer !== 'avatars';
const paginated = total > PAGE_SIZE;
const safeCurrent = current < 0 ? 0 : current;
// Slide the visible window so the current segment stays in view with a bit of
// context on either side, clamped to the loaded range.
const sliceStart = Math.min(
Math.max(0, safeCurrent - Math.floor(VISIBLE_SEGMENTS / 2)),
Math.max(0, loadedCount - VISIBLE_SEGMENTS),
);
const sliceEnd = Math.min(loadedCount, sliceStart + VISIBLE_SEGMENTS);
const visibleCount = sliceEnd - sliceStart;
const paginated = loadedCount > VISIBLE_SEGMENTS || !!hasMoreOlder;
// Older = lower indices (left); newer = higher indices (right).
const hasOlder = sliceStart > 0 || !!hasMoreOlder;
const hasNewer = sliceEnd < loadedCount;
// Stubs jump a page at a time; reaching the oldest loaded pulls in history.
const goOlder = () => {
const target = safeCurrent - VISIBLE_SEGMENTS;
if (target >= 0) onGoTo(target);
else if (sliceStart > 0) onGoTo(0);
else if (hasMoreOlder) onLoadOlder?.();
};
const goNewer = () => {
onGoTo(Math.min(loadedCount - 1, safeCurrent + VISIBLE_SEGMENTS));
};
const pageStart = paginated
? Math.floor(safeCurrent / PAGE_SIZE) * PAGE_SIZE
: 0;
const visibleCount = paginated
? Math.min(PAGE_SIZE, total - pageStart)
: total;
const hasPrevPage = paginated && pageStart > 0;
const hasNextPage = paginated && pageStart + PAGE_SIZE < total;
return (
<div className="flex w-full flex-col items-stretch leading-none">
<div className="flex w-full items-end gap-px">
{paginated && (
<GhostStub
visible={hasOlder}
visible={hasPrevPage}
interactive={showTracks}
onClick={goOlder}
onClick={() => onGoTo(pageStart - 1)}
/>
)}
<div className="flex flex-1 items-end gap-px">
{Array.from({ length: visibleCount }, (_, j) => {
const i = sliceStart + j;
const i = pageStart + j;
const presence = presenceBySegment?.get(i);
return (
<div key={i} className="flex flex-1 flex-col items-stretch">
@@ -129,12 +100,17 @@ export function PlaybackPageIndicator({
</div>
{paginated && (
<GhostStub
visible={hasNewer}
visible={hasNextPage}
interactive={showTracks}
onClick={goNewer}
onClick={() => onGoTo(pageStart + PAGE_SIZE)}
/>
)}
</div>
{paginated && showTracks && current >= 0 && (
<div className="pointer-events-none pt-1 text-center text-[10px] font-medium tabular-nums tracking-wide text-white/40">
{current + 1} / {total}
</div>
)}
</div>
);
}
@@ -7,28 +7,24 @@ import type { HumanPresence } from '@/hooks/use-presence-positions';
export function BottomBar({
visible,
loadedCount,
total,
current,
progress,
onGoTo,
presenceBySegment,
onlineHumanIds,
hasMoreOlder,
onLoadOlder,
exitRemainingMs,
onOpenKeybindings,
onOpenHuddle,
onExit,
}: {
visible: boolean;
loadedCount: number;
total: number;
current: number;
progress: number;
onGoTo: (index: number) => void;
presenceBySegment: Map<number, HumanPresence[]>;
onlineHumanIds: Set<string>;
hasMoreOlder: boolean;
onLoadOlder: () => void;
exitRemainingMs: number | null;
onOpenKeybindings: () => void;
onOpenHuddle: () => void;
@@ -45,25 +41,21 @@ export function BottomBar({
>
{/* Presence avatars — above the blurred background */}
<PlaybackPageIndicator
loadedCount={loadedCount}
total={total}
current={current}
progress={progress}
onGoTo={onGoTo}
presenceBySegment={presenceBySegment}
onlineHumanIds={onlineHumanIds}
hasMoreOlder={hasMoreOlder}
onLoadOlder={onLoadOlder}
layer="avatars"
/>
{/* Blurred background container — tracks + controls */}
<div className="pb-3">
<PlaybackPageIndicator
loadedCount={loadedCount}
total={total}
current={current}
progress={progress}
onGoTo={onGoTo}
hasMoreOlder={hasMoreOlder}
onLoadOlder={onLoadOlder}
layer="tracks"
/>
<div className="flex items-center justify-center px-3 pt-2 gap-2">
@@ -1,13 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
import {
CircleCheck,
FileText,
Image,
List,
Loader2,
Mic,
Video,
} from 'lucide-react';
import { useEffect, useRef } from 'react';
import { CircleCheck, FileText, Image, List, Mic, Video } from 'lucide-react';
import { isParticleDeleted, type Human, type Particle } from '@/api/types';
import { cn } from '@/lib/utils';
import { useNetwork } from '@/hooks/use-networks';
@@ -23,18 +15,12 @@ interface StreamListSidebarProps {
currentIndex: number;
onSelect: (index: number) => void;
onToggle: () => void;
/** More (older) particles exist before the loaded window. */
hasMoreOlder: boolean;
/** Load the next page of older particles. */
onLoadOlder: () => void;
isLoadingOlder: boolean;
}
/**
* Browse-mode panel beside the stream: a chat-like timeline of the loaded
* particles. Selecting a message plays it in the immersive stream view;
* nothing auto-advances. Older history is fetched automatically as the user
* scrolls toward the top.
* Browse-mode panel beside the stream: a chat-like timeline of every
* particle. Selecting a message plays it in the immersive stream view;
* nothing auto-advances.
*/
export function StreamListSidebar({
items,
@@ -42,67 +28,22 @@ export function StreamListSidebar({
currentIndex,
onSelect,
onToggle,
hasMoreOlder,
onLoadOlder,
isLoadingOlder,
}: StreamListSidebarProps) {
const network = useNetwork(networkId);
const rowRefs = useRef<Array<HTMLDivElement | null>>([]);
const viewportRef = useRef<HTMLDivElement>(null);
const sentinelRef = useRef<HTMLDivElement>(null);
// Scroll into view only when the selection genuinely changes — not when the
// current index shifts because older particles were prepended.
const selectedId = currentIndex >= 0 ? items[currentIndex]?.id : undefined;
const prevSelectedIdRef = useRef<string | undefined>(undefined);
useEffect(() => {
if (selectedId && selectedId !== prevSelectedIdRef.current) {
if (currentIndex >= 0) {
rowRefs.current[currentIndex]?.scrollIntoView({ block: 'nearest' });
}
prevSelectedIdRef.current = selectedId;
}, [selectedId, currentIndex]);
// Anchor the viewport when older particles are prepended so the content the
// user is looking at stays put instead of jumping.
const pendingAnchorRef = useRef<{ height: number; top: number } | null>(null);
const requestOlder = useCallback(() => {
const vp = viewportRef.current;
if (!vp) return;
pendingAnchorRef.current = { height: vp.scrollHeight, top: vp.scrollTop };
onLoadOlder();
}, [onLoadOlder]);
useLayoutEffect(() => {
const vp = viewportRef.current;
const anchor = pendingAnchorRef.current;
if (!vp || !anchor) return;
const delta = vp.scrollHeight - anchor.height;
if (delta > 0) vp.scrollTop = anchor.top + delta;
pendingAnchorRef.current = null;
}, [items]);
// Auto-fetch older history when the top sentinel scrolls into view.
useEffect(() => {
const vp = viewportRef.current;
const sentinel = sentinelRef.current;
if (!vp || !sentinel || !hasMoreOlder) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0]?.isIntersecting && !isLoadingOlder) requestOlder();
},
{ root: vp, rootMargin: '120px 0px 0px 0px' },
);
observer.observe(sentinel);
return () => observer.disconnect();
}, [hasMoreOlder, isLoadingOlder, requestOlder]);
}, [currentIndex]);
return (
<aside className="dark flex w-60 shrink-0 flex-col overflow-hidden border-l border-white/10 bg-zinc-950">
<div className="flex shrink-0 items-center gap-2 border-b border-white/10 px-4 py-3">
<List className="size-3.5 text-white/40" />
<span className="truncate text-sm font-medium text-white/90 mr-auto">
{items.length}
{hasMoreOlder ? '+' : ''} messages
{items.length} messages
</span>
<KeyHint
keys="L"
@@ -113,14 +54,8 @@ export function StreamListSidebar({
to close
</KeyHint>
</div>
<ScrollArea viewportRef={viewportRef} className="min-h-0 flex-1">
<ScrollArea className="min-h-0 flex-1">
<div className="flex flex-col gap-0.5 px-2 py-2">
<div ref={sentinelRef} aria-hidden />
{hasMoreOlder && (
<div className="flex items-center justify-center py-2 text-white/40">
<Loader2 className="size-3.5 animate-spin" />
</div>
)}
{items.map((item, index) => (
<div
key={item.id}
@@ -219,9 +219,6 @@ function StreamViewInner({ path, streamParticle }: StreamViewProps) {
currentParticle,
currentIndex,
status,
hasMoreOlder,
loadOlder,
isLoadingOlder,
next,
prev,
goTo,
@@ -548,14 +545,12 @@ function StreamViewInner({ path, streamParticle }: StreamViewProps) {
{/* BottomBar — pinned visible while browsing, mouse-activity in player */}
<BottomBar
visible={mode === 'list' || controlsVisible}
loadedCount={children.length}
total={children.length}
current={currentIndex}
progress={progress}
onGoTo={goTo}
presenceBySegment={presenceBySegment}
onlineHumanIds={onlineHumanIds}
hasMoreOlder={hasMoreOlder}
onLoadOlder={loadOlder}
exitRemainingMs={exitRemainingMs}
onOpenKeybindings={() => setShowKeybindings(true)}
onOpenHuddle={handleOpenHuddle}
@@ -578,9 +573,6 @@ function StreamViewInner({ path, streamParticle }: StreamViewProps) {
currentIndex={currentIndex}
onSelect={goTo}
onToggle={toggleViewMode}
hasMoreOlder={hasMoreOlder}
onLoadOlder={loadOlder}
isLoadingOlder={isLoadingOlder}
/>
)}
</div>
+56 -102
View File
@@ -8,7 +8,7 @@ import {
} from 'react';
import { useAuthStore } from '@/stores/auth-store';
import type { Particle } from '@/api/types';
import { useWindowedStreamParticles } from '@/hooks/use-windowed-stream-particles';
import { useLiveParticleChildren } from '@/hooks/use-particle';
import { toFirestoreDocPath, type ParticlePath } from '@/lib/particle-path';
import { updateStreamPlaybackMarker } from '@/lib/firestore-particles';
@@ -92,11 +92,6 @@ interface UseStreamPlaybackResult {
currentIndex: number;
status: PlaybackStatus;
initialized: boolean;
/** Whether older particles exist before the loaded window (list scroll-up). */
hasMoreOlder: boolean;
/** Extend the loaded window backward. */
loadOlder: () => void;
isLoadingOlder: boolean;
next: () => void;
prev: () => void;
goTo: (index: number) => void;
@@ -118,26 +113,50 @@ export function useStreamPlayback(
): UseStreamPlaybackResult {
const userId = useAuthStore((s) => s.user?.id);
const [state, dispatch] = useReducer(playbackReducer, initialState);
const marker = userId
? (streamParticle.playback_markers?.[userId] ?? null)
: null;
// Windowed source: only the tail (plus enough history to cover the marker)
// is loaded, instead of every particle in the stream.
const { children, hasMoreOlder, loadOlder, isLoadingOlder } =
useWindowedStreamParticles(path, { marker });
// Read via ref so the new-particle effect stays cheap to reason about.
// Read via ref so the onAdded subscription callback stays stable.
const autoAdvanceOnNewRef = useRef(autoAdvanceOnNew);
useEffect(() => {
autoAdvanceOnNewRef.current = autoAdvanceOnNew;
}, [autoAdvanceOnNew]);
// Track the stream ID we've initialized for, to reset when navigating streams.
// Track the stream ID we've initialized for, to reset when navigating between streams
const initializedForRef = useRef<string | null>(null);
// Latest currentIndex for onParticleRemoved, which is passed into
// useLiveParticleChildren. Reading it through a ref keeps the callback stable
// (no re-subscription) and breaks the declaration cycle
// children -> currentIndex -> callback -> children. useEffectEvent can't be
// used here — Effect Events may not be passed to another hook.
const currentIndexRef = useRef(0);
// Derive current index and particle from ID.
// --- Firestore change callbacks ---
const onParticleAdded = useCallback((particle: Particle) => {
if (!autoAdvanceOnNewRef.current) return;
dispatch({ type: 'PARTICLE_ADDED', particleId: particle.id });
}, []);
const onParticleRemoved = useCallback(
(removed: Particle, updatedChildren: Particle[]) => {
const fallbackIndex = Math.min(
currentIndexRef.current,
updatedChildren.length - 1,
);
const fallback = updatedChildren[Math.max(0, fallbackIndex)];
dispatch({
type: 'PARTICLE_REMOVED',
removedParticleId: removed.id,
fallbackParticleId: fallback?.id ?? null,
});
},
[],
);
const { children } = useLiveParticleChildren(path, {
orderByField: 'created_at',
orderDirection: 'asc',
onAdded: onParticleAdded,
onRemoved: onParticleRemoved,
});
// Derive current index and particle from ID
const currentIndex = useMemo(() => {
if (!state.currentParticleId) return -1;
return children.findIndex((c) => c.id === state.currentParticleId);
@@ -145,64 +164,12 @@ export function useStreamPlayback(
const currentParticle = currentIndex !== -1 ? children[currentIndex] : null;
// Remember the last index the current particle was actually found at, so a
// removal can fall back to a sensible neighbour even though `currentIndex`
// has already gone to -1 by the time we notice.
const lastValidIndexRef = useRef(0);
// Keep the ref read by onParticleRemoved in sync with the derived index.
useEffect(() => {
if (currentIndex >= 0) lastValidIndexRef.current = currentIndex;
currentIndexRef.current = currentIndex;
}, [currentIndex]);
// --- New tail particle → resume from end ---
// Derive arrivals from the children tail rather than Firestore change events,
// which can't distinguish a genuine new particle from pagination backfill.
const prevNewestIdRef = useRef<string | null>(null);
useEffect(() => {
if (children.length === 0) {
prevNewestIdRef.current = null;
return;
}
const newestId = children[children.length - 1].id;
const prevNewestId = prevNewestIdRef.current;
prevNewestIdRef.current = newestId;
if (prevNewestId === null || newestId === prevNewestId) return;
if (!autoAdvanceOnNewRef.current) return;
// Resume at the first particle added after where playback ended.
const prevIndex = children.findIndex((c) => c.id === prevNewestId);
const firstNew =
prevIndex >= 0
? (children[prevIndex + 1] ?? children[children.length - 1])
: children[children.length - 1];
dispatch({ type: 'PARTICLE_ADDED', particleId: firstNew.id });
}, [children]);
// --- Current particle removed (deletion) → fall back to a neighbour ---
const prevIdsRef = useRef<Set<string>>(new Set());
useEffect(() => {
const id = state.currentParticleId;
const prevIds = prevIdsRef.current;
const currIds = new Set(children.map((c) => c.id));
prevIdsRef.current = currIds;
if (!id || children.length === 0) return;
if (currIds.has(id)) return;
// Only treat as a removal if it was present before — a not-yet-arrived id
// (e.g. optimistic goToParticle) should wait, not fall back.
if (!prevIds.has(id)) return;
const fallbackIndex = Math.min(
lastValidIndexRef.current,
children.length - 1,
);
const fallback = children[Math.max(0, fallbackIndex)];
dispatch({
type: 'PARTICLE_REMOVED',
removedParticleId: id,
fallbackParticleId: fallback?.id ?? null,
});
}, [children, state.currentParticleId]);
// Fallback init — always sees latest children/state via useEffectEvent.
// Fallback init — always sees latest children/state via useEffectEvent
const initFallback = useEffectEvent(() => {
if (state.initialized || children.length === 0) return;
initializedForRef.current = streamParticle.id;
@@ -211,7 +178,7 @@ export function useStreamPlayback(
// --- Init logic: runs on every children change until initialized ---
useEffect(() => {
// Reset if we navigated to a different stream.
// Reset if we navigated to a different stream
if (
initializedForRef.current !== null &&
initializedForRef.current !== streamParticle.id
@@ -219,7 +186,7 @@ export function useStreamPlayback(
initializedForRef.current = null;
}
// Already initialized for this stream.
// Already initialized for this stream
if (state.initialized && initializedForRef.current === streamParticle.id)
return;
@@ -228,39 +195,35 @@ export function useStreamPlayback(
const playbackPosition = streamParticle.playback_markers?.[userId ?? ''];
if (!playbackPosition) {
// No marker — start from the start of the loaded window.
// No marker — start from the beginning
initializedForRef.current = streamParticle.id;
dispatch({ type: 'INIT', particleId: children[0].id });
return;
}
// Resume at the first particle after the marker.
// Try to find the marker's target particle
const found = children.find(
(c) => c.created_at.getTime() > playbackPosition.getTime(),
);
if (found) {
initializedForRef.current = streamParticle.id;
dispatch({ type: 'INIT', particleId: found.id });
return;
} else {
initializedForRef.current = streamParticle.id;
dispatch({ type: 'INIT', particleId: children[children.length - 1].id });
}
// Marker is older than everything loaded so far. If the window is still
// growing backward to reach it, wait for more particles to arrive.
if (hasMoreOlder) {
const timeout = setTimeout(initFallback, INIT_FALLBACK_TIMEOUT_MS);
return () => clearTimeout(timeout);
}
// Reached the start with no particle after the marker → caught up.
initializedForRef.current = streamParticle.id;
dispatch({ type: 'INIT', particleId: children[children.length - 1].id });
// Marker target not found yet — fall back after timeout
const timeout = setTimeout(initFallback, INIT_FALLBACK_TIMEOUT_MS);
return () => clearTimeout(timeout);
}, [
children,
streamParticle.id,
streamParticle.playback_markers,
userId,
state.initialized,
hasMoreOlder,
]);
// --- Persist playback marker (only advance forward, never backwards) ---
@@ -274,7 +237,7 @@ export function useStreamPlayback(
lastPersistedMarkerRef.current ??
streamParticle.playback_markers?.[userId];
// Only update if advancing beyond the current marker.
// Only update if advancing beyond the current marker
if (existingMarker && currentTime.getTime() <= existingMarker.getTime())
return;
@@ -303,18 +266,12 @@ export function useStreamPlayback(
}, [children, currentIndex]);
const prev = useCallback(() => {
if (currentIndex < 0) return;
if (currentIndex === 0) {
// At the start of the loaded window — pull in older history so the user
// can keep going back.
if (hasMoreOlder) loadOlder();
return;
}
if (currentIndex <= 0) return;
dispatch({
type: 'SET_PARTICLE',
particleId: children[currentIndex - 1].id,
});
}, [children, currentIndex, hasMoreOlder, loadOlder]);
}, [children, currentIndex]);
const goTo = useCallback(
(index: number) => {
@@ -338,9 +295,6 @@ export function useStreamPlayback(
currentIndex,
status: state.status,
initialized: state.initialized,
hasMoreOlder,
loadOlder,
isLoadingOlder,
next,
prev,
goTo,
@@ -1,214 +0,0 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { subscribeToParticleChildren } from '@/lib/firestore-particles';
import type { Particle } from '@/api/types';
import {
toFirestoreChildrenPath,
type ParticlePath,
} from '@/lib/particle-path';
const DEFAULT_PAGE_SIZE = 30;
interface UseWindowedStreamParticlesParams {
/**
* Resume anchor (the viewer's playback marker). The window grows backward
* until it covers this timestamp so the resume particle is always loaded.
* Captured once per stream — advancing the marker during playback does not
* re-window.
*/
marker?: Date | null;
/** How many particles to add per backward growth step. */
pageSize?: number;
}
export interface UseWindowedStreamParticlesResult {
/**
* Loaded window, ascending (oldest → newest). The newest particle in the
* stream is always present — the window only ever grows backward.
*/
children: Particle[];
isLoading: boolean;
error: Error | null;
/** Whether older particles likely exist before the loaded window. */
hasMoreOlder: boolean;
/** Extend the window backward (older history). No-op when nothing remains. */
loadOlder: () => void;
isLoadingOlder: boolean;
}
/** Per-stream mutable tracking that must survive limit-driven re-subscriptions. */
interface WindowTracking {
path: string | null;
/** Newest created_at (ms) seen — tells new tail particles from backfill. */
newestMs: number | null;
/** Oldest created_at (ms) currently loaded. */
oldestMs: number | null;
/** Backward growth target (the marker, ms), frozen on first capture. */
coverageMs: number | null;
}
/**
* Live, windowed view of a stream's particles.
*
* Instead of subscribing to every child (the old behaviour), this keeps a
* `orderBy(created_at desc) limit(N)` window anchored at the newest particle
* and grows it backward on demand. Because the window is anchored at the tail
* it always contains the most recent particles, so new arrivals stream in and
* forward playback never needs a fetch. The window grows backward to:
* 1. cover the resume marker, so playback can start where the user left off;
* 2. service `loadOlder()` when the list view scrolls up.
*
* Output is reversed to ascending order to match the rest of the playback code.
*/
export function useWindowedStreamParticles(
path: ParticlePath | undefined,
{
marker = null,
pageSize = DEFAULT_PAGE_SIZE,
}: UseWindowedStreamParticlesParams = {},
): UseWindowedStreamParticlesResult {
const [children, setChildren] = useState<Particle[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [hasMoreOlder, setHasMoreOlder] = useState(false);
const [isLoadingOlder, setIsLoadingOlder] = useState(false);
const [limit, setLimit] = useState(pageSize);
const collectionPath = path ? toFirestoreChildrenPath(path) : null;
const trackingRef = useRef<WindowTracking>({
path: null,
newestMs: null,
oldestMs: null,
coverageMs: null,
});
// Latest marker, read lazily inside the snapshot callback so a late-resolving
// marker (e.g. auth after first paint) still seeds backward coverage.
const markerRef = useRef(marker);
useEffect(() => {
markerRef.current = marker;
}, [marker]);
// Reset window state when the stream changes (render-phase adjustment — the
// blessed alternative to a reset effect, avoids cascading effect renders).
const [trackedPath, setTrackedPath] = useState(collectionPath);
if (trackedPath !== collectionPath) {
setTrackedPath(collectionPath);
setLimit(pageSize);
setChildren([]);
setIsLoading(true);
setError(null);
setHasMoreOlder(false);
setIsLoadingOlder(false);
}
useEffect(() => {
if (!collectionPath) return;
// Reset per-stream tracking on a genuine stream change, but keep it across
// limit-driven re-subscriptions (newest/coverage must persist).
const tracking = trackingRef.current;
if (tracking.path !== collectionPath) {
tracking.path = collectionPath;
tracking.newestMs = null;
tracking.oldestMs = null;
tracking.coverageMs = null;
}
const unsubscribe = subscribeToParticleChildren(collectionPath, {
orderByField: 'created_at',
orderDirection: 'desc',
limit,
onData: (descData) => {
const t = trackingRef.current;
// Lazily freeze the backward-coverage target from the marker.
if (t.coverageMs === null && markerRef.current) {
t.coverageMs = markerRef.current.getTime();
}
// Firestore caps results at `limit`; a full window means more older
// particles may exist beyond it.
const saturated = descData.length === limit;
const newest = descData[0];
const newestMs = newest ? newest.created_at.getTime() : null;
// Anti-eviction: if the window is full and genuinely newer particles
// arrived at the tail, grow the limit so the oldest loaded particles
// aren't pushed out. Skip rendering the evicted snapshot — the regrown
// query delivers the complete window a beat later.
const prevNewest = t.newestMs;
if (
saturated &&
newestMs !== null &&
prevNewest !== null &&
newestMs > prevNewest
) {
const newerCount = descData.filter(
(d) => d.created_at.getTime() > prevNewest,
).length;
if (newerCount > 0) {
t.newestMs = newestMs;
setLimit((l) => l + newerCount);
return;
}
}
if (newestMs !== null) t.newestMs = newestMs;
const ascData = descData.slice().reverse();
t.oldestMs =
ascData.length > 0 ? ascData[0].created_at.getTime() : null;
// Marker coverage: keep growing backward until the resume marker falls
// within the window (or we reach the start of the stream).
if (
saturated &&
t.coverageMs !== null &&
t.oldestMs !== null &&
t.oldestMs > t.coverageMs
) {
setLimit((l) => l + pageSize);
}
setChildren(ascData);
setHasMoreOlder(saturated);
setIsLoading(false);
setIsLoadingOlder(false);
},
onError: (err) => {
console.warn(err);
setError(err);
setIsLoading(false);
setIsLoadingOlder(false);
},
});
return () => unsubscribe();
}, [collectionPath, limit, pageSize]);
const loadOlder = useCallback(() => {
if (!hasMoreOlder || isLoadingOlder) return;
setIsLoadingOlder(true);
setLimit((l) => l + pageSize);
}, [hasMoreOlder, isLoadingOlder, pageSize]);
if (!path) {
return {
children: [],
isLoading: false,
error: null,
hasMoreOlder: false,
loadOlder: () => {},
isLoadingOlder: false,
};
}
return {
children,
isLoading,
error,
hasMoreOlder,
loadOlder,
isLoadingOlder,
};
}
-6
View File
@@ -4,12 +4,6 @@ export const MAX_ATTACHMENT_SIZE_BYTES = 25 * 1024 * 1024;
/** Maximum number of file attachments per particle. */
export const MAX_ATTACHMENTS = 10;
/** Maximum duration for a media (audio/video) recording, in seconds. */
export const RECORDING_MAX_DURATION_SECONDS = 60;
/** When this many seconds or fewer remain, show the red warning state. */
export const RECORDING_WARNING_SECONDS = 10;
export const SUPPORT_EMAIL = 'team@flowylabs.ai';
export const PRIVACY_URL = 'https://flowylabs.ai/llink/privacy';
-36
View File
@@ -186,39 +186,3 @@
.no-drag {
-webkit-app-region: no-drag;
}
/* Recording time-limit progress bar: a single CSS animation fills the bar
left→right over the recording duration (duration set inline), avoiding
per-frame React renders. */
@keyframes record-progress {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
.record-progress {
transform: scaleX(0);
animation-name: record-progress;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
/* Pulsing red glow around the recording overlay during the final warning window. */
@keyframes record-warning-glow {
0%,
100% {
box-shadow:
inset 0 0 0 2px var(--destructive),
inset 0 0 24px 0 oklch(0.6 0.24 27 / 0.25);
}
50% {
box-shadow:
inset 0 0 0 3px var(--destructive),
inset 0 0 60px 0 oklch(0.6 0.24 27 / 0.5);
}
}
.record-warning-glow {
animation: record-warning-glow 1s ease-in-out infinite;
}