refactor: restructure frontend and backend by domain services
PR — Ouverture automatique / create-pr (push) Successful in 3s
PR — Ouverture automatique / create-pr (push) Successful in 3s
Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts) into a layered structure inspired by JeanXXIII-CRM: - config/: appConfig, db - middleware/: auth (session, roles, cookies) - models/: shared types - routes/: *Routes.ts (thin HTTP handlers) - services/: *Service.ts (business logic, one per domain) - utils/: errors, http, migrate, ratelimit, validators, service bootstrap Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format. Route files now carry the "Routes" suffix; service files are named authService.ts, ratelimit.ts, etc. and live in their own files, frontend and backend separated. Updated docs and READMEs to reflect the new layout. Typecheck and builds pass.
This commit is contained in:
@@ -1,605 +0,0 @@
|
||||
import { getLanguage, getLocale } from "./locale";
|
||||
|
||||
export type Theme = "system" | "light" | "dark";
|
||||
export type Language = "fr" | "en";
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
role_name: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
must_change_password: boolean;
|
||||
theme: Theme;
|
||||
language: Language;
|
||||
has_avatar: boolean;
|
||||
avatar_updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface Folder {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
is_system: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface UploadedFile {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
checksum_sha256: string | null;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
download_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface UploadSession {
|
||||
uploadId: string;
|
||||
name: string;
|
||||
folderId: string | null;
|
||||
size: number;
|
||||
chunkSize: number;
|
||||
uploadedBytes: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
|
||||
|
||||
export interface FavoriteFile extends UploadedFile {
|
||||
folder_name: string | null;
|
||||
}
|
||||
|
||||
export interface FolderPermission {
|
||||
user_id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
level: string;
|
||||
expires_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
id: string;
|
||||
ip_address: string | null;
|
||||
user_agent: string | null;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
current: boolean;
|
||||
}
|
||||
|
||||
export interface TrashFolder {
|
||||
id: string;
|
||||
parent_id: string | null;
|
||||
name: string;
|
||||
owner_id: string | null;
|
||||
access_type: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
export interface TrashFile {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
deleted_at: string;
|
||||
}
|
||||
|
||||
export interface MediaItem {
|
||||
id: string;
|
||||
folder_id: string | null;
|
||||
name: string;
|
||||
mime_type: string | null;
|
||||
size_bytes: number;
|
||||
owner_id: string | null;
|
||||
is_starred: boolean;
|
||||
kind: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
created_at: string;
|
||||
has_thumbnail: boolean;
|
||||
}
|
||||
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
used_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: boolean;
|
||||
must_change_password: boolean;
|
||||
last_login_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface StorageLocation {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
mount_path: string;
|
||||
quota_bytes: number | null;
|
||||
used_bytes: number;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AdminStats {
|
||||
users: number;
|
||||
folders: number;
|
||||
files: number;
|
||||
usedBytes: number;
|
||||
trashFiles: number;
|
||||
locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[];
|
||||
}
|
||||
|
||||
export interface AuditEntry {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
user_email: string | null;
|
||||
action: string;
|
||||
resource: string;
|
||||
resource_id: string | null;
|
||||
details: string | null;
|
||||
ip_address: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ChatMember {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
has_avatar: boolean;
|
||||
avatar_updated_at: string | null;
|
||||
last_login_at: string | null;
|
||||
is_self: boolean;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
edited_at: string | null;
|
||||
is_pinned: boolean;
|
||||
has_avatar: boolean;
|
||||
avatar_updated_at: string | null;
|
||||
}
|
||||
|
||||
export interface DirectoryUser {
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
has_avatar: boolean;
|
||||
avatar_updated_at: string | null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const BASE = "/api/cloud";
|
||||
|
||||
const messageOf = (body: unknown, fallback: string): string =>
|
||||
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
|
||||
|
||||
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, {
|
||||
credentials: "same-origin",
|
||||
...init,
|
||||
headers: {
|
||||
...(init?.body ? { "content-type": "application/json" } : {}),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
|
||||
}
|
||||
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue."));
|
||||
return body as T;
|
||||
};
|
||||
|
||||
const post = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "POST",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
const patch = <T>(path: string, payload: unknown): Promise<T> =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
|
||||
const put = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "PUT",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
|
||||
|
||||
const query = (params: Record<string, string | number | null | undefined>): string => {
|
||||
const search = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value !== null && value !== undefined && value !== "") search.set(key, String(value));
|
||||
}
|
||||
const suffix = search.toString();
|
||||
return suffix ? `?${suffix}` : "";
|
||||
};
|
||||
|
||||
const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${BASE}${path}`, {
|
||||
method: "PUT",
|
||||
credentials: "same-origin",
|
||||
headers: type ? { "content-type": type } : {},
|
||||
body,
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion.");
|
||||
}
|
||||
const parsed: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue."));
|
||||
return parsed as T;
|
||||
};
|
||||
|
||||
const resumeKey = (file: File, folderId: string | null): string =>
|
||||
`cohaise.upload:${folderId ?? "root"}:${file.name}:${file.size}:${file.lastModified}`;
|
||||
|
||||
const readResume = (key: string): string | null => {
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeResume = (key: string, uploadId: string): void => {
|
||||
try {
|
||||
window.localStorage.setItem(key, uploadId);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const clearResume = (key: string): void => {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const sendChunk = (
|
||||
uploadId: string,
|
||||
blob: Blob,
|
||||
onProgress: (loaded: number) => void,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("PUT", `${BASE}/uploads/${encodeURIComponent(uploadId)}/chunks`);
|
||||
xhr.withCredentials = true;
|
||||
xhr.setRequestHeader("content-type", "application/octet-stream");
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) onProgress(event.loaded);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
}
|
||||
reject(new ApiError(xhr.status, messageOf(parsed, "L'envoi du morceau a echoue.")));
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, "Serveur injoignable. Verifiez votre connexion."));
|
||||
xhr.onabort = () => reject(new ApiError(0, "Envoi interrompu."));
|
||||
xhr.send(blob);
|
||||
});
|
||||
|
||||
const sessionPath = (uploadId: string): string => `/uploads/${encodeURIComponent(uploadId)}`;
|
||||
|
||||
const uploadFileResumable = async (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
): Promise<{ file: UploadedFile }> => {
|
||||
const key = resumeKey(file, folderId);
|
||||
let upload: UploadSession | null = null;
|
||||
|
||||
const saved = readResume(key);
|
||||
if (saved !== null) {
|
||||
try {
|
||||
const result = await request<{ upload: UploadSession }>(sessionPath(saved));
|
||||
if (result.upload.name === file.name && result.upload.size === file.size) {
|
||||
upload = result.upload;
|
||||
} else {
|
||||
clearResume(key);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) clearResume(key);
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (upload === null) {
|
||||
const result = await post<{ upload: UploadSession }>("/uploads", {
|
||||
name: file.name,
|
||||
folderId,
|
||||
size: file.size,
|
||||
mimeType: file.type || null,
|
||||
});
|
||||
upload = result.upload;
|
||||
writeResume(key, upload.uploadId);
|
||||
}
|
||||
|
||||
const uploadId = upload.uploadId;
|
||||
let offset = upload.uploadedBytes;
|
||||
let attempts = 0;
|
||||
|
||||
while (offset < file.size) {
|
||||
const end = Math.min(offset + upload.chunkSize, file.size);
|
||||
try {
|
||||
await sendChunk(uploadId, file.slice(offset, end), (loaded) =>
|
||||
onProgress?.(offset + loaded, file.size),
|
||||
);
|
||||
offset = end;
|
||||
attempts = 0;
|
||||
} catch (error) {
|
||||
const transient =
|
||||
!(error instanceof ApiError) ||
|
||||
error.status === 0 ||
|
||||
error.status === 409 ||
|
||||
error.status >= 500;
|
||||
attempts += 1;
|
||||
if (!transient || attempts > 4) throw error;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 400 * attempts));
|
||||
const status = await request<{ upload: UploadSession }>(sessionPath(uploadId));
|
||||
if (status.upload.name !== file.name || status.upload.size !== file.size) {
|
||||
throw new ApiError(409, "La session d'envoi ne correspond plus au fichier.");
|
||||
}
|
||||
offset = status.upload.uploadedBytes;
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.(file.size, file.size);
|
||||
const result = await post<{ file: UploadedFile }>(`${sessionPath(uploadId)}/complete`);
|
||||
clearResume(key);
|
||||
return result;
|
||||
};
|
||||
|
||||
export const api = {
|
||||
me: () => request<{ user: User }>("/auth/me"),
|
||||
login: (email: string, password: string) =>
|
||||
post<{ user: User }>("/auth/login", { email, password }),
|
||||
logout: () => post<{ ok: boolean }>("/auth/logout"),
|
||||
changePassword: (current: string, next: string) =>
|
||||
post<{ ok: boolean }>("/auth/change-password", { current, next }),
|
||||
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
|
||||
resetPassword: (token: string, password: string) =>
|
||||
post<{ ok: boolean }>("/account/reset-password", { token, password }),
|
||||
requestEmailChange: (password: string, new_email: string) =>
|
||||
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
|
||||
confirmEmailChange: (token: string) =>
|
||||
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
|
||||
|
||||
updateProfile: (first_name: string, last_name: string) =>
|
||||
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
|
||||
preferences: () => request<{ theme: Theme; language: Language }>("/account/preferences"),
|
||||
updatePreferences: (theme: Theme, language: Language) =>
|
||||
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
|
||||
sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"),
|
||||
revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`),
|
||||
revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"),
|
||||
avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`,
|
||||
uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type),
|
||||
deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"),
|
||||
|
||||
directory: () => request<{ users: DirectoryUser[] }>("/directory"),
|
||||
folders: (parentId?: string | null) =>
|
||||
request<{ parentId: string | null; folders: Folder[] }>(
|
||||
`/folders${query({ parentId })}`,
|
||||
),
|
||||
createFolder: (name: string, parentId?: string | null) =>
|
||||
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null }),
|
||||
updateFolder: (id: string, name: string) =>
|
||||
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, { name }),
|
||||
moveFolder: (id: string, parentId: string | null) =>
|
||||
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
|
||||
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
|
||||
folderPermissions: (id: string) =>
|
||||
request<{ permissions: FolderPermission[] }>(
|
||||
`/folders/${encodeURIComponent(id)}/permissions`,
|
||||
),
|
||||
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
|
||||
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
|
||||
email,
|
||||
level,
|
||||
expiresAt,
|
||||
}),
|
||||
revokePermission: (id: string, userId: string) =>
|
||||
del<{ ok: boolean }>(
|
||||
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
|
||||
),
|
||||
|
||||
files: (folderId?: string | null) =>
|
||||
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
|
||||
uploadFile: (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
) => {
|
||||
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
|
||||
return uploadFileResumable(file, folderId, onProgress);
|
||||
}
|
||||
return putBinary<{ file: UploadedFile }>(
|
||||
`/files${query({ name: file.name, folderId })}`,
|
||||
file,
|
||||
file.type,
|
||||
).then((result) => {
|
||||
onProgress?.(file.size, file.size);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
uploadSession: (uploadId: string) =>
|
||||
request<{ upload: UploadSession }>(sessionPath(uploadId)),
|
||||
cancelUpload: (uploadId: string) => del<{ ok: boolean }>(sessionPath(uploadId)),
|
||||
renameFile: (id: string, name: string) =>
|
||||
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
|
||||
moveFile: (id: string, folderId: string | null) =>
|
||||
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
|
||||
starFile: (id: string) =>
|
||||
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
|
||||
favorites: () => request<{ files: FavoriteFile[] }>("/favorites"),
|
||||
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
|
||||
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
|
||||
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
|
||||
previewUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/preview`,
|
||||
|
||||
trash: () =>
|
||||
request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
|
||||
restoreFolder: (id: string) =>
|
||||
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
|
||||
restoreFile: (id: string) =>
|
||||
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
|
||||
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
|
||||
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
|
||||
emptyTrash: () => del<{ ok: boolean }>("/trash"),
|
||||
|
||||
search: (q: string) =>
|
||||
request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
|
||||
gallery: (kind: string, limit = 60, offset = 0) =>
|
||||
request<{ kind: string | null; items: MediaItem[] }>(
|
||||
`/media${query({ kind, limit, offset })}`,
|
||||
),
|
||||
|
||||
chatMembers: (folderId: string) =>
|
||||
request<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
|
||||
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
|
||||
request<{ messages: ChatMessage[]; cursor: string }>(
|
||||
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`,
|
||||
),
|
||||
chatSend: (folderId: string, body: string) =>
|
||||
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
|
||||
chatEditMessage: (folderId: string, id: number, body: string) =>
|
||||
patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, {
|
||||
body,
|
||||
}),
|
||||
chatTogglePin: (folderId: string, id: number) =>
|
||||
put<{ pinned: boolean }>(
|
||||
`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`,
|
||||
),
|
||||
chatPins: (folderId: string) =>
|
||||
request<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
|
||||
chatDeleteMessage: (folderId: string, id: number) =>
|
||||
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
|
||||
chatUnread: () => request<{ unread: Record<string, number> }>("/chat/unread"),
|
||||
|
||||
adminStats: () => request<AdminStats>("/admin/stats"),
|
||||
adminUsers: (q?: string) =>
|
||||
request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`),
|
||||
adminCreateUser: (payload: {
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes?: number | null;
|
||||
max_file_bytes?: number | null;
|
||||
}) => post<{ user: AdminUser }>("/admin/users", payload),
|
||||
adminUpdateUser: (
|
||||
id: string,
|
||||
payload: Partial<{
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
quota_bytes: number;
|
||||
max_file_bytes: number;
|
||||
is_active: boolean;
|
||||
}>,
|
||||
) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload),
|
||||
adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`),
|
||||
adminResetPassword: (id: string) =>
|
||||
post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`),
|
||||
adminStorageLocations: () =>
|
||||
request<{ locations: StorageLocation[] }>("/admin/storage-locations"),
|
||||
adminCreateStorageLocation: (payload: {
|
||||
name: string;
|
||||
slug: string;
|
||||
mount_path: string;
|
||||
quota_bytes?: number | null;
|
||||
}) => post<{ ok: boolean }>("/admin/storage-locations", payload),
|
||||
adminUpdateStorageLocation: (
|
||||
id: number,
|
||||
payload: { name?: string; quota_bytes?: number | null; is_active?: boolean },
|
||||
) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload),
|
||||
adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) =>
|
||||
request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
|
||||
adminAuditFilters: () =>
|
||||
request<{ actions: string[]; users: { id: string; email: string | null }[] }>(
|
||||
"/admin/audit/filters",
|
||||
),
|
||||
};
|
||||
|
||||
export const formatBytes = (bytes: number): string => {
|
||||
const english = getLanguage() === "en";
|
||||
if (bytes < 1024) return `${bytes} ${english ? "B" : "o"}`;
|
||||
const units = english ? ["KB", "MB", "GB", "TB"] : ["Ko", "Mo", "Go", "To"];
|
||||
let value = bytes;
|
||||
let index = -1;
|
||||
do {
|
||||
value /= 1024;
|
||||
index += 1;
|
||||
} while (value >= 1024 && index < units.length - 1);
|
||||
return `${value.toLocaleString(getLocale(), { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`;
|
||||
};
|
||||
|
||||
export const formatDate = (value: string | null): string =>
|
||||
value ? new Date(value).toLocaleString(getLocale(), { dateStyle: "medium", timeStyle: "short" }) : "—";
|
||||
|
||||
export const formatDateTimeSeconds = (value: string | null): string =>
|
||||
value
|
||||
? new Date(value).toLocaleString(getLocale(), {
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
})
|
||||
: "—";
|
||||
@@ -1,376 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Language } from "./api.js";
|
||||
import { setLanguage } from "./locale.js";
|
||||
|
||||
const en: Record<string, string> = {
|
||||
"Annuler": "Cancel",
|
||||
"Enregistrer": "Save",
|
||||
"Créer": "Create",
|
||||
"Supprimer": "Delete",
|
||||
"Confirmer": "Confirm",
|
||||
"Fermer": "Close",
|
||||
"Retour": "Back",
|
||||
"Rafraîchir": "Refresh",
|
||||
"Filtrer": "Filter",
|
||||
"Tous les utilisateurs": "All users",
|
||||
"Toutes les actions": "All actions",
|
||||
"Type d'action": "Action type",
|
||||
"Charger plus": "Load more",
|
||||
"Chargement…": "Loading…",
|
||||
"Chargement impossible.": "Unable to load.",
|
||||
"Action impossible.": "Action failed.",
|
||||
"Envoi impossible.": "Upload failed.",
|
||||
"Suppression impossible.": "Deletion failed.",
|
||||
"Enregistrement impossible.": "Saving failed.",
|
||||
"Création impossible.": "Creation failed.",
|
||||
"Mise à jour impossible.": "Update failed.",
|
||||
"Réinitialisation impossible.": "Reset failed.",
|
||||
"Révocation impossible.": "Revocation failed.",
|
||||
"Déplacement impossible.": "Move failed.",
|
||||
"Renommage impossible.": "Rename failed.",
|
||||
"Partage impossible.": "Sharing failed.",
|
||||
"Demande impossible.": "Request failed.",
|
||||
"Confirmation impossible.": "Confirmation failed.",
|
||||
"Recherche impossible.": "Search failed.",
|
||||
"Changement impossible.": "Change failed.",
|
||||
"Connexion impossible.": "Unable to sign in.",
|
||||
"Chargement des dossiers impossible.": "Unable to load folders.",
|
||||
"Chargement des dossiers…": "Loading folders…",
|
||||
"Chargement des partages impossible.": "Unable to load shares.",
|
||||
|
||||
"Fichiers": "Files",
|
||||
"Favoris": "Favorites",
|
||||
"Recherche": "Search",
|
||||
"Galerie": "Gallery",
|
||||
"Corbeille": "Trash",
|
||||
"Comptes": "Accounts",
|
||||
"Stockage": "Storage",
|
||||
"Journal": "Log",
|
||||
"Mon compte": "My account",
|
||||
"Administration": "Administration",
|
||||
"Déconnexion": "Sign out",
|
||||
"Fermer le menu": "Close menu",
|
||||
"Ouvrir le menu": "Open menu",
|
||||
|
||||
"Connectez-vous pour accéder à vos fichiers.": "Sign in to access your files.",
|
||||
"Connexion": "Sign in",
|
||||
"Votre session reste ouverte 14 jours.": "Your session stays open for 14 days.",
|
||||
"Adresse e-mail": "Email address",
|
||||
"Mot de passe": "Password",
|
||||
"Se connecter": "Sign in",
|
||||
"Mot de passe oublié ?": "Forgot your password?",
|
||||
|
||||
"Mot de passe oublié": "Forgot password",
|
||||
"Réinitialisation": "Reset",
|
||||
"Nous vous enverrons un lien valable une heure.": "We will email you a link valid for one hour.",
|
||||
"Si cette adresse correspond à un compte, un message contenant le lien de réinitialisation vient d'être envoyé.":
|
||||
"If this address matches an account, a message with the reset link has just been sent.",
|
||||
"Retour à la connexion": "Back to sign in",
|
||||
"Envoyer le lien": "Send link",
|
||||
|
||||
"Nouveau mot de passe": "New password",
|
||||
"Choisissez un mot de passe robuste.": "Choose a strong password.",
|
||||
"Ce lien est incomplet ou invalide.": "This link is incomplete or invalid.",
|
||||
"Demander un nouveau lien": "Request a new link",
|
||||
"Votre mot de passe a été réinitialisé. Vous pouvez vous connecter.":
|
||||
"Your password has been reset. You can now sign in.",
|
||||
"Confirmation": "Confirmation",
|
||||
"8 caractères minimum.": "At least 8 characters.",
|
||||
"Réinitialiser": "Reset",
|
||||
"Les deux mots de passe ne correspondent pas.": "The two passwords do not match.",
|
||||
|
||||
"Changement d'adresse": "Email change",
|
||||
"Votre adresse e-mail a été mise à jour.": "Your email address has been updated.",
|
||||
"Accéder à mes fichiers": "Go to my files",
|
||||
|
||||
"Bienvenue {name}. Ce mot de passe a été défini par un administrateur : choisissez le vôtre.":
|
||||
"Welcome {name}. This password was set by an administrator: choose your own.",
|
||||
"Changement requis": "Change required",
|
||||
"Les autres sessions ouvertes sur ce compte seront fermées.":
|
||||
"Other sessions open on this account will be closed.",
|
||||
"Mot de passe actuel": "Current password",
|
||||
"Se déconnecter": "Sign out",
|
||||
|
||||
"Racine": "Root",
|
||||
"Vos dossiers et fichiers. Envoyez un fichier ou créez un dossier.":
|
||||
"Your folders and files. Upload a file or create a folder.",
|
||||
"Fil d'Ariane": "Breadcrumb",
|
||||
"Discussion": "Discussion",
|
||||
"Espace utilisé": "Space used",
|
||||
"{used} sur {quota}": "{used} of {quota}",
|
||||
"Envoyer": "Upload",
|
||||
"Nouveau dossier": "New folder",
|
||||
"Contrats 2026": "Contracts 2026",
|
||||
"Emplacement vide": "Empty location",
|
||||
"Créez un sous-dossier ou envoyez un fichier pour commencer.":
|
||||
"Create a subfolder or upload a file to get started.",
|
||||
"Dossiers": "Folders",
|
||||
"Aperçu de {name}": "Preview of {name}",
|
||||
"Retirer l'étoile de {name}": "Remove star from {name}",
|
||||
"Étoiler {name}": "Star {name}",
|
||||
"Télécharger": "Download",
|
||||
"Renommer {name}": "Rename {name}",
|
||||
"Déplacer {name}": "Move {name}",
|
||||
"Supprimer {name}": "Delete {name}",
|
||||
"Partager {name}": "Share {name}",
|
||||
"Discussion {name}": "Discussion {name}",
|
||||
"Mettre à la corbeille": "Move to trash",
|
||||
"ce dossier": "this folder",
|
||||
"ce fichier": "this file",
|
||||
"Placer {name} ({kind}) dans la corbeille ?": "Move {name} ({kind}) to the trash?",
|
||||
|
||||
"Lecture": "Read",
|
||||
"Écriture": "Write",
|
||||
"Nom": "Name",
|
||||
"Renommer": "Rename",
|
||||
"Déplacer": "Move",
|
||||
"Destination de {name}.": "Destination for {name}.",
|
||||
"Destination": "Destination",
|
||||
"Partager « {name} »": "Share “{name}”",
|
||||
"Membre": "Member",
|
||||
"Choisir un membre": "Choose a member",
|
||||
"Niveau": "Level",
|
||||
"Expire le": "Expires on",
|
||||
"Autoriser": "Grant",
|
||||
"Accès accordés": "Granted access",
|
||||
"Aucun partage pour ce dossier.": "No shares for this folder.",
|
||||
"Révoquer {email}": "Revoke {email}",
|
||||
"{level} · jusqu'au {date}": "{level} · until {date}",
|
||||
"Aucun autre membre à ajouter.": "No other member to add.",
|
||||
|
||||
"Modification impossible.": "Unable to edit.",
|
||||
"Épinglage impossible.": "Unable to pin.",
|
||||
"Envoi du message impossible.": "Unable to send the message.",
|
||||
|
||||
"Compte supprimé": "Deleted account",
|
||||
"Supprimer le message": "Delete message",
|
||||
"Ce message sera retiré du salon pour tout le monde.":
|
||||
"This message will be removed from the room for everyone.",
|
||||
"Membres du dossier": "Folder members",
|
||||
"Membres": "Members",
|
||||
"(vous)": "(you)",
|
||||
"Dernière connexion le {date}": "Last sign-in on {date}",
|
||||
"Jamais connecté": "Never signed in",
|
||||
"Masquer les membres": "Hide members",
|
||||
"Afficher les membres": "Show members",
|
||||
"Discussion · {name}": "Discussion · {name}",
|
||||
"Membres ayant accès à ce dossier": "Members with access to this folder",
|
||||
"Fermer la discussion": "Close discussion",
|
||||
"Aucun message": "No messages",
|
||||
"Lancez la discussion : les membres du dossier verront votre message.":
|
||||
"Start the conversation: folder members will see your message.",
|
||||
"Écrire un message… (Entrée pour envoyer, Maj+Entrée pour retour à la ligne)":
|
||||
"Write a message… (Enter to send, Shift+Enter for a new line)",
|
||||
"Votre message": "Your message",
|
||||
"(modifié)": "(edited)",
|
||||
"Modifier le message": "Edit message",
|
||||
"Épingler le message": "Pin message",
|
||||
"Désépingler le message": "Unpin message",
|
||||
"Messages épinglés": "Pinned messages",
|
||||
|
||||
"Déposez vos fichiers ici": "Drop your files here",
|
||||
"{count} fichier(s) déposé(s) dans {name}.": "{count} file(s) uploaded to {name}.",
|
||||
"{count} fichier(s) déposé(s) dans ce dossier.": "{count} file(s) uploaded to this folder.",
|
||||
"Envoi en cours": "Uploading",
|
||||
"Envoi {current}/{total}…": "Uploading {current}/{total}…",
|
||||
"{current}/{total}": "{current}/{total}",
|
||||
|
||||
"Sélectionner {name}": "Select {name}",
|
||||
"{count} élément(s) sélectionné(s).": "{count} item(s) selected.",
|
||||
"Annuler la sélection": "Clear selection",
|
||||
"Déplacer {count} éléments": "Move {count} items",
|
||||
"{count} éléments seront déplacés.": "{count} items will be moved.",
|
||||
"{count} élément(s) seront placés dans la corbeille.":
|
||||
"{count} item(s) will be moved to the trash.",
|
||||
"Seuls les fichiers peuvent être téléchargés.": "Only files can be downloaded.",
|
||||
"Les dossiers n'ont pas été téléchargés.": "Folders were not downloaded.",
|
||||
|
||||
"Lecture impossible.": "Unable to read.",
|
||||
"Ouvrir": "Open",
|
||||
"Le PDF s'ouvre dans un nouvel onglet.": "The PDF opens in a new tab.",
|
||||
"Aperçu indisponible pour ce format.": "Preview unavailable for this format.",
|
||||
"Fichier précédent": "Previous file",
|
||||
"Fichier suivant": "Next file",
|
||||
|
||||
"Les fichiers que vous avez étoilés, tous dossiers confondus.":
|
||||
"The files you starred, across all folders.",
|
||||
"Aucun favori": "No favorites",
|
||||
"Étoilez un fichier dans l'explorateur pour le retrouver ici.":
|
||||
"Star a file in the browser to find it here.",
|
||||
|
||||
"Saisissez au moins deux caractères.": "Enter at least two characters.",
|
||||
"Recherchez par nom dans les dossiers et fichiers auxquels vous avez accès.":
|
||||
"Search by name in the folders and files you can access.",
|
||||
"Terme recherché": "Search term",
|
||||
"facture, rapport…": "invoice, report…",
|
||||
"Rechercher": "Search",
|
||||
"Télécharger {name}": "Download {name}",
|
||||
"Aucun résultat": "No results",
|
||||
"Rien ne correspond à « {q} ».": "Nothing matches “{q}”.",
|
||||
|
||||
"Tout": "All",
|
||||
"Images": "Images",
|
||||
"Vidéos": "Videos",
|
||||
"Audio": "Audio",
|
||||
"Documents": "Documents",
|
||||
"Archives": "Archives",
|
||||
"Autres": "Other",
|
||||
"Parcourez les médias auxquels vous avez accès.": "Browse the media you can access.",
|
||||
"Filtrer par type": "Filter by type",
|
||||
"Aucun média": "No media",
|
||||
"Rien à afficher pour ce filtre.": "Nothing to show for this filter.",
|
||||
|
||||
"Vider la corbeille": "Empty trash",
|
||||
"Tous les éléments seront définitivement supprimés. Cette action est irréversible.":
|
||||
"All items will be permanently deleted. This action cannot be undone.",
|
||||
"Vider": "Empty",
|
||||
"Supprimer définitivement": "Delete permanently",
|
||||
"Supprimer définitivement {name} ? Cette action est irréversible.":
|
||||
"Permanently delete {name}? This action cannot be undone.",
|
||||
"Les éléments sont définitivement supprimés après {days} jours.":
|
||||
"Items are permanently deleted after {days} days.",
|
||||
"Éléments supprimés récemment.": "Recently deleted items.",
|
||||
"Corbeille vide": "Trash is empty",
|
||||
"Aucun élément supprimé pour le moment.": "No items deleted yet.",
|
||||
"Dossiers supprimés": "Deleted folders",
|
||||
"Fichiers supprimés": "Deleted files",
|
||||
"Supprimé le {date}": "Deleted on {date}",
|
||||
"Restaurer {name}": "Restore {name}",
|
||||
"Supprimer définitivement {name}": "Permanently delete {name}",
|
||||
|
||||
"Profil, photo, adresse e-mail et sessions ouvertes.":
|
||||
"Profile, photo, email address and open sessions.",
|
||||
"Identité": "Identity",
|
||||
"Informations affichées dans l'interface.": "Information shown in the interface.",
|
||||
"Prénom": "First name",
|
||||
"Informations enregistrées.": "Information saved.",
|
||||
"Photo de profil": "Profile photo",
|
||||
"Image carrée, format PNG ou JPEG.": "Square image, PNG or JPEG.",
|
||||
"Choisir une image": "Choose an image",
|
||||
"Retirer": "Remove",
|
||||
"Si aucune image n'est définie, vos initiales sont affichées.":
|
||||
"If no image is set, your initials are shown.",
|
||||
"Adresse actuelle : {email}": "Current address: {email}",
|
||||
"Nouvelle adresse": "New address",
|
||||
"Un e-mail de confirmation a été envoyé à la nouvelle adresse.":
|
||||
"A confirmation email has been sent to the new address.",
|
||||
"Demander le changement": "Request change",
|
||||
"Sessions ouvertes": "Open sessions",
|
||||
"Appareils actuellement connectés à votre compte.":
|
||||
"Devices currently connected to your account.",
|
||||
"Aucune session active.": "No active session.",
|
||||
"Appareil inconnu": "Unknown device",
|
||||
"Cette session": "This session",
|
||||
"IP inconnue": "Unknown IP",
|
||||
"vue le {date}": "seen on {date}",
|
||||
"Fermer cette session": "Close this session",
|
||||
"Fermer les autres sessions": "Close other sessions",
|
||||
"Fermer la session": "Close session",
|
||||
"Fermer la session en cours vous déconnectera immédiatement.":
|
||||
"Closing the current session will sign you out immediately.",
|
||||
|
||||
"Préférences": "Preferences",
|
||||
"Apparence et langue de l'interface.": "Interface appearance and language.",
|
||||
"Thème": "Theme",
|
||||
"Système": "System",
|
||||
"Clair": "Light",
|
||||
"Sombre": "Dark",
|
||||
"Langue": "Language",
|
||||
"Préférences enregistrées.": "Preferences saved.",
|
||||
|
||||
"Créer des membres, ajustez leurs quotas et gérez les accès.":
|
||||
"Create members, adjust their quotas and manage access.",
|
||||
"Nouveau membre": "New member",
|
||||
"nom ou e-mail": "name or email",
|
||||
"Aucun membre": "No members",
|
||||
"Inactif": "Inactive",
|
||||
"À changer": "To change",
|
||||
"vu le {date}": "seen on {date}",
|
||||
"jamais connecté": "never signed in",
|
||||
"Modifier": "Edit",
|
||||
"Désactiver": "Deactivate",
|
||||
"Réactiver": "Reactivate",
|
||||
"Réinitialiser le mot de passe": "Reset password",
|
||||
"Mot de passe réinitialisé. Les identifiants ont été envoyés à {email}.":
|
||||
"Password reset. Credentials have been sent to {email}.",
|
||||
"Supprimer le membre": "Delete member",
|
||||
"Supprimer définitivement {email} ainsi que ses fichiers ? Cette action est irréversible.":
|
||||
"Permanently delete {email} and their files? This action cannot be undone.",
|
||||
"Compte créé. Les identifiants ont été envoyés à {email}.":
|
||||
"Account created. Credentials have been sent to {email}.",
|
||||
"Rôle": "Role",
|
||||
"Utilisateur": "User",
|
||||
"Administrateur": "Administrator",
|
||||
"Quota (Go, optionnel)": "Quota (GB, optional)",
|
||||
"Fichier max (Mo)": "Max file (MB)",
|
||||
"Modifier le membre": "Edit member",
|
||||
"Quota (Go)": "Quota (GB)",
|
||||
"Emplacements de stockage": "Storage locations",
|
||||
"Volumes montés utilisés pour stocker les fichiers.":
|
||||
"Mounted volumes used to store files.",
|
||||
"Nouvel emplacement": "New location",
|
||||
"Aucun emplacement": "No locations",
|
||||
"Go utilisés": "GB used",
|
||||
"Identifiant technique": "Technical identifier",
|
||||
"Chemin de montage": "Mount path",
|
||||
"Journal d'activité": "Activity log",
|
||||
"Dernières actions enregistrées.": "Latest recorded actions.",
|
||||
"Filtrer par action": "Filter by action",
|
||||
"Aucune entrée": "No entries",
|
||||
"système": "system",
|
||||
"{value} Go": "{value} GB",
|
||||
"{used} / {quota} Go": "{used} / {quota} GB",
|
||||
"{used} Go utilisés": "{used} GB used",
|
||||
};
|
||||
|
||||
export type Translate = (source: string, vars?: Record<string, string | number>) => string;
|
||||
|
||||
export const translate = (
|
||||
language: Language,
|
||||
source: string,
|
||||
vars?: Record<string, string | number>,
|
||||
): string => {
|
||||
const template = language === "en" ? en[source] ?? source : source;
|
||||
if (!vars) return template;
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) =>
|
||||
vars[key] !== undefined ? String(vars[key]) : match,
|
||||
);
|
||||
};
|
||||
|
||||
interface I18nValue {
|
||||
lang: Language;
|
||||
t: Translate;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nValue | null>(null);
|
||||
|
||||
export const I18nProvider = ({
|
||||
language,
|
||||
children,
|
||||
}: {
|
||||
language: Language;
|
||||
children: ReactNode;
|
||||
}) => {
|
||||
setLanguage(language);
|
||||
|
||||
const t = useCallback<Translate>(
|
||||
(source, vars) => translate(language, source, vars),
|
||||
[language],
|
||||
);
|
||||
|
||||
const value = useMemo<I18nValue>(() => ({ lang: language, t }), [language, t]);
|
||||
|
||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||
};
|
||||
|
||||
export const useI18n = (): I18nValue => {
|
||||
const value = useContext(I18nContext);
|
||||
if (!value) throw new Error("useI18n doit etre utilise dans un I18nProvider.");
|
||||
return value;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Language } from "./api";
|
||||
import type { Language } from "../types/index.js";
|
||||
|
||||
let language: Language = "fr";
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { api, type User } from "./api.js";
|
||||
|
||||
interface SessionValue {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
setUser: (user: User | null) => void;
|
||||
logout: () => Promise<void>;
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionValue | null>(null);
|
||||
|
||||
export const SessionProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const { user: current } = await api.me();
|
||||
setUser(current);
|
||||
} catch {
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api.logout().catch(() => undefined);
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<SessionValue>(
|
||||
() => ({ user, loading, refresh, setUser, logout }),
|
||||
[user, loading, refresh, logout],
|
||||
);
|
||||
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
};
|
||||
|
||||
export const useSession = (): SessionValue => {
|
||||
const value = useContext(SessionContext);
|
||||
if (!value) throw new Error("useSession doit etre utilise dans un SessionProvider.");
|
||||
return value;
|
||||
};
|
||||
@@ -1,32 +0,0 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import type { Theme } from "./api.js";
|
||||
|
||||
const STORAGE_KEY = "cohaise-theme";
|
||||
|
||||
const prefersDark = (): boolean =>
|
||||
typeof window !== "undefined" &&
|
||||
window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
|
||||
const isDark = (theme: Theme): boolean =>
|
||||
theme === "dark" || (theme === "system" && prefersDark());
|
||||
|
||||
export const ThemeProvider = ({ theme, children }: { theme: Theme; children: ReactNode }) => {
|
||||
useEffect(() => {
|
||||
const apply = () => {
|
||||
document.documentElement.classList.toggle("dark", isDark(theme));
|
||||
};
|
||||
apply();
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
} catch {
|
||||
}
|
||||
|
||||
if (theme !== "system") return undefined;
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = () => apply();
|
||||
media.addEventListener("change", onChange);
|
||||
return () => media.removeEventListener("change", onChange);
|
||||
}, [theme]);
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
Reference in New Issue
Block a user