Files
ChatApp/apps/desktop/src/context/AuthContext.tsx
T
byGalax 672c8738c7 feat: file variety, user status, DND gate, drag-drop, mentions, link preview, emoji picker, soundboard, ringtone
Attachments
- Video: native <video controls>, decrypted blob, metadata preload
- PDF: collapsible <object> viewer with download + preview toggle
- Generic: file card with lazy decrypt, mime-to-extension map
- MessageBubble dispatch: audio/image/video/pdf/generic by mime
- Composer accept widened from image/* to any; AttachmentPreview renders
  non-images as file cards

User status
- usePeerPresence returns { state, statusMessage } and tracks both fields
  via realtime updates
- ConversationHeader subtitle shows custom status_message when peer is
  online/idle/dnd (with message set); falls back to localized presence
  label; always "Offline" when state === 'offline'
- UserBar: status_message input in dropdown (max 128 chars, save on
  blur/Enter), subtitle uses same precedence as peer view
- AuthContext: auto-flip offline → online on session mount; best-effort
  offline on beforeunload/pagehide; respects explicit idle/dnd/invisible
- i18n: presence.status_placeholder (DE + EN)

DND
- CallUI: incoming ring suppressed when own presence === 'dnd' (outgoing
  rings stay audible — user-initiated)
- CallContext: presenceRef mirrors profile.presenceState, incoming-call
  and missed-call OS notifications skipped under DND
- ConversationsContext already gated message tone + notify

Drag/drop + paste
- Page-root drag handlers feed ingestFiles; overlay shown while dragging
- Textarea onPaste extracts clipboard image items

@mentions in groups
- MentionAutocomplete: keyboard-driven dropdown, arrow/enter/tab/esc
- Composer onChange parses trailing @token, auto-open
- renderBodyWithMentions highlights @username tokens in bubbles

Link previews
- Migration 20260421000003_link_previews.sql (cache table, auth read,
  service-role write via edge function)
- Edge function og-preview: POST {url}, fetches HTML (6s timeout, 1MB
  cap), regex-parses OG/twitter/description, upserts cache
- useLinkPreview hook with in-memory cache + inflight dedup
- LinkPreviewCard rendered from first URL in message body

Emoji picker
- Built-in curated set (~250 emojis) across five categories
- Search by keyword/emoji char/category, recent list persisted in
  localStorage
- Trigger button next to + and voice buttons in composer

Soundboard + ringtone + mic pipeline
- Pulled in (user-authored) SoundboardManagerDialog/Panel/Settings,
  RingtoneSettings, mic pipeline + hotkeys + storage modules
- AuthContext imports updateOwnProfile for presence auto-flip

Fixes
- AttachmentAudio min-width so bubbles don't collapse to 0px on peer
  side
- Focus flicker: visibility/online wake refresh throttled to 30s,
  focus listener dropped, loading flag only on first fetch
2026-04-21 09:13:30 +02:00

211 lines
6.9 KiB
TypeScript

import {
type DeviceRecord,
getOwnProfile,
signOut as supabaseSignOut,
type Profile,
updateOwnProfile,
} from '@chat-app/shared/auth';
import { changeLocale, isSupportedLocale } from '@chat-app/shared/i18n';
import type { Session } from '@supabase/supabase-js';
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { findExistingDevice } from '../lib/device';
import { setSecretStoreUser } from '../lib/secretStore';
import { supabase } from '../lib/supabase';
import { registerWebPush } from '../lib/webPush';
interface AuthContextValue {
session: Session | null;
profile: Profile | null;
device: DeviceRecord | null;
// null while we're still resolving the very first auth state.
ready: boolean;
// null until a device lookup has finished for the current session.
deviceLookupDone: boolean;
refreshProfile: () => Promise<void>;
refreshDevice: () => Promise<void>;
setDevice: (device: DeviceRecord | null) => void;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const { i18n } = useTranslation();
const [session, setSession] = useState<Session | null>(null);
const [ready, setReady] = useState(false);
const [profile, setProfile] = useState<Profile | null>(null);
const [device, setDevice] = useState<DeviceRecord | null>(null);
const [deviceLookupDone, setDeviceLookupDone] = useState(false);
// Initial session + auth subscription. We verify the cached JWT against the
// server (via getUser) once on mount. Only purge the session on an
// unambiguous 401/403 — a network failure (Supabase stack offline) must not
// log the user out, otherwise every local `supabase stop` wipes their session.
useEffect(() => {
let cancelled = false;
(async () => {
const { data: sessionRes } = await supabase.auth.getSession();
if (cancelled) return;
// Flip `ready` immediately on cached session read so the UI unblocks even
// if the network is slow/down. Validate the token in the background and
// only wipe on an unambiguous 401/403 — a stalled getUser (Tauri WebView
// with no network, server unreachable) must not keep the app on the
// loading spinner forever.
setSession(sessionRes.session ?? null);
setReady(true);
if (sessionRes.session) {
supabase.auth
.getUser()
.then(({ error }) => {
if (cancelled || !error) return;
const status = (error as { status?: number }).status;
if (status === 401 || status === 403) {
void supabase.auth.signOut({ scope: 'local' }).catch(() => {
/* ignore */
});
setSession(null);
} else {
// Network / server unreachable — keep cached session.
console.warn('auth.getUser failed, keeping cached session:', error);
}
})
.catch((err: unknown) => {
console.warn('auth.getUser rejected, keeping cached session:', err);
});
}
})();
const { data: sub } = supabase.auth.onAuthStateChange((_event, s) => {
setSession(s);
setReady(true);
void setSecretStoreUser(s?.user.id ?? null);
});
return () => {
cancelled = true;
sub.subscription.unsubscribe();
};
}, []);
const refreshProfile = useCallback(async () => {
if (!session) {
setProfile(null);
return;
}
const p = await getOwnProfile(supabase);
setProfile(p);
if (p && p.locale !== i18n.resolvedLanguage && isSupportedLocale(p.locale)) {
void changeLocale(p.locale);
}
}, [session, i18n.resolvedLanguage]);
const refreshDevice = useCallback(async () => {
if (!session) {
setDevice(null);
setDeviceLookupDone(false);
return;
}
setDeviceLookupDone(false);
const found = await findExistingDevice(session.user.id);
setDevice(found);
setDeviceLookupDone(true);
}, [session]);
// Re-pull profile + device whenever session flips.
useEffect(() => {
if (!session) {
setProfile(null);
setDevice(null);
setDeviceLookupDone(false);
return;
}
void refreshProfile().catch((err: unknown) => {
console.error('refreshProfile failed', err);
});
void refreshDevice().catch((err: unknown) => {
console.error('refreshDevice failed', err);
setDeviceLookupDone(true);
});
}, [session, refreshProfile, refreshDevice]);
// Best-effort web-push registration once we know the device id. No-op on
// Tauri (uses native notifications) or when VITE_VAPID_PUBLIC_KEY is unset.
useEffect(() => {
if (!device?.id) return;
void registerWebPush(device.id);
}, [device?.id]);
// Auto online/offline transition.
//
// - On mount with a session whose last persisted state is `offline`, flip
// to `online`. We never override an explicit `idle`, `dnd`, or
// `invisible` choice — those are user intent.
// - On `pagehide` / `beforeunload`, fire a best-effort update to
// `offline`. Browsers don't guarantee delivery during unload, but the
// request usually slips through; the next page load corrects state if it
// didn't.
useEffect(() => {
if (!session || !profile) return;
if (profile.presenceState === 'offline') {
void updateOwnProfile(supabase, { presenceState: 'online' })
.then(() => refreshProfile())
.catch((err: unknown) => {
console.warn('auto online flip failed', err);
});
}
const onLeave = () => {
// Skip if user explicitly chose a non-online state — they probably
// want to look unavailable on next reconnect too.
if (
profile.presenceState !== 'online' &&
profile.presenceState !== 'offline'
) {
return;
}
void updateOwnProfile(supabase, { presenceState: 'offline' }).catch(() => {});
};
window.addEventListener('beforeunload', onLeave);
window.addEventListener('pagehide', onLeave);
return () => {
window.removeEventListener('beforeunload', onLeave);
window.removeEventListener('pagehide', onLeave);
};
}, [session, profile, refreshProfile]);
const signOut = useCallback(async () => {
await supabaseSignOut(supabase);
}, []);
const value = useMemo<AuthContextValue>(
() => ({
session,
profile,
device,
ready,
deviceLookupDone,
refreshProfile,
refreshDevice,
setDevice,
signOut,
}),
[session, profile, device, ready, deviceLookupDone, refreshProfile, refreshDevice, signOut],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
return ctx;
}