This commit is contained in:
Michael committed 2026-08-06 19:00:08 +12:00
1 parent f7037a6780
commit acb5070622
44 files changed
+5047

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Garage</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+2344
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "vlog-frontend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"private": "true",
"type": "module",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^5.1.1",
"@tailwindcss/vite": "^4.3.3",
"svelte": "^5.56.8",
"tailwindcss": "^4.3.3",
"vite": "^6.4.3"
},
"dependencies": {
"qrcode": "^1.5.4",
"svelte-spa-router": "^5.1.1"
}
}
+93
View File
@@ -0,0 +1,93 @@
<script>
import Router from 'svelte-spa-router'
import { apiGet, apiPost } from './lib/api.js'
import { user } from './lib/stores.js'
import LoginGate from './lib/components/LoginGate.svelte'
import ConfirmDialog from './lib/components/ConfirmDialog.svelte'
import Spinner from './lib/components/Spinner.svelte'
import PublicShare from './routes/PublicShare.svelte'
import Garage from './routes/Garage.svelte'
import CarDetail from './routes/CarDetail.svelte'
import AddCar from './routes/AddCar.svelte'
import EditCar from './routes/EditCar.svelte'
const routes = {
'/': Garage,
'/cars/new': AddCar,
'/cars/:id/edit': EditCar,
'/cars/:id': CarDetail,
'/share/:token': PublicShare,
}
// /#/share/:token is a public, unauthenticated page (QR code / link, no
// login) — checked before anything else so it never triggers the /api/me
// auth check or shows the app chrome.
let isPublicRoute = $state(window.location.hash.startsWith('#/share/'))
window.addEventListener('hashchange', () => {
isPublicRoute = window.location.hash.startsWith('#/share/')
})
let loading = $state(true)
let authed = $state(false)
async function checkAuth() {
try {
$user = await apiGet('/me')
authed = true
} catch {
authed = false
} finally {
loading = false
}
}
if (isPublicRoute) {
loading = false
} else {
checkAuth()
}
async function handleLogout() {
await apiPost('/auth/logout', {})
$user = null
authed = false
}
function initials(name, email) {
const source = name || email || '?'
return source
.split(/\s+/)
.map((p) => p[0])
.slice(0, 2)
.join('')
.toUpperCase()
}
</script>
{#if isPublicRoute}
<Router {routes} />
{:else if loading}
<div class="flex min-h-screen items-center justify-center text-stone-400">
<Spinner class="h-6 w-6 text-teal-600" />
</div>
{:else if !authed}
<LoginGate />
{:else}
<div class="min-h-screen bg-stone-50">
<ConfirmDialog />
<header class="bg-gradient-to-r from-teal-700 to-teal-600 shadow-sm">
<div class="mx-auto flex max-w-4xl items-center justify-between px-4 py-3">
<a href="#/" class="text-base font-semibold tracking-tight text-white"> My Garage </a>
<div class="flex items-center gap-3">
<span class="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 text-xs font-semibold text-white">
{initials($user?.name, $user?.email)}
</span>
<button onclick={handleLogout} class="text-sm text-teal-50/80 hover:text-white"> Log out </button>
</div>
</div>
</header>
<main class="mx-auto max-w-4xl px-4 py-6">
<Router {routes} />
</main>
<footer class="mx-auto max-w-4xl px-4 pb-6 text-center text-xs text-stone-400">© Michael Rausch 2026</footer>
</div>
{/if}
+1
View File
@@ -0,0 +1 @@
@import "tailwindcss";
+61
View File
@@ -0,0 +1,61 @@
// Small fetch wrapper. No CORS/credential plumbing needed — the SPA and API
// are same-origin in production (the Go binary serves both), and the
// dev-server proxy makes it same-origin in development too.
const BASE = '/api'
async function handleResponse(res) {
if (res.status === 204) return null
const contentType = res.headers.get('content-type') || ''
const body = contentType.includes('application/json') ? await res.json() : await res.text()
if (!res.ok) {
const message = (body && body.error) || res.statusText
throw new Error(message)
}
return body
}
export function apiGet(path) {
return fetch(BASE + path).then(handleResponse)
}
export function apiPost(path, data) {
return fetch(BASE + path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).then(handleResponse)
}
export function apiPut(path, data) {
return fetch(BASE + path, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).then(handleResponse)
}
export function apiPatch(path, data) {
return fetch(BASE + path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).then(handleResponse)
}
export function apiDelete(path) {
return fetch(BASE + path, { method: 'DELETE' }).then(handleResponse)
}
// Uploads a single file as multipart/form-data under the "file" field —
// matches what the Go handlers expect for photo/attachment uploads.
export function apiUpload(path, file) {
const form = new FormData()
form.append('file', file)
return fetch(BASE + path, { method: 'POST', body: form }).then(handleResponse)
}
// Builds the URL for an <img>/<a> that streams a file straight from the API
// (photo/attachment endpoints are proxied through Go, not presigned S3 URLs).
export function fileUrl(path) {
return BASE + path
}
@@ -0,0 +1,61 @@
<script>
import { fileUrl } from '../api.js'
import { formatDate, daysUntil } from '../utils.js'
import { card, photoPlaceholder, photoPlaceholderTextureStyle } from '../ui.js'
import RegoPlate from './RegoPlate.svelte'
let { car } = $props()
let worstStatus = $derived.by(() => {
const days = [daysUntil(car.regoExpiry), daysUntil(car.wofExpiry)].filter((d) => d !== null)
if (days.some((d) => d < 0)) return 'overdue'
if (days.some((d) => d <= 30)) return 'upcoming'
return null
})
</script>
<a
href="#/cars/{car.id}"
class="{card} group block overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-lg"
>
<div class="relative aspect-video overflow-hidden {car.hasPhoto ? 'bg-stone-100' : photoPlaceholder}">
{#if car.hasPhoto}
<img
src={fileUrl(`/cars/${car.id}/photo`)}
alt={car.rego}
class="h-full w-full object-cover transition-transform group-hover:scale-105"
/>
{:else}
<div class="absolute inset-0" style={photoPlaceholderTextureStyle}></div>
<div class="relative z-10 flex h-full w-full items-center justify-center text-5xl opacity-90">🚗</div>
{/if}
{#if car.name}
<div
class="pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/55 to-transparent px-3 pb-2 pt-6"
>
<p class="truncate text-sm font-semibold text-white drop-shadow-sm">{car.name}</p>
</div>
{/if}
{#if worstStatus}
<span
class="absolute right-2 top-2 rounded px-2 py-0.5 text-xs font-semibold uppercase tracking-wide shadow-sm
{worstStatus === 'overdue' ? 'bg-red-600 text-white' : 'bg-amber-500 text-white'}"
>
{worstStatus === 'overdue' ? 'Overdue' : 'Due soon'}
</span>
{/if}
</div>
<div class="p-4">
<div class="flex items-center justify-between gap-2">
<RegoPlate rego={car.rego} size="sm" />
{#if car.year || car.make}
<span class="text-sm text-stone-500">{car.year ?? ''} {car.make ?? ''}</span>
{/if}
</div>
{#if car.model}<p class="mt-2 text-sm text-stone-500">{car.model}</p>{/if}
<div class="mt-3 flex gap-3 text-xs text-stone-400">
<span>Rego: {formatDate(car.regoExpiry)}</span>
<span>WoF: {formatDate(car.wofExpiry)}</span>
</div>
</div>
</a>
+132
View File
@@ -0,0 +1,132 @@
<script>
import { apiPost, apiPut } from '../api.js'
import { btnPrimary, input, label as labelClass } from '../ui.js'
// car is optional — present in edit mode, absent (null) in create mode.
let { car = null, onSave } = $props()
// Intentional one-time snapshot of `car` into editable local state (not
// $derived) — this form is only ever mounted once car has fully loaded,
// so there's nothing to stay in sync with after that.
let rego = $state(car?.rego ?? '')
let name = $state(car?.name ?? '')
let make = $state(car?.make ?? '')
let model = $state(car?.model ?? '')
let year = $state(car?.year ?? '')
let color = $state(car?.color ?? '')
let odometer = $state(car?.odometer ?? '')
let regoExpiry = $state(car?.regoExpiry ? car.regoExpiry.slice(0, 10) : '')
let wofExpiry = $state(car?.wofExpiry ? car.wofExpiry.slice(0, 10) : '')
let serviceIntervalKm = $state(car?.serviceIntervalKm ?? '')
let serviceIntervalMonths = $state(car?.serviceIntervalMonths ?? '')
let saving = $state(false)
let error = $state('')
async function handleSubmit(e) {
e.preventDefault()
if (!rego.trim()) {
error = 'Rego is required'
return
}
saving = true
error = ''
const payload = {
rego: rego.trim(),
name: name.trim() || null,
make: make || null,
model: model || null,
year: year ? Number(year) : null,
color: color || null,
odometer: odometer ? Number(odometer) : null,
regoExpiry: regoExpiry || null,
wofExpiry: wofExpiry || null,
serviceIntervalKm: serviceIntervalKm ? Number(serviceIntervalKm) : null,
serviceIntervalMonths: serviceIntervalMonths ? Number(serviceIntervalMonths) : null,
}
try {
const saved = car ? await apiPut(`/cars/${car.id}`, payload) : await apiPost('/cars', payload)
onSave?.(saved)
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<form onsubmit={handleSubmit} class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<label for="car-rego" class={labelClass}>Rego *</label>
<input id="car-rego" bind:value={rego} required class={input} />
</div>
<div>
<label for="car-name" class={labelClass}>Name</label>
<input id="car-name" bind:value={name} placeholder="e.g. The Beast" class={input} />
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label for="car-make" class={labelClass}>Make</label>
<input id="car-make" bind:value={make} class={input} />
</div>
<div>
<label for="car-model" class={labelClass}>Model</label>
<input id="car-model" bind:value={model} class={input} />
</div>
</div>
<div class="grid grid-cols-3 gap-4">
<div>
<label for="car-year" class={labelClass}>Year</label>
<input id="car-year" type="number" bind:value={year} class={input} />
</div>
<div>
<label for="car-color" class={labelClass}>Color</label>
<input id="car-color" bind:value={color} class={input} />
</div>
<div>
<label for="car-odometer" class={labelClass}>Odometer</label>
<input id="car-odometer" type="number" bind:value={odometer} class={input} />
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label for="car-rego-expiry" class={labelClass}>Rego expiry</label>
<input id="car-rego-expiry" type="date" bind:value={regoExpiry} class={input} />
</div>
<div>
<label for="car-wof-expiry" class={labelClass}>WoF expiry</label>
<input id="car-wof-expiry" type="date" bind:value={wofExpiry} class={input} />
</div>
</div>
<div>
<span class={labelClass}>Service interval (optional)</span>
<p class="mb-1.5 -mt-1 text-xs text-stone-400">
Whichever comes first triggers a reminder, counted from the last entry marked "full service".
</p>
<div class="grid grid-cols-2 gap-4">
<div>
<label for="car-service-km" class="sr-only">Every (km)</label>
<input id="car-service-km" type="number" bind:value={serviceIntervalKm} placeholder="Every (km)" class={input} />
</div>
<div>
<label for="car-service-months" class="sr-only">Every (months)</label>
<input
id="car-service-months"
type="number"
bind:value={serviceIntervalMonths}
placeholder="Every (months)"
class={input}
/>
</div>
</div>
</div>
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
<button type="submit" disabled={saving} class={btnPrimary}>
{saving ? 'Saving…' : car ? 'Save changes' : 'Create car'}
</button>
</form>
@@ -0,0 +1,26 @@
<script>
import { confirmState } from '../confirm.js'
import Modal from './Modal.svelte'
import { btnSecondary, btnDanger, btnPrimary } from '../ui.js'
// Mounted once at the app shell — renders whatever confirmAction() puts in
// the shared store, so any component can `await confirmAction(...)` and get
// an on-brand dialog instead of the browser's native confirm() popup.
function respond(value) {
const current = $confirmState
confirmState.set(null)
current?.resolve(value)
}
</script>
{#if $confirmState}
<Modal title={$confirmState.title} onClose={() => respond(false)}>
<p class="text-sm text-stone-600">{$confirmState.message}</p>
<div class="mt-5 flex justify-end gap-2">
<button onclick={() => respond(false)} class={btnSecondary}>Cancel</button>
<button onclick={() => respond(true)} class={$confirmState.danger ? btnDanger : btnPrimary}>
{$confirmState.confirmLabel}
</button>
</div>
</Modal>
{/if}
@@ -0,0 +1,94 @@
<script>
import { apiPost, apiPut } from '../api.js'
import { btnPrimary, btnSecondary, input, label as labelClass } from '../ui.js'
// entry is optional — present in edit mode, absent (null) in create mode.
let { carId, entry = null, onSaved, onCancel } = $props()
// Intentional one-time snapshot of `entry` (not $derived) — a fresh form
// instance mounts each time an edit modal opens, and the modal backdrop
// blocks switching to a different entry while one is open.
let entryDate = $state(entry?.entryDate?.slice(0, 10) ?? new Date().toISOString().slice(0, 10))
let litres = $state(entry?.litres ?? '')
let cost = $state(entry?.cost ?? '')
let odometer = $state(entry?.odometer ?? '')
let location = $state(entry?.location ?? '')
let notes = $state(entry?.notes ?? '')
let saving = $state(false)
let error = $state('')
async function handleSubmit(e) {
e.preventDefault()
if (!litres || Number(litres) <= 0) {
error = 'Litres is required'
return
}
if (!cost || Number(cost) <= 0) {
error = 'Cost is required'
return
}
saving = true
error = ''
const payload = {
entryDate,
litres: Number(litres),
cost: Number(cost),
odometer: odometer ? Number(odometer) : null,
location: location || null,
notes: notes || null,
}
try {
if (entry) {
await apiPut(`/fuel-entries/${entry.id}`, payload)
} else {
await apiPost(`/cars/${carId}/fuel-entries`, payload)
}
onSaved?.()
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<form onsubmit={handleSubmit} class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<label for="fuel-date" class={labelClass}>Date</label>
<input id="fuel-date" type="date" bind:value={entryDate} required class={input} />
</div>
<div>
<label for="fuel-location" class={labelClass}>Where</label>
<input id="fuel-location" bind:value={location} placeholder="BP" class={input} />
</div>
</div>
<div class="grid grid-cols-3 gap-4">
<div>
<label for="fuel-litres" class={labelClass}>Litres *</label>
<input id="fuel-litres" type="number" step="0.01" bind:value={litres} required class={input} />
</div>
<div>
<label for="fuel-cost" class={labelClass}>Total cost *</label>
<input id="fuel-cost" type="number" step="0.01" bind:value={cost} required class={input} />
</div>
<div>
<label for="fuel-odometer" class={labelClass}>Odometer</label>
<input id="fuel-odometer" type="number" bind:value={odometer} class={input} />
</div>
</div>
<div>
<label for="fuel-notes" class={labelClass}>Notes</label>
<textarea id="fuel-notes" bind:value={notes} rows="2" class={input}></textarea>
</div>
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
<div class="flex justify-end gap-2 pt-2">
<button type="button" onclick={() => onCancel?.()} class={btnSecondary}>Cancel</button>
<button type="submit" disabled={saving} class={btnPrimary}>
{saving ? 'Saving…' : entry ? 'Save changes' : 'Add fuel-up'}
</button>
</div>
</form>
@@ -0,0 +1,201 @@
<script>
import { apiGet, apiDelete } from '../api.js'
import { confirmAction } from '../confirm.js'
import { formatDate } from '../utils.js'
import { btnGhost, btnIcon, statTile, statLabel, statValue } from '../ui.js'
import Icon from './Icon.svelte'
import Modal from './Modal.svelte'
import LoadingState from './LoadingState.svelte'
import FuelEntryForm from './FuelEntryForm.svelte'
let { carId } = $props()
const PAGE_SIZE = 20
let items = $state([])
let hasMore = $state(false)
let loading = $state(true)
let loadingMore = $state(false)
let error = $state('')
let showAddModal = $state(false)
let editingItem = $state(null)
// Loads the first page fresh — used on mount and after any add/edit/
// delete, so we don't have to reconcile where a changed entry now falls
// across already-loaded pages.
async function loadFirstPage() {
loading = true
error = ''
try {
const result = await apiGet(`/cars/${carId}/fuel-entries?limit=${PAGE_SIZE}&offset=0`)
items = result.items
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loading = false
}
}
async function loadMore() {
loadingMore = true
try {
const result = await apiGet(`/cars/${carId}/fuel-entries?limit=${PAGE_SIZE}&offset=${items.length}`)
items = [...items, ...result.items]
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loadingMore = false
}
}
$effect(() => {
carId
loadFirstPage()
})
async function remove(item) {
if (!(await confirmAction(`Delete this fuel entry from ${formatDate(item.entryDate)}?`))) return
await apiDelete(`/fuel-entries/${item.id}`)
loadFirstPage()
}
function handleSaved() {
showAddModal = false
editingItem = null
loadFirstPage()
}
// Numeric summary computed from whatever's loaded so far — entries are
// newest-first, so "this month"/"this fortnight" are always a prefix of
// the list; a personal car realistically never has 20+ fill-ups within
// either window, so the first page alone is enough.
let summary = $derived.by(() => {
const now = new Date()
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
const twoWeeksAgo = new Date(now)
twoWeeksAgo.setDate(now.getDate() - 14)
let monthCost = 0
let fortnightCost = 0
let totalCost = 0
let totalLitres = 0
for (const e of items) {
const d = new Date(e.entryDate)
totalCost += e.cost
totalLitres += e.litres
if (d >= startOfMonth) monthCost += e.cost
if (d >= twoWeeksAgo) fortnightCost += e.cost
}
const avgPricePerLitre = totalLitres > 0 ? totalCost / totalLitres : null
// Efficiency: span the loaded entries that have an odometer reading and
// sum the litres used across that span.
const withOdo = items
.filter((e) => e.odometer != null)
.slice()
.sort((a, b) => a.odometer - b.odometer)
let avgL100km = null
if (withOdo.length >= 2) {
const first = withOdo[0]
const last = withOdo[withOdo.length - 1]
const kmDriven = last.odometer - first.odometer
const litresUsed = items
.filter((e) => e.odometer > first.odometer && e.odometer <= last.odometer)
.reduce((sum, e) => sum + e.litres, 0)
if (kmDriven > 0 && litresUsed > 0) {
avgL100km = (litresUsed / kmDriven) * 100
}
}
return { monthCost, fortnightCost, avgPricePerLitre, avgL100km }
})
</script>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else}
{#if items.length > 0}
<div class="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
<div class={statTile}>
<p class={statLabel}>This month</p>
<p class={statValue}>${summary.monthCost.toFixed(2)}</p>
</div>
<div class={statTile}>
<p class={statLabel}>Last 14 days</p>
<p class={statValue}>${summary.fortnightCost.toFixed(2)}</p>
</div>
<div class={statTile}>
<p class={statLabel}>Avg price/L</p>
<p class={statValue}>
{summary.avgPricePerLitre != null ? `$${summary.avgPricePerLitre.toFixed(2)}` : '—'}
</p>
</div>
<div class={statTile}>
<p class={statLabel}>Avg L/100km</p>
<p class={statValue}>
{summary.avgL100km != null ? summary.avgL100km.toFixed(1) : '—'}
</p>
</div>
</div>
{/if}
{#if items.length === 0}
<p class="text-sm text-stone-400">No fuel-ups logged yet.</p>
{:else}
<ul class="divide-y divide-stone-100">
{#each items as item (item.id)}
<li class="flex items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
<div class="min-w-0">
<p class="font-medium text-stone-900">
{item.litres.toFixed(1)} L · ${item.cost.toFixed(2)}
<span class="font-normal text-stone-400">(${(item.cost / item.litres).toFixed(2)}/L)</span>
</p>
<p class="text-sm text-stone-500">
{formatDate(item.entryDate)}
{#if item.location}· {item.location}{/if}
{#if item.odometer}· {item.odometer.toLocaleString()} km{/if}
</p>
</div>
<div class="flex shrink-0 gap-1">
<button onclick={() => (editingItem = item)} aria-label="Edit fuel entry" class={btnIcon}>
<Icon name="pencil" class="h-4 w-4" />
</button>
<button onclick={() => remove(item)} aria-label="Delete fuel entry" class="{btnIcon} hover:text-red-600">
<Icon name="trash" class="h-4 w-4" />
</button>
</div>
</li>
{/each}
</ul>
{#if hasMore}
<button onclick={loadMore} disabled={loadingMore} class="{btnGhost} mt-3 disabled:opacity-50">
<Icon name="chevronDown" class="h-4 w-4" />
{loadingMore ? 'Loading…' : 'Load more'}
</button>
{/if}
{/if}
{/if}
<button onclick={() => (showAddModal = true)} class="{btnGhost} mt-3">
<Icon name="plus" class="h-4 w-4" />
Add fuel-up
</button>
{#if showAddModal}
<Modal title="Add fuel-up" onClose={() => (showAddModal = false)}>
<FuelEntryForm {carId} onSaved={handleSaved} onCancel={() => (showAddModal = false)} />
</Modal>
{/if}
{#if editingItem}
<Modal title="Edit fuel-up" onClose={() => (editingItem = null)}>
<FuelEntryForm {carId} entry={editingItem} onSaved={handleSaved} onCancel={() => (editingItem = null)} />
</Modal>
{/if}
+53
View File
@@ -0,0 +1,53 @@
<script>
// Small hand-authored inline icon set — no icon library dependency, no
// network fetch, just enough glyphs for this app's actions.
let { name, class: className = 'w-4 h-4' } = $props()
const paths = {
plus: 'M12 5v14M5 12h14',
pencil: 'M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z',
trash: 'M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-8 0v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V7',
x: 'M6 6l12 12M18 6L6 18',
check: 'M5 13l4 4L19 7',
chevronDown: 'M6 9l6 6 6-6',
chevronRight: 'M9 6l6 6-6 6',
paperclip: 'M8 12.5l6.5-6.5a3 3 0 1 1 4.24 4.24l-8.5 8.5a5 5 0 1 1-7.07-7.07L11 3.84',
bookOpen: 'M12 6c-1.5-1.2-4-2-7-2v13c3 0 5.5.8 7 2m0-13c1.5-1.2 4-2 7-2v13c-3 0-5.5.8-7 2m0-13v13',
undo: 'M9 14l-4-4 4-4M5 10h9a5 5 0 0 1 0 10h-1',
share: 'M12 15V3m0 0 4 4m-4-4-4 4M5 13v6a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-6',
fuel: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-9 4-4',
wrench:
'M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.4-3.4a6 6 0 0 1-7.9 7.9l-6.5 6.5a2.1 2.1 0 0 1-3-3l6.5-6.5a6 6 0 0 1 7.9-7.9z',
calendar: 'M8 2v4M16 2v4M3.5 9h17M5 4.5h14a1.5 1.5 0 0 1 1.5 1.5v13a1.5 1.5 0 0 1-1.5 1.5H5A1.5 1.5 0 0 1 3.5 19V6A1.5 1.5 0 0 1 5 4.5Z',
bell: 'M9 17a3 3 0 0 0 6 0M5 17h14l-1.4-2.1a5 5 0 0 1-.85-2.8V9a4.75 4.75 0 0 0-9.5 0v3.1a5 5 0 0 1-.85 2.8L5 17Z',
}
const camera = 'M4 8a2 2 0 0 1 2-2h1.5l1-1.5h5l1 1.5H17a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8z'
</script>
{#if name === 'camera'}
<svg
viewBox="0 0 24 24"
fill="none"
class={className}
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d={camera} />
<circle cx="12" cy="13" r="3.2" />
</svg>
{:else}
<svg
viewBox="0 0 24 24"
fill="none"
class={className}
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d={paths[name] ?? ''} />
</svg>
{/if}
@@ -0,0 +1,64 @@
<script>
import { apiPost, apiPut } from '../api.js'
import { btnPrimary, btnSecondary, input, label as labelClass } from '../ui.js'
// entry is optional — present in edit mode, absent (null) in create mode.
let { carId, entry = null, onSaved, onCancel } = $props()
// Intentional one-time snapshot of `entry` (not $derived) — a fresh form
// instance mounts each time an edit modal opens, and the modal backdrop
// blocks switching to a different entry while one is open.
let title = $state(entry?.title ?? '')
let body = $state(entry?.body ?? '')
let saving = $state(false)
let error = $state('')
async function handleSubmit(e) {
e.preventDefault()
if (!title.trim()) {
error = 'Title is required'
return
}
saving = true
error = ''
const payload = { title: title.trim(), body }
try {
if (entry) {
await apiPut(`/knowledge/${entry.id}`, payload)
} else {
await apiPost(`/cars/${carId}/knowledge`, payload)
}
onSaved?.()
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<form onsubmit={handleSubmit} class="space-y-4">
<div>
<label for="kb-title" class={labelClass}>Title *</label>
<input id="kb-title" bind:value={title} placeholder="Coolant type" required class={input} />
</div>
<div>
<label for="kb-body" class={labelClass}>Details</label>
<textarea
id="kb-body"
bind:value={body}
rows="8"
placeholder="e.g. Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple with the heater on full."
class={input}></textarea>
</div>
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
<div class="flex justify-end gap-2 pt-2">
<button type="button" onclick={() => onCancel?.()} class={btnSecondary}>Cancel</button>
<button type="submit" disabled={saving} class={btnPrimary}>
{saving ? 'Saving…' : entry ? 'Save changes' : 'Add entry'}
</button>
</div>
</form>
@@ -0,0 +1,143 @@
<script>
import { apiGet, apiDelete } from '../api.js'
import { confirmAction } from '../confirm.js'
import { formatDate } from '../utils.js'
import { btnGhost, btnIcon } from '../ui.js'
import Icon from './Icon.svelte'
import Modal from './Modal.svelte'
import LoadingState from './LoadingState.svelte'
import KnowledgeForm from './KnowledgeForm.svelte'
let { carId } = $props()
const PAGE_SIZE = 20
let items = $state([])
let hasMore = $state(false)
let loading = $state(true)
let loadingMore = $state(false)
let error = $state('')
let viewingItem = $state(null)
let showAddModal = $state(false)
let editingItem = $state(null)
// Loads the first page fresh — used on mount and after any add/edit/
// delete, so we don't have to reconcile where a changed entry now falls
// across already-loaded pages.
async function loadFirstPage() {
loading = true
error = ''
try {
const result = await apiGet(`/cars/${carId}/knowledge?limit=${PAGE_SIZE}&offset=0`)
items = result.items
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loading = false
}
}
async function loadMore() {
loadingMore = true
try {
const result = await apiGet(`/cars/${carId}/knowledge?limit=${PAGE_SIZE}&offset=${items.length}`)
items = [...items, ...result.items]
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loadingMore = false
}
}
$effect(() => {
carId
loadFirstPage()
})
async function remove(item) {
if (!(await confirmAction(`Delete "${item.title}"?`))) return
await apiDelete(`/knowledge/${item.id}`)
viewingItem = null
loadFirstPage()
}
function handleSaved() {
showAddModal = false
editingItem = null
loadFirstPage()
}
function edit(item) {
viewingItem = null
editingItem = item
}
</script>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if items.length === 0}
<p class="text-sm text-stone-400">
No knowledgebase entries yet — document procedures, common problems, or reference info like coolant type.
</p>
{:else}
<div class="divide-y divide-stone-100">
{#each items as item (item.id)}
<button
type="button"
onclick={() => (viewingItem = item)}
class="flex w-full items-center justify-between gap-2 py-3 text-left hover:text-teal-700"
>
<span class="min-w-0">
<span class="block truncate font-medium text-stone-900">{item.title}</span>
<span class="text-xs text-stone-400">Updated {formatDate(item.updatedAt)}</span>
</span>
<Icon name="chevronRight" class="h-4 w-4 shrink-0 text-stone-400" />
</button>
{/each}
</div>
{#if hasMore}
<button onclick={loadMore} disabled={loadingMore} class="{btnGhost} mt-3 disabled:opacity-50">
<Icon name="chevronDown" class="h-4 w-4" />
{loadingMore ? 'Loading…' : 'Load more'}
</button>
{/if}
{/if}
<button onclick={() => (showAddModal = true)} class="{btnGhost} mt-3">
<Icon name="plus" class="h-4 w-4" />
Add knowledge
</button>
{#if viewingItem}
<Modal title={viewingItem.title} onClose={() => (viewingItem = null)} wide>
<p class="whitespace-pre-wrap text-sm text-stone-700">{viewingItem.body}</p>
<div class="mt-4 flex items-center justify-between border-t border-stone-100 pt-3">
<span class="text-xs text-stone-400">Updated {formatDate(viewingItem.updatedAt)}</span>
<div class="flex gap-1">
<button onclick={() => edit(viewingItem)} aria-label="Edit entry" class={btnIcon}>
<Icon name="pencil" class="h-4 w-4" />
</button>
<button onclick={() => remove(viewingItem)} aria-label="Delete entry" class="{btnIcon} hover:text-red-600">
<Icon name="trash" class="h-4 w-4" />
</button>
</div>
</div>
</Modal>
{/if}
{#if showAddModal}
<Modal title="Add knowledge entry" onClose={() => (showAddModal = false)}>
<KnowledgeForm {carId} onSaved={handleSaved} onCancel={() => (showAddModal = false)} />
</Modal>
{/if}
{#if editingItem}
<Modal title="Edit knowledge entry" onClose={() => (editingItem = null)}>
<KnowledgeForm {carId} entry={editingItem} onSaved={handleSaved} onCancel={() => (editingItem = null)} />
</Modal>
{/if}
@@ -0,0 +1,12 @@
<script>
import Spinner from './Spinner.svelte'
// Drop-in replacement for a plain "Loading…" text node — same footprint,
// just with a spinner so it reads as active rather than stalled.
let { label = 'Loading…', center = false } = $props()
</script>
<div class="flex items-center gap-2 py-2 text-sm text-stone-400 {center ? 'justify-center' : ''}">
<Spinner class="h-4 w-4 text-teal-600" />
{label}
</div>
@@ -0,0 +1,24 @@
<!-- Shown when GET /api/me returns 401. A real navigation (not a fetch) since
login is a redirect chain out to the OIDC provider and back. -->
<div
class="flex min-h-screen items-center justify-center bg-stone-100"
style="background-image: repeating-linear-gradient(135deg, transparent, transparent 22px, rgba(0,0,0,0.025) 22px, rgba(0,0,0,0.025) 24px);"
>
<div class="mx-4 w-full max-w-sm rounded-lg border border-stone-200 bg-white p-8 text-center shadow-sm">
<div
class="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-lg bg-teal-700 text-2xl shadow-sm shadow-teal-900/30"
>
🔧
</div>
<h1 class="text-xl font-semibold tracking-tight text-stone-900">My Garage</h1>
<p class="mt-1.5 text-sm text-stone-500">
Service history, rego &amp; WoF reminders, and a knowledgebase for every car you own.
</p>
<a
href="/api/auth/login"
class="mt-6 inline-flex w-full items-center justify-center gap-1.5 rounded-lg bg-teal-700 px-5 py-2.5 text-sm font-medium text-white shadow-sm shadow-teal-900/20 transition-colors hover:bg-teal-600"
>
Log in
</a>
</div>
</div>
@@ -0,0 +1,108 @@
<script>
import { apiGet, apiPatch } from '../api.js'
import { formatDate } from '../utils.js'
import { input, btnPrimary, statTile, statLabel, statValue } from '../ui.js'
import Icon from './Icon.svelte'
import LoadingState from './LoadingState.svelte'
// Rendered inside a Modal (triggered from the odometer pill on the car
// header) — deliberately just the numbers, no chart. A graph of odometer
// readings over time turned out to be more visual weight than the data
// was worth for what's a supporting stat, not the page's main content.
let { carId, odometer, onUpdated } = $props()
let data = $state(null)
let loading = $state(true)
let error = $state('')
let editingOdometer = $state(false)
let odometerInput = $state('')
let saving = $state(false)
async function load() {
loading = true
error = ''
try {
data = await apiGet(`/cars/${carId}/mileage`)
} catch (err) {
error = err.message
} finally {
loading = false
}
}
$effect(() => {
carId
load()
})
function startEdit() {
odometerInput = odometer ?? ''
editingOdometer = true
}
async function saveOdometer(e) {
e.preventDefault()
if (odometerInput === '' || Number(odometerInput) < 0) return
saving = true
try {
await apiPatch(`/cars/${carId}/odometer`, { odometer: Number(odometerInput) })
editingOdometer = false
await load()
onUpdated?.()
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<div class="space-y-4">
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if data}
<div class={statTile}>
<p class={statLabel}>Odometer</p>
{#if editingOdometer}
<form onsubmit={saveOdometer} class="mt-1 flex items-center gap-2">
<input type="number" bind:value={odometerInput} class="{input} w-32 py-1" autofocus />
<button type="submit" disabled={saving} class="{btnPrimary} px-3 py-1 text-sm">
{saving ? 'Saving…' : 'Save'}
</button>
<button type="button" onclick={() => (editingOdometer = false)} class="text-sm text-stone-500">Cancel</button>
</form>
{:else}
<button onclick={startEdit} class="{statValue} flex items-center gap-1.5 hover:text-teal-700">
{data.currentOdometer != null ? `${data.currentOdometer.toLocaleString()} km` : 'Not set'}
<Icon name="pencil" class="h-3.5 w-3.5 text-stone-400" />
</button>
{/if}
</div>
{#if data.kmPerYear}
<div class={statTile}>
<p class={statLabel}>Estimated usage</p>
<p class={statValue}>~{Math.round(data.kmPerYear).toLocaleString()} km/year</p>
</div>
{/if}
{#if data.yearsPer100k}
<div class={statTile}>
<p class={statLabel}>Next 100,000 km</p>
<p class={statValue}>
~{data.yearsPer100k.toFixed(1)} years
{#if data.next100kEta}<span class="text-sm font-normal text-stone-400">· by ~{formatDate(data.next100kEta)}</span
>{/if}
</p>
<p class="mt-0.5 text-xs text-stone-500">At your current rate, from today — not tied to a round odometer number.</p>
</div>
{:else}
<p class="text-xs text-stone-400">
Log a service or fuel-up with an odometer reading (from a different date) to start estimating your usage rate.
</p>
{/if}
{/if}
</div>
+46
View File
@@ -0,0 +1,46 @@
<script>
import { fade, scale } from 'svelte/transition'
import Icon from './Icon.svelte'
// wide — use a broader max-width for content that needs more breathing
// room, e.g. a knowledgebase article that may run to a lot of text.
let { title, onClose, children, wide = false } = $props()
function handleKeydown(e) {
if (e.key === 'Escape') onClose?.()
}
</script>
<svelte:window onkeydown={handleKeydown} />
<div class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto p-4 sm:items-center sm:p-6">
<button
type="button"
aria-label="Close"
class="fixed inset-0 bg-stone-900/60 backdrop-blur-sm"
onclick={() => onClose?.()}
transition:fade={{ duration: 150 }}
></button>
<div
class="relative my-8 w-full {wide
? 'max-w-2xl'
: 'max-w-lg'} rounded-lg border border-stone-200 bg-white shadow-xl sm:my-0"
transition:scale={{ duration: 150, start: 0.97, opacity: 0 }}
>
<div class="flex items-center justify-between border-b border-stone-100 px-5 py-4">
<h3 class="text-base font-semibold text-stone-900">{title}</h3>
<button
type="button"
onclick={() => onClose?.()}
aria-label="Close"
class="rounded-md p-1 text-stone-400 hover:bg-stone-100 hover:text-stone-600"
>
<Icon name="x" class="h-5 w-5" />
</button>
</div>
<div class="max-h-[75vh] overflow-y-auto p-5">
{@render children?.()}
</div>
</div>
</div>
@@ -0,0 +1,79 @@
<script>
import { apiUpload, fileUrl } from '../api.js'
import { photoPlaceholder, photoPlaceholderTextureStyle } from '../ui.js'
import Icon from './Icon.svelte'
let { carId, hasPhoto = false, alt = 'Car photo', name = null, onUploaded } = $props()
let uploading = $state(false)
let error = $state('')
// Cache-bust the <img> after a replace so the browser doesn't keep
// showing the old photo from the same URL.
let cacheBust = $state(0)
async function handleChange(e) {
const file = e.target.files[0]
if (!file) return
uploading = true
error = ''
try {
await apiUpload(`/cars/${carId}/photo`, file)
cacheBust += 1
onUploaded?.()
} catch (err) {
error = err.message
} finally {
uploading = false
e.target.value = ''
}
}
</script>
<div class="space-y-1.5">
{#if hasPhoto}
<label
class="group relative block aspect-[21/9] w-full cursor-pointer overflow-hidden rounded-lg border border-stone-200"
>
<img src={fileUrl(`/cars/${carId}/photo?v=${cacheBust}`)} {alt} class="h-full w-full object-cover" />
{#if name}
<div
class="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent px-4 pb-3 pt-8"
>
<p class="text-lg font-semibold text-white drop-shadow-sm">{name}</p>
</div>
{/if}
<div
class="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all group-hover:bg-black/40 group-hover:opacity-100"
>
<span
class="inline-flex items-center gap-1.5 rounded-lg bg-white/90 px-3 py-1.5 text-sm font-medium text-stone-900 shadow"
>
<Icon name="camera" class="h-4 w-4" />
{uploading ? 'Uploading…' : 'Replace photo'}
</span>
</div>
<input type="file" accept="image/png,image/jpeg" class="hidden" onchange={handleChange} disabled={uploading} />
</label>
{:else}
<label
class="group relative flex aspect-[21/9] w-full cursor-pointer flex-col items-center justify-center gap-3 overflow-hidden rounded-lg {photoPlaceholder} text-teal-50 transition-transform hover:scale-[1.005]"
>
<div class="absolute inset-0" style={photoPlaceholderTextureStyle}></div>
<div
class="relative z-10 flex h-14 w-14 items-center justify-center rounded-full bg-white/15 transition-colors group-hover:bg-white/25"
>
<Icon name="camera" class="h-7 w-7" />
</div>
<span class="relative z-10 text-sm font-medium">{uploading ? 'Uploading…' : 'Add a photo'}</span>
{#if name}
<div
class="pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/40 to-transparent px-4 pb-3 pt-8"
>
<p class="text-lg font-semibold text-white drop-shadow-sm">{name}</p>
</div>
{/if}
<input type="file" accept="image/png,image/jpeg" class="hidden" onchange={handleChange} disabled={uploading} />
</label>
{/if}
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
</div>
@@ -0,0 +1,18 @@
<script>
// A literal number-plate chip — the app's one recurring signature motif.
let { rego, size = 'md' } = $props()
const sizes = {
sm: 'px-2 py-0.5 text-xs tracking-wider',
md: 'px-3 py-1 text-base tracking-widest',
lg: 'px-4 py-2 text-2xl tracking-widest',
}
</script>
<span
class="inline-block rounded border-2 border-stone-900 bg-gradient-to-b from-white to-stone-100 font-mono font-bold text-stone-900 shadow-sm {sizes[
size
]}"
>
{rego}
</span>
@@ -0,0 +1,99 @@
<script>
import { apiPost, apiPut } from '../api.js'
import { btnPrimary, btnSecondary, input, label as labelClass } from '../ui.js'
// reminder is optional — present in edit mode, absent (null) in create mode.
let { carId, reminder = null, onSaved, onCancel } = $props()
const BUILTIN_TYPES = [
{ value: 'service', label: 'Service' },
{ value: 'wheel_rotation', label: 'Wheel rotation' },
{ value: 'alignment', label: 'Alignment' },
{ value: 'custom', label: 'Custom…' },
]
// Intentional one-time snapshot of `reminder` (not $derived) — a fresh
// form instance mounts each time an edit modal opens, and the modal
// backdrop blocks switching to a different reminder while one is open.
let reminderType = $state(reminder?.reminderType ?? 'service')
let label = $state(reminder?.label ?? '')
let dueDate = $state(reminder?.dueDate?.slice(0, 10) ?? '')
let dueOdometer = $state(reminder?.dueOdometer ?? '')
let notes = $state(reminder?.notes ?? '')
let saving = $state(false)
let error = $state('')
async function handleSubmit(e) {
e.preventDefault()
if (reminderType === 'custom' && !label.trim()) {
error = 'Label is required for a custom reminder'
return
}
if (!dueDate && !dueOdometer) {
error = 'Set a due date or a due odometer reading'
return
}
saving = true
error = ''
const payload = {
reminderType,
label: reminderType === 'custom' ? label.trim() : null,
dueDate: dueDate || null,
dueOdometer: dueOdometer ? Number(dueOdometer) : null,
notes: notes || null,
}
try {
if (reminder) {
await apiPut(`/reminders/${reminder.id}`, payload)
} else {
await apiPost(`/cars/${carId}/reminders`, payload)
}
onSaved?.()
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<form onsubmit={handleSubmit} class="space-y-4">
<div>
<label for="reminder-type" class={labelClass}>Type</label>
<select id="reminder-type" bind:value={reminderType} class={input}>
{#each BUILTIN_TYPES as t (t.value)}
<option value={t.value}>{t.label}</option>
{/each}
</select>
</div>
{#if reminderType === 'custom'}
<div>
<label for="reminder-label" class={labelClass}>Label *</label>
<input id="reminder-label" bind:value={label} placeholder="Spark plugs" class={input} />
</div>
{/if}
<div class="grid grid-cols-2 gap-4">
<div>
<label for="reminder-due-date" class={labelClass}>Due date</label>
<input id="reminder-due-date" type="date" bind:value={dueDate} class={input} />
</div>
<div>
<label for="reminder-due-odometer" class={labelClass}>Due odometer (km)</label>
<input id="reminder-due-odometer" type="number" bind:value={dueOdometer} class={input} />
</div>
</div>
<div>
<label for="reminder-notes" class={labelClass}>Notes</label>
<textarea id="reminder-notes" bind:value={notes} rows="2" class={input}></textarea>
</div>
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
<div class="flex justify-end gap-2 pt-2">
<button type="button" onclick={() => onCancel?.()} class={btnSecondary}>Cancel</button>
<button type="submit" disabled={saving} class={btnPrimary}>
{saving ? 'Saving…' : reminder ? 'Save changes' : 'Add reminder'}
</button>
</div>
</form>
@@ -0,0 +1,160 @@
<script>
import { apiGet, apiPut, apiDelete } from '../api.js'
import { confirmAction } from '../confirm.js'
import { formatDate, reminderKindLabel } from '../utils.js'
import { btnGhost, btnIcon } from '../ui.js'
import Icon from './Icon.svelte'
import Modal from './Modal.svelte'
import LoadingState from './LoadingState.svelte'
import ReminderForm from './ReminderForm.svelte'
// No carId → whole-garage dashboard (GET /api/dashboard, mixes reminders
// + synthesized rego/WoF/service-due across all cars, read-only here).
// With carId → this car's own reminders (GET /api/cars/:id/reminders),
// which support add/edit/complete/delete — fully self-contained, so
// CarDetail doesn't need to manage any of that state itself. The server
// already hides completed reminders unless asked for (?completed=1).
let { carId = null } = $props()
let items = $state([])
let loading = $state(true)
let error = $state('')
let showCompleted = $state(false)
let showAddModal = $state(false)
let editingItem = $state(null)
async function load() {
loading = true
error = ''
try {
if (carId) {
items = await apiGet(`/cars/${carId}/reminders${showCompleted ? '?completed=1' : ''}`)
} else {
items = await apiGet('/dashboard')
}
} catch (err) {
error = err.message
} finally {
loading = false
}
}
$effect(() => {
carId
showCompleted
load()
})
async function toggleComplete(item) {
await apiPut(`/reminders/${item.id}`, { completed: !item.completedAt })
await load()
}
// A small colored icon chip per reminder gives the list some visual
// rhythm — otherwise it's just rows of plain text with no way to scan it
// at a glance.
function reminderIcon(item) {
const type = item.kind ?? item.reminderType
if (type === 'rego' || type === 'wof') return 'calendar'
if (type === 'custom') return 'bell'
return 'wrench'
}
function reminderIconTone(item) {
if (item.completedAt) return 'bg-stone-100 text-stone-400'
if (item.status === 'overdue') return 'bg-red-100 text-red-600'
if (item.status === 'upcoming') return 'bg-amber-100 text-amber-600'
return 'bg-teal-100 text-teal-700'
}
async function remove(item) {
if (!(await confirmAction('Delete this reminder?'))) return
await apiDelete(`/reminders/${item.id}`)
await load()
}
function handleSaved() {
showAddModal = false
editingItem = null
load()
}
</script>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if items.length === 0}
<p class="text-sm text-stone-400">
{showCompleted ? 'No completed reminders.' : `Nothing due${carId ? '' : ' across your garage'}.`}
</p>
{:else}
<ul class="divide-y divide-stone-100">
{#each items as item (item.id ?? `${item.reminderType}-${item.carId}`)}
<li class="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
<span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full {reminderIconTone(item)}">
<Icon name={reminderIcon(item)} class="h-4 w-4" />
</span>
<div class="min-w-0 flex-1">
<p class="flex flex-wrap items-center gap-2 font-medium text-stone-900">
{reminderKindLabel(item)}
{#if item.status === 'overdue'}
<span class="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">Overdue</span>
{:else if item.status === 'upcoming'}
<span class="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">Due soon</span>
{/if}
{#if !carId}<span class="font-normal text-stone-400">· {item.carRego}</span>{/if}
</p>
<p class="text-sm text-stone-500">
{#if item.dueDate}Due {formatDate(item.dueDate)}{/if}
{#if item.dueOdometer}{item.dueDate ? ' · ' : 'Due '}{item.dueOdometer.toLocaleString()} km{/if}
</p>
</div>
{#if carId && item.id}
<div class="flex shrink-0 items-center gap-1">
<button
onclick={() => toggleComplete(item)}
aria-label={item.completedAt ? 'Reopen' : 'Mark done'}
class={btnIcon}
>
<Icon name={item.completedAt ? 'undo' : 'check'} class="h-4 w-4" />
</button>
<button onclick={() => (editingItem = item)} aria-label="Edit reminder" class={btnIcon}>
<Icon name="pencil" class="h-4 w-4" />
</button>
<button onclick={() => remove(item)} aria-label="Delete reminder" class="{btnIcon} hover:text-red-600">
<Icon name="trash" class="h-4 w-4" />
</button>
</div>
{:else if !carId && item.carId}
<a href="#/cars/{item.carId}" class="shrink-0 text-xs font-medium text-teal-600 hover:underline">View car</a>
{/if}
</li>
{/each}
</ul>
{/if}
{#if carId}
<div class="mt-3 flex items-center justify-between">
<button onclick={() => (showAddModal = true)} class={btnGhost}>
<Icon name="plus" class="h-4 w-4" />
Add reminder
</button>
<button onclick={() => (showCompleted = !showCompleted)} class="text-xs text-stone-400 hover:text-stone-600">
{showCompleted ? 'Hide completed' : 'Show completed'}
</button>
</div>
{/if}
{#if showAddModal}
<Modal title="Add reminder" onClose={() => (showAddModal = false)}>
<ReminderForm {carId} onSaved={handleSaved} onCancel={() => (showAddModal = false)} />
</Modal>
{/if}
{#if editingItem}
<Modal title="Edit reminder" onClose={() => (editingItem = null)}>
<ReminderForm {carId} reminder={editingItem} onSaved={handleSaved} onCancel={() => (editingItem = null)} />
</Modal>
{/if}
@@ -0,0 +1,55 @@
<script>
import { fileUrl } from '../api.js'
import { formatDate } from '../utils.js'
import { btnIcon } from '../ui.js'
import Icon from './Icon.svelte'
// Plain content block — no card/border of its own. Rendered as one
// timeline entry's content by ServiceTimeline, which supplies the
// surrounding dot/line and spacing.
//
// onEdit/onDelete are both optional — omit both for a read-only rendering
// (used by the public share page), which also hides the action buttons.
// fileHref lets the public page point attachments at the public file
// endpoint instead of the authenticated one.
let { entry, onEdit, onDelete, fileHref = (file) => fileUrl(`/files/${file.id}`) } = $props()
</script>
<div class="flex items-start justify-between gap-2">
<div>
<p class="text-xs text-stone-400">{formatDate(entry.entryDate)}</p>
<p class="font-medium text-stone-900">{entry.entryType}</p>
<p class="text-sm text-stone-500">
{#if entry.performedAt}{entry.performedAt}{/if}
{#if entry.odometer}{entry.performedAt ? ' · ' : ''}{entry.odometer.toLocaleString()} km{/if}
</p>
</div>
{#if onEdit || onDelete}
<div class="flex shrink-0 gap-1">
<button onclick={() => onEdit?.(entry)} aria-label="Edit entry" class={btnIcon}>
<Icon name="pencil" class="h-4 w-4" />
</button>
<button onclick={() => onDelete?.(entry)} aria-label="Delete entry" class="{btnIcon} hover:text-red-600">
<Icon name="trash" class="h-4 w-4" />
</button>
</div>
{/if}
</div>
{#if entry.description}
<p class="mt-1.5 whitespace-pre-wrap text-sm text-stone-700">{entry.description}</p>
{/if}
{#if entry.files?.length}
<div class="mt-2 flex flex-wrap gap-2">
{#each entry.files as file (file.id)}
<a
href={fileHref(file)}
target="_blank"
rel="noopener"
class="inline-flex items-center gap-1 rounded-md border border-stone-200 px-2 py-1 text-xs text-stone-600 hover:bg-stone-50"
>
<Icon name="paperclip" class="h-3.5 w-3.5" />
{file.fileName}
</a>
{/each}
</div>
{/if}
@@ -0,0 +1,152 @@
<script>
import { apiPost, apiPut, apiUpload, apiDelete, fileUrl } from '../api.js'
import { confirmAction } from '../confirm.js'
import { btnPrimary, btnSecondary, input, label as labelClass } from '../ui.js'
import Icon from './Icon.svelte'
// entry is optional — present in edit mode (with its already-attached
// .files array), absent (null) in create mode.
let { carId, entry = null, onSaved, onCancel } = $props()
// Intentional one-time snapshot of `entry` (not $derived) — a fresh form
// instance mounts each time an edit modal opens, and the modal backdrop
// blocks switching to a different entry while one is open.
let entryDate = $state(entry?.entryDate?.slice(0, 10) ?? new Date().toISOString().slice(0, 10))
let entryType = $state(entry?.entryType ?? '')
let performedAt = $state(entry?.performedAt ?? '')
let odometer = $state(entry?.odometer ?? '')
let description = $state(entry?.description ?? '')
let isService = $state(entry?.isService ?? false)
let newFiles = $state([])
let existingFiles = $state(entry?.files ?? [])
let saving = $state(false)
let error = $state('')
function handleFiles(e) {
newFiles = Array.from(e.target.files)
}
async function removeExistingFile(file) {
if (!(await confirmAction(`Remove "${file.fileName}"?`, { confirmLabel: 'Remove' }))) return
await apiDelete(`/files/${file.id}`)
existingFiles = existingFiles.filter((f) => f.id !== file.id)
}
async function handleSubmit(e) {
e.preventDefault()
if (!entryType.trim()) {
error = 'Type is required'
return
}
saving = true
error = ''
const payload = {
entryDate,
entryType: entryType.trim(),
performedAt: performedAt || null,
odometer: odometer ? Number(odometer) : null,
description: description || null,
isService,
}
try {
const saved = entry
? await apiPut(`/service-entries/${entry.id}`, payload)
: await apiPost(`/cars/${carId}/service-entries`, payload)
// One request per file — simplest way to reuse the single-file upload
// endpoint for a multi-file attach.
for (const file of newFiles) {
await apiUpload(`/service-entries/${saved.id}/files`, file)
}
onSaved?.()
} catch (err) {
error = err.message
} finally {
saving = false
}
}
</script>
<form onsubmit={handleSubmit} class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<label for="entry-date" class={labelClass}>Date</label>
<input id="entry-date" type="date" bind:value={entryDate} required class={input} />
</div>
<div>
<label for="entry-type" class={labelClass}>Type *</label>
<input id="entry-type" bind:value={entryType} placeholder="Oil change" required class={input} />
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label for="entry-performed-at" class={labelClass}>Where</label>
<input id="entry-performed-at" bind:value={performedAt} placeholder="Bob's Garage" class={input} />
</div>
<div>
<label for="entry-odometer" class={labelClass}>Odometer</label>
<input id="entry-odometer" type="number" bind:value={odometer} class={input} />
</div>
</div>
<div>
<label for="entry-description" class={labelClass}>Notes</label>
<textarea id="entry-description" bind:value={description} rows="3" class={input}></textarea>
</div>
<label class="flex items-center gap-2 text-sm text-stone-700">
<input type="checkbox" bind:checked={isService} class="h-4 w-4 rounded border-stone-300 text-teal-700 focus:ring-teal-500/40" />
This was a full service (resets the service-due reminder)
</label>
{#if existingFiles.length > 0}
<div>
<span class={labelClass}>Attached files</span>
<div class="flex flex-wrap gap-2">
{#each existingFiles as file (file.id)}
<span
class="inline-flex items-center gap-1.5 rounded-md border border-stone-200 py-1 pl-2 pr-1 text-xs text-stone-600"
>
<Icon name="paperclip" class="h-3.5 w-3.5 shrink-0" />
<a href={fileUrl(`/files/${file.id}`)} target="_blank" rel="noopener" class="hover:underline"
>{file.fileName}</a
>
<button
type="button"
onclick={() => removeExistingFile(file)}
aria-label="Remove file"
class="rounded p-0.5 text-stone-400 hover:bg-stone-100 hover:text-red-600"
>
<Icon name="x" class="h-3 w-3" />
</button>
</span>
{/each}
</div>
</div>
{/if}
<div>
<label for="entry-files" class={labelClass}>
{existingFiles.length > 0 ? 'Attach more files (PNG/PDF)' : 'Attach files (PNG/PDF)'}
</label>
<input
id="entry-files"
type="file"
accept="image/png,application/pdf"
multiple
onchange={handleFiles}
class="block w-full text-sm text-stone-600 file:mr-3 file:rounded-lg file:border-0 file:bg-stone-100 file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-stone-700 hover:file:bg-stone-200"
/>
{#if newFiles.length > 0}
<p class="mt-1 text-xs text-stone-400">{newFiles.length} file{newFiles.length === 1 ? '' : 's'} selected</p>
{/if}
</div>
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
<div class="flex justify-end gap-2 pt-2">
<button type="button" onclick={() => onCancel?.()} class={btnSecondary}>Cancel</button>
<button type="submit" disabled={saving} class={btnPrimary}>
{saving ? 'Saving…' : entry ? 'Save changes' : 'Add entry'}
</button>
</div>
</form>
@@ -0,0 +1,100 @@
<script>
import { apiGet, apiDelete } from '../api.js'
import { confirmAction } from '../confirm.js'
import ServiceTimeline from './ServiceTimeline.svelte'
import ServiceEntryForm from './ServiceEntryForm.svelte'
import Modal from './Modal.svelte'
import LoadingState from './LoadingState.svelte'
import { btnGhost } from '../ui.js'
import Icon from './Icon.svelte'
let { carId } = $props()
const PAGE_SIZE = 20
let entries = $state([])
let hasMore = $state(false)
let loading = $state(true)
let loadingMore = $state(false)
let error = $state('')
let showAddModal = $state(false)
let editingEntry = $state(null)
// Loads the first page fresh — used on mount and after any add/edit/
// delete, so we don't have to reconcile where a changed row now falls
// across already-loaded pages.
async function loadFirstPage() {
loading = true
error = ''
try {
const result = await apiGet(`/cars/${carId}/service-entries?limit=${PAGE_SIZE}&offset=0`)
entries = result.items
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loading = false
}
}
async function loadMore() {
loadingMore = true
try {
const result = await apiGet(`/cars/${carId}/service-entries?limit=${PAGE_SIZE}&offset=${entries.length}`)
entries = [...entries, ...result.items]
hasMore = result.hasMore
} catch (err) {
error = err.message
} finally {
loadingMore = false
}
}
$effect(() => {
carId
loadFirstPage()
})
async function handleDelete(entry) {
if (!(await confirmAction(`Delete "${entry.entryType}"?`, { confirmLabel: 'Delete' }))) return
await apiDelete(`/service-entries/${entry.id}`)
loadFirstPage()
}
function handleSaved() {
showAddModal = false
editingEntry = null
loadFirstPage()
}
</script>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else}
<ServiceTimeline {entries} onEdit={(e) => (editingEntry = e)} onDelete={handleDelete} />
{#if hasMore}
<button onclick={loadMore} disabled={loadingMore} class="{btnGhost} mt-3 disabled:opacity-50">
<Icon name="chevronDown" class="h-4 w-4" />
{loadingMore ? 'Loading…' : 'Load more'}
</button>
{/if}
{/if}
<button onclick={() => (showAddModal = true)} class="{btnGhost} mt-3">
<Icon name="plus" class="h-4 w-4" />
Add service entry
</button>
{#if showAddModal}
<Modal title="Add service entry" onClose={() => (showAddModal = false)}>
<ServiceEntryForm {carId} onSaved={handleSaved} onCancel={() => (showAddModal = false)} />
</Modal>
{/if}
{#if editingEntry}
<Modal title="Edit service entry" onClose={() => (editingEntry = null)}>
<ServiceEntryForm {carId} entry={editingEntry} onSaved={handleSaved} onCancel={() => (editingEntry = null)} />
</Modal>
{/if}
@@ -0,0 +1,30 @@
<script>
import ServiceEntryCard from './ServiceEntryCard.svelte'
// A real timeline — a dot per entry connected by a line, newest first
// (the API already returns entries newest-first). The dot/line column is
// a flex sibling of the content rather than absolutely positioned, so it
// naturally stretches to match each entry's height regardless of how much
// text/attachments it has.
let { entries, onEdit, onDelete, fileHref } = $props()
</script>
{#if entries.length === 0}
<p class="text-sm text-stone-400">No service history yet.</p>
{:else}
<ol>
{#each entries as entry, i (entry.id)}
<li class="flex gap-4">
<div class="flex w-3 shrink-0 flex-col items-center">
<span class="mt-1.5 h-3 w-3 shrink-0 rounded-full bg-teal-700 ring-4 ring-teal-100"></span>
{#if i < entries.length - 1}
<span class="w-px flex-1 bg-stone-200"></span>
{/if}
</div>
<div class="min-w-0 flex-1 pb-6">
<ServiceEntryCard {entry} {onEdit} {onDelete} {fileHref} />
</div>
</li>
{/each}
</ol>
{/if}
@@ -0,0 +1,108 @@
<script>
import QRCode from 'qrcode'
import { apiPost, apiDelete } from '../api.js'
import { confirmAction } from '../confirm.js'
import { btnPrimary, btnSecondary, btnDanger } from '../ui.js'
let { car, onUpdated } = $props()
let shareToken = $state(car.shareToken)
let qrDataUrl = $state('')
let loading = $state(false)
let copied = $state(false)
let error = $state('')
let shareUrl = $derived(shareToken ? `${window.location.origin}/#/share/${shareToken}` : '')
$effect(() => {
if (!shareUrl) {
qrDataUrl = ''
return
}
QRCode.toDataURL(shareUrl, { width: 220, margin: 1 }).then((url) => (qrDataUrl = url))
})
async function enableSharing() {
loading = true
error = ''
try {
const updated = await apiPost(`/cars/${car.id}/share`, {})
shareToken = updated.shareToken
onUpdated?.(updated)
} catch (err) {
error = err.message
} finally {
loading = false
}
}
async function regenerate() {
if (
!(await confirmAction('Regenerate the link? The current QR code/link will stop working.', {
confirmLabel: 'Regenerate',
danger: false,
}))
)
return
await enableSharing()
}
async function disableSharing() {
if (
!(await confirmAction('Turn off sharing? The current link/QR code will stop working.', {
confirmLabel: 'Turn off sharing',
}))
)
return
loading = true
error = ''
try {
await apiDelete(`/cars/${car.id}/share`)
shareToken = null
onUpdated?.({ ...car, shareToken: null })
} catch (err) {
error = err.message
} finally {
loading = false
}
}
async function copyLink() {
await navigator.clipboard.writeText(shareUrl)
copied = true
setTimeout(() => (copied = false), 1500)
}
</script>
<div class="space-y-4">
<p class="text-sm text-stone-500">
Share a read-only view of {car.rego}'s service history (including attached docs) — no login required. Handy for
a QR code in the glovebox, or a link when selling the car.
</p>
{#if !shareToken}
<button onclick={enableSharing} disabled={loading} class={btnPrimary}>
{loading ? 'Generating…' : 'Turn on sharing'}
</button>
{:else}
<div class="flex flex-col items-center gap-3 rounded-lg border border-stone-200 p-4">
{#if qrDataUrl}
<img src={qrDataUrl} alt="QR code for share link" class="h-48 w-48" />
{/if}
<div class="flex w-full items-center gap-2">
<input
readonly
value={shareUrl}
class="flex-1 rounded-md border border-stone-300 bg-stone-50 px-2 py-1.5 text-xs text-stone-600"
/>
<button onclick={copyLink} class={btnSecondary}>{copied ? 'Copied!' : 'Copy'}</button>
</div>
</div>
<div class="flex gap-2">
<button onclick={regenerate} disabled={loading} class={btnSecondary}>Regenerate link</button>
<button onclick={disableSharing} disabled={loading} class={btnDanger}>Turn off sharing</button>
</div>
{/if}
{#if error}<p class="text-sm text-red-600">{error}</p>{/if}
</div>
@@ -0,0 +1,8 @@
<script>
let { class: className = 'h-4 w-4' } = $props()
</script>
<svg class="{className} animate-spin" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2.5" opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" />
</svg>
+19
View File
@@ -0,0 +1,19 @@
import { writable } from 'svelte/store'
// A single global confirm-dialog slot — any component can call confirmAction()
// to get an in-app, on-brand confirmation instead of the browser's native
// confirm() popup. <ConfirmDialog /> (mounted once, in App.svelte) renders
// whatever's in this store.
export const confirmState = writable(null)
export function confirmAction(message, opts = {}) {
return new Promise((resolve) => {
confirmState.set({
message,
title: opts.title ?? 'Are you sure?',
confirmLabel: opts.confirmLabel ?? 'Delete',
danger: opts.danger ?? true,
resolve,
})
})
}
+6
View File
@@ -0,0 +1,6 @@
import { writable } from 'svelte/store'
// The one global store the app needs: who's logged in, populated once at
// mount via GET /api/me. Everything else (cars, entries, reminders) is
// fetched per-page with local component state — no global cache.
export const user = writable(null)
+53
View File
@@ -0,0 +1,53 @@
// Shared class-string constants so buttons/cards/inputs look consistent
// across the app without repeating long Tailwind class lists everywhere.
// Tailwind's scanner finds these fine since they're plain string literals,
// not dynamically constructed.
export const btnPrimary =
'inline-flex items-center justify-center gap-1.5 rounded-lg bg-teal-700 px-4 py-2 text-sm font-medium text-white shadow-sm shadow-teal-900/20 hover:bg-teal-600 active:bg-teal-800 active:scale-[0.98] disabled:opacity-50 disabled:pointer-events-none transition'
export const btnSecondary =
'inline-flex items-center justify-center gap-1.5 rounded-lg border border-stone-300 bg-white px-4 py-2 text-sm font-medium text-stone-700 hover:bg-stone-50 active:scale-[0.98] disabled:opacity-50 disabled:pointer-events-none transition'
export const btnDanger =
'inline-flex items-center justify-center gap-1.5 rounded-lg border border-red-200 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 active:scale-[0.98] transition'
// Small text-style trigger, e.g. "+ Add reminder" links that open a modal.
export const btnGhost =
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm font-medium text-teal-600 hover:bg-teal-50 active:scale-[0.97] transition'
// Small icon-only buttons (edit/delete pencils on list rows).
export const btnIcon =
'inline-flex items-center justify-center rounded-md p-1.5 text-stone-400 hover:bg-stone-100 hover:text-stone-700 active:scale-[0.94] transition'
export const card = 'rounded-lg border border-stone-200 bg-white shadow-sm'
// Section cards on the car detail page get a colored top edge instead of
// being plain boxes — a small workshop-docket touch rather than three
// identical white rectangles stacked on top of each other.
export const sectionCard = 'rounded-lg border border-stone-200 border-t-4 border-t-teal-700 bg-white shadow-sm p-5'
export const input =
'w-full rounded-lg border border-stone-300 bg-white px-3 py-2 text-sm text-stone-900 placeholder-stone-400 focus:outline-none focus:ring-2 focus:ring-teal-500/40 focus:border-teal-500 transition-shadow'
export const label = 'mb-1 block text-sm font-medium text-stone-700'
export const sectionHeading = 'text-sm font-semibold uppercase tracking-wide text-stone-500'
// A small stat/number readout — tinted rather than plain white-on-white, so
// pages with a lot of numbers (fuel summary, mileage) have some color
// rhythm instead of reading as one flat gray block.
export const statTile = 'rounded-lg border border-teal-100 bg-teal-50/60 p-3'
export const statLabel = 'text-xs font-medium uppercase tracking-wide text-teal-700/70'
export const statValue = 'mt-0.5 text-xl font-bold text-stone-900'
// The car photo's empty state — a real color moment (used on both the
// garage grid cards and the car detail hero) rather than a flat gray dashed
// box, which otherwise ends up the single largest, blandest thing on the
// page for any car without a photo yet. The diagonal texture is applied via
// a separate absolutely-positioned overlay element (not an inline style on
// this same element) — an inline `style` background-image would otherwise
// win the cascade over this class's gradient and blank it out entirely.
export const photoPlaceholder = 'bg-gradient-to-br from-teal-600 to-teal-800'
export const photoPlaceholderTextureStyle =
'background-image: repeating-linear-gradient(135deg, rgba(255,255,255,0.07), rgba(255,255,255,0.07) 12px, transparent 12px, transparent 24px);'
+36
View File
@@ -0,0 +1,36 @@
export function formatDate(value) {
if (!value) return '—'
return new Date(value).toLocaleDateString('en-NZ', {
day: 'numeric',
month: 'short',
year: 'numeric',
})
}
// Positive = days from now until due, negative = days overdue.
export function daysUntil(dateStr) {
if (!dateStr) return null
const today = new Date()
today.setHours(0, 0, 0, 0)
const target = new Date(dateStr)
target.setHours(0, 0, 0, 0)
return Math.round((target - today) / 86400000)
}
export const REMINDER_KIND_LABELS = {
service: 'Service',
wheel_rotation: 'Wheel rotation',
alignment: 'Alignment',
rego: 'Rego',
wof: 'WoF',
custom: 'Custom',
}
// Dashboard items use `kind`; a car's own reminders (GET .../reminders) use
// `reminderType` — same underlying value, different field name depending on
// which endpoint it came from, so accept either.
export function reminderKindLabel(item) {
const type = item.kind ?? item.reminderType
if (type === 'custom' && item.label) return item.label
return REMINDER_KIND_LABELS[type] || type
}
+7
View File
@@ -0,0 +1,7 @@
import { mount } from 'svelte'
import './app.css'
import App from './App.svelte'
const app = mount(App, { target: document.getElementById('app') })
export default app
+18
View File
@@ -0,0 +1,18 @@
<script>
import { push } from 'svelte-spa-router'
import { card } from '../lib/ui.js'
import CarForm from '../lib/components/CarForm.svelte'
function handleSave(car) {
// Photo upload happens on the car-detail page right after creation —
// keeps CarForm/PhotoUpload from having to handle a not-yet-existing car.
push(`/cars/${car.id}`)
}
</script>
<div class="mx-auto max-w-md">
<h2 class="mb-4 text-lg font-semibold tracking-tight text-stone-900">Add a car</h2>
<div class="{card} p-5">
<CarForm onSave={handleSave} />
</div>
</div>
+155
View File
@@ -0,0 +1,155 @@
<script>
import { push } from 'svelte-spa-router'
import { apiGet, apiDelete } from '../lib/api.js'
import { confirmAction } from '../lib/confirm.js'
import { formatDate, daysUntil } from '../lib/utils.js'
import { btnSecondary, btnIcon, sectionCard } from '../lib/ui.js'
import Icon from '../lib/components/Icon.svelte'
import RegoPlate from '../lib/components/RegoPlate.svelte'
import PhotoUpload from '../lib/components/PhotoUpload.svelte'
import Modal from '../lib/components/Modal.svelte'
import LoadingState from '../lib/components/LoadingState.svelte'
import ShareModal from '../lib/components/ShareModal.svelte'
import RemindersPanel from '../lib/components/RemindersPanel.svelte'
import KnowledgePanel from '../lib/components/KnowledgePanel.svelte'
import ServiceHistorySection from '../lib/components/ServiceHistorySection.svelte'
import FuelPanel from '../lib/components/FuelPanel.svelte'
import MileagePanel from '../lib/components/MileagePanel.svelte'
let { params } = $props()
// $derived (not a plain const) so navigating directly between two car
// detail pages — where svelte-spa-router reuses this component instance
// and just updates `params` — still points at the right car.
let carId = $derived(params.id)
let car = $state(null)
let loading = $state(true)
let error = $state('')
let showShareModal = $state(false)
let showMileageModal = $state(false)
const TABS = [
{ key: 'reminders', label: 'Reminders', icon: 'check' },
{ key: 'service', label: 'Service history', icon: 'paperclip' },
{ key: 'fuel', label: 'Fuel', icon: 'fuel' },
{ key: 'knowledge', label: 'Knowledgebase', icon: 'bookOpen' },
]
let activeTab = $state('reminders')
async function loadCar() {
car = await apiGet(`/cars/${carId}`)
}
$effect(() => {
carId
loading = true
error = ''
loadCar()
.catch((err) => (error = err.message))
.finally(() => (loading = false))
})
async function handleDeleteCar() {
if (!(await confirmAction(`Delete ${car.rego} and all its history? This can't be undone.`, { confirmLabel: 'Delete car' })))
return
await apiDelete(`/cars/${carId}`)
push('/')
}
function expiryPill(dateStr, label) {
const d = daysUntil(dateStr)
let tone = 'border-stone-200 text-stone-600'
if (d !== null) {
if (d < 0) tone = 'border-red-200 bg-red-50 text-red-700'
else if (d <= 30) tone = 'border-amber-200 bg-amber-50 text-amber-700'
}
return { text: `${label} ${formatDate(dateStr)}`, tone }
}
</script>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if car}
<div class="space-y-6">
<PhotoUpload {carId} hasPhoto={car.hasPhoto} alt={car.rego} name={car.name} onUploaded={loadCar} />
<div class="flex flex-wrap items-start justify-between gap-4">
<div>
<RegoPlate rego={car.rego} size="lg" />
<p class="mt-2 text-stone-500">
{[car.year, car.make, car.model].filter(Boolean).join(' ')}{car.color ? ` · ${car.color}` : ''}
</p>
<div class="mt-2 flex flex-wrap gap-2">
{#if car.regoExpiry}
{@const p = expiryPill(car.regoExpiry, 'Rego')}
<span class="rounded-full border px-2.5 py-0.5 text-xs font-medium {p.tone}">{p.text}</span>
{/if}
{#if car.wofExpiry}
{@const p = expiryPill(car.wofExpiry, 'WoF')}
<span class="rounded-full border px-2.5 py-0.5 text-xs font-medium {p.tone}">{p.text}</span>
{/if}
<button
onclick={() => (showMileageModal = true)}
class="rounded-full border border-stone-200 px-2.5 py-0.5 text-xs font-medium text-stone-600 hover:border-teal-600 hover:text-teal-700"
>
{car.odometer ? `${car.odometer.toLocaleString()} km` : 'Set odometer'}
</button>
</div>
</div>
<div class="flex shrink-0 gap-2">
<button onclick={() => (showShareModal = true)} class={btnSecondary}>
<Icon name="share" class="h-4 w-4" />
Share
</button>
<a href="#/cars/{carId}/edit" class={btnSecondary}>
<Icon name="pencil" class="h-4 w-4" />
Edit
</a>
<button onclick={handleDeleteCar} aria-label="Delete car" title="Delete car" class="{btnIcon} hover:text-red-600">
<Icon name="trash" class="h-4 w-4" />
</button>
</div>
</div>
<div class="flex gap-1 overflow-x-auto rounded-lg bg-stone-100 p-1">
{#each TABS as tab (tab.key)}
<button
onclick={() => (activeTab = tab.key)}
class="flex shrink-0 items-center gap-1.5 rounded-md px-3 py-2 text-sm font-medium transition-all
{activeTab === tab.key
? 'bg-white text-teal-700 shadow-sm'
: 'text-stone-500 hover:text-stone-900'}"
>
<Icon name={tab.icon} class="h-4 w-4" />
{tab.label}
</button>
{/each}
</div>
<div class={sectionCard}>
{#if activeTab === 'reminders'}
<RemindersPanel {carId} />
{:else if activeTab === 'knowledge'}
<KnowledgePanel {carId} />
{:else if activeTab === 'service'}
<ServiceHistorySection {carId} />
{:else if activeTab === 'fuel'}
<FuelPanel {carId} />
{/if}
</div>
</div>
{#if showShareModal}
<Modal title="Share {car.rego}" onClose={() => (showShareModal = false)}>
<ShareModal {car} onUpdated={(updated) => (car = updated)} />
</Modal>
{/if}
{#if showMileageModal}
<Modal title="Mileage" onClose={() => (showMileageModal = false)}>
<MileagePanel {carId} odometer={car.odometer} onUpdated={loadCar} />
</Modal>
{/if}
{/if}
+41
View File
@@ -0,0 +1,41 @@
<script>
import { onMount } from 'svelte'
import { push } from 'svelte-spa-router'
import { apiGet } from '../lib/api.js'
import { card } from '../lib/ui.js'
import CarForm from '../lib/components/CarForm.svelte'
import LoadingState from '../lib/components/LoadingState.svelte'
let { params } = $props()
let car = $state(null)
let loading = $state(true)
let error = $state('')
onMount(async () => {
try {
car = await apiGet(`/cars/${params.id}`)
} catch (err) {
error = err.message
} finally {
loading = false
}
})
function handleSave() {
push(`/cars/${params.id}`)
}
</script>
<div class="mx-auto max-w-md">
<h2 class="mb-4 text-lg font-semibold tracking-tight text-stone-900">Edit car</h2>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else}
<div class="{card} p-5">
<CarForm {car} onSave={handleSave} />
</div>
{/if}
</div>
+61
View File
@@ -0,0 +1,61 @@
<script>
import { onMount } from 'svelte'
import { apiGet } from '../lib/api.js'
import { btnPrimary, card, sectionCard, sectionHeading } from '../lib/ui.js'
import Icon from '../lib/components/Icon.svelte'
import CarCard from '../lib/components/CarCard.svelte'
import RemindersPanel from '../lib/components/RemindersPanel.svelte'
import LoadingState from '../lib/components/LoadingState.svelte'
let cars = $state([])
let loading = $state(true)
let error = $state('')
onMount(async () => {
try {
cars = await apiGet('/cars')
} catch (err) {
error = err.message
} finally {
loading = false
}
})
</script>
<div class="space-y-8">
<section class={sectionCard}>
<h2 class="{sectionHeading} mb-3">Coming up</h2>
<RemindersPanel />
</section>
<section>
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold tracking-tight text-stone-900">Your garage</h2>
<a href="#/cars/new" class={btnPrimary}>
<Icon name="plus" class="h-4 w-4" />
Add car
</a>
</div>
{#if loading}
<LoadingState />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if cars.length === 0}
<div class="{card} flex flex-col items-center gap-3 px-6 py-12 text-center">
<span class="text-4xl">🚗</span>
<p class="text-sm text-stone-500">No cars yet — add your first one to get started.</p>
<a href="#/cars/new" class={btnPrimary}>
<Icon name="plus" class="h-4 w-4" />
Add car
</a>
</div>
{:else}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{#each cars as car (car.id)}
<CarCard {car} />
{/each}
</div>
{/if}
</section>
</div>
+81
View File
@@ -0,0 +1,81 @@
<script>
import { apiGet, fileUrl } from '../lib/api.js'
import RegoPlate from '../lib/components/RegoPlate.svelte'
import ServiceTimeline from '../lib/components/ServiceTimeline.svelte'
import LoadingState from '../lib/components/LoadingState.svelte'
import { btnGhost } from '../lib/ui.js'
let { params } = $props()
const token = params.token
let car = $state(null)
let entries = $state([])
let hasMore = $state(false)
let loading = $state(true)
let error = $state('')
async function load() {
try {
car = await apiGet(`/public/cars/${token}`)
const result = await apiGet(`/public/cars/${token}/service-entries?limit=20&offset=0`)
entries = result.items
hasMore = result.hasMore
} catch (err) {
error = 'This share link is invalid, or sharing has been turned off.'
} finally {
loading = false
}
}
load()
async function loadMore() {
const result = await apiGet(`/public/cars/${token}/service-entries?limit=20&offset=${entries.length}`)
entries = [...entries, ...result.items]
hasMore = result.hasMore
}
const fileHref = (file) => fileUrl(`/public/cars/${token}/files/${file.id}`)
</script>
<div class="min-h-screen bg-stone-50">
<div class="h-1.5 bg-teal-700"></div>
<header class="border-b border-stone-200 bg-white/90 px-4 py-3">
<div class="mx-auto flex max-w-2xl items-center gap-2">
<span class="flex h-7 w-7 items-center justify-center rounded-lg bg-teal-700 text-sm">🔧</span>
<span class="font-semibold text-stone-900">My Garage</span>
<span class="text-sm text-stone-400">· shared service history</span>
</div>
</header>
<main class="mx-auto max-w-2xl px-4 py-6">
{#if loading}
<LoadingState center />
{:else if error}
<p class="text-sm text-red-600">{error}</p>
{:else if car}
<div class="mb-6 flex items-center gap-4">
{#if car.hasPhoto}
<img
src={fileUrl(`/public/cars/${token}/photo`)}
alt={car.rego}
class="h-20 w-28 rounded-lg border border-stone-200 object-cover"
/>
{/if}
<div>
<RegoPlate rego={car.rego} size="md" />
<p class="mt-1 text-sm text-stone-500">
{[car.year, car.make, car.model].filter(Boolean).join(' ')}{car.color ? ` · ${car.color}` : ''}
</p>
</div>
</div>
<h2 class="mb-3 text-sm font-semibold uppercase tracking-wide text-stone-500">Service history</h2>
<div class="rounded-lg border border-t-4 border-stone-200 border-t-teal-700 bg-white p-5 shadow-sm">
<ServiceTimeline {entries} {fileHref} />
{#if hasMore}
<button onclick={loadMore} class="{btnGhost} mt-3">Load more</button>
{/if}
</div>
{/if}
</main>
<footer class="mx-auto max-w-2xl px-4 pb-6 text-center text-xs text-stone-400">© Michael Rausch 2026</footer>
</div>
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [svelte(), tailwindcss()],
build: {
outDir: 'dist',
},
server: {
proxy: {
// `npm run dev` proxies API calls to the Go backend so the SPA can be
// developed without rebuilding the whole binary on every change.
'/api': 'http://localhost:8080',
},
},
})