first commit

This commit is contained in:
Piotr Domański 2026-04-01 23:51:16 +02:00
commit 805bdcb831
52 changed files with 9566 additions and 0 deletions

23
.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

3
.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"recommendations": ["svelte.svelte-vscode"]
}

13
Dockerfile Normal file
View file

@ -0,0 +1,13 @@
# Stage 1: build
FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: serve with nginx
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html
EXPOSE 80

7
Dockerfile.dev Normal file
View file

@ -0,0 +1,7 @@
FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 5173
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"]

42
README.md Normal file
View file

@ -0,0 +1,42 @@
# sv
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```sh
# create a new project
npx sv create my-app
```
To recreate this project with the same configuration:
```sh
# recreate this project
npx sv@0.13.1 create --template minimal --types ts --install npm .
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```sh
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```sh
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.

7
docker-compose.build.yml Normal file
View file

@ -0,0 +1,7 @@
services:
app:
image: registry.domandoman.xyz/fooder/app
build:
context: .
dockerfile: Dockerfile
platform: linux/amd64

17
docker-compose.yml Normal file
View file

@ -0,0 +1,17 @@
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "5173:5173"
volumes:
- ./src:/app/src
- ./static:/app/static
- ./svelte.config.js:/app/svelte.config.js
- ./vite.config.ts:/app/vite.config.ts
environment:
- VITE_API_URL=http://host.docker.internal:8000
#- VITE_API_URL=https://fooderapi.domandoman.xyz
extra_hosts:
- "host.docker.internal:host-gateway"

20
nginx.conf Normal file
View file

@ -0,0 +1,20 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
# Proxy API requests to the backend
location /api {
proxy_pass http://api:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# SPA fallback all other routes serve index.html
location / {
try_files $uri $uri/ /index.html;
}
}

7095
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

31
package.json Normal file
View file

@ -0,0 +1,31 @@
{
"name": "app",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/vite": "^4.2.2",
"svelte": "^5.54.0",
"svelte-check": "^4.4.2",
"tailwindcss": "^4.2.2",
"typescript": "^5.9.3",
"vite": "^7.3.1",
"vite-plugin-pwa": "^1.2.0"
},
"dependencies": {
"@tanstack/svelte-query": "^6.1.12",
"idb": "^8.0.3"
}
}

21
src/app.css Normal file
View file

@ -0,0 +1,21 @@
@import 'tailwindcss';
@theme {
--color-brand: #16a34a;
--color-brand-light: #22c55e;
}
/* Safe area padding for PWA on notched devices */
:root {
--safe-top: env(safe-area-inset-top, 0px);
--safe-bottom: env(safe-area-inset-bottom, 0px);
}
/* Smooth scrolling, no tap highlight */
* {
-webkit-tap-highlight-color: transparent;
}
html {
scroll-behavior: smooth;
}

13
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

16
src/app.html Normal file
View file

@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#16a34a" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<title>Fooder</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" class="bg-zinc-950 text-zinc-100 antialiased">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

58
src/lib/api/auth.ts Normal file
View file

@ -0,0 +1,58 @@
import { auth } from '$lib/auth/store.svelte';
import type { Token, User } from '$lib/types/api';
const BASE = '/api';
export async function login(username: string, password: string): Promise<void> {
const body = new URLSearchParams({ username, password });
const res = await fetch(`${BASE}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString()
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Login failed'), { status: res.status, detail: err });
}
const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token);
}
export async function register(username: string, password: string): Promise<User> {
const res = await fetch(`${BASE}/user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Registration failed'), { status: res.status, detail: err });
}
return res.json();
}
export async function tryRestoreSession(): Promise<boolean> {
const refreshToken = auth.getRefreshToken();
if (!refreshToken) return false;
try {
const res = await fetch(`${BASE}/token/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken })
});
if (!res.ok) {
auth.clear();
return false;
}
const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token);
return true;
} catch {
return false;
}
}
export function logout(): void {
auth.clear();
}

102
src/lib/api/client.ts Normal file
View file

