Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1a80cc7c7 | ||
|
|
77f15ed7c3 | ||
|
|
0f0e809940 | ||
|
|
e6ce5e26c7 | ||
|
|
fee4a2eb13 | ||
|
|
55d7ac8039 | ||
|
|
fa78fe7ccf | ||
|
|
450f142193 | ||
|
|
789b550301 |
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:
|
||||
|
||||
@@ -44,3 +44,54 @@ jobs:
|
||||
files: |-
|
||||
tern-web-*.tgz
|
||||
tern-web-*.tgz.sha256
|
||||
|
||||
# Deploys the release to tern.mtps.pl (kara, deploy/compose). It lives
|
||||
# here rather than in tern-server because tags are pushed server-first and
|
||||
# the single runner works through them in order, so by the time this runs
|
||||
# both the server image and this webapp release exist. A deploy job in
|
||||
# tern-server would have to wait for this repo's release while holding
|
||||
# the only runner.
|
||||
deploy:
|
||||
needs: release
|
||||
runs-on: rocky-10
|
||||
steps:
|
||||
# The deployment definition is versioned with the server it deploys.
|
||||
- name: Check out deployment definition
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: mtps/tern-server
|
||||
ref: ${{ gitea.ref_name }}
|
||||
|
||||
- name: Check the server image exists
|
||||
env:
|
||||
IMAGE: git.app.ygg/mtps/tern-server
|
||||
TAG: ${{ gitea.ref_name }}
|
||||
run: |
|
||||
# Fails fast with a clear message if the server release didn't
|
||||
# publish this version (failed, or still running on another
|
||||
# runner), instead of a deploy that can't pull its image.
|
||||
VERSION="${TAG#v}"
|
||||
for i in $(seq 1 20); do
|
||||
docker manifest inspect "$IMAGE:$VERSION" >/dev/null 2>&1 && exit 0
|
||||
echo "waiting for $IMAGE:$VERSION ($i/20)"
|
||||
sleep 30
|
||||
done
|
||||
echo "::error::$IMAGE:$VERSION not found in the registry — did the tern-server release succeed?"
|
||||
exit 1
|
||||
|
||||
- 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: compose
|
||||
dist-path: deploy/tern.yml
|
||||
extra-vars: |
|
||||
version=${{ steps.version.outputs.version }}
|
||||
ssh-key: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
known-hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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: mail client with organisation** (build order phases 3–5). 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).
|
||||
@@ -13,11 +13,13 @@ Desktop webapp client for [Tern](../) — see [`docs/webapp-client-spec.md`](doc
|
||||
- **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, Trash, your folders, your tags), with tag chips on list rows.
|
||||
- **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, `Shift+I`/`Shift+U` read/unread, `v`/`l` move/tag, `c`, `r`/`a`, `Shift+R`, `?`.
|
||||
- **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.
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "tern-web",
|
||||
"version": "0.5.0",
|
||||
"version": "0.8.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tern-web",
|
||||
"version": "0.5.0",
|
||||
"version": "0.8.2",
|
||||
"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.5.0",
|
||||
"version": "0.8.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
}
|
||||
|
||||
const inTrash = $derived(view.kind === 'trash');
|
||||
const inJunk = $derived(view.kind === 'junk');
|
||||
const tagged = (id: string) => thread?.tag_ids.includes(id) ?? false;
|
||||
</script>
|
||||
|
||||
@@ -66,6 +67,11 @@
|
||||
{: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>
|
||||
@@ -75,7 +81,7 @@
|
||||
|
||||
<p class="heading">Move to</p>
|
||||
<button role="menuitem" onclick={() => pick([{ type: 'move', folder_id: null }])}>Inbox</button>
|
||||
{#each folders as f (f.id)}
|
||||
{#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}
|
||||
|
||||
|
||||
+236
-28
@@ -12,11 +12,12 @@
|
||||
listOutbox,
|
||||
listTags,
|
||||
listThreads,
|
||||
pollEvents,
|
||||
threadActions,
|
||||
clearSessionToken,
|
||||
type Account,
|
||||
type Action,
|
||||
type Folder,
|
||||
type LiveEvent,
|
||||
type MailView,
|
||||
type MessageDetail,
|
||||
type OutboxItem,
|
||||
@@ -31,12 +32,11 @@
|
||||
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';
|
||||
|
||||
// No WebSocket server-side yet (build order phase 7), so the open tab
|
||||
// polls the delta endpoint. §3 keeps this as the fallback afterwards.
|
||||
const POLL_INTERVAL_MS = 30_000;
|
||||
// After sending, watch the outbox closely so the reader sees the message
|
||||
// go out, rather than waiting for the next slow poll.
|
||||
// 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'];
|
||||
@@ -45,6 +45,8 @@
|
||||
let folders = $state<Folder[]>([]);
|
||||
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'>('mail');
|
||||
let mailView = $state<MailView>({ kind: 'inbox' });
|
||||
@@ -59,7 +61,14 @@
|
||||
let menu = $state<{ thread: ThreadSummary; at: { x: number; y: number } } | null>(null);
|
||||
let adding = $state<'folder' | 'tag' | null>(null);
|
||||
let newName = $state('');
|
||||
let eventCursor: string | null = null;
|
||||
let liveStatus = $state<LiveStatus>('connecting');
|
||||
let alerts = $state<AlertState>(alertState());
|
||||
let rulesReloadKey = $state(0);
|
||||
/** 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('@')),
|
||||
@@ -71,6 +80,7 @@
|
||||
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'; }
|
||||
}
|
||||
@@ -81,11 +91,20 @@
|
||||
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() {
|
||||
error = null;
|
||||
try {
|
||||
const page = await listThreads(mailView);
|
||||
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;
|
||||
@@ -97,6 +116,24 @@
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshMeta() {
|
||||
[folders, tags] = await Promise.all([listFolders(), listTags()]);
|
||||
}
|
||||
@@ -109,33 +146,116 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
function reloadAll() {
|
||||
refreshMeta().catch(() => {});
|
||||
listAccounts().then((a) => (accounts = a)).catch(() => {});
|
||||
refresh();
|
||||
refreshList();
|
||||
refreshOutbox();
|
||||
rulesReloadKey++;
|
||||
}
|
||||
|
||||
const timer = setInterval(async () => {
|
||||
try {
|
||||
const events = await pollEvents(eventCursor);
|
||||
eventCursor = events.cursor;
|
||||
// Only re-fetch when something actually changed, so an idle tab
|
||||
// isn't re-rendering the list every 30s.
|
||||
if (events.changed_messages.length > 0) {
|
||||
await refresh();
|
||||
threadReloadKey++;
|
||||
}
|
||||
} catch {
|
||||
// A failed poll is not worth surfacing; the next tick retries.
|
||||
/**
|
||||
* 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') listAccounts().then((a) => (accounts = a)).catch(() => {});
|
||||
else if (e.data.what === 'rules') rulesReloadKey++;
|
||||
else {
|
||||
refreshMeta().catch(() => {});
|
||||
// Tag chips and folder names show in the list too.
|
||||
mail = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}, POLL_INTERVAL_MS);
|
||||
}
|
||||
if (mail && section === 'mail') refreshList();
|
||||
if (outboxChanged) refreshOutbox();
|
||||
}
|
||||
|
||||
return () => clearInterval(timer);
|
||||
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;
|
||||
@@ -238,7 +358,8 @@
|
||||
composeSeed = null;
|
||||
if (!changed) return;
|
||||
await refreshOutbox();
|
||||
if (sentId) watchSend(sentId);
|
||||
// Live, the worker's own events report the send; this is the fallback.
|
||||
if (sentId && liveStatus !== 'live') watchSend(sentId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,6 +395,8 @@
|
||||
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();
|
||||
@@ -322,6 +445,12 @@
|
||||
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();
|
||||
@@ -356,7 +485,8 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKeydown} />
|
||||
<svelte:window onkeydown={onKeydown} onfocus={seen} />
|
||||
<svelte:document onvisibilitychange={seen} />
|
||||
|
||||
<div class="shell">
|
||||
<nav class="sidebar" aria-label="Mailboxes">
|
||||
@@ -369,13 +499,15 @@
|
||||
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>
|
||||
{#each folders as f (f.id)}
|
||||
<!-- 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}
|
||||
@@ -413,13 +545,25 @@
|
||||
|
||||
<div class="bottom">
|
||||
<button class:active={section === 'rules'} onclick={() => { section = 'rules'; selected = null; }}>Rules</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>
|
||||
|
||||
{#if section === 'rules'}
|
||||
<section class="wide-pane">
|
||||
<RulesView {folders} {tags} />
|
||||
<RulesView {folders} {tags} reloadKey={rulesReloadKey} />
|
||||
</section>
|
||||
{:else}
|
||||
<section class="list-pane">
|
||||
@@ -442,6 +586,9 @@
|
||||
{activeIndex}
|
||||
onSelect={open}
|
||||
onContextMenu={(t, i, x, y) => { activeIndex = i; openMenu(t, x, y); }}
|
||||
hasMore={nextCursor !== null}
|
||||
{loadingMore}
|
||||
onLoadMore={loadMore}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -478,6 +625,17 @@
|
||||
<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;
|
||||
@@ -589,6 +747,56 @@
|
||||
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;
|
||||
}
|
||||
.toast span {
|
||||
color: var(--primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.view-title {
|
||||
margin: 0;
|
||||
padding: 0.75rem 0.9rem 0.5rem;
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
onCancel: () => void;
|
||||
} = $props();
|
||||
|
||||
type ActionType = 'tag' | 'move' | 'archive' | 'mark_read' | 'delete';
|
||||
type ActionType = 'tag' | 'move' | 'archive' | 'junk' | 'mark_read' | 'delete' | 'dont_notify' | 'notify';
|
||||
|
||||
const fields: [RuleField, string][] = [
|
||||
['from', 'From'],
|
||||
@@ -29,6 +29,7 @@
|
||||
['subject', 'Subject'],
|
||||
['body', 'Body'],
|
||||
['header', 'Header…'],
|
||||
['spam_score', 'Spam score'],
|
||||
];
|
||||
const ops: [RuleOp, string][] = [
|
||||
['contains', 'contains'],
|
||||
@@ -38,12 +39,21 @@
|
||||
['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
|
||||
@@ -143,7 +153,11 @@
|
||||
</legend>
|
||||
{#each tests as t, i}
|
||||
<div class="row">
|
||||
<select bind:value={t.field} aria-label="Field">
|
||||
<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'}
|
||||
@@ -151,7 +165,7 @@
|
||||
{/if}
|
||||
<label class="negate"><input type="checkbox" bind:checked={t.negate} /> not</label>
|
||||
<select bind:value={t.op} aria-label="Comparison">
|
||||
{#each ops as [v, label]}<option value={v}>{label}</option>{/each}
|
||||
{#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" />
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
createRule,
|
||||
deleteRule,
|
||||
@@ -15,7 +14,16 @@
|
||||
} from './api';
|
||||
import RuleEditor from './RuleEditor.svelte';
|
||||
|
||||
let { folders, tags }: { folders: Folder[]; tags: Tag[] } = $props();
|
||||
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);
|
||||
@@ -24,7 +32,12 @@
|
||||
let runResult = $state<Record<string, string>>({});
|
||||
let running = $state<string | null>(null);
|
||||
|
||||
onMount(load);
|
||||
// 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 {
|
||||
@@ -42,7 +55,13 @@
|
||||
}
|
||||
|
||||
async function runNow(rule: Rule) {
|
||||
const what = describeActions(rule.actions);
|
||||
// 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 {
|
||||
@@ -55,6 +74,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
@@ -73,7 +112,7 @@
|
||||
}
|
||||
|
||||
const fieldLabel: Record<string, string> = {
|
||||
from: 'from', to: 'to', cc: 'cc', recipients: 'to/cc', subject: 'subject', body: 'body',
|
||||
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',
|
||||
@@ -87,8 +126,11 @@
|
||||
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;
|
||||
}
|
||||
})
|
||||
@@ -119,7 +161,12 @@
|
||||
{:else}
|
||||
<header>
|
||||
<h2>Rules</h2>
|
||||
<button class="primary" onclick={() => (editing = 'new')}>New rule</button>
|
||||
<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.
|
||||
@@ -169,6 +216,10 @@
|
||||
margin: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.hint,
|
||||
.empty,
|
||||
.error {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
['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'],
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
tags,
|
||||
onSelect,
|
||||
onContextMenu,
|
||||
hasMore,
|
||||
loadingMore,
|
||||
onLoadMore,
|
||||
}: {
|
||||
threads: ThreadSummary[];
|
||||
selectedId: string | null;
|
||||
@@ -17,8 +20,27 @@
|
||||
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 {
|
||||
@@ -79,6 +101,13 @@
|
||||
{/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>
|
||||
@@ -160,6 +189,15 @@
|
||||
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;
|
||||
|
||||
@@ -89,6 +89,11 @@
|
||||
{: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
|
||||
@@ -119,6 +124,9 @@
|
||||
<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>
|
||||
@@ -218,6 +226,15 @@
|
||||
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;
|
||||
|
||||
+44
-12
@@ -36,8 +36,8 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
export interface Folder {
|
||||
id: string;
|
||||
name: string;
|
||||
/** 'archive' for the system Archive folder, null for the user's own. */
|
||||
role: 'archive' | null;
|
||||
/** System folders (Archive, Junk) have a role; the user's own have null. */
|
||||
role: 'archive' | 'junk' | null;
|
||||
}
|
||||
|
||||
export interface MessageSummary {
|
||||
@@ -53,6 +53,8 @@ export interface MessageSummary {
|
||||
/** '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 {
|
||||
@@ -94,17 +96,20 @@ export type MailView =
|
||||
| { kind: 'all' }
|
||||
| { kind: 'sent' }
|
||||
| { kind: 'trash' }
|
||||
| { kind: 'junk' }
|
||||
| { kind: 'folder'; id: string }
|
||||
| { kind: 'tag'; id: string };
|
||||
|
||||
export function listThreads(view: MailView, before?: string): Promise<{
|
||||
/** `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({ view: view.kind });
|
||||
if (view.kind === 'folder') query.set('folder_id', view.id);
|
||||
if (view.kind === 'tag') query.set('tag_id', view.id);
|
||||
if (before) query.set('before', before);
|
||||
if (cursor) query.set('before', cursor);
|
||||
if (limit) query.set('limit', String(limit));
|
||||
return request(`/threads?${query}`);
|
||||
}
|
||||
|
||||
@@ -112,15 +117,38 @@ 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' } }
|
||||
);
|
||||
|
||||
/**
|
||||
* Delta endpoint (§3.8). WebSocket push is a later phase, so the client
|
||||
* polls this to notice new mail while the tab is open.
|
||||
* 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: string | null): Promise<{
|
||||
changed_messages: MessageSummary[];
|
||||
cursor: string;
|
||||
export function pollEvents(since: number | null): Promise<{
|
||||
events: LiveEvent[];
|
||||
cursor: number;
|
||||
reset: boolean;
|
||||
more: boolean;
|
||||
}> {
|
||||
return request(`/events${since ? `?since=${encodeURIComponent(since)}` : ''}`);
|
||||
return request(`/events${since !== null ? `?since=${since}` : ''}`);
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string): Promise<void> {
|
||||
@@ -211,12 +239,16 @@ export type Action =
|
||||
| { 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' };
|
||||
| { 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';
|
||||
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 {
|
||||
|
||||
+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 { 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', 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();
|
||||
};
|
||||
}
|
||||
+2
-1
@@ -7,7 +7,8 @@ export default defineConfig({
|
||||
proxy: {
|
||||
// Defaults to tern-server's dev bind address (see server/.env.example).
|
||||
// Override with TERN_API when the server runs on another port or host.
|
||||
'/api': process.env.TERN_API ?? 'http://127.0.0.1:8080',
|
||||
// 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