Add read-only mail view
CI / build (push) Successful in 14s

Thread-grouped list, thread view with older messages collapsed, and
keyboard navigation (j/k, Enter/o, u/Esc, g/G, r, ?). Mutating shortcuts
are deliberately absent until the endpoints behind them exist.

Untrusted mail renders in an iframe sandboxed without allow-scripts or
allow-same-origin, with a CSP inside the frame doing the actual blocking
of remote loads. CSP rather than rewriting <img src> because rewriting
misses srcset, <picture>, CSS background-image and @font-face; img-src
covers every image load however it was requested. Remote images stay
blocked per message until the reader opts in.

Verified against mail carrying a tracking pixel, remote hero image, CSS
background image and inline <script>: the script neither ran nor reached
the parent, the frame was not same-origin accessible, and no request was
made even for a resolvable, actively-served image URL.

Note the quotes in img-src 'none' are load-bearing — unquoted, CSP reads
'none' as a hostname and would allow https://none/pixel.gif.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Mateusz PstruchaandClaude Opus 5 committed 2026-09-22 22:53:24 +02:00
1 parent 74243bf3d3
commit f0b42baa50
9 files changed
+725 -66

No files matched your search

+21 -3
View File
@@ -2,14 +2,32 @@
Desktop webapp client for [Tern](../) — see [`docs/webapp-client-spec.md`](docs/webapp-client-spec.md) and [`docs/branding-spec.md`](docs/branding-spec.md).
**Status: thin scaffold.** This is a minimal placeholder, not a built-out feature set — the server side (IMAP sync + REST API) was the priority for this first pass. What's here:
**Status: read-only mail view** (build order phase 3). What's here:
- Vite + Svelte 5 + TypeScript, no other runtime dependencies, per the spec's "fast and simple" priority (§1) and browser-API-only approach (§5).
- The decided color palette wired up as CSS custom properties with `data-theme` light/dark/system switching (§4).
- A two-pane shell (folder list / message list / reading pane) that calls the real `tern-server` REST API for folders and messages, plus a login form against `/api/auth/login`.
- Two-pane desktop layout as the base case, not a breakpoint-unlocked extra (§4a): folders / thread list / reading pane.
- **Thread-grouped list**, one row per conversation, with unread weighting, message counts and attachment markers.
- **Thread view** with older messages collapsed and the newest expanded.
- **Sandboxed HTML mail rendering with remote images blocked by default** (§6) — see below.
- **Keyboard shortcuts** (§4a): `j`/`k`, `Enter`/`o`, `u`/`Esc`, `g`/`G`, `r`, `?`. Mutating shortcuts (`e`, `c`) are deliberately absent until the endpoints behind them exist — a shortcut that silently does nothing is worse than one that doesn't exist.
- Polls `/events` while the tab is open, since WebSocket push is phase 7.
- No PWA, no service worker, no offline cache — matches §2's explicit scope cut.
**Not built yet** (left for later passes, matching the server's `docs/server-architecture-spec.md` §9 build order): compose/reply, tag/rule management UI, search, keyboard shortcuts (§4a/§9 open item), sandboxed HTML mail rendering (§6), WebSocket live updates (falls back to nothing right now — no polling loop wired up either).
## How untrusted mail is rendered
Two independent defences in `src/lib/MessageBody.svelte`:
1. **`sandbox` with neither `allow-scripts` nor `allow-same-origin`.** Scripts never run, and the frame gets an opaque origin, so even if something did execute it couldn't reach the app's DOM, cookies or storage.
2. **A CSP `<meta>` inside the frame**, which is what actually blocks remote loads. This is done with CSP rather than by rewriting `<img src>` because rewriting only catches what you remember to look for — it misses `srcset`, `<picture>`, CSS `background-image` and `@font-face`. `img-src` covers every image load however it was requested.
Remote images stay blocked until the reader opts in per message, since loading them is what confirms to a sender that the mail was opened.
Verified against a message containing a tracking pixel, a remote hero image, a CSS background image and an inline `<script>`: the script did not execute or reach the parent document, the frame was not same-origin accessible, and **no network request was made even for an image URL that was resolvable and actively served**. The opt-in path is verified at the policy level (the CSP switches to `img-src https: data:`).
Note the quotes in `img-src 'none'` are load-bearing — unquoted, CSP parses `none` as a *hostname*, which would let `https://none/pixel.gif` through.
**Not built yet** (later phases): compose/reply, tag/rule management UI, search, attachment download, mutation actions (mark read, archive, tag), WebSocket live updates.
## Running
+169 -58
View File
@@ -1,126 +1,237 @@
<script lang="ts">
// Two-pane layout is the base case here, not a breakpoint-unlocked
// extra (webapp-client-spec.md §4a) — this is a desktop-first app.
// Two-pane layout is the base case here, not something unlocked at a
// breakpoint (webapp-client-spec.md §4a) — this is a desktop-first app.
import { onMount } from 'svelte';
import { listFolders, listMessages, type Folder, type MessageSummary } from './api';
import {
listFolders,
listThreads,
pollEvents,
type Folder,
type ThreadSummary,
} from './api';
import ThreadList from './ThreadList.svelte';
import ThreadView from './ThreadView.svelte';
import ShortcutHelp from './ShortcutHelp.svelte';
// No WebSocket server-side yet (build order phase 7), so the open tab
// polls the delta endpoint. §3 keeps this as the fallback afterwards.
const POLL_INTERVAL_MS = 30_000;
let folders = $state<Folder[]>([]);
let messages = $state<MessageSummary[]>([]);
let threads = $state<ThreadSummary[]>([]);
let selectedFolderId = $state<string | undefined>(undefined);
let selectedMessage = $state<MessageSummary | null>(null);
let loadError = $state<string | null>(null);
let selected = $state<ThreadSummary | null>(null);
let activeIndex = $state(0);
let loading = $state(true);
let error = $state<string | null>(null);
let helpOpen = $state(false);
let eventCursor: string | null = null;
async function refresh() {
loadError = null;
error = null;
try {
folders = await listFolders();
const page = await listMessages({ folderId: selectedFolderId });
messages = page.messages;
} catch (err) {
loadError = err instanceof Error ? err.message : 'failed to load';
const page = await listThreads({ folderId: selectedFolderId });
threads = page.threads;
if (selected && !threads.some((t) => t.thread_id === selected!.thread_id)) {
selected = null;
}
} catch (e) {
error = e instanceof Error ? e.message : 'failed to load conversations';
} finally {
loading = false;
}
}
onMount(refresh);
onMount(() => {
listFolders()
.then((f) => (folders = f))
.catch(() => {});
refresh();
const timer = setInterval(async () => {
try {
const events = await pollEvents(eventCursor);
eventCursor = events.cursor;
// Only re-fetch when something actually changed, so an idle tab
// isn't re-rendering the list every 30s.
if (events.changed_messages.length > 0) await refresh();
} catch {
// A failed poll is not worth surfacing; the next tick retries.
}
}, POLL_INTERVAL_MS);
return () => clearInterval(timer);
});
function selectFolder(id: string | undefined) {
selectedFolderId = id;
selectedMessage = null;
selected = null;
activeIndex = 0;
loading = true;
refresh();
}
function open(thread: ThreadSummary, index: number) {
selected = thread;
activeIndex = index;
}
// Gmail-style single-key navigation (§4a: treated as core UX, not a
// stretch feature). Mutating shortcuts (e = archive, c = compose) are
// deliberately absent — there are no mutation endpoints yet, and a
// shortcut that silently does nothing is worse than one that doesn't exist.
function onKeydown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null;
if (target && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName))) {
return;
}
if (event.metaKey || event.ctrlKey || event.altKey) return;
switch (event.key) {
case 'j':
event.preventDefault();
activeIndex = Math.min(activeIndex + 1, threads.length - 1);
break;
case 'k':
event.preventDefault();
activeIndex = Math.max(activeIndex - 1, 0);
break;
case 'Enter':
case 'o':
if (threads[activeIndex]) {
event.preventDefault();
open(threads[activeIndex], activeIndex);
}
break;
case 'u':
case 'Escape':
event.preventDefault();
selected = null;
break;
case 'g':
event.preventDefault();
activeIndex = 0;
break;
case 'G':
event.preventDefault();
activeIndex = Math.max(threads.length - 1, 0);
break;
case 'r':
event.preventDefault();
refresh();
break;
case '?':
event.preventDefault();
helpOpen = true;
break;
}
}
</script>
<svelte:window onkeydown={onKeydown} />
<div class="shell">
<nav class="folders">
<button class:active={!selectedFolderId} onclick={() => selectFolder(undefined)}>All Mail</button>
<nav class="folders" aria-label="Folders">
<button class:active={!selectedFolderId} onclick={() => selectFolder(undefined)}>
All mail
</button>
{#each folders as folder (folder.id)}
<button class:active={selectedFolderId === folder.id} onclick={() => selectFolder(folder.id)}>
<button
class:active={selectedFolderId === folder.id}
onclick={() => selectFolder(folder.id)}
>
{folder.name}
</button>
{/each}
<button class="help-hint" onclick={() => (helpOpen = true)}>Shortcuts&nbsp;?</button>
</nav>
<section class="list">
{#if loadError}
<p class="error">{loadError}</p>
{:else if messages.length === 0}
<p class="empty">No messages yet — this is a scaffold, the sync engine + tag/rule UI land in a later phase.</p>
<section class="list-pane">
{#if loading}
<p class="note">Loading…</p>
{:else if error}
<p class="note error">{error}</p>
{:else if threads.length === 0}
<p class="note">
No mail yet. Add an IMAP account and the sync engine will pull the INBOX.
</p>
{:else}
{#each messages as message (message.id)}
<button class="row" class:selected={selectedMessage?.id === message.id} onclick={() => (selectedMessage = message)}>
<strong>{message.from_name || message.from_addr || 'Unknown sender'}</strong>
<span>{message.subject || '(no subject)'}</span>
</button>
{/each}
<ThreadList {threads} selectedId={selected?.thread_id ?? null} {activeIndex} onSelect={open} />
{/if}
</section>
<section class="reading-pane">
{#if selectedMessage}
<h2>{selectedMessage.subject || '(no subject)'}</h2>
<p class="meta">From {selectedMessage.from_name || selectedMessage.from_addr}</p>
<p class="placeholder">
Body rendering (sandboxed iframe + remote-image blocking per §6) isn't wired up yet in this scaffold.
</p>
{#if selected}
<ThreadView thread={selected} />
{:else}
<p class="placeholder">Select a message to read it.</p>
<p class="note">Select a conversation to read it. Press <kbd>?</kbd> for shortcuts.</p>
{/if}
</section>
</div>
<ShortcutHelp open={helpOpen} onClose={() => (helpOpen = false)} />
<style>
.shell {
display: grid;
grid-template-columns: 14rem 20rem 1fr;
grid-template-columns: 12rem 22rem 1fr;
height: 100%;
min-height: 0;
}
.folders {
background: var(--primary);
background: color-mix(in srgb, var(--primary) 35%, transparent);
display: flex;
flex-direction: column;
padding: 0.75rem;
gap: 0.25rem;
border-right: 1px solid var(--secondary);
}
.folders button {
text-align: left;
background: none;
border: none;
color: var(--text);
padding: 0.5rem 0.75rem;
padding: 0.45rem 0.7rem;
border-radius: 0.375rem;
cursor: pointer;
font: inherit;
font-size: 0.9rem;
}
.folders button:hover {
background: color-mix(in srgb, var(--secondary) 50%, transparent);
}
.folders button.active {
background: var(--secondary);
font-weight: 600;
}
.list {
.help-hint {
margin-top: auto;
font-size: 0.78rem !important;
color: var(--primary) !important;
}
.list-pane {
border-right: 1px solid var(--secondary);
overflow-y: auto;
}
.row {
display: flex;
flex-direction: column;
width: 100%;
text-align: left;
padding: 0.75rem 1rem;
border: none;
border-bottom: 1px solid var(--secondary);
background: var(--background);
color: var(--text);
cursor: pointer;
}
.row:hover,
.row.selected {
background: var(--secondary);
min-height: 0;
}
.reading-pane {
padding: 1.5rem;
display: flex;
flex-direction: column;
min-height: 0;
}
.empty,
.placeholder,
.error {
.note {
padding: 1rem;
color: var(--primary);
font-size: 0.9rem;
}
.error {
color: var(--accent);
}
kbd {
border: 1px solid var(--secondary);
border-radius: 0.25rem;
padding: 0 0.3rem;
font-size: 0.85em;
}
</style>
+80
View File
@@ -0,0 +1,80 @@
<script lang="ts">
// Renders untrusted HTML email (webapp-client-spec.md §6). Two separate
// defences, because each covers what the other can't:
//
// 1. `sandbox` with neither allow-scripts nor allow-same-origin. Scripts
// never run, and the frame gets an opaque origin, so even if something
// did execute it couldn't reach our DOM, cookies or localStorage.
// 2. A CSP `<meta>` inside the document, which is what actually blocks
// remote loads. Doing this with CSP rather than by rewriting <img src>
// matters: rewriting only catches what you remember to look for, and
// misses srcset, <picture>, CSS background-image, @font-face and
// friends. `img-src` covers every image load however it was requested.
//
// Remote images stay blocked until the reader asks for them, since loading
// them is what confirms to a sender that mail was opened (§6).
let {
html,
text,
imagesAllowed = false,
}: { html: string | null; text: string | null; imagesAllowed?: boolean } = $props();
// The quotes on 'none' are load-bearing: unquoted, CSP parses `none` as a
// hostname rather than the keyword, so `https://none/pixel.gif` would be
// allowed through. Only https: is permitted once the reader opts in —
// http: images would be blocked as mixed content in production anyway.
const imgPolicy = $derived(imagesAllowed ? 'https: data:' : "'none'");
const csp = $derived(
[
"default-src 'none'",
`img-src ${imgPolicy}`,
"style-src 'unsafe-inline'",
"font-src 'none'",
"form-action 'none'",
"base-uri 'none'",
].join('; '),
);
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
const bodyMarkup = $derived(
html ?? `<pre class="plain">${escapeHtml(text ?? '(no content)')}</pre>`,
);
const srcdoc = $derived(`<!doctype html>
<html><head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="${csp}">
<base target="_blank" rel="noopener noreferrer">
<style>
body { font-family: system-ui, sans-serif; font-size: 14px; line-height: 1.5;
color: #111; background: #fff; margin: 12px; overflow-wrap: anywhere; }
img { max-width: 100%; height: auto; }
pre.plain { white-space: pre-wrap; font: inherit; margin: 0; }
</style>
</head><body>${bodyMarkup}</body></html>`);
</script>
<iframe
title="Message content"
{srcdoc}
sandbox="allow-popups allow-popups-to-escape-sandbox"
></iframe>
<style>
iframe {
width: 100%;
flex: 1;
min-height: 20rem;
border: none;
background: #fff;
border-radius: 0.375rem;
}
</style>
+89
View File
@@ -0,0 +1,89 @@
<script lang="ts">
// Native <dialog> rather than a JS modal library (§5) — it brings focus
// trapping, Escape-to-close and the backdrop for free.
let { open, onClose }: { open: boolean; onClose: () => void } = $props();
let dialog = $state<HTMLDialogElement | null>(null);
$effect(() => {
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
});
const shortcuts: [string, string][] = [
['j / k', 'Next / previous conversation'],
['Enter or o', 'Open conversation'],
['u or Esc', 'Back to list'],
['g / G', 'Jump to first / last'],
['r', 'Refresh'],
['?', 'This help'],
];
</script>
<dialog bind:this={dialog} onclose={onClose}>
<h2>Keyboard shortcuts</h2>
<dl>
{#each shortcuts as [keys, description]}
<dt><kbd>{keys}</kbd></dt>
<dd>{description}</dd>
{/each}
</dl>
<p class="note">
Archive, tag and compose shortcuts arrive with the phases that add those actions.
</p>
<button onclick={onClose}>Close</button>
</dialog>
<style>
dialog {
border: 1px solid var(--secondary);
border-radius: 0.5rem;
background: var(--background);
color: var(--text);
padding: 1.25rem;
min-width: 22rem;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
}
h2 {
margin: 0 0 0.75rem;
font-size: 1.05rem;
}
dl {
display: grid;
grid-template-columns: auto 1fr;
gap: 0.4rem 1rem;
margin: 0 0 0.75rem;
font-size: 0.875rem;
}
dt {
text-align: right;
}
dd {
margin: 0;
color: var(--primary);
}
kbd {
border: 1px solid var(--secondary);
border-radius: 0.25rem;
padding: 0 0.35rem;
font-family: ui-monospace, monospace;
font-size: 0.85em;
}
.note {
font-size: 0.8rem;
color: var(--primary);
margin: 0 0 0.75rem;
}
button {
border: 1px solid var(--secondary);
background: var(--accent);
color: var(--text);
border-radius: 0.375rem;
padding: 0.35rem 0.8rem;
cursor: pointer;
font: inherit;
}
</style>
+130
View File
@@ -0,0 +1,130 @@
<script lang="ts">
import type { ThreadSummary } from './api';
import { formatListDate } from './format';
let {
threads,
selectedId,
activeIndex,
onSelect,
}: {
threads: ThreadSummary[];
selectedId: string | null;
activeIndex: number;
onSelect: (thread: ThreadSummary, index: number) => void;
} = $props();
let listEl = $state<HTMLElement | null>(null);
// Keep the keyboard cursor visible when j/k walks past the viewport edge.
$effect(() => {
const row = listEl?.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`);
row?.scrollIntoView({ block: 'nearest' });
});
</script>
<div class="list" bind:this={listEl} role="listbox" aria-label="Conversations" tabindex="-1">
{#each threads as thread, i (thread.thread_id)}
<button
class="row"
class:unread={thread.unread_count > 0}
class:selected={thread.thread_id === selectedId}
class:active={i === activeIndex}
data-index={i}
role="option"
aria-selected={thread.thread_id === selectedId}
onclick={() => onSelect(thread, i)}
>
<span class="top">
<span class="from">{thread.last_from || 'Unknown sender'}</span>
<span class="date">{formatListDate(thread.last_message_at)}</span>
</span>
<span class="subject">
{thread.subject || '(no subject)'}
{#if thread.message_count > 1}
<span class="count">{thread.message_count}</span>
{/if}
{#if thread.has_attachments}
<span class="attach" aria-label="Has attachments">&#128206;</span>
{/if}
</span>
</button>
{/each}
</div>
<style>
.list {
overflow-y: auto;
display: flex;
flex-direction: column;
}
.row {
display: flex;
flex-direction: column;
gap: 0.2rem;
width: 100%;
text-align: left;
padding: 0.6rem 0.9rem;
border: none;
border-bottom: 1px solid var(--secondary);
border-left: 3px solid transparent;
background: var(--background);
color: var(--text);
cursor: pointer;
font: inherit;
}
.row:hover {
background: color-mix(in srgb, var(--secondary) 45%, transparent);
}
.row.selected {
background: color-mix(in srgb, var(--secondary) 70%, transparent);
}
/* Keyboard cursor is shown distinctly from selection, so j/k movement is
visible before the reading pane has caught up. */
.row.active {
border-left-color: var(--accent);
}
.row:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.top {
display: flex;
justify-content: space-between;
gap: 0.5rem;
font-size: 0.85rem;
}
.from {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.row.unread .from,
.row.unread .subject {
font-weight: 700;
}
.date {
color: var(--primary);
font-size: 0.75rem;
white-space: nowrap;
}
.subject {
font-size: 0.85rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
}
.count {
display: inline-block;
font-size: 0.7rem;
padding: 0 0.3rem;
border-radius: 0.6rem;
background: var(--secondary);
color: var(--text);
font-weight: 600;
}
.attach {
font-size: 0.75rem;
}
</style>
+160
View File
@@ -0,0 +1,160 @@
<script lang="ts">
import { getThread, type MessageDetail, type ThreadSummary } from './api';
import { formatFullDate } from './format';
import MessageBody from './MessageBody.svelte';
let { thread }: { thread: ThreadSummary } = $props();
let messages = $state<MessageDetail[]>([]);
let loading = $state(true);
let error = $state<string | null>(null);
// Per-message, and reset whenever the thread changes: allowing images on
// one message must not silently allow them on the next one opened.
let imagesAllowed = $state<Record<string, boolean>>({});
let expanded = $state<Record<string, boolean>>({});
$effect(() => {
const id = thread.thread_id;
loading = true;
error = null;
imagesAllowed = {};
getThread(id)
.then((result) => {
messages = result;
// Collapse all but the newest, the one most likely to be read.
expanded = Object.fromEntries(
result.map((m, i) => [m.id, i === result.length - 1]),
);
})
.catch((e) => (error = e instanceof Error ? e.message : 'failed to load thread'))
.finally(() => (loading = false));
});
function hasRemoteImages(m: MessageDetail): boolean {
const html = m.body?.html_body;
return !!html && /<img|background-image|srcset=/i.test(html);
}
</script>
<article class="thread">
<header>
<h1>{thread.subject || '(no subject)'}</h1>
<p class="count">
{thread.message_count}
{thread.message_count === 1 ? 'message' : 'messages'}
</p>
</header>
{#if loading}
<p class="note">Loading…</p>
{:else if error}
<p class="note error">{error}</p>
{:else}
{#each messages as message (message.id)}
<section class="message">
<button
class="message-header"
onclick={() => (expanded[message.id] = !expanded[message.id])}
aria-expanded={expanded[message.id]}
>
<span class="sender">{message.from_name || message.from_addr || 'Unknown sender'}</span>
<span class="date">{formatFullDate(message.sent_at)}</span>
</button>
{#if expanded[message.id]}
{#if hasRemoteImages(message) && !imagesAllowed[message.id]}
<div class="image-bar">
<span>Remote images blocked — loading them tells the sender you opened this.</span>
<button onclick={() => (imagesAllowed[message.id] = true)}>Load images</button>
</div>
{/if}
{#if !message.body}
<p class="note">Body not fetched yet — the sync engine pulls bodies in a trailing pass.</p>
{:else}
<MessageBody
html={message.body.html_body}
text={message.body.text_body}
imagesAllowed={!!imagesAllowed[message.id]}
/>
{/if}
{/if}
</section>
{/each}
{/if}
</article>
<style>
.thread {
display: flex;
flex-direction: column;
height: 100%;
overflow-y: auto;
padding: 1.25rem;
gap: 0.75rem;
}
header h1 {
margin: 0;
font-size: 1.25rem;
}
.count {
margin: 0.25rem 0 0;
font-size: 0.8rem;
color: var(--primary);
}
.message {
display: flex;
flex-direction: column;
border: 1px solid var(--secondary);
border-radius: 0.5rem;
overflow: hidden;
}
.message-header {
display: flex;
justify-content: space-between;
gap: 1rem;
width: 100%;
padding: 0.6rem 0.8rem;
background: color-mix(in srgb, var(--secondary) 40%, transparent);
border: none;
color: var(--text);
cursor: pointer;
text-align: left;
font-size: 0.9rem;
}
.sender {
font-weight: 600;
}
.date {
color: var(--primary);
font-size: 0.8rem;
white-space: nowrap;
}
.image-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.5rem 0.8rem;
font-size: 0.8rem;
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
.image-bar button {
border: 1px solid var(--accent);
background: none;
color: var(--text);
border-radius: 0.375rem;
padding: 0.2rem 0.6rem;
cursor: pointer;
white-space: nowrap;
}
.note {
padding: 0.75rem;
font-size: 0.85rem;
color: var(--primary);
}
.error {
color: var(--accent);
}
</style>
+45 -3
View File
@@ -43,24 +43,66 @@ export interface MessageSummary {
subject: string | null;
from_addr: string | null;
from_name: string | null;
to_addrs: string[];
sent_at: string | null;
thread_id: string;
flags: string[];
}
export interface MessageBody {
message_id: string;
text_body: string | null;
html_body: string | null;
}
/** A message plus its body, as returned by the thread endpoint. */
export interface MessageDetail extends MessageSummary {
body: MessageBody | null;
}
export interface ThreadSummary {
thread_id: string;
subject: string | null;
last_from: string | null;
last_message_at: string | null;
message_count: number;
unread_count: number;
has_attachments: boolean;
}
/** Flags are stored in IMAP wire format, so unread is the absence of \Seen. */
export function isUnread(flags: string[]): boolean {
return !flags.includes('\\Seen');
}
export function listFolders(): Promise<Folder[]> {
return request('/folders');
}
export function listMessages(params: { folderId?: string; before?: string } = {}): Promise<{
messages: MessageSummary[];
export function listThreads(params: { folderId?: string; before?: string } = {}): Promise<{
threads: ThreadSummary[];
next_cursor: string | null;
}> {
const query = new URLSearchParams();
if (params.folderId) query.set('folder_id', params.folderId);
if (params.before) query.set('before', params.before);
const qs = query.toString();
return request(`/messages${qs ? `?${qs}` : ''}`);
return request(`/threads${qs ? `?${qs}` : ''}`);
}
export function getThread(threadId: string): Promise<MessageDetail[]> {
return request(`/threads/${threadId}`);
}
/**
* Delta endpoint (§3.8). WebSocket push is a later phase, so the client
* polls this to notice new mail while the tab is open.
*/
export function pollEvents(since: string | null): Promise<{
changed_messages: MessageSummary[];
cursor: string;
}> {
return request(`/events${since ? `?since=${encodeURIComponent(since)}` : ''}`);
}
export async function login(username: string, password: string): Promise<void> {
+28
View File
@@ -0,0 +1,28 @@
/** Short, scannable timestamps for list rows: time today, date otherwise. */
export function formatListDate(iso: string | null): string {
if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
const now = new Date();
const sameDay =
d.getFullYear() === now.getFullYear() &&
d.getMonth() === now.getMonth() &&
d.getDate() === now.getDate();
if (sameDay) {
return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
}
const sameYear = d.getFullYear() === now.getFullYear();
return d.toLocaleDateString(undefined, {
day: 'numeric',
month: 'short',
...(sameYear ? {} : { year: 'numeric' }),
});
}
export function formatFullDate(iso: string | null): string {
if (!iso) return '';
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString();
}
+3 -2
View File
@@ -5,8 +5,9 @@ export default defineConfig({
plugins: [svelte()],
server: {
proxy: {
// Points at tern-server's default dev bind address (see server/.env.example).
'/api': 'http://127.0.0.1:8080',
// Defaults to tern-server's dev bind address (see server/.env.example).
// Override with TERN_API when the server runs on another port or host.
'/api': process.env.TERN_API ?? 'http://127.0.0.1:8080',
},
},
});