Compare commits
No files matched your search
@@ -19,6 +19,18 @@ jobs:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Gitea rejects a workflow file it can't parse without running
|
||||
# anything, which for release.yml only shows up when a tag is pushed.
|
||||
# Parsing them all here catches that on master, before tagging.
|
||||
- name: Check workflow files parse
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, yaml
|
||||
for f in sorted(glob.glob(".gitea/workflows/*.yml")):
|
||||
yaml.safe_load(open(f))
|
||||
print("ok", f)
|
||||
PY
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -23,8 +23,12 @@ jobs:
|
||||
- name: Type check
|
||||
run: npm run check
|
||||
|
||||
# The API is its own origin when deployed. Overridable with the
|
||||
# TERN_API_URL repository variable.
|
||||
- name: Build
|
||||
run: npm run build
|
||||
env:
|
||||
VITE_TERN_API: ${{ vars.TERN_API_URL || 'https://tern-api.mtps.pl' }}
|
||||
|
||||
- name: Create release archive
|
||||
run: |
|
||||
@@ -44,3 +48,28 @@ jobs:
|
||||
files: |-
|
||||
tern-web-*.tgz
|
||||
tern-web-*.tgz.sha256
|
||||
|
||||
# Deploys the release just published to tern.mtps.pl (deploy/static on
|
||||
# the swarm; see deploy/static.yml).
|
||||
deploy:
|
||||
needs: release
|
||||
runs-on: rocky-10
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Derive version
|
||||
id: version
|
||||
env:
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
run: echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Deploy
|
||||
uses: https://git.app.ygg/ygg/actions/deploy@v2
|
||||
with:
|
||||
type: static
|
||||
dist-path: deploy/static.yml
|
||||
extra-vars: |
|
||||
version=${{ steps.version.outputs.version }}
|
||||
ssh-key: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
known-hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
@@ -2,18 +2,45 @@
|
||||
|
||||
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: mail client with organisation and spam handling** (build order phases 3–6). 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.
|
||||
- **Views, folders and tags** in the sidebar (Inbox, All mail, Sent, Outbox, Junk, Trash, your folders, your tags), with tag chips on list rows.
|
||||
- **Conversation lists load older pages as you scroll** (or press `j` past the end), with a *Load older* button as a keyboard-reachable fallback.
|
||||
- **Spam** — *Report spam* / *Not spam* (`!`), each message's spam score shown as a badge, and an **Add spam filter** preset in Rules.
|
||||
- **Conversation actions** — archive, delete/restore, mark read/unread, move, tag — from a toolbar, a right-click context menu (native Popover API, §5), or the keyboard. Keyboard actions apply to the row under the cursor when nothing is open, so mail can be triaged straight from the list.
|
||||
- **Rules editor** — conditions and actions edited as the structured JSON they're stored as, so anything the API accepts the editor can show. Each rule can stop later rules when it matches, and **Run now** applies it to existing mail. Server validation errors (e.g. a bad regex) appear inline without losing the form.
|
||||
- **Trash** shows when each conversation will be permanently deleted.
|
||||
- **Keyboard shortcuts** (§4a): `j`/`k`, `Enter`/`o`, `u`/`Esc`, `g`/`G`, `e` archive, `#` delete/restore, `!` spam/not spam, `Shift+I`/`Shift+U` read/unread, `v`/`l` move/tag, `c`, `r`/`a`, `Shift+R`, `?`.
|
||||
- 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): search, attachment download, 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
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# tern-web's deployment: a Swarm stack of ygg/static-server serving this
|
||||
# version's release asset, on tern.mtps.pl (deploy/static in the ygg
|
||||
# management repo). Run by this repo's release workflow through
|
||||
# ygg/actions/deploy; `version` arrives as an extra var (the tag without
|
||||
# its v) and is templated in by Ansible.
|
||||
#
|
||||
# The webapp talks to tern-server at tern-api.mtps.pl, baked in at build
|
||||
# time (VITE_TERN_API in the release workflow).
|
||||
|
||||
static_stack_name: tern-web
|
||||
|
||||
domain: tern.mtps.pl
|
||||
cert: mtps.pl
|
||||
|
||||
static_service:
|
||||
name: static
|
||||
image: git.app.ygg/ygg/static-server:latest
|
||||
environment:
|
||||
GITEA_REPOSITORY_URL: https://git.app.ygg/mtps/tern-web
|
||||
GITEA_RELEASE: "v{{ version }}"
|
||||
GITEA_ASSET_NAME: "tern-web-{{ version }}.tgz"
|
||||
SSL_CERT_FILE: /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
|
||||
volumes:
|
||||
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:ro
|
||||
ports:
|
||||
- target: 8080
|
||||
published: 11902
|
||||
protocol: tcp
|
||||
mode: ingress
|
||||
replicas: 2
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "tern-web",
|
||||
"version": "0.1.0",
|
||||
"version": "0.8.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tern-web",
|
||||
"version": "0.1.0",
|
||||
"version": "0.8.4",
|
||||
"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.8.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
<script lang="ts">
|
||||
// The mail accounts Tern syncs, with how each one's sync is going, and
|
||||
// the form to connect another. Only the server ever talks to the mail
|
||||
// server (server-architecture-spec.md §2); this screen just hands it the
|
||||
// settings and shows what it reports back.
|
||||
import { createAccount, deleteAccount, listAccounts, type Account } from './api';
|
||||
import { formatFullDate } from './format';
|
||||
|
||||
let {
|
||||
reloadKey = 0,
|
||||
onChanged,
|
||||
}: {
|
||||
/** Bumped by the parent when accounts change elsewhere (another tab). */
|
||||
reloadKey?: number;
|
||||
/** Tells the parent the account list changed (sidebar, compose). */
|
||||
onChanged?: () => void;
|
||||
} = $props();
|
||||
|
||||
/** Sync status isn't pushed as an event, so an open screen polls it. */
|
||||
const STATUS_POLL_MS = 5_000;
|
||||
|
||||
let accounts = $state<Account[]>([]);
|
||||
let loaded = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let adding = $state(false);
|
||||
let saving = $state(false);
|
||||
let formError = $state<string | null>(null);
|
||||
|
||||
// Form fields. Login and hosts follow the address until edited by hand.
|
||||
let email = $state('');
|
||||
let displayName = $state('');
|
||||
let imapHost = $state('');
|
||||
let imapPort = $state(993);
|
||||
let smtpHost = $state('');
|
||||
let smtpPort = $state(587);
|
||||
let login = $state('');
|
||||
let password = $state('');
|
||||
let loginEdited = $state(false);
|
||||
let hostsEdited = $state(false);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
accounts = await listAccounts();
|
||||
error = null;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to load accounts';
|
||||
} finally {
|
||||
loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Loads on mount and whenever the parent bumps reloadKey; polls while open.
|
||||
$effect(() => {
|
||||
void reloadKey;
|
||||
load();
|
||||
});
|
||||
$effect(() => {
|
||||
const timer = setInterval(load, STATUS_POLL_MS);
|
||||
return () => clearInterval(timer);
|
||||
});
|
||||
|
||||
// With no account yet, the form is the whole point of the screen.
|
||||
$effect(() => {
|
||||
if (loaded && accounts.length === 0) adding = true;
|
||||
});
|
||||
|
||||
function emailChanged() {
|
||||
const domain = email.includes('@') ? email.split('@')[1] : '';
|
||||
if (!loginEdited) login = email;
|
||||
if (!hostsEdited) {
|
||||
imapHost = domain ? `mail.${domain}` : '';
|
||||
smtpHost = imapHost;
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
email = displayName = imapHost = smtpHost = login = password = '';
|
||||
imapPort = 993;
|
||||
smtpPort = 587;
|
||||
loginEdited = hostsEdited = false;
|
||||
formError = null;
|
||||
}
|
||||
|
||||
async function add(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
saving = true;
|
||||
formError = null;
|
||||
try {
|
||||
await createAccount({
|
||||
name: email.split('@')[1] || email,
|
||||
imap_host: imapHost.trim(),
|
||||
imap_port: Number(imapPort),
|
||||
smtp_host: smtpHost.trim(),
|
||||
smtp_port: Number(smtpPort),
|
||||
username: login.trim(),
|
||||
password,
|
||||
email_address: email.trim() || null,
|
||||
display_name: displayName.trim() || null,
|
||||
});
|
||||
resetForm();
|
||||
adding = false;
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (e) {
|
||||
formError = e instanceof Error ? e.message : 'failed to add the account';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(a: Account) {
|
||||
const what = a.email_address ?? a.username;
|
||||
const count = a.sync?.messages ?? 0;
|
||||
if (
|
||||
!confirm(
|
||||
`Remove ${what}?\n\nTern stops syncing it and deletes the ${count} message${count === 1 ? '' : 's'} it synced from it, ` +
|
||||
`including anything you've tagged or filed. Mail on your mail server isn't touched — adding the account again re-syncs the inbox.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await deleteAccount(a.id);
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to remove the account';
|
||||
}
|
||||
}
|
||||
|
||||
function statusText(a: Account): string {
|
||||
const s = a.sync;
|
||||
if (!s || s.status === 'pending') return 'Waiting to connect…';
|
||||
switch (s.status) {
|
||||
case 'syncing':
|
||||
return s.caught_up ? 'Connecting…' : 'First sync in progress…';
|
||||
case 'idle':
|
||||
return 'Connected — new mail arrives as it lands';
|
||||
case 'error':
|
||||
return 'Can’t sync — retrying';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="accounts">
|
||||
<header>
|
||||
<h2>Accounts</h2>
|
||||
{#if !adding}
|
||||
<button class="primary" onclick={() => { resetForm(); adding = true; }}>Add account</button>
|
||||
{/if}
|
||||
</header>
|
||||
<p class="hint">
|
||||
The mailboxes Tern syncs. Your Tern server connects to each one itself — IMAP over TLS on port 993 to
|
||||
read, SMTP on 587 (STARTTLS) or 465 to send — so the mail server has to be reachable from it.
|
||||
</p>
|
||||
{#if error}<p class="error">{error}</p>{/if}
|
||||
|
||||
{#if accounts.length > 0}
|
||||
<ul>
|
||||
{#each accounts as a (a.id)}
|
||||
<li>
|
||||
<span class="dot state-{a.sync?.status ?? 'pending'}" aria-hidden="true"></span>
|
||||
<div class="body">
|
||||
<strong>{a.display_name ? `${a.display_name} <${a.email_address ?? a.username}>` : (a.email_address ?? a.username)}</strong>
|
||||
<span class="detail">IMAP {a.imap_host}:{a.imap_port} · SMTP {a.smtp_host}:{a.smtp_port} · login {a.username}</span>
|
||||
<span class="status state-{a.sync?.status ?? 'pending'}">
|
||||
{statusText(a)}{#if a.sync}{` · ${a.sync.messages} message${a.sync.messages === 1 ? '' : 's'}`}{/if}
|
||||
</span>
|
||||
{#if a.sync?.status === 'error' && a.sync.last_error}
|
||||
<span class="last-error">{a.sync.last_error}</span>
|
||||
{/if}
|
||||
{#if a.sync}<span class="detail">Last update {formatFullDate(a.sync.updated_at)}</span>{/if}
|
||||
</div>
|
||||
<button onclick={() => remove(a)}>Remove</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if adding}
|
||||
<form onsubmit={add}>
|
||||
<h3>{accounts.length === 0 ? 'Connect your first mailbox' : 'Add an account'}</h3>
|
||||
<label class="wide">Email address
|
||||
<input type="email" bind:value={email} oninput={emailChanged} required autocomplete="email" />
|
||||
</label>
|
||||
<label class="wide">Your name <span class="optional">(optional, shown on mail you send)</span>
|
||||
<input bind:value={displayName} autocomplete="name" />
|
||||
</label>
|
||||
<label>IMAP server
|
||||
<input bind:value={imapHost} oninput={() => (hostsEdited = true)} required />
|
||||
</label>
|
||||
<label class="port">Port
|
||||
<input type="number" min="1" max="65535" bind:value={imapPort} required />
|
||||
</label>
|
||||
<label>SMTP server
|
||||
<input bind:value={smtpHost} oninput={() => (hostsEdited = true)} required />
|
||||
</label>
|
||||
<label class="port">Port
|
||||
<input type="number" min="1" max="65535" bind:value={smtpPort} required />
|
||||
</label>
|
||||
<label class="wide">Login
|
||||
<input bind:value={login} oninput={() => (loginEdited = true)} required autocomplete="username" />
|
||||
</label>
|
||||
<label class="wide">Password
|
||||
<input type="password" bind:value={password} required autocomplete="current-password" />
|
||||
</label>
|
||||
<p class="hint wide">
|
||||
Stored encrypted on your Tern server, never in this browser. Tern only reads your inbox and sends —
|
||||
it never changes anything on the mail server.
|
||||
</p>
|
||||
{#if formError}<p class="error wide">{formError}</p>{/if}
|
||||
<div class="actions wide">
|
||||
{#if accounts.length > 0}
|
||||
<button type="button" onclick={() => { adding = false; resetForm(); }}>Cancel</button>
|
||||
{/if}
|
||||
<button type="submit" class="primary" disabled={saving}>{saving ? 'Adding…' : 'Add account'}</button>
|
||||
</div>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.accounts {
|
||||
overflow-y: auto;
|
||||
height: 100%;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.25rem 1.25rem 0;
|
||||
}
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
h3 {
|
||||
grid-column: 1 / -1;
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.hint,
|
||||
.error {
|
||||
padding: 0 1.25rem;
|
||||
font-size: 0.82rem;
|
||||
color: var(--primary);
|
||||
max-width: 48rem;
|
||||
}
|
||||
.error {
|
||||
color: var(--accent);
|
||||
}
|
||||
ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 1.25rem 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
li {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
padding: 0.7rem 0.75rem;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.45rem;
|
||||
}
|
||||
.body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
.detail {
|
||||
font-size: 0.78rem;
|
||||
color: var(--primary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.status {
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
.status.state-error {
|
||||
color: var(--accent);
|
||||
}
|
||||
.last-error {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.75rem;
|
||||
color: var(--accent);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dot {
|
||||
flex-shrink: 0;
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
margin-top: 0.35rem;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--primary);
|
||||
}
|
||||
.dot.state-idle {
|
||||
background: var(--primary);
|
||||
}
|
||||
.dot.state-syncing {
|
||||
border-style: dashed;
|
||||
}
|
||||
.dot.state-error {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
form {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 6rem;
|
||||
gap: 0.6rem 0.75rem;
|
||||
margin: 0 1.25rem 1.25rem;
|
||||
padding: 1rem;
|
||||
max-width: 34rem;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.45rem;
|
||||
}
|
||||
form .hint,
|
||||
form .error {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.optional {
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
input {
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
color: var(--text);
|
||||
background: var(--background);
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.35rem 0.5rem;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.25rem 0.6rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,165 @@
|
||||
<script lang="ts">
|
||||
// One menu for a conversation's actions, used for both the right-click
|
||||
// context menu and the toolbar's "More" button (webapp-client-spec.md
|
||||
// §4a). Native Popover API (§5): light-dismiss and Escape come free.
|
||||
import type { Action, Folder, MailView, Tag, ThreadSummary } from './api';
|
||||
|
||||
let {
|
||||
at,
|
||||
thread,
|
||||
view,
|
||||
folders,
|
||||
tags,
|
||||
onAction,
|
||||
onClose,
|
||||
}: {
|
||||
/** Viewport position to open at; null closes the menu. */
|
||||
at: { x: number; y: number } | null;
|
||||
thread: ThreadSummary | null;
|
||||
view: MailView;
|
||||
folders: Folder[];
|
||||
tags: Tag[];
|
||||
onAction: (actions: Action[]) => void;
|
||||
onClose: () => void;
|
||||
} = $props();
|
||||
|
||||
let menu = $state<HTMLElement | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (!menu) return;
|
||||
const open = menu.matches(':popover-open');
|
||||
if (at && !open) {
|
||||
menu.style.left = '0px';
|
||||
menu.style.top = '0px';
|
||||
menu.showPopover();
|
||||
// Measure once shown, then keep the whole menu inside the viewport.
|
||||
const { width, height } = menu.getBoundingClientRect();
|
||||
menu.style.left = `${Math.max(4, Math.min(at.x, innerWidth - width - 4))}px`;
|
||||
menu.style.top = `${Math.max(4, Math.min(at.y, innerHeight - height - 4))}px`;
|
||||
menu.querySelector<HTMLButtonElement>('button')?.focus();
|
||||
} else if (!at && open) {
|
||||
menu.hidePopover();
|
||||
}
|
||||
});
|
||||
|
||||
function pick(actions: Action[]) {
|
||||
// Close through our own path rather than waiting on the popover's
|
||||
// toggle event, which browsers may defer (see Compose.svelte).
|
||||
onAction(actions);
|
||||
onClose();
|
||||
}
|
||||
|
||||
const inTrash = $derived(view.kind === 'trash');
|
||||
const inJunk = $derived(view.kind === 'junk');
|
||||
const tagged = (id: string) => thread?.tag_ids.includes(id) ?? false;
|
||||
</script>
|
||||
|
||||
<div
|
||||
bind:this={menu}
|
||||
popover="auto"
|
||||
class="menu"
|
||||
role="menu"
|
||||
ontoggle={(e) => { if ((e as ToggleEvent).newState === 'closed') onClose(); }}
|
||||
>
|
||||
{#if thread}
|
||||
{#if inTrash}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'restore' }])}>Restore</button>
|
||||
{:else}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'archive' }])}>Archive <kbd>e</kbd></button>
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'delete' }])}>Delete <kbd>#</kbd></button>
|
||||
{#if inJunk}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'move', folder_id: null }])}>Not spam <kbd>!</kbd></button>
|
||||
{:else}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'junk' }])}>Report spam <kbd>!</kbd></button>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if thread.unread_count > 0}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'mark_read' }])}>Mark read <kbd>I</kbd></button>
|
||||
{:else}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'mark_unread' }])}>Mark unread <kbd>U</kbd></button>
|
||||
{/if}
|
||||
|
||||
<p class="heading">Move to</p>
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'move', folder_id: null }])}>Inbox</button>
|
||||
{#each folders.filter((f) => f.role !== 'junk') as f (f.id)}
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'move', folder_id: f.id }])}>{f.name}</button>
|
||||
{/each}
|
||||
|
||||
{#if tags.length > 0}
|
||||
<p class="heading">Tags</p>
|
||||
{#each tags as t (t.id)}
|
||||
<button
|
||||
role="menuitemcheckbox"
|
||||
aria-checked={tagged(t.id)}
|
||||
onclick={() => pick([{ type: tagged(t.id) ? 'untag' : 'tag', tag_id: t.id }])}
|
||||
>
|
||||
<span class="dot" style:background={t.color ?? 'var(--primary)'}></span>
|
||||
{t.name}
|
||||
{#if tagged(t.id)}<span class="check">✓</span>{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.menu {
|
||||
position: fixed;
|
||||
margin: 0;
|
||||
inset: auto;
|
||||
min-width: 13rem;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
padding: 0.3rem;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.45rem;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
box-shadow: 0 8px 24px rgb(0 0 0 / 0.25);
|
||||
}
|
||||
button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 0.35rem 0.6rem;
|
||||
border: none;
|
||||
border-radius: 0.3rem;
|
||||
background: none;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover,
|
||||
button:focus-visible {
|
||||
background: color-mix(in srgb, var(--secondary) 60%, transparent);
|
||||
outline: none;
|
||||
}
|
||||
.heading {
|
||||
margin: 0.4rem 0.6rem 0.15rem;
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--primary);
|
||||
}
|
||||
.dot {
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.check {
|
||||
margin-left: auto;
|
||||
color: var(--accent);
|
||||
}
|
||||
kbd {
|
||||
margin-left: auto;
|
||||
font-size: 0.7rem;
|
||||
color: var(--primary);
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.2rem;
|
||||
padding: 0 0.25rem;
|
||||
}
|
||||
</style>
|
||||
@@ -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>
|
||||
+821
-76
@@ -1,126 +1,871 @@
|
||||
<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 {
|
||||
createFolder,
|
||||
createTag,
|
||||
deleteFolder,
|
||||
deleteTag,
|
||||
listAccounts,
|
||||
listFolders,
|
||||
listOutbox,
|
||||
listTags,
|
||||
listThreads,
|
||||
threadActions,
|
||||
clearSessionToken,
|
||||
type Account,
|
||||
type Action,
|
||||
type Folder,
|
||||
type LiveEvent,
|
||||
type MailView,
|
||||
type MessageDetail,
|
||||
type OutboxItem,
|
||||
type Tag,
|
||||
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 RulesView from './RulesView.svelte';
|
||||
import AccountsView from './AccountsView.svelte';
|
||||
import ActionMenu from './ActionMenu.svelte';
|
||||
import Compose from './Compose.svelte';
|
||||
import ShortcutHelp from './ShortcutHelp.svelte';
|
||||
import { startLive, type LiveStatus } from './live';
|
||||
import { alertState, disableAlerts, enableAlerts, showAlert, type AlertState } from './notify';
|
||||
|
||||
// After sending without a live connection, watch the outbox closely so
|
||||
// the reader sees the message go out rather than waiting for a slow poll.
|
||||
const SEND_WATCH_INTERVAL_MS = 1_500;
|
||||
const SEND_WATCH_LIMIT_MS = 20_000;
|
||||
const TAG_COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#64748b'];
|
||||
|
||||
let accounts = $state<Account[]>([]);
|
||||
let folders = $state<Folder[]>([]);
|
||||
let messages = $state<MessageSummary[]>([]);
|
||||
let selectedFolderId = $state<string | undefined>(undefined);
|
||||
let selectedMessage = $state<MessageSummary | null>(null);
|
||||
let loadError = $state<string | null>(null);
|
||||
let tags = $state<Tag[]>([]);
|
||||
let threads = $state<ThreadSummary[]>([]);
|
||||
let nextCursor = $state<string | null>(null);
|
||||
let loadingMore = $state(false);
|
||||
let outbox = $state<OutboxItem[]>([]);
|
||||
let section = $state<'mail' | 'outbox' | 'rules' | 'accounts'>('mail');
|
||||
let mailView = $state<MailView>({ kind: 'inbox' });
|
||||
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 menu = $state<{ thread: ThreadSummary; at: { x: number; y: number } } | null>(null);
|
||||
let adding = $state<'folder' | 'tag' | null>(null);
|
||||
let newName = $state('');
|
||||
let liveStatus = $state<LiveStatus>('connecting');
|
||||
let alerts = $state<AlertState>(alertState());
|
||||
let rulesReloadKey = $state(0);
|
||||
let accountsReloadKey = $state(0);
|
||||
/** Accounts have been fetched at least once (so "none" means none). */
|
||||
let accountsLoaded = $state(false);
|
||||
/** In-page notices for new mail; OS alerts replace them while the tab is hidden. */
|
||||
let toasts = $state<{ key: number; threadId: string | null; from: string; subject: string }[]>([]);
|
||||
let toastSeq = 0;
|
||||
/** New mail that notified while the reader was looking elsewhere — shown in the tab title. */
|
||||
let unseen = $state(0);
|
||||
|
||||
const ownAddresses = $derived(
|
||||
accounts.flatMap((a) => [a.email_address, a.username]).filter((a): a is string => !!a && a.includes('@')),
|
||||
);
|
||||
const outboxCount = $derived(outbox.length);
|
||||
const viewTitle = $derived.by(() => {
|
||||
switch (mailView.kind) {
|
||||
case 'inbox': return 'Inbox';
|
||||
case 'all': return 'All mail';
|
||||
case 'sent': return 'Sent';
|
||||
case 'trash': return 'Trash';
|
||||
case 'junk': return 'Junk';
|
||||
case 'folder': { const id = mailView.id; return folders.find((f) => f.id === id)?.name ?? 'Folder'; }
|
||||
case 'tag': { const id = mailView.id; return tags.find((t) => t.id === id)?.name ?? 'Tag'; }
|
||||
}
|
||||
});
|
||||
|
||||
function isView(v: MailView): boolean {
|
||||
if (section !== 'mail' || v.kind !== mailView.kind) return false;
|
||||
return !('id' in v) || ('id' in mailView && v.id === mailView.id);
|
||||
}
|
||||
|
||||
const PAGE = 50;
|
||||
const MAX_PAGE = 200;
|
||||
|
||||
/**
|
||||
* Re-reads the list from the top. Asks for as many rows as are currently
|
||||
* loaded (up to the API's cap), so refreshing after an action doesn't
|
||||
* collapse a list the reader has scrolled deep into back to one page.
|
||||
*/
|
||||
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(mailView, undefined, Math.min(MAX_PAGE, Math.max(PAGE, threads.length)));
|
||||
threads = page.threads;
|
||||
nextCursor = page.next_cursor;
|
||||
// Keep the open conversation's summary current (tags, counts), or
|
||||
// drop it if an action moved it out of this view.
|
||||
if (selected) selected = threads.find((t) => t.thread_id === selected!.thread_id) ?? null;
|
||||
activeIndex = Math.min(activeIndex, Math.max(threads.length - 1, 0));
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to load conversations';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(refresh);
|
||||
async function loadMore() {
|
||||
if (!nextCursor || loadingMore) return;
|
||||
loadingMore = true;
|
||||
const view = mailView;
|
||||
try {
|
||||
const page = await listThreads(view, nextCursor, PAGE);
|
||||
// The view may have changed while this was in flight.
|
||||
if (view !== mailView) return;
|
||||
const known = new Set(threads.map((t) => t.thread_id));
|
||||
threads = [...threads, ...page.threads.filter((t) => !known.has(t.thread_id))];
|
||||
nextCursor = page.next_cursor;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to load older conversations';
|
||||
} finally {
|
||||
loadingMore = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectFolder(id: string | undefined) {
|
||||
selectedFolderId = id;
|
||||
selectedMessage = null;
|
||||
async function refreshMeta() {
|
||||
[folders, tags] = await Promise.all([listFolders(), listTags()]);
|
||||
}
|
||||
|
||||
async function refreshAccounts() {
|
||||
try {
|
||||
accounts = await listAccounts();
|
||||
accountsLoaded = true;
|
||||
} catch {
|
||||
// Non-critical here; the Accounts screen shows its own errors.
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshOutbox() {
|
||||
try {
|
||||
outbox = await listOutbox();
|
||||
} catch {
|
||||
// Non-critical; the next action or poll retries.
|
||||
}
|
||||
}
|
||||
|
||||
function reloadAll() {
|
||||
refreshMeta().catch(() => {});
|
||||
refreshAccounts();
|
||||
refreshList();
|
||||
refreshOutbox();
|
||||
rulesReloadKey++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the list, and the open conversation only if it gained or lost
|
||||
* messages — reloading it for a flag or tag change would collapse what
|
||||
* the reader expanded and re-block images they'd allowed.
|
||||
*/
|
||||
async function refreshList() {
|
||||
const before = selected?.message_count;
|
||||
await refresh();
|
||||
if (selected && selected.message_count !== before) threadReloadKey++;
|
||||
}
|
||||
|
||||
function onEvents(events: LiveEvent[]) {
|
||||
let mail = false;
|
||||
let outboxChanged = false;
|
||||
for (const e of events) {
|
||||
switch (e.kind) {
|
||||
case 'message_new':
|
||||
mail = true;
|
||||
if (e.data.notify) announce(e.data.thread_id, e.data.from ?? 'Unknown sender', e.data.subject ?? '(no subject)');
|
||||
break;
|
||||
case 'mailbox_changed':
|
||||
mail = true;
|
||||
break;
|
||||
case 'outbox_changed':
|
||||
outboxChanged = true;
|
||||
break;
|
||||
case 'config_changed':
|
||||
if (e.data.what === 'accounts') {
|
||||
refreshAccounts();
|
||||
accountsReloadKey++;
|
||||
}
|
||||
else if (e.data.what === 'rules') rulesReloadKey++;
|
||||
else {
|
||||
refreshMeta().catch(() => {});
|
||||
// Tag chips and folder names show in the list too.
|
||||
mail = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mail && section === 'mail') refreshList();
|
||||
if (outboxChanged) refreshOutbox();
|
||||
}
|
||||
|
||||
function lookingAtTab(): boolean {
|
||||
return document.visibilityState === 'visible' && document.hasFocus();
|
||||
}
|
||||
|
||||
function announce(threadId: string | null, from: string, subject: string) {
|
||||
if (lookingAtTab()) {
|
||||
const key = ++toastSeq;
|
||||
toasts = [...toasts.slice(-2), { key, threadId, from, subject }];
|
||||
setTimeout(() => (toasts = toasts.filter((t) => t.key !== key)), 8_000);
|
||||
return;
|
||||
}
|
||||
unseen++;
|
||||
showAlert(from, subject, threadId ?? subject, () => threadId && openThreadById(threadId));
|
||||
}
|
||||
|
||||
function seen() {
|
||||
if (lookingAtTab()) unseen = 0;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
document.title = unseen > 0 ? `(${unseen}) Tern` : 'Tern';
|
||||
});
|
||||
|
||||
/** Opens a conversation from a notification, wherever it's filed. */
|
||||
async function openThreadById(id: string) {
|
||||
toasts = toasts.filter((t) => t.threadId !== id);
|
||||
let i = section === 'mail' ? threads.findIndex((t) => t.thread_id === id) : -1;
|
||||
if (i < 0) {
|
||||
// Not in this view (e.g. a rule filed it into a folder): All mail
|
||||
// shows it wherever it lives.
|
||||
showView({ kind: 'all' });
|
||||
await refresh();
|
||||
i = threads.findIndex((t) => t.thread_id === id);
|
||||
}
|
||||
if (i >= 0) open(threads[i], i);
|
||||
}
|
||||
|
||||
async function toggleAlerts() {
|
||||
alerts = alerts === 'on' ? disableAlerts() : await enableAlerts();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
reloadAll();
|
||||
const stop = startLive({
|
||||
onEvents,
|
||||
onReset: reloadAll,
|
||||
onStatus: (s) => (liveStatus = s),
|
||||
onUnauthorized: () => {
|
||||
// Back to the sign-in screen rather than a UI that silently fails.
|
||||
clearSessionToken();
|
||||
location.reload();
|
||||
},
|
||||
});
|
||||
return stop;
|
||||
});
|
||||
|
||||
function showView(v: MailView) {
|
||||
section = 'mail';
|
||||
mailView = v;
|
||||
threads = [];
|
||||
nextCursor = null;
|
||||
selected = null;
|
||||
activeIndex = 0;
|
||||
loading = true;
|
||||
refresh();
|
||||
}
|
||||
|
||||
function showOutbox() {
|
||||
section = '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;
|
||||
}
|
||||
|
||||
/** The conversation an action applies to: the open one, else the row under the keyboard cursor. */
|
||||
function target(): ThreadSummary | null {
|
||||
return selected ?? threads[activeIndex] ?? null;
|
||||
}
|
||||
|
||||
async function act(thread: ThreadSummary, actions: Action[]) {
|
||||
try {
|
||||
await threadActions(thread.thread_id, actions);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'action failed';
|
||||
return;
|
||||
}
|
||||
// If the action took the conversation out of this view (archive, move,
|
||||
// delete), go back to the list with the cursor where it was, rather
|
||||
// than auto-opening the next one — opening marks it read.
|
||||
await refresh();
|
||||
threadReloadKey++;
|
||||
}
|
||||
|
||||
function openMenu(thread: ThreadSummary, x: number, y: number) {
|
||||
menu = { thread, at: { x, y } };
|
||||
}
|
||||
|
||||
async function addItem() {
|
||||
const name = newName.trim();
|
||||
if (!name) {
|
||||
adding = null;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (adding === 'folder') await createFolder(name);
|
||||
else await createTag(name, TAG_COLORS[tags.length % TAG_COLORS.length]);
|
||||
await refreshMeta();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed';
|
||||
}
|
||||
adding = null;
|
||||
newName = '';
|
||||
}
|
||||
|
||||
async function removeFolder(f: Folder) {
|
||||
if (!confirm(`Delete the folder "${f.name}"? Its mail goes back to the inbox.`)) return;
|
||||
await deleteFolder(f.id);
|
||||
if (mailView.kind === 'folder' && mailView.id === f.id) showView({ kind: 'inbox' });
|
||||
await refreshMeta();
|
||||
}
|
||||
|
||||
async function removeTag(t: Tag) {
|
||||
if (!confirm(`Delete the tag "${t.name}"? It's removed from all mail.`)) return;
|
||||
await deleteTag(t.id);
|
||||
if (mailView.kind === 'tag' && mailView.id === t.id) showView({ kind: 'inbox' });
|
||||
await refreshMeta();
|
||||
await refresh();
|
||||
}
|
||||
|
||||
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();
|
||||
// Live, the worker's own events report the send; this is the fallback.
|
||||
if (sentId && liveStatus !== 'live') 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 shortcuts (§4a: core UX, not a stretch feature).
|
||||
// Actions work on the open conversation, or on the row under the cursor
|
||||
// when none is open, so mail can be triaged straight from the list.
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
const el = event.target as HTMLElement | null;
|
||||
if (el && (el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName))) return;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (composeSeed || helpOpen || menu) return;
|
||||
|
||||
const newest = threadMessages[threadMessages.length - 1];
|
||||
const t = section === 'mail' ? target() : null;
|
||||
const inTrash = mailView.kind === 'trash';
|
||||
|
||||
switch (event.key) {
|
||||
case 'j':
|
||||
event.preventDefault();
|
||||
activeIndex = Math.min(activeIndex + 1, threads.length - 1);
|
||||
// Walking off the end with j pulls in the next page.
|
||||
if (activeIndex >= threads.length - 5) loadMore();
|
||||
break;
|
||||
case 'k':
|
||||
event.preventDefault();
|
||||
activeIndex = Math.max(activeIndex - 1, 0);
|
||||
break;
|
||||
case 'Enter':
|
||||
case 'o':
|
||||
if (section === '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 'e':
|
||||
if (t && !inTrash) {
|
||||
event.preventDefault();
|
||||
act(t, [{ type: 'archive' }]);
|
||||
}
|
||||
break;
|
||||
case '#':
|
||||
if (t) {
|
||||
event.preventDefault();
|
||||
act(t, [inTrash ? { type: 'restore' } : { type: 'delete' }]);
|
||||
}
|
||||
break;
|
||||
case '!':
|
||||
if (t && !inTrash) {
|
||||
event.preventDefault();
|
||||
act(t, [mailView.kind === 'junk' ? { type: 'move', folder_id: null } : { type: 'junk' }]);
|
||||
}
|
||||
break;
|
||||
case 'I':
|
||||
if (t) {
|
||||
event.preventDefault();
|
||||
act(t, [{ type: 'mark_read' }]);
|
||||
}
|
||||
break;
|
||||
case 'U':
|
||||
if (t) {
|
||||
event.preventDefault();
|
||||
act(t, [{ type: 'mark_unread' }]);
|
||||
}
|
||||
break;
|
||||
case 'v':
|
||||
case 'l': {
|
||||
if (!t) break;
|
||||
event.preventDefault();
|
||||
const row = document.querySelector<HTMLElement>(`[data-index="${activeIndex}"]`);
|
||||
const r = row?.getBoundingClientRect();
|
||||
openMenu(t, r ? r.left + 24 : 200, r ? r.bottom : 120);
|
||||
break;
|
||||
}
|
||||
case 'R':
|
||||
event.preventDefault();
|
||||
refresh();
|
||||
refreshOutbox();
|
||||
break;
|
||||
case '?':
|
||||
event.preventDefault();
|
||||
helpOpen = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKeydown} onfocus={seen} />
|
||||
<svelte:document onvisibilitychange={seen} />
|
||||
|
||||
<div class="shell">
|
||||
<nav class="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)}>
|
||||
{folder.name}
|
||||
</button>
|
||||
<nav class="sidebar" aria-label="Mailboxes">
|
||||
<button class="compose" onclick={compose}>Compose</button>
|
||||
|
||||
<button class:active={isView({ kind: 'inbox' })} onclick={() => showView({ kind: 'inbox' })}>Inbox</button>
|
||||
<button class:active={isView({ kind: 'all' })} onclick={() => showView({ kind: 'all' })}>All mail</button>
|
||||
<button class:active={isView({ kind: 'sent' })} onclick={() => showView({ kind: 'sent' })}>Sent</button>
|
||||
<button class:active={section === 'outbox'} onclick={showOutbox}>
|
||||
Outbox
|
||||
{#if outboxCount > 0}<span class="badge">{outboxCount}</span>{/if}
|
||||
</button>
|
||||
<button class:active={isView({ kind: 'junk' })} onclick={() => showView({ kind: 'junk' })}>Junk</button>
|
||||
<button class:active={isView({ kind: 'trash' })} onclick={() => showView({ kind: 'trash' })}>Trash</button>
|
||||
|
||||
<div class="group">
|
||||
<span>Folders</span>
|
||||
<button class="plus" aria-label="New folder" onclick={() => { adding = 'folder'; newName = ''; }}>+</button>
|
||||
</div>
|
||||
<!-- Junk is listed with the system views above, not among folders. -->
|
||||
{#each folders.filter((f) => f.role !== 'junk') as f (f.id)}
|
||||
<div class="item">
|
||||
<button class:active={isView({ kind: 'folder', id: f.id })} onclick={() => showView({ kind: 'folder', id: f.id })}>
|
||||
{f.name}
|
||||
</button>
|
||||
{#if f.role === null}
|
||||
<button class="remove" aria-label={`Delete folder ${f.name}`} onclick={() => removeFolder(f)}>✕</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if adding === 'folder'}
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input class="new" bind:value={newName} placeholder="Folder name" autofocus
|
||||
onkeydown={(e) => { if (e.key === 'Enter') addItem(); if (e.key === 'Escape') adding = null; }}
|
||||
onblur={addItem} />
|
||||
{/if}
|
||||
|
||||
<div class="group">
|
||||
<span>Tags</span>
|
||||
<button class="plus" aria-label="New tag" onclick={() => { adding = 'tag'; newName = ''; }}>+</button>
|
||||
</div>
|
||||
{#each tags as t (t.id)}
|
||||
<div class="item">
|
||||
<button class:active={isView({ kind: 'tag', id: t.id })} onclick={() => showView({ kind: 'tag', id: t.id })}>
|
||||
<span class="dot" style:background={t.color ?? 'var(--primary)'}></span>{t.name}
|
||||
</button>
|
||||
<button class="remove" aria-label={`Delete tag ${t.name}`} onclick={() => removeTag(t)}>✕</button>
|
||||
</div>
|
||||
{/each}
|
||||
{#if adding === 'tag'}
|
||||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input class="new" bind:value={newName} placeholder="Tag name" autofocus
|
||||
onkeydown={(e) => { if (e.key === 'Enter') addItem(); if (e.key === 'Escape') adding = null; }}
|
||||
onblur={addItem} />
|
||||
{/if}
|
||||
|
||||
<div class="bottom">
|
||||
<button class:active={section === 'rules'} onclick={() => { section = 'rules'; selected = null; }}>Rules</button>
|
||||
<button class:active={section === 'accounts'} onclick={() => { section = 'accounts'; selected = null; }}>Accounts</button>
|
||||
{#if alerts === 'on' || alerts === 'off'}
|
||||
<button class="help-hint" onclick={toggleAlerts} title="OS notifications for new mail while this tab is open">
|
||||
{alerts === 'on' ? 'Desktop alerts: on' : 'Enable desktop alerts'}
|
||||
</button>
|
||||
{:else if alerts === 'blocked'}
|
||||
<span class="status" title="Allow notifications for this site in the browser to use them">Desktop alerts blocked</span>
|
||||
{/if}
|
||||
<button class="help-hint" onclick={() => (helpOpen = true)}>Shortcuts ?</button>
|
||||
<span class="status" class:live={liveStatus === 'live'} title={liveStatus === 'live'
|
||||
? 'New mail appears as it arrives'
|
||||
: 'Live connection down — checking for changes every 30 seconds while it reconnects'}>
|
||||
<span class="led"></span>{liveStatus === 'live' ? 'Live' : liveStatus === 'connecting' ? 'Connecting…' : 'Reconnecting…'}
|
||||
</span>
|
||||
</div>
|
||||
</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>
|
||||
{: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}
|
||||
{/if}
|
||||
</section>
|
||||
{#if section === 'rules'}
|
||||
<section class="wide-pane">
|
||||
<RulesView {folders} {tags} reloadKey={rulesReloadKey} />
|
||||
</section>
|
||||
{:else if section === 'accounts'}
|
||||
<section class="wide-pane">
|
||||
<AccountsView reloadKey={accountsReloadKey} onChanged={() => { refreshAccounts(); refreshList(); }} />
|
||||
</section>
|
||||
{:else}
|
||||
<section class="list-pane">
|
||||
{#if section === 'outbox'}
|
||||
<OutboxView items={outbox} onOpen={openOutboxItem} onChanged={refreshOutbox} />
|
||||
{:else}
|
||||
<h2 class="view-title">{viewTitle}</h2>
|
||||
{#if error}<p class="note error">{error}</p>{/if}
|
||||
{#if loading}
|
||||
<p class="note">Loading…</p>
|
||||
{:else if accountsLoaded && accounts.length === 0}
|
||||
<p class="note">
|
||||
No mailbox connected yet.
|
||||
<button class="link" onclick={() => { section = 'accounts'; selected = null; }}>Connect one</button>
|
||||
and its mail will show up here.
|
||||
</p>
|
||||
{:else if threads.length === 0}
|
||||
<p class="note">
|
||||
{mailView.kind === 'inbox' ? 'Inbox zero.' : 'Nothing here.'}
|
||||
</p>
|
||||
{:else}
|
||||
<ThreadList
|
||||
{threads}
|
||||
{tags}
|
||||
selectedId={selected?.thread_id ?? null}
|
||||
{activeIndex}
|
||||
onSelect={open}
|
||||
onContextMenu={(t, i, x, y) => { activeIndex = i; openMenu(t, x, y); }}
|
||||
hasMore={nextCursor !== null}
|
||||
{loadingMore}
|
||||
onLoadMore={loadMore}
|
||||
/>
|
||||
{/if}
|
||||
{/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>
|
||||
{:else}
|
||||
<p class="placeholder">Select a message to read it.</p>
|
||||
{/if}
|
||||
</section>
|
||||
<section class="reading-pane">
|
||||
{#if selected}
|
||||
<ThreadView
|
||||
thread={selected}
|
||||
view={mailView}
|
||||
reloadKey={threadReloadKey}
|
||||
onReply={reply}
|
||||
onLoaded={(m) => (threadMessages = m)}
|
||||
onRead={markedRead}
|
||||
onAction={(actions) => act(selected!, actions)}
|
||||
onMore={(x, y) => openMenu(selected!, x, y)}
|
||||
/>
|
||||
{:else}
|
||||
<p class="note">Select a conversation to read it. Press <kbd>?</kbd> for shortcuts.</p>
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<ActionMenu
|
||||
at={menu?.at ?? null}
|
||||
thread={menu?.thread ?? null}
|
||||
view={mailView}
|
||||
{folders}
|
||||
{tags}
|
||||
onAction={(actions) => menu && act(menu.thread, actions)}
|
||||
onClose={() => (menu = null)}
|
||||
/>
|
||||
<Compose seed={composeSeed} {accounts} onClose={composeClosed} />
|
||||
<ShortcutHelp open={helpOpen} onClose={() => (helpOpen = false)} />
|
||||
|
||||
{#if toasts.length > 0}
|
||||
<div class="toasts" role="status" aria-live="polite">
|
||||
{#each toasts as t (t.key)}
|
||||
<button class="toast" onclick={() => t.threadId && openThreadById(t.threadId)}>
|
||||
<strong>{t.from}</strong>
|
||||
<span>{t.subject}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: 14rem 20rem 1fr;
|
||||
grid-template-columns: 12.5rem 22rem 1fr;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
.folders {
|
||||
background: var(--primary);
|
||||
.sidebar {
|
||||
background: color-mix(in srgb, var(--primary) 35%, transparent);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.75rem;
|
||||
gap: 0.25rem;
|
||||
gap: 0.15rem;
|
||||
border-right: 1px solid var(--secondary);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.folders button {
|
||||
.sidebar button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
padding: 0.5rem 0.75rem;
|
||||
padding: 0.4rem 0.7rem;
|
||||
border-radius: 0.375rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.folders button.active {
|
||||
background: var(--secondary);
|
||||
}
|
||||
.list {
|
||||
border-right: 1px solid var(--secondary);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font: inherit;
|
||||
font-size: 0.88rem;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 0.75rem 1rem;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--secondary);
|
||||
}
|
||||
.sidebar button:hover {
|
||||
background: color-mix(in srgb, var(--secondary) 50%, transparent);
|
||||
}
|
||||
.sidebar button.active {
|
||||
background: var(--secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
/* The compose button is one of the few places the accent belongs
|
||||
(branding-spec.md §1). */
|
||||
.sidebar button.compose {
|
||||
justify-content: center;
|
||||
background: var(--accent);
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.badge {
|
||||
margin-left: auto;
|
||||
font-size: 0.7rem;
|
||||
padding: 0 0.4rem;
|
||||
border-radius: 0.6rem;
|
||||
background: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
.group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin: 0.7rem 0 0.15rem;
|
||||
padding: 0 0.7rem;
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--primary);
|
||||
}
|
||||
.sidebar .group .plus {
|
||||
width: auto;
|
||||
padding: 0 0.35rem;
|
||||
font-size: 0.9rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.sidebar .item .remove {
|
||||
width: auto;
|
||||
visibility: hidden;
|
||||
padding: 0.2rem 0.4rem;
|
||||
font-size: 0.7rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
/* Hover reveals row actions rather than cluttering every row (§4a). */
|
||||
.item:hover .remove,
|
||||
.item:focus-within .remove {
|
||||
visibility: visible;
|
||||
}
|
||||
.dot {
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.new {
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
margin: 0.1rem 0.3rem;
|
||||
padding: 0.3rem 0.45rem;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 0.3rem;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
}
|
||||
.bottom {
|
||||
margin-top: auto;
|
||||
padding-top: 0.6rem;
|
||||
}
|
||||
.help-hint {
|
||||
font-size: 0.78rem !important;
|
||||
color: var(--primary) !important;
|
||||
}
|
||||
.status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
padding: 0.3rem 0.7rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.led {
|
||||
width: 0.45rem;
|
||||
height: 0.45rem;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--primary);
|
||||
}
|
||||
.status.live .led {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.toasts {
|
||||
position: fixed;
|
||||
right: 1rem;
|
||||
bottom: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
z-index: 10;
|
||||
max-width: min(22rem, calc(100vw - 2rem));
|
||||
}
|
||||
.toast {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
text-align: left;
|
||||
padding: 0.6rem 0.8rem;
|
||||
border: 1px solid var(--secondary);
|
||||
border-left: 3px solid var(--accent);
|
||||
border-radius: 0.45rem;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
box-shadow: 0 8px 24px rgb(0 0 0 / 0.2);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.row:hover,
|
||||
.row.selected {
|
||||
background: var(--secondary);
|
||||
.toast span {
|
||||
color: var(--primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.view-title {
|
||||
margin: 0;
|
||||
padding: 0.75rem 0.9rem 0.5rem;
|
||||
font-size: 0.95rem;
|
||||
border-bottom: 1px solid var(--secondary);
|
||||
}
|
||||
.list-pane {
|
||||
border-right: 1px solid var(--secondary);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.reading-pane {
|
||||
padding: 1.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.empty,
|
||||
.placeholder,
|
||||
.error {
|
||||
.wide-pane {
|
||||
grid-column: 2 / 4;
|
||||
min-height: 0;
|
||||
}
|
||||
.note {
|
||||
padding: 1rem;
|
||||
color: var(--primary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.link {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: var(--accent);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.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,329 @@
|
||||
<script lang="ts">
|
||||
// Edits a rule as the structured JSON it's stored as — one level of
|
||||
// all/any conditions plus an action list — so there's no rule syntax to
|
||||
// parse on either side (server-architecture-spec.md §3.5).
|
||||
import type { Action, Folder, Rule, RuleField, RuleInput, RuleOp, RuleTest, Tag } from './api';
|
||||
|
||||
let {
|
||||
rule,
|
||||
folders,
|
||||
tags,
|
||||
onSave,
|
||||
onCancel,
|
||||
}: {
|
||||
rule: Rule | null;
|
||||
folders: Folder[];
|
||||
tags: Tag[];
|
||||
/** Rejects with the server's validation message, shown inline. */
|
||||
onSave: (input: RuleInput) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
} = $props();
|
||||
|
||||
type ActionType = 'tag' | 'move' | 'archive' | 'junk' | 'mark_read' | 'delete' | 'dont_notify' | 'notify';
|
||||
|
||||
const fields: [RuleField, string][] = [
|
||||
['from', 'From'],
|
||||
['to', 'To'],
|
||||
['cc', 'Cc'],
|
||||
['recipients', 'To or Cc'],
|
||||
['subject', 'Subject'],
|
||||
['body', 'Body'],
|
||||
['header', 'Header…'],
|
||||
['spam_score', 'Spam score'],
|
||||
];
|
||||
const ops: [RuleOp, string][] = [
|
||||
['contains', 'contains'],
|
||||
['equals', 'is'],
|
||||
['matches', 'matches regex'],
|
||||
['exists', 'exists'],
|
||||
['greater_than', 'is greater than'],
|
||||
['less_than', 'is less than'],
|
||||
];
|
||||
// A spam score is a number: only numeric comparisons make sense.
|
||||
const numericOps = new Set<RuleOp>(['greater_than', 'less_than', 'exists']);
|
||||
const opsFor = (field: RuleField) => (field === 'spam_score' ? ops.filter(([v]) => numericOps.has(v)) : ops);
|
||||
|
||||
const actionTypes: [ActionType, string][] = [
|
||||
['tag', 'Tag with'],
|
||||
['move', 'Move to'],
|
||||
['archive', 'Archive'],
|
||||
['junk', 'Move to Junk'],
|
||||
['mark_read', 'Mark read'],
|
||||
['delete', 'Move to Trash'],
|
||||
// New mail notifies when it stays unread in the inbox; these override
|
||||
// that either way (e.g. alert for a folder, or silence a noisy sender).
|
||||
['dont_notify', "Don't notify"],
|
||||
['notify', 'Notify anyway'],
|
||||
];
|
||||
|
||||
// The form deliberately snapshots the rule it opened with — edits are
|
||||
// local until saved. RulesView keys this component on the rule, so
|
||||
// opening a different one remounts it rather than reusing stale state.
|
||||
const initial = snapshot();
|
||||
let name = $state(initial.name);
|
||||
let match = $state<'all' | 'any'>(initial.match);
|
||||
let enabled = $state(initial.enabled);
|
||||
let stopAfterMatch = $state(initial.stopAfterMatch);
|
||||
let tests = $state<RuleTest[]>(initial.tests);
|
||||
let actions = $state<{ type: ActionType; target: string }[]>(initial.actions);
|
||||
|
||||
function snapshot() {
|
||||
return {
|
||||
name: rule?.name ?? '',
|
||||
match: rule?.conditions.match ?? ('all' as const),
|
||||
enabled: rule?.enabled ?? true,
|
||||
stopAfterMatch: rule?.stop_after_match ?? false,
|
||||
tests: rule ? rule.conditions.tests.map((t) => ({ ...t, header: t.header ?? '' })) : [blankTest()],
|
||||
actions: rule ? rule.actions.map(toRow) : [{ type: 'tag' as ActionType, target: tags[0]?.id ?? '' }],
|
||||
};
|
||||
}
|
||||
let error = $state<string | null>(null);
|
||||
let saving = $state(false);
|
||||
|
||||
function blankTest(): RuleTest {
|
||||
return { field: 'from', header: '', op: 'contains', value: '', negate: false };
|
||||
}
|
||||
|
||||
function toRow(a: Action): { type: ActionType; target: string } {
|
||||
switch (a.type) {
|
||||
case 'tag':
|
||||
return { type: 'tag', target: a.tag_id };
|
||||
case 'move':
|
||||
return { type: 'move', target: a.folder_id ?? '' };
|
||||
default:
|
||||
return { type: a.type as ActionType, target: '' };
|
||||
}
|
||||
}
|
||||
|
||||
function toAction(row: { type: ActionType; target: string }): Action {
|
||||
switch (row.type) {
|
||||
case 'tag':
|
||||
return { type: 'tag', tag_id: row.target };
|
||||
case 'move':
|
||||
return { type: 'move', folder_id: row.target || null };
|
||||
default:
|
||||
return { type: row.type };
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
error = null;
|
||||
saving = true;
|
||||
try {
|
||||
await onSave({
|
||||
name,
|
||||
enabled,
|
||||
stop_after_match: stopAfterMatch,
|
||||
conditions: {
|
||||
match,
|
||||
tests: tests.map((t) => ({
|
||||
field: t.field,
|
||||
op: t.op,
|
||||
value: t.op === 'exists' ? '' : t.value,
|
||||
negate: t.negate,
|
||||
...(t.field === 'header' ? { header: t.header } : {}),
|
||||
})),
|
||||
},
|
||||
actions: actions.map(toAction),
|
||||
});
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to save';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<form class="editor" onsubmit={(e) => { e.preventDefault(); save(); }}>
|
||||
<h2>{rule ? 'Edit rule' : 'New rule'}</h2>
|
||||
|
||||
<label class="name">
|
||||
Name
|
||||
<input bind:value={name} placeholder="e.g. File the weekly newsletter" />
|
||||
</label>
|
||||
|
||||
<fieldset>
|
||||
<legend>
|
||||
When
|
||||
<select bind:value={match}>
|
||||
<option value="all">all</option>
|
||||
<option value="any">any</option>
|
||||
</select>
|
||||
of these are true
|
||||
</legend>
|
||||
{#each tests as t, i}
|
||||
<div class="row">
|
||||
<select
|
||||
bind:value={t.field}
|
||||
aria-label="Field"
|
||||
onchange={() => { if (t.field === 'spam_score' && !numericOps.has(t.op)) t.op = 'greater_than'; }}
|
||||
>
|
||||
{#each fields as [v, label]}<option value={v}>{label}</option>{/each}
|
||||
</select>
|
||||
{#if t.field === 'header'}
|
||||
<input class="header" bind:value={t.header} placeholder="List-Id" aria-label="Header name" />
|
||||
{/if}
|
||||
<label class="negate"><input type="checkbox" bind:checked={t.negate} /> not</label>
|
||||
<select bind:value={t.op} aria-label="Comparison">
|
||||
{#each opsFor(t.field) as [v, label]}<option value={v}>{label}</option>{/each}
|
||||
</select>
|
||||
{#if t.op !== 'exists'}
|
||||
<input class="value" bind:value={t.value} aria-label="Value" />
|
||||
{/if}
|
||||
<button type="button" class="remove" aria-label="Remove condition" onclick={() => tests.splice(i, 1)} disabled={tests.length === 1}>✕</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button type="button" class="add" onclick={() => tests.push(blankTest())}>+ Condition</button>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend>Then</legend>
|
||||
{#each actions as a, i}
|
||||
<div class="row">
|
||||
<select bind:value={a.type} aria-label="Action">
|
||||
{#each actionTypes as [v, label]}<option value={v}>{label}</option>{/each}
|
||||
</select>
|
||||
{#if a.type === 'tag'}
|
||||
<select bind:value={a.target} aria-label="Tag">
|
||||
{#each tags as tag (tag.id)}<option value={tag.id}>{tag.name}</option>{/each}
|
||||
</select>
|
||||
{:else if a.type === 'move'}
|
||||
<select bind:value={a.target} aria-label="Folder">
|
||||
<option value="">Inbox</option>
|
||||
{#each folders as f (f.id)}<option value={f.id}>{f.name}</option>{/each}
|
||||
</select>
|
||||
{/if}
|
||||
<button type="button" class="remove" aria-label="Remove action" onclick={() => actions.splice(i, 1)} disabled={actions.length === 1}>✕</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button type="button" class="add" onclick={() => actions.push({ type: 'archive', target: '' })}>+ Action</button>
|
||||
</fieldset>
|
||||
|
||||
<label class="enabled"><input type="checkbox" bind:checked={enabled} /> Enabled for new mail</label>
|
||||
<label class="enabled">
|
||||
<input type="checkbox" bind:checked={stopAfterMatch} /> Stop — don't run rules below this one when it matches
|
||||
</label>
|
||||
<p class="hint">Rules run on new mail as it arrives, in the order listed. Delete moves mail to Trash, where it can be restored.</p>
|
||||
|
||||
{#if error}<p class="error">{error}</p>{/if}
|
||||
|
||||
<footer>
|
||||
<button type="submit" class="primary" disabled={saving}>{saving ? 'Saving…' : 'Save rule'}</button>
|
||||
<button type="button" onclick={onCancel}>Cancel</button>
|
||||
</footer>
|
||||
</form>
|
||||
|
||||
<style>
|
||||
.editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
padding: 1.25rem;
|
||||
max-width: 52rem;
|
||||
}
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.name {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
fieldset {
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.45rem;
|
||||
padding: 0.6rem 0.8rem 0.8rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
legend {
|
||||
font-size: 0.85rem;
|
||||
padding: 0 0.3rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
input,
|
||||
select {
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
background: var(--background);
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.3rem 0.45rem;
|
||||
}
|
||||
input:focus-visible,
|
||||
select:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
.header {
|
||||
width: 9rem;
|
||||
}
|
||||
.value {
|
||||
flex: 1;
|
||||
min-width: 10rem;
|
||||
}
|
||||
.negate,
|
||||
.enabled {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.3rem 0.7rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.add {
|
||||
align-self: flex-start;
|
||||
border-style: dashed;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.remove {
|
||||
border: none;
|
||||
color: var(--primary);
|
||||
}
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
footer {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
font-size: 0.78rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--accent);
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,304 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
createRule,
|
||||
deleteRule,
|
||||
listRules,
|
||||
reorderRules,
|
||||
runRule,
|
||||
updateRule,
|
||||
type Action,
|
||||
type Folder,
|
||||
type Rule,
|
||||
type RuleInput,
|
||||
type Tag,
|
||||
} from './api';
|
||||
import RuleEditor from './RuleEditor.svelte';
|
||||
|
||||
let {
|
||||
folders,
|
||||
tags,
|
||||
reloadKey = 0,
|
||||
}: {
|
||||
folders: Folder[];
|
||||
tags: Tag[];
|
||||
/** Bumped by the parent when rules change elsewhere (another tab). */
|
||||
reloadKey?: number;
|
||||
} = $props();
|
||||
|
||||
let rules = $state<Rule[]>([]);
|
||||
let editing = $state<Rule | 'new' | null>(null);
|
||||
let error = $state<string | null>(null);
|
||||
/** Per-rule outcome of the last Run now, shown under that rule. */
|
||||
let runResult = $state<Record<string, string>>({});
|
||||
let running = $state<string | null>(null);
|
||||
|
||||
// Loads on mount and again whenever the parent bumps reloadKey. An open
|
||||
// editor keeps its own copy, so a reload never clobbers edits.
|
||||
$effect(() => {
|
||||
void reloadKey;
|
||||
load();
|
||||
});
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
rules = await listRules();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'failed to load rules';
|
||||
}
|
||||
}
|
||||
|
||||
async function save(input: RuleInput) {
|
||||
if (editing === 'new') await createRule(input);
|
||||
else if (editing) await updateRule(editing.id, input);
|
||||
editing = null;
|
||||
await load();
|
||||
}
|
||||
|
||||
async function runNow(rule: Rule) {
|
||||
// Notifications only exist for mail as it arrives.
|
||||
const applicable = rule.actions.filter((a) => a.type !== 'notify' && a.type !== 'dont_notify');
|
||||
if (applicable.length === 0) {
|
||||
alert(`"${rule.name}" only changes notifications, which apply to new mail as it arrives — there's nothing to run on existing mail.`);
|
||||
return;
|
||||
}
|
||||
const what = describeActions(applicable);
|
||||
if (!confirm(`Run "${rule.name}" on your existing mail now?\n\nEvery matching message outside Trash will: ${what}.`)) return;
|
||||
running = rule.id;
|
||||
try {
|
||||
const r = await runRule(rule.id);
|
||||
runResult[rule.id] = `Matched ${r.matched} of ${r.scanned} messages.`;
|
||||
} catch (e) {
|
||||
runResult[rule.id] = e instanceof Error ? e.message : 'failed';
|
||||
} finally {
|
||||
running = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The spec's threshold rule (§3.5): score over N → Junk. Placed first so
|
||||
* it runs before anything else — otherwise a list rule could file spam
|
||||
* into a folder before it's caught — and stops later rules for spam.
|
||||
* 5 is SpamAssassin's own default; PMG only adds its header from level 3.
|
||||
*/
|
||||
async function addSpamFilter() {
|
||||
const rule = await createRule({
|
||||
name: 'Spam filter',
|
||||
enabled: true,
|
||||
stop_after_match: true,
|
||||
conditions: { match: 'all', tests: [{ field: 'spam_score', op: 'greater_than', value: '5', negate: false }] },
|
||||
actions: [{ type: 'junk' }],
|
||||
});
|
||||
rules = await reorderRules([rule.id, ...rules.map((r) => r.id)]);
|
||||
editing = rules[0];
|
||||
}
|
||||
|
||||
const hasSpamFilter = $derived(rules.some((r) => r.conditions.tests.some((t) => t.field === 'spam_score')));
|
||||
|
||||
async function toggle(rule: Rule) {
|
||||
await updateRule(rule.id, { ...rule, enabled: !rule.enabled });
|
||||
await load();
|
||||
}
|
||||
|
||||
async function remove(rule: Rule) {
|
||||
if (!confirm(`Delete the rule "${rule.name}"?`)) return;
|
||||
await deleteRule(rule.id);
|
||||
await load();
|
||||
}
|
||||
|
||||
async function move(index: number, by: -1 | 1) {
|
||||
const ids = rules.map((r) => r.id);
|
||||
[ids[index], ids[index + by]] = [ids[index + by], ids[index]];
|
||||
rules = await reorderRules(ids);
|
||||
}
|
||||
|
||||
const fieldLabel: Record<string, string> = {
|
||||
from: 'from', to: 'to', cc: 'cc', recipients: 'to/cc', subject: 'subject', body: 'body', spam_score: 'spam score',
|
||||
};
|
||||
const opLabel: Record<string, string> = {
|
||||
contains: 'contains', equals: 'is', matches: 'matches', exists: 'exists',
|
||||
greater_than: '>', less_than: '<',
|
||||
};
|
||||
|
||||
function describeActions(actions: Action[]): string {
|
||||
return actions
|
||||
.map((a) => {
|
||||
switch (a.type) {
|
||||
case 'tag': return `tag “${tags.find((t) => t.id === a.tag_id)?.name ?? 'deleted tag'}”`;
|
||||
case 'move': return `move to ${a.folder_id ? (folders.find((f) => f.id === a.folder_id)?.name ?? 'deleted folder') : 'Inbox'}`;
|
||||
case 'archive': return 'archive';
|
||||
case 'junk': return 'move to Junk';
|
||||
case 'mark_read': return 'mark read';
|
||||
case 'delete': return 'move to Trash';
|
||||
case 'dont_notify': return "don't notify";
|
||||
case 'notify': return 'notify';
|
||||
default: return a.type;
|
||||
}
|
||||
})
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
function describeTests(rule: Rule): string {
|
||||
const parts = rule.conditions.tests.map((t) => {
|
||||
const field = t.field === 'header' ? (t.header ?? 'header') : fieldLabel[t.field];
|
||||
const value = t.op === 'exists' ? '' : ` “${t.value}”`;
|
||||
return `${field} ${t.negate ? 'not ' : ''}${opLabel[t.op]}${value}`;
|
||||
});
|
||||
return parts.join(rule.conditions.match === 'all' ? ' and ' : ' or ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="rules">
|
||||
{#if editing}
|
||||
{#key editing}
|
||||
<RuleEditor
|
||||
rule={editing === 'new' ? null : editing}
|
||||
{folders}
|
||||
{tags}
|
||||
onSave={save}
|
||||
onCancel={() => (editing = null)}
|
||||
/>
|
||||
{/key}
|
||||
{:else}
|
||||
<header>
|
||||
<h2>Rules</h2>
|
||||
<div class="header-actions">
|
||||
{#if !hasSpamFilter}
|
||||
<button onclick={addSpamFilter} title="Score over 5 → Junk, placed first">Add spam filter</button>
|
||||
{/if}
|
||||
<button class="primary" onclick={() => (editing = 'new')}>New rule</button>
|
||||
</div>
|
||||
</header>
|
||||
<p class="hint">
|
||||
Applied to new mail in this order; every matching rule runs unless one above it is set to stop. Run now applies a single rule to mail you already have — disabled rules included, so you can try one before switching it on.
|
||||
</p>
|
||||
{#if error}<p class="error">{error}</p>{/if}
|
||||
{#if rules.length === 0}
|
||||
<p class="empty">No rules yet.</p>
|
||||
{/if}
|
||||
<ol>
|
||||
{#each rules as rule, i (rule.id)}
|
||||
<li class:disabled={!rule.enabled}>
|
||||
<div class="order">
|
||||
<button aria-label="Move up" disabled={i === 0} onclick={() => move(i, -1)}>▲</button>
|
||||
<button aria-label="Move down" disabled={i === rules.length - 1} onclick={() => move(i, 1)}>▼</button>
|
||||
</div>
|
||||
<div class="body">
|
||||
<strong>{rule.name}</strong>
|
||||
<span class="summary">
|
||||
If {describeTests(rule)} → {describeActions(rule.actions)}{rule.stop_after_match ? ', then stop' : ''}
|
||||
</span>
|
||||
{#if runResult[rule.id]}<span class="result">{runResult[rule.id]}</span>{/if}
|
||||
</div>
|
||||
<label class="toggle"><input type="checkbox" checked={rule.enabled} onchange={() => toggle(rule)} /> on</label>
|
||||
<button onclick={() => runNow(rule)} disabled={running !== null} title="Apply to existing mail">
|
||||
{running === rule.id ? 'Running…' : 'Run now'}
|
||||
</button>
|
||||
<button onclick={() => (editing = rule)}>Edit</button>
|
||||
<button onclick={() => remove(rule)}>Delete</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.rules {
|
||||
overflow-y: auto;
|
||||
height: 100%;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.25rem 1.25rem 0;
|
||||
}
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.hint,
|
||||
.empty,
|
||||
.error {
|
||||
padding: 0 1.25rem;
|
||||
font-size: 0.82rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.error {
|
||||
color: var(--accent);
|
||||
}
|
||||
ol {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 1.25rem 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.45rem;
|
||||
}
|
||||
/* Dim the description only: Run now still works on a disabled rule, so
|
||||
its buttons mustn't look disabled too. */
|
||||
li.disabled .body {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.order {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.order button {
|
||||
border: none;
|
||||
padding: 0 0.2rem;
|
||||
font-size: 0.6rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
.summary {
|
||||
font-size: 0.8rem;
|
||||
color: var(--primary);
|
||||
}
|
||||
.result {
|
||||
font-size: 0.78rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
.toggle {
|
||||
font-size: 0.8rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
font-size: 0.82rem;
|
||||
color: var(--text);
|
||||
background: none;
|
||||
border: 1px solid var(--secondary);
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.25rem 0.6rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.3;
|
||||
cursor: default;
|
||||
}
|
||||
.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,98 @@
|
||||
<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'],
|
||||
['e', 'Archive'],
|
||||
['#', 'Delete (restore, in Trash)'],
|
||||
['!', 'Report spam (not spam, in Junk)'],
|
||||
['Shift+I / Shift+U', 'Mark read / unread'],
|
||||
['v or l', 'Move or tag'],
|
||||
['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">
|
||||
Actions apply to the open conversation, or to the one under the cursor when none is open.
|
||||
Right-click a conversation for the same menu.
|
||||
</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,214 @@
|
||||
<script lang="ts">
|
||||
import type { Tag, ThreadSummary } from './api';
|
||||
import { formatListDate } from './format';
|
||||
|
||||
let {
|
||||
threads,
|
||||
selectedId,
|
||||
activeIndex,
|
||||
tags,
|
||||
onSelect,
|
||||
onContextMenu,
|
||||
hasMore,
|
||||
loadingMore,
|
||||
onLoadMore,
|
||||
}: {
|
||||
threads: ThreadSummary[];
|
||||
selectedId: string | null;
|
||||
activeIndex: number;
|
||||
tags: Tag[];
|
||||
onSelect: (thread: ThreadSummary, index: number) => void;
|
||||
/** Right-click on a row (§4a: context menus instead of a "…" per row). */
|
||||
onContextMenu: (thread: ThreadSummary, index: number, x: number, y: number) => void;
|
||||
hasMore: boolean;
|
||||
loadingMore: boolean;
|
||||
onLoadMore: () => void;
|
||||
} = $props();
|
||||
|
||||
let sentinel = $state<HTMLElement | null>(null);
|
||||
|
||||
// Infinite scroll: fetch the next page as the end of the list comes into
|
||||
// view (with some margin, so it's usually there before it's needed).
|
||||
$effect(() => {
|
||||
if (!sentinel || !hasMore) return;
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((e) => e.isIntersecting)) onLoadMore();
|
||||
},
|
||||
{ root: listEl, rootMargin: '300px' },
|
||||
);
|
||||
observer.observe(sentinel);
|
||||
return () => observer.disconnect();
|
||||
});
|
||||
|
||||
const tagById = $derived(new Map(tags.map((t) => [t.id, t])));
|
||||
|
||||
function purgeText(at: string): string {
|
||||
const days = Math.ceil((new Date(at).getTime() - Date.now()) / 86_400_000);
|
||||
return days <= 0 ? 'Deleted permanently soon' : `Deleted permanently in ${days} day${days === 1 ? '' : 's'}`;
|
||||
}
|
||||
|
||||
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)}
|
||||
oncontextmenu={(e) => {
|
||||
e.preventDefault();
|
||||
onContextMenu(thread, i, e.clientX, e.clientY);
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
{#if thread.purges_at}
|
||||
<span class="purge">{purgeText(thread.purges_at)}</span>
|
||||
{/if}
|
||||
{#if thread.tag_ids.length > 0}
|
||||
<span class="chips">
|
||||
{#each thread.tag_ids as id (id)}
|
||||
{@const tag = tagById.get(id)}
|
||||
{#if tag}
|
||||
<span class="chip" style:--chip={tag.color ?? 'var(--primary)'}>{tag.name}</span>
|
||||
{/if}
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{#if hasMore}
|
||||
<!-- Also a button: a fallback where IntersectionObserver doesn't fire,
|
||||
and reachable by keyboard. -->
|
||||
<button class="more" bind:this={sentinel} onclick={onLoadMore} disabled={loadingMore}>
|
||||
{loadingMore ? 'Loading…' : 'Load older'}
|
||||
</button>
|
||||
{/if}
|
||||
</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;
|
||||
}
|
||||
.purge {
|
||||
font-size: 0.72rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
.more {
|
||||
padding: 0.7rem;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--primary);
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
.chip {
|
||||
font-size: 0.68rem;
|
||||
padding: 0 0.4rem;
|
||||
border-radius: 0.6rem;
|
||||
border: 1px solid var(--chip);
|
||||
background: color-mix(in srgb, var(--chip) 18%, transparent);
|
||||
color: var(--text);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,288 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
getThread,
|
||||
markThreadRead,
|
||||
type Action,
|
||||
type MailView,
|
||||
type MessageDetail,
|
||||
type ThreadSummary,
|
||||
} from './api';
|
||||
import { formatFullDate } from './format';
|
||||
import MessageBody from './MessageBody.svelte';
|
||||
|
||||
let {
|
||||
thread,
|
||||
view,
|
||||
reloadKey = 0,
|
||||
onReply,
|
||||
onLoaded,
|
||||
onRead,
|
||||
onAction,
|
||||
onMore,
|
||||
}: {
|
||||
thread: ThreadSummary;
|
||||
view: MailView;
|
||||
onAction: (actions: Action[]) => void;
|
||||
/** Opens the full action menu (move, tags) at a viewport position. */
|
||||
onMore: (x: number, y: number) => void;
|
||||
/** 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 loaded = $state<MessageDetail[]>([]);
|
||||
// A rule may have trashed one message of a thread; outside Trash it's
|
||||
// hidden, in Trash only the trashed ones show.
|
||||
const messages = $derived(
|
||||
loaded.filter((m) => (view.kind === 'trash') === (m.deleted_at !== null)),
|
||||
);
|
||||
const inTrash = $derived(view.kind === 'trash');
|
||||
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) => {
|
||||
loaded = 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?.(messages);
|
||||
// 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">
|
||||
<div class="toolbar" role="toolbar" aria-label="Conversation actions">
|
||||
{#if inTrash}
|
||||
<button onclick={() => onAction([{ type: 'restore' }])}>Restore</button>
|
||||
{:else}
|
||||
<button onclick={() => onAction([{ type: 'archive' }])} title="Archive (e)">Archive</button>
|
||||
<button onclick={() => onAction([{ type: 'delete' }])} title="Delete (#)">Delete</button>
|
||||
{#if view.kind === 'junk'}
|
||||
<button onclick={() => onAction([{ type: 'move', folder_id: null }])} title="Not spam (!)">Not spam</button>
|
||||
{:else}
|
||||
<button onclick={() => onAction([{ type: 'junk' }])} title="Report spam (!)">Spam</button>
|
||||
{/if}
|
||||
{/if}
|
||||
<button onclick={() => onAction([{ type: 'mark_unread' }])} title="Mark unread (Shift+U)">Mark unread</button>
|
||||
<button
|
||||
onclick={(e) => {
|
||||
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
onMore(r.left, r.bottom + 4);
|
||||
}}
|
||||
title="Move or tag (v / l)"
|
||||
>Move / Tag ▾</button>
|
||||
</div>
|
||||
<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}
|
||||
{#if message.spam_score !== null}
|
||||
<span class="spam-tag" title="Score from the spam filter's headers">spam {message.spam_score}</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>
|
||||
.toolbar {
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
padding-bottom: 0.25rem;
|
||||
border-bottom: 1px solid var(--secondary);
|
||||
}
|
||||
.toolbar 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;
|
||||
}
|
||||
.toolbar button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.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);
|
||||
}
|
||||
.spam-tag {
|
||||
margin-left: 0.4rem;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 500;
|
||||
padding: 0 0.35rem;
|
||||
border-radius: 0.6rem;
|
||||
border: 1px solid var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
.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>
|
||||
+302
-8
@@ -4,6 +4,13 @@
|
||||
|
||||
const SESSION_KEY = 'tern-session-token';
|
||||
|
||||
/**
|
||||
* Where tern-server lives, fixed at build time (VITE_TERN_API). Deployed,
|
||||
* the webapp and the API are separate origins; in development it's empty
|
||||
* and Vite's proxy forwards /api on the same origin.
|
||||
*/
|
||||
export const API_ORIGIN = (import.meta.env.VITE_TERN_API ?? '').replace(/\/+$/, '');
|
||||
|
||||
export function getSessionToken(): string | null {
|
||||
return localStorage.getItem(SESSION_KEY);
|
||||
}
|
||||
@@ -18,7 +25,7 @@ export function clearSessionToken(): void {
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const token = getSessionToken();
|
||||
const res = await fetch(`/api${path}`, {
|
||||
const res = await fetch(`${API_ORIGIN}/api${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -36,6 +43,8 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
export interface Folder {
|
||||
id: string;
|
||||
name: string;
|
||||
/** System folders (Archive, Junk) have a role; the user's own have null. */
|
||||
role: 'archive' | 'junk' | null;
|
||||
}
|
||||
|
||||
export interface MessageSummary {
|
||||
@@ -43,24 +52,110 @@ 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';
|
||||
deleted_at: string | null;
|
||||
/** From the spam filter's headers; null means the filter didn't flag it. */
|
||||
spam_score: number | null;
|
||||
}
|
||||
|
||||
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;
|
||||
tag_ids: string[];
|
||||
/** In Trash: when this conversation is deleted for good. */
|
||||
purges_at: string | null;
|
||||
}
|
||||
|
||||
/** 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[];
|
||||
/** Which slice of the mailbox a thread list shows. */
|
||||
export type MailView =
|
||||
| { kind: 'inbox' }
|
||||
| { kind: 'all' }
|
||||
| { kind: 'sent' }
|
||||
| { kind: 'trash' }
|
||||
| { kind: 'junk' }
|
||||
| { kind: 'folder'; id: string }
|
||||
| { kind: 'tag'; id: string };
|
||||
|
||||
/** `cursor` is the opaque `next_cursor` from the previous page; null there means no more pages. */
|
||||
export function listThreads(view: MailView, cursor?: string, limit?: number): 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}` : ''}`);
|
||||
const query = new URLSearchParams({ view: view.kind });
|
||||
if (view.kind === 'folder') query.set('folder_id', view.id);
|
||||
if (view.kind === 'tag') query.set('tag_id', view.id);
|
||||
if (cursor) query.set('before', cursor);
|
||||
if (limit) query.set('limit', String(limit));
|
||||
return request(`/threads?${query}`);
|
||||
}
|
||||
|
||||
export function getThread(threadId: string): Promise<MessageDetail[]> {
|
||||
return request(`/threads/${threadId}`);
|
||||
}
|
||||
|
||||
/** A change pushed over the WebSocket or returned by the poll endpoint. */
|
||||
export type LiveEvent = { id: number; created_at: string } & (
|
||||
| {
|
||||
kind: 'message_new';
|
||||
data: {
|
||||
message_id: string;
|
||||
thread_id: string | null;
|
||||
account_id: string;
|
||||
/** The server's final say, after rules — alert on this and only this. */
|
||||
notify: boolean;
|
||||
from: string | null;
|
||||
subject: string | null;
|
||||
};
|
||||
}
|
||||
/** `thread_ids: null` means "could be anything" — reload. */
|
||||
| { kind: 'mailbox_changed'; data: { thread_ids: string[] | null } }
|
||||
| { kind: 'outbox_changed'; data: { id: string; status: OutboxStatus | 'deleted' } }
|
||||
| { kind: 'config_changed'; data: { what: 'tags' | 'folders' | 'rules' | 'accounts' } }
|
||||
);
|
||||
|
||||
/**
|
||||
* Polling fallback for the WebSocket (webapp-client-spec.md §3). Without
|
||||
* `since` it only returns the current cursor; with a cursor the server can
|
||||
* no longer honour, `reset` is set and the caller should reload everything.
|
||||
*/
|
||||
export function pollEvents(since: number | null): Promise<{
|
||||
events: LiveEvent[];
|
||||
cursor: number;
|
||||
reset: boolean;
|
||||
more: boolean;
|
||||
}> {
|
||||
return request(`/events${since !== null ? `?since=${since}` : ''}`);
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string): Promise<void> {
|
||||
@@ -70,3 +165,202 @@ 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;
|
||||
imap_host: string;
|
||||
imap_port: number;
|
||||
smtp_host: string;
|
||||
smtp_port: number;
|
||||
created_at: string;
|
||||
/** Null until the sync engine first touches the account. */
|
||||
sync: AccountSync | null;
|
||||
}
|
||||
|
||||
export interface AccountSync {
|
||||
status: 'pending' | 'syncing' | 'idle' | 'error';
|
||||
last_error: string | null;
|
||||
updated_at: string;
|
||||
/** The first full pass over the mailbox has finished. */
|
||||
caught_up: boolean;
|
||||
messages: number;
|
||||
}
|
||||
|
||||
export interface NewAccount {
|
||||
name: string;
|
||||
imap_host: string;
|
||||
imap_port: number;
|
||||
smtp_host: string;
|
||||
smtp_port: number;
|
||||
username: string;
|
||||
password: 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 createAccount(account: NewAccount): Promise<Account> {
|
||||
return request('/accounts', { method: 'POST', body: JSON.stringify(account) });
|
||||
}
|
||||
|
||||
/** Removes the account and every message synced from it. */
|
||||
export function deleteAccount(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/accounts/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function markThreadRead(threadId: string): Promise<{ messages: 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' });
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string;
|
||||
name: string;
|
||||
color: string | null;
|
||||
}
|
||||
|
||||
/** Same shape as rule actions — manual actions and rules share one applier. */
|
||||
export type Action =
|
||||
| { type: 'tag'; tag_id: string }
|
||||
| { type: 'untag'; tag_id: string }
|
||||
| { type: 'move'; folder_id: string | null }
|
||||
| { type: 'archive' }
|
||||
| { type: 'junk' }
|
||||
| { type: 'mark_read' }
|
||||
| { type: 'mark_unread' }
|
||||
| { type: 'delete' }
|
||||
| { type: 'restore' }
|
||||
// Rule-only: decide whether new mail alerts (see live.ts).
|
||||
| { type: 'notify' }
|
||||
| { type: 'dont_notify' };
|
||||
|
||||
export type RuleField = 'from' | 'to' | 'cc' | 'recipients' | 'subject' | 'body' | 'header' | 'spam_score';
|
||||
export type RuleOp = 'contains' | 'equals' | 'matches' | 'exists' | 'greater_than' | 'less_than';
|
||||
|
||||
export interface RuleTest {
|
||||
field: RuleField;
|
||||
header?: string;
|
||||
op: RuleOp;
|
||||
value: string;
|
||||
negate: boolean;
|
||||
}
|
||||
|
||||
export interface Rule {
|
||||
id: string;
|
||||
name: string;
|
||||
conditions: { match: 'all' | 'any'; tests: RuleTest[] };
|
||||
actions: Action[];
|
||||
enabled: boolean;
|
||||
/** Skip lower-priority rules once this one matches. */
|
||||
stop_after_match: boolean;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
export type RuleInput = Omit<Rule, 'id' | 'priority'>;
|
||||
|
||||
export function threadActions(threadId: string, actions: Action[]): Promise<{ messages: number }> {
|
||||
return request(`/threads/${threadId}/actions`, { method: 'POST', body: JSON.stringify({ actions }) });
|
||||
}
|
||||
|
||||
export function listTags(): Promise<Tag[]> {
|
||||
return request('/tags');
|
||||
}
|
||||
|
||||
export function createTag(name: string, color: string | null): Promise<Tag> {
|
||||
return request('/tags', { method: 'POST', body: JSON.stringify({ name, color }) });
|
||||
}
|
||||
|
||||
export function deleteTag(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/tags/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function createFolder(name: string): Promise<Folder> {
|
||||
return request('/folders', { method: 'POST', body: JSON.stringify({ name }) });
|
||||
}
|
||||
|
||||
export function deleteFolder(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/folders/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function listRules(): Promise<Rule[]> {
|
||||
return request('/rules');
|
||||
}
|
||||
|
||||
export function createRule(rule: RuleInput): Promise<Rule> {
|
||||
return request('/rules', { method: 'POST', body: JSON.stringify(rule) });
|
||||
}
|
||||
|
||||
export function updateRule(id: string, rule: RuleInput): Promise<Rule> {
|
||||
return request(`/rules/${id}`, { method: 'PUT', body: JSON.stringify(rule) });
|
||||
}
|
||||
|
||||
export function deleteRule(id: string): Promise<{ ok: boolean }> {
|
||||
return request(`/rules/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** Applies a rule to existing mail — what "Run now" does. */
|
||||
export function runRule(id: string): Promise<{ scanned: number; matched: number }> {
|
||||
return request(`/rules/${id}/run`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function reorderRules(ids: string[]): Promise<Rule[]> {
|
||||
return request('/rules/reorder', { method: 'POST', body: JSON.stringify({ ids }) });
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// Live updates (webapp-client-spec.md §3): a WebSocket while it's up, and
|
||||
// polling the same event log while it isn't. Both carry the same cursor,
|
||||
// so switching between them neither drops nor repeats a change.
|
||||
|
||||
import { API_ORIGIN, getSessionToken, pollEvents, type LiveEvent } from './api';
|
||||
|
||||
export type LiveStatus = 'connecting' | 'live' | 'polling';
|
||||
|
||||
export interface LiveHandlers {
|
||||
/** Changes in order, batched so a burst causes one reload, not fifty. */
|
||||
onEvents: (events: LiveEvent[]) => void;
|
||||
/** The server couldn't replay what was missed — reload everything. */
|
||||
onReset: () => void;
|
||||
onStatus: (status: LiveStatus) => void;
|
||||
/** The session ended (logged out elsewhere, or expired). */
|
||||
onUnauthorized: () => void;
|
||||
}
|
||||
|
||||
const POLL_INTERVAL_MS = 30_000;
|
||||
const MAX_BACKOFF_MS = 30_000;
|
||||
const BATCH_MS = 250;
|
||||
/** Must match the server's close code for a missing or expired session. */
|
||||
const CLOSE_UNAUTHORIZED = 4401;
|
||||
|
||||
/** Starts live updates; returns a function that stops them. */
|
||||
export function startLive(handlers: LiveHandlers): () => void {
|
||||
let cursor: number | null = null;
|
||||
let socket: WebSocket | null = null;
|
||||
let live = false;
|
||||
let stopped = false;
|
||||
let attempt = 0;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pollTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let polling = false;
|
||||
let pending: LiveEvent[] = [];
|
||||
let flushTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
function deliver(events: LiveEvent[]) {
|
||||
if (events.length === 0) return;
|
||||
pending.push(...events);
|
||||
flushTimer ??= setTimeout(() => {
|
||||
flushTimer = undefined;
|
||||
const batch = pending;
|
||||
pending = [];
|
||||
handlers.onEvents(batch);
|
||||
}, BATCH_MS);
|
||||
}
|
||||
|
||||
function connect() {
|
||||
clearTimeout(reconnectTimer);
|
||||
if (stopped || socket) return;
|
||||
const token = getSessionToken();
|
||||
if (!token) {
|
||||
handlers.onUnauthorized();
|
||||
return;
|
||||
}
|
||||
handlers.onStatus(cursor === null ? 'connecting' : 'polling');
|
||||
const url = new URL('/api/ws', API_ORIGIN || location.href);
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const ws = new WebSocket(url);
|
||||
socket = ws;
|
||||
|
||||
// Browsers can't set headers on a WebSocket; the token goes in-band.
|
||||
ws.onopen = () => ws.send(JSON.stringify({ type: 'auth', token, since: cursor }));
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.type === 'ready') {
|
||||
// Also sent mid-stream if this tab fell too far behind to replay.
|
||||
const resumed = cursor !== null;
|
||||
cursor = msg.cursor;
|
||||
attempt = 0;
|
||||
live = true;
|
||||
stopPolling();
|
||||
handlers.onStatus('live');
|
||||
if (msg.reset && resumed) handlers.onReset();
|
||||
} else if (msg.type === 'event') {
|
||||
const { type: _, ...event } = msg;
|
||||
cursor = event.id;
|
||||
deliver([event as LiveEvent]);
|
||||
}
|
||||
};
|
||||
ws.onclose = (e) => {
|
||||
if (socket !== ws) return;
|
||||
socket = null;
|
||||
live = false;
|
||||
if (stopped) return;
|
||||
if (e.code === CLOSE_UNAUTHORIZED) {
|
||||
handlers.onUnauthorized();
|
||||
return;
|
||||
}
|
||||
// Poll while reconnecting, so a flaky connection still sees mail.
|
||||
handlers.onStatus('polling');
|
||||
startPolling();
|
||||
const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** attempt) * (0.5 + Math.random() / 2);
|
||||
attempt++;
|
||||
reconnectTimer = setTimeout(connect, delay);
|
||||
};
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (polling || live || stopped) return;
|
||||
polling = true;
|
||||
try {
|
||||
let more = true;
|
||||
while (more && !live && !stopped) {
|
||||
const res = await pollEvents(cursor);
|
||||
if (live) break; // the socket came back mid-request and owns the cursor now
|
||||
if (res.reset && cursor !== null) handlers.onReset();
|
||||
cursor = res.cursor;
|
||||
deliver(res.events);
|
||||
more = res.more;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message === 'unauthorized') handlers.onUnauthorized();
|
||||
// Otherwise the server is unreachable; the next tick retries.
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
if (pollTimer) return;
|
||||
poll();
|
||||
pollTimer = setInterval(poll, POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
clearInterval(pollTimer);
|
||||
pollTimer = undefined;
|
||||
}
|
||||
|
||||
// Coming back online or to the tab is the moment to retry straight away
|
||||
// rather than waiting out the backoff.
|
||||
function retryNow() {
|
||||
if (socket || stopped) return;
|
||||
attempt = 0;
|
||||
connect();
|
||||
}
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === 'visible') retryNow();
|
||||
};
|
||||
window.addEventListener('online', retryNow);
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
|
||||
connect();
|
||||
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(reconnectTimer);
|
||||
clearTimeout(flushTimer);
|
||||
stopPolling();
|
||||
window.removeEventListener('online', retryNow);
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
socket?.close();
|
||||
socket = null;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// OS-level alerts while the tab is open (webapp-client-spec.md §3): the
|
||||
// Notification API works without a service worker, it just can't fire once
|
||||
// the tab is closed. Off until the reader turns it on — permission is asked
|
||||
// for from that click, never on page load.
|
||||
|
||||
const PREF_KEY = 'tern-desktop-alerts';
|
||||
|
||||
export type AlertState = 'unsupported' | 'blocked' | 'off' | 'on';
|
||||
|
||||
function stored(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(PREF_KEY) === 'on';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function store(on: boolean) {
|
||||
try {
|
||||
if (on) localStorage.setItem(PREF_KEY, 'on');
|
||||
else localStorage.removeItem(PREF_KEY);
|
||||
} catch {
|
||||
// Private mode etc.: the setting just won't survive a reload.
|
||||
}
|
||||
}
|
||||
|
||||
export function alertState(): AlertState {
|
||||
if (!('Notification' in window)) return 'unsupported';
|
||||
if (Notification.permission === 'denied') return 'blocked';
|
||||
return Notification.permission === 'granted' && stored() ? 'on' : 'off';
|
||||
}
|
||||
|
||||
export async function enableAlerts(): Promise<AlertState> {
|
||||
if (!('Notification' in window)) return 'unsupported';
|
||||
const permission = await Notification.requestPermission();
|
||||
store(permission === 'granted');
|
||||
return alertState();
|
||||
}
|
||||
|
||||
export function disableAlerts(): AlertState {
|
||||
store(false);
|
||||
return alertState();
|
||||
}
|
||||
|
||||
/** Shows an alert if they're on. `tag` collapses repeats for one thread. */
|
||||
export function showAlert(title: string, body: string, tag: string, onClick: () => void): void {
|
||||
if (alertState() !== 'on') return;
|
||||
const n = new Notification(title, { body, tag });
|
||||
n.onclick = () => {
|
||||
window.focus();
|
||||
onClick();
|
||||
n.close();
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Vendored
+5
@@ -1,2 +1,7 @@
|
||||
/// <reference types="svelte" />
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
/** tern-server's origin, e.g. https://tern-api.mtps.pl. Empty: same origin. */
|
||||
readonly VITE_TERN_API?: string;
|
||||
}
|
||||
+4
-2
@@ -5,8 +5,10 @@ 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.
|
||||
// ws: the live-update socket at /api/ws goes through the same proxy.
|
||||
'/api': { target: process.env.TERN_API ?? 'http://127.0.0.1:8080', ws: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user