@ -0,0 +1,102 @@
import { auth } from '$lib/auth/store.svelte';
import { goto } from '$app/navigation';
const BASE = '/api';
let isRefreshing = false;
let refreshPromise: Promise<string | null> | null = null;
async function doRefresh(): Promise<string | null> {
const refreshToken = auth.getRefreshToken();
if (!refreshToken) return null;
try {
const res = await fetch(`${BASE}/token/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken })
});
if (!res.ok) return null;
const data = await res.json();
auth.setTokens(data.access_token, data.refresh_token);
return data.access_token;
} catch {
return null;
}
}
async function getValidToken(): Promise<string | null> {
if (auth.accessToken) return auth.accessToken;
// Deduplicate concurrent refresh calls
if (isRefreshing) return refreshPromise;
isRefreshing = true;
refreshPromise = doRefresh().finally(() => {
isRefreshing = false;
refreshPromise = null;
});
return refreshPromise;
}
export async function apiFetch(
path: string,
options: RequestInit = {},
retry = true
): Promise<Response> {
const token = await getValidToken();
const headers = new Headers(options.headers);
if (token) headers.set('Authorization', `Bearer ${token}`);
const res = await fetch(`${BASE}${path}`, { ...options, headers });
if (res.status === 401 && retry) {
// Force a refresh and retry once
auth.setAccessToken(''); // clear so getValidToken triggers refresh
const newToken = await doRefresh();
if (!newToken) {
auth.clear();
goto('/login');
return res;
}
auth.setAccessToken(newToken);
headers.set('Authorization', `Bearer ${newToken}`);
return fetch(`${BASE}${path}`, { ...options, headers });
}
return res;
}
export async function apiGet<T>(path: string): Promise<T> {
const res = await apiFetch(path);
if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
return res.json();
}
export async function apiPost<T>(path: string, body: unknown): Promise<T> {
const res = await apiFetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error(`POST ${path} failed: ${res.status}`), { status: res.status, detail: err });
}
return res.json();
}
export async function apiPatch<T>(path: string, body: unknown): Promise<T> {
const res = await apiFetch(path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) throw new Error(`PATCH ${path} failed: ${res.status}`);
return res.json();
}
export async function apiDelete(path: string): Promise<void> {
const res = await apiFetch(path, { method: 'DELETE' });
if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status}`);
}

6
src/lib/api/diary.ts Normal file
View file

@ -0,0 +1,6 @@
import { apiGet } from './client';
import type { Diary } from '$lib/types/api';
export function getDiary(date: string): Promise<Diary> {
return apiGet<Diary>(`/diary?date=${date}`);
}

14
src/lib/api/entries.ts Normal file
View file

@ -0,0 +1,14 @@
import { apiPost, apiPatch, apiDelete } from './client';
import type { Entry } from '$lib/types/api';
export function createEntry(mealId: number, productId: number, grams: number): Promise<Entry> {
return apiPost<Entry>('/entry', { meal_id: mealId, product_id: productId, grams });
}
export function updateEntry(id: number, patch: { grams?: number; product_id?: number; meal_id?: number }): Promise<Entry> {
return apiPatch<Entry>(`/entry/${id}`, patch);
}
export function deleteEntry(id: number): Promise<void> {
return apiDelete(`/entry/${id}`);
}

26
src/lib/api/meals.ts Normal file
View file

@ -0,0 +1,26 @@
import { apiPost, apiDelete, apiPatch } from './client';
import type { Meal, Preset } from '$lib/types/api';
export function createMeal(diaryId: number, name?: string): Promise<Meal> {
return apiPost<Meal>('/meal', { diary_id: diaryId, ...(name ? { name } : {}) });
}
export function renameMeal(id: number, name: string): Promise<Meal> {
return apiPatch<Meal>(`/meal/${id}`, { name });
}
export function deleteMeal(id: number): Promise<void> {
return apiDelete(`/meal/${id}`);
}
export function saveMealAsPreset(mealId: number, name?: string): Promise<Preset> {
return apiPost<Preset>(`/meal/${mealId}/save`, name ? { name } : {});
}
export function createMealFromPreset(diaryId: number, presetId: number, name?: string): Promise<Meal> {
return apiPost<Meal>('/meal/from_preset', {
diary_id: diaryId,
preset_id: presetId,
...(name ? { name } : {})
});
}

15
src/lib/api/presets.ts Normal file
View file

@ -0,0 +1,15 @@
import { apiGet, apiDelete } from './client';
import type { PresetList, PresetDetails } from '$lib/types/api';
export function listPresets(q = '', limit = 20, offset = 0): Promise<PresetList> {
const params = new URLSearchParams({ q, limit: String(limit), offset: String(offset) });
return apiGet<PresetList>(`/preset?${params}`);
}
export function getPreset(id: number): Promise<PresetDetails> {
return apiGet<PresetDetails>(`/preset/${id}`);
}
export function deletePreset(id: number): Promise<void> {
return apiDelete(`/preset/${id}`);
}

22
src/lib/api/products.ts Normal file
View file

@ -0,0 +1,22 @@
import { apiGet, apiPost } from './client';
import type { Product, ProductList } from '$lib/types/api';
export function listProducts(q = '', limit = 20, offset = 0): Promise<ProductList> {
const params = new URLSearchParams({ q, limit: String(limit), offset: String(offset) });
return apiGet<ProductList>(`/product?${params}`);
}
export function createProduct(data: {
name: string;
protein: number;
carb: number;
fat: number;
fiber: number;
barcode?: string;
}): Promise<Product> {
return apiPost<Product>('/product', data);
}
export function getProductByBarcode(barcode: string): Promise<Product> {
return apiGet<Product>(`/product/by_barcode?barcode=${encodeURIComponent(barcode)}`);
}

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,46 @@
import type { User } from '$lib/types/api';
const REFRESH_TOKEN_KEY = 'fooder_refresh_token';
interface AuthState {
accessToken: string | null;
user: User | null;
}
let state = $state<AuthState>({
accessToken: null,
user: null
});
export const auth = {
get accessToken() {
return state.accessToken;
},
get user() {
return state.user;
},
get isAuthenticated() {
return state.accessToken !== null;
},
setTokens(accessToken: string, refreshToken: string, user?: User) {
state.accessToken = accessToken;
if (user) state.user = user;
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
},
setAccessToken(accessToken: string) {
state.accessToken = accessToken;
},
getRefreshToken(): string | null {
if (typeof localStorage === 'undefined') return null;
return localStorage.getItem(REFRESH_TOKEN_KEY);
},
clear() {
state.accessToken = null;
state.user = null;
localStorage.removeItem(REFRESH_TOKEN_KEY);
}
};

View file

@ -0,0 +1,91 @@
<script lang="ts">
import { today } from '$lib/utils/date';
interface Props {
selected: string;
onSelect: (date: string) => void;
}
let { selected, onSelect }: Props = $props();
const todayStr = today();
let viewYear = $state(parseInt(selected.slice(0, 4)));
let viewMonth = $state(parseInt(selected.slice(5, 7)) - 1); // 0-based
function prevMonth() {
if (viewMonth === 0) { viewYear--; viewMonth = 11; }
else viewMonth--;
}
function nextMonth() {
if (viewMonth === 11) { viewYear++; viewMonth = 0; }
else viewMonth++;
}
const monthLabel = $derived(
new Date(viewYear, viewMonth, 1).toLocaleDateString(undefined, { month: 'long', year: 'numeric' })
);
function iso(year: number, month: number, day: number): string {
return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
const cells = $derived.by(() => {
const firstDay = new Date(viewYear, viewMonth, 1);
const startDow = (firstDay.getDay() + 6) % 7; // Mon = 0
const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
const result: (string | null)[] = [];
for (let i = 0; i < startDow; i++) result.push(null);
for (let d = 1; d <= daysInMonth; d++) result.push(iso(viewYear, viewMonth, d));
return result;
});
</script>
<div>
<div class="flex items-center justify-between mb-4">
<button
onclick={prevMonth}
class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
</button>
<span class="font-medium text-sm">{monthLabel}</span>
<button
onclick={nextMonth}
class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
<div class="grid grid-cols-7 mb-1">
{#each ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] as h}
<div class="text-center text-xs text-zinc-600 py-1">{h}</div>
{/each}
</div>
<div class="grid grid-cols-7 gap-y-1">
{#each cells as cell}
{#if cell === null}
<div></div>
{:else}
<button
onclick={() => onSelect(cell)}
class="aspect-square w-full rounded-full text-sm flex items-center justify-center transition-colors
{cell === selected
? 'bg-green-600 text-white font-semibold'
: cell === todayStr
? 'ring-1 ring-green-500 text-green-400'
: 'hover:bg-zinc-800 text-zinc-300'}"
>
{parseInt(cell.slice(8))}
</button>
{/if}
{/each}
</div>
</div>

View file

@ -0,0 +1,45 @@
<script lang="ts">
interface Props {
date: string;
label: string;
onPrev: () => void;
onNext: () => void;
isToday: boolean;
onDateClick?: () => void;
}
let { date, label, onPrev, onNext, isToday, onDateClick }: Props = $props();
</script>
<div class="flex items-center justify-between">
<button
onclick={onPrev}
class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors"
aria-label="Previous day"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
</button>
<button
onclick={onDateClick}
class="text-center {onDateClick ? 'hover:opacity-70 transition-opacity' : 'cursor-default'}"
>
<span class="font-semibold text-lg">{label}</span>
{#if !isToday}
<p class="text-xs text-zinc-500">{date}</p>
{/if}
</button>
<button
onclick={onNext}
disabled={isToday}
class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-zinc-800 disabled:opacity-30 transition-colors"
aria-label="Next day"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>

View file

@ -0,0 +1,44 @@
<script lang="ts">
import type { Entry } from '$lib/types/api';
import { kcal, g } from '$lib/utils/format';
interface Props {
entry: Entry;
onDelete: (id: number) => void;
onEdit: (entry: Entry) => void;
}
let { entry, onDelete, onEdit }: Props = $props();
</script>
<div
role="button"
tabindex="0"
onclick={() => onEdit(entry)}
onkeydown={(e) => e.key === 'Enter' && onEdit(entry)}
class="w-full flex items-center justify-between py-2.5 cursor-pointer group"
>
<div class="flex-1 min-w-0">
<p class="text-sm font-medium truncate">{entry.product.name}</p>
<p class="text-xs text-zinc-500">{entry.grams}g · {kcal(entry.calories)} kcal</p>
</div>
<div class="flex items-center gap-3 ml-3">
<div class="text-right hidden group-hover:grid grid-cols-2 gap-x-3">
<p class="text-xs text-zinc-500">P {g(entry.protein)}g</p>
<p class="text-xs text-zinc-500">Fat {g(entry.fat)}g</p>
<p class="text-xs text-zinc-500">C {g(entry.carb)}g</p>
<p class="text-xs text-zinc-500">Fib {g(entry.fiber)}g</p>
</div>
<button
onclick={(e) => { e.stopPropagation(); onDelete(entry.id); }}
class="w-7 h-7 flex items-center justify-center rounded-full text-zinc-600 hover:text-red-400 hover:bg-red-400/10 transition-colors"
aria-label="Delete entry"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>

View file

@ -0,0 +1,60 @@
<script lang="ts">
import type { Macros } from '$lib/types/api';
import { kcal, g } from '$lib/utils/format';
interface Props {
macros: Macros;
}
let { macros }: Props = $props();
const CALORIE_GOAL = 2000;
const pct = $derived(Math.min(100, Math.round((macros.calories / CALORIE_GOAL) * 100)));
const circumference = 2 * Math.PI * 40;
const dash = $derived(circumference * (pct / 100));
</script>
<div class="bg-zinc-900 rounded-2xl p-4">
<div class="flex items-center gap-5">
<!-- Calorie ring -->
<div class="relative w-24 h-24 shrink-0">
<svg class="w-24 h-24 -rotate-90" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="none" stroke="#27272a" stroke-width="10" />
<circle
cx="50" cy="50" r="40" fill="none"
stroke="#16a34a" stroke-width="10"
stroke-linecap="round"
stroke-dasharray="{dash} {circumference}"
class="transition-all duration-500"
/>
</svg>
<div class="absolute inset-0 flex flex-col items-center justify-center">
<span class="text-xl font-bold leading-none">{kcal(macros.calories)}</span>
<span class="text-xs text-zinc-500">kcal</span>
</div>
</div>
<!-- Macro bars -->
<div class="flex-1 space-y-2">
{#each [
{ label: 'Protein', value: g(macros.protein), color: 'bg-blue-500', max: 150 },
{ label: 'Carbs', value: g(macros.carb), color: 'bg-yellow-500', max: 300 },
{ label: 'Fat', value: g(macros.fat), color: 'bg-orange-500', max: 100 },
{ label: 'Fiber', value: g(macros.fiber), color: 'bg-green-500', max: 40 }
] as macro}
<div>
<div class="flex justify-between text-xs text-zinc-400 mb-1">
<span>{macro.label}</span>
<span class="font-medium text-zinc-200">{macro.value}g</span>
</div>
<div class="h-1.5 bg-zinc-800 rounded-full overflow-hidden">
<div
class="h-full {macro.color} rounded-full transition-all duration-500"
style="width: {Math.min(100, (macro.value / macro.max) * 100)}%"
></div>
</div>
</div>
{/each}
</div>
</div>
</div>

View file

@ -0,0 +1,182 @@
<script lang="ts">
import type { Meal } from '$lib/types/api';
import { kcal, g } from '$lib/utils/format';
import EntryRow from './EntryRow.svelte';
import { useQueryClient } from '@tanstack/svelte-query';
import { deleteMeal, renameMeal, saveMealAsPreset } from '$lib/api/meals';
import { deleteEntry } from '$lib/api/entries';
import { goto } from '$app/navigation';
import Sheet from '$lib/components/ui/Sheet.svelte';
interface Props {
meal: Meal;
date: string;
diaryId: number;
}
let { meal, date, diaryId }: Props = $props();
const queryClient = useQueryClient();
let collapsed = $state(false);
let saving = $state(false);
let renameOpen = $state(false);
let renameName = $state('');
let renaming = $state(false);
function openRename() {
renameName = meal.name;
renameOpen = true;
}
async function handleRename(e: SubmitEvent) {
e.preventDefault();
if (!renameName.trim()) return;
renaming = true;
try {
await renameMeal(meal.id, renameName.trim());
queryClient.invalidateQueries({ queryKey: ['diary', date] });
renameOpen = false;
} finally {
renaming = false;
}
}
async function handleDeleteMeal() {
if (!confirm(`Delete meal "${meal.name}"?`)) return;
await deleteMeal(meal.id);
queryClient.invalidateQueries({ queryKey: ['diary', date] });
}
async function handleSavePreset() {
saving = true;
try {
await saveMealAsPreset(meal.id);
await new Promise(r => setTimeout(r, 600));
} finally {
saving = false;
}
}
async function handleDeleteEntry(entryId: number) {
await deleteEntry(entryId);
queryClient.invalidateQueries({ queryKey: ['diary', date] });
}
function handleEditEntry(entry: import('$lib/types/api').Entry) {
goto(`/diary/${date}/edit-entry/${entry.id}`);
}
</script>
<div class="bg-zinc-900 rounded-2xl overflow-hidden">
<!-- Meal header -->
<div class="flex items-center justify-between px-4 py-3 border-b border-zinc-800">
<button
onclick={() => collapsed = !collapsed}
class="flex-1 flex items-center gap-2 text-left min-w-0"
>
<svg
class="w-4 h-4 text-zinc-500 shrink-0 transition-transform {collapsed ? '-rotate-90' : ''}"
fill="none" stroke="currentColor" viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
<div class="min-w-0 flex-1">
<p class="font-medium truncate">{meal.name}</p>
<p class="text-xs text-zinc-500">{kcal(meal.calories)} kcal · P {g(meal.protein)}g · C {g(meal.carb)}g · Fat {g(meal.fat)}g · Fib {g(meal.fiber)}g</p>
</div>
</button>
<div class="flex gap-1 ml-2 shrink-0">
<!-- Add entry -->
<button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)}
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-500 hover:text-green-400 hover:bg-green-400/10 transition-colors"
aria-label="Add food"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
</button>
<!-- Rename -->
<button
onclick={openRename}
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-500 hover:text-blue-400 hover:bg-blue-400/10 transition-colors"
aria-label="Rename meal"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
<!-- Save as preset -->
<button
onclick={handleSavePreset}
disabled={saving || meal.entries.length === 0}
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-500 hover:text-yellow-400 hover:bg-yellow-400/10 disabled:opacity-30 transition-colors"
aria-label="Save as preset"
>
{#if saving}
<svg class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
{:else}
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
{/if}
</button>
<!-- Delete meal -->
<button
onclick={handleDeleteMeal}
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-600 hover:text-red-400 hover:bg-red-400/10 transition-colors"
aria-label="Delete meal"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
<!-- Entries -->
{#if !collapsed}
<div class="px-4 divide-y divide-zinc-800">
{#if meal.entries.length === 0}
<button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)}
class="w-full text-sm text-zinc-600 py-4 text-center hover:text-zinc-400 transition-colors"
>
Tap + to add food
</button>
{/if}
{#each meal.entries as entry (entry.id)}
<EntryRow
{entry}
onDelete={handleDeleteEntry}
onEdit={handleEditEntry}
/>
{/each}
</div>
{/if}
</div>
<Sheet open={renameOpen} onclose={() => renameOpen = false} title="Rename meal">
<form onsubmit={handleRename} class="space-y-4">
<input
type="text"
bind:value={renameName}
required
autofocus
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
<button
type="submit"
disabled={renaming || !renameName.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{renaming ? 'Saving…' : 'Save'}
</button>
</form>
</Sheet>

View file

@ -0,0 +1,66 @@
<script lang="ts">
import { onMount } from 'svelte';
interface Props {
open: boolean;
onclose: () => void;
title?: string;
children: import('svelte').Snippet;
}
let { open, onclose, title, children }: Props = $props();
function handleBackdrop(e: MouseEvent) {
if (e.target === e.currentTarget) onclose();
}
function handleKey(e: KeyboardEvent) {
if (e.key === 'Escape') onclose();
}
</script>
<svelte:window onkeydown={handleKey} />
{#if open}
<!-- Backdrop -->
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div
class="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm"
onclick={handleBackdrop}
></div>
<!-- Sheet (mobile bottom sheet / desktop centered modal) -->
<div
class="fixed z-50 bg-zinc-900 px-4 pt-4
bottom-0 left-0 right-0 rounded-t-2xl pb-[calc(1.5rem+var(--safe-bottom))] max-w-lg mx-auto animate-slide-up
lg:bottom-auto lg:left-1/2 lg:top-1/2 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:rounded-2xl lg:max-w-md lg:w-full lg:pb-6 lg:animate-fade-in"
>
<!-- Handle (mobile only) -->
<div class="w-10 h-1 bg-zinc-700 rounded-full mx-auto mb-4 lg:hidden"></div>
{#if title}
<h2 class="text-base font-semibold mb-4">{title}</h2>
{/if}
{@render children()}
</div>
{/if}
<style>
@keyframes slide-up {
from { transform: translateY(100%); }
to { transform: translateY(0); }
}
@keyframes fade-in {
from { opacity: 0; transform: translate(-50%, -48%); }
to { opacity: 1; transform: translate(-50%, -50%); }
}
.animate-slide-up {
animation: slide-up 0.22s cubic-bezier(0.32, 0.72, 0, 1);
}
@media (min-width: 1024px) {
.animate-slide-up {
animation: fade-in 0.18s ease-out;
}
}
</style>

View file

@ -0,0 +1,37 @@
<script lang="ts">
import { goto } from '$app/navigation';
interface Props {
title: string;
back?: string | (() => void);
action?: import('svelte').Snippet;
}
let { title, back, action }: Props = $props();
function handleBack() {
if (!back) return;
if (typeof back === 'function') back();
else goto(back);
}
</script>
<header class="flex items-center gap-3 px-2 pt-[calc(0.75rem+var(--safe-top))] pb-3 bg-zinc-950 sticky top-0 z-10 border-b border-zinc-800">
{#if back}
<button
onclick={handleBack}
class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors shrink-0 lg:hidden"
aria-label="Go back"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
</button>
{/if}
<h1 class="flex-1 font-semibold text-lg truncate">{title}</h1>
{#if action}
{@render action()}
{/if}
</header>

1
src/lib/index.ts Normal file
View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

41
src/lib/offline/db.ts Normal file
View file

@ -0,0 +1,41 @@
import { openDB, type IDBPDatabase } from 'idb';
import type { Diary } from '$lib/types/api';
const DB_NAME = 'fooder';
const DB_VERSION = 1;
export interface QueuedMutation {
id?: number;
method: 'POST' | 'PATCH' | 'DELETE';
url: string;
body: unknown;
queryKeysToInvalidate: string[][];
createdAt: number;
}
let dbInstance: IDBPDatabase | null = null;
export async function getDb() {
if (dbInstance) return dbInstance;
dbInstance = await openDB(DB_NAME, DB_VERSION, {
upgrade(db) {
if (!db.objectStoreNames.contains('diaries')) {
db.createObjectStore('diaries', { keyPath: 'date' });
}
if (!db.objectStoreNames.contains('mutation_queue')) {
db.createObjectStore('mutation_queue', { keyPath: 'id', autoIncrement: true });
}
}
});
return dbInstance;
}
export async function cacheDiary(diary: Diary): Promise<void> {
const db = await getDb();
await db.put('diaries', diary);
}
export async function getCachedDiary(date: string): Promise<Diary | undefined> {
const db = await getDb();
return db.get('diaries', date);
}

98
src/lib/types/api.ts Normal file
View file

@ -0,0 +1,98 @@
export interface Token {
access_token: string;
refresh_token: string;
token_type: string;
}
export interface User {
username: string;
}
export interface Macros {
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface Product {
id: number;
name: string;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
barcode: string | null;
usage_count_cached: number | null;
}
export interface Entry {
id: number;
grams: number;
product: Product;
meal_id: number;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface Meal {
id: number;
name: string;
order: number;
diary_id: number;
entries: Entry[];
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface Diary {
id: number;
date: string;
meals: Meal[];
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface Preset {
id: number;
name: string;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface PresetDetails extends Preset {
preset_entries: PresetEntry[];
}
export interface PresetEntry {
id: number;
grams: number;
product: Product;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface ProductList {
products: Product[];
}
export interface PresetList {
presets: Preset[];
}

25
src/lib/utils/date.ts Normal file
View file

@ -0,0 +1,25 @@
export function toISODate(date: Date): string {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
export function today(): string {
return toISODate(new Date());
}
export function addDays(dateStr: string, days: number): string {
const d = new Date(dateStr + 'T00:00:00');
d.setDate(d.getDate() + days);
return toISODate(d);
}
export function formatDisplay(dateStr: string): string {
const d = new Date(dateStr + 'T00:00:00');
const t = today();
if (dateStr === t) return 'Today';
if (dateStr === addDays(t, -1)) return 'Yesterday';
if (dateStr === addDays(t, 1)) return 'Tomorrow';
return d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
}

9
src/lib/utils/format.ts Normal file
View file

@ -0,0 +1,9 @@
/** Round to nearest integer (for kcal) */
export function kcal(x: number): number {
return Math.round(x);
}
/** Round to 1 decimal (for macros in grams) */
export function g(x: number): number {
return Math.round(x * 10) / 10;
}

View file

@ -0,0 +1,107 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { auth } from '$lib/auth/store.svelte';
import { logout } from '$lib/api/auth';
import { useQueryClient } from '@tanstack/svelte-query';
import { today } from '$lib/utils/date';
import { page } from '$app/state';
import { onMount } from 'svelte';
let { children } = $props();
const queryClient = useQueryClient();
onMount(() => {
if (!auth.isAuthenticated) goto('/login');
});
function handleLogout() {
logout();
queryClient.clear();
goto('/login');
}
const isDiary = $derived(page.url.pathname.startsWith('/diary'));
const isPresets = $derived(page.url.pathname.startsWith('/presets'));
</script>
{#if auth.isAuthenticated}
<div class="lg:flex min-h-screen">
<!-- Sidebar (desktop only) -->
<aside class="hidden lg:flex flex-col w-52 shrink-0 fixed inset-y-0 border-r border-zinc-800 bg-zinc-950 px-3 py-6 z-20">
<div class="px-2 mb-8">
<span class="text-lg font-bold text-green-400">fooder</span>
</div>
<nav class="flex-1 space-y-1">
<a
href="/diary/{today()}"
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors
{isDiary ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'}"
>
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
Diary
</a>
<a
href="/presets"
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors
{isPresets ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'}"
>
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
Presets
</a>
</nav>
<button
onclick={handleLogout}
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900 transition-colors"
>
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
Log out
</button>
</aside>
<!-- Main content -->
<div class="flex-1 lg:ml-52 flex flex-col min-h-screen">
{@render children()}
</div>
<!-- Bottom tab bar (mobile only) -->
<nav class="lg:hidden fixed bottom-0 left-0 right-0 z-20 bg-zinc-950 border-t border-zinc-800 flex items-center pb-[var(--safe-bottom)]">
<a
href="/diary/{today()}"
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors
{isDiary ? 'text-green-400' : 'text-zinc-500 hover:text-zinc-300'}"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
Diary
</a>
<a
href="/presets"
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors
{isPresets ? 'text-green-400' : 'text-zinc-500 hover:text-zinc-300'}"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
Presets
</a>
<button
onclick={handleLogout}
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium text-zinc-500 hover:text-zinc-300 transition-colors"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
Log out
</button>
</nav>
</div>
{/if}

View file

@ -0,0 +1,9 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { today } from '$lib/utils/date';
import { onMount } from 'svelte';
onMount(() => {
goto(`/diary/${today()}`, { replaceState: true });
});
</script>

View file

@ -0,0 +1,108 @@
<script lang="ts">
import { page } from '$app/state';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getDiary } from '$lib/api/diary';
import { getCachedDiary, cacheDiary } from '$lib/offline/db';
import { addDays, formatDisplay, today } from '$lib/utils/date';
import { goto } from '$app/navigation';
import MacroSummary from '$lib/components/diary/MacroSummary.svelte';
import MealCard from '$lib/components/diary/MealCard.svelte';
import DateNav from '$lib/components/diary/DateNav.svelte';
import CalendarPicker from '$lib/components/diary/CalendarPicker.svelte';
import Sheet from '$lib/components/ui/Sheet.svelte';
const date = $derived(page.params.date);
const queryClient = useQueryClient();
let calendarOpen = $state(false);
const diaryQuery = createQuery(() => ({
queryKey: ['diary', date],
queryFn: async () => {
if (!navigator.onLine) {
const cached = await getCachedDiary(date);
if (cached) return cached;
throw new Error('Offline and no cached data');
}
const diary = await getDiary(date);
await cacheDiary(diary);
return diary;
}
}));
function goDate(delta: number) {
goto(`/diary/${addDays(date, delta)}`);
}
function handleDateSelect(d: string) {
calendarOpen = false;
goto(`/diary/${d}`);
}
</script>
<div class="flex flex-col h-screen">
<!-- Header -->
<header class="px-4 pt-[calc(0.75rem+var(--safe-top))] pb-3 bg-zinc-950 sticky top-0 z-10 border-b border-zinc-800">
<DateNav
{date}
label={formatDisplay(date)}
onPrev={() => goDate(-1)}
onNext={() => goDate(1)}
isToday={date === today()}
onDateClick={() => calendarOpen = true}
/>
</header>
<!-- Content -->
<main class="flex-1 overflow-y-auto px-4 py-4 pb-[calc(5rem+var(--safe-bottom))] lg:pb-6">
{#if diaryQuery.isPending}
<!-- Skeleton -->
<div class="animate-pulse space-y-4 lg:grid lg:grid-cols-[300px_1fr] lg:gap-6 lg:space-y-0 lg:items-start">
<div class="h-28 bg-zinc-800 rounded-2xl"></div>
<div class="space-y-4">
<div class="h-40 bg-zinc-800 rounded-2xl"></div>
<div class="h-40 bg-zinc-800 rounded-2xl"></div>
</div>
</div>
{:else if diaryQuery.isError}
<div class="text-center text-zinc-500 mt-20">
<p class="text-lg">Could not load diary</p>
<p class="text-sm mt-1">{diaryQuery.error.message}</p>
<button
onclick={() => diaryQuery.refetch()}
class="mt-4 px-4 py-2 bg-zinc-800 rounded-xl text-sm"
>
Retry
</button>
</div>
{:else if diaryQuery.data}
{@const diary = diaryQuery.data}
<div class="space-y-4 lg:grid lg:grid-cols-[300px_1fr] lg:gap-6 lg:space-y-0 lg:items-start">
<!-- Left: macros summary (sticky on desktop) -->
<div class="lg:sticky lg:top-[4.5rem]">
<MacroSummary macros={diary} />
</div>
<!-- Right: meals -->
<div class="space-y-4">
{#each diary.meals as meal (meal.id)}
<MealCard {meal} {date} diaryId={diary.id} />
{/each}
<!-- Add meal button -->
<button
onclick={() => goto(`/diary/${date}/add-meal?diary_id=${diaryQuery.data?.id}`)}
class="w-full border border-dashed border-zinc-700 rounded-2xl py-4 text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors text-sm font-medium"
>
+ Add meal
</button>
</div>
</div>
{/if}
</main>
<Sheet open={calendarOpen} onclose={() => calendarOpen = false}>
<CalendarPicker selected={date} onSelect={handleDateSelect} />
</Sheet>
</div>

View file

@ -0,0 +1,176 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { listProducts } from '$lib/api/products';
import { createEntry } from '$lib/api/entries';
import type { Product } from '$lib/types/api';
import TopBar from '$lib/components/ui/TopBar.svelte';
import Sheet from '$lib/components/ui/Sheet.svelte';
import { kcal, g } from '$lib/utils/format';
const date = $derived(page.params.date);
const mealId = $derived(Number(page.url.searchParams.get('meal_id')));
const queryClient = useQueryClient();
let q = $state('');
let debouncedQ = $state('');
let debounceTimer: ReturnType<typeof setTimeout>;
let selectedProduct = $state<Product | null>(null);
let grams = $state(100);
let submitting = $state(false);
function handleSearch(value: string) {
q = value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => { debouncedQ = value; }, 300);
}
const productsQuery = createQuery(() => ({
queryKey: ['products', debouncedQ],
queryFn: () => listProducts(debouncedQ, 30),
staleTime: 0
}));
function selectProduct(product: Product) {
selectedProduct = product;
grams = 100;
}
async function handleAddEntry() {
if (!selectedProduct || !mealId) return;
submitting = true;
try {
await createEntry(mealId, selectedProduct.id, grams);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} finally {
submitting = false;
}
}
// Estimated macros preview
const preview = $derived(selectedProduct ? {
calories: Math.round(selectedProduct.calories * grams / 100),
protein: Math.round(selectedProduct.protein * grams / 100 * 10) / 10,
carb: Math.round(selectedProduct.carb * grams / 100 * 10) / 10,
fat: Math.round(selectedProduct.fat * grams / 100 * 10) / 10,
} : null);
</script>
<div class="flex flex-col h-screen">
<TopBar title="Add food" back="/diary/{date}" />
<!-- Search bar -->
<div class="px-4 py-3 border-b border-zinc-800 bg-zinc-950">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="search"
placeholder="Search foods…"
value={q}
oninput={(e) => handleSearch(e.currentTarget.value)}
autofocus
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl pl-9 pr-4 py-2.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
</div>
<!-- Results -->
<main class="flex-1 overflow-y-auto">
{#if productsQuery.isPending}
<div class="space-y-px mt-2 px-4">
{#each Array(6) as _}
<div class="h-14 bg-zinc-900 rounded-xl animate-pulse mb-2"></div>
{/each}
</div>
{:else if productsQuery.data?.products.length === 0}
<div class="text-center text-zinc-500 mt-16 px-6">
<p class="text-base">No products found</p>
<p class="text-sm mt-1">Try a different name or</p>
<a href="/products/new?name={encodeURIComponent(q)}" class="mt-3 inline-block text-green-500 text-sm">
Create "{q || 'new product'}"
</a>
</div>
{:else}
<ul class="divide-y divide-zinc-800/50">
{#each productsQuery.data?.products ?? [] as product (product.id)}
<li>
<button
onclick={() => selectProduct(product)}
class="w-full flex items-center justify-between px-4 py-3.5 hover:bg-zinc-900 transition-colors text-left"
>
<div class="min-w-0">
<p class="font-medium text-sm truncate capitalize">{product.name}</p>
<p class="text-xs text-zinc-500 mt-0.5">
{kcal(product.calories)} kcal · P {g(product.protein)}g · C {g(product.carb)}g · F {g(product.fat)}g
<span class="text-zinc-600">per 100g</span>
</p>
</div>
<svg class="w-4 h-4 text-zinc-600 ml-3 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
</button>
</li>
{/each}
</ul>
{/if}
</main>
<!-- Grams sheet -->
<Sheet
open={selectedProduct !== null}
onclose={() => selectedProduct = null}
title={selectedProduct?.name ?? ''}
>
{#if selectedProduct}
<!-- Macro preview -->
{#if preview}
<div class="grid grid-cols-4 gap-2 mb-5">
{#each [
{ label: 'kcal', value: preview.calories },
{ label: 'protein', value: preview.protein + 'g' },
{ label: 'carbs', value: preview.carb + 'g' },
{ label: 'fat', value: preview.fat + 'g' },
] as m}
<div class="bg-zinc-800 rounded-xl p-2.5 text-center">
<p class="text-base font-semibold">{m.value}</p>
<p class="text-xs text-zinc-500 mt-0.5">{m.label}</p>
</div>
{/each}
</div>
{/if}
<!-- Grams input -->
<label class="block text-sm text-zinc-400 mb-2">Grams</label>
<div class="flex items-center gap-3 mb-5">
<button
onclick={() => grams = Math.max(1, grams - 10)}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
></button>
<input
type="number"
bind:value={grams}
min="1"
max="5000"
class="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-center text-xl font-semibold focus:outline-none focus:border-green-500 transition-colors"
/>
<button
onclick={() => grams = grams + 10}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
>+</button>
</div>
<button
onclick={handleAddEntry}
disabled={submitting || grams < 1}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{submitting ? 'Adding…' : 'Add to meal'}
</button>
{/if}
</Sheet>
</div>

View file

@ -0,0 +1,152 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { createMeal, createMealFromPreset } from '$lib/api/meals';
import { listPresets } from '$lib/api/presets';
import type { Preset } from '$lib/types/api';
import TopBar from '$lib/components/ui/TopBar.svelte';
import { kcal, g } from '$lib/utils/format';
const date = $derived(page.params.date);
const diaryId = $derived(Number(page.url.searchParams.get('diary_id')));
const queryClient = useQueryClient();
type Tab = 'new' | 'preset';
let tab = $state<Tab>('new');
let mealName = $state('');
let presetQ = $state('');
let presetDebounced = $state('');
let presetTimer: ReturnType<typeof setTimeout>;
let submitting = $state(false);
let error = $state('');
function handlePresetSearch(v: string) {
presetQ = v;
clearTimeout(presetTimer);
presetTimer = setTimeout(() => { presetDebounced = v; }, 300);
}
const presetsQuery = createQuery(() => ({
queryKey: ['presets', presetDebounced],
queryFn: () => listPresets(presetDebounced, 30)
}));
async function handleCreateNew(e: SubmitEvent) {
e.preventDefault();
submitting = true;
try {
await createMeal(diaryId, mealName || undefined);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} finally {
submitting = false;
}
}
async function handleFromPreset(preset: Preset) {
submitting = true;
error = '';
try {
await createMealFromPreset(diaryId, preset.id, preset.name);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} catch {
error = 'Failed to add preset';
submitting = false;
}
}
</script>
<div class="flex flex-col h-screen">
<TopBar title="Add meal" back="/diary/{date}" />
<!-- Tabs -->
<div class="flex border-b border-zinc-800 bg-zinc-950">
{#each [{ id: 'new', label: 'New meal' }, { id: 'preset', label: 'From preset' }] as t}
<button
onclick={() => tab = t.id as Tab}
class="flex-1 py-3 text-sm font-medium transition-colors border-b-2 {tab === t.id
? 'border-green-500 text-green-400'
: 'border-transparent text-zinc-500 hover:text-zinc-300'}"
>
{t.label}
</button>
{/each}
</div>
<main class="flex-1 overflow-y-auto">
{#if tab === 'new'}
<form onsubmit={handleCreateNew} class="px-4 py-6 space-y-4">
<div>
<label for="meal-name" class="block text-sm text-zinc-400 mb-2">Meal name <span class="text-zinc-600">(optional)</span></label>
<input
id="meal-name"
type="text"
bind:value={mealName}
placeholder="e.g. Breakfast, Lunch…"
autofocus
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 placeholder-zinc-600 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<button
type="submit"
disabled={submitting}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{submitting ? 'Creating…' : 'Create meal'}
</button>
</form>
{:else}
<!-- Preset search -->
<div class="px-4 py-3 border-b border-zinc-800">
<input
type="search"
placeholder="Search presets…"
value={presetQ}
oninput={(e) => handlePresetSearch(e.currentTarget.value)}
autofocus
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-2.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{#if error}
<p class="text-red-400 text-sm px-4 pt-3">{error}</p>
{/if}
{#if presetsQuery.isPending}
<div class="space-y-2 p-4">
{#each Array(4) as _}
<div class="h-16 bg-zinc-900 rounded-xl animate-pulse"></div>
{/each}
</div>
{:else if presetsQuery.data?.presets.length === 0}
<div class="text-center text-zinc-500 mt-16 px-6">
<p>No presets yet</p>
<p class="text-sm mt-1">Save a meal as preset from the diary view</p>
</div>
{:else}
<ul class="divide-y divide-zinc-800/50">
{#each presetsQuery.data?.presets ?? [] as preset (preset.id)}
<li>
<button
onclick={() => handleFromPreset(preset)}
disabled={submitting}
class="w-full flex items-center justify-between px-4 py-4 hover:bg-zinc-900 transition-colors text-left disabled:opacity-50"
>
<div>
<p class="font-medium">{preset.name}</p>
<p class="text-xs text-zinc-500 mt-0.5">{kcal(preset.calories)} kcal · P {g(preset.protein)}g · C {g(preset.carb)}g · F {g(preset.fat)}g</p>
</div>
<svg class="w-4 h-4 text-zinc-600 ml-3 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
</button>
</li>
{/each}
</ul>
{/if}
{/if}
</main>
</div>

View file

@ -0,0 +1,139 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { useQueryClient } from '@tanstack/svelte-query';
import { updateEntry, deleteEntry } from '$lib/api/entries';
import TopBar from '$lib/components/ui/TopBar.svelte';
const date = $derived(page.params.date);
const entryId = $derived(Number(page.params.entry_id));
const queryClient = useQueryClient();
// Read entry from cache — diary was already fetched on the diary page
const cachedDiary = $derived(
queryClient.getQueryData<import('$lib/types/api').Diary>(['diary', date])
);
const entry = $derived(
cachedDiary?.meals.flatMap(m => m.entries).find(e => e.id === entryId)
);
let grams = $state(entry?.grams ?? 100);
$effect(() => { if (entry) grams = entry.grams; });
let saving = $state(false);
let deleting = $state(false);
const preview = $derived(entry ? {
calories: Math.round(entry.product.calories * grams / 100),
protein: Math.round(entry.product.protein * grams / 100 * 10) / 10,
carb: Math.round(entry.product.carb * grams / 100 * 10) / 10,
fat: Math.round(entry.product.fat * grams / 100 * 10) / 10,
} : null);
async function handleSave() {
if (!entry) return;
saving = true;
try {
await updateEntry(entryId, { grams });
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} finally {
saving = false;
}
}
async function handleDelete() {
if (!confirm('Remove this entry?')) return;
deleting = true;
try {
await deleteEntry(entryId);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} finally {
deleting = false;
}
}
</script>
<div class="flex flex-col h-screen">
<TopBar title="Edit entry" back="/diary/{date}">
{#snippet action()}
<button
onclick={handleDelete}
disabled={deleting}
class="w-10 h-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-red-400 hover:bg-red-400/10 transition-colors"
aria-label="Delete entry"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
{/snippet}
</TopBar>
{#if !entry}
<div class="flex-1 flex items-center justify-center text-zinc-500">
Entry not found
</div>
{:else}
<main class="flex-1 px-4 py-6 space-y-6">
<!-- Product info -->
<div class="bg-zinc-900 rounded-2xl px-4 py-4">
<p class="font-semibold capitalize">{entry.product.name}</p>
<p class="text-xs text-zinc-500 mt-1">
{entry.product.calories} kcal · P {entry.product.protein}g · C {entry.product.carb}g · F {entry.product.fat}g
<span class="text-zinc-600">per 100g</span>
</p>
</div>
<!-- Macro preview -->
{#if preview}
<div class="grid grid-cols-4 gap-2">
{#each [
{ label: 'kcal', value: preview.calories },
{ label: 'protein', value: preview.protein + 'g' },
{ label: 'carbs', value: preview.carb + 'g' },
{ label: 'fat', value: preview.fat + 'g' },
] as m}
<div class="bg-zinc-900 rounded-xl p-2.5 text-center">
<p class="text-base font-semibold">{m.value}</p>
<p class="text-xs text-zinc-500 mt-0.5">{m.label}</p>
</div>
{/each}
</div>
{/if}
<!-- Grams input -->
<div>
<label class="block text-sm text-zinc-400 mb-2">Grams</label>
<div class="flex items-center gap-3">
<button
onclick={() => grams = Math.max(1, grams - 10)}
class="w-12 h-12 rounded-xl bg-zinc-900 hover:bg-zinc-800 transition-colors text-xl font-medium flex items-center justify-center"
></button>
<input
type="number"
bind:value={grams}
min="1"
max="5000"
class="flex-1 bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-center text-2xl font-semibold focus:outline-none focus:border-green-500 transition-colors"
/>
<button
onclick={() => grams = grams + 10}
class="w-12 h-12 rounded-xl bg-zinc-900 hover:bg-zinc-800 transition-colors text-xl font-medium flex items-center justify-center"
>+</button>
</div>
</div>
</main>
<div class="px-4 pb-[calc(1.5rem+var(--safe-bottom))]">
<button
onclick={handleSave}
disabled={saving || grams < 1 || grams === entry.grams}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-40 rounded-xl py-3.5 font-semibold transition-colors"
>
{saving ? 'Saving…' : 'Save changes'}
</button>
</div>
{/if}
</div>

View file

@ -0,0 +1,144 @@
<script lang="ts">
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { listPresets, deletePreset } from '$lib/api/presets';
import { getDiary } from '$lib/api/diary';
import { createMealFromPreset } from '$lib/api/meals';
import { today } from '$lib/utils/date';
import { kcal, g } from '$lib/utils/format';
import TopBar from '$lib/components/ui/TopBar.svelte';
import type { Preset } from '$lib/types/api';
const queryClient = useQueryClient();
let q = $state('');
let debouncedQ = $state('');
let debounceTimer: ReturnType<typeof setTimeout>;
let addingId = $state<number | null>(null);
let addedId = $state<number | null>(null);
let deletingId = $state<number | null>(null);
function handleSearch(value: string) {
q = value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => { debouncedQ = value; }, 300);
}
const presetsQuery = createQuery(() => ({
queryKey: ['presets', debouncedQ],
queryFn: () => listPresets(debouncedQ, 50)
}));
async function handleAddToToday(preset: Preset) {
addingId = preset.id;
try {
const diary = await getDiary(today());
await createMealFromPreset(diary.id, preset.id, preset.name);
queryClient.invalidateQueries({ queryKey: ['diary', today()] });
addedId = preset.id;
setTimeout(() => { addedId = null; }, 1500);
} finally {
addingId = null;
}
}
async function handleDelete(preset: Preset) {
if (!confirm(`Delete preset "${preset.name}"?`)) return;
deletingId = preset.id;
try {
await deletePreset(preset.id);
queryClient.invalidateQueries({ queryKey: ['presets'] });
} finally {
deletingId = null;
}
}
</script>
<div class="flex flex-col h-screen">
<TopBar title="Presets" back="/diary/{today()}" />
<!-- Search -->
<div class="px-4 py-3 border-b border-zinc-800 bg-zinc-950">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="search"
placeholder="Search presets…"
value={q}
oninput={(e) => handleSearch(e.currentTarget.value)}
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl pl-9 pr-4 py-2.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
</div>
<main class="flex-1 overflow-y-auto">
{#if presetsQuery.isPending}
<div class="space-y-2 p-4">
{#each Array(5) as _}
<div class="h-16 bg-zinc-900 rounded-xl animate-pulse"></div>
{/each}
</div>
{:else if presetsQuery.isError}
<p class="text-center text-zinc-500 mt-16">Could not load presets</p>
{:else if !presetsQuery.data?.presets.length}
<div class="text-center text-zinc-500 mt-16 px-6">
<p>No presets yet</p>
<p class="text-sm mt-1">Save a meal as preset from the diary view</p>
</div>
{:else}
<ul class="divide-y divide-zinc-800/50">
{#each presetsQuery.data.presets as preset (preset.id)}
<li class="flex items-center justify-between px-4 py-4">
<div class="min-w-0 flex-1">
<p class="font-medium truncate">{preset.name}</p>
<p class="text-xs text-zinc-500 mt-0.5">
{kcal(preset.calories)} kcal · P {g(preset.protein)}g · C {g(preset.carb)}g · F {g(preset.fat)}g
</p>
</div>
<div class="flex gap-1 ml-3 shrink-0">
<!-- Add to today -->
<button
onclick={() => handleAddToToday(preset)}
disabled={addingId === preset.id}
class="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors
{addedId === preset.id
? 'bg-green-600/20 text-green-400'
: 'bg-zinc-800 hover:bg-zinc-700 text-zinc-300 disabled:opacity-50'}"
>
{#if addingId === preset.id}
<svg class="w-3 h-3 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
{:else if addedId === preset.id}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
Added
{:else}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
Today
{/if}
</button>
<!-- Delete -->
<button
onclick={() => handleDelete(preset)}
disabled={deletingId === preset.id}
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-600 hover:text-red-400 hover:bg-red-400/10 disabled:opacity-30 transition-colors"
aria-label="Delete preset"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</li>
{/each}
</ul>
{/if}
</main>
</div>

View file

@ -0,0 +1,120 @@
<script lang="ts">
import { page } from '$app/state';
import { createProduct } from '$lib/api/products';
import TopBar from '$lib/components/ui/TopBar.svelte';
let name = $state(page.url.searchParams.get('name') ?? '');
let protein = $state(0);
let carb = $state(0);
let fat = $state(0);
let fiber = $state(0);
let submitting = $state(false);
let error = $state('');
// calories = protein×4 + carb×4 + fat×9 + fiber×2
const calories = $derived(Math.round(protein * 4 + carb * 4 + fat * 9 + fiber * 2));
async function handleSubmit(e: SubmitEvent) {
e.preventDefault();
submitting = true;
error = '';
try {
await createProduct({ name, protein, carb, fat, fiber });
history.back();
} catch {
error = 'Failed to save product';
submitting = false;
}
}
</script>
<div class="flex flex-col h-screen">
<TopBar title="New product" back={() => history.back()} />
<main class="flex-1 overflow-y-auto px-4 py-6">
<form onsubmit={handleSubmit} class="space-y-4">
<p class="text-xs text-zinc-500">All values per 100g</p>
<div>
<label for="name" class="block text-sm text-zinc-400 mb-2">Name</label>
<input
id="name"
type="text"
bind:value={name}
placeholder="e.g. Chicken breast"
required
autofocus
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 placeholder-zinc-600 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label for="protein" class="block text-sm text-zinc-400 mb-2">Protein (g)</label>
<input
id="protein"
type="number"
bind:value={protein}
min="0"
step="0.1"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="carb" class="block text-sm text-zinc-400 mb-2">Carbs (g)</label>
<input
id="carb"
type="number"
bind:value={carb}
min="0"
step="0.1"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="fat" class="block text-sm text-zinc-400 mb-2">Fat (g)</label>
<input
id="fat"
type="number"
bind:value={fat}
min="0"
step="0.1"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="fiber" class="block text-sm text-zinc-400 mb-2">Fiber (g)</label>
<input
id="fiber"
type="number"
bind:value={fiber}
min="0"
step="0.1"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
</div>
<div class="bg-zinc-900 rounded-xl px-4 py-3 flex items-center justify-between">
<span class="text-sm text-zinc-400">Calories</span>
<span class="font-semibold">{calories} kcal</span>
</div>
{#if error}
<p class="text-red-400 text-sm">{error}</p>
{/if}
<button
type="submit"
disabled={submitting || !name.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{submitting ? 'Saving…' : 'Save product'}
</button>
</form>
</main>
</div>

View file

@ -0,0 +1,79 @@
<script lang="ts">
import { login } from '$lib/api/auth';
import { goto } from '$app/navigation';
import { auth } from '$lib/auth/store.svelte';
import { onMount } from 'svelte';
import { today } from '$lib/utils/date';
let username = $state('');
let password = $state('');
let error = $state('');
let loading = $state(false);
onMount(() => {
if (auth.isAuthenticated) goto(`/diary/${today()}`);
});
async function handleSubmit(e: SubmitEvent) {
e.preventDefault();
error = '';
loading = true;
try {
await login(username, password);
goto(`/diary/${today()}`);
} catch (err: unknown) {
error = 'Invalid username or password';
} finally {
loading = false;
}
}
</script>
<div class="min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-sm">
<h1 class="text-3xl font-bold text-center mb-8 text-green-500">Fooder</h1>
<form onsubmit={handleSubmit} class="space-y-4">
<div>
<label for="username" class="block text-sm font-medium text-zinc-400 mb-1">Username</label>
<input
id="username"
type="text"
bind:value={username}
autocomplete="username"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="password" class="block text-sm font-medium text-zinc-400 mb-1">Password</label>
<input
id="password"
type="password"
bind:value={password}
autocomplete="current-password"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{#if error}
<p class="text-red-400 text-sm">{error}</p>
{/if}
<button
type="submit"
disabled={loading}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
<p class="text-center mt-6 text-zinc-500 text-sm">
No account?
<a href="/register" class="text-green-500 hover:text-green-400">Register</a>
</p>
</div>
</div>

View file

@ -0,0 +1,92 @@
<script lang="ts">
import { register, login } from '$lib/api/auth';
import { goto } from '$app/navigation';
import { today } from '$lib/utils/date';
let username = $state('');
let password = $state('');
let confirm = $state('');
let error = $state('');
let loading = $state(false);
async function handleSubmit(e: SubmitEvent) {
e.preventDefault();
error = '';
if (password !== confirm) {
error = 'Passwords do not match';
return;
}
loading = true;
try {
await register(username, password);
await login(username, password);
goto(`/diary/${today()}`);
} catch (err: unknown) {
const e2 = err as { detail?: { detail?: string } };
error = e2.detail?.detail ?? 'Registration failed';
} finally {
loading = false;
}
}
</script>
<div class="min-h-screen flex items-center justify-center px-4">
<div class="w-full max-w-sm">
<h1 class="text-3xl font-bold text-center mb-8 text-green-500">Fooder</h1>
<form onsubmit={handleSubmit} class="space-y-4">
<div>
<label for="username" class="block text-sm font-medium text-zinc-400 mb-1">Username</label>
<input
id="username"
type="text"
bind:value={username}
autocomplete="username"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="password" class="block text-sm font-medium text-zinc-400 mb-1">Password</label>
<input
id="password"
type="password"
bind:value={password}
autocomplete="new-password"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<div>
<label for="confirm" class="block text-sm font-medium text-zinc-400 mb-1">Confirm password</label>
<input
id="confirm"
type="password"
bind:value={confirm}
autocomplete="new-password"
required
class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{#if error}
<p class="text-red-400 text-sm">{error}</p>
{/if}
<button
type="submit"
disabled={loading}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{loading ? 'Creating account…' : 'Create account'}
</button>
</form>
<p class="text-center mt-6 text-zinc-500 text-sm">
Already have an account?
<a href="/login" class="text-green-500 hover:text-green-400">Sign in</a>
</p>
</div>
</div>

30
src/routes/+layout.svelte Normal file
View file

@ -0,0 +1,30 @@
<script lang="ts">
import '../app.css';
import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query';
import { tryRestoreSession } from '$lib/api/auth';
import { onMount } from 'svelte';
let { children } = $props();
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 1
}
}
});
let ready = $state(false);
onMount(async () => {
await tryRestoreSession();
ready = true;
});
</script>
<QueryClientProvider client={queryClient}>
{#if ready}
{@render children()}
{/if}
</QueryClientProvider>

2
src/routes/+layout.ts Normal file
View file

@ -0,0 +1,2 @@
export const ssr = false;
export const prerender = false;

14
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,14 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { auth } from '$lib/auth/store.svelte';
import { today } from '$lib/utils/date';
import { onMount } from 'svelte';
onMount(() => {
if (auth.isAuthenticated) {
goto(`/diary/${today()}`, { replaceState: true });
} else {
goto('/login', { replaceState: true });
}
});
</script>

3
static/robots.txt Normal file
View file

@ -0,0 +1,3 @@
# allow crawling everything by default
User-agent: *
Disallow:

21
svelte.config.js Normal file
View file

@ -0,0 +1,21 @@
import adapter from '@sveltejs/adapter-static';
import { relative, sep } from 'node:path';
/** @type {import('@sveltejs/kit').Config} */
const config = {
compilerOptions: {
runes: ({ filename }) => {
const relativePath = relative(import.meta.dirname, filename);
const pathSegments = relativePath.toLowerCase().split(sep);
return pathSegments.includes('node_modules') ? undefined : true;
}
},
kit: {
adapter: adapter({ fallback: 'index.html' }),
alias: {
$lib: './src/lib'
}
}
};
export default config;

20
tsconfig.json Normal file
View file

@ -0,0 +1,20 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"rewriteRelativeImportExtensions": true,
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}

52
vite.config.ts Normal file
View file

@ -0,0 +1,52 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
server: {
proxy: {
'/api': {
target: process.env.VITE_API_URL ?? 'http://localhost:8000',
changeOrigin: true
}
}
},
plugins: [
tailwindcss(),
sveltekit(),
VitePWA({
registerType: 'autoUpdate',
devOptions: { enabled: true },
manifest: {
name: 'Fooder',
short_name: 'Fooder',
description: 'Simple calorie and macro tracker',
theme_color: '#16a34a',
background_color: '#09090b',
display: 'standalone',
orientation: 'portrait',
start_url: '/',
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
]
},
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
runtimeCaching: [
{
urlPattern: /^https?:\/\/.*\/api\//,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
networkTimeoutSeconds: 5,
cacheableResponse: { statuses: [200] }
}
}
]
}
})
]
});