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,13 @@ jobs:
|
||||
files: |-
|
||||
tern-web-*.tgz
|
||||
tern-web-*.tgz.sha256
|
||||
|
||||
# Straight to the bucket, with a key that only reaches it. The bucket and
|
||||
# the nginx site come from deployments/tern-web.yml in ygg/deployments.
|
||||
- name: Publish
|
||||
uses: https://git.app.ygg/ygg/actions/static-publish@v2
|
||||
with:
|
||||
path: dist
|
||||
bucket: tern.mtps.pl
|
||||
access-key-id: ${{ secrets.STATIC_ACCESS_KEY_ID }}
|
||||
secret-access-key: ${{ secrets.STATIC_SECRET_ACCESS_KEY }}
|
||||
@@ -3,3 +3,7 @@ dist
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Local Claude Code files
|
||||
CLAUDE.md
|
||||
.claude/
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "tern-web",
|
||||
"version": "0.6.0",
|
||||
"version": "0.8.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tern-web",
|
||||
"version": "0.6.0",
|
||||
"version": "0.8.5",
|
||||
"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.6.0",
|
||||
"version": "0.8.5",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
<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, updateAccount, 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);
|
||||
/** The account being edited; the form is shared with adding. */
|
||||
let editing = $state<Account | null>(null);
|
||||
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;
|
||||
}
|
||||
|
||||
function startEdit(a: Account) {
|
||||
adding = false;
|
||||
editing = a;
|
||||
email = a.email_address ?? '';
|
||||
displayName = a.display_name ?? '';
|
||||
imapHost = a.imap_host;
|
||||
imapPort = a.imap_port;
|
||||
smtpHost = a.smtp_host;
|
||||
smtpPort = a.smtp_port;
|
||||
login = a.username;
|
||||
password = '';
|
||||
// Editing the address must not silently rewrite settings that work.
|
||||
loginEdited = hostsEdited = true;
|
||||
formError = null;
|
||||
}
|
||||
|
||||
function closeForm() {
|
||||
adding = false;
|
||||
editing = null;
|
||||
resetForm();
|
||||
}
|
||||
|
||||
async function save(event: SubmitEvent) {
|
||||
event.preventDefault();
|
||||
saving = true;
|
||||
formError = null;
|
||||
const settings = {
|
||||
name: editing?.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,
|
||||
};
|
||||
try {
|
||||
if (editing) await updateAccount(editing.id, settings);
|
||||
else await createAccount(settings);
|
||||
closeForm();
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (e) {
|
||||
formError = e instanceof Error ? e.message : 'failed to save 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 && !editing}
|
||||
<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>
|
||||
<div class="row-actions">
|
||||
<button onclick={() => startEdit(a)} disabled={editing?.id === a.id}>Edit</button>
|
||||
<button onclick={() => remove(a)}>Remove</button>
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if adding || editing}
|
||||
<form onsubmit={save}>
|
||||
<h3>
|
||||
{#if editing}Edit {editing.email_address ?? editing.username}
|
||||
{:else if accounts.length === 0}Connect your first mailbox
|
||||
{:else}Add an account{/if}
|
||||
</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={!editing}
|
||||
placeholder={editing ? 'unchanged — type a new one to replace it' : ''}
|
||||
autocomplete={editing ? 'new-password' : 'current-password'}
|
||||
/>
|
||||
</label>
|
||||
{#if editing}
|
||||
<p class="hint wide">
|
||||
Saving reconnects with the new settings. Mail already here stays as long as it's the same mailbox;
|
||||
point it at a different one and it's synced afresh.
|
||||
</p>
|
||||
{/if}
|
||||
<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={closeForm}>Cancel</button>
|
||||
{/if}
|
||||
<button type="submit" class="primary" disabled={saving}>
|
||||
{saving ? 'Saving…' : editing ? 'Save changes' : '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;
|
||||
}
|
||||
.row-actions {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.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>
|
||||
+227
-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,
|
||||
@@ -28,15 +29,15 @@
|
||||
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';
|
||||
|
||||
// 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'];
|
||||
@@ -48,7 +49,7 @@
|
||||
let nextCursor = $state<string | null>(null);
|
||||
let loadingMore = $state(false);
|
||||
let outbox = $state<OutboxItem[]>([]);
|
||||
let section = $state<'mail' | 'outbox' | 'rules'>('mail');
|
||||
let section = $state<'mail' | 'outbox' | 'rules' | 'accounts'>('mail');
|
||||
let mailView = $state<MailView>({ kind: 'inbox' });
|
||||
let selected = $state<ThreadSummary | null>(null);
|
||||
let threadMessages = $state<MessageDetail[]>([]);
|
||||
@@ -61,7 +62,17 @@
|
||||
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);
|
||||
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('@')),
|
||||
@@ -131,6 +142,15 @@
|
||||
[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();
|
||||
@@ -139,28 +159,112 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
function reloadAll() {
|
||||
refreshMeta().catch(() => {});
|
||||
listAccounts().then((a) => (accounts = a)).catch(() => {});
|
||||
refresh();
|
||||
refreshAccounts();
|
||||
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') {
|
||||
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;
|
||||
}
|
||||
}, 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) {
|
||||
@@ -270,7 +374,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -396,7 +501,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">
|
||||
@@ -455,13 +561,30 @@
|
||||
|
||||
<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>
|
||||
|
||||
{#if section === 'rules'}
|
||||
<section class="wide-pane">
|
||||
<RulesView {folders} {tags} />
|
||||
<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">
|
||||
@@ -472,6 +595,12 @@
|
||||
{#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.'}
|
||||
@@ -523,6 +652,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;
|
||||
@@ -634,6 +774,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;
|
||||
@@ -660,6 +850,15 @@
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
onCancel: () => void;
|
||||
} = $props();
|
||||
|
||||
type ActionType = 'tag' | 'move' | 'archive' | 'junk' | 'mark_read' | 'delete';
|
||||
type ActionType = 'tag' | 'move' | 'archive' | 'junk' | 'mark_read' | 'delete' | 'dont_notify' | 'notify';
|
||||
|
||||
const fields: [RuleField, string][] = [
|
||||
['from', 'From'],
|
||||
@@ -50,6 +50,10 @@
|
||||
['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
|
||||
|
||||
@@ -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 {
|
||||
@@ -110,6 +129,8 @@
|
||||
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;
|
||||
}
|
||||
})
|
||||
|
||||
+86
-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',
|
||||
@@ -117,15 +124,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> {
|
||||
@@ -142,6 +172,34 @@ export interface Account {
|
||||
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';
|
||||
@@ -174,6 +232,23 @@ export function listAccounts(): Promise<Account[]> {
|
||||
return request('/accounts');
|
||||
}
|
||||
|
||||
export function createAccount(account: NewAccount): Promise<Account> {
|
||||
return request('/accounts', { method: 'POST', body: JSON.stringify(account) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces an account's settings. Leave `password` empty to keep the
|
||||
* stored one. The server restarts the account's sync with the new settings.
|
||||
*/
|
||||
export function updateAccount(id: string, account: NewAccount): Promise<Account> {
|
||||
return request(`/accounts/${id}`, { method: 'PUT', 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' });
|
||||
}
|
||||
@@ -220,7 +295,10 @@ export type Action =
|
||||
| { 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' | 'spam_score';
|
||||
export type RuleOp = 'contains' | 'equals' | 'matches' | 'exists' | 'greater_than' | 'less_than';
|
||||
|
||||
+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();
|
||||
};
|
||||
}
|
||||
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;
|
||||
}
|
||||
+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