đ§â¨ Beautiful email. For everyone.
feat: polish everyday email workflows (#22)
Paul Koeck2d57d1192c3d
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex b7f2268..c638a30 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -99,6 +99,7 @@ import { targetAccounts, targetLimit } from './account-limits'import { SubmissionList } from './SendingStatus'import { IndexingMeter } from './IndexingMeter'import { UpdateNotice } from './UpdateNotice'+import { offersAction } from './view-actions'const Composer = lazy(() => import('./Composer').then((m) => ({ default: m.Composer })))const SettingsPanel = lazy(() => import('./Settings').then((m) => ({ default: m.SettingsPanel })))@@ -500,7 +501,7 @@ export function App() {queryFn: () => api.identities(id),})if (!identities.length) {- notify('This account has no permitted sending identities.')+ notify('This account has no permitted sending identities.', 'error')return}const recipients = message@@ -1390,7 +1391,20 @@ export function App() {hasAttachment: 'Has attachments',}const filterChips = Object.entries(filters).filter(([key, value]) => key !== 'unread' && value)+ // Picked days are stored as UTC midnight; reading them in UTC keeps the day that was chosen.+ const chipDate = (value: string) =>+ new Date(value).toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ timeZone: 'UTC',+ })const selectedCount = allMatching ? total : selected.size+ // Search results can come from anywhere, so they offer every action.+ const listView: View = route.q ? 'all' : view+ const selectedConversations = conversations.filter((c) => selected.has(c.key))+ const selectionStarred =+ !allMatching && !!selectedConversations.length && selectedConversations.every((c) => c.starred)const changeFolder = async (name: string) => {if (!folderDialog) returnconst accountId = folderDialog.accountId || folderDialog.folder?.accountId || folderAccountId@@ -1479,6 +1493,7 @@ export function App() {<Readerkey={scopeKey(readerAccount.id, route.thread!)}messages={thread.data}+ view={route.q ? 'all' : view}backLabel={title}busy={busy}account={readerAccount}@@ -1508,7 +1523,7 @@ export function App() {title={thread.isError ? 'This conversation is unavailable' : 'Opening conversation'}description={thread.isError ? friendlyError(thread.error) : undefined}>- <Button onClick={back}>Back to inbox</Button>+ <Button onClick={back}>Back to {title.toLowerCase()}</Button></EmptyState>)) : (@@ -1582,14 +1597,7 @@ export function App() {className={mail.isFetching && !mail.isFetchingNextPage ? 'spin' : ''}/></IconButton>- <IconButton- label="Search mail"- shortcut={keys('search')}- onClick={() => {- setSearchOpen(!searchOpen)- requestAnimationFrame(() => searchInput.current?.focus())- }}- >+ <IconButton label="Search mail" shortcut={keys('search')} onClick={focusSearch}><Search size={16} /></IconButton>{view !== 'drafts' && (@@ -1658,7 +1666,7 @@ export function App() {<span>{filterLabels[key] || key}{typeof value === 'string' &&- ': ' + (key === 'after' || key === 'before' ? value.slice(0, 10) : value)}+ ': ' + (key === 'after' || key === 'before' ? chipDate(value) : value)}</span><X size={12} /></button>@@ -1698,7 +1706,10 @@ export function App() {<buttonaria-pressed={!!filters.unread}className={filters.unread ? 'active' : ''}- title={keys('toggleUnread')}+ title={+ 'Show only unread conversations' ++ (keys('toggleUnread') ? ' ¡ ' + keys('toggleUnread') : '')+ }onClick={() => setFilters((f) => ({ ...f, unread: true }))}>Unread@@ -1708,7 +1719,7 @@ export function App() {<Buttonvariant="ghost"size="small"- title={keys('filter')}+ title={'Filter conversations' + (keys('filter') ? ' ¡ ' + keys('filter') : '')}onClick={() => setFilterOpen(true)}><SlidersHorizontal size={13} />@@ -1734,32 +1745,36 @@ export function App() {)}</div><span className="toolbar-divider" />- <HintIconButton- label="Archive selected"- shortcut={keys('archive')}- disabled={busy}- hint={unavailable('archive')}- onClick={() => void act('archive')}- >- <Archive size={16} />- </HintIconButton>+ {offersAction(listView, 'archive') && (+ <HintIconButton+ label="Archive selected"+ shortcut={keys('archive')}+ disabled={busy}+ hint={unavailable('archive')}+ onClick={() => void act('archive')}+ >+ <Archive size={16} />+ </HintIconButton>+ )}<IconButton- label="Mark selected read"+ label="Mark selected as read"shortcut={keys('read')}disabled={busy}onClick={() => void act('read')}>- <Check size={16} />+ <MailOpen size={16} /></IconButton>- <HintIconButton- label="Trash selected"- shortcut={keys('trash')}- disabled={busy}- hint={unavailable('trash')}- onClick={() => void act('trash')}- >- <Trash2 size={16} />- </HintIconButton>+ {offersAction(listView, 'trash') && (+ <HintIconButton+ label="Move selected to trash"+ shortcut={keys('trash')}+ disabled={busy}+ hint={unavailable('trash')}+ onClick={() => void act('trash')}+ >+ <Trash2 size={16} />+ </HintIconButton>+ )}<Dropdowntrigger={<Button@@ -1773,42 +1788,66 @@ export function App() {}><MenuItem onClick={() => void act('unread')}>- Mark unread+ <Mail size={14} />+ Mark as unread<ShortcutHint id="unread" className="menu-shortcut" /></MenuItem>- <MenuItem onClick={() => void act('star')}>- Star+ <MenuItem onClick={() => void act(selectionStarred ? 'unstar' : 'star')}>+ <Star size={14} />+ {selectionStarred ? 'Remove star' : 'Star'}<ShortcutHint id="star" className="menu-shortcut" /></MenuItem><MenuItemonClick={() => openMove(targets())}disabled={allMatching || !!unavailable('move')}>+ <FolderInput size={14} />Move to folder<ShortcutHint id="move" className="menu-shortcut" /></MenuItem>- <MenuItem onClick={() => void act('spam')} disabled={!!unavailable('spam')}>- Mark spam- <ShortcutHint id="spam" className="menu-shortcut" />- </MenuItem>- <MenuItem onClick={() => void act('notSpam')} disabled={!!unavailable('notSpam')}>- Not spam- <ShortcutHint id="notSpam" className="menu-shortcut" />- </MenuItem>- <MenuItem onClick={() => void act('restore')} disabled={!!unavailable('restore')}>- Restore to inbox- <ShortcutHint id="restore" className="menu-shortcut" />- </MenuItem>- {view === 'trash' && (+ {offersAction(listView, 'spam') && (+ <MenuItem onClick={() => void act('spam')} disabled={!!unavailable('spam')}>+ <ShieldX size={14} />+ Mark as spam+ <ShortcutHint id="spam" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(listView, 'notSpam') && (+ <MenuItem+ onClick={() => void act('notSpam')}+ disabled={!!unavailable('notSpam')}+ >+ <ShieldCheck size={14} />+ Not spam+ <ShortcutHint id="notSpam" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(listView, 'restore') && (+ <MenuItem+ onClick={() => void act('restore')}+ disabled={!!unavailable('restore')}+ >+ <Inbox size={14} />+ Restore to inbox+ <ShortcutHint id="restore" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(listView, 'destroy') && (<MenuItemdangeronClick={() => void act('destroy')}disabled={!!unavailable('destroy')}>+ <Trash2 size={14} />Delete permanently</MenuItem>)}- {[...new Set([unavailable('move'), view === 'trash' && unavailable('destroy')])]+ {[+ ...new Set([+ unavailable('move'),+ offersAction(listView, 'destroy') && unavailable('destroy'),+ ]),+ ].filter(Boolean).map((reason) => (<p className="menu-note" key={String(reason)}>@@ -1934,6 +1973,7 @@ export function App() {{...emptyListState(view, {searching: !!route.q || hasSearchFilters,unreadOnly: !!filters.unread,+ keys,})}>{hasSearchFilters && (@@ -1958,7 +1998,7 @@ export function App() {focused={focused}busy={busy}remoteImages={settings.remoteImages}- view={view}+ view={listView}hasNextPage={!!mail.hasNextPage}isFetchingNextPage={mail.isFetchingNextPage}listRef={listRef}@@ -2127,7 +2167,7 @@ export function App() {/><ConfirmActionDialogaction={confirmAction}- total={total}+ count={allMatching ? total : targets().length}onClose={() => setConfirmAction(undefined)}onConfirm={(action) => {setConfirmAction(undefined)diff --git a/apps/desktop/src/renderer/src/AppDialogs.tsx b/apps/desktop/src/renderer/src/AppDialogs.tsxindex a695241..7bf5bb0 100644--- a/apps/desktop/src/renderer/src/AppDialogs.tsx+++ b/apps/desktop/src/renderer/src/AppDialogs.tsx@@ -145,6 +145,9 @@ export function FolderDialog({onSave: (name: string) => void}) {const [name, setName] = useState(dialog?.folder?.name || '')+ const operation = dialog?.operation+ // Renaming to the same name would only make a round trip to the server.+ const ready = !!name.trim() && !(operation === 'rename' && name.trim() === dialog?.folder?.name)return (<Modalopen={!!dialog}@@ -152,84 +155,119 @@ export function FolderDialog({if (!open) onClose()}}title={- dialog?.operation === 'delete'+ operation === 'delete'? 'Delete â' + name + 'â?'- : dialog?.operation === 'rename'+ : operation === 'rename'? 'Rename folder': 'Create a folder'}description={- dialog?.operation === 'delete'+ operation === 'delete'? 'The folder is deleted on the server. Messages that are also in other folders stay there.': undefined}>- {dialog?.operation !== 'delete' && (- <label>- Folder name- <input- autoFocus- value={name}- onChange={(event) => setName(event.target.value)}- onKeyDown={(event) => {- if (event.key === 'Enter' && name.trim()) onSave(name)- }}- />- </label>- )}- <div className="modal-actions">- <Button onClick={onClose}>Cancel</Button>- <Button- variant={dialog?.operation === 'delete' ? 'danger' : 'primary'}- disabled={!name.trim()}- onClick={() => onSave(name)}- >- {dialog?.operation === 'delete' ? 'Delete folder' : 'Save folder'}- </Button>- </div>+ <form+ onSubmit={(event) => {+ event.preventDefault()+ if (ready) onSave(name)+ }}+ >+ {operation !== 'delete' && (+ <label className="modal-field">+ Folder name+ <input autoFocus value={name} onChange={(event) => setName(event.target.value)} />+ </label>+ )}+ <div className="modal-actions">+ <Button onClick={onClose}>Cancel</Button>+ <Button+ type="submit"+ variant={operation === 'delete' ? 'danger' : 'primary'}+ disabled={!ready}+ >+ {operation === 'delete'+ ? 'Delete folder'+ : operation === 'rename'+ ? 'Rename folder'+ : 'Create folder'}+ </Button>+ </div>+ </form></Modal>)}+/** Names the action and how many conversations it reaches, so the choice is never vague. */+export function confirmActionCopy(action: MailAction, count: number) {+ const n = count.toLocaleString()+ const them = count === 1 ? 'this conversation' : 'all ' + n + ' conversations'+ if (action === 'destroy')+ return {+ title:+ count === 1+ ? 'Delete this conversation permanently?'+ : 'Delete ' + n + ' conversations permanently?',+ description:+ (count === 1 ? 'Its' : 'Their') ++ ' messages are removed from the server. This canât be undone.',+ confirm: 'Delete permanently',+ }+ const copy: Record<Exclude<MailAction, 'destroy'>, [title: string, confirm: string]> = {+ archive: ['Archive ' + them + '?', 'Archive'],+ trash: ['Move ' + them + ' to trash?', 'Move to trash'],+ spam: ['Mark ' + them + ' as spam?', 'Mark as spam'],+ notSpam: ['Move ' + them + ' to the inbox?', 'Not spam'],+ read: ['Mark ' + them + ' as read?', 'Mark as read'],+ unread: ['Mark ' + them + ' as unread?', 'Mark as unread'],+ star: ['Star ' + them + '?', 'Star'],+ unstar: ['Remove the star from ' + them + '?', 'Remove star'],+ move: ['Move ' + them + '?', 'Move'],+ restore: ['Restore ' + them + ' to the inbox?', 'Restore'],+ }+ const [title, confirm] = copy[action]+ return {+ title,+ description:+ 'Includes conversations that havenât loaded yet. Inlark tells you about any it couldnât change.',+ confirm,+ }+}+export function ConfirmActionDialog({action,- total,+ count,onClose,onConfirm,}: {action?: MailAction- total: number+ /** How many conversations the action reaches. */+ count: numberonClose: () => voidonConfirm: (action: MailAction) => void}) {+ // Keep the wording while the dialog fades out after the action is cleared.+ const [shown, setShown] = useState({ action, count })+ if (action && (action !== shown.action || count !== shown.count)) setShown({ action, count })+ const copy = shown.action && confirmActionCopy(shown.action, shown.count)return (<Modalopen={!!action}onOpenChange={(open) => {if (!open) onClose()}}- title={- action === 'destroy'- ? 'Permanently delete these conversations?'- : 'Update all matching conversations?'- }- description={- action === 'destroy'- ? 'This removes messages from the server permanently and cannot be undone.'- : 'This applies to all ' +- total.toLocaleString() +- ' matching conversations, including those beyond the loaded page. Partial failures will be reported.'- }+ title={copy ? copy.title : ''}+ description={copy?.description}><div className="modal-actions"><Button onClick={onClose}>Cancel</Button><Button- variant={action === 'destroy' ? 'danger' : 'primary'}+ variant={shown.action === 'destroy' ? 'danger' : 'primary'}onClick={() => {if (action) onConfirm(action)}}>- Confirm+ {copy?.confirm}</Button></div></Modal>diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxindex 982b11b..94639d2 100644--- a/apps/desktop/src/renderer/src/Composer.tsx+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -33,6 +33,12 @@ import { RecipientField } from './RecipientField'import { formatBytes } from './mail-date'import { bindingText, useShortcutHandlers, useShortcutText, useShortcuts } from './shortcuts'import { SignatureNode } from './signature'+import { linkTarget } from './link-target'++const validAddress = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)+/** The editor's own formatting keys, which follow the platform (â on macOS, Ctrl elsewhere). */+const boldKeys = bindingText(['Mod+B'])+const italicKeys = bindingText(['Mod+I'])/** Plain wording for a finished send; the Drafts view offers recovery for anything left over. */function sentMessage(result: SendResult): string {@@ -112,6 +118,8 @@ export function Composer({[expanded, setExpanded] = useState(false),[linkOpen, setLinkOpen] = useState(false),[linkValue, setLinkValue] = useState(''),+ [linkError, setLinkError] = useState(''),+ [editingLink, setEditingLink] = useState(false),[discardOpen, setDiscardOpen] = useState(false)const latest = useRef(draft),sync = useRef<Promise<unknown>>(Promise.resolve()),@@ -259,18 +267,28 @@ export function Composer({onSaved()onClose()} catch (e) {- notify('Your draft could not be saved. ' + friendlyError(e))+ notify('Your draft could not be saved. ' + friendlyError(e), 'error')}}const send = async () => {if (sending || account.status !== 'connected') return- const recipients = [...latest.current.to, ...latest.current.cc, ...latest.current.bcc]- if (!recipients.length || recipients.some((a) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.email))) {- notify('Add valid email addresses before sending.')+ const fields = ['to', 'cc', 'bcc'] as const+ if (!fields.some((field) => latest.current[field].length)) {+ notify('Add a recipient before sending.', 'error')+ document.getElementById('compose-to')?.focus()+ return+ }+ // Point at the address to fix; its chip is already marked in red.+ const field = fields.find((name) => latest.current[name].some((a) => !validAddress(a.email)))+ if (field) {+ const invalid = latest.current[field].find((a) => !validAddress(a.email))!+ notify('â' + (invalid.email || invalid.name) + 'â isnât a valid email address.', 'error')+ if (field === 'to') document.getElementById('compose-to')?.focus()+ else focusRecipient(field)return}if (!latest.current.identityId) {- notify('Select a sending identity.')+ notify('Select a sending identity.', 'error')return}setSending(true)@@ -290,7 +308,7 @@ export function Composer({onSaved()onClose()} else {- notify(result.message)+ notify(result.message, 'error')const uncertain = { ...latest.current, status: 'uncertain' as const }latest.current = uncertainsetDraft(uncertain)@@ -332,8 +350,26 @@ export function Composer({if (!alive.current || lockedRef.current) returnupdate({ attachments: [...latest.current.attachments, ...attachments] })} catch (error) {- notify(friendlyError(error))+ notify(friendlyError(error), 'error')+ }+ }+ const insertLink = () => {+ const href = linkTarget(linkValue)+ if (!href || !editor) {+ setLinkError('Enter a web address such as example.com, or an email address.')+ return}+ const chain = editor.chain().focus()+ // With nothing selected, the address itself becomes the link text, so the link is visible.+ if (editor.state.selection.empty && !editor.isActive('link'))+ chain.insertContent({+ type: 'text',+ text: linkValue.trim(),+ marks: [{ type: 'link', attrs: { href } }],+ })+ else chain.extendMarkRange('link').setLink({ href })+ chain.run()+ setLinkOpen(false)}const focusRecipient = (field: 'cc' | 'bcc') => {setShowCc(true)@@ -464,7 +500,7 @@ export function Composer({serverFingerprint: undefined,})} catch (error) {- notify(friendlyError(error))+ notify(friendlyError(error), 'error')}}}/>@@ -575,7 +611,7 @@ export function Composer({<fieldset className="compose-format" disabled={locked}><IconButtonlabel="Bold"- shortcut="Ctrl B"+ shortcut={boldKeys}onClick={() => editor?.chain().focus().toggleBold().run()}className={formatting?.bold ? 'active-format' : ''}aria-pressed={formatting?.bold || false}@@ -586,7 +622,7 @@ export function Composer({label="Italic"className={formatting?.italic ? 'active-format' : ''}aria-pressed={formatting?.italic || false}- shortcut="Ctrl I"+ shortcut={italicKeys}onClick={() => editor?.chain().focus().toggleItalic().run()}><Italic size={14} />@@ -600,11 +636,14 @@ export function Composer({<BulletList size={15} /></IconButton><IconButton- label="Add link"+ label={formatting?.link ? 'Edit link' : 'Add link'}className={formatting?.link ? 'active-format' : ''}aria-pressed={formatting?.link || false}onClick={() => {- setLinkValue(editor?.getAttributes('link').href || '')+ const href: string = editor?.getAttributes('link').href || ''+ setEditingLink(!!href)+ setLinkValue(href.replace(/^mailto:/i, ''))+ setLinkError('')setLinkOpen(true)}}>@@ -667,7 +706,7 @@ export function Composer({onSaved()onClose()} catch (e) {- notify(friendlyError(e))+ notify(friendlyError(e), 'error')}}}>@@ -675,29 +714,56 @@ export function Composer({</Button></div></Modal>- <Modal open={linkOpen} onOpenChange={setLinkOpen} title="Add a link">- <label>- URL- <input- value={linkValue}- placeholder="https://âŚ"- onChange={(e) => setLinkValue(e.target.value)}- />- </label>- <div className="modal-actions">- <Button onClick={() => setLinkOpen(false)}>Cancel</Button>- <Button- variant="primary"- onClick={() => {- if (/^https?:\/\//.test(linkValue)) {- editor?.chain().focus().extendMarkRange('link').setLink({ href: linkValue }).run()- setLinkOpen(false)- }- }}- >- Insert link- </Button>- </div>+ <Modal+ open={linkOpen}+ onOpenChange={setLinkOpen}+ title={editingLink ? 'Edit link' : 'Add a link'}+ >+ <form+ onSubmit={(event) => {+ event.preventDefault()+ insertLink()+ }}+ >+ <label className="modal-field">+ Web or email address+ <input+ autoFocus+ value={linkValue}+ placeholder="example.com"+ spellCheck={false}+ aria-invalid={!!linkError || undefined}+ aria-describedby={linkError ? 'compose-link-error' : undefined}+ onChange={(e) => {+ setLinkValue(e.target.value)+ setLinkError('')+ }}+ />+ </label>+ {linkError && (+ <span className="field-error" id="compose-link-error" role="alert">+ {linkError}+ </span>+ )}+ <div className="modal-actions">+ {editingLink && (+ <Button+ variant="ghost"+ className="modal-action-start"+ onClick={() => {+ editor?.chain().focus().extendMarkRange('link').unsetLink().run()+ setLinkOpen(false)+ }}+ >+ Remove link+ </Button>+ )}+ <Button onClick={() => setLinkOpen(false)}>Cancel</Button>+ <Button variant="primary" type="submit">+ {editingLink ? 'Update link' : 'Insert link'}+ </Button>+ </div>+ </form></Modal></Dialog.Root>)diff --git a/apps/desktop/src/renderer/src/ConversationList.tsx b/apps/desktop/src/renderer/src/ConversationList.tsxindex e379888..aba8cc0 100644--- a/apps/desktop/src/renderer/src/ConversationList.tsx+++ b/apps/desktop/src/renderer/src/ConversationList.tsx@@ -9,10 +9,11 @@ import {} from 'react'import type { Ref, RefObject } from 'react'import { useVirtualizer } from '@tanstack/react-virtual'-import type { Account, Conversation, MailAction } from '@inlark/core'+import type { Account, Conversation, MailAction, View } from '@inlark/core'import { Spinner } from '@inlark/ui'import { ConversationRow, senderLabel } from './ConversationRow'import { day } from './mail-date'+import { offersAction } from './view-actions'export type ConversationListHandle = {scrollToConversation: (key: string) => void@@ -39,7 +40,7 @@ const ListConversationRow = memo(function ListConversationRow({focused: booleanbusy: booleanremoteImages: boolean- view: string+ view: ViewonOpen: (conversation: Conversation) => voidonFocus: (key: string) => voidonSelect: (key: string, range: boolean) => void@@ -56,8 +57,10 @@ const ListConversationRow = memo(function ListConversationRow({onSelect={(range) => onSelect(conversation.key, range)}busy={busy}remoteImages={remoteImages}- onArchive={view === 'archive' ? undefined : () => onAction('archive', conversation)}- onTrash={view === 'trash' ? undefined : () => onAction('trash', conversation)}+ onArchive={+ offersAction(view, 'archive') ? () => onAction('archive', conversation) : undefined+ }+ onTrash={offersAction(view, 'trash') ? () => onAction('trash', conversation) : undefined}onToggleRead={() => onAction(conversation.unread ? 'read' : 'unread', conversation)}onStar={() => onAction(conversation.starred ? 'unstar' : 'star', conversation)}/>@@ -97,7 +100,7 @@ export function ConversationList({focused: stringbusy: booleanremoteImages: boolean- view: string+ view: ViewhasNextPage: booleanisFetchingNextPage: booleanlistRef: RefObject<HTMLDivElement | null>diff --git a/apps/desktop/src/renderer/src/ConversationRow.tsx b/apps/desktop/src/renderer/src/ConversationRow.tsxindex fe5c2ae..20ce929 100644--- a/apps/desktop/src/renderer/src/ConversationRow.tsx+++ b/apps/desktop/src/renderer/src/ConversationRow.tsx@@ -43,6 +43,7 @@ export function ConversationRow({}) {const keys = useShortcutText()const moveLimit = actionLimit(a, 'move')+ const subject = c.subject || '(No subject)'return (<divclassName={@@ -59,7 +60,7 @@ export function ConversationRow({><div className="row-selector" role="gridcell" onClick={(event) => event.stopPropagation()}><Checkbox- aria-label={'Select ' + c.subject}+ aria-label={'Select ' + subject}checked={selected}disabled={busy}onCheckedChange={(_, event) => onSelect(!!(event as MouseEvent).shiftKey)}@@ -78,7 +79,7 @@ export function ConversationRow({{c.count > 1 && <small>{c.count}</small>}</div><div className="row-content" role="gridcell">- <span className="row-subject">{c.subject || '(No subject)'}</span>+ <span className="row-subject">{subject}</span><span className="row-preview">{c.preview}</span></div><div className="row-meta" role="gridcell">@@ -91,7 +92,7 @@ export function ConversationRow({</time><buttonclassName={'row-star ' + (c.starred ? 'starred' : '')}- aria-label={c.starred ? 'Unstar ' + c.subject : 'Star ' + c.subject}+ aria-label={(c.starred ? 'Unstar ' : 'Star ') + subject}aria-pressed={c.starred}disabled={busy}onClick={(event) => {diff --git a/apps/desktop/src/renderer/src/MoveDialog.tsx b/apps/desktop/src/renderer/src/MoveDialog.tsxindex a754f95..af0f81b 100644--- a/apps/desktop/src/renderer/src/MoveDialog.tsx+++ b/apps/desktop/src/renderer/src/MoveDialog.tsx@@ -1,10 +1,24 @@+import { useEffect, useId, useRef, useState } from 'react'import { useQuery } from '@tanstack/react-query'-import { ChevronRight, Folder } from '@inlark/ui/icons'-import { Modal } from '@inlark/ui'-import type { Bootstrap, MutationTarget } from '@inlark/core'+import { ChevronRight, Folder, Search } from '@inlark/ui/icons'+import { Modal, Spinner } from '@inlark/ui'+import { friendlyError, type Bootstrap, type Mailbox, type MutationTarget } from '@inlark/core'import { api } from './api'import { actionLimit } from './account-limits'+/** Folders whose name contains the typed text, those starting with it first. */+export function matchFolders<T extends Pick<Mailbox, 'name'>>(folders: T[], text: string): T[] {+ const query = text.trim().toLowerCase()+ if (!query) return folders+ const starts = (name: string) =>+ name.startsWith(query) || name.split(/[\s/._-]+/).some((word) => word.startsWith(query))+ const found = folders.filter((f) => f.name.toLowerCase().includes(query))+ return [+ ...found.filter((f) => starts(f.name.toLowerCase())),+ ...found.filter((f) => !starts(f.name.toLowerCase())),+ ]+}+export function MoveDialog({targets,accounts,@@ -27,9 +41,31 @@ export function MoveDialog({queryFn: () => api.mailboxes(accountId),enabled: !!targets && ids.size === 1,})+ const [text, setText] = useState('')+ const [active, setActive] = useState(0)+ const listId = useId()+ const list = useRef<HTMLDivElement>(null)+ const open = !!targets+ useEffect(() => {+ if (open) {+ setText('')+ setActive(0)+ }+ }, [open])+ const folders = matchFolders(+ (boxes.data || []).filter(+ (b) => b.rights.mayAddItems && b.role !== 'drafts' && b.role !== 'sent',+ ),+ text,+ )+ const highlighted = Math.max(0, Math.min(active, folders.length - 1))+ useEffect(() => {+ list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' })+ }, [highlighted, text])+ const choosable = ids.size === 1 && !limitreturn (<Modal- open={!!targets}+ open={open}onOpenChange={(open) => {if (!open) onClose()}}@@ -39,21 +75,82 @@ export function MoveDialog({? 'Select conversations within one account to move them to a folder.': accounts.find((a) => a.id === accountId)?.email}+ className="move-modal">{limit && <p className="modal-body-text">{limit}</p>}- <div className="folder-picker">- {ids.size === 1 &&- !limit &&- boxes.data- ?.filter((b) => b.rights.mayAddItems && b.role !== 'drafts' && b.role !== 'sent')- .map((b) => (- <button key={b.id} onClick={() => onMove(b.id)}>+ {choosable && (+ <>+ <div className="folder-search">+ <Search size={14} />+ <input+ autoFocus+ value={text}+ placeholder="Find a folder"+ aria-label="Find a folder"+ role="combobox"+ aria-autocomplete="list"+ aria-expanded+ aria-controls={listId}+ aria-activedescendant={folders.length ? listId + '-' + highlighted : undefined}+ onChange={(event) => {+ setText(event.target.value)+ setActive(0)+ }}+ onKeyDown={(event) => {+ const step =+ event.key === 'ArrowDown' || (event.ctrlKey && event.key === 'n')+ ? 1+ : event.key === 'ArrowUp' || (event.ctrlKey && event.key === 'p')+ ? -1+ : 0+ if (step && folders.length) {+ event.preventDefault()+ setActive((highlighted + step + folders.length) % folders.length)+ }+ if (event.key === 'Enter') {+ event.preventDefault()+ if (folders[highlighted]) onMove(folders[highlighted].id)+ }+ }}+ />+ </div>+ <div className="folder-picker" role="listbox" id={listId} aria-label="Folders" ref={list}>+ {folders.map((b, i) => (+ <button+ key={b.id}+ id={listId + '-' + i}+ role="option"+ aria-selected={i === highlighted}+ tabIndex={-1}+ className={i === highlighted ? 'active' : ''}+ onMouseMove={() => i !== highlighted && setActive(i)}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => onMove(b.id)}+ ><Folder size={15} />- {b.name}+ <span>{b.name}</span><ChevronRight size={13} /></button>))}- </div>+ {boxes.isLoading && (+ <div className="folder-picker-note" role="status">+ <Spinner size={14} />+ Loading foldersâŚ+ </div>+ )}+ {boxes.isError && (+ <div className="folder-picker-note" role="alert">+ {friendlyError(boxes.error)}+ </div>+ )}+ {boxes.data && !folders.length && (+ <div className="folder-picker-note">+ {text.trim() ? 'No folders match â' + text.trim() + 'â' : 'No folders to move to'}+ </div>+ )}+ </div>+ </>+ )}</Modal>)}diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsxindex 674389d..6bfe5e8 100644--- a/apps/desktop/src/renderer/src/Reader.tsx+++ b/apps/desktop/src/renderer/src/Reader.tsx@@ -36,6 +36,7 @@ import {type Message,type Settings,type MailAction,+ type View,} from '@inlark/core'import { api } from './api'import { SenderAvatar } from './SenderAvatar'@@ -46,6 +47,7 @@ import { HintIconButton } from './HintIconButton'import { actionLimit } from './account-limits'import { ShortcutHint, useShortcutText } from './shortcuts'import { emailSanitizeOptions } from './email-html'+import { offersAction } from './view-actions'const formatAddress = (a: { name: string; email: string }) =>a.name ? a.name + ' <' + a.email + '>' : a.email@@ -482,6 +484,8 @@ interface ReaderProps {messages: Message[]account: Accountsettings: Settings+ /** Where the conversation was opened from, which decides the actions worth offering. */+ view: ViewbackLabel: stringbusy: booleanonBack: () => void@@ -491,7 +495,7 @@ interface ReaderProps {onAction: (action: MailAction) => voidonMove: () => voidonReply: (message: Message, kind: 'reply' | 'replyAll' | 'forward') => void- notify: (message: string) => void+ notify: (message: string, tone?: 'error' | 'info') => voidonMailto: (url: string) => void/** Set when the conversation comes from a mailing list that can be left. */unsubscribe?: UnsubscribeState@@ -562,6 +566,7 @@ export function Reader({messages,account,settings,+ view,backLabel,busy,onBack,@@ -598,8 +603,17 @@ export function Reader({setExpanded(initiallyExpanded())}}, [messageIds])+ const scroller = useRef<HTMLDivElement>(null)+ useEffect(() => {+ // Space, Page Up/Down, Home and End scroll the conversation without clicking into it first.+ // Never take focus from a field or dialog, e.g. when a notification opens a conversation.+ const active = document.activeElement+ if (!active?.closest('[role="dialog"], input, textarea, [contenteditable="true"]'))+ scroller.current?.focus({ preventScroll: true })+ }, [])const starred = messages.some((m) => m.keywords.$flagged)const moveLimit = actionLimit(account, 'move')+ const destroyLimit = actionLimit(account, 'destroy')const toggle = (id: string, setter: typeof setExpanded) =>setter((current) => {const next = new Set(current)@@ -625,33 +639,37 @@ export function Reader({className="reader-back"aria-label={'Back to ' + backLabel.toLowerCase()}onClick={onBack}- title="Back ¡ Esc"+ title={'Back' + (keys('back') ? ' ¡ ' + keys('back') : '')}><ArrowLeft size={16} /><span>{backLabel}</span></Button><span className="toolbar-divider" />- <HintIconButton- disabled={busy}- label="Archive"- shortcut={keys('archive')}- hint={moveLimit}- onClick={() => onAction('archive')}- >- <Archive size={16} />- </HintIconButton>- <HintIconButton- disabled={busy}- label="Move to trash"- shortcut={keys('trash')}- hint={moveLimit}- onClick={() => onAction('trash')}- >- <Trash2 size={16} />- </HintIconButton>+ {offersAction(view, 'archive') && (+ <HintIconButton+ disabled={busy}+ label="Archive"+ shortcut={keys('archive')}+ hint={moveLimit}+ onClick={() => onAction('archive')}+ >+ <Archive size={16} />+ </HintIconButton>+ )}+ {offersAction(view, 'trash') && (+ <HintIconButton+ disabled={busy}+ label="Move to trash"+ shortcut={keys('trash')}+ hint={moveLimit}+ onClick={() => onAction('trash')}+ >+ <Trash2 size={16} />+ </HintIconButton>+ )}<IconButtondisabled={busy}- label="Mark unread"+ label="Mark as unread"shortcut={keys('unread')}onClick={() => onAction('unread')}>@@ -683,22 +701,40 @@ export function Reader({Move to folder<ShortcutHint id="move" className="menu-shortcut" /></MenuItem>- <MenuItem onClick={() => onAction('spam')} disabled={!!moveLimit}>- <ShieldX size={14} />- Mark as spam- <ShortcutHint id="spam" className="menu-shortcut" />- </MenuItem>- <MenuItem onClick={() => onAction('notSpam')} disabled={!!moveLimit}>- <ShieldCheck size={14} />- Not spam- <ShortcutHint id="notSpam" className="menu-shortcut" />- </MenuItem>- <MenuItem onClick={() => onAction('restore')} disabled={!!moveLimit}>- <Inbox size={14} />- Restore to inbox- <ShortcutHint id="restore" className="menu-shortcut" />- </MenuItem>- {moveLimit && <p className="menu-note">{moveLimit}</p>}+ {offersAction(view, 'spam') && (+ <MenuItem onClick={() => onAction('spam')} disabled={!!moveLimit}>+ <ShieldX size={14} />+ Mark as spam+ <ShortcutHint id="spam" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(view, 'notSpam') && (+ <MenuItem onClick={() => onAction('notSpam')} disabled={!!moveLimit}>+ <ShieldCheck size={14} />+ Not spam+ <ShortcutHint id="notSpam" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(view, 'restore') && (+ <MenuItem onClick={() => onAction('restore')} disabled={!!moveLimit}>+ <Inbox size={14} />+ Restore to inbox+ <ShortcutHint id="restore" className="menu-shortcut" />+ </MenuItem>+ )}+ {offersAction(view, 'destroy') && (+ <MenuItem danger onClick={() => onAction('destroy')} disabled={!!destroyLimit}>+ <Trash2 size={14} />+ Delete permanently+ </MenuItem>+ )}+ {[...new Set([moveLimit, offersAction(view, 'destroy') && destroyLimit])]+ .filter(Boolean)+ .map((reason) => (+ <p className="menu-note" key={String(reason)}>+ {reason}+ </p>+ ))}</Dropdown>{unsubscribe && (<>@@ -726,7 +762,7 @@ export function Reader({</IconButton></div></div>- <div className="reader-scroll">+ <div className="reader-scroll" ref={scroller} tabIndex={-1}><div className="reader-content"><div className="reader-eyebrow"><AccountMark account={account} size={16} />@@ -854,7 +890,7 @@ export function Reader({onClick={() =>void api.attachment(account.id, attachment, true)- .catch((e) => notify(friendlyError(e)))+ .catch((e) => notify(friendlyError(e), 'error'))}><span className="attachment-icon">@@ -872,7 +908,7 @@ export function Reader({onClick={() =>void api.attachment(account.id, attachment, false)- .catch((e) => notify(friendlyError(e)))+ .catch((e) => notify(friendlyError(e), 'error'))}><Download size={14} />diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsxindex 10e30b4..1a6f330 100644--- a/apps/desktop/src/renderer/src/Settings.tsx+++ b/apps/desktop/src/renderer/src/Settings.tsx@@ -63,7 +63,7 @@ function AccountDetailsForm({}: {account: AccountonDone: () => void- notify: (message: string) => void+ notify: (message: string, tone?: 'error' | 'info') => void}) {const [name, setName] = useState(account.name)const [senderName, setSenderName] = useState(account.senderName || '')@@ -83,7 +83,7 @@ function AccountDetailsForm({])onDone()} catch (error) {- notify(friendlyError(error))+ notify(friendlyError(error), 'error')} finally {setSaving(false)}@@ -146,7 +146,7 @@ export function SettingsPanel({onClose: () => voidbootstrap: BootstraponChange: (settings: Preferences) => void- notify: (message: string) => void+ notify: (message: string, tone?: 'error' | 'info') => voidinitialTab?: string}) {// With nothing connected yet, opening Accounts can only mean adding one.@@ -180,7 +180,7 @@ export function SettingsPanel({},)api.updateAccount(account.id, appearance).catch((e) => {- notify(friendlyError(e))+ notify(friendlyError(e), 'error')void queryClient.invalidateQueries({ queryKey: ['bootstrap'] })})}@@ -190,7 +190,7 @@ export function SettingsPanel({onChange(next)return true} catch (e) {- notify(friendlyError(e))+ notify(friendlyError(e), 'error')return false}}@@ -332,18 +332,29 @@ export function SettingsPanel({/></div></div>- <div className="setting-section">- <h4>Default sending account</h4>- <Select- aria-label="Default sending account"- value={bootstrap.settings.defaultAccountId || bootstrap.accounts[0]?.id || ''}- options={bootstrap.accounts.map((a) => ({- value: a.id,- label: a.name + ' ¡ ' + a.email,- }))}- onValueChange={(defaultAccountId) => void update({ defaultAccountId })}- />- </div>+ {bootstrap.accounts.length > 1 && (+ <div className="setting-section">+ <h4>Writing</h4>+ <div className="setting-row">+ <div>+ <strong>Default sending account</strong>+ <p>New messages start from this account unless youâre in another one.</p>+ </div>+ <Select+ aria-label="Default sending account"+ className="setting-select"+ value={+ bootstrap.settings.defaultAccountId || bootstrap.accounts[0]?.id || ''+ }+ options={bootstrap.accounts.map((a) => ({+ value: a.id,+ label: a.name + ' ¡ ' + a.email,+ }))}+ onValueChange={(defaultAccountId) => void update({ defaultAccountId })}+ />+ </div>+ </div>+ )}</>)}{tab === 'accounts' &&@@ -391,7 +402,7 @@ export function SettingsPanel({value={{ seed: account.seed, image: account.image }}portalContainer={modalRef}onChange={(appearance) => updateAppearance(account, appearance)}- onError={(e) => notify(friendlyError(e))}+ onError={(e) => notify(friendlyError(e), 'error')}/><div className="settings-account-text"><strong>@@ -482,7 +493,7 @@ export function SettingsPanel({void api.reconnect(account.connectionId).then(() => notify('Reconnected.'))- .catch((e) => notify(friendlyError(e)))+ .catch((e) => notify(friendlyError(e), 'error'))}><RefreshCw size={14} />@@ -620,7 +631,7 @@ export function SettingsPanel({await navigator.clipboard.writeText(diagnostics)notify('Redacted diagnostics copied.')} catch (e) {- notify(friendlyError(e))+ notify(friendlyError(e), 'error')}}}>@@ -664,7 +675,7 @@ export function SettingsPanel({setRemove(undefined)notify('Account removed from this device.')} catch (e) {- notify(friendlyError(e))+ notify(friendlyError(e), 'error')}}}>diff --git a/apps/desktop/src/renderer/src/demo.ts b/apps/desktop/src/renderer/src/demo.tsindex 9ab8287..356ac86 100644--- a/apps/desktop/src/renderer/src/demo.ts+++ b/apps/desktop/src/renderer/src/demo.ts@@ -762,9 +762,11 @@ export const demoAPI: DesktopMailAPI = {if (destination) next.mailboxIds = { [destination]: true }changes.set(key, input.action === 'destroy' ? null : next)}+ changed()+ // Like the desktop service, a permanent deletion has nothing to undo.+ if (input.action === 'destroy') return { changed: saved.length, failures: [] }const undoId = crypto.randomUUID()undoStack.set(undoId, saved)- changed()return { changed: saved.length, failures: [], undoId }},mutateAll: async (query, action) => {diff --git a/apps/desktop/src/renderer/src/empty-states.ts b/apps/desktop/src/renderer/src/empty-states.tsindex 8de038c..2dc834a 100644--- a/apps/desktop/src/renderer/src/empty-states.ts+++ b/apps/desktop/src/renderer/src/empty-states.ts@@ -1,12 +1,22 @@import { Folder, Search, type IconComponent } from '@inlark/ui/icons'import type { View } from '@inlark/core'import { views } from './Sidebar'+import type { ShortcutId } from './shortcuts'-const copy: Record<Exclude<View, 'drafts'>, { title: string; description: string }> = {+/** The label of a shortcut's first binding, or nothing when the user removed it. */+type KeyText = (id: ShortcutId) => string | undefined++const copy: Record<+ Exclude<View, 'drafts'>,+ { title: string; description: string | ((keys: KeyText) => string) }+> = {inbox: { title: 'Youâre all caught up', description: 'New mail will show up here.' },starred: {title: 'No starred conversations',- description: 'Press S to star the selected conversation.',+ description: (keys) =>+ keys('star')+ ? 'Press ' + keys('star') + ' to star the selected conversation.'+ : 'Conversations you star will show up here.',},sent: { title: 'Nothing sent yet', description: 'Messages you send will appear here.' },archive: {@@ -17,14 +27,21 @@ const copy: Record<Exclude<View, 'drafts'>, { title: string; description: stringtrash: { title: 'Trash is empty', description: 'Deleted conversations will show up here.' },all: {title: 'This folder is empty',- description: 'Press V to move conversations here.',+ description: (keys) =>+ keys('move')+ ? 'Press ' + keys('move') + ' to move conversations here.'+ : 'Move conversations here to keep them together.',},}/** What an empty conversation list says, depending on where the user is and why it's empty. */export function emptyListState(view: View,- { searching, unreadOnly }: { searching: boolean; unreadOnly: boolean },+ {+ searching,+ unreadOnly,+ keys = () => undefined,+ }: { searching: boolean; unreadOnly: boolean; keys?: KeyText },): { icon: IconComponent; title: string; description: string } {if (searching)return {@@ -35,5 +52,10 @@ export function emptyListState(const icon = views.find((v) => v.id === view)?.icon || Folderif (unreadOnly)return { icon, title: 'No unread conversations', description: 'Youâve read everything here.' }- return { icon, ...copy[view === 'drafts' ? 'all' : view] }+ const { title, description } = copy[view === 'drafts' ? 'all' : view]+ return {+ icon,+ title,+ description: typeof description === 'function' ? description(keys) : description,+ }}diff --git a/apps/desktop/src/renderer/src/link-target.ts b/apps/desktop/src/renderer/src/link-target.tsnew file mode 100644index 0000000..b7c9e64--- /dev/null+++ b/apps/desktop/src/renderer/src/link-target.ts@@ -0,0 +1,25 @@+/**+ * The address a typed link should point to, or nothing if it can't be a web or email link.+ * People paste `example.com` or `[email protected]` far more often than a full URL, so those+ * become `https://âŚ` and `mailto:âŚ` links instead of being refused.+ */+export function linkTarget(value: string): string | undefined {+ const text = value.trim()+ if (!text || /\s/.test(text)) return undefined+ const candidate = /^(https?:\/\/|mailto:)/i.test(text)+ ? text+ : /^[^@/:]+@[^@/:]+\.[^@/:]+$/.test(text)+ ? 'mailto:' + text+ : /^[^@/:]+\.[^@/:]+/.test(text)+ ? 'https://' + text+ : undefined+ if (!candidate) return undefined+ try {+ const url = new URL(candidate)+ if (url.protocol === 'mailto:')+ return /^[^@]+@[^@]+\.[^@]+$/.test(decodeURIComponent(url.pathname)) ? candidate : undefined+ return url.hostname ? candidate : undefined+ } catch {+ return undefined+ }+}diff --git a/apps/desktop/src/renderer/src/styles.css b/apps/desktop/src/renderer/src/styles.cssindex af92975..c9bb476 100644--- a/apps/desktop/src/renderer/src/styles.css+++ b/apps/desktop/src/renderer/src/styles.css@@ -513,7 +513,7 @@border: 0;background: none;color: var(--accent);- font-size: 10px;+ font-size: 11px;padding: 0;text-align: left;}@@ -867,6 +867,10 @@ svg.starred {flex: 1;overflow: auto;}+/* Focused on open so the keyboard scrolls the conversation; the whole pane needs no ring. */+.reader-scroll:focus-visible {+ outline: none;+}.reader-content {width: min(840px, 100%);margin: 0 auto;@@ -1923,7 +1927,7 @@ svg.starred {padding: 10px 22px;font-size: 11px;color: var(--red);- background: var(--accent-tint);+ background: color-mix(in srgb, var(--red) 8%, transparent);}.compose-attachments {display: flex;@@ -2186,6 +2190,45 @@ svg.starred {margin-left: -10px;color: var(--muted);}+.move-modal {+ width: min(440px, calc(100vw - 40px));+}+.folder-search {+ display: flex;+ align-items: center;+ gap: 8px;+ height: 36px;+ margin-bottom: 8px;+ padding: 0 11px;+ color: var(--muted);+ background: var(--field);+ border: 1px solid var(--border-strong);+ border-radius: 7px;+ transition:+ border-color 120ms,+ box-shadow 120ms;+}+.folder-search:focus-within {+ border-color: var(--accent-solid);+ box-shadow: 0 0 0 3px var(--accent-tint);+}+.folder-search input {+ height: 100%;+ padding: 0;+ font-size: 12px;+ background: none;+ border: 0;+}+.folder-search input:focus-visible {+ outline: none;+}+/* Long folder lists scroll inside the dialog so the search field stays in view. */+.folder-picker {+ max-height: min(340px, calc(100vh - 280px));+ overflow-y: auto;+ margin: 0 -6px;+ padding: 0 6px;+}.folder-picker button {width: 100%;display: flex;@@ -2193,16 +2236,49 @@ svg.starred {gap: 12px;background: none;border: 0;- padding: 12px;+ padding: 10px 12px;border-radius: 6px;font-size: 12px;text-align: left;+ color: var(--secondary);}-.folder-picker button svg:last-child {- margin-left: auto;+.folder-picker button > span {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;}-.folder-picker button:hover {+.folder-picker button svg {+ color: var(--muted);+}+.folder-picker button.active {background: var(--hover);+ color: var(--text-strong);+}+.folder-picker button.active svg {+ color: var(--text-strong);+}+.folder-picker-note {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 14px 12px;+ font-size: 12px;+ color: var(--muted);+}+/* A text field directly inside a dialog, labelled above. */+.modal-field input {+ margin-top: 6px;+}+/* A secondary choice such as âRemove linkâ sits apart from Cancel and the main action. */+.modal-actions > .modal-action-start {+ margin-right: auto;+ margin-left: -10px;+ color: var(--muted);+}+.modal-actions > .modal-action-start:hover:not(:disabled) {+ color: var(--red);}.startup-error {max-width: 520px;@@ -2553,7 +2629,8 @@ fieldset.compose-format:disabled {.reply-prompt:hover {background: var(--hover);}-.reply-prompt > span {+/* Only the label grows; the shortcut hint is a span too and belongs at the far end. */+.reply-prompt > span:not(.shortcut-keys) {flex: 1;min-width: 0;}diff --git a/apps/desktop/src/renderer/src/view-actions.ts b/apps/desktop/src/renderer/src/view-actions.tsnew file mode 100644index 0000000..f399c8d--- /dev/null+++ b/apps/desktop/src/renderer/src/view-actions.ts@@ -0,0 +1,25 @@+import type { MailAction, View } from '@inlark/core'++/**+ * Whether an action belongs in the menus for conversations listed in this view. Archiving what's+ * already archived or restoring the inbox to itself only adds noise. All mail, folders and search+ * can hold anything, so they offer everything. Keyboard shortcuts stay available everywhere.+ */+export function offersAction(view: View, action: MailAction): boolean {+ switch (action) {+ case 'archive':+ return view !== 'archive'+ case 'trash':+ return view !== 'trash'+ case 'spam':+ return view !== 'junk'+ case 'notSpam':+ return view === 'junk' || view === 'all'+ case 'restore':+ return view !== 'inbox' && view !== 'junk'+ case 'destroy':+ return view === 'trash'+ default:+ return true+ }+}diff --git a/tests/link-target.test.ts b/tests/link-target.test.tsnew file mode 100644index 0000000..d09a362--- /dev/null+++ b/tests/link-target.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'+import { linkTarget } from '../apps/desktop/src/renderer/src/link-target'++describe('composer link addresses', () => {+ it('keeps full web and email links', () => {+ expect(linkTarget('https://example.com/a?b=1')).toBe('https://example.com/a?b=1')+ expect(linkTarget('http://localhost:3000')).toBe('http://localhost:3000')+ expect(linkTarget('mailto:[email protected]?subject=Hi')).toBe(+ 'mailto:[email protected]?subject=Hi',+ )+ })++ it('completes bare domains and email addresses', () => {+ expect(linkTarget(' example.com ')).toBe('https://example.com')+ expect(linkTarget('docs.example.com/guide#setup')).toBe('https://docs.example.com/guide#setup')+ expect(linkTarget('[email protected]')).toBe('mailto:[email protected]')+ })++ it('refuses text that cannot be a link', () => {+ for (const text of [+ '',+ 'not a link',+ 'example',+ 'javascript:alert(1)',+ 'mailto:nobody',+ 'https://',+ ])+ expect(linkTarget(text)).toBeUndefined()+ })+})diff --git a/tests/view-actions.test.ts b/tests/view-actions.test.tsnew file mode 100644index 0000000..8b28784--- /dev/null+++ b/tests/view-actions.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it, vi } from 'vitest'+import { offersAction } from '../apps/desktop/src/renderer/src/view-actions'++describe('actions offered per view', () => {+ it('leaves out actions that would change nothing where the conversation already is', () => {+ expect(offersAction('archive', 'archive')).toBe(false)+ expect(offersAction('trash', 'trash')).toBe(false)+ expect(offersAction('junk', 'spam')).toBe(false)+ expect(offersAction('inbox', 'restore')).toBe(false)+ expect(offersAction('inbox', 'notSpam')).toBe(false)+ })++ it('offers permanent deletion only in Trash', () => {+ expect(offersAction('trash', 'destroy')).toBe(true)+ expect(offersAction('inbox', 'destroy')).toBe(false)+ expect(offersAction('all', 'destroy')).toBe(false)+ })++ it('offers every moving action in All mail, folders and search', () => {+ for (const action of ['archive', 'trash', 'spam', 'notSpam', 'restore'] as const)+ expect(offersAction('all', action)).toBe(true)+ })+})++describe('action wording', async () => {+ vi.stubGlobal('location', { search: '', protocol: 'file:' })+ vi.stubGlobal('window', {})+ const { confirmActionCopy } = await import('../apps/desktop/src/renderer/src/AppDialogs')+ const { emptyListState } = await import('../apps/desktop/src/renderer/src/empty-states')+ const { matchFolders } = await import('../apps/desktop/src/renderer/src/MoveDialog')+ vi.unstubAllGlobals()++ it('names the action and how many conversations it reaches', () => {+ expect(confirmActionCopy('archive', 1234)).toMatchObject({+ title: 'Archive all ' + (1234).toLocaleString() + ' conversations?',+ confirm: 'Archive',+ })+ expect(confirmActionCopy('read', 2).title).toBe('Mark all 2 conversations as read?')+ expect(confirmActionCopy('destroy', 1)).toMatchObject({+ title: 'Delete this conversation permanently?',+ confirm: 'Delete permanently',+ })+ })++ it('quotes the shortcut the user actually has, or none when it was removed', () => {+ expect(+ emptyListState('starred', { searching: false, unreadOnly: false, keys: () => 'L' })+ .description,+ ).toBe('Press L to star the selected conversation.')+ expect(+ emptyListState('starred', { searching: false, unreadOnly: false, keys: () => undefined })+ .description,+ ).not.toMatch(/Press/)+ })++ it('finds folders by any part of their name, word starts first', () => {+ const folders = [{ name: 'Archive' }, { name: 'Receipts' }, { name: 'Projects' }]+ expect(matchFolders(folders, 'r').map((f) => f.name)).toEqual([+ 'Receipts',+ 'Archive',+ 'Projects',+ ])+ expect(matchFolders(folders, 'PRO').map((f) => f.name)).toEqual(['Projects'])+ expect(matchFolders(folders, ' ')).toBe(folders)+ expect(matchFolders(folders, 'zzz')).toEqual([])+ })+})