Compare commits

...
12 Commits
28 changed files with 1102 additions and 189 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
name: CI
on:
pull_request:
branches: [main]
types: [edited]
jobs:
verify:
if: >-
contains(github.event.pull_request.body, format('CI-Head: {0}', github.event.pull_request.head.sha))
runs-on: ubuntu-latest
container: node:20-bookworm
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install dependencies and build
run: |
corepack enable
pnpm install --frozen-lockfile
pnpm --filter @family-wishlist/backend prisma:generate
pnpm build
+55
View File
@@ -0,0 +1,55 @@
name: Publish images
on:
push:
branches: [main]
jobs:
images:
if: github.server_url == 'https://git.vakanaut.ru' && github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository == 'admin/family_wishlist'
runs-on: home-publish
strategy:
matrix:
include:
- component: backend
dockerfile: docker/backend.Dockerfile
- component: frontend
dockerfile: docker/frontend.Dockerfile
env:
REGISTRY: git.vakanaut.ru
COMPONENT: ${{ matrix.component }}
DOCKERFILE: ${{ matrix.dockerfile }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Publish Docker image and record its digest
shell: bash
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
REGISTRY_OWNER: ${{ vars.REGISTRY_OWNER }}
run: |
set -euo pipefail
: "${REGISTRY_USERNAME:?set REGISTRY_USERNAME}"
: "${REGISTRY_TOKEN:?set REGISTRY_TOKEN}"
owner="${REGISTRY_OWNER:-$REGISTRY_USERNAME}"
[[ "$owner" =~ ^[a-z0-9][a-z0-9_-]*$ ]]
export DOCKER_CONFIG
DOCKER_CONFIG="$(mktemp -d)"
metadata="$(mktemp)"
trap 'rm -rf -- "$DOCKER_CONFIG"; rm -f -- "$metadata"' EXIT
image="$REGISTRY/$owner/family-wishlist-$COMPONENT"
printf '%s\n' "$REGISTRY_TOKEN" | docker login "$REGISTRY" --username "$REGISTRY_USERNAME" --password-stdin
docker buildx build --file "$DOCKERFILE" --tag "$image:$GITHUB_SHA" \
--label "org.opencontainers.image.revision=$GITHUB_SHA" \
--label "org.opencontainers.image.source=$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" \
--metadata-file "$metadata" --push .
digest="$(jq -er '."containerimage.digest" | select(test("^sha256:[a-f0-9]{64}$"))' "$metadata")"
printf '%s\n' "$image@$digest"
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
printf '%s\n' "$image@$digest" >> "$GITHUB_STEP_SUMMARY"
fi
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## Unreleased
- CI builds the final pull request commit before merge. A separate workflow publishes backend and frontend images after merge to main.
## 0.6.0
- Both signed-in users can rename, update the description of, and delete shared folders. Deleting a folder preserves its wishes and their other assignments.
- Both users’ fulfilled wishes move to the permanent Fulfilled folder on the dashboard. All and the other dashboard folders show active wishes. Existing `/completed` links open the permanent folder.
- A categorized emoji picker displays the selected emoji in the folder creation form and on the saved folder cover.
+22 -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, in separate views for active and fulfilled wishes. Active wishes can be filtered by author or shared folder. 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 signed-in user can create, rename, update the description of, or delete a shared folder. When creating a folder, choose an emoji from the category picker or upload an image. Deleting a folder removes its assignments and preserves its wishes. The wish author can assign active wishes to several shared folders and their own folder. All shows both users’ active wishes. Fulfilled wishes from both users automatically appear in the permanent Fulfilled folder.
- 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. |
@@ -211,6 +225,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
| POST | `/api/wishes/:id/archive` | owner | |
| POST | `/api/wishes/:id/complete` | owner | |
| POST | `/api/wishes/:id/restore` | owner | From archive or trash back to active. |
| PATCH | `/api/folders/:id` | signed in | Update a shared folder name or description. |
| DELETE | `/api/folders/:id` | signed in | Remove a shared folder and its assignments. Its wishes are retained. |
| POST | `/api/wishes/:id/duplicate` | owner | Copy fulfilled wish into a new active one. |
| POST | `/api/wishes/:id/image` | owner | Multipart image upload. |
| POST | `/api/wishes/:id/image/refresh-og` | owner | Re-fetch OG image from link. |
@@ -220,6 +236,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 +245,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.3.4 · backend v0.3.0
frontend v0.6.0 · backend v0.6.0
```
Bump them per semver on each change:
@@ -240,7 +258,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.3.0",
"version": "0.6.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' });
@@ -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,141 @@
import { randomUUID } from 'node:crypto';
import { Prisma } from '@prisma/client';
import type { FastifyInstance } from 'fastify';
import { createFolderSchema, NEW_BADGE_DAYS, updateFolderSchema } from '@family-wishlist/shared';
import { usersRegistry } from '../../auth/users.registry.js';
import { MAX_UPLOAD_BYTES } from '../../plugins/multipart.js';
import { NotFoundError, UnauthorizedError, ValidationError } from '../../utils/errors.js';
import { deleteLocalImageIfAny, saveUploadedImage } from '../images/storage.service.js';
import { includeWishFolders, withFolderIds } from './wishes.service.js';
const folderSelect = { id: true, name: true, description: true, emoji: true, imageUrl: true } as const;
function rethrowFolderError(error: unknown): never {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2025') {
throw new NotFoundError('Folder');
}
throw error;
}
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: folderSelect,
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.patch<{ Params: { id: string } }>('/folders/:id', async (request) => {
const input = updateFolderSchema.parse(request.body);
try {
return await app.prisma.wishFolder.update({
where: { id: request.params.id },
data: {
name: input.name,
description: input.description === undefined ? undefined : input.description || null,
},
select: folderSelect,
});
} catch (error) {
rethrowFolderError(error);
}
});
app.delete<{ Params: { id: string } }>('/folders/:id', async (request, reply) => {
try {
const { imageUrl } = await app.prisma.wishFolder.delete({
where: { id: request.params.id },
select: { imageUrl: true },
});
await deleteLocalImageIfAny(imageUrl);
return reply.code(204).send();
} catch (error) {
rethrowFolderError(error);
}
});
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: folderSelect,
});
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.3.4",
"version": "0.6.0",
"private": true,
"type": "module",
"scripts": {
@@ -1,5 +1,5 @@
import { Link, NavLink, useNavigate } from 'react-router-dom';
import { Archive, CheckCircle2, Gift, LogOut, Sparkles, Trash2, UserCog, Users } from 'lucide-react';
import { Archive, 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';
@@ -18,8 +18,7 @@ interface FriendProfile {
}
const links = [
{ to: '/', label: 'header.active', icon: Sparkles, end: true },
{ to: '/completed', label: 'header.fulfilled', icon: CheckCircle2 },
{ to: '/', label: 'header.home', icon: House, end: true },
{ to: '/archive', label: 'header.archive', icon: Archive },
{ to: '/trash', label: 'header.trash', icon: Trash2 },
] satisfies Array<{
@@ -57,8 +57,10 @@ function WishCardInner({
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: t('wish.action.edit'), onClick: onEdit });
if (onComplete)
actions.push({
key: 'complete',
@@ -0,0 +1,76 @@
import { useRef, useState } from 'react';
import { ChevronDown, Smile } from 'lucide-react';
import { useI18n } from '@/i18n/i18n';
import { Button } from '../ui/Button';
const categories = [
{ label: 'emoji.faces', icon: '😀', symbols: '😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😋 😜 🤪 🤩 🤗 🤭 🤫 🤔 😎 🥳 😴 🤓 🫠 😺 😻 🙈 🙉 🙊 👍 🙌 👏 🫶 ✨' },
{ label: 'emoji.nature', icon: '🌿', symbols: '🌿 🌱 🌵 🌴 🌳 🌲 🍀 🍁 🍂 🌻 🌷 🌸 🌺 🌼 🌹 🪴 🪷 🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼 🐨 🐯 🦁 🐮 🐸 🦄 🦋 🐝 🐢 🐬 🐳 🐙 🐧 ☀️ 🌙 ⭐ 🌈 ❄️' },
{ label: 'emoji.food', icon: '🍎', symbols: '🍎 🍐 🍋 🍌 🍉 🍇 🍓 🫐 🍒 🍑 🥭 🍍 🥑 🥕 🌽 🍄 🥐 🥖 🧀 🍔 🍟 🍕 🌮 🥗 🍝 🍜 🍣 🍱 🍦 🍰 🎂 🧁 🍫 🍪 🍩 ☕ 🍵 🧋 🍷 🥂' },
{ label: 'emoji.activities', icon: '⚽', symbols: '⚽ 🏀 🏈 ⚾ 🎾 🏐 🏓 🏸 🥊 🏹 🛹 🛼 🛷 ⛸️ 🎿 🏆 🥇 🎯 🎮 🕹️ 🎲 🧩 ♟️ 🎨 🖌️ 🎭 🎤 🎧 🎸 🎹 🥁 🎬 📸 📚 🚴 🧘 🏊' },
{ label: 'emoji.travel', icon: '✈️', symbols: '✈️ 🚗 🚕 🚌 🚎 🚲 🛵 🏍️ 🚅 🚁 🚀 🛸 ⛵ 🚢 🗺️ 🧭 ⛰️ 🏔️ 🏕️ ⛺ 🏖️ 🏝️ 🏜️ 🏞️ 🗻 🌋 🌅 🌌 🏠 🏡 🏰 🗼 🗽 🎡 🎢 🛝' },
{ label: 'emoji.objects', icon: '🎁', symbols: '🎁 🎈 🎉 🎊 🪄 🎀 🛍️ 🛒 💎 💍 👑 👓 👟 👠 👗 👚 🧥 🧢 🎒 🧳 💻 📱 ⌚ 🖥️ 🔋 💡 🕯️ 🪞 🛋️ 🪑 🛏️ 🧸 🧶 🧵 🛠️ 🔑 📔 ✏️ 💌 🧴' },
{ label: 'emoji.symbols', icon: '❤️', symbols: '❤️ 🧡 💛 💚 💙 💜 🖤 🤍 🤎 🩷 🩵 🩶 💖 💝 💕 💫 💯 🔥 ✅ ✔️ ♻️ ♾️ ☮️ ☯️ 🎵 🎶 ➕ ❗ ❓ 💬 💭 💤' },
] as const;
export function EmojiPicker({ value, onChange }: { value: string; onChange: (emoji: string) => void }) {
const { t } = useI18n();
const [open, setOpen] = useState(false);
const [active, setActive] = useState<(typeof categories)[number]>(categories[0]);
const trigger = useRef<HTMLButtonElement>(null);
const grid = useRef<HTMLDivElement>(null);
function close() {
setOpen(false);
trigger.current?.focus();
}
return (
<div className="field" onKeyDown={(event) => {
if (event.key === 'Escape' && open) {
event.preventDefault();
event.stopPropagation();
close();
}
}}>
<span id="folder-emoji-label" className="field__label">{t('folders.emoji')}</span>
<Button
ref={trigger}
variant="outline"
className="justify-between"
aria-labelledby="folder-emoji-label folder-emoji-value"
aria-expanded={open}
aria-controls={open ? 'folder-emoji-panel' : undefined}
onClick={() => setOpen(!open)}
>
<span id="folder-emoji-value" className="flex items-center gap-2">
{value ? <span className="emoji-picker__symbol">{value}</span> : <><Smile className="h-4 w-4" aria-hidden />{t('emoji.choose')}</>}
</span>
<ChevronDown className="h-4 w-4" aria-hidden />
</Button>
{open && (
<div id="folder-emoji-panel" className="emoji-picker">
<div className="emoji-picker__categories" role="group" aria-label={t('emoji.categories')}>
{categories.map((category) => (
<Button key={category.label} variant="ghost" className="emoji-picker__category" size="icon"
aria-label={t(category.label)} aria-pressed={category === active}
onClick={() => { setActive(category); if (grid.current) grid.current.scrollTop = 0; }}
>
<span className="emoji-picker__symbol" aria-hidden="true">{category.icon}</span>
</Button>
))}
</div>
<div ref={grid} className="emoji-picker__grid" role="group" aria-label={t(active.label)}>
{active.symbols.split(' ').map((emoji) => (
<Button key={emoji} variant="ghost" className="emoji-picker__option" size="icon"
aria-pressed={emoji === value} onClick={() => { onChange(emoji); close(); }}
>
<span className="emoji-picker__symbol">{emoji}</span>
</Button>
))}
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,113 @@
import { useState, type FormEvent } from 'react';
import { createFolderSchema, type WishFolder } from '@family-wishlist/shared';
import { FolderPlus } from 'lucide-react';
import { useCreateFolder, useUpdateFolder } 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';
import { EmojiPicker } from './EmojiPicker';
const coverTypes = 'image/jpeg,image/png,image/webp,image/gif';
export function FolderForm({
onCancel,
onSaved,
folder,
}: {
onCancel: () => void;
onSaved: (folder: WishFolder) => void;
folder?: WishFolder;
}) {
const { t } = useI18n();
const create = useCreateFolder();
const update = useUpdateFolder();
const pending = create.isPending || update.isPending;
const [emoji, setEmoji] = useState('');
const [coverType, setCoverType] = useState<'none' | 'emoji' | 'image'>('none');
const [error, setError] = useState<string>();
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (pending) return;
const form = new FormData(event.currentTarget);
const input = createFolderSchema.safeParse({
name: form.get('name'),
description: form.get('description'),
emoji: coverType === 'emoji' ? 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 {
const saved = folder
? await update.mutateAsync({ id: folder.id, input: { name: input.data.name, description: input.data.description } })
: await create.mutateAsync({ input: input.data, cover });
onSaved(saved);
} catch {
setError(t('folders.saveError'));
}
}
return (
<form className="wish-folders__form" onSubmit={submit} aria-busy={pending}>
<div className="field">
<Label htmlFor="folder-name">{t('folders.name')}</Label>
<Input id="folder-name" name="name" maxLength={80} defaultValue={folder?.name} autoFocus required />
</div>
<div className="field">
<Label htmlFor="folder-description">{t('folders.description')}</Label>
<Textarea id="folder-description" name="description" maxLength={500} rows={2} defaultValue={folder?.description ?? undefined} />
</div>
{!folder && <div className="grid items-start 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' && (
<EmojiPicker value={emoji} onChange={(value) => { setEmoji(value); setError(undefined); }} />
)}
{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={pending}>
{!folder && <FolderPlus className="h-4 w-4" aria-hidden />}
{t(folder ? 'common.save' : 'folders.create')}
</Button>
<Button variant="ghost" onClick={onCancel} disabled={pending}>
{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';
@@ -18,13 +18,15 @@ import {
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();
@@ -33,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),
@@ -48,37 +49,31 @@ 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' ? t('wishForm.addTitle') : t('wishForm.editTitle')}
description={
@@ -102,12 +97,52 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
<form id="wish-form" className="grid gap-4" onSubmit={submit}>
<div className="field">
<Label htmlFor="title">{t('wishForm.title')}</Label>
<Input id="title" placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
<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">{t('wishForm.price')}</Label>
@@ -153,7 +188,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
</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" />
@@ -1,11 +1,19 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { CreateWishInput, UpdateWishInput } from '@family-wishlist/shared';
import type {
CreateFolderInput,
CreateWishInput,
UpdateFolderInput,
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'] });
@@ -24,6 +32,58 @@ 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 useUpdateFolder() {
const client = useQueryClient();
return useMutation({
mutationFn: ({ id, input }: { id: string; input: UpdateFolderInput }) =>
api.patch<WishFolder>(`/api/folders/${encodeURIComponent(id)}`, input),
onSuccess: (folder) => {
client.setQueryData<WishDashboard>(DASHBOARD_KEY, (current) =>
current && { ...current, folders: current.folders.map((item) => item.id === folder.id ? folder : item) },
);
void client.invalidateQueries({ queryKey: DASHBOARD_KEY });
},
});
}
export function useDeleteFolder() {
const client = useQueryClient();
return useMutation({
mutationFn: (id: string) => api.delete<void>(`/api/folders/${encodeURIComponent(id)}`),
onSuccess: () => client.invalidateQueries({ queryKey: DASHBOARD_KEY }),
});
}
export function useCreateWish() {
const client = useQueryClient();
const { t } = useI18n();
+66 -14
View File
@@ -29,7 +29,7 @@ const translations = {
'common.days.many': '{count} дней',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.active': 'Активные',
'header.home': 'Главная',
'header.fulfilled': 'Исполненные',
'header.archive': 'Архив',
'header.trash': 'Корзина',
@@ -44,18 +44,44 @@ const translations = {
'login.password': 'Пароль',
'login.submit': 'Войти',
'login.failed': 'Не удалось войти',
'dashboard.title': 'Ваш список желаний',
'dashboard.description': 'Добавляйте вещи, о которых мечтаете. Публичная страница доступна по адресу ',
'dashboard.title': 'Семейный список желаний',
'dashboard.publicPage': 'Моя публичная страница',
'dashboard.addWish': 'Добавить желание',
'dashboard.emptyTitle': 'Желаний пока нет',
'dashboard.emptyText': 'Начните с того, что вам действительно хочется получить.',
'dashboard.addFirstWish': 'Добавить первое желание',
'dashboard.loadError': 'Не удалось загрузить список желаний.',
'dashboard.retry': 'Повторить',
'folders.title': 'Папки желаний',
'folders.all': 'Все',
'folders.create': 'Создать папку',
'folders.edit': 'Редактировать',
'folders.delete': 'Удалить папку',
'folders.deleteDescription': 'Папка будет удалена у обоих пользователей. Желания из неё сохранятся.',
'folders.deleteError': 'Не удалось удалить папку. Попробуйте ещё раз.',
'emoji.choose': 'Выбрать эмодзи',
'emoji.categories': 'Категории эмодзи',
'emoji.faces': 'Лица и жесты',
'emoji.nature': 'Природа',
'emoji.food': 'Еда и напитки',
'emoji.activities': 'Занятия',
'emoji.travel': 'Путешествия',
'emoji.objects': 'Предметы',
'emoji.symbols': 'Символы',
'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': 'Корзина',
@@ -146,7 +172,7 @@ const translations = {
'common.days.many': '{count} days',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.active': 'Active',
'header.home': 'Home',
'header.fulfilled': 'Fulfilled',
'header.archive': 'Archive',
'header.trash': 'Trash',
@@ -161,18 +187,44 @@ const translations = {
'login.password': 'Password',
'login.submit': 'Sign in',
'login.failed': 'Login failed',
'dashboard.title': 'Your wishlist',
'dashboard.description': 'Add things you dream of. Share your public page at ',
'dashboard.title': 'Family wishlist',
'dashboard.publicPage': 'My public page',
'dashboard.addWish': 'Add wish',
'dashboard.emptyTitle': 'No wishes yet',
'dashboard.emptyText': "Start by adding something you'd love to receive.",
'dashboard.addFirstWish': 'Add your first wish',
'dashboard.loadError': "Couldn't load wishes.",
'dashboard.retry': 'Try again',
'folders.title': 'Wish folders',
'folders.all': 'All',
'folders.create': 'Create folder',
'folders.edit': 'Edit folder',
'folders.delete': 'Delete folder',
'folders.deleteDescription': 'This removes the folder for both users. Its wishes will remain.',
'folders.deleteError': 'Could not delete the folder. Try again.',
'emoji.choose': 'Choose an emoji',
'emoji.categories': 'Emoji categories',
'emoji.faces': 'Faces and gestures',
'emoji.nature': 'Nature',
'emoji.food': 'Food and drink',
'emoji.activities': 'Activities',
'emoji.travel': 'Travel',
'emoji.objects': 'Objects',
'emoji.symbols': 'Symbols',
'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': 'Active wishes appear in “All”. Once fulfilled, they move to “Fulfilled”.',
'folders.invalidDetails': 'Check the folder name and description.',
'folders.invalidEmoji': 'Choose an emoji for the cover.',
'folders.invalidImage': 'Choose a JPEG, PNG, WebP, or GIF file up to 8 MB.',
'folders.saveError': "Couldn't save 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',
-52
View File
@@ -1,52 +0,0 @@
import { CheckCircle2 } from 'lucide-react';
import { WishCard } from '@/components/WishCard/WishCard';
import {
useDeleteWish,
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 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">{t('common.loading')}</div>}
{!isLoading && data && data.length === 0 && (
<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>
)}
{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"
onDuplicate={() => duplicate.mutate(wish.id)}
onDelete={() => remove.mutate(wish.id)}
/>
))}
</div>
)}
</div>
);
}
+280 -62
View File
@@ -1,104 +1,322 @@
import { useState } from 'react';
import { Plus, Sparkles } from 'lucide-react';
import type { Wish } from '@family-wishlist/shared';
import { useRef, useState, type ReactNode } from 'react';
import { CheckCircle2, Folder, FolderPlus, LayoutGrid, Pencil, Plus, Trash2, UserRound } from 'lucide-react';
import type { Wish, WishFolder } from '@family-wishlist/shared';
import { Link, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { WishCard } from '@/components/WishCard/WishCard';
import { FolderForm } from '@/components/WishForm/FolderForm';
import { WishForm } from '@/components/WishForm/WishForm';
import {
useArchiveWish,
useCompleteWish,
useDeleteFolder,
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 { t } = useI18n();
const { data, isLoading } = useWishes('active');
const [creating, setCreating] = useState(false);
const { data, isPending, isError, refetch } = useWishDashboard();
const [selection, setSelection] = useState<Selection>({ type: 'all' });
const [params, setParams] = useSearchParams();
const showCompleted = params.get('folder') === 'completed';
const [editingFolderId, setEditingFolderId] = useState<string>();
const [folderToDelete, setFolderToDelete] = useState<WishFolder>();
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 removeFolder = useDeleteFolder();
const duplicate = useDuplicateWish();
const user = useAuthStore((state) => state.user);
const selectedAuthor = !showCompleted && selection.type === 'author'
? data?.authors.find(({ id }) => id === selection.id)
: undefined;
const selectedFolder = !showCompleted && selection.type === 'folder'
? data?.folders.find(({ id }) => id === selection.id)
: undefined;
const wishes = data?.wishes.filter((wish) => {
if (showCompleted) return wish.status === 'COMPLETED';
if (wish.status !== 'ACTIVE') return false;
if (selectedAuthor) return wish.userId === selectedAuthor.id && wish.showInAuthorFolder !== false;
if (selectedFolder) return wish.folderIds?.includes(selectedFolder.id) ?? wish.folderId === selectedFolder.id;
return true;
});
const canAddWish = !showCompleted && (!selectedAuthor || selectedAuthor.id === user?.id);
const sectionTitle = showCompleted
? t('header.fulfilled')
: selectedAuthor?.displayName ?? selectedFolder?.name ?? t('folders.all');
function selectFolder(next: Selection) {
setEditingFolderId(undefined);
setSelection(next);
if (showCompleted) setParams({});
}
function closeDeleteDialog() {
if (removeFolder.isPending) return;
setFolderToDelete(undefined);
removeFolder.reset();
}
function closeFolderForm() {
setCreatingFolder(false);
createFolderButton.current?.focus();
}
return (
<div className="grid gap-6">
<section className="page-section flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="page-section__title">{t('dashboard.title')}</h1>
<p className="page-section__text">
{t('dashboard.description')}
{user && (
<Link
to={`/u/${user.slug}`}
className="font-medium text-primary hover:text-primary-600"
>
/u/{user.slug}
</Link>
)}
.
</p>
{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" />
{t('dashboard.addWish')}
</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={() => { setEditingFolderId(undefined); 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={!showCompleted && !selectedAuthor && !selectedFolder}
onClick={() => selectFolder({ 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={() => selectFolder({ type: 'author', id: author.id })}
/>
))}
<FolderButton
label={t('header.fulfilled')}
cover={<CheckCircle2 className="h-4 w-4" />}
selected={showCompleted}
onClick={() => { setEditingFolderId(undefined); setParams({ folder: 'completed' }); }}
/>
{data.folders.map((folder) => (
<FolderButton
key={folder.id}
label={folder.name}
cover={folder.imageUrl
? <img src={folder.imageUrl} alt="" loading="lazy" />
: folder.emoji ? <span className="emoji-picker__symbol">{folder.emoji}</span>
: <Folder className="h-4 w-4" />}
selected={selectedFolder?.id === folder.id}
onClick={() => selectFolder({ type: 'folder', id: folder.id })}
/>
))}
</div>
{creatingFolder && (
<FolderForm
onCancel={closeFolderForm}
onSaved={(folder) => {
selectFolder({ 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 && (
{isError && (
<div className="empty-state gap-4">
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
<div>
<h2 className="empty-state__title">{t('dashboard.emptyTitle')}</h2>
<p className="empty-state__text mt-1">
{t('dashboard.emptyText')}
</p>
</div>
<Button onClick={() => setCreating(true)}>
<Sparkles className="h-4 w-4" />
{t('dashboard.addFirstWish')}
<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)}
{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">
{selectedFolder && (
<>
<Button variant="outline" onClick={() => {
setCreatingFolder(false);
setEditingFolderId(selectedFolder.id);
}} aria-expanded={editingFolderId === selectedFolder.id}>
<Pencil className="h-4 w-4" aria-hidden />
{t('folders.edit')}
</Button>
<Button variant="ghost" onClick={() => setFolderToDelete(selectedFolder)}>
<Trash2 className="h-4 w-4" aria-hidden />
{t('folders.delete')}
</Button>
</>
)}
{canAddWish && (
<Button onClick={() => setCreatingWish(true)}>
<Plus className="h-4 w-4" aria-hidden />
{t('dashboard.addWish')}
</Button>
)}
</div>
</div>
{selectedFolder && editingFolderId === selectedFolder.id && (
<FolderForm
key={selectedFolder.id}
folder={selectedFolder}
onCancel={() => setEditingFolderId(undefined)}
onSaved={() => setEditingFolderId(undefined)}
/>
))}
</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(showCompleted ? 'completed.emptyTitle' : 'dashboard.emptyTitle')}
</h3>
{showCompleted && <p className="empty-state__text">{t('completed.emptyText')}</p>}
</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)}
/>
{folderToDelete && (
<Modal
open
onClose={closeDeleteDialog}
title={`${t('folders.delete')} · ${folderToDelete.name}`}
description={t('folders.deleteDescription')}
footer={(
<>
<Button autoFocus variant="ghost" onClick={closeDeleteDialog} disabled={removeFolder.isPending}>
{t('common.cancel')}
</Button>
<Button variant="danger" disabled={removeFolder.isPending} onClick={() => {
removeFolder.mutate(folderToDelete.id, { onSuccess: () => {
selectFolder({ type: 'all' });
setFolderToDelete(undefined);
createFolderButton.current?.focus();
} });
}}>
{t('folders.delete')}
</Button>
</>
)}
>
{removeFolder.isError && <p role="alert" className="field__error">{t('folders.deleteError')}</p>}
</Modal>
)}
{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>
);
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { Navigate, useLocation, useNavigate, type Location } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Gift, Loader2 } from 'lucide-react';
@@ -19,7 +19,7 @@ export function LoginPage() {
const { user, login } = useAuthStore();
const navigate = useNavigate();
const location = useLocation();
const from = (location.state as { from?: { pathname: string } } | null)?.from?.pathname ?? '/';
const from = (location.state as { from?: Pick<Location, 'pathname' | 'search' | 'hash'> } | null)?.from ?? '/';
const {
register,
+2 -3
View File
@@ -1,10 +1,9 @@
import { createBrowserRouter, type RouterProviderProps } from 'react-router-dom';
import { createBrowserRouter, Navigate, type RouterProviderProps } from 'react-router-dom';
import { ProtectedRoute } from './components/Layout/ProtectedRoute';
import { AppShell } from './components/Layout/AppShell';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { ArchivePage } from './pages/ArchivePage';
import { CompletedPage } from './pages/CompletedPage';
import { TrashPage } from './pages/TrashPage';
import { ProfileSettingsPage } from './pages/ProfileSettingsPage';
import { PublicProfilePage } from './pages/PublicProfilePage';
@@ -22,7 +21,7 @@ export const router: RouterProviderProps['router'] = createBrowserRouter([
children: [
{ path: '/', element: <DashboardPage /> },
{ path: '/archive', element: <ArchivePage /> },
{ path: '/completed', element: <CompletedPage /> },
{ path: '/completed', element: <Navigate to="/?folder=completed" replace /> },
{ path: '/trash', element: <TrashPage /> },
{ path: '/settings', element: <ProfileSettingsPage /> },
],
+52
View File
@@ -131,6 +131,58 @@
@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;
}
.emoji-picker {
@apply grid gap-2 rounded-md border border-border bg-surface p-2;
}
.emoji-picker__categories {
@apply grid grid-cols-7 gap-0.5 border-b border-border pb-2;
}
.emoji-picker__grid {
@apply grid max-h-48 grid-cols-6 gap-1 overflow-y-auto overscroll-contain p-1;
}
.emoji-picker .emoji-picker__category,
.emoji-picker .emoji-picker__option {
@apply h-10 w-full min-w-0 px-0;
}
.emoji-picker [aria-pressed='true'] {
@apply bg-primary/10 ring-1 ring-inset ring-primary;
}
.emoji-picker__symbol {
font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
@apply text-lg leading-none;
}
.emoji-picker__option .emoji-picker__symbol {
@apply text-xl;
}
.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;
}
+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"]
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/shared",
"version": "0.3.0",
"version": "0.6.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
+33
View File
@@ -0,0 +1,33 @@
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 const updateFolderSchema = createFolderSchema.pick({ name: true, description: true }).partial().strict();
export type UpdateFolderInput = z.infer<typeof updateFolderSchema>;
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';
+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([