[autofocus] fix

This commit is contained in:
Piotr Domański 2026-04-15 21:35:14 +02:00
parent befc1d9384
commit 8656e92c5d
5 changed files with 333 additions and 249 deletions

View file

@ -1,111 +1,159 @@
<script lang="ts">
export interface Command {
id: string;
label: string;
description?: string;
keywords?: string[];
action: () => void;
}
export interface Command {
id: string;
label: string;
description?: string;
keywords?: string[];
action: () => void;
}
interface Props {
commands: Command[];
open: boolean;
onclose: () => void;
}
interface Props {
commands: Command[];
open: boolean;
onclose: () => void;
}
let { commands, open, onclose }: Props = $props();
let { commands, open, onclose }: Props = $props();
let query = $state('');
let selectedIdx = $state(0);
let inputEl = $state<HTMLInputElement | null>(null);
let query = $state("");
let selectedIdx = $state(0);
let inputEl = $state<HTMLInputElement | null>(null);
const filtered = $derived(
query.trim()
? commands.filter(c =>
c.label.toLowerCase().includes(query.toLowerCase()) ||
c.keywords?.some(k => k.toLowerCase().includes(query.toLowerCase()))
)
: commands
);
const filtered = $derived(
query.trim()
? commands.filter(
(c) =>
c.label.toLowerCase().includes(query.toLowerCase()) ||
c.keywords?.some((k) =>
k.toLowerCase().includes(query.toLowerCase()),
),
)
: commands,
);
$effect(() => {
if (open) {
query = '';
selectedIdx = 0;
setTimeout(() => inputEl?.focus(), 50);
}
});
$effect(() => {
if (open) {
query = "";
selectedIdx = 0;
}
});
// Reset selection when filter changes
$effect(() => { filtered; selectedIdx = 0; });
// Reset selection when filter changes
$effect(() => {
filtered;
selectedIdx = 0;
});
function execute(cmd: Command) {
onclose();
cmd.action();
}
function execute(cmd: Command) {
onclose();
cmd.action();
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') { onclose(); return; }
if (e.key === 'ArrowDown') { e.preventDefault(); selectedIdx = Math.min(selectedIdx + 1, filtered.length - 1); }
if (e.key === 'ArrowUp') { e.preventDefault(); selectedIdx = Math.max(selectedIdx - 1, 0); }
if (e.key === 'Enter' && filtered[selectedIdx]) { e.preventDefault(); execute(filtered[selectedIdx]); }
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === "Escape") {
onclose();
return;
}
if (e.key === "ArrowDown") {
e.preventDefault();
selectedIdx = Math.min(selectedIdx + 1, filtered.length - 1);
}
if (e.key === "ArrowUp") {
e.preventDefault();
selectedIdx = Math.max(selectedIdx - 1, 0);
}
if (e.key === "Enter" && filtered[selectedIdx]) {
e.preventDefault();
execute(filtered[selectedIdx]);
}
}
</script>
{#if open}
<!-- Backdrop -->
<div
class="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"
onclick={onclose}
></div>
<!-- Backdrop -->
<div
class="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"
onclick={onclose}
></div>
<!-- Palette -->
<div class="fixed top-[20%] left-1/2 -translate-x-1/2 z-50 w-full max-w-md px-4 pointer-events-none">
<div class="bg-zinc-900 border border-zinc-700 rounded-2xl shadow-2xl overflow-hidden pointer-events-auto">
<!-- Input -->
<div class="flex items-center gap-2.5 px-4 py-3 border-b border-zinc-800">
<svg class="w-4 h-4 text-zinc-500 shrink-0" 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={inputEl}
bind:value={query}
onkeydown={handleKeydown}
placeholder="Type a command…"
class="flex-1 bg-transparent text-zinc-100 placeholder-zinc-500 focus:outline-none text-sm"
/>
<kbd class="text-xs text-zinc-600 border border-zinc-700 rounded px-1.5 py-0.5">esc</kbd>
</div>
<!-- Palette -->
<div
class="fixed top-[20%] left-1/2 -translate-x-1/2 z-50 w-full max-w-md px-4 pointer-events-none"
>
<div
class="bg-zinc-900 border border-zinc-700 rounded-2xl shadow-2xl overflow-hidden pointer-events-auto"
>
<!-- Input -->
<div class="flex items-center gap-2.5 px-4 py-3 border-b border-zinc-800">
<svg
class="w-4 h-4 text-zinc-500 shrink-0"
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={inputEl}
bind:value={query}
autofocus
onkeydown={handleKeydown}
placeholder="Type a command…"
class="flex-1 bg-transparent text-zinc-100 placeholder-zinc-500 focus:outline-none text-sm"
/>
<kbd
class="text-xs text-zinc-600 border border-zinc-700 rounded px-1.5 py-0.5"
>esc</kbd
>
</div>
<!-- Commands -->
<ul class="py-1 max-h-72 overflow-y-auto">
{#each filtered as cmd, i (cmd.id)}
<li>
<button
onclick={() => execute(cmd)}
onmouseenter={() => selectedIdx = i}
class="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors {i === selectedIdx ? 'bg-zinc-800' : 'hover:bg-zinc-800/50'}"
>
<div class="flex-1 min-w-0">
<p class="text-sm text-zinc-100">{cmd.label}</p>
{#if cmd.description}
<p class="text-xs text-zinc-500 mt-0.5 truncate">{cmd.description}</p>
{/if}
</div>
</button>
</li>
{/each}
<!-- Commands -->
<ul class="py-1 max-h-72 overflow-y-auto">
{#each filtered as cmd, i (cmd.id)}
<li>
<button
onclick={() => execute(cmd)}
onmouseenter={() => (selectedIdx = i)}
class="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors {i ===
selectedIdx
? 'bg-zinc-800'
: 'hover:bg-zinc-800/50'}"
>
<div class="flex-1 min-w-0">
<p class="text-sm text-zinc-100">{cmd.label}</p>
{#if cmd.description}
<p class="text-xs text-zinc-500 mt-0.5 truncate">
{cmd.description}
</p>
{/if}
</div>
</button>
</li>
{/each}
{#if filtered.length === 0}
<li class="px-4 py-4 text-sm text-zinc-500 text-center">No commands found</li>
{/if}
</ul>
{#if filtered.length === 0}
<li class="px-4 py-4 text-sm text-zinc-500 text-center">
No commands found
</li>
{/if}
</ul>
<!-- Footer hint -->
<div class="px-4 py-2 border-t border-zinc-800 flex gap-4 text-xs text-zinc-600">
<span><kbd class="border border-zinc-700 rounded px-1">↑↓</kbd> navigate</span>
<span><kbd class="border border-zinc-700 rounded px-1"></kbd> select</span>
</div>
</div>
</div>
<!-- Footer hint -->
<div
class="px-4 py-2 border-t border-zinc-800 flex gap-4 text-xs text-zinc-600"
>
<span
><kbd class="border border-zinc-700 rounded px-1">↑↓</kbd> navigate</span
>
<span
><kbd class="border border-zinc-700 rounded px-1"></kbd> select</span
>
</div>
</div>
</div>
{/if}

View file

@ -10,6 +10,25 @@
let { open, onclose, title, children }: Props = $props();
let bottomOffset = $state(0);
onMount(() => {
const vv = window.visualViewport;
if (!vv) return;
function update() {
bottomOffset = Math.max(0, window.innerHeight - vv!.offsetTop - vv!.height);
}
vv.addEventListener('resize', update);
vv.addEventListener('scroll', update);
return () => {
vv.removeEventListener('resize', update);
vv.removeEventListener('scroll', update);
};
});
function handleBackdrop(e: MouseEvent) {
if (e.target === e.currentTarget) onclose();
}
@ -32,8 +51,9 @@
<!-- Sheet (mobile bottom sheet / desktop centered modal) -->
<div
class="fixed z-50 bg-zinc-900 px-4 pt-4
bottom-0 left-0 right-0 rounded-t-2xl pb-[calc(1.5rem+var(--safe-bottom))] max-w-lg mx-auto animate-slide-up
left-0 right-0 rounded-t-2xl pb-[calc(1.5rem+var(--safe-bottom))] max-w-lg mx-auto animate-slide-up
lg:bottom-auto lg:left-1/2 lg:top-1/2 lg:-translate-x-1/2 lg:-translate-y-1/2 lg:rounded-2xl lg:max-w-md lg:w-full lg:pb-6 lg:animate-fade-in"
style="bottom: {bottomOffset}px"
>
<!-- Handle (mobile only) -->
<div class="w-10 h-1 bg-zinc-700 rounded-full mx-auto mb-4 lg:hidden"></div>

View file

@ -13,7 +13,9 @@
import { kcal, g } from "$lib/utils/format";
import { today } from "$lib/utils/date";
const date = $derived(page.params.date === 'today' ? today() : page.params.date!);
const date = $derived(
page.params.date === "today" ? today() : page.params.date!,
);
const mealId = $derived(Number(page.url.searchParams.get("meal_id")));
const queryClient = useQueryClient();
@ -31,16 +33,8 @@
let scanError = $state<string | null>(null);
let searchInput = $state<HTMLInputElement | null>(null);
$effect(() => {
if (searchInput) setTimeout(() => searchInput?.focus(), 50);
});
let gramsInput = $state<HTMLInputElement | null>(null);
$effect(() => {
if (selectedProduct && gramsInput) {
setTimeout(() => gramsInput?.focus(), 50);
}
});
function handleSearch(value: string) {
q = value;
@ -147,6 +141,7 @@
</svg>
<input
bind:this={searchInput}
autofocus
type="search"
placeholder="Search foods…"
value={q}
@ -300,7 +295,6 @@
onpointerdown={(e) => e.preventDefault()}
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
@ -312,6 +306,7 @@
min="1"
max="5000"
inputmode="decimal"
autofocus
onfocus={(e) => e.currentTarget.select()}
onkeydown={(e) => {
if (e.key === "Enter") handleAddEntry();
@ -322,7 +317,6 @@
onpointerdown={(e) => e.preventDefault()}
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

View file

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

View file

@ -547,7 +547,6 @@
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
@ -557,6 +556,7 @@
type="number"
bind:value={editGrams}
min="1"
autofocus
inputmode="decimal"
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"
@ -566,7 +566,6 @@
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
@ -655,7 +654,6 @@
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
@ -675,7 +673,6 @@
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