[ts] lint

This commit is contained in:
Piotr Domański 2026-04-16 11:37:28 +02:00
parent 8656e92c5d
commit 4eef8a0f05
34 changed files with 2561 additions and 2062 deletions

16
src/app.d.ts vendored
View file

@ -1,13 +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 {}
}
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
export { };

View file

@ -1,20 +1,20 @@
import type { HandleClientError } from '@sveltejs/kit';
export const handleError: HandleClientError = ({ error }) => {
const msg = error instanceof Error ? error.message : String(error);
const msg = error instanceof Error ? error.message : String(error);
// SvelteKit lazy-loads route chunks via dynamic import(). When offline and the
// chunk isn't cached, the import fails with this error. Show a helpful message
// instead of the generic "Internal Error" page.
if (
msg.includes('Importing a module script failed') ||
msg.includes('Failed to fetch dynamically imported module') ||
msg.includes('Unable to preload CSS')
) {
return {
message: 'App not cached yet. Open the app while online at least once to enable offline use.'
};
}
// SvelteKit lazy-loads route chunks via dynamic import(). When offline and the
// chunk isn't cached, the import fails with this error. Show a helpful message
// instead of the generic "Internal Error" page.
if (
msg.includes('Importing a module script failed') ||
msg.includes('Failed to fetch dynamically imported module') ||
msg.includes('Unable to preload CSS')
) {
return {
message: 'App not cached yet. Open the app while online at least once to enable offline use.'
};
}
return { message: msg || 'An unexpected error occurred.' };
return { message: msg || 'An unexpected error occurred.' };
};

View file

@ -4,56 +4,56 @@ import type { Token } 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);
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, captchaToken: string): Promise<void> {
const res = await fetch(`${BASE}/user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, captcha_token: captchaToken })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Registration failed'), { status: res.status, detail: err });
}
const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token);
const res = await fetch(`${BASE}/user`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, captcha_token: captchaToken })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Registration failed'), { status: res.status, detail: err });
}
const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token);
}
export async function tryRestoreSession(): Promise<boolean> {
const refreshToken = auth.getRefreshToken();
if (!refreshToken) return false;
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;
}
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();
auth.clear();
}

View file

@ -9,172 +9,172 @@ let isRefreshing = false;
let refreshPromise: Promise<string | null> | null = null;
async function doRefresh(): Promise<string | null> {
const refreshToken = auth.getRefreshToken();
if (!refreshToken) return 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;
}
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;
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;
// 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
path: string,
options: RequestInit = {},
retry = true
): Promise<Response> {
const token = await getValidToken();
const token = await getValidToken();
const headers = new Headers(options.headers);
if (token) headers.set('Authorization', `Bearer ${token}`);
const headers = new Headers(options.headers);
if (token) headers.set('Authorization', `Bearer ${token}`);
const res = await fetch(`${BASE}${path}`, { ...options, headers });
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 });
}
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;
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();
const res = await apiFetch(path);
if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
return res.json();
}
// Auth endpoints must never be queued (token ops need live responses)
function isAuthPath(path: string) {
return path.startsWith('/token/');
return path.startsWith('/token/');
}
// A TypeError thrown by fetch() always means a network-level failure
function isNetworkFailure(e: unknown): boolean {
return e instanceof TypeError;
return e instanceof TypeError;
}
// 5xx from the proxy/server when backend is down — treat same as offline
function isServerUnavailable(res: Response): boolean {
return res.status >= 500;
return res.status >= 500;
}
async function queueMutation(method: 'POST' | 'PATCH' | 'DELETE', path: string, body: unknown): Promise<void> {
network.setOffline();
await enqueueMutation({ method, url: path, body });
network.incrementPending();
network.setOffline();
await enqueueMutation({ method, url: path, body });
network.incrementPending();
}
export async function apiPost<T>(path: string, body: unknown): Promise<T> {
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('POST', path, body);
return {} as T;
}
let res: Response;
try {
res = await apiFetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('POST', path, body);
return {} as T;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('POST', path, body);
return {} as T;
}
const err = await res.json().catch(() => ({}));
throw Object.assign(new Error(`POST ${path} failed: ${res.status}`), { status: res.status, detail: err });
}
return res.json();
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('POST', path, body);
return {} as T;
}
let res: Response;
try {
res = await apiFetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('POST', path, body);
return {} as T;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('POST', path, body);
return {} as T;
}
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> {
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
let res: Response;
try {
res = await apiFetch(path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
throw new Error(`PATCH ${path} failed: ${res.status}`);
}
return res.json();
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
let res: Response;
try {
res = await apiFetch(path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('PATCH', path, body);
return {} as T;
}
throw new Error(`PATCH ${path} failed: ${res.status}`);
}
return res.json();
}
export async function apiDelete(path: string): Promise<void> {
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('DELETE', path, undefined);
return;
}
let res: Response;
try {
res = await apiFetch(path, { method: 'DELETE' });
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('DELETE', path, undefined);
return;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('DELETE', path, undefined);
return;
}
throw new Error(`DELETE ${path} failed: ${res.status}`);
}
if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('DELETE', path, undefined);
return;
}
let res: Response;
try {
res = await apiFetch(path, { method: 'DELETE' });
} catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('DELETE', path, undefined);
return;
}
throw e;
}
if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('DELETE', path, undefined);
return;
}
throw new Error(`DELETE ${path} failed: ${res.status}`);
}
}

View file

@ -2,22 +2,22 @@ import { apiFetch, apiPost, apiPatch } from './client';
import type { Diary } from '$lib/types/api';
export async function getDiary(date: string): Promise<Diary | null> {
const res = await apiFetch(`/diary/${date}`);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`GET /diary/${date} failed: ${res.status}`);
return res.json();
const res = await apiFetch(`/diary/${date}`);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`GET /diary/${date} failed: ${res.status}`);
return res.json();
}
export function createDiary(date: string): Promise<Diary> {
return apiPost<Diary>('/diary', { date });
return apiPost<Diary>('/diary', { date });
}
export function updateDiary(date: string, patch: {
protein_goal?: number | null;
carb_goal?: number | null;
fat_goal?: number | null;
fiber_goal?: number | null;
calories_goal?: number | null;
protein_goal?: number | null;
carb_goal?: number | null;
fat_goal?: number | null;
fiber_goal?: number | null;
calories_goal?: number | null;
}): Promise<Diary> {
return apiPatch<Diary>(`/diary/${date}`, patch);
return apiPatch<Diary>(`/diary/${date}`, patch);
}

View file

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

View file

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

View file

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

View file

@ -2,9 +2,9 @@ import { apiGet, apiPatch } from './client';
import type { UserSettings } from '$lib/types/api';
export function getUserSettings(): Promise<UserSettings> {
return apiGet<UserSettings>('/user/settings');
return apiGet<UserSettings>('/user/settings');
}
export function updateUserSettings(patch: Omit<Partial<UserSettings>, 'id' | 'calories_goal'> & { calories_goal?: number | null }): Promise<UserSettings> {
return apiPatch<UserSettings>('/user/settings', patch);
return apiPatch<UserSettings>('/user/settings', patch);
}

View file

@ -3,44 +3,44 @@ import type { User } from '$lib/types/api';
const REFRESH_TOKEN_KEY = 'fooder_refresh_token';
interface AuthState {
accessToken: string | null;
user: User | null;
accessToken: string | null;
user: User | null;
}
let state = $state<AuthState>({
accessToken: null,
user: null
accessToken: null,
user: null
});
export const auth = {
get accessToken() {
return state.accessToken;
},
get user() {
return state.user;
},
get isAuthenticated() {
return state.accessToken !== null;
},
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);
},
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;
},
setAccessToken(accessToken: string) {
state.accessToken = accessToken;
},
getRefreshToken(): string | null {
if (typeof localStorage === 'undefined') return null;
return localStorage.getItem(REFRESH_TOKEN_KEY);
},
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);
}
clear() {
state.accessToken = null;
state.user = null;
localStorage.removeItem(REFRESH_TOKEN_KEY);
}
};

View file

@ -1,91 +1,119 @@
<script lang="ts">
import { today } from '$lib/utils/date';
import { today } from "$lib/utils/date";
interface Props {
selected: string;
onSelect: (date: string) => void;
}
interface Props {
selected: string;
onSelect: (date: string) => void;
}
let { selected, onSelect }: Props = $props();
let { selected, onSelect }: Props = $props();
const todayStr = today();
const todayStr = today();
let viewYear = $state(parseInt(selected.slice(0, 4)));
let viewMonth = $state(parseInt(selected.slice(5, 7)) - 1); // 0-based
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 prevMonth() {
if (viewMonth === 0) {
viewYear--;
viewMonth = 11;
} else viewMonth--;
}
function nextMonth() {
if (viewMonth === 11) { viewYear++; viewMonth = 0; }
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' })
);
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')}`;
}
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;
});
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="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 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
<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>
? '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

