[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 // See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces // for information about these interfaces
declare global { declare global {
namespace App { namespace App {
// interface Error {} // interface Error {}
// interface Locals {} // interface Locals {}
// interface PageData {} // interface PageData {}
// interface PageState {} // interface PageState {}
// interface Platform {} // interface Platform {}
} }
} }
export {}; export { };

View file

@ -1,20 +1,20 @@
import type { HandleClientError } from '@sveltejs/kit'; import type { HandleClientError } from '@sveltejs/kit';
export const handleError: HandleClientError = ({ error }) => { 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 // 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 // chunk isn't cached, the import fails with this error. Show a helpful message
// instead of the generic "Internal Error" page. // instead of the generic "Internal Error" page.
if ( if (
msg.includes('Importing a module script failed') || msg.includes('Importing a module script failed') ||
msg.includes('Failed to fetch dynamically imported module') || msg.includes('Failed to fetch dynamically imported module') ||
msg.includes('Unable to preload CSS') msg.includes('Unable to preload CSS')
) { ) {
return { return {
message: 'App not cached yet. Open the app while online at least once to enable offline use.' 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'; const BASE = '/api';
export async function login(username: string, password: string): Promise<void> { export async function login(username: string, password: string): Promise<void> {
const body = new URLSearchParams({ username, password }); const body = new URLSearchParams({ username, password });
const res = await fetch(`${BASE}/token`, { const res = await fetch(`${BASE}/token`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString() body: body.toString()
}); });
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({})); const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Login failed'), { status: res.status, detail: err }); throw Object.assign(new Error('Login failed'), { status: res.status, detail: err });
} }
const token: Token = await res.json(); const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token); auth.setTokens(token.access_token, token.refresh_token);
} }
export async function register(username: string, password: string, captchaToken: string): Promise<void> { export async function register(username: string, password: string, captchaToken: string): Promise<void> {
const res = await fetch(`${BASE}/user`, { const res = await fetch(`${BASE}/user`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, captcha_token: captchaToken }) body: JSON.stringify({ username, password, captcha_token: captchaToken })
}); });
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({})); const err = await res.json().catch(() => ({}));
throw Object.assign(new Error('Registration failed'), { status: res.status, detail: err }); throw Object.assign(new Error('Registration failed'), { status: res.status, detail: err });
} }
const token: Token = await res.json(); const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token); auth.setTokens(token.access_token, token.refresh_token);
} }
export async function tryRestoreSession(): Promise<boolean> { export async function tryRestoreSession(): Promise<boolean> {
const refreshToken = auth.getRefreshToken(); const refreshToken = auth.getRefreshToken();
if (!refreshToken) return false; if (!refreshToken) return false;
try { try {
const res = await fetch(`${BASE}/token/refresh`, { const res = await fetch(`${BASE}/token/refresh`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }) body: JSON.stringify({ refresh_token: refreshToken })
}); });
if (!res.ok) { if (!res.ok) {
auth.clear(); auth.clear();
return false; return false;
} }
const token: Token = await res.json(); const token: Token = await res.json();
auth.setTokens(token.access_token, token.refresh_token); auth.setTokens(token.access_token, token.refresh_token);
return true; return true;
} catch { } catch {
return false; return false;
} }
} }
export function logout(): void { export function logout(): void {
auth.clear(); auth.clear();
} }

View file

