update
CI / Lint, types, build, tests (push) Canceled after 0s
CI / Docker images build (push) Canceled after 0s

This commit is contained in:
olehhapuk
2026-12-03 10:53:09 +02:00
parent f8de87955b
commit 98b2e0ce4b
182 changed files with 24134 additions and 288 deletions
+65
View File
@@ -0,0 +1,65 @@
export const apiUrl: string =
import.meta.env.VITE_API_URL ?? 'http://localhost:3001';
/** The API answered with an error status; `message` is safe to show. */
export class ApiError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = 'ApiError';
this.status = status;
}
}
interface RequestOptions<T> {
/** A schema from @repo/contracts; the response is checked against it. */
schema: { parse: (data: unknown) => T };
method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
/** Sent as JSON. */
body?: unknown;
signal?: AbortSignal;
}
/** Calls the API as the signed-in user (the session cookie goes along). */
export async function api<T>(
path: string,
{ schema, method = 'GET', body, signal }: RequestOptions<T>,
): Promise<T> {
const response = await fetch(`${apiUrl}${path}`, {
method,
signal,
credentials: 'include',
headers:
body === undefined ? undefined : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) {
throw new ApiError(response.status, await readErrorMessage(response));
}
// 204 has no body to read.
return schema.parse(
response.status === 204 ? undefined : await response.json(),
);
}
/** The `schema` for routes that answer 204 with no body. */
export const noContent = { parse: (): void => undefined };
// Errors come back as { statusCode, message, error }, where message is a
// string or, for validation errors, a list of strings.
async function readErrorMessage(response: Response): Promise<string> {
const fallback = response.statusText || 'Something went wrong.';
try {
const data: unknown = await response.json();
if (typeof data !== 'object' || data === null || !('message' in data)) {
return fallback;
}
const { message } = data;
if (typeof message === 'string') return message;
if (Array.isArray(message)) return message.join(' ');
return fallback;
} catch {
return fallback;
}
}
+87
View File
@@ -0,0 +1,87 @@
import {
ATTACHMENT_MAX_SIZE,
INLINE_IMAGE_TYPES,
attachmentUploadSchema,
} from '@repo/contracts';
import type { Attachment } from '@repo/contracts';
import { ApiError, api, apiUrl, noContent } from '@/lib/api';
/**
* Where a file is fetched from: usable as an image source or a link. The
* API checks that the signed-in user can read the message it is on.
*/
export function attachmentUrl(attachmentId: string): string {
return `${apiUrl}/attachments/${attachmentId}`;
}
/** "840 B", "12 KB", "3.4 MB". */
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
/** Why a file can't be attached, in words to show; nothing when it can. */
export function fileProblem(file: File): string | undefined {
if (file.size === 0) return `“${file.name}” is empty.`;
if (file.size > ATTACHMENT_MAX_SIZE) {
return `“${file.name}” is too big. Files can be at most ${formatFileSize(ATTACHMENT_MAX_SIZE)}.`;
}
return undefined;
}
/** A picture's size in pixels; nothing for other files or unreadable ones. */
async function pictureSize(
file: File,
): Promise<{ width: number; height: number } | undefined> {
if (!INLINE_IMAGE_TYPES.includes(file.type)) return undefined;
try {
const bitmap = await createImageBitmap(file);
const size = { width: bitmap.width, height: bitmap.height };
bitmap.close();
return size;
} catch {
return undefined;
}
}
/**
* Uploads a file for a message that is about to be sent: tells the API
* about it, then sends the bytes to the address the API answers with (the
* storage itself, so no cookies go along). The attachment's id then goes in
* the message.
*/
export async function uploadAttachment(
file: File,
signal?: AbortSignal,
): Promise<Attachment> {
const { attachment, upload } = await api('/attachments', {
method: 'POST',
body: {
filename: file.name,
contentType: file.type || 'application/octet-stream',
size: file.size,
...(await pictureSize(file)),
},
schema: attachmentUploadSchema,
signal,
});
const response = await fetch(upload.url, {
method: upload.method,
headers: upload.headers,
body: file,
signal,
});
if (!response.ok) {
throw new ApiError(response.status, `Could not upload “${file.name}”.`);
}
return attachment;
}
/** Takes back an upload that won't be sent after all. */
export function discardAttachment(attachmentId: string): Promise<void> {
return api(`/attachments/${attachmentId}`, {
method: 'DELETE',
schema: noContent,
});
}
+9
View File
@@ -0,0 +1,9 @@
import { usernameClient } from 'better-auth/client/plugins';
import { createAuthClient } from 'better-auth/react';
import { apiUrl } from '@/lib/api';
export const authClient = createAuthClient({
baseURL: apiUrl,
// Mirrors the username plugin options in apps/api/src/auth/auth.ts.
plugins: [usernameClient({ displayUsername: false })],
});
+131
View File
@@ -0,0 +1,131 @@
import { useSyncExternalStore } from 'react';
import { queryOptions, useQuery } from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import { callAccessSchema, callsOverviewSchema } from '@repo/contracts';
import type { Call, CallAccess } from '@repo/contracts';
import { api } from '@/lib/api';
/**
* The calls going on in the user's conversations and cauldrons, and whether
* the server has calls at all. Kept current by "call:changed" events.
*/
export const callsQuery = queryOptions({
queryKey: ['calls'],
queryFn: ({ signal }) =>
api('/calls', { schema: callsOverviewSchema, signal }),
});
/** Asks to join the call of a conversation or cauldron, starting it if need be. */
export function requestCallAccess(conversationId: string): Promise<CallAccess> {
return api(`/conversations/${conversationId}/call`, {
method: 'POST',
schema: callAccessSchema,
});
}
/** False until known, and when the server has no calls set up. */
export function useCallsEnabled(): boolean {
const { data } = useQuery(callsQuery);
return data?.enabled ?? false;
}
/** The call going on in a conversation or cauldron, if there is one. */
export function useCallIn(conversationId: string): Call | undefined {
const { data } = useQuery(callsQuery);
return data?.calls.find((call) => call.conversationId === conversationId);
}
/** The ids of the conversations and cauldrons with a call going on. */
export function useCallPlaces(): {
conversationIds: ReadonlySet<string>;
realmIds: ReadonlySet<string>;
} {
const { data } = useQuery(callsQuery);
const calls = data?.calls ?? [];
return {
conversationIds: new Set(calls.map((call) => call.conversationId)),
realmIds: new Set(calls.flatMap((call) => call.realmId ?? [])),
};
}
/**
* Folds a "call:changed" event into the cache. Answers whether it is news
* of a call starting: one the cache was loaded without.
*/
export function applyCallChange(queryClient: QueryClient, call: Call): boolean {
const before = queryClient.getQueryData(callsQuery.queryKey);
if (!before) return false;
const others = before.calls.filter(
(item) => item.conversationId !== call.conversationId,
);
const isOver = call.participants.length === 0;
queryClient.setQueryData(callsQuery.queryKey, {
...before,
calls: isOver ? others : [...others, call],
});
return !isOver && others.length === before.calls.length;
}
/** "Ana is in a call", "Ana and Ben are in a call", "Ana and 2 others are in a call". */
export function callSummary(call: Call): string {
const [first, second, ...rest] = call.participants.map(
(participant) => participant.name,
);
if (!first) return 'Nobody is in the call';
if (!second) return `${first} is in a call`;
if (rest.length === 0) return `${first} and ${second} are in a call`;
return `${first} and ${rest.length + 1} others are in a call`;
}
// Calls someone just started in one of the user's chats, which the app
// offers to join for a while: "ringing". Not part of the query cache
// because it is about this tab's moment, not about the server's state.
/** How long a call is offered before the offer goes away by itself. */
const RING_MS = 30 * 1000;
let ringing: readonly Call[] = [];
const timers = new Map<string, ReturnType<typeof setTimeout>>();
const listeners = new Set<() => void>();
function setRinging(next: readonly Call[]) {
ringing = next;
for (const listener of listeners) listener();
}
/** Offers a call that just started to the user. */
export function ring(call: Call) {
stopRinging(call.conversationId);
setRinging([...ringing, call]);
timers.set(
call.conversationId,
setTimeout(() => stopRinging(call.conversationId), RING_MS),
);
}
/** Takes the offer back: answered, dismissed, over, or run out. */
export function stopRinging(conversationId: string) {
clearTimeout(timers.get(conversationId));
timers.delete(conversationId);
if (ringing.some((call) => call.conversationId === conversationId)) {
setRinging(
ringing.filter((call) => call.conversationId !== conversationId),
);
}
}
function subscribe(onChange: () => void) {
listeners.add(onChange);
return () => listeners.delete(onChange);
}
const NONE: readonly Call[] = [];
/** The calls being offered to the user right now, oldest first. */
export function useRinging(): readonly Call[] {
return useSyncExternalStore(
subscribe,
() => ringing,
() => NONE,
);
}
+401
View File
@@ -0,0 +1,401 @@
import {
infiniteQueryOptions,
queryOptions,
useMutation,
useQueryClient,
} from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import {
conversationListSchema,
conversationSchema,
messagePageSchema,
messageSchema,
} from '@repo/contracts';
import type {
Conversation,
CreateGroup,
Message,
MessageDeletion,
Reaction,
ReactionChange,
UserSummary,
} from '@repo/contracts';
import { api, noContent } from '@/lib/api';
import { realmQuery, realmsQuery } from '@/lib/realms';
/** The signed-in user's conversations, most recently active first. */
export const conversationsQuery = queryOptions({
queryKey: ['conversations', 'list'],
queryFn: ({ signal }) =>
api('/conversations', { schema: conversationListSchema, signal }),
});
/**
* A conversation's history. Pages run from newest to oldest and so do the
* messages inside each page; `chronological()` turns them around for display.
*/
export const messagesQuery = (conversationId: string) =>
infiniteQueryOptions({
queryKey: ['conversations', 'messages', conversationId],
queryFn: ({ pageParam, signal }) =>
api(
`/conversations/${conversationId}/messages${pageParam ? `?before=${pageParam}` : ''}`,
{ schema: messagePageSchema, signal },
),
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
/** Oldest first, the order a chat is read in. */
export function chronological(pages: { items: Message[] }[]): Message[] {
return pages.flatMap((page) => page.items).reverse();
}
/** In a direct conversation: the person who isn't the signed-in user. */
export function otherMember(
conversation: Conversation,
ownId: string,
): UserSummary | undefined {
return conversation.members.find((member) => member.id !== ownId);
}
/**
* What to call a conversation: the other person, the group's name or, for a
* group without one, the people in it.
*/
export function conversationTitle(
conversation: Conversation,
ownId: string,
): string {
const others = conversation.members.filter((member) => member.id !== ownId);
if (conversation.type === 'direct') {
return others.at(0)?.name ?? 'Unknown user';
}
if (conversation.name) return conversation.name;
return others.length > 0
? others.map((member) => member.name).join(', ')
: 'Just you';
}
/** "1 member", "3 members". */
export function memberCount(conversation: Conversation): string {
const count = conversation.members.length;
return count === 1 ? '1 member' : `${count} members`;
}
/** A message in a line: its text, or what was attached when it has none. */
export function messagePreview(message: Message): string {
if (message.content) return message.content;
const count = message.attachments.length;
return count === 1 ? message.attachments[0].filename : `${count} files`;
}
/** Replaces a conversation in the loaded list, or puts a new one on top. */
function putConversationInCache(
queryClient: QueryClient,
conversation: Conversation,
) {
queryClient.setQueryData(conversationsQuery.queryKey, (conversations) => {
if (!conversations) return conversations;
return conversations.some((item) => item.id === conversation.id)
? conversations.map((item) =>
item.id === conversation.id ? conversation : item,
)
: [conversation, ...conversations];
});
}
/**
* Puts a new message at the end of its conversation's (or cauldron's)
* history, if that is loaded. Called for the answer to a send and for
* "message:created" from the socket, which may both carry the same message,
* so it does nothing the second time.
*/
export function addMessageToHistory(
queryClient: QueryClient,
message: Message,
) {
queryClient.setQueryData(
messagesQuery(message.conversationId).queryKey,
(history) => {
if (!history) return history;
const known = history.pages.some((page) =>
page.items.some((item) => item.id === message.id),
);
if (known) return history;
const [newest, ...older] = history.pages;
return {
...history,
pages: [{ ...newest, items: [message, ...newest.items] }, ...older],
};
},
);
}
/**
* A new message in a direct or group chat: into its history and to the top
* of the conversation list. Like `addMessageToHistory`, safe to call twice.
*/
export function addMessageToCache(queryClient: QueryClient, message: Message) {
addMessageToHistory(queryClient, message);
const conversations = queryClient.getQueryData(conversationsQuery.queryKey);
const conversation = conversations?.find(
(item) => item.id === message.conversationId,
);
if (!conversations || !conversation) {
// A conversation this tab hasn't seen yet (someone's first message).
void queryClient.invalidateQueries({
queryKey: conversationsQuery.queryKey,
});
return;
}
// Ids are time-ordered, so this also ignores a message older than the one
// already shown.
if (conversation.lastMessage && conversation.lastMessage.id >= message.id) {
return;
}
queryClient.setQueryData(conversationsQuery.queryKey, [
{
...conversation,
lastMessage: message,
lastActivityAt: message.createdAt,
},
...conversations.filter((item) => item.id !== conversation.id),
]);
}
/**
* Takes a deleted message out of the loaded history. What the lists show of
* it (the last message of a chat, unread counts) is fetched again, since
* what comes in its place isn't known here. Safe to call twice: once for
* the user's own click, once for the socket's echo.
*/
export function removeMessageFromCache(
queryClient: QueryClient,
{ conversationId, messageId, realmId }: MessageDeletion,
) {
queryClient.setQueryData(
messagesQuery(conversationId).queryKey,
(history) =>
history && {
...history,
pages: history.pages.map((page) => ({
...page,
items: page.items.filter((item) => item.id !== messageId),
})),
},
);
if (!realmId) {
void queryClient.invalidateQueries({
queryKey: conversationsQuery.queryKey,
});
return;
}
// A realm's details carry the unread counts of its cauldrons, and the
// list of realms whether any of them has some.
void queryClient.invalidateQueries({
queryKey: realmQuery(realmId).queryKey,
});
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
}
/** Deletes a message for everyone who can read its conversation. */
export function useDeleteMessage(
conversationId: string,
realmId: string | null,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (messageId: string) =>
api(`/conversations/${conversationId}/messages/${messageId}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: (_, messageId) =>
removeMessageFromCache(queryClient, {
conversationId,
messageId,
realmId,
}),
});
}
/** Opens the chat with a friend, creating it on first use. */
export function useOpenDirectConversation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userId: string) =>
api('/conversations/direct', {
method: 'POST',
body: { userId },
schema: conversationSchema,
}),
onSuccess: (conversation) =>
putConversationInCache(queryClient, conversation),
});
}
/**
* Posts in a conversation, or in a cauldron when `inRealm` is set: cauldrons
* aren't in the conversation list, so only their history is updated.
*/
export function useSendMessage(conversationId: string, inRealm = false) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (body: { content: string; attachmentIds: string[] }) =>
api(`/conversations/${conversationId}/messages`, {
method: 'POST',
body,
schema: messageSchema,
}),
onSuccess: (message) =>
inRealm
? addMessageToHistory(queryClient, message)
: addMessageToCache(queryClient, message),
});
}
/**
* Applies a reaction someone added or took back to the loaded history.
* The change carries the emoji's new count, so applying it twice (once for
* the user's own click, once for the socket's echo) does no harm.
*/
export function applyReactionChange(
queryClient: QueryClient,
change: ReactionChange,
ownId: string | undefined,
) {
const update = (reactions: Reaction[]): Reaction[] => {
const existing = reactions.find((item) => item.emoji === change.emoji);
const mine =
change.userId === ownId ? change.added : (existing?.mine ?? false);
if (change.count <= 0) {
return reactions.filter((item) => item.emoji !== change.emoji);
}
const next = { emoji: change.emoji, count: change.count, mine };
return existing
? reactions.map((item) => (item === existing ? next : item))
: [...reactions, next];
};
queryClient.setQueryData(
messagesQuery(change.conversationId).queryKey,
(history) =>
history && {
...history,
pages: history.pages.map((page) => ({
...page,
items: page.items.map((item) =>
item.id === change.messageId
? { ...item, reactions: update(item.reactions) }
: item,
),
})),
},
);
}
/**
* Adds the user's emoji to a message, or takes it back if it is there.
* The chat shows it at once; if the API refuses, the history is fetched
* again to put things right.
*/
export function useToggleReaction(conversationId: string, ownId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ message, emoji }: { message: Message; emoji: string }) => {
const mine = message.reactions.some(
(item) => item.emoji === emoji && item.mine,
);
return api(
`/conversations/${conversationId}/messages/${message.id}/reactions/${encodeURIComponent(emoji)}`,
{ method: mine ? 'DELETE' : 'PUT', schema: noContent },
);
},
onMutate: ({ message, emoji }) => {
const existing = message.reactions.find((item) => item.emoji === emoji);
const added = !existing?.mine;
applyReactionChange(
queryClient,
{
conversationId,
messageId: message.id,
emoji,
count: (existing?.count ?? 0) + (added ? 1 : -1),
userId: ownId,
added,
},
ownId,
);
},
onError: () =>
queryClient.invalidateQueries({
queryKey: messagesQuery(conversationId).queryKey,
}),
});
}
// The group changes below also reach everyone in the group as
// "conversations:changed" over the socket, which refetches the list.
/** Starts a group chat with some friends. */
export function useCreateGroup() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (body: CreateGroup) =>
api('/conversations/group', {
method: 'POST',
body,
schema: conversationSchema,
}),
onSuccess: (conversation) =>
putConversationInCache(queryClient, conversation),
});
}
export function useRenameGroup(conversationId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (name: string) =>
api(`/conversations/${conversationId}`, {
method: 'PATCH',
body: { name },
schema: conversationSchema,
}),
onSuccess: (conversation) =>
putConversationInCache(queryClient, conversation),
});
}
export function useAddGroupMembers(conversationId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userIds: string[]) =>
api(`/conversations/${conversationId}/members`, {
method: 'POST',
body: { userIds },
schema: conversationSchema,
}),
onSuccess: (conversation) =>
putConversationInCache(queryClient, conversation),
});
}
/** Takes someone out of a group; with the user's own id, leaves it. */
export function useRemoveGroupMember(conversationId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userId: string) =>
api(`/conversations/${conversationId}/members/${userId}`, {
method: 'DELETE',
schema: noContent,
}),
// Not awaited: callers move on (say, away from a group they left)
// without waiting for the list to come back.
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: conversationsQuery.queryKey,
});
},
});
}
+15
View File
@@ -0,0 +1,15 @@
import { toast } from '@repo/ui/components/toast';
import { ApiError } from '@/lib/api';
/** The API's own words when it gave any, a general apology otherwise. */
export function errorMessage(
error: unknown,
fallback = 'Something went wrong. Please try again.',
): string {
return error instanceof ApiError ? error.message : fallback;
}
/** Shows a failed action as a toast. */
export function showError(error: unknown) {
toast.add({ title: errorMessage(error), type: 'error' });
}
+17
View File
@@ -0,0 +1,17 @@
const timeFormat = new Intl.DateTimeFormat(undefined, { timeStyle: 'short' });
const dateTimeFormat = new Intl.DateTimeFormat(undefined, {
dateStyle: 'medium',
timeStyle: 'short',
});
/** "14:05" for today, "2 Dec 2026, 14:05" for any other day. */
export function formatMessageTime(iso: string): string {
const date = new Date(iso);
const isToday = date.toDateString() === new Date().toDateString();
return isToday ? timeFormat.format(date) : dateTimeFormat.format(date);
}
/** "2 Dec 2026, 14:05", whatever the day. */
export function formatDateTime(iso: string): string {
return dateTimeFormat.format(new Date(iso));
}
+84
View File
@@ -0,0 +1,84 @@
import {
queryOptions,
useMutation,
useQueryClient,
} from '@tanstack/react-query';
import {
friendRequestResultSchema,
friendsOverviewSchema,
} from '@repo/contracts';
import type { SendFriendRequest } from '@repo/contracts';
import { api, noContent } from '@/lib/api';
/** Friends, the requests waiting in either direction, and who is blocked. */
export const friendsQuery = queryOptions({
queryKey: ['friends'],
queryFn: ({ signal }) =>
api('/friends', { schema: friendsOverviewSchema, signal }),
});
// Each change refetches the overview. The API also sends "friends:changed"
// over the socket, which does the same for the other person and other tabs.
function useRefreshFriends() {
const queryClient = useQueryClient();
return () =>
queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
}
export function useSendFriendRequest() {
const refresh = useRefreshFriends();
return useMutation({
mutationFn: (body: SendFriendRequest) =>
api('/friends/requests', {
method: 'POST',
body,
schema: friendRequestResultSchema,
}),
onSuccess: refresh,
});
}
export function useAcceptFriendRequest() {
const refresh = useRefreshFriends();
return useMutation({
mutationFn: (userId: string) =>
api(`/friends/requests/${userId}/accept`, {
method: 'POST',
schema: noContent,
}),
onSuccess: refresh,
});
}
/** Unfriends, declines an incoming request or cancels an outgoing one. */
export function useRemoveFriend() {
const refresh = useRefreshFriends();
return useMutation({
mutationFn: (userId: string) =>
api(`/friends/${userId}`, { method: 'DELETE', schema: noContent }),
onSuccess: refresh,
});
}
/**
* Blocks someone: the friendship or any request between the two ends, and
* they can't send another or message the user until it is lifted.
*/
export function useBlockUser() {
const refresh = useRefreshFriends();
return useMutation({
mutationFn: (userId: string) =>
api(`/friends/blocks/${userId}`, { method: 'PUT', schema: noContent }),
onSuccess: refresh,
});
}
/** Lifts a block. The two aren't friends again until one asks. */
export function useUnblockUser() {
const refresh = useRefreshFriends();
return useMutation({
mutationFn: (userId: string) =>
api(`/friends/blocks/${userId}`, { method: 'DELETE', schema: noContent }),
onSuccess: refresh,
});
}
+174
View File
@@ -0,0 +1,174 @@
import { useSyncExternalStore } from 'react';
import type { QueryClient } from '@tanstack/react-query';
import type { Call, Message } from '@repo/contracts';
import { conversationTitle, conversationsQuery } from '@/lib/conversations';
import { realmQuery, realmsQuery } from '@/lib/realms';
import { isAttentive } from '@/lib/unread';
/** Which messages may pop up as desktop notifications. Kept per browser. */
export interface NotificationSettings {
/** Direct and group chats. */
chats: boolean;
/** Cauldrons of realms. */
realms: boolean;
}
const STORAGE_KEY = 'notifications';
const OFF: NotificationSettings = { chats: false, realms: false };
let cached: NotificationSettings | undefined;
const listeners = new Set<() => void>();
function read(): NotificationSettings {
if (cached) return cached;
cached = OFF;
try {
const stored: unknown = JSON.parse(
localStorage.getItem(STORAGE_KEY) ?? 'null',
);
if (typeof stored === 'object' && stored !== null) {
cached = {
chats: 'chats' in stored && stored.chats === true,
realms: 'realms' in stored && stored.realms === true,
};
}
} catch {
// Storage is blocked or holds something else: notifications stay off.
}
return cached;
}
function subscribe(onChange: () => void) {
listeners.add(onChange);
return () => listeners.delete(onChange);
}
export function setNotificationSettings(settings: NotificationSettings) {
cached = settings;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
} catch {
// Kept for this visit only.
}
for (const listener of listeners) listener();
}
export function useNotificationSettings(): NotificationSettings {
return useSyncExternalStore(subscribe, read, () => OFF);
}
export function notificationsSupported(): boolean {
return typeof window !== 'undefined' && 'Notification' in window;
}
/**
* Asks the browser for leave to show notifications, if it hasn't been
* asked. Call it from a click. Answers whether they may be shown.
*/
export async function allowNotifications(): Promise<boolean> {
if (!notificationsSupported()) return false;
if (Notification.permission === 'default') {
await Notification.requestPermission();
}
return Notification.permission === 'granted';
}
function describe(message: Message): string {
if (message.content) return message.content;
const count = message.attachments.length;
return count === 1
? `Sent ${message.attachments[0].filename}`
: `Sent ${count} files`;
}
/**
* Shows a desktop notification for a message from someone else, when the
* user has asked for them and isn't looking at the app. `open` is called
* with the place to go when the notification is clicked.
*/
export function notifyOfMessage(
queryClient: QueryClient,
message: Message,
realmId: string | null,
ownId: string,
open: (to: { realmId: string | null; conversationId: string }) => void,
) {
const settings = read();
if (!(realmId ? settings.realms : settings.chats)) return;
if (!notificationsSupported() || Notification.permission !== 'granted')
return;
if (isAttentive()) return;
let title = message.author.name;
let body = describe(message);
if (realmId) {
const realm = queryClient.getQueryData(realmQuery(realmId).queryKey);
const cauldron = realm?.cauldrons.find(
(item) => item.id === message.conversationId,
);
const realmName =
realm?.name ??
queryClient
.getQueryData(realmsQuery.queryKey)
?.find((item) => item.id === realmId)?.name;
title =
[cauldron && `#${cauldron.name}`, realmName]
.filter(Boolean)
.join(' · ') || title;
body = `${message.author.name}: ${body}`;
} else {
const conversation = queryClient
.getQueryData(conversationsQuery.queryKey)
?.find((item) => item.id === message.conversationId);
if (conversation?.type === 'group') {
title = conversationTitle(conversation, ownId);
body = `${message.author.name}: ${body}`;
}
}
const notification = new Notification(title, {
body,
// A newer message from the same place replaces the older notification.
tag: message.conversationId,
});
notification.addEventListener('click', () => {
window.focus();
open({ realmId, conversationId: message.conversationId });
notification.close();
});
}
/**
* Shows a desktop notification for a call a friend just started in one of
* the user's chats, under the same conditions as for a message there.
*/
export function notifyOfCall(
queryClient: QueryClient,
call: Call,
ownId: string,
open: (to: { realmId: string | null; conversationId: string }) => void,
) {
if (!read().chats) return;
if (!notificationsSupported() || Notification.permission !== 'granted')
return;
if (isAttentive()) return;
const caller = call.participants.at(0);
if (!caller) return;
const conversation = queryClient
.getQueryData(conversationsQuery.queryKey)
?.find((item) => item.id === call.conversationId);
const isGroup = conversation?.type === 'group';
const notification = new Notification(
isGroup ? conversationTitle(conversation, ownId) : caller.name,
{
body: isGroup ? `${caller.name} started a call` : 'Incoming call',
tag: `call:${call.conversationId}`,
},
);
notification.addEventListener('click', () => {
window.focus();
open({ realmId: call.realmId, conversationId: call.conversationId });
notification.close();
});
}
+31
View File
@@ -0,0 +1,31 @@
import {
queryOptions,
useMutation,
useQueryClient,
} from '@tanstack/react-query';
import { ownProfileSchema } from '@repo/contracts';
import type { UpdateProfile } from '@repo/contracts';
import { api } from '@/lib/api';
/** The signed-in user's profile; fails with a 401 ApiError when signed out. */
export const ownProfileQuery = queryOptions({
queryKey: ['users', 'me'],
queryFn: ({ signal }) =>
api('/users/me', { schema: ownProfileSchema, signal }),
staleTime: 60_000,
});
export function useUpdateProfile() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (changes: UpdateProfile) =>
api('/users/me', {
method: 'PATCH',
body: changes,
schema: ownProfileSchema,
}),
onSuccess: (profile) => {
queryClient.setQueryData(ownProfileQuery.queryKey, profile);
},
});
}
+448
View File
@@ -0,0 +1,448 @@
import {
queryOptions,
useMutation,
useQueryClient,
} from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import {
REALM_PERMISSIONS,
cauldronSchema,
hasPermissions,
invitePreviewSchema,
realmBanListSchema,
realmInviteListSchema,
realmInviteSchema,
realmListSchema,
realmMemberListSchema,
realmMemberSchema,
realmRoleSchema,
realmSchema,
} from '@repo/contracts';
import type {
BanMemberInput,
CreateInviteInput,
CreateRole,
Realm,
RealmMember,
RealmPermission,
UpdateRole,
} from '@repo/contracts';
import { api, noContent } from '@/lib/api';
/** The realms the signed-in user is in, in the order they joined them. */
export const realmsQuery = queryOptions({
queryKey: ['realms', 'list'],
queryFn: ({ signal }) => api('/realms', { schema: realmListSchema, signal }),
});
/** A realm with its cauldrons, roles and what the user may do in it. */
export const realmQuery = (realmId: string) =>
queryOptions({
queryKey: ['realms', 'detail', realmId],
queryFn: ({ signal }) =>
api(`/realms/${realmId}`, { schema: realmSchema, signal }),
});
export const realmMembersQuery = (realmId: string) =>
queryOptions({
queryKey: ['realms', 'members', realmId],
queryFn: ({ signal }) =>
api(`/realms/${realmId}/members`, {
schema: realmMemberListSchema,
signal,
}),
});
/** The invites that still work, as far as the user may see them. */
export const realmInvitesQuery = (realmId: string) =>
queryOptions({
queryKey: ['realms', 'invites', realmId],
queryFn: ({ signal }) =>
api(`/realms/${realmId}/invites`, {
schema: realmInviteListSchema,
signal,
}),
});
/** The people banned from a realm, newest ban first. */
export const realmBansQuery = (realmId: string) =>
queryOptions({
queryKey: ['realms', 'bans', realmId],
queryFn: ({ signal }) =>
api(`/realms/${realmId}/bans`, { schema: realmBanListSchema, signal }),
});
/** Where an invite link leads. Always asked afresh: links run out. */
export const invitePreviewQuery = (code: string) =>
queryOptions({
queryKey: ['invites', code],
queryFn: ({ signal }) =>
api(`/invites/${code}`, { schema: invitePreviewSchema, signal }),
staleTime: 0,
});
/** What each permission lets its holder do, in the words the app shows. */
export const PERMISSION_LABELS: Record<
RealmPermission,
{ name: string; description: string }
> = {
manageRealm: {
name: 'Manage realm',
description: 'Rename the realm and revoke anyone’s invites.',
},
manageCauldrons: {
name: 'Manage cauldrons',
description: 'Create, rename and delete cauldrons.',
},
manageRoles: {
name: 'Manage roles',
description:
'Create roles and give them to members, up to what they can do themselves.',
},
kickMembers: {
name: 'Remove members',
description: 'Remove members who can’t do more than they can.',
},
banMembers: {
name: 'Ban members',
description: 'Ban members who can’t do more than they can, and lift bans.',
},
createInvites: {
name: 'Invite people',
description: 'Make invite links.',
},
sendMessages: {
name: 'Send messages',
description: 'Post in cauldrons and join their calls.',
},
manageMessages: {
name: 'Manage messages',
description: 'Delete other people’s messages.',
},
};
/** Whether the signed-in user may do this in a realm. */
export function can(realm: Realm, permission: RealmPermission): boolean {
return realm.permissions.includes(permission);
}
/** Whether the user may do everything this role allows, so may manage it. */
export function canManageRole(
realm: Realm,
role: { permissions: RealmPermission[] },
): boolean {
return (
can(realm, 'manageRoles') &&
hasPermissions(realm.permissions, role.permissions)
);
}
/** What a member may do, worked out the way the API does it. */
export function memberPermissions(
realm: Realm,
member: RealmMember,
): RealmPermission[] {
if (member.user.id === realm.ownerId) return [...REALM_PERMISSIONS];
const roles = realm.roles.filter(
(role) => role.isDefault || member.roleIds.includes(role.id),
);
return REALM_PERMISSIONS.filter((permission) =>
roles.some((role) => role.permissions.includes(permission)),
);
}
/** Never the owner, and nobody who can do more than the user can. */
function outranks(realm: Realm, member: RealmMember): boolean {
return (
member.user.id !== realm.ownerId &&
hasPermissions(realm.permissions, memberPermissions(realm, member))
);
}
/** Whether the user may remove this member. */
export function canRemoveMember(realm: Realm, member: RealmMember): boolean {
return can(realm, 'kickMembers') && outranks(realm, member);
}
/** Whether the user may ban this member. */
export function canBanMember(realm: Realm, member: RealmMember): boolean {
return can(realm, 'banMembers') && outranks(realm, member);
}
/** The address to share for an invite code. */
export function inviteLink(code: string): string {
return `${window.location.origin}/app/invite/${code}`;
}
/**
* The code in what someone pasted: a whole invite link or the code alone.
* Nothing when it can't be either.
*/
export function inviteCodeFrom(pasted: string): string | undefined {
const last = pasted.trim().split(/[/?#]/).filter(Boolean).at(-1);
return last && /^[A-Za-z0-9_-]{8,32}$/.test(last) ? last : undefined;
}
/** "1 member", "3 members". */
export function realmMemberCount(count: number): string {
return count === 1 ? '1 member' : `${count} members`;
}
/** Stores a realm the API just answered with, in the list as well. */
function putRealmInCache(queryClient: QueryClient, realm: Realm) {
queryClient.setQueryData(realmQuery(realm.id).queryKey, realm);
const summary = {
id: realm.id,
name: realm.name,
ownerId: realm.ownerId,
hasUnread: realm.cauldrons.some((cauldron) => cauldron.unreadCount > 0),
};
queryClient.setQueryData(realmsQuery.queryKey, (realms) => {
if (!realms) return realms;
return realms.some((item) => item.id === realm.id)
? realms.map((item) => (item.id === realm.id ? summary : item))
: [...realms, summary];
});
}
// Every change below also reaches the realm's members as "realm:changed"
// over the socket, which refetches what they have open. The refreshes here
// are for the person who made the change, so they needn't wait for it.
function useRefreshRealm(realmId: string) {
const queryClient = useQueryClient();
return () =>
queryClient.invalidateQueries({ queryKey: realmQuery(realmId).queryKey });
}
function useRefreshMembers(realmId: string) {
const queryClient = useQueryClient();
return () =>
Promise.all([
queryClient.invalidateQueries({
queryKey: realmMembersQuery(realmId).queryKey,
}),
queryClient.invalidateQueries({ queryKey: realmQuery(realmId).queryKey }),
]);
}
export function useCreateRealm() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (name: string) =>
api('/realms', { method: 'POST', body: { name }, schema: realmSchema }),
onSuccess: (realm) => putRealmInCache(queryClient, realm),
});
}
export function useRenameRealm(realmId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (name: string) =>
api(`/realms/${realmId}`, {
method: 'PATCH',
body: { name },
schema: realmSchema,
}),
onSuccess: (realm) => putRealmInCache(queryClient, realm),
});
}
export function useDeleteRealm(realmId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: () =>
api(`/realms/${realmId}`, { method: 'DELETE', schema: noContent }),
// Not awaited: callers move away from the realm without waiting.
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
},
});
}
/** Removes someone from a realm; with the user's own id, leaves it. */
export function useRemoveRealmMember(realmId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userId: string) =>
api(`/realms/${realmId}/members/${userId}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
void queryClient.invalidateQueries({
queryKey: realmMembersQuery(realmId).queryKey,
});
},
});
}
/** Puts a member out of a realm and keeps invites from letting them back. */
export function useBanMember(realmId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ userId, ...body }: BanMemberInput & { userId: string }) =>
api(`/realms/${realmId}/bans/${userId}`, {
method: 'PUT',
body,
schema: noContent,
}),
onSuccess: () => {
void queryClient.invalidateQueries({
queryKey: realmMembersQuery(realmId).queryKey,
});
void queryClient.invalidateQueries({
queryKey: realmBansQuery(realmId).queryKey,
});
},
});
}
/** Lifts a ban. The person still needs an invite to come back. */
export function useUnbanMember(realmId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userId: string) =>
api(`/realms/${realmId}/bans/${userId}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: realmBansQuery(realmId).queryKey,
}),
});
}
export function useSetMemberRoles(realmId: string) {
const refresh = useRefreshMembers(realmId);
return useMutation({
mutationFn: ({ userId, roleIds }: { userId: string; roleIds: string[] }) =>
api(`/realms/${realmId}/members/${userId}/roles`, {
method: 'PUT',
body: { roleIds },
schema: realmMemberSchema,
}),
onSuccess: refresh,
});
}
export function useCreateRole(realmId: string) {
const refresh = useRefreshRealm(realmId);
return useMutation({
mutationFn: (body: CreateRole) =>
api(`/realms/${realmId}/roles`, {
method: 'POST',
body,
schema: realmRoleSchema,
}),
onSuccess: refresh,
});
}
export function useUpdateRole(realmId: string) {
const refresh = useRefreshRealm(realmId);
return useMutation({
mutationFn: ({ roleId, ...body }: UpdateRole & { roleId: string }) =>
api(`/realms/${realmId}/roles/${roleId}`, {
method: 'PATCH',
body,
schema: realmRoleSchema,
}),
onSuccess: refresh,
});
}
export function useDeleteRole(realmId: string) {
const refresh = useRefreshMembers(realmId);
return useMutation({
mutationFn: (roleId: string) =>
api(`/realms/${realmId}/roles/${roleId}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: refresh,
});
}
export function useCreateCauldron(realmId: string) {
const refresh = useRefreshRealm(realmId);
return useMutation({
mutationFn: (name: string) =>
api(`/realms/${realmId}/cauldrons`, {
method: 'POST',
body: { name },
schema: cauldronSchema,
}),
onSuccess: refresh,
});
}
export function useRenameCauldron(realmId: string) {
const refresh = useRefreshRealm(realmId);
return useMutation({
mutationFn: ({ cauldronId, name }: { cauldronId: string; name: string }) =>
api(`/realms/${realmId}/cauldrons/${cauldronId}`, {
method: 'PATCH',
body: { name },
schema: cauldronSchema,
}),
onSuccess: refresh,
});
}
export function useDeleteCauldron(realmId: string) {
const refresh = useRefreshRealm(realmId);
return useMutation({
mutationFn: (cauldronId: string) =>
api(`/realms/${realmId}/cauldrons/${cauldronId}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: refresh,
});
}
function useRefreshInvites(realmId: string) {
const queryClient = useQueryClient();
return () =>
queryClient.invalidateQueries({
queryKey: realmInvitesQuery(realmId).queryKey,
});
}
export function useCreateInvite(realmId: string) {
const refresh = useRefreshInvites(realmId);
return useMutation({
mutationFn: (body: CreateInviteInput) =>
api(`/realms/${realmId}/invites`, {
method: 'POST',
body,
schema: realmInviteSchema,
}),
onSuccess: refresh,
});
}
export function useRevokeInvite(realmId: string) {
const refresh = useRefreshInvites(realmId);
return useMutation({
mutationFn: (code: string) =>
api(`/realms/${realmId}/invites/${code}`, {
method: 'DELETE',
schema: noContent,
}),
onSuccess: refresh,
});
}
/** Joins the realm an invite leads to. */
export function useAcceptInvite() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (code: string) =>
api(`/invites/${code}/accept`, { method: 'POST', schema: realmSchema }),
onSuccess: (realm) => putRealmInCache(queryClient, realm),
});
}
+175
View File
@@ -0,0 +1,175 @@
import { useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from '@tanstack/react-router';
import {
callSchema,
conversationReadSchema,
messageDeletionSchema,
messageSchema,
reactionChangeSchema,
} from '@repo/contracts';
import type {
ClientToServerEvents,
ServerToClientEvents,
} from '@repo/contracts';
import { io } from 'socket.io-client';
import type { Socket } from 'socket.io-client';
import { apiUrl } from '@/lib/api';
import { applyCallChange, callsQuery, ring, stopRinging } from '@/lib/calls';
import {
addMessageToCache,
addMessageToHistory,
applyReactionChange,
conversationsQuery,
removeMessageFromCache,
} from '@/lib/conversations';
import { friendsQuery } from '@/lib/friends';
import { notifyOfCall, notifyOfMessage } from '@/lib/notifications';
import { ownProfileQuery } from '@/lib/profile';
import {
realmBansQuery,
realmMembersQuery,
realmQuery,
realmsQuery,
} from '@/lib/realms';
import { addUnread, isBeingRead, setUnreadCount } from '@/lib/unread';
/**
* Keeps a socket to the API open while the component is mounted and folds
* what it hears into the query cache, so every screen updates live. The
* browser sends the session cookie with the connection.
*/
export function useRealtime() {
const queryClient = useQueryClient();
const router = useRouter();
useEffect(() => {
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(
apiUrl,
// The API accepts WebSocket connections only (no HTTP long-polling).
{ transports: ['websocket'], withCredentials: true },
);
let hasConnectedBefore = false;
socket.on('connect', () => {
// Events sent while the connection was down are gone; fetch again.
if (hasConnectedBefore) {
void queryClient.invalidateQueries({ queryKey: ['conversations'] });
void queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
void queryClient.invalidateQueries({ queryKey: ['realms'] });
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
}
hasConnectedBefore = true;
});
socket.on('disconnect', (reason) => {
// The API closes a socket when its session ends or runs out. After
// that the client doesn't retry on its own, so try once: it gets back
// in if the session was only renewed, and is refused if it is over.
if (reason === 'io server disconnect') socket.connect();
});
const ownId = () => queryClient.getQueryData(ownProfileQuery.queryKey)?.id;
const open = (to: { realmId: string | null; conversationId: string }) =>
void (to.realmId
? router.navigate({
to: '/app/r/$realmId/$cauldronId',
params: { realmId: to.realmId, cauldronId: to.conversationId },
})
: router.navigate({
to: '/app/c/$conversationId',
params: { conversationId: to.conversationId },
}));
socket.on('message:created', (payload, context) => {
const parsed = messageSchema.safeParse(payload);
if (!parsed.success) return;
const message = parsed.data;
const { realmId } = context;
// A cauldron's message belongs to its realm, not the list of chats.
if (realmId) addMessageToHistory(queryClient, message);
else addMessageToCache(queryClient, message);
const me = ownId();
if (!me || message.author.id === me) return;
// A message arriving in front of the reader is marked read by the
// chat itself; any other one counts as unread.
if (!isBeingRead(message.conversationId)) {
addUnread(queryClient, message.conversationId, realmId);
}
notifyOfMessage(queryClient, message, realmId, me, open);
});
socket.on('message:deleted', (payload) => {
const deletion = messageDeletionSchema.safeParse(payload);
if (deletion.success) removeMessageFromCache(queryClient, deletion.data);
});
socket.on('reaction:changed', (payload) => {
const change = reactionChangeSchema.safeParse(payload);
if (change.success)
applyReactionChange(queryClient, change.data, ownId());
});
socket.on('conversation:read', (payload) => {
const read = conversationReadSchema.safeParse(payload);
if (read.success) setUnreadCount(queryClient, read.data);
});
socket.on('call:changed', (payload) => {
const parsed = callSchema.safeParse(payload);
if (!parsed.success) return;
const call = parsed.data;
const hasStarted = applyCallChange(queryClient, call);
const me = ownId();
const isIn = call.participants.some((person) => person.id === me);
// A friend starting a call in a chat is a call to the user. A realm's
// cauldron is a room people drop into; it only shows there.
if (hasStarted && me && !isIn && call.realmId === null) {
ring(call);
notifyOfCall(queryClient, call, me, open);
} else if (isIn || call.participants.length === 0) {
stopRinging(call.conversationId);
}
});
socket.on('realm:changed', (realmId, what) => {
// Either kind can change what the realm's own details carry (the
// member count, what the user may do there).
void queryClient.invalidateQueries({
queryKey: realmQuery(realmId).queryKey,
});
if (what === 'members') {
void queryClient.invalidateQueries({
queryKey: realmMembersQuery(realmId).queryKey,
});
// A member may have gone by being banned.
void queryClient.invalidateQueries({
queryKey: realmBansQuery(realmId).queryKey,
});
} else {
// Renamed, deleted, joined or left: the list of realms shows those.
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
// A cauldron that is gone, or a realm the user is out of, takes its
// calls along without a word about each.
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
}
});
socket.on('conversations:changed', () => {
void queryClient.invalidateQueries({
queryKey: conversationsQuery.queryKey,
});
// Someone taken out of a group hears no more about its call.
void queryClient.invalidateQueries({ queryKey: callsQuery.queryKey });
});
socket.on('friends:changed', () => {
void queryClient.invalidateQueries({ queryKey: friendsQuery.queryKey });
});
return () => {
socket.disconnect();
};
}, [queryClient, router]);
}
+29
View File
@@ -0,0 +1,29 @@
/** Where the app sends people once they are signed in. */
export const DEFAULT_SIGNED_IN_PATH = '/app';
export interface AuthSearch {
/** The page that asked for sign-in, to return to afterwards. */
redirect?: string;
}
/**
* Returns the value only when it is a path on this site ("/app/settings"),
* so a crafted link can't send someone to another site after they log in.
* Absolute URLs, "//host" and "/\host" are all refused.
*/
export function toSitePath(value: unknown): string | undefined {
return typeof value === 'string' && /^\/(?![/\\])/.test(value)
? value
: undefined;
}
/**
* `validateSearch` for the login and register routes. It always returns the
* `redirect` key: the router fills any key left out from the raw query
* string, which would let an unchecked value through.
*/
export function validateAuthSearch(
search: Record<string, unknown>,
): AuthSearch {
return { redirect: toSitePath(search.redirect) };
}
+5
View File
@@ -0,0 +1,5 @@
/** Shown in the page title and on the welcome page. Change it in one place. */
export const site = {
name: 'electro4ort',
tagline: 'Chat, gather and call in one place',
};
+167
View File
@@ -0,0 +1,167 @@
import { useEffect, useSyncExternalStore } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { QueryClient } from '@tanstack/react-query';
import { UNREAD_COUNT_MAX, conversationReadSchema } from '@repo/contracts';
import type { ConversationRead } from '@repo/contracts';
import { api } from '@/lib/api';
import { conversationsQuery } from '@/lib/conversations';
import { realmQuery, realmsQuery } from '@/lib/realms';
import { site } from '@/lib/site';
/** "3", or "99+" once the count has reached where the API stops counting. */
export function formatUnread(count: number): string {
return count >= UNREAD_COUNT_MAX ? `${UNREAD_COUNT_MAX - 1}+` : String(count);
}
/** Stores a conversation's or cauldron's unread count wherever it shows. */
export function setUnreadCount(
queryClient: QueryClient,
{ conversationId, realmId, unreadCount }: ConversationRead,
) {
if (!realmId) {
queryClient.setQueryData(conversationsQuery.queryKey, (conversations) =>
conversations?.map((item) =>
item.id === conversationId ? { ...item, unreadCount } : item,
),
);
return;
}
queryClient.setQueryData(realmQuery(realmId).queryKey, (realm) =>
realm
? {
...realm,
cauldrons: realm.cauldrons.map((item) =>
item.id === conversationId ? { ...item, unreadCount } : item,
),
}
: realm,
);
// The list of realms only says whether anything in a realm is unread.
const realm = queryClient.getQueryData(realmQuery(realmId).queryKey);
if (realm) {
const hasUnread = realm.cauldrons.some((item) => item.unreadCount > 0);
queryClient.setQueryData(realmsQuery.queryKey, (realms) =>
realms?.map((item) =>
item.id === realmId ? { ...item, hasUnread } : item,
),
);
} else if (unreadCount > 0) {
queryClient.setQueryData(realmsQuery.queryKey, (realms) =>
realms?.map((item) =>
item.id === realmId ? { ...item, hasUnread: true } : item,
),
);
} else {
// Other cauldrons of a realm that isn't loaded may still have some.
void queryClient.invalidateQueries({ queryKey: realmsQuery.queryKey });
}
}
/** Counts one more unread message, for one that just came in. */
export function addUnread(
queryClient: QueryClient,
conversationId: string,
realmId: string | null,
) {
const current = realmId
? queryClient
.getQueryData(realmQuery(realmId).queryKey)
?.cauldrons.find((item) => item.id === conversationId)?.unreadCount
: queryClient
.getQueryData(conversationsQuery.queryKey)
?.find((item) => item.id === conversationId)?.unreadCount;
setUnreadCount(queryClient, {
conversationId,
realmId,
unreadCount: Math.min((current ?? 0) + 1, UNREAD_COUNT_MAX),
});
}
// Which conversation is on screen with its newest messages in view. New
// messages there are read as they arrive, so they are never counted.
let onScreen: string | null = null;
/** Called by the chat as it is shown, scrolled and hidden. */
export function setConversationOnScreen(
conversationId: string,
isOnScreen: boolean,
) {
if (isOnScreen) onScreen = conversationId;
else if (onScreen === conversationId) onScreen = null;
}
/** Whether the app is in front of the person: tab showing, window focused. */
export function isAttentive(): boolean {
return document.visibilityState === 'visible' && document.hasFocus();
}
/** Whether a new message in this conversation is being looked at right now. */
export function isBeingRead(conversationId: string): boolean {
return onScreen === conversationId && isAttentive();
}
function subscribeToAttention(onChange: () => void) {
window.addEventListener('focus', onChange);
window.addEventListener('blur', onChange);
document.addEventListener('visibilitychange', onChange);
return () => {
window.removeEventListener('focus', onChange);
window.removeEventListener('blur', onChange);
document.removeEventListener('visibilitychange', onChange);
};
}
/** `isAttentive()` as state: re-renders when the person leaves or returns. */
export function useAttentive(): boolean {
return useSyncExternalStore(subscribeToAttention, isAttentive, () => true);
}
/**
* Tells the API how far the user has read. The badge goes at once; the
* answer (and "conversation:read" in other tabs) brings the true count.
*/
export function useMarkRead(conversationId: string, realmId: string | null) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (messageId: string) =>
api(`/conversations/${conversationId}/read`, {
method: 'PUT',
body: { messageId },
schema: conversationReadSchema,
}),
onMutate: () =>
setUnreadCount(queryClient, { conversationId, realmId, unreadCount: 0 }),
onSuccess: (read) => setUnreadCount(queryClient, read),
});
}
/**
* What is waiting across the app: unread messages in the user's chats, and
* whether any realm has something new.
*/
export function useUnreadSummary() {
const { data: conversations } = useQuery(conversationsQuery);
const { data: realms } = useQuery(realmsQuery);
const messages = (conversations ?? []).reduce(
(total, item) => total + item.unreadCount,
0,
);
const inRealms = (realms ?? []).some((item) => item.hasUnread);
return { messages, inRealms, any: messages > 0 || inRealms };
}
/** Shows what is unread in the tab's title: "(3) name", or a dot for realms. */
export function useUnreadTitle() {
const { messages, inRealms } = useUnreadSummary();
const mark =
messages > 0 ? `(${formatUnread(messages)}) ` : inRealms ? '• ' : '';
useEffect(() => {
const original = document.title;
document.title = `${mark}${site.name}`;
return () => {
document.title = original;
};
}, [mark]);
}
+62
View File
@@ -0,0 +1,62 @@
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
// Closer to the bottom than this counts as "reading the newest messages".
const END_THRESHOLD_PX = 80;
interface Snapshot {
firstId: string | undefined;
lastId: string | undefined;
scrollHeight: number;
}
/**
* Scrolling for a message list that grows at both ends:
* - it opens at the newest message;
* - a new message scrolls into view only if the reader was at the bottom;
* - older messages loaded above leave the ones being read where they are.
*
* Put `viewportRef` and `onScroll` on the scrolling element, which also needs
* `overflow-anchor: none` so the browser doesn't adjust the position as well.
*/
export function useChatScroll(messages: { id: string }[]) {
const viewportRef = useRef<HTMLDivElement>(null);
const atEndRef = useRef(true);
const [isAtEnd, setIsAtEnd] = useState(true);
const previous = useRef<Snapshot | null>(null);
const firstId = messages.at(0)?.id;
const lastId = messages.at(-1)?.id;
useLayoutEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
const before = previous.current;
const prepended =
before !== null && before.firstId !== firstId && before.lastId === lastId;
if (prepended) {
viewport.scrollTop += viewport.scrollHeight - before.scrollHeight;
} else if (atEndRef.current) {
viewport.scrollTop = viewport.scrollHeight;
}
previous.current = { firstId, lastId, scrollHeight: viewport.scrollHeight };
}, [firstId, lastId, messages.length]);
const onScroll = useCallback(() => {
const viewport = viewportRef.current;
if (!viewport) return;
const distance =
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
atEndRef.current = distance < END_THRESHOLD_PX;
setIsAtEnd(atEndRef.current);
}, []);
/** Jumps to the newest message and follows new ones again. */
const scrollToEnd = useCallback(() => {
atEndRef.current = true;
setIsAtEnd(true);
const viewport = viewportRef.current;
if (viewport) viewport.scrollTop = viewport.scrollHeight;
}, []);
return { viewportRef, onScroll, isAtEnd, scrollToEnd };
}
+21
View File
@@ -0,0 +1,21 @@
import { useCallback, useSyncExternalStore } from 'react';
/** Whether a CSS media query matches right now; follows the window. */
export function useMediaQuery(query: string): boolean {
const subscribe = useCallback(
(onChange: () => void) => {
const list = window.matchMedia(query);
list.addEventListener('change', onChange);
return () => list.removeEventListener('change', onChange);
},
[query],
);
return useSyncExternalStore(
subscribe,
() => window.matchMedia(query).matches,
() => false,
);
}
/** Tailwind's `md` breakpoint: wide enough for the side columns. */
export const WIDE_SCREEN = '(min-width: 48rem)';