Compare commits

..
Author SHA1 Message Date
codex a3c05c606a Keep legacy folder assignments and allow hiding from the author's folder 2026-11-18 21:01:24 +00:00
codex ebf8e3b5d4 Allow wishes in multiple folders and hide fulfilled wishes 2026-11-18 20:57:38 +00:00
codex aeedb6c753 Document the coordinated 0.4.0 production release 2026-11-18 05:16:48 +00:00
codex d0fe2906c7 Prevent destructive schema sync and document rollback 2026-11-17 20:47:52 +00:00
codex e9b2f76ee3 Add shared wish folders and family dashboard 2026-11-17 20:45:02 +00:00
admin 26cf978e3c Merge pull request 'chore: fix package versions' (#17) from chore/fix-package-versions into main
Reviewed-on: #17
2026-04-27 19:54:48 +00:00
Vaka.pro dbffefc26f chore: fix package versions 2026-04-27 22:54:06 +03:00
admin 5ab8ef3ba8 Merge pull request 'fix: move header nav to separate row' (#16) from fix/header-nav-separate-row into main
Reviewed-on: #16
2026-04-27 18:44:52 +00:00
Vaka.pro 235b40b326 fix: move header nav to separate row 2026-04-27 21:44:09 +03:00
admin 13b3b1a257 Merge pull request 'fix: prevent header wrapping and uploaded image 404s' (#15) from fix/header-actions-and-uploaded-images into main
Reviewed-on: #15
2026-04-27 18:31:07 +00:00
Vaka.pro fbf1d2d02f fix: prevent header wrapping and uploaded image 404s 2026-04-27 21:29:47 +03:00
admin 0ada42017f Merge pull request 'refactor(frontend): move repeated Tailwind chains into BEM classes' (#14) from refactor/frontend-bem-classes into main
Reviewed-on: #14
2026-04-27 17:49:30 +00:00
Vaka.pro 1bb0d0814c Merge remote-tracking branch 'origin/main' into refactor/frontend-bem-classes
# Conflicts:
#	apps/frontend/src/components/Layout/Header.tsx
#	apps/frontend/src/pages/PublicProfilePage.tsx
2026-04-27 20:47:08 +03:00
Vaka.pro d46d4c4487 refactor(frontend): move repeated Tailwind chains into BEM classes 2026-04-27 20:42:21 +03:00
admin 55736f2ea3 Merge pull request 'fix: improve friend wishlist navigation layout' (#13) from fix/friend-link-layout into main
Reviewed-on: #13
2026-04-26 20:46:07 +00:00
Vaka.pro 14a57b19b7 fix: improve friend wishlist navigation layout 2026-04-26 23:44:06 +03:00
admin 17d59c3639 Merge pull request 'feat: add friend wishlist link' (#12) from feature/friend-wishlist-link into main
Reviewed-on: #12
2026-04-26 20:30:23 +00:00
Vaka.pro 34179b3f30 feat: add friend wishlist link 2026-04-26 23:29:20 +03:00
admin f8fcda0d13 Merge pull request 'feat: add i18n and avatar upload' (#11) from feature/i18n-avatar-upload into main
Reviewed-on: #11
2026-04-26 19:18:14 +00:00
Vaka.pro 1b23097b18 feat: add i18n and avatar upload 2026-04-26 22:16:59 +03:00
admin db41d4a246 Merge pull request 'chore: update frontend port mapping' (#10) from chore/update-frontend-port into main
Reviewed-on: #10
2026-04-26 18:52:25 +00:00
Vaka.pro 547a452097 chore: update frontend port mapping 2026-04-26 21:50:55 +03:00
admin 3d7501f028 Merge pull request 'fix: build shared package for runtime' (#9) from fix/shared-runtime-build into main
Reviewed-on: #9
2026-04-26 18:42:52 +00:00
41 changed files with 1833 additions and 347 deletions

No files matched your search

+20 -4
View File
@@ -1,6 +1,6 @@
# Family Wishlist
A small, private wishlist app for two users. Each user has their own profile, slug, and independent wishlist. Guests see a public page at `/u/<slug>` and can view active and fulfilled wishes.
A small, private wishlist app for two users. The signed-in dashboard shows both users' active and fulfilled wishes, with filters for each author and shared folders. Each user also has a public profile at `/u/<slug>` with their own active and fulfilled wishes.
- **Backend**: Node.js 20, Fastify 4, Prisma 5, PostgreSQL 16
- **Frontend**: React 18, Vite 5, Tailwind CSS, TanStack Query, React Hook Form + Zod
@@ -12,6 +12,7 @@ A small, private wishlist app for two users. Each user has their own profile, sl
## Features
- Two fixed accounts (credentials in env), password stored only as a **bcrypt hash**.
- Either user can create a shared folder with an optional description and emoji or image cover. The author can select several shared folders and their own folder when creating or editing a wish. Active and fulfilled wishes always appear in All. The dashboard can hide fulfilled wishes across these views.
- Wish entity: title, price, currency, link, comment, image (auto-fetched from link or uploaded).
- Statuses: **Active → Archive / Fulfilled → Trash** (kept for 30 days, then permanently removed by a daily cron job).
- Restore from archive or trash. Duplicate from fulfilled into a new active wish.
@@ -59,7 +60,8 @@ utils/ errors, bcrypt helpers, version helper
See `apps/backend/prisma/schema.prisma`. Tables:
- `User` — `id`, `username`, `slug`, `displayName`, `bio`, `avatarUrl`. **No password hash.**
- `Wish` — `userId`, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `Wish` — `userId`, optional `folderId` and additional folder links, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `WishFolder` — shared folder metadata and its creator.
- `GuestView` — `(guestId, wishId)` pairs for "already seen" tracking.
### Password storage
@@ -156,6 +158,16 @@ On first start, the backend:
3. Starts Fastify on port 3000.
4. Registers the daily trash-purge cron (runs at 03:17 UTC, also once on startup).
### Production release
Follow the [controlled deployment runbook in infra-home](https://git.vakanaut.ru/admin/infra-home/src/branch/main/docs/runbooks/deployment.md). Build the frontend and backend images from the same merged revision and record both image digests. Release the pair together so the frontend can read and save multi-folder assignments.
Before upgrading an existing deployment, back up PostgreSQL and the uploads volume. Verify that the backup can be restored in an isolated environment. After deployment, check `/api/health`, `/api/version` and the signed-in dashboard. Confirm that an existing wish is still visible and a new wish in a shared folder also appears in the author's folder.
If a rollback is needed, restore the previous frontend and backend images together. Start a pre-0.5.0 backend with `node dist/src/index.js` (from `/app/apps/backend`) to preserve the new schema. Version 0.4.0 shows the first shared folder while it is running. Backend images older than 0.4.0 run `prisma db push --accept-data-loss` by default, which can remove the shared folder data.
### Development schema migrations
> For a stricter migration workflow, switch to `prisma migrate dev` locally to produce
> versioned migration files and change the Docker `CMD` to `prisma migrate deploy`.
@@ -203,6 +215,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
| GET | `/api/auth/me` | owner | Current user. |
| GET | `/api/profile` | owner | Own profile. |
| PATCH | `/api/profile` | owner | Update slug/displayName/bio/avatar. |
| GET | `/api/dashboard` | signed in | Shared folders, authors, and active and fulfilled wishes from both accounts. |
| POST | `/api/folders` | signed in | Create a shared folder. Multipart fields: `name`, optional `description`, and optional `emoji` or `cover` file. |
| GET | `/api/wishes?status=active\|archived\|completed\|deleted` | owner | List own wishes. |
| POST | `/api/wishes` | owner | Create. |
| GET | `/api/wishes/:id` | owner | Get own wish. |
@@ -220,6 +234,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
| POST | `/api/public/:slug/views` | — | Body `{ wishIds: [] }`. Marks as seen. |
| GET | `/api/health`, `/api/version` | — | Meta. |
For create and update, `folderIds` accepts the selected shared folder IDs. An empty array removes all shared assignments. When both folder ID keys are omitted from an update, assignments are preserved. Version 0.4.0 clients can still update the primary folder with `folderId`. `showInAuthorFolder` is true for existing wishes and by default for new wishes. The author can set it to false to hide the wish from their own folder.
---
## Versioning
@@ -227,7 +243,7 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
Each package has its own version (`apps/backend/package.json` and `apps/frontend/package.json`). The app footer shows both:
```
frontend v0.1.0 · backend v0.1.0
frontend v0.5.0 · backend v0.5.0
```
Bump them per semver on each change:
@@ -240,7 +256,7 @@ Bump them per semver on each change:
## Security notes
- Cookies are `httpOnly`, `SameSite=Lax`, `Secure` in production.
- All auth-scoped routes re-check ownership in the service layer (`userId` vs `req.user.id`).
- Wish mutations check ownership in the service layer (`userId` vs `req.user.id`). The shared dashboard requires a signed-in account.
- `/api/auth/login` is rate-limited; username enumeration is mitigated by a constant-time dummy compare.
- Image fetcher has a 10s timeout, a 5 MB cap, and accepts only `image/jpeg|png|webp|gif`.
- Multipart upload cap: 8 MB, one file per request.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/backend",
"version": "0.1.0",
"version": "0.5.0",
"private": true,
"type": "module",
"main": "dist/index.js",
+19
View File
@@ -28,6 +28,20 @@ model User {
updatedAt DateTime @updatedAt
wishes Wish[]
folders WishFolder[]
}
model WishFolder {
id String @id @default(cuid())
name String
description String?
emoji String?
imageUrl String?
creatorId String
creator User @relation(fields: [creatorId], references: [id])
createdAt DateTime @default(now())
wishes Wish[]
additionalWishes Wish[] @relation("AdditionalWishFolders")
}
enum WishStatus {
@@ -61,12 +75,17 @@ model Wish {
completedAt DateTime?
deletedAt DateTime?
sourceWishId String?
folderId String?
folder WishFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
additionalFolders WishFolder[] @relation("AdditionalWishFolders")
showInAuthorFolder Boolean @default(true)
views GuestView[]
@@index([userId, status])
@@index([deletedAt])
@@index([createdAt])
@@index([folderId])
}
model GuestView {
+2
View File
@@ -16,6 +16,7 @@ import multipartPlugin from './plugins/multipart.js';
import authRoutes from './modules/auth/auth.routes.js';
import profileRoutes from './modules/profile/profile.routes.js';
import wishesRoutes from './modules/wishes/wishes.routes.js';
import dashboardRoutes from './modules/wishes/dashboard.routes.js';
import imagesRoutes from './modules/images/images.routes.js';
import publicRoutes from './modules/public/public.routes.js';
import metaRoutes from './modules/meta/meta.routes.js';
@@ -77,6 +78,7 @@ export async function buildApp(): Promise<FastifyInstance> {
await app.register(authRoutes, { prefix: '/api/auth' });
await app.register(profileRoutes, { prefix: '/api/profile' });
await app.register(wishesRoutes, { prefix: '/api/wishes' });
await app.register(dashboardRoutes, { prefix: '/api' });
await app.register(imagesRoutes, { prefix: '/api/wishes' });
await app.register(publicRoutes, { prefix: '/api/public' });
@@ -25,6 +25,20 @@ export async function saveUploadedImage(
return { imageUrl: relative };
}
export async function saveUploadedAvatar(
userId: string,
mime: string,
buffer: Buffer,
): Promise<{ imageUrl: string }> {
const ext = MIME_TO_EXT[mime];
if (!ext) throw new ValidationError('Unsupported image type');
const filename = `${userId}-${nanoid(8)}.${ext}`;
const relative = `/uploads/avatar/${filename}`;
const absPath = resolve(env.UPLOADS_DIR, 'avatar', filename);
await writeFile(absPath, buffer);
return { imageUrl: relative };
}
export async function deleteLocalImageIfAny(imageUrl: string | null): Promise<void> {
if (!imageUrl) return;
if (!imageUrl.startsWith('/uploads/')) return;
@@ -1,7 +1,11 @@
import type { FastifyInstance } from 'fastify';
import { updateProfileSchema } from '@family-wishlist/shared';
import { ConflictError, NotFoundError } from '../../utils/errors.js';
import { ConflictError, NotFoundError, ValidationError } from '../../utils/errors.js';
import { Prisma } from '@prisma/client';
import { deleteLocalImageIfAny, saveUploadedAvatar } from '../images/storage.service.js';
import { usersRegistry } from '../../auth/users.registry.js';
const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
export default async function profileRoutes(app: FastifyInstance) {
app.addHook('preHandler', app.authenticate);
@@ -12,6 +16,16 @@ export default async function profileRoutes(app: FastifyInstance) {
return profile;
});
app.get('/friend', async (request) => {
const friend = usersRegistry.all().find((u) => u.id !== request.user.id);
if (!friend) return null;
return app.prisma.user.findUnique({
where: { id: friend.id },
select: { slug: true, displayName: true, avatarUrl: true },
});
});
app.patch('/', async (request) => {
const body = updateProfileSchema.parse(request.body);
try {
@@ -27,4 +41,25 @@ export default async function profileRoutes(app: FastifyInstance) {
throw err;
}
});
app.post('/avatar', async (request) => {
const current = await app.prisma.user.findUnique({ where: { id: request.user.id } });
if (!current) throw new NotFoundError('Profile');
const data = await request.file();
if (!data) throw new ValidationError('No file uploaded');
const buffer = await data.toBuffer();
if (buffer.byteLength > MAX_AVATAR_BYTES) {
throw new ValidationError('Avatar must be 2 MB or less');
}
const { imageUrl } = await saveUploadedAvatar(request.user.id, data.mimetype, buffer);
await deleteLocalImageIfAny(current.avatarUrl);
return app.prisma.user.update({
where: { id: request.user.id },
data: { avatarUrl: imageUrl },
});
});
}
@@ -31,7 +31,7 @@ export default async function publicRoutes(app: FastifyInstance) {
})
: [];
const seenSet = new Set(seen.map((s) => s.wishId));
return wishes.map((w) => ({
return wishes.map(({ folderId: _folderId, showInAuthorFolder: _showInAuthorFolder, ...w }) => ({
...w,
isNewForGuest: w.status === 'ACTIVE' && !seenSet.has(w.id),
}));
@@ -0,0 +1,102 @@
import { randomUUID } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import { createFolderSchema, NEW_BADGE_DAYS } from '@family-wishlist/shared';
import { usersRegistry } from '../../auth/users.registry.js';
import { MAX_UPLOAD_BYTES } from '../../plugins/multipart.js';
import { UnauthorizedError, ValidationError } from '../../utils/errors.js';
import { deleteLocalImageIfAny, saveUploadedImage } from '../images/storage.service.js';
import { includeWishFolders, withFolderIds } from './wishes.service.js';
const folderFields = ['name', 'description', 'emoji'];
export default async function dashboardRoutes(app: FastifyInstance) {
app.addHook('preHandler', async (request) => {
await app.authenticate(request);
if (!usersRegistry.findById(request.user.id)) throw new UnauthorizedError();
});
app.get('/dashboard', async (_request, reply) => {
const authorIds = usersRegistry.all().map((user) => user.id);
const [users, folders, wishes] = await Promise.all([
app.prisma.user.findMany({
where: { id: { in: authorIds } },
select: { id: true, displayName: true, avatarUrl: true },
}),
app.prisma.wishFolder.findMany({
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
}),
app.prisma.wish.findMany({
where: { userId: { in: authorIds }, status: { in: ['ACTIVE', 'COMPLETED'] } },
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }, { id: 'asc' }],
include: includeWishFolders,
}),
]);
const newSince = Date.now() - NEW_BADGE_DAYS * 24 * 60 * 60 * 1000;
reply.header('Cache-Control', 'private, no-store');
return {
authors: users.sort((a, b) => authorIds.indexOf(a.id) - authorIds.indexOf(b.id)),
folders,
wishes: wishes.map((wish) => ({
...withFolderIds(wish),
isNewForOwner: wish.status === 'ACTIVE' && wish.createdAt.getTime() > newSince,
})),
};
});
app.post('/folders', async (request, reply) => {
if (!request.isMultipart()) throw new ValidationError('Expected form data');
const fields: Record<string, unknown> = {};
let cover: { mime: string; buffer: Buffer } | undefined;
try {
for await (const part of request.parts({
limits: { files: 1, fields: 3, fieldSize: 4096, fileSize: MAX_UPLOAD_BYTES },
})) {
if (part.type === 'file') {
const buffer = await part.toBuffer();
if (part.fieldname !== 'cover' || part.file.truncated || !buffer.length) {
throw new ValidationError('Invalid cover');
}
cover = { mime: part.mimetype, buffer };
} else if (folderFields.includes(part.fieldname) && !part.valueTruncated) {
fields[part.fieldname] = part.value;
} else {
throw new ValidationError('Invalid folder field');
}
}
} catch (error) {
if (error instanceof app.multipartErrors.RequestFileTooLargeError) {
throw new ValidationError('File too large');
}
if (error instanceof app.multipartErrors.FilesLimitError ||
error instanceof app.multipartErrors.FieldsLimitError) {
throw new ValidationError('Invalid folder form');
}
throw error;
}
const input = createFolderSchema.parse(fields);
if (input.emoji && cover) throw new ValidationError('Choose one cover type');
const imageUrl = cover
? (await saveUploadedImage(`folder-${randomUUID()}`, cover.mime, cover.buffer)).imageUrl
: null;
try {
const folder = await app.prisma.wishFolder.create({
data: {
name: input.name,
description: input.description || null,
emoji: input.emoji || null,
imageUrl,
creatorId: request.user.id,
},
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
});
reply.code(201);
return folder;
} catch (error) {
await deleteLocalImageIfAny(imageUrl);
throw error;
}
});
}
@@ -15,45 +15,88 @@ const statusMap: Record<Status, WishStatus> = {
deleted: 'DELETED',
};
export const includeWishFolders = {
additionalFolders: { select: { id: true }, orderBy: { id: 'asc' as const } },
};
export function withFolderIds({ additionalFolders, ...wish }: Wish & {
additionalFolders: { id: string }[];
}) {
const folderIds = new Set(wish.folderId ? [wish.folderId] : []);
for (const { id } of additionalFolders) folderIds.add(id);
return { ...wish, folderIds: [...folderIds] };
}
export class WishesService {
constructor(private readonly prisma: PrismaClient) {}
list(userId: string, status: Status): Promise<Wish[]> {
return this.prisma.wish.findMany({
async list(userId: string, status: Status) {
const wishes = await this.prisma.wish.findMany({
where: { userId, status: statusMap[status] },
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }],
include: includeWishFolders,
});
return wishes.map(withFolderIds);
}
async getOwned(userId: string, id: string): Promise<Wish> {
const wish = await this.prisma.wish.findUnique({ where: { id } });
async getOwned(userId: string, id: string) {
const wish = await this.prisma.wish.findUnique({ where: { id }, include: includeWishFolders });
if (!wish) throw new NotFoundError('Wish');
if (wish.userId !== userId) throw new ForbiddenError();
return wish;
return withFolderIds(wish);
}
create(userId: string, input: CreateWishInput): Promise<Wish> {
return this.prisma.wish.create({
private async checkFolders(folderIds: string[]): Promise<void> {
if (folderIds.length && await this.prisma.wishFolder.count({
where: { id: { in: folderIds } },
}) !== folderIds.length) {
throw new NotFoundError('Folder');
}
}
async create(userId: string, input: CreateWishInput) {
const folderIds = [...new Set(input.folderIds ?? (input.folderId ? [input.folderId] : []))];
await this.checkFolders(folderIds);
const [folderId, ...additional] = folderIds;
const wish = await this.prisma.wish.create({
data: {
userId,
folderId,
additionalFolders: { connect: additional.map((id) => ({ id })) },
title: input.title,
showInAuthorFolder: input.showInAuthorFolder,
price: input.price ?? null,
currency: input.currency ?? 'RUB',
url: input.url ?? null,
comment: input.comment ?? null,
},
include: includeWishFolders,
});
return withFolderIds(wish);
}
async update(userId: string, id: string, input: UpdateWishInput): Promise<Wish> {
async update(userId: string, id: string, input: UpdateWishInput) {
await this.getOwned(userId, id);
const data: Record<string, unknown> = {};
if (input.folderIds !== undefined) {
const folderIds = [...new Set(input.folderIds)];
await this.checkFolders(folderIds);
const [folderId, ...additional] = folderIds;
data.folderId = folderId ?? null;
data.additionalFolders = { set: additional.map((id) => ({ id })) };
} else if (input.folderId !== undefined) {
await this.checkFolders(input.folderId ? [input.folderId] : []);
data.folderId = input.folderId;
}
if (input.showInAuthorFolder !== undefined) data.showInAuthorFolder = input.showInAuthorFolder;
if (input.title !== undefined) data.title = input.title;
if (input.price !== undefined) data.price = input.price ?? null;
if (input.currency !== undefined) data.currency = input.currency ?? 'RUB';
if (input.url !== undefined) data.url = input.url ?? null;
if (input.comment !== undefined) data.comment = input.comment ?? null;
return this.prisma.wish.update({ where: { id }, data });
return withFolderIds(await this.prisma.wish.update({
where: { id }, data, include: includeWishFolders,
}));
}
async archive(userId: string, id: string): Promise<Wish> {
@@ -98,9 +141,9 @@ export class WishesService {
});
}
async duplicate(userId: string, id: string): Promise<Wish> {
async duplicate(userId: string, id: string) {
const source = await this.getOwned(userId, id);
return this.prisma.wish.create({
const wish = await this.prisma.wish.create({
data: {
userId,
title: source.title,
@@ -111,7 +154,14 @@ export class WishesService {
imageUrl: source.imageSource === 'UPLOADED' ? null : source.imageUrl,
imageSource: source.imageSource === 'UPLOADED' ? 'DEFAULT' : source.imageSource,
sourceWishId: source.id,
showInAuthorFolder: source.showInAuthorFolder,
folderId: source.folderId,
additionalFolders: {
connect: source.folderIds.filter((id) => id !== source.folderId).map((id) => ({ id })),
},
},
include: includeWishFolders,
});
return withFolderIds(wish);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/frontend",
"version": "0.1.0",
"version": "0.5.0",
"private": true,
"type": "module",
"scripts": {
+9 -6
View File
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from 'sonner';
import { router } from './routes';
import { useAuthStore } from './features/auth/authStore';
import { I18nProvider } from './i18n/i18n';
const queryClient = new QueryClient({
defaultOptions: {
@@ -24,11 +25,13 @@ function AuthBoot({ children }: { children: React.ReactNode }) {
export function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthBoot>
<RouterProvider router={router} />
</AuthBoot>
<Toaster position="top-center" richColors closeButton />
</QueryClientProvider>
<I18nProvider>
<QueryClientProvider client={queryClient}>
<AuthBoot>
<RouterProvider router={router} />
</AuthBoot>
<Toaster position="top-center" richColors closeButton />
</QueryClientProvider>
</I18nProvider>
);
}
@@ -0,0 +1,39 @@
import { Languages } from 'lucide-react';
import { useI18n, type Language } from '@/i18n/i18n';
import { cn } from '@/lib/cn';
const languages: Array<{ value: Language; label: string }> = [
{ value: 'ru', label: 'RU' },
{ value: 'en', label: 'EN' },
];
export function LanguageSwitcher({ className }: { className?: string }) {
const { language, setLanguage, t } = useI18n();
return (
<div
className={cn(
'language-switcher',
className,
)}
aria-label={t('language.switch')}
>
<Languages className="language-switcher__icon" aria-hidden />
{languages.map((item) => (
<button
key={item.value}
type="button"
onClick={() => setLanguage(item.value)}
className={cn(
'language-switcher__button',
language === item.value && 'language-switcher__button--active',
)}
aria-pressed={language === item.value}
title={item.value === 'ru' ? t('language.ru') : t('language.en')}
>
{item.label}
</button>
))}
</div>
);
}
@@ -4,9 +4,9 @@ import { Footer } from './Footer';
export function AppShell() {
return (
<div className="flex min-h-screen flex-col">
<div className="app-shell">
<Header />
<main className="container-page flex-1 py-6 sm:py-10">
<main className="app-shell__main">
<Outlet />
</main>
<Footer />
+10 -8
View File
@@ -2,12 +2,14 @@ import { useQuery } from '@tanstack/react-query';
import { Gift } from 'lucide-react';
import { api } from '@/lib/api';
import { FRONTEND_VERSION } from '@/lib/version';
import { useI18n } from '@/i18n/i18n';
interface VersionInfo {
backend: string;
}
export function Footer() {
const { t } = useI18n();
const { data } = useQuery({
queryKey: ['version'],
queryFn: () => api.get<VersionInfo>('/api/version'),
@@ -15,16 +17,16 @@ export function Footer() {
});
return (
<footer className="container-page mt-10 py-6 text-xs text-muted">
<div className="flex flex-col items-center justify-between gap-2 sm:flex-row">
<div className="flex items-center gap-2">
<footer className="app-footer">
<div className="app-footer__inner">
<div className="app-footer__brand">
<Gift className="h-4 w-4" aria-hidden />
<span className="font-display text-sm">Family Wishlist</span>
<span className="app-footer__brand-name">{t('app.name')}</span>
</div>
<div className="flex items-center gap-3">
<span>frontend v{FRONTEND_VERSION}</span>
<span className="opacity-50">·</span>
<span>backend v{data?.backend ?? '...'}</span>
<div className="app-footer__meta">
<span>{t('footer.frontend', { version: FRONTEND_VERSION })}</span>
<span className="app-footer__separator">·</span>
<span>{t('footer.backend', { version: data?.backend ?? '...' })}</span>
</div>
</div>
</footer>
+82 -37
View File
@@ -1,79 +1,124 @@
import { Link, NavLink, useNavigate } from 'react-router-dom';
import { Archive, Gift, LogOut, Sparkles, Trash2, UserCog, CheckCircle2 } from 'lucide-react';
import { Archive, CheckCircle2, Gift, House, LogOut, Trash2, UserCog, Users } from 'lucide-react';
import type { ComponentType } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '../ui/Button';
import { useAuthStore } from '@/features/auth/authStore';
import { cn } from '@/lib/cn';
import { useI18n, type TranslationKey } from '@/i18n/i18n';
import { LanguageSwitcher } from '../LanguageSwitcher';
import { api } from '@/lib/api';
type NavIcon = ComponentType<{ className?: string }>;
interface FriendProfile {
slug: string;
displayName: string;
avatarUrl: string | null;
}
const links = [
{ to: '/', label: 'Active', icon: Sparkles, end: true },
{ to: '/completed', label: 'Fulfilled', icon: CheckCircle2 },
{ to: '/archive', label: 'Archive', icon: Archive },
{ to: '/trash', label: 'Trash', icon: Trash2 },
];
{ to: '/', label: 'header.home', icon: House, end: true },
{ to: '/completed', label: 'header.fulfilled', icon: CheckCircle2 },
{ to: '/archive', label: 'header.archive', icon: Archive },
{ to: '/trash', label: 'header.trash', icon: Trash2 },
] satisfies Array<{
to: string;
label: TranslationKey;
icon: NavIcon;
end?: boolean;
}>;
export function Header() {
const user = useAuthStore((s) => s.user);
const logout = useAuthStore((s) => s.logout);
const navigate = useNavigate();
const { t } = useI18n();
const friend = useQuery({
queryKey: ['profile-friend'],
queryFn: () => api.get<FriendProfile | null>('/api/profile/friend'),
staleTime: 10 * 60 * 1000,
enabled: user != null,
});
if (!user) return null;
return (
<header className="container-page pt-6">
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-surface/80 px-4 py-3 backdrop-blur">
<Link to="/" className="flex items-center gap-2">
<span className="inline-flex h-9 w-9 items-center justify-center rounded-md bg-primary text-primary-foreground shadow-card">
<header className="app-header">
<div className="app-header__inner">
<Link to="/" className="app-header__brand">
<span className="app-header__brand-mark">
<Gift className="h-4 w-4" />
</span>
<div>
<div className="font-display text-lg leading-tight">Family Wishlist</div>
<div className="text-xs text-muted">
signed in as <span className="font-medium text-ink">{user.displayName}</span>
<div className="min-w-0">
<div className="app-header__brand-title">{t('app.name')}</div>
<div className="app-header__brand-subtitle">
{t('header.signedInAs', { name: user.displayName })}
</div>
</div>
</Link>
<nav className="flex flex-wrap items-center gap-1">
{links.map((l) => (
<NavLink
key={l.to}
to={l.to}
end={l.end}
className={({ isActive }) =>
cn(
'inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
isActive ? 'bg-primary text-primary-foreground shadow-card' : 'text-ink hover:bg-ink/5',
)
}
>
<l.icon className="h-4 w-4" />
{l.label}
</NavLink>
))}
</nav>
<div className="flex items-center gap-1">
<div className="app-header__actions">
<LanguageSwitcher />
<Button
variant="ghost"
size="sm"
className="app-header__action"
onClick={() => navigate('/settings')}
title="Profile settings"
title={t('header.profileSettings')}
aria-label={t('header.profileSettings')}
>
<UserCog className="h-4 w-4" />
Profile
<span className="app-header__action-text">{t('header.profile')}</span>
</Button>
<Button
variant="ghost"
size="sm"
className="app-header__action"
onClick={() => {
void logout().then(() => navigate('/login'));
}}
title={t('header.logout')}
aria-label={t('header.logout')}
>
<LogOut className="h-4 w-4" />
Log out
<span className="app-header__action-text">{t('header.logout')}</span>
</Button>
</div>
</div>
<nav className="app-header__nav">
{links.map((l) => (
<NavLink
key={l.to}
to={l.to}
end={l.end}
className={({ isActive }) =>
cn(
'app-header__nav-link',
isActive && 'app-header__nav-link--active',
)
}
>
<l.icon className="h-4 w-4" />
{t(l.label)}
</NavLink>
))}
{friend.data && (
<NavLink
to={`/u/${friend.data.slug}`}
className={({ isActive }) =>
cn(
'app-header__nav-link',
isActive && 'app-header__nav-link--active',
)
}
>
<Users className="h-4 w-4" />
{t('header.friendWishes', { name: friend.data.displayName })}
</NavLink>
)}
</nav>
</header>
);
}
@@ -1,13 +1,17 @@
import { Navigate, useLocation } from 'react-router-dom';
import type { ReactNode } from 'react';
import { useAuthStore } from '@/features/auth/authStore';
import { useI18n } from '@/i18n/i18n';
export function ProtectedRoute({ children }: { children: ReactNode }) {
const { user, status } = useAuthStore();
const location = useLocation();
const { t } = useI18n();
if (status !== 'ready') {
return (
<div className="flex min-h-[50vh] items-center justify-center text-muted">Loading...</div>
<div className="flex min-h-[50vh] items-center justify-center text-muted">
{t('protected.loading')}
</div>
);
}
if (!user) {
@@ -1,6 +1,7 @@
import { Check, Sparkles, Archive, Trash2 } from 'lucide-react';
import type { Wish } from '@family-wishlist/shared';
import { cn } from '@/lib/cn';
import { useI18n } from '@/i18n/i18n';
interface Props {
wish: Wish & { isNewForOwner?: boolean };
@@ -9,6 +10,7 @@ interface Props {
}
export function WishBadges({ wish, view, className }: Props) {
const { t } = useI18n();
const badges: JSX.Element[] = [];
const isNew =
@@ -17,7 +19,7 @@ export function WishBadges({ wish, view, className }: Props) {
badges.push(
<span className="wish-badge wish-badge--new" key="new">
<Sparkles className="h-3 w-3" aria-hidden />
new
{t('wish.badge.new')}
</span>,
);
}
@@ -25,7 +27,7 @@ export function WishBadges({ wish, view, className }: Props) {
badges.push(
<span className="wish-badge wish-badge--completed" key="done">
<Check className="h-3 w-3" aria-hidden />
fulfilled
{t('wish.badge.fulfilled')}
</span>,
);
}
@@ -33,7 +35,7 @@ export function WishBadges({ wish, view, className }: Props) {
badges.push(
<span className="wish-badge wish-badge--archived" key="arch">
<Archive className="h-3 w-3" aria-hidden />
archived
{t('wish.badge.archived')}
</span>,
);
}
@@ -41,7 +43,7 @@ export function WishBadges({ wish, view, className }: Props) {
badges.push(
<span className="wish-badge wish-badge--deleted" key="del">
<Trash2 className="h-3 w-3" aria-hidden />
trash
{t('wish.badge.trash')}
</span>,
);
}
@@ -14,6 +14,7 @@ import { WishBadges } from '../WishBadges/WishBadges';
import { Button } from '../ui/Button';
import { cn } from '@/lib/cn';
import { formatPrice } from '@/lib/format';
import { useI18n } from '@/i18n/i18n';
export type WishCardView = 'owner' | 'guest';
@@ -49,39 +50,42 @@ function WishCardInner({
footer,
}: WishCardProps) {
const [menuOpen, setMenuOpen] = useState(false);
const { locale, t } = useI18n();
const completed = wish.status === 'COMPLETED';
const priceLabel = formatPrice(wish.price, wish.currency);
const priceLabel = formatPrice(wish.price, wish.currency, locale);
const imageSrc = wish.imageUrl ?? '/default-gift.svg';
const actions: WishCardAction[] = [];
if (view === 'owner') {
if (onEdit && (wish.status === 'ACTIVE' || completed)) {
actions.push({ key: 'edit', icon: Pencil, label: t('wish.action.edit'), onClick: onEdit });
}
if (wish.status === 'ACTIVE') {
if (onEdit) actions.push({ key: 'edit', icon: Pencil, label: 'Edit', onClick: onEdit });
if (onComplete)
actions.push({
key: 'complete',
icon: CheckCircle2,
label: 'Mark fulfilled',
label: t('wish.action.complete'),
onClick: onComplete,
});
if (onArchive)
actions.push({ key: 'archive', icon: Archive, label: 'Archive', onClick: onArchive });
actions.push({ key: 'archive', icon: Archive, label: t('wish.action.archive'), onClick: onArchive });
if (onDelete)
actions.push({
key: 'delete',
icon: Trash2,
label: 'Delete',
label: t('wish.action.delete'),
onClick: onDelete,
danger: true,
});
} else if (wish.status === 'ARCHIVED') {
if (onRestore)
actions.push({ key: 'restore', icon: RotateCcw, label: 'Restore', onClick: onRestore });
actions.push({ key: 'restore', icon: RotateCcw, label: t('wish.action.restore'), onClick: onRestore });
if (onDelete)
actions.push({
key: 'delete',
icon: Trash2,
label: 'Delete',
label: t('wish.action.delete'),
onClick: onDelete,
danger: true,
});
@@ -90,20 +94,20 @@ function WishCardInner({
actions.push({
key: 'duplicate',
icon: Copy,
label: 'Create copy as new',
label: t('wish.action.duplicate'),
onClick: onDuplicate,
});
if (onDelete)
actions.push({
key: 'delete',
icon: Trash2,
label: 'Delete',
label: t('wish.action.delete'),
onClick: onDelete,
danger: true,
});
} else if (wish.status === 'DELETED') {
if (onRestore)
actions.push({ key: 'restore', icon: RotateCcw, label: 'Restore', onClick: onRestore });
actions.push({ key: 'restore', icon: RotateCcw, label: t('wish.action.restore'), onClick: onRestore });
}
}
@@ -128,7 +132,7 @@ function WishCardInner({
<Button
variant="secondary"
size="icon"
aria-label="Actions"
aria-label={t('wish.actions')}
onClick={() => setMenuOpen((v) => !v)}
>
<MoreHorizontal className="h-4 w-4" />
@@ -177,7 +181,7 @@ function WishCardInner({
className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary-600"
>
<ExternalLink className="h-3 w-3" />
open link
{t('wish.openLink')}
</a>
)}
</div>
@@ -0,0 +1,107 @@
import { useState, type FormEvent } from 'react';
import { createFolderSchema, type WishFolder } from '@family-wishlist/shared';
import { FolderPlus } from 'lucide-react';
import { useCreateFolder } from '@/features/wishes/wishes.hooks';
import { useI18n } from '@/i18n/i18n';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { Label } from '../ui/Label';
import { Textarea } from '../ui/Textarea';
const coverTypes = 'image/jpeg,image/png,image/webp,image/gif';
export function FolderForm({
onCancel,
onCreated,
}: {
onCancel: () => void;
onCreated: (folder: WishFolder) => void;
}) {
const { t } = useI18n();
const create = useCreateFolder();
const [coverType, setCoverType] = useState<'none' | 'emoji' | 'image'>('none');
const [error, setError] = useState<string>();
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (create.isPending) return;
const form = new FormData(event.currentTarget);
const input = createFolderSchema.safeParse({
name: form.get('name'),
description: form.get('description'),
emoji: form.get('emoji') ?? undefined,
});
const file = form.get('cover');
const cover = file instanceof File && file.size > 0 ? file : null;
if (!input.success) {
const errors = input.error.flatten().fieldErrors;
setError(t(errors.emoji ? 'folders.invalidEmoji' : 'folders.invalidDetails'));
return;
}
if (coverType === 'image' && (!cover || !coverTypes.split(',').includes(cover.type) ||
cover.size > 8 * 1024 * 1024)) {
setError(t('folders.invalidImage'));
return;
}
setError(undefined);
try {
onCreated(await create.mutateAsync({ input: input.data, cover }));
} catch {
setError(t('folders.saveError'));
}
}
return (
<form className="wish-folders__form" onSubmit={submit} aria-busy={create.isPending}>
<div className="field">
<Label htmlFor="folder-name">{t('folders.name')}</Label>
<Input id="folder-name" name="name" maxLength={80} autoFocus required />
</div>
<div className="field">
<Label htmlFor="folder-description">{t('folders.description')}</Label>
<Textarea id="folder-description" name="description" maxLength={500} rows={2} />
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="field">
<Label htmlFor="folder-cover-type">{t('folders.cover')}</Label>
<select
id="folder-cover-type"
className="field__select"
value={coverType}
onChange={(event) => {
setCoverType(event.target.value as typeof coverType);
setError(undefined);
}}
>
<option value="none">{t('folders.noCover')}</option>
<option value="emoji">{t('folders.emoji')}</option>
<option value="image">{t('folders.image')}</option>
</select>
</div>
{coverType === 'emoji' && (
<div className="field">
<Label htmlFor="folder-emoji">{t('folders.emoji')}</Label>
<Input id="folder-emoji" name="emoji" placeholder="🎁" maxLength={32} required />
</div>
)}
{coverType === 'image' && (
<div className="field">
<Label htmlFor="folder-cover-file">{t('folders.image')}</Label>
<Input id="folder-cover-file" name="cover" type="file" accept={coverTypes} required />
</div>
)}
</div>
{error && <p role="alert" className="field__error">{error}</p>}
<div className="flex flex-wrap gap-2">
<Button type="submit" disabled={create.isPending}>
<FolderPlus className="h-4 w-4" aria-hidden />
{t('folders.create')}
</Button>
<Button variant="ghost" onClick={onCancel} disabled={create.isPending}>
{t('common.cancel')}
</Button>
</div>
</form>
);
}
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useRef } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createWishSchema, type CreateWishInput, type Wish } from '@family-wishlist/shared';
import { createWishSchema, type CreateWishInput, type Wish, type WishFolder } from '@family-wishlist/shared';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { Textarea } from '../ui/Textarea';
@@ -15,15 +15,19 @@ import {
useUpdateWish,
useUploadWishImage,
} from '@/features/wishes/wishes.hooks';
import { translateValidation, useI18n } from '@/i18n/i18n';
interface Props {
open: boolean;
mode: 'create' | 'edit';
initial?: Wish;
folders?: WishFolder[];
authorName: string;
defaultFolderId?: string;
onClose: () => void;
}
export function WishForm({ open, mode, initial, onClose }: Props) {
export function WishForm({ mode, initial, folders, authorName, defaultFolderId, onClose }: Props) {
const { t } = useI18n();
const create = useCreateWish();
const update = useUpdateWish();
const upload = useUploadWishImage();
@@ -31,12 +35,11 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
const resetImage = useResetWishImage();
const fileInputRef = useRef<HTMLInputElement>(null);
const [pendingId, setPendingId] = useState<string | null>(null);
const {
register,
control,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<CreateWishInput>({
resolver: zodResolver(createWishSchema),
@@ -46,101 +49,150 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
currency: initial?.currency ?? 'RUB',
url: initial?.url ?? '',
comment: initial?.comment ?? '',
folderIds: initial?.folderIds ??
(initial?.folderId ? [initial.folderId] : defaultFolderId ? [defaultFolderId] : []),
showInAuthorFolder: initial?.showInAuthorFolder ?? true,
},
});
useEffect(() => {
if (!open) return;
reset({
title: initial?.title ?? '',
price: initial?.price ?? '',
currency: initial?.currency ?? 'RUB',
url: initial?.url ?? '',
comment: initial?.comment ?? '',
});
setPendingId(initial?.id ?? null);
}, [open, initial, reset]);
const submit = handleSubmit(async (values) => {
if (mode === 'create') {
const created = await create.mutateAsync(values);
setPendingId(created.id);
} else if (initial) {
await update.mutateAsync({ id: initial.id, input: values });
const input = { ...values, folderIds: folders ? values.folderIds : undefined };
try {
if (mode === 'create') {
await create.mutateAsync(input);
} else if (initial) {
await update.mutateAsync({ id: initial.id, input });
}
onClose();
} catch {
// The mutation reports the error and the form retains the draft.
}
onClose();
});
const activeId = pendingId ?? initial?.id ?? null;
const canEditImage = activeId != null;
const activeId = initial?.id;
return (
<Modal
open={open}
open
onClose={onClose}
title={mode === 'create' ? 'Add a wish' : 'Edit wish'}
title={mode === 'create' ? t('wishForm.addTitle') : t('wishForm.editTitle')}
description={
mode === 'create'
? 'Tell us what you want. A link helps us grab a preview image automatically.'
: 'Update the details of your wish.'
? t('wishForm.addDescription')
: t('wishForm.editDescription')
}
size="lg"
footer={
<>
<Button variant="ghost" onClick={onClose}>
Cancel
{t('common.cancel')}
</Button>
<Button type="submit" form="wish-form" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
{mode === 'create' ? 'Add wish' : 'Save'}
{mode === 'create' ? t('wishForm.addSubmit') : t('common.save')}
</Button>
</>
}
>
<form id="wish-form" className="grid gap-4" onSubmit={submit}>
<div className="field">
<Label htmlFor="title">Title</Label>
<Input id="title" placeholder="Moka pot, size 3" {...register('title')} />
{errors.title && <span className="field__error">{errors.title.message}</span>}
<Label htmlFor="title">{t('wishForm.title')}</Label>
<Input id="title" autoFocus placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
{errors.title && (
<span className="field__error">{translateValidation(t, errors.title.message)}</span>
)}
</div>
<fieldset aria-describedby="wish-folders-hint" className="field min-w-0">
<legend className="field__label">{t('folders.field')}</legend>
<p id="wish-folders-hint" className="text-sm text-ink">
{t('folders.alwaysVisible')}
</p>
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
<label className="wish-checkbox">
<input type="checkbox" {...register('showInAuthorFolder')} />
<span>{authorName}</span>
</label>
{folders && folders.length > 0 && (
<Controller
name="folderIds"
control={control}
render={({ field }) => {
const ids = field.value ?? [];
return (
<>
{folders.map(({ id, name }) => (
<label key={id} className="wish-checkbox">
<input
type="checkbox"
name={field.name}
checked={ids.includes(id)}
onBlur={field.onBlur}
onChange={(event) => field.onChange(event.target.checked
? [...ids, id]
: ids.filter((selectedId) => selectedId !== id))}
/>
<span>{name}</span>
</label>
))}
</>
);
}}
/>
)}
</div>
</fieldset>
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
<div className="field">
<Label htmlFor="price">Price (optional)</Label>
<Input id="price" placeholder="e.g. 2490" inputMode="decimal" {...register('price')} />
{errors.price && <span className="field__error">{errors.price.message as string}</span>}
<Label htmlFor="price">{t('wishForm.price')}</Label>
<Input
id="price"
placeholder={t('wishForm.pricePlaceholder')}
inputMode="decimal"
{...register('price')}
/>
{errors.price && (
<span className="field__error">
{translateValidation(t, errors.price.message as string)}
</span>
)}
</div>
<div className="field">
<Label htmlFor="currency">Currency</Label>
<Label htmlFor="currency">{t('wishForm.currency')}</Label>
<Input id="currency" maxLength={3} className="uppercase w-24" {...register('currency')} />
</div>
</div>
<div className="field">
<Label htmlFor="url">Link (optional)</Label>
<Label htmlFor="url">{t('wishForm.link')}</Label>
<Input id="url" type="url" placeholder="https://..." {...register('url')} />
{errors.url && <span className="field__error">{errors.url.message as string}</span>}
{errors.url && (
<span className="field__error">
{translateValidation(t, errors.url.message as string)}
</span>
)}
<p className="text-xs text-muted">
We will try to pull a preview image from the link after saving.
{t('wishForm.linkHint')}
</p>
</div>
<div className="field">
<Label htmlFor="comment">Comment (optional)</Label>
<Label htmlFor="comment">{t('wishForm.comment')}</Label>
<Textarea
id="comment"
rows={3}
placeholder="Size / color / notes..."
placeholder={t('wishForm.commentPlaceholder')}
{...register('comment')}
/>
</div>
</form>
{canEditImage && activeId && (
{activeId && (
<section className="mt-6 rounded-md border border-border bg-surface-muted p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-ink">
<ImageIcon className="h-4 w-4" />
Image
{t('wishForm.image')}
</div>
<div className="flex flex-wrap items-center gap-2">
<input
@@ -165,7 +217,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
) : (
<Upload className="h-4 w-4" />
)}
Upload custom
{t('wishForm.uploadCustom')}
</Button>
<Button
variant="outline"
@@ -178,7 +230,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
) : (
<RefreshCcw className="h-4 w-4" />
)}
Refresh from link
{t('wishForm.refreshFromLink')}
</Button>
<Button
variant="ghost"
@@ -187,7 +239,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
disabled={resetImage.isPending}
>
<Trash2 className="h-4 w-4" />
Reset to default
{t('wishForm.resetImage')}
</Button>
</div>
</section>
+10 -16
View File
@@ -40,9 +40,9 @@ export function Modal({
if (!open) return null;
return createPortal(
<div className="fixed inset-0 z-50 flex items-end justify-center p-0 sm:items-center sm:p-6">
<div className="modal">
<div
className="absolute inset-0 bg-ink/40 backdrop-blur-sm animate-fade-in-up"
className="modal__backdrop"
onClick={onClose}
aria-hidden
/>
@@ -50,27 +50,21 @@ export function Modal({
role="dialog"
aria-modal="true"
className={cn(
'relative w-full bg-surface shadow-pop animate-fade-in-up',
'rounded-t-xl sm:rounded-xl',
size === 'md' ? 'sm:max-w-lg' : 'sm:max-w-2xl',
'max-h-[90vh] overflow-hidden flex flex-col',
'modal__panel',
size === 'md' ? 'modal__panel--md' : 'modal__panel--lg',
)}
>
<header className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
<div className="min-w-0">
<h2 className="text-lg font-semibold text-ink">{title}</h2>
{description && <p className="mt-1 text-sm text-muted">{description}</p>}
<header className="modal__header">
<div className="modal__title-wrap">
<h2 className="modal__title">{title}</h2>
{description && <p className="modal__description">{description}</p>}
</div>
<Button variant="ghost" size="icon" onClick={onClose} aria-label="Close">
<X className="h-5 w-5" />
</Button>
</header>
<div className="overflow-y-auto px-5 py-5">{children}</div>
{footer && (
<footer className="flex items-center justify-end gap-2 border-t border-border px-5 py-4">
{footer}
</footer>
)}
<div className="modal__body">{children}</div>
{footer && <footer className="modal__footer">{footer}</footer>}
</div>
</div>,
document.body,
@@ -1,16 +1,24 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { CreateWishInput, UpdateWishInput } from '@family-wishlist/shared';
import type {
CreateFolderInput,
CreateWishInput,
UpdateWishInput,
WishDashboard,
WishFolder,
} from '@family-wishlist/shared';
import { toast } from 'sonner';
import { wishesApi, type OwnerStatus } from './wishes.api';
import { ApiError } from '@/lib/api';
import { api, ApiError } from '@/lib/api';
import { useI18n } from '@/i18n/i18n';
const LIST_KEY = (status: OwnerStatus) => ['wishes', status] as const;
const DASHBOARD_KEY = ['wishes', 'dashboard'] as const;
function invalidateAll(client: ReturnType<typeof useQueryClient>): void {
void client.invalidateQueries({ queryKey: ['wishes'] });
}
function toastError(err: unknown, fallback = 'Something went wrong'): void {
function toastError(err: unknown, fallback: string): void {
if (err instanceof ApiError) toast.error(err.message);
else toast.error(fallback);
}
@@ -23,123 +31,163 @@ export function useWishes(status: OwnerStatus) {
});
}
export function useWishDashboard() {
return useQuery({
queryKey: DASHBOARD_KEY,
queryFn: ({ signal }) => api.get<WishDashboard>('/api/dashboard', signal),
});
}
export function useCreateFolder() {
const client = useQueryClient();
return useMutation({
mutationFn: ({ input, cover }: { input: CreateFolderInput; cover: File | null }) => {
const data = new FormData();
data.append('name', input.name);
if (input.description) data.append('description', input.description);
if (input.emoji) data.append('emoji', input.emoji);
if (cover) data.append('cover', cover);
return api.upload<WishFolder>('/api/folders', data);
},
onSuccess: (folder) => {
client.setQueryData<WishDashboard>(DASHBOARD_KEY, (current) =>
current && {
...current,
folders: [...current.folders.filter(({ id }) => id !== folder.id), folder],
},
);
void client.invalidateQueries({ queryKey: DASHBOARD_KEY });
},
});
}
export function useCreateWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (input: CreateWishInput) => wishesApi.create(input),
onSuccess: () => {
invalidateAll(client);
toast.success('Wish added');
toast.success(t('toast.wishAdded'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useUpdateWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (vars: { id: string; input: UpdateWishInput }) =>
wishesApi.update(vars.id, vars.input),
onSuccess: () => {
invalidateAll(client);
toast.success('Saved');
toast.success(t('toast.saved'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useArchiveWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.archive(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Moved to archive');
toast.success(t('toast.archived'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useCompleteWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.complete(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Marked as fulfilled');
toast.success(t('toast.fulfilled'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useDeleteWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.remove(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Moved to trash (30 days to restore)');
toast.success(t('toast.deleted'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useRestoreWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.restore(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Restored');
toast.success(t('toast.restored'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useDuplicateWish() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.duplicate(id),
onSuccess: () => {
invalidateAll(client);
toast.success('New wish created from the fulfilled one');
toast.success(t('toast.duplicated'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useUploadWishImage() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (vars: { id: string; file: File }) => wishesApi.uploadImage(vars.id, vars.file),
onSuccess: () => {
invalidateAll(client);
toast.success('Image updated');
toast.success(t('toast.imageUpdated'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
export function useRefreshOg() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.refreshOg(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Image refreshed from link');
toast.success(t('toast.imageRefreshed'));
},
onError: (err) => toastError(err, 'Could not fetch image from link'),
onError: (err) => toastError(err, t('toast.imageFetchFailed')),
});
}
export function useResetWishImage() {
const client = useQueryClient();
const { t } = useI18n();
return useMutation({
mutationFn: (id: string) => wishesApi.deleteImage(id),
onSuccess: () => {
invalidateAll(client);
toast.success('Reset to default image');
toast.success(t('toast.imageReset'));
},
onError: (err) => toastError(err),
onError: (err) => toastError(err, t('toast.genericError')),
});
}
+373
View File
@@ -0,0 +1,373 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
export type Language = 'ru' | 'en';
const STORAGE_KEY = 'family-wishlist-language';
const FALLBACK_LANGUAGE: Language = 'ru';
const translations = {
ru: {
'app.name': 'Family Wishlist',
'language.ru': 'Русский',
'language.en': 'English',
'language.switch': 'Язык',
'common.loading': 'Загрузка...',
'common.cancel': 'Отмена',
'common.save': 'Сохранить',
'common.saveChanges': 'Сохранить изменения',
'common.backHome': 'На главную',
'common.days.one': '{count} день',
'common.days.few': '{count} дня',
'common.days.many': '{count} дней',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.home': 'Главная',
'header.fulfilled': 'Исполненные',
'header.archive': 'Архив',
'header.trash': 'Корзина',
'header.signedInAs': 'вошли как {name}',
'header.profileSettings': 'Настройки профиля',
'header.profile': 'Профиль',
'header.friendWishes': 'Желания {name}',
'header.logout': 'Выйти',
'login.title': 'С возвращением',
'login.description': 'Войдите, чтобы управлять списком желаний. Доступы задаются на сервере.',
'login.username': 'Логин',
'login.password': 'Пароль',
'login.submit': 'Войти',
'login.failed': 'Не удалось войти',
'dashboard.title': 'Семейный список желаний',
'dashboard.publicPage': 'Моя публичная страница',
'dashboard.addWish': 'Добавить желание',
'dashboard.emptyTitle': 'Желаний пока нет',
'dashboard.loadError': 'Не удалось загрузить список желаний.',
'dashboard.retry': 'Повторить',
'dashboard.hideCompleted': 'Скрыть исполненные',
'dashboard.completedHidden': 'Исполненные желания скрыты',
'folders.title': 'Папки желаний',
'folders.all': 'Все',
'folders.create': 'Создать папку',
'folders.name': 'Название',
'folders.description': 'Описание (необязательно)',
'folders.cover': 'Обложка',
'folders.noCover': 'Без обложки',
'folders.emoji': 'Эмодзи',
'folders.image': 'Изображение',
'folders.field': 'В каких папках видно желание',
'folders.alwaysVisible': 'Желание всегда видно во «Все».',
'folders.invalidDetails': 'Проверьте название и описание папки.',
'folders.invalidEmoji': 'Введите эмодзи для обложки.',
'folders.invalidImage': 'Выберите файл JPEG, PNG, WebP или GIF размером до 8 МБ.',
'folders.saveError': 'Не удалось создать папку. Попробуйте ещё раз.',
'archive.title': 'Архив',
'archive.description': 'Отложенные желания. Их видите только вы, и их можно вернуть в активный список.',
'archive.emptyTitle': 'Архив пуст',
'archive.emptyText': 'Архивированные желания появятся здесь.',
'completed.title': 'Исполненные',
'completed.description': 'Желания, которые уже исполнились. Из любого можно создать новое.',
'completed.emptyTitle': 'Исполненных желаний пока нет',
'completed.emptyText': 'Когда желание исполнится, отметьте его, и оно появится здесь.',
'trash.title': 'Корзина',
'trash.description': 'Удалённые желания хранятся {days}, затем удаляются навсегда.',
'trash.emptyTitle': 'Корзина пуста',
'trash.emptyText': 'Удалённые желания будут появляться здесь на {days}.',
'trash.autoRemove': 'Автоудаление через {days}',
'profile.title': 'Профиль',
'profile.publicPage': 'Публичная страница доступна по адресу ',
'profile.slug': 'Slug (публичный URL)',
'profile.displayName': 'Отображаемое имя',
'profile.bio': 'О себе',
'profile.avatarUrl': 'Ссылка на аватар',
'profile.avatar': 'Аватар',
'profile.avatarHint': 'Можно вставить ссылку или загрузить фото до 2 MB.',
'profile.uploadAvatar': 'Загрузить фото',
'profile.avatarTooLarge': 'Фото должно быть не больше 2 MB',
'profile.avatarUnsupported': 'Поддерживаются JPEG, PNG, WebP и GIF',
'profile.saved': 'Профиль сохранён',
'profile.avatarUploaded': 'Аватар обновлён',
'profile.saveFailed': 'Не удалось сохранить',
'public.loadingWishes': 'Загрузка желаний...',
'public.notFoundTitle': 'Профиль не найден',
'public.notFoundText': 'Проверьте ссылку и попробуйте ещё раз. Slug чувствителен к регистру.',
'public.backToMine': 'Вернуться к моим желаниям',
'public.wishlistTitle': 'Список желаний {name}',
'public.emptyTitle': 'Желаний пока нет',
'public.emptyText': 'Загляните позже!',
'notFound.text': 'Не удалось найти эту страницу.',
'protected.loading': 'Загрузка...',
'wish.action.edit': 'Редактировать',
'wish.action.complete': 'Отметить исполненным',
'wish.action.archive': 'В архив',
'wish.action.delete': 'Удалить',
'wish.action.restore': 'Восстановить',
'wish.action.duplicate': 'Создать копию как новое',
'wish.actions': 'Действия',
'wish.openLink': 'открыть ссылку',
'wish.badge.new': 'новое',
'wish.badge.fulfilled': 'исполнено',
'wish.badge.archived': 'архив',
'wish.badge.trash': 'корзина',
'wishForm.addTitle': 'Добавить желание',
'wishForm.editTitle': 'Редактировать желание',
'wishForm.addDescription': 'Расскажите, чего хочется. По ссылке мы попробуем подтянуть картинку.',
'wishForm.editDescription': 'Обновите детали желания.',
'wishForm.title': 'Название',
'wishForm.titlePlaceholder': 'Гейзерная кофеварка, размер 3',
'wishForm.price': 'Цена (необязательно)',
'wishForm.pricePlaceholder': 'например, 2490',
'wishForm.currency': 'Валюта',
'wishForm.link': 'Ссылка (необязательно)',
'wishForm.linkHint': 'После сохранения попробуем подтянуть превью-картинку по ссылке.',
'wishForm.comment': 'Комментарий (необязательно)',
'wishForm.commentPlaceholder': 'Размер / цвет / заметки...',
'wishForm.image': 'Картинка',
'wishForm.uploadCustom': 'Загрузить свою',
'wishForm.refreshFromLink': 'Обновить по ссылке',
'wishForm.resetImage': 'Сбросить на стандартную',
'wishForm.addSubmit': 'Добавить желание',
'toast.genericError': 'Что-то пошло не так',
'toast.wishAdded': 'Желание добавлено',
'toast.saved': 'Сохранено',
'toast.archived': 'Перемещено в архив',
'toast.fulfilled': 'Отмечено исполненным',
'toast.deleted': 'Перемещено в корзину (30 дней на восстановление)',
'toast.restored': 'Восстановлено',
'toast.duplicated': 'Новое желание создано из исполненного',
'toast.imageUpdated': 'Картинка обновлена',
'toast.imageRefreshed': 'Картинка обновлена по ссылке',
'toast.imageFetchFailed': 'Не удалось получить картинку по ссылке',
'toast.imageReset': 'Картинка сброшена на стандартную',
'validation.invalid': 'Проверьте значение поля',
'validation.slug': 'Slug: 3-32 символа, строчные латинские буквы, цифры и дефисы',
},
en: {
'app.name': 'Family Wishlist',
'language.ru': 'Русский',
'language.en': 'English',
'language.switch': 'Language',
'common.loading': 'Loading...',
'common.cancel': 'Cancel',
'common.save': 'Save',
'common.saveChanges': 'Save changes',
'common.backHome': 'Back to home',
'common.days.one': '{count} day',
'common.days.few': '{count} days',
'common.days.many': '{count} days',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.home': 'Home',
'header.fulfilled': 'Fulfilled',
'header.archive': 'Archive',
'header.trash': 'Trash',
'header.signedInAs': 'signed in as {name}',
'header.profileSettings': 'Profile settings',
'header.profile': 'Profile',
'header.friendWishes': "{name}'s wishes",
'header.logout': 'Log out',
'login.title': 'Welcome back',
'login.description': 'Sign in to manage your wishlist. Credentials are set up via the server environment.',
'login.username': 'Username',
'login.password': 'Password',
'login.submit': 'Sign in',
'login.failed': 'Login failed',
'dashboard.title': 'Family wishlist',
'dashboard.publicPage': 'My public page',
'dashboard.addWish': 'Add wish',
'dashboard.emptyTitle': 'No wishes yet',
'dashboard.loadError': "Couldn't load wishes.",
'dashboard.retry': 'Try again',
'dashboard.hideCompleted': 'Hide fulfilled wishes',
'dashboard.completedHidden': 'Fulfilled wishes are hidden',
'folders.title': 'Wish folders',
'folders.all': 'All',
'folders.create': 'Create folder',
'folders.name': 'Name',
'folders.description': 'Description (optional)',
'folders.cover': 'Cover',
'folders.noCover': 'No cover',
'folders.emoji': 'Emoji',
'folders.image': 'Image',
'folders.field': 'Show wish in folders',
'folders.alwaysVisible': 'The wish always appears in “All”.',
'folders.invalidDetails': 'Check the folder name and description.',
'folders.invalidEmoji': 'Enter an emoji for the cover.',
'folders.invalidImage': 'Choose a JPEG, PNG, WebP, or GIF file up to 8 MB.',
'folders.saveError': "Couldn't create the folder. Try again.",
'archive.title': 'Archive',
'archive.description': 'Wishes you put aside. Only you see this. Restore them to your active list any time.',
'archive.emptyTitle': 'Archive is empty',
'archive.emptyText': 'Archived wishes will show up here.',
'completed.title': 'Fulfilled',
'completed.description': "Wishes you've received. You can create a new wish based on any of them.",
'completed.emptyTitle': 'Nothing fulfilled yet',
'completed.emptyText': 'When a wish comes true, mark it as fulfilled and it lands here.',
'trash.title': 'Trash',
'trash.description': 'Deleted wishes are kept for {days}, then permanently removed.',
'trash.emptyTitle': 'Trash is empty',
'trash.emptyText': 'Deleted wishes will appear here for {days}.',
'trash.autoRemove': 'Auto-removes in {days}',
'profile.title': 'Profile',
'profile.publicPage': 'Your public page lives at ',
'profile.slug': 'Slug (public URL)',
'profile.displayName': 'Display name',
'profile.bio': 'Bio',
'profile.avatarUrl': 'Avatar URL',
'profile.avatar': 'Avatar',
'profile.avatarHint': 'Paste a link or upload a photo up to 2 MB.',
'profile.uploadAvatar': 'Upload photo',
'profile.avatarTooLarge': 'Avatar must be 2 MB or less',
'profile.avatarUnsupported': 'JPEG, PNG, WebP and GIF are supported',
'profile.saved': 'Profile saved',
'profile.avatarUploaded': 'Avatar updated',
'profile.saveFailed': 'Save failed',
'public.loadingWishes': 'Loading wishes...',
'public.notFoundTitle': 'Profile not found',
'public.notFoundText': 'Check the link and try again. Slugs are case-sensitive.',
'public.backToMine': 'Back to my wishlist',
'public.wishlistTitle': "{name}'s wishlist",
'public.emptyTitle': 'No wishes yet',
'public.emptyText': 'Check back later!',
'notFound.text': "We couldn't find that page.",
'protected.loading': 'Loading...',
'wish.action.edit': 'Edit',
'wish.action.complete': 'Mark fulfilled',
'wish.action.archive': 'Archive',
'wish.action.delete': 'Delete',
'wish.action.restore': 'Restore',
'wish.action.duplicate': 'Create copy as new',
'wish.actions': 'Actions',
'wish.openLink': 'open link',
'wish.badge.new': 'new',
'wish.badge.fulfilled': 'fulfilled',
'wish.badge.archived': 'archived',
'wish.badge.trash': 'trash',
'wishForm.addTitle': 'Add a wish',
'wishForm.editTitle': 'Edit wish',
'wishForm.addDescription': 'Tell us what you want. A link helps us grab a preview image automatically.',
'wishForm.editDescription': 'Update the details of your wish.',
'wishForm.title': 'Title',
'wishForm.titlePlaceholder': 'Moka pot, size 3',
'wishForm.price': 'Price (optional)',
'wishForm.pricePlaceholder': 'e.g. 2490',
'wishForm.currency': 'Currency',
'wishForm.link': 'Link (optional)',
'wishForm.linkHint': 'We will try to pull a preview image from the link after saving.',
'wishForm.comment': 'Comment (optional)',
'wishForm.commentPlaceholder': 'Size / color / notes...',
'wishForm.image': 'Image',
'wishForm.uploadCustom': 'Upload custom',
'wishForm.refreshFromLink': 'Refresh from link',
'wishForm.resetImage': 'Reset to default',
'wishForm.addSubmit': 'Add wish',
'toast.genericError': 'Something went wrong',
'toast.wishAdded': 'Wish added',
'toast.saved': 'Saved',
'toast.archived': 'Moved to archive',
'toast.fulfilled': 'Marked as fulfilled',
'toast.deleted': 'Moved to trash (30 days to restore)',
'toast.restored': 'Restored',
'toast.duplicated': 'New wish created from the fulfilled one',
'toast.imageUpdated': 'Image updated',
'toast.imageRefreshed': 'Image refreshed from link',
'toast.imageFetchFailed': 'Could not fetch image from link',
'toast.imageReset': 'Reset to default image',
'validation.invalid': 'Check this field',
'validation.slug': 'Slug must be 3-32 chars, lowercase letters, digits, hyphens',
},
} as const;
export type TranslationKey = keyof typeof translations.ru;
interface I18nContextValue {
language: Language;
locale: string;
setLanguage: (language: Language) => void;
t: (key: TranslationKey, vars?: Record<string, string | number>) => string;
dayCount: (count: number) => string;
}
const I18nContext = createContext<I18nContextValue | null>(null);
function isLanguage(value: string | null): value is Language {
return value === 'ru' || value === 'en';
}
function detectLanguage(): Language {
if (typeof window === 'undefined') return FALLBACK_LANGUAGE;
const saved = window.localStorage.getItem(STORAGE_KEY);
if (isLanguage(saved)) return saved;
const languages = navigator.languages.length ? navigator.languages : [navigator.language];
for (const lang of languages) {
const normalized = lang.toLowerCase();
if (normalized.startsWith('ru')) return 'ru';
if (normalized.startsWith('en')) return 'en';
}
return FALLBACK_LANGUAGE;
}
function interpolate(template: string, vars?: Record<string, string | number>): string {
if (!vars) return template;
return template.replace(/\{(\w+)\}/g, (_, key: string) => String(vars[key] ?? `{${key}}`));
}
function dayKey(language: Language, count: number): TranslationKey {
if (language === 'en') return count === 1 ? 'common.days.one' : 'common.days.many';
const mod10 = count % 10;
const mod100 = count % 100;
if (mod10 === 1 && mod100 !== 11) return 'common.days.one';
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'common.days.few';
return 'common.days.many';
}
export function I18nProvider({ children }: { children: ReactNode }) {
const [language, setLanguageState] = useState<Language>(() => detectLanguage());
useEffect(() => {
document.documentElement.lang = language;
window.localStorage.setItem(STORAGE_KEY, language);
}, [language]);
const setLanguage = useCallback((next: Language) => setLanguageState(next), []);
const t = useCallback(
(key: TranslationKey, vars?: Record<string, string | number>) =>
interpolate(translations[language][key] ?? translations[FALLBACK_LANGUAGE][key], vars),
[language],
);
const dayCount = useCallback(
(count: number) => t(dayKey(language, count), { count }),
[language, t],
);
const value = useMemo<I18nContextValue>(
() => ({
language,
locale: language === 'ru' ? 'ru-RU' : 'en-US',
setLanguage,
t,
dayCount,
}),
[dayCount, language, setLanguage, t],
);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}
export function useI18n(): I18nContextValue {
const value = useContext(I18nContext);
if (!value) throw new Error('useI18n must be used within I18nProvider');
return value;
}
export function translateValidation(t: I18nContextValue['t'], message: string | undefined): string {
if (!message) return t('validation.invalid');
if (message.includes('Slug must be')) return t('validation.slug');
return t('validation.invalid');
}
+9 -5
View File
@@ -1,21 +1,25 @@
export function formatPrice(price: string | null | undefined, currency: string): string | null {
export function formatPrice(
price: string | null | undefined,
currency: string,
locale?: string,
): string | null {
if (!price) return null;
const n = Number(price);
if (Number.isNaN(n)) return `${price} ${currency}`;
try {
return new Intl.NumberFormat(undefined, {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
maximumFractionDigits: 2,
}).format(n);
} catch {
return `${n.toLocaleString()} ${currency}`;
return `${n.toLocaleString(locale)} ${currency}`;
}
}
export function formatDate(iso: string | Date): string {
export function formatDate(iso: string | Date, locale?: string): string {
const d = typeof iso === 'string' ? new Date(iso) : iso;
return d.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
return d.toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric' });
}
export function daysLeftUntil(iso: string | Date, retentionDays: number): number {
+11 -9
View File
@@ -5,28 +5,30 @@ import {
useWishes,
} from '@/features/wishes/wishes.hooks';
import { Archive } from 'lucide-react';
import { useI18n } from '@/i18n/i18n';
export function ArchivePage() {
const { t } = useI18n();
const { data, isLoading } = useWishes('archived');
const restore = useRestoreWish();
const remove = useDeleteWish();
return (
<div className="grid gap-6">
<section>
<h1 className="font-display text-3xl">Archive</h1>
<p className="text-sm text-muted">
Wishes you put aside. Only you see this. Restore them to your active list any time.
<section className="page-section">
<h1 className="page-section__title">{t('archive.title')}</h1>
<p className="page-section__text">
{t('archive.description')}
</p>
</section>
{isLoading && <div className="text-muted">Loading...</div>}
{isLoading && <div className="text-muted">{t('common.loading')}</div>}
{!isLoading && data && data.length === 0 && (
<div className="flex flex-col items-center gap-2 rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card">
<Archive className="h-10 w-10 text-muted" />
<h2 className="text-xl font-semibold">Archive is empty</h2>
<p className="text-sm text-muted">Archived wishes will show up here.</p>
<div className="empty-state">
<Archive className="empty-state__icon" />
<h2 className="empty-state__title">{t('archive.emptyTitle')}</h2>
<p className="empty-state__text">{t('archive.emptyText')}</p>
</div>
)}
+12 -10
View File
@@ -5,29 +5,31 @@ import {
useDuplicateWish,
useWishes,
} from '@/features/wishes/wishes.hooks';
import { useI18n } from '@/i18n/i18n';
export function CompletedPage() {
const { t } = useI18n();
const { data, isLoading } = useWishes('completed');
const duplicate = useDuplicateWish();
const remove = useDeleteWish();
return (
<div className="grid gap-6">
<section>
<h1 className="font-display text-3xl">Fulfilled</h1>
<p className="text-sm text-muted">
Wishes you've received. You can create a new wish based on any of them.
<section className="page-section">
<h1 className="page-section__title">{t('completed.title')}</h1>
<p className="page-section__text">
{t('completed.description')}
</p>
</section>
{isLoading && <div className="text-muted">Loading...</div>}
{isLoading && <div className="text-muted">{t('common.loading')}</div>}
{!isLoading && data && data.length === 0 && (
<div className="flex flex-col items-center gap-2 rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card">
<CheckCircle2 className="h-10 w-10 text-muted" />
<h2 className="text-xl font-semibold">Nothing fulfilled yet</h2>
<p className="text-sm text-muted">
When a wish comes true, mark it as fulfilled and it lands here.
<div className="empty-state">
<CheckCircle2 className="empty-state__icon" />
<h2 className="empty-state__title">{t('completed.emptyTitle')}</h2>
<p className="empty-state__text">
{t('completed.emptyText')}
</p>
</div>
)}
+217 -65
View File
@@ -1,102 +1,254 @@
import { useState } from 'react';
import { Plus, Sparkles } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react';
import { Folder, FolderPlus, LayoutGrid, Plus, UserRound } from 'lucide-react';
import type { Wish } from '@family-wishlist/shared';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { WishCard } from '@/components/WishCard/WishCard';
import { FolderForm } from '@/components/WishForm/FolderForm';
import { WishForm } from '@/components/WishForm/WishForm';
import {
useArchiveWish,
useCompleteWish,
useDeleteWish,
useWishes,
useDuplicateWish,
useWishDashboard,
} from '@/features/wishes/wishes.hooks';
import { useAuthStore } from '@/features/auth/authStore';
import { Link } from 'react-router-dom';
import { useI18n } from '@/i18n/i18n';
type Selection = { type: 'all' } | { type: 'author' | 'folder'; id: string };
function FolderButton({
label,
cover,
selected,
onClick,
}: {
label: string;
cover: ReactNode;
selected: boolean;
onClick: () => void;
}) {
return (
<Button
variant="outline"
aria-pressed={selected}
onClick={onClick}
className="wish-folders__item"
>
<span className="wish-folders__cover" aria-hidden="true">{cover}</span>
<span className="min-w-0 break-words text-left">{label}</span>
</Button>
);
}
export function DashboardPage() {
const { data, isLoading } = useWishes('active');
const [creating, setCreating] = useState(false);
const { t } = useI18n();
const { data, isPending, isError, refetch } = useWishDashboard();
const [selection, setSelection] = useState<Selection>({ type: 'all' });
const [hideCompleted, setHideCompleted] = useState(false);
const [creatingFolder, setCreatingFolder] = useState(false);
const [creatingWish, setCreatingWish] = useState(false);
const [editing, setEditing] = useState<Wish | null>(null);
const createFolderButton = useRef<HTMLButtonElement>(null);
const archive = useArchiveWish();
const complete = useCompleteWish();
const remove = useDeleteWish();
const user = useAuthStore((s) => s.user);
const duplicate = useDuplicateWish();
const user = useAuthStore((state) => state.user);
const selectedAuthor = selection.type === 'author'
? data?.authors.find(({ id }) => id === selection.id)
: undefined;
const selectedFolder = selection.type === 'folder'
? data?.folders.find(({ id }) => id === selection.id)
: undefined;
const folderWishes = data?.wishes.filter((wish) =>
selectedAuthor ? wish.userId === selectedAuthor.id && wish.showInAuthorFolder !== false
: selectedFolder ? (wish.folderIds?.includes(selectedFolder.id) ?? wish.folderId === selectedFolder.id)
: true,
);
const wishes = hideCompleted
? folderWishes?.filter(({ status }) => status !== 'COMPLETED')
: folderWishes;
const canAddWish = !selectedAuthor || selectedAuthor.id === user?.id;
const sectionTitle = selectedAuthor?.displayName ?? selectedFolder?.name ?? t('folders.all');
function closeFolderForm() {
setCreatingFolder(false);
createFolderButton.current?.focus();
}
return (
<div className="grid gap-6">
<section className="flex flex-wrap items-end justify-between gap-4">
<section className="page-section flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="font-display text-3xl">Your wishlist</h1>
<p className="text-sm text-muted">
Add things you dream of. Share your public page at{' '}
{user && (
<Link
to={`/u/${user.slug}`}
className="font-medium text-primary hover:text-primary-600"
>
/u/{user.slug}
</Link>
)}
.
</p>
<h1 className="page-section__title">{t('dashboard.title')}</h1>
{user && (
<Link
to={`/u/${user.slug}`}
className="mt-1 inline-block text-sm font-medium text-ink underline underline-offset-4 hover:decoration-primary"
>
{t('dashboard.publicPage')}
</Link>
)}
</div>
<Button size="lg" onClick={() => setCreating(true)}>
<Plus className="h-4 w-4" />
Add wish
</Button>
</section>
{isLoading && (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{[0, 1, 2].map((i) => (
<div
key={i}
className="wish-card animate-pulse"
style={{ minHeight: 320, background: 'rgb(var(--color-surface-muted))' }}
{data && (
<section className="wish-folders" aria-label={t('folders.title')}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="font-semibold text-ink">{t('folders.title')}</h2>
<Button
ref={createFolderButton}
variant="ghost"
aria-expanded={creatingFolder}
onClick={() => setCreatingFolder(true)}
>
<FolderPlus className="h-4 w-4" aria-hidden />
{t('folders.create')}
</Button>
</div>
<div className="wish-folders__list">
<FolderButton
label={t('folders.all')}
cover={<LayoutGrid className="h-4 w-4" />}
selected={!selectedAuthor && !selectedFolder}
onClick={() => setSelection({ type: 'all' })}
/>
{data.authors.map((author) => (
<FolderButton
key={author.id}
label={author.displayName}
cover={author.avatarUrl
? <img src={author.avatarUrl} alt="" />
: <UserRound className="h-4 w-4" />}
selected={selectedAuthor?.id === author.id}
onClick={() => setSelection({ type: 'author', id: author.id })}
/>
))}
{data.folders.map((folder) => (
<FolderButton
key={folder.id}
label={folder.name}
cover={folder.imageUrl
? <img src={folder.imageUrl} alt="" loading="lazy" />
: folder.emoji ?? <Folder className="h-4 w-4" />}
selected={selectedFolder?.id === folder.id}
onClick={() => setSelection({ type: 'folder', id: folder.id })}
/>
))}
</div>
{creatingFolder && (
<FolderForm
onCancel={closeFolderForm}
onCreated={(folder) => {
setSelection({ type: 'folder', id: folder.id });
closeFolderForm();
}}
/>
)}
</section>
)}
{isPending && (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true">
{[0, 1, 2].map((i) => (
<div key={i} className="wish-card min-h-80 animate-pulse bg-surface-muted" />
))}
</div>
)}
{!isLoading && data && data.length === 0 && (
<div className="flex flex-col items-center gap-4 rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card">
<img src="/empty-state.svg" alt="" className="h-40 w-40 opacity-90" />
<div>
<h2 className="text-xl font-semibold">No wishes yet</h2>
<p className="mt-1 text-sm text-muted">
Start by adding something you'd love to receive.
</p>
</div>
<Button onClick={() => setCreating(true)}>
<Sparkles className="h-4 w-4" />
Add your first wish
{isError && (
<div className="empty-state gap-4">
<p role="alert" className="empty-state__text">{t('dashboard.loadError')}</p>
<Button variant="outline" onClick={() => void refetch()}>
{t('dashboard.retry')}
</Button>
</div>
)}
{!isLoading && data && data.length > 0 && (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
{data.map((wish) => (
<WishCard
key={wish.id}
wish={wish}
view="owner"
onEdit={() => setEditing(wish)}
onArchive={() => archive.mutate(wish.id)}
onComplete={() => complete.mutate(wish.id)}
onDelete={() => remove.mutate(wish.id)}
/>
))}
</div>
{wishes && (
<section className="grid min-w-0 gap-4" aria-label={sectionTitle}>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<h2 className="break-words text-xl font-semibold text-ink">{sectionTitle}</h2>
{selectedFolder?.description && (
<p className="mt-1 whitespace-pre-wrap break-words text-sm text-muted">
{selectedFolder.description}
</p>
)}
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<label className="wish-checkbox">
<input
type="checkbox"
checked={hideCompleted}
onChange={(event) => setHideCompleted(event.target.checked)}
/>
<span>{t('dashboard.hideCompleted')}</span>
</label>
{canAddWish && (
<Button onClick={() => setCreatingWish(true)}>
<Plus className="h-4 w-4" aria-hidden />
{t('dashboard.addWish')}
</Button>
)}
</div>
</div>
{wishes.length === 0 ? (
<div className="empty-state">
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
<h3 className="empty-state__title">
{t(folderWishes?.length ? 'dashboard.completedHidden' : 'dashboard.emptyTitle')}
</h3>
</div>
) : (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
{wishes.map((wish) => {
const owned = wish.userId === user?.id;
const author = data?.authors.find(({ id }) => id === wish.userId);
return (
<WishCard
key={wish.id}
wish={wish}
view={owned ? 'owner' : 'guest'}
onEdit={() => setEditing(wish)}
onArchive={() => archive.mutate(wish.id)}
onComplete={() => complete.mutate(wish.id)}
onDelete={() => remove.mutate(wish.id)}
onDuplicate={() => duplicate.mutate(wish.id)}
footer={!selectedAuthor && author && (
<p className="mt-auto break-words pt-2 text-xs text-muted">
{author.displayName}
</p>
)}
/>
);
})}
</div>
)}
</section>
)}
<WishForm open={creating} mode="create" onClose={() => setCreating(false)} />
<WishForm
open={editing !== null}
mode="edit"
initial={editing ?? undefined}
onClose={() => setEditing(null)}
/>
{creatingWish && user && (
<WishForm
mode="create"
authorName={user.displayName}
folders={data?.folders}
defaultFolderId={selectedFolder?.id}
onClose={() => setCreatingWish(false)}
/>
)}
{editing && user && (
<WishForm
mode="edit"
authorName={user.displayName}
initial={editing}
folders={data?.folders}
onClose={() => setEditing(null)}
/>
)}
</div>
);
}
+22 -12
View File
@@ -11,8 +11,11 @@ import { Label } from '@/components/ui/Label';
import { useAuthStore } from '@/features/auth/authStore';
import { ApiError } from '@/lib/api';
import { Footer } from '@/components/Layout/Footer';
import { LanguageSwitcher } from '@/components/LanguageSwitcher';
import { translateValidation, useI18n } from '@/i18n/i18n';
export function LoginPage() {
const { t } = useI18n();
const { user, login } = useAuthStore();
const navigate = useNavigate();
const location = useLocation();
@@ -39,29 +42,32 @@ export function LoginPage() {
navigate(from, { replace: true });
} catch (err) {
if (err instanceof ApiError) toast.error(err.message);
else toast.error('Login failed');
else toast.error(t('login.failed'));
}
});
return (
<div className="flex min-h-screen flex-col">
<div className="container-page flex flex-1 items-center justify-center py-12">
<div className="app-shell">
<div className="public-profile__toolbar">
<LanguageSwitcher />
</div>
<div className="app-shell__main flex items-center justify-center py-12">
<div className="w-full max-w-md animate-fade-in-up">
<div className="mb-6 flex items-center justify-center gap-2">
<span className="inline-flex h-11 w-11 items-center justify-center rounded-md bg-primary text-primary-foreground shadow-card">
<Gift className="h-5 w-5" />
</span>
<h1 className="font-display text-3xl">Family Wishlist</h1>
<h1 className="font-display text-3xl">{t('app.name')}</h1>
</div>
<div className="rounded-xl border border-border bg-surface p-6 shadow-card sm:p-8">
<h2 className="mb-1 text-xl font-semibold">Welcome back</h2>
<div className="profile-form p-6 sm:p-8">
<h2 className="mb-1 text-xl font-semibold">{t('login.title')}</h2>
<p className="mb-6 text-sm text-muted">
Sign in to manage your wishlist. Credentials are set up via the server environment.
{t('login.description')}
</p>
<form className="grid gap-4" onSubmit={submit}>
<div className="field">
<Label htmlFor="username">Username</Label>
<Label htmlFor="username">{t('login.username')}</Label>
<Input
id="username"
autoComplete="username"
@@ -69,11 +75,13 @@ export function LoginPage() {
{...register('username')}
/>
{errors.username && (
<span className="field__error">{errors.username.message}</span>
<span className="field__error">
{translateValidation(t, errors.username.message)}
</span>
)}
</div>
<div className="field">
<Label htmlFor="password">Password</Label>
<Label htmlFor="password">{t('login.password')}</Label>
<Input
id="password"
type="password"
@@ -81,12 +89,14 @@ export function LoginPage() {
{...register('password')}
/>
{errors.password && (
<span className="field__error">{errors.password.message}</span>
<span className="field__error">
{translateValidation(t, errors.password.message)}
</span>
)}
</div>
<Button type="submit" size="lg" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
Sign in
{t('login.submit')}
</Button>
</form>
</div>
+6 -4
View File
@@ -1,14 +1,16 @@
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { useI18n } from '@/i18n/i18n';
export function NotFoundPage() {
const { t } = useI18n();
return (
<div className="flex min-h-screen items-center justify-center p-6">
<div className="max-w-md rounded-xl border border-border bg-surface p-8 text-center shadow-card">
<div className="app-shell items-center justify-center p-6">
<div className="empty-state max-w-md bg-surface p-8">
<h1 className="font-display text-4xl">404</h1>
<p className="mt-2 text-muted">We couldn't find that page.</p>
<p className="mt-2 text-muted">{t('notFound.text')}</p>
<Link to="/" className="mt-4 inline-block">
<Button variant="secondary">Back to home</Button>
<Button variant="secondary">{t('common.backHome')}</Button>
</Link>
</div>
</div>
+124 -23
View File
@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
@@ -8,17 +8,24 @@ import {
type Profile,
} from '@family-wishlist/shared';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { Gift, Loader2, Upload } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Label } from '@/components/ui/Label';
import { Textarea } from '@/components/ui/Textarea';
import { api, ApiError } from '@/lib/api';
import { useAuthStore } from '@/features/auth/authStore';
import { translateValidation, useI18n } from '@/i18n/i18n';
const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
const AVATAR_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
export function ProfileSettingsPage() {
const { t } = useI18n();
const refresh = useAuthStore((s) => s.refresh);
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [avatarFailed, setAvatarFailed] = useState(false);
const { data, isLoading } = useQuery({
queryKey: ['profile'],
@@ -29,6 +36,7 @@ export function ProfileSettingsPage() {
register,
handleSubmit,
reset,
watch,
formState: { errors, isSubmitting, isDirty },
} = useForm<UpdateProfileInput>({
resolver: zodResolver(updateProfileSchema),
@@ -50,7 +58,7 @@ export function ProfileSettingsPage() {
mutationFn: (values: UpdateProfileInput) =>
api.patch<Profile, UpdateProfileInput>('/api/profile', values),
onSuccess: (p) => {
toast.success('Profile saved');
toast.success(t('profile.saved'));
void queryClient.invalidateQueries({ queryKey: ['profile'] });
void refresh();
reset({
@@ -62,10 +70,46 @@ export function ProfileSettingsPage() {
},
onError: (err) => {
if (err instanceof ApiError) toast.error(err.message);
else toast.error('Save failed');
else toast.error(t('profile.saveFailed'));
},
});
const uploadAvatar = useMutation({
mutationFn: (file: File) => {
const form = new FormData();
form.append('file', file);
return api.upload<Profile>('/api/profile/avatar', form);
},
onSuccess: (p) => {
toast.success(t('profile.avatarUploaded'));
void queryClient.invalidateQueries({ queryKey: ['profile'] });
void refresh();
reset({
slug: p.slug,
displayName: p.displayName,
bio: p.bio ?? '',
avatarUrl: p.avatarUrl ?? '',
});
},
onError: (err) => {
if (err instanceof ApiError) toast.error(err.message);
else toast.error(t('profile.saveFailed'));
},
});
function handleAvatarFile(file: File | undefined): void {
if (!file) return;
if (!AVATAR_MIME_TYPES.has(file.type)) {
toast.error(t('profile.avatarUnsupported'));
return;
}
if (file.size > MAX_AVATAR_BYTES) {
toast.error(t('profile.avatarTooLarge'));
return;
}
uploadAvatar.mutate(file);
}
const submit = handleSubmit((values) => {
const payload: UpdateProfileInput = {
...values,
@@ -75,43 +119,100 @@ export function ProfileSettingsPage() {
update.mutate(payload);
});
const avatarPreview = watch('avatarUrl') || data?.avatarUrl;
useEffect(() => {
setAvatarFailed(false);
}, [avatarPreview]);
return (
<div className="grid max-w-2xl gap-6">
<section>
<h1 className="font-display text-3xl">Profile</h1>
<p className="text-sm text-muted">
Your public page lives at <code className="rounded bg-ink/5 px-1.5 py-0.5">/u/{data?.slug ?? '...'}</code>.
<section className="page-section">
<h1 className="page-section__title">{t('profile.title')}</h1>
<p className="page-section__text">
{t('profile.publicPage')}
<code className="rounded bg-ink/5 px-1.5 py-0.5">/u/{data?.slug ?? '...'}</code>.
</p>
</section>
{isLoading ? (
<div className="text-muted">Loading...</div>
<div className="text-muted">{t('common.loading')}</div>
) : (
<form className="grid gap-4 rounded-xl border border-border bg-surface p-6 shadow-card" onSubmit={submit}>
<form className="profile-form" onSubmit={submit}>
<section className="profile-form__avatar-panel">
<span className="profile-form__avatar-preview">
{avatarPreview && !avatarFailed ? (
<img
src={avatarPreview}
alt=""
className="profile-form__avatar-image"
onError={() => setAvatarFailed(true)}
/>
) : (
<Gift className="h-6 w-6" />
)}
</span>
<div className="profile-form__avatar-copy">
<h2 className="profile-form__avatar-title">{t('profile.avatar')}</h2>
<p className="profile-form__avatar-hint">{t('profile.avatarHint')}</p>
</div>
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/gif"
className="hidden"
onChange={(e) => {
handleAvatarFile(e.target.files?.[0]);
e.currentTarget.value = '';
}}
/>
<Button
type="button"
variant="secondary"
onClick={() => fileInputRef.current?.click()}
disabled={uploadAvatar.isPending}
>
{uploadAvatar.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Upload className="h-4 w-4" />
)}
{t('profile.uploadAvatar')}
</Button>
</section>
<div className="field">
<Label htmlFor="slug">Slug (public URL)</Label>
<Label htmlFor="slug">{t('profile.slug')}</Label>
<Input id="slug" {...register('slug')} />
{errors.slug && <span className="field__error">{errors.slug.message}</span>}
</div>
<div className="field">
<Label htmlFor="displayName">Display name</Label>
<Input id="displayName" {...register('displayName')} />
{errors.displayName && (
<span className="field__error">{errors.displayName.message}</span>
{errors.slug && (
<span className="field__error">{translateValidation(t, errors.slug.message)}</span>
)}
</div>
<div className="field">
<Label htmlFor="bio">Bio</Label>
<Label htmlFor="displayName">{t('profile.displayName')}</Label>
<Input id="displayName" {...register('displayName')} />
{errors.displayName && (
<span className="field__error">
{translateValidation(t, errors.displayName.message)}
</span>
)}
</div>
<div className="field">
<Label htmlFor="bio">{t('profile.bio')}</Label>
<Textarea id="bio" rows={3} {...register('bio')} />
</div>
<div className="field">
<Label htmlFor="avatarUrl">Avatar URL</Label>
<Input id="avatarUrl" type="url" {...register('avatarUrl')} />
<Label htmlFor="avatarUrl">{t('profile.avatarUrl')}</Label>
<Input id="avatarUrl" inputMode="url" {...register('avatarUrl')} />
{errors.avatarUrl && (
<span className="field__error">
{translateValidation(t, errors.avatarUrl.message)}
</span>
)}
</div>
<div className="flex items-center justify-end gap-2">
<div className="profile-form__actions">
<Button type="submit" disabled={!isDirty || isSubmitting}>
{isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
Save changes
{t('common.saveChanges')}
</Button>
</div>
</form>
+45 -19
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef } from 'react';
import { useParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type {
PublicProfile,
@@ -9,10 +9,17 @@ import { api } from '@/lib/api';
import { WishCard } from '@/components/WishCard/WishCard';
import { Footer } from '@/components/Layout/Footer';
import { Gift } from 'lucide-react';
import { LanguageSwitcher } from '@/components/LanguageSwitcher';
import { useI18n } from '@/i18n/i18n';
import { useAuthStore } from '@/features/auth/authStore';
import { Button } from '@/components/ui/Button';
export function PublicProfilePage() {
const { t } = useI18n();
const user = useAuthStore((s) => s.user);
const { slug = '' } = useParams<{ slug: string }>();
const queryClient = useQueryClient();
const [avatarFailed, setAvatarFailed] = useState(false);
const profile = useQuery({
queryKey: ['public-profile', slug],
@@ -51,46 +58,65 @@ export function PublicProfilePage() {
return () => window.clearTimeout(t);
}, [wishes.data, markSeen, queryClient, slug]);
useEffect(() => {
setAvatarFailed(false);
}, [profile.data?.avatarUrl]);
return (
<div className="flex min-h-screen flex-col">
<main className="container-page flex-1 py-10">
{profile.isLoading && <div className="text-muted">Loading...</div>}
<div className="public-profile">
<div className="public-profile__toolbar">
{user ? (
<Link to="/">
<Button variant="secondary" size="sm">
{t('public.backToMine')}
</Button>
</Link>
) : (
<span />
)}
<LanguageSwitcher />
</div>
<main className="public-profile__main">
{profile.isLoading && <div className="text-muted">{t('common.loading')}</div>}
{profile.isError && (
<div className="mx-auto max-w-lg rounded-xl border border-border bg-surface p-8 text-center shadow-card">
<h1 className="font-display text-2xl">Profile not found</h1>
<p className="mt-2 text-sm text-muted">
Check the link and try again. Slugs are case-sensitive.
<div className="empty-state mx-auto max-w-lg bg-surface p-8">
<h1 className="empty-state__title">{t('public.notFoundTitle')}</h1>
<p className="empty-state__text mt-2">
{t('public.notFoundText')}
</p>
</div>
)}
{profile.data && (
<>
<section className="mb-10 flex flex-col items-center gap-3 text-center">
<span className="inline-flex h-14 w-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-card">
{profile.data.avatarUrl ? (
<section className="public-profile__hero">
<span className="public-profile__avatar">
{profile.data.avatarUrl && !avatarFailed ? (
<img
src={profile.data.avatarUrl}
alt=""
className="h-14 w-14 rounded-full object-cover"
className="public-profile__avatar-image"
onError={() => setAvatarFailed(true)}
/>
) : (
<Gift className="h-6 w-6" />
)}
</span>
<h1 className="font-display text-4xl">{profile.data.displayName}'s wishlist</h1>
<h1 className="public-profile__title">
{t('public.wishlistTitle', { name: profile.data.displayName })}
</h1>
{profile.data.bio && (
<p className="max-w-xl text-muted">{profile.data.bio}</p>
<p className="public-profile__bio">{profile.data.bio}</p>
)}
</section>
{wishes.isLoading && <div className="text-muted">Loading wishes...</div>}
{wishes.isLoading && <div className="text-muted">{t('public.loadingWishes')}</div>}
{wishes.data && wishes.data.length === 0 && (
<div className="mx-auto max-w-lg rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card">
<h2 className="text-xl font-semibold">No wishes yet</h2>
<p className="mt-1 text-sm text-muted">Check back later!</p>
<div className="empty-state mx-auto max-w-lg">
<h2 className="empty-state__title">{t('public.emptyTitle')}</h2>
<p className="empty-state__text mt-1">{t('public.emptyText')}</p>
</div>
)}
+14 -10
View File
@@ -3,27 +3,31 @@ import { TRASH_RETENTION_DAYS } from '@family-wishlist/shared';
import { WishCard } from '@/components/WishCard/WishCard';
import { useRestoreWish, useWishes } from '@/features/wishes/wishes.hooks';
import { daysLeftUntil } from '@/lib/format';
import { useI18n } from '@/i18n/i18n';
export function TrashPage() {
const { dayCount, t } = useI18n();
const { data, isLoading } = useWishes('deleted');
const restore = useRestoreWish();
return (
<div className="grid gap-6">
<section>
<h1 className="font-display text-3xl">Trash</h1>
<p className="text-sm text-muted">
Deleted wishes are kept for {TRASH_RETENTION_DAYS} days, then permanently removed.
<section className="page-section">
<h1 className="page-section__title">{t('trash.title')}</h1>
<p className="page-section__text">
{t('trash.description', { days: dayCount(TRASH_RETENTION_DAYS) })}
</p>
</section>
{isLoading && <div className="text-muted">Loading...</div>}
{isLoading && <div className="text-muted">{t('common.loading')}</div>}
{!isLoading && data && data.length === 0 && (
<div className="flex flex-col items-center gap-2 rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card">
<Trash2 className="h-10 w-10 text-muted" />
<h2 className="text-xl font-semibold">Trash is empty</h2>
<p className="text-sm text-muted">Deleted wishes will appear here for 30 days.</p>
<div className="empty-state">
<Trash2 className="empty-state__icon" />
<h2 className="empty-state__title">{t('trash.emptyTitle')}</h2>
<p className="empty-state__text">
{t('trash.emptyText', { days: dayCount(TRASH_RETENTION_DAYS) })}
</p>
</div>
)}
@@ -41,7 +45,7 @@ export function TrashPage() {
onRestore={() => restore.mutate(wish.id)}
footer={
<p className="mt-2 text-xs font-medium text-warning">
Auto-removes in {left} day{left === 1 ? '' : 's'}
{t('trash.autoRemove', { days: dayCount(left) })}
</p>
}
/>
+215
View File
@@ -29,6 +29,221 @@
@layer components {
/* BEM-friendly classes: kept parallel to Tailwind utilities where possible. */
.app-shell {
@apply flex min-h-screen flex-col;
}
.app-shell__main {
@apply mx-auto w-full max-w-6xl flex-1 px-4 py-6 sm:px-6 sm:py-10 lg:px-8;
}
.app-header {
@apply mx-auto w-full max-w-6xl px-4 pt-6 sm:px-6 lg:px-8;
}
.app-header__inner {
@apply flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-surface/80 px-4 py-3 backdrop-blur;
}
.app-header__brand {
@apply flex min-w-0 items-center gap-2;
}
.app-header__brand-mark {
@apply inline-flex h-9 w-9 items-center justify-center rounded-md bg-primary text-primary-foreground shadow-card;
}
.app-header__brand-title {
@apply font-display text-lg leading-tight;
}
.app-header__brand-subtitle {
@apply truncate text-xs text-muted;
}
.app-header__nav {
@apply mt-3 flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap rounded-lg border border-border bg-surface/80 px-4 py-2 backdrop-blur;
}
.app-header__nav-link {
@apply inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium text-ink transition-colors hover:bg-ink/5;
}
.app-header__nav-link--active {
@apply bg-primary text-primary-foreground shadow-card hover:bg-primary;
}
.app-header__actions {
@apply flex shrink-0 items-center gap-1 whitespace-nowrap;
}
.app-header__action {
@apply shrink-0;
}
.app-header__action-text {
@apply hidden xl:inline;
}
.app-footer {
@apply mx-auto mt-10 w-full max-w-6xl px-4 py-6 text-xs text-muted sm:px-6 lg:px-8;
}
.app-footer__inner {
@apply flex flex-col items-center justify-between gap-2 sm:flex-row;
}
.app-footer__brand {
@apply flex items-center gap-2;
}
.app-footer__brand-name {
@apply font-display text-sm;
}
.app-footer__meta {
@apply flex items-center gap-3;
}
.app-footer__separator {
@apply opacity-50;
}
.language-switcher {
@apply inline-flex items-center gap-1 rounded-md border border-border bg-surface/90 p-1 text-xs shadow-card;
}
.language-switcher__icon {
@apply ml-1 h-3.5 w-3.5 text-muted;
}
.language-switcher__button {
@apply rounded px-2 py-1 font-semibold text-muted transition-colors hover:bg-surface-muted hover:text-ink;
}
.language-switcher__button--active {
@apply bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground;
}
.empty-state {
@apply flex flex-col items-center gap-2 rounded-xl border border-border bg-surface/80 p-10 text-center shadow-card;
}
.empty-state__icon {
@apply h-10 w-10 text-muted;
}
.empty-state__icon--image {
@apply h-40 w-40 opacity-90;
}
.empty-state__title {
@apply text-xl font-semibold;
}
.empty-state__text {
@apply text-sm text-muted;
}
.page-section {
@apply grid gap-1;
}
.page-section__title {
@apply font-display text-3xl;
}
.page-section__text {
@apply text-sm text-muted;
}
.wish-folders {
@apply grid min-w-0 gap-3 border-b border-border pb-5;
}
.wish-folders__list {
@apply flex flex-wrap gap-2;
}
.wish-folders .wish-folders__item {
@apply h-auto min-h-11 max-w-full justify-start px-2.5 py-1.5 pr-3;
}
.wish-folders__item[aria-pressed='true'] {
@apply border-primary bg-primary/10 text-ink;
}
.wish-folders__cover {
@apply grid h-7 w-7 shrink-0 place-items-center overflow-hidden rounded-sm bg-surface-muted text-base;
}
.wish-folders__cover img {
@apply h-full w-full object-cover;
}
.wish-folders__form {
@apply grid min-w-0 max-w-xl gap-4 rounded-md border border-border bg-surface p-4;
}
.wish-checkbox {
@apply inline-flex min-h-9 min-w-0 cursor-pointer items-center gap-2 text-sm text-ink;
overflow-wrap: anywhere;
}
.wish-checkbox input {
@apply h-4 w-4 shrink-0 accent-primary;
}
.public-profile {
@apply flex min-h-screen flex-col;
}
.public-profile__toolbar {
@apply mx-auto flex w-full max-w-6xl items-center justify-between gap-3 px-4 pt-6 sm:px-6 lg:px-8;
}
.public-profile__main {
@apply mx-auto w-full max-w-6xl flex-1 px-4 py-10 sm:px-6 lg:px-8;
}
.public-profile__hero {
@apply mb-10 flex flex-col items-center gap-3 text-center;
}
.public-profile__avatar {
@apply inline-flex h-14 w-14 items-center justify-center overflow-hidden rounded-full bg-primary text-primary-foreground shadow-card;
}
.public-profile__avatar-image {
@apply h-14 w-14 rounded-full object-cover;
}
.public-profile__title {
@apply font-display text-4xl;
}
.public-profile__bio {
@apply max-w-xl text-muted;
}
.profile-form {
@apply grid gap-4 rounded-xl border border-border bg-surface p-6 shadow-card;
}
.profile-form__avatar-panel {
@apply flex flex-wrap items-center gap-4 rounded-md border border-border bg-surface-muted p-4;
}
.profile-form__avatar-preview {
@apply inline-flex h-16 w-16 items-center justify-center overflow-hidden rounded-full bg-primary text-primary-foreground;
}
.profile-form__avatar-image {
@apply h-16 w-16 object-cover;
}
.profile-form__avatar-copy {
@apply min-w-0 flex-1;
}
.profile-form__avatar-title {
@apply text-sm font-semibold;
}
.profile-form__avatar-hint {
@apply text-xs text-muted;
}
.profile-form__actions {
@apply flex items-center justify-end gap-2;
}
.modal {
@apply fixed inset-0 z-50 flex items-end justify-center p-0 sm:items-center sm:p-6;
}
.modal__backdrop {
@apply absolute inset-0 animate-fade-in-up bg-ink/40 backdrop-blur-sm;
}
.modal__panel {
@apply relative flex max-h-[90vh] w-full animate-fade-in-up flex-col overflow-hidden rounded-t-xl bg-surface shadow-pop sm:rounded-xl;
}
.modal__panel--md {
@apply sm:max-w-lg;
}
.modal__panel--lg {
@apply sm:max-w-2xl;
}
.modal__header {
@apply flex items-start justify-between gap-4 border-b border-border px-5 py-4;
}
.modal__title-wrap {
@apply min-w-0;
}
.modal__title {
@apply text-lg font-semibold text-ink;
}
.modal__description {
@apply mt-1 text-sm text-muted;
}
.modal__body {
@apply overflow-y-auto px-5 py-5;
}
.modal__footer {
@apply flex items-center justify-end gap-2 border-t border-border px-5 py-4;
}
.wish-card {
@apply relative flex flex-col overflow-hidden rounded-lg bg-surface shadow-card transition-transform duration-200;
}
+1 -1
View File
@@ -38,7 +38,7 @@ services:
family-wishlist-backend:
condition: service_healthy
ports:
- "8080:80"
- "3055:80"
networks:
- postgres_default
+1 -1
View File
@@ -49,4 +49,4 @@ WORKDIR /app/apps/backend
EXPOSE 3000
# Apply schema (idempotent; uses `db push` so no prior migrations required) +
# seed env users + start server.
CMD ["sh", "-c", "pnpm exec prisma db push --accept-data-loss --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
CMD ["sh", "-c", "pnpm exec prisma db push --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
+8 -8
View File
@@ -4,13 +4,6 @@ server {
root /usr/share/nginx/html;
index index.html;
# Static files with long cache
location ~* \.(?:js|css|woff2?|svg|png|jpg|jpeg|gif|webp|ico)$ {
expires 7d;
add_header Cache-Control "public";
try_files $uri =404;
}
# API proxy
location /api/ {
proxy_pass http://family-wishlist-backend:3000/api/;
@@ -24,13 +17,20 @@ server {
}
# Uploaded files (images)
location /uploads/ {
location ^~ /uploads/ {
proxy_pass http://family-wishlist-backend:3000/uploads/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_cache_valid 200 1h;
}
# Static files with long cache
location ~* \.(?:js|css|woff2?|svg|png|jpg|jpeg|gif|webp|ico)$ {
expires 7d;
add_header Cache-Control "public";
try_files $uri =404;
}
# SPA fallback
location / {
try_files $uri /index.html;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/shared",
"version": "0.1.0",
"version": "0.5.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
+29
View File
@@ -0,0 +1,29 @@
import { z } from 'zod';
import type { Wish } from './wish.schema.js';
export const createFolderSchema = z.object({
name: z.string().trim().min(1).max(80),
description: z.string().trim().max(500).optional(),
emoji: z
.string()
.trim()
.max(32)
.regex(/^(?:(?:\p{Extended_Pictographic}|\p{Regional_Indicator})[\p{Extended_Pictographic}\p{Regional_Indicator}\p{Emoji_Modifier}\uFE0F\u200D]*|[#*0-9]\uFE0F?\u20E3)$/u)
.optional(),
});
export type CreateFolderInput = z.infer<typeof createFolderSchema>;
export interface WishFolder {
id: string;
name: string;
description: string | null;
emoji: string | null;
imageUrl: string | null;
}
export interface WishDashboard {
authors: { id: string; displayName: string; avatarUrl: string | null }[];
folders: WishFolder[];
wishes: (Wish & { userId: string; isNewForOwner: boolean })[];
}
+1
View File
@@ -1,5 +1,6 @@
export * from './auth.schema.js';
export * from './profile.schema.js';
export * from './wish.schema.js';
export * from './folder.schema.js';
export * from './public.schema.js';
export * from './types.js';
+22 -1
View File
@@ -15,6 +15,14 @@ export const profileSchema = z.object({
export type Profile = z.infer<typeof profileSchema>;
export const friendProfileSchema = z.object({
slug: z.string(),
displayName: z.string(),
avatarUrl: z.string().nullable(),
});
export type FriendProfile = z.infer<typeof friendProfileSchema>;
export const updateProfileSchema = z.object({
slug: z
.string()
@@ -24,7 +32,20 @@ export const updateProfileSchema = z.object({
.optional(),
displayName: z.string().trim().min(1).max(64).optional(),
bio: z.string().trim().max(500).nullable().optional(),
avatarUrl: z.string().url().nullable().optional(),
avatarUrl: z
.preprocess(
(value) => (value === '' ? null : value),
z
.string()
.refine(
(value) => value.startsWith('/uploads/avatar/') || z.string().url().safeParse(value).success,
{
message: 'Avatar must be a URL or an uploaded avatar path',
},
)
.nullable(),
)
.optional(),
});
export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
+6
View File
@@ -22,12 +22,18 @@ export const wishSchema = z.object({
completedAt: z.string().nullable(),
deletedAt: z.string().nullable(),
sourceWishId: z.string().nullable(),
folderId: z.string().nullable().optional(),
folderIds: z.array(z.string()).optional(),
showInAuthorFolder: z.boolean().optional(),
isNewForGuest: z.boolean().optional(),
});
export type Wish = z.infer<typeof wishSchema>;
export const createWishSchema = z.object({
folderId: z.string().cuid().nullable().optional(),
folderIds: z.array(z.string().cuid()).optional(),
showInAuthorFolder: z.boolean().optional(),
title: z.string().trim().min(1).max(200),
price: z
.union([