feat(web): the settings surface

There was no /indstillinger route at all. The Gmail OAuth callback
redirects there and had been answering 404 since it was written.

Six pages rather than one long scroll, because the sections have nothing
to do with each other and somebody opening API tokens should not have to
walk past their own password to get there: the account and its second
factor, notifications, integrations, AI, tokens, and data. Everything
listed as having no interface in the handoff is reachable from one of
them — the calendar feed, the mail-to-task address, Gmail, the AI
provider, import, export, templates and the update notice.

Two decisions worth naming. The AI key field starts empty and says why:
a settings page that repopulates a password field is one that will
eventually leak a key into a screenshot, and an empty value means "leave
the stored one alone" rather than "clear it". And the form chrome lives
in the layout as :global rules, because scoped styles do not reach a
child route and six copies of the same twelve selectors is six places for
them to drift.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kristian Wind
2026-08-17 10:56:33 +02:00
committed by Kristian Wind
co-authored by Claude Opus 5
parent fc4dba8549
commit 9d9444d0ac
9 changed files with 2036 additions and 0 deletions
+86
View File
@@ -90,8 +90,45 @@ async function request(method, path, body, options = {}) {
const get = (path, options) => request('GET', path, undefined, options);
const post = (path, body, options) => request('POST', path, body ?? {}, options);
const patch = (path, body) => request('PATCH', path, body);
const put = (path, body) => request('PUT', path, body);
const del = (path) => request('DELETE', path);
/**
* Uploads a file. Not routed through `request`, which serialises JSON and sets a
* Content-Type — a multipart body has to set its own boundary, and the browser
* only does that when nothing has claimed the header.
*/
async function upload(path, file, field = 'file') {
const form = new FormData();
form.append(field, file);
let res;
try {
res = await fetch(`/api/v1${path}`, { method: 'POST', body: form, credentials: 'same-origin' });
} catch {
throw new ApiError(0, 'offline', 'ingen forbindelse');
}
const text = await res.text();
let payload = null;
if (text) {
try {
payload = JSON.parse(text);
} catch {
payload = null;
}
}
if (!res.ok) {
throw new ApiError(
res.status,
payload?.code ?? 'internal_error',
payload?.error ?? res.statusText,
payload?.fields
);
}
return payload;
}
export const api = {
// --- auth
setupState: () => get('/auth/setup'),
@@ -100,6 +137,7 @@ export const api = {
loginTOTP: (code) => post('/auth/login/totp', { code }),
logout: () => post('/auth/logout'),
me: () => get('/auth/me'),
updateProfile: (data) => patch('/auth/me', data),
signup: (data) => post('/auth/signup', data),
forgotPassword: (email) => post('/auth/password/forgot', { email }),
resetPassword: (token, password) => post('/auth/password/reset', { token, password }),
@@ -175,6 +213,54 @@ export const api = {
useTemplate: (id, data) => post(`/templates/${id}/use`, data),
deleteTemplate: (id) => del(`/templates/${id}`),
// --- comments and attachments
listComments: (taskId) => get(`/tasks/${taskId}/comments`),
createComment: (taskId, body) => post(`/tasks/${taskId}/comments`, { body }),
updateComment: (id, body) => patch(`/comments/${id}`, { body }),
deleteComment: (id) => del(`/comments/${id}`),
uploadAttachment: (taskId, file) => upload(`/tasks/${taskId}/attachments`, file),
deleteAttachment: (id) => del(`/attachments/${id}`),
attachmentURL: (id) => `/api/v1/attachments/${id}`,
// --- API tokens
listTokens: () => get('/tokens'),
createToken: (name, expiresInDays) =>
post('/tokens', { name, expires_in_days: expiresInDays ?? 0 }),
deleteToken: (id) => del(`/tokens/${id}`),
// --- notifications and push
listNotifications: () => get('/notifications'),
markNotificationsRead: (id) => post(id ? `/notifications/${id}/read` : '/notifications/read'),
pushKey: () => get('/push/key'),
subscribePush: (subscription) => post('/push/subscribe', subscription),
unsubscribePush: (endpoint) => post('/push/unsubscribe', { endpoint, keys: {} }),
// --- integrations
getMailAddress: () => get('/mail-address'),
rotateMailAddress: () => post('/mail-address/rotate'),
getGmail: () => get('/gmail'),
setGmail: (data) => put('/gmail', data),
disconnectGmail: () => del('/gmail'),
authorizeGmail: () => post('/gmail/authorize'),
syncGmail: () => post('/gmail/sync'),
getAISettings: () => get('/ai/settings'),
setAISettings: (data) => put('/ai/settings', data),
aiSummary: () => post('/ai/summary'),
aiSplit: (taskId) => post(`/ai/tasks/${taskId}/split`),
version: () => get('/version'),
// --- import and export
importTodoist: (file) => upload('/import/todoist', file),
importCSV: (data) => post('/import/csv', data),
exportAccountURL: () => '/api/v1/export/account',
exportProjectCSVURL: (id) => `/api/v1/export/projects/${id}.csv`,
exportProjectICSURL: (id) => `/api/v1/export/projects/${id}.ics`,
// --- views
today: () => get('/today'),
upcoming: (days) => get(`/upcoming${days ? `?days=${days}` : ''}`),
+26
View File
@@ -154,6 +154,21 @@
{/if}
<div class="foot">
<a
href="/indstillinger"
class="settings"
class:active={current.startsWith('/indstillinger')}
onclick={onnavigate}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="3" />
<path
d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09A1.65 1.65 0 008 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06A1.65 1.65 0 004.6 15a1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06A1.65 1.65 0 009 4.6a1.65 1.65 0 001-1.51V3a2 2 0 114 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06A1.65 1.65 0 0019.4 9v0a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z"
/>
</svg>
Indstillinger
</a>
<!-- A quiet indicator, not an alarm: losing the socket for a moment is
normal, and the app keeps working without it. -->
{#if !app.connected}
@@ -310,6 +325,17 @@
gap: var(--s2);
}
.settings svg {
width: 15px;
height: 15px;
flex: none;
fill: none;
stroke: currentColor;
stroke-width: 1.6;
stroke-linecap: round;
stroke-linejoin: round;
}
.offline {
font-size: var(--text-xs);
color: var(--ink-faint);
+263
View File
@@ -0,0 +1,263 @@
<script>
/**
* The settings surface.
*
* Six pages rather than one long scroll: the sections have nothing to do with
* each other, and a person opening "API-tokens" should not have to walk past
* their own password to get there.
*
* The form chrome lives here as `:global` rules. Scoped styles do not reach a
* child route, and the alternative — six copies of the same twelve selectors —
* is six places for them to drift apart.
*/
import { page } from '$app/stores';
let { children } = $props();
const SECTIONS = [
{ href: '/indstillinger', label: 'Konto' },
{ href: '/indstillinger/notifikationer', label: 'Notifikationer' },
{ href: '/indstillinger/integrationer', label: 'Integrationer' },
{ href: '/indstillinger/ai', label: 'AI' },
{ href: '/indstillinger/tokens', label: 'API-tokens' },
{ href: '/indstillinger/data', label: 'Data og skabeloner' }
];
let current = $derived($page.url.pathname.replace(/\/$/, '') || '/indstillinger');
</script>
<div class="settings">
<header>
<h1>Indstillinger</h1>
</header>
<nav aria-label="Indstillinger">
{#each SECTIONS as section (section.href)}
<a href={section.href} class:active={current === section.href}>{section.label}</a>
{/each}
</nav>
<div class="body">
{@render children()}
</div>
</div>
<style>
.settings {
max-width: var(--content-max);
margin: 0 auto;
padding: var(--s6) var(--s4) var(--s8);
}
h1 {
font-size: var(--text-2xl);
margin-bottom: var(--s5);
}
/* A scrolling strip rather than a wrapping row: six labels wrap to two lines on
a phone, and a two-line tab bar looks like a mistake. */
nav {
display: flex;
gap: var(--s1);
overflow-x: auto;
border-bottom: 1px solid var(--line);
margin-bottom: var(--s5);
scrollbar-width: none;
}
nav::-webkit-scrollbar {
display: none;
}
nav a {
flex: none;
padding: var(--s2) var(--s3);
font-size: var(--text-sm);
color: var(--ink-muted);
text-decoration: none;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
white-space: nowrap;
transition: color var(--fast) var(--ease);
}
nav a:hover {
color: var(--ink);
}
nav a.active {
color: var(--ink);
border-bottom-color: var(--accent);
}
.body {
display: flex;
flex-direction: column;
gap: var(--s5);
}
/* --- shared form chrome, for the child routes ------------------------------- */
.settings :global(section.panel) {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius-lg);
padding: var(--s5);
display: flex;
flex-direction: column;
gap: var(--s4);
}
.settings :global(.panel > header) {
display: flex;
flex-direction: column;
gap: var(--s1);
}
.settings :global(.panel h2) {
font-size: var(--text-lg);
}
.settings :global(.panel .hint) {
margin: 0;
font-size: var(--text-sm);
color: var(--ink-muted);
line-height: 1.5;
}
.settings :global(.field) {
display: flex;
flex-direction: column;
gap: var(--s2);
}
.settings :global(.field > label) {
font-size: var(--text-sm);
color: var(--ink-muted);
}
.settings :global(.field input),
.settings :global(.field select),
.settings :global(.field textarea) {
width: 100%;
padding: var(--s2) var(--s3);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
font-size: var(--text-sm);
outline: none;
transition: border-color var(--fast) var(--ease);
}
.settings :global(.field input:focus),
.settings :global(.field select:focus),
.settings :global(.field textarea:focus) {
border-color: var(--accent);
}
/* The field error sits under its own input rather than in a summary at the top:
the server answers with a map of field to message, and putting each one where
it belongs is the whole point of that shape. */
.settings :global(.field .error) {
margin: 0;
font-size: var(--text-xs);
color: var(--danger);
}
.settings :global(.field input[aria-invalid='true']) {
border-color: var(--danger);
}
.settings :global(.row) {
display: flex;
gap: var(--s3);
align-items: center;
flex-wrap: wrap;
}
.settings :global(button.primary) {
padding: var(--s2) var(--s4);
background: var(--accent);
color: var(--accent-ink);
border-radius: var(--radius);
font-size: var(--text-sm);
font-weight: 500;
transition: background var(--fast) var(--ease);
}
.settings :global(button.primary:hover) {
background: var(--accent-hover);
}
.settings :global(button.primary:disabled) {
opacity: 0.5;
cursor: default;
}
.settings :global(button.secondary) {
padding: var(--s2) var(--s4);
border: 1px solid var(--line-strong);
border-radius: var(--radius);
font-size: var(--text-sm);
color: var(--ink-muted);
transition:
color var(--fast) var(--ease),
border-color var(--fast) var(--ease);
}
.settings :global(button.secondary:hover) {
color: var(--ink);
border-color: var(--ink-faint);
}
.settings :global(button.danger) {
padding: var(--s2) var(--s4);
border: 1px solid var(--danger);
border-radius: var(--radius);
font-size: var(--text-sm);
color: var(--danger);
transition: background var(--fast) var(--ease);
}
.settings :global(button.danger:hover) {
background: var(--danger-sunken);
}
/* Saved-confirmations are deliberately quiet and inline. A toast for "saved"
would interrupt to say nothing went wrong. */
.settings :global(.saved) {
font-size: var(--text-sm);
color: var(--accent);
}
.settings :global(.list) {
display: flex;
flex-direction: column;
border: 1px solid var(--line);
border-radius: var(--radius);
overflow: hidden;
}
.settings :global(.list > li) {
display: flex;
align-items: center;
gap: var(--s3);
padding: var(--s3);
border-bottom: 1px solid var(--line);
}
.settings :global(.list > li:last-child) {
border-bottom: 0;
}
.settings :global(.mono) {
font-family: var(--font-mono);
font-size: var(--text-xs);
}
.settings :global(.empty) {
margin: 0;
font-size: var(--text-sm);
color: var(--ink-faint);
}
</style>
+369
View File
@@ -0,0 +1,369 @@
<script>
/** Konto: who you are, your password, and the second factor. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
// --- profile ---------------------------------------------------------------
let name = $state('');
let timezone = $state('');
let locale = $state('da');
let profileErrors = $state({});
let profileSaved = $state(false);
let savingProfile = $state(false);
let loaded = $state(false);
// Seeded once. Binding straight to app.user would overwrite what somebody is
// halfway through typing every time the store reloads.
$effect(() => {
if (loaded || !app.user) return;
name = app.user.name;
timezone = app.user.timezone;
locale = app.user.locale;
loaded = true;
});
// Whatever the browser knows, plus the current value in case it is not in the
// list — a server configured with a zone this browser has never heard of must
// not have it silently replaced on the next save.
let zones = $derived.by(() => {
let all = [];
try {
all = Intl.supportedValuesOf('timeZone');
} catch {
all = ['Europe/Copenhagen', 'Europe/London', 'UTC'];
}
return timezone && !all.includes(timezone) ? [timezone, ...all] : all;
});
async function saveProfile(event) {
event.preventDefault();
savingProfile = true;
profileErrors = {};
profileSaved = false;
try {
app.user = await api.updateProfile({ name, timezone, locale });
profileSaved = true;
} catch (e) {
profileErrors = e.fields ?? {};
if (!Object.keys(profileErrors).length) app.toast(humanMessage(e));
} finally {
savingProfile = false;
}
}
// --- password ---------------------------------------------------------------
let currentPassword = $state('');
let newPassword = $state('');
let passwordErrors = $state({});
let passwordSaved = $state(false);
async function changePassword(event) {
event.preventDefault();
passwordErrors = {};
passwordSaved = false;
try {
await api.changePassword(currentPassword, newPassword);
currentPassword = '';
newPassword = '';
passwordSaved = true;
} catch (e) {
passwordErrors = e.fields ?? {};
if (!Object.keys(passwordErrors).length) app.toast(humanMessage(e));
}
}
// --- two-factor --------------------------------------------------------------
let totpSecret = $state('');
let totpURI = $state('');
let totpCode = $state('');
let totpErrors = $state({});
let recoveryCodes = $state([]);
let remaining = $state(null);
let disablePassword = $state('');
$effect(() => {
if (app.user?.totp_enabled) {
api.recoveryCodes().then((r) => (remaining = r.remaining)).catch(() => {});
}
});
async function beginTOTP() {
try {
const r = await api.totpSetup();
totpSecret = r.secret;
totpURI = r.uri;
} catch (e) {
app.toast(humanMessage(e));
}
}
async function confirmTOTP(event) {
event.preventDefault();
totpErrors = {};
try {
const r = await api.totpConfirm(totpCode);
recoveryCodes = r.recovery_codes;
totpSecret = '';
totpURI = '';
totpCode = '';
app.user = await api.me();
} catch (e) {
totpErrors = e.fields ?? {};
if (!Object.keys(totpErrors).length) app.toast(humanMessage(e));
}
}
async function disableTOTP(event) {
event.preventDefault();
totpErrors = {};
try {
await api.totpDisable(disablePassword);
disablePassword = '';
recoveryCodes = [];
remaining = null;
app.user = await api.me();
} catch (e) {
totpErrors = e.fields ?? {};
if (!Object.keys(totpErrors).length) app.toast(humanMessage(e));
}
}
async function regenerate(event) {
event.preventDefault();
totpErrors = {};
try {
const r = await api.regenerateRecoveryCodes(disablePassword);
recoveryCodes = r.recovery_codes;
remaining = r.recovery_codes.length;
disablePassword = '';
} catch (e) {
totpErrors = e.fields ?? {};
if (!Object.keys(totpErrors).length) app.toast(humanMessage(e));
}
}
</script>
<section class="panel">
<header>
<h2>Profil</h2>
<p class="hint">
Tidszonen er ikke pynt: alle datoer i appen bliver afgjort i den, så
&ldquo;i morgen kl. 9&rdquo; betyder noget andet, når du skifter den.
</p>
</header>
<form onsubmit={saveProfile}>
<div class="field">
<label for="name">Navn</label>
<input
id="name"
bind:value={name}
aria-invalid={profileErrors.name ? 'true' : undefined}
/>
{#if profileErrors.name}<p class="error">{profileErrors.name}</p>{/if}
</div>
<div class="field">
<label for="email">E-mail</label>
<!-- Read-only: the address identifies the account and is what invitations
were sent to. Changing it is a re-verification flow, not a field. -->
<input id="email" value={app.user?.email ?? ''} readonly disabled />
<p class="hint">Kan ikke ændres her.</p>
</div>
<div class="field">
<label for="timezone">Tidszone</label>
<select id="timezone" bind:value={timezone}>
{#each zones as zone (zone)}
<option value={zone}>{zone}</option>
{/each}
</select>
{#if profileErrors.timezone}<p class="error">{profileErrors.timezone}</p>{/if}
</div>
<div class="field">
<label for="locale">Sprog i hurtig tilføjelse</label>
<select id="locale" bind:value={locale}>
<option value="da">Dansk</option>
<option value="en">English</option>
</select>
<p class="hint">
Afgør hvilken grammatik der tolker en linje — &ldquo;hver mandag&rdquo;
eller &ldquo;every monday&rdquo;.
</p>
{#if profileErrors.locale}<p class="error">{profileErrors.locale}</p>{/if}
</div>
<div class="row">
<button class="primary" type="submit" disabled={savingProfile}>Gem</button>
{#if profileSaved}<span class="saved">Gemt.</span>{/if}
</div>
</form>
</section>
<section class="panel">
<header>
<h2>Adgangskode</h2>
<p class="hint">
At skifte den logger alle andre sessioner ud — hvilket for det meste er
grunden til at gøre det.
</p>
</header>
<form onsubmit={changePassword}>
<div class="field">
<label for="current">Nuværende adgangskode</label>
<input
id="current"
type="password"
autocomplete="current-password"
bind:value={currentPassword}
aria-invalid={passwordErrors.current_password ? 'true' : undefined}
/>
{#if passwordErrors.current_password}
<p class="error">{passwordErrors.current_password}</p>
{/if}
</div>
<div class="field">
<label for="new">Ny adgangskode</label>
<input
id="new"
type="password"
autocomplete="new-password"
bind:value={newPassword}
aria-invalid={passwordErrors.new_password ? 'true' : undefined}
/>
{#if passwordErrors.new_password}<p class="error">{passwordErrors.new_password}</p>{/if}
</div>
<div class="row">
<button class="primary" type="submit">Skift adgangskode</button>
{#if passwordSaved}<span class="saved">Skiftet.</span>{/if}
</div>
</form>
</section>
<section class="panel">
<header>
<h2>To-faktor</h2>
<p class="hint">En engangskode fra en authenticator-app oven i adgangskoden.</p>
</header>
{#if recoveryCodes.length}
<!-- Shown once, and the interface has to say so: only the hashes are kept,
so there is no later screen that could show them again. -->
<div class="field">
<p class="hint">
<strong>Skriv dem ned nu.</strong> De vises kun denne ene gang — serveren
har kun deres hash.
</p>
<ul class="codes mono">
{#each recoveryCodes as code (code)}
<li>{code}</li>
{/each}
</ul>
<div class="row">
<button class="secondary" onclick={() => (recoveryCodes = [])}>Jeg har dem</button>
</div>
</div>
{:else if app.user?.totp_enabled}
<p class="hint">
Slået til.{#if remaining !== null}
{remaining} gendannelseskode{remaining === 1 ? '' : 'r'} tilbage.{/if}
</p>
<form onsubmit={disableTOTP}>
<div class="field">
<label for="disable-pw">Adgangskode</label>
<input
id="disable-pw"
type="password"
autocomplete="current-password"
bind:value={disablePassword}
aria-invalid={totpErrors.password ? 'true' : undefined}
/>
{#if totpErrors.password}<p class="error">{totpErrors.password}</p>{/if}
<p class="hint">
Kræves til begge handlinger nedenfor. At slå to-faktor fra er præcis
det, en fremmed med din session ville gøre først.
</p>
</div>
<div class="row">
<button class="secondary" onclick={regenerate}>Nye gendannelseskoder</button>
<button class="danger" type="submit">Slå to-faktor fra</button>
</div>
</form>
{:else if totpSecret}
<div class="field">
<p class="hint">Scan i din authenticator-app, eller indtast nøglen manuelt.</p>
<p class="mono secret">{totpSecret}</p>
<p class="hint mono uri">{totpURI}</p>
</div>
<form onsubmit={confirmTOTP}>
<div class="field">
<label for="totp">Koden fra appen</label>
<input
id="totp"
bind:value={totpCode}
inputmode="numeric"
autocomplete="one-time-code"
aria-invalid={totpErrors.code ? 'true' : undefined}
/>
{#if totpErrors.code}<p class="error">{totpErrors.code}</p>{/if}
<p class="hint">
To-faktor er først slået til, når en kode har bevist, at appen faktisk
har nøglen.
</p>
</div>
<div class="row">
<button class="primary" type="submit">Bekræft</button>
<button class="secondary" onclick={() => (totpSecret = '')}>Fortryd</button>
</div>
</form>
{:else}
<div class="row">
<button class="primary" onclick={beginTOTP}>Slå to-faktor til</button>
</div>
{/if}
</section>
<style>
form {
display: flex;
flex-direction: column;
gap: var(--s4);
}
.codes {
list-style: none;
margin: 0;
padding: var(--s3);
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: var(--s2);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.secret {
margin: 0;
padding: var(--s3);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
letter-spacing: 0.08em;
overflow-wrap: anywhere;
}
.uri {
overflow-wrap: anywhere;
}
</style>
@@ -0,0 +1,188 @@
<script>
/** The AI provider: which one, which model, and the key. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
let settings = $state(null);
let apiKey = $state('');
let saving = $state(false);
let saved = $state(false);
let errors = $state({});
let summary = $state('');
let summarising = $state(false);
const PROVIDERS = [
{ value: '', label: 'Slået fra' },
{ value: 'anthropic', label: 'Anthropic' },
{ value: 'openai', label: 'OpenAI' },
{ value: 'google', label: 'Google' },
{ value: 'compatible', label: 'OpenAI-kompatibel (Ollama, LM Studio, …)' }
];
// Suggestions, not a closed list: the model field is free text, because a new
// model name must not require a new release of this app to be usable.
const SUGGESTED_MODEL = {
anthropic: 'claude-sonnet-5',
openai: 'gpt-5',
google: 'gemini-2.5-pro',
compatible: 'llama3.1'
};
$effect(() => {
api
.getAISettings()
.then((s) => (settings = s))
.catch((e) => app.toast(humanMessage(e)));
});
async function save(event) {
event.preventDefault();
saving = true;
saved = false;
errors = {};
try {
await api.setAISettings({
provider: settings.provider,
base_url: settings.base_url ?? '',
model: settings.model ?? '',
// An empty key means "leave the stored one alone" on the server. That
// is why this field starts empty rather than pre-filled with dots.
api_key: apiKey
});
apiKey = '';
settings = await api.getAISettings();
saved = true;
} catch (e) {
errors = e.fields ?? {};
if (!Object.keys(errors).length) app.toast(humanMessage(e));
} finally {
saving = false;
}
}
async function weeklySummary() {
summarising = true;
summary = '';
try {
summary = (await api.aiSummary()).summary;
} catch (e) {
app.toast(humanMessage(e));
} finally {
summarising = false;
}
}
</script>
<section class="panel">
<header>
<h2>AI</h2>
<p class="hint">
Bruges to steder: at dele en opgave op i undertasks, og at skrive et kort
overblik over det, der er udestående. Nøglen ligger på din server og sendes
kun til den udbyder, du vælger her.
</p>
</header>
{#if settings === null}
<p class="empty">…</p>
{:else}
<form onsubmit={save}>
<div class="field">
<label for="provider">Udbyder</label>
<select id="provider" bind:value={settings.provider}>
{#each PROVIDERS as provider (provider.value)}
<option value={provider.value}>{provider.label}</option>
{/each}
</select>
{#if errors.provider}<p class="error">{errors.provider}</p>{/if}
</div>
{#if settings.provider}
<div class="field">
<label for="model">Model</label>
<input
id="model"
bind:value={settings.model}
placeholder={SUGGESTED_MODEL[settings.provider] ?? ''}
/>
</div>
{#if settings.provider === 'compatible'}
<div class="field">
<label for="base">Adresse</label>
<input
id="base"
class="mono"
bind:value={settings.base_url}
placeholder="http://localhost:11434/v1"
/>
</div>
{/if}
<div class="field">
<label for="key">API-nøgle</label>
<input
id="key"
type="password"
autocomplete="off"
bind:value={apiKey}
placeholder={settings.has_key ? 'Der er gemt en nøgle — lad feltet stå tomt' : ''}
/>
<p class="hint">
{#if settings.has_key}
Feltet er tomt med vilje. Nøglen sendes aldrig tilbage til browseren
— en indstillingsside, der fylder et kodeordsfelt ud igen, er en side,
der en dag lækker en nøgle ud i et skærmbillede.
{:else}
Gemmes på serveren og vises aldrig igen.
{/if}
</p>
</div>
{/if}
<div class="row">
<button class="primary" type="submit" disabled={saving}>Gem</button>
{#if saved}<span class="saved">Gemt.</span>{/if}
</div>
</form>
{/if}
</section>
{#if settings?.provider && settings?.has_key}
<section class="panel">
<header>
<h2>Ugentligt overblik</h2>
<p class="hint">En kort note om, hvad der ser vigtigst ud lige nu.</p>
</header>
<div class="row">
<button class="secondary" onclick={weeklySummary} disabled={summarising}>
{summarising ? 'Skriver …' : 'Skriv et overblik'}
</button>
</div>
{#if summary}
<p class="summary">{summary}</p>
{/if}
</section>
{/if}
<style>
form {
display: flex;
flex-direction: column;
gap: var(--s4);
}
.summary {
margin: 0;
padding: var(--s4);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
font-size: var(--text-sm);
line-height: 1.6;
white-space: pre-wrap;
}
</style>
@@ -0,0 +1,340 @@
<script>
/** Import, export and project templates. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
import { goto } from '$app/navigation';
// --- Todoist import ------------------------------------------------------------
let importing = $state(false);
let result = $state(null);
async function importTodoist(event) {
const file = event.target.files?.[0];
if (!file) return;
event.target.value = ''; // so the same file can be picked twice after a failure
importing = true;
result = null;
try {
result = await api.importTodoist(file);
await app.refreshProjects();
} catch (e) {
app.toast(e.fields?.file ?? humanMessage(e));
} finally {
importing = false;
}
}
// --- templates --------------------------------------------------------------
let templates = $state([]);
let loadingTemplates = $state(true);
let saveFrom = $state('');
let templateName = $state('');
let savingTemplate = $state(false);
let usingId = $state('');
let newProjectName = $state('');
let startDate = $state('');
$effect(() => {
api
.listTemplates()
.then((r) => (templates = r.templates))
.catch((e) => app.toast(humanMessage(e)))
.finally(() => (loadingTemplates = false));
});
let projects = $derived(app.projects.filter((p) => !p.is_inbox));
async function saveTemplate(event) {
event.preventDefault();
if (!saveFrom) return;
savingTemplate = true;
try {
const created = await api.saveTemplate({
project_id: saveFrom,
name: templateName.trim() || app.projectById(saveFrom)?.name || 'Skabelon',
description: ''
});
templates = [created, ...templates];
saveFrom = '';
templateName = '';
} catch (e) {
app.toast(humanMessage(e));
} finally {
savingTemplate = false;
}
}
async function useTemplate(event) {
event.preventDefault();
if (!usingId) return;
try {
const project = await api.useTemplate(usingId, {
name: newProjectName.trim(),
start_date: startDate
});
await app.refreshProjects();
usingId = '';
newProjectName = '';
startDate = '';
goto(`/projekt/${project.id}`);
} catch (e) {
app.toast(e.fields?.start_date ?? humanMessage(e));
}
}
async function deleteTemplate(template) {
if (!confirm(`Slet skabelonen "${template.name}"?`)) return;
const previous = templates;
templates = templates.filter((t) => t.id !== template.id);
try {
await api.deleteTemplate(template.id);
} catch (e) {
templates = previous;
app.toast(humanMessage(e));
}
}
let exportProject = $state('');
</script>
<section class="panel">
<header>
<h2>Importér fra Todoist</h2>
<p class="hint">
Vælg CSV-eksporten af ét projekt. Prioriteterne bliver konverteret, ikke
kopieret: Todoist skriver 4 for det, grænsefladen kalder P1.
</p>
</header>
<div class="field">
<label for="todoist">CSV-fil</label>
<input id="todoist" type="file" accept=".csv,text/csv" onchange={importTodoist} disabled={importing} />
</div>
{#if importing}
<p class="hint">Importerer …</p>
{/if}
{#if result}
<div class="result">
<p class="hint">
{result.tasks} opgave{result.tasks === 1 ? '' : 'r'}, {result.sections}
sektion{result.sections === 1 ? '' : 'er'} og {result.comments}
kommentar{result.comments === 1 ? '' : 'er'} hentet ind.
</p>
{#if result.warnings?.length}
<!-- Reported rather than silently dropped: a partial import that says
nothing is discovered weeks later. -->
<ul class="warnings">
{#each result.warnings as warning, i (i)}
<li>{warning}</li>
{/each}
</ul>
{/if}
{#if result.project_id}
<div class="row">
<a class="link" href="/projekt/{result.project_id}">Åbn projektet</a>
</div>
{/if}
</div>
{/if}
</section>
<section class="panel">
<header>
<h2>Eksport</h2>
<p class="hint">
Alt, i den rå form. Det er garantien for, at du kan gå igen — en
eksport, der er blevet pyntet, er en eksport, der har mistet noget.
</p>
</header>
<div class="row">
<!-- Plain links, not fetch: the browser's own download handling knows what to
do with a Content-Disposition, and the session cookie rides along. -->
<a class="link" href={api.exportAccountURL()} download>Hele kontoen som JSON</a>
</div>
<div class="field">
<label for="export-project">Ét projekt</label>
<select id="export-project" bind:value={exportProject}>
<option value="">Vælg et projekt</option>
{#each app.projects as project (project.id)}
<option value={project.id}>{project.name}</option>
{/each}
</select>
</div>
{#if exportProject}
<div class="row">
<a class="link" href={api.exportProjectCSVURL(exportProject)} download>CSV</a>
<a class="link" href={api.exportProjectICSURL(exportProject)} download>Kalenderfil</a>
</div>
{/if}
</section>
<section class="panel">
<header>
<h2>Skabeloner</h2>
<p class="hint">
Et projekt gemt som en form, der kan bruges igen. Datoerne i skabelonen er
relative, så de bliver regnet ud fra den startdato, du vælger.
</p>
</header>
<form onsubmit={saveTemplate}>
<div class="field">
<label for="save-from">Gem et projekt som skabelon</label>
<select id="save-from" bind:value={saveFrom}>
<option value="">Vælg et projekt</option>
{#each projects as project (project.id)}
<option value={project.id}>{project.name}</option>
{/each}
</select>
</div>
{#if saveFrom}
<div class="field">
<label for="template-name">Navn på skabelonen</label>
<input
id="template-name"
bind:value={templateName}
placeholder={app.projectById(saveFrom)?.name ?? ''}
/>
</div>
<div class="row">
<button class="primary" type="submit" disabled={savingTemplate}>Gem som skabelon</button>
</div>
{/if}
</form>
{#if loadingTemplates}
<p class="empty">…</p>
{:else if templates.length === 0}
<p class="empty">Ingen skabeloner endnu.</p>
{:else}
<ul class="list">
{#each templates as template (template.id)}
<li>
<div class="what">
<span class="title">{template.name}</span>
<span class="meta">
{template.task_count} opgave{template.task_count === 1 ? '' : 'r'}
</span>
</div>
<button class="use" onclick={() => (usingId = usingId === template.id ? '' : template.id)}>
Brug
</button>
<button class="remove" onclick={() => deleteTemplate(template)}>Slet</button>
</li>
{#if usingId === template.id}
<li class="use-form">
<form onsubmit={useTemplate}>
<div class="field">
<label for="new-name">Navn på det nye projekt</label>
<input id="new-name" bind:value={newProjectName} placeholder={template.name} />
</div>
<div class="field">
<label for="start">Startdato</label>
<input id="start" type="date" bind:value={startDate} />
<p class="hint">Dag nul for skabelonens datoer. Tom betyder i dag.</p>
</div>
<div class="row">
<button class="primary" type="submit">Opret projektet</button>
</div>
</form>
</li>
{/if}
{/each}
</ul>
{/if}
</section>
<style>
form {
display: flex;
flex-direction: column;
gap: var(--s4);
}
.result {
display: flex;
flex-direction: column;
gap: var(--s2);
padding: var(--s4);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.warnings {
margin: 0;
padding-left: var(--s5);
font-size: var(--text-sm);
color: var(--ink-muted);
}
.what {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.title {
font-size: var(--text-sm);
}
.meta {
font-size: var(--text-xs);
color: var(--ink-faint);
}
.use,
.remove {
flex: none;
font-size: var(--text-xs);
padding: var(--s1) var(--s2);
border-radius: var(--radius-sm);
color: var(--ink-faint);
transition: color var(--fast) var(--ease);
}
.use:hover {
color: var(--accent);
}
.remove:hover {
color: var(--danger);
background: var(--danger-sunken);
}
.use-form {
background: var(--surface-sunken);
}
.use-form form {
width: 100%;
}
.link {
font-size: var(--text-sm);
color: var(--accent);
text-decoration: none;
}
.link:hover {
text-decoration: underline;
}
</style>
@@ -0,0 +1,281 @@
<script>
/** Gmail, the calendar feed, and the mail-to-task address. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
import { page } from '$app/stores';
// --- Gmail ------------------------------------------------------------------
let gmail = $state(null);
let savingGmail = $state(false);
let gmailSaved = $state(false);
let syncing = $state(false);
/**
* What the OAuth callback redirected back with. It arrives as a query parameter
* because the callback is a top-level navigation from Google — there is no fetch
* whose response could have carried it.
*/
const CALLBACK = {
connected: { tone: 'ok', text: 'Gmail er forbundet.' },
state: {
tone: 'bad',
text: 'Svaret fra Google passede ikke til det forsøg, der blev startet her. Prøv igen.'
},
expired: { tone: 'bad', text: 'Forsøget udløb undervejs. Prøv igen.' },
invalid: { tone: 'bad', text: 'Svaret fra Google kunne ikke læses. Prøv igen.' },
failed: { tone: 'bad', text: 'Google afviste ombytningen af koden.' },
norefresh: {
tone: 'bad',
text: 'Google sendte ingen refresh-token. Fjern verdande under din Google-konto og forbind igen.'
},
access_denied: { tone: 'bad', text: 'Adgangen blev afvist hos Google.' }
};
let callback = $derived.by(() => {
const value = $page.url.searchParams.get('gmail');
if (!value) return null;
return CALLBACK[value] ?? { tone: 'bad', text: `Gmail svarede: ${value}` };
});
$effect(() => {
api
.getGmail()
.then((g) => (gmail = g))
.catch((e) => app.toast(humanMessage(e)));
});
async function connect() {
try {
const { url } = await api.authorizeGmail();
location.href = url;
} catch (e) {
app.toast(humanMessage(e));
}
}
async function saveGmail(event) {
event.preventDefault();
savingGmail = true;
gmailSaved = false;
try {
await api.setGmail({ trigger: gmail.trigger, label: gmail.label ?? '' });
gmailSaved = true;
} catch (e) {
app.toast(humanMessage(e));
} finally {
savingGmail = false;
}
}
async function syncNow() {
syncing = true;
try {
const result = await api.syncGmail();
app.toast(
result?.created ? `${result.created} opgave(r) hentet.` : 'Ingen nye beskeder.'
);
} catch (e) {
app.toast(humanMessage(e));
} finally {
syncing = false;
}
}
async function disconnectGmail() {
if (!confirm('Afbryd forbindelsen til Gmail? Tokens bliver glemt.')) return;
try {
await api.disconnectGmail();
gmail = await api.getGmail();
} catch (e) {
app.toast(humanMessage(e));
}
}
// --- calendar feed -------------------------------------------------------------
let feedURL = $state('');
let mailAddress = $state('');
$effect(() => {
api.feed().then((r) => (feedURL = r.url)).catch(() => {});
api.getMailAddress().then((r) => (mailAddress = r.address)).catch(() => {});
});
async function rotateFeed() {
if (!confirm('Nyt feed-link? Alle eksisterende abonnementer holder op med at virke.')) return;
try {
feedURL = (await api.rotateFeed()).url;
} catch (e) {
app.toast(humanMessage(e));
}
}
async function rotateMail() {
if (!confirm('Ny adresse? Mail til den gamle bliver afvist.')) return;
try {
mailAddress = (await api.rotateMailAddress()).address;
} catch (e) {
app.toast(humanMessage(e));
}
}
async function copy(text) {
try {
await navigator.clipboard.writeText(text);
app.toast('Kopieret.');
} catch {
app.toast('Kunne ikke kopiere — markér teksten i stedet.');
}
}
</script>
<section class="panel">
<header>
<h2>Gmail</h2>
<p class="hint">
Stjernemarkér en mail, eller giv den en etiket, og den bliver en opgave.
Envejs: at fjerne stjernen gør ikke noget ved opgaven.
</p>
</header>
{#if callback}
<p class="callback" data-tone={callback.tone}>{callback.text}</p>
{/if}
{#if gmail === null}
<p class="empty">…</p>
{:else if !gmail.connected}
<div class="row">
<button class="primary" onclick={connect}>Forbind Gmail</button>
</div>
<p class="hint">
Kræver at administratoren har registreret en OAuth-klient hos Google og sat
<span class="mono">VERDANDE_GMAIL_CLIENT_ID</span> og
<span class="mono">_SECRET</span>.
</p>
{:else}
<p class="hint">Forbundet som <strong>{gmail.email || 'ukendt konto'}</strong>.</p>
<form onsubmit={saveGmail}>
<div class="field">
<label for="trigger">Hvad laver en opgave</label>
<select id="trigger" bind:value={gmail.trigger}>
<option value="starred">Stjernemarkerede</option>
<option value="label">En bestemt etiket</option>
<option value="both">Begge dele</option>
</select>
</div>
{#if gmail.trigger === 'label' || gmail.trigger === 'both'}
<div class="field">
<label for="gmail-label">Etikettens navn i Gmail</label>
<input id="gmail-label" bind:value={gmail.label} placeholder="fx Opgaver" />
</div>
{/if}
<div class="row">
<button class="primary" type="submit" disabled={savingGmail}>Gem</button>
{#if gmailSaved}<span class="saved">Gemt.</span>{/if}
<button class="secondary" onclick={syncNow} disabled={syncing}>Hent nu</button>
<button class="danger" onclick={disconnectGmail}>Afbryd</button>
</div>
</form>
{/if}
</section>
<section class="panel">
<header>
<h2>Kalenderfeed</h2>
<p class="hint">
Abonnér i Apple Kalender, Google eller Thunderbird. En kalenderklient kan
ikke logge ind, så nøglen i adressen <em>er</em> hele adgangskoden — del den
ikke.
</p>
</header>
<div class="field">
<label for="feed">Adresse</label>
<input id="feed" class="mono" value={feedURL} readonly />
</div>
<div class="row">
<button class="secondary" onclick={() => copy(feedURL)}>Kopiér</button>
<button class="danger" onclick={rotateFeed}>Nyt link</button>
</div>
<p class="hint">
Et nyt link bryder alle eksisterende abonnementer med det samme. Det er
pointen: det er det, man gør, når det gamle er havnet et forkert sted.
</p>
</section>
<section class="panel">
<header>
<h2>Mail til opgave</h2>
<p class="hint">
Send eller videresend en mail hertil, og emnelinjen bliver tolket som en
hurtig tilføjelse — &ldquo;Fakturer Anders p1 #Firma&rdquo; virker også her.
</p>
</header>
<div class="field">
<label for="mail">Din adresse</label>
<input id="mail" class="mono" value={mailAddress} readonly />
</div>
<div class="row">
<button class="secondary" onclick={() => copy(mailAddress)}>Kopiér</button>
<button class="danger" onclick={rotateMail}>Ny adresse</button>
</div>
</section>
<section class="panel">
<header>
<h2>CalDAV</h2>
<p class="hint">
Tovejs, i modsætning til feedet ovenfor: Apple Påmindelser og Thunderbird
kan også skrive tilbage.
</p>
</header>
<div class="field">
<label for="caldav">Server</label>
<input id="caldav" class="mono" value={`${location.origin}/caldav/`} readonly />
<p class="hint">
Brugernavn er din e-mail. Adgangskoden er en
<a href="/indstillinger/tokens">API-token</a> — ikke din rigtige adgangskode.
</p>
</div>
</section>
<style>
form {
display: flex;
flex-direction: column;
gap: var(--s4);
}
.callback {
margin: 0;
padding: var(--s3);
border-radius: var(--radius);
font-size: var(--text-sm);
border: 1px solid;
}
.callback[data-tone='ok'] {
color: var(--accent);
background: var(--accent-sunken);
border-color: var(--accent);
}
.callback[data-tone='bad'] {
color: var(--danger);
background: var(--danger-sunken);
border-color: var(--danger);
}
a {
color: var(--accent);
}
</style>
@@ -0,0 +1,256 @@
<script>
/** Notifications: what has happened, and whether the browser should tell you. */
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
import * as push from '$lib/push.js';
// --- web push ----------------------------------------------------------------
let pushState = $state('loading');
let busy = $state(false);
$effect(() => {
if (!push.supported()) {
pushState = 'unsupported';
return;
}
if (push.permission() === 'denied') {
pushState = 'blocked';
return;
}
push.current().then((sub) => (pushState = sub ? 'on' : 'off'));
});
async function enablePush() {
busy = true;
try {
await push.subscribe();
pushState = 'on';
} catch (e) {
app.toast(e.message ?? humanMessage(e));
if (push.permission() === 'denied') pushState = 'blocked';
} finally {
busy = false;
}
}
async function disablePush() {
busy = true;
try {
await push.unsubscribe();
pushState = 'off';
} catch (e) {
app.toast(e.message ?? humanMessage(e));
} finally {
busy = false;
}
}
// --- the list -----------------------------------------------------------------
let notifications = $state([]);
let unread = $state(0);
let loading = $state(true);
$effect(() => {
api
.listNotifications()
.then((r) => {
notifications = r.notifications;
unread = r.unread;
})
.catch((e) => app.toast(humanMessage(e)))
.finally(() => (loading = false));
});
async function markAllRead() {
const previous = notifications;
notifications = notifications.map((n) => ({ ...n, read: true }));
unread = 0;
try {
await api.markNotificationsRead();
} catch (e) {
notifications = previous;
app.toast(humanMessage(e));
}
}
function when(iso) {
const then = new Date(iso);
const minutes = Math.round((Date.now() - then) / 60000);
if (minutes < 1) return 'lige nu';
if (minutes < 60) return `${minutes} min. siden`;
if (minutes < 60 * 24) return `${Math.round(minutes / 60)} t. siden`;
return then.toLocaleDateString('da-DK', { day: 'numeric', month: 'short' });
}
// --- version ------------------------------------------------------------------
let version = $state(null);
$effect(() => {
api.version().then((v) => (version = v)).catch(() => {});
});
</script>
<section class="panel">
<header>
<h2>Notifikationer på enheden</h2>
<p class="hint">
Påmindelser og beskeder fra andre, også når fanen er lukket. Beskeden
krypteres til din browser undervejs — push-tjenesten kan ikke læse den.
</p>
</header>
{#if pushState === 'loading'}
<p class="empty">…</p>
{:else if pushState === 'unsupported'}
<p class="hint">
Denne browser understøtter det ikke. Safari kræver, at appen er lagt på
hjemmeskærmen; over almindelig HTTP virker det kun på localhost.
</p>
{:else if pushState === 'blocked'}
<p class="hint">
Browseren har blokeret notifikationer for dette site. Det kan kun laves om i
browserens egne indstillinger — en side kan ikke spørge igen, når svaret har
været nej.
</p>
{:else if pushState === 'on'}
<p class="hint">Slået til på denne enhed.</p>
<div class="row">
<button class="secondary" onclick={disablePush} disabled={busy}>Slå fra</button>
</div>
{:else}
<div class="row">
<button class="primary" onclick={enablePush} disabled={busy}>
Slå til på denne enhed
</button>
</div>
<p class="hint">Gælder kun den browser, du sidder i nu.</p>
{/if}
</section>
<section class="panel">
<header>
<h2>Seneste</h2>
{#if unread > 0}
<p class="hint">{unread} ulæst{unread === 1 ? '' : 'e'}.</p>
{/if}
</header>
{#if loading}
<p class="empty">…</p>
{:else if notifications.length === 0}
<p class="empty">Ingenting endnu.</p>
{:else}
<ul class="list">
{#each notifications as note (note.id)}
<li class:unread={!note.read}>
<div class="what">
<span class="title">{note.title}</span>
{#if note.body}<span class="body">{note.body}</span>{/if}
<span class="meta">
{#if note.actor_name}{note.actor_name} · {/if}{when(note.created_at)}
</span>
</div>
{#if note.task_id && note.project_id}
<a class="go" href="/projekt/{note.project_id}">Åbn</a>
{/if}
</li>
{/each}
</ul>
{#if unread > 0}
<div class="row">
<button class="secondary" onclick={markAllRead}>Markér alle som læst</button>
</div>
{/if}
{/if}
</section>
{#if version}
<section class="panel">
<header>
<h2>Version</h2>
</header>
<p class="hint">
Kører <span class="mono">{version.current}</span>.
{#if version.disabled}
Der bliver ikke set efter opdateringer.
{:else if version.update_available}
<strong>{version.latest} er ude.</strong>
{:else if version.checked_at}
Ingen nyere version fundet.
{/if}
</p>
{#if version.update_available}
{#if version.notes}
<p class="notes">{version.notes}</p>
{/if}
{#if version.url}
<div class="row">
<a class="release" href={version.url} target="_blank" rel="noreferrer noopener">
Se udgivelsen
</a>
</div>
{/if}
{/if}
</section>
{/if}
<style>
.what {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.title {
font-size: var(--text-sm);
overflow-wrap: anywhere;
}
.body {
font-size: var(--text-sm);
color: var(--ink-muted);
overflow-wrap: anywhere;
}
.meta {
font-size: var(--text-xs);
color: var(--ink-faint);
}
/* An accent bar rather than a bold row: the list is read top to bottom, and
weight changes make it look ragged. */
li.unread {
border-left: 2px solid var(--accent);
}
.go,
.release {
flex: none;
font-size: var(--text-xs);
color: var(--accent);
text-decoration: none;
}
.release {
font-size: var(--text-sm);
}
.notes {
margin: 0;
padding: var(--s3);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
font-size: var(--text-sm);
white-space: pre-wrap;
line-height: 1.6;
}
</style>
@@ -0,0 +1,227 @@
<script>
/**
* Personal API tokens.
*
* The one screen in the app that shows a secret. It is shown exactly once, and
* the copy has to say so — the server keeps a hash, so there is no later screen
* that could reveal it even if this one offered to.
*/
import { api, humanMessage } from '$lib/api.js';
import { app } from '$lib/stores.svelte.js';
let tokens = $state([]);
let loading = $state(true);
let name = $state('');
let expiresInDays = $state(0);
let errors = $state({});
let creating = $state(false);
/** The plaintext of the token just minted. Held only in this variable. */
let fresh = $state(null);
let copied = $state(false);
$effect(() => {
api
.listTokens()
.then((r) => (tokens = r.tokens))
.catch((e) => app.toast(humanMessage(e)))
.finally(() => (loading = false));
});
async function create(event) {
event.preventDefault();
errors = {};
creating = true;
try {
const created = await api.createToken(name.trim(), Number(expiresInDays));
fresh = created;
copied = false;
name = '';
expiresInDays = 0;
tokens = [{ ...created, token: undefined }, ...tokens];
} catch (e) {
errors = e.fields ?? {};
if (!Object.keys(errors).length) app.toast(humanMessage(e));
} finally {
creating = false;
}
}
async function copy() {
try {
await navigator.clipboard.writeText(fresh.token);
copied = true;
} catch {
// Insecure context, or permission refused. The token is on screen and
// selectable, so this is a convenience that failed, not the feature.
app.toast('Kunne ikke kopiere — markér teksten i stedet.');
}
}
async function revoke(token) {
if (!confirm(`Tilbagekald "${token.name}"? Alt, der bruger den, holder op med at virke.`))
return;
const previous = tokens;
tokens = tokens.filter((t) => t.id !== token.id);
try {
await api.deleteToken(token.id);
} catch (e) {
tokens = previous;
app.toast(humanMessage(e));
}
}
const date = (iso) =>
iso ? new Date(iso).toLocaleDateString('da-DK', { day: 'numeric', month: 'short', year: 'numeric' }) : null;
const expired = (iso) => iso && new Date(iso) < new Date();
</script>
<section class="panel">
<header>
<h2>API-tokens</h2>
<p class="hint">
Det, et script, en CalDAV-klient eller en MCP-forbindelse logger ind med. En
token bærer dine rettigheder præcist — den kan intet, du ikke selv kan.
</p>
</header>
{#if fresh}
<div class="fresh">
<p class="hint">
<strong>Kopiér den nu.</strong> Den vises kun denne ene gang — serveren har
kun dens hash.
</p>
<p class="mono value">{fresh.token}</p>
<div class="row">
<button class="primary" onclick={copy}>Kopiér</button>
{#if copied}<span class="saved">Kopieret.</span>{/if}
<button class="secondary" onclick={() => (fresh = null)}>Færdig</button>
</div>
</div>
{/if}
<form onsubmit={create}>
<div class="field">
<label for="token-name">Navn</label>
<input
id="token-name"
bind:value={name}
placeholder="fx min bærbare, eller backup-scriptet"
aria-invalid={errors.name ? 'true' : undefined}
/>
{#if errors.name}<p class="error">{errors.name}</p>{/if}
</div>
<div class="field">
<label for="token-expiry">Udløber</label>
<select id="token-expiry" bind:value={expiresInDays}>
<option value={0}>Aldrig</option>
<option value={30}>Om 30 dage</option>
<option value={90}>Om 90 dage</option>
<option value={365}>Om et år</option>
</select>
<p class="hint">
En kalenderklient, der har abonneret i årevis, har brug for
&ldquo;aldrig&rdquo;. Et script, du kører én gang, har ikke.
</p>
{#if errors.expires_in_days}<p class="error">{errors.expires_in_days}</p>{/if}
</div>
<div class="row">
<button class="primary" type="submit" disabled={creating}>Lav en token</button>
</div>
</form>
{#if loading}
<p class="empty">…</p>
{:else if tokens.length === 0}
<p class="empty">Ingen tokens endnu.</p>
{:else}
<ul class="list">
{#each tokens as token (token.id)}
<li>
<div class="what">
<span class="token-name">{token.name}</span>
<span class="meta mono">
{token.prefix}…
{#if token.last_used_at}
· sidst brugt {date(token.last_used_at)}
{:else}
· aldrig brugt
{/if}
{#if token.expires_at}
· {expired(token.expires_at) ? 'udløbet' : 'udløber'}
{date(token.expires_at)}
{/if}
</span>
</div>
<button class="revoke" onclick={() => revoke(token)} aria-label="Tilbagekald {token.name}">
Tilbagekald
</button>
</li>
{/each}
</ul>
{/if}
</section>
<style>
form {
display: flex;
flex-direction: column;
gap: var(--s4);
}
.fresh {
display: flex;
flex-direction: column;
gap: var(--s3);
padding: var(--s4);
background: var(--accent-sunken);
border: 1px solid var(--accent);
border-radius: var(--radius);
}
.value {
margin: 0;
padding: var(--s3);
background: var(--surface-sunken);
border: 1px solid var(--line);
border-radius: var(--radius);
overflow-wrap: anywhere;
user-select: all;
}
.what {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
flex: 1;
}
.token-name {
font-size: var(--text-sm);
overflow-wrap: anywhere;
}
.meta {
color: var(--ink-faint);
}
.revoke {
flex: none;
font-size: var(--text-xs);
color: var(--ink-faint);
padding: var(--s1) var(--s2);
border-radius: var(--radius-sm);
transition: color var(--fast) var(--ease);
}
.revoke:hover {
color: var(--danger);
background: var(--danger-sunken);
}
</style>