@ -9,172 +9,172 @@ let isRefreshing = false;
let refreshPromise: Promise<string | null> | null = null; let refreshPromise: Promise<string | null> | null = null;
async function doRefresh(): Promise<string | null> { async function doRefresh(): Promise<string | null> {
const refreshToken = auth.getRefreshToken(); const refreshToken = auth.getRefreshToken();
if (!refreshToken) return null; if (!refreshToken) return null;
try { try {
const res = await fetch(`${BASE}/token/refresh`, { const res = await fetch(`${BASE}/token/refresh`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refreshToken }) body: JSON.stringify({ refresh_token: refreshToken })
}); });
if (!res.ok) return null; if (!res.ok) return null;
const data = await res.json(); const data = await res.json();
auth.setTokens(data.access_token, data.refresh_token); auth.setTokens(data.access_token, data.refresh_token);
return data.access_token; return data.access_token;
} catch { } catch {
return null; return null;
} }
} }
async function getValidToken(): Promise<string | null> { async function getValidToken(): Promise<string | null> {
if (auth.accessToken) return auth.accessToken; if (auth.accessToken) return auth.accessToken;
// Deduplicate concurrent refresh calls // Deduplicate concurrent refresh calls
if (isRefreshing) return refreshPromise; if (isRefreshing) return refreshPromise;
isRefreshing = true; isRefreshing = true;
refreshPromise = doRefresh().finally(() => { refreshPromise = doRefresh().finally(() => {
isRefreshing = false; isRefreshing = false;
refreshPromise = null; refreshPromise = null;
}); });
return refreshPromise; return refreshPromise;
} }
export async function apiFetch( export async function apiFetch(
path: string, path: string,
options: RequestInit = {}, options: RequestInit = {},
retry = true retry = true
): Promise<Response> { ): Promise<Response> {
const token = await getValidToken(); const token = await getValidToken();
const headers = new Headers(options.headers); const headers = new Headers(options.headers);
if (token) headers.set('Authorization', `Bearer ${token}`); 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) { if (res.status === 401 && retry) {
// Force a refresh and retry once // Force a refresh and retry once
auth.setAccessToken(''); // clear so getValidToken triggers refresh auth.setAccessToken(''); // clear so getValidToken triggers refresh
const newToken = await doRefresh(); const newToken = await doRefresh();
if (!newToken) { if (!newToken) {
auth.clear(); auth.clear();
goto('/login'); goto('/login');
return res; return res;
} }
auth.setAccessToken(newToken); auth.setAccessToken(newToken);
headers.set('Authorization', `Bearer ${newToken}`); headers.set('Authorization', `Bearer ${newToken}`);
return fetch(`${BASE}${path}`, { ...options, headers }); return fetch(`${BASE}${path}`, { ...options, headers });
} }
return res; return res;
} }
export async function apiGet<T>(path: string): Promise<T> { export async function apiGet<T>(path: string): Promise<T> {
const res = await apiFetch(path); const res = await apiFetch(path);
if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`); if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
return res.json(); return res.json();
} }
// Auth endpoints must never be queued (token ops need live responses) // Auth endpoints must never be queued (token ops need live responses)
function isAuthPath(path: string) { function isAuthPath(path: string) {
return path.startsWith('/token/'); return path.startsWith('/token/');
} }
// A TypeError thrown by fetch() always means a network-level failure // A TypeError thrown by fetch() always means a network-level failure
function isNetworkFailure(e: unknown): boolean { 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 // 5xx from the proxy/server when backend is down — treat same as offline
function isServerUnavailable(res: Response): boolean { 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> { async function queueMutation(method: 'POST' | 'PATCH' | 'DELETE', path: string, body: unknown): Promise<void> {
network.setOffline(); network.setOffline();
await enqueueMutation({ method, url: path, body }); await enqueueMutation({ method, url: path, body });
network.incrementPending(); network.incrementPending();
} }
export async function apiPost<T>(path: string, body: unknown): Promise<T> { export async function apiPost<T>(path: string, body: unknown): Promise<T> {
if (!navigator.onLine && !isAuthPath(path)) { if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('POST', path, body); await queueMutation('POST', path, body);
return {} as T; return {} as T;
} }
let res: Response; let res: Response;
try { try {
res = await apiFetch(path, { res = await apiFetch(path, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) body: JSON.stringify(body)
}); });
} catch (e) { } catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) { if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('POST', path, body); await queueMutation('POST', path, body);
return {} as T; return {} as T;
} }
throw e; throw e;
} }
if (!res.ok) { if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) { if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('POST', path, body); await queueMutation('POST', path, body);
return {} as T; return {} as T;
} }
const err = await res.json().catch(() => ({})); const err = await res.json().catch(() => ({}));
throw Object.assign(new Error(`POST ${path} failed: ${res.status}`), { status: res.status, detail: err }); throw Object.assign(new Error(`POST ${path} failed: ${res.status}`), { status: res.status, detail: err });
} }
return res.json(); return res.json();
} }
export async function apiPatch<T>(path: string, body: unknown): Promise<T> { export async function apiPatch<T>(path: string, body: unknown): Promise<T> {
if (!navigator.onLine && !isAuthPath(path)) { if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('PATCH', path, body); await queueMutation('PATCH', path, body);
return {} as T; return {} as T;
} }
let res: Response; let res: Response;
try { try {
res = await apiFetch(path, { res = await apiFetch(path, {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) body: JSON.stringify(body)
}); });
} catch (e) { } catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) { if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('PATCH', path, body); await queueMutation('PATCH', path, body);
return {} as T; return {} as T;
} }
throw e; throw e;
} }
if (!res.ok) { if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) { if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('PATCH', path, body); await queueMutation('PATCH', path, body);
return {} as T; return {} as T;
} }
throw new Error(`PATCH ${path} failed: ${res.status}`); throw new Error(`PATCH ${path} failed: ${res.status}`);
} }
return res.json(); return res.json();
} }
export async function apiDelete(path: string): Promise<void> { export async function apiDelete(path: string): Promise<void> {
if (!navigator.onLine && !isAuthPath(path)) { if (!navigator.onLine && !isAuthPath(path)) {
await queueMutation('DELETE', path, undefined); await queueMutation('DELETE', path, undefined);
return; return;
} }
let res: Response; let res: Response;
try { try {
res = await apiFetch(path, { method: 'DELETE' }); res = await apiFetch(path, { method: 'DELETE' });
} catch (e) { } catch (e) {
if (!isAuthPath(path) && isNetworkFailure(e)) { if (!isAuthPath(path) && isNetworkFailure(e)) {
await queueMutation('DELETE', path, undefined); await queueMutation('DELETE', path, undefined);
return; return;
} }
throw e; throw e;
} }
if (!res.ok) { if (!res.ok) {
if (!isAuthPath(path) && isServerUnavailable(res)) { if (!isAuthPath(path) && isServerUnavailable(res)) {
await queueMutation('DELETE', path, undefined); await queueMutation('DELETE', path, undefined);
return; return;
} }
throw new Error(`DELETE ${path} failed: ${res.status}`); 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'; import type { Diary } from '$lib/types/api';
export async function getDiary(date: string): Promise<Diary | null> { export async function getDiary(date: string): Promise<Diary | null> {
const res = await apiFetch(`/diary/${date}`); const res = await apiFetch(`/diary/${date}`);
if (res.status === 404) return null; if (res.status === 404) return null;
if (!res.ok) throw new Error(`GET /diary/${date} failed: ${res.status}`); if (!res.ok) throw new Error(`GET /diary/${date} failed: ${res.status}`);
return res.json(); return res.json();
} }
export function createDiary(date: string): Promise<Diary> { export function createDiary(date: string): Promise<Diary> {
return apiPost<Diary>('/diary', { date }); return apiPost<Diary>('/diary', { date });
} }
export function updateDiary(date: string, patch: { export function updateDiary(date: string, patch: {
protein_goal?: number | null; protein_goal?: number | null;
carb_goal?: number | null; carb_goal?: number | null;
fat_goal?: number | null; fat_goal?: number | null;
fiber_goal?: number | null; fiber_goal?: number | null;
calories_goal?: number | null; calories_goal?: number | null;
}): Promise<Diary> { }): 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'; import type { Entry } from '$lib/types/api';
export function createEntry(date: string, mealId: number, productId: number, grams: number): Promise<Entry> { 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> { 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> { 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'; import type { Meal, Preset } from '$lib/types/api';
export function createMeal(date: string, name: string): Promise<Meal> { 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> { 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> { 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> { 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> { export function createMealFromPreset(date: string, presetId: number, name?: string): Promise<Meal> {
return apiPost<Meal>(`/diary/${date}/meal/from_preset`, { return apiPost<Meal>(`/diary/${date}/meal/from_preset`, {
preset_id: presetId, preset_id: presetId,
...(name ? { name } : {}) ...(name ? { name } : {})
}); });
} }

View file

@ -2,21 +2,21 @@ import { apiGet, apiPost } from './client';
import type { Product } from '$lib/types/api'; import type { Product } from '$lib/types/api';
export function listProducts(q = '', limit = 20, offset = 0): Promise<Product[]> { export function listProducts(q = '', limit = 20, offset = 0): Promise<Product[]> {
const params = new URLSearchParams({ q, limit: String(limit), offset: String(offset) }); const params = new URLSearchParams({ q, limit: String(limit), offset: String(offset) });
return apiGet<Product[]>(`/product?${params}`); return apiGet<Product[]>(`/product?${params}`);
} }
export function createProduct(data: { export function createProduct(data: {
name: string; name: string;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
barcode?: string; barcode?: string;
}): Promise<Product> { }): Promise<Product> {
return apiPost<Product>('/product', data); return apiPost<Product>('/product', data);
} }
export function getProductByBarcode(barcode: string): Promise<Product> { 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'; import type { UserSettings } from '$lib/types/api';
export function getUserSettings(): Promise<UserSettings> { 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> { 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'; const REFRESH_TOKEN_KEY = 'fooder_refresh_token';
interface AuthState { interface AuthState {
accessToken: string | null; accessToken: string | null;
user: User | null; user: User | null;
} }
let state = $state<AuthState>({ let state = $state<AuthState>({
accessToken: null, accessToken: null,
user: null user: null
}); });
export const auth = { export const auth = {
get accessToken() { get accessToken() {
return state.accessToken; return state.accessToken;
}, },
get user() { get user() {
return state.user; return state.user;
}, },
get isAuthenticated() { get isAuthenticated() {
return state.accessToken !== null; return state.accessToken !== null;
}, },
setTokens(accessToken: string, refreshToken: string, user?: User) { setTokens(accessToken: string, refreshToken: string, user?: User) {
state.accessToken = accessToken; state.accessToken = accessToken;
if (user) state.user = user; if (user) state.user = user;
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken); localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
}, },
setAccessToken(accessToken: string) { setAccessToken(accessToken: string) {
state.accessToken = accessToken; state.accessToken = accessToken;
}, },
getRefreshToken(): string | null { getRefreshToken(): string | null {
if (typeof localStorage === 'undefined') return null; if (typeof localStorage === 'undefined') return null;
return localStorage.getItem(REFRESH_TOKEN_KEY); return localStorage.getItem(REFRESH_TOKEN_KEY);
}, },
clear() { clear() {
state.accessToken = null; state.accessToken = null;
state.user = null; state.user = null;
localStorage.removeItem(REFRESH_TOKEN_KEY); localStorage.removeItem(REFRESH_TOKEN_KEY);
} }
}; };

View file

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

View file

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

View file

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

View file

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

View file

@ -1,213 +1,285 @@
<script lang="ts"> <script lang="ts">
import type { Meal } from '$lib/types/api'; import type { Meal } from "$lib/types/api";
import { kcal, g } from '$lib/utils/format'; import { kcal, g } from "$lib/utils/format";
import EntryRow from './EntryRow.svelte'; import EntryRow from "./EntryRow.svelte";
import { useQueryClient } from '@tanstack/svelte-query'; import { useQueryClient } from "@tanstack/svelte-query";
import { deleteMeal, renameMeal, saveMealAsPreset } from '$lib/api/meals'; import { deleteMeal, renameMeal, saveMealAsPreset } from "$lib/api/meals";
import { deleteEntry } from '$lib/api/entries'; import { deleteEntry } from "$lib/api/entries";
import { goto } from '$app/navigation'; import { goto } from "$app/navigation";
import Sheet from '$lib/components/ui/Sheet.svelte'; import Sheet from "$lib/components/ui/Sheet.svelte";
interface Props { interface Props {
meal: Meal; meal: Meal;
date: string; date: string;
} }
let { meal, date }: Props = $props(); let { meal, date }: Props = $props();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
let collapsed = $state(false); let collapsed = $state(false);
let saving = $state(false); let saving = $state(false);
let renameOpen = $state(false); let renameOpen = $state(false);
let renameName = $state(''); let renameName = $state("");
let renaming = $state(false); let renaming = $state(false);
let presetOpen = $state(false); let presetOpen = $state(false);
let presetName = $state(''); let presetName = $state("");
function openRename() { function openRename() {
renameName = meal.name; renameName = meal.name;
renameOpen = true; renameOpen = true;
} }
async function handleRename(e: SubmitEvent) { async function handleRename(e: SubmitEvent) {
e.preventDefault(); e.preventDefault();
if (!renameName.trim()) return; if (!renameName.trim()) return;
renaming = true; renaming = true;
try { try {
await renameMeal(date, meal.id, renameName.trim()); await renameMeal(date, meal.id, renameName.trim());
queryClient.invalidateQueries({ queryKey: ['diary', date] }); queryClient.invalidateQueries({ queryKey: ["diary", date] });
renameOpen = false; renameOpen = false;
} finally { } finally {
renaming = false; renaming = false;
} }
} }
async function handleDeleteMeal() { async function handleDeleteMeal() {
if (!confirm(`Delete meal "${meal.name}"?`)) return; if (!confirm(`Delete meal "${meal.name}"?`)) return;
await deleteMeal(date, meal.id); await deleteMeal(date, meal.id);
queryClient.invalidateQueries({ queryKey: ['diary', date] }); queryClient.invalidateQueries({ queryKey: ["diary", date] });
} }
function openPresetSheet() { function openPresetSheet() {
presetName = meal.name; presetName = meal.name;
presetOpen = true; presetOpen = true;
} }
async function handleSavePreset(e: SubmitEvent) { async function handleSavePreset(e: SubmitEvent) {
e.preventDefault(); e.preventDefault();
saving = true; saving = true;
try { try {
await saveMealAsPreset(date, meal.id, presetName.trim() || meal.name); await saveMealAsPreset(date, meal.id, presetName.trim() || meal.name);
queryClient.invalidateQueries({ queryKey: ['presets'] }); queryClient.invalidateQueries({ queryKey: ["presets"] });
presetOpen = false; presetOpen = false;
} finally { } finally {
saving = false; saving = false;
} }
} }
async function handleDeleteEntry(entryId: number) { async function handleDeleteEntry(entryId: number) {
await deleteEntry(date, meal.id, entryId); await deleteEntry(date, meal.id, entryId);
queryClient.invalidateQueries({ queryKey: ['diary', date] }); queryClient.invalidateQueries({ queryKey: ["diary", date] });
} }
function handleEditEntry(entry: import('$lib/types/api').Entry) { function handleEditEntry(entry: import("$lib/types/api").Entry) {
goto(`/diary/${date}/edit-entry/${entry.id}`); goto(`/diary/${date}/edit-entry/${entry.id}`);
} }
</script> </script>
<div class="bg-zinc-900 rounded-2xl overflow-hidden"> <div class="bg-zinc-900 rounded-2xl overflow-hidden">
<!-- Meal header --> <!-- Meal header -->
<div class="flex items-center justify-between px-4 py-3 border-b border-zinc-800"> <div
<button class="flex items-center justify-between px-4 py-3 border-b border-zinc-800"
onclick={() => collapsed = !collapsed} >
class="flex-1 flex items-center gap-2 text-left min-w-0" <button
> onclick={() => (collapsed = !collapsed)}
<svg class="flex-1 flex items-center gap-2 text-left min-w-0"
class="w-4 h-4 text-zinc-500 shrink-0 transition-transform {collapsed ? '-rotate-90' : ''}" >
fill="none" stroke="currentColor" viewBox="0 0 24 24" <svg
> class="w-4 h-4 text-zinc-500 shrink-0 transition-transform {collapsed
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /> ? '-rotate-90'
</svg> : ''}"
<div class="min-w-0 flex-1"> fill="none"
<p class="font-medium truncate">{meal.name}</p> stroke="currentColor"
<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> viewBox="0 0 24 24"
</div> >
</button> <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"> <div class="flex gap-1 ml-2 shrink-0 items-center">
<!-- Add entry --> <!-- Add entry -->
<button <button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)} 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" 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" aria-label="Add food"
> >
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4" /> class="w-3.5 h-3.5"
</svg> fill="none"
Add stroke="currentColor"
</button> viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2.5"
d="M12 4v16m8-8H4"
/>
</svg>
Add
</button>
<!-- Rename --> <!-- Rename -->
<button <button
onclick={openRename} 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" 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" aria-label="Rename meal"
> >
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<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" /> class="w-4 h-4"
</svg> fill="none"
</button> 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 --> <!-- Save as preset -->
<button <button
onclick={openPresetSheet} onclick={openPresetSheet}
disabled={saving || meal.entries.length === 0} 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" 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" aria-label="Save as preset"
> >
{#if saving} {#if saving}
<svg class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<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" /> class="w-4 h-4 animate-spin"
</svg> fill="none"
{:else} stroke="currentColor"
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> 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> <path
{/if} stroke-linecap="round"
</button> 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 --> <!-- Delete meal -->
<button <button
onclick={handleDeleteMeal} 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" 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" aria-label="Delete meal"
> >
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<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" /> class="w-4 h-4"
</svg> fill="none"
</button> stroke="currentColor"
</div> viewBox="0 0 24 24"
</div> >
<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 --> <!-- Entries -->
{#if !collapsed} {#if !collapsed}
<div class="px-4 divide-y divide-zinc-800"> <div class="px-4 divide-y divide-zinc-800">
{#if meal.entries.length === 0} {#if meal.entries.length === 0}
<button <button
onclick={() => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`)} 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" class="w-full text-sm text-zinc-600 py-4 text-center hover:text-zinc-400 transition-colors"
> >
Tap + to add food Tap + to add food
</button> </button>
{/if} {/if}
{#each meal.entries as entry (entry.id)} {#each meal.entries as entry (entry.id)}
<EntryRow <EntryRow
{entry} {entry}
onDelete={handleDeleteEntry} onDelete={handleDeleteEntry}
onEdit={handleEditEntry} onEdit={handleEditEntry}
/> />
{/each} {/each}
</div> </div>
{/if} {/if}
</div> </div>
<Sheet open={presetOpen} onclose={() => presetOpen = false} title="Save as preset"> <Sheet
<form onsubmit={handleSavePreset} class="space-y-4"> open={presetOpen}
<div> onclose={() => (presetOpen = false)}
<label class="block text-sm text-zinc-400 mb-1.5">Preset name</label> title="Save as preset"
<input >
type="text" <form onsubmit={handleSavePreset} class="space-y-4">
bind:value={presetName} <div>
required <label class="block text-sm text-zinc-400 mb-1.5">Preset name</label>
autofocus <input
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" type="text"
/> bind:value={presetName}
</div> required
<button autofocus
type="submit" 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"
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" </div>
> <button
{saving ? 'Saving…' : 'Save preset'} type="submit"
</button> disabled={saving || !presetName.trim()}
</form> 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>
<Sheet open={renameOpen} onclose={() => renameOpen = false} title="Rename meal"> <Sheet
<form onsubmit={handleRename} class="space-y-4"> open={renameOpen}
<input onclose={() => (renameOpen = false)}
type="text" title="Rename meal"
bind:value={renameName} >
required <form onsubmit={handleRename} class="space-y-4">
autofocus <input
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" type="text"
/> bind:value={renameName}
<button required
type="submit" autofocus
disabled={renaming || !renameName.trim()} 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"
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors" />
> <button
{renaming ? 'Saving…' : 'Save'} type="submit"
</button> disabled={renaming || !renameName.trim()}
</form> 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> </Sheet>

View file

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

View file

@ -1,86 +1,99 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from "svelte";
interface Props { interface Props {
open: boolean; open: boolean;
onclose: () => void; onclose: () => void;
title?: string; title?: string;
children: import('svelte').Snippet; 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(() => { onMount(() => {
const vv = window.visualViewport; const vv = window.visualViewport;
if (!vv) return; if (!vv) return;
function update() { function update() {
bottomOffset = Math.max(0, window.innerHeight - vv!.offsetTop - vv!.height); bottomOffset = Math.max(
} 0,
window.innerHeight - vv!.offsetTop - vv!.height,
);
}
vv.addEventListener('resize', update); vv.addEventListener("resize", update);
vv.addEventListener('scroll', update); vv.addEventListener("scroll", update);
return () => { return () => {
vv.removeEventListener('resize', update); vv.removeEventListener("resize", update);
vv.removeEventListener('scroll', update); vv.removeEventListener("scroll", update);
}; };
}); });
function handleBackdrop(e: MouseEvent) { function handleBackdrop(e: MouseEvent) {
if (e.target === e.currentTarget) onclose(); if (e.target === e.currentTarget) onclose();
} }
function handleKey(e: KeyboardEvent) { function handleKey(e: KeyboardEvent) {
if (e.key === 'Escape') onclose(); if (e.key === "Escape") onclose();
} }
</script> </script>
<svelte:window onkeydown={handleKey} /> <svelte:window onkeydown={handleKey} />
{#if open} {#if open}
<!-- Backdrop --> <!-- Backdrop -->
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div <div
class="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm" class="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm"
onclick={handleBackdrop} onclick={handleBackdrop}
></div> ></div>
<!-- Sheet (mobile bottom sheet / desktop centered modal) --> <!-- Sheet (mobile bottom sheet / desktop centered modal) -->
<div <div
class="fixed z-50 bg-zinc-900 px-4 pt-4 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 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" 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" style="bottom: {bottomOffset}px"
> >
<!-- Handle (mobile only) --> <!-- Handle (mobile only) -->
<div class="w-10 h-1 bg-zinc-700 rounded-full mx-auto mb-4 lg:hidden"></div> <div class="w-10 h-1 bg-zinc-700 rounded-full mx-auto mb-4 lg:hidden"></div>
{#if title} {#if title}
<h2 class="text-base font-semibold mb-4">{title}</h2> <h2 class="text-base font-semibold mb-4">{title}</h2>
{/if} {/if}
{@render children()} {@render children()}
</div> </div>
{/if} {/if}
<style> <style>
@keyframes slide-up { @keyframes slide-up {
from { transform: translateY(100%); } from {
to { transform: translateY(0); } transform: translateY(100%);
} }
@keyframes fade-in { to {
from { opacity: 0; transform: translate(-50%, -48%); } transform: translateY(0);
to { opacity: 1; transform: translate(-50%, -50%); } }
} }
.animate-slide-up { @keyframes fade-in {
animation: slide-up 0.22s cubic-bezier(0.32, 0.72, 0, 1); from {
} opacity: 0;
@media (min-width: 1024px) { transform: translate(-50%, -48%);
.animate-slide-up { }
animation: fade-in 0.18s ease-out; 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> </style>

View file

@ -1,37 +1,49 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from "$app/navigation";
interface Props { interface Props {
title: string; title: string;
back?: string | (() => void); back?: string | (() => void);
action?: import('svelte').Snippet; action?: import("svelte").Snippet;
} }
let { title, back, action }: Props = $props(); let { title, back, action }: Props = $props();
function handleBack() { function handleBack() {
if (!back) return; if (!back) return;
if (typeof back === 'function') back(); if (typeof back === "function") back();
else goto(back); else goto(back);
} }
</script> </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"> <header
{#if back} 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"
<button >
onclick={handleBack} {#if back}
class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors shrink-0 lg:hidden" <button
aria-label="Go back" onclick={handleBack}
> class="w-10 h-10 flex items-center justify-center rounded-full hover:bg-zinc-800 transition-colors shrink-0 lg:hidden"
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> aria-label="Go back"
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" /> >
</svg> <svg
</button> class="w-5 h-5"
{/if} 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} {#if action}
{@render action()} {@render action()}
{/if} {/if}
</header> </header>

View file

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

View file

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

View file

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

View file

@ -1,105 +1,105 @@
export interface Token { export interface Token {
access_token: string; access_token: string;
refresh_token: string; refresh_token: string;
token_type: string; token_type: string;
} }
export interface User { export interface User {
username: string; username: string;
} }
export interface Macros { export interface Macros {
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
} }
export interface Product { export interface Product {
id: number; id: number;
name: string; name: string;
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
barcode: string | null; barcode: string | null;
usage_count_cached?: number | null; usage_count_cached?: number | null;
} }
export interface Entry { export interface Entry {
id: number; id: number;
grams: number; grams: number;
product_id: number; product_id: number;
product: Product; product: Product;
meal_id: number; meal_id: number;
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
} }
export interface Meal { export interface Meal {
id: number; id: number;
name: string; name: string;
order: number; order: number;
diary_id: number; diary_id: number;
entries: Entry[]; entries: Entry[];
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
} }
export interface Diary { export interface Diary {
id: number; id: number;
date: string; date: string;
protein_goal: number; protein_goal: number;
carb_goal: number; carb_goal: number;
fat_goal: number; fat_goal: number;
fiber_goal: number; fiber_goal: number;
calories_goal: number; calories_goal: number;
meals: Meal[]; meals: Meal[];
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
} }
export interface Preset { export interface Preset {
id: number; id: number;
name: string; name: string;
user_id: number; user_id: number;
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
entries: PresetEntry[]; entries: PresetEntry[];
} }
export interface UserSettings { export interface UserSettings {
id: number; id: number;
protein_goal: number; protein_goal: number;
carb_goal: number; carb_goal: number;
fat_goal: number; fat_goal: number;
fiber_goal: number; fiber_goal: number;
calories_goal: number; calories_goal: number;
} }
export interface PresetEntry { export interface PresetEntry {
id: number; id: number;
grams: number; grams: number;
product_id: number; product_id: number;
preset_id: number; preset_id: number;
product: Product; product: Product;
calories: number; calories: number;
protein: number; protein: number;
carb: number; carb: number;
fat: number; fat: number;
fiber: number; fiber: number;
} }

View file

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

View file

@ -1,9 +1,9 @@
/** Round to nearest integer (for kcal) */ /** Round to nearest integer (for kcal) */
export function kcal(x: number): number { export function kcal(x: number): number {
return Math.round(x); return Math.round(x);
} }
/** Round to 1 decimal (for macros in grams) */ /** Round to 1 decimal (for macros in grams) */
export function g(x: number): number { 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"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from "$app/navigation";
import { auth } from '$lib/auth/store.svelte'; import { auth } from "$lib/auth/store.svelte";
import { logout } from '$lib/api/auth'; import { logout } from "$lib/api/auth";
import { useQueryClient } from '@tanstack/svelte-query'; import { useQueryClient } from "@tanstack/svelte-query";
import { page } from '$app/state'; import { page } from "$app/state";
import { onMount } from 'svelte'; import { onMount } from "svelte";
import { network } from '$lib/offline/network.svelte'; import { network } from "$lib/offline/network.svelte";
import { syncOfflineQueue } from '$lib/offline/sync'; import { syncOfflineQueue } from "$lib/offline/sync";
import { getMutationQueueLength } from '$lib/offline/db'; import { getMutationQueueLength } from "$lib/offline/db";
let { children } = $props(); let { children } = $props();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
onMount(async () => { onMount(async () => {
if (!auth.isAuthenticated) goto('/login'); if (!auth.isAuthenticated) goto("/login");
// Restore pending count from IndexedDB in case of page reload while offline // Restore pending count from IndexedDB in case of page reload while offline
const queued = await getMutationQueueLength(); const queued = await getMutationQueueLength();
network.setPendingCount(queued); network.setPendingCount(queued);
// Sync on reconnect // Sync on reconnect
window.addEventListener('online', handleReconnect); window.addEventListener("online", handleReconnect);
return () => window.removeEventListener('online', handleReconnect); return () => window.removeEventListener("online", handleReconnect);
}); });
async function handleReconnect() { async function handleReconnect() {
if (network.syncing) return; // prevent concurrent sync on rapid reconnects if (network.syncing) return; // prevent concurrent sync on rapid reconnects
if (network.pendingCount === 0) return; if (network.pendingCount === 0) return;
network.setSyncing(true); network.setSyncing(true);
try { try {
await syncOfflineQueue(); await syncOfflineQueue();
network.setPendingCount(0); network.setPendingCount(0);
// Refetch everything so optimistic data is replaced by server truth // Refetch everything so optimistic data is replaced by server truth
await queryClient.invalidateQueries(); await queryClient.invalidateQueries();
} finally { } finally {
network.setSyncing(false); network.setSyncing(false);
} }
} }
function handleLogout() { function handleLogout() {
logout(); logout();
queryClient.clear(); queryClient.clear();
goto('/login'); goto("/login");
} }
const isDiary = $derived(page.url.pathname.startsWith('/diary')); const isDiary = $derived(page.url.pathname.startsWith("/diary"));
const isPresets = $derived(page.url.pathname.startsWith('/presets')); const isPresets = $derived(page.url.pathname.startsWith("/presets"));
const isSettings = $derived(page.url.pathname.startsWith('/settings')); const isSettings = $derived(page.url.pathname.startsWith("/settings"));
</script> </script>
{#if auth.isAuthenticated} {#if auth.isAuthenticated}
<div class="lg:flex min-h-screen"> <div class="lg:flex min-h-screen">
<!-- Offline / syncing banner --> <!-- Offline / syncing banner -->
{#if !network.online || network.syncing} {#if !network.online || network.syncing}
<div <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 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'}" {network.syncing ? 'bg-blue-600' : 'bg-zinc-700'}"
style="padding-top: calc(0.5rem + var(--safe-top))" style="padding-top: calc(0.5rem + var(--safe-top))"
> >
{#if network.syncing} {#if network.syncing}
<svg class="w-3.5 h-3.5 animate-spin shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<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" /> class="w-3.5 h-3.5 animate-spin shrink-0"
</svg> fill="none"
Syncing changes… stroke="currentColor"
{:else} viewBox="0 0 24 24"
<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" /> <path
</svg> stroke-linecap="round"
Offline{network.pendingCount > 0 ? ` · ${network.pendingCount} change${network.pendingCount === 1 ? '' : 's'} pending sync` : ''} stroke-linejoin="round"
{/if} stroke-width="2"
</div> 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"
{/if} />
</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) --> <!-- 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"> <aside
<div class="px-2 mb-8"> 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"
<span class="text-lg font-bold text-green-400">fooder</span> >
</div> <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"> <nav class="flex-1 space-y-1">
<a <a
href="/diary/today" href="/diary/today"
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors 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'}" {isDiary
> ? 'bg-zinc-800 text-zinc-100'
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'}"
<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> <svg
Diary class="w-4 h-4 shrink-0"
</a> fill="none"
<a stroke="currentColor"
href="/presets" viewBox="0 0 24 24"
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'}" <path
> stroke-linecap="round"
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> stroke-linejoin="round"
<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" /> stroke-width="2"
</svg> 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"
Presets />
</a> </svg>
<a Diary
href="/settings" </a>
class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors <a
{isSettings ? 'bg-zinc-800 text-zinc-100' : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'}" href="/presets"
> class="flex items-center gap-2.5 px-3 py-2 rounded-xl text-sm font-medium transition-colors
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> {isPresets
<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" /> ? 'bg-zinc-800 text-zinc-100'
</svg> : 'text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900'}"
Settings >
</a> <svg
</nav> 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 <button
onclick={handleLogout} 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" 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"> <svg
<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" /> class="w-4 h-4 shrink-0"
</svg> fill="none"
Log out stroke="currentColor"
</button> viewBox="0 0 24 24"
</aside> >
<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 --> <!-- Main content -->
<div class="flex-1 lg:ml-52 flex flex-col min-h-screen"> <div class="flex-1 lg:ml-52 flex flex-col min-h-screen">
{@render children()} {@render children()}
</div> </div>
<!-- Bottom tab bar (mobile only) --> <!-- 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)]"> <nav
<a 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)]"
href="/diary/today" >
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors <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'}" {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"> <svg
<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" /> class="w-5 h-5"
</svg> fill="none"
Diary stroke="currentColor"
</a> viewBox="0 0 24 24"
<a >
href="/presets" <path
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors 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'}" {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"> <svg
<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" /> class="w-5 h-5"
</svg> fill="none"
Presets stroke="currentColor"
</a> viewBox="0 0 24 24"
<a >
href="/settings" <path
class="flex-1 flex flex-col items-center gap-1 py-3 text-xs font-medium transition-colors 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'}" {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"> <svg
<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" /> class="w-5 h-5"
</svg> fill="none"
Settings stroke="currentColor"
</a> viewBox="0 0 24 24"
<button >
onclick={handleLogout} <path
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" stroke-linecap="round"
> stroke-linejoin="round"
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> stroke-width="2"
<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" /> 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"
</svg> /><path
Log out stroke-linecap="round"
</button> stroke-linejoin="round"
</nav> stroke-width="2"
</div> 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} {/if}

View file

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

View file

@ -1,207 +1,236 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from "$app/state";
import { createQuery, useQueryClient } from '@tanstack/svelte-query'; import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getDiary, createDiary } from '$lib/api/diary'; import { getDiary, createDiary } from "$lib/api/diary";
import { getCachedDiary, cacheDiary } from '$lib/offline/db'; import { getCachedDiary, cacheDiary } from "$lib/offline/db";
import { addDays, formatDisplay, today } from '$lib/utils/date'; import { addDays, formatDisplay, today } from "$lib/utils/date";
import { goto } from '$app/navigation'; import { goto } from "$app/navigation";
import { network } from '$lib/offline/network.svelte'; import { network } from "$lib/offline/network.svelte";
import { onMount } from 'svelte'; import { onMount } from "svelte";
import MacroSummary from '$lib/components/diary/MacroSummary.svelte'; import MacroSummary from "$lib/components/diary/MacroSummary.svelte";
import MealCard from '$lib/components/diary/MealCard.svelte'; import MealCard from "$lib/components/diary/MealCard.svelte";
import DateNav from '$lib/components/diary/DateNav.svelte'; import DateNav from "$lib/components/diary/DateNav.svelte";
import CalendarPicker from '$lib/components/diary/CalendarPicker.svelte'; import CalendarPicker from "$lib/components/diary/CalendarPicker.svelte";
import Sheet from '$lib/components/ui/Sheet.svelte'; import Sheet from "$lib/components/ui/Sheet.svelte";
import CommandPalette from '$lib/components/ui/CommandPalette.svelte'; import CommandPalette from "$lib/components/ui/CommandPalette.svelte";
import type { Command } from '$lib/components/ui/CommandPalette.svelte'; import type { Command } from "$lib/components/ui/CommandPalette.svelte";
const date = $derived(page.params.date!); const date = $derived(page.params.date!);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
let calendarOpen = $state(false); let calendarOpen = $state(false);
let commandOpen = $state(false); let commandOpen = $state(false);
let creating = $state(false); let creating = $state(false);
const commands = $derived<Command[]>([ const commands = $derived<Command[]>([
...(diaryQuery.data?.meals ?? []).map(meal => ({ ...(diaryQuery.data?.meals ?? []).map((meal) => ({
id: `entry-${meal.id}`, id: `entry-${meal.id}`,
label: `Add entry → ${meal.name}`, label: `Add entry → ${meal.name}`,
keywords: ['e', 'entry', 'food', 'add'], keywords: ["e", "entry", "food", "add"],
action: () => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`) action: () => goto(`/diary/${date}/add-entry?meal_id=${meal.id}`),
})), })),
{ {
id: 'add-meal', id: "add-meal",
label: 'Add meal', label: "Add meal",
keywords: ['m', 'meal'], keywords: ["m", "meal"],
action: () => goto(`/diary/${date}/add-meal`) action: () => goto(`/diary/${date}/add-meal`),
} },
]); ]);
onMount(() => { onMount(() => {
function handleKeydown(e: KeyboardEvent) { function handleKeydown(e: KeyboardEvent) {
const tag = (e.target as HTMLElement).tagName; const tag = (e.target as HTMLElement).tagName;
const editable = (e.target as HTMLElement).isContentEditable; const editable = (e.target as HTMLElement).isContentEditable;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || editable) return; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || editable)
if (e.key === '/' || e.key === ':') { return;
e.preventDefault(); if (e.key === "/" || e.key === ":") {
commandOpen = true; e.preventDefault();
} commandOpen = true;
} }
document.addEventListener('keydown', handleKeydown); }
return () => document.removeEventListener('keydown', handleKeydown); document.addEventListener("keydown", handleKeydown);
}); return () => document.removeEventListener("keydown", handleKeydown);
});
const diaryQuery = createQuery(() => ({ const diaryQuery = createQuery(() => ({
queryKey: ['diary', date], queryKey: ["diary", date],
queryFn: async () => { queryFn: async () => {
if (!network.online) { if (!network.online) {
// Prefer in-memory cache — it contains any optimistic updates // Prefer in-memory cache — it contains any optimistic updates
const inMemory = queryClient.getQueryData<import('$lib/types/api').Diary>(['diary', date]); const inMemory = queryClient.getQueryData<
if (inMemory) return inMemory; import("$lib/types/api").Diary
// Fall back to IndexedDB (survives page reload) >(["diary", date]);
const cached = await getCachedDiary(date); if (inMemory) return inMemory;
if (cached) return cached; // Fall back to IndexedDB (survives page reload)
throw new Error('Offline and no cached data'); const cached = await getCachedDiary(date);
} if (cached) return cached;
// Online: fetch fresh data — this overwrites both TQ cache and IndexedDB, throw new Error("Offline and no cached data");
// replacing any temporary negative-ID entries from optimistic updates }
try { // Online: fetch fresh data — this overwrites both TQ cache and IndexedDB,
const diary = await getDiary(date); // replacing any temporary negative-ID entries from optimistic updates
if (diary === null) { try {
if (date === today()) { const diary = await getDiary(date);
const created = await createDiary(date); if (diary === null) {
await cacheDiary(JSON.parse(JSON.stringify(created))); if (date === today()) {
return created; const created = await createDiary(date);
} await cacheDiary(JSON.parse(JSON.stringify(created)));
return null; return created;
} }
await cacheDiary(JSON.parse(JSON.stringify(diary))); return null;
return diary; }
} catch { await cacheDiary(JSON.parse(JSON.stringify(diary)));
// Network failed despite network.online being true — fall back to cache return diary;
network.setOffline(); } catch {
const inMemory = queryClient.getQueryData<import('$lib/types/api').Diary>(['diary', date]); // Network failed despite network.online being true — fall back to cache
if (inMemory) return inMemory; network.setOffline();
const cached = await getCachedDiary(date); const inMemory = queryClient.getQueryData<
if (cached) return cached; import("$lib/types/api").Diary
throw new Error('Offline and no cached data'); >(["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() { async function handleCreate() {
creating = true; creating = true;
try { try {
await createDiary(date); await createDiary(date);
queryClient.invalidateQueries({ queryKey: ['diary', date] }); queryClient.invalidateQueries({ queryKey: ["diary", date] });
} finally { } finally {
creating = false; creating = false;
} }
} }
function goDate(delta: number) { function goDate(delta: number) {
goto(`/diary/${addDays(date, delta)}`); goto(`/diary/${addDays(date, delta)}`);
} }
function handleDateSelect(d: string) { function handleDateSelect(d: string) {
calendarOpen = false; calendarOpen = false;
goto(`/diary/${d}`); goto(`/diary/${d}`);
} }
</script> </script>
<div class="flex flex-col h-screen"> <div class="flex flex-col h-screen">
<!-- 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"> <header
<DateNav 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"
{date} >
label={formatDisplay(date)} <DateNav
onPrev={() => goDate(-1)} {date}
onNext={() => goDate(1)} label={formatDisplay(date)}
isToday={date === today()} onPrev={() => goDate(-1)}
onDateClick={() => calendarOpen = true} onNext={() => goDate(1)}
/> isToday={date === today()}
</header> onDateClick={() => (calendarOpen = true)}
/>
</header>
<!-- Content --> <!-- Content -->
<main class="flex-1 overflow-y-auto px-4 py-4 pb-[calc(5rem+var(--safe-bottom))] lg:pb-6"> <main
{#if diaryQuery.isPending} class="flex-1 overflow-y-auto px-4 py-4 pb-[calc(5rem+var(--safe-bottom))] lg:pb-6"
<!-- 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"> {#if diaryQuery.isPending}
<div class="h-28 bg-zinc-800 rounded-2xl"></div> <!-- Skeleton -->
<div class="space-y-4"> <div
<div class="h-40 bg-zinc-800 rounded-2xl"></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-40 bg-zinc-800 rounded-2xl"></div> >
</div> <div class="h-28 bg-zinc-800 rounded-2xl"></div>
</div> <div class="space-y-4">
{:else if diaryQuery.isError} <div class="h-40 bg-zinc-800 rounded-2xl"></div>
<div class="text-center text-zinc-500 mt-20"> <div class="h-40 bg-zinc-800 rounded-2xl"></div>
<p class="text-lg">Could not load diary</p> </div>
<p class="text-sm mt-1">{diaryQuery.error?.message ?? 'Unknown error'}</p> </div>
<button {:else if diaryQuery.isError}
onclick={() => diaryQuery.refetch()} <div class="text-center text-zinc-500 mt-20">
class="mt-4 px-4 py-2 bg-zinc-800 rounded-xl text-sm" <p class="text-lg">Could not load diary</p>
> <p class="text-sm mt-1">
Retry {diaryQuery.error?.message ?? "Unknown error"}
</button> </p>
</div> <button
{:else if diaryQuery.data === null} onclick={() => diaryQuery.refetch()}
<div class="text-center text-zinc-500 mt-20"> class="mt-4 px-4 py-2 bg-zinc-800 rounded-xl text-sm"
<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> Retry
<button </button>
onclick={handleCreate} </div>
disabled={creating} {:else if diaryQuery.data === null}
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" <div class="text-center text-zinc-500 mt-20">
> <p class="text-lg">No diary for {formatDisplay(date)}</p>
{creating ? 'Creating…' : 'Create diary'} <p class="text-sm mt-1">No entries have been tracked for this date.</p>
</button> <button
</div> onclick={handleCreate}
{:else if diaryQuery.data} disabled={creating}
{@const diary = diaryQuery.data} 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"> <div
<!-- Left: macros summary (sticky on desktop) --> class="space-y-4 lg:grid lg:grid-cols-[300px_1fr] lg:gap-6 lg:space-y-0 lg:items-start"
<div class="lg:sticky lg:top-[4.5rem]"> >
<MacroSummary {diary} {date} /> <!-- Left: macros summary (sticky on desktop) -->
</div> <div class="lg:sticky lg:top-[4.5rem]">
<MacroSummary {diary} {date} />
</div>
<!-- Right: meals --> <!-- Right: meals -->
<div class="space-y-4"> <div class="space-y-4">
{#each diary.meals as meal (meal.id)} {#each diary.meals as meal (meal.id)}
<MealCard {meal} {date} /> <MealCard {meal} {date} />
{/each} {/each}
<!-- Add meal button --> <!-- Add meal button -->
<button <button
onclick={() => goto(`/diary/${date}/add-meal`)} 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" 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 + Add meal
</button> </button>
</div> </div>
</div> </div>
{/if} {/if}
</main> </main>
<!-- FAB: Add entry (mobile only) --> <!-- FAB: Add entry (mobile only) -->
{#if diaryQuery.data != null} {#if diaryQuery.data != null}
<button <button
onclick={() => { onclick={() => {
const firstMeal = diaryQuery.data?.meals[0]; const firstMeal = diaryQuery.data?.meals[0];
if (firstMeal) goto(`/diary/${date}/add-entry?meal_id=${firstMeal.id}`); 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" 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" aria-label="Add entry"
> >
<svg class="w-7 h-7" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <svg
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /> class="w-7 h-7"
</svg> fill="none"
</button> stroke="currentColor"
{/if} 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}> <Sheet open={calendarOpen} onclose={() => (calendarOpen = false)}>
<CalendarPicker selected={date} onSelect={handleDateSelect} /> <CalendarPicker selected={date} onSelect={handleDateSelect} />
</Sheet> </Sheet>
<CommandPalette {commands} open={commandOpen} onclose={() => commandOpen = false} /> <CommandPalette
{commands}
open={commandOpen}
onclose={() => (commandOpen = false)}
/>
</div> </div>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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