@ -1,45 +1,57 @@
<script lang="ts">
interface Props {
date: string;
label: string;
onPrev: () => void;
onNext: () => void;
isToday: boolean;
onDateClick?: () => void;
}
interface Props {
date: string;
label: string;
onPrev: () => void;
onNext: () => void;
isToday: boolean;
onDateClick?: () => void;
}
let { date, label, onPrev, onNext, isToday, onDateClick }: Props = $props();
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={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={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>
<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

@ -1,44 +1,59 @@
<script lang="ts">
import type { Entry } from '$lib/types/api';
import { kcal, g } from '$lib/utils/format';
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;
}
interface Props {
entry: Entry;
onDelete: (id: number) => void;
onEdit: (entry: Entry) => void;
}
let { entry, onDelete, onEdit }: Props = $props();
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"
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-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>
<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>
<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

@ -1,203 +1,263 @@
<script lang="ts">
import type { Diary } from '$lib/types/api';
import { kcal, g } from '$lib/utils/format';
import { updateDiary } from '$lib/api/diary';
import { updateUserSettings } from '$lib/api/settings';
import { useQueryClient } from '@tanstack/svelte-query';
import Sheet from '$lib/components/ui/Sheet.svelte';
import type { Diary } from "$lib/types/api";
import { kcal, g } from "$lib/utils/format";
import { updateDiary } from "$lib/api/diary";
import { updateUserSettings } from "$lib/api/settings";
import { useQueryClient } from "@tanstack/svelte-query";
import Sheet from "$lib/components/ui/Sheet.svelte";
interface Props {
diary: Diary;
date: string;
}
interface Props {
diary: Diary;
date: string;
}
let { diary, date }: Props = $props();
let { diary, date }: Props = $props();
const queryClient = useQueryClient();
const queryClient = useQueryClient();
// Calorie ring
const pct = $derived(diary.calories_goal > 0
? Math.min(100, Math.round((diary.calories / diary.calories_goal) * 100))
: 0);
const circumference = 2 * Math.PI * 40;
const dash = $derived(circumference * (pct / 100));
// Calorie ring
const pct = $derived(
diary.calories_goal > 0
? Math.min(100, Math.round((diary.calories / diary.calories_goal) * 100))
: 0,
);
const circumference = 2 * Math.PI * 40;
const dash = $derived(circumference * (pct / 100));
const macroRows = $derived([
{ label: 'Protein', value: g(diary.protein), goal: diary.protein_goal, color: 'bg-blue-500' },
{ label: 'Carbs', value: g(diary.carb), goal: diary.carb_goal, color: 'bg-yellow-500' },
{ label: 'Fat', value: g(diary.fat), goal: diary.fat_goal, color: 'bg-orange-500' },
{ label: 'Fiber', value: g(diary.fiber), goal: diary.fiber_goal, color: 'bg-green-500' },
]);
const macroRows = $derived([
{
label: "Protein",
value: g(diary.protein),
goal: diary.protein_goal,
color: "bg-blue-500",
},
{
label: "Carbs",
value: g(diary.carb),
goal: diary.carb_goal,
color: "bg-yellow-500",
},
{
label: "Fat",
value: g(diary.fat),
goal: diary.fat_goal,
color: "bg-orange-500",
},
{
label: "Fiber",
value: g(diary.fiber),
goal: diary.fiber_goal,
color: "bg-green-500",
},
]);
// Goal editing sheet
let sheetOpen = $state(false);
let saving = $state(false);
let syncSettingsOpen = $state(false);
let lastSavedForm: typeof form | null = null;
let form = $state<{
calories_goal: number | null;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
}>({
calories_goal: null,
protein_goal: diary.protein_goal,
carb_goal: diary.carb_goal,
fat_goal: diary.fat_goal,
fiber_goal: diary.fiber_goal,
});
// Goal editing sheet
let sheetOpen = $state(false);
let saving = $state(false);
let syncSettingsOpen = $state(false);
let lastSavedForm: typeof form | null = null;
let form = $state<{
calories_goal: number | null;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
}>({
calories_goal: null,
protein_goal: diary.protein_goal,
carb_goal: diary.carb_goal,
fat_goal: diary.fat_goal,
fiber_goal: diary.fiber_goal,
});
$effect(() => {
form = {
calories_goal: null, // always reset to auto when diary refreshes
protein_goal: diary.protein_goal,
carb_goal: diary.carb_goal,
fat_goal: diary.fat_goal,
fiber_goal: diary.fiber_goal,
};
});
$effect(() => {
form = {
calories_goal: null, // always reset to auto when diary refreshes
protein_goal: diary.protein_goal,
carb_goal: diary.carb_goal,
fat_goal: diary.fat_goal,
fiber_goal: diary.fiber_goal,
};
});
async function handleSave(e: SubmitEvent) {
e.preventDefault();
saving = true;
try {
await updateDiary(date, form);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
lastSavedForm = { ...form };
sheetOpen = false;
syncSettingsOpen = true;
} finally {
saving = false;
}
}
async function handleSave(e: SubmitEvent) {
e.preventDefault();
saving = true;
try {
await updateDiary(date, form);
await queryClient.invalidateQueries({ queryKey: ["diary", date] });
lastSavedForm = { ...form };
sheetOpen = false;
syncSettingsOpen = true;
} finally {
saving = false;
}
}
async function handleSyncToSettings() {
if (!lastSavedForm) return;
await updateUserSettings(lastSavedForm);
syncSettingsOpen = false;
}
async function handleSyncToSettings() {
if (!lastSavedForm) return;
await updateUserSettings(lastSavedForm);
syncSettingsOpen = false;
}
</script>
<div class="bg-zinc-900 rounded-2xl p-4 relative">
<!-- Mobile: ring left, bars right. Desktop: ring top-center, bars below -->
<div class="flex items-center gap-5 lg:flex-col lg:items-stretch lg:gap-4">
<!-- Mobile: ring left, bars right. Desktop: ring top-center, bars below -->
<div class="flex items-center gap-5 lg:flex-col lg:items-stretch lg:gap-4">
<!-- Calorie ring -->
<div class="relative w-24 h-24 shrink-0 lg:w-32 lg:h-32 lg:mx-auto">
<svg class="w-full h-full -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 lg:text-2xl"
>{kcal(diary.calories)}</span
>
<span class="text-xs text-zinc-500">
{diary.calories_goal > 0 ? `/ ${kcal(diary.calories_goal)}` : "kcal"}
</span>
</div>
</div>
<!-- Calorie ring -->
<div class="relative w-24 h-24 shrink-0 lg:w-32 lg:h-32 lg:mx-auto">
<svg class="w-full h-full -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 lg:text-2xl">{kcal(diary.calories)}</span>
<span class="text-xs text-zinc-500">
{diary.calories_goal > 0 ? `/ ${kcal(diary.calories_goal)}` : 'kcal'}
</span>
</div>
</div>
<!-- Macro bars -->
<div class="flex-1 space-y-2 min-w-0">
{#each macroRows 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{macro.goal > 0 ? ` / ${macro.goal}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: {macro.goal > 0
? Math.min(100, (macro.value / macro.goal) * 100)
: 0}%"
></div>
</div>
</div>
{/each}
</div>
<!-- Macro bars -->
<div class="flex-1 space-y-2 min-w-0">
{#each macroRows 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{macro.goal > 0 ? ` / ${macro.goal}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: {macro.goal > 0 ? Math.min(100, (macro.value / macro.goal) * 100) : 0}%"
></div>
</div>
</div>
{/each}
</div>
<!-- Edit goals button -->
<button
onclick={() => sheetOpen = true}
class="self-start shrink-0 w-7 h-7 flex items-center justify-center rounded-full text-zinc-600 hover:text-zinc-300 hover:bg-zinc-800 transition-colors lg:absolute lg:top-3 lg:right-3"
aria-label="Edit day goals"
>
<svg class="w-3.5 h-3.5" 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>
</div>
<!-- Edit goals button -->
<button
onclick={() => (sheetOpen = true)}
class="self-start shrink-0 w-7 h-7 flex items-center justify-center rounded-full text-zinc-600 hover:text-zinc-300 hover:bg-zinc-800 transition-colors lg:absolute lg:top-3 lg:right-3"
aria-label="Edit day goals"
>
<svg
class="w-3.5 h-3.5"
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>
</div>
</div>
<Sheet open={syncSettingsOpen} onclose={() => syncSettingsOpen = false} title="Update global settings?">
<p class="text-sm text-zinc-400 mb-5">Override your default macro goals in user settings with these values as well?</p>
<div class="flex gap-3">
<button
onclick={() => syncSettingsOpen = false}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors"
>No</button>
<button
onclick={handleSyncToSettings}
class="flex-1 bg-green-600 hover:bg-green-500 rounded-xl py-3 font-semibold transition-colors"
>Yes</button>
</div>
<Sheet
open={syncSettingsOpen}
onclose={() => (syncSettingsOpen = false)}
title="Update global settings?"
>
<p class="text-sm text-zinc-400 mb-5">
Override your default macro goals in user settings with these values as
well?
</p>
<div class="flex gap-3">
<button
onclick={() => (syncSettingsOpen = false)}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors"
>No</button
>
<button
onclick={handleSyncToSettings}
class="flex-1 bg-green-600 hover:bg-green-500 rounded-xl py-3 font-semibold transition-colors"
>Yes</button
>
</div>
</Sheet>
<Sheet open={sheetOpen} onclose={() => sheetOpen = false} title="Day goals">
<form onsubmit={handleSave} class="space-y-4">
<!-- Calories: null = auto-calculated by server from macros -->
<div>
<div class="flex items-center justify-between mb-1.5">
<label class="text-sm text-zinc-400">Calories <span class="text-zinc-600">(kcal)</span></label>
{#if form.calories_goal === null}
<span class="text-xs font-medium text-zinc-500 bg-zinc-800 px-2 py-0.5 rounded-full">auto</span>
{/if}
</div>
<input
type="number"
min="0"
step="1"
value={form.calories_goal ?? diary.calories_goal}
oninput={(e) => {
const v = e.currentTarget.value;
form.calories_goal = v === '' ? null : Number(v);
}}
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
<p class="text-xs text-zinc-600 mt-1">Clear to auto-calculate from macro goals</p>
</div>
<Sheet open={sheetOpen} onclose={() => (sheetOpen = false)} title="Day goals">
<form onsubmit={handleSave} class="space-y-4">
<!-- Calories: null = auto-calculated by server from macros -->
<div>
<div class="flex items-center justify-between mb-1.5">
<label class="text-sm text-zinc-400"
>Calories <span class="text-zinc-600">(kcal)</span></label
>
{#if form.calories_goal === null}
<span
class="text-xs font-medium text-zinc-500 bg-zinc-800 px-2 py-0.5 rounded-full"
>auto</span
>
{/if}
</div>
<input
type="number"
min="0"
step="1"
value={form.calories_goal ?? diary.calories_goal}
oninput={(e) => {
const v = e.currentTarget.value;
form.calories_goal = v === "" ? null : Number(v);
}}
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
<p class="text-xs text-zinc-600 mt-1">
Clear to auto-calculate from macro goals
</p>
</div>
{#each [
{ label: 'Protein', key: 'protein_goal' as const, unit: 'g' },
{ label: 'Carbs', key: 'carb_goal' as const, unit: 'g' },
{ label: 'Fat', key: 'fat_goal' as const, unit: 'g' },
{ label: 'Fiber', key: 'fiber_goal' as const, unit: 'g' },
] as field}
<div>
<label class="block text-sm text-zinc-400 mb-1.5">{field.label} <span class="text-zinc-600">({field.unit})</span></label>
<input
type="number"
min="0"
step="1"
bind:value={form[field.key]}
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{/each}
{#each [{ label: "Protein", key: "protein_goal" as const, unit: "g" }, { label: "Carbs", key: "carb_goal" as const, unit: "g" }, { label: "Fat", key: "fat_goal" as const, unit: "g" }, { label: "Fiber", key: "fiber_goal" as const, unit: "g" }] as field}
<div>
<label class="block text-sm text-zinc-400 mb-1.5"
>{field.label}
<span class="text-zinc-600">({field.unit})</span></label
>
<input
type="number"
min="0"
step="1"
bind:value={form[field.key]}
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{/each}
<button
type="submit"
disabled={saving}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{saving ? 'Saving…' : 'Save'}
</button>
</form>
<button
type="submit"
disabled={saving}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{saving ? "Saving…" : "Save"}
</button>
</form>
</Sheet>

View file

@ -1,213 +1,285 @@
<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';
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;
}
interface Props {
meal: Meal;
date: string;
}
let { meal, date }: Props = $props();
let { meal, date }: Props = $props();
const queryClient = useQueryClient();
let collapsed = $state(false);
let saving = $state(false);
let renameOpen = $state(false);
let renameName = $state('');
let renaming = $state(false);
let presetOpen = $state(false);
let presetName = $state('');
const queryClient = useQueryClient();
let collapsed = $state(false);
let saving = $state(false);
let renameOpen = $state(false);
let renameName = $state("");
let renaming = $state(false);
let presetOpen = $state(false);
let presetName = $state("");
function openRename() {
renameName = meal.name;
renameOpen = true;
}
function openRename() {
renameName = meal.name;
renameOpen = true;
}
async function handleRename(e: SubmitEvent) {
e.preventDefault();
if (!renameName.trim()) return;
renaming = true;
try {
await renameMeal(date, meal.id, renameName.trim());
queryClient.invalidateQueries({ queryKey: ['diary', date] });
renameOpen = false;
} finally {
renaming = false;
}
}
async function handleRename(e: SubmitEvent) {
e.preventDefault();
if (!renameName.trim()) return;
renaming = true;
try {
await renameMeal(date, 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(date, meal.id);
queryClient.invalidateQueries({ queryKey: ['diary', date] });
}
async function handleDeleteMeal() {
if (!confirm(`Delete meal "${meal.name}"?`)) return;
await deleteMeal(date, meal.id);
queryClient.invalidateQueries({ queryKey: ["diary", date] });
}
function openPresetSheet() {
presetName = meal.name;
presetOpen = true;
}
function openPresetSheet() {
presetName = meal.name;
presetOpen = true;
}
async function handleSavePreset(e: SubmitEvent) {
e.preventDefault();
saving = true;
try {
await saveMealAsPreset(date, meal.id, presetName.trim() || meal.name);
queryClient.invalidateQueries({ queryKey: ['presets'] });
presetOpen = false;
} finally {
saving = false;
}
}
async function handleSavePreset(e: SubmitEvent) {
e.preventDefault();
saving = true;
try {
await saveMealAsPreset(date, meal.id, presetName.trim() || meal.name);
queryClient.invalidateQueries({ queryKey: ["presets"] });
presetOpen = false;
} finally {
saving = false;
}
}
async function handleDeleteEntry(entryId: number) {
await deleteEntry(date, meal.id, entryId);
queryClient.invalidateQueries({ queryKey: ['diary', date] });
}
async function handleDeleteEntry(entryId: number) {
await deleteEntry(date, meal.id, entryId);
queryClient.invalidateQueries({ queryKey: ["diary", date] });
}
function handleEditEntry(entry: import('$lib/types/api').Entry) {
goto(`/diary/${date}/edit-entry/${entry.id}`);
}
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>
<!-- 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 items-center">
<!-- Add entry -->
<button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)}
class="flex items-center gap-1 px-2.5 h-7 rounded-full bg-green-600 hover:bg-green-500 text-white transition-colors text-xs font-medium"
aria-label="Add food"
>
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4" />
</svg>
Add
</button>
<div class="flex gap-1 ml-2 shrink-0 items-center">
<!-- Add entry -->
<button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)}
class="flex items-center gap-1 px-2.5 h-7 rounded-full bg-green-600 hover:bg-green-500 text-white transition-colors text-xs font-medium"
aria-label="Add food"
>
<svg
class="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2.5"
d="M12 4v16m8-8H4"
/>
</svg>
Add
</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>
<!-- 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={openPresetSheet}
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>
<!-- Save as preset -->
<button
onclick={openPresetSheet}
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>
<!-- 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}
<!-- 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={presetOpen} onclose={() => presetOpen = false} title="Save as preset">
<form onsubmit={handleSavePreset} class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1.5">Preset name</label>
<input
type="text"
bind:value={presetName}
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"
/>
</div>
<button
type="submit"
disabled={saving || !presetName.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{saving ? 'Saving…' : 'Save preset'}
</button>
</form>
<Sheet
open={presetOpen}
onclose={() => (presetOpen = false)}
title="Save as preset"
>
<form onsubmit={handleSavePreset} class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1.5">Preset name</label>
<input
type="text"
bind:value={presetName}
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"
/>
</div>
<button
type="submit"
disabled={saving || !presetName.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{saving ? "Saving…" : "Save preset"}
</button>
</form>
</Sheet>
<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
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

@ -1,154 +1,223 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { onMount, onDestroy } from "svelte";
interface Props {
ondetect: (barcode: string) => void;
onclose: () => void;
}
interface Props {
ondetect: (barcode: string) => void;
onclose: () => void;
}
let { ondetect, onclose }: Props = $props();
let { ondetect, onclose }: Props = $props();
let videoEl = $state<HTMLVideoElement | null>(null);
let error = $state<string | null>(null);
let stream: MediaStream | null = null;
let animFrame: number | null = null;
let detector: InstanceType<typeof BarcodeDetector> | null = null;
let detected = $state(false);
let videoEl = $state<HTMLVideoElement | null>(null);
let error = $state<string | null>(null);
let stream: MediaStream | null = null;
let animFrame: number | null = null;
let detector: InstanceType<typeof BarcodeDetector> | null = null;
let detected = $state(false);
onMount(async () => {
// Use native BarcodeDetector if available, otherwise load polyfill (Safari, Firefox)
let BarcodeDetectorImpl: typeof BarcodeDetector;
if ('BarcodeDetector' in window) {
BarcodeDetectorImpl = BarcodeDetector;
} else {
const { BarcodeDetector: Polyfill } = await import('barcode-detector/ponyfill');
BarcodeDetectorImpl = Polyfill as unknown as typeof BarcodeDetector;
}
onMount(async () => {
// Use native BarcodeDetector if available, otherwise load polyfill (Safari, Firefox)
let BarcodeDetectorImpl: typeof BarcodeDetector;
if ("BarcodeDetector" in window) {
BarcodeDetectorImpl = BarcodeDetector;
} else {
const { BarcodeDetector: Polyfill } = await import(
"barcode-detector/ponyfill"
);
BarcodeDetectorImpl = Polyfill as unknown as typeof BarcodeDetector;
}
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }
});
} catch {
error = 'Camera access denied. Please allow camera permission and try again.';
return;
}
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment",
width: { ideal: 1280 },
height: { ideal: 720 },
},
});
} catch {
error =
"Camera access denied. Please allow camera permission and try again.";
return;
}
if (!videoEl) return;
videoEl.srcObject = stream;
await videoEl.play();
if (!videoEl) return;
videoEl.srcObject = stream;
await videoEl.play();
detector = new BarcodeDetectorImpl({ formats: ['ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128', 'code_39', 'qr_code'] });
scanLoop();
});
detector = new BarcodeDetectorImpl({
formats: [
"ean_13",
"ean_8",
"upc_a",
"upc_e",
"code_128",
"code_39",
"qr_code",
],
});
scanLoop();
});
onDestroy(cleanup);
onDestroy(cleanup);
function cleanup() {
if (animFrame !== null) cancelAnimationFrame(animFrame);
stream?.getTracks().forEach(t => t.stop());
}
function cleanup() {
if (animFrame !== null) cancelAnimationFrame(animFrame);
stream?.getTracks().forEach((t) => t.stop());
}
async function scanLoop() {
if (!videoEl || !detector || videoEl.readyState < 2) {
animFrame = requestAnimationFrame(scanLoop);
return;
}
async function scanLoop() {
if (!videoEl || !detector || videoEl.readyState < 2) {
animFrame = requestAnimationFrame(scanLoop);
return;
}
try {
const results = await detector.detect(videoEl);
if (results.length > 0 && !detected) {
detected = true;
cleanup();
ondetect(results[0].rawValue);
return;
}
} catch {
// frame not ready, keep scanning
}
try {
const results = await detector.detect(videoEl);
if (results.length > 0 && !detected) {
detected = true;
cleanup();
ondetect(results[0].rawValue);
return;
}
} catch {
// frame not ready, keep scanning
}
animFrame = requestAnimationFrame(scanLoop);
}
animFrame = requestAnimationFrame(scanLoop);
}
</script>
<!-- Full-screen scanner overlay -->
<div class="fixed inset-0 z-50 bg-black flex flex-col">
<!-- Top bar -->
<div class="flex items-center justify-between px-4 pt-[calc(1rem+var(--safe-top))] pb-4">
<span class="text-sm font-medium text-white">Scan barcode</span>
<button
onclick={() => { cleanup(); onclose(); }}
class="w-9 h-9 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
aria-label="Close scanner"
>
<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="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- Top bar -->
<div
class="flex items-center justify-between px-4 pt-[calc(1rem+var(--safe-top))] pb-4"
>
<span class="text-sm font-medium text-white">Scan barcode</span>
<button
onclick={() => {
cleanup();
onclose();
}}
class="w-9 h-9 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition-colors"
aria-label="Close scanner"
>
<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="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{#if error}
<div class="flex-1 flex items-center justify-center px-8 text-center">
<div>
<svg class="w-12 h-12 text-zinc-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01M5.07 19H19a2 2 0 001.75-2.97L13.75 4a2 2 0 00-3.5 0L3.25 16.03A2 2 0 005.07 19z" />
</svg>
<p class="text-white text-sm">{error}</p>
</div>
</div>
{:else}
<!-- Camera feed -->
<div class="flex-1 relative overflow-hidden">
<!-- svelte-ignore a11y_media_has_caption -->
<video
bind:this={videoEl}
playsinline
muted
class="absolute inset-0 w-full h-full object-cover"
></video>
{#if error}
<div class="flex-1 flex items-center justify-center px-8 text-center">
<div>
<svg
class="w-12 h-12 text-zinc-500 mx-auto mb-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.5"
d="M12 9v2m0 4h.01M5.07 19H19a2 2 0 001.75-2.97L13.75 4a2 2 0 00-3.5 0L3.25 16.03A2 2 0 005.07 19z"
/>
</svg>
<p class="text-white text-sm">{error}</p>
</div>
</div>
{:else}
<!-- Camera feed -->
<div class="flex-1 relative overflow-hidden">
<!-- svelte-ignore a11y_media_has_caption -->
<video
bind:this={videoEl}
playsinline
muted
class="absolute inset-0 w-full h-full object-cover"
></video>
<!-- Dark overlay with cutout effect -->
<div class="absolute inset-0 flex items-center justify-center">
<div class="absolute inset-0 bg-black/50"></div>
<!-- Dark overlay with cutout effect -->
<div class="absolute inset-0 flex items-center justify-center">
<div class="absolute inset-0 bg-black/50"></div>
<!-- Scan window -->
<div class="relative z-10 w-64 h-40">
<!-- Clear the overlay in the scan area -->
<div class="absolute inset-0 bg-transparent mix-blend-normal"></div>
<!-- Scan window -->
<div class="relative z-10 w-64 h-40">
<!-- Clear the overlay in the scan area -->
<div class="absolute inset-0 bg-transparent mix-blend-normal"></div>
<!-- Corner brackets -->
<div class="absolute top-0 left-0 w-6 h-6 border-t-2 border-l-2 border-green-400 rounded-tl"></div>
<div class="absolute top-0 right-0 w-6 h-6 border-t-2 border-r-2 border-green-400 rounded-tr"></div>
<div class="absolute bottom-0 left-0 w-6 h-6 border-b-2 border-l-2 border-green-400 rounded-bl"></div>
<div class="absolute bottom-0 right-0 w-6 h-6 border-b-2 border-r-2 border-green-400 rounded-br"></div>
<!-- Corner brackets -->
<div
class="absolute top-0 left-0 w-6 h-6 border-t-2 border-l-2 border-green-400 rounded-tl"
></div>
<div
class="absolute top-0 right-0 w-6 h-6 border-t-2 border-r-2 border-green-400 rounded-tr"
></div>
<div
class="absolute bottom-0 left-0 w-6 h-6 border-b-2 border-l-2 border-green-400 rounded-bl"
></div>
<div
class="absolute bottom-0 right-0 w-6 h-6 border-b-2 border-r-2 border-green-400 rounded-br"
></div>
<!-- Scanning line -->
{#if !detected}
<div class="absolute left-1 right-1 h-0.5 bg-green-400/80 rounded animate-scan"></div>
{:else}
<div class="absolute inset-0 bg-green-400/20 rounded flex items-center justify-center">
<svg class="w-8 h-8 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
</svg>
</div>
{/if}
</div>
</div>
</div>
<!-- Scanning line -->
{#if !detected}
<div
class="absolute left-1 right-1 h-0.5 bg-green-400/80 rounded animate-scan"
></div>
{:else}
<div
class="absolute inset-0 bg-green-400/20 rounded flex items-center justify-center"
>
<svg
class="w-8 h-8 text-green-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2.5"
d="M5 13l4 4L19 7"
/>
</svg>
</div>
{/if}
</div>
</div>
</div>
<!-- Hint -->
<div class="py-6 text-center pb-[calc(1.5rem+var(--safe-bottom))]">
<p class="text-zinc-400 text-sm">Point the camera at a barcode</p>
</div>
{/if}
<!-- Hint -->
<div class="py-6 text-center pb-[calc(1.5rem+var(--safe-bottom))]">
<p class="text-zinc-400 text-sm">Point the camera at a barcode</p>
</div>
{/if}
</div>
<style>
@keyframes scan {
0%, 100% { top: 8px; }
50% { top: calc(100% - 8px); }
}
.animate-scan {
animation: scan 1.8s ease-in-out infinite;
}
@keyframes scan {
0%,
100% {
top: 8px;
}
50% {
top: calc(100% - 8px);
}
}
.animate-scan {
animation: scan 1.8s ease-in-out infinite;
}
</style>

View file

@ -1,86 +1,99 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount } from "svelte";
interface Props {
open: boolean;
onclose: () => void;
title?: string;
children: import('svelte').Snippet;
}
interface Props {
open: boolean;
onclose: () => void;
title?: string;
children: import("svelte").Snippet;
}
let { open, onclose, title, children }: Props = $props();
let { open, onclose, title, children }: Props = $props();
let bottomOffset = $state(0);
let bottomOffset = $state(0);
onMount(() => {
const vv = window.visualViewport;
if (!vv) return;
onMount(() => {
const vv = window.visualViewport;
if (!vv) return;
function update() {
bottomOffset = Math.max(0, window.innerHeight - vv!.offsetTop - vv!.height);
}
function update() {
bottomOffset = Math.max(
0,
window.innerHeight - vv!.offsetTop - vv!.height,
);
}
vv.addEventListener('resize', update);
vv.addEventListener('scroll', update);
vv.addEventListener("resize", update);
vv.addEventListener("scroll", update);
return () => {
vv.removeEventListener('resize', update);
vv.removeEventListener('scroll', update);
};
});
return () => {
vv.removeEventListener("resize", update);
vv.removeEventListener("scroll", update);
};
});
function handleBackdrop(e: MouseEvent) {
if (e.target === e.currentTarget) onclose();
}
function handleBackdrop(e: MouseEvent) {
if (e.target === e.currentTarget) onclose();
}
function handleKey(e: KeyboardEvent) {
if (e.key === 'Escape') 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>
<!-- 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
<!-- Sheet (mobile bottom sheet / desktop centered modal) -->
<div
class="fixed z-50 bg-zinc-900 px-4 pt-4
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"
style="bottom: {bottomOffset}px"
>
<!-- Handle (mobile only) -->
<div class="w-10 h-1 bg-zinc-700 rounded-full mx-auto mb-4 lg:hidden"></div>
style="bottom: {bottomOffset}px"
>
<!-- 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}
{#if title}
<h2 class="text-base font-semibold mb-4">{title}</h2>
{/if}
{@render children()}
</div>
{@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;
}
}
@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

@ -1,37 +1,49 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { goto } from "$app/navigation";
interface Props {
title: string;
back?: string | (() => void);
action?: import('svelte').Snippet;
}
interface Props {
title: string;
back?: string | (() => void);
action?: import("svelte").Snippet;
}
let { title, back, action }: Props = $props();
let { title, back, action }: Props = $props();
function handleBack() {
if (!back) return;
if (typeof back === 'function') back();
else goto(back);
}
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}
<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>
<h1 class="flex-1 font-semibold text-lg truncate">{title}</h1>
{#if action}
{@render action()}
{/if}
{#if action}
{@render action()}
{/if}
</header>

View file

@ -5,84 +5,84 @@ const DB_NAME = 'fooder';
const DB_VERSION = 2;
export interface QueuedMutation {
id?: number;
method: 'POST' | 'PATCH' | 'DELETE';
url: string;
body: unknown;
createdAt: number;
id?: number;
method: 'POST' | 'PATCH' | 'DELETE';
url: string;
body: unknown;
createdAt: number;
}
let dbInstance: IDBPDatabase | null = null;
export async function getDb() {
if (dbInstance) return dbInstance;
dbInstance = await openDB(DB_NAME, DB_VERSION, {
upgrade(db, oldVersion) {
if (oldVersion < 1) {
db.createObjectStore('diaries', { keyPath: 'date' });
db.createObjectStore('mutation_queue', { keyPath: 'id', autoIncrement: true });
}
if (oldVersion < 2) {
if (!db.objectStoreNames.contains('products')) {
db.createObjectStore('products', { keyPath: 'id' });
}
}
}
});
return dbInstance;
if (dbInstance) return dbInstance;
dbInstance = await openDB(DB_NAME, DB_VERSION, {
upgrade(db, oldVersion) {
if (oldVersion < 1) {
db.createObjectStore('diaries', { keyPath: 'date' });
db.createObjectStore('mutation_queue', { keyPath: 'id', autoIncrement: true });
}
if (oldVersion < 2) {
if (!db.objectStoreNames.contains('products')) {
db.createObjectStore('products', { keyPath: 'id' });
}
}
}
});
return dbInstance;
}
// ── Diary cache ──────────────────────────────────────────────────────────────
export async function cacheDiary(diary: Diary): Promise<void> {
const db = await getDb();
await db.put('diaries', diary);
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);
const db = await getDb();
return db.get('diaries', date);
}
// ── Product cache ─────────────────────────────────────────────────────────────
export async function cacheProducts(products: Product[]): Promise<void> {
if (products.length === 0) return;
const db = await getDb();
const tx = db.transaction('products', 'readwrite');
await Promise.all(products.map(p => tx.store.put(p)));
await tx.done;
if (products.length === 0) return;
const db = await getDb();
const tx = db.transaction('products', 'readwrite');
await Promise.all(products.map(p => tx.store.put(p)));
await tx.done;
}
export async function searchCachedProducts(q: string): Promise<Product[]> {
const db = await getDb();
const all = await db.getAll('products');
if (!q.trim()) return all.slice(0, 30);
const lower = q.toLowerCase();
return all
.filter(p => p.name.toLowerCase().includes(lower))
.sort((a, b) => (b.usage_count_cached ?? 0) - (a.usage_count_cached ?? 0))
.slice(0, 30);
const db = await getDb();
const all = await db.getAll('products');
if (!q.trim()) return all.slice(0, 30);
const lower = q.toLowerCase();
return all
.filter(p => p.name.toLowerCase().includes(lower))
.sort((a, b) => (b.usage_count_cached ?? 0) - (a.usage_count_cached ?? 0))
.slice(0, 30);
}
// ── Mutation queue ────────────────────────────────────────────────────────────
export async function enqueueMutation(mutation: Omit<QueuedMutation, 'id' | 'createdAt'>): Promise<void> {
const db = await getDb();
await db.add('mutation_queue', { ...mutation, createdAt: Date.now() });
const db = await getDb();
await db.add('mutation_queue', { ...mutation, createdAt: Date.now() });
}
export async function getMutationQueue(): Promise<QueuedMutation[]> {
const db = await getDb();
return db.getAll('mutation_queue');
const db = await getDb();
return db.getAll('mutation_queue');
}
export async function dequeueMutation(id: number): Promise<void> {
const db = await getDb();
await db.delete('mutation_queue', id);
const db = await getDb();
await db.delete('mutation_queue', id);
}
export async function getMutationQueueLength(): Promise<number> {
const db = await getDb();
return db.count('mutation_queue');
const db = await getDb();
return db.count('mutation_queue');
}

View file

@ -9,171 +9,171 @@ import { network } from './network.svelte';
// ── Helpers ───────────────────────────────────────────────────────────────────
function macrosFromProduct(product: Product, grams: number) {
const f = grams / 100;
return {
calories: product.calories * f,
protein: product.protein * f,
carb: product.carb * f,
fat: product.fat * f,
fiber: product.fiber * f,
};
const f = grams / 100;
return {
calories: product.calories * f,
protein: product.protein * f,
carb: product.carb * f,
fat: product.fat * f,
fiber: product.fiber * f,
};
}
function addMacros<T extends { calories: number; protein: number; carb: number; fat: number; fiber: number }>(
obj: T,
delta: { calories: number; protein: number; carb: number; fat: number; fiber: number }
obj: T,
delta: { calories: number; protein: number; carb: number; fat: number; fiber: number }
): T {
return {
...obj,
calories: obj.calories + delta.calories,
protein: obj.protein + delta.protein,
carb: obj.carb + delta.carb,
fat: obj.fat + delta.fat,
fiber: obj.fiber + delta.fiber,
};
return {
...obj,
calories: obj.calories + delta.calories,
protein: obj.protein + delta.protein,
carb: obj.carb + delta.carb,
fat: obj.fat + delta.fat,
fiber: obj.fiber + delta.fiber,
};
}
// Persist optimistic diary to IndexedDB so it survives page reloads while offline.
// Uses JSON round-trip to strip Svelte 5 reactive proxies before structured clone.
// Non-throwing: in-memory TQ optimistic update works regardless.
async function persistOptimistic(queryClient: QueryClient, date: string) {
try {
const diary = queryClient.getQueryData<Diary>(['diary', date]);
if (diary) await cacheDiary(JSON.parse(JSON.stringify(diary)));
} catch {
// Non-critical — in-memory optimistic update already applied
}
try {
const diary = queryClient.getQueryData<Diary>(['diary', date]);
if (diary) await cacheDiary(JSON.parse(JSON.stringify(diary)));
} catch {
// Non-critical — in-memory optimistic update already applied
}
}
// ── Add entry ─────────────────────────────────────────────────────────────────
export async function offlineAddEntry(
queryClient: QueryClient,
date: string,
mealId: number,
product: Product,
grams: number
queryClient: QueryClient,
date: string,
mealId: number,
product: Product,
grams: number
): Promise<void> {
if (network.online) {
await createEntry(date, mealId, product.id, grams);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
if (network.online) {
await createEntry(date, mealId, product.id, grams);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
if (mealId < 0) {
throw new Error('Cannot add entry to an unsaved meal — please sync first.');
}
if (mealId < 0) {
throw new Error('Cannot add entry to an unsaved meal — please sync first.');
}
await enqueueMutation({ method: 'POST', url: `/diary/${date}/meal/${mealId}/entry`, body: { product_id: product.id, grams } });
network.incrementPending();
await enqueueMutation({ method: 'POST', url: `/diary/${date}/meal/${mealId}/entry`, body: { product_id: product.id, grams } });
network.incrementPending();
const macros = macrosFromProduct(product, grams);
// Strip Svelte reactive proxy from product before storing/using in structured clone contexts
const plainProduct: Product = JSON.parse(JSON.stringify(product));
const fakeEntry: Entry = { id: -Date.now(), grams, product_id: product.id, product: plainProduct, meal_id: mealId, ...macros };
const macros = macrosFromProduct(product, grams);
// Strip Svelte reactive proxy from product before storing/using in structured clone contexts
const plainProduct: Product = JSON.parse(JSON.stringify(product));
const fakeEntry: Entry = { id: -Date.now(), grams, product_id: product.id, product: plainProduct, meal_id: mealId, ...macros };
queryClient.setQueryData<Diary>(['diary', date], diary => {
if (!diary) return diary;
return addMacros({
...diary,
meals: diary.meals.map(meal =>
meal.id !== mealId ? meal : addMacros({
...meal,
entries: [...meal.entries, fakeEntry],
}, macros)
),
}, macros);
});
queryClient.setQueryData<Diary>(['diary', date], diary => {
if (!diary) return diary;
return addMacros({
...diary,
meals: diary.meals.map(meal =>
meal.id !== mealId ? meal : addMacros({
...meal,
entries: [...meal.entries, fakeEntry],
}, macros)
),
}, macros);
});
await persistOptimistic(queryClient, date);
await persistOptimistic(queryClient, date);
}
// ── Edit entry ────────────────────────────────────────────────────────────────
export async function offlineEditEntry(
queryClient: QueryClient,
date: string,
entryId: number,
newGrams: number
queryClient: QueryClient,
date: string,
entryId: number,
newGrams: number
): Promise<void> {
const diary = queryClient.getQueryData<Diary>(['diary', date]);
const mealId = diary?.meals.find(m => m.entries.some(e => e.id === entryId))?.id;
const diary = queryClient.getQueryData<Diary>(['diary', date]);
const mealId = diary?.meals.find(m => m.entries.some(e => e.id === entryId))?.id;
if (network.online) {
await updateEntry(date, mealId!, entryId, { grams: newGrams });
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
if (network.online) {
await updateEntry(date, mealId!, entryId, { grams: newGrams });
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
if (entryId < 0) {
throw new Error('Cannot edit an unsaved entry — please sync first.');
}
if (entryId < 0) {
throw new Error('Cannot edit an unsaved entry — please sync first.');
}
await enqueueMutation({ method: 'PATCH', url: `/diary/${date}/meal/${mealId}/entry/${entryId}`, body: { grams: newGrams } });
network.incrementPending();
await enqueueMutation({ method: 'PATCH', url: `/diary/${date}/meal/${mealId}/entry/${entryId}`, body: { grams: newGrams } });
network.incrementPending();
queryClient.setQueryData<Diary>(['diary', date], diary => {
if (!diary) return diary;
let delta = { calories: 0, protein: 0, carb: 0, fat: 0, fiber: 0 };
queryClient.setQueryData<Diary>(['diary', date], diary => {
if (!diary) return diary;
let delta = { calories: 0, protein: 0, carb: 0, fat: 0, fiber: 0 };
const meals = diary.meals.map(meal => {
const idx = meal.entries.findIndex(e => e.id === entryId);
if (idx === -1) return meal;
const meals = diary.meals.map(meal => {
const idx = meal.entries.findIndex(e => e.id === entryId);
if (idx === -1) return meal;
const old = meal.entries[idx];
const newMacros = macrosFromProduct(old.product, newGrams);
const oldMacros = macrosFromProduct(old.product, old.grams);
delta = {
calories: newMacros.calories - oldMacros.calories,
protein: newMacros.protein - oldMacros.protein,
carb: newMacros.carb - oldMacros.carb,
fat: newMacros.fat - oldMacros.fat,
fiber: newMacros.fiber - oldMacros.fiber,
};
const old = meal.entries[idx];
const newMacros = macrosFromProduct(old.product, newGrams);
const oldMacros = macrosFromProduct(old.product, old.grams);
delta = {
calories: newMacros.calories - oldMacros.calories,
protein: newMacros.protein - oldMacros.protein,
carb: newMacros.carb - oldMacros.carb,
fat: newMacros.fat - oldMacros.fat,
fiber: newMacros.fiber - oldMacros.fiber,
};
const updatedEntry: Entry = { ...old, grams: newGrams, ...newMacros };
const entries = [...meal.entries];
entries[idx] = updatedEntry;
return addMacros({ ...meal, entries }, delta);
});
const updatedEntry: Entry = { ...old, grams: newGrams, ...newMacros };
const entries = [...meal.entries];
entries[idx] = updatedEntry;
return addMacros({ ...meal, entries }, delta);
});
return addMacros({ ...diary, meals }, delta);
});
return addMacros({ ...diary, meals }, delta);
});
await persistOptimistic(queryClient, date);
await persistOptimistic(queryClient, date);
}
// ── Add meal ──────────────────────────────────────────────────────────────────
export async function offlineAddMeal(
queryClient: QueryClient,
date: string,
name: string
queryClient: QueryClient,
date: string,
name: string
): Promise<void> {
if (network.online) {
await createMeal(date, name || 'Meal');
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
if (network.online) {
await createMeal(date, name || 'Meal');
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
return;
}
await enqueueMutation({ method: 'POST', url: `/diary/${date}/meal`, body: { name: name || 'Meal' } });
network.incrementPending();
await enqueueMutation({ method: 'POST', url: `/diary/${date}/meal`, body: { name: name || 'Meal' } });
network.incrementPending();
const diary = queryClient.getQueryData<Diary>(['diary', date]);
const order = (diary?.meals.length ?? 0) + 1;
const fakeMeal: Meal = {
id: -Date.now(),
name: name || `Meal ${order}`,
order,
diary_id: diary?.id ?? 0,
entries: [],
calories: 0, protein: 0, carb: 0, fat: 0, fiber: 0,
};
const diary = queryClient.getQueryData<Diary>(['diary', date]);
const order = (diary?.meals.length ?? 0) + 1;
const fakeMeal: Meal = {
id: -Date.now(),
name: name || `Meal ${order}`,
order,
diary_id: diary?.id ?? 0,
entries: [],
calories: 0, protein: 0, carb: 0, fat: 0, fiber: 0,
};
queryClient.setQueryData<Diary>(['diary', date], d => {
if (!d) return d;
return { ...d, meals: [...d.meals, fakeMeal] };
});
queryClient.setQueryData<Diary>(['diary', date], d => {
if (!d) return d;
return { ...d, meals: [...d.meals, fakeMeal] };
});
await persistOptimistic(queryClient, date);
await persistOptimistic(queryClient, date);
}

View file

@ -3,18 +3,18 @@ let _pendingCount = $state(0);
let _syncing = $state(false);
if (typeof window !== 'undefined') {
window.addEventListener('online', () => { _online = true; });
window.addEventListener('offline', () => { _online = false; });
window.addEventListener('online', () => { _online = true; });
window.addEventListener('offline', () => { _online = false; });
}
export const network = {
get online() { return _online; },
get pendingCount() { return _pendingCount; },
get syncing() { return _syncing; },
get online() { return _online; },
get pendingCount() { return _pendingCount; },
get syncing() { return _syncing; },
incrementPending() { _pendingCount++; },
decrementPending() { _pendingCount = Math.max(0, _pendingCount - 1); },
setPendingCount(n: number) { _pendingCount = n; },
setSyncing(v: boolean) { _syncing = v; },
setOffline() { _online = false; }
incrementPending() { _pendingCount++; },
decrementPending() { _pendingCount = Math.max(0, _pendingCount - 1); },
setPendingCount(n: number) { _pendingCount = n; },
setSyncing(v: boolean) { _syncing = v; },
setOffline() { _online = false; }
};

View file

@ -7,34 +7,34 @@ import { apiFetch } from '$lib/api/client';
* Stops at the first failure to preserve ordering.
*/
export async function syncOfflineQueue(): Promise<number> {
const queue = await getMutationQueue();
let synced = 0;
const queue = await getMutationQueue();
let synced = 0;
for (const mutation of queue) {
try {
const headers: Record<string, string> = {};
if (mutation.body !== undefined) {
headers['Content-Type'] = 'application/json';
}
for (const mutation of queue) {
try {
const headers: Record<string, string> = {};
if (mutation.body !== undefined) {
headers['Content-Type'] = 'application/json';
}
const res = await apiFetch(mutation.url, {
method: mutation.method,
headers,
body: mutation.body !== undefined ? JSON.stringify(mutation.body) : undefined
});
const res = await apiFetch(mutation.url, {
method: mutation.method,
headers,
body: mutation.body !== undefined ? JSON.stringify(mutation.body) : undefined
});
if (res.ok) {
await dequeueMutation(mutation.id!);
synced++;
} else {
// Non-retryable failure (e.g. 400 validation error) — drop it to unblock the queue
await dequeueMutation(mutation.id!);
}
} catch {
// Network error mid-sync — stop here, retry next time online
break;
}
}
if (res.ok) {
await dequeueMutation(mutation.id!);
synced++;
} else {
// Non-retryable failure (e.g. 400 validation error) — drop it to unblock the queue
await dequeueMutation(mutation.id!);
}
} catch {
// Network error mid-sync — stop here, retry next time online
break;
}
}
return synced;
return synced;
}

View file

@ -1,105 +1,105 @@
export interface Token {
access_token: string;
refresh_token: string;
token_type: string;
access_token: string;
refresh_token: string;
token_type: string;
}
export interface User {
username: string;
username: string;
}
export interface Macros {
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
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;
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_id: number;
product: Product;
meal_id: number;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
id: number;
grams: number;
product_id: 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;
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;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
calories_goal: number;
meals: Meal[];
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
id: number;
date: string;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
calories_goal: number;
meals: Meal[];
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}
export interface Preset {
id: number;
name: string;
user_id: number;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
entries: PresetEntry[];
id: number;
name: string;
user_id: number;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
entries: PresetEntry[];
}
export interface UserSettings {
id: number;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
calories_goal: number;
id: number;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
calories_goal: number;
}
export interface PresetEntry {
id: number;
grams: number;
product_id: number;
preset_id: number;
product: Product;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
id: number;
grams: number;
product_id: number;
preset_id: number;
product: Product;
calories: number;
protein: number;
carb: number;
fat: number;
fiber: number;
}

View file

@ -1,25 +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}`;
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());
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);
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' });
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' });
}

View file

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

View file

@ -1,173 +1,295 @@
<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 { page } from '$app/state';
import { onMount } from 'svelte';
import { network } from '$lib/offline/network.svelte';
import { syncOfflineQueue } from '$lib/offline/sync';
import { getMutationQueueLength } from '$lib/offline/db';
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 { page } from "$app/state";
import { onMount } from "svelte";
import { network } from "$lib/offline/network.svelte";
import { syncOfflineQueue } from "$lib/offline/sync";
import { getMutationQueueLength } from "$lib/offline/db";
let { children } = $props();
const queryClient = useQueryClient();
let { children } = $props();
const queryClient = useQueryClient();
onMount(async () => {
if (!auth.isAuthenticated) goto('/login');
onMount(async () => {
if (!auth.isAuthenticated) goto("/login");
// Restore pending count from IndexedDB in case of page reload while offline
const queued = await getMutationQueueLength();
network.setPendingCount(queued);
// Restore pending count from IndexedDB in case of page reload while offline
const queued = await getMutationQueueLength();
network.setPendingCount(queued);
// Sync on reconnect
window.addEventListener('online', handleReconnect);
return () => window.removeEventListener('online', handleReconnect);
});
// Sync on reconnect
window.addEventListener("online", handleReconnect);
return () => window.removeEventListener("online", handleReconnect);
});
async function handleReconnect() {
if (network.syncing) return; // prevent concurrent sync on rapid reconnects
if (network.pendingCount === 0) return;
network.setSyncing(true);
try {
await syncOfflineQueue();
network.setPendingCount(0);
// Refetch everything so optimistic data is replaced by server truth
await queryClient.invalidateQueries();
} finally {
network.setSyncing(false);
}
}
async function handleReconnect() {
if (network.syncing) return; // prevent concurrent sync on rapid reconnects
if (network.pendingCount === 0) return;
network.setSyncing(true);
try {
await syncOfflineQueue();
network.setPendingCount(0);
// Refetch everything so optimistic data is replaced by server truth
await queryClient.invalidateQueries();
} finally {
network.setSyncing(false);
}
}
function handleLogout() {
logout();
queryClient.clear();
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'));
const isSettings = $derived(page.url.pathname.startsWith('/settings'));
const isDiary = $derived(page.url.pathname.startsWith("/diary"));
const isPresets = $derived(page.url.pathname.startsWith("/presets"));
const isSettings = $derived(page.url.pathname.startsWith("/settings"));
</script>
{#if auth.isAuthenticated}
<div class="lg:flex min-h-screen">
<!-- Offline / syncing banner -->
{#if !network.online || network.syncing}
<div
class="fixed top-0 inset-x-0 z-50 flex items-center justify-center gap-2 px-4 py-2 text-xs font-medium
<div class="lg:flex min-h-screen">
<!-- Offline / syncing banner -->
{#if !network.online || network.syncing}
<div
class="fixed top-0 inset-x-0 z-50 flex items-center justify-center gap-2 px-4 py-2 text-xs font-medium
{network.syncing ? 'bg-blue-600' : 'bg-zinc-700'}"
style="padding-top: calc(0.5rem + var(--safe-top))"
>
{#if network.syncing}
<svg class="w-3.5 h-3.5 animate-spin shrink-0" 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>
Syncing changes…
{:else}
<svg class="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636a9 9 0 010 12.728M15.536 8.464a5 5 0 010 7.072M3 3l18 18" />
</svg>
Offline{network.pendingCount > 0 ? ` · ${network.pendingCount} change${network.pendingCount === 1 ? '' : 's'} pending sync` : ''}
{/if}
</div>
{/if}
style="padding-top: calc(0.5rem + var(--safe-top))"
>
{#if network.syncing}
<svg
class="w-3.5 h-3.5 animate-spin shrink-0"
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>
Syncing changes…
{:else}
<svg
class="w-3.5 h-3.5 shrink-0"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M18.364 5.636a9 9 0 010 12.728M15.536 8.464a5 5 0 010 7.072M3 3l18 18"
/>
</svg>
Offline{network.pendingCount > 0
? ` · ${network.pendingCount} change${network.pendingCount === 1 ? "" : "s"} pending sync`
: ""}
{/if}
</div>
{/if}
<!-- 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>
<!-- 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>
<a
href="/settings"
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors
{isSettings ? '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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Settings
</a>
</nav>
<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>
<a
href="/settings"
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors
{isSettings
? '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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
/><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
Settings
</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>
<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>
<!-- 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
<!-- 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
>
<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>
<a
href="/settings"
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium 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="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"
/>
</svg>
Presets
</a>
<a
href="/settings"
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors
{isSettings ? '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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Settings
</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>
>
<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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
/><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
Settings
</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

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

View file

@ -1,207 +1,236 @@
<script lang="ts">
import { page } from '$app/state';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getDiary, createDiary } 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 { network } from '$lib/offline/network.svelte';
import { onMount } from 'svelte';
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';
import CommandPalette from '$lib/components/ui/CommandPalette.svelte';
import type { Command } from '$lib/components/ui/CommandPalette.svelte';
import { page } from "$app/state";
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getDiary, createDiary } 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 { network } from "$lib/offline/network.svelte";
import { onMount } from "svelte";
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";
import CommandPalette from "$lib/components/ui/CommandPalette.svelte";
import type { Command } from "$lib/components/ui/CommandPalette.svelte";
const date = $derived(page.params.date!);
const queryClient = useQueryClient();
const date = $derived(page.params.date!);
const queryClient = useQueryClient();
let calendarOpen = $state(false);
let commandOpen = $state(false);
let creating = $state(false);
let calendarOpen = $state(false);
let commandOpen = $state(false);
let creating = $state(false);
const commands = $derived<Command[]>([
...(diaryQuery.data?.meals ?? []).map(meal => ({
id: `entry-${meal.id}`,
label: `Add entry → ${meal.name}`,
keywords: ['e', 'entry', 'food', 'add'],
action: () => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)
})),
{
id: 'add-meal',
label: 'Add meal',
keywords: ['m', 'meal'],
action: () => goto(`/diary/${date}/add-meal`)
}
]);
const commands = $derived<Command[]>([
...(diaryQuery.data?.meals ?? []).map((meal) => ({
id: `entry-${meal.id}`,
label: `Add entry → ${meal.name}`,
keywords: ["e", "entry", "food", "add"],
action: () => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`),
})),
{
id: "add-meal",
label: "Add meal",
keywords: ["m", "meal"],
action: () => goto(`/diary/${date}/add-meal`),
},
]);
onMount(() => {
function handleKeydown(e: KeyboardEvent) {
const tag = (e.target as HTMLElement).tagName;
const editable = (e.target as HTMLElement).isContentEditable;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || editable) return;
if (e.key === '/' || e.key === ':') {
e.preventDefault();
commandOpen = true;
}
}
document.addEventListener('keydown', handleKeydown);
return () => document.removeEventListener('keydown', handleKeydown);
});
onMount(() => {
function handleKeydown(e: KeyboardEvent) {
const tag = (e.target as HTMLElement).tagName;
const editable = (e.target as HTMLElement).isContentEditable;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || editable)
return;
if (e.key === "/" || e.key === ":") {
e.preventDefault();
commandOpen = true;
}
}
document.addEventListener("keydown", handleKeydown);
return () => document.removeEventListener("keydown", handleKeydown);
});
const diaryQuery = createQuery(() => ({
queryKey: ['diary', date],
queryFn: async () => {
if (!network.online) {
// Prefer in-memory cache — it contains any optimistic updates
const inMemory = queryClient.getQueryData<import('$lib/types/api').Diary>(['diary', date]);
if (inMemory) return inMemory;
// Fall back to IndexedDB (survives page reload)
const cached = await getCachedDiary(date);
if (cached) return cached;
throw new Error('Offline and no cached data');
}
// Online: fetch fresh data — this overwrites both TQ cache and IndexedDB,
// replacing any temporary negative-ID entries from optimistic updates
try {
const diary = await getDiary(date);
if (diary === null) {
if (date === today()) {
const created = await createDiary(date);
await cacheDiary(JSON.parse(JSON.stringify(created)));
return created;
}
return null;
}
await cacheDiary(JSON.parse(JSON.stringify(diary)));
return diary;
} catch {
// Network failed despite network.online being true — fall back to cache
network.setOffline();
const inMemory = queryClient.getQueryData<import('$lib/types/api').Diary>(['diary', date]);
if (inMemory) return inMemory;
const cached = await getCachedDiary(date);
if (cached) return cached;
throw new Error('Offline and no cached data');
}
}
}));
const diaryQuery = createQuery(() => ({
queryKey: ["diary", date],
queryFn: async () => {
if (!network.online) {
// Prefer in-memory cache — it contains any optimistic updates
const inMemory = queryClient.getQueryData<
import("$lib/types/api").Diary
>(["diary", date]);
if (inMemory) return inMemory;
// Fall back to IndexedDB (survives page reload)
const cached = await getCachedDiary(date);
if (cached) return cached;
throw new Error("Offline and no cached data");
}
// Online: fetch fresh data — this overwrites both TQ cache and IndexedDB,
// replacing any temporary negative-ID entries from optimistic updates
try {
const diary = await getDiary(date);
if (diary === null) {
if (date === today()) {
const created = await createDiary(date);
await cacheDiary(JSON.parse(JSON.stringify(created)));
return created;
}
return null;
}
await cacheDiary(JSON.parse(JSON.stringify(diary)));
return diary;
} catch {
// Network failed despite network.online being true — fall back to cache
network.setOffline();
const inMemory = queryClient.getQueryData<
import("$lib/types/api").Diary
>(["diary", date]);
if (inMemory) return inMemory;
const cached = await getCachedDiary(date);
if (cached) return cached;
throw new Error("Offline and no cached data");
}
},
}));
async function handleCreate() {
creating = true;
try {
await createDiary(date);
queryClient.invalidateQueries({ queryKey: ['diary', date] });
} finally {
creating = false;
}
}
async function handleCreate() {
creating = true;
try {
await createDiary(date);
queryClient.invalidateQueries({ queryKey: ["diary", date] });
} finally {
creating = false;
}
}
function goDate(delta: number) {
goto(`/diary/${addDays(date, delta)}`);
}
function goDate(delta: number) {
goto(`/diary/${addDays(date, delta)}`);
}
function handleDateSelect(d: string) {
calendarOpen = false;
goto(`/diary/${d}`);
}
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>
<!-- 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 ?? 'Unknown error'}</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 === null}
<div class="text-center text-zinc-500 mt-20">
<p class="text-lg">No diary for {formatDisplay(date)}</p>
<p class="text-sm mt-1">No entries have been tracked for this date.</p>
<button
onclick={handleCreate}
disabled={creating}
class="mt-4 px-5 py-2.5 bg-green-600 hover:bg-green-500 disabled:opacity-50 text-white rounded-xl text-sm font-medium transition-colors"
>
{creating ? 'Creating…' : 'Create diary'}
</button>
</div>
{:else if diaryQuery.data}
{@const diary = diaryQuery.data}
<!-- 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 ?? "Unknown error"}
</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 === null}
<div class="text-center text-zinc-500 mt-20">
<p class="text-lg">No diary for {formatDisplay(date)}</p>
<p class="text-sm mt-1">No entries have been tracked for this date.</p>
<button
onclick={handleCreate}
disabled={creating}
class="mt-4 px-5 py-2.5 bg-green-600 hover:bg-green-500 disabled:opacity-50 text-white rounded-xl text-sm font-medium transition-colors"
>
{creating ? "Creating…" : "Create diary"}
</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 {diary} {date} />
</div>
<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 {diary} {date} />
</div>
<!-- Right: meals -->
<div class="space-y-4">
{#each diary.meals as meal (meal.id)}
<MealCard {meal} {date} />
{/each}
<!-- Right: meals -->
<div class="space-y-4">
{#each diary.meals as meal (meal.id)}
<MealCard {meal} {date} />
{/each}
<!-- Add meal button -->
<button
onclick={() => goto(`/diary/${date}/add-meal`)}
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>
<!-- Add meal button -->
<button
onclick={() => goto(`/diary/${date}/add-meal`)}
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>
<!-- FAB: Add entry (mobile only) -->
{#if diaryQuery.data != null}
<button
onclick={() => {
const firstMeal = diaryQuery.data?.meals[0];
if (firstMeal) goto(`/diary/${date}/add-entry?meal_id=${firstMeal.id}`);
}}
class="lg:hidden fixed bottom-[calc(4rem+var(--safe-bottom))] right-4 z-30 w-14 h-14 rounded-full bg-green-600 hover:bg-green-500 shadow-lg flex items-center justify-center transition-colors"
aria-label="Add entry"
>
<svg class="w-7 h-7" 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>
{/if}
<!-- FAB: Add entry (mobile only) -->
{#if diaryQuery.data != null}
<button
onclick={() => {
const firstMeal = diaryQuery.data?.meals[0];
if (firstMeal) goto(`/diary/${date}/add-entry?meal_id=${firstMeal.id}`);
}}
class="lg:hidden fixed bottom-[calc(4rem+var(--safe-bottom))] right-4 z-30 w-14 h-14 rounded-full bg-green-600 hover:bg-green-500 shadow-lg flex items-center justify-center transition-colors"
aria-label="Add entry"
>
<svg
class="w-7 h-7"
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>
{/if}
<Sheet open={calendarOpen} onclose={() => calendarOpen = false}>
<CalendarPicker selected={date} onSelect={handleDateSelect} />
</Sheet>
<Sheet open={calendarOpen} onclose={() => (calendarOpen = false)}>
<CalendarPicker selected={date} onSelect={handleDateSelect} />
</Sheet>
<CommandPalette {commands} open={commandOpen} onclose={() => commandOpen = false} />
<CommandPalette
{commands}
open={commandOpen}
onclose={() => (commandOpen = false)}
/>
</div>

View file

@ -1,157 +1,185 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { createMealFromPreset } from '$lib/api/meals';
import { offlineAddMeal } from '$lib/offline/mutations';
import { network } from '$lib/offline/network.svelte';
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';
import { today } from '$lib/utils/date';
import { page } from "$app/state";
import { goto } from "$app/navigation";
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { createMealFromPreset } from "$lib/api/meals";
import { offlineAddMeal } from "$lib/offline/mutations";
import { network } from "$lib/offline/network.svelte";
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";
import { today } from "$lib/utils/date";
const date = $derived(page.params.date === 'today' ? today() : page.params.date!);
const queryClient = useQueryClient();
const date = $derived(
page.params.date === "today" ? today() : page.params.date!,
);
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('');
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);
}
function handlePresetSearch(v: string) {
presetQ = v;
clearTimeout(presetTimer);
presetTimer = setTimeout(() => {
presetDebounced = v;
}, 300);
}
const presetsQuery = createQuery(() => ({
queryKey: ['presets'],
queryFn: () => listPresets(30)
}));
const presetsQuery = createQuery(() => ({
queryKey: ["presets"],
queryFn: () => listPresets(30),
}));
async function handleCreateNew(e: SubmitEvent) {
e.preventDefault();
submitting = true;
try {
await offlineAddMeal(queryClient, date, mealName);
goto(`/diary/${date}`);
} catch {
// mutation was queued offline — navigate back anyway
goto(`/diary/${date}`);
} finally {
submitting = false;
}
}
async function handleCreateNew(e: SubmitEvent) {
e.preventDefault();
submitting = true;
try {
await offlineAddMeal(queryClient, date, mealName);
goto(`/diary/${date}`);
} catch {
// mutation was queued offline — navigate back anyway
goto(`/diary/${date}`);
} finally {
submitting = false;
}
}
async function handleFromPreset(preset: Preset) {
submitting = true;
error = '';
try {
await createMealFromPreset(date, preset.id, preset.name);
await queryClient.invalidateQueries({ queryKey: ['diary', date] });
goto(`/diary/${date}`);
} catch {
error = 'Failed to add preset';
submitting = false;
}
}
async function handleFromPreset(preset: Preset) {
submitting = true;
error = "";
try {
await createMealFromPreset(date, 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}" />
<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', offlineDisabled: true }] as t}
<button
onclick={() => tab = t.id as Tab}
disabled={t.offlineDisabled && !network.online}
class="flex-1 py-3 text-sm font-medium transition-colors border-b-2 disabled:opacity-40 {tab === t.id
? 'border-green-500 text-green-400'
: 'border-transparent text-zinc-500 hover:text-zinc-300'}"
>
{t.label}
</button>
{/each}
</div>
<!-- Tabs -->
<div class="flex border-b border-zinc-800 bg-zinc-950">
{#each [{ id: "new", label: "New meal" }, { id: "preset", label: "From preset", offlineDisabled: true }] as t}
<button
onclick={() => (tab = t.id as Tab)}
disabled={t.offlineDisabled && !network.online}
class="flex-1 py-3 text-sm font-medium transition-colors border-b-2 disabled:opacity-40 {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…' : network.online ? 'Create meal' : 'Create meal (offline)'}
</button>
</form>
<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…"
: network.online
? "Create meal"
: "Create meal (offline)"}
</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>
{: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 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 ?? []).filter(p => !presetDebounced || p.name.toLowerCase().includes(presetDebounced.toLowerCase())).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 ?? []).filter(p => !presetDebounced || p.name.toLowerCase().includes(presetDebounced.toLowerCase())) 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>
{#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 ?? []).filter((p) => !presetDebounced || p.name
.toLowerCase()
.includes(presetDebounced.toLowerCase())).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 ?? []).filter((p) => !presetDebounced || p.name
.toLowerCase()
.includes(presetDebounced.toLowerCase())) 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

@ -2,5 +2,5 @@ import { redirect } from '@sveltejs/kit';
import { today } from '$lib/utils/date';
export function load() {
throw redirect(307, `/diary/${today()}`);
throw redirect(307, `/diary/${today()}`);
}

View file

@ -1,125 +1,144 @@
<script lang="ts">
import { page } from '$app/state';
import { createProduct } from '$lib/api/products';
import TopBar from '$lib/components/ui/TopBar.svelte';
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 barcode = $state(page.url.searchParams.get('barcode') ?? '');
let protein = $state(0);
let carb = $state(0);
let fat = $state(0);
let fiber = $state(0);
let submitting = $state(false);
let error = $state('');
let name = $state(page.url.searchParams.get("name") ?? "");
let barcode = $state(page.url.searchParams.get("barcode") ?? "");
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));
// 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, ...(barcode ? { barcode } : {}) });
history.back();
} catch {
error = 'Failed to save product';
submitting = false;
}
}
async function handleSubmit(e: SubmitEvent) {
e.preventDefault();
submitting = true;
error = "";
try {
await createProduct({
name,
protein,
carb,
fat,
fiber,
...(barcode ? { barcode } : {}),
});
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()} />
<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>
<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>
<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"
inputmode="decimal"
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"
inputmode="decimal"
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"
inputmode="decimal"
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"
inputmode="decimal"
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="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"
inputmode="decimal"
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"
inputmode="decimal"
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"
inputmode="decimal"
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"
inputmode="decimal"
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>
<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}
{#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>
<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

@ -1,168 +1,188 @@
<script lang="ts">
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getUserSettings, updateUserSettings } from '$lib/api/settings';
import { updateDiary } from '$lib/api/diary';
import TopBar from '$lib/components/ui/TopBar.svelte';
import Sheet from '$lib/components/ui/Sheet.svelte';
import { today } from '$lib/utils/date';
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getUserSettings, updateUserSettings } from "$lib/api/settings";
import { updateDiary } from "$lib/api/diary";
import TopBar from "$lib/components/ui/TopBar.svelte";
import Sheet from "$lib/components/ui/Sheet.svelte";
import { today } from "$lib/utils/date";
const queryClient = useQueryClient();
const queryClient = useQueryClient();
const settingsQuery = createQuery(() => ({
queryKey: ['user-settings'],
queryFn: getUserSettings,
staleTime: 5 * 60 * 1000,
}));
const settingsQuery = createQuery(() => ({
queryKey: ["user-settings"],
queryFn: getUserSettings,
staleTime: 5 * 60 * 1000,
}));
let saving = $state(false);
let saved = $state(false);
let error = $state('');
let syncDiaryOpen = $state(false);
let lastSavedForm: typeof form | null = null;
let saving = $state(false);
let saved = $state(false);
let error = $state("");
let syncDiaryOpen = $state(false);
let lastSavedForm: typeof form | null = null;
let form = $state<{
calories_goal: number | null;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
}>({
calories_goal: null as number | null,
protein_goal: 0,
carb_goal: 0,
fat_goal: 0,
fiber_goal: 0,
});
let form = $state<{
calories_goal: number | null;
protein_goal: number;
carb_goal: number;
fat_goal: number;
fiber_goal: number;
}>({
calories_goal: null as number | null,
protein_goal: 0,
carb_goal: 0,
fat_goal: 0,
fiber_goal: 0,
});
$effect(() => {
if (settingsQuery.data) {
form = {
calories_goal: null, // always reset to auto when settings refresh
protein_goal: settingsQuery.data.protein_goal,
carb_goal: settingsQuery.data.carb_goal,
fat_goal: settingsQuery.data.fat_goal,
fiber_goal: settingsQuery.data.fiber_goal,
};
}
});
$effect(() => {
if (settingsQuery.data) {
form = {
calories_goal: null, // always reset to auto when settings refresh
protein_goal: settingsQuery.data.protein_goal,
carb_goal: settingsQuery.data.carb_goal,
fat_goal: settingsQuery.data.fat_goal,
fiber_goal: settingsQuery.data.fiber_goal,
};
}
});
async function handleSave(e: SubmitEvent) {
e.preventDefault();
saving = true;
error = '';
try {
await updateUserSettings(form);
queryClient.invalidateQueries({ queryKey: ['user-settings'] });
lastSavedForm = { ...form };
saved = true;
setTimeout(() => { saved = false; }, 2000);
syncDiaryOpen = true;
} catch {
error = 'Failed to save settings';
} finally {
saving = false;
}
}
async function handleSave(e: SubmitEvent) {
e.preventDefault();
saving = true;
error = "";
try {
await updateUserSettings(form);
queryClient.invalidateQueries({ queryKey: ["user-settings"] });
lastSavedForm = { ...form };
saved = true;
setTimeout(() => {
saved = false;
}, 2000);
syncDiaryOpen = true;
} catch {
error = "Failed to save settings";
} finally {
saving = false;
}
}
async function handleSyncToDiary() {
if (!lastSavedForm) return;
await updateDiary(today(), lastSavedForm);
queryClient.invalidateQueries({ queryKey: ['diary', today()] });
syncDiaryOpen = false;
}
async function handleSyncToDiary() {
if (!lastSavedForm) return;
await updateDiary(today(), lastSavedForm);
queryClient.invalidateQueries({ queryKey: ["diary", today()] });
syncDiaryOpen = false;
}
</script>
<div class="flex flex-col h-screen">
<TopBar title="Settings" back="/diary/{today()}" />
<TopBar title="Settings" back="/diary/{today()}" />
<main class="flex-1 overflow-y-auto px-4 py-6">
{#if settingsQuery.isPending}
<div class="space-y-4">
{#each Array(5) as _}
<div class="h-16 bg-zinc-900 rounded-xl animate-pulse"></div>
{/each}
</div>
{:else if settingsQuery.isError}
<p class="text-center text-zinc-500 mt-16">Could not load settings</p>
{:else}
<form onsubmit={handleSave} class="space-y-6">
<section>
<h2 class="text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-3">Daily goals</h2>
<div class="space-y-3">
<!-- Calories: null = auto-calculated by server from macros -->
<div class="bg-zinc-900 rounded-xl px-4 py-3 flex items-center gap-4">
<div class="flex-1">
<div class="flex items-center gap-2">
<p class="text-sm font-medium">Calories</p>
{#if form.calories_goal === null}
<span class="text-xs font-medium text-zinc-500 bg-zinc-800 border border-zinc-700 px-1.5 py-0.5 rounded-full">auto</span>
{/if}
</div>
<p class="text-xs text-zinc-500">kcal · clear to auto-calculate</p>
</div>
<input
type="number"
min="0"
step="1"
value={form.calories_goal ?? settingsQuery.data?.calories_goal ?? ''}
oninput={(e) => {
const v = e.currentTarget.value;
form.calories_goal = v === '' ? null : Number(v);
}}
class="w-24 bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-right text-sm text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
<main class="flex-1 overflow-y-auto px-4 py-6">
{#if settingsQuery.isPending}
<div class="space-y-4">
{#each Array(5) as _}
<div class="h-16 bg-zinc-900 rounded-xl animate-pulse"></div>
{/each}
</div>
{:else if settingsQuery.isError}
<p class="text-center text-zinc-500 mt-16">Could not load settings</p>
{:else}
<form onsubmit={handleSave} class="space-y-6">
<section>
<h2
class="text-xs font-semibold text-zinc-500 uppercase tracking-wider mb-3"
>
Daily goals
</h2>
<div class="space-y-3">
<!-- Calories: null = auto-calculated by server from macros -->
<div
class="bg-zinc-900 rounded-xl px-4 py-3 flex items-center gap-4"
>
<div class="flex-1">
<div class="flex items-center gap-2">
<p class="text-sm font-medium">Calories</p>
{#if form.calories_goal === null}
<span
class="text-xs font-medium text-zinc-500 bg-zinc-800 border border-zinc-700 px-1.5 py-0.5 rounded-full"
>auto</span
>
{/if}
</div>
<p class="text-xs text-zinc-500">
kcal · clear to auto-calculate
</p>
</div>
<input
type="number"
min="0"
step="1"
value={form.calories_goal ??
settingsQuery.data?.calories_goal ??
""}
oninput={(e) => {
const v = e.currentTarget.value;
form.calories_goal = v === "" ? null : Number(v);
}}
class="w-24 bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-right text-sm text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{#each [
{ label: 'Protein', key: 'protein_goal' as const, unit: 'g' },
{ label: 'Carbs', key: 'carb_goal' as const, unit: 'g' },
{ label: 'Fat', key: 'fat_goal' as const, unit: 'g' },
{ label: 'Fiber', key: 'fiber_goal' as const, unit: 'g' },
] as field}
<div class="bg-zinc-900 rounded-xl px-4 py-3 flex items-center gap-4">
<div class="flex-1">
<p class="text-sm font-medium">{field.label}</p>
<p class="text-xs text-zinc-500">{field.unit} per day</p>
</div>
<input
type="number"
min="0"
step="1"
bind:value={form[field.key]}
class="w-24 bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-right text-sm text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{/each}
</div>
</section>
{#each [{ label: "Protein", key: "protein_goal" as const, unit: "g" }, { label: "Carbs", key: "carb_goal" as const, unit: "g" }, { label: "Fat", key: "fat_goal" as const, unit: "g" }, { label: "Fiber", key: "fiber_goal" as const, unit: "g" }] as field}
<div
class="bg-zinc-900 rounded-xl px-4 py-3 flex items-center gap-4"
>
<div class="flex-1">
<p class="text-sm font-medium">{field.label}</p>
<p class="text-xs text-zinc-500">{field.unit} per day</p>
</div>
<input
type="number"
min="0"
step="1"
bind:value={form[field.key]}
class="w-24 bg-zinc-800 border border-zinc-700 rounded-lg px-3 py-2 text-right text-sm text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
</div>
{/each}
</div>
</section>
{#if error}
<p class="text-red-400 text-sm">{error}</p>
{/if}
{#if error}
<p class="text-red-400 text-sm">{error}</p>
{/if}
<button
type="submit"
disabled={saving}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors
<button
type="submit"
disabled={saving}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors
{saved ? 'bg-zinc-700 hover:bg-zinc-700' : ''}"
>
{saving ? 'Saving…' : saved ? 'Saved!' : 'Save'}
</button>
</form>
{/if}
</main>
>
{saving ? "Saving…" : saved ? "Saved!" : "Save"}
</button>
</form>
{/if}
</main>
</div>
<Sheet open={syncDiaryOpen} onclose={() => syncDiaryOpen = false} title="Update today's diary?">
<p class="text-sm text-zinc-400 mb-5">Override today's diary macro goals with these values as well?</p>
<div class="flex gap-3">
<button
onclick={() => syncDiaryOpen = false}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors"
>No</button>
<button
onclick={handleSyncToDiary}
class="flex-1 bg-green-600 hover:bg-green-500 rounded-xl py-3 font-semibold transition-colors"
>Yes</button>
</div>
<Sheet
open={syncDiaryOpen}
onclose={() => (syncDiaryOpen = false)}
title="Update today's diary?"
>
<p class="text-sm text-zinc-400 mb-5">
Override today's diary macro goals with these values as well?
</p>
<div class="flex gap-3">
<button
onclick={() => (syncDiaryOpen = false)}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors"
>No</button
>
<button
onclick={handleSyncToDiary}
class="flex-1 bg-green-600 hover:bg-green-500 rounded-xl py-3 font-semibold transition-colors"
>Yes</button
>
</div>
</Sheet>

View file

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

View file

@ -1,14 +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';
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 });
}
});
onMount(() => {
if (auth.isAuthenticated) {
goto(`/diary/${today()}`, { replaceState: true });
} else {
goto("/login", { replaceState: true });
}
});
</script>