Compare commits

...

8 Commits

Author SHA1 Message Date
byGalax b89ec90813 chore: bump version to 0.8.0
Release desktop app / build (, windows-latest) (push) Has been cancelled
Release desktop app / build (--target universal-apple-darwin --bundles app,updater, macos-14) (push) Has been cancelled
Voice messages, offline queue, delivery receipts, group call scaling,
recovery code, push notifications scaffolding, admin panel, search v2,
focus-flicker fix.
2026-04-21 01:15:57 +02:00
byGalax a04ecf7a19 feat: voice messages, offline queue, delivery ticks, volume slider, admin + scaling
- Voice messages: MediaRecorder → encrypted attachment, custom waveform
  player via OfflineAudioContext, 60s limit + live mic-level meter
- Offline message queue: localStorage outbox, exponential backoff retries,
  optimistic pending bubble with retry/discard
- Delivery indicator: message_deliveries table + RLS (reciprocal receipts),
  ✓ / ✓✓ / ✓✓-blue tick states, group-aware (all members must ack)
- Per-participant volume slider in calls via right-click tile menu,
  persisted to localStorage, applied to attached audio elements
- Group call scaling: grid up to 12 tiles with pagination,
  active-speaker auto-promotion in fullscreen
- Push notifications scaffolding: service worker, VAPID subscription
  registration, notify-push edge function skeleton
- Backup recovery code: 24-char base32 code (~120 bits entropy) as
  alternative decrypt path, restore UI with mode toggle
- Admin panel: conversations list, audit log (admin_audit_log table +
  admin_log_action RPC), audit entry on user flag toggle
- Search v2: sender filter, attachment-only toggle, date range
- Reactions pop animation (scale 0.4→1.15→1 on count change)
- Message list windowing (150 default, expand via IntersectionObserver)
- Stub cleanup: removed dead ScreenshareStub from CallParticipantTile

Fixes:
- Focus-triggered flicker: dropped window.focus listeners in three spots,
  throttled visibilitychange/online wake-refreshes to 30s, keep existing
  data visible during background re-syncs (no more spinner on every click)
- Voice attachment audio element collapsed to 0px on peer side — now
  forces 280px min-width on bubble

Migrations (push required):
  20260421000001_message_deliveries.sql
  20260421000002_admin_audit_log.sql

Server TODO:
  VAPID keys + notify-push edge function deploy
2026-04-21 01:14:16 +02:00
byGalax da85f0ba54 feat: call UX overhaul — deafen sync, share dialog, fullscreen redesign
Speaking ring:
- Switch useActiveSpeakers from LiveKit's smoothed isSpeaking / server-
  batched ActiveSpeakersChanged to Web Audio API AnalyserNode on each
  participant's raw audio MediaStreamTrack. Poll 50ms, RMS threshold 0.03,
  250ms hold. Feels real-time vs the old ~500ms lag
- Defensive syncProbe on every tick so probes catch up if TrackPublished
  missed (local mic publish race on join)
- Universal speaking overlay on tile (3px emerald border + inset glow,
  z-10) so video mode shows the ring too, not just audio mode

Screen sharing:
- Separate "screen" tile per sharer so the sharer's avatar tile stays
  intact with its speaking ring. Tile.id is kind-prefixed (user:xxx /
  screen:xxx) so focus tracking distinguishes them
- New ScreenShareDialog (quality preset + fps override + displaySurface
  hint) opens on the share button. startScreenShare / stopScreenShare
  actions in CallContext replace the one-shot toggle
- ScreenShareViewer: plain CSS-only fullscreen overlay (Tauri WKWebView
  doesn't implement requestFullscreen), always `h-full w-full
  object-contain`, Esc exits

Camera:
- toggleCamera action in CallContext tracks isCameraEnabled
- VideoStub renders real <video> srcObject for the participant's camera
  MediaStreamTrack; local preview is mirrored
- Tile video track resolves to Track.Source.Camera publications of the
  LocalParticipant / each RemoteParticipant
- Room listens for TrackMuted / TrackUnmuted and re-publishes remote
  state so peers switch to avatar placeholder when a camera is disabled

Deafen:
- New isDeafened state + toggleDeafen action. Sets `muted = true` on all
  attached `<audio[data-livekit-track]>` plus mutes fresh ones on attach
  via module-level flag
- Broadcast state over the LiveKit data channel
  ({type:'presence', deafened}) so peers can render the headphones-off
  badge. Attributes API not used because the self-hosted server may run
  older LiveKit versions
- remoteDeafen: Record<identity, bool> exposed via context, bumped on
  DataReceived and re-broadcast on ParticipantConnected

Incoming video call:
- acceptIncoming takes an optional CallKind override so the receiver can
  answer a video invite with audio only or promote an audio invite to
  video on accept
- IncomingCallPanel shows two accept buttons (audio + video) when the
  invite is a video call

Audio devices:
- audioSettings adds inputDeviceId + outputDeviceId, persisted
- CallContext uses them on setMicrophoneEnabled, plus new
  setAudioInputDevice / setAudioOutputDevice hot-swap actions.
  Output swap applies setSinkId to every attached remote-audio element
  since LiveKit's own switchActiveDevice only tracks elements it
  attached itself
- SettingsPage "Mikrofon" + "Ausgabegerät" selects with devicechange
  listener and a permission-probe button

Fullscreen mode:
- Replaced absolute-positioned speaker + floating thumbnails with a real
  flex layout. Default = even grid of all tiles. Clicking a tile flips
  to big-speaker + horizontal thumbnail strip. Click focused tile =
  back to grid
- Controls overlay pinned bottom; content wrapper has pb-24 so tiles
  never sit behind the toolbar
- Grid now uses explicit grid-rows-* so cells get a defined 1fr height
  (without it, video intrinsic dimensions blew tiles past the container
  bounds on Windows)

UI chips:
- Mic-off badge combines isMuted flag AND
  localParticipant.isMicrophoneEnabled, so a user with no mic / denied
  permission sees the badge + the toolbar button red even though they
  never pressed mute
- Deafen badge on tile chips for local + remote (remote driven by the
  data-channel broadcast)
2026-04-21 00:02:43 +02:00
byGalax a4c9b959a9 fix: editable decrypt + windows realtime wake (v0.7.1)
Release desktop app / build (, windows-latest) (push) Has been cancelled
Release desktop app / build (--target universal-apple-darwin --bundles app,updater, macos-14) (push) Has been cancelled
Edit message decrypt:
- handleUpdate in useConversationMessages now refetches the canonical row
  via REST after a realtime UPDATE instead of trusting the realtime
  payload's bytea encoding. Same pattern as handleInsert — base64 vs
  `\x…` hex serialisation varies across supabase/postgrest versions and
  was silently producing undecryptable ciphertext for edited messages
  on the receiver side

Windows WebView2 background throttling:
- ConversationsContext, useFriendships and useConversationMessages now
  listen for visibilitychange / focus / online events and trigger both a
  fresh REST refresh and a best-effort channel.subscribe() on wake.
  WebView2 aggressively throttles background WebSockets and was dropping
  realtime events entirely while the window was minimised, so new
  messages and friend acceptances only surfaced after a manual reload

Bump tauri version 0.7.0 -> 0.7.1
2026-04-20 22:15:49 +02:00
byGalax 37becba7e2 feat: audio devices + fullscreen + banner cleanup (v0.7.0)
Release desktop app / build (, windows-latest) (push) Has been cancelled
Release desktop app / build (--target universal-apple-darwin --bundles app,updater, macos-14) (push) Has been cancelled
Audio device selection:
- audioSettings: persisted inputDeviceId + outputDeviceId
- CallContext: uses stored input deviceId on mic enable, new
  setAudioInputDevice / setAudioOutputDevice actions that hot-swap
  without reconnect. Output swap applies HTMLMediaElement.setSinkId
  to every attached remote-audio element (LiveKit's switchActiveDevice
  only tracks elements it attached itself)
- SettingsPage: new "Mikrofon" + "Ausgabegerät" selects with
  enumerateDevices, devicechange listener, permission-probe button.
  setSinkId-unsupported fallback is messaged but non-blocking

Fullscreen:
- FullscreenCall was absolute inset-0 z-40 which trapped it inside the
  <main> pane — sidebar + chat-list stayed visible. Switched to
  fixed inset-0 z-[60] so the call overlays the whole window
  Discord-style
- ScreenShareViewer fullscreen: CSS-only toggle (native Fullscreen API
  unreliable under Tauri WKWebView), portalled to document.body when
  active so no ancestor stacking context can clip it. Esc exits

ActiveCallBanner:
- cleanup effect returned early when presence was entirely empty,
  leaving the "1 im Raum" fallback stuck after both peers left. Now
  schedules dismissLastCall as soon as othersIn.length === 0, with a
  3s grace window to absorb presence re-sync flicker

Bump tauri version 0.6.0 -> 0.7.0
2026-04-20 21:26:10 +02:00
byGalax eb8f9857ff feat: device backup/restore + quick wins + username casing
Backup / restore flow:
- deviceBackup.ts: v2 format wrapping userId + deviceId + privateKey in
  an encrypted JSON payload so restore can re-seed localStorage, vault,
  and reattach to the existing server-side device row without provisioning
  a new one (conv-key bundles stay valid, no "awaiting key" state)
- shared/auth: restoreDeviceFromServerRecord — verifies session.user.id
  matches the backup's userId, confirms the server device row still
  exists, then writes the private key into the local secret store
- BackupExportDialog — passphrase + confirm, generates portable string,
  copy + download .txt
- DeviceRestore — textarea + passphrase → seeds vault + writes
  deviceId cache, treats this install as the original device
- DevicePage now has tabs "Neu einrichten" / "Backup wiederherstellen"
- BackupPromptBanner — post-registration nudge, reads sessionStorage
  signal from fresh provisions and persists "never-ask-again" in
  localStorage so it stops nagging
- SettingsPage backup section: uses the new dialog; removes the
  dangerous in-place key import (restore now lives in the device flow)

Username casing:
- Migration 20260420000002 drops lower() from the handle_new_user trigger
  and widens the regex to [A-Za-z0-9_]. profiles.username is citext so
  uniqueness + lookups stay case-insensitive regardless of stored casing
- Shared auth: trim() only, no toLowerCase on signup/lookups/search.
  ilike handles CI anyway and citext makes client normalisation redundant
- AuthPage regex + input preserve case, FriendsPage search preserves case
- i18n (de+en): updated username_hint / username_invalid / ERR_USERNAME_INVALID
  to reflect the new rule

Quick wins:
- React Router v7 future flags (v7_startTransition + v7_relativeSplatPath)
  set on BrowserRouter — silences the upgrade warning
- appUpdates.checkForUpdate: swallow benign network/fetch/"could not
  fetch valid release JSON" cases silently instead of console spam
- osNotify: persist an "asked" marker in localStorage so the permission
  prompt only fires once per install (OS already persists the answer,
  but the plugin re-queries loudly otherwise)
2026-04-20 19:07:31 +02:00
byGalax de431386ea feat: reply + search + forward + archive/mute + error boundary
Messages:
- Reply-to: hover action, composer chip with cancel, quote bubble inside
  the replying message with tap-to-jump + amber highlight ring
- Search: header search button toggles in-conversation search bar with
  prev/next + match counter, auto-jump to active match
- Forward: multi-select conversation picker. Attachments are now carried
  over: download + decrypt source, re-encrypt under each target conv-key,
  re-upload with fresh per-attachment keys, insert new attachment rows

Conversations:
- Archive + mute per member. New migration 20260420000001 adds `archived`
  + `muted_until` on conversation_members. Shared helpers:
  setConversationArchived / setConversationMutedUntil / isConversationMuted
- ChatsPage: archive toggle in header with unread badge for archived
  bucket, split active/archived lists, muted indicator (BellOff icon,
  dimmed unread badge)
- ConversationRowMenu via createPortal (escapes sidebar overflow clip),
  forwardRef-based MenuItem so submenu positioning refs survive React 18
- ConversationsContext: suppresses notification sound + OS notif when
  target conversation is muted
- Refresh on `profiles UPDATE` realtime so peer avatar / displayName
  changes flow to conversation.members without manual refresh

Resilience:
- ErrorBoundary (Discord-style): centred spinner + escalating copy, no
  manual reload button. Backoff retry schedule [2s, 4s, 8s, 15s, 30s].
  Uses a keyed Fragment (not a div wrapper) so flex h-full chains survive
- App wrapped root + per-route RouteBoundary, conversation-level boundary
- AuthContext: flip `ready` immediately on cached session read; validate
  getUser in background so a stalled/offline Supabase doesn't freeze the
  app on the loading spinner

Crypto:
- Swap libsodium-wrappers -> libsodium-wrappers-sumo (compact build was
  missing crypto_pwhash so Argon2id vault KDF threw, falling back to
  plaintext localStorage on every launch)
- Shim d.ts for sumo types (sumo is API superset, no official types ship)
- vite optimizeDeps includes sumo with the "require" condition
- secureFileStore: exists(dir) check before mkdir; surface genuine
  permission errors instead of silent catch

Tauri:
- fs scope adds `$APPLOCALDATA` direct entry (not just /**) so the app
  data directory itself can be mkdir'd on first launch

Chat layout:
- Skip call_event messages when computing avatar run boundaries so a
  regular bubble followed by a call event from the same sender still
  shows its avatar
2026-04-20 15:42:49 +02:00
byGalax 1fab2edc57 fix(messages): peer avatar visibility in chat bubbles
- ConversationsContext: subscribe to profiles UPDATE realtime so
  conversation members[].profile picks up peer avatar / displayName changes
  without a manual refresh
- ConversationPage: skip call_event messages when computing run boundaries.
  Previously a peer bubble followed by a call event from the same sender
  was treated as mid-run -> avatar slot collapsed to a placeholder
- DM peer-profile fallback already added in previous commit covers transient
  member-lookup misses
2026-04-20 00:49:21 +02:00
87 changed files with 8211 additions and 864 deletions
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@chat-app/desktop",
"version": "0.1.0",
"version": "0.8.0",
"private": true,
"description": "Tauri v2 desktop client (Windows / macOS / Linux)",
"type": "module",
@@ -30,7 +30,7 @@
"@tauri-apps/plugin-stronghold": "^2.0.1",
"@tauri-apps/plugin-updater": "^2.10.1",
"i18next": "^23.16.4",
"libsodium-wrappers": "0.7.15",
"libsodium-wrappers-sumo": "0.7.15",
"livekit-client": "^2.7.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -41,6 +41,7 @@
"devDependencies": {
"@tauri-apps/cli": "^2.1.0",
"@types/libsodium-wrappers": "^0.7.14",
"@types/libsodium-wrappers-sumo": "^0.8.2",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
+67
View File
@@ -0,0 +1,67 @@
// Web Push service worker.
//
// Handles browser-delivered push events when the app tab is closed or in the
// background. Tauri desktop does not install service workers; native OS
// notifications are routed through the Tauri notification plugin instead
// (see src/lib/osNotify.ts).
//
// Payload contract — server sends JSON of shape:
// { title: string, body?: string, conversationId?: string, kind?: 'message' | 'call' }
// Body is intentionally generic; message ciphertext is never included.
self.addEventListener('install', (event) => {
// Activate immediately so updates apply on next page load.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('push', (event) => {
let data = { title: 'Neue Nachricht', body: '' };
try {
if (event.data) {
data = { ...data, ...event.data.json() };
}
} catch (_err) {
/* malformed payload — fall back to defaults */
}
const opts = {
body: data.body || '',
icon: '/favicon.svg',
badge: '/favicon.svg',
tag: data.conversationId || 'default',
renotify: true,
data: {
conversationId: data.conversationId,
kind: data.kind,
},
};
event.waitUntil(self.registration.showNotification(data.title, opts));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const conversationId = event.notification.data && event.notification.data.conversationId;
const target = conversationId ? '/chats/' + conversationId : '/';
event.waitUntil(
self.clients
.matchAll({ type: 'window', includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
if ('focus' in client) {
client.postMessage({ type: 'navigate', to: target });
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(target);
}
return undefined;
}),
);
});
+1 -1
View File
@@ -678,7 +678,7 @@ dependencies = [
[[package]]
name = "chat-app-desktop"
version = "0.1.0"
version = "0.8.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "chat-app-desktop"
version = "0.1.0"
version = "0.8.0"
description = "ChatApp desktop client"
authors = ["Dennis"]
edition = "2021"
@@ -34,6 +34,7 @@
{
"identifier": "fs:scope",
"allow": [
{ "path": "$APPLOCALDATA" },
{ "path": "$APPLOCALDATA/**" }
]
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "ChatApp",
"version": "0.6.0",
"version": "0.8.0",
"identifier": "com.meinname.chatapp",
"build": {
"beforeDevCommand": "pnpm vite:dev",
+81 -37
View File
@@ -1,6 +1,7 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { BrowserRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom';
import { AppShell } from './components/AppShell';
import { ErrorBoundary } from './components/ErrorBoundary';
import { UpdateToast } from './components/UpdateToast';
import { RequireAdmin, RequireAuth, RequireDevice } from './components/guards';
import { AuthProvider } from './context/AuthContext';
@@ -17,42 +18,85 @@ import { DevicePage } from './pages/DevicePage';
import { FriendsPage } from './pages/FriendsPage';
import { SettingsPage } from './pages/SettingsPage';
export function App() {
// Isolates each top-level route so a crash in one page doesn't take the whole
// shell down. The boundary auto-retries via `ErrorBoundary`'s backoff schedule.
function RouteBoundary({ scope }: { scope: string }) {
return (
<ThemeProvider>
<AuthProvider>
<FriendshipsProvider>
<ConversationsProvider>
<CallProvider>
<BrowserRouter>
<Routes>
<Route path="/auth" element={<AuthPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route element={<RequireAuth />}>
<Route path="/device" element={<DevicePage />} />
<Route element={<RequireDevice />}>
<Route element={<AppShell />}>
<Route index element={<Navigate to="/chats" replace />} />
<Route path="/chats" element={<ChatsPage />}>
<Route index element={<ChatsEmptyState />} />
<Route path=":id" element={<ConversationPage />} />
</Route>
<Route path="/friends" element={<FriendsPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route element={<RequireAdmin />}>
<Route path="/admin" element={<AdminPage />} />
</Route>
</Route>
</Route>
</Route>
<Route path="*" element={<Navigate to="/chats" replace />} />
</Routes>
<UpdateToast />
</BrowserRouter>
</CallProvider>
</ConversationsProvider>
</FriendshipsProvider>
</AuthProvider>
</ThemeProvider>
<ErrorBoundary scope={scope}>
<Outlet />
</ErrorBoundary>
);
}
export function App() {
return (
<ErrorBoundary scope="root">
<ThemeProvider>
<AuthProvider>
<FriendshipsProvider>
<ConversationsProvider>
<CallProvider>
<BrowserRouter
future={{
// Opt into v7 behaviour early so the upgrade is a no-op:
// - `v7_startTransition` wraps navigations in startTransition
// so Suspense / concurrent rendering deal with the new tree
// - `v7_relativeSplatPath` matches relative paths inside
// splat routes against the parent splat segment (not the
// full matched path). Our tree has no splat routes today
// but this kills the runtime warning and future-proofs.
v7_startTransition: true,
v7_relativeSplatPath: true,
}}
>
<Routes>
<Route element={<RouteBoundary scope="auth" />}>
<Route path="/auth" element={<AuthPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
</Route>
<Route element={<RequireAuth />}>
<Route element={<RouteBoundary scope="device" />}>
<Route path="/device" element={<DevicePage />} />
</Route>
<Route element={<RequireDevice />}>
<Route element={<AppShell />}>
<Route index element={<Navigate to="/chats" replace />} />
<Route element={<RouteBoundary scope="chats" />}>
<Route path="/chats" element={<ChatsPage />}>
<Route index element={<ChatsEmptyState />} />
<Route
path=":id"
element={
<ErrorBoundary scope="conversation">
<ConversationPage />
</ErrorBoundary>
}
/>
</Route>
</Route>
<Route element={<RouteBoundary scope="friends" />}>
<Route path="/friends" element={<FriendsPage />} />
</Route>
<Route element={<RouteBoundary scope="settings" />}>
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route element={<RequireAdmin />}>
<Route element={<RouteBoundary scope="admin" />}>
<Route path="/admin" element={<AdminPage />} />
</Route>
</Route>
</Route>
</Route>
</Route>
<Route path="*" element={<Navigate to="/chats" replace />} />
</Routes>
<UpdateToast />
</BrowserRouter>
</CallProvider>
</ConversationsProvider>
</FriendshipsProvider>
</AuthProvider>
</ThemeProvider>
</ErrorBoundary>
);
}
+2
View File
@@ -4,6 +4,7 @@ import { Outlet } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { startConversationKeySync } from '../lib/conversationKeySync';
import { ensureNotificationPermission } from '../lib/osNotify';
import { BackupPromptBanner } from './BackupPromptBanner';
import { CallUI } from './CallUI';
import { Sidebar } from './Sidebar';
@@ -32,6 +33,7 @@ export function AppShell() {
</main>
</div>
<CallUI />
<BackupPromptBanner />
</div>
);
}
@@ -0,0 +1,239 @@
import { type AttachmentHandle, downloadAndDecryptAttachment } from '@chat-app/shared/chat';
import { useEffect, useMemo, useRef, useState } from 'react';
import { supabase } from '../lib/supabase';
import { AlertIcon, MicIcon, SpinnerIcon } from './icons';
interface Props {
handle: AttachmentHandle;
}
const BAR_COUNT = 48;
// Custom voice-message player with waveform visualisation. Decoded peaks are
// computed once per blob via OfflineAudioContext so playback only carries the
// rendered DOM. Falls back to a rectangular bar if decoding fails (e.g. the
// blob mime is recognised by <audio> but not by AudioContext).
export function AttachmentAudio({ handle }: Props) {
const [blobUrl, setBlobUrl] = useState<string | null>(null);
const [arrayBuf, setArrayBuf] = useState<ArrayBuffer | null>(null);
const [error, setError] = useState<string | null>(null);
const [peaks, setPeaks] = useState<number[] | null>(null);
const [duration, setDuration] = useState<number>(0);
const [position, setPosition] = useState<number>(0);
const [playing, setPlaying] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
let cancelled = false;
let url: string | null = null;
setError(null);
setBlobUrl(null);
setArrayBuf(null);
downloadAndDecryptAttachment({ client: supabase, handle })
.then(async (blob) => {
if (cancelled) return;
url = URL.createObjectURL(blob);
setBlobUrl(url);
const buf = await blob.arrayBuffer();
if (!cancelled) setArrayBuf(buf);
})
.catch((err: unknown) => {
if (!cancelled) {
setError(err instanceof Error ? err.message : 'download failed');
}
});
return () => {
cancelled = true;
if (url) URL.revokeObjectURL(url);
};
}, [handle.id, handle.storagePath, handle.keyB64, handle.nonceB64]);
// Compute peaks via OfflineAudioContext. Cheap O(n) scan over PCM samples
// bucketed into BAR_COUNT bars. Done once per attachment.
useEffect(() => {
if (!arrayBuf) return;
let cancelled = false;
const Ctx =
window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
const ctx = new Ctx();
ctx
.decodeAudioData(arrayBuf.slice(0))
.then((decoded) => {
if (cancelled) return;
setDuration(decoded.duration);
const channel = decoded.getChannelData(0);
const bucket = Math.max(1, Math.floor(channel.length / BAR_COUNT));
const out = new Array<number>(BAR_COUNT).fill(0);
for (let i = 0; i < BAR_COUNT; i++) {
let max = 0;
const start = i * bucket;
const end = Math.min(channel.length, start + bucket);
for (let j = start; j < end; j++) {
const v = Math.abs(channel[j]!);
if (v > max) max = v;
}
out[i] = max;
}
// Normalize so loudest peak is 1; keeps quiet recordings visible.
const peak = Math.max(...out, 0.001);
setPeaks(out.map((v) => v / peak));
})
.catch(() => {
// Fall through — UI shows a flat bar but playback still works.
})
.finally(() => {
void ctx.close().catch(() => {});
});
return () => {
cancelled = true;
};
}, [arrayBuf]);
const fallbackPeaks = useMemo(
() => (peaks ? null : Array.from({ length: BAR_COUNT }, () => 0.5)),
[peaks],
);
const visiblePeaks = peaks ?? fallbackPeaks!;
const progress = duration > 0 ? position / duration : 0;
const onTogglePlay = () => {
const el = audioRef.current;
if (!el || !blobUrl) return;
if (el.paused) void el.play();
else el.pause();
};
const onSeek = (e: React.MouseEvent<HTMLDivElement>) => {
const el = audioRef.current;
if (!el || duration === 0) return;
const rect = e.currentTarget.getBoundingClientRect();
const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
el.currentTime = ratio * duration;
};
if (error) {
return (
<div className="mt-2 inline-flex items-center gap-2 rounded-lg border border-rose-500/20 bg-rose-500/10 px-3 py-2 text-xs text-rose-200">
<AlertIcon className="h-4 w-4" />
<span>{error}</span>
</div>
);
}
return (
<div className="mt-2 flex w-[280px] min-w-[280px] items-center gap-2 rounded-lg border border-line bg-surface-2 px-3 py-2">
<button
type="button"
onClick={onTogglePlay}
disabled={!blobUrl}
aria-label={playing ? 'Pause' : 'Wiedergabe'}
title={playing ? 'Pause' : 'Wiedergabe'}
className="flex h-9 w-9 shrink-0 cursor-pointer items-center justify-center rounded-full bg-accent text-accent-fg transition hover:brightness-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
>
{!blobUrl ? (
<SpinnerIcon className="h-4 w-4" />
) : playing ? (
<PauseGlyph />
) : (
<PlayGlyph />
)}
</button>
<div className="flex min-w-0 flex-1 flex-col gap-1">
<div
role="slider"
aria-label="Position"
aria-valuemin={0}
aria-valuemax={Math.max(1, Math.floor(duration))}
aria-valuenow={Math.floor(position)}
tabIndex={0}
onClick={onSeek}
className="flex h-7 cursor-pointer items-center gap-[2px]"
>
{visiblePeaks.map((v, i) => {
const playedRatio = (i + 0.5) / BAR_COUNT;
const played = playedRatio <= progress;
const h = Math.max(2, Math.round(v * 22));
return (
<span
key={i}
style={{ height: h + 'px' }}
className={
'w-[3px] rounded-full ' +
(played ? 'bg-accent' : 'bg-fg-muted/40')
}
/>
);
})}
</div>
<div className="flex items-center justify-between text-[10px] tabular-nums text-fg-muted">
<span className="inline-flex items-center gap-1">
<MicIcon className="h-3 w-3" />
<span>{formatSec(playing ? position : duration)}</span>
</span>
</div>
</div>
{blobUrl && (
<audio
ref={audioRef}
src={blobUrl}
preload="metadata"
onLoadedMetadata={(e) => {
// Some webm/opus blobs report Infinity until first seek (Chrome
// bug). Force a seek to flush real duration.
const el = e.currentTarget;
if (!Number.isFinite(el.duration)) {
el.currentTime = 1e9;
setTimeout(() => {
el.currentTime = 0;
}, 0);
} else if (duration === 0) {
setDuration(el.duration);
}
}}
onDurationChange={(e) => {
const d = e.currentTarget.duration;
if (Number.isFinite(d) && d > 0) setDuration(d);
}}
onTimeUpdate={(e) => setPosition(e.currentTarget.currentTime)}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onEnded={() => {
setPlaying(false);
setPosition(0);
}}
className="hidden"
>
<track kind="captions" />
</audio>
)}
</div>
);
}
function PlayGlyph() {
return (
<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true">
<path d="M5 3.5l8 4.5-8 4.5z" />
</svg>
);
}
function PauseGlyph() {
return (
<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true">
<rect x="4" y="3" width="3" height="10" rx="1" />
<rect x="9" y="3" width="3" height="10" rx="1" />
</svg>
);
}
function formatSec(sec: number): string {
if (!Number.isFinite(sec) || sec < 0) sec = 0;
const m = Math.floor(sec / 60);
const s = Math.floor(sec % 60);
return m + ':' + s.toString().padStart(2, '0');
}
@@ -0,0 +1,306 @@
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { type BackupBundle, exportDeviceBackupWithRecovery } from '../lib/deviceBackup';
import { AlertIcon, CopyIcon, LockIcon, ShieldIcon, SpinnerIcon, XIcon } from './icons';
interface Props {
open: boolean;
userId: string;
deviceId: string;
privateKey: Uint8Array;
onClose: () => void;
}
// Exports the device's private key + identity into a passphrase-protected
// portable string. The user can store this string anywhere (password manager,
// printed paper, encrypted file on a USB stick). Without it, losing local
// storage on this install means losing all past conversation keys.
export function BackupExportDialog({ open, userId, deviceId, privateKey, onClose }: Props) {
const { t } = useTranslation(['app']);
const [passphrase, setPassphrase] = useState('');
const [confirm, setConfirm] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [bundle, setBundle] = useState<BackupBundle | null>(null);
const [copied, setCopied] = useState(false);
const [copiedRecovery, setCopiedRecovery] = useState(false);
const canGenerate = useMemo(() => {
return passphrase.length >= 8 && passphrase === confirm && !busy;
}, [passphrase, confirm, busy]);
const reset = useCallback(() => {
setPassphrase('');
setConfirm('');
setBundle(null);
setError(null);
setCopied(false);
setCopiedRecovery(false);
}, []);
const handleClose = useCallback(() => {
reset();
onClose();
}, [reset, onClose]);
const handleGenerate = useCallback(async () => {
if (!canGenerate) return;
setBusy(true);
setError(null);
try {
const b = await exportDeviceBackupWithRecovery({
userId,
deviceId,
privateKey,
passphrase,
});
setBundle(b);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}, [canGenerate, userId, deviceId, privateKey, passphrase]);
const copyText = async (text: string, marker: 'main' | 'recovery'): Promise<void> => {
try {
await navigator.clipboard.writeText(text);
if (marker === 'main') {
setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
} else {
setCopiedRecovery(true);
window.setTimeout(() => setCopiedRecovery(false), 1500);
}
} catch {
/* fall back — user can select manually */
}
};
const handleDownload = useCallback(() => {
if (!bundle) return;
const text =
'=== Passphrase backup ===\n' +
bundle.passphraseBackup +
'\n\n=== Recovery code ===\n' +
bundle.recoveryCode +
'\n\n=== Recovery backup (use with the recovery code) ===\n' +
bundle.recoveryBackup +
'\n';
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `chatapp-device-backup-${deviceId.slice(0, 8)}.txt`;
a.click();
URL.revokeObjectURL(url);
}, [bundle, deviceId]);
if (!open) return null;
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:backup.export_title', { defaultValue: 'Gerätesicherung erstellen' })}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={handleClose}
>
<div
onClick={(e) => e.stopPropagation()}
className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-line bg-surface-3 shadow-xl"
>
<header className="flex items-center justify-between border-b border-line px-5 py-3">
<div className="flex items-center gap-2">
<ShieldIcon className="h-4 w-4 text-accent" />
<h3 className="font-display text-sm font-semibold text-fg">
{t('app:backup.export_title', { defaultValue: 'Gerätesicherung erstellen' })}
</h3>
</div>
<button
type="button"
onClick={handleClose}
aria-label="Close"
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-fg-muted transition hover:bg-surface-2 hover:text-fg"
>
<XIcon className="h-4 w-4" />
</button>
</header>
<div className="flex-1 overflow-y-auto p-5">
{!bundle ? (
<>
<p className="text-sm text-fg-muted">
{t('app:backup.export_explainer', {
defaultValue:
'Verschlüssele den Geräteschlüssel mit einer Passphrase. Ohne Passphrase UND Backup-String ist keine Wiederherstellung möglich.',
})}
</p>
<div className="mt-4 space-y-3">
<div className="space-y-1">
<label className="block text-xs font-medium uppercase tracking-wide text-fg-muted">
{t('app:backup.passphrase', { defaultValue: 'Passphrase' })}
</label>
<input
type="password"
autoFocus
minLength={8}
value={passphrase}
onChange={(e) => setPassphrase(e.target.value)}
placeholder="min. 8 Zeichen"
className="w-full rounded-lg border border-line bg-surface-2 px-3 py-2.5 text-sm text-fg placeholder-fg-muted transition focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
/>
</div>
<div className="space-y-1">
<label className="block text-xs font-medium uppercase tracking-wide text-fg-muted">
{t('app:backup.passphrase_confirm', { defaultValue: 'Passphrase wiederholen' })}
</label>
<input
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
className="w-full rounded-lg border border-line bg-surface-2 px-3 py-2.5 text-sm text-fg placeholder-fg-muted transition focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
/>
</div>
{confirm.length > 0 && confirm !== passphrase && (
<p className="text-xs text-rose-500 dark:text-rose-300">
{t('app:backup.passphrase_mismatch', { defaultValue: 'Passphrasen stimmen nicht überein.' })}
</p>
)}
</div>
<div className="mt-4 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-700 dark:text-amber-200">
<div className="flex items-start gap-2">
<AlertIcon className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-300" />
<span>
{t('app:backup.export_warning', {
defaultValue:
'Anthropic: Backup + Passphrase sicher aufbewahren. Passphrase kann nicht wiederhergestellt werden.',
})}
</span>
</div>
</div>
{error && (
<p role="alert" className="mt-3 text-sm text-rose-600 dark:text-rose-200">
{error}
</p>
)}
</>
) : (
<>
<div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-3 text-xs text-emerald-700 dark:text-emerald-200">
<div className="flex items-start gap-2">
<LockIcon className="mt-0.5 h-4 w-4 shrink-0" />
<span>
{t('app:backup.export_success', {
defaultValue:
'Backup erstellt. Speichere diesen String + Passphrase in einem Passwortmanager oder drucke ihn aus.',
})}
</span>
</div>
</div>
<label className="mt-3 block text-xs font-medium uppercase tracking-wide text-fg-muted">
Backup-String
</label>
<textarea
readOnly
value={bundle.passphraseBackup}
rows={6}
onFocus={(e) => e.currentTarget.select()}
className="mt-1 w-full resize-none rounded-lg border border-line bg-surface-2 p-3 font-mono text-[11px] leading-relaxed text-fg"
/>
<div className="mt-2 flex gap-2">
<button
type="button"
onClick={() => void copyText(bundle.passphraseBackup, 'main')}
className="inline-flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm font-medium text-fg transition hover:bg-surface-3"
>
<CopyIcon className="h-4 w-4" />
<span>{copied ? 'Kopiert!' : 'Kopieren'}</span>
</button>
<button
type="button"
onClick={handleDownload}
className="inline-flex flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm font-medium text-fg transition hover:bg-surface-3"
>
Als Datei speichern (alles)
</button>
</div>
<div className="mt-5 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3">
<div className="flex items-start gap-2">
<ShieldIcon className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-300" />
<div className="min-w-0 flex-1">
<p className="text-xs font-semibold text-amber-700 dark:text-amber-200">
Recovery-Code (Passphrase vergessen?)
</p>
<p className="mt-0.5 text-[11px] text-amber-700/80 dark:text-amber-200/80">
Code separat aufbewahren. Mit dem Recovery-Backup unten lässt sich der Schlüssel
ohne Passphrase wiederherstellen.
</p>
<p className="mt-2 select-all rounded bg-surface-3 px-2 py-1.5 font-mono text-sm tracking-widest text-fg">
{bundle.recoveryCode}
</p>
</div>
</div>
</div>
<label className="mt-3 block text-xs font-medium uppercase tracking-wide text-fg-muted">
Recovery-Backup-String
</label>
<textarea
readOnly
value={bundle.recoveryBackup}
rows={6}
onFocus={(e) => e.currentTarget.select()}
className="mt-1 w-full resize-none rounded-lg border border-line bg-surface-2 p-3 font-mono text-[11px] leading-relaxed text-fg"
/>
<button
type="button"
onClick={() => void copyText(bundle.recoveryBackup, 'recovery')}
className="mt-2 inline-flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm font-medium text-fg transition hover:bg-surface-3"
>
<CopyIcon className="h-4 w-4" />
<span>{copiedRecovery ? 'Kopiert!' : 'Recovery-Backup kopieren'}</span>
</button>
</>
)}
</div>
<footer className="flex items-center justify-end gap-2 border-t border-line bg-surface-2 px-5 py-3">
{!bundle ? (
<>
<button
type="button"
onClick={handleClose}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-2 text-sm text-fg transition hover:bg-surface-2"
>
{t('app:friends.action_cancel', { defaultValue: 'Abbrechen' })}
</button>
<button
type="button"
onClick={() => void handleGenerate()}
disabled={!canGenerate}
className="inline-flex cursor-pointer items-center gap-1.5 rounded-md bg-accent px-3 py-2 text-sm font-semibold text-accent-fg transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60"
>
{busy && <SpinnerIcon className="h-4 w-4" />}
<span>{t('app:backup.generate', { defaultValue: 'Backup erstellen' })}</span>
</button>
</>
) : (
<button
type="button"
onClick={handleClose}
className="cursor-pointer rounded-md bg-accent px-3 py-2 text-sm font-semibold text-accent-fg transition hover:brightness-110"
>
{t('app:backup.done', { defaultValue: 'Fertig' })}
</button>
)}
</footer>
</div>
</div>
);
}
@@ -0,0 +1,122 @@
import { loadDevicePrivateKey } from '@chat-app/shared/auth';
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
import { devLocalSecretStore } from '../lib/secretStore';
import { BackupExportDialog } from './BackupExportDialog';
import { ShieldIcon, XIcon } from './icons';
const DISMISS_KEY = 'chatapp.backup.prompt.dismissed';
const SESSION_KEY = 'chatapp.backup.prompt';
// Post-registration nudge: right after a fresh device provision we set
// `chatapp.backup.prompt` in sessionStorage. This component reads it and
// shows a floating "mach jetzt ein Backup" banner until the user either
// creates one or explicitly dismisses (persisted in localStorage so we stop
// nagging across reloads).
export function BackupPromptBanner() {
const { t } = useTranslation(['app']);
const { profile, device } = useAuth();
const [visible, setVisible] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [privateKey, setPrivateKey] = useState<Uint8Array | null>(null);
useEffect(() => {
try {
if (window.localStorage.getItem(DISMISS_KEY) === '1') return;
if (window.sessionStorage.getItem(SESSION_KEY) !== '1') return;
setVisible(true);
} catch {
/* storage unavailable */
}
}, []);
const dismiss = useCallback((persist: boolean) => {
setVisible(false);
try {
window.sessionStorage.removeItem(SESSION_KEY);
if (persist) window.localStorage.setItem(DISMISS_KEY, '1');
} catch {
/* ignore */
}
}, []);
const openDialog = useCallback(async () => {
if (!profile?.userId || !device?.id) return;
const priv = await loadDevicePrivateKey(devLocalSecretStore, profile.userId, device.id);
if (!priv) return;
setPrivateKey(priv);
setDialogOpen(true);
}, [profile, device]);
const closeDialog = useCallback(() => {
setDialogOpen(false);
if (privateKey) {
for (let i = 0; i < privateKey.length; i++) privateKey[i] = 0;
}
setPrivateKey(null);
// After the user interacts with the dialog, drop the banner regardless
// of whether they actually completed the backup — they're aware now.
dismiss(true);
}, [privateKey, dismiss]);
if (!visible) return null;
return (
<>
<div
role="status"
className="fixed bottom-6 left-1/2 z-40 flex w-[min(92vw,520px)] -translate-x-1/2 items-start gap-3 rounded-2xl border border-amber-500/40 bg-amber-500/10 p-4 text-sm text-amber-800 shadow-xl backdrop-blur-md dark:text-amber-100"
>
<ShieldIcon className="mt-0.5 h-5 w-5 shrink-0 text-amber-600 dark:text-amber-300" />
<div className="min-w-0 flex-1">
<p className="font-semibold">
{t('app:backup.prompt_title', { defaultValue: 'Erstelle jetzt ein Geräte-Backup' })}
</p>
<p className="mt-0.5 text-xs text-amber-700/90 dark:text-amber-200/90">
{t('app:backup.prompt_body', {
defaultValue:
'Ohne Backup verlierst du Zugriff auf alte Nachrichten, wenn Browser oder Gerät ihren Speicher verlieren. Dauert 10 Sekunden.',
})}
</p>
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
onClick={() => void openDialog()}
className="cursor-pointer rounded-md bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-amber-500"
>
{t('app:backup.prompt_create', { defaultValue: 'Jetzt erstellen' })}
</button>
<button
type="button"
onClick={() => dismiss(true)}
className="cursor-pointer rounded-md border border-amber-500/40 bg-transparent px-3 py-1.5 text-xs font-semibold text-amber-700 transition hover:bg-amber-500/15 dark:text-amber-200"
>
{t('app:backup.prompt_never', { defaultValue: 'Nicht mehr fragen' })}
</button>
</div>
</div>
<button
type="button"
onClick={() => dismiss(false)}
aria-label={t('app:backup.prompt_dismiss', { defaultValue: 'Später' })}
className="cursor-pointer text-amber-600/70 transition hover:text-amber-600 dark:text-amber-200/70 dark:hover:text-amber-200"
>
<XIcon className="h-4 w-4" />
</button>
</div>
{dialogOpen && profile?.userId && device?.id && privateKey && (
<BackupExportDialog
open={dialogOpen}
userId={profile.userId}
deviceId={device.id}
privateKey={privateKey}
onClose={closeDialog}
/>
)}
</>
);
}
@@ -1,6 +1,8 @@
import { useTranslation } from 'react-i18next';
import {
HeadphonesIcon,
HeadphonesOffIcon,
MicIcon,
MicOffIcon,
MonitorShareIcon,
@@ -14,9 +16,11 @@ interface Props {
muted: boolean;
sharing: boolean;
video: boolean;
deafened: boolean;
onToggleMute: () => void;
onToggleShare: () => void;
onToggleVideo?: () => void;
onToggleDeafen: () => void;
onHangup: () => void;
onOpenParticipants?: () => void;
/** Compact variant used inside the docked call (36px buttons). */
@@ -31,9 +35,11 @@ export function CallControls({
muted,
sharing,
video,
deafened,
onToggleMute,
onToggleShare,
onToggleVideo,
onToggleDeafen,
onHangup,
onOpenParticipants,
compact = false,
@@ -59,6 +65,24 @@ export function CallControls({
>
{muted ? <MicOffIcon className="h-5 w-5" /> : <MicIcon className="h-5 w-5" />}
</CallButton>
<CallButton
label={
deafened
? t('app:call.undeafen', { defaultValue: 'Ton wieder aktiv' })
: t('app:call.deafen', { defaultValue: 'Alle stumm' })
}
active={deafened}
activeTone="danger"
onClick={onToggleDeafen}
glass={glass}
className={btnSize}
>
{deafened ? (
<HeadphonesOffIcon className="h-5 w-5" />
) : (
<HeadphonesIcon className="h-5 w-5" />
)}
</CallButton>
{onToggleVideo && (
<CallButton
label={t('app:call.start_video', { defaultValue: 'Video' })}
@@ -1,4 +1,6 @@
import { CrownIcon, LockIcon, MicOffIcon, MonitorShareIcon } from './icons';
import { useEffect, useRef } from 'react';
import { CrownIcon, HeadphonesOffIcon, LockIcon, MicOffIcon } from './icons';
export type AvatarColorKey = 'violet' | 'amber' | 'rose' | 'teal';
@@ -41,14 +43,20 @@ export interface ParticipantTileProps {
avatarUrl: string | null;
me: boolean;
muted: boolean;
/** Local-only: true when THIS user has muted everyone else via the deafen
* toggle. Remote deafen state is not propagated, so only the own tile
* ever carries a truthy value. */
deafened: boolean;
speaking: boolean;
sharing: boolean;
video: boolean;
e2ee: boolean;
/** MediaStreamTrack for the participant's active camera, when `video` is
* true. When null the tile falls back to the avatar placeholder. */
videoTrack?: MediaStreamTrack | null;
size?: 'default' | 'small';
focused?: boolean;
onClick?: () => void;
onOpenScreenShare?: () => void;
onContextMenu?: (e: React.MouseEvent) => void;
}
export function CallParticipantTile(props: ParticipantTileProps) {
@@ -56,14 +64,14 @@ export function CallParticipantTile(props: ParticipantTileProps) {
displayName,
me,
muted,
deafened,
speaking,
sharing,
video,
e2ee,
size = 'default',
focused = false,
onClick,
onOpenScreenShare,
onContextMenu,
} = props;
const small = size === 'small';
@@ -76,6 +84,7 @@ export function CallParticipantTile(props: ParticipantTileProps) {
return (
<div
onClick={onClick}
onContextMenu={onContextMenu}
className={
'relative flex flex-col overflow-hidden rounded-[14px] border bg-surface-3 transition ' +
(onClick ? 'cursor-pointer ' : '') +
@@ -83,18 +92,21 @@ export function CallParticipantTile(props: ParticipantTileProps) {
(small ? ' min-w-[140px]' : '')
}
>
{sharing ? (
<ScreenshareStub
displayName={displayName}
small={small}
onOpen={onOpenScreenShare}
/>
) : video ? (
{video ? (
<VideoStub {...props} small={small} />
) : (
<AudioContent {...props} small={small} />
)}
{/* Speaking indicator visible regardless of content type (video or
audio). z-10 ensures it sits above the video element. */}
{speaking && (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-10 rounded-[14px] border-[3px] border-emerald-400 shadow-[inset_0_0_18px_rgba(34,197,94,0.55)]"
/>
)}
<div className="pointer-events-none absolute inset-x-2 bottom-2 flex items-center justify-between gap-2 rounded-lg glass-chip px-2.5 py-1.5">
<div className="flex min-w-0 items-center gap-1.5 text-xs font-semibold">
{me && <CrownIcon className="h-3 w-3 shrink-0 text-amber-300" />}
@@ -114,13 +126,21 @@ export function CallParticipantTile(props: ParticipantTileProps) {
</div>
<div className="flex shrink-0 items-center gap-1">
{muted && (
<span className="flex h-5 w-5 items-center justify-center rounded-md bg-rose-500/80 text-white">
<span
aria-label="Mikro stumm"
title="Mikro stumm"
className="flex h-5 w-5 items-center justify-center rounded-md bg-rose-500/80 text-white"
>
<MicOffIcon className="h-3 w-3" />
</span>
)}
{sharing && (
<span className="flex h-5 w-5 items-center justify-center rounded-md bg-emerald-500/80 text-white">
<MonitorShareIcon className="h-3 w-3" />
{deafened && (
<span
aria-label="Ton aus"
title="Ton aus"
className="flex h-5 w-5 items-center justify-center rounded-md bg-rose-500/80 text-white"
>
<HeadphonesOffIcon className="h-3 w-3" />
</span>
)}
</div>
@@ -179,11 +199,45 @@ function VideoStub({
userId,
displayName,
avatarUrl,
videoTrack,
me,
small,
}: ParticipantTileProps & { small: boolean }) {
// Video capture playback is out of scope for this UI iteration — show the
// audio-avatar gradient background as a placeholder so the layout is stable
// when a participant enables video.
const videoRef = useRef<HTMLVideoElement | null>(null);
useEffect(() => {
const el = videoRef.current;
if (!el || !videoTrack) return;
el.srcObject = new MediaStream([videoTrack]);
return () => {
if (el.srcObject) {
(el.srcObject as MediaStream).getTracks().forEach((t) => {
// Don't stop the live track — other consumers may still need it.
// Just detach from this element.
void t;
});
el.srcObject = null;
}
};
}, [videoTrack]);
if (videoTrack) {
return (
<div className="relative flex min-h-0 flex-1 items-center justify-center bg-black">
<video
ref={videoRef}
autoPlay
playsInline
muted
className={
'h-full w-full object-cover ' +
(me ? 'scale-x-[-1]' : '') /* mirror local preview */
}
/>
</div>
);
}
// Camera flag true but no track yet (publishing / subscribing race).
const key = colorKeyFor(userId);
const colors = AVATAR_COLORS[key];
const letter = displayName.trim().charAt(0).toUpperCase() || '?';
@@ -206,49 +260,3 @@ function VideoStub({
);
}
interface ScreenshareStubProps {
displayName: string;
small: boolean;
onOpen?: (() => void) | undefined;
}
// Fake browser window placeholder — click to open the real <video> viewer.
// Matches the design spec's "screenshare-stub" look.
function ScreenshareStub({ displayName, small, onOpen }: ScreenshareStubProps) {
return (
<button
type="button"
onClick={
onOpen
? (e) => {
e.stopPropagation();
onOpen();
}
: undefined
}
aria-label={`${displayName} teilt Bildschirm`}
className="relative flex min-h-0 flex-1 cursor-pointer items-center justify-center bg-ink-900 p-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
>
<div className="h-[85%] w-[90%] overflow-hidden rounded-lg border border-white/10 bg-ink-700">
<div className="flex h-[20px] items-center gap-1 bg-ink-600 px-2">
<span className="h-1.5 w-1.5 rounded-full bg-ink-500" />
<span className="h-1.5 w-1.5 rounded-full bg-ink-500" />
<span className="h-1.5 w-1.5 rounded-full bg-ink-500" />
</div>
<div className={'flex flex-col gap-2 ' + (small ? 'gap-[3px] p-1.5' : 'p-3.5')}>
<div className={'w-[60%] rounded ' + (small ? 'h-[3px]' : 'h-1.5') + ' bg-ink-500'} />
<div className={'w-[80%] rounded ' + (small ? 'h-[3px]' : 'h-1.5') + ' bg-ink-500'} />
<div className={'w-[40%] rounded ' + (small ? 'h-[3px]' : 'h-1.5') + ' bg-ink-500'} />
<div className={'my-1 rounded ' + (small ? 'h-[14px]' : 'h-10') + ' bg-accent/30'} />
<div className={'w-[70%] rounded ' + (small ? 'h-[3px]' : 'h-1.5') + ' bg-ink-500'} />
</div>
</div>
{!small && (
<div className="absolute left-3 top-3 flex items-center gap-1.5 glass-chip rounded-lg px-2.5 py-1 text-[10px] font-medium">
<MonitorShareIcon className="h-3 w-3" />
<span>{displayName} teilt Bildschirm</span>
</div>
)}
</button>
);
}
@@ -28,9 +28,10 @@ interface Props {
conversation: ConversationSummary | null;
peerPresence: PresenceState | null;
onInfoClick?: () => void;
onSearchClick?: () => void;
}
export function ConversationHeader({ conversation, peerPresence, onInfoClick }: Props) {
export function ConversationHeader({ conversation, peerPresence, onInfoClick, onSearchClick }: Props) {
if (!conversation) {
return <header className="h-[57px] border-b border-line px-6 py-3" aria-busy="true" />;
}
@@ -41,6 +42,7 @@ export function ConversationHeader({ conversation, peerPresence, onInfoClick }:
conversation={conversation}
peerPresence={peerPresence}
{...(onInfoClick ? { onInfoClick } : {})}
{...(onSearchClick ? { onSearchClick } : {})}
/>
<ActiveCallBanner conversationId={conversation.id} />
</>
@@ -51,9 +53,10 @@ interface HeaderBarProps {
conversation: ConversationSummary;
peerPresence: PresenceState | null;
onInfoClick?: () => void;
onSearchClick?: () => void;
}
function HeaderBar({ conversation, peerPresence, onInfoClick }: HeaderBarProps) {
function HeaderBar({ conversation, peerPresence, onInfoClick, onSearchClick }: HeaderBarProps) {
const { t } = useTranslation(['app']);
const isDm = conversation.type === 'dm';
@@ -108,7 +111,11 @@ function HeaderBar({ conversation, peerPresence, onInfoClick }: HeaderBarProps)
</p>
</div>
<HeaderActionButton label={t('app:chats.search', { defaultValue: 'Suche' })} icon={SearchIcon} />
<HeaderActionButton
label={t('app:chats.search', { defaultValue: 'Suche' })}
icon={SearchIcon}
{...(onSearchClick ? { onClick: onSearchClick } : {})}
/>
<CallHeaderButton conversationId={conversation.id} kind="audio" />
<CallHeaderButton conversationId={conversation.id} kind="video" />
{!isDm && onInfoClick && (
@@ -203,17 +210,14 @@ function ActiveCallBanner({ conversationId }: { conversationId: string }) {
const justLeft = state.kind === 'idle' && lastCallConversationId === conversationId;
// Once presence confirms the room is empty, drop the "just left" hint so the
// banner hides cleanly instead of sticking forever.
// banner hides cleanly instead of sticking forever. Grace window handles the
// brief gap between hangup and presence re-sync so we don't flicker.
useEffect(() => {
if (!justLeft) return;
if (active.length === 0) return;
if (othersIn.length === 0) {
// Active reports only us (or something stale) — wait, then dismiss.
const id = window.setTimeout(() => dismissLastCall(), 3000);
return () => window.clearTimeout(id);
}
return undefined;
}, [justLeft, active.length, othersIn.length, dismissLastCall]);
if (othersIn.length > 0) return; // still live — keep banner
const id = window.setTimeout(() => dismissLastCall(), 3000);
return () => window.clearTimeout(id);
}, [justLeft, othersIn.length, dismissLastCall]);
if (iAmIn) return null;
if (othersIn.length === 0 && !justLeft) return null;
@@ -0,0 +1,264 @@
import {
muteDurationToIso,
setConversationArchived,
setConversationMutedUntil,
} from '@chat-app/shared/chat';
import { forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { supabase } from '../lib/supabase';
import { ArchiveIcon, BellIcon, BellOffIcon, MoreVerticalIcon } from './icons';
interface Props {
conversationId: string;
archived: boolean;
mutedUntil: string | null;
}
interface MuteOption {
key: string;
labelKey: string;
labelDefault: string;
minutes: number | null;
}
// Muted-forever sentinel ≈ 100 years. UI treats any future timestamp as muted
// until that moment; 100y is indistinguishable from "forever" at the UX level
// without requiring a dedicated `bool muted_forever` column.
const FOREVER_MINUTES = 100 * 365 * 24 * 60;
const MUTE_OPTIONS: MuteOption[] = [
{ key: '1h', labelKey: 'app:chats.mute_1h', labelDefault: '1 Stunde', minutes: 60 },
{ key: '8h', labelKey: 'app:chats.mute_8h', labelDefault: '8 Stunden', minutes: 8 * 60 },
{ key: '24h', labelKey: 'app:chats.mute_24h', labelDefault: '24 Stunden', minutes: 24 * 60 },
{ key: '1w', labelKey: 'app:chats.mute_1w', labelDefault: '1 Woche', minutes: 7 * 24 * 60 },
{
key: 'forever',
labelKey: 'app:chats.mute_forever',
labelDefault: 'Bis auf Weiteres',
minutes: FOREVER_MINUTES,
},
];
interface MenuPos {
top: number;
left: number;
}
// Per-conversation row context-menu. Renders via portal so the submenu can
// escape the sidebar's `overflow-y-auto` clipping context. Position is
// computed from the trigger's bounding rect — menu anchors right-aligned
// under the trigger so it doesn't push off-screen on narrow windows.
export function ConversationRowMenu({ conversationId, archived, mutedUntil }: Props) {
const { t } = useTranslation(['app']);
const [open, setOpen] = useState(false);
const [submenuOpen, setSubmenuOpen] = useState<'mute' | null>(null);
const [menuPos, setMenuPos] = useState<MenuPos | null>(null);
const [submenuPos, setSubmenuPos] = useState<MenuPos | null>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const muteItemRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!open) return;
function onDocClick(e: MouseEvent) {
const target = e.target as Node;
if (triggerRef.current?.contains(target)) return;
if (menuRef.current?.contains(target)) return;
setOpen(false);
setSubmenuOpen(null);
}
function onEsc(e: KeyboardEvent) {
if (e.key === 'Escape') {
setOpen(false);
setSubmenuOpen(null);
}
}
document.addEventListener('mousedown', onDocClick);
document.addEventListener('keydown', onEsc);
return () => {
document.removeEventListener('mousedown', onDocClick);
document.removeEventListener('keydown', onEsc);
};
}, [open]);
useEffect(() => {
if (!open) {
setMenuPos(null);
setSubmenuPos(null);
return;
}
const rect = triggerRef.current?.getBoundingClientRect();
if (!rect) return;
// Anchor: right edge aligns with trigger's right edge, menu hangs below.
const menuWidth = 208;
setMenuPos({
top: rect.bottom + 4,
left: Math.max(8, rect.right - menuWidth),
});
}, [open]);
useEffect(() => {
if (submenuOpen !== 'mute') {
setSubmenuPos(null);
return;
}
const rect = muteItemRef.current?.getBoundingClientRect();
if (!rect) return;
const submenuWidth = 192;
const viewportWidth = window.innerWidth;
// Prefer right of the item. Flip to left when it would overflow viewport.
const wantLeft = rect.right + 4;
const flip = wantLeft + submenuWidth > viewportWidth - 8;
setSubmenuPos({
top: rect.top,
left: flip ? rect.left - submenuWidth - 4 : wantLeft,
});
}, [submenuOpen]);
const isMuted =
mutedUntil !== null && new Date(mutedUntil).getTime() > Date.now();
const handleArchive = useCallback(
async (next: boolean) => {
setOpen(false);
try {
await setConversationArchived(supabase, conversationId, next);
} catch (err: unknown) {
console.error('archive toggle failed', err);
}
},
[conversationId],
);
const handleMute = useCallback(
async (minutes: number | null) => {
setOpen(false);
setSubmenuOpen(null);
try {
await setConversationMutedUntil(
supabase,
conversationId,
muteDurationToIso(minutes),
);
} catch (err: unknown) {
console.error('mute toggle failed', err);
}
},
[conversationId],
);
return (
<>
<button
ref={triggerRef}
type="button"
aria-label={t('app:chats.row_menu', { defaultValue: 'Aktionen' })}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setOpen((v) => !v);
}}
onMouseDown={(e) => e.stopPropagation()}
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted opacity-0 transition group-hover:opacity-100 hover:bg-surface-3 hover:text-fg focus:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
>
<MoreVerticalIcon className="h-4 w-4" />
</button>
{open &&
menuPos &&
createPortal(
<div
ref={menuRef}
role="menu"
style={{ top: menuPos.top, left: menuPos.left }}
className="fixed z-50 w-52 rounded-lg border border-line bg-surface-3 p-1 shadow-xl"
>
<MenuItem
icon={<ArchiveIcon className="h-4 w-4" />}
label={
archived
? t('app:chats.unarchive', { defaultValue: 'Entarchivieren' })
: t('app:chats.archive', { defaultValue: 'Archivieren' })
}
onClick={() => void handleArchive(!archived)}
/>
<MenuItem
ref={muteItemRef}
icon={
isMuted ? (
<BellOffIcon className="h-4 w-4" />
) : (
<BellIcon className="h-4 w-4" />
)
}
label={
isMuted
? t('app:chats.unmute', { defaultValue: 'Stummschaltung aufheben' })
: t('app:chats.mute', { defaultValue: 'Stummschalten' })
}
onClick={() => {
if (isMuted) void handleMute(null);
else setSubmenuOpen((v) => (v === 'mute' ? null : 'mute'));
}}
hasSubmenu={!isMuted}
/>
</div>,
document.body,
)}
{open &&
submenuOpen === 'mute' &&
submenuPos &&
createPortal(
<div
role="menu"
style={{ top: submenuPos.top, left: submenuPos.left }}
className="fixed z-50 w-48 rounded-lg border border-line bg-surface-3 p-1 shadow-xl"
>
{MUTE_OPTIONS.map((opt) => (
<MenuItem
key={opt.key}
label={t(opt.labelKey, { defaultValue: opt.labelDefault })}
onClick={() => void handleMute(opt.minutes)}
/>
))}
</div>,
document.body,
)}
</>
);
}
interface MenuItemProps {
icon?: React.ReactNode;
label: string;
onClick: () => void;
hasSubmenu?: boolean;
}
// React 18 requires forwardRef for function components to receive refs —
// without it the `ref` prop is stripped before reaching the component and
// measurement-dependent submenus never position.
const MenuItem = forwardRef<HTMLButtonElement, MenuItemProps>(
({ icon, label, onClick, hasSubmenu }, ref) => (
<button
ref={ref}
type="button"
role="menuitem"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClick();
}}
onMouseDown={(e) => e.stopPropagation()}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-1.5 text-left text-sm text-fg transition hover:bg-surface-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
>
{icon && <span className="shrink-0 text-fg-muted">{icon}</span>}
<span className="min-w-0 flex-1 truncate">{label}</span>
{hasSubmenu && <span className="shrink-0 text-xs text-fg-muted"></span>}
</button>
),
);
MenuItem.displayName = 'MenuItem';
@@ -0,0 +1,190 @@
import {
type DeviceRecord,
restoreDeviceFromServerRecord,
} from '@chat-app/shared/auth';
import { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
decodePrivateKeyFromBackup,
importDeviceBackup,
normalizeRecoveryCode,
} from '../lib/deviceBackup';
import { devLocalSecretStore } from '../lib/secretStore';
import { supabase } from '../lib/supabase';
import { writeLocalDeviceId } from '../lib/device';
import { AlertIcon, ArrowRightIcon, LockIcon, ShieldIcon, SpinnerIcon } from './icons';
interface Props {
userId: string;
onRestored: (device: DeviceRecord) => void;
}
// Restores a device from a user-provided backup string. The backup embeds
// userId + deviceId + X25519 private key; we verify userId matches the current
// session, confirm the device row still exists server-side, and then re-seed
// the local vault + cached deviceId so the app treats this install as the
// original device (conv-key bundles stay valid, no "awaiting" state).
export function DeviceRestore({ userId, onRestored }: Props) {
const { t } = useTranslation(['app', 'errors']);
const [backup, setBackup] = useState('');
const [passphrase, setPassphrase] = useState('');
const [mode, setMode] = useState<'passphrase' | 'recovery'>('passphrase');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = useCallback(
async (e: React.FormEvent) => {
e.preventDefault();
if (!backup.trim() || passphrase.length < 1 || busy) return;
setBusy(true);
setError(null);
let privateKey: Uint8Array | null = null;
try {
const secret =
mode === 'recovery' ? normalizeRecoveryCode(passphrase) : passphrase;
const payload = await importDeviceBackup(backup.trim(), secret);
privateKey = decodePrivateKeyFromBackup(payload);
const device = await restoreDeviceFromServerRecord({
client: supabase,
secretStore: devLocalSecretStore,
userId: payload.userId,
deviceId: payload.deviceId,
privateKey,
});
// Cache deviceId locally so findExistingDevice picks it up on next load.
writeLocalDeviceId(userId, device.id);
onRestored(device);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : String(err));
} finally {
if (privateKey) {
for (let i = 0; i < privateKey.length; i++) privateKey[i] = 0;
}
setBusy(false);
}
},
[backup, passphrase, mode, userId, onRestored, busy],
);
return (
<form
onSubmit={handleSubmit}
className="w-full max-w-md animate-slide-up rounded-2xl border border-white/10 bg-ink-900/70 p-7 shadow-glow backdrop-blur-xl sm:p-8"
>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-lg bg-emerald-500/20 ring-1 ring-emerald-400/30">
<ShieldIcon className="h-5 w-5 text-emerald-300" />
</div>
<div>
<h2 className="font-display text-lg font-semibold text-white">
{t('app:backup.restore_title', { defaultValue: 'Backup wiederherstellen' })}
</h2>
<p className="text-xs text-neutral-400">
{t('app:backup.restore_subtitle', {
defaultValue: 'Bringe einen zuvor erstellten Backup-String + Passphrase mit.',
})}
</p>
</div>
</div>
<div className="mt-6 space-y-3">
<div className="space-y-1">
<label className="block text-xs font-medium uppercase tracking-wide text-neutral-400">
{t('app:backup.backup_string', { defaultValue: 'Backup-String' })}
</label>
<textarea
required
rows={5}
value={backup}
onChange={(e) => setBackup(e.target.value)}
placeholder="chatapp-backup-v1…"
className="w-full resize-none rounded-lg border border-white/10 bg-ink-800 px-3 py-2.5 font-mono text-[11px] leading-relaxed text-white placeholder-neutral-500 transition focus:border-brand-400 focus:outline-none focus:ring-2 focus:ring-brand-500/40"
/>
</div>
<div className="space-y-1">
<div className="flex items-center justify-between">
<label className="block text-xs font-medium uppercase tracking-wide text-neutral-400">
{mode === 'passphrase' ? 'Passphrase' : 'Recovery-Code'}
</label>
<button
type="button"
onClick={() => {
setMode((m) => (m === 'passphrase' ? 'recovery' : 'passphrase'));
setPassphrase('');
setError(null);
}}
className="cursor-pointer text-[11px] font-semibold text-brand-300 hover:underline"
>
{mode === 'passphrase'
? 'Passphrase vergessen? Recovery-Code nutzen'
: 'Stattdessen Passphrase eingeben'}
</button>
</div>
<input
type={mode === 'passphrase' ? 'password' : 'text'}
required
value={passphrase}
onChange={(e) => setPassphrase(e.target.value)}
placeholder={mode === 'recovery' ? 'XXXXXX-XXXXXX-XXXXXX-XXXXXX' : ''}
spellCheck={false}
autoComplete={mode === 'recovery' ? 'off' : 'current-password'}
className={
'w-full rounded-lg border border-white/10 bg-ink-800 px-3 py-2.5 text-sm text-white placeholder-neutral-500 transition focus:border-brand-400 focus:outline-none focus:ring-2 focus:ring-brand-500/40 ' +
(mode === 'recovery' ? 'font-mono tracking-widest' : '')
}
/>
{mode === 'recovery' && (
<p className="text-[11px] text-neutral-500">
Stattdessen den Recovery-Backup-String oben einfügen.
</p>
)}
</div>
</div>
<div className="mt-5 rounded-lg border border-brand-500/20 bg-brand-500/10 p-3 text-xs text-brand-100">
<div className="flex items-start gap-2">
<LockIcon className="mt-0.5 h-4 w-4 shrink-0 text-brand-300" />
<span className="min-w-0 flex-1 break-words">
{t('app:backup.restore_hint', {
defaultValue:
'Nach Wiederherstellung übernimmt dieses Gerät die alte Identität — existierende Nachrichten sind wieder entschlüsselbar.',
})}
</span>
</div>
</div>
<button
type="submit"
disabled={busy || backup.trim().length === 0 || passphrase.length === 0}
aria-busy={busy}
className="group mt-6 inline-flex w-full cursor-pointer items-center justify-center gap-2 rounded-lg bg-gradient-to-br from-emerald-400 to-emerald-600 px-4 py-3 text-sm font-semibold text-white shadow-glow transition hover:from-emerald-300 hover:to-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-400/60 focus:ring-offset-2 focus:ring-offset-ink-900 disabled:cursor-not-allowed disabled:opacity-60"
>
{busy ? (
<>
<SpinnerIcon className="h-4 w-4" />
<span>{t('app:backup.restoring', { defaultValue: 'Wiederherstellen…' })}</span>
</>
) : (
<>
<span>{t('app:backup.restore_cta', { defaultValue: 'Gerät wiederherstellen' })}</span>
<ArrowRightIcon className="h-4 w-4 transition group-hover:translate-x-0.5" />
</>
)}
</button>
{error && (
<div
role="alert"
className="mt-4 flex items-start gap-3 rounded-lg border border-rose-500/20 bg-rose-500/10 p-3 text-sm text-rose-100"
>
<AlertIcon className="mt-0.5 h-5 w-5 shrink-0 text-rose-400" />
<p className="min-w-0 flex-1 break-words">{error}</p>
</div>
)}
</form>
);
}
@@ -0,0 +1,133 @@
import { Component, type ErrorInfo, Fragment, type ReactNode } from 'react';
import { SpinnerIcon } from './icons';
interface Props {
children: ReactNode;
/**
* Optional scope label shown in logs / devtools. Defaults to `root` — set
* per boundary (e.g. `route`, `conversation`) so multiple boundaries can be
* distinguished at a glance.
*/
scope?: string;
/**
* If the retry count exceeds this, the boundary stops auto-retrying and
* shows a more helpful message (still without a button — Discord-style,
* the app keeps trying but hints the user to hold on or check network).
*/
maxAutoRetries?: number;
}
interface State {
error: Error | null;
retryKey: number;
attempt: number;
}
const RETRY_DELAYS_MS = [2000, 4000, 8000, 15000, 30000];
// Discord-style error boundary.
// - Catches render-time errors in its subtree.
// - Shows a centred spinner + status text. Never renders a manual "Reload"
// button; the boundary remounts its children on an exponential-backoff
// schedule so the UI self-heals once the underlying issue clears (typical
// causes: a realtime reconnect, a transient network blip, or a race that
// only fires once).
// - Escalates the label after each failed retry so the user sees that the
// app is trying, rather than silent infinite spinning.
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null, retryKey: 0, attempt: 0 };
private retryTimer: number | null = null;
static getDerivedStateFromError(error: Error): Partial<State> {
return { error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
const scope = this.props.scope ?? 'root';
// We explicitly log here — the boundary itself swallows the error from
// React, so without this the failure would be invisible in production.
console.error('[ErrorBoundary:' + scope + '] caught render error', error, info);
}
override componentDidUpdate(_prev: Props, prevState: State): void {
if (this.state.error && !prevState.error) {
this.scheduleRetry();
}
}
override componentWillUnmount(): void {
if (this.retryTimer !== null) {
window.clearTimeout(this.retryTimer);
this.retryTimer = null;
}
}
private scheduleRetry(): void {
if (this.retryTimer !== null) return;
const attempt = this.state.attempt;
const delay =
RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)] ??
RETRY_DELAYS_MS[RETRY_DELAYS_MS.length - 1] ??
30000;
this.retryTimer = window.setTimeout(() => {
this.retryTimer = null;
this.setState((prev) => ({
error: null,
retryKey: prev.retryKey + 1,
attempt: prev.attempt + 1,
}));
}, delay);
}
override render(): ReactNode {
if (this.state.error) {
const max = this.props.maxAutoRetries ?? RETRY_DELAYS_MS.length;
const escalated = this.state.attempt >= max;
return <RetryingScreen escalated={escalated} attempt={this.state.attempt} />;
}
// `retryKey` forces a remount of the subtree so hooks re-run cleanly after
// an error (otherwise stale state from the crashed tree can immediately
// re-throw). Use a keyed Fragment so the boundary doesn't inject an extra
// wrapper div — that would break `flex h-full` chains (e.g. AppShell →
// Outlet → page column).
return <Fragment key={this.state.retryKey}>{this.props.children}</Fragment>;
}
}
function RetryingScreen({ escalated, attempt }: { escalated: boolean; attempt: number }) {
const primary = escalated
? 'Verbindungsprobleme…'
: attempt === 0
? 'Einen Moment bitte'
: 'Versuche erneut zu laden…';
const secondary = escalated
? 'Prüfe deine Internetverbindung. Wir versuchen es weiter.'
: 'Die App lädt sich gleich selbst neu.';
return (
<div
role="status"
aria-live="polite"
className="flex min-h-screen w-full items-center justify-center bg-surface-3 px-6"
>
<div className="flex flex-col items-center gap-4 text-center">
<div className="relative flex h-16 w-16 items-center justify-center">
<span
aria-hidden="true"
className="absolute inset-0 rounded-full border-2 border-accent/20"
/>
<span
aria-hidden="true"
className="absolute inset-0 rounded-full border-2 border-accent border-r-transparent border-b-transparent animate-spin"
/>
<SpinnerIcon className="hidden" />
</div>
<div className="max-w-sm space-y-1.5">
<p className="font-display text-lg font-semibold text-fg">{primary}</p>
<p className="text-sm text-fg-muted">{secondary}</p>
</div>
</div>
</div>
);
}
@@ -0,0 +1,315 @@
import { loadDevicePrivateKey } from '@chat-app/shared/auth';
import {
type AttachmentHandle,
type DecryptedMessage,
downloadAndDecryptAttachment,
encryptAndUploadAttachment,
insertAttachmentRow,
parseMessagePayload,
sendEncryptedMessage,
} from '@chat-app/shared/chat';
import { extractErrorCode } from '@chat-app/shared/i18n';
import { bytesToPgHex } from '@chat-app/shared/supabase';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
import { useConversationsContext } from '../context/ConversationsContext';
import { devLocalSecretStore } from '../lib/secretStore';
import { supabase } from '../lib/supabase';
import { Avatar } from './Avatar';
import { ForwardIcon, SpinnerIcon, UsersIcon, XIcon } from './icons';
interface Props {
open: boolean;
message: DecryptedMessage | null;
currentConversationId: string | null;
onClose: () => void;
}
// Forwards a message's plaintext to one or more conversations. Attachments are
// NOT carried over yet (would require re-uploading + re-encrypting under the
// new conversation key); only the text payload is forwarded for now and the
// preview hints at the dropped attachment.
export function ForwardDialog({ open, message, currentConversationId, onClose }: Props) {
const { t } = useTranslation(['app', 'errors']);
const { session, device } = useAuth();
const { conversations } = useConversationsContext();
const [selected, setSelected] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState(false);
useEffect(() => {
if (!open) return;
setSelected(new Set());
setError(null);
setDone(false);
}, [open, message?.id]);
const targets = useMemo(() => {
return conversations
.filter((c) => c.id !== currentConversationId && c.acceptedByMe)
.sort((a, b) => {
const ta = a.lastMessageAt ?? a.createdAt;
const tb = b.lastMessageAt ?? b.createdAt;
return tb.localeCompare(ta);
});
}, [conversations, currentConversationId]);
const preview = useMemo(() => {
if (!message?.plaintext) return '';
const p = parseMessagePayload(message.plaintext);
if (p.kind !== 'text') return '';
return p.text.length > 140 ? p.text.slice(0, 140) + '…' : p.text;
}, [message]);
const sourceAttachments = useMemo<AttachmentHandle[]>(() => {
if (!message?.plaintext) return [];
const p = parseMessagePayload(message.plaintext);
return p.kind === 'text' ? p.attachments : [];
}, [message]);
if (!open || !message) return null;
function toggle(id: string) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
async function handleSend() {
if (!session?.user.id || !device?.id || !message) return;
if (selected.size === 0) return;
setBusy(true);
setError(null);
try {
const priv = await loadDevicePrivateKey(devLocalSecretStore, session.user.id, device.id);
if (!priv) throw new Error('private key not loaded');
const hasAttachments = sourceAttachments.length > 0;
const text = preview || (hasAttachments ? '' : '');
if (!text && !hasAttachments) throw new Error('nothing to forward');
// Download+decrypt source attachments ONCE (same plaintext goes to every
// target). For each target conv we re-encrypt under fresh per-attachment
// keys and re-upload under the target conv's storage folder — source and
// target conv-keys differ, so the bytes must actually move.
const decryptedBlobs: { mime: string; size: number; width?: number; height?: number; blob: Blob }[] =
[];
for (const h of sourceAttachments) {
const blob = await downloadAndDecryptAttachment({ client: supabase, handle: h });
const entry: {
mime: string;
size: number;
width?: number;
height?: number;
blob: Blob;
} = { mime: h.mimeType, size: h.sizeBytes, blob };
if (h.width !== undefined) entry.width = h.width;
if (h.height !== undefined) entry.height = h.height;
decryptedBlobs.push(entry);
}
for (const convId of selected) {
const newHandles: AttachmentHandle[] = [];
const blobNonceHex = new Map<string, string>();
for (const src of decryptedBlobs) {
const res = await encryptAndUploadAttachment({
client: supabase,
conversationId: convId,
file: src.blob,
mimeType: src.mime,
sizeBytes: src.size,
...(src.width !== undefined ? { width: src.width } : {}),
...(src.height !== undefined ? { height: src.height } : {}),
});
newHandles.push(res.handle);
blobNonceHex.set(res.handle.id, bytesToPgHex(res.nonce));
}
const msg = await sendEncryptedMessage({
client: supabase,
conversationId: convId,
plaintext: text,
senderUserId: session.user.id,
senderDeviceId: device.id,
senderPrivateKey: priv,
...(newHandles.length > 0 ? { attachmentHandles: newHandles } : {}),
});
for (const h of newHandles) {
const bn = blobNonceHex.get(h.id) ?? '\\x';
await insertAttachmentRow(supabase, msg.id, h, bn);
}
}
setDone(true);
window.setTimeout(onClose, 700);
} catch (err: unknown) {
const code = extractErrorCode(err);
setError(
code
? t('errors:' + code, { defaultValue: t('errors:generic') })
: err instanceof Error
? err.message
: t('errors:generic'),
);
} finally {
setBusy(false);
}
}
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:chats.forward', { defaultValue: 'Weiterleiten' })}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={onClose}
>
<div
onClick={(e) => e.stopPropagation()}
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-line bg-surface-3 shadow-xl"
>
<header className="flex items-center justify-between border-b border-line px-5 py-3">
<div className="flex items-center gap-2">
<ForwardIcon className="h-4 w-4 text-accent" />
<h3 className="font-display text-sm font-semibold text-fg">
{t('app:chats.forward', { defaultValue: 'Weiterleiten' })}
</h3>
</div>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-fg-muted transition hover:bg-surface-2 hover:text-fg"
>
<XIcon className="h-4 w-4" />
</button>
</header>
<div className="border-b border-line bg-surface-2 px-5 py-3">
<p className="text-[10px] font-semibold uppercase tracking-wider text-fg-muted">
{t('app:chats.forward_preview', { defaultValue: 'Vorschau' })}
</p>
<p className="mt-1 line-clamp-3 break-words text-sm text-fg">
{preview || (sourceAttachments.length > 0 ? '📎' : '…')}
</p>
{sourceAttachments.length > 0 && (
<p className="mt-1 text-[11px] text-fg-muted">
📎{' '}
{t('app:chats.forward_attachments_count', {
count: sourceAttachments.length,
defaultValue: '{{count}} Anhang wird mit weitergeleitet',
})}
</p>
)}
</div>
<div className="flex-1 overflow-y-auto p-2">
{targets.length === 0 ? (
<p className="px-4 py-6 text-center text-sm text-fg-muted">
{t('app:chats.forward_no_targets', {
defaultValue: 'Keine anderen Unterhaltungen verfügbar.',
})}
</p>
) : (
<ul className="space-y-0.5">
{targets.map((c) => {
const isGroup = c.type === 'group';
const title = isGroup ? c.name ?? '?' : c.peer?.displayName ?? '?';
const avatarUrl = isGroup ? c.avatarUrl ?? null : c.peer?.avatarUrl ?? null;
const checked = selected.has(c.id);
return (
<li key={c.id}>
<button
type="button"
onClick={() => toggle(c.id)}
className={
'flex w-full cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-left transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
(checked ? 'bg-accent/15' : 'hover:bg-surface-2')
}
>
{avatarUrl ? (
<Avatar
url={avatarUrl}
displayName={title}
className="h-9 w-9 text-sm"
/>
) : isGroup ? (
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-accent/20 text-accent">
<UsersIcon className="h-4 w-4" />
</div>
) : (
<Avatar
url={null}
displayName={title}
className="h-9 w-9 text-sm"
/>
)}
<span className="min-w-0 flex-1 truncate text-sm font-medium text-fg">
{title}
</span>
<span
aria-hidden="true"
className={
'flex h-5 w-5 shrink-0 items-center justify-center rounded border ' +
(checked ? 'border-accent bg-accent text-accent-fg' : 'border-line bg-surface-2')
}
>
{checked && (
<svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
)}
</span>
</button>
</li>
);
})}
</ul>
)}
</div>
{error && (
<p
role="alert"
className="border-t border-rose-500/30 bg-rose-500/10 px-5 py-2 text-xs text-rose-700 dark:text-rose-200"
>
{error}
</p>
)}
<footer className="flex items-center justify-end gap-2 border-t border-line bg-surface-2 px-5 py-3">
<button
type="button"
onClick={onClose}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-2 text-sm text-fg transition hover:bg-surface-2"
>
{t('app:friends.action_cancel', { defaultValue: 'Abbrechen' })}
</button>
<button
type="button"
disabled={busy || selected.size === 0 || done}
onClick={() => void handleSend()}
className="inline-flex cursor-pointer items-center gap-1.5 rounded-md bg-accent px-3 py-2 text-sm font-semibold text-accent-fg transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60"
>
{busy && <SpinnerIcon className="h-4 w-4" />}
<span>
{done
? t('app:chats.forward_done', { defaultValue: 'Gesendet' })
: t('app:chats.forward_send', {
count: selected.size,
defaultValue: 'An {{count}} senden',
})}
</span>
</button>
</footer>
</div>
</div>
);
}
+479 -174
View File
@@ -1,5 +1,7 @@
import type { ConversationSummary } from '@chat-app/shared/chat';
import { useEffect, useState } from 'react';
import type { RemoteParticipant, Room } from 'livekit-client';
import { Track } from 'livekit-client';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../context/AuthContext';
@@ -13,6 +15,8 @@ import { useActiveSpeakers } from '../lib/useActiveSpeakers';
import { CallControls } from './CallControls';
import { CallParticipantTile } from './CallParticipantTile';
import { FocusIcon, GridIcon, LockIcon, MaximizeIcon, SpinnerIcon, UsersIcon } from './icons';
import { ParticipantVolumeMenu } from './ParticipantVolumeMenu';
import { ScreenShareDialog } from './ScreenShareDialog';
import { ScreenShareViewer } from './ScreenShareViewer';
// Discord-style in-call dock rendered above the message list. Renders three
@@ -24,13 +28,24 @@ interface Props {
}
interface Tile {
// `user` = person with avatar/video/mute info. Speaking ring applies here.
// `screen` = a separate screen-share window from a user. No speaking
// indicator, no mute, no avatar — just the stream.
kind: 'user' | 'screen';
// Stable id used for focus tracking + React keys. `user:${userId}` or
// `screen:${userId}`.
id: string;
userId: string;
displayName: string;
avatarUrl: string | null;
self: boolean;
muted: boolean;
deafened: boolean;
video: boolean;
videoTrack: MediaStreamTrack | null;
// True iff this is the current user's own screen-share tile.
sharing: boolean;
// True iff this is a remote user's screen-share tile.
remoteSharing: boolean;
}
@@ -43,11 +58,17 @@ export function InCallPanel({ conversation }: Props) {
isMuted,
isE2EEActive,
isScreenSharing,
isCameraEnabled,
isDeafened,
remoteDeafen,
remoteScreenShares,
callMode,
focusedId,
toggleMute,
toggleScreenShare,
startScreenShare,
stopScreenShare,
toggleCamera,
toggleDeafen,
hangup,
setCallMode,
setFocusedId,
@@ -55,6 +76,22 @@ export function InCallPanel({ conversation }: Props) {
const { session } = useAuth();
const myId = session?.user.id ?? null;
const activeSpeakers = useActiveSpeakers(room);
const [shareDialogOpen, setShareDialogOpen] = useState(false);
const [volumeMenu, setVolumeMenu] = useState<
{ userId: string; displayName: string; x: number; y: number } | null
>(null);
const openVolumeMenu = (tile: Tile, e: React.MouseEvent) => {
if (tile.self) return;
if (tile.kind !== 'user') return;
e.preventDefault();
setVolumeMenu({
userId: tile.userId,
displayName: tile.displayName,
x: e.clientX,
y: e.clientY,
});
};
const active =
(state.kind === 'connected' ||
@@ -66,9 +103,13 @@ export function InCallPanel({ conversation }: Props) {
const tiles = buildTiles({
conversation,
myId,
remoteIdentities: remoteParticipants.map((p) => p.identity),
room,
remoteParticipants,
isMuted,
isDeafened,
remoteDeafen,
isScreenSharing,
isCameraEnabled,
remoteSharerIds: new Set(remoteScreenShares.map((s) => s.participantId)),
});
@@ -86,17 +127,29 @@ export function InCallPanel({ conversation }: Props) {
? t('app:call.waiting_for_peers', { defaultValue: 'Warte auf andere…' })
: t('app:call.connected');
const sharingTile = tiles.find((p) => p.sharing);
const effectiveFocusedId = focusedId ?? sharingTile?.userId ?? tiles[0]?.userId ?? null;
const speaker = tiles.find((p) => p.userId === effectiveFocusedId) ?? tiles[0];
// A screen-share tile becomes the auto-focus target when no one explicitly
// picked a tile yet. Focus ids now use Tile.id (kind-prefixed) so we can
// distinguish a user's own avatar tile from their screen tile.
const screenTile = tiles.find((p) => p.kind === 'screen');
const effectiveFocusedId = focusedId ?? screenTile?.id ?? tiles[0]?.id ?? null;
const speaker = tiles.find((p) => p.id === effectiveFocusedId) ?? tiles[0];
const controls = (
<CallControls
muted={isMuted}
muted={isMuted || !(room?.localParticipant?.isMicrophoneEnabled ?? false)}
sharing={isScreenSharing}
video={false}
video={isCameraEnabled}
deafened={isDeafened}
onToggleMute={toggleMute}
onToggleShare={() => void toggleScreenShare()}
onToggleShare={() => {
if (isScreenSharing) {
void stopScreenShare();
} else {
setShareDialogOpen(true);
}
}}
onToggleVideo={() => void toggleCamera()}
onToggleDeafen={toggleDeafen}
onHangup={() => void hangup()}
compact={callMode !== 'fullscreen'}
glass={callMode === 'fullscreen'}
@@ -105,20 +158,46 @@ export function InCallPanel({ conversation }: Props) {
);
if (callMode === 'fullscreen') {
// In fullscreen, a "manual focus" = user explicitly picked someone, OR
// someone is sharing a screen, OR exactly one non-self speaker is talking
// (auto-promote). Without that we show an even grid of all participants
// (Discord default). Clicking a tile switches to the big-speaker layout.
const speakingNonSelf = tiles.filter(
(t: Tile) => activeSpeakers.has(t.userId) && !t.self && t.kind === 'user',
);
const autoSpeaker =
focusedId === null && screenTile === undefined && speakingNonSelf.length === 1
? speakingNonSelf[0]
: undefined;
const hasFocus = focusedId !== null || screenTile !== undefined || autoSpeaker !== undefined;
const effectiveSpeaker = hasFocus ? speaker ?? autoSpeaker : undefined;
return (
<FullscreenCall
tiles={tiles}
speaker={speaker}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversation.members}
activeSpeakers={activeSpeakers}
e2ee={isE2EEActive}
onExit={() => setCallMode('grid')}
onFocusTile={(id) => {
setFocusedId(id);
}}
controls={controls}
/>
<>
<FullscreenCall
tiles={tiles}
speaker={effectiveSpeaker}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversation.members}
activeSpeakers={activeSpeakers}
e2ee={isE2EEActive}
onExit={() => setCallMode('grid')}
onFocusTile={(id) => {
// Toggle: click the already-focused tile to return to grid.
setFocusedId(focusedId === id ? null : id);
}}
onTileContextMenu={openVolumeMenu}
controls={controls}
/>
{volumeMenu && (
<ParticipantVolumeMenu
userId={volumeMenu.userId}
displayName={volumeMenu.displayName}
x={volumeMenu.x}
y={volumeMenu.y}
onClose={() => setVolumeMenu(null)}
/>
)}
</>
);
}
@@ -127,11 +206,19 @@ export function InCallPanel({ conversation }: Props) {
? conversation.name ?? t('app:chats.new_group')
: conversation.peer?.displayName ?? '—';
// Focus mode dedicates the entire call-panel vertical slot to the speaker so
// the tile can grow in height (grid mode's 420px cap leaves it squashed).
const sectionClass =
callMode === 'focus'
? 'flex min-h-[420px] shrink-0 flex-col overflow-hidden border-b border-line bg-surface-2'
: 'flex min-h-[280px] max-h-[420px] shrink-0 flex-col overflow-hidden border-b border-line bg-surface-2';
const sectionHeight = callMode === 'focus' ? '75%' : '50%';
return (
<section
aria-label={t('app:call.in_call', { defaultValue: 'Im Anruf' })}
className="flex min-h-[280px] max-h-[420px] shrink-0 flex-col overflow-hidden border-b border-line bg-surface-2"
style={{ height: '50%' }}
className={sectionClass}
style={{ height: sectionHeight }}
>
<div className="flex items-center justify-between border-b border-line bg-surface-3 px-4 py-2">
<div className="flex min-w-0 flex-col gap-0.5">
@@ -168,12 +255,31 @@ export function InCallPanel({ conversation }: Props) {
setFocusedId(id);
if (callMode === 'grid') setCallMode('focus');
}}
onTileContextMenu={openVolumeMenu}
compact
/>
{controls}
<PttHint />
<ScreenShareDialog
open={shareDialogOpen}
onClose={() => setShareDialogOpen(false)}
onStart={async (opts) => {
await startScreenShare(opts);
}}
/>
{volumeMenu && (
<ParticipantVolumeMenu
userId={volumeMenu.userId}
displayName={volumeMenu.displayName}
x={volumeMenu.x}
y={volumeMenu.y}
onClose={() => setVolumeMenu(null)}
/>
)}
</section>
);
}
@@ -185,49 +291,118 @@ export function InCallPanel({ conversation }: Props) {
interface BuildArgs {
conversation: ConversationSummary;
myId: string | null;
remoteIdentities: string[];
room: Room | null;
remoteParticipants: RemoteParticipant[];
isMuted: boolean;
isDeafened: boolean;
remoteDeafen: Record<string, boolean>;
isScreenSharing: boolean;
isCameraEnabled: boolean;
remoteSharerIds: Set<string>;
}
function cameraTrackFor(
participant: { videoTrackPublications: Map<string, { source: Track.Source; track?: { mediaStreamTrack: MediaStreamTrack } | undefined }> } | null,
): MediaStreamTrack | null {
if (!participant) return null;
for (const pub of participant.videoTrackPublications.values()) {
if (pub.source === Track.Source.Camera && pub.track) {
return pub.track.mediaStreamTrack ?? null;
}
}
return null;
}
function buildTiles({
conversation,
myId,
remoteIdentities,
room,
remoteParticipants,
isMuted,
isDeafened,
remoteDeafen,
isScreenSharing,
isCameraEnabled,
remoteSharerIds,
}: BuildArgs): Tile[] {
const remoteSet = new Set(remoteIdentities);
const remoteById = new Map<string, RemoteParticipant>();
for (const p of remoteParticipants) {
if (p.identity) remoteById.set(p.identity, p);
}
const out: Tile[] = [];
if (myId) {
const me = conversation.members.find((m) => m.userId === myId) ?? null;
// Source-of-truth for own mic: the LocalParticipant publication state.
// `isMuted` reflects the toggle button, but if mic never published (no
// device / permission denied) the toggle stays false while the real
// state is "muted". Combine both so the badge always matches reality.
const micLive = room?.localParticipant?.isMicrophoneEnabled ?? false;
out.push({
kind: 'user',
id: 'user:' + myId,
userId: myId,
displayName: me?.profile?.displayName ?? '?',
avatarUrl: me?.profile?.avatarUrl ?? null,
self: true,
muted: isMuted,
video: false,
sharing: isScreenSharing,
muted: isMuted || !micLive,
deafened: isDeafened,
video: isCameraEnabled,
videoTrack: cameraTrackFor(room?.localParticipant ?? null),
sharing: false,
remoteSharing: false,
});
if (isScreenSharing) {
out.push({
kind: 'screen',
id: 'screen:' + myId,
userId: myId,
displayName: (me?.profile?.displayName ?? '?') + ' · Bildschirm',
avatarUrl: me?.profile?.avatarUrl ?? null,
self: true,
muted: false,
deafened: false,
video: false,
videoTrack: null,
sharing: true,
remoteSharing: false,
});
}
}
for (const m of conversation.members) {
if (m.userId === myId) continue;
if (!remoteSet.has(m.userId)) continue;
const sharing = remoteSharerIds.has(m.userId);
const rp = remoteById.get(m.userId);
if (!rp) continue;
out.push({
kind: 'user',
id: 'user:' + m.userId,
userId: m.userId,
displayName: m.profile?.displayName ?? '?',
avatarUrl: m.profile?.avatarUrl ?? null,
self: false,
muted: false,
video: false,
sharing,
remoteSharing: sharing,
muted: !rp.isMicrophoneEnabled,
// Deafen state arrives via LiveKit data channel; see CallContext.
deafened: remoteDeafen[m.userId] ?? false,
video: rp.isCameraEnabled,
videoTrack: cameraTrackFor(rp),
sharing: false,
remoteSharing: false,
});
if (remoteSharerIds.has(m.userId)) {
out.push({
kind: 'screen',
id: 'screen:' + m.userId,
userId: m.userId,
displayName: (m.profile?.displayName ?? '?') + ' · Bildschirm',
avatarUrl: m.profile?.avatarUrl ?? null,
self: false,
muted: false,
deafened: false,
video: false,
videoTrack: null,
sharing: false,
remoteSharing: true,
});
}
}
return out;
}
@@ -319,9 +494,92 @@ interface StageProps {
}[];
conversationMembers: ConversationSummary['members'];
onFocusTile: (id: string) => void;
onTileContextMenu?: (tile: Tile, e: React.MouseEvent) => void;
compact?: boolean;
}
// Dispatches a Tile to the right renderer. Screen-tiles show the screenshare
// stream directly (no avatar, no speaking ring, no mic indicator); user-tiles
// render via CallParticipantTile with all its chrome.
function TileRender({
tile,
activeSpeakers,
e2ee,
remoteScreenShares,
conversationMembers,
size,
focused,
onClick,
onContextMenu,
}: {
tile: Tile;
activeSpeakers: Set<string>;
e2ee: boolean;
remoteScreenShares: StageProps['remoteScreenShares'];
conversationMembers: StageProps['conversationMembers'];
size?: 'default' | 'small';
focused?: boolean;
onClick?: () => void;
onContextMenu?: (e: React.MouseEvent) => void;
}): JSX.Element {
if (tile.kind === 'screen') {
if (tile.self) {
// Local screenshare preview — we don't mirror a copy of the outgoing
// stream. Render a labelled placeholder card so the user knows their
// share is live without double-encoding the stream.
return (
<div
onClick={onClick}
className={
'relative flex h-full w-full items-center justify-center overflow-hidden rounded-[14px] border border-emerald-500/40 bg-emerald-500/5 text-emerald-700 dark:text-emerald-200 ' +
(onClick ? 'cursor-pointer' : '')
}
>
<div className="flex flex-col items-center gap-2 p-4 text-center">
<div className="text-xs font-semibold uppercase tracking-wider">
Live
</div>
<div className="text-sm">{tile.displayName}</div>
</div>
</div>
);
}
const share = remoteScreenShares.find((s) => s.participantId === tile.userId);
const member = conversationMembers.find((m) => m.userId === tile.userId);
if (!share) return <div className="h-full w-full" />;
return (
<div
onClick={onClick}
className={'h-full w-full [&>div]:h-full [&>div]:w-full ' + (onClick ? 'cursor-pointer' : '')}
>
<ScreenShareViewer
share={share}
avatarUrl={member?.profile?.avatarUrl ?? tile.avatarUrl}
displayName={member?.profile?.displayName ?? tile.displayName}
/>
</div>
);
}
return (
<CallParticipantTile
userId={tile.userId}
displayName={tile.displayName}
avatarUrl={tile.avatarUrl}
me={tile.self}
muted={tile.muted}
deafened={tile.deafened}
speaking={activeSpeakers.has(tile.userId)}
video={tile.video}
videoTrack={tile.videoTrack}
e2ee={e2ee}
{...(size ? { size } : {})}
{...(focused ? { focused } : {})}
{...(onClick ? { onClick } : {})}
{...(onContextMenu ? { onContextMenu } : {})}
/>
);
}
function CallStage({
tiles,
speaker,
@@ -331,37 +589,40 @@ function CallStage({
remoteScreenShares,
conversationMembers,
onFocusTile,
onTileContextMenu,
compact = false,
}: StageProps) {
if (mode === 'focus' && speaker) {
const others = tiles.filter((p) => p.userId !== speaker.userId);
const others = tiles.filter((p) => p.id !== speaker.id);
return (
<div className="flex min-h-0 flex-1 flex-col gap-2.5 p-3">
<div className="min-h-0 flex-1">
<FocusedTile
tile={speaker}
e2ee={e2ee}
speaking={activeSpeakers.has(speaker.userId)}
activeSpeakers={activeSpeakers}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
/>
</div>
{others.length > 0 && (
<div className="flex h-[110px] gap-2.5 overflow-x-auto">
<div className="flex h-[180px] gap-2.5 overflow-x-auto">
{others.map((p) => (
<div key={p.userId} className="h-full min-w-[160px]">
<CallParticipantTile
userId={p.userId}
displayName={p.displayName}
avatarUrl={p.avatarUrl}
me={p.self}
muted={p.muted}
speaking={activeSpeakers.has(p.userId)}
sharing={p.sharing}
video={p.video}
<div
key={p.id}
className="h-full w-[240px] shrink-0 [&>div]:h-full"
>
<TileRender
tile={p}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
size="small"
onClick={() => onFocusTile(p.userId)}
onClick={() => onFocusTile(p.id)}
{...(onTileContextMenu
? { onContextMenu: (e: React.MouseEvent) => onTileContextMenu(p, e) }
: {})}
/>
</div>
))}
@@ -377,19 +638,19 @@ function CallStage({
<div className={'min-h-0 flex-1 p-3 ' + (compact ? '' : 'p-4')}>
<div className={'grid h-full gap-2 ' + gridClass}>
{tiles.map((p) => (
<CallParticipantTile
key={p.userId}
userId={p.userId}
displayName={p.displayName}
avatarUrl={p.avatarUrl}
me={p.self}
muted={p.muted}
speaking={activeSpeakers.has(p.userId)}
sharing={p.sharing}
video={p.video}
e2ee={e2ee}
onClick={() => onFocusTile(p.userId)}
/>
<div key={p.id} className="[&>div]:h-full [&>div]:w-full">
<TileRender
tile={p}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
onClick={() => onFocusTile(p.id)}
{...(onTileContextMenu
? { onContextMenu: (e: React.MouseEvent) => onTileContextMenu(p, e) }
: {})}
/>
</div>
))}
</div>
</div>
@@ -399,57 +660,57 @@ function CallStage({
function FocusedTile({
tile,
e2ee,
speaking,
activeSpeakers,
remoteScreenShares,
conversationMembers,
}: {
tile: Tile;
e2ee: boolean;
speaking: boolean;
activeSpeakers: Set<string>;
remoteScreenShares: StageProps['remoteScreenShares'];
conversationMembers: StageProps['conversationMembers'];
}) {
// When the focused participant is remotely sharing their screen, embed the
// real video stream rather than the fake-window placeholder.
if (tile.remoteSharing) {
const share = remoteScreenShares.find((s) => s.participantId === tile.userId);
const member = conversationMembers.find((m) => m.userId === tile.userId);
if (share) {
return (
<div className="h-full">
<ScreenShareViewer
share={share}
avatarUrl={member?.profile?.avatarUrl ?? tile.avatarUrl}
displayName={member?.profile?.displayName ?? tile.displayName}
/>
</div>
);
}
}
return (
<div className="h-full">
<CallParticipantTile
userId={tile.userId}
displayName={tile.displayName}
avatarUrl={tile.avatarUrl}
me={tile.self}
muted={tile.muted}
speaking={speaking}
sharing={tile.sharing}
video={tile.video}
<div className="h-full [&>div]:h-full">
<TileRender
tile={tile}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
focused
/>
</div>
);
}
const GRID_PAGE_SIZE = 12;
function gridColsFor(n: number): string {
if (n <= 1) return 'grid-cols-1';
if (n === 2) return 'grid-cols-2';
if (n === 3) return 'grid-cols-3';
// Explicit `grid-rows-*` so cells get a defined height (1fr of available
// space). Without this, implicit rows default to auto → they size to
// content, and a video element's intrinsic size blows the tile past the
// container bounds (overlapping the toolbar below).
if (n <= 1) return 'grid-cols-1 grid-rows-1';
if (n === 2) return 'grid-cols-2 grid-rows-1';
if (n === 3) return 'grid-cols-3 grid-rows-1';
if (n === 4) return 'grid-cols-2 grid-rows-2';
return 'grid-cols-3 grid-rows-2';
if (n <= 6) return 'grid-cols-3 grid-rows-2';
if (n <= 9) return 'grid-cols-3 grid-rows-3';
return 'grid-cols-4 grid-rows-3';
}
// Promote self + active speakers to the front of the tile list. Stable
// otherwise. Used by both pagination (so page 1 always carries the most
// "useful" tiles) and active-speaker promotion in fullscreen.
function prioritizeTiles(tiles: Tile[], activeSpeakers: Set<string>): Tile[] {
const score = (t: Tile): number => {
if (t.self) return 3;
if (activeSpeakers.has(t.userId)) return 2;
if (t.kind === 'screen') return 1;
return 0;
};
return [...tiles].sort((a, b) => score(b) - score(a));
}
// ---------------------------------------------------------------------------
@@ -465,6 +726,7 @@ interface FullscreenProps {
e2ee: boolean;
onExit: () => void;
onFocusTile: (id: string) => void;
onTileContextMenu?: (tile: Tile, e: React.MouseEvent) => void;
controls: React.ReactNode;
}
@@ -477,99 +739,142 @@ function FullscreenCall({
e2ee,
onExit: _onExit,
onFocusTile,
onTileContextMenu,
controls,
}: FullscreenProps) {
const others = speaker ? tiles.filter((p) => p.userId !== speaker.userId) : tiles;
const [hintGone, setHintGone] = useState(false);
const [page, setPage] = useState(0);
useEffect(() => {
const id = window.setTimeout(() => setHintGone(true), 3500);
return () => window.clearTimeout(id);
}, []);
const hasFocus = speaker !== undefined;
const others = hasFocus ? tiles.filter((p) => p.id !== speaker!.id) : [];
// Active-speaker reorder + paginate. When more than GRID_PAGE_SIZE tiles
// exist, slice them into pages. Reset to page 0 if the page count drops
// below the current page (someone left).
const sortedGridTiles = useMemo(
() => prioritizeTiles(tiles, activeSpeakers),
[tiles, activeSpeakers],
);
const pageCount = Math.max(1, Math.ceil(sortedGridTiles.length / GRID_PAGE_SIZE));
useEffect(() => {
if (page >= pageCount) setPage(0);
}, [pageCount, page]);
const visibleTiles = sortedGridTiles.slice(
page * GRID_PAGE_SIZE,
(page + 1) * GRID_PAGE_SIZE,
);
const gridClass = gridColsFor(visibleTiles.length);
return (
<div className="absolute inset-0 z-40 flex flex-col overflow-hidden bg-surface">
<div className="relative min-h-0 flex-1">
{speaker && (
<div className="absolute inset-0">
{speaker.remoteSharing ? (
<FullscreenShare speaker={speaker} remoteScreenShares={remoteScreenShares} conversationMembers={conversationMembers} />
) : (
<div className="h-full w-full [&>div]:rounded-none [&>div]:border-0">
<CallParticipantTile
userId={speaker.userId}
displayName={speaker.displayName}
avatarUrl={speaker.avatarUrl}
me={speaker.self}
muted={speaker.muted}
speaking={activeSpeakers.has(speaker.userId)}
sharing={speaker.sharing}
video={speaker.video}
e2ee={e2ee}
focused
/>
<div className="fixed inset-0 z-[60] flex flex-col overflow-hidden bg-surface">
{/* Content area. pb-24 reserves ~96px space at the bottom for the
floating controls bar so tiles never sit behind it. */}
<div className="relative flex min-h-0 flex-1 flex-col pb-24">
{hasFocus ? (
<>
<div
className="relative min-h-0 flex-1 cursor-pointer p-4 pb-2 [&>div]:h-full [&>div]:w-full"
onClick={() => onFocusTile(speaker!.id)}
title="Zurück zur Übersicht"
>
<TileRender
tile={speaker!}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
focused
{...(onTileContextMenu
? { onContextMenu: (e: React.MouseEvent) => onTileContextMenu(speaker!, e) }
: {})}
/>
</div>
{others.length > 0 && (
<div className="flex h-[160px] shrink-0 gap-2.5 overflow-x-auto px-4 pb-2">
{others.map((p) => (
<div
key={p.id}
className="h-full w-[220px] shrink-0 [&>div]:h-full [&>div]:w-full"
>
<TileRender
tile={p}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
size="small"
onClick={() => onFocusTile(p.id)}
{...(onTileContextMenu
? { onContextMenu: (e: React.MouseEvent) => onTileContextMenu(p, e) }
: {})}
/>
</div>
))}
</div>
)}
</>
) : (
<div className="min-h-0 flex-1 p-4">
<div className={'grid h-full gap-2 ' + gridClass}>
{visibleTiles.map((p) => (
<div key={p.id} className="min-h-0 min-w-0 [&>div]:h-full [&>div]:w-full">
<TileRender
tile={p}
activeSpeakers={activeSpeakers}
e2ee={e2ee}
remoteScreenShares={remoteScreenShares}
conversationMembers={conversationMembers}
onClick={() => onFocusTile(p.id)}
{...(onTileContextMenu
? { onContextMenu: (e: React.MouseEvent) => onTileContextMenu(p, e) }
: {})}
/>
</div>
))}
</div>
{pageCount > 1 && (
<div className="mt-2 flex items-center justify-center gap-3 text-xs text-fg-muted">
<button
type="button"
onClick={() => setPage((p) => (p === 0 ? pageCount - 1 : p - 1))}
className="cursor-pointer rounded-md border border-line bg-surface-2 px-2 py-1 hover:bg-surface-3"
aria-label="Vorherige Seite"
>
</button>
<span className="tabular-nums">
{page + 1} / {pageCount}
</span>
<button
type="button"
onClick={() => setPage((p) => (p + 1) % pageCount)}
className="cursor-pointer rounded-md border border-line bg-surface-2 px-2 py-1 hover:bg-surface-3"
aria-label="Nächste Seite"
>
</button>
</div>
)}
</div>
)}
{others.length > 0 && (
<div className="absolute bottom-24 right-4 flex w-[180px] flex-col gap-2">
{others.slice(0, 4).map((p) => (
<div key={p.userId} className="h-[100px] backdrop-blur-xl">
<CallParticipantTile
userId={p.userId}
displayName={p.displayName}
avatarUrl={p.avatarUrl}
me={p.self}
muted={p.muted}
speaking={activeSpeakers.has(p.userId)}
sharing={p.sharing}
video={p.video}
e2ee={e2ee}
size="small"
onClick={() => onFocusTile(p.userId)}
/>
</div>
))}
</div>
)}
{!hintGone && (
<div
aria-hidden="true"
className="pointer-events-none absolute left-1/2 top-5 z-10 animate-fs-hint rounded-lg border border-white/10 bg-black/60 px-3.5 py-1.5 text-[11px] font-medium tracking-wide text-white/70 backdrop-blur-md"
>
Esc zum Verlassen
</div>
)}
<div className="pointer-events-auto absolute bottom-4 left-1/2 -translate-x-1/2">
{controls}
</div>
</div>
</div>
);
}
function FullscreenShare({
speaker,
remoteScreenShares,
conversationMembers,
}: {
speaker: Tile;
remoteScreenShares: StageProps['remoteScreenShares'];
conversationMembers: StageProps['conversationMembers'];
}) {
const share = remoteScreenShares.find((s) => s.participantId === speaker.userId);
const member = conversationMembers.find((m) => m.userId === speaker.userId);
if (!share) return null;
return (
<div className="h-full w-full">
<ScreenShareViewer
share={share}
avatarUrl={member?.profile?.avatarUrl ?? speaker.avatarUrl}
displayName={member?.profile?.displayName ?? speaker.displayName}
/>
{!hintGone && (
<div
aria-hidden="true"
className="pointer-events-none absolute left-1/2 top-5 z-10 animate-fs-hint rounded-lg border border-white/10 bg-black/60 px-3.5 py-1.5 text-[11px] font-medium tracking-wide text-white/70 backdrop-blur-md"
>
Esc zum Verlassen
</div>
)}
<div className="pointer-events-auto absolute bottom-4 left-1/2 -translate-x-1/2">
{controls}
</div>
</div>
);
}
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { useCall } from '../context/CallContext';
import { useFriendshipsContext } from '../context/FriendshipsContext';
import { AvatarColorKey, colorKeyFor } from './CallParticipantTile';
import { LockIcon, PhoneIcon, PhoneOffIcon } from './icons';
import { LockIcon, PhoneIcon, PhoneOffIcon, VideoIcon } from './icons';
interface Props {
conversation: ConversationSummary;
@@ -99,23 +99,37 @@ export function IncomingCallPanel({ conversation }: Props) {
</>
)}
</p>
<div className="mt-5 flex w-full max-w-[360px] gap-3">
<div className="mt-5 flex w-full max-w-[440px] flex-wrap gap-3">
<button
type="button"
onClick={rejectIncoming}
className="inline-flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-[14px] border border-rose-500/40 bg-transparent px-5 py-3.5 text-sm font-semibold text-rose-600 transition hover:bg-rose-500/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-500/40 dark:text-rose-400"
className="inline-flex flex-1 basis-[30%] cursor-pointer items-center justify-center gap-2 rounded-[14px] border border-rose-500/40 bg-transparent px-4 py-3.5 text-sm font-semibold text-rose-600 transition hover:bg-rose-500/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-500/40 dark:text-rose-400"
>
<PhoneOffIcon className="h-4 w-4" />
<span>{t('app:call.decline')}</span>
</button>
<button
type="button"
onClick={() => void acceptIncoming()}
className="inline-flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-[14px] bg-emerald-600 px-5 py-3.5 text-sm font-semibold text-white shadow-accept-btn transition hover:bg-emerald-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/50"
onClick={() => void acceptIncoming('audio')}
className="inline-flex flex-1 basis-[30%] cursor-pointer items-center justify-center gap-2 rounded-[14px] bg-emerald-600 px-4 py-3.5 text-sm font-semibold text-white shadow-accept-btn transition hover:bg-emerald-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500/50"
>
<PhoneIcon className="h-4 w-4" />
<span>{t('app:call.accept')}</span>
<span>
{state.mediaKind === 'video'
? t('app:call.accept_audio', { defaultValue: 'Nur Audio' })
: t('app:call.accept')}
</span>
</button>
{state.mediaKind === 'video' && (
<button
type="button"
onClick={() => void acceptIncoming('video')}
className="inline-flex flex-1 basis-[30%] cursor-pointer items-center justify-center gap-2 rounded-[14px] bg-accent px-4 py-3.5 text-sm font-semibold text-accent-fg shadow-accept-btn transition hover:brightness-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50"
>
<VideoIcon className="h-4 w-4" />
<span>{t('app:call.accept_video', { defaultValue: 'Mit Video' })}</span>
</button>
)}
</div>
</div>
</section>
+131 -11
View File
@@ -13,13 +13,22 @@ import { useAuth } from '../context/AuthContext';
import { devLocalSecretStore } from '../lib/secretStore';
import { supabase } from '../lib/supabase';
import type { AggregatedReaction } from '../lib/useMessageReactions';
import { AttachmentAudio } from './AttachmentAudio';
import { AttachmentImage } from './AttachmentImage';
import { Avatar } from './Avatar';
import { PencilIcon, PhoneIcon, PhoneOffIcon, SmileIcon, SpinnerIcon, TrashIcon, XIcon } from './icons';
import { ForwardIcon, PencilIcon, PhoneIcon, PhoneOffIcon, ReplyIcon, SmileIcon, SpinnerIcon, TrashIcon, XIcon } from './icons';
const EMOJI_CHOICES = ['👍', '❤️', '😂', '🎉', '🔥', '😮', '😢', '🙏'];
const EDIT_WINDOW_MS = 24 * 60 * 60 * 1000;
export interface QuotedRef {
id: string;
senderName: string;
snippet: string;
isAttachment: boolean;
deleted: boolean;
}
interface Props {
message: DecryptedMessage;
mine: boolean;
@@ -32,6 +41,18 @@ interface Props {
reactions: AggregatedReaction[];
onToggleReaction: (emoji: string) => Promise<void>;
showSeen?: boolean;
/** Delivery state for own messages: 'sent' / 'delivered' / 'read'. */
deliveryState?: 'sent' | 'delivered' | 'read';
/** Resolved quoted message info (parent does the lookup). */
quoted?: QuotedRef | null;
/** Tap-to-jump on quote bubble. Receives the quoted message's id. */
onJumpToMessage?: (id: string) => void;
/** Hover action: parent receives current message to start a reply. */
onReply?: (m: DecryptedMessage) => void;
/** Hover action: parent opens forward dialog for current message. */
onForward?: (m: DecryptedMessage) => void;
/** Highlighted state — set briefly after a jump. */
highlighted?: boolean;
}
export function MessageBubble({
@@ -45,6 +66,12 @@ export function MessageBubble({
reactions,
onToggleReaction,
showSeen = false,
deliveryState,
quoted = null,
onJumpToMessage,
onReply,
onForward,
highlighted = false,
}: Props) {
const { t } = useTranslation(['app']);
const { session, device } = useAuth();
@@ -228,21 +255,58 @@ export function MessageBubble({
</div>
) : (
<div
data-message-id={message.id}
className={
'break-words px-3.5 py-2 text-sm ' +
'break-words px-3.5 py-2 text-sm transition ' +
(highlighted ? 'ring-2 ring-amber-400 ring-offset-2 ring-offset-surface-3 ' : '') +
(mine
? 'rounded-[18px_18px_4px_18px] bg-accent text-accent-fg'
: 'rounded-[18px_18px_18px_4px] border border-line text-fg')
}
>
{quoted && (
<button
type="button"
onClick={() => onJumpToMessage?.(quoted.id)}
className={
'mb-1.5 flex w-full cursor-pointer items-stretch gap-2 rounded-md px-2 py-1.5 text-left text-xs transition hover:opacity-90 ' +
(mine
? 'bg-white/15 text-accent-fg/90'
: 'bg-surface-2 text-fg-muted')
}
>
<span
aria-hidden="true"
className={
'w-0.5 shrink-0 rounded-full ' + (mine ? 'bg-white/50' : 'bg-accent')
}
/>
<span className="min-w-0 flex-1">
<span className={'block truncate font-semibold ' + (mine ? '' : 'text-fg')}>
{quoted.senderName}
</span>
<span className="block truncate italic opacity-90">
{quoted.deleted
? t('app:chats.deleted')
: quoted.isAttachment && !quoted.snippet
? '📎 ' + t('app:chats.attachment', { defaultValue: 'Anhang' })
: quoted.snippet}
</span>
</span>
</button>
)}
{message.plaintext === null ? (
<span className="italic opacity-70">cannot decrypt</span>
) : (
<>
{bodyText.length > 0 && <div>{bodyText}</div>}
{attachments.map((a) => (
<AttachmentImage key={a.id} handle={a} />
))}
{attachments.map((a) =>
a.mimeType.startsWith('audio/') ? (
<AttachmentAudio key={a.id} handle={a} />
) : (
<AttachmentImage key={a.id} handle={a} />
),
)}
</>
)}
<div
@@ -259,21 +323,24 @@ export function MessageBubble({
</div>
)}
{showSeen && mine && !editing && !message.deletedAt && (
<p className="mt-0.5 text-right text-[10px] text-fg-muted">
{t('app:chats.seen')}
</p>
{mine && !editing && !message.deletedAt && deliveryState && (
<div className="mt-0.5 flex items-center justify-end gap-1 text-[10px] text-fg-muted">
<DeliveryTicks state={deliveryState} />
{showSeen && <span>{t('app:chats.seen')}</span>}
</div>
)}
{reactions.length > 0 && !editing && (
<div className={'mt-1 flex flex-wrap gap-1 ' + (mine ? 'justify-end' : 'justify-start')}>
{reactions.map((r) => (
<button
key={r.emoji}
// Keying by emoji+count makes React remount the chip when the
// count flips, replaying the pop animation. Cheap visual cue.
key={r.emoji + ':' + r.count}
type="button"
onClick={() => void onToggleReaction(r.emoji)}
className={
'inline-flex cursor-pointer items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
'inline-flex origin-bottom animate-reaction-pop cursor-pointer items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
(r.mine
? 'border-accent/40 bg-accent/20 text-accent'
: 'border-line bg-surface-2 text-fg hover:bg-surface-3')
@@ -299,6 +366,20 @@ export function MessageBubble({
onClick={() => setPickerOpen((v) => !v)}
icon={<SmileIcon className="h-4 w-4" />}
/>
{onReply && !message.deletedAt && (
<ActionButton
label={t('app:chats.reply', { defaultValue: 'Antworten' })}
onClick={() => onReply(message)}
icon={<ReplyIcon className="h-4 w-4" />}
/>
)}
{onForward && !message.deletedAt && (
<ActionButton
label={t('app:chats.forward', { defaultValue: 'Weiterleiten' })}
onClick={() => onForward(message)}
icon={<ForwardIcon className="h-4 w-4" />}
/>
)}
{canEdit && (
<ActionButton
label="Edit"
@@ -429,6 +510,45 @@ function formatDuration(totalSec: number): string {
return m + ':' + s.toString().padStart(2, '0');
}
function DeliveryTicks({ state }: { state: 'sent' | 'delivered' | 'read' }) {
// One checkmark for sent, two for delivered/read. Read shifts color to the
// accent to match WhatsApp/Telegram blue-tick convention.
const color =
state === 'read'
? 'text-sky-500 dark:text-sky-400'
: 'text-fg-muted';
return (
<span
aria-label={
state === 'read'
? 'Gelesen'
: state === 'delivered'
? 'Zugestellt'
: 'Gesendet'
}
title={
state === 'read'
? 'Gelesen'
: state === 'delivered'
? 'Zugestellt'
: 'Gesendet'
}
className={'flex items-center ' + color}
>
<svg viewBox="0 0 16 12" width="14" height="10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
{state === 'sent' ? (
<polyline points="2 7 6 11 14 1" />
) : (
<>
<polyline points="1 7 5 11 11 2" />
<polyline points="6 11 10 11 14 1" />
</>
)}
</svg>
</span>
);
}
function ActionButton({
label,
onClick,
@@ -0,0 +1,87 @@
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import {
getParticipantVolume,
setParticipantVolume,
subscribeParticipantVolumes,
} from '../lib/participantVolumes';
interface Props {
userId: string;
displayName: string;
x: number;
y: number;
onClose: () => void;
}
const MENU_W = 240;
const MENU_H = 84;
export function ParticipantVolumeMenu({
userId,
displayName,
x,
y,
onClose,
}: Props) {
const [volume, setVolume] = useState<number>(() => getParticipantVolume(userId));
// Re-sync from store in case another menu instance changed the same user.
useEffect(() => subscribeParticipantVolumes(() => {
setVolume(getParticipantVolume(userId));
}), [userId]);
// Outside click + Esc to close.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
const onDown = (e: MouseEvent) => {
const target = e.target as HTMLElement | null;
if (target?.closest('[data-volume-menu]')) return;
onClose();
};
window.addEventListener('keydown', onKey);
window.addEventListener('mousedown', onDown);
return () => {
window.removeEventListener('keydown', onKey);
window.removeEventListener('mousedown', onDown);
};
}, [onClose]);
const left = Math.min(Math.max(8, x), window.innerWidth - MENU_W - 8);
const top = Math.min(Math.max(8, y), window.innerHeight - MENU_H - 8);
return createPortal(
<div
data-volume-menu
role="dialog"
aria-label={'Lautstärke ' + displayName}
style={{ left, top, width: MENU_W }}
className="fixed z-[80] rounded-xl border border-line bg-surface-2/95 p-3 shadow-xl backdrop-blur-md"
>
<div className="mb-2 flex items-center justify-between gap-2 text-xs">
<span className="truncate font-semibold text-fg">{displayName}</span>
<span className="tabular-nums text-fg-muted">
{Math.round(volume * 100)}%
</span>
</div>
<input
type="range"
min={0}
max={1}
step={0.01}
value={volume}
onChange={(e) => {
const v = Number(e.target.value);
setVolume(v);
setParticipantVolume(userId, v);
}}
aria-label={'Lautstärke ' + displayName}
className="w-full accent-accent"
/>
</div>,
document.body,
);
}
@@ -0,0 +1,233 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
type DisplaySurfaceHint,
getPresetParams,
getScreenShareSettings,
PRESET_ORDER,
type ScreenSharePreset,
} from '../lib/screenShareSettings';
import {
MonitorShareIcon,
SpinnerIcon,
XIcon,
} from './icons';
interface Props {
open: boolean;
onClose: () => void;
onStart: (opts: {
preset: ScreenSharePreset;
displaySurface: DisplaySurfaceHint;
framerate: number | null;
}) => Promise<void>;
}
const FRAMERATE_OPTIONS: ReadonlyArray<{ value: number | null; label: string }> = [
{ value: null, label: 'Preset-Standard' },
{ value: 15, label: '15 fps' },
{ value: 30, label: '30 fps' },
{ value: 60, label: '60 fps' },
];
// Discord-style pre-share dialog. The OS still owns the final source picker
// (browser/OS limitation — only Chrome/Edge plus a native plugin can enumerate
// windows from JS), but we pre-filter with the `displaySurface` hint and lock
// in quality + framerate up-front so the user doesn't have to re-open the
// system picker to adjust them mid-call.
export function ScreenShareDialog({ open, onClose, onStart }: Props) {
const { t } = useTranslation(['app']);
const initial = getScreenShareSettings();
const [surface, setSurface] = useState<DisplaySurfaceHint>(initial.displaySurface);
const [preset, setPreset] = useState<ScreenSharePreset>(initial.preset);
const [framerate, setFramerate] = useState<number | null>(initial.framerateOverride);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
if (!open) return null;
async function handleStart() {
setBusy(true);
setError(null);
try {
await onStart({ preset, displaySurface: surface, framerate });
onClose();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'screenshare failed');
} finally {
setBusy(false);
}
}
const presetParams = getPresetParams(preset);
const effectiveFps = framerate ?? presetParams.framerate;
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('app:call.share_dialog_title', { defaultValue: 'Bildschirm teilen' })}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={onClose}
>
<div
onClick={(e) => e.stopPropagation()}
className="flex w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-line bg-surface-3 shadow-xl"
>
<header className="flex items-center justify-between border-b border-line px-5 py-3">
<div className="flex items-center gap-2">
<MonitorShareIcon className="h-4 w-4 text-accent" />
<h3 className="font-display text-sm font-semibold text-fg">
{t('app:call.share_dialog_title', { defaultValue: 'Bildschirm teilen' })}
</h3>
</div>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-fg-muted transition hover:bg-surface-2 hover:text-fg"
>
<XIcon className="h-4 w-4" />
</button>
</header>
<div className="space-y-5 p-5">
<div>
<p className="mb-2 text-xs font-semibold uppercase tracking-wider text-fg-muted">
{t('app:call.share_surface', { defaultValue: 'Quelle' })}
</p>
<div className="grid grid-cols-3 gap-2">
<SurfaceOption
active={surface === null}
onClick={() => setSurface(null)}
label={t('app:call.share_any', { defaultValue: 'Alle anzeigen' })}
sub={t('app:call.share_any_sub', { defaultValue: 'Bildschirm + Fenster' })}
/>
<SurfaceOption
active={surface === 'monitor'}
onClick={() => setSurface('monitor')}
label={t('app:call.share_monitor', { defaultValue: 'Bildschirm' })}
sub={t('app:call.share_monitor_sub', { defaultValue: 'Ganzer Monitor' })}
/>
<SurfaceOption
active={surface === 'window'}
onClick={() => setSurface('window')}
label={t('app:call.share_window', { defaultValue: 'Fenster' })}
sub={t('app:call.share_window_sub', { defaultValue: 'Einzelnes Fenster' })}
/>
</div>
</div>
<div>
<p className="mb-2 text-xs font-semibold uppercase tracking-wider text-fg-muted">
{t('app:call.share_quality', { defaultValue: 'Qualität' })}
</p>
<select
value={preset}
onChange={(e) => setPreset(e.target.value as ScreenSharePreset)}
className="w-full rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm text-fg focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
{PRESET_ORDER.map((p) => (
<option key={p} value={p}>
{getPresetParams(p).label} · {getPresetParams(p).bitrateKbps} kbps
</option>
))}
</select>
</div>
<div>
<p className="mb-2 text-xs font-semibold uppercase tracking-wider text-fg-muted">
{t('app:call.share_fps', { defaultValue: 'Bildrate' })}
</p>
<div className="flex flex-wrap gap-2">
{FRAMERATE_OPTIONS.map((opt) => (
<button
key={String(opt.value)}
type="button"
onClick={() => setFramerate(opt.value)}
className={
'cursor-pointer rounded-lg border px-3 py-1.5 text-xs font-medium transition ' +
(framerate === opt.value
? 'border-accent bg-accent/15 text-accent'
: 'border-line bg-surface-2 text-fg hover:bg-surface')
}
>
{opt.label}
</button>
))}
</div>
<p className="mt-2 text-[11px] text-fg-muted">
{t('app:call.share_fps_effective', {
defaultValue: 'Effektiv: {{fps}} fps',
fps: effectiveFps,
})}
</p>
</div>
{error && (
<p role="alert" className="text-sm text-rose-600 dark:text-rose-300">
{error}
</p>
)}
<p className="text-[11px] text-fg-muted">
{t('app:call.share_hint', {
defaultValue:
'Nach "Teilen starten" öffnet das Betriebssystem den Quellen-Picker. Qualität + Bildrate werden bereits angewendet.',
})}
</p>
</div>
<footer className="flex items-center justify-end gap-2 border-t border-line bg-surface-2 px-5 py-3">
<button
type="button"
onClick={onClose}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-3 py-2 text-sm text-fg transition hover:bg-surface-2"
>
{t('app:friends.action_cancel', { defaultValue: 'Abbrechen' })}
</button>
<button
type="button"
onClick={() => void handleStart()}
disabled={busy}
className="inline-flex cursor-pointer items-center gap-1.5 rounded-md bg-accent px-3 py-2 text-sm font-semibold text-accent-fg transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60"
>
{busy && <SpinnerIcon className="h-4 w-4" />}
<span>
{t('app:call.share_start', { defaultValue: 'Teilen starten' })}
</span>
</button>
</footer>
</div>
</div>
);
}
function SurfaceOption({
active,
onClick,
label,
sub,
}: {
active: boolean;
onClick: () => void;
label: string;
sub: string;
}) {
return (
<button
type="button"
onClick={onClick}
className={
'flex flex-col items-start gap-0.5 rounded-lg border p-2.5 text-left transition ' +
(active
? 'border-accent bg-accent/10 text-fg'
: 'border-line bg-surface-2 text-fg hover:bg-surface')
}
>
<span className="text-xs font-semibold">{label}</span>
<span className="text-[10px] text-fg-muted">{sub}</span>
</button>
);
}
@@ -32,30 +32,31 @@ export function ScreenShareViewer({ share, avatarUrl, displayName }: ScreenShare
};
}, [share.track, watching]);
// Esc exits CSS fullscreen.
useEffect(() => {
const onChange = () => {
setIsFullscreen(document.fullscreenElement === containerRef.current);
if (!isFullscreen) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setIsFullscreen(false);
};
document.addEventListener('fullscreenchange', onChange);
return () => document.removeEventListener('fullscreenchange', onChange);
}, []);
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [isFullscreen]);
// CSS-only "app fullscreen" — Discord-style: overlay the whole window
// including the left sidebar + chat list. Native Fullscreen API is
// unreliable in Tauri's WKWebView and doesn't add useful chrome-hiding
// beyond what `fixed inset-0 z-[60]` already gives us.
const toggleFullscreen = () => {
const el = containerRef.current;
if (!el) return;
if (document.fullscreenElement === el) {
void document.exitFullscreen();
} else {
void el.requestFullscreen();
}
setIsFullscreen((v) => !v);
};
return (
<div
ref={containerRef}
className={
'overflow-hidden rounded-xl border border-emerald-500/30 bg-black ' +
(isFullscreen ? 'flex h-screen w-screen flex-col rounded-none' : '')
isFullscreen
? 'fixed inset-0 z-[60] flex h-screen w-screen flex-col overflow-hidden border-0 bg-black'
: 'flex h-full w-full flex-col overflow-hidden rounded-xl border border-emerald-500/30 bg-black'
}
>
<div className="flex shrink-0 items-center gap-2 border-b border-emerald-500/20 bg-emerald-500/15 px-3 py-1.5 text-xs text-emerald-700 dark:text-emerald-200">
@@ -102,10 +103,7 @@ export function ScreenShareViewer({ share, avatarUrl, displayName }: ScreenShare
playsInline
muted
onDoubleClick={toggleFullscreen}
className={
'block cursor-zoom-in bg-black ' +
(isFullscreen ? 'h-full w-full flex-1 object-contain' : 'w-full')
}
className="block h-full w-full flex-1 cursor-zoom-in bg-black object-contain"
/>
) : (
<button
@@ -0,0 +1,252 @@
import { useEffect, useRef, useState } from 'react';
import { MicIcon, SpinnerIcon, XIcon } from './icons';
interface Props {
/** Called with the recorded audio file when the user confirms. The button
* ships as a single-attachment message, so the parent can feed it into
* the normal send flow. */
onComplete: (file: File) => Promise<void> | void;
disabled?: boolean;
}
// Single-button voice recorder. Click to start; shows an inline pill with
// elapsed time + stop + cancel while recording. On stop, hands a File to the
// parent. No in-place preview yet — we lean on the optimistic message bubble
// to appear once the parent sends.
const MAX_RECORD_SEC = 60;
export function VoiceRecorder({ onComplete, disabled = false }: Props) {
const [state, setState] = useState<'idle' | 'recording' | 'finalizing'>('idle');
const [elapsedSec, setElapsedSec] = useState(0);
const [level, setLevel] = useState(0);
const recorderRef = useRef<MediaRecorder | null>(null);
const chunksRef = useRef<Blob[]>([]);
const streamRef = useRef<MediaStream | null>(null);
const startedAtRef = useRef<number>(0);
const cancelledRef = useRef(false);
const audioCtxRef = useRef<AudioContext | null>(null);
const analyserRef = useRef<AnalyserNode | null>(null);
const rafRef = useRef<number>(0);
// Tick elapsed + auto-stop at MAX_RECORD_SEC.
useEffect(() => {
if (state !== 'recording') return;
const id = window.setInterval(() => {
const sec = Math.floor((Date.now() - startedAtRef.current) / 1000);
setElapsedSec(sec);
if (sec >= MAX_RECORD_SEC) {
const rec = recorderRef.current;
if (rec && rec.state !== 'inactive') rec.stop();
}
}, 200);
return () => {
window.clearInterval(id);
};
}, [state]);
// Live mic level meter via Web Audio AnalyserNode. RMS on 0..1, smoothed.
useEffect(() => {
if (state !== 'recording') return;
const analyser = analyserRef.current;
if (!analyser) return;
const buf = new Uint8Array(analyser.frequencyBinCount);
let cancelled = false;
const tick = () => {
if (cancelled) return;
analyser.getByteFrequencyData(buf as Uint8Array<ArrayBuffer>);
let sum = 0;
for (let i = 0; i < buf.length; i++) sum += buf[i]!;
setLevel(sum / (buf.length * 255));
rafRef.current = window.requestAnimationFrame(tick);
};
rafRef.current = window.requestAnimationFrame(tick);
return () => {
cancelled = true;
window.cancelAnimationFrame(rafRef.current);
};
}, [state]);
const stopStream = () => {
if (streamRef.current) {
streamRef.current.getTracks().forEach((t) => t.stop());
streamRef.current = null;
}
if (audioCtxRef.current) {
void audioCtxRef.current.close().catch(() => {});
audioCtxRef.current = null;
}
analyserRef.current = null;
setLevel(0);
};
const start = async () => {
if (disabled) return;
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
streamRef.current = stream;
try {
const ctx = new (window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();
const source = ctx.createMediaStreamSource(stream);
const analyser = ctx.createAnalyser();
analyser.fftSize = 256;
analyser.smoothingTimeConstant = 0.4;
source.connect(analyser);
audioCtxRef.current = ctx;
analyserRef.current = analyser;
} catch {
/* Analyser is best-effort; recording still works without level meter. */
}
const mime = pickMime();
const rec = new MediaRecorder(stream, mime ? { mimeType: mime } : undefined);
recorderRef.current = rec;
chunksRef.current = [];
cancelledRef.current = false;
rec.ondataavailable = (ev: BlobEvent) => {
if (ev.data && ev.data.size > 0) chunksRef.current.push(ev.data);
};
rec.onstop = () => {
const blob = new Blob(chunksRef.current, { type: rec.mimeType || 'audio/webm' });
chunksRef.current = [];
stopStream();
if (cancelledRef.current || blob.size === 0) {
setState('idle');
setElapsedSec(0);
return;
}
setState('finalizing');
const ext = extFor(blob.type);
const filename = 'voice-' + new Date().toISOString().replace(/[:.]/g, '-') + '.' + ext;
const file = new File([blob], filename, { type: blob.type });
void Promise.resolve(onComplete(file)).finally(() => {
setState('idle');
setElapsedSec(0);
});
};
rec.start();
startedAtRef.current = Date.now();
setElapsedSec(0);
setState('recording');
} catch (err: unknown) {
stopStream();
// Surface device-permission denials or capture failures via console;
// the composer doesn't have space for inline errors here and the
// browser already shows a system-level permission prompt.
console.error('VoiceRecorder.start failed', err);
}
};
const confirm = () => {
const rec = recorderRef.current;
if (!rec) return;
if (rec.state !== 'inactive') rec.stop();
};
const cancel = () => {
cancelledRef.current = true;
const rec = recorderRef.current;
if (rec && rec.state !== 'inactive') rec.stop();
else {
stopStream();
setState('idle');
setElapsedSec(0);
}
};
if (state === 'idle') {
return (
<button
type="button"
onClick={() => void start()}
disabled={disabled}
aria-label="Sprachnachricht aufnehmen"
title="Sprachnachricht aufnehmen"
className="inline-flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-lg bg-surface-2 text-fg transition hover:bg-surface-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
>
<MicIcon className="h-4 w-4" />
</button>
);
}
if (state === 'finalizing') {
return (
<div className="inline-flex h-11 items-center gap-2 rounded-lg bg-surface-2 px-3 text-xs text-fg-muted">
<SpinnerIcon className="h-4 w-4" />
<span>Wird gesendet</span>
</div>
);
}
// Visual level: scale from 0..1 → 0..100% width. Floor at 4% so the bar
// stays visible when silent.
const levelPct = Math.max(4, Math.min(100, Math.round(level * 180)));
const remaining = Math.max(0, MAX_RECORD_SEC - elapsedSec);
return (
<div className="inline-flex h-11 items-center gap-2 rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 text-xs font-semibold text-rose-700 dark:text-rose-200">
<span className="h-2 w-2 animate-pulse rounded-full bg-rose-500" />
<span className="tabular-nums">{formatTime(elapsedSec)}</span>
<div
aria-hidden="true"
className="relative h-1.5 w-20 overflow-hidden rounded-full bg-rose-500/20"
>
<span
className="absolute inset-y-0 left-0 rounded-full bg-rose-500 transition-[width] duration-75"
style={{ width: levelPct + '%' }}
/>
</div>
<span className="tabular-nums text-[10px] text-rose-700/70 dark:text-rose-200/70">
{remaining}s
</span>
<button
type="button"
onClick={cancel}
aria-label="Aufnahme abbrechen"
title="Abbrechen"
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md text-fg-muted hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-3.5 w-3.5" />
</button>
<button
type="button"
onClick={confirm}
aria-label="Aufnahme senden"
title="Senden"
className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md bg-accent text-accent-fg transition hover:brightness-110"
>
<MicIcon className="h-3.5 w-3.5" />
</button>
</div>
);
}
function pickMime(): string | null {
const candidates = [
'audio/webm;codecs=opus',
'audio/webm',
'audio/ogg;codecs=opus',
'audio/mp4',
];
for (const c of candidates) {
if (typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(c)) return c;
}
return null;
}
function extFor(mime: string): string {
if (mime.includes('webm')) return 'webm';
if (mime.includes('ogg')) return 'ogg';
if (mime.includes('mp4')) return 'm4a';
return 'bin';
}
function formatTime(sec: number): string {
const m = Math.floor(sec / 60);
const s = sec % 60;
return m + ':' + s.toString().padStart(2, '0');
}
+90
View File
@@ -409,6 +409,96 @@ export function SendIcon(props: IconProps) {
);
}
export function ArchiveIcon(props: IconProps) {
return (
<Base {...props}>
<rect x="3" y="4" width="18" height="5" rx="1" />
<path d="M5 9v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9" />
<path d="M10 13h4" />
</Base>
);
}
export function BellIcon(props: IconProps) {
return (
<Base {...props}>
<path d="M6 8a6 6 0 1 1 12 0c0 4 1.5 5 2 6H4c.5-1 2-2 2-6Z" />
<path d="M9.5 18a2.5 2.5 0 0 0 5 0" />
</Base>
);
}
export function BellOffIcon(props: IconProps) {
return (
<Base {...props}>
<path d="M9.5 18a2.5 2.5 0 0 0 5 0" />
<path d="M13.73 4A2 2 0 0 0 10 4" />
<path d="M18 8c0 1-.1 1.9-.2 2.7" />
<path d="M4 4 20 20" />
<path d="M6 8a6 6 0 0 1 .2-1.7" />
<path d="M4 18h13.5L18 17.4c.5-1 2-2 2-6" />
</Base>
);
}
export function MoreVerticalIcon(props: IconProps) {
return (
<Base {...props}>
<circle cx="12" cy="5" r="1.5" />
<circle cx="12" cy="12" r="1.5" />
<circle cx="12" cy="19" r="1.5" />
</Base>
);
}
export function HeadphonesIcon(props: IconProps) {
return (
<Base {...props}>
<path d="M3 14v-2a9 9 0 0 1 18 0v2" />
<path d="M3 14h4v7H5a2 2 0 0 1-2-2Z" />
<path d="M21 14h-4v7h2a2 2 0 0 0 2-2Z" />
</Base>
);
}
export function HeadphonesOffIcon(props: IconProps) {
return (
<Base {...props}>
<path d="M3 14v-2a9 9 0 0 1 11.3-8.7" />
<path d="M21 14v-2a9 9 0 0 0-1.5-5" />
<path d="M3 14h4v7H5a2 2 0 0 1-2-2Z" />
<path d="M21 14h-4v7h2a2 2 0 0 0 2-2Z" />
<path d="M3 3 21 21" />
</Base>
);
}
export function ReplyIcon(props: IconProps) {
return (
<Base {...props}>
<polyline points="9 17 4 12 9 7" />
<path d="M20 18v-2a4 4 0 0 0-4-4H4" />
</Base>
);
}
export function ForwardIcon(props: IconProps) {
return (
<Base {...props}>
<polyline points="15 17 20 12 15 7" />
<path d="M4 18v-2a4 4 0 0 1 4-4h12" />
</Base>
);
}
export function ChevronUpIcon(props: IconProps) {
return (
<Base {...props}>
<polyline points="18 15 12 9 6 15" />
</Base>
);
}
export function AddUserIcon(props: IconProps) {
return (
<Base {...props}>
+35 -23
View File
@@ -20,6 +20,7 @@ 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;
@@ -54,30 +55,34 @@ export function AuthProvider({ children }: { children: ReactNode }) {
(async () => {
const { data: sessionRes } = await supabase.auth.getSession();
if (cancelled) return;
if (sessionRes.session) {
const { error } = await supabase.auth.getUser();
if (cancelled) return;
if (error) {
const status = (error as { status?: number }).status;
if (status === 401 || status === 403) {
// Token genuinely invalid — wipe.
await supabase.auth.signOut({ scope: 'local' }).catch(() => {
/* ignore */
});
setSession(null);
} else {
// Network / server unreachable — keep cached session, let reads
// fail gracefully and recover when the stack is back.
console.warn('auth.getUser failed, keeping cached session:', error);
setSession(sessionRes.session);
}
} else {
setSession(sessionRes.session);
}
} else {
setSession(null);
}
// 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);
@@ -131,6 +136,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
});
}, [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]);
const signOut = useCallback(async () => {
await supabaseSignOut(supabase);
}, []);
+312 -41
View File
@@ -40,15 +40,20 @@ import { getPttSettings, subscribePttSettings } from '../lib/pttSettings';
import {
getAudioQualityParams,
getAudioSettings,
updateAudioSettings,
} from '../lib/audioSettings';
import {
createCallE2EE,
getCallE2EESettings,
isE2EESupported,
} from '../lib/callE2EE';
import { getParticipantVolume } from '../lib/participantVolumes';
import {
type DisplaySurfaceHint,
getPresetParams,
getScreenShareSettings,
type ScreenSharePreset,
updateScreenShareSettings,
} from '../lib/screenShareSettings';
import { devLocalSecretStore } from '../lib/secretStore';
import { supabase } from '../lib/supabase';
@@ -101,6 +106,10 @@ interface CallContextValue {
isMuted: boolean;
isE2EEActive: boolean;
isScreenSharing: boolean;
isCameraEnabled: boolean;
isDeafened: boolean;
/** identity -> their deafen state, received via data channel. */
remoteDeafen: Record<string, boolean>;
// Zero or more remote screen shares (LiveKit supports multiple simultaneous).
remoteScreenShares: RemoteScreenShare[];
// Remembers the conversation of the last call we left so a sidebar widget
@@ -112,14 +121,30 @@ interface CallContextValue {
// Actions:
startCall: (conversationId: string, mediaKind?: CallKind) => Promise<void>;
joinActiveCall: (conversationId: string, mediaKind?: CallKind) => Promise<void>;
acceptIncoming: () => Promise<void>;
acceptIncoming: (override?: CallKind) => Promise<void>;
rejectIncoming: () => void;
hangup: () => Promise<void>;
toggleMute: () => void;
toggleScreenShare: () => Promise<void>;
startScreenShare: (
overrides?: Partial<{
preset: ScreenSharePreset;
displaySurface: DisplaySurfaceHint;
framerate: number | null;
}>,
) => Promise<void>;
stopScreenShare: () => Promise<void>;
toggleCamera: () => Promise<void>;
toggleDeafen: () => void;
dismissLastCall: () => void;
setCallMode: (mode: CallMode) => void;
setFocusedId: (id: string | null) => void;
// Runtime mic switch. Persists choice so subsequent calls reuse it, and
// hot-swaps the input on an active call without a reconnect.
setAudioInputDevice: (deviceId: string | null) => Promise<void>;
// Runtime speaker/headphone switch. Persists + applies setSinkId to all
// currently-attached remote-audio elements.
setAudioOutputDevice: (deviceId: string | null) => Promise<void>;
}
const CallContext = createContext<CallContextValue | null>(null);
@@ -142,6 +167,8 @@ export function CallProvider({ children }: { children: ReactNode }) {
const [isMuted, setIsMuted] = useState(false);
const [isE2EEActive, setIsE2EEActive] = useState(false);
const [isScreenSharing, setIsScreenSharing] = useState(false);
const [isCameraEnabled, setIsCameraEnabled] = useState(false);
const [isDeafened, setIsDeafened] = useState(false);
const [remoteScreenShares, setRemoteScreenShares] = useState<RemoteScreenShare[]>([]);
const [lastCallConversationId, setLastCallConversationId] = useState<string | null>(null);
const [callMode, setCallModeState] = useState<CallMode>('grid');
@@ -160,6 +187,10 @@ export function CallProvider({ children }: { children: ReactNode }) {
// For 1:1 calls the set has one entry so behaviour is unchanged; for
// groups, a single reject doesn't terminate the call while others ring.
const pendingPeersRef = useRef<Set<string>>(new Set());
// identity -> their current deafen state. Populated via LiveKit data
// channel messages ({ type: 'presence', deafened: bool }). Exposed as
// state so consumer components re-render on change.
const [remoteDeafen, setRemoteDeafen] = useState<Record<string, boolean>>({});
const stateRef = useRef<CallState>(state);
stateRef.current = state;
// Keep latest conversations accessible from signal-channel closures without
@@ -236,6 +267,10 @@ export function CallProvider({ children }: { children: ReactNode }) {
setRemoteParticipants([]);
setRemoteScreenShares([]);
setIsScreenSharing(false);
setIsCameraEnabled(false);
setIsDeafened(false);
deafenedActive = false;
setRemoteDeafen({});
setIsE2EEActive(false);
const pres = presenceChannelRef.current;
@@ -456,6 +491,45 @@ export function CallProvider({ children }: { children: ReactNode }) {
}
});
// Mute/unmute a camera doesn't publish or unpublish — the publication
// stays, just its `muted` flag flips. Without this listener, remote
// participants who toggle video mid-call appear as a frozen last frame
// or (worse) a black tile on every other client. Bumping the
// remoteParticipants state reference forces buildTiles to re-read
// `isCameraEnabled` and swap to the avatar placeholder.
const bumpParticipants = () => {
setRemoteParticipants(Array.from(r.remoteParticipants.values()));
};
r.on(RoomEvent.TrackMuted, bumpParticipants);
r.on(RoomEvent.TrackUnmuted, bumpParticipants);
// Remote deafen state is broadcast via the LiveKit data channel. We
// store incoming states in `remoteDeafenMapRef` and bump participants
// so buildTiles re-reads it.
r.on(
RoomEvent.DataReceived,
(payload: Uint8Array, participant?: RemoteParticipant | undefined) => {
if (!participant?.identity) return;
try {
const text = new TextDecoder().decode(payload);
const msg = JSON.parse(text) as { type?: string; deafened?: boolean };
if (msg.type === 'presence' && typeof msg.deafened === 'boolean') {
const id: string = participant.identity;
const deafened: boolean = msg.deafened;
setRemoteDeafen((prev) => {
if (prev[id] === deafened) return prev;
return { ...prev, [id]: deafened };
});
}
} catch {
/* ignore malformed */
}
},
);
// When someone joins, re-send our current deafen state so they know.
r.on(RoomEvent.ParticipantConnected, () => {
void broadcastPresence(r, deafenedActive);
});
// Track my own screen-share state via LocalTrack events so the toggle
// stays in sync if the user stops sharing via the browser's native UI.
r.on(RoomEvent.LocalTrackPublished, (publication) => {
@@ -482,12 +556,16 @@ export function CallProvider({ children }: { children: ReactNode }) {
setIsE2EEActive(false);
}
try {
const inputId = getAudioSettings().inputDeviceId;
await r.localParticipant.setMicrophoneEnabled(true, {
echoCancellation: aParams.echoCancellation,
noiseSuppression: aParams.noiseSuppression,
autoGainControl: aParams.autoGainControl,
channelCount: aParams.stereo ? 2 : 1,
sampleRate: aParams.sampleRateHz,
// Plain string maps to `ideal` — if the device is gone we fall back
// to OS default instead of throwing NotFoundError.
...(inputId ? { deviceId: inputId } : {}),
});
} catch (micErr: unknown) {
console.error('setMicrophoneEnabled failed', micErr);
@@ -495,6 +573,7 @@ export function CallProvider({ children }: { children: ReactNode }) {
if (mediaKind === 'video') {
try {
await r.localParticipant.setCameraEnabled(true);
setIsCameraEnabled(true);
} catch (camErr: unknown) {
console.error('setCameraEnabled failed', camErr);
}
@@ -639,23 +718,31 @@ export function CallProvider({ children }: { children: ReactNode }) {
[myId, joinRoom, disconnectRoom],
);
const acceptIncoming = useCallback(async () => {
const s = stateRef.current;
if (s.kind !== 'incoming' || !myId) return;
const { callId, conversationId, mediaKind } = s;
everConnectedRef.current = false;
setLastCallConversationId(null);
setState({ kind: 'connecting', callId, conversationId, mediaKind });
try {
await joinRoom(conversationId, mediaKind, callId);
} catch (err: unknown) {
setState({
kind: 'error',
message: err instanceof Error ? err.message : 'join failed',
});
await disconnectRoom();
}
}, [myId, joinRoom, disconnectRoom]);
const acceptIncoming = useCallback(
async (override?: CallKind) => {
const s = stateRef.current;
if (s.kind !== 'incoming' || !myId) return;
const { callId, conversationId } = s;
// Caller's `mediaKind` is the INVITE kind (what they started with). The
// receiver can accept with audio even if the caller rang as video, or
// upgrade an audio invite to video on accept. `override` picks the
// receiver's choice.
const mediaKind: CallKind = override ?? s.mediaKind;
everConnectedRef.current = false;
setLastCallConversationId(null);
setState({ kind: 'connecting', callId, conversationId, mediaKind });
try {
await joinRoom(conversationId, mediaKind, callId);
} catch (err: unknown) {
setState({
kind: 'error',
message: err instanceof Error ? err.message : 'join failed',
});
await disconnectRoom();
}
},
[myId, joinRoom, disconnectRoom],
);
const rejectIncoming = useCallback(() => {
const s = stateRef.current;
@@ -729,33 +816,129 @@ export function CallProvider({ children }: { children: ReactNode }) {
});
}, []);
const toggleScreenShare = useCallback(async () => {
const startScreenShare = useCallback(
async (
overrides?: Partial<{
preset: ScreenSharePreset;
displaySurface: DisplaySurfaceHint;
framerate: number | null;
}>,
) => {
const r = roomRef.current;
if (!r) return;
const lp = r.localParticipant;
if (lp.isScreenShareEnabled) return;
// Persist the user's choice so subsequent shares use the same config
// without re-opening the picker unless they want to change something.
const settings = getScreenShareSettings();
const preset = overrides?.preset ?? settings.preset;
const displaySurface =
overrides?.displaySurface !== undefined
? overrides.displaySurface
: settings.displaySurface;
const framerateOverride =
overrides?.framerate !== undefined
? overrides.framerate
: settings.framerateOverride;
updateScreenShareSettings({ preset, displaySurface, framerateOverride });
const ssParams = getPresetParams(preset);
const fps = framerateOverride ?? ssParams.framerate;
try {
await lp.setScreenShareEnabled(true, {
audio: false,
...(ssParams.dims
? {
resolution: {
width: ssParams.dims.width,
height: ssParams.dims.height,
frameRate: fps,
},
}
: {
resolution: {
width: 3840,
height: 2160,
frameRate: fps,
},
}),
// Hints the OS picker to pre-filter by source kind. `null` = no
// filter (show both). Cast because TS lib.dom doesn't know the
// field yet on all branches.
...(displaySurface
? ({ displaySurface } as { displaySurface: DisplaySurfaceHint })
: {}),
contentHint: 'detail',
});
setIsScreenSharing(true);
} catch (err: unknown) {
console.error('setScreenShareEnabled failed', err);
}
},
[],
);
const stopScreenShare = useCallback(async () => {
const r = roomRef.current;
if (!r) return;
const lp = r.localParticipant;
const nextOn = !lp.isScreenShareEnabled;
if (!lp.isScreenShareEnabled) return;
try {
const ssParams = getPresetParams(getScreenShareSettings().preset);
await lp.setScreenShareEnabled(nextOn, {
audio: false,
// Omitting `resolution` lets the browser return native source size —
// best possible input quality. Fixed presets pass explicit dims so
// the encoder has a predictable target.
...(ssParams.dims
? {
resolution: {
width: ssParams.dims.width,
height: ssParams.dims.height,
frameRate: ssParams.framerate,
},
}
: {}),
contentHint: 'detail',
});
setIsScreenSharing(nextOn);
await lp.setScreenShareEnabled(false);
setIsScreenSharing(false);
} catch (err: unknown) {
console.error('setScreenShareEnabled failed', err);
// User cancelled or permission denied — leave state as-is.
console.error('stopScreenShare failed', err);
}
}, []);
// Legacy toggle kept for convenience elsewhere — opens/closes with the
// last-persisted settings and no picker UI.
const toggleScreenShare = useCallback(async () => {
const r = roomRef.current;
if (!r) return;
if (r.localParticipant.isScreenShareEnabled) {
await stopScreenShare();
} else {
await startScreenShare();
}
}, [startScreenShare, stopScreenShare]);
const toggleDeafen = useCallback(() => {
setIsDeafened((prev) => {
const next = !prev;
deafenedActive = next;
// Apply to every currently-attached remote-audio element. Fresh tracks
// that attach during a deafened session are muted in attachTrack above.
const els = document.querySelectorAll<HTMLAudioElement>(
'audio[data-livekit-track]',
);
els.forEach((el) => {
el.muted = next;
});
// Broadcast via LiveKit data channel so peers' UIs can show the
// headphones-off badge. Data channel works on any LiveKit server
// version, unlike `setAttributes` which requires a newer server.
const r = roomRef.current;
if (r) void broadcastPresence(r, next);
return next;
});
}, []);
const toggleCamera = useCallback(async () => {
const r = roomRef.current;
if (!r) return;
const lp = r.localParticipant;
const nextOn = !lp.isCameraEnabled;
try {
await lp.setCameraEnabled(nextOn);
setIsCameraEnabled(nextOn);
} catch (err: unknown) {
console.error('setCameraEnabled failed', err);
// Permission denied / no camera — keep state in sync with actual
// publication state so the button doesn't lie.
setIsCameraEnabled(lp.isCameraEnabled);
}
}, []);
@@ -973,6 +1156,46 @@ export function CallProvider({ children }: { children: ReactNode }) {
setFocusedIdState(id);
}, []);
const setAudioInputDevice = useCallback(async (deviceId: string | null) => {
updateAudioSettings({ inputDeviceId: deviceId });
const r = roomRef.current;
if (!r) return;
try {
// LiveKit API: `switchActiveDevice(kind, deviceId)` hot-swaps without a
// reconnect. Pass empty string or `default` to revert to OS default.
await r.switchActiveDevice('audioinput', deviceId ?? 'default');
} catch (err: unknown) {
console.error('switchActiveDevice(audioinput) failed', err);
}
}, []);
const setAudioOutputDevice = useCallback(async (deviceId: string | null) => {
updateAudioSettings({ outputDeviceId: deviceId });
const sinkId = deviceId ?? '';
// Apply to every <audio> element we've attached to the body. LiveKit's
// switchActiveDevice only tracks elements it attached itself; our custom
// appendChild path bypasses that, so we iterate and setSinkId manually.
const els = document.querySelectorAll<HTMLAudioElement>(
'audio[data-livekit-track]',
);
for (const el of Array.from(els)) {
if (typeof el.setSinkId !== 'function') continue;
try {
await el.setSinkId(sinkId);
} catch (err: unknown) {
console.warn('setSinkId on audio element failed', err);
}
}
const r = roomRef.current;
if (r) {
try {
await r.switchActiveDevice('audiooutput', sinkId || 'default');
} catch (err: unknown) {
console.warn('switchActiveDevice(audiooutput) failed', err);
}
}
}, []);
// Reset UI call-mode state when the call leaves any active phase so the next
// call starts fresh at grid/unfocused.
useEffect(() => {
@@ -1003,6 +1226,9 @@ export function CallProvider({ children }: { children: ReactNode }) {
isMuted,
isE2EEActive,
isScreenSharing,
isCameraEnabled,
isDeafened,
remoteDeafen,
remoteScreenShares,
lastCallConversationId,
callMode,
@@ -1014,9 +1240,15 @@ export function CallProvider({ children }: { children: ReactNode }) {
hangup,
toggleMute,
toggleScreenShare,
startScreenShare,
stopScreenShare,
toggleCamera,
toggleDeafen,
dismissLastCall,
setCallMode,
setFocusedId,
setAudioInputDevice,
setAudioOutputDevice,
}),
[
state,
@@ -1025,6 +1257,9 @@ export function CallProvider({ children }: { children: ReactNode }) {
isMuted,
isE2EEActive,
isScreenSharing,
isCameraEnabled,
isDeafened,
remoteDeafen,
remoteScreenShares,
lastCallConversationId,
callMode,
@@ -1036,9 +1271,15 @@ export function CallProvider({ children }: { children: ReactNode }) {
hangup,
toggleMute,
toggleScreenShare,
startScreenShare,
stopScreenShare,
toggleCamera,
toggleDeafen,
dismissLastCall,
setCallMode,
setFocusedId,
setAudioInputDevice,
setAudioOutputDevice,
],
);
@@ -1051,10 +1292,26 @@ export function useCall(): CallContextValue {
return ctx;
}
// Shared flag so attachTrack (called from LiveKit event listeners, outside the
// React component) can apply the current deafen state to freshly-attached
// audio elements. Toggled by toggleDeafen in sync with the React state.
let deafenedActive = false;
async function broadcastPresence(room: Room, deafened: boolean): Promise<void> {
try {
const payload = new TextEncoder().encode(
JSON.stringify({ type: 'presence', deafened }),
);
await room.localParticipant.publishData(payload, { reliable: true });
} catch (err: unknown) {
console.warn('broadcastPresence failed', err);
}
}
function attachTrack(
track: RemoteTrack,
_publication: RemoteTrackPublication,
_participant: RemoteParticipant,
participant: RemoteParticipant,
): void {
if (track.kind === Track.Kind.Audio) {
const audio = track.attach();
@@ -1062,7 +1319,21 @@ function attachTrack(
audio.autoplay = true;
audio.setAttribute('playsinline', 'true');
audio.setAttribute('data-livekit-track', track.sid ?? '');
if (participant.identity) {
audio.setAttribute('data-participant', participant.identity);
audio.volume = getParticipantVolume(participant.identity);
}
if (deafenedActive) audio.muted = true;
document.body.appendChild(audio);
// Apply persisted sinkId so the element routes to the user's chosen
// speaker/headphone from the start (LiveKit's own `switchActiveDevice`
// doesn't track custom-appended elements).
const sinkId = getAudioSettings().outputDeviceId;
if (sinkId && typeof audio.setSinkId === 'function') {
void audio.setSinkId(sinkId).catch((err: unknown) => {
console.warn('setSinkId on attach failed', err);
});
}
}
}
// Video is handled later in M2.6/M3 by a dedicated <video> element.
@@ -1,4 +1,8 @@
import { type ConversationSummary, listConversations } from '@chat-app/shared/chat';
import {
type ConversationSummary,
isConversationMuted,
listConversations,
} from '@chat-app/shared/chat';
import {
createContext,
type ReactNode,
@@ -95,7 +99,9 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
return;
}
try {
setLoading(true);
// Only flag loading on initial fetch so background re-syncs (visibility
// change, online event) don't blank the list each time.
setLoading((prev) => (conversationsRef.current.length === 0 ? true : prev));
const convs = await listConversations(supabase);
setConversations(convs);
const entries = await Promise.all(
@@ -151,6 +157,15 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
.on('postgres_changes', { event: '*', schema: 'public', table: 'conversations' }, () => {
void refresh();
})
.on(
'postgres_changes',
{ event: 'UPDATE', schema: 'public', table: 'profiles' },
() => {
// Peer updated their profile (e.g. uploaded avatar / changed name).
// Re-pull conversations so members[].profile picks up the new data.
void refresh();
},
)
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'messages' },
@@ -168,10 +183,15 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
...prev,
[row.conversation_id]: (prev[row.conversation_id] ?? 0) + 1,
}));
// Notification sound + OS notification — respect DND. Body stays
// empty because message content is E2E-encrypted and only
// decryptable in the conversation view (not at this hook level).
if (presenceRef.current !== 'dnd') {
// Notification sound + OS notification — respect DND and
// per-conversation mute. Body stays empty because message
// content is E2E-encrypted and only decryptable in the
// conversation view (not at this hook level).
const convForMute = conversationsRef.current.find(
(c) => c.id === row.conversation_id,
);
const muted = isConversationMuted(convForMute?.mutedUntil ?? null);
if (presenceRef.current !== 'dnd' && !muted) {
playNotificationTone();
const conv = conversationsRef.current.find(
(c) => c.id === row.conversation_id,
@@ -195,7 +215,34 @@ export function ConversationsProvider({ children }: { children: ReactNode }) {
)
.subscribe();
// Windows WebView2 aggressively throttles background WebSockets and
// sometimes drops events entirely while the window is minimised. Force a
// refresh + realtime reconnect on visibility/focus regain so we never
// leave stale conversation lists on a Windows client after the user
// returns to the app.
let lastAwakeRefresh = 0;
const AWAKE_THROTTLE_MS = 30_000;
const onAwake = () => {
if (document.visibilityState !== 'visible') return;
const now = Date.now();
if (now - lastAwakeRefresh < AWAKE_THROTTLE_MS) return;
lastAwakeRefresh = now;
void refresh();
try {
// If the socket got wedged during background throttle, a no-op
// unsubscribe+resubscribe brings it back. `subscribe()` on an already
// joined channel is a no-op so this is safe.
channel.subscribe();
} catch {
/* ignore — already live */
}
};
document.addEventListener('visibilitychange', onAwake);
window.addEventListener('online', onAwake);
return () => {
document.removeEventListener('visibilitychange', onAwake);
window.removeEventListener('online', onAwake);
void supabase.removeChannel(channel);
};
}, [myId, refresh, markRead]);
+14 -2
View File
@@ -44,10 +44,22 @@ export async function checkForUpdate(): Promise<UpdateState> {
error: null,
};
} catch (err: unknown) {
console.warn('checkForUpdate failed', err);
// Swallow "no release on GitHub yet" / network-unreachable cases silently.
// The updater endpoint serves `latest.json` from GitHub releases; a fresh
// repo or offline machine produces a generic "Could not fetch a valid
// release JSON" error that has no actionable information for the user —
// logging it on every launch just pollutes the console.
const msg = err instanceof Error ? err.message : String(err);
const benign =
/could not fetch a valid release json|network|timed? out|failed to fetch|connection/i.test(
msg,
);
if (!benign) {
console.warn('checkForUpdate failed', err);
}
return {
...IDLE_UPDATE_STATE,
error: err instanceof Error ? err.message : 'update check failed',
error: benign ? null : msg,
};
}
}
+17
View File
@@ -9,10 +9,19 @@ export type AudioQuality = 'voice' | 'hifi';
export interface AudioSettings {
quality: AudioQuality;
// Preferred input deviceId from enumerateDevices. null = use browser default
// (whatever the OS points at). Persisted across sessions, so "grandma's
// mic is default" stays even after browser picks the wrong device.
inputDeviceId: string | null;
// Preferred output (speaker/headphone) deviceId. null = system default.
// Applied to every <audio> element we attach via HTMLMediaElement.setSinkId.
outputDeviceId: string | null;
}
const DEFAULTS: AudioSettings = {
quality: 'voice',
inputDeviceId: null,
outputDeviceId: null,
};
export interface AudioQualityParams {
@@ -73,6 +82,14 @@ function read(): AudioSettings {
const parsed = JSON.parse(raw) as Partial<AudioSettings>;
cached = {
quality: isQuality(parsed.quality) ? parsed.quality : DEFAULTS.quality,
inputDeviceId:
typeof parsed.inputDeviceId === 'string' && parsed.inputDeviceId.length > 0
? parsed.inputDeviceId
: DEFAULTS.inputDeviceId,
outputDeviceId:
typeof parsed.outputDeviceId === 'string' && parsed.outputDeviceId.length > 0
? parsed.outputDeviceId
: DEFAULTS.outputDeviceId,
};
return cached;
} catch {
+1 -1
View File
@@ -1,5 +1,5 @@
import type { CryptoBackend } from '@chat-app/shared/crypto';
import _sodium from 'libsodium-wrappers';
import _sodium from 'libsodium-wrappers-sumo';
// Build the libsodium-backed CryptoBackend. Awaits the WASM ready-gate once,
// then returns a synchronous implementation of the CryptoBackend contract.
+1 -1
View File
@@ -25,7 +25,7 @@ export function readLocalDeviceId(userId: string): string | null {
return window.localStorage.getItem(deviceIdStorageKey(userId));
}
function writeLocalDeviceId(userId: string, deviceId: string): void {
export function writeLocalDeviceId(userId: string, deviceId: string): void {
window.localStorage.setItem(deviceIdStorageKey(userId), deviceId);
}
+106 -1
View File
@@ -1,5 +1,5 @@
import { getCryptoBackend } from '@chat-app/shared/crypto';
import sodium from 'libsodium-wrappers';
import sodium from 'libsodium-wrappers-sumo';
// Encrypts/decrypts the device private key with a user-provided passphrase
// so the backup string can be safely written down or stored in a password
@@ -91,3 +91,108 @@ export async function importDeviceKey(
s.memzero(key);
}
}
// Full-device backup. Wraps userId + deviceId + privateKey in a JSON payload
// before encrypting, so a restore flow can re-seed localStorage + vault + server
// device row without requiring the user to remember IDs.
export interface DeviceBackupPayload {
v: 2;
userId: string;
deviceId: string;
privateKeyB64: string;
}
export async function exportDeviceBackup(
params: {
userId: string;
deviceId: string;
privateKey: Uint8Array;
passphrase: string;
},
): Promise<string> {
const payload: DeviceBackupPayload = {
v: 2,
userId: params.userId,
deviceId: params.deviceId,
privateKeyB64: b64url(params.privateKey),
};
const bytes = new TextEncoder().encode(JSON.stringify(payload));
return exportDeviceKey(bytes, params.passphrase);
}
export async function importDeviceBackup(
backup: string,
passphrase: string,
): Promise<DeviceBackupPayload> {
const plain = await importDeviceKey(backup, passphrase);
const text = new TextDecoder().decode(plain);
try {
const obj = JSON.parse(text) as DeviceBackupPayload;
if (obj && obj.v === 2 && obj.userId && obj.deviceId && obj.privateKeyB64) {
return obj;
}
} catch {
/* fall through */
}
throw new Error('Backup format not supported — v2 expected');
}
export function decodePrivateKeyFromBackup(payload: DeviceBackupPayload): Uint8Array {
return unb64url(payload.privateKeyB64);
}
// ---------------------------------------------------------------------------
// Recovery code
// ---------------------------------------------------------------------------
//
// Generates a high-entropy code shown to the user once at backup time. The
// same payload is encrypted twice — once with the user's passphrase, once
// with the recovery code — so either string can decrypt the device key.
//
// The recovery code is 24 chars from a 32-symbol alphabet (no ambiguous
// characters), grouped as 4×6. ~120 bits of entropy.
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
export interface BackupBundle {
passphraseBackup: string;
recoveryBackup: string;
recoveryCode: string;
}
export async function exportDeviceBackupWithRecovery(params: {
userId: string;
deviceId: string;
privateKey: Uint8Array;
passphrase: string;
}): Promise<BackupBundle> {
const recoveryCode = await generateRecoveryCode();
const [passphraseBackup, recoveryBackup] = await Promise.all([
exportDeviceBackup(params),
exportDeviceBackup({ ...params, passphrase: recoveryCode }),
]);
return { passphraseBackup, recoveryBackup, recoveryCode };
}
async function generateRecoveryCode(): Promise<string> {
const s = await ensureSodium();
const raw = s.randombytes_buf(24);
let out = '';
for (let i = 0; i < raw.length; i++) {
out += RECOVERY_ALPHABET[raw[i]! % RECOVERY_ALPHABET.length];
if ((i + 1) % 6 === 0 && i !== raw.length - 1) out += '-';
}
return out;
}
// Normalizes a user-typed recovery code: strips dashes/spaces, uppercases,
// maps look-alike characters. Lets users enter the code with imperfect
// spacing without rejecting valid input.
export function normalizeRecoveryCode(input: string): string {
return input
.toUpperCase()
.replace(/[\s-]/g, '')
.split('')
.filter((c) => RECOVERY_ALPHABET.includes(c))
.join('');
}
+164
View File
@@ -0,0 +1,164 @@
// Offline text-message outbox.
//
// When `sendEncryptedMessage` fails (network loss, server 5xx, transient
// realtime hiccups) we stash the plaintext in localStorage keyed by
// conversation. The UI shows it inline with a "sending…" indicator; the
// drain loop retries with exponential backoff until it lands.
//
// Attachments are intentionally NOT queued — they're too large to persist
// and require server-side upload that can't be deferred reliably. The
// composer surfaces an immediate error for those.
const STORAGE_KEY = 'chat.outbox.v1';
const MAX_ATTEMPTS = 8;
export interface OutboxItem {
/** Local-only id (never collides with server UUIDs). */
id: string;
conversationId: string;
text: string;
replyToId: string | null;
createdAt: string;
attempts: number;
/** Timestamp of the next permitted send attempt. */
nextAttemptAt: string;
/** Last error message for surface in the UI. */
lastError: string | null;
}
type Store = Record<string, OutboxItem[]>; // keyed by conversationId
type Listener = (byConv: Store) => void;
function load(): Store {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const parsed: unknown = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return {};
const out: Store = {};
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
if (Array.isArray(v)) {
out[k] = v.filter((x): x is OutboxItem => isItem(x));
}
}
return out;
} catch {
return {};
}
}
function isItem(x: unknown): x is OutboxItem {
if (!x || typeof x !== 'object') return false;
const o = x as Record<string, unknown>;
return (
typeof o.id === 'string' &&
typeof o.conversationId === 'string' &&
typeof o.text === 'string' &&
typeof o.createdAt === 'string'
);
}
let store: Store = load();
const listeners = new Set<Listener>();
function persist(): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(store));
} catch {
/* quota exceeded — ignore; in-memory queue still retries */
}
}
function notify(): void {
for (const fn of listeners) fn(store);
}
export function subscribeOutbox(fn: Listener): () => void {
listeners.add(fn);
fn(store);
return () => {
listeners.delete(fn);
};
}
export function getOutbox(conversationId: string): OutboxItem[] {
return store[conversationId] ?? [];
}
export function enqueueOutbox(args: {
conversationId: string;
text: string;
replyToId: string | null;
error: string | null;
}): OutboxItem {
const item: OutboxItem = {
id: 'local-' + crypto.randomUUID(),
conversationId: args.conversationId,
text: args.text,
replyToId: args.replyToId,
createdAt: new Date().toISOString(),
attempts: 0,
nextAttemptAt: new Date().toISOString(),
lastError: args.error,
};
const bucket = store[args.conversationId] ?? [];
store = { ...store, [args.conversationId]: [...bucket, item] };
persist();
notify();
return item;
}
export function removeOutbox(conversationId: string, id: string): void {
const bucket = store[conversationId];
if (!bucket) return;
const next = bucket.filter((x) => x.id !== id);
if (next.length === bucket.length) return;
if (next.length === 0) {
const copy = { ...store };
delete copy[conversationId];
store = copy;
} else {
store = { ...store, [conversationId]: next };
}
persist();
notify();
}
export function markAttempt(
conversationId: string,
id: string,
error: string | null,
): OutboxItem | null {
const bucket = store[conversationId];
if (!bucket) return null;
const idx = bucket.findIndex((x) => x.id === id);
if (idx < 0) return null;
const prev = bucket[idx]!;
const attempts = prev.attempts + 1;
// Exponential backoff: 2^n seconds, capped at 60s.
const delaySec = Math.min(60, Math.pow(2, attempts));
const next: OutboxItem = {
...prev,
attempts,
lastError: error,
nextAttemptAt: new Date(Date.now() + delaySec * 1000).toISOString(),
};
const nextBucket = [...bucket];
nextBucket[idx] = next;
store = { ...store, [conversationId]: nextBucket };
persist();
notify();
return next;
}
export function shouldGiveUp(item: OutboxItem): boolean {
return item.attempts >= MAX_ATTEMPTS;
}
export function isDue(item: OutboxItem): boolean {
return new Date(item.nextAttemptAt).getTime() <= Date.now();
}
export function allConversationsWithItems(): string[] {
return Object.keys(store);
}
+27 -2
View File
@@ -7,10 +7,31 @@ import {
import { isTauriRuntime } from './globalShortcut';
// Tracks whether permission has already been requested this session so we
// don't spam the OS prompt. Actual permission state lives in the OS.
// don't spam the OS prompt. Actual permission state lives in the OS, but we
// also persist a "we've asked" marker in localStorage so reloads don't
// re-request (OS would block anyway after denial, but calling it every reload
// triggers noisy plugin warnings on some platforms).
let permissionChecked = false;
let permissionGranted = false;
const ASKED_KEY = 'chatapp.notif.asked';
function readAskedMarker(): boolean {
try {
return window.localStorage.getItem(ASKED_KEY) === '1';
} catch {
return false;
}
}
function writeAskedMarker(): void {
try {
window.localStorage.setItem(ASKED_KEY, '1');
} catch {
/* quota / private mode */
}
}
export async function ensureNotificationPermission(): Promise<boolean> {
if (permissionChecked) return permissionGranted;
permissionChecked = true;
@@ -21,9 +42,13 @@ export async function ensureNotificationPermission(): Promise<boolean> {
}
try {
let granted = await isPermissionGranted();
if (!granted) {
if (!granted && !readAskedMarker()) {
// First-install: prompt the user once. After this we remember via the
// marker and never re-prompt — the user can re-enable later via OS
// system settings if they change their mind.
const result = await requestPermission();
granted = result === 'granted';
writeAskedMarker();
}
permissionGranted = granted;
} catch (err: unknown) {
@@ -0,0 +1,91 @@
// Per-participant output volume overrides. Values are 0..1 (HTMLMediaElement
// scale). Persisted so the user's mixing choices survive reconnects.
//
// The store is intentionally tiny — a flat Record keyed by LiveKit identity
// (our `userId`). `attachTrack` reads from here when a remote audio track
// first lands; live changes are pushed to any already-attached audio
// elements via the `data-participant` attribute selector.
const STORAGE_KEY = 'call.participantVolumes.v1';
const DEFAULT_VOLUME = 1;
type VolumeMap = Record<string, number>;
type Listener = (map: VolumeMap) => void;
function load(): VolumeMap {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const parsed: unknown = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') return {};
const out: VolumeMap = {};
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof v === 'number' && Number.isFinite(v)) {
out[k] = clamp(v);
}
}
return out;
} catch {
return {};
}
}
function clamp(v: number): number {
if (v < 0) return 0;
if (v > 1) return 1;
return v;
}
let current: VolumeMap = load();
const listeners = new Set<Listener>();
function persist(): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(current));
} catch {
/* ignore quota */
}
}
function notify(): void {
for (const fn of listeners) fn(current);
}
export function getParticipantVolume(userId: string): number {
return current[userId] ?? DEFAULT_VOLUME;
}
export function setParticipantVolume(userId: string, volume: number): void {
const next = clamp(volume);
if (next === (current[userId] ?? DEFAULT_VOLUME)) return;
current = { ...current, [userId]: next };
persist();
applyToAttachedElements(userId, next);
notify();
}
export function subscribeParticipantVolumes(fn: Listener): () => void {
listeners.add(fn);
return () => {
listeners.delete(fn);
};
}
// Apply a volume to any audio elements already attached for this user.
// Attached elements are tagged with `data-participant` in attachTrack.
function applyToAttachedElements(userId: string, volume: number): void {
const nodes = document.querySelectorAll<HTMLAudioElement>(
'audio[data-participant="' + cssEscape(userId) + '"]',
);
nodes.forEach((el) => {
el.volume = volume;
});
}
function cssEscape(v: string): string {
if (typeof (globalThis as { CSS?: { escape?: (s: string) => string } }).CSS
?.escape === 'function') {
return (globalThis as { CSS: { escape: (s: string) => string } }).CSS.escape(v);
}
return v.replace(/"/g, '\\"');
}
@@ -14,12 +14,22 @@ export type ScreenSharePreset =
| '1440p60'
| '4k60';
// Browser getDisplayMedia `displaySurface` hint. The OS picker honours this
// to pre-filter the source list (monitor = whole display, window = single
// window). `null` leaves everything selectable.
export type DisplaySurfaceHint = 'monitor' | 'window' | null;
export interface ScreenShareSettings {
preset: ScreenSharePreset;
displaySurface: DisplaySurfaceHint;
// User-chosen framerate. `null` falls back to preset's default.
framerateOverride: number | null;
}
const DEFAULTS: ScreenShareSettings = {
preset: 'auto',
displaySurface: null,
framerateOverride: null,
};
export interface PresetParams {
@@ -103,6 +113,14 @@ function read(): ScreenShareSettings {
const parsed = JSON.parse(raw) as Partial<ScreenShareSettings>;
cached = {
preset: isPreset(parsed.preset) ? parsed.preset : DEFAULTS.preset,
displaySurface:
parsed.displaySurface === 'monitor' || parsed.displaySurface === 'window'
? parsed.displaySurface
: DEFAULTS.displaySurface,
framerateOverride:
typeof parsed.framerateOverride === 'number' && parsed.framerateOverride > 0
? parsed.framerateOverride
: DEFAULTS.framerateOverride,
};
return cached;
} catch {
+9 -4
View File
@@ -1,7 +1,9 @@
import type { SecretStore } from '@chat-app/shared/auth';
import { exists, mkdir, readFile, rename, writeFile } from '@tauri-apps/plugin-fs';
import { appLocalDataDir } from '@tauri-apps/api/path';
import sodium from 'libsodium-wrappers';
// sumo variant ships crypto_pwhash (Argon2id). Standard `libsodium-wrappers`
// is the compact build without Argon2 — vault KDF would error otherwise.
import sodium from 'libsodium-wrappers-sumo';
// Encrypted single-file SecretStore for Tauri. Replaces the flaky
// tauri-plugin-stronghold implementation.
@@ -93,10 +95,13 @@ async function loadOrCreateVault(userId: string): Promise<VaultState> {
const path = joinPath(dir, fileName);
const tmpPath = path + '.tmp';
try {
// First-run: AppLocalData dir may not exist yet. `mkdir(recursive)` is
// idempotent on macOS/Linux, but we need to surface genuine permission
// errors (silent catch masked a previous bug where the dir was never
// created and every subsequent writeFile failed with ENOENT).
const dirExists = await exists(dir).catch(() => false);
if (!dirExists) {
await mkdir(dir, { recursive: true });
} catch {
/* parent likely already exists */
}
const fileExists = await exists(path).catch(() => false);
+151 -14
View File
@@ -1,10 +1,83 @@
import type { Participant, Room } from 'livekit-client';
import { RoomEvent } from 'livekit-client';
import type { AudioTrack, Participant, Room } from 'livekit-client';
import { ParticipantEvent, RoomEvent, Track } from 'livekit-client';
import { useEffect, useState } from 'react';
// Subscribe to LiveKit ActiveSpeakersChanged to drive the speaking-ring pulse
// on participant tiles. Returns the set of currently speaking identities
// (includes local participant when they're active).
// Real-time speaking ring driven by Web Audio API AnalyserNodes directly on
// each participant's audio MediaStreamTrack. LiveKit's own `audioLevel` +
// `isSpeaking` are updated by a background monitor (default ~1s) — too
// laggy. AnalyserNodes give us raw PCM at browser frame rate, so the ring
// lights up within one animation frame of actual speech.
//
// Hold time of 250ms prevents flicker between words / short pauses.
const POLL_MS = 50;
const HOLD_MS = 250;
const THRESHOLD = 0.03; // RMS on 0..1 — tuned against soft speech
const FFT_SIZE = 256;
interface Probe {
ctx: AudioContext;
analyser: AnalyserNode;
source: MediaStreamAudioSourceNode;
buf: Uint8Array;
// Cached MediaStreamTrack reference — if a publication swaps tracks
// (mute/unmute, device switch) we rebuild the node chain.
trackId: string;
}
function makeProbe(track: MediaStreamTrack): Probe | null {
try {
const ctx = new (window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)();
const stream = new MediaStream([track]);
const source = ctx.createMediaStreamSource(stream);
const analyser = ctx.createAnalyser();
analyser.fftSize = FFT_SIZE;
analyser.smoothingTimeConstant = 0.2;
source.connect(analyser);
return {
ctx,
analyser,
source,
buf: new Uint8Array(analyser.frequencyBinCount),
trackId: track.id,
};
} catch {
return null;
}
}
function destroyProbe(probe: Probe): void {
try {
probe.source.disconnect();
} catch {
/* ignore */
}
try {
void probe.ctx.close();
} catch {
/* ignore */
}
}
function sampleRms(probe: Probe): number {
// `getByteFrequencyData` types expect `Uint8Array<ArrayBuffer>` (no
// SharedArrayBuffer). Our `probe.buf` satisfies that at runtime; the cast
// sidesteps the TS lib signature quirk.
probe.analyser.getByteFrequencyData(probe.buf as Uint8Array<ArrayBuffer>);
let sum = 0;
for (let i = 0; i < probe.buf.length; i++) sum += probe.buf[i]!;
return sum / (probe.buf.length * 255);
}
function firstAudioTrack(p: Participant): AudioTrack | null {
const pubs = p.audioTrackPublications;
for (const pub of pubs.values()) {
if (pub.kind === Track.Kind.Audio && pub.track) {
return pub.track as AudioTrack;
}
}
return null;
}
export function useActiveSpeakers(room: Room | null): Set<string> {
const [ids, setIds] = useState<Set<string>>(() => new Set());
@@ -14,20 +87,84 @@ export function useActiveSpeakers(room: Room | null): Set<string> {
return;
}
const update = (speakers: Participant[]) => {
const next = new Set<string>();
for (const s of speakers) {
if (s.identity) next.add(s.identity);
const probes = new Map<string, Probe>();
const lastActive = new Map<string, number>();
const syncProbe = (p: Participant): void => {
if (!p.identity) return;
const track = firstAudioTrack(p);
const mst = track?.mediaStreamTrack ?? null;
const existing = probes.get(p.identity);
if (!mst) {
if (existing) {
destroyProbe(existing);
probes.delete(p.identity);
}
return;
}
setIds(next);
if (existing && existing.trackId === mst.id) return;
if (existing) destroyProbe(existing);
const probe = makeProbe(mst);
if (probe) probes.set(p.identity, probe);
};
// Seed from current state.
update(room.activeSpeakers ?? []);
const bind = (p: Participant): void => {
p.on(ParticipantEvent.TrackPublished, () => syncProbe(p));
p.on(ParticipantEvent.TrackUnpublished, () => syncProbe(p));
p.on(ParticipantEvent.TrackSubscribed, () => syncProbe(p));
p.on(ParticipantEvent.TrackUnsubscribed, () => syncProbe(p));
p.on(ParticipantEvent.TrackMuted, () => syncProbe(p));
p.on(ParticipantEvent.TrackUnmuted, () => syncProbe(p));
syncProbe(p);
};
bind(room.localParticipant);
room.remoteParticipants.forEach(bind);
const onConnected = (p: Participant) => bind(p);
const onDisconnected = (p: Participant) => {
if (!p.identity) return;
const probe = probes.get(p.identity);
if (probe) {
destroyProbe(probe);
probes.delete(p.identity);
}
lastActive.delete(p.identity);
};
room.on(RoomEvent.ParticipantConnected, onConnected);
room.on(RoomEvent.ParticipantDisconnected, onDisconnected);
const tick = () => {
// Defensively resync every tick — covers the gap where local mic
// finishes publishing between effect mount and the first
// TrackPublished event, and handles event misses on Tauri WebView.
syncProbe(room.localParticipant);
room.remoteParticipants.forEach(syncProbe);
const now = Date.now();
for (const [id, probe] of probes) {
if (sampleRms(probe) > THRESHOLD) lastActive.set(id, now);
}
const next = new Set<string>();
for (const [id, t] of lastActive) {
if (now - t <= HOLD_MS) next.add(id);
}
setIds((prev) => {
if (prev.size === next.size && Array.from(prev).every((v) => next.has(v))) {
return prev;
}
return next;
});
};
const interval = window.setInterval(tick, POLL_MS);
room.on(RoomEvent.ActiveSpeakersChanged, update);
return () => {
room.off(RoomEvent.ActiveSpeakersChanged, update);
window.clearInterval(interval);
room.off(RoomEvent.ParticipantConnected, onConnected);
room.off(RoomEvent.ParticipantDisconnected, onDisconnected);
for (const probe of probes.values()) destroyProbe(probe);
probes.clear();
};
}, [room]);
+256 -9
View File
@@ -13,6 +13,16 @@ import {
import { bytesToPgHex, pgBytesToBytes } from '@chat-app/shared/supabase';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
enqueueOutbox,
getOutbox,
isDue,
markAttempt,
type OutboxItem,
removeOutbox,
shouldGiveUp,
subscribeOutbox,
} from './messageOutbox';
import { devLocalSecretStore } from './secretStore';
import { supabase } from './supabase';
@@ -51,12 +61,28 @@ function rowToMessage(row: Record<string, unknown>): MessageWithCipher {
}
export function useConversationMessages({ conversationId, userId, deviceId }: Args): State & {
send: (text: string, images?: File[]) => Promise<void>;
send: (text: string, images?: File[], replyToId?: string | null) => Promise<void>;
refresh: () => Promise<void>;
pending: OutboxItem[];
retryPending: (id: string) => void;
cancelPending: (id: string) => void;
} {
const [state, setState] = useState<State>({ messages: [], loading: true, error: null });
const [pending, setPending] = useState<OutboxItem[]>(() =>
conversationId ? getOutbox(conversationId) : [],
);
const privateKeyRef = useRef<Uint8Array | null>(null);
useEffect(() => {
if (!conversationId) {
setPending([]);
return;
}
return subscribeOutbox((byConv) => {
setPending(byConv[conversationId] ?? []);
});
}, [conversationId]);
// Load own private key once per (user, device).
useEffect(() => {
privateKeyRef.current = null;
@@ -85,7 +111,12 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
const refresh = useCallback(async () => {
if (!conversationId) return;
try {
setState((prev) => ({ ...prev, loading: true }));
// Only show the loading spinner on the *initial* fetch — subsequent
// refreshes (focus/visibility) replace messages in-place to avoid
// flickering an empty state on every wake.
setState((prev) =>
prev.messages.length === 0 ? { ...prev, loading: true } : prev,
);
const rows = await fetchConversationMessages(supabase, conversationId);
const decrypted = await decryptBatch(rows);
setState({ messages: decrypted, loading: false, error: null });
@@ -192,18 +223,71 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
return { ...prev, messages: next };
});
if (partial.editedAt && !partial.deletedAt) {
const [decrypted] = await decryptBatch([partial]);
// Realtime bytea encoding varies (base64 vs hex, even null for
// unchanged columns on some configs). Refetch via REST to get the
// canonical `\x…` hex then decrypt — same pattern as handleInsert.
if (!conversationId || !deviceId) return;
let decrypted: DecryptedMessage | null = null;
for (let attempt = 0; attempt < 6; attempt++) {
const { data, error } = await supabase
.from('messages')
.select(
'id, conversation_id, sender_id, sender_device_id, reply_to_id, edited_at, deleted_at, created_at, ciphertext, nonce, key_version',
)
.eq('id', partial.id)
.maybeSingle();
if (error) {
console.warn('handleUpdate refetch failed', error);
return;
}
if (!data) {
await new Promise((r) => window.setTimeout(r, 120 * (attempt + 1)));
continue;
}
const r = data as unknown as {
id: string;
conversation_id: string;
sender_id: string;
sender_device_id: string | null;
reply_to_id: string | null;
edited_at: string | null;
deleted_at: string | null;
created_at: string;
ciphertext: string;
nonce: string;
key_version: number;
};
const msg: MessageWithCipher = {
id: r.id,
conversationId: r.conversation_id,
senderId: r.sender_id,
senderDeviceId: r.sender_device_id,
replyToId: r.reply_to_id,
editedAt: r.edited_at,
deletedAt: r.deleted_at,
createdAt: r.created_at,
ciphertext: pgBytesToBytes(String(r.ciphertext)),
nonce: pgBytesToBytes(String(r.nonce)),
keyVersion: r.key_version,
};
const [d] = await decryptBatch([msg]);
if (d) {
decrypted = d;
if (d.plaintext !== null) break;
}
await new Promise((r) => window.setTimeout(r, 200 * (attempt + 1)));
}
if (!decrypted) return;
setState((prev) => {
const idx = prev.messages.findIndex((m) => m.id === decrypted.id);
const idx = prev.messages.findIndex((m) => m.id === decrypted!.id);
if (idx === -1) return prev;
const next = [...prev.messages];
next[idx] = decrypted;
next[idx] = decrypted!;
return { ...prev, messages: next };
});
}
},
[decryptBatch],
[conversationId, deviceId, decryptBatch],
);
const handleDelete = useCallback((row: Record<string, unknown>) => {
@@ -256,18 +340,86 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
)
.subscribe();
// Refresh + reconnect on wake from background throttle (mostly Windows
// WebView2). Without this, messages inserted while the window is
// minimised never arrive until the user explicitly reloads. Throttled to
// at most once per AWAKE_THROTTLE_MS so the inevitable cluster of
// visibility/online events on focus does not cause a flicker storm.
let lastAwakeRefresh = 0;
const AWAKE_THROTTLE_MS = 30_000;
const onAwake = () => {
if (document.visibilityState !== 'visible') return;
const now = Date.now();
if (now - lastAwakeRefresh < AWAKE_THROTTLE_MS) return;
lastAwakeRefresh = now;
void refresh();
try {
channel.subscribe();
} catch {
/* already live */
}
};
document.addEventListener('visibilitychange', onAwake);
window.addEventListener('online', onAwake);
return () => {
document.removeEventListener('visibilitychange', onAwake);
window.removeEventListener('online', onAwake);
void supabase.removeChannel(channel);
};
}, [conversationId, userId, deviceId, refresh, handleInsert, handleUpdate, handleDelete]);
const sendText = useCallback(
async (convId: string, uid: string, did: string, priv: Uint8Array, text: string, replyToId: string | null): Promise<void> => {
const msg = await sendEncryptedMessage({
client: supabase,
conversationId: convId,
plaintext: text,
senderUserId: uid,
senderDeviceId: did,
senderPrivateKey: priv,
...(replyToId ? { replyToId } : {}),
});
setState((prev) => {
if (prev.messages.some((m) => m.id === msg.id)) return prev;
return {
...prev,
messages: [
...prev.messages,
{ ...msg, plaintext: text } as DecryptedMessage,
],
};
});
},
[],
);
const send = useCallback(
async (text: string, images: File[] = []) => {
async (text: string, images: File[] = [], replyToId: string | null = null) => {
const trimmed = text.trim();
if ((!trimmed && images.length === 0) || !conversationId || !userId || !deviceId) return;
const priv = privateKeyRef.current;
if (!priv) throw new Error('private key not loaded');
// Text-only path is retryable — if the network is down or the server
// rejects transiently, stash in the outbox and keep the UI optimistic.
// Attachments can't be deferred (large payloads, uploaded separately),
// so those still surface the error immediately.
if (images.length === 0) {
try {
await sendText(conversationId, userId, deviceId, priv, trimmed, replyToId);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'send failed';
enqueueOutbox({
conversationId,
text: trimmed,
replyToId,
error: msg,
});
}
return;
}
// 1. Upload + encrypt each image. Collect handles + raw blob nonces
// (so the public attachment row can reference the blob-level nonce).
const handles: AttachmentHandle[] = [];
@@ -299,6 +451,7 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
senderDeviceId: deviceId,
senderPrivateKey: priv,
...(handles.length > 0 ? { attachmentHandles: handles } : {}),
...(replyToId ? { replyToId } : {}),
});
// 3. Optimistic insert — we already have the plaintext in hand and the
@@ -328,10 +481,104 @@ export function useConversationMessages({ conversationId, userId, deviceId }: Ar
await insertAttachmentRow(supabase, msg.id, h, blobNonce);
}
},
[conversationId, userId, deviceId],
[conversationId, userId, deviceId, sendText],
);
return useMemo(() => ({ ...state, send, refresh }), [state, send, refresh]);
// Drain outbox: retry due items, remove on success, record attempt on fail.
// Runs on online event, window focus, and a 10s interval.
useEffect(() => {
if (!conversationId || !userId || !deviceId) return;
let draining = false;
const drain = async (): Promise<void> => {
if (draining) return;
const priv = privateKeyRef.current;
if (!priv) return;
if (typeof navigator !== 'undefined' && navigator.onLine === false) return;
draining = true;
try {
const items = getOutbox(conversationId).filter(isDue);
for (const item of items) {
if (shouldGiveUp(item)) continue;
try {
await sendText(
conversationId,
userId,
deviceId,
priv,
item.text,
item.replyToId,
);
removeOutbox(conversationId, item.id);
} catch (err: unknown) {
markAttempt(
conversationId,
item.id,
err instanceof Error ? err.message : 'send failed',
);
}
}
} finally {
draining = false;
}
};
const interval = window.setInterval(() => {
void drain();
}, 10_000);
const onOnline = () => void drain();
window.addEventListener('online', onOnline);
window.addEventListener('focus', onOnline);
// Kick once immediately on mount for stale queued items.
void drain();
return () => {
window.clearInterval(interval);
window.removeEventListener('online', onOnline);
window.removeEventListener('focus', onOnline);
};
}, [conversationId, userId, deviceId, sendText]);
const retryPending = useCallback(
(id: string) => {
if (!conversationId) return;
// Force due now; the drain loop will pick it up on next tick.
markAttempt(conversationId, id, null);
// Manual kick: mutate nextAttemptAt by re-enqueuing? Simpler — just
// trigger a drain-ish by queueing a microtask. The interval picks up
// due items within 10s, but for UX we also eagerly try here.
const priv = privateKeyRef.current;
if (!priv || !userId || !deviceId) return;
const item = getOutbox(conversationId).find((x) => x.id === id);
if (!item) return;
void (async () => {
try {
await sendText(conversationId, userId, deviceId, priv, item.text, item.replyToId);
removeOutbox(conversationId, id);
} catch (err: unknown) {
markAttempt(
conversationId,
id,
err instanceof Error ? err.message : 'send failed',
);
}
})();
},
[conversationId, userId, deviceId, sendText],
);
const cancelPending = useCallback(
(id: string) => {
if (!conversationId) return;
removeOutbox(conversationId, id);
},
[conversationId],
);
return useMemo(
() => ({ ...state, send, refresh, pending, retryPending, cancelPending }),
[state, send, refresh, pending, retryPending, cancelPending],
);
}
// Best-effort image dimension probe. Falls back silently on non-images.
+22
View File
@@ -44,7 +44,29 @@ export function useFriendships(userId: string | undefined): FriendshipsState & {
})
.subscribe();
// Windows WebView2 throttles background sockets — refresh on wake.
// Throttled + visibility-only so a normal click into the window does not
// re-fetch on every focus.
let lastAwakeRefresh = 0;
const AWAKE_THROTTLE_MS = 30_000;
const onAwake = () => {
if (document.visibilityState !== 'visible') return;
const now = Date.now();
if (now - lastAwakeRefresh < AWAKE_THROTTLE_MS) return;
lastAwakeRefresh = now;
void refresh();
try {
channel.subscribe();
} catch {
/* already live */
}
};
document.addEventListener('visibilitychange', onAwake);
window.addEventListener('online', onAwake);
return () => {
document.removeEventListener('visibilitychange', onAwake);
window.removeEventListener('online', onAwake);
void supabase.removeChannel(channel);
};
}, [userId, refresh]);
+87
View File
@@ -0,0 +1,87 @@
import {
listGroupDeliveriesForMessages,
listGroupReadsForMessages,
} from '@chat-app/shared/chat';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { supabase } from './supabase';
export interface GroupReceiptState {
// message_id → set of user ids who have delivered/read.
deliveredByMessage: Map<string, Set<string>>;
readByMessage: Map<string, Set<string>>;
refresh: () => Promise<void>;
}
// Aggregated delivery + read receipts for group conversations. Returns the
// set of user ids per message; consumers join with conversation members to
// figure out who has not yet acknowledged.
export function useGroupReceipts(
messageIds: string[],
selfUserId: string | undefined,
active: boolean,
): GroupReceiptState {
const idsKey = useMemo(() => messageIds.join(','), [messageIds]);
const [deliveredByMessage, setDelivered] = useState<Map<string, Set<string>>>(new Map());
const [readByMessage, setRead] = useState<Map<string, Set<string>>>(new Map());
const refresh = useCallback(async () => {
if (!active || !selfUserId || messageIds.length === 0) {
setDelivered(new Map());
setRead(new Map());
return;
}
try {
const [delivered, read] = await Promise.all([
listGroupDeliveriesForMessages(supabase, messageIds, selfUserId),
listGroupReadsForMessages(supabase, messageIds, selfUserId),
]);
setDelivered(toIdSets(delivered));
setRead(toIdSets(read));
} catch (err: unknown) {
console.warn('useGroupReceipts refresh failed', err);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active, selfUserId, idsKey]);
useEffect(() => {
void refresh();
if (!active || !selfUserId) return;
// Listen on both tables. RLS already enforces visibility.
const reads = supabase
.channel('group-reads:' + selfUserId)
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'message_reads' },
() => {
void refresh();
},
)
.subscribe();
const deliveries = supabase
.channel('group-deliv:' + selfUserId)
.on(
'postgres_changes',
{ event: 'INSERT', schema: 'public', table: 'message_deliveries' },
() => {
void refresh();
},
)
.subscribe();
return () => {
void supabase.removeChannel(reads);
void supabase.removeChannel(deliveries);
};
}, [active, selfUserId, refresh]);
return { deliveredByMessage, readByMessage, refresh };
}
function toIdSets(input: Map<string, Map<string, string>>): Map<string, Set<string>> {
const out = new Map<string, Set<string>>();
for (const [mid, inner] of input) {
out.set(mid, new Set(inner.keys()));
}
return out;
}
@@ -0,0 +1,61 @@
import {
listPeerDeliveriesForMessages,
markMessagesDelivered,
} from '@chat-app/shared/chat';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { supabase } from './supabase';
// Tracks peer delivery acknowledgements for our own messages. Single peer
// (DM). For groups this would need a per-user map; keep parity with
// `useMessageReads` for now.
export function useMessageDeliveries(
messageIds: string[],
peerUserId: string | undefined,
): { peerDeliveredSet: Set<string>; refresh: () => Promise<void> } {
const idsKey = useMemo(() => messageIds.join(','), [messageIds]);
const [peerDeliveredSet, setPeerDeliveredSet] = useState<Set<string>>(new Set());
const refresh = useCallback(async () => {
if (!peerUserId || messageIds.length === 0) {
setPeerDeliveredSet(new Set());
return;
}
try {
const s = await listPeerDeliveriesForMessages(supabase, messageIds, peerUserId);
setPeerDeliveredSet(s);
} catch (err: unknown) {
console.error('listPeerDeliveriesForMessages failed', err);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [peerUserId, idsKey]);
useEffect(() => {
void refresh();
if (!peerUserId) return;
const channel = supabase
.channel('deliveries:' + peerUserId)
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'message_deliveries',
filter: 'user_id=eq.' + peerUserId,
},
() => {
void refresh();
},
)
.subscribe();
return () => {
void supabase.removeChannel(channel);
};
}, [peerUserId, refresh]);
return { peerDeliveredSet, refresh };
}
export async function markDelivered(messageIds: string[]): Promise<void> {
await markMessagesDelivered(supabase, messageIds);
}
+87
View File
@@ -0,0 +1,87 @@
// Web Push subscription registration. Browser-only; Tauri WebView2 / WebKit
// do not install service workers. The Tauri build relies on native OS
// notifications via osNotify.ts instead.
//
// Flow:
// 1. Register /sw.js if not already.
// 2. Subscribe with the VAPID public key (Vite injects it via env).
// 3. Persist {endpoint, keys} JSON-encoded into push_tokens.token for the
// current device. Server-side fan-out reads this row to send pushes.
import { isTauriRuntime } from './globalShortcut';
import { supabase } from './supabase';
const VAPID_PUBLIC_KEY: string | undefined =
(import.meta as unknown as { env?: { VITE_VAPID_PUBLIC_KEY?: string } }).env
?.VITE_VAPID_PUBLIC_KEY;
export async function registerWebPush(deviceId: string): Promise<void> {
// Tauri uses native notifications — no service worker.
if (isTauriRuntime()) return;
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return;
if (!('PushManager' in window)) return;
if (!VAPID_PUBLIC_KEY) {
console.warn('VITE_VAPID_PUBLIC_KEY not set — push disabled');
return;
}
try {
const reg = await navigator.serviceWorker.register('/sw.js');
await navigator.serviceWorker.ready;
let sub = await reg.pushManager.getSubscription();
if (!sub) {
const permission = await Notification.requestPermission();
if (permission !== 'granted') return;
sub = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY) as BufferSource,
});
}
const token = JSON.stringify({
endpoint: sub.endpoint,
keys: sub.toJSON().keys ?? {},
});
const { error } = await supabase
.from('push_tokens')
.upsert(
{ device_id: deviceId, platform: 'web' as never, token },
{ onConflict: 'device_id' },
);
if (error) {
console.warn('push_tokens upsert failed', error);
}
} catch (err: unknown) {
console.error('registerWebPush failed', err);
}
}
export async function unregisterWebPush(deviceId: string): Promise<void> {
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return;
try {
const reg = await navigator.serviceWorker.getRegistration();
if (reg) {
const sub = await reg.pushManager.getSubscription();
if (sub) await sub.unsubscribe();
}
} catch {
/* ignore */
}
try {
await supabase.from('push_tokens').delete().eq('device_id', deviceId);
} catch (err: unknown) {
console.warn('push_tokens delete failed', err);
}
}
// VAPID public key arrives as URL-safe base64; PushManager expects a raw byte
// array. Standard conversion.
function urlBase64ToUint8Array(base64: string): Uint8Array {
const padding = '='.repeat((4 - (base64.length % 4)) % 4);
const padded = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/');
const raw = atob(padded);
const out = new Uint8Array(raw.length);
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
return out;
}
+122 -2
View File
@@ -1,4 +1,6 @@
import {
type AdminAuditEntry,
type AdminConversationRow,
type AdminProfileFlag,
type AdminProfileRow,
type AdminSetting,
@@ -6,8 +8,11 @@ import {
deleteInvite,
type InviteRecord,
listAdminSettings,
listAllConversations,
listAllProfiles,
listAuditLog,
listInvites,
logAdminAction,
setInviteDisabled,
setUserFlag,
updateAdminSetting,
@@ -31,20 +36,26 @@ export function AdminPage() {
const [settings, setSettings] = useState<AdminSetting[]>([]);
const [invites, setInvites] = useState<InviteRecord[]>([]);
const [users, setUsers] = useState<AdminProfileRow[]>([]);
const [conversations, setConversations] = useState<AdminConversationRow[]>([]);
const [audit, setAudit] = useState<AdminAuditEntry[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const refresh = useCallback(async () => {
try {
setLoading(true);
const [s, i, u] = await Promise.all([
const [s, i, u, c, a] = await Promise.all([
listAdminSettings(supabase),
listInvites(supabase),
listAllProfiles(supabase),
listAllConversations(supabase),
listAuditLog(supabase, 50),
]);
setSettings(s);
setInvites(i);
setUsers(u);
setConversations(c);
setAudit(a);
setError(null);
} catch (err: unknown) {
const code = extractErrorCode(err);
@@ -65,7 +76,7 @@ export function AdminPage() {
}, [refresh]);
return (
<div className="h-full bg-surface-3 text-fg">
<div className="min-h-full bg-surface-3 text-fg">
<div className="mx-auto flex max-w-4xl flex-col gap-6 px-6 py-8">
<header>
<h1 className="font-display text-2xl font-semibold tracking-tight text-fg">
@@ -92,6 +103,8 @@ export function AdminPage() {
<SettingsSection settings={settings} onRefresh={refresh} />
<InvitesSection invites={invites} onRefresh={refresh} />
<UsersSection users={users} onRefresh={refresh} />
<ConversationsSection conversations={conversations} />
<AuditSection entries={audit} users={users} />
</>
)}
</div>
@@ -295,6 +308,13 @@ function UsersSection({ users, onRefresh }: { users: AdminProfileRow[]; onRefres
async function toggle(userId: string, flag: AdminProfileFlag, value: boolean) {
try {
await setUserFlag(supabase, userId, flag, value);
// Best-effort audit; don't fail the UI if the log write fails.
void logAdminAction(
supabase,
'user.set_flag',
{ type: 'user', id: userId },
{ flag, value },
).catch(() => undefined);
await onRefresh();
} catch (err: unknown) {
console.error(err);
@@ -345,6 +365,106 @@ function UsersSection({ users, onRefresh }: { users: AdminProfileRow[]; onRefres
);
}
// --- Conversations ---------------------------------------------------------
function ConversationsSection({ conversations }: { conversations: AdminConversationRow[] }) {
if (conversations.length === 0) {
return (
<Section title="Unterhaltungen">
<p className="text-sm text-fg-muted">Keine Unterhaltungen.</p>
</Section>
);
}
return (
<Section title={'Unterhaltungen (' + conversations.length + ')'}>
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="text-[10px] uppercase tracking-[0.1em] text-fg-muted">
<tr>
<th className="py-2 pr-3">Name/ID</th>
<th className="py-2 pr-3">Typ</th>
<th className="py-2 pr-3">Members</th>
<th className="py-2 pr-3">Letzte Nachricht</th>
<th className="py-2 pr-3">Erstellt</th>
</tr>
</thead>
<tbody className="divide-y divide-line">
{conversations.map((c) => (
<tr key={c.id}>
<td className="py-2 pr-3 font-mono text-[11px] text-fg">
{c.name ?? c.id.slice(0, 12)}
</td>
<td className="py-2 pr-3 text-xs text-fg-muted">{c.type}</td>
<td className="py-2 pr-3 text-xs text-fg">{c.memberCount}</td>
<td className="py-2 pr-3 text-xs text-fg-muted">
{c.lastMessageAt
? new Date(c.lastMessageAt).toLocaleString()
: '—'}
</td>
<td className="py-2 pr-3 text-xs text-fg-muted">
{new Date(c.createdAt).toLocaleDateString()}
</td>
</tr>
))}
</tbody>
</table>
</div>
</Section>
);
}
// --- Audit log -------------------------------------------------------------
function AuditSection({
entries,
users,
}: {
entries: AdminAuditEntry[];
users: AdminProfileRow[];
}) {
const nameByUserId = new Map(users.map((u) => [u.userId, u.displayName]));
if (entries.length === 0) {
return (
<Section title="Audit-Log">
<p className="text-sm text-fg-muted">Keine Einträge.</p>
</Section>
);
}
return (
<Section title={'Audit-Log (letzte ' + entries.length + ')'}>
<ul className="divide-y divide-line text-sm">
{entries.map((e) => (
<li key={e.id} className="flex items-start gap-3 py-2">
<span className="w-32 shrink-0 font-mono text-[10px] text-fg-muted">
{new Date(e.createdAt).toLocaleString()}
</span>
<div className="min-w-0 flex-1">
<p className="text-xs">
<span className="font-semibold text-fg">
{e.actorId ? nameByUserId.get(e.actorId) ?? e.actorId.slice(0, 8) : '—'}
</span>{' '}
<span className="text-accent">{e.action}</span>
{e.targetId && (
<span className="text-fg-muted">
{' '}
on {e.targetType}:{e.targetId.slice(0, 8)}
</span>
)}
</p>
{Object.keys(e.metadata).length > 0 && (
<p className="mt-0.5 font-mono text-[10px] text-fg-muted">
{JSON.stringify(e.metadata)}
</p>
)}
</div>
</li>
))}
</ul>
</Section>
);
}
// --- Bits ------------------------------------------------------------------
function Toggle({
+2 -2
View File
@@ -38,7 +38,7 @@ type UiState =
| { kind: 'sent'; email: string }
| { kind: 'error'; message: string };
const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/;
const USERNAME_PATTERN = /^[A-Za-z0-9_]{3,32}$/;
export function AuthPage() {
const { session } = useAuth();
@@ -314,7 +314,7 @@ function FormCard({
required
placeholder={t('auth:fields.username_placeholder')}
value={username}
onChange={(e) => onUsernameChange(e.target.value.toLowerCase())}
onChange={(e) => onUsernameChange(e.target.value)}
pattern={USERNAME_PATTERN.source}
className="w-full rounded-lg border border-white/10 bg-ink-800 py-2.5 pl-10 pr-3 text-sm text-white placeholder-neutral-500 transition focus:border-brand-400 focus:outline-none focus:ring-2 focus:ring-brand-500/40"
/>
+126 -26
View File
@@ -1,12 +1,19 @@
import { acceptDm, type ConversationSummary } from '@chat-app/shared/chat';
import {
acceptDm,
type ConversationSummary,
isConversationMuted,
} from '@chat-app/shared/chat';
import { extractErrorCode } from '@chat-app/shared/i18n';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NavLink, Outlet, useParams } from 'react-router-dom';
import { ConversationRowMenu } from '../components/ConversationRowMenu';
import { CreateGroupDialog } from '../components/CreateGroupDialog';
import {
AddUserIcon,
ArchiveIcon,
BellOffIcon,
ChatBubbleIcon,
SearchIcon,
SpinnerIcon,
@@ -21,6 +28,7 @@ export function ChatsPage() {
const { id: activeId } = useParams<{ id: string }>();
const [createOpen, setCreateOpen] = useState(false);
const [query, setQuery] = useState('');
const [showArchived, setShowArchived] = useState(false);
const sorted = useMemo(() => {
return [...conversations].sort((a, b) => {
@@ -30,7 +38,7 @@ export function ChatsPage() {
});
}, [conversations]);
const filtered = useMemo(() => {
const queryFiltered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return sorted;
return sorted.filter((c) => {
@@ -40,10 +48,24 @@ export function ChatsPage() {
});
}, [sorted, query]);
// Split into active vs archived — the user toggles which bucket shows in the
// main list. Archived conversations with unread messages still surface so
// the user can't accidentally silence an ongoing conversation permanently.
const activeItems = useMemo(
() => queryFiltered.filter((c) => !c.archived),
[queryFiltered],
);
const archivedItems = useMemo(
() => queryFiltered.filter((c) => c.archived),
[queryFiltered],
);
const archivedUnread = archivedItems.reduce((s, c) => s + (unread[c.id] ?? 0), 0);
return (
<div className="flex h-full">
<ConversationList
items={filtered}
items={showArchived ? archivedItems : activeItems}
loading={loading}
error={error}
activeId={activeId}
@@ -60,6 +82,9 @@ export function ChatsPage() {
}
}}
onNewGroup={() => setCreateOpen(true)}
showArchived={showArchived}
onToggleArchived={() => setShowArchived((v) => !v)}
archivedUnread={archivedUnread}
/>
<div className="flex-1 border-l border-line bg-surface-3">
<Outlet />
@@ -79,6 +104,9 @@ interface ConversationListProps {
onQueryChange: (q: string) => void;
onAccept: (id: string) => void;
onNewGroup: () => void;
showArchived: boolean;
onToggleArchived: () => void;
archivedUnread: number;
}
function ConversationList({
@@ -91,6 +119,9 @@ function ConversationList({
onQueryChange,
onAccept,
onNewGroup,
showArchived,
onToggleArchived,
archivedUnread,
}: ConversationListProps) {
const { t } = useTranslation(['app']);
@@ -101,17 +132,53 @@ function ConversationList({
>
<header className="flex items-center justify-between px-4 pb-3 pt-5">
<h2 className="font-display text-base font-semibold tracking-tight text-fg">
{t('app:nav.chats')}
{showArchived
? t('app:chats.archived_title', { defaultValue: 'Archiv' })
: t('app:nav.chats')}
</h2>
<button
type="button"
onClick={onNewGroup}
aria-label={t('app:chats.new_group')}
title={t('app:chats.new_group')}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-fg-muted transition hover:bg-surface-3 hover:text-fg focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
>
<AddUserIcon className="h-4 w-4" />
</button>
<div className="flex items-center gap-1">
<button
type="button"
onClick={onToggleArchived}
aria-label={
showArchived
? t('app:chats.show_active', { defaultValue: 'Aktive anzeigen' })
: t('app:chats.show_archived', { defaultValue: 'Archiv anzeigen' })
}
title={
showArchived
? t('app:chats.show_active', { defaultValue: 'Aktive anzeigen' })
: t('app:chats.show_archived', { defaultValue: 'Archiv anzeigen' })
}
className={
'relative flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
(showArchived
? 'bg-accent/15 text-accent'
: 'text-fg-muted hover:bg-surface-3 hover:text-fg')
}
>
<ArchiveIcon className="h-4 w-4" />
{!showArchived && archivedUnread > 0 && (
<span
aria-hidden="true"
className="absolute -right-0.5 -top-0.5 flex min-w-[16px] items-center justify-center rounded-full bg-accent px-1 text-[9px] font-bold leading-tight text-accent-fg"
>
{archivedUnread > 9 ? '9+' : archivedUnread}
</span>
)}
</button>
{!showArchived && (
<button
type="button"
onClick={onNewGroup}
aria-label={t('app:chats.new_group')}
title={t('app:chats.new_group')}
className="flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg text-fg-muted transition hover:bg-surface-3 hover:text-fg focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
>
<AddUserIcon className="h-4 w-4" />
</button>
)}
</div>
</header>
<div className="px-3 pb-2">
@@ -140,10 +207,24 @@ function ConversationList({
) : items.length === 0 ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
<div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-line bg-surface-3 text-accent">
<ChatBubbleIcon className="h-5 w-5" />
{showArchived ? (
<ArchiveIcon className="h-5 w-5" />
) : (
<ChatBubbleIcon className="h-5 w-5" />
)}
</div>
<p className="text-sm text-fg-muted">{t('app:chats.empty_title')}</p>
<p className="text-xs text-fg-muted/80">{t('app:chats.empty_subtitle')}</p>
<p className="text-sm text-fg-muted">
{showArchived
? t('app:chats.archived_empty_title', { defaultValue: 'Nichts archiviert' })
: t('app:chats.empty_title')}
</p>
<p className="text-xs text-fg-muted/80">
{showArchived
? t('app:chats.archived_empty_subtitle', {
defaultValue: 'Archivierte Unterhaltungen erscheinen hier.',
})
: t('app:chats.empty_subtitle')}
</p>
</div>
) : (
<ul className="flex-1 overflow-y-auto px-2 pb-2">
@@ -213,11 +294,12 @@ function ConversationRow({
);
}
const muted = isConversationMuted(item.mutedUntil);
return (
<NavLink
to={'/chats/' + item.id}
className={
'my-1 flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2.5 transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
'group relative my-1 flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2.5 transition focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40 ' +
(active
? 'bg-accent/15 text-fg'
: 'text-fg hover:bg-surface-3/70')
@@ -225,24 +307,42 @@ function ConversationRow({
>
<ConvAvatar url={avatarUrl} title={title} isGroup={item.type === 'group'} />
<div className="min-w-0 flex-1">
<p
className={
'truncate text-sm ' +
(unreadCount > 0 ? 'font-bold' : 'font-semibold')
}
>
{title}
</p>
<div className="flex items-center gap-1.5">
<p
className={
'truncate text-sm ' +
(unreadCount > 0 && !muted ? 'font-bold' : 'font-semibold')
}
>
{title}
</p>
{muted && (
<BellOffIcon
aria-hidden="true"
className="h-3 w-3 shrink-0 text-fg-muted"
/>
)}
</div>
<p className="truncate text-xs text-fg-muted">{preview}</p>
</div>
{unreadCount > 0 && (
<span
aria-label={'Unread: ' + unreadCount}
className="inline-flex min-w-[20px] items-center justify-center rounded-full bg-accent px-1.5 text-[10px] font-bold leading-tight text-accent-fg"
className={
'inline-flex min-w-[20px] items-center justify-center rounded-full px-1.5 text-[10px] font-bold leading-tight ' +
(muted
? 'bg-fg-muted/30 text-fg-muted'
: 'bg-accent text-accent-fg')
}
>
{unreadCount > 99 ? '99+' : unreadCount}
</span>
)}
<ConversationRowMenu
conversationId={item.id}
archived={item.archived}
mutedUntil={item.mutedUntil}
/>
</NavLink>
);
}
+582 -15
View File
@@ -1,20 +1,37 @@
import { parseMessagePayload } from '@chat-app/shared/chat';
import { extractErrorCode } from '@chat-app/shared/i18n';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { ConversationHeader } from '../components/ConversationHeader';
import { ForwardDialog } from '../components/ForwardDialog';
import { GroupInfoPanel } from '../components/GroupInfoPanel';
import { AlertIcon, ArrowRightIcon, PlusIcon, SpinnerIcon, XIcon } from '../components/icons';
import {
AlertIcon,
ArrowRightIcon,
ChevronDownIcon,
ChevronUpIcon,
PlusIcon,
ReplyIcon,
SearchIcon,
SpinnerIcon,
XIcon,
} from '../components/icons';
import { InCallPanel } from '../components/InCallPanel';
import { IncomingCallPanel } from '../components/IncomingCallPanel';
import { MessageBubble } from '../components/MessageBubble';
import { MessageBubble, type QuotedRef } from '../components/MessageBubble';
import { TypingIndicator } from '../components/TypingIndicator';
import { VoiceRecorder } from '../components/VoiceRecorder';
import type { DecryptedMessage } from '@chat-app/shared/chat';
import { useAuth } from '../context/AuthContext';
import { useCall } from '../context/CallContext';
import { useConversationsContext } from '../context/ConversationsContext';
import type { OutboxItem } from '../lib/messageOutbox';
import { useConversationMessages } from '../lib/useConversationMessages';
import { useMessageReactions } from '../lib/useMessageReactions';
import { useGroupReceipts } from '../lib/useGroupReceipts';
import { markDelivered, useMessageDeliveries } from '../lib/useMessageDeliveries';
import { markRead as markMessagesReadRemote, useMessageReads } from '../lib/useMessageReads';
import { usePeerPresence } from '../lib/usePeerPresence';
import { useTypingChannel } from '../lib/useTypingChannel';
@@ -34,11 +51,12 @@ export function ConversationPage() {
const peerId = conversation?.peer?.userId;
const peerPresence = usePeerPresence(peerId);
const { messages, loading, error, send } = useConversationMessages({
conversationId: id,
userId: session?.user.id,
deviceId: device?.id,
});
const { messages, loading, error, send, pending, retryPending, cancelPending } =
useConversationMessages({
conversationId: id,
userId: session?.user.id,
deviceId: device?.id,
});
const messageIds = useMemo(() => messages.map((m) => m.id), [messages]);
const { byMessage: reactionsByMessage, toggle: toggleReaction } = useMessageReactions(
messageIds,
@@ -53,6 +71,36 @@ export function ConversationPage() {
[messages, myId],
);
const { peerReadSet } = useMessageReads(ownMessageIds, peerId);
const { peerDeliveredSet } = useMessageDeliveries(ownMessageIds, peerId);
// Group receipts: only meaningful when conversation is a group. We feed it
// ownMessageIds since we only render delivery state on the sender side.
const isGroup = conversation?.type === 'group';
const { deliveredByMessage: groupDelivered, readByMessage: groupRead } =
useGroupReceipts(ownMessageIds, myId, !!isGroup);
const groupRecipientCount = useMemo(() => {
if (!isGroup || !conversation) return 0;
return conversation.members.filter((m) => m.userId !== myId).length;
}, [isGroup, conversation, myId]);
// Mark every peer-authored message as delivered on our side. Idempotent,
// so rerunning for already-acknowledged ids is a no-op server-side.
const deliveredTrackedRef = useRef<Set<string>>(new Set());
useEffect(() => {
if (!myId || messages.length === 0) return;
const toMark: string[] = [];
for (const m of messages) {
if (m.senderId === myId) continue;
if (deliveredTrackedRef.current.has(m.id)) continue;
deliveredTrackedRef.current.add(m.id);
toMark.push(m.id);
}
if (toMark.length > 0) {
void markDelivered(toMark).catch((err: unknown) => {
console.warn('markDelivered failed', err);
});
}
}, [messages, myId]);
const lastSeenMessageId = useMemo(() => {
for (let i = messages.length - 1; i >= 0; i--) {
@@ -82,8 +130,162 @@ export function ConversationPage() {
const [stickToBottom, setStickToBottom] = useState(true);
const [attachments, setAttachments] = useState<File[]>([]);
const [infoPanelOpen, setInfoPanelOpen] = useState(false);
const [replyTo, setReplyTo] = useState<DecryptedMessage | null>(null);
const [forwardTarget, setForwardTarget] = useState<DecryptedMessage | null>(null);
const [searchOpen, setSearchOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [searchIdx, setSearchIdx] = useState(0);
const [searchSenderId, setSearchSenderId] = useState<string>('');
const [searchAttachmentsOnly, setSearchAttachmentsOnly] = useState(false);
const [searchDateFrom, setSearchDateFrom] = useState<string>('');
const [searchDateTo, setSearchDateTo] = useState<string>('');
const [highlightedId, setHighlightedId] = useState<string | null>(null);
const [displayCount, setDisplayCount] = useState<number>(150);
const scrollRef = useRef<HTMLDivElement>(null);
const loadMoreSentinelRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
// Drop reply-to / clear search state when switching conversation.
useEffect(() => {
setReplyTo(null);
setForwardTarget(null);
setSearchOpen(false);
setSearchQuery('');
setDisplayCount(150);
}, [id]);
// Expand window when the "load older" sentinel scrolls into view. Doubles
// effective window on each trigger so scrolling up quickly converges to
// rendering everything.
useEffect(() => {
const el = loadMoreSentinelRef.current;
if (!el) return;
if (displayCount >= messages.length) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0]?.isIntersecting) {
setDisplayCount((n) => Math.min(messages.length, n * 2));
}
},
{ root: scrollRef.current, rootMargin: '200px 0px' },
);
observer.observe(el);
return () => observer.disconnect();
}, [displayCount, messages.length]);
const messageById = useMemo(() => {
const m = new Map<string, DecryptedMessage>();
for (const msg of messages) m.set(msg.id, msg);
return m;
}, [messages]);
const senderNameFor = useCallback(
(senderId: string): string => {
if (senderId === myId) return t('app:chats.you', { defaultValue: 'Du' });
const profile =
conversation?.members.find((mm) => mm.userId === senderId)?.profile ??
(senderId !== myId ? conversation?.peer ?? null : null);
return profile?.displayName ?? '?';
},
[conversation, myId, t],
);
const buildQuoted = useCallback(
(replyToId: string | null): QuotedRef | null => {
if (!replyToId) return null;
const target = messageById.get(replyToId);
if (!target) {
return {
id: replyToId,
senderName: '…',
snippet: t('app:chats.quote_unavailable', { defaultValue: 'Nachricht nicht verfügbar' }),
isAttachment: false,
deleted: true,
};
}
const parsed = parseMessagePayload(target.plaintext);
const text = parsed.kind === 'text' ? parsed.text : '';
const hasAttachment = parsed.kind === 'text' && parsed.attachments.length > 0;
return {
id: target.id,
senderName: senderNameFor(target.senderId),
snippet: text.length > 120 ? text.slice(0, 120) + '…' : text,
isAttachment: hasAttachment,
deleted: !!target.deletedAt,
};
},
[messageById, senderNameFor, t],
);
const jumpToMessage = useCallback((targetId: string) => {
const el = scrollRef.current?.querySelector<HTMLElement>(
'[data-message-id="' + CSS.escape(targetId) + '"]',
);
if (!el) return;
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
setHighlightedId(targetId);
window.setTimeout(() => setHighlightedId((cur) => (cur === targetId ? null : cur)), 1600);
}, []);
const handleReply = useCallback((m: DecryptedMessage) => {
setReplyTo(m);
composerRef.current?.focus();
}, []);
const handleForward = useCallback((m: DecryptedMessage) => {
setForwardTarget(m);
}, []);
// Search matches: messages matching query + filters. Empty query is allowed
// when filters are active, so users can e.g. show "all attachments from
// alice in the last week" without a text query.
const searchActive = useMemo(
() =>
searchQuery.trim().length > 0 ||
searchSenderId !== '' ||
searchAttachmentsOnly ||
searchDateFrom !== '' ||
searchDateTo !== '',
[searchQuery, searchSenderId, searchAttachmentsOnly, searchDateFrom, searchDateTo],
);
const searchMatches = useMemo(() => {
if (!searchActive) return [] as DecryptedMessage[];
const q = searchQuery.trim().toLowerCase();
const fromTs = searchDateFrom ? new Date(searchDateFrom).getTime() : null;
// Date inputs cover whole days — bump 'to' to end-of-day.
const toTs = searchDateTo
? new Date(searchDateTo).getTime() + 24 * 3600 * 1000 - 1
: null;
return messages.filter((m) => {
if (searchSenderId && m.senderId !== searchSenderId) return false;
const created = new Date(m.createdAt).getTime();
if (fromTs !== null && created < fromTs) return false;
if (toTs !== null && created > toTs) return false;
if (!m.plaintext) return false;
const parsed = parseMessagePayload(m.plaintext);
if (parsed.kind !== 'text') return false;
if (searchAttachmentsOnly && parsed.attachments.length === 0) return false;
if (q && !parsed.text.toLowerCase().includes(q)) return false;
return true;
});
}, [messages, searchActive, searchQuery, searchSenderId, searchAttachmentsOnly, searchDateFrom, searchDateTo]);
// Reset/clamp the active match index when the match set changes.
useEffect(() => {
if (searchMatches.length === 0) {
setSearchIdx(0);
return;
}
setSearchIdx((cur) => Math.min(cur, searchMatches.length - 1));
}, [searchMatches.length]);
// Auto-jump to current match.
useEffect(() => {
if (!searchOpen || searchMatches.length === 0) return;
const target = searchMatches[searchIdx];
if (target) jumpToMessage(target.id);
}, [searchOpen, searchMatches, searchIdx, jumpToMessage]);
useEffect(() => {
if (!id) return;
@@ -122,9 +324,10 @@ export function ConversationPage() {
setSending(true);
setSendError(null);
try {
await send(text, attachments);
await send(text, attachments, replyTo?.id ?? null);
setText('');
setAttachments([]);
setReplyTo(null);
if (fileInputRef.current) fileInputRef.current.value = '';
setStickToBottom(true);
notifyStopTyping();
@@ -158,7 +361,6 @@ export function ConversationPage() {
setAttachments((prev) => [...prev, ...next].slice(0, 4));
}
const isGroup = conversation?.type === 'group';
const { state: callState } = useCall();
// Hide the chat header while this conversation hosts an active call — the
// call topbar inside the dock already shows the channel name + duration,
@@ -177,10 +379,45 @@ export function ConversationPage() {
<ConversationHeader
conversation={conversation}
peerPresence={peerPresence}
onSearchClick={() => setSearchOpen((v) => !v)}
{...(isGroup ? { onInfoClick: () => setInfoPanelOpen(true) } : {})}
/>
)}
{!callHereActive && searchOpen && (
<SearchBar
query={searchQuery}
onQueryChange={setSearchQuery}
matches={searchMatches.length}
activeIdx={searchIdx}
senderId={searchSenderId}
onSenderChange={setSearchSenderId}
attachmentsOnly={searchAttachmentsOnly}
onAttachmentsOnlyChange={setSearchAttachmentsOnly}
dateFrom={searchDateFrom}
onDateFromChange={setSearchDateFrom}
dateTo={searchDateTo}
onDateToChange={setSearchDateTo}
members={conversation?.members ?? []}
onPrev={() =>
setSearchIdx((cur) =>
searchMatches.length === 0 ? 0 : (cur - 1 + searchMatches.length) % searchMatches.length,
)
}
onNext={() =>
setSearchIdx((cur) => (searchMatches.length === 0 ? 0 : (cur + 1) % searchMatches.length))
}
onClose={() => {
setSearchOpen(false);
setSearchQuery('');
setSearchSenderId('');
setSearchAttachmentsOnly(false);
setSearchDateFrom('');
setSearchDateTo('');
}}
/>
)}
{isGroup && conversation && (
<GroupInfoPanel
open={infoPanelOpen}
@@ -203,13 +440,43 @@ export function ConversationPage() {
<p className="text-center text-sm text-fg-muted"></p>
) : (
<ul className="space-y-0.5">
{messages.map((m, idx) => {
const prev = messages[idx - 1];
const next = messages[idx + 1];
const grouped = idx > 0 && prev?.senderId === m.senderId;
const isLastOfRun = !next || next.senderId !== m.senderId;
const senderProfile =
{displayCount < messages.length && (
<li>
<div
ref={loadMoreSentinelRef}
className="flex items-center justify-center py-2 text-xs text-fg-muted"
>
Lade ältere Nachrichten
</div>
</li>
)}
{messages.slice(Math.max(0, messages.length - displayCount)).map((m, sliceIdx) => {
const idx = Math.max(0, messages.length - displayCount) + sliceIdx;
// A "run" is consecutive bubbles from the same sender with
// nothing between them. Call-event separators break the run —
// a bubble whose immediate next neighbour is a call_event must
// anchor the avatar, even if another bubble from the same
// sender appears after the separator.
const prevRaw = messages[idx - 1];
const nextRaw = messages[idx + 1];
const prevIsCallEvent =
!!prevRaw && parseMessagePayload(prevRaw.plaintext).kind === 'call_event';
const nextIsCallEvent =
!!nextRaw && parseMessagePayload(nextRaw.plaintext).kind === 'call_event';
const grouped =
!!prevRaw && prevRaw.senderId === m.senderId && !prevIsCallEvent;
// Anchor avatar on the LAST message of a run so it aligns with
// the bubble's tail (bottom corner). Tail is bottom-left for
// mine, bottom-right for peer — see rounded-[…_4px_…] above.
const isLastOfRun =
!nextRaw || nextRaw.senderId !== m.senderId || nextIsCallEvent;
// DM fallback: if member lookup fails (e.g. transient sync), fall
// back to conversation.peer so the peer's avatar still resolves.
const memberProfile =
conversation?.members.find((mm) => mm.userId === m.senderId)?.profile ?? null;
const senderProfile =
memberProfile ??
(m.senderId !== myId ? (conversation?.peer ?? null) : null);
return (
<li key={m.id}>
<MessageBubble
@@ -223,10 +490,37 @@ export function ConversationPage() {
reactions={reactionsByMessage.get(m.id) ?? []}
onToggleReaction={(emoji) => toggleReaction(m.id, emoji)}
showSeen={m.id === lastSeenMessageId}
{...(m.senderId === myId
? {
deliveryState: computeDeliveryState({
messageId: m.id,
isGroup: !!isGroup,
recipientCount: groupRecipientCount,
peerReadSet,
peerDeliveredSet,
groupRead,
groupDelivered,
}),
}
: {})}
quoted={buildQuoted(m.replyToId)}
onJumpToMessage={jumpToMessage}
onReply={handleReply}
onForward={handleForward}
highlighted={highlightedId === m.id}
/>
</li>
);
})}
{pending.map((p) => (
<li key={p.id}>
<PendingBubble
item={p}
onRetry={() => retryPending(p.id)}
onCancel={() => cancelPending(p.id)}
/>
</li>
))}
</ul>
)}
</div>
@@ -243,6 +537,38 @@ export function ConversationPage() {
</div>
)}
{replyTo && (
<div className="mb-2 flex items-stretch gap-2 rounded-lg border border-line bg-surface-2 p-2 text-sm">
<span aria-hidden="true" className="w-1 shrink-0 rounded-full bg-accent" />
<ReplyIcon className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-semibold text-fg">
{t('app:chats.replying_to', {
name: senderNameFor(replyTo.senderId),
defaultValue: 'Antwort an ' + senderNameFor(replyTo.senderId),
})}
</p>
<p className="truncate text-xs italic text-fg-muted">
{(() => {
if (!replyTo.plaintext) return '…';
const p = parseMessagePayload(replyTo.plaintext);
if (p.kind !== 'text') return '';
if (!p.text && p.attachments.length > 0) return '📎';
return p.text;
})()}
</p>
</div>
<button
type="button"
onClick={() => setReplyTo(null)}
aria-label={t('app:friends.action_cancel', { defaultValue: 'Abbrechen' })}
className="shrink-0 cursor-pointer rounded-md p-1 text-fg-muted transition hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-4 w-4" />
</button>
</div>
)}
{attachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-2">
{attachments.map((file, idx) => (
@@ -275,7 +601,20 @@ export function ConversationPage() {
>
<PlusIcon className="h-4 w-4" />
</button>
<VoiceRecorder
disabled={sending}
onComplete={async (file) => {
try {
await send('', [file], replyTo?.id ?? null);
setReplyTo(null);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : 'send failed';
setSendError(msg);
}
}}
/>
<textarea
ref={composerRef}
value={text}
onChange={(e) => {
setText(e.target.value);
@@ -301,6 +640,234 @@ export function ConversationPage() {
</button>
</div>
</form>
<ForwardDialog
open={forwardTarget !== null}
message={forwardTarget}
currentConversationId={id ?? null}
onClose={() => setForwardTarget(null)}
/>
</div>
);
}
interface SearchBarProps {
query: string;
onQueryChange: (q: string) => void;
matches: number;
activeIdx: number;
senderId: string;
onSenderChange: (id: string) => void;
attachmentsOnly: boolean;
onAttachmentsOnlyChange: (v: boolean) => void;
dateFrom: string;
onDateFromChange: (v: string) => void;
dateTo: string;
onDateToChange: (v: string) => void;
members: { userId: string; profile: { displayName?: string | null } | null }[];
onPrev: () => void;
onNext: () => void;
onClose: () => void;
}
function SearchBar({
query,
onQueryChange,
matches,
activeIdx,
senderId,
onSenderChange,
attachmentsOnly,
onAttachmentsOnlyChange,
dateFrom,
onDateFromChange,
dateTo,
onDateToChange,
members,
onPrev,
onNext,
onClose,
}: SearchBarProps) {
const { t } = useTranslation(['app']);
return (
<div className="flex flex-col gap-2 border-b border-line bg-surface-2 px-4 py-2">
<div className="flex items-center gap-2">
<SearchIcon className="h-4 w-4 shrink-0 text-fg-muted" />
<input
type="search"
autoFocus
value={query}
onChange={(e) => onQueryChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Escape') onClose();
if (e.key === 'Enter') {
e.preventDefault();
if (e.shiftKey) onPrev();
else onNext();
}
}}
placeholder={t('app:chats.search_in_conv', { defaultValue: 'In Unterhaltung suchen…' })}
className="min-w-0 flex-1 bg-transparent text-sm text-fg placeholder-fg-muted outline-none"
/>
<span className="shrink-0 text-xs tabular-nums text-fg-muted">
{matches === 0
? query.trim().length > 0
? t('app:chats.search_none', { defaultValue: 'Keine Treffer' })
: ''
: activeIdx + 1 + ' / ' + matches}
</span>
<button
type="button"
onClick={onPrev}
disabled={matches === 0}
aria-label="Previous"
className="cursor-pointer rounded-md p-1 text-fg-muted transition hover:bg-surface-3 hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
<ChevronUpIcon className="h-4 w-4" />
</button>
<button
type="button"
onClick={onNext}
disabled={matches === 0}
aria-label="Next"
className="cursor-pointer rounded-md p-1 text-fg-muted transition hover:bg-surface-3 hover:text-fg disabled:cursor-not-allowed disabled:opacity-40"
>
<ChevronDownIcon className="h-4 w-4" />
</button>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="cursor-pointer rounded-md p-1 text-fg-muted transition hover:bg-surface-3 hover:text-fg"
>
<XIcon className="h-4 w-4" />
</button>
</div>
<div className="flex flex-wrap items-center gap-2 text-xs text-fg-muted">
<select
value={senderId}
onChange={(e) => onSenderChange(e.target.value)}
className="cursor-pointer rounded-md border border-line bg-surface-3 px-2 py-1 text-fg outline-none focus:border-accent"
>
<option value="">Alle Sender</option>
{members.map((m) => (
<option key={m.userId} value={m.userId}>
{m.profile?.displayName ?? m.userId.slice(0, 6)}
</option>
))}
</select>
<label className="flex cursor-pointer items-center gap-1 rounded-md border border-line bg-surface-3 px-2 py-1 text-fg">
<input
type="checkbox"
checked={attachmentsOnly}
onChange={(e) => onAttachmentsOnlyChange(e.target.checked)}
className="accent-accent"
/>
<span>Nur Anhänge</span>
</label>
<label className="flex items-center gap-1">
<span>Von</span>
<input
type="date"
value={dateFrom}
onChange={(e) => onDateFromChange(e.target.value)}
className="rounded-md border border-line bg-surface-3 px-2 py-1 text-fg outline-none focus:border-accent"
/>
</label>
<label className="flex items-center gap-1">
<span>Bis</span>
<input
type="date"
value={dateTo}
onChange={(e) => onDateToChange(e.target.value)}
className="rounded-md border border-line bg-surface-3 px-2 py-1 text-fg outline-none focus:border-accent"
/>
</label>
</div>
</div>
);
}
// Walks `messages` from `idx + step` skipping call_event entries until a
// regular bubble is found or the array boundary is reached. Used to decide
// run-grouping for avatar placement so call separators don't bleed into
// sender continuity.
function computeDeliveryState(args: {
messageId: string;
isGroup: boolean;
recipientCount: number;
peerReadSet: Set<string>;
peerDeliveredSet: Set<string>;
groupRead: Map<string, Set<string>>;
groupDelivered: Map<string, Set<string>>;
}): 'sent' | 'delivered' | 'read' {
// DM: single peer ack flips state.
if (!args.isGroup) {
if (args.peerReadSet.has(args.messageId)) return 'read';
if (args.peerDeliveredSet.has(args.messageId)) return 'delivered';
return 'sent';
}
// Group: state advances only when ALL recipients have acknowledged. With
// 0 recipients (admin-only group), we keep 'sent' so we don't show
// misleading completed ticks.
if (args.recipientCount === 0) return 'sent';
const reads = args.groupRead.get(args.messageId);
if (reads && reads.size >= args.recipientCount) return 'read';
const delivered = args.groupDelivered.get(args.messageId);
if (delivered && delivered.size >= args.recipientCount) return 'delivered';
return 'sent';
}
function PendingBubble({
item,
onRetry,
onCancel,
}: {
item: OutboxItem;
onRetry: () => void;
onCancel: () => void;
}) {
const failed = item.attempts >= 8;
return (
<div className="flex justify-end py-0.5">
<div
className={
'max-w-[72%] rounded-[18px] px-3.5 py-2 text-sm ' +
(failed
? 'border border-rose-500/40 bg-rose-500/10 text-rose-700 dark:text-rose-100'
: 'border border-dashed border-accent/50 bg-accent/10 text-fg opacity-80')
}
>
<p className="whitespace-pre-wrap break-words">{item.text}</p>
<div className="mt-1 flex items-center justify-end gap-2 text-[10px] uppercase tracking-wider text-fg-muted">
{failed ? (
<>
<span>{item.lastError ?? 'Senden fehlgeschlagen'}</span>
<button
type="button"
onClick={onRetry}
className="cursor-pointer rounded px-1.5 py-0.5 font-semibold text-accent hover:underline"
>
Erneut
</button>
<button
type="button"
onClick={onCancel}
className="cursor-pointer rounded px-1.5 py-0.5 font-semibold text-rose-600 hover:underline dark:text-rose-300"
>
Verwerfen
</button>
</>
) : (
<>
<SpinnerIcon className="h-3 w-3 animate-spin" />
<span>
{item.attempts === 0 ? 'Senden…' : 'Wiederhole (' + item.attempts + ')'}
</span>
</>
)}
</div>
</div>
</div>
);
}
+77 -9
View File
@@ -1,11 +1,18 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { DeviceRegistration } from '../components/DeviceRegistration';
import { DeviceRestore } from '../components/DeviceRestore';
import { useAuth } from '../context/AuthContext';
type Mode = 'register' | 'restore';
export function DevicePage() {
const { t } = useTranslation(['app']);
const { session, profile, setDevice } = useAuth();
const navigate = useNavigate();
const [mode, setMode] = useState<Mode>('register');
if (!session) return null; // Guarded by RequireAuth, but be defensive.
@@ -15,20 +22,81 @@ export function DevicePage() {
return (
<main className="relative flex min-h-screen items-center justify-center overflow-hidden bg-ink-950 px-5 py-10 text-neutral-100 sm:px-8">
<BackgroundStage />
<div className="relative z-10 w-full max-w-md">
<DeviceRegistration
userId={session.user.id}
defaultName={defaultName}
onRegistered={(device) => {
setDevice(device);
navigate('/chats', { replace: true });
}}
/>
<div className="relative z-10 w-full max-w-md space-y-3">
<div
role="tablist"
aria-label={t('app:backup.mode_label', { defaultValue: 'Gerätemodus' })}
className="flex gap-1 rounded-xl border border-white/10 bg-ink-900/60 p-1 backdrop-blur-xl"
>
<TabButton
active={mode === 'register'}
onClick={() => setMode('register')}
label={t('app:backup.mode_register', { defaultValue: 'Neu einrichten' })}
/>
<TabButton
active={mode === 'restore'}
onClick={() => setMode('restore')}
label={t('app:backup.mode_restore', { defaultValue: 'Backup wiederherstellen' })}
/>
</div>
{mode === 'register' ? (
<DeviceRegistration
userId={session.user.id}
defaultName={defaultName}
onRegistered={(device) => {
setDevice(device);
// Signal the chats page to open the post-registration backup
// prompt (AppShell reads this on mount).
try {
window.sessionStorage.setItem('chatapp.backup.prompt', '1');
} catch {
/* storage disabled — skip hint */
}
navigate('/chats', { replace: true });
}}
/>
) : (
<DeviceRestore
userId={session.user.id}
onRestored={(device) => {
setDevice(device);
navigate('/chats', { replace: true });
}}
/>
)}
</div>
</main>
);
}
function TabButton({
active,
onClick,
label,
}: {
active: boolean;
onClick: () => void;
label: string;
}) {
return (
<button
type="button"
role="tab"
aria-selected={active}
onClick={onClick}
className={
'flex-1 cursor-pointer rounded-lg px-3 py-2 text-xs font-semibold transition focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-400/40 ' +
(active
? 'bg-brand-500/20 text-brand-100 ring-1 ring-brand-400/40'
: 'text-neutral-400 hover:bg-white/5 hover:text-neutral-100')
}
>
{label}
</button>
);
}
function BackgroundStage() {
return (
<div aria-hidden="true" className="pointer-events-none absolute inset-0">
+3 -3
View File
@@ -107,8 +107,8 @@ export function FriendsPage() {
);
return (
<div className="h-full bg-surface-3 text-fg">
<div className="mx-auto flex h-full max-w-3xl flex-col gap-5 px-6 py-8">
<div className="min-h-full bg-surface-3 text-fg">
<div className="mx-auto flex min-h-full max-w-3xl flex-col gap-5 px-6 py-8">
<header className="flex items-center justify-between gap-4">
<h1 className="font-display text-2xl font-semibold tracking-tight text-fg">
{t('app:friends.title')}
@@ -121,7 +121,7 @@ export function FriendsPage() {
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value.toLowerCase())}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('app:friends.search_placeholder')}
autoComplete="off"
autoCapitalize="none"
+239 -131
View File
@@ -4,15 +4,16 @@ import {
SUPPORTED_LOCALES,
type SupportedLocale,
} from '@chat-app/shared/i18n';
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Avatar } from '../components/Avatar';
import { BackupExportDialog } from '../components/BackupExportDialog';
import { LockIcon } from '../components/icons';
import { useAuth } from '../context/AuthContext';
import { loadDevicePrivateKey, saveDevicePrivateKey } from '@chat-app/shared/auth';
import { useCall } from '../context/CallContext';
import { loadDevicePrivateKey } from '@chat-app/shared/auth';
import { deleteAvatarObject, uploadAvatar } from '../lib/avatarUpload';
import { exportDeviceKey, importDeviceKey } from '../lib/deviceBackup';
import { devLocalSecretStore } from '../lib/secretStore';
import {
getPttSettings,
@@ -76,7 +77,7 @@ export function SettingsPage() {
}
return (
<div className="h-full bg-surface-3 text-fg">
<div className="min-h-full bg-surface-3 text-fg">
<div className="mx-auto flex max-w-3xl flex-col gap-6 px-6 py-8">
<header className="mb-2">
<h1 className="font-display text-2xl font-semibold tracking-tight text-fg">
@@ -142,7 +143,10 @@ export function SettingsPage() {
{/* Voice / Push-to-Talk + Audio Quality + E2EE */}
<Section title={t('app:settings.section_voice', { defaultValue: 'Sprache' })}>
<AudioQualityControls />
<AudioDeviceControls />
<div className="mt-3 border-t border-line pt-3">
<AudioQualityControls />
</div>
<div className="mt-3 border-t border-line pt-3">
<PttControls />
</div>
@@ -447,65 +451,32 @@ function AvatarControls({ patchProfile, busy }: AvatarControlsProps) {
function DeviceKeyBackupControls() {
const { t } = useTranslation(['app']);
const { profile, device } = useAuth();
const [busy, setBusy] = useState(false);
const [backupOut, setBackupOut] = useState<string | null>(null);
const [exportPass, setExportPass] = useState('');
const [importPass, setImportPass] = useState('');
const [importBlob, setImportBlob] = useState('');
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
const [open, setOpen] = useState(false);
const [privateKey, setPrivateKey] = useState<Uint8Array | null>(null);
const [err, setErr] = useState<string | null>(null);
const canRun = !!profile?.userId && !!device?.id;
async function handleExport() {
async function handleOpen() {
if (!canRun) return;
setMsg(null);
setBusy(true);
setErr(null);
try {
const priv = await loadDevicePrivateKey(devLocalSecretStore, profile.userId, device.id);
if (!priv) throw new Error('No device key on this install');
const out = await exportDeviceKey(priv, exportPass);
setBackupOut(out);
setExportPass('');
setMsg({
kind: 'ok',
text: t('app:settings.backup_export_ok', {
defaultValue: 'Backup erstellt — kopiere und bewahre es sicher auf.',
}),
});
} catch (err: unknown) {
setMsg({
kind: 'err',
text: err instanceof Error ? err.message : 'export failed',
});
} finally {
setBusy(false);
if (!priv) throw new Error(t('app:backup.no_key_here', {
defaultValue: 'Kein Geräteschlüssel auf dieser Installation.',
}));
setPrivateKey(priv);
setOpen(true);
} catch (e: unknown) {
setErr(e instanceof Error ? e.message : 'failed to load key');
}
}
async function handleImport() {
if (!canRun) return;
setMsg(null);
setBusy(true);
try {
const priv = await importDeviceKey(importBlob.trim(), importPass);
await saveDevicePrivateKey(devLocalSecretStore, profile.userId, device.id, priv);
setImportBlob('');
setImportPass('');
setMsg({
kind: 'ok',
text: t('app:settings.backup_import_ok', {
defaultValue:
'Schlüssel importiert. Beim nächsten Reload sollten alte Nachrichten lesbar sein.',
}),
});
} catch (err: unknown) {
setMsg({
kind: 'err',
text: err instanceof Error ? err.message : 'import failed',
});
} finally {
setBusy(false);
function handleClose() {
setOpen(false);
if (privateKey) {
for (let i = 0; i < privateKey.length; i++) privateKey[i] = 0;
}
setPrivateKey(null);
}
return (
@@ -514,87 +485,31 @@ function DeviceKeyBackupControls() {
{t('app:settings.device_key_backup', { defaultValue: 'Geräteschlüssel-Backup' })}
</div>
<p className="mt-1 text-xs text-fg-muted">
{t('app:settings.device_key_backup_hint', {
{t('app:settings.device_key_backup_hint_v2', {
defaultValue:
'Sichere deinen privaten Schlüssel passwortgeschützt, damit du auf neuen Geräten alte Nachrichten weiter lesen kannst.',
'Backup deines Geräteschlüssels. Ohne Backup kein Zugriff auf alte Nachrichten wenn Gerät oder Browser-Storage verloren geht. Wiederherstellung passiert im Gerät-Einrichtungsbildschirm.',
})}
</p>
<button
type="button"
disabled={!canRun}
onClick={() => void handleOpen()}
className="mt-3 inline-flex cursor-pointer items-center gap-1.5 rounded-lg bg-accent px-3 py-2 text-sm font-semibold text-accent-fg transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:backup.export_open', { defaultValue: 'Backup erstellen' })}
</button>
{err && (
<p className="mt-2 text-xs text-rose-600 dark:text-rose-300">{err}</p>
)}
<div className="mt-4 space-y-2">
<div className="text-xs font-semibold uppercase tracking-[0.1em] text-fg-muted">
{t('app:settings.backup_export', { defaultValue: 'Export' })}
</div>
<div className="flex gap-2">
<input
type="password"
value={exportPass}
onChange={(e) => setExportPass(e.target.value)}
placeholder={t('app:settings.backup_passphrase', { defaultValue: 'Passphrase (min 8)' })}
className="flex-1 rounded-lg border border-line bg-surface-3 px-3 py-2 text-sm text-fg placeholder-fg-muted focus:border-accent focus:outline-none"
/>
<button
type="button"
disabled={busy || exportPass.length < 8 || !canRun}
onClick={() => void handleExport()}
className="cursor-pointer rounded-lg bg-accent px-4 text-sm font-semibold text-accent-fg transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:settings.backup_create', { defaultValue: 'Erstellen' })}
</button>
</div>
{backupOut && (
<textarea
readOnly
value={backupOut}
onClick={(e) => (e.target as HTMLTextAreaElement).select()}
rows={3}
className="w-full rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-2 font-mono text-[10px] text-emerald-700 dark:text-emerald-200"
/>
)}
</div>
<div className="mt-4 space-y-2 border-t border-line pt-4">
<div className="text-xs font-semibold uppercase tracking-[0.1em] text-fg-muted">
{t('app:settings.backup_import', { defaultValue: 'Import' })}
</div>
<textarea
value={importBlob}
onChange={(e) => setImportBlob(e.target.value)}
rows={3}
placeholder={t('app:settings.backup_blob_placeholder', {
defaultValue: 'chatapp-backup-v1.…',
})}
className="w-full rounded-lg border border-line bg-surface-3 p-2 font-mono text-[11px] text-fg placeholder-fg-muted focus:border-accent focus:outline-none"
{open && profile && device && privateKey && (
<BackupExportDialog
open={open}
userId={profile.userId}
deviceId={device.id}
privateKey={privateKey}
onClose={handleClose}
/>
<div className="flex gap-2">
<input
type="password"
value={importPass}
onChange={(e) => setImportPass(e.target.value)}
placeholder={t('app:settings.backup_passphrase', { defaultValue: 'Passphrase' })}
className="flex-1 rounded-lg border border-line bg-surface-3 px-3 py-2 text-sm text-fg placeholder-fg-muted focus:border-accent focus:outline-none"
/>
<button
type="button"
disabled={busy || !importBlob || !importPass || !canRun}
onClick={() => void handleImport()}
className="cursor-pointer rounded-lg bg-emerald-600 px-4 text-sm font-semibold text-white transition hover:bg-emerald-500 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('app:settings.backup_restore', { defaultValue: 'Wiederherstellen' })}
</button>
</div>
</div>
{msg && (
<p
className={
'mt-3 text-xs ' +
(msg.kind === 'ok'
? 'text-emerald-600 dark:text-emerald-300'
: 'text-rose-600 dark:text-rose-300')
}
>
{msg.text}
</p>
)}
</div>
);
@@ -731,3 +646,196 @@ function Toggle({
</label>
);
}
// ---------------------------------------------------------------------------
// Audio device selection — persisted input + output deviceIds, hot-swap on
// active calls. Output swap uses HTMLMediaElement.setSinkId on our attached
// <audio> elements (LiveKit's switchActiveDevice only tracks elements it
// attached itself).
// ---------------------------------------------------------------------------
function AudioDeviceControls() {
const { t } = useTranslation(['app']);
const { setAudioInputDevice, setAudioOutputDevice } = useCall();
const [inputs, setInputs] = useState<MediaDeviceInfo[]>([]);
const [outputs, setOutputs] = useState<MediaDeviceInfo[]>([]);
const [inputId, setInputId] = useState<string | null>(
() => getAudioSettings().inputDeviceId,
);
const [outputId, setOutputId] = useState<string | null>(
() => getAudioSettings().outputDeviceId,
);
const [error, setError] = useState<string | null>(null);
const [permission, setPermission] = useState<'unknown' | 'granted' | 'denied'>(
'unknown',
);
const refresh = useCallback(async () => {
try {
const list = await navigator.mediaDevices.enumerateDevices();
setInputs(list.filter((d) => d.kind === 'audioinput'));
setOutputs(list.filter((d) => d.kind === 'audiooutput'));
// If labels are empty, permission hasn't been granted yet — browsers
// mask device names until a getUserMedia call succeeds at least once.
const hasLabels = list.some(
(d) => (d.kind === 'audioinput' || d.kind === 'audiooutput') && d.label.length > 0,
);
setPermission(hasLabels ? 'granted' : 'unknown');
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'enumerateDevices failed');
}
}, []);
useEffect(() => {
void refresh();
const onChange = () => void refresh();
try {
navigator.mediaDevices.addEventListener('devicechange', onChange);
} catch {
/* some browsers omit devicechange */
}
const unsubSettings = subscribeAudioSettings((s) => {
setInputId(s.inputDeviceId);
setOutputId(s.outputDeviceId);
});
return () => {
try {
navigator.mediaDevices.removeEventListener('devicechange', onChange);
} catch {
/* ignore */
}
unsubSettings();
};
}, [refresh]);
const requestPermission = useCallback(async () => {
setError(null);
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach((t) => t.stop());
setPermission('granted');
await refresh();
} catch (err: unknown) {
setPermission('denied');
setError(err instanceof Error ? err.message : 'permission denied');
}
}, [refresh]);
const handleInput = useCallback(
async (id: string) => {
const next = id === '' ? null : id;
setInputId(next);
await setAudioInputDevice(next);
},
[setAudioInputDevice],
);
const handleOutput = useCallback(
async (id: string) => {
const next = id === '' ? null : id;
setOutputId(next);
await setAudioOutputDevice(next);
},
[setAudioOutputDevice],
);
const outputSupported =
typeof HTMLAudioElement !== 'undefined' &&
typeof HTMLAudioElement.prototype.setSinkId === 'function';
return (
<div className="space-y-4">
<div>
<div className="text-sm font-semibold text-fg">
{t('app:settings.mic_title', { defaultValue: 'Mikrofon' })}
</div>
<p className="mt-1 text-xs text-fg-muted">
{t('app:settings.mic_hint', {
defaultValue: 'Eingabegerät. Bei aktivem Anruf wird live umgeschaltet.',
})}
</p>
<div className="mt-2 flex items-center gap-2">
<select
value={inputId ?? ''}
onChange={(e) => void handleInput(e.target.value)}
className="flex-1 rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm text-fg focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
<option value="">
{t('app:settings.mic_default', { defaultValue: 'Systemstandard' })}
</option>
{inputs.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || t('app:settings.mic_unnamed', { defaultValue: 'Unbenannt' })}
</option>
))}
</select>
<button
type="button"
onClick={() => void refresh()}
className="cursor-pointer rounded-lg border border-line bg-surface-2 px-3 py-2 text-xs font-medium text-fg transition hover:bg-surface-3"
>
{t('app:settings.mic_refresh', { defaultValue: 'Neu laden' })}
</button>
</div>
</div>
<div>
<div className="text-sm font-semibold text-fg">
{t('app:settings.speaker_title', { defaultValue: 'Ausgabegerät' })}
</div>
<p className="mt-1 text-xs text-fg-muted">
{t('app:settings.speaker_hint', {
defaultValue:
'Lautsprecher oder Kopfhörer. Wird auf alle aktiven Audio-Streams angewendet.',
})}
</p>
{!outputSupported && (
<p className="mt-1 text-xs text-amber-600 dark:text-amber-300">
{t('app:settings.speaker_unsupported', {
defaultValue: 'Browser unterstützt setSinkId nicht — Ausgabe folgt System-Default.',
})}
</p>
)}
<div className="mt-2 flex items-center gap-2">
<select
value={outputId ?? ''}
disabled={!outputSupported}
onChange={(e) => void handleOutput(e.target.value)}
className="flex-1 rounded-lg border border-line bg-surface-2 px-3 py-2 text-sm text-fg focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:opacity-50"
>
<option value="">
{t('app:settings.mic_default', { defaultValue: 'Systemstandard' })}
</option>
{outputs.map((d) => (
<option key={d.deviceId} value={d.deviceId}>
{d.label || t('app:settings.mic_unnamed', { defaultValue: 'Unbenannt' })}
</option>
))}
</select>
</div>
</div>
{permission !== 'granted' && (
<div className="flex items-center justify-between gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-700 dark:text-amber-200">
<span>
{t('app:settings.mic_permission_hint', {
defaultValue:
'Ohne Mikrofon-Freigabe erscheinen Gerätenamen nicht. Einmal erlauben und Liste lädt neu.',
})}
</span>
<button
type="button"
onClick={() => void requestPermission()}
className="shrink-0 cursor-pointer rounded-md bg-amber-600 px-2.5 py-1 text-xs font-semibold text-white transition hover:bg-amber-500"
>
{t('app:settings.mic_grant', { defaultValue: 'Freigeben' })}
</button>
</div>
)}
{error && (
<p className="text-xs text-rose-600 dark:text-rose-300">{error}</p>
)}
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
// Shim sumo types to the non-sumo types package. sumo is an API superset of
// libsodium-wrappers; its runtime exports match the standard wrappers module
// and additionally include `crypto_pwhash` (Argon2id). Reuse the existing
// `@types/libsodium-wrappers` definitions rather than duplicating them.
declare module 'libsodium-wrappers-sumo' {
import sodium from 'libsodium-wrappers';
export default sodium;
export * from 'libsodium-wrappers';
}
+6
View File
@@ -74,6 +74,7 @@ export default {
'live-dot': 'liveDotPulse 1.5s ease-in-out infinite',
'slide-in-call': 'slideInCall 0.4s cubic-bezier(0.22,1,0.36,1)',
'fs-hint': 'fsHintFade 3.5s ease-out forwards',
'reaction-pop': 'reactionPop 220ms cubic-bezier(0.34, 1.56, 0.64, 1)',
},
keyframes: {
blob: {
@@ -110,6 +111,11 @@ export default {
'15%, 75%': { opacity: '1', transform: 'translate(-50%, 0)' },
'100%': { opacity: '0', transform: 'translate(-50%, -6px)' },
},
reactionPop: {
'0%': { opacity: '0', transform: 'scale(0.4)' },
'70%': { opacity: '1', transform: 'scale(1.15)' },
'100%': { opacity: '1', transform: 'scale(1)' },
},
},
boxShadow: {
glow: '0 0 40px -8px rgba(99, 102, 241, 0.35)',
+5 -5
View File
@@ -16,11 +16,11 @@ export default defineConfig({
},
},
optimizeDeps: {
// libsodium-wrappers 0.7.16 ships a broken "import" condition in its
// package exports (the ESM bundle references a sibling ./libsodium.mjs
// that isn't in the published artefact). Force esbuild to pick the
// "require" condition so the self-contained CJS build is used.
include: ['libsodium-wrappers'],
// libsodium-wrappers-sumo (and the compact variant) ship broken "import"
// conditions in package exports the ESM bundle references a sibling
// ./libsodium.mjs that isn't in the published artefact. Force esbuild to
// pick the "require" condition so the self-contained CJS build is used.
include: ['libsodium-wrappers-sumo'],
esbuildOptions: {
conditions: ['require', 'node', 'default'],
},
@@ -10,6 +10,11 @@
<link rel="stylesheet" href="styles/variants.css">
<link rel="stylesheet" href="styles/rail.css">
<link rel="stylesheet" href="styles/call.css">
<link rel="stylesheet" href="styles/pages.css">
<style>
/* Cache-busting inline override for rail page-mode grid */
.rail-layout.page-mode { grid-template-columns: 64px 1fr !important; }
</style>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js" integrity="sha384-hD6/rw4ppMLGNu3tX5cjIb+uRZ7UkRJ6BPkLpg4hAu/6onKUg4lLsHAs9EBPT82L" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js" integrity="sha384-u6aeetuaXnQ38mYT8rp6sbXaQe3NL9t+IBXmnYxwkUI2Hw4bsp2Wvmx4yRQF1uAm" crossorigin="anonymous"></script>
@@ -57,6 +62,7 @@ const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
<script src="components/icons.jsx" type="text/babel"></script>
<script src="components/data.jsx" type="text/babel"></script>
<script src="components/call.jsx" type="text/babel"></script>
<script src="components/pages.jsx" type="text/babel"></script>
<script src="components/app.jsx" type="text/babel"></script>
<script type="text/babel">
+312 -214
View File
@@ -1,30 +1,38 @@
# Handoff: ChatApp — Clean Rail Redesign + Discord-Style Call UI
# Handoff: ChatApp — Clean Rail Redesign (Chat + Friends + Admin + Settings + Calls)
## Overview
This package contains the full design spec for redesigning the existing ChatApp (Netralax) interface around a **Clean Rail** layout aesthetic, plus a complete **Discord-style call system** (incoming call, in-call dock, picture-in-picture, fullscreen cinema mode).
Full design spec for redesigning the existing ChatApp (Netralax) interface around a **Clean Rail** layout aesthetic. Covers **four main screens** plus the complete call UX:
The redesign covers:
1. The main chat interface (icon-rail sidebar + chat list + conversation area) in both **light** and **dark** mode.
2. The call UX: incoming call overlay → active call docked above the chat (so users can keep typing while on a call) → fullscreen cinema mode → minimizable PiP bubble.
1. **Chat** — icon-rail + chat list + conversation area
2. **Friends** — friends list, outgoing requests, incoming requests, user search
3. **Admin** — stats, invite-code management, user administration
4. **Settings** — account, appearance, privacy, voice/audio, screenshare, devices, danger zone
5. **Calls** — incoming overlay → in-call dock → fullscreen → picture-in-picture
All screens work in **light** and **dark** mode.
---
## About the Design Files
The files in this bundle are **design references created in HTML/React/CSS** — prototypes showing the intended look, layout, and behavior. They are **not production code** to copy verbatim.
Your task is to **recreate these designs inside the existing ChatApp codebase**, using its established patterns (existing React components, styling conventions, state management, icon library, etc.). If some tokens or helper components don't exist yet in the codebase, add them but keep them aligned with what's already there.
Your task is to **recreate these designs inside the existing ChatApp codebase** using its established patterns (existing React components, styling conventions, state management, icon library, etc.). If some tokens or helper components don't exist yet in the codebase, add them but keep them aligned with what's already there.
The design files are organized as:
- `ChatApp Redesign.html` — entry HTML that boots the prototype
- `components/app.jsx` — main layout (rail + chat list + chat area, plus call state machine)
- `components/call.jsx`all call UI components (IncomingCallScreen, ActiveCallScreen, ParticipantTile, CallControls, PipCall)
- `components/icons.jsx`SVG icon set used
File layout:
- `ChatApp Redesign.html` — entry HTML (open in a browser to see the prototype)
- `components/app.jsx` — main layout (rail + chat list + chat area + call state machine + tab switching)
- `components/pages.jsx`**Friends, Admin, Settings page components** plus shared page primitives (PageHeader, Section, Toggle, SegmentedControl, Row, Empty, Banner, FlagChip, FriendRow)
- `components/call.jsx`call UI (IncomingCallScreen, ActiveCallScreen, ParticipantTile, CallControls, PipCall)
- `components/icons.jsx` — SVG icon set
- `components/data.jsx` — dummy chat/message data
- `styles/base.css` — shared base tokens + layout primitives
- `styles/variants.css``variant-clean` light + dark token definitions (this is the look you're targeting)
- `styles/variants.css``variant-clean` light + dark token definitions
- `styles/rail.css` — rail-layout specifics
- `styles/call.css` **all call UI styles** (the most important file for the call feature)
- `screenshots/` — reference images of each state
- `styles/call.css` — call UI styles
- `styles/pages.css` — **Friends/Admin/Settings page styles**
- `screenshots/` — reference images
## Fidelity
@@ -36,13 +44,13 @@ The design files are organized as:
### Colors — Light mode (`.variant-clean`)
```
--bg: #fafaf9 (app background)
--bg-2: #f4f4f2 (secondary surfaces, hover, search input)
--bg-3: #ffffff (elevated surfaces — chat list, chat area, cards)
--fg: #0a0a0f (primary text)
--fg-muted: #737380 (secondary text, icons)
--line: rgba(10,10,15,0.08) (dividers, borders)
--accent: #4F46E5 (indigo — primary actions, active states, my-bubble)
--bg: #fafaf9
--bg-2: #f4f4f2
--bg-3: #ffffff
--fg: #0a0a0f
--fg-muted: #737380
--line: rgba(10,10,15,0.08)
--accent: #4F46E5
--accent-fg: #ffffff
```
@@ -54,20 +62,19 @@ The design files are organized as:
--fg: #f4f4f5
--fg-muted: #8a8a99
--line: rgba(255,255,255,0.07)
--accent: #6D73FF (slightly lighter indigo for contrast)
--accent: #6D73FF
--accent-fg: #ffffff
```
### Status / Semantic Colors (both modes)
### Semantic Colors
```
Speaking/Online/Success: #16a34a light · #22c55e / #4ade80 dark
Danger/Decline/Hangup: #dc2626 (hover #b91c1c) · #fb7185 dark accent
Warning/Idle: #f59e0b
Live/Recording: #ef4444
E2EE indicator (light): #16a34a (dark: #4ade80)
Success / Online / E2EE: #16a34a (light) · #4ade80 / #22c55e (dark)
Danger / Decline: #dc2626 / #b91c1c hover · #fb7185 (dark accent for borders/text)
Warning / Expired: #f59e0b · #d97706 light · #fbbf24 dark
Live / Recording: #ef4444
```
### Avatar color swatches (assigned per chat)
### Avatar swatches (assigned per user)
```
violet: bg #ddd6fe / fg #5b21b6 (dark: #312E81 / #C4B5FD)
amber: bg #fde68a / fg #78350f
@@ -76,239 +83,330 @@ teal: bg #99f6e4 / fg #134e4a (dark: #134e4a / #99f6e4)
```
### Typography
- Family: `'Inter', system-ui, sans-serif` — Inter is the base. Display/headline use `'Outfit'` (participant name in IncomingCall).
- Family: `'Inter', system-ui, sans-serif` base; display `'Outfit'` (page titles, call participant name, stat-card values); mono `'JetBrains Mono'` (invite codes, device IDs, keyboard hotkeys, inline stats).
- Scale:
- Chat title / participant name large: 24px / 700
- Primary labels, chat name: 1415px / 600
- Body (bubbles, messages): 14px / 400500
- Meta, timestamps, presence: 1112px / 400500
- Rail tooltips, badges: 1011px / 500600
- Uppercase eyebrow (e.g. "EINGEHENDER ANRUF"): 12px / 600 / letter-spacing 0.12em
- Page title (`Freunde`, `Admin`, `Einstellungen`, call participant): 28px (page) / 24px (call) / 700 / Outfit / letter-spacing -0.02em
- Section label (uppercase eyebrow): 11px / 600 / tracked 0.08em
- Body labels, chat name, friend name: 1415px / 600
- Body text, bubbles, settings hint: 1214px / 400500
- Meta, timestamps, handles, stat labels: 1112px / 500, uppercase 1011px tracked 0.06em
- Mono values: 1112px / JetBrains Mono / 500
### Spacing
- Container padding: 16px (call-stage), 1420px (topbars, composer)
- Tile gap in grid: 810px
- Control-button row gap: 810px
- Border radius scale: 4 (small), 8 (tiles/badges), 10 (buttons), 14 (cards, large buttons), 18 (bubbles, bottom-fs controls), 24 (modal/card)
### Spacing / Radius
- Page content max-width: **820px**, centered, 28px top padding, 32px horizontal.
- Section card radius 16, section header padded 16×20 with bottom border, section body padded 16×20 gap 14.
- Button radius 810, chip/pill 999, stat card 12, device card 12.
- Toggle switch: 40×22 with 16×16 thumb, 2px inset, transitions all 0.2s.
### Shadows
- Elevated card light: `0 20px 60px rgba(0,0,0,0.1)`
- Elevated card dark: `0 20px 60px rgba(0,0,0,0.5)`
- Accent button: `0 4px 14px rgba(22,163,74,0.3)` (green accept) / same pattern for accent
- PiP glow: `0 12px 40px rgba(0,0,0,0.2), 0 0 0 3px rgba(79,70,229,0.15)`
- Accent button: `0 4px 14px rgba(79,70,229,0.25)`
- Avatar-large glow: `0 2px 6px rgba(0,0,0,0.08)`
### Motion
- Standard UI transition: `all 0.15s`
- Pulse ring (incoming call): `2s ease-out infinite`, scale 0.85→1.25, opacity 0.6→0
- Audio pulse (speaking ring): `1.3s ease-out infinite`, scale 1→1.3
- Live dot: `1.5s ease-in-out infinite`, opacity 1↔0.4
- PiP entrance: `slideInCall 0.4s cubic-bezier(0.22,1,0.36,1)`
- Fullscreen hint fade: 3.5s total (015% fade in, 75100% fade out)
- Toggle switch thumb: `transform 0.2s`
- PTT hotkey capture pulse: `keyPulse 1.2s ease-in-out infinite` (opacity 1↔0.6)
---
## Screens / Views
## Tab Switching Behavior
### 1. Main Chat — Clean Rail Layout
The icon rail (`.icon-rail`) holds 4 primary tabs: **Chats**, **Friends**, **Admin**, **Settings**. Clicking an icon sets `activeTab`. Layout adapts:
- **`activeTab === 'chats'`** → renders icon-rail + chat-list + chat-area (3 columns: `64px 280px 1fr`).
- **`activeTab !== 'chats'`** → renders icon-rail + page content (2 columns: `64px 1fr`). Chat list is removed. The page component (`FriendsPageContent`, `AdminPageContent`, `SettingsPageContent`) renders inside the chat-area slot with its own scroll container and 820px centered inner.
The `.rail-layout.page-mode` class toggles the grid-template-columns. **IMPORTANT:** this override is inlined in the entry HTML as a `<style>` block to avoid CSS-cache issues during dev. In production, put it in your main stylesheet.
The **call dock** and **call screen switcher** are only shown on the chats tab.
---
## Screen 1: Chat
**Structure (left → right):**
- **Icon Rail** (72px wide): brand logo at top, tab buttons (Chats / Friends / Admin), spacer, Settings + theme-toggle at bottom. Active tab shows a vertical pill indicator on the left edge.
- **Chat List** (280px wide): header with title + "new chat" icon, search input, list of `ChatItem`s (avatar + name + time + preview, optional unread dot), `rail-user` footer showing own profile + quick mute/settings.
- **Chat Area** (flex, fills rest): chat header (counterpart avatar + name + presence/handle + search/voice/video buttons), messages scroll area, composer at bottom.
**Chat header actions (right side):** search icon, phone icon, video icon. Phone triggers voice call (`callScreen → 'active'`, `callState.video = false`), Video triggers video call (`callState.video = true`).
- **Icon Rail** (64px): brand logo, tab buttons (Chats/Friends/Admin), spacer, Settings + theme-toggle at bottom. Active tab shows a vertical pill indicator on the left edge.
- **Chat List** (280px): header with title + "new chat" icon, search input, list of `ChatItem`s (avatar + name + time + preview, optional unread dot), `rail-user` footer showing own profile + quick mute/settings.
- **Chat Area** (flex): chat header (counterpart avatar + name + presence/handle + search/voice/video), messages, composer.
**Message bubbles:**
- Mine (outgoing): filled accent bg, white text, radius `18px 18px 4px 18px`.
- Theirs (incoming): transparent bg, 1px line border, fg text, radius `18px 18px 18px 4px`.
- Avatars appear only on the **last message of a run** from that sender.
- Reactions: pill row below bubble, `.mine` = filled accent.
- System events ("Kaiwandi hat einen Anruf gestartet — Anruf beitreten"): centered `event-pill`, muted bg, muted fg, 11px.
**Composer:** plus button (attach), rounded input bar with inline emoji + mic icons, send button.
- Mine: filled accent bg, white text, radius `18px 18px 4px 18px`.
- Theirs: transparent bg, 1px line border, fg text, radius `18px 18px 18px 4px`.
- Avatars only on the **last message of a run**.
- Reactions: pill row below, `.mine` = filled accent.
- System events: centered `event-pill`, muted bg/fg, 11px.
---
### 2. Incoming Call Overlay
## Screen 2: Friends
Full-bleed overlay replacing the chat area (takes over `.chat-area` space), radial-gradient background tinted with accent.
Component: **`FriendsPageContent`** (`components/pages.jsx`)
Centered card (420px wide):
- Eyebrow "EINGEHENDER ANRUF" (uppercase, 12px, tracked)
- Large avatar (96px) with **two pulsing rings** (staggered 1s)
- Caller name (24px / 700 / Outfit)
- Subtitle row: lock icon + "E2E verschlüsselt · Voice Call"
- Two side-by-side action buttons:
- **Ablehnen**: transparent, red border/text, hover = 8% red bg
- **Annehmen**: green #16a34a, white, shadow
### Layout
- `PageHeader` with title "Freunde" and subtitle `"{N} Freunde · {M} offene Anfragen"`.
- **Global search bar** (sticky at top of scroll): icon + input, placeholder "Benutzer suchen oder hinzufügen…". Focused state → border becomes accent.
- **Tabs** (only when not searching): 3 pill tabs with inline counts — `Freunde`, `Ausgehend`, `Anfragen`. When there are pending incoming requests, the tab count badge is red (`.tab-count.highlight`).
- **List area**: either tab content OR search results, mutually exclusive.
### 3. Active Call — Docked (Default)
### Search behavior
- Trigger: input.length ≥ 2. Below that, tabs show.
- Filters a global user directory (API: `GET /api/users/search?q={query}` — returns up to 20 matches).
- Each result renders a `FriendRow` with a single primary button: "Anfrage senden" (icon + label). On click → `POST /api/friendships` with `{ targetUserId }`, optimistically updates the row to "Angefragt".
- Empty state: "Keine Ergebnisse für „{query}"" with Search icon.
**CRITICAL layout decision:** The active call does NOT take over the chat area. Instead it renders as a **dock above the messages**, taking roughly 50% of the chat-area height (min 280px, max 420px). The chat header is **hidden** while the dock is active (redundant — call topbar shows the channel name). Messages + composer remain fully visible and usable below, so users can keep chatting during the call. This is the Discord desktop pattern.
### Tabs
**Dock content:**
- **Call topbar**: left side shows group icon + "Die Squad" + duration (tabular-nums), with E2E verschlüsselt below in success-green. Right side has 3 mode toggles: Grid / Focus / Fullscreen.
- **Call stage**: fills the remaining space, renders either:
- **Grid**: CSS grid, 2×2 for 4 people, 3×2 for 56, 1fr 1fr for 2.
- **Focus**: main speaker tile takes most height, bottom strip with 110px-tall smaller tiles for others.
- **Fullscreen**: switches to `mode === 'fullscreen'` — see screen 4.
- **Call controls bar** at the bottom of the dock: Mic, Video, Screen-share, Participants, **Hangup** (wider, red). Compact 36px buttons when docked.
**Freunde** (`status === 'accepted'`):
- FriendRow with: Nachricht (primary button opens conversation), Voice icon button (starts call), "Entfernen" (danger-ghost, confirms before `DELETE /api/friendships/{id}`).
- Empty: "Noch keine Freunde. Suche oben nach Benutzern um anzufangen."
### 4. Active Call — Fullscreen Cinema Mode
**Ausgehend** (`status === 'pending' && direction === 'outgoing'`):
- "Wartet auf Antwort…" italicized + `btn-ghost` "Abbrechen" → `DELETE /api/friendships/{id}`.
- Empty: "Keine ausgehenden Anfragen."
When mode = `fullscreen`:
- Entire call-dock container becomes absolute-positioned and takes over everything below the window bar (chat list still visible on the left).
- The **call topbar is hidden** entirely.
- Main speaker fills the whole frame, no border/radius.
- Participants strip moves to a **floating column in the bottom-right** (`.fs-strip`): 180px wide, 100px tall tiles, glass-blurred bg.
- **Call controls bar floats** at bottom center — glass pill: `rgba(10,10,15,0.7)` + `backdrop-filter: blur(20px)` + subtle border + 18px radius.
- **"Esc zum Verlassen" hint** fades in top-center on entry and auto-fades out over 3.5s. Pressing Esc or clicking Grid/Focus buttons exits.
- **No visible X button** (intentional — keyboard-only exit, confirmed design decision).
**Anfragen** (`status === 'pending' && direction === 'incoming'`):
- `btn-primary` "Annehmen" (check icon) → `PATCH /api/friendships/{id}` with `{ accept: true }`; `btn-ghost` "Ablehnen" → same endpoint `{ accept: false }`.
- Empty: "Keine eingehenden Anfragen."
### 5. Participant Tile — Shared Component
### FriendRow (shared)
12px gap row, hover → `bg-2`. Avatar (with presence indicator on accepted friends), name (14px/600), handle `@{username}` (12px muted), actions on the right.
A participant is either in **audio-only**, **video**, or **sharing screen** mode.
- Tile border: 1px `var(--line)`, radius 14 (10 in dock). Hover → border becomes accent. `.speaking` → 2px green border + green glow shadow. `.focused` → accent border.
- **Audio-only**: centered avatar (72px large, 44px small). When `speaking`, a green ring pulses around the avatar (`::before` pseudo).
- **Video**: placeholder stub (gradient background + centered avatar, since real video not in scope here).
- **Screenshare**: renders a "fake window" — chrome row with 3 dots, content row with grey skeleton lines + one accent-tinted block. A glass badge top-left: monitor icon + "Max teilt Bildschirm" (badge hidden on small tiles).
- **Meta row** (absolute, bottom 8px, glass): left shows crown (if me) + name + lock (if E2EE), right shows muted mic icon (red chip) and/or sharing icon (green chip).
### 6. Picture-in-Picture (PiP)
A compact 260px pill docked bottom-right of the chat area:
- 44px preview square (avatar of speaker, or mini shared-window placeholder if someone's sharing)
- Title "Die Squad · {participantCount}"
- Subtitle row: red pulsing dot + "Live · tippe zum Öffnen"
- Circular red hangup button on the right
- Whole thing is clickable → expands back to active call
- Entrance animation: slide from bottom + fade in (`slideInCall`)
- Shadow: standard + 3px accent glow ring
### Data shapes
```ts
type Friendship = {
id: string;
userId: string; // the OTHER user's ID
displayName: string;
username: string; // @handle
avatarColor: 'violet'|'amber'|'rose'|'teal';
initial: string; // derived from displayName[0] uppercase
status: 'accepted' | 'pending';
direction: 'outgoing' | 'incoming' | null; // null when accepted
presence?: 'online' | 'idle' | 'dnd' | 'offline';
};
```
---
## Interactions & Behavior
## Screen 3: Admin
### Call State Machine (lives in `ChatApp`)
Component: **`AdminPageContent`** (`components/pages.jsx`)
Gated route — only accessible if `currentUser.isAdmin === true`. If not, render 403 "Kein Zugriff" page.
### Layout
1. **`PageHeader`** "Admin" + subtitle `"{userCount} User · {activeInviteCount} aktive Invites"`.
2. **Stats grid** (4 cards, 1fr × 4 @ ≥1200px, 2×2 below):
- Gesamt User
- Admins
- Gebannt (value in `#dc2626` / dark `#fb7185`)
- Aktive Invites
- Each card: 11px uppercase tracked label, 28px Outfit bold value, tabular-nums.
3. **System section**: single `Toggle` for `invites_enabled`. Hint: "Wenn aus, können keine neuen User per Invite-Code beitreten."
- Maps to `PATCH /api/admin/settings { invitesEnabled: boolean }`.
4. **Invite-Codes section**:
- Header action: **+ Neuer Code** primary button → opens modal (out of scope here) with fields for `code` (optional; auto-generated if blank), `usesLimit` (int or ∞), `expiresAt` (date or never).
- Table columns: Code · Nutzungen · Ablauf · Status · actions.
- Code column: mono 12px.
- Status pill: `Aktiv` (green), `Abgelaufen` (amber), `Deaktiviert` (red).
- Actions (per row, right-aligned): Copy icon (shows check on copy, 1.4s timeout), "Deaktivieren/Aktivieren" ghost xs button, red Trash icon.
- API:
- List: `GET /api/admin/invites`
- Create: `POST /api/admin/invites`
- Toggle: `PATCH /api/admin/invites/{code} { disabled: boolean }`
- Delete: `DELETE /api/admin/invites/{code}`
5. **Benutzer section**:
- Row per user: avatar + name (with **Admin badge** if admin — pill with crown icon, accent bg + `accent-fg`) + `@handle · beigetreten {date}` meta.
- Flag chips on the right:
- **Admin** (toggle accent when active)
- **Invite-Block** (toggle accent when active) — prevents this user from creating invites
- **Bann** (`tone="danger"` — red when active)
- Click a chip → `PATCH /api/admin/users/{userId} { [flag]: boolean }`. Optimistic update.
- No delete — banning is the terminal state.
### Data shapes
```ts
type Invite = {
code: string;
usesCount: number;
usesLimit: number | null; // null = unlimited
expiresAt: string | null; // ISO date
disabled: boolean;
createdBy: string; // userId
createdAt: string;
};
type AdminUser = {
userId: string;
displayName: string;
username: string;
initial: string;
avatarColor: string;
isAdmin: boolean;
blockedFromInviting: boolean;
banned: boolean;
joinedAt: string; // display-formatted in list
};
```
---
## Screen 4: Settings
Component: **`SettingsPageContent`** (`components/pages.jsx`)
### Sections (in this exact order)
**1. Account**
- `avatar-control` row: 64px circular avatar with initial, label + hint, "Ändern" primary, "Entfernen" danger-ghost.
- Upload: 512×512 max, WebP only, client-side crop, `POST /api/me/avatar`.
- `row-stack` with 3 `Row` entries:
- Benutzername (editable — click to inline-edit, `PATCH /api/me { username }`, uniqueness check)
- Anzeigename (editable, `PATCH /api/me { displayName }`)
- User-ID (mono, read-only)
**2. Aussehen**
- Sprache: `SegmentedControl` Deutsch/English → `PATCH /api/me { locale }` and updates i18n context.
- Theme: `SegmentedControl` ☀ Light / ☾ Dark → toggles dark mode globally. Wire to your theme provider; persist in localStorage + `PATCH /api/me { theme }`.
**3. Datenschutz**
- `Toggle` Lesebestätigungen (bidirectional — hint explains).
- `Toggle` DMs von Fremden erlauben.
**4. Sprache & Audio**
- `SegmentedControl` Audio-Qualität: `Sprache` (default) vs `HiFi`.
- **Sprache**: 48 kbps Mono Opus, 48 kHz, DSP on (noise suppression + echo cancellation + auto-gain).
- **HiFi**: 510 kbps Stereo Opus, 48 kHz, DSP off.
- Hint text updates live with the mode.
- Inline `stats-inline` box showing the 4 resolved parameters (Bitrate / Channels / Sample / DSP).
- Divider.
- `Toggle` Push-to-Talk. When enabled, an extra row appears: label "Hotkey" + `.key-capture` button showing the current key. Click → enters capture mode (pulsing animation), next keydown sets the key. Esc cancels.
- Divider.
- `Toggle` E2EE (default on). Hint: all participants must have it on.
**5. Bildschirmfreigabe**
- `SegmentedControl` Flüssig / Balanced / Scharf:
- Flüssig: 3 Mbps, 1280×720, 60 fps
- Balanced: 6 Mbps, 1920×1080, 30 fps (default)
- Scharf: 12 Mbps, 2560×1440, 30 fps
- Inline `stats-inline` shows resolved params.
**6. Geräte**
- `device-card` (green-tinted): lock icon + "Dieses Gerät", followed by Row stack: Name, Plattform, Device-ID (mono).
- `device-backup` card: password input + "Export erstellen" button → generates an encrypted JSON file containing the device's private key + room keys, downloaded client-side (never sent to server).
**7. Danger Zone**
- Single `btn-danger` "Abmelden" (full red button). Triggers sign-out + clears all local state.
### SegmentedControl
Inline group with 3px padding, transparent buttons, active button elevated with white bg (light) or elevated surface (dark) + shadow. 12px/500.
### Toggle
40×22 track, 16×16 thumb, 999 radius. Off: `bg-2` bg + `line` border. On: `accent` bg+border. Thumb translates 18px on. Full click target = entire row (via `<label>`).
### State persistence
Every setting writes to `PATCH /api/me/settings { [key]: value }` on change, with a debounced save (300ms for toggles is fine, immediate for segmented controls). Show a subtle top-right toast "Gespeichert" on success (not shown in this prototype).
---
## Screen 5: Calls (unchanged from previous scope)
See previous sections — Incoming → Active Dock → Fullscreen Cinema → PiP flow with `callScreen` + `callMode` state machine, Esc key handling, Discord-style dock above messages.
---
## Shared Page Primitives
All in `components/pages.jsx`. Re-use these across Friends/Admin/Settings; they define the aesthetic rhythm of the whole app.
```jsx
<PageHeader title="…" subtitle="…" actions={<button />} />
<Section title="…" action={<button />}>…</Section>
<Toggle label="…" hint="…" checked={} onChange={} />
<SegmentedControl value={} onChange={} options={[{value, label}]} />
<Row label="…" value="…" mono /> // key/value line in a stack
<Stat label="…" value="…" /> // used inside stats-inline
<Banner kind="error|success">…</Banner>
<Empty icon={Icon.X}>…</Empty> // for empty states
<FlagChip active={} tone="danger" onToggle={}>Admin</FlagChip>
<FriendRow profile={}>{actions}</FriendRow>
```
---
## API Endpoints (used by pages)
Friends:
```
GET /api/friendships → { accepted, outgoing, incoming }
POST /api/friendships { targetUserId } → creates outgoing
PATCH /api/friendships/{id} { accept: boolean }
DELETE /api/friendships/{id}
GET /api/users/search?q=… → up to 20 users (friendships excluded)
```
Admin:
```
GET /api/admin/stats → { userCount, adminCount, bannedCount, activeInviteCount }
GET /api/admin/settings → { invitesEnabled }
PATCH /api/admin/settings { invitesEnabled }
GET /api/admin/invites → Invite[]
POST /api/admin/invites { code?, usesLimit?, expiresAt? } → Invite
PATCH /api/admin/invites/{code} { disabled }
DELETE /api/admin/invites/{code}
GET /api/admin/users → AdminUser[]
PATCH /api/admin/users/{userId} { isAdmin? | blockedFromInviting? | banned? }
```
Settings / Me:
```
GET /api/me → profile + settings
PATCH /api/me { username? | displayName? | locale? | theme? }
PATCH /api/me/settings { readReceipts? | allowDmsFromStrangers? | audioQuality? | ptt? | pttKey? | e2ee? | screenShareQuality? }
POST /api/me/avatar multipart → new avatar URL
DELETE /api/me/avatar
GET /api/me/devices → Device[]
POST /api/me/devices/backup { passphrase } → encrypted blob download
POST /api/auth/signout
```
Scope assumption: your codebase already has most of these (see `FriendshipsContext.tsx`, `AdminPage.tsx`, `SettingsPage.tsx`). Wire the new UI to the existing hooks — don't rebuild the data layer.
---
## Call State Machine (unchanged)
```js
// Primary state
const [callScreen, setCallScreen] = useState('none'); // 'none' | 'incoming' | 'active' | 'pip'
const [callMode, setCallMode] = useState('grid'); // 'grid' | 'focus' | 'fullscreen'
const [focusedId, setFocusedId] = useState(firstSharingOrSpeakerId);
const [callState, setCallState] = useState({ muted: false, sharing: false, video: false, duration });
```
### Triggers & Transitions
- Chat-header **phone icon** click → `setCallScreen('active')`, `callState.video = false`
- Chat-header **video icon** click → `setCallScreen('active')`, `callState.video = true`
- Grid tile click → `setFocusedId(id); setCallMode('focus')`
- Focus/Grid/Fullscreen buttons in call topbar → set mode directly
- Incoming "Annehmen" → `setCallScreen('active')`
- Incoming "Ablehnen" → `setCallScreen('none')`
- Hangup → `setCallScreen('none')`
- PiP clicked → `setCallScreen('active')`
- PiP hangup (circle red btn) → `stopPropagation()` + `setCallScreen('none')`
- **Esc key** (global listener while `callScreen === 'active' && callMode === 'fullscreen'`) → `setCallMode('grid')`
### Chat Header Visibility Rule
```
if (callScreen === 'active' && callMode !== 'fullscreen') → hide chat header
else → show chat header
```
### Keyboard
- `Esc` exits fullscreen (only). No other global keybindings.
---
## State Management
Data shapes to wire up (see `components/call.jsx`):
```ts
type Participant = {
id: string;
name: string;
initial: string;
color: 'violet' | 'amber' | 'rose' | 'teal';
speaking: boolean;
muted: boolean;
video: boolean;
sharing?: boolean;
me?: boolean;
e2ee: boolean;
};
type CallState = {
muted: boolean;
sharing: boolean;
video: boolean;
duration: string; // "HH:MM:SS"
};
```
In production these all come from your real-time signaling layer (WebRTC, LiveKit, etc.). The prototype uses static data for layout purposes only — wire them to your call store.
---
## Assets
No custom imagery. Everything is SVG icons (inlined in `components/icons.jsx`) and CSS. Fonts from Google Fonts: `Inter`, `Outfit`.
Icons used in this scope: Chat, Friends, Shield, Settings, Logo, AddUser, Search, Phone, Video, Plus, Smile, Mic, MicOff, Send, Sun, Moon, Monitor, Lock, Crown, Grid, Focus, Maximize, PhoneOff.
Replace with your codebase's icon library if one exists (e.g. lucide-react, heroicons) — names match lucide conventions.
Triggers, keyboard and visibility rules identical to previous spec.
---
## Implementation Checklist
1. **Tokens**: add the Clean-variant light + dark CSS variables to your theme layer. If you already have a token system, map them to your existing names; otherwise create `--bg`, `--bg-2`, `--bg-3`, `--fg`, `--fg-muted`, `--line`, `--accent`, `--accent-fg`.
2. **Icon rail + chat list + chat area**: refactor the current top-nav layout into the 3-column rail layout. Use your existing `Avatar`, `ChatItem`, `Message` components — only restyle.
3. **Message bubbles**: outlined `them` / filled `me`, asymmetric radius, avatars only on last-of-run.
4. **Call state machine**: add the four `useState` hooks to whatever component owns the chat screen. Hook the Esc key effect.
5. **IncomingCallScreen**: new component, full-bleed overlay of `.chat-area`.
6. **Call dock**: new component, renders above `.messages`. Hide chat-header while docked.
7. **ParticipantTile**: audio / video / sharing modes, speaking ring, meta overlay.
8. **Fullscreen mode**: switch call container to position absolute, floating strip + floating controls + Esc hint.
9. **PiP**: minimizable widget bottom-right of chat area.
10. **Wire real data**: replace `CALL_PARTICIPANTS` dummy with your live call-session participants.
---
## Files in This Handoff
```
design_handoff_chatapp/
├── README.md (this file)
├── ChatApp Redesign.html (entry — open in browser to see the prototype)
├── components/
│ ├── app.jsx (chat app + rail layout + call state machine)
│ ├── call.jsx (Incoming / Active / Pip / ParticipantTile / CallControls)
│ ├── icons.jsx (all SVG icons)
│ └── data.jsx (dummy chats, messages)
├── styles/
│ ├── base.css
│ ├── variants.css (Clean light + dark tokens — this is your theme)
│ ├── rail.css (rail layout)
│ └── call.css (all call UI — highest priority file)
└── screenshots/
├── 01-chat-light.png
├── 03-chat-dark.png
├── 04-incoming-dark.png
├── 05-incall-grid-dark.png
├── 06-incall-focus-dark.png
├── 07-incall-fullscreen-dark.png
├── 09-pip-dark.png
└── 11-incall-light.png
```
1. **Tokens**: add the Clean variant light + dark CSS variables to your theme layer.
2. **Rail layout**: refactor top-nav to icon-rail + chat list + chat area (`.rail-layout`). Add `.rail-layout.page-mode` (2-column) for non-chat tabs.
3. **Tab switching**: lift `activeTab` state. Conditionally render chat area vs page content.
4. **Page primitives**: implement `PageHeader`, `Section`, `Toggle`, `SegmentedControl`, `Row`, `Stat`, `Banner`, `Empty`, `FlagChip`, `FriendRow` using your existing component library where possible.
5. **FriendsPage**: wire to `FriendshipsContext` + user-search endpoint. Tabs + search + optimistic mutations.
6. **AdminPage**: stats grid + system toggle + invites table (copy-to-clipboard, enable/disable, delete) + users list (flag chips with optimistic updates).
7. **SettingsPage**: all 7 sections with two-way binding to user profile + settings. Debounced saves. Theme toggle wired to theme context.
8. **Message bubbles + call UX** (already specified in previous scope — unchanged).
---
## Notes for Claude Code
- The Clean Rail variant is **Variante 2** in the prototype's variant switcher — ignore the other 5 aesthetic variants (Playful, Y2K, Cyberpunk, Warm, Brutal), they were design exploration and not the chosen direction.
- Prefer composition over copying raw CSS. If the codebase has a `Card`, `Button`, `Tooltip`, use them.
- Duration ("00:12:47") should tick live from the call start timestamp, not be static.
- For WebRTC/media handling: this package specifies **UI only**. The media/signaling layer is out of scope and already exists in the codebase (see `CallUI.tsx`, `InCallPanel.tsx`).
- The Clean Rail variant is **Variante 2** in the prototype's variant switcher — ignore the other 5 aesthetic variants (Playful, Y2K, Cyberpunk, Warm, Brutal).
- `components/pages.jsx` uses **dummy data** for display. Replace with your live contexts (`FriendshipsContext`, admin API hooks, user/settings hooks).
- Prefer composition over copying raw CSS. If the codebase has a `Card`, `Button`, `Toggle`, use them.
- Keep German copy as-is — it matches the existing product. English translations via i18n are a separate task.
- The `.rail-layout.page-mode` grid override is inlined in the HTML in this prototype. Move it to your main stylesheet.
- All settings that affect media (audio quality, PTT, E2EE, screen-share quality) must be read at **call-start time** by the existing call code — they do not hot-apply to an active call.
+18 -6
View File
@@ -188,7 +188,7 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
<div className="app-body">
{variant.layout === 'rail' ? (
<div className="rail-layout">
<div className={`rail-layout ${activeTab !== 'chats' ? 'page-mode' : ''}`}>
{/* Icon rail left */}
<div className="icon-rail">
<div className="rail-brand" title="Netralax"><Icon.Logo /></div>
@@ -213,7 +213,8 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
{isDark ? <Icon.Sun /> : <Icon.Moon />}
</button>
</div>
{/* Chatlist + user profile at bottom */}
{/* Chatlist + user profile at bottom — only on chats tab */}
{activeTab === 'chats' && (
<div className="chat-list rail-chatlist">
<div className="chat-list-header">
<div className="chat-list-title">Chats</div>
@@ -235,8 +236,13 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
<button className="icon-btn" title="Einstellungen"><Icon.Settings /></button>
</div>
</div>
{/* Chat area (unchanged below) */}
<div className="chat-area">
)}
{/* Chat area OR page content */}
<div className={`chat-area ${activeTab !== 'chats' ? 'has-page' : ''}`}>
{activeTab === 'friends' && <FriendsPageContent />}
{activeTab === 'admin' && <AdminPageContent />}
{activeTab === 'settings' && <SettingsPageContent isDark={isDark} onToggleDark={onToggleDark} />}
{activeTab === 'chats' && <>
{!(callScreen === 'active' && callMode !== 'fullscreen') && (
<div className="chat-header">
<Avatar chat={activeChat} />
@@ -290,6 +296,7 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
</div>
<button className="composer-btn"><Icon.Send /></button>
</div>
</>}
</div>
</div>
) : (
@@ -329,6 +336,10 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
</div>
<div className="main-area">
{activeTab === 'friends' && <div className="chat-area has-page" style={{width: '100%'}}><FriendsPageContent /></div>}
{activeTab === 'admin' && <div className="chat-area has-page" style={{width: '100%'}}><AdminPageContent /></div>}
{activeTab === 'settings' && <div className="chat-area has-page" style={{width: '100%'}}><SettingsPageContent isDark={isDark} onToggleDark={onToggleDark} /></div>}
{activeTab === 'chats' && <>
<div className="chat-list">
<div className="chat-list-header">
<div className="chat-list-title">Chats</div>
@@ -382,13 +393,14 @@ const ChatApp = ({ variant, showCall, showProfile, isDark, onToggleDark }) => {
<button className="composer-btn"><Icon.Send /></button>
</div>
</div>
</>}
</div>
</>
)}
</div>
{/* Call screen switcher — only in Clean Rail */}
{variant.layout === 'rail' && (
{/* Call screen switcher — only in Clean Rail, only on chats tab */}
{variant.layout === 'rail' && activeTab === 'chats' && (
<div className="screen-switcher">
<button className={callScreen === 'none' ? 'active' : ''} onClick={() => setCallScreen('none')}>Chat</button>
<button className={callScreen === 'incoming' ? 'active' : ''} onClick={() => setCallScreen('incoming')}>Incoming</button>
@@ -82,6 +82,18 @@ const Icon = {
Minimize: () => (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"/></svg>
),
Copy: () => (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
),
Trash: () => (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
),
Alert: () => (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
),
Check: () => (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
),
};
Object.assign(window, { Icon });
+591
View File
@@ -0,0 +1,591 @@
// Freunde / Admin / Settings pages Clean Rail aesthetic
// ===================================================================
// SHARED PRIMITIVES
// ===================================================================
const PageHeader = ({ title, subtitle, actions }) => (
<div className="page-header">
<div>
<h1 className="page-title">{title}</h1>
{subtitle && <p className="page-subtitle">{subtitle}</p>}
</div>
{actions && <div className="page-header-actions">{actions}</div>}
</div>
);
const Section = ({ title, children, action }) => (
<section className="page-section">
<div className="page-section-header">
<h2 className="page-section-title">{title}</h2>
{action}
</div>
<div className="page-section-body">{children}</div>
</section>
);
const Toggle = ({ checked, onChange, label, hint, disabled }) => (
<label className={`toggle-row ${disabled ? 'disabled' : ''}`}>
<div className="toggle-copy">
<div className="toggle-label">{label}</div>
{hint && <div className="toggle-hint">{hint}</div>}
</div>
<span className={`toggle-switch ${checked ? 'on' : ''}`} onClick={() => !disabled && onChange(!checked)}>
<span className="toggle-thumb"></span>
</span>
</label>
);
const SegmentedControl = ({ options, value, onChange }) => (
<div className="segmented">
{options.map(opt => (
<button
key={opt.value}
className={`seg-btn ${value === opt.value ? 'active' : ''}`}
onClick={() => onChange(opt.value)}
>
{opt.label}
</button>
))}
</div>
);
const Row = ({ label, value, mono }) => (
<div className="row-kv">
<span className="row-label">{label}</span>
<span className={`row-value ${mono ? 'mono' : ''}`}>{value}</span>
</div>
);
const Stat = ({ label, value }) => (
<div className="stat">
<div className="stat-label">{label}</div>
<div className="stat-value">{value}</div>
</div>
);
const Banner = ({ kind = 'info', children }) => (
<div className={`banner ${kind}`}>
{kind === 'error' && <Icon.Alert />}
{kind === 'success' && <Icon.Check />}
<span>{children}</span>
</div>
);
const Empty = ({ icon: IconComp = Icon.Friends, children }) => (
<div className="empty-state">
<div className="empty-icon"><IconComp /></div>
<p>{children}</p>
</div>
);
// ===================================================================
// FRIENDS PAGE
// ===================================================================
const FRIENDS_DATA = [
{ id: 'max', userId: 'max', displayName: 'Max', username: 'maxx', initial: 'M', color: 'teal', status: 'accepted', direction: null, presence: 'online' },
{ id: 'lena', userId: 'lena', displayName: 'Lena', username: 'lena_k', initial: 'L', color: 'amber', status: 'accepted', direction: null, presence: 'online' },
{ id: 'tom', userId: 'tom', displayName: 'Tom', username: 'tomtom', initial: 'T', color: 'violet', status: 'accepted', direction: null, presence: 'idle' },
{ id: 'nico', userId: 'nico', displayName: 'nico', username: 'niklas', initial: 'N', color: 'teal', status: 'accepted', direction: null, presence: 'offline' },
{ id: 'julia', userId: 'julia', displayName: 'Julia', username: 'jul', initial: 'J', color: 'rose', status: 'accepted', direction: null, presence: 'dnd' },
{ id: 'ben', userId: 'ben', displayName: 'Ben', username: 'benny', initial: 'B', color: 'amber', status: 'pending', direction: 'outgoing' },
{ id: 'anna', userId: 'anna', displayName: 'Anna', username: 'anna_m', initial: 'A', color: 'violet', status: 'pending', direction: 'outgoing' },
{ id: 'kai', userId: 'kai', displayName: 'Kai', username: 'kaiser', initial: 'K', color: 'teal', status: 'pending', direction: 'incoming' },
{ id: 'sara', userId: 'sara', displayName: 'Sara', username: 'sari', initial: 'S', color: 'rose', status: 'pending', direction: 'incoming' },
];
const SEARCH_RESULTS = [
{ id: 'felix', userId: 'felix', displayName: 'Felix', username: 'felix_x', initial: 'F', color: 'violet' },
{ id: 'mia', userId: 'mia', displayName: 'Mia', username: 'mia_w', initial: 'M', color: 'amber' },
{ id: 'paul', userId: 'paul', displayName: 'Paul', username: 'paulk', initial: 'P', color: 'teal' },
];
const FriendRow = ({ profile, children }) => (
<div className="friend-row">
<Avatar chat={{initial: profile.initial, color: profile.color, presence: profile.presence}} />
<div className="friend-body">
<div className="friend-name">{profile.displayName}</div>
<div className="friend-handle">@{profile.username}</div>
</div>
<div className="friend-actions">{children}</div>
</div>
);
const FriendsPageContent = () => {
const [tab, setTab] = React.useState('friends');
const [query, setQuery] = React.useState('');
const accepted = FRIENDS_DATA.filter(f => f.status === 'accepted');
const outgoing = FRIENDS_DATA.filter(f => f.status === 'pending' && f.direction === 'outgoing');
const incoming = FRIENDS_DATA.filter(f => f.status === 'pending' && f.direction === 'incoming');
const showSearch = query.trim().length >= 2;
const tabs = [
{ key: 'friends', label: 'Freunde', count: accepted.length },
{ key: 'pending', label: 'Ausgehend', count: outgoing.length },
{ key: 'requests', label: 'Anfragen', count: incoming.length, highlight: incoming.length > 0 },
];
const currentList = tab === 'friends' ? accepted : tab === 'pending' ? outgoing : incoming;
return (
<div className="page-scroll">
<div className="page-inner friends-page">
<PageHeader title="Freunde" subtitle={`${accepted.length} Freunde · ${incoming.length} offene Anfragen`} />
<div className="search-wrap">
<Icon.Search />
<input
type="search"
placeholder="Benutzer suchen oder hinzufügen…"
value={query}
onChange={e => setQuery(e.target.value)}
/>
</div>
{showSearch && (
<div className="page-section">
<div className="page-section-header">
<h2 className="page-section-title">Suchergebnisse</h2>
</div>
<div className="friend-list">
{SEARCH_RESULTS.filter(r =>
r.displayName.toLowerCase().includes(query.toLowerCase()) ||
r.username.toLowerCase().includes(query.toLowerCase())
).map(p => (
<FriendRow key={p.id} profile={p}>
<button className="btn btn-primary">
<Icon.AddUser /> Anfrage senden
</button>
</FriendRow>
))}
{SEARCH_RESULTS.filter(r =>
r.displayName.toLowerCase().includes(query.toLowerCase()) ||
r.username.toLowerCase().includes(query.toLowerCase())
).length === 0 && (
<Empty icon={Icon.Search}>Keine Ergebnisse für {query}"</Empty>
)}
</div>
</div>
)}
{!showSearch && (
<>
<div className="tab-row">
{tabs.map(t => (
<button
key={t.key}
className={`tab-btn ${tab === t.key ? 'active' : ''}`}
onClick={() => setTab(t.key)}
>
{t.label}
<span className={`tab-count ${t.highlight ? 'highlight' : ''}`}>{t.count}</span>
</button>
))}
</div>
<div className="friend-list">
{currentList.length === 0 && (
<Empty>
{tab === 'friends' && 'Noch keine Freunde. Suche oben nach Benutzern um anzufangen.'}
{tab === 'pending' && 'Keine ausgehenden Anfragen.'}
{tab === 'requests' && 'Keine eingehenden Anfragen.'}
</Empty>
)}
{currentList.map(f => (
<FriendRow key={f.id} profile={f}>
{tab === 'friends' && (
<>
<button className="btn btn-primary">
<Icon.Chat /> Nachricht
</button>
<button className="btn btn-ghost" title="Voice"><Icon.Phone /></button>
<button className="btn btn-danger-ghost">Entfernen</button>
</>
)}
{tab === 'pending' && (
<>
<span className="pending-label">Wartet auf Antwort</span>
<button className="btn btn-ghost">Abbrechen</button>
</>
)}
{tab === 'requests' && (
<>
<button className="btn btn-primary">
<Icon.Check /> Annehmen
</button>
<button className="btn btn-ghost">Ablehnen</button>
</>
)}
</FriendRow>
))}
</div>
</>
)}
</div>
</div>
);
};
// ===================================================================
// ADMIN PAGE
// ===================================================================
const INVITES_DATA = [
{ code: 'SQUAD-2k26', usesCount: 3, usesLimit: 10, expiresAt: '2026-05-01', disabled: false },
{ code: 'FRIENDS-OF-DENNIS', usesCount: 1, usesLimit: null, expiresAt: null, disabled: false },
{ code: 'BETA-ROUND-1', usesCount: 12, usesLimit: 12, expiresAt: null, disabled: false },
{ code: 'OLD-UNUSED', usesCount: 0, usesLimit: 5, expiresAt: '2026-03-01', disabled: true },
];
const USERS_DATA = [
{ userId: 'dennis', displayName: 'dennis', username: 'dennis', initial: 'D', color: 'teal', isAdmin: true, blockedFromInviting: false, banned: false, joinedAt: '14. Mär 2026' },
{ userId: 'max', displayName: 'Max', username: 'maxx', initial: 'M', color: 'teal', isAdmin: false, blockedFromInviting: false, banned: false, joinedAt: '16. Mär 2026' },
{ userId: 'lena', displayName: 'Lena', username: 'lena_k', initial: 'L', color: 'amber', isAdmin: false, blockedFromInviting: false, banned: false, joinedAt: '02. Apr 2026' },
{ userId: 'tom', displayName: 'Tom', username: 'tomtom', initial: 'T', color: 'violet', isAdmin: false, blockedFromInviting: true, banned: false, joinedAt: '08. Apr 2026' },
{ userId: 'spam', displayName: 'spam_user_42', username: 'spam42', initial: 'S', color: 'rose', isAdmin: false, blockedFromInviting: false, banned: true, joinedAt: '11. Apr 2026' },
];
const FlagChip = ({ active, tone, onToggle, children }) => (
<button
className={`flag-chip ${active ? 'active' : ''} ${tone === 'danger' ? 'danger' : ''}`}
onClick={() => onToggle(!active)}
>
{children}
</button>
);
const AdminPageContent = () => {
const [invitesEnabled, setInvitesEnabled] = React.useState(true);
const [invites, setInvites] = React.useState(INVITES_DATA);
const [users, setUsers] = React.useState(USERS_DATA);
const [copiedCode, setCopiedCode] = React.useState(null);
const handleCopy = (code) => {
setCopiedCode(code);
setTimeout(() => setCopiedCode(null), 1400);
};
const toggleUserFlag = (userId, flag) => {
setUsers(us => us.map(u => u.userId === userId ? {...u, [flag]: !u[flag]} : u));
};
const toggleInvite = (code) => {
setInvites(is => is.map(i => i.code === code ? {...i, disabled: !i.disabled} : i));
};
const deleteInvite = (code) => {
setInvites(is => is.filter(i => i.code !== code));
};
return (
<div className="page-scroll">
<div className="page-inner admin-page">
<PageHeader
title="Admin"
subtitle={`${users.length} User · ${invites.filter(i => !i.disabled).length} aktive Invites`}
/>
<div className="stats-grid">
<div className="stat-card">
<div className="stat-card-label">Gesamt User</div>
<div className="stat-card-value">{users.length}</div>
</div>
<div className="stat-card">
<div className="stat-card-label">Admins</div>
<div className="stat-card-value">{users.filter(u => u.isAdmin).length}</div>
</div>
<div className="stat-card">
<div className="stat-card-label">Gebannt</div>
<div className="stat-card-value danger">{users.filter(u => u.banned).length}</div>
</div>
<div className="stat-card">
<div className="stat-card-label">Aktive Invites</div>
<div className="stat-card-value">{invites.filter(i => !i.disabled).length}</div>
</div>
</div>
<Section title="System">
<Toggle
label="Invites aktiviert"
hint="Wenn aus, können keine neuen User per Invite-Code beitreten."
checked={invitesEnabled}
onChange={setInvitesEnabled}
/>
</Section>
<Section
title="Invite-Codes"
action={
<button className="btn btn-primary">
<Icon.Plus /> Neuer Code
</button>
}
>
<div className="table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Code</th>
<th>Nutzungen</th>
<th>Ablauf</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{invites.map(inv => {
const expired = inv.expiresAt && new Date(inv.expiresAt) < new Date('2026-04-19');
const status = inv.disabled ? 'disabled' : expired ? 'expired' : 'active';
const usesText = inv.usesLimit ? `${inv.usesCount}/${inv.usesLimit}` : `${inv.usesCount}/∞`;
return (
<tr key={inv.code}>
<td className="mono">{inv.code}</td>
<td className="muted">{usesText}</td>
<td className="muted">{inv.expiresAt || 'nie'}</td>
<td><span className={`status-pill ${status}`}>{status === 'active' ? 'Aktiv' : status === 'expired' ? 'Abgelaufen' : 'Deaktiviert'}</span></td>
<td>
<div className="row-actions">
<button className="icon-btn sm" title={copiedCode === inv.code ? 'Kopiert!' : 'Kopieren'} onClick={() => handleCopy(inv.code)}>
{copiedCode === inv.code ? <Icon.Check /> : <Icon.Copy />}
</button>
<button className="btn btn-xs btn-ghost" onClick={() => toggleInvite(inv.code)}>
{inv.disabled ? 'Aktivieren' : 'Deaktivieren'}
</button>
<button className="icon-btn sm danger" title="Löschen" onClick={() => deleteInvite(inv.code)}>
<Icon.Trash />
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Section>
<Section title="Benutzer">
<div className="user-admin-list">
{users.map(u => (
<div key={u.userId} className="user-admin-row">
<Avatar chat={{initial: u.initial, color: u.color}} />
<div className="user-admin-body">
<div className="user-admin-name">
{u.displayName}
{u.isAdmin && <span className="admin-badge"><Icon.Crown /> Admin</span>}
</div>
<div className="user-admin-meta">@{u.username} · beigetreten {u.joinedAt}</div>
</div>
<div className="user-admin-flags">
<FlagChip active={u.isAdmin} onToggle={() => toggleUserFlag(u.userId, 'isAdmin')}>Admin</FlagChip>
<FlagChip active={u.blockedFromInviting} onToggle={() => toggleUserFlag(u.userId, 'blockedFromInviting')}>Invite-Block</FlagChip>
<FlagChip active={u.banned} tone="danger" onToggle={() => toggleUserFlag(u.userId, 'banned')}>Bann</FlagChip>
</div>
</div>
))}
</div>
</Section>
</div>
</div>
);
};
// ===================================================================
// SETTINGS PAGE
// ===================================================================
const SettingsPageContent = ({ isDark, onToggleDark }) => {
const [language, setLanguage] = React.useState('de');
const [readReceipts, setReadReceipts] = React.useState(true);
const [allowDms, setAllowDms] = React.useState(true);
const [audioQuality, setAudioQuality] = React.useState('voice');
const [ptt, setPtt] = React.useState(false);
const [pttKey, setPttKey] = React.useState('Space');
const [capturingKey, setCapturingKey] = React.useState(false);
const [e2ee, setE2ee] = React.useState(true);
const [screenShareQuality, setScreenShareQuality] = React.useState('balanced');
const audioParams = audioQuality === 'hifi'
? { bitrate: '510 kbps', channels: 'Stereo', sample: '48 kHz', dsp: 'Off' }
: { bitrate: '48 kbps', channels: 'Mono', sample: '48 kHz', dsp: 'On' };
const screenParams = {
smooth: { bitrate: '3 Mbps', resolution: '1280×720', framerate: '60 fps' },
balanced: { bitrate: '6 Mbps', resolution: '1920×1080', framerate: '30 fps' },
crisp: { bitrate: '12 Mbps', resolution: '2560×1440', framerate: '30 fps' },
}[screenShareQuality];
return (
<div className="page-scroll">
<div className="page-inner settings-page">
<PageHeader title="Einstellungen" />
<Section title="Account">
<div className="avatar-control">
<div className="avatar-large" data-color="teal">D</div>
<div className="avatar-copy">
<div className="avatar-label">Avatar</div>
<div className="avatar-hint">Quadratisch, max 512×512, WebP. Sichtbar für deine Freunde.</div>
</div>
<button className="btn btn-primary">Ändern</button>
<button className="btn btn-danger-ghost">Entfernen</button>
</div>
<div className="row-stack">
<Row label="Benutzername" value="dennis" />
<Row label="Anzeigename" value="dennis" />
<Row label="User-ID" value="b4f2-a912-c7e8-d091" mono />
</div>
</Section>
<Section title="Aussehen">
<div className="toggle-row">
<div className="toggle-copy">
<div className="toggle-label">Sprache</div>
<div className="toggle-hint">Sprache der App-Oberfläche</div>
</div>
<SegmentedControl
value={language}
onChange={setLanguage}
options={[{value: 'de', label: 'Deutsch'}, {value: 'en', label: 'English'}]}
/>
</div>
<div className="toggle-row">
<div className="toggle-copy">
<div className="toggle-label">Theme</div>
<div className="toggle-hint">Dark Mode ist dezenter für späte Gaming-Sessions.</div>
</div>
<SegmentedControl
value={isDark ? 'dark' : 'light'}
onChange={v => { if ((v === 'dark') !== isDark) onToggleDark(); }}
options={[{value: 'light', label: '☀ Light'}, {value: 'dark', label: '☾ Dark'}]}
/>
</div>
</Section>
<Section title="Datenschutz">
<Toggle
label="Lesebestätigungen anzeigen"
hint="Freunde sehen wann du ihre Nachrichten gelesen hast. Beidseitig — du siehst dann auch ihre."
checked={readReceipts}
onChange={setReadReceipts}
/>
<Toggle
label="DMs von Fremden erlauben"
hint="Erlaubt Direktnachrichten von Usern mit denen du (noch) nicht befreundet bist."
checked={allowDms}
onChange={setAllowDms}
/>
</Section>
<Section title="Sprache & Audio">
<div className="toggle-row">
<div className="toggle-copy">
<div className="toggle-label">Audio-Qualität</div>
<div className="toggle-hint">
{audioQuality === 'hifi'
? 'Stereo 510 kbps Opus ohne Noise-Suppression — bester Musik/Broadcast-Sound.'
: 'Mono 48 kbps mit Noise-Suppression, Echo-Cancellation und Auto-Gain — optimiert für Sprache.'}
</div>
</div>
<SegmentedControl
value={audioQuality}
onChange={setAudioQuality}
options={[{value: 'voice', label: 'Sprache'}, {value: 'hifi', label: 'HiFi'}]}
/>
</div>
<div className="stats-inline">
<Stat label="Bitrate" value={audioParams.bitrate} />
<Stat label="Channels" value={audioParams.channels} />
<Stat label="Sample" value={audioParams.sample} />
<Stat label="DSP" value={audioParams.dsp} />
</div>
<div className="divider"></div>
<Toggle
label="Push-to-Talk"
hint="Mic bleibt stumm bis die Taste gedrückt wird. Überschreibt den Mute-Button."
checked={ptt}
onChange={setPtt}
/>
{ptt && (
<div className="toggle-row">
<div className="toggle-copy">
<div className="toggle-label">Hotkey</div>
<div className="toggle-hint">Klick zum Ändern. Esc zum Abbrechen.</div>
</div>
<button
className={`key-capture ${capturingKey ? 'active' : ''}`}
onClick={() => setCapturingKey(!capturingKey)}
>
{capturingKey ? 'Taste drücken…' : pttKey}
</button>
</div>
)}
<div className="divider"></div>
<Toggle
label="Ende-zu-Ende-Verschlüsselung für Calls"
hint="Audio + Video werden vor dem Upload verschlüsselt. Der Server sieht nur Ciphertext. Alle Teilnehmer müssen die Option aktiv haben."
checked={e2ee}
onChange={setE2ee}
/>
</Section>
<Section title="Bildschirmfreigabe">
<div className="toggle-row">
<div className="toggle-copy">
<div className="toggle-label">Qualität</div>
<div className="toggle-hint">
WebRTC passt Bitrate + Auflösung dynamisch an die Netzwerkqualität an. Die Werte sind Obergrenzen.
</div>
</div>
<SegmentedControl
value={screenShareQuality}
onChange={setScreenShareQuality}
options={[
{value: 'smooth', label: 'Flüssig'},
{value: 'balanced', label: 'Balanced'},
{value: 'crisp', label: 'Scharf'},
]}
/>
</div>
<div className="stats-inline">
<Stat label="Bitrate (max)" value={screenParams.bitrate} />
<Stat label="Resolution" value={screenParams.resolution} />
<Stat label="Framerate" value={screenParams.framerate} />
</div>
</Section>
<Section title="Geräte">
<div className="device-card">
<div className="device-card-title">
<Icon.Lock /> Dieses Gerät
</div>
<div className="row-stack" style={{marginTop: 10}}>
<Row label="Name" value="Dennis' MacBook Pro" />
<Row label="Plattform" value="macOS 14 · Desktop" />
<Row label="Device-ID" value="dev_01JC4NKT7XYZ" mono />
</div>
</div>
<div className="device-backup">
<div className="toggle-label">Geräteschlüssel-Backup</div>
<div className="toggle-hint" style={{marginTop: 4}}>
Sichere deinen privaten Schlüssel passwortgeschützt, damit du auf neuen Geräten alte Nachrichten weiter lesen kannst.
</div>
<div className="backup-row">
<input type="password" placeholder="Passphrase (min 8 Zeichen)" />
<button className="btn btn-primary">Export erstellen</button>
</div>
</div>
</Section>
<Section title="Danger Zone">
<button className="btn btn-danger">Abmelden</button>
</Section>
</div>
</div>
);
};
Object.assign(window, { FriendsPageContent, AdminPageContent, SettingsPageContent });
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+651
View File
@@ -0,0 +1,651 @@
/* ============================================================
PAGES Friends / Admin / Settings (Clean Rail aesthetic)
============================================================ */
.page-scroll {
flex: 1;
overflow-y: auto;
background: var(--bg);
}
.page-inner {
max-width: 820px;
margin: 0 auto;
padding: 28px 32px 64px;
display: flex;
flex-direction: column;
gap: 24px;
}
.page-header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
padding-bottom: 4px;
}
.page-title {
font-family: 'Outfit', 'Inter', sans-serif;
font-size: 28px;
font-weight: 700;
letter-spacing: -0.02em;
color: var(--fg);
margin: 0;
}
.page-subtitle {
font-size: 13px;
color: var(--fg-muted);
margin: 6px 0 0;
}
.page-header-actions { display: flex; gap: 8px; }
/* ------------- Section ------------- */
.page-section {
background: var(--bg-3);
border: 1px solid var(--line);
border-radius: 16px;
overflow: hidden;
}
.page-section-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid var(--line);
}
.page-section-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--fg-muted);
margin: 0;
}
.page-section-body {
padding: 16px 20px;
display: flex;
flex-direction: column;
gap: 14px;
}
/* ------------- Toggle Row ------------- */
.toggle-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
cursor: pointer;
}
.toggle-row.disabled { opacity: 0.5; cursor: not-allowed; }
.toggle-copy { flex: 1; min-width: 0; }
.toggle-label {
font-size: 14px;
font-weight: 500;
color: var(--fg);
line-height: 1.3;
}
.toggle-hint {
font-size: 12px;
color: var(--fg-muted);
margin-top: 4px;
line-height: 1.5;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 40px;
height: 22px;
background: var(--bg-2);
border: 1px solid var(--line);
border-radius: 999px;
flex-shrink: 0;
transition: all 0.2s;
cursor: pointer;
}
.toggle-switch.on {
background: var(--accent);
border-color: var(--accent);
}
.toggle-thumb {
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
background: #fff;
border-radius: 50%;
transition: transform 0.2s;
box-shadow: 0 1px 3px rgba(0,0,0,0.15);
}
.toggle-switch.on .toggle-thumb { transform: translateX(18px); }
/* ------------- Segmented ------------- */
.segmented {
display: inline-flex;
background: var(--bg-2);
border: 1px solid var(--line);
border-radius: 10px;
padding: 3px;
flex-shrink: 0;
}
.seg-btn {
background: transparent;
border: none;
padding: 6px 12px;
border-radius: 7px;
font-size: 12px;
font-weight: 500;
color: var(--fg-muted);
cursor: pointer;
transition: all 0.15s;
font-family: inherit;
}
.seg-btn:hover { color: var(--fg); }
.seg-btn.active {
background: var(--bg-3);
color: var(--fg);
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}
.variant-clean.dark .seg-btn.active { box-shadow: 0 1px 3px rgba(0,0,0,0.3); }
/* ------------- Row KV ------------- */
.row-stack { display: flex; flex-direction: column; gap: 10px; }
.row-kv {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 8px 0;
border-bottom: 1px solid var(--line);
}
.row-kv:last-child { border-bottom: none; }
.row-label { font-size: 13px; color: var(--fg-muted); }
.row-value { font-size: 13px; color: var(--fg); font-weight: 500; text-align: right; }
.row-value.mono {
font-family: 'JetBrains Mono', monospace;
font-size: 11px;
color: var(--fg-muted);
}
/* ------------- Buttons ------------- */
.btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border-radius: 8px;
border: 1px solid transparent;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s;
font-family: inherit;
white-space: nowrap;
}
.btn svg { width: 14px; height: 14px; }
.btn-primary {
background: var(--accent);
color: var(--accent-fg);
}
.btn-primary:hover { filter: brightness(1.08); }
.btn-ghost {
background: transparent;
color: var(--fg);
border-color: var(--line);
}
.btn-ghost:hover { background: var(--bg-2); }
.btn-danger {
background: #dc2626;
color: #fff;
}
.btn-danger:hover { background: #b91c1c; }
.variant-clean.dark .btn-danger { background: #dc2626; }
.variant-clean.dark .btn-danger:hover { background: #ef4444; }
.btn-danger-ghost {
background: transparent;
color: #dc2626;
border-color: rgba(220,38,38,0.3);
}
.btn-danger-ghost:hover { background: rgba(220,38,38,0.08); }
.variant-clean.dark .btn-danger-ghost {
color: #fb7185;
border-color: rgba(251,113,133,0.3);
}
.variant-clean.dark .btn-danger-ghost:hover { background: rgba(251,113,133,0.1); }
.btn-xs { padding: 4px 8px; font-size: 11px; }
/* ------------- Search ------------- */
.search-wrap {
position: relative;
display: flex;
align-items: center;
background: var(--bg-3);
border: 1px solid var(--line);
border-radius: 12px;
padding: 10px 14px;
gap: 10px;
transition: border-color 0.15s;
}
.search-wrap:focus-within { border-color: var(--accent); }
.search-wrap svg { width: 16px; height: 16px; color: var(--fg-muted); flex-shrink: 0; }
.search-wrap input {
flex: 1;
background: transparent;
border: none;
outline: none;
font-size: 14px;
color: var(--fg);
font-family: inherit;
}
.search-wrap input::placeholder { color: var(--fg-muted); }
/* ------------- Tabs ------------- */
.tab-row {
display: flex;
gap: 2px;
border-bottom: 1px solid var(--line);
}
.tab-btn {
background: transparent;
border: none;
padding: 10px 16px;
font-size: 13px;
font-weight: 500;
color: var(--fg-muted);
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
display: inline-flex;
align-items: center;
gap: 8px;
font-family: inherit;
transition: all 0.15s;
}
.tab-btn:hover { color: var(--fg); }
.tab-btn.active { color: var(--fg); border-bottom-color: var(--accent); font-weight: 600; }
.tab-count {
background: var(--bg-2);
color: var(--fg-muted);
padding: 2px 7px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
min-width: 20px;
text-align: center;
}
.tab-btn.active .tab-count { background: var(--accent); color: var(--accent-fg); }
.tab-count.highlight:not(.tab-btn.active .tab-count) {
background: #dc2626;
color: #fff;
}
/* ------------- Friend Row ------------- */
.friend-list { display: flex; flex-direction: column; gap: 2px; }
.friend-row {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
border-radius: 10px;
transition: background 0.15s;
}
.friend-row:hover { background: var(--bg-2); }
.friend-body { flex: 1; min-width: 0; }
.friend-name {
font-size: 14px;
font-weight: 600;
color: var(--fg);
line-height: 1.3;
}
.friend-handle {
font-size: 12px;
color: var(--fg-muted);
margin-top: 2px;
}
.friend-actions {
display: flex;
gap: 6px;
flex-shrink: 0;
}
.pending-label {
font-size: 12px;
color: var(--fg-muted);
font-style: italic;
align-self: center;
padding-right: 4px;
}
/* ------------- Empty State ------------- */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 16px;
text-align: center;
color: var(--fg-muted);
}
.empty-icon {
width: 48px;
height: 48px;
border-radius: 14px;
background: var(--bg-2);
display: grid;
place-items: center;
margin-bottom: 12px;
color: var(--fg-muted);
}
.empty-icon svg { width: 20px; height: 20px; }
.empty-state p { font-size: 13px; margin: 0; max-width: 320px; }
/* ------------- Banner ------------- */
.banner {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
border-radius: 10px;
font-size: 13px;
border: 1px solid;
}
.banner.error { background: rgba(220,38,38,0.08); border-color: rgba(220,38,38,0.2); color: #dc2626; }
.variant-clean.dark .banner.error { color: #fb7185; }
.banner.success { background: rgba(22,163,74,0.08); border-color: rgba(22,163,74,0.2); color: #16a34a; }
.banner svg { width: 16px; height: 16px; flex-shrink: 0; margin-top: 1px; }
/* ============================================================
ADMIN PAGE
============================================================ */
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.stat-card {
background: var(--bg-3);
border: 1px solid var(--line);
border-radius: 12px;
padding: 14px 16px;
}
.stat-card-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--fg-muted);
font-weight: 500;
}
.stat-card-value {
font-family: 'Outfit', 'Inter', sans-serif;
font-size: 28px;
font-weight: 700;
color: var(--fg);
margin-top: 4px;
font-variant-numeric: tabular-nums;
}
.stat-card-value.danger { color: #dc2626; }
.variant-clean.dark .stat-card-value.danger { color: #fb7185; }
/* Inline stats (inside sections) */
.stats-inline {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
padding: 12px 14px;
background: var(--bg-2);
border: 1px solid var(--line);
border-radius: 10px;
}
.stat-label, .stat .stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--fg-muted);
font-weight: 500;
}
.stat-value, .stat .stat-value {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: var(--fg);
margin-top: 2px;
font-weight: 500;
}
/* ------------- Admin Table ------------- */
.table-wrap { overflow-x: auto; margin: -4px; padding: 4px; }
.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.admin-table thead th {
text-align: left;
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--fg-muted);
padding: 4px 12px 10px;
border-bottom: 1px solid var(--line);
}
.admin-table tbody td {
padding: 12px 12px;
border-bottom: 1px solid var(--line);
color: var(--fg);
vertical-align: middle;
}
.admin-table tbody tr:last-child td { border-bottom: none; }
.admin-table td.mono {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
font-weight: 500;
}
.admin-table td.muted { color: var(--fg-muted); font-size: 12px; }
.status-pill {
display: inline-block;
padding: 3px 9px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
border: 1px solid;
}
.status-pill.active { background: rgba(22,163,74,0.08); border-color: rgba(22,163,74,0.25); color: #16a34a; }
.variant-clean.dark .status-pill.active { color: #4ade80; border-color: rgba(74,222,128,0.3); }
.status-pill.expired { background: rgba(245,158,11,0.08); border-color: rgba(245,158,11,0.25); color: #d97706; }
.variant-clean.dark .status-pill.expired { color: #fbbf24; border-color: rgba(251,191,36,0.3); }
.status-pill.disabled { background: rgba(220,38,38,0.08); border-color: rgba(220,38,38,0.25); color: #dc2626; }
.variant-clean.dark .status-pill.disabled { color: #fb7185; border-color: rgba(251,113,133,0.3); }
.row-actions { display: flex; gap: 4px; justify-content: flex-end; }
.icon-btn.sm { width: 28px; height: 28px; }
.icon-btn.sm svg { width: 13px; height: 13px; }
.icon-btn.sm.danger { color: #dc2626; border-color: rgba(220,38,38,0.2); }
.icon-btn.sm.danger:hover { background: rgba(220,38,38,0.08); }
.variant-clean.dark .icon-btn.sm.danger { color: #fb7185; }
/* ------------- User Admin Row ------------- */
.user-admin-list { display: flex; flex-direction: column; }
.user-admin-row {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 4px;
border-bottom: 1px solid var(--line);
}
.user-admin-row:last-child { border-bottom: none; }
.user-admin-body { flex: 1; min-width: 0; }
.user-admin-name {
font-size: 14px;
font-weight: 600;
color: var(--fg);
display: flex;
align-items: center;
gap: 8px;
}
.user-admin-meta {
font-size: 12px;
color: var(--fg-muted);
margin-top: 2px;
}
.admin-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 10px;
font-weight: 600;
padding: 2px 7px;
border-radius: 999px;
background: var(--accent);
color: var(--accent-fg);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.admin-badge svg { width: 9px; height: 9px; }
.user-admin-flags { display: flex; gap: 6px; flex-shrink: 0; }
.flag-chip {
background: var(--bg-2);
border: 1px solid var(--line);
color: var(--fg-muted);
padding: 4px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
font-family: inherit;
}
.flag-chip:hover { color: var(--fg); background: var(--bg-3); }
.flag-chip.active {
background: var(--accent);
color: var(--accent-fg);
border-color: var(--accent);
}
.flag-chip.active.danger {
background: #dc2626;
border-color: #dc2626;
color: #fff;
}
.variant-clean.dark .flag-chip.active.danger { background: #ef4444; border-color: #ef4444; }
/* ============================================================
SETTINGS PAGE
============================================================ */
.avatar-control {
display: flex;
align-items: center;
gap: 14px;
}
.avatar-large {
width: 64px;
height: 64px;
border-radius: 50%;
background: var(--accent);
color: var(--accent-fg);
display: grid;
place-items: center;
font-family: 'Outfit', sans-serif;
font-size: 26px;
font-weight: 700;
flex-shrink: 0;
box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}
.avatar-copy { flex: 1; min-width: 0; }
.avatar-label { font-size: 14px; font-weight: 500; color: var(--fg); }
.avatar-hint { font-size: 12px; color: var(--fg-muted); margin-top: 4px; }
.divider {
height: 1px;
background: var(--line);
margin: 6px -20px;
}
.key-capture {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
font-weight: 600;
padding: 6px 14px;
border-radius: 8px;
background: var(--bg-2);
border: 1px solid var(--line);
color: var(--fg);
cursor: pointer;
min-width: 90px;
transition: all 0.15s;
}
.key-capture:hover { background: var(--bg-3); }
.key-capture.active {
background: var(--accent);
color: var(--accent-fg);
border-color: var(--accent);
animation: keyPulse 1.2s ease-in-out infinite;
}
@keyframes keyPulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
.device-card {
background: rgba(22,163,74,0.06);
border: 1px solid rgba(22,163,74,0.2);
border-radius: 12px;
padding: 14px 16px;
}
.variant-clean.dark .device-card {
background: rgba(74,222,128,0.08);
border-color: rgba(74,222,128,0.2);
}
.device-card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
color: #16a34a;
}
.variant-clean.dark .device-card-title { color: #4ade80; }
.device-card-title svg { width: 14px; height: 14px; }
.device-backup {
background: var(--bg-2);
border: 1px solid var(--line);
border-radius: 12px;
padding: 14px 16px;
}
.backup-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
.backup-row input {
flex: 1;
padding: 8px 12px;
border-radius: 8px;
border: 1px solid var(--line);
background: var(--bg-3);
color: var(--fg);
font-size: 13px;
font-family: inherit;
outline: none;
}
.backup-row input:focus { border-color: var(--accent); }
/* ============================================================
Layout glue make pages fill the rail's chat-area slot
============================================================ */
.rail-layout.page-mode {
grid-template-columns: 64px 1fr !important;
}
.rail-layout .chat-area.has-page {
padding: 0;
}
.rail-layout .chat-area.has-page > .page-scroll {
height: 100%;
}
/* Responsive tweaks */
@media (max-width: 1200px) {
.stats-grid { grid-template-columns: repeat(2, 1fr); }
}
+138
View File
@@ -187,3 +187,141 @@ export async function setUserFlag(
.eq('user_id', userId);
if (error) throw error;
}
// ---------------------------------------------------------------------------
// Conversations (admin view — reads all regardless of membership)
// ---------------------------------------------------------------------------
export interface AdminConversationRow {
id: string;
type: 'dm' | 'group';
name: string | null;
memberCount: number;
lastMessageAt: string | null;
createdAt: string;
}
export async function listAllConversations(
client: AppSupabaseClient,
): Promise<AdminConversationRow[]> {
const { data, error } = await client
.from('conversations')
.select('id, type, name, created_at')
.order('created_at', { ascending: false });
if (error) throw error;
const conversations = data ?? [];
if (conversations.length === 0) return [];
const ids = conversations.map((c) => c.id);
const { data: memberRows, error: mErr } = await client
.from('conversation_members')
.select('conversation_id')
.in('conversation_id', ids);
if (mErr) throw mErr;
const counts = new Map<string, number>();
for (const row of memberRows ?? []) {
counts.set(row.conversation_id, (counts.get(row.conversation_id) ?? 0) + 1);
}
// Approximate "last message at" by peeking at latest message.created_at per
// conversation. Cheap since conversation count stays small (<20 users,
// <few hundred conversations).
const { data: lastMsg, error: lErr } = await client
.from('messages')
.select('conversation_id, created_at')
.in('conversation_id', ids)
.order('created_at', { ascending: false })
.limit(5000);
if (lErr) throw lErr;
const lastAt = new Map<string, string>();
for (const row of lastMsg ?? []) {
if (!lastAt.has(row.conversation_id)) {
lastAt.set(row.conversation_id, row.created_at);
}
}
return conversations.map((c) => ({
id: c.id,
type: c.type as 'dm' | 'group',
name: c.name,
memberCount: counts.get(c.id) ?? 0,
lastMessageAt: lastAt.get(c.id) ?? null,
createdAt: c.created_at,
}));
}
// ---------------------------------------------------------------------------
// Audit log
// ---------------------------------------------------------------------------
export interface AdminAuditEntry {
id: string;
actorId: string | null;
action: string;
targetType: string | null;
targetId: string | null;
metadata: Record<string, unknown>;
createdAt: string;
}
export async function listAuditLog(
client: AppSupabaseClient,
limit = 100,
): Promise<AdminAuditEntry[]> {
const { data, error } = await (client as unknown as {
from: (t: string) => {
select: (cols: string) => {
order: (
col: string,
opts: { ascending: boolean },
) => {
limit: (n: number) => Promise<{
data:
| {
id: string;
actor_id: string | null;
action: string;
target_type: string | null;
target_id: string | null;
metadata: Record<string, unknown>;
created_at: string;
}[]
| null;
error: Error | null;
}>;
};
};
};
})
.from('admin_audit_log')
.select('id, actor_id, action, target_type, target_id, metadata, created_at')
.order('created_at', { ascending: false })
.limit(limit);
if (error) throw error;
return (data ?? []).map((r) => ({
id: r.id,
actorId: r.actor_id,
action: r.action,
targetType: r.target_type,
targetId: r.target_id,
metadata: r.metadata ?? {},
createdAt: r.created_at,
}));
}
export async function logAdminAction(
client: AppSupabaseClient,
action: string,
target?: { type?: string; id?: string },
metadata?: Record<string, unknown>,
): Promise<void> {
const { error } = await (client as unknown as {
rpc: (
name: string,
args: Record<string, unknown>,
) => Promise<{ error: Error | null }>;
}).rpc('admin_log_action', {
p_action: action,
p_target_type: target?.type ?? null,
p_target_id: target?.id ?? null,
p_metadata: metadata ?? {},
});
if (error) throw error;
}
+50
View File
@@ -152,6 +152,56 @@ export async function saveDevicePrivateKey(
await secretStore.setSecret(privateKeySecretName(userId, deviceId), privateKey);
}
// Restores a device record from a backup by re-seeding the local private key
// store for an EXISTING server-side device row. Does NOT insert a new row —
// the original row is kept intact so conversation-key bundles stay valid.
// Throws when the server-side device was removed (the backup is then unusable;
// user must provision a fresh device and get conv-keys shared from another
// live device).
export async function restoreDeviceFromServerRecord(params: {
client: AppSupabaseClient;
secretStore: SecretStore;
userId: string;
deviceId: string;
privateKey: Uint8Array;
}): Promise<DeviceRecord> {
const { data: session } = await params.client.auth.getUser();
if (!session.user) throw new Error('not authenticated');
if (session.user.id !== params.userId) {
throw new Error(
'Backup is for a different account — sign in as the owner before restoring.',
);
}
const { data: row, error } = await params.client
.from('devices')
.select('id, name, platform, public_key, last_seen_at')
.eq('id', params.deviceId)
.eq('user_id', params.userId)
.maybeSingle();
if (error) throw error;
if (!row) {
throw new Error(
'Device record not found on server — it was removed. Backup is no longer valid; register a new device instead.',
);
}
await saveDevicePrivateKey(
params.secretStore,
params.userId,
params.deviceId,
params.privateKey,
);
return {
id: row.id,
name: row.name,
platform: row.platform,
publicKey: pgHexToBytes(row.public_key),
lastSeenAt: row.last_seen_at,
};
}
// Lightweight helpers for platforms that want to cache their current device id
// in JSON storage (separate from the secret store, which only holds raw bytes).
export const DEVICE_ID_STORAGE_KEY_PREFIX = 'chatapp.device_id';
+5 -2
View File
@@ -3,7 +3,8 @@ import type { AppSupabaseClient } from '../supabase/client.js';
export interface SignupParams {
email: string;
// Login handle. Lowercased server-side; must match ^[a-z0-9_]{3,32}$ once lowercased.
// Login handle. Stored with original casing but uniqueness is case-insensitive
// (citext). Must match ^[A-Za-z0-9_]{3,32}$.
username: string;
// Optional human-readable name. Defaults to username server-side if omitted.
displayName?: string;
@@ -29,7 +30,9 @@ export async function signUpWithMagicLink(
shouldCreateUser: true,
data: {
invite_code: params.inviteCode,
username: params.username.toLowerCase(),
// Preserve case. `profiles.username` is citext so uniqueness + lookups
// stay case-insensitive regardless of stored casing.
username: params.username.trim(),
display_name: params.displayName ?? params.username,
...(params.locale ? { locale: params.locale } : {}),
},
+4 -2
View File
@@ -72,7 +72,8 @@ export async function getProfileByUsername(
const { data, error } = await client
.from('profiles')
.select(PROFILE_COLS)
.eq('username', username.toLowerCase())
// citext column compares CI server-side — send raw input, don't force case.
.eq('username', username.trim())
.maybeSingle();
if (error) throw error;
return data ? mapProfile(data as unknown as ProfileRow) : null;
@@ -85,7 +86,8 @@ export async function isUsernameAvailable(
const { count, error } = await client
.from('profiles')
.select('user_id', { count: 'exact', head: true })
.eq('username', username.toLowerCase());
// citext compares CI — no manual normalization needed.
.eq('username', username.trim());
if (error) throw error;
return (count ?? 0) === 0;
}
+62 -5
View File
@@ -28,13 +28,21 @@ async function currentUserId(client: AppSupabaseClient): Promise<string> {
export async function listConversations(client: AppSupabaseClient): Promise<ConversationSummary[]> {
const myId = await currentUserId(client);
// 1. Caller's memberships
// 1. Caller's memberships. `archived` / `muted_until` live on the members
// row (see migration 20260420000001). db-types snapshot predates them so
// cast the select to bypass typing.
const { data: myMembers, error: mErr } = await client
.from('conversation_members')
.select('conversation_id, role, accepted')
.select('conversation_id, role, accepted, archived, muted_until' as '*')
.eq('user_id', myId);
if (mErr) throw mErr;
const myMembersList = myMembers ?? [];
const myMembersList = (myMembers ?? []) as unknown as Array<{
conversation_id: string;
role: string;
accepted: boolean;
archived: boolean | null;
muted_until: string | null;
}>;
if (myMembersList.length === 0) return [];
const convIds = myMembersList.map((m) => m.conversation_id);
@@ -103,6 +111,9 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
c.type === 'dm'
? (members.find((m) => m.userId !== myId)?.profile ?? null)
: null;
const mineRow = mine as
| { accepted: boolean; role: string; archived?: boolean; muted_until?: string | null }
| undefined;
return {
id: c.id,
type: c.type,
@@ -110,10 +121,56 @@ export async function listConversations(client: AppSupabaseClient): Promise<Conv
avatarUrl: c.avatar_url,
createdAt: c.created_at,
peer,
acceptedByMe: mine?.accepted ?? false,
myRole: mine?.role ?? 'member',
acceptedByMe: mineRow?.accepted ?? false,
myRole: (mineRow?.role ?? 'member') as ConversationSummary['myRole'],
members,
lastMessageAt: lastSeen.get(c.id) ?? null,
archived: mineRow?.archived ?? false,
mutedUntil: mineRow?.muted_until ?? null,
};
});
}
// Toggle archive flag on the caller's own conversation_members row.
export async function setConversationArchived(
client: AppSupabaseClient,
conversationId: string,
archived: boolean,
): Promise<void> {
const myId = await currentUserId(client);
const { error } = await client
.from('conversation_members')
.update({ archived } as never)
.eq('conversation_id', conversationId)
.eq('user_id', myId);
if (error) throw error;
}
// Set mute until a specific ISO timestamp (null clears the mute). A
// far-future timestamp is the "muted forever" representation.
export async function setConversationMutedUntil(
client: AppSupabaseClient,
conversationId: string,
until: string | null,
): Promise<void> {
const myId = await currentUserId(client);
const { error } = await client
.from('conversation_members')
.update({ muted_until: until } as never)
.eq('conversation_id', conversationId)
.eq('user_id', myId);
if (error) throw error;
}
// Convenience: `null` unmutes, number means minutes from now. For "forever"
// pass a very large number (e.g. 100 years worth of minutes).
export function muteDurationToIso(minutes: number | null): string | null {
if (minutes === null) return null;
return new Date(Date.now() + minutes * 60 * 1000).toISOString();
}
// True iff the member is currently muted (mutedUntil present and > now).
export function isConversationMuted(mutedUntil: string | null): boolean {
if (!mutedUntil) return false;
return new Date(mutedUntil).getTime() > Date.now();
}
+128
View File
@@ -245,6 +245,134 @@ export async function listPeerReadsForMessages(
return new Set((data ?? []).map((r) => r.message_id));
}
// Group variant: returns reads from ALL users (other than `excludeUserId`,
// typically caller themselves) keyed by message id → user id → timestamp.
// RLS already filters out users whose receipts are off.
export async function listGroupReadsForMessages(
client: AppSupabaseClient,
messageIds: string[],
excludeUserId: string,
): Promise<Map<string, Map<string, string>>> {
if (messageIds.length === 0) return new Map();
const { data, error } = await client
.from('message_reads')
.select('message_id, user_id, read_at')
.neq('user_id', excludeUserId)
.in('message_id', messageIds);
if (error) throw error;
const out = new Map<string, Map<string, string>>();
for (const row of data ?? []) {
const mid = row.message_id;
const uid = row.user_id;
const at = row.read_at;
let inner = out.get(mid);
if (!inner) {
inner = new Map();
out.set(mid, inner);
}
inner.set(uid, at);
}
return out;
}
// Group variant of delivery receipts. Same shape as listGroupReadsForMessages.
export async function listGroupDeliveriesForMessages(
client: AppSupabaseClient,
messageIds: string[],
excludeUserId: string,
): Promise<Map<string, Map<string, string>>> {
if (messageIds.length === 0) return new Map();
const { data, error } = await (client as unknown as {
from: (t: string) => {
select: (cols: string) => {
neq: (col: string, val: string) => {
in: (
col: string,
vals: string[],
) => Promise<{
data:
| { message_id: string; user_id: string; delivered_at: string }[]
| null;
error: Error | null;
}>;
};
};
};
})
.from('message_deliveries')
.select('message_id, user_id, delivered_at')
.neq('user_id', excludeUserId)
.in('message_id', messageIds);
if (error) throw error;
const out = new Map<string, Map<string, string>>();
for (const row of data ?? []) {
let inner = out.get(row.message_id);
if (!inner) {
inner = new Map();
out.set(row.message_id, inner);
}
inner.set(row.user_id, row.delivered_at);
}
return out;
}
// ---------------------------------------------------------------------------
// Delivery receipts
// ---------------------------------------------------------------------------
// Records that the caller has received (fetched + decrypted) these messages.
// Idempotent; composite PK absorbs duplicates.
export async function markMessagesDelivered(
client: AppSupabaseClient,
messageIds: string[],
): Promise<void> {
if (messageIds.length === 0) return;
const { data: session, error: aErr } = await client.auth.getUser();
if (aErr) throw aErr;
if (!session.user) return;
const myId = session.user.id;
const rows = messageIds.map((id) => ({ message_id: id, user_id: myId }));
// `message_deliveries` is a later migration and not yet in the generated
// Supabase types; skip the strict table-name check for this call.
const { error } = await (client as unknown as {
from: (t: string) => {
upsert: (
rows: unknown,
opts: { onConflict: string; ignoreDuplicates: boolean },
) => Promise<{ error: Error | null }>;
};
})
.from('message_deliveries')
.upsert(rows, { onConflict: 'message_id,user_id', ignoreDuplicates: true });
if (error) throw error;
}
export async function listPeerDeliveriesForMessages(
client: AppSupabaseClient,
messageIds: string[],
peerUserId: string,
): Promise<Set<string>> {
if (messageIds.length === 0) return new Set();
const { data, error } = await (client as unknown as {
from: (t: string) => {
select: (cols: string) => {
eq: (col: string, val: string) => {
in: (
col: string,
vals: string[],
) => Promise<{ data: { message_id: string }[] | null; error: Error | null }>;
};
};
};
})
.from('message_deliveries')
.select('message_id')
.eq('user_id', peerUserId)
.in('message_id', messageIds);
if (error) throw error;
return new Set((data ?? []).map((r) => r.message_id));
}
// ---------------------------------------------------------------------------
// Reactions
// ---------------------------------------------------------------------------
+5
View File
@@ -23,6 +23,11 @@ export interface ConversationSummary {
members: ConversationMember[];
// Latest message timestamp (server can't see content, only metadata).
lastMessageAt: string | null;
// Caller's per-member preferences.
archived: boolean;
// ISO timestamp. null = not muted. Past timestamp = expired mute (treat as
// not muted — the server row is kept for history until the next toggle).
mutedUntil: string | null;
}
export interface ChatMessage {
+1 -1
View File
@@ -55,7 +55,7 @@ export async function searchProfiles(
query: string,
limit = 10,
): Promise<ProfileBrief[]> {
const trimmed = query.trim().toLowerCase();
const trimmed = query.trim();
if (trimmed.length < 2) return [];
const myId = await currentUserId(client);
+31 -1
View File
@@ -33,7 +33,37 @@
"call_incoming": "Eingehender Anruf",
"call_missed": "Verpasster Anruf",
"call_no_answer": "Keine Antwort",
"call_declined": "Anruf abgelehnt"
"call_declined": "Anruf abgelehnt",
"you": "Du",
"attachment": "Anhang",
"reply": "Antworten",
"forward": "Weiterleiten",
"replying_to": "Antwort an {{name}}",
"quote_unavailable": "Nachricht nicht verfügbar",
"search_in_conv": "In Unterhaltung suchen…",
"search_none": "Keine Treffer",
"forward_preview": "Vorschau",
"forward_attachments_dropped": "Anhänge werden nicht mit weitergeleitet.",
"forward_no_targets": "Keine anderen Unterhaltungen verfügbar.",
"forward_done": "Gesendet",
"forward_send": "An {{count}} senden",
"forward_attachments_count_one": "{{count}} Anhang wird mit weitergeleitet",
"forward_attachments_count_other": "{{count}} Anhänge werden mit weitergeleitet",
"archive": "Archivieren",
"unarchive": "Entarchivieren",
"archived_title": "Archiv",
"show_archived": "Archiv anzeigen",
"show_active": "Aktive anzeigen",
"archived_empty_title": "Nichts archiviert",
"archived_empty_subtitle": "Archivierte Unterhaltungen erscheinen hier.",
"mute": "Stummschalten",
"unmute": "Stummschaltung aufheben",
"mute_1h": "1 Stunde",
"mute_8h": "8 Stunden",
"mute_24h": "24 Stunden",
"mute_1w": "1 Woche",
"mute_forever": "Bis auf Weiteres",
"row_menu": "Aktionen"
},
"call": {
"start_audio": "Sprachanruf",
@@ -30,8 +30,8 @@
"email_placeholder": "du@beispiel.de",
"username": "Benutzername",
"username_placeholder": "dennis",
"username_hint": "Damit meldest du dich an. Nur Kleinbuchstaben.",
"username_invalid": "Kleinbuchstaben az, Ziffern, Unterstrich · 332 Zeichen.",
"username_hint": "Damit meldest du dich an. Groß-/Kleinschreibung bleibt, ist aber nicht unterscheidbar (dennis = Dennis).",
"username_invalid": "Buchstaben, Ziffern oder Unterstrich · 332 Zeichen.",
"invite_code": "Einladungscode",
"invite_hint": "Pflichtfeld · Zugang nur auf Einladung."
},
@@ -3,7 +3,7 @@
"network": "Netzwerkfehler. Prüfe deine Verbindung.",
"ERR_NOT_AUTH": "Du bist nicht angemeldet.",
"ERR_INVITE_CODE_REQUIRED": "Einladungscode ist erforderlich.",
"ERR_USERNAME_INVALID": "Benutzername muss aus Kleinbuchstaben az, Ziffern oder Unterstrich bestehen (332 Zeichen).",
"ERR_USERNAME_INVALID": "Benutzername darf nur aus Buchstaben (AZ, az), Ziffern oder Unterstrich bestehen (332 Zeichen).",
"ERR_INVITES_DISABLED": "Registrierungen sind derzeit vom Admin deaktiviert.",
"ERR_INVITE_NOT_FOUND": "Einladungscode nicht gefunden.",
"ERR_INVITE_DISABLED": "Diese Einladung wurde deaktiviert.",
+31 -1
View File
@@ -33,7 +33,37 @@
"call_incoming": "Incoming call",
"call_missed": "Missed call",
"call_no_answer": "No answer",
"call_declined": "Call declined"
"call_declined": "Call declined",
"you": "You",
"attachment": "Attachment",
"reply": "Reply",
"forward": "Forward",
"replying_to": "Replying to {{name}}",
"quote_unavailable": "Message not available",
"search_in_conv": "Search in conversation…",
"search_none": "No matches",
"forward_preview": "Preview",
"forward_attachments_dropped": "Attachments are not forwarded.",
"forward_no_targets": "No other conversations available.",
"forward_done": "Sent",
"forward_send": "Send to {{count}}",
"forward_attachments_count_one": "{{count}} attachment forwarded",
"forward_attachments_count_other": "{{count}} attachments forwarded",
"archive": "Archive",
"unarchive": "Unarchive",
"archived_title": "Archive",
"show_archived": "Show archive",
"show_active": "Show active",
"archived_empty_title": "Nothing archived",
"archived_empty_subtitle": "Archived conversations appear here.",
"mute": "Mute",
"unmute": "Unmute",
"mute_1h": "1 hour",
"mute_8h": "8 hours",
"mute_24h": "24 hours",
"mute_1w": "1 week",
"mute_forever": "Until further notice",
"row_menu": "Actions"
},
"call": {
"start_audio": "Voice call",
@@ -30,8 +30,8 @@
"email_placeholder": "you@example.com",
"username": "Username",
"username_placeholder": "dennis",
"username_hint": "You log in with this. Lowercase only.",
"username_invalid": "Lowercase az, digits, underscore · 332 chars.",
"username_hint": "You log in with this. Case is preserved but not unique (dennis = Dennis).",
"username_invalid": "Letters, digits, or underscore · 332 chars.",
"invite_code": "Invite code",
"invite_hint": "Required · invite-only access."
},
@@ -3,7 +3,7 @@
"network": "Network error. Check your connection.",
"ERR_NOT_AUTH": "You are not signed in.",
"ERR_INVITE_CODE_REQUIRED": "Invite code is required.",
"ERR_USERNAME_INVALID": "Username must be lowercase az, digits, underscore, 332 chars.",
"ERR_USERNAME_INVALID": "Username must be letters (AZ, az), digits, or underscore, 332 chars.",
"ERR_INVITES_DISABLED": "Signups are currently disabled by the admin.",
"ERR_INVITE_NOT_FOUND": "Invite code not found.",
"ERR_INVITE_DISABLED": "This invite has been disabled.",
+24 -1
View File
@@ -86,7 +86,7 @@ importers:
i18next:
specifier: ^23.16.4
version: 23.16.8
libsodium-wrappers:
libsodium-wrappers-sumo:
specifier: 0.7.15
version: 0.7.15
livekit-client:
@@ -114,6 +114,9 @@ importers:
'@types/libsodium-wrappers':
specifier: ^0.7.14
version: 0.7.14
'@types/libsodium-wrappers-sumo':
specifier: ^0.8.2
version: 0.8.2
'@types/react':
specifier: ^18.3.12
version: 18.3.28
@@ -1853,6 +1856,10 @@ packages:
'@types/json5@0.0.29':
resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==}
'@types/libsodium-wrappers-sumo@0.8.2':
resolution: {integrity: sha512-uFOBpg/r21hExVlh2ty8YpDfSR+Yy3Jn8XS4+SSjitbhTxdYq+pBz/49XRxyUFe8SzqujHf/Wu0/O4d+FUtNfQ==}
deprecated: This is a stub types definition. libsodium-wrappers-sumo provides its own type definitions, so you do not need this installed.
'@types/libsodium-wrappers@0.7.14':
resolution: {integrity: sha512-5Kv68fXuXK0iDuUir1WPGw2R9fOZUlYlSAa0ztMcL0s0BfIDTqg9GXz8K30VJpPP3sxWhbolnQma2x+/TfkzDQ==}
@@ -3642,9 +3649,15 @@ packages:
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
engines: {node: '>= 0.8.0'}
libsodium-sumo@0.7.16:
resolution: {integrity: sha512-x6atrz2AdXCJg6G709x9W9TTJRI6/0NcL5dD0l5GGVqNE48UJmDsjO4RUWYTeyXXUpg+NXZ2SHECaZnFRYzwGA==}
libsodium-sumo@0.8.3:
resolution: {integrity: sha512-z5CLkGJqilCXpfYxrXWh8fHVv2C8lpnIVxsZAHkxbEFyS+zZtL8VyM8FjtAmuDYP/rHgw8ftdwxSV8Efhzb8GQ==}
libsodium-wrappers-sumo@0.7.15:
resolution: {integrity: sha512-aSWY8wKDZh5TC7rMvEdTHoyppVq/1dTSAeAR7H6pzd6QRT3vQWcT5pGwCotLcpPEOLXX6VvqihSPkpEhYAjANA==}
libsodium-wrappers-sumo@0.8.3:
resolution: {integrity: sha512-EfLSlxKJ7RUGVospOlvbvse0suAAVPR+CkZfFcFjPzPtTEgVfvIaZUPsWndVjxYp/om2HDc0iLeR5wLF8YbHZg==}
@@ -7492,6 +7505,10 @@ snapshots:
'@types/json5@0.0.29': {}
'@types/libsodium-wrappers-sumo@0.8.2':
dependencies:
libsodium-wrappers-sumo: 0.7.15
'@types/libsodium-wrappers@0.7.14': {}
'@types/node-forge@1.3.14':
@@ -9591,8 +9608,14 @@ snapshots:
prelude-ls: 1.2.1
type-check: 0.4.0
libsodium-sumo@0.7.16: {}
libsodium-sumo@0.8.3: {}
libsodium-wrappers-sumo@0.7.15:
dependencies:
libsodium-sumo: 0.7.16
libsodium-wrappers-sumo@0.8.3:
dependencies:
libsodium-sumo: 0.8.3
+102
View File
@@ -0,0 +1,102 @@
// Supabase Edge Function — fan-out push notifications via Web Push (VAPID).
//
// Trigger: server-side (e.g. database trigger on messages INSERT calling
// pg_net.http_post → this function), or app-level after sendEncryptedMessage
// resolves successfully.
//
// Required environment variables (set via supabase secrets):
// VAPID_PUBLIC_KEY
// VAPID_PRIVATE_KEY
// VAPID_SUBJECT e.g. "mailto:admin@example.com"
// PUSH_FANOUT_SHARED_SECRET shared header secret to authenticate caller
//
// Request body:
// { conversationId: string, senderUserId: string, senderName: string, kind?: "message" | "call" }
//
// The function:
// 1. Looks up conversation_members minus sender.
// 2. Joins to push_tokens via devices.
// 3. Sends a Web Push to each token using web-push npm via npm: specifier.
//
// Note: this is a skeleton — wire web-push library and verify against the
// chosen Deno deploy runtime.
// deno-lint-ignore-file no-explicit-any
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import webPush from 'npm:web-push@3.6.7';
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';
const VAPID_PUBLIC_KEY = Deno.env.get('VAPID_PUBLIC_KEY') ?? '';
const VAPID_PRIVATE_KEY = Deno.env.get('VAPID_PRIVATE_KEY') ?? '';
const VAPID_SUBJECT = Deno.env.get('VAPID_SUBJECT') ?? 'mailto:admin@example.com';
const SHARED_SECRET = Deno.env.get('PUSH_FANOUT_SHARED_SECRET') ?? '';
if (VAPID_PUBLIC_KEY && VAPID_PRIVATE_KEY) {
webPush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY);
}
interface Payload {
conversationId: string;
senderUserId: string;
senderName: string;
kind?: 'message' | 'call';
}
Deno.serve(async (req) => {
if (req.method !== 'POST') return new Response('method', { status: 405 });
// Shared-secret gate. Cheap, replaces user JWT here because the trigger has
// no authenticated session.
const auth = req.headers.get('x-shared-secret');
if (!SHARED_SECRET || auth !== SHARED_SECRET) {
return new Response('unauthorized', { status: 401 });
}
let body: Payload;
try {
body = await req.json();
} catch {
return new Response('bad json', { status: 400 });
}
const client = createClient(SUPABASE_URL, SERVICE_ROLE_KEY);
const { data: members, error: mErr } = await client
.from('conversation_members')
.select('user_id')
.eq('conversation_id', body.conversationId);
if (mErr) return new Response('members lookup failed', { status: 500 });
const recipientIds = (members ?? [])
.map((m: any) => m.user_id as string)
.filter((id: string) => id !== body.senderUserId);
if (recipientIds.length === 0) return new Response('no recipients', { status: 200 });
const { data: tokens, error: tErr } = await client
.from('push_tokens')
.select('token, devices!inner(user_id)')
.in('devices.user_id', recipientIds);
if (tErr) return new Response('tokens lookup failed', { status: 500 });
const payload = JSON.stringify({
title: body.senderName,
body: body.kind === 'call' ? 'Eingehender Anruf' : 'Neue Nachricht',
conversationId: body.conversationId,
kind: body.kind ?? 'message',
});
const results = await Promise.allSettled(
(tokens ?? []).map(async (row: any) => {
try {
const sub = JSON.parse(row.token);
await webPush.sendNotification(sub, payload);
} catch (err) {
console.warn('push send failed', err);
}
}),
);
return new Response(JSON.stringify({ sent: results.length }), {
headers: { 'content-type': 'application/json' },
});
});
@@ -0,0 +1,16 @@
-- Per-member conversation preferences: archive + mute.
--
-- Both live on `conversation_members` because they are per-user state, not
-- shared across the conversation. Archive hides the conversation from the
-- main list until explicitly unarchived. Mute silences notifications until
-- `muted_until` (null = not muted, a far-future timestamp = muted forever).
alter table public.conversation_members
add column if not exists archived boolean not null default false,
add column if not exists muted_until timestamptz null;
-- Update policy on conversation_members already allows self-updates via
-- `members_update_self_or_admin`. No additional policy needed — users can
-- toggle their own archive / mute flags.
-- Realtime publication already includes `conversation_members`.
@@ -0,0 +1,71 @@
-- Keep raw casing on usernames at signup.
--
-- `profiles.username` is already `citext` so unique + lookup checks are
-- case-insensitive regardless of stored casing. Previously the signup
-- trigger force-lowercased via `lower(trim(...))`, losing the user's
-- preferred display case. Drop the lower(), widen the validation regex to
-- accept A-Z, keep trim() + uniqueness semantics.
create or replace function public.handle_new_user()
returns trigger language plpgsql security definer set search_path = public as $$
declare
v_invite_code text;
v_username text;
v_display_name text;
v_locale text;
v_invite public.invites%rowtype;
begin
v_invite_code := new.raw_user_meta_data->>'invite_code';
v_username := trim(new.raw_user_meta_data->>'username');
v_display_name := nullif(trim(new.raw_user_meta_data->>'display_name'), '');
v_locale := lower(trim(new.raw_user_meta_data->>'locale'));
if v_display_name is null then
v_display_name := v_username;
end if;
if v_locale is null or v_locale not in ('en', 'de') then
v_locale := 'en';
end if;
if v_invite_code is null or length(v_invite_code) = 0 then
raise exception 'ERR_INVITE_CODE_REQUIRED';
end if;
if v_username is null or v_username !~ '^[A-Za-z0-9_]{3,32}$' then
raise exception 'ERR_USERNAME_INVALID';
end if;
if not coalesce((select (value)::boolean from public.admin_settings where key = 'invites_enabled'), true) then
raise exception 'ERR_INVITES_DISABLED';
end if;
select * into v_invite from public.invites
where code = v_invite_code
for update;
if not found then
raise exception 'ERR_INVITE_NOT_FOUND';
end if;
if v_invite.disabled then
raise exception 'ERR_INVITE_DISABLED';
end if;
if v_invite.expires_at is not null and v_invite.expires_at < now() then
raise exception 'ERR_INVITE_EXPIRED';
end if;
if v_invite.uses_limit is not null and v_invite.uses_count >= v_invite.uses_limit then
raise exception 'ERR_INVITE_EXHAUSTED';
end if;
update public.invites
set uses_count = uses_count + 1
where code = v_invite.code;
insert into public.profiles (user_id, username, display_name, locale)
values (new.id, v_username, v_display_name, v_locale);
return new;
end;
$$;
@@ -0,0 +1,54 @@
-- ============================================================================
-- Delivery receipts — "✓✓" tick in WhatsApp/Telegram parlance: the recipient's
-- device has fetched the message from the server, regardless of whether they
-- have actually opened the conversation yet. `message_reads` already covers
-- the "read" step; this table fills the gap between "sent" and "read".
--
-- A row exists iff the recipient user has acknowledged receiving the message
-- on at least one device. Writes are triggered client-side after successful
-- message fetch/decrypt. Select policy mirrors read receipts (opt-out via
-- profiles.show_read_receipts on BOTH ends).
-- ============================================================================
create table public.message_deliveries (
message_id uuid not null references public.messages(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
delivered_at timestamptz not null default now(),
primary key (message_id, user_id)
);
alter table public.message_deliveries enable row level security;
create policy deliveries_select_reciprocal on public.message_deliveries
for select to authenticated
using (
user_id = auth.uid()
or (
coalesce(
(select show_read_receipts from public.profiles where profiles.user_id = auth.uid()),
true
)
and coalesce(
(select show_read_receipts from public.profiles where profiles.user_id = message_deliveries.user_id),
true
)
and exists (
select 1 from public.messages m
where m.id = message_id and public.is_conversation_member(m.conversation_id)
)
)
);
create policy deliveries_insert_own on public.message_deliveries
for insert to authenticated
with check (
user_id = auth.uid()
and exists (
select 1 from public.messages m
where m.id = message_id and public.is_conversation_member(m.conversation_id)
)
);
create index message_deliveries_message_id_idx on public.message_deliveries (message_id);
create index message_deliveries_user_id_idx on public.message_deliveries (user_id);
alter publication supabase_realtime add table public.message_deliveries;
@@ -0,0 +1,63 @@
-- ============================================================================
-- Admin audit log — append-only journal of administrative actions. Writes
-- go through an RPC so the insert path is a single choke-point with input
-- validation; reads are admin-only via RLS.
-- ============================================================================
create table public.admin_audit_log (
id uuid primary key default gen_random_uuid(),
actor_id uuid not null references auth.users(id) on delete set null,
action text not null,
target_type text,
target_id text,
metadata jsonb not null default '{}'::jsonb,
created_at timestamptz not null default now()
);
create index admin_audit_log_created_at_idx on public.admin_audit_log (created_at desc);
create index admin_audit_log_actor_idx on public.admin_audit_log (actor_id);
alter table public.admin_audit_log enable row level security;
create policy audit_log_select_admin on public.admin_audit_log
for select to authenticated
using (public.current_user_is_admin());
-- Insert via RPC only — no direct insert policy, so clients can't forge rows
-- with a different actor_id.
create or replace function public.admin_log_action(
p_action text,
p_target_type text default null,
p_target_id text default null,
p_metadata jsonb default '{}'::jsonb
) returns uuid
language plpgsql
security definer
set search_path = public
as $$
declare
new_id uuid;
begin
if not public.current_user_is_admin() then
raise exception 'not an admin';
end if;
insert into public.admin_audit_log (actor_id, action, target_type, target_id, metadata)
values (auth.uid(), p_action, p_target_type, p_target_id, coalesce(p_metadata, '{}'::jsonb))
returning id into new_id;
return new_id;
end;
$$;
revoke all on function public.admin_log_action(text, text, text, jsonb) from public;
grant execute on function public.admin_log_action(text, text, text, jsonb) to authenticated;
-- ============================================================================
-- Admin conversations view — lets admins list every conversation (bypassing
-- is_conversation_member). Read-only: no writes flow through the view.
-- ============================================================================
create policy conversations_select_admin on public.conversations
for select to authenticated
using (public.current_user_is_admin());
create policy conversation_members_select_admin on public.conversation_members
for select to authenticated
using (public.current_user_is_admin());