feat: implement shared-album multi-user photo album
Backend (Go/Gin/pgx): env config, pgx pool with retries, Garage S3 client (path-style, region garage), embedded golang-migrate migrations, JWT auth with refresh rotation, albums CRUD, members/roles/invites with no-escalation matrix, photo upload + async imaging/goexif WebP variants, cursor pagination, presigned URLs, likes/comments, SSE hub (album + personal), notifications, share links. Frontend (SvelteKit 2 + Svelte 5 + Tailwind v4): API wrapper with 401 refresh, auth store, all screens, Uploader/PhotoGrid/Lightbox/Comments, SSE client with reconnect + REST catch-up, three themes + system via data-theme. Deploy without Docker: Makefile builds the frontend into backend/static and embeds it (go:embed) into a single statically linked binary; systemd unit and nginx SSE example included. Use gen2brain/webp (-tags nodynamic) instead of cgo kolesa-team/go-webp to keep CGO_ENABLED=0 static builds; design.md/proposal.md updated accordingly.
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
@import 'tailwindcss';
|
||||
@config '../tailwind.config.ts';
|
||||
|
||||
/* Светлая */
|
||||
:root,
|
||||
[data-theme='light'] {
|
||||
--bg: 0 0% 100%;
|
||||
--bg-elevated: 0 0% 98%;
|
||||
--bg-muted: 0 0% 95%;
|
||||
--border: 0 0% 88%;
|
||||
--text: 0 0% 9%;
|
||||
--text-muted: 0 0% 45%;
|
||||
--text-subtle: 0 0% 60%;
|
||||
--primary: 221 83% 53%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 84% 60%;
|
||||
--success: 142 71% 45%;
|
||||
--shadow: 0 0% 0% / 0.08;
|
||||
}
|
||||
|
||||
/* Тёмная */
|
||||
[data-theme='dark'] {
|
||||
--bg: 0 0% 7%;
|
||||
--bg-elevated: 0 0% 11%;
|
||||
--bg-muted: 0 0% 16%;
|
||||
--border: 0 0% 22%;
|
||||
--text: 0 0% 96%;
|
||||
--text-muted: 0 0% 65%;
|
||||
--text-subtle: 0 0% 45%;
|
||||
--primary: 217 91% 60%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 84% 65%;
|
||||
--success: 142 65% 50%;
|
||||
--shadow: 0 0% 0% / 0.4;
|
||||
}
|
||||
|
||||
/* Нейтральная (тёплая серо-бежевая) */
|
||||
[data-theme='neutral'] {
|
||||
--bg: 40 20% 96%;
|
||||
--bg-elevated: 40 22% 92%;
|
||||
--bg-muted: 40 18% 87%;
|
||||
--border: 40 14% 78%;
|
||||
--text: 30 10% 15%;
|
||||
--text-muted: 30 8% 40%;
|
||||
--text-subtle: 30 6% 55%;
|
||||
--primary: 25 90% 50%;
|
||||
--primary-fg: 0 0% 100%;
|
||||
--danger: 0 72% 55%;
|
||||
--success: 142 55% 42%;
|
||||
--shadow: 30 20% 20% / 0.12;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: hsl(var(--bg));
|
||||
color: hsl(var(--text));
|
||||
transition:
|
||||
background-color 200ms ease,
|
||||
color 200ms ease;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html,
|
||||
body {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!doctype html>
|
||||
<html lang="ru" data-theme="light">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
var stored = localStorage.getItem('theme') || 'system';
|
||||
var resolved = stored;
|
||||
if (stored === 'system') {
|
||||
resolved = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
}
|
||||
document.documentElement.setAttribute('data-theme', resolved);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,101 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { auth, type Tokens, type User } from './stores/auth.svelte';
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code: string;
|
||||
constructor(status: number, code: string, message: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
form?: FormData;
|
||||
}
|
||||
|
||||
let refreshing: Promise<boolean> | null = null;
|
||||
|
||||
async function raw(path: string, opts: RequestOptions): Promise<Response> {
|
||||
const headers = new Headers();
|
||||
if (auth.access) headers.set('Authorization', `Bearer ${auth.access}`);
|
||||
let body: BodyInit | undefined;
|
||||
if (opts.form) {
|
||||
body = opts.form;
|
||||
} else if (opts.body !== undefined) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
body = JSON.stringify(opts.body);
|
||||
}
|
||||
return fetch(`/api${path}`, { method: opts.method ?? 'GET', headers, body });
|
||||
}
|
||||
|
||||
async function doRefresh(): Promise<boolean> {
|
||||
if (!auth.refresh) return false;
|
||||
try {
|
||||
const res = await fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: auth.refresh })
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json();
|
||||
auth.setTokens(data.tokens as Tokens);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, opts: RequestOptions = {}): Promise<T> {
|
||||
let res = await raw(path, opts);
|
||||
if (res.status === 401 && auth.refresh) {
|
||||
if (!refreshing) {
|
||||
refreshing = doRefresh().finally(() => {
|
||||
refreshing = null;
|
||||
});
|
||||
}
|
||||
const ok = await refreshing;
|
||||
if (ok) res = await raw(path, opts);
|
||||
}
|
||||
if (!res.ok) {
|
||||
let code = 'error';
|
||||
let message = res.statusText;
|
||||
try {
|
||||
const body = await res.json();
|
||||
if (body?.error) {
|
||||
code = body.error.code ?? code;
|
||||
message = body.error.message ?? message;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (res.status === 401) {
|
||||
auth.clear();
|
||||
goto('/login');
|
||||
}
|
||||
throw new ApiError(res.status, code, message);
|
||||
}
|
||||
if (res.status === 204) return null as T;
|
||||
const ct = res.headers.get('content-type') ?? '';
|
||||
if (ct.includes('application/json')) return (await res.json()) as T;
|
||||
return (await res.text()) as unknown as T;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
register: (email: string, password: string, name: string) =>
|
||||
api<{ user: User; tokens: Tokens }>('/auth/register', {
|
||||
method: 'POST',
|
||||
body: { email, password, name }
|
||||
}),
|
||||
login: (email: string, password: string) =>
|
||||
api<{ user: User; tokens: Tokens }>('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { email, password }
|
||||
}),
|
||||
logout: (refresh_token: string) =>
|
||||
api('/auth/logout', { method: 'POST', body: { refresh_token } }),
|
||||
me: () => api<{ user: User }>('/auth/me')
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Comment } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
photoId: string;
|
||||
}
|
||||
|
||||
let { photoId }: Props = $props();
|
||||
|
||||
let comments = $state<Comment[]>([]);
|
||||
let text = $state('');
|
||||
let error = $state('');
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await api<{ comments: Comment[] }>(`/photos/${photoId}/comments`);
|
||||
comments = data.comments;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
photoId;
|
||||
load();
|
||||
});
|
||||
|
||||
async function submit(ev: Event) {
|
||||
ev.preventDefault();
|
||||
if (!text.trim()) return;
|
||||
try {
|
||||
const data = await api<{ comment: Comment }>(`/photos/${photoId}/comments`, {
|
||||
method: 'POST',
|
||||
body: { text }
|
||||
});
|
||||
comments = [...comments, data.comment];
|
||||
text = '';
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: string) {
|
||||
try {
|
||||
await api(`/comments/${id}`, { method: 'DELETE' });
|
||||
comments = comments.filter((c) => c.id !== id);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mt-2">
|
||||
{#each comments as comment (comment.id)}
|
||||
<div class="border-border mb-1 flex items-start justify-between gap-2 border-b py-1 text-sm">
|
||||
<span class="text-text">
|
||||
<strong>{comment.user.name}</strong>: {comment.text}
|
||||
</span>
|
||||
{#if auth.user?.id === comment.user_id}
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-subtle hover:text-danger text-xs"
|
||||
onclick={() => remove(comment.id)}>удалить</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
{#if auth.isAuthenticated}
|
||||
<form class="mt-2 flex gap-2" onsubmit={submit}>
|
||||
<input
|
||||
bind:value={text}
|
||||
placeholder="Комментарий…"
|
||||
class="border-border bg-bg text-text flex-1 rounded-lg border px-3 py-1.5 text-sm"
|
||||
/>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-3 py-1.5 text-sm" type="submit"
|
||||
>Отправить</button
|
||||
>
|
||||
</form>
|
||||
{/if}
|
||||
{#if error}
|
||||
<p class="text-danger mt-1 text-xs">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,110 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import type { Photo } from '$lib/types';
|
||||
import Comments from './Comments.svelte';
|
||||
|
||||
interface Props {
|
||||
photos: Photo[];
|
||||
index: number;
|
||||
onClose: () => void;
|
||||
onIndexChange: (index: number) => void;
|
||||
}
|
||||
|
||||
let { photos, index, onClose, onIndexChange }: Props = $props();
|
||||
|
||||
let fresh = $state<Photo | null>(null);
|
||||
let touchX = 0;
|
||||
|
||||
const current = $derived(photos[index]);
|
||||
|
||||
$effect(() => {
|
||||
const id = current?.id;
|
||||
fresh = null;
|
||||
if (!id) return;
|
||||
api<{ photo: Photo }>(`/photos/${id}`)
|
||||
.then((data) => (fresh = data.photo))
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
function prev() {
|
||||
if (index > 0) onIndexChange(index - 1);
|
||||
}
|
||||
function next() {
|
||||
if (index < photos.length - 1) onIndexChange(index + 1);
|
||||
}
|
||||
|
||||
function onKey(ev: KeyboardEvent) {
|
||||
if (ev.key === 'Escape') onClose();
|
||||
if (ev.key === 'ArrowLeft') prev();
|
||||
if (ev.key === 'ArrowRight') next();
|
||||
}
|
||||
|
||||
function onTouchStart(ev: TouchEvent) {
|
||||
touchX = ev.changedTouches[0].clientX;
|
||||
}
|
||||
function onTouchEnd(ev: TouchEvent) {
|
||||
const dx = ev.changedTouches[0].clientX - touchX;
|
||||
if (dx > 50) prev();
|
||||
else if (dx < -50) next();
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKey} />
|
||||
|
||||
<div
|
||||
class="bg-bg/95 fixed inset-0 z-50 flex flex-col"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
ontouchstart={onTouchStart}
|
||||
ontouchend={onTouchEnd}
|
||||
>
|
||||
<div class="flex items-center justify-between p-3">
|
||||
<span class="text-text-muted text-sm">{index + 1} / {photos.length}</span>
|
||||
<div class="flex gap-2">
|
||||
{#if fresh?.download_url}
|
||||
<a
|
||||
href={fresh.download_url}
|
||||
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm"
|
||||
target="_blank"
|
||||
rel="noreferrer">Скачать</a
|
||||
>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={onClose}
|
||||
class="border-border text-text rounded-lg border px-3 py-1.5 text-sm">✕</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 items-center justify-center overflow-hidden px-2 pb-2">
|
||||
<button type="button" class="text-text-muted px-2 text-3xl" onclick={prev} disabled={index === 0}
|
||||
>‹</button
|
||||
>
|
||||
{#if current}
|
||||
<img
|
||||
src={fresh?.preview_url ?? fresh?.original_url ?? current.preview_url ?? current.original_url}
|
||||
alt={current.original_filename}
|
||||
class="max-h-[75vh] max-w-full rounded-lg object-contain"
|
||||
/>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-muted px-2 text-3xl"
|
||||
onclick={next}
|
||||
disabled={index === photos.length - 1}>›</button
|
||||
>
|
||||
</div>
|
||||
|
||||
{#if current}
|
||||
<div class="border-border bg-bg-elevated max-h-56 overflow-y-auto border-t p-3">
|
||||
<p class="text-text text-sm">
|
||||
{current.uploader.name} · {current.original_filename}
|
||||
</p>
|
||||
<Comments photoId={current.id} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,45 @@
|
||||
<script lang="ts">
|
||||
import type { Photo } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
photos: Photo[];
|
||||
onOpen?: (index: number) => void;
|
||||
}
|
||||
|
||||
let { photos, onOpen }: Props = $props();
|
||||
</script>
|
||||
|
||||
{#if photos.length === 0}
|
||||
<p class="text-text-muted p-8 text-center">Пока нет фотографий.</p>
|
||||
{:else}
|
||||
<ul class="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
||||
{#each photos as photo, i (photo.id)}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
class="border-border bg-bg-muted group relative block aspect-square w-full overflow-hidden rounded-lg border"
|
||||
onclick={() => onOpen?.(i)}
|
||||
>
|
||||
{#if photo.thumb_url}
|
||||
<img
|
||||
src={photo.thumb_url}
|
||||
alt={photo.original_filename}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
class="h-full w-full object-cover transition-transform duration-200 group-hover:scale-105"
|
||||
/>
|
||||
{:else}
|
||||
<span class="text-text-subtle flex h-full w-full items-center justify-center text-xs">
|
||||
обработка…
|
||||
</span>
|
||||
{/if}
|
||||
<span
|
||||
class="bg-bg/70 text-text absolute right-1 bottom-1 rounded px-1.5 py-0.5 text-xs"
|
||||
>
|
||||
♥ {photo.likes_count} · 💬 {photo.comments_count}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
@@ -0,0 +1,27 @@
|
||||
<script lang="ts">
|
||||
import { theme, type Theme } from '$lib/stores/theme.svelte';
|
||||
|
||||
const options: { value: Theme; label: string; icon: string }[] = [
|
||||
{ value: 'light', label: 'Light', icon: '☀️' },
|
||||
{ value: 'dark', label: 'Dark', icon: '🌙' },
|
||||
{ value: 'neutral', label: 'Neutral', icon: '🌾' },
|
||||
{ value: 'system', label: 'System', icon: '💻' }
|
||||
];
|
||||
</script>
|
||||
|
||||
<div class="border-border bg-bg-elevated inline-flex gap-1 rounded-lg border p-1" role="group" aria-label="Theme">
|
||||
{#each options as option (option.value)}
|
||||
<button
|
||||
type="button"
|
||||
title={option.label}
|
||||
aria-label={option.label}
|
||||
aria-pressed={theme.current === option.value}
|
||||
onclick={() => theme.set(option.value)}
|
||||
class="rounded-md px-2 py-1 text-sm transition-colors {theme.current === option.value
|
||||
? 'bg-primary text-primary-fg'
|
||||
: 'text-text-muted hover:bg-bg-muted'}"
|
||||
>
|
||||
{option.icon}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
@@ -0,0 +1,117 @@
|
||||
<script lang="ts">
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Photo } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
albumId: string;
|
||||
onUploaded?: (photos: Photo[]) => void;
|
||||
}
|
||||
|
||||
let { albumId, onUploaded }: Props = $props();
|
||||
|
||||
let dragging = $state(false);
|
||||
let progress = $state(0);
|
||||
let busy = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
function pick() {
|
||||
fileInput?.click();
|
||||
}
|
||||
|
||||
let fileInput: HTMLInputElement | undefined = $state();
|
||||
|
||||
function onDrop(ev: DragEvent) {
|
||||
ev.preventDefault();
|
||||
dragging = false;
|
||||
if (ev.dataTransfer?.files?.length) {
|
||||
upload(ev.dataTransfer.files);
|
||||
}
|
||||
}
|
||||
|
||||
function onChange(ev: Event) {
|
||||
const target = ev.target as HTMLInputElement;
|
||||
if (target.files?.length) upload(target.files);
|
||||
target.value = '';
|
||||
}
|
||||
|
||||
function upload(files: FileList) {
|
||||
error = '';
|
||||
busy = true;
|
||||
progress = 0;
|
||||
const form = new FormData();
|
||||
for (const file of Array.from(files)) {
|
||||
form.append('files', file);
|
||||
}
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', `/api/albums/${albumId}/photos`);
|
||||
if (auth.access) xhr.setRequestHeader('Authorization', `Bearer ${auth.access}`);
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) progress = Math.round((e.loaded / e.total) * 100);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
busy = false;
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
onUploaded?.(data.photos ?? []);
|
||||
} catch {
|
||||
onUploaded?.([]);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
error = JSON.parse(xhr.responseText)?.error?.message ?? 'Ошибка загрузки';
|
||||
} catch {
|
||||
error = 'Ошибка загрузки';
|
||||
}
|
||||
}
|
||||
};
|
||||
xhr.onerror = () => {
|
||||
busy = false;
|
||||
error = 'Сетевая ошибка';
|
||||
};
|
||||
xhr.send(form);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="border-border rounded-xl border-2 border-dashed p-6 text-center transition-colors {dragging
|
||||
? 'bg-bg-muted border-primary'
|
||||
: 'bg-bg-elevated'}"
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
dragging = true;
|
||||
}}
|
||||
ondragleave={() => (dragging = false)}
|
||||
ondrop={onDrop}
|
||||
ondragenter={(e) => e.preventDefault()}
|
||||
role="region"
|
||||
aria-label="Загрузка фотографий"
|
||||
>
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
class="hidden"
|
||||
onchange={onChange}
|
||||
/>
|
||||
<p class="text-text mb-3 text-sm">Перетащите фото сюда или</p>
|
||||
<button
|
||||
type="button"
|
||||
onclick={pick}
|
||||
disabled={busy}
|
||||
class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{busy ? 'Загрузка…' : 'Выбрать файлы'}
|
||||
</button>
|
||||
|
||||
{#if busy}
|
||||
<div class="bg-bg-muted mt-4 h-2 w-full overflow-hidden rounded">
|
||||
<div class="bg-primary h-full transition-all" style="width: {progress}%"></div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if error}
|
||||
<p class="text-danger mt-3 text-sm">{error}</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,77 @@
|
||||
export interface SSEEvent {
|
||||
type: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface SSEClientOptions {
|
||||
path: string;
|
||||
onEvent: (event: SSEEvent) => void;
|
||||
onReconnect?: () => void;
|
||||
}
|
||||
|
||||
// Wrapper над EventSource с экспоненциальным backoff и догоном через REST.
|
||||
export class SSEClient {
|
||||
private es: EventSource | null = null;
|
||||
private stopped = false;
|
||||
private attempt = 0;
|
||||
private readonly knownEvents = [
|
||||
'photo.created',
|
||||
'photo.deleted',
|
||||
'comment.created',
|
||||
'like.added',
|
||||
'like.removed',
|
||||
'member.joined',
|
||||
'member.left',
|
||||
'member.updated',
|
||||
'album.updated',
|
||||
'album.deleted',
|
||||
'notification'
|
||||
];
|
||||
|
||||
constructor(private opts: SSEClientOptions) {}
|
||||
|
||||
connect(token: string) {
|
||||
this.stopped = false;
|
||||
this.open(token);
|
||||
}
|
||||
|
||||
private open(token: string) {
|
||||
if (this.stopped) return;
|
||||
const url = `${this.opts.path}?token=${encodeURIComponent(token)}`;
|
||||
this.es = new EventSource(url);
|
||||
|
||||
this.es.onopen = () => {
|
||||
if (this.attempt > 0) {
|
||||
this.opts.onReconnect?.();
|
||||
}
|
||||
this.attempt = 0;
|
||||
};
|
||||
|
||||
for (const name of this.knownEvents) {
|
||||
this.es.addEventListener(name, (ev) => {
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = JSON.parse((ev as MessageEvent).data);
|
||||
} catch {
|
||||
data = (ev as MessageEvent).data;
|
||||
}
|
||||
this.opts.onEvent({ type: name, data });
|
||||
});
|
||||
}
|
||||
|
||||
this.es.onerror = () => {
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
if (this.stopped) return;
|
||||
const delay = Math.min(1000 * 2 ** this.attempt, 30000);
|
||||
this.attempt += 1;
|
||||
setTimeout(() => this.open(token), delay);
|
||||
};
|
||||
}
|
||||
|
||||
close() {
|
||||
this.stopped = true;
|
||||
this.es?.close();
|
||||
this.es = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
export interface Tokens {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
const ACCESS_KEY = 'galo.access';
|
||||
const REFRESH_KEY = 'galo.refresh';
|
||||
const USER_KEY = 'galo.user';
|
||||
|
||||
class AuthStore {
|
||||
access = $state<string | null>(null);
|
||||
refresh = $state<string | null>(null);
|
||||
user = $state<User | null>(null);
|
||||
|
||||
constructor() {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
this.access = localStorage.getItem(ACCESS_KEY);
|
||||
this.refresh = localStorage.getItem(REFRESH_KEY);
|
||||
const raw = localStorage.getItem(USER_KEY);
|
||||
if (raw) {
|
||||
try {
|
||||
this.user = JSON.parse(raw);
|
||||
} catch {
|
||||
this.user = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get isAuthenticated(): boolean {
|
||||
return !!this.access;
|
||||
}
|
||||
|
||||
setTokens(tokens: Tokens) {
|
||||
this.access = tokens.access_token;
|
||||
this.refresh = tokens.refresh_token;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(ACCESS_KEY, tokens.access_token);
|
||||
localStorage.setItem(REFRESH_KEY, tokens.refresh_token);
|
||||
}
|
||||
}
|
||||
|
||||
setUser(user: User) {
|
||||
this.user = user;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user));
|
||||
}
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.access = null;
|
||||
this.refresh = null;
|
||||
this.user = null;
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const auth = new AuthStore();
|
||||
@@ -0,0 +1,44 @@
|
||||
export type Theme = 'light' | 'dark' | 'neutral' | 'system';
|
||||
type Resolved = 'light' | 'dark' | 'neutral';
|
||||
|
||||
const KEY = 'theme';
|
||||
|
||||
function resolve(theme: Theme): Resolved {
|
||||
if (theme === 'system') {
|
||||
if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
return 'dark';
|
||||
}
|
||||
return 'light';
|
||||
}
|
||||
return theme;
|
||||
}
|
||||
|
||||
class ThemeStore {
|
||||
current = $state<Theme>('system');
|
||||
resolved = $state<Resolved>('light');
|
||||
private media: MediaQueryList | null = null;
|
||||
|
||||
init() {
|
||||
if (typeof window === 'undefined') return;
|
||||
const stored = (localStorage.getItem(KEY) as Theme | null) ?? 'system';
|
||||
this.current = stored;
|
||||
this.apply();
|
||||
this.media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
this.media.addEventListener('change', () => {
|
||||
if (this.current === 'system') this.apply();
|
||||
});
|
||||
}
|
||||
|
||||
set(theme: Theme) {
|
||||
this.current = theme;
|
||||
localStorage.setItem(KEY, theme);
|
||||
this.apply();
|
||||
}
|
||||
|
||||
private apply() {
|
||||
this.resolved = resolve(this.current);
|
||||
document.documentElement.setAttribute('data-theme', this.resolved);
|
||||
}
|
||||
}
|
||||
|
||||
export const theme = new ThemeStore();
|
||||
@@ -0,0 +1,88 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email?: string;
|
||||
name: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
export interface Album {
|
||||
id: string;
|
||||
owner_id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
cover_photo_id?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AlbumMember {
|
||||
album_id: string;
|
||||
user_id: string;
|
||||
role: string;
|
||||
joined_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface Photo {
|
||||
id: string;
|
||||
album_id: string;
|
||||
uploader_id: string;
|
||||
original_filename: string;
|
||||
size: number;
|
||||
width: number;
|
||||
height: number;
|
||||
mime_type: string;
|
||||
taken_at?: string | null;
|
||||
latitude?: number | null;
|
||||
longitude?: number | null;
|
||||
caption: string;
|
||||
created_at: string;
|
||||
uploader: User;
|
||||
likes_count: number;
|
||||
comments_count: number;
|
||||
liked_by_me: boolean;
|
||||
thumb_url?: string;
|
||||
preview_url?: string;
|
||||
original_url?: string;
|
||||
download_url?: string;
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: string;
|
||||
photo_id: string;
|
||||
user_id: string;
|
||||
text: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface Invite {
|
||||
id: string;
|
||||
album_id: string;
|
||||
token: string;
|
||||
role: string;
|
||||
expires_at: string;
|
||||
max_uses: number;
|
||||
uses: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ShareLink {
|
||||
id: string;
|
||||
album_id: string;
|
||||
token: string;
|
||||
created_by: string;
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
revoked_at?: string | null;
|
||||
}
|
||||
|
||||
export interface Notification {
|
||||
id: string;
|
||||
user_id: string;
|
||||
type: string;
|
||||
payload: Record<string, unknown>;
|
||||
read_at?: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import '../app.css';
|
||||
import ThemeSwitcher from '$lib/components/ThemeSwitcher.svelte';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import { theme } from '$lib/stores/theme.svelte';
|
||||
import { authApi } from '$lib/api';
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
onMount(() => {
|
||||
theme.init();
|
||||
if (auth.isAuthenticated && !auth.user) {
|
||||
authApi
|
||||
.me()
|
||||
.then((data) => auth.setUser(data.user))
|
||||
.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
async function logout() {
|
||||
if (auth.refresh) {
|
||||
await authApi.logout(auth.refresh).catch(() => {});
|
||||
}
|
||||
auth.clear();
|
||||
goto('/login');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="bg-bg text-text min-h-screen">
|
||||
<header class="border-border bg-bg-elevated border-b">
|
||||
<div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-3">
|
||||
<a href="/" class="text-lg font-semibold">📷 Galo</a>
|
||||
<div class="flex items-center gap-3">
|
||||
{#if auth.isAuthenticated}
|
||||
<span class="text-text-muted hidden text-sm sm:inline">{auth.user?.name ?? ''}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-text-muted hover:text-text text-sm"
|
||||
onclick={logout}>Выйти</button
|
||||
>
|
||||
{:else}
|
||||
<a href="/login" class="text-text-muted hover:text-text text-sm">Войти</a>
|
||||
{/if}
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main class="mx-auto max-w-6xl px-4 py-6">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
@@ -0,0 +1,2 @@
|
||||
export const ssr = false;
|
||||
export const prerender = false;
|
||||
@@ -0,0 +1,91 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Album } from '$lib/types';
|
||||
|
||||
let albums = $state<Album[]>([]);
|
||||
let loading = $state(true);
|
||||
let title = $state('');
|
||||
let error = $state('');
|
||||
|
||||
async function load() {
|
||||
if (!auth.isAuthenticated) {
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await api<{ albums: Album[] }>('/albums');
|
||||
albums = data.albums;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function create(ev: Event) {
|
||||
ev.preventDefault();
|
||||
if (!title.trim()) return;
|
||||
try {
|
||||
const data = await api<{ album: Album }>('/albums', {
|
||||
method: 'POST',
|
||||
body: { title }
|
||||
});
|
||||
albums = [data.album, ...albums];
|
||||
title = '';
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !auth.isAuthenticated}
|
||||
<div class="py-16 text-center">
|
||||
<h1 class="mb-2 text-2xl font-bold">Общие фотоальбомы</h1>
|
||||
<p class="text-text-muted mb-6">Войдите, чтобы создавать альбомы и делиться фотографиями.</p>
|
||||
<a href="/login" class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium">Войти</a>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="mb-6 flex items-center justify-between gap-4">
|
||||
<h1 class="text-2xl font-bold">Мои альбомы</h1>
|
||||
<form class="flex gap-2" onsubmit={create}>
|
||||
<input
|
||||
bind:value={title}
|
||||
placeholder="Название альбома"
|
||||
class="border-border bg-bg-elevated text-text rounded-lg border px-3 py-2 text-sm"
|
||||
/>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать</button
|
||||
>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
{#if loading}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{:else if albums.length === 0}
|
||||
<p class="text-text-muted">Альбомов пока нет. Создайте первый.</p>
|
||||
{:else}
|
||||
<ul class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{#each albums as album (album.id)}
|
||||
<li>
|
||||
<a
|
||||
href="/albums/{album.id}"
|
||||
class="border-border bg-bg-elevated hover:border-primary block overflow-hidden rounded-xl border transition-colors"
|
||||
>
|
||||
<div class="bg-bg-muted flex aspect-video items-center justify-center text-4xl">🖼️</div>
|
||||
<div class="p-4">
|
||||
<h2 class="text-text font-semibold">{album.title}</h2>
|
||||
<p class="text-text-muted line-clamp-2 text-sm">{album.description}</p>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -0,0 +1,176 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import PhotoGrid from '$lib/components/PhotoGrid.svelte';
|
||||
import Lightbox from '$lib/components/Lightbox.svelte';
|
||||
import Uploader from '$lib/components/Uploader.svelte';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import { SSEClient, type SSEEvent } from '$lib/sse';
|
||||
import type { Album, Photo } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let role = $state('');
|
||||
let photos = $state<Photo[]>([]);
|
||||
let nextCursor = $state('');
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let lightboxIndex = $state(-1);
|
||||
|
||||
let canUpload = $derived(['owner', 'admin', 'editor', 'member'].includes(role));
|
||||
|
||||
async function loadAlbum() {
|
||||
const data = await api<{ album: Album; role: string }>(`/albums/${albumId}`);
|
||||
album = data.album;
|
||||
role = data.role;
|
||||
}
|
||||
|
||||
async function loadPhotos() {
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/albums/${albumId}/photos`
|
||||
);
|
||||
photos = data.photos;
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!nextCursor) return;
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/albums/${albumId}/photos?cursor=${encodeURIComponent(nextCursor)}`
|
||||
);
|
||||
photos = [...photos, ...data.photos];
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const id = albumId;
|
||||
loading = true;
|
||||
error = '';
|
||||
Promise.all([loadAlbum(), loadPhotos()])
|
||||
.catch((e) => (error = (e as Error).message))
|
||||
.finally(() => (loading = false));
|
||||
});
|
||||
|
||||
let client: SSEClient | null = null;
|
||||
|
||||
$effect(() => {
|
||||
const id = albumId;
|
||||
if (!auth.access) return;
|
||||
client = new SSEClient({
|
||||
path: `/api/sse/albums/${id}`,
|
||||
onEvent: handleEvent,
|
||||
onReconnect: () => loadPhotos()
|
||||
});
|
||||
client.connect(auth.access);
|
||||
return () => {
|
||||
client?.close();
|
||||
client = null;
|
||||
};
|
||||
});
|
||||
|
||||
function handleEvent(ev: SSEEvent) {
|
||||
const data = ev.data as Record<string, unknown>;
|
||||
switch (ev.type) {
|
||||
case 'photo.created': {
|
||||
const photo = data as unknown as Photo;
|
||||
if (photos.some((p) => p.id === photo.id)) {
|
||||
photos = photos.map((p) => (p.id === photo.id ? photo : p));
|
||||
} else {
|
||||
photos = [photo, ...photos];
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'photo.deleted': {
|
||||
photos = photos.filter((p) => p.id !== data.id);
|
||||
break;
|
||||
}
|
||||
case 'like.added': {
|
||||
photos = photos.map((p) =>
|
||||
p.id === data.photo_id
|
||||
? { ...p, likes_count: p.likes_count + 1, liked_by_me: data.user_id === auth.user?.id || p.liked_by_me }
|
||||
: p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'like.removed': {
|
||||
photos = photos.map((p) =>
|
||||
p.id === data.photo_id
|
||||
? { ...p, likes_count: Math.max(0, p.likes_count - 1), liked_by_me: false }
|
||||
: p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'comment.created': {
|
||||
const comment = data as unknown as { photo_id: string };
|
||||
photos = photos.map((p) =>
|
||||
p.id === comment.photo_id ? { ...p, comments_count: p.comments_count + 1 } : p
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'album.updated': {
|
||||
loadAlbum().catch(() => {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if loading}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{:else if error}
|
||||
<p class="text-danger">{error}</p>
|
||||
{:else if album}
|
||||
<div class="mb-6 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold">{album.title}</h1>
|
||||
<p class="text-text-muted">{album.description}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<a
|
||||
href="/albums/{albumId}/members"
|
||||
class="border-border text-text rounded-lg border px-3 py-2 text-sm">Участники</a
|
||||
>
|
||||
{#if role === 'owner' || role === 'admin'}
|
||||
<a
|
||||
href="/albums/{albumId}/settings"
|
||||
class="border-border text-text rounded-lg border px-3 py-2 text-sm">Настройки</a
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if canUpload}
|
||||
<div class="mb-6">
|
||||
<Uploader
|
||||
{albumId}
|
||||
onUploaded={(created) => {
|
||||
for (const p of created) {
|
||||
if (!photos.some((x) => x.id === p.id)) photos = [p, ...photos];
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<PhotoGrid {photos} onOpen={(i) => (lightboxIndex = i)} />
|
||||
|
||||
{#if nextCursor}
|
||||
<div class="mt-6 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="border-border text-text rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={loadMore}>Показать ещё</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if lightboxIndex >= 0}
|
||||
<Lightbox
|
||||
{photos}
|
||||
index={lightboxIndex}
|
||||
onClose={() => (lightboxIndex = -1)}
|
||||
onIndexChange={(i) => (lightboxIndex = i)}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
import type { Album, AlbumMember } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let members = $state<AlbumMember[]>([]);
|
||||
let role = $state('');
|
||||
let inviteRole = $state('member');
|
||||
let inviteUses = $state(1);
|
||||
let inviteExpires = $state('168h');
|
||||
let inviteUrl = $state('');
|
||||
let error = $state('');
|
||||
|
||||
const assignableRoles = $derived(
|
||||
role === 'owner'
|
||||
? ['admin', 'editor', 'member', 'viewer']
|
||||
: role === 'admin'
|
||||
? ['editor', 'member', 'viewer']
|
||||
: []
|
||||
);
|
||||
const inviteRoles = $derived(role === 'owner' ? ['admin', 'editor', 'member', 'viewer'] : ['member', 'viewer']);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [membersData, albumData] = await Promise.all([
|
||||
api<{ members: AlbumMember[] }>(`/albums/${albumId}/members`),
|
||||
api<{ album: Album; role: string }>(`/albums/${albumId}`)
|
||||
]);
|
||||
members = membersData.members;
|
||||
role = albumData.role;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function invite(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
try {
|
||||
const data = await api<{ invite: { token: string } }>(`/albums/${albumId}/invites`, {
|
||||
method: 'POST',
|
||||
body: { role: inviteRole, expires_in: inviteExpires, max_uses: inviteUses }
|
||||
});
|
||||
inviteUrl = `${location.origin}/invites/${data.invite.token}`;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function changeRole(userId: string, newRole: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/members/${userId}`, {
|
||||
method: 'PATCH',
|
||||
body: { role: newRole }
|
||||
});
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMember(userId: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/members/${userId}`, { method: 'DELETE' });
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mb-6 flex items-center justify-between">
|
||||
<h1 class="text-2xl font-bold">Участники</h1>
|
||||
<a href="/albums/{albumId}" class="text-primary text-sm">← К альбому</a>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
<ul class="mb-8 divide-y divide-border border-border rounded-xl border">
|
||||
<li class="bg-bg-muted flex items-center justify-between px-4 py-3">
|
||||
<span class="font-medium">Владелец</span>
|
||||
</li>
|
||||
{#each members as member (member.user_id)}
|
||||
<li class="flex items-center justify-between gap-4 px-4 py-3">
|
||||
<span class="text-text"
|
||||
>{member.user.name} <span class="text-text-muted text-sm">({member.user.email})</span></span
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
{#if assignableRoles.length > 0}
|
||||
<select
|
||||
value={member.role}
|
||||
onchange={(e) => changeRole(member.user_id, e.currentTarget.value)}
|
||||
class="border-border bg-bg-elevated text-text rounded-lg border px-2 py-1 text-sm"
|
||||
>
|
||||
{#each Array.from(new Set([member.role, ...assignableRoles])) as r}
|
||||
<option value={r}>{r}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
class="text-danger text-sm"
|
||||
onclick={() => removeMember(member.user_id)}>Удалить</button
|
||||
>
|
||||
{:else}
|
||||
<span class="text-text-muted text-sm">{member.role}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if assignableRoles.length > 0}
|
||||
<form class="border-border bg-bg-elevated space-y-3 rounded-xl border p-4" onsubmit={invite}>
|
||||
<h2 class="font-semibold">Пригласить</h2>
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Роль</span>
|
||||
<select
|
||||
bind:value={inviteRole}
|
||||
class="border-border bg-bg text-text rounded-lg border px-2 py-1.5"
|
||||
>
|
||||
{#each inviteRoles as r}
|
||||
<option value={r}>{r}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Использований</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
bind:value={inviteUses}
|
||||
class="border-border bg-bg text-text w-24 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Срок</span>
|
||||
<input
|
||||
bind:value={inviteExpires}
|
||||
class="border-border bg-bg text-text w-32 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать ссылку</button
|
||||
>
|
||||
{#if inviteUrl}
|
||||
<p class="text-text-muted break-all text-sm">Ссылка: <a class="text-primary" href={inviteUrl}>{inviteUrl}</a></p>
|
||||
{/if}
|
||||
</form>
|
||||
{/if}
|
||||
@@ -0,0 +1,143 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { api } from '$lib/api';
|
||||
import type { Album, ShareLink } from '$lib/types';
|
||||
|
||||
const albumId = $derived($page.params.id);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let shareLinks = $state<ShareLink[]>([]);
|
||||
let title = $state('');
|
||||
let description = $state('');
|
||||
let expiresIn = $state('168h');
|
||||
let error = $state('');
|
||||
let saved = $state(false);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [albumData, linksData] = await Promise.all([
|
||||
api<{ album: Album }>(`/albums/${albumId}`),
|
||||
api<{ share_links: ShareLink[] }>(`/albums/${albumId}/share`)
|
||||
]);
|
||||
album = albumData.album;
|
||||
title = album.title;
|
||||
description = album.description;
|
||||
shareLinks = linksData.share_links;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
load();
|
||||
});
|
||||
|
||||
async function save(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
saved = false;
|
||||
try {
|
||||
const data = await api<{ album: Album }>(`/albums/${albumId}`, {
|
||||
method: 'PATCH',
|
||||
body: { title, description }
|
||||
});
|
||||
album = data.album;
|
||||
saved = true;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function createLink(ev: Event) {
|
||||
ev.preventDefault();
|
||||
try {
|
||||
await api(`/albums/${albumId}/share`, { method: 'POST', body: { expires_in: expiresIn } });
|
||||
await load();
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(id: string) {
|
||||
try {
|
||||
await api(`/albums/${albumId}/share/${id}`, { method: 'DELETE' });
|
||||
shareLinks = shareLinks.filter((l) => l.id !== id);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAlbum() {
|
||||
if (!confirm('Удалить альбом вместе с фото?')) return;
|
||||
try {
|
||||
await api(`/albums/${albumId}`, { method: 'DELETE' });
|
||||
goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mb-6 flex items-center justify-between">
|
||||
<h1 class="text-2xl font-bold">Настройки</h1>
|
||||
<a href="/albums/{albumId}" class="text-primary text-sm">← К альбому</a>
|
||||
</div>
|
||||
|
||||
{#if error}<p class="text-danger mb-4 text-sm">{error}</p>{/if}
|
||||
|
||||
<form class="border-border bg-bg-elevated mb-6 space-y-3 rounded-xl border p-4" onsubmit={save}>
|
||||
<h2 class="font-semibold">Альбом</h2>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Название</span>
|
||||
<input
|
||||
bind:value={title}
|
||||
class="border-border bg-bg text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Описание</span>
|
||||
<textarea
|
||||
bind:value={description}
|
||||
rows="3"
|
||||
class="border-border bg-bg text-text w-full rounded-lg border px-3 py-2"
|
||||
></textarea>
|
||||
</label>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit">Сохранить</button>
|
||||
{#if saved}<span class="text-success ml-3 text-sm">Сохранено</span>{/if}
|
||||
</form>
|
||||
|
||||
<div class="border-border bg-bg-elevated mb-6 space-y-3 rounded-xl border p-4">
|
||||
<h2 class="font-semibold">Ссылки для просмотра</h2>
|
||||
<form class="flex items-end gap-2" onsubmit={createLink}>
|
||||
<label class="text-sm">
|
||||
<span class="text-text-muted mb-1 block">Срок действия</span>
|
||||
<input
|
||||
bind:value={expiresIn}
|
||||
class="border-border bg-bg text-text w-32 rounded-lg border px-2 py-1.5"
|
||||
/>
|
||||
</label>
|
||||
<button class="bg-primary text-primary-fg rounded-lg px-4 py-2 text-sm" type="submit"
|
||||
>Создать ссылку</button
|
||||
>
|
||||
</form>
|
||||
<ul class="divide-border divide-y">
|
||||
{#each shareLinks as link (link.id)}
|
||||
<li class="flex items-center justify-between gap-2 py-2 text-sm">
|
||||
<span class="text-text-muted truncate">
|
||||
{link.revoked_at ? 'отозвана' : 'до ' + new Date(link.expires_at).toLocaleString()}
|
||||
· <a class="text-primary" href="/share/{link.token}">/share/{link.token}</a>
|
||||
</span>
|
||||
{#if !link.revoked_at}
|
||||
<button type="button" class="text-danger" onclick={() => revoke(link.id)}>Отозвать</button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="border-danger text-danger rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={removeAlbum}>Удалить альбом</button
|
||||
>
|
||||
@@ -0,0 +1,57 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { api } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
|
||||
const token = $derived($page.params.token);
|
||||
|
||||
let info = $state<{ album_id: string; role: string; expires_at: string } | null>(null);
|
||||
let error = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
api<{ invite: typeof info }>(`/invites/${token}`)
|
||||
.then((data) => (info = data.invite))
|
||||
.catch((e) => (error = (e as Error).message));
|
||||
});
|
||||
|
||||
async function accept() {
|
||||
busy = true;
|
||||
error = '';
|
||||
try {
|
||||
const data = await api<{ album_id: string }>(`/invites/${token}/accept`, {
|
||||
method: 'POST'
|
||||
});
|
||||
goto(`/albums/${data.album_id}`);
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-md py-12 text-center">
|
||||
<h1 class="mb-4 text-2xl font-bold">Приглашение в альбом</h1>
|
||||
{#if error}
|
||||
<p class="text-danger">{error}</p>
|
||||
{:else if info}
|
||||
<p class="text-text-muted mb-6">Вас приглашают с ролью <strong>{info.role}</strong>.</p>
|
||||
{#if auth.isAuthenticated}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onclick={accept}
|
||||
class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium"
|
||||
>
|
||||
{busy ? 'Принятие…' : 'Принять приглашение'}
|
||||
</button>
|
||||
{:else}
|
||||
<p class="mb-4 text-sm">Войдите или зарегистрируйтесь, чтобы принять приглашение.</p>
|
||||
<a href="/login" class="bg-primary text-primary-fg rounded-lg px-5 py-2.5 font-medium">Войти</a>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { authApi } from '$lib/api';
|
||||
import { auth } from '$lib/stores/auth.svelte';
|
||||
|
||||
let mode = $state<'login' | 'register'>('login');
|
||||
let email = $state('');
|
||||
let password = $state('');
|
||||
let name = $state('');
|
||||
let error = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
async function submit(ev: Event) {
|
||||
ev.preventDefault();
|
||||
error = '';
|
||||
busy = true;
|
||||
try {
|
||||
const data =
|
||||
mode === 'login'
|
||||
? await authApi.login(email, password)
|
||||
: await authApi.register(email, password, name);
|
||||
auth.setTokens(data.tokens);
|
||||
auth.setUser(data.user);
|
||||
goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mx-auto max-w-sm py-10">
|
||||
<h1 class="mb-6 text-2xl font-bold">{mode === 'login' ? 'Вход' : 'Регистрация'}</h1>
|
||||
|
||||
<form class="space-y-4" onsubmit={submit}>
|
||||
{#if mode === 'register'}
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Имя</span>
|
||||
<input
|
||||
bind:value={name}
|
||||
required
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
{/if}
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Email</span>
|
||||
<input
|
||||
bind:value={email}
|
||||
type="email"
|
||||
required
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-text-muted mb-1 block text-sm">Пароль</span>
|
||||
<input
|
||||
bind:value={password}
|
||||
type="password"
|
||||
required
|
||||
minlength="8"
|
||||
class="border-border bg-bg-elevated text-text w-full rounded-lg border px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if error}<p class="text-danger text-sm">{error}</p>{/if}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
class="bg-primary text-primary-fg w-full rounded-lg px-4 py-2.5 font-medium disabled:opacity-50"
|
||||
>
|
||||
{busy ? 'Подождите…' : mode === 'login' ? 'Войти' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="text-primary mt-4 text-sm"
|
||||
onclick={() => (mode = mode === 'login' ? 'register' : 'login')}
|
||||
>
|
||||
{mode === 'login' ? 'Нет аккаунта? Зарегистрироваться' : 'Уже есть аккаунт? Войти'}
|
||||
</button>
|
||||
</div>
|
||||
@@ -0,0 +1,85 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { api } from '$lib/api';
|
||||
import PhotoGrid from '$lib/components/PhotoGrid.svelte';
|
||||
import type { Album, Photo } from '$lib/types';
|
||||
|
||||
const token = $derived($page.params.token);
|
||||
|
||||
let album = $state<Album | null>(null);
|
||||
let photos = $state<Photo[]>([]);
|
||||
let nextCursor = $state('');
|
||||
let error = $state('');
|
||||
let active = $state(-1);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [albumData, photosData] = await Promise.all([
|
||||
api<{ album: Album }>(`/share/${token}`),
|
||||
api<{ photos: Photo[]; next_cursor: string }>(`/share/${token}/photos`)
|
||||
]);
|
||||
album = albumData.album;
|
||||
photos = photosData.photos;
|
||||
nextCursor = photosData.next_cursor;
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!nextCursor) return;
|
||||
const data = await api<{ photos: Photo[]; next_cursor: string }>(
|
||||
`/share/${token}/photos?cursor=${encodeURIComponent(nextCursor)}`
|
||||
);
|
||||
photos = [...photos, ...data.photos];
|
||||
nextCursor = data.next_cursor;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
token;
|
||||
load();
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if error}
|
||||
<div class="py-16 text-center">
|
||||
<h1 class="mb-2 text-2xl font-bold">Доступ недоступен</h1>
|
||||
<p class="text-danger">{error}</p>
|
||||
</div>
|
||||
{:else if album}
|
||||
<h1 class="mb-2 text-2xl font-bold">{album.title}</h1>
|
||||
<p class="text-text-muted mb-6">Доступ только для просмотра · {album.description}</p>
|
||||
<PhotoGrid {photos} onOpen={(i) => (active = i)} />
|
||||
{#if nextCursor}
|
||||
<div class="mt-6 text-center">
|
||||
<button
|
||||
type="button"
|
||||
class="border-border text-text rounded-lg border px-4 py-2 text-sm"
|
||||
onclick={loadMore}>Показать ещё</button
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if active >= 0}
|
||||
<div
|
||||
class="bg-bg/95 fixed inset-0 z-50 flex items-center justify-center"
|
||||
role="dialog"
|
||||
onclick={() => (active = -1)}
|
||||
>
|
||||
<img
|
||||
src={photos[active].preview_url ?? photos[active].original_url}
|
||||
alt={photos[active].original_filename}
|
||||
class="max-h-[90vh] max-w-full object-contain"
|
||||
/>
|
||||
<a
|
||||
href={photos[active].download_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="border-border bg-bg-elevated text-text absolute top-4 right-4 rounded-lg border px-3 py-1.5 text-sm"
|
||||
onclick={(e) => e.stopPropagation()}>Скачать</a
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="text-text-muted">Загрузка…</p>
|
||||
{/if}
|
||||
Reference in New Issue
Block a user