create empty preset

This commit is contained in:
Piotr Domański 2026-04-08 20:14:36 +02:00
parent a219b4449a
commit 0bb87b3933
4 changed files with 986 additions and 678 deletions

View file

@ -6,6 +6,10 @@ export function listPresets(limit = 20, offset = 0): Promise<Preset[]> {
return apiGet<Preset[]>(`/preset?${params}`);
}
export function createPreset(name: string): Promise<Preset> {
return apiPost<Preset>(`/preset/`, { name });
}
export function renamePreset(id: number, name: string): Promise<Preset> {
return apiPatch<Preset>(`/preset/${id}`, { name });
}

View file

@ -1,36 +1,38 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { listProducts, getProductByBarcode } from '$lib/api/products';
import { cacheProducts, searchCachedProducts } from '$lib/offline/db';
import { offlineAddEntry } from '$lib/offline/mutations';
import { network } from '$lib/offline/network.svelte';
import type { Product } from '$lib/types/api';
import TopBar from '$lib/components/ui/TopBar.svelte';
import Sheet from '$lib/components/ui/Sheet.svelte';
import BarcodeScanner from '$lib/components/ui/BarcodeScanner.svelte';
import { kcal, g } from '$lib/utils/format';
import { page } from "$app/state";
import { goto } from "$app/navigation";
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { listProducts, getProductByBarcode } from "$lib/api/products";
import { cacheProducts, searchCachedProducts } from "$lib/offline/db";
import { offlineAddEntry } from "$lib/offline/mutations";
import { network } from "$lib/offline/network.svelte";
import type { Product } from "$lib/types/api";
import TopBar from "$lib/components/ui/TopBar.svelte";
import Sheet from "$lib/components/ui/Sheet.svelte";
import BarcodeScanner from "$lib/components/ui/BarcodeScanner.svelte";
import { kcal, g } from "$lib/utils/format";
const date = $derived(page.params.date!);
const mealId = $derived(Number(page.url.searchParams.get('meal_id')));
const mealId = $derived(Number(page.url.searchParams.get("meal_id")));
const queryClient = useQueryClient();
let q = $state('');
let debouncedQ = $state('');
let q = $state("");
let debouncedQ = $state("");
let debounceTimer: ReturnType<typeof setTimeout>;
let selectedProduct = $state<Product | null>(null);
let grams = $state(100);
let submitting = $state(false);
let error = $state('');
let error = $state("");
let scannerOpen = $state(false);
let scanLoading = $state(false);
let scanError = $state<string | null>(null);
let searchInput = $state<HTMLInputElement | null>(null);
$effect(() => { if (searchInput) setTimeout(() => searchInput?.focus(), 50); });
$effect(() => {
if (searchInput) setTimeout(() => searchInput?.focus(), 50);
});
let gramsInput = $state<HTMLInputElement | null>(null);
$effect(() => {
@ -42,11 +44,13 @@
function handleSearch(value: string) {
q = value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => { debouncedQ = value; }, 300);
debounceTimer = setTimeout(() => {
debouncedQ = value;
}, 300);
}
const productsQuery = createQuery(() => ({
queryKey: ['products', debouncedQ],
queryKey: ["products", debouncedQ],
queryFn: async () => {
if (!network.online) {
return searchCachedProducts(debouncedQ);
@ -56,13 +60,13 @@
cacheProducts(products);
return products;
},
staleTime: 0
staleTime: 0,
}));
function selectProduct(product: Product) {
selectedProduct = product;
grams = 100;
error = '';
error = "";
}
async function handleBarcodeDetected(barcode: string) {
@ -76,7 +80,7 @@
if (err?.status === 404) {
goto(`/products/new?barcode=${encodeURIComponent(barcode)}`);
} else {
scanError = 'Could not look up barcode. Try searching manually.';
scanError = "Could not look up barcode. Try searching manually.";
}
} finally {
scanLoading = false;
@ -86,28 +90,33 @@
async function handleAddEntry() {
if (!selectedProduct || !mealId) return;
submitting = true;
error = '';
error = "";
try {
await offlineAddEntry(queryClient, date, mealId, selectedProduct, grams);
goto(`/diary/${date}`);
} catch (e: any) {
error = e.message ?? 'Failed to add entry';
error = e.message ?? "Failed to add entry";
submitting = false;
}
}
const preview = $derived(selectedProduct ? {
calories: Math.round(selectedProduct.calories * grams / 100),
protein: Math.round(selectedProduct.protein * grams / 100 * 10) / 10,
carb: Math.round(selectedProduct.carb * grams / 100 * 10) / 10,
fat: Math.round(selectedProduct.fat * grams / 100 * 10) / 10,
} : null);
const preview = $derived(
selectedProduct
? {
calories: Math.round((selectedProduct.calories * grams) / 100),
protein:
Math.round(((selectedProduct.protein * grams) / 100) * 10) / 10,
carb: Math.round(((selectedProduct.carb * grams) / 100) * 10) / 10,
fat: Math.round(((selectedProduct.fat * grams) / 100) * 10) / 10,
}
: null,
);
</script>
{#if scannerOpen}
<BarcodeScanner
ondetect={handleBarcodeDetected}
onclose={() => scannerOpen = false}
onclose={() => (scannerOpen = false)}
/>
{/if}
@ -118,8 +127,18 @@
<div class="px-4 py-3 border-b border-zinc-800 bg-zinc-950">
<div class="flex gap-2">
<div class="relative flex-1">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
<svg
class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
<input
bind:this={searchInput}
@ -128,7 +147,7 @@
value={q}
oninput={(e) => handleSearch(e.currentTarget.value)}
onkeydown={(e) => {
if (e.key === 'Enter') {
if (e.key === "Enter") {
const first = productsQuery.data?.[0];
if (first) selectProduct(first);
}
@ -140,18 +159,41 @@
<!-- Barcode scan button (online only) -->
{#if network.online}
<button
onclick={() => { scanError = null; scannerOpen = true; }}
onclick={() => {
scanError = null;
scannerOpen = true;
}}
disabled={scanLoading}
class="w-11 h-11 flex items-center justify-center rounded-xl bg-zinc-900 border border-zinc-700 text-zinc-400 hover:text-green-400 hover:border-green-500 disabled:opacity-50 transition-colors shrink-0"
aria-label="Scan barcode"
>
{#if scanLoading}
<svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
<svg
class="w-5 h-5 animate-spin"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
/>
</svg>
{:else}
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m0 14v1M4 12h1m14 0h1M6.343 6.343l.707.707m9.9 9.9.707.707M6.343 17.657l.707-.707m9.9-9.9.707-.707M12 8a4 4 0 100 8 4 4 0 000-8z" />
<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="M12 4v1m0 14v1M4 12h1m14 0h1M6.343 6.343l.707.707m9.9 9.9.707.707M6.343 17.657l.707-.707m9.9-9.9.707-.707M12 8a4 4 0 100 8 4 4 0 000-8z"
/>
</svg>
{/if}
</button>
@ -179,8 +221,11 @@
{:else}
<p class="text-base">No products found</p>
<p class="text-sm mt-1">Try a different name or</p>
<a href="/products/new?name={encodeURIComponent(q)}" class="mt-3 inline-block text-green-500 text-sm">
Create "{q || 'new product'}"
<a
href="/products/new?name={encodeURIComponent(q)}"
class="mt-3 inline-block text-green-500 hover:text-green-300 transition-colors text-sm"
>
Create "{q || "new product"}"
</a>
{/if}
</div>
@ -193,14 +238,28 @@
class="w-full flex items-center justify-between px-4 py-3.5 hover:bg-zinc-900 transition-colors text-left"
>
<div class="min-w-0">
<p class="font-medium text-sm truncate capitalize">{product.name}</p>
<p class="font-medium text-sm truncate capitalize">
{product.name}
</p>
<p class="text-xs text-zinc-500 mt-0.5">
{kcal(product.calories)} kcal · P {g(product.protein)}g · C {g(product.carb)}g · F {g(product.fat)}g
{kcal(product.calories)} kcal · P {g(product.protein)}g · C {g(
product.carb,
)}g · F {g(product.fat)}g
<span class="text-zinc-600">per 100g</span>
</p>
</div>
<svg class="w-4 h-4 text-zinc-600 ml-3 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
<svg
class="w-4 h-4 text-zinc-600 ml-3 shrink-0"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 4v16m8-8H4"
/>
</svg>
</button>
</li>
@ -212,18 +271,16 @@
<!-- Grams sheet -->
<Sheet
open={selectedProduct !== null}
onclose={() => { selectedProduct = null; error = ''; }}
title={selectedProduct?.name ?? ''}
onclose={() => {
selectedProduct = null;
error = "";
}}
title={selectedProduct?.name ?? ""}
>
{#if selectedProduct}
{#if preview}
<div class="grid grid-cols-4 gap-2 mb-5">
{#each [
{ label: 'kcal', value: preview.calories },
{ label: 'protein', value: preview.protein + 'g' },
{ label: 'carbs', value: preview.carb + 'g' },
{ label: 'fat', value: preview.fat + 'g' },
] as m}
{#each [{ label: "kcal", value: preview.calories }, { label: "protein", value: preview.protein + "g" }, { label: "carbs", value: preview.carb + "g" }, { label: "fat", value: preview.fat + "g" }] as m}
<div class="bg-zinc-800 rounded-xl p-2.5 text-center">
<p class="text-base font-semibold">{m.value}</p>
<p class="text-xs text-zinc-500 mt-0.5">{m.label}</p>
@ -236,9 +293,13 @@
<div class="flex items-center gap-3 mb-4">
<button
onpointerdown={(e) => e.preventDefault()}
onclick={() => { grams = Math.max(1, grams - 10); gramsInput?.focus(); }}
onclick={() => {
grams = Math.max(1, grams - 10);
gramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
></button>
></button
>
<input
bind:this={gramsInput}
type="number"
@ -247,14 +308,20 @@
max="5000"
inputmode="decimal"
onfocus={(e) => e.currentTarget.select()}
onkeydown={(e) => { if (e.key === 'Enter') handleAddEntry(); }}
onkeydown={(e) => {
if (e.key === "Enter") handleAddEntry();
}}
class="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-center text-xl font-semibold focus:outline-none focus:border-green-500 transition-colors"
/>
<button
onpointerdown={(e) => e.preventDefault()}
onclick={() => { grams = grams + 10; gramsInput?.focus(); }}
onclick={() => {
grams = grams + 10;
gramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
>+</button>
>+</button
>
</div>
{#if error}
@ -266,7 +333,11 @@
disabled={submitting || grams < 1}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{submitting ? 'Adding…' : network.online ? 'Add to meal' : 'Add to meal (offline)'}
{submitting
? "Adding…"
: network.online
? "Add to meal"
: "Add to meal (offline)"}
</button>
{/if}
</Sheet>

View file

@ -1,36 +1,47 @@
<script lang="ts">
import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { listPresets, deletePreset, renamePreset, createPresetEntry, updatePresetEntry, deletePresetEntry } from '$lib/api/presets';
import { listProducts } from '$lib/api/products';
import { createMealFromPreset } from '$lib/api/meals';
import { today } from '$lib/utils/date';
import { kcal, g } from '$lib/utils/format';
import TopBar from '$lib/components/ui/TopBar.svelte';
import Sheet from '$lib/components/ui/Sheet.svelte';
import type { Preset, PresetEntry, Product } from '$lib/types/api';
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import {
listPresets,
createPreset,
deletePreset,
renamePreset,
createPresetEntry,
updatePresetEntry,
deletePresetEntry,
} from "$lib/api/presets";
import { listProducts } from "$lib/api/products";
import { createMealFromPreset } from "$lib/api/meals";
import { today } from "$lib/utils/date";
import { kcal, g } from "$lib/utils/format";
import TopBar from "$lib/components/ui/TopBar.svelte";
import Sheet from "$lib/components/ui/Sheet.svelte";
import type { Preset, PresetEntry, Product } from "$lib/types/api";
const queryClient = useQueryClient();
// ── Search / filter ───────────────────────────────────────────────────────
let q = $state('');
let debouncedQ = $state('');
let q = $state("");
let debouncedQ = $state("");
let debounceTimer: ReturnType<typeof setTimeout>;
function handleSearch(value: string) {
q = value;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => { debouncedQ = value; }, 300);
debounceTimer = setTimeout(() => {
debouncedQ = value;
}, 300);
}
const presetsQuery = createQuery(() => ({
queryKey: ['presets'],
queryKey: ["presets"],
queryFn: () => listPresets(100),
}));
const filteredPresets = $derived(
(presetsQuery.data ?? []).filter(p =>
!debouncedQ || p.name.toLowerCase().includes(debouncedQ.toLowerCase())
)
(presetsQuery.data ?? []).filter(
(p) =>
!debouncedQ || p.name.toLowerCase().includes(debouncedQ.toLowerCase()),
),
);
// ── Expand/collapse ───────────────────────────────────────────────────────
@ -48,14 +59,33 @@
addingId = preset.id;
try {
await createMealFromPreset(today(), preset.id, preset.name);
queryClient.invalidateQueries({ queryKey: ['diary', today()] });
queryClient.invalidateQueries({ queryKey: ["diary", today()] });
addedId = preset.id;
setTimeout(() => { addedId = null; }, 1500);
setTimeout(() => {
addedId = null;
}, 1500);
} finally {
addingId = null;
}
}
// ── Create preset ─────────────────────────────────────────────────────────
let creating = $state<boolean>(false);
let creatingName = $state("");
let creatingSaving = $state(false);
async function handleCreate() {
creatingSaving = true;
try {
await createPreset(creatingName.trim());
queryClient.invalidateQueries({ queryKey: ["presets"] });
creating = false;
creatingName = "";
} finally {
creatingSaving = false;
}
}
// ── Delete preset ─────────────────────────────────────────────────────────
let deletingId = $state<number | null>(null);
@ -65,7 +95,7 @@
try {
await deletePreset(preset.id);
if (expandedId === preset.id) expandedId = null;
queryClient.invalidateQueries({ queryKey: ['presets'] });
queryClient.invalidateQueries({ queryKey: ["presets"] });
} finally {
deletingId = null;
}
@ -73,7 +103,7 @@
// ── Rename preset ─────────────────────────────────────────────────────────
let renamePreset_: Preset | null = $state(null);
let renameName = $state('');
let renameName = $state("");
let renaming = $state(false);
function openRename(preset: Preset) {
@ -87,7 +117,7 @@
renaming = true;
try {
await renamePreset(renamePreset_.id, renameName.trim());
queryClient.invalidateQueries({ queryKey: ['presets'] });
queryClient.invalidateQueries({ queryKey: ["presets"] });
renamePreset_ = null;
} finally {
renaming = false;
@ -95,7 +125,9 @@
}
// ── Edit entry grams ──────────────────────────────────────────────────────
let editingEntry = $state<{ presetId: number; entry: PresetEntry } | null>(null);
let editingEntry = $state<{ presetId: number; entry: PresetEntry } | null>(
null,
);
let editGrams = $state(0);
let editSaving = $state(false);
let editGramsInput = $state<HTMLInputElement | null>(null);
@ -110,8 +142,12 @@
if (!editingEntry) return;
editSaving = true;
try {
await updatePresetEntry(editingEntry.presetId, editingEntry.entry.id, editGrams);
queryClient.invalidateQueries({ queryKey: ['presets'] });
await updatePresetEntry(
editingEntry.presetId,
editingEntry.entry.id,
editGrams,
);
queryClient.invalidateQueries({ queryKey: ["presets"] });
editingEntry = null;
} finally {
editSaving = false;
@ -121,13 +157,13 @@
// ── Delete entry ──────────────────────────────────────────────────────────
async function handleDeleteEntry(presetId: number, entryId: number) {
await deletePresetEntry(presetId, entryId);
queryClient.invalidateQueries({ queryKey: ['presets'] });
queryClient.invalidateQueries({ queryKey: ["presets"] });
}
// ── Add entry to preset ───────────────────────────────────────────────────
let addEntryPresetId = $state<number | null>(null);
let productQ = $state('');
let productDebouncedQ = $state('');
let productQ = $state("");
let productDebouncedQ = $state("");
let productDebounceTimer: ReturnType<typeof setTimeout>;
let selectedProduct = $state<Product | null>(null);
let addGrams = $state(100);
@ -136,8 +172,8 @@
function openAddEntry(presetId: number) {
addEntryPresetId = presetId;
productQ = '';
productDebouncedQ = '';
productQ = "";
productDebouncedQ = "";
selectedProduct = null;
addGrams = 100;
}
@ -145,11 +181,13 @@
function handleProductSearch(v: string) {
productQ = v;
clearTimeout(productDebounceTimer);
productDebounceTimer = setTimeout(() => { productDebouncedQ = v; }, 300);
productDebounceTimer = setTimeout(() => {
productDebouncedQ = v;
}, 300);
}
const productsQuery = createQuery(() => ({
queryKey: ['products', productDebouncedQ],
queryKey: ["products", productDebouncedQ],
queryFn: () => listProducts(productDebouncedQ, 30),
enabled: addEntryPresetId !== null,
staleTime: 30_000,
@ -161,7 +199,7 @@
addSaving = true;
try {
await createPresetEntry(addEntryPresetId, selectedProduct.id, addGrams);
queryClient.invalidateQueries({ queryKey: ['presets'] });
queryClient.invalidateQueries({ queryKey: ["presets"] });
addEntryPresetId = null;
} finally {
addSaving = false;
@ -175,8 +213,18 @@
<!-- Search -->
<div class="px-4 py-3 border-b border-zinc-800 bg-zinc-950">
<div class="relative">
<svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
<svg
class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
<input
type="search"
@ -200,8 +248,14 @@
{:else if !filteredPresets.length}
<div class="text-center text-zinc-500 mt-16 px-6">
<p>No presets yet</p>
<p class="text-sm mt-1">Save a meal as preset from the diary view</p>
<p class="text-sm mt-1">Save a meal as preset from the diary view or</p>
</div>
<button
onclick={() => (creating = true)}
class="w-full rounded-xl py-4 text-green-500 hover:text-green-300 transition-colors text-sm font-medium"
>
Add preset
</button>
{:else}
<ul class="divide-y divide-zinc-800/50">
{#each filteredPresets as preset (preset.id)}
@ -214,15 +268,27 @@
class="flex-1 flex items-center gap-2 text-left min-w-0"
>
<svg
class="w-4 h-4 text-zinc-500 shrink-0 transition-transform {expandedId === preset.id ? '' : '-rotate-90'}"
fill="none" stroke="currentColor" viewBox="0 0 24 24"
class="w-4 h-4 text-zinc-500 shrink-0 transition-transform {expandedId ===
preset.id
? ''
: '-rotate-90'}"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 9l-7 7-7-7"
/>
</svg>
<div class="min-w-0">
<p class="font-medium truncate">{preset.name}</p>
<p class="text-xs text-zinc-500 mt-0.5">
{kcal(preset.calories)} kcal · P {g(preset.protein)}g · C {g(preset.carb)}g · F {g(preset.fat)}g
{kcal(preset.calories)} kcal · P {g(preset.protein)}g · C {g(
preset.carb,
)}g · F {g(preset.fat)}g
</p>
</div>
</button>
@ -239,17 +305,47 @@
: 'bg-zinc-800 hover:bg-zinc-700 text-zinc-300 disabled:opacity-50'}"
>
{#if addingId === preset.id}
<svg class="w-3 h-3 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
<svg
class="w-3 h-3 animate-spin"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
/>
</svg>
{:else if addedId === preset.id}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
<svg
class="w-3 h-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
/>
</svg>
Added
{:else}
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
<svg
class="w-3 h-3"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 4v16m8-8H4"
/>
</svg>
Today
{/if}
@ -261,8 +357,18 @@
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 preset"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
</button>
@ -273,8 +379,18 @@
class="w-8 h-8 flex items-center justify-center rounded-full text-zinc-600 hover:text-red-400 hover:bg-red-400/10 disabled:opacity-30 transition-colors"
aria-label="Delete preset"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</button>
</div>
@ -284,7 +400,9 @@
{#if expandedId === preset.id}
<div class="px-4 pb-3 border-t border-zinc-800/60">
{#if preset.entries.length === 0}
<p class="text-sm text-zinc-600 py-3 text-center">No entries yet</p>
<p class="text-sm text-zinc-600 py-3 text-center">
No entries yet
</p>
{:else}
<ul class="divide-y divide-zinc-800/50">
{#each preset.entries as entry (entry.id)}
@ -293,16 +411,30 @@
onclick={() => openEditEntry(preset.id, entry)}
class="flex-1 text-left min-w-0 group"
>
<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-sm font-medium truncate">
{entry.product.name}
</p>
<p class="text-xs text-zinc-500">
{entry.grams}g · {kcal(entry.calories)} kcal
</p>
</button>
<button
onclick={() => handleDeleteEntry(preset.id, entry.id)}
class="w-7 h-7 flex items-center justify-center rounded-full text-zinc-600 hover:text-red-400 hover:bg-red-400/10 transition-colors ml-2 shrink-0"
aria-label="Delete entry"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
<svg
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>
</li>
@ -315,8 +447,18 @@
onclick={() => openAddEntry(preset.id)}
class="mt-2 flex items-center gap-1.5 text-xs font-medium text-zinc-500 hover:text-green-400 transition-colors"
>
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4" />
<svg
class="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2.5"
d="M12 4v16m8-8H4"
/>
</svg>
Add food
</button>
@ -324,13 +466,52 @@
{/if}
</li>
{/each}
<li>
<button
onclick={() => (creating = true)}
class="w-full rounded-xl py-4 text-zinc-500 hover:text-zinc-300 transition-colors text-sm font-medium"
>
+ Add preset
</button>
</li>
</ul>
{/if}
</main>
</div>
<!-- Create preset sheet -->
<Sheet
open={creating === true}
onclose={() => {
creating = false;
creatingName = "";
}}
title="Create new preset"
>
<form onsubmit={handleCreate} class="space-y-4">
<input
type="text"
bind:value={creatingName}
required
autofocus
class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
/>
<button
type="submit"
disabled={creatingSaving || !creatingName.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{creatingSaving ? "Saving…" : "Save"}
</button>
</form>
</Sheet>
<!-- Rename preset sheet -->
<Sheet open={renamePreset_ !== null} onclose={() => renamePreset_ = null} title="Rename preset">
<Sheet
open={renamePreset_ !== null}
onclose={() => (renamePreset_ = null)}
title="Rename preset"
>
<form onsubmit={handleRename} class="space-y-4">
<input
type="text"
@ -344,23 +525,33 @@
disabled={renaming || !renameName.trim()}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{renaming ? 'Saving…' : 'Save'}
{renaming ? "Saving…" : "Save"}
</button>
</form>
</Sheet>
<!-- Edit entry grams sheet -->
<Sheet open={editingEntry !== null} onclose={() => editingEntry = null} title="Edit entry">
<Sheet
open={editingEntry !== null}
onclose={() => (editingEntry = null)}
title="Edit entry"
>
{#if editingEntry}
<form onsubmit={handleEditEntry} class="space-y-4">
<p class="text-sm text-zinc-400">{editingEntry.entry.product.name}</p>
<div>
<label class="block text-sm text-zinc-400 mb-2">Grams</label>
<div class="flex items-center gap-3">
<button type="button"
<button
type="button"
onpointerdown={(e) => e.preventDefault()}
onclick={() => { editGrams = Math.max(1, editGrams - 10); editGramsInput?.focus(); }}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"></button>
onclick={() => {
editGrams = Math.max(1, editGrams - 10);
editGramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
></button
>
<input
bind:this={editGramsInput}
type="number"
@ -370,10 +561,16 @@
onfocus={(e) => e.currentTarget.select()}
class="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-center text-xl font-semibold focus:outline-none focus:border-green-500 transition-colors"
/>
<button type="button"
<button
type="button"
onpointerdown={(e) => e.preventDefault()}
onclick={() => { editGrams = editGrams + 10; editGramsInput?.focus(); }}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center">+</button>
onclick={() => {
editGrams = editGrams + 10;
editGramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
>+</button
>
</div>
</div>
<button
@ -381,14 +578,21 @@
disabled={editSaving || editGrams < 1}
class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{editSaving ? 'Saving…' : 'Save'}
{editSaving ? "Saving…" : "Save"}
</button>
</form>
{/if}
</Sheet>
<!-- Add entry to preset sheet -->
<Sheet open={addEntryPresetId !== null} onclose={() => { addEntryPresetId = null; selectedProduct = null; }} title="Add food to preset">
<Sheet
open={addEntryPresetId !== null}
onclose={() => {
addEntryPresetId = null;
selectedProduct = null;
}}
title="Add food to preset"
>
{#if addEntryPresetId !== null}
{#if selectedProduct === null}
<!-- Product search -->
@ -404,16 +608,27 @@
{#if productsQuery.isPending && productDebouncedQ}
<p class="text-sm text-zinc-500 text-center py-4">Searching…</p>
{:else}
<ul class="max-h-64 overflow-y-auto divide-y divide-zinc-800/50 -mx-4">
<ul
class="max-h-64 overflow-y-auto divide-y divide-zinc-800/50 -mx-4"
>
{#each productsQuery.data ?? [] as product (product.id)}
<li>
<button
onclick={() => { selectedProduct = product; addGrams = 100; }}
onclick={() => {
selectedProduct = product;
addGrams = 100;
}}
class="w-full flex items-center justify-between px-4 py-3 hover:bg-zinc-800 transition-colors text-left"
>
<div class="min-w-0">
<p class="text-sm font-medium truncate capitalize">{product.name}</p>
<p class="text-xs text-zinc-500">{kcal(product.calories)} kcal · P {g(product.protein)}g · C {g(product.carb)}g · F {g(product.fat)}g <span class="text-zinc-600">/ 100g</span></p>
<p class="text-sm font-medium truncate capitalize">
{product.name}
</p>
<p class="text-xs text-zinc-500">
{kcal(product.calories)} kcal · P {g(product.protein)}g ·
C {g(product.carb)}g · F {g(product.fat)}g
<span class="text-zinc-600">/ 100g</span>
</p>
</div>
</button>
</li>
@ -425,16 +640,26 @@
<!-- Grams input -->
<form onsubmit={handleAddEntry} class="space-y-4">
<div>
<p class="text-sm font-medium capitalize mb-0.5">{selectedProduct.name}</p>
<p class="text-xs text-zinc-500">{kcal(selectedProduct.calories)} kcal / 100g</p>
<p class="text-sm font-medium capitalize mb-0.5">
{selectedProduct.name}
</p>
<p class="text-xs text-zinc-500">
{kcal(selectedProduct.calories)} kcal / 100g
</p>
</div>
<div>
<label class="block text-sm text-zinc-400 mb-2">Grams</label>
<div class="flex items-center gap-3">
<button type="button"
<button
type="button"
onpointerdown={(e) => e.preventDefault()}
onclick={() => { addGrams = Math.max(1, addGrams - 10); addGramsInput?.focus(); }}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"></button>
onclick={() => {
addGrams = Math.max(1, addGrams - 10);
addGramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
></button
>
<input
bind:this={addGramsInput}
type="number"
@ -445,15 +670,24 @@
onfocus={(e) => e.currentTarget.select()}
class="flex-1 bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2.5 text-center text-xl font-semibold focus:outline-none focus:border-green-500 transition-colors"
/>
<button type="button"
<button
type="button"
onpointerdown={(e) => e.preventDefault()}
onclick={() => { addGrams = addGrams + 10; addGramsInput?.focus(); }}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center">+</button>
onclick={() => {
addGrams = addGrams + 10;
addGramsInput?.focus();
}}
class="w-11 h-11 rounded-xl bg-zinc-800 hover:bg-zinc-700 transition-colors text-lg font-medium flex items-center justify-center"
>+</button
>
</div>
</div>
<div class="flex gap-2">
<button type="button" onclick={() => selectedProduct = null}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors">
<button
type="button"
onclick={() => (selectedProduct = null)}
class="flex-1 bg-zinc-800 hover:bg-zinc-700 rounded-xl py-3 text-sm font-medium transition-colors"
>
Back
</button>
<button
@ -461,7 +695,7 @@
disabled={addSaving || addGrams < 1}
class="flex-1 bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
>
{addSaving ? 'Adding…' : 'Add'}
{addSaving ? "Adding…" : "Add"}
</button>
</div>
</form>

View file

@ -1,7 +1,6 @@
<script lang="ts">
import { register } from "$lib/api/auth";
import { goto } from "$app/navigation";
import { today } from "$lib/utils/date";
import { onMount } from "svelte";
import { PUBLIC_TURNSTILE_SITE_KEY } from "$env/static/public";