Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5a49b851a | ||
|
|
f538853a0c | ||
|
|
f0b42baa50 |
No files matched your search
@@ -2,18 +2,39 @@
|
||||
|
||||
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-and-reply mail client** (build order phases 3–4). 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.
|
||||
- **Compose, reply and reply-all** in a native `<dialog>`, with drafts. Replying to your own sent message addresses the people you wrote to, not yourself. `Ctrl+Enter` sends.
|
||||
- **Outbox** view for drafts, queued and failed messages, showing retry timing and the last error, with Retry/Delete for failures.
|
||||
- Opening a conversation marks it read.
|
||||
- **Keyboard shortcuts** (§4a): `j`/`k`, `Enter`/`o`, `u`/`Esc`, `g`/`G`, `c`, `r`/`a`, `Shift+R`, `?`. Archive (`e`) is deliberately absent until phase 5 adds the folder semantics behind it — 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): tag/rule management UI, search, attachment download, archive and tagging, WebSocket live updates. Composing is plain text only.
|
||||
|
||||
## Running
|
||||
|
||||
Requires `tern-server` running on `127.0.0.1:8080` (see [`../server/README.md`](../server/README.md)) — the dev server proxies `/api` to it.
|
||||
Requires `tern-server` running (see [`../server/README.md`](../server/README.md)) — the dev server proxies `/api` to `127.0.0.1:8080` by default, or wherever `TERN_API` points (e.g. `TERN_API=http://127.0.0.1:8088 npm run dev`).
|
||||
|
||||
```bash
|
||||
npm install
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "tern-web",
|
||||
"version": "0.1.0",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tern-web",
|
||||
"version": "0.1.0",
|
||||
"version": "0.4.0",
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^4.0.0",
|
||||
"@tsconfig/svelte": "^5.0.4",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "tern-web",
|
||||
"private": true,
|
||||
"version": "0.2.0",
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
<script lang="ts">
|
||||
// Native <dialog> (§5): focus trapping, Escape and the backdrop come free.
|
||||
import {
|
||||
createOutboxItem,
|
||||
deleteOutboxItem,
|
||||
sendOutboxItem,
|
||||
updateDraft,
|
||||
type Account,
|
||||
type ComposeFields,
|
||||
} from './api';
|
||||
import { parseRecipients, type ComposeSeed } from './reply';
|
||||
|
||||
let {
|
||||
seed,
|
||||
accounts,
|
||||
onClose,
|
||||
}: {
|
||||
seed: ComposeSeed | null;
|
||||
accounts: Account[];
|
||||
/** Called after the dialog closes. `changed` means the outbox may
|
||||
* differ; `sentId` is the item just queued for sending, if any. */
|
||||
onClose: (changed: boolean, sentId?: string) => void;
|
||||
} = $props();
|
||||
|
||||
let dialog = $state<HTMLDialogElement | null>(null);
|
||||
let accountId = $state('');
|
||||
let to = $state('');
|
||||
let cc = $state('');
|
||||
let bcc = $state('');
|
||||
let showBcc = $state(false);
|
||||
let subject = $state('');
|
||||
let body = $state('');
|
||||
let busy = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let draftId = $state<string | undefined>(undefined);
|
||||
let changed = false;
|
||||
let sentId: string | undefined;
|
||||
// Programmatic closes notify the parent directly rather than relying on
|
||||
// the dialog's `close` event: browsers are free to defer that event (Chrome
|
||||
// doesn't deliver it at all while the tab is hidden), and the parent's
|
||||
// state must not wait on it. The event still covers Escape; this flag
|
||||
// stops the two paths notifying twice.
|
||||
let notified = false;
|
||||
|
||||
function notifyClosed() {
|
||||
if (notified) return;
|
||||
notified = true;
|
||||
onClose(changed, sentId);
|
||||
}
|
||||
|
||||
function finish() {
|
||||
dialog?.close();
|
||||
notifyClosed();
|
||||
}
|
||||
|
||||
// Only accounts with a usable From address can send.
|
||||
const sendable = $derived(
|
||||
accounts.filter((a) => a.email_address || a.username.includes('@')),
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (!dialog) return;
|
||||
if (seed && !dialog.open) {
|
||||
accountId = seed.accountId ?? sendable[0]?.id ?? '';
|
||||
to = seed.to.join(', ');
|
||||
cc = seed.cc.join(', ');
|
||||
bcc = seed.bcc.join(', ');
|
||||
showBcc = seed.bcc.length > 0;
|
||||
subject = seed.subject;
|
||||
body = seed.text_body;
|
||||
draftId = seed.draftId;
|
||||
error = null;
|
||||
changed = false;
|
||||
sentId = undefined;
|
||||
notified = false;
|
||||
dialog.showModal();
|
||||
// Replies open with a quote below; start the cursor above it.
|
||||
queueMicrotask(() => {
|
||||
const target = seed.to.length ? '#compose-body' : '#compose-to';
|
||||
const el = dialog?.querySelector<HTMLTextAreaElement | HTMLInputElement>(target);
|
||||
el?.focus();
|
||||
if (el instanceof HTMLTextAreaElement) el.setSelectionRange(0, 0);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function fields(): ComposeFields {
|
||||
return {
|
||||
to: parseRecipients(to),
|
||||
cc: parseRecipients(cc),
|
||||
bcc: parseRecipients(bcc),
|
||||
subject,
|
||||
text_body: body,
|
||||
};
|
||||
}
|
||||
|
||||
async function submit(send: boolean) {
|
||||
busy = true;
|
||||
error = null;
|
||||
try {
|
||||
if (draftId) {
|
||||
await updateDraft(draftId, fields());
|
||||
// The draft is saved even if the send below is rejected, so the
|
||||
// outbox has changed either way.
|
||||
changed = true;
|
||||
if (send) {
|
||||
await sendOutboxItem(draftId);
|
||||
sentId = draftId;
|
||||
}
|
||||
} else {
|
||||
const item = await createOutboxItem({
|
||||
...fields(),
|
||||
account_id: seed?.replyToMessageId ? undefined : accountId,
|
||||
reply_to_message_id: seed?.replyToMessageId,
|
||||
send,
|
||||
});
|
||||
draftId = item.id;
|
||||
changed = true;
|
||||
if (send) sentId = item.id;
|
||||
}
|
||||
finish();
|
||||
} catch (e) {
|
||||
// Keep the dialog open with everything typed intact; closing on error
|
||||
// would throw away the message.
|
||||
error = e instanceof Error ? e.message : 'failed';
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function discard() {
|
||||
if (draftId) {
|
||||
busy = true;
|
||||
try {
|
||||
await deleteOutboxItem(draftId);
|
||||
changed = true;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to discard';
|
||||
busy = false;
|
||||
return;
|
||||
}
|
||||
busy = false;
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (!dialog?.open) return;
|
||||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !busy) {
|
||||
e.preventDefault();
|
||||
submit(true);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<dialog bind:this={dialog} onclose={notifyClosed} onkeydown={onKeydown} aria-label="Compose">
|
||||
<form method="dialog" onsubmit={(e) => { e.preventDefault(); submit(true); }}>
|
||||
<header>
|
||||
<h2>{seed?.replyToMessageId ? 'Reply' : draftId ? 'Edit draft' : 'New message'}</h2>
|
||||
</header>
|
||||
|
||||
{#if !seed?.replyToMessageId}
|
||||
<label>
|
||||
<span>From</span>
|
||||
{#if sendable.length === 0}
|
||||
<em class="warn">No account has a sender address yet — set one on the account first.</em>
|
||||
{:else}
|
||||
<select bind:value={accountId} disabled={!!draftId}>
|
||||
{#each sendable as a (a.id)}
|
||||
<option value={a.id}>
|
||||
{a.display_name ? `${a.display_name} <${a.email_address ?? a.username}>` : (a.email_address ?? a.username)}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<label>
|
||||
<span>To</span>
|
||||
<input id="compose-to" bind:value={to} autocomplete="off" spellcheck="false" />
|
||||
{#if !showBcc}
|
||||
<button type="button" class="link" onclick={() => (showBcc = true)}>Bcc</button>
|
||||
{/if}
|
||||
</label>
|
||||
<label>
|
||||
<span>Cc</span>
|
||||
<input bind:value={cc} autocomplete="off" spellcheck="false" />
|
||||
</label>
|
||||
{#if showBcc}
|
||||
<label>
|
||||
<span>Bcc</span>
|
||||
<input bind:value={bcc} autocomplete="off" spellcheck="false" />
|
||||
</label>
|
||||
{/if}
|
||||
<label>
|
||||
<span>Subject</span>
|
||||
<input bind:value={subject} />
|
||||
</label>
|
||||
|
||||
<textarea id="compose-body" bind:value={body} rows="14"></textarea>
|
||||
|
||||
{#if error}
|
||||
<p class="error">{error}</p>
|
||||
{/if}
|
||||
|
||||
<footer>
|
||||
<button type="submit" class="primary" disabled={busy}>Send</button>
|
||||
<button type="button" disabled={busy} onclick={() => submit(false)}>Save draft</button>
|
||||
<span class="hint"><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to send</span>
|
||||
<button type="button" class="discard" disabled={busy} onclick={discard}>
|
||||
{draftId ? 'Delete draft' : 'Discard'}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<style>
|
||||
dialog {
|
||||
width: min(44rem, 92vw);
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
padding: 0;
|
||||
}
|
||||
dialog::backdrop {
|
||||
background: rgb(0 0 0 / 0.45);
|
||||
}
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
padding: 1rem 1.1rem;
|
||||
}
|
||||
h2 {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
border-bottom: 1px solid var(--secondary);
|
||||
padding: 0.15rem 0;
|
||||
}
|
||||
label > span {
|
||||
width: 3.8rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
flex: 1;
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text);
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0.35rem 0;
|
||||
}
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
textarea:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
label:focus-within {
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
select {
|
||||
background: var(--background);
|
||||
}
|
||||
textarea {
|
||||
margin-top: 0.4rem;
|
||||
resize: vertical;
|
||||
min-height: 12rem;
|
||||
line-height: 1.5;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.6rem;
|
||||
}
|
||||
textarea:focus-visible {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
border: 1px solid var(--secondary);
|
||||
background: none;
|
||||
color: var(--text);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.4rem 0.9rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
button.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
button.discard {
|
||||
margin-left: auto;
|
||||
}
|
||||
button.link {
|
||||
border: none;
|
||||
padding: 0 0.2rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.hint {
|
||||
font-size: 0.75rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
kbd {
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.2rem;
|
||||
padding: 0 0.25rem;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.error {
|
||||
margin: 0.2rem 0 0;
|
||||
color: var(--accent);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.warn {
|
||||
font-size: 0.85rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
</style>
|
||||
+308
-58
@@ -1,126 +1,376 @@
|
||||
<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 {
|
||||
listAccounts,
|
||||
listFolders,
|
||||
listOutbox,
|
||||
listThreads,
|
||||
pollEvents,
|
||||
type Account,
|
||||
type Folder,
|
||||
type MessageDetail,
|
||||
type OutboxItem,
|
||||
type ThreadSummary,
|
||||
} from './api';
|
||||
import { emptySeed, replySeed, type ComposeSeed } from './reply';
|
||||
import ThreadList from './ThreadList.svelte';
|
||||
import ThreadView from './ThreadView.svelte';
|
||||
import OutboxView from './OutboxView.svelte';
|
||||
import Compose from './Compose.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;
|
||||
// After sending, watch the outbox closely so the reader sees the message
|
||||
// go out, rather than waiting for the next slow poll.
|
||||
const SEND_WATCH_INTERVAL_MS = 1_500;
|
||||
const SEND_WATCH_LIMIT_MS = 20_000;
|
||||
|
||||
let accounts = $state<Account[]>([]);
|
||||
let folders = $state<Folder[]>([]);
|
||||
let messages = $state<MessageSummary[]>([]);
|
||||
let threads = $state<ThreadSummary[]>([]);
|
||||
let outbox = $state<OutboxItem[]>([]);
|
||||
let view = $state<'mail' | 'outbox'>('mail');
|
||||
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 threadMessages = $state<MessageDetail[]>([]);
|
||||
let threadReloadKey = $state(0);
|
||||
let activeIndex = $state(0);
|
||||
let loading = $state(true);
|
||||
let error = $state<string | null>(null);
|
||||
let helpOpen = $state(false);
|
||||
let composeSeed = $state<ComposeSeed | null>(null);
|
||||
let eventCursor: string | null = null;
|
||||
|
||||
const ownAddresses = $derived(
|
||||
accounts.flatMap((a) => [a.email_address, a.username]).filter((a): a is string => !!a && a.includes('@')),
|
||||
);
|
||||
const outboxCount = $derived(outbox.length);
|
||||
|
||||
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);
|
||||
async function refreshOutbox() {
|
||||
try {
|
||||
outbox = await listOutbox();
|
||||
} catch {
|
||||
// Non-critical; the next action or poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
listFolders().then((f) => (folders = f)).catch(() => {});
|
||||
listAccounts().then((a) => (accounts = a)).catch(() => {});
|
||||
refresh();
|
||||
refreshOutbox();
|
||||
|
||||
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();
|
||||
threadReloadKey++;
|
||||
}
|
||||
} catch {
|
||||
// A failed poll is not worth surfacing; the next tick retries.
|
||||
}
|
||||
}, POLL_INTERVAL_MS);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
});
|
||||
|
||||
function selectFolder(id: string | undefined) {
|
||||
view = 'mail';
|
||||
selectedFolderId = id;
|
||||
selectedMessage = null;
|
||||
selected = null;
|
||||
activeIndex = 0;
|
||||
loading = true;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function showOutbox() {
|
||||
view = 'outbox';
|
||||
selected = null;
|
||||
refreshOutbox();
|
||||
}
|
||||
|
||||
function open(thread: ThreadSummary, index: number) {
|
||||
selected = thread;
|
||||
activeIndex = index;
|
||||
threadMessages = [];
|
||||
}
|
||||
|
||||
function markedRead(threadId: string) {
|
||||
const t = threads.find((t) => t.thread_id === threadId);
|
||||
if (t) t.unread_count = 0;
|
||||
}
|
||||
|
||||
function compose() {
|
||||
composeSeed = emptySeed(accounts.find((a) => a.email_address || a.username.includes('@'))?.id);
|
||||
}
|
||||
|
||||
function reply(message: MessageDetail, all: boolean) {
|
||||
composeSeed = replySeed(message, ownAddresses, all);
|
||||
}
|
||||
|
||||
function openOutboxItem(item: OutboxItem) {
|
||||
composeSeed = {
|
||||
to: item.to_addrs,
|
||||
cc: item.cc_addrs,
|
||||
bcc: item.bcc_addrs,
|
||||
subject: item.subject,
|
||||
text_body: item.text_body,
|
||||
accountId: item.account_id,
|
||||
draftId: item.id,
|
||||
};
|
||||
}
|
||||
|
||||
async function composeClosed(changed: boolean, sentId?: string) {
|
||||
composeSeed = null;
|
||||
if (!changed) return;
|
||||
await refreshOutbox();
|
||||
if (sentId) watchSend(sentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls briefly until the message just sent leaves the queue, then
|
||||
* refreshes mail so it appears in its conversation. Watches that one item
|
||||
* only — an unrelated message stuck retrying must not hold this up.
|
||||
*/
|
||||
async function watchSend(id: string) {
|
||||
const inFlight = () => outbox.some((i) => i.id === id && (i.status === 'pending' || i.status === 'sending'));
|
||||
const started = Date.now();
|
||||
while (inFlight() && Date.now() - started < SEND_WATCH_LIMIT_MS) {
|
||||
await new Promise((r) => setTimeout(r, SEND_WATCH_INTERVAL_MS));
|
||||
await refreshOutbox();
|
||||
}
|
||||
await refresh();
|
||||
threadReloadKey++;
|
||||
}
|
||||
|
||||
// Gmail-style single-key navigation (§4a: treated as core UX, not a
|
||||
// stretch feature). Archive (`e`) is still absent — it needs folder
|
||||
// semantics that arrive with tags and rules.
|
||||
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;
|
||||
if (composeSeed || helpOpen) return;
|
||||
|
||||
const newest = threadMessages[threadMessages.length - 1];
|
||||
|
||||
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 (view === 'mail' && 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 'c':
|
||||
event.preventDefault();
|
||||
compose();
|
||||
break;
|
||||
case 'r':
|
||||
case 'a':
|
||||
if (selected && newest) {
|
||||
event.preventDefault();
|
||||
reply(newest, event.key === 'a');
|
||||
}
|
||||
break;
|
||||
case 'R':
|
||||
event.preventDefault();
|
||||
refresh();
|
||||
refreshOutbox();
|
||||
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="compose" onclick={compose}>Compose</button>
|
||||
<button class:active={view === 'mail' && !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={view === 'mail' && selectedFolderId === folder.id}
|
||||
onclick={() => selectFolder(folder.id)}
|
||||
>
|
||||
{folder.name}
|
||||
</button>
|
||||
{/each}
|
||||
<button class:active={view === 'outbox'} onclick={showOutbox}>
|
||||
Outbox
|
||||
{#if outboxCount > 0}<span class="badge">{outboxCount}</span>{/if}
|
||||
</button>
|
||||
<button class="help-hint" onclick={() => (helpOpen = true)}>Shortcuts ?</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 view === 'outbox'}
|
||||
<OutboxView items={outbox} onOpen={openOutboxItem} onChanged={refreshOutbox} />
|
||||
{:else 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}
|
||||
reloadKey={threadReloadKey}
|
||||
onReply={reply}
|
||||
onLoaded={(m) => (threadMessages = m)}
|
||||
onRead={markedRead}
|
||||
/>
|
||||
{: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>
|
||||
|
||||
<Compose seed={composeSeed} {accounts} onClose={composeClosed} />
|
||||
<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 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
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 {
|
||||
/* The compose button is one of the few places the accent belongs
|
||||
(branding-spec.md §1). */
|
||||
.folders button.compose {
|
||||
justify-content: center;
|
||||
background: var(--accent);
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.folders button.compose:hover {
|
||||
background: color-mix(in srgb, var(--accent) 85%, var(--text));
|
||||
}
|
||||
.badge {
|
||||
font-size: 0.7rem;
|
||||
padding: 0 0.4rem;
|
||||
border-radius: 0.6rem;
|
||||
background: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.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>
|
||||
@@ -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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
}
|
||||
|
||||
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>
|
||||
@@ -0,0 +1,159 @@
|
||||
<script lang="ts">
|
||||
import { deleteOutboxItem, sendOutboxItem, type OutboxItem } from './api';
|
||||
import { formatListDate } from './format';
|
||||
|
||||
let {
|
||||
items,
|
||||
onOpen,
|
||||
onChanged,
|
||||
}: {
|
||||
items: OutboxItem[];
|
||||
onOpen: (item: OutboxItem) => void;
|
||||
onChanged: () => void;
|
||||
} = $props();
|
||||
|
||||
let error = $state<string | null>(null);
|
||||
|
||||
const label: Record<OutboxItem['status'], string> = {
|
||||
draft: 'Draft',
|
||||
pending: 'Queued',
|
||||
sending: 'Sending…',
|
||||
sent: 'Sent',
|
||||
failed: 'Failed',
|
||||
};
|
||||
|
||||
function retryText(item: OutboxItem): string {
|
||||
if (item.status !== 'pending' || item.attempts === 0 || !item.next_attempt_at) return '';
|
||||
const secs = Math.max(0, Math.round((new Date(item.next_attempt_at).getTime() - Date.now()) / 1000));
|
||||
return secs > 0 ? `retrying in ${secs < 90 ? `${secs}s` : `${Math.round(secs / 60)} min`}` : 'retrying now';
|
||||
}
|
||||
|
||||
async function act(fn: () => Promise<unknown>) {
|
||||
error = null;
|
||||
try {
|
||||
await fn();
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="outbox">
|
||||
{#if error}
|
||||
<p class="note error">{error}</p>
|
||||
{/if}
|
||||
{#if items.length === 0}
|
||||
<p class="note">Nothing waiting. Drafts, queued and failed messages show up here; sent mail lives in its conversation.</p>
|
||||
{:else}
|
||||
{#each items as item (item.id)}
|
||||
<div class="row" class:failed={item.status === 'failed'}>
|
||||
<button class="main" onclick={() => onOpen(item)} disabled={item.status === 'pending' || item.status === 'sending'}>
|
||||
<span class="top">
|
||||
<span class="to">{item.to_addrs.join(', ') || '(no recipients)'}</span>
|
||||
<span class="date">{formatListDate(item.updated_at)}</span>
|
||||
</span>
|
||||
<span class="subject">{item.subject || '(no subject)'}</span>
|
||||
<span class="status status-{item.status}">
|
||||
{label[item.status]}
|
||||
{#if retryText(item)}· {retryText(item)}{/if}
|
||||
{#if item.last_error}— {item.last_error}{/if}
|
||||
</span>
|
||||
</button>
|
||||
{#if item.status === 'failed'}
|
||||
<div class="actions">
|
||||
<button onclick={() => act(() => sendOutboxItem(item.id))}>Retry</button>
|
||||
<button onclick={() => act(() => deleteOutboxItem(item.id))}>Delete</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.outbox {
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid var(--secondary);
|
||||
border-left: 3px solid transparent;
|
||||
}
|
||||
.row.failed {
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
.main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
text-align: left;
|
||||
padding: 0.6rem 0.9rem;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.main:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
.main:not(:disabled):hover {
|
||||
background: color-mix(in srgb, var(--secondary) 45%, transparent);
|
||||
}
|
||||
.top {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.to,
|
||||
.subject {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.subject {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.date {
|
||||
color: var(--primary);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.status {
|
||||
font-size: 0.75rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.status-failed {
|
||||
color: var(--accent);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.3rem;
|
||||
padding-right: 0.6rem;
|
||||
}
|
||||
.actions button {
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--secondary);
|
||||
background: none;
|
||||
color: var(--text);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.note {
|
||||
padding: 1rem;
|
||||
color: var(--primary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.error {
|
||||
color: var(--accent);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,92 @@
|
||||
<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'],
|
||||
['c', 'Compose'],
|
||||
['r / a', 'Reply / reply all to the open conversation'],
|
||||
['Ctrl+Enter', 'Send (while composing)'],
|
||||
['Shift+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 and tag shortcuts arrive with the phase that adds tags and rules.
|
||||
</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>
|
||||
@@ -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">📎</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>
|
||||
@@ -0,0 +1,216 @@
|
||||
<script lang="ts">
|
||||
import { getThread, markThreadRead, type MessageDetail, type ThreadSummary } from './api';
|
||||
import { formatFullDate } from './format';
|
||||
import MessageBody from './MessageBody.svelte';
|
||||
|
||||
let {
|
||||
thread,
|
||||
reloadKey = 0,
|
||||
onReply,
|
||||
onLoaded,
|
||||
onRead,
|
||||
}: {
|
||||
thread: ThreadSummary;
|
||||
/** Bumped by the parent to refetch, e.g. after a reply is sent. */
|
||||
reloadKey?: number;
|
||||
onReply: (message: MessageDetail, all: boolean) => void;
|
||||
/** Lets the parent know the newest message, for the r / a shortcuts. */
|
||||
onLoaded?: (messages: MessageDetail[]) => void;
|
||||
onRead?: (threadId: string) => void;
|
||||
} = $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;
|
||||
void reloadKey;
|
||||
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]),
|
||||
);
|
||||
onLoaded?.(result);
|
||||
// Opening a conversation reads it. Only bother the server when
|
||||
// something is actually unread.
|
||||
if (thread.unread_count > 0) {
|
||||
markThreadRead(id).then(() => onRead?.(id)).catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch((e) => (error = e instanceof Error ? e.message : 'failed to load thread'))
|
||||
.finally(() => (loading = false));
|
||||
});
|
||||
|
||||
// Counted from what's loaded rather than the summary captured when the
|
||||
// thread was opened, which goes stale once a reply is sent into it.
|
||||
const count = $derived(messages.length || thread.message_count);
|
||||
|
||||
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">{count} {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'}
|
||||
{#if message.source === 'sent'}<span class="sent-tag">sent</span>{/if}
|
||||
</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}
|
||||
<div class="reply-bar">
|
||||
<button onclick={() => onReply(message, false)}>Reply</button>
|
||||
<button onclick={() => onReply(message, true)}>Reply all</button>
|
||||
</div>
|
||||
{/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;
|
||||
}
|
||||
.sent-tag {
|
||||
margin-left: 0.4rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
padding: 0 0.35rem;
|
||||
border-radius: 0.6rem;
|
||||
background: var(--secondary);
|
||||
}
|
||||
.reply-bar {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
padding: 0.5rem 0.8rem;
|
||||
border-top: 1px solid var(--secondary);
|
||||
}
|
||||
.reply-bar button {
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
border: 1px solid var(--secondary);
|
||||
background: none;
|
||||
color: var(--text);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.25rem 0.7rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.reply-bar button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.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>
|
||||
+116
-3
@@ -43,24 +43,69 @@ export interface MessageSummary {
|
||||
subject: string | null;
|
||||
from_addr: string | null;
|
||||
from_name: string | null;
|
||||
to_addrs: string[];
|
||||
cc_addrs: string[];
|
||||
sent_at: string | null;
|
||||
thread_id: string;
|
||||
flags: string[];
|
||||
/** 'imap' for received mail, 'sent' for mail sent from Tern. */
|
||||
source: 'imap' | 'sent';
|
||||
}
|
||||
|
||||
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> {
|
||||
@@ -70,3 +115,71 @@ export async function login(username: string, password: string): Promise<void> {
|
||||
});
|
||||
setSessionToken(res.token);
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email_address: string | null;
|
||||
display_name: string | null;
|
||||
}
|
||||
|
||||
export type OutboxStatus = 'draft' | 'pending' | 'sending' | 'sent' | 'failed';
|
||||
|
||||
export interface OutboxItem {
|
||||
id: string;
|
||||
account_id: string;
|
||||
status: OutboxStatus;
|
||||
to_addrs: string[];
|
||||
cc_addrs: string[];
|
||||
bcc_addrs: string[];
|
||||
subject: string;
|
||||
text_body: string;
|
||||
thread_id: string | null;
|
||||
attempts: number;
|
||||
last_error: string | null;
|
||||
next_attempt_at: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ComposeFields {
|
||||
to: string[];
|
||||
cc: string[];
|
||||
bcc: string[];
|
||||
subject: string;
|
||||
text_body: string;
|
||||
}
|
||||
|
||||
export function listAccounts(): Promise<Account[]> {
|
||||
return request('/accounts');
|
||||
}
|
||||
|
||||
export function markThreadRead(threadId: string): Promise<{ updated: number }> {
|
||||
return request(`/threads/${threadId}/read`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function listOutbox(): Promise<OutboxItem[]> {
|
||||
return request('/outbox');
|
||||
}
|
||||
|
||||
export function createOutboxItem(
|
||||
fields: ComposeFields & {
|
||||
account_id?: string;
|
||||
reply_to_message_id?: string;
|
||||
send: boolean;
|
||||
},
|
||||
): Promise<OutboxItem> {
|
||||
return request('/outbox', { method: 'POST', body: JSON.stringify(fields) });
|
||||
}
|
||||
|
||||
export function updateDraft(id: string, fields: ComposeFields): Promise<OutboxItem> {
|
||||
return request(`/outbox/${id}`, { method: 'PUT', body: JSON.stringify(fields) });
|
||||
}
|
||||
|
||||
export function sendOutboxItem(id: string): Promise<OutboxItem> {
|
||||
return request(`/outbox/${id}/send`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function deleteOutboxItem(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/outbox/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { MessageDetail } from './api';
|
||||
import { formatFullDate } from './format';
|
||||
|
||||
/** What the compose dialog opens with. */
|
||||
export interface ComposeSeed {
|
||||
to: string[];
|
||||
cc: string[];
|
||||
bcc: string[];
|
||||
subject: string;
|
||||
text_body: string;
|
||||
/** Present when replying; threading headers are derived server-side from it. */
|
||||
replyToMessageId?: string;
|
||||
accountId?: string;
|
||||
/** Present when reopening an existing draft or failed message. */
|
||||
draftId?: string;
|
||||
}
|
||||
|
||||
export function emptySeed(accountId?: string): ComposeSeed {
|
||||
return { to: [], cc: [], bcc: [], subject: '', text_body: '', accountId };
|
||||
}
|
||||
|
||||
export function replySubject(subject: string | null): string {
|
||||
const s = (subject ?? '').trim();
|
||||
return /^re:/i.test(s) ? s : `Re: ${s}`;
|
||||
}
|
||||
|
||||
function quote(message: MessageDetail): string {
|
||||
const text = message.body?.text_body?.trimEnd();
|
||||
if (!text) return '';
|
||||
const who = message.from_name || message.from_addr || 'someone';
|
||||
const quoted = text
|
||||
.split('\n')
|
||||
.map((line) => (line.startsWith('>') ? `>${line}` : `> ${line}`))
|
||||
.join('\n');
|
||||
return `\n\nOn ${formatFullDate(message.sent_at)}, ${who} wrote:\n${quoted}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replying to your own sent message means continuing to write to the same
|
||||
* people, not to yourself — so recipients come from its To line instead.
|
||||
*/
|
||||
export function replySeed(message: MessageDetail, ownAddresses: string[], all: boolean): ComposeSeed {
|
||||
const own = new Set(ownAddresses.map((a) => a.toLowerCase()));
|
||||
const notOwn = (a: string) => !own.has(a.toLowerCase());
|
||||
const dedupe = (list: string[]) =>
|
||||
list.filter((a, i) => list.findIndex((b) => b.toLowerCase() === a.toLowerCase()) === i);
|
||||
|
||||
const fromSelf = message.source === 'sent' || (message.from_addr ? own.has(message.from_addr.toLowerCase()) : false);
|
||||
|
||||
let to: string[];
|
||||
let cc: string[] = [];
|
||||
if (fromSelf) {
|
||||
to = [...message.to_addrs];
|
||||
if (all) cc = [...message.cc_addrs];
|
||||
} else {
|
||||
to = message.from_addr ? [message.from_addr] : [];
|
||||
if (all) {
|
||||
to = [...to, ...message.to_addrs];
|
||||
cc = [...message.cc_addrs];
|
||||
}
|
||||
}
|
||||
|
||||
to = dedupe(to.filter(notOwn));
|
||||
cc = dedupe(cc.filter(notOwn)).filter((a) => !to.some((t) => t.toLowerCase() === a.toLowerCase()));
|
||||
|
||||
return {
|
||||
to,
|
||||
cc,
|
||||
bcc: [],
|
||||
subject: replySubject(message.subject),
|
||||
text_body: quote(message),
|
||||
replyToMessageId: message.id,
|
||||
accountId: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Splits a free-typed recipient field on commas, semicolons and whitespace. */
|
||||
export function parseRecipients(input: string): string[] {
|
||||
return input
|
||||
.split(/[,;\s]+/)
|
||||
.map((a) => a.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
+3
-2
@@ -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',
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user