From 12730e4f7e48dbb0534c28a31f57a38aae4d94ea Mon Sep 17 00:00:00 2001 From: Tero Date: Sun, 4 Oct 2026 23:42:17 +0300 Subject: [PATCH] Add multi account support and fixed functionality of buttons calendar etc --- README.md | 4 +- account-ui.js | 22 ++ app.js | 4 +- desktop/main.cjs | 383 ++++++++++++++++++++++++++++++- desktop/preload.cjs | 15 ++ index.html | 27 ++- mail-ui.js | 156 +++++++++++++ package-lock.json | 546 ++++++++++++++++++++++++++++++++++++++++++++ package.json | 9 + productivity.js | 28 +++ service-worker.js | 4 +- styles.css | 2 + 12 files changed, 1181 insertions(+), 19 deletions(-) create mode 100644 account-ui.js create mode 100644 desktop/preload.cjs create mode 100644 mail-ui.js create mode 100644 productivity.js diff --git a/README.md b/README.md index 0998f36..a4cd344 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A desktop-style mail client concept with the **Eternity Daylight** and **Wastela ## Desktop app -The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. +The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. @@ -20,4 +20,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati ## Current scope -This build is a local UI prototype with sample messages and in-memory interactions. It does not connect to IMAP/SMTP, sync a real address book or calendar, or persist edits to a server. Those integrations need an account setup flow and a secure mail/calendar backend. Avoid entering real credentials into this prototype. +Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Account credentials are kept in the OS-encrypted credential store. Contacts and calendar entries can be added, edited, and removed; they are saved locally on this device and do not sync to an address book or calendar server. Your display name is also saved locally and appears in the greeting. diff --git a/account-ui.js b/account-ui.js new file mode 100644 index 0000000..fe24b16 --- /dev/null +++ b/account-ui.js @@ -0,0 +1,22 @@ +async function openAccountManager(){ + const root=$('#modal-root'); + try{ + const data=await window.daybreakMail.listAccounts(); + const accounts=data.accounts||[]; + const rows=accounts.map(account=>`
`).join(''); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close); + root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()}; + root.onclick=async event=>{ + const switchButton=event.target.closest('[data-switch-account]'); + if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return} + const removeButton=event.target.closest('[data-remove-account]'); + if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return} + }; + }catch(error){toast(error.message||'Could not load mail accounts')} +} + +document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); +document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); diff --git a/app.js b/app.js index f64906e..b5a767d 100644 --- a/app.js +++ b/app.js @@ -13,8 +13,8 @@ const contacts=[['Amelia Laurent','amelia@northstar.design','Design partner','AL let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))} -function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent')return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=''} -function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

${m.attachment?`
${m.attachment.endsWith('.pdf')?'▤':'▧'}
${esc(m.attachment)}${m.size} · Preview ready
`:''}
`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)} +function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=''} +function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}
`).join('')}
`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)} function emptyReader(){return `
✉

Your inbox, at your pace

Select a message to read it here.

`} function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)} function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:'MS',color:'#dce9dd',sender:'Mira Sol',email:'mira@daybreak.studio',subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()} diff --git a/desktop/main.cjs b/desktop/main.cjs index 492a347..d42076b 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -1,5 +1,381 @@ -const { app, BrowserWindow, shell } = require('electron'); +const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog } = require('electron'); const path = require('node:path'); +const fs = require('node:fs/promises'); +const { ImapFlow } = require('imapflow'); +const nodemailer = require('nodemailer'); +const { simpleParser } = require('mailparser'); +const { randomUUID } = require('node:crypto'); + +const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); + +function normalizeAccount(input) { + const email = String(input?.email || '').trim(); + const password = String(input?.password || ''); + const imapHost = String(input?.imapHost || '').trim(); + const smtpHost = String(input?.smtpHost || '').trim(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) { + throw new Error('Enter a valid email, password, and both mail server names.'); + } + return { email, password, imapHost, smtpHost, imapPort: 143, smtpPort: 587 }; +} + +function imapClient(account) { + return new ImapFlow({ + host: account.imapHost, + port: account.imapPort, + secure: false, + doSTARTTLS: true, + auth: { user: account.email, pass: account.password }, + tls: { rejectUnauthorized: true }, + logger: false, + connectionTimeout: 15000, + greetingTimeout: 10000, + socketTimeout: 20000 + }); +} + +function smtpTransport(account) { + return nodemailer.createTransport({ + host: account.smtpHost, + port: account.smtpPort, + secure: false, + requireTLS: true, + auth: { user: account.email, pass: account.password }, + tls: { rejectUnauthorized: true, servername: account.smtpHost }, + connectionTimeout: 15000, + greetingTimeout: 10000, + socketTimeout: 20000 + }); +} + +async function readAccountStore() { + try { + if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.'); + const encrypted = await fs.readFile(credentialsPath()); + const { result } = await safeStorage.decryptStringAsync(encrypted); + const stored = JSON.parse(result); + if (Array.isArray(stored.accounts)) return stored; + if (stored.email) { + const account = { ...stored, id: stored.id || randomUUID() }; + const migrated = { accounts: [account], activeId: account.id }; + await saveAccountStore(migrated); + return migrated; + } + return { accounts: [], activeId: null }; + } catch (error) { + if (error.code === 'ENOENT') return null; + throw error; + } +} + +async function saveAccountStore(store) { + if (!await safeStorage.isAsyncEncryptionAvailable()) { + throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.'); + } + const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store)); + const file = credentialsPath(); + await fs.mkdir(path.dirname(file), { recursive: true }); + await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 }); + await fs.rename(`${file}.tmp`, file); +} + +async function readAccount(accountId = null) { + const store = await readAccountStore(); + if (!store?.accounts.length) return null; + return store.accounts.find(account => account.id === (accountId || store.activeId)) || null; +} + +function publicAccount(account) { + return { id: account.id, email: account.email, imapHost: account.imapHost, smtpHost: account.smtpHost }; +} + +async function saveAccount(account) { + const store = (await readAccountStore()) || { accounts: [], activeId: null }; + const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase()); + const saved = { ...account, id: existing?.id || randomUUID() }; + store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved]; + store.activeId = saved.id; + await saveAccountStore(store); + return saved; +} + +async function connectMail(account) { + const client = imapClient(account); + let transport; + try { + await client.connect(); + const mailbox = await client.mailboxOpen('INBOX', { readOnly: true }); + transport = smtpTransport(account); + await transport.verify(); + return { mailbox: mailbox.name, messages: mailbox.exists }; + } finally { + if (transport) transport.close(); + if (client.usable) await client.logout().catch(() => {}); + } +} + +async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) { + const mailboxes = await client.list(); + const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) || + mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop())); + if (match) return match.path; + if (!createName) return null; + return (await client.mailboxCreate(createName)).path; +} + +async function findSentMailbox(client, createIfMissing = false) { + return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null); +} + +async function folderPath(client, folder, createIfMissing = false) { + if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX'; + const definitions = { + Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'], + Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'], + Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash'] + }; + const definition = definitions[folder]; + if (!definition) throw new Error('This folder is not available on the mail server.'); + return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null); +} + +async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { + const client = imapClient(account); + try { + await client.connect(); + const mailboxPath = await folderPath(client, folder); + if (!mailboxPath) return { messages: [], total: 0 }; + const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true }); + const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0)); + if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder }; + const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1); + const fetched = await client.fetchAll(`${first}:${end}`, { + uid: true, + envelope: true, + flags: true, + internalDate: true, + source: true + }); + const messages = []; + for (const item of fetched.reverse()) { + if (!item.source) continue; + const parsed = await simpleParser(item.source); + const sender = parsed.from?.value?.[0]; + const bodyText = String(parsed.text || '').replace(/\r/g, '').trim(); + const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.']; + const date = parsed.date || item.internalDate || new Date(); + messages.push({ + id: Number(item.uid), + initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(), + color: '#dce6df', + sender: sender?.name || sender?.address || 'Unknown sender', + email: sender?.address || '', + subject: parsed.subject || '(no subject)', + snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), + time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date), + date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date), + unread: !item.flags?.has('\\Seen'), + star: item.flags?.has('\\Flagged') || false, + tags: [folder], + sent: folder === 'Sent', + archived: folder === 'Archive', + deleted: folder === 'Trash', + body, + uid: Number(item.uid), + attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), + attachment: parsed.attachments?.[0]?.filename || null, + size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : '' + }); + } + return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder }; + } finally { + if (client.usable) await client.logout().catch(() => {}); + } +} + +ipcMain.handle('mail:get-account', async () => { + const account = await readAccount(); + return account ? publicAccount(account) : null; +}); + +ipcMain.handle('mail:list-accounts', async () => { + const store = (await readAccountStore()) || { accounts: [], activeId: null }; + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +}); + +ipcMain.handle('mail:select-account', async (_event, accountId) => { + const store = await readAccountStore(); + const account = store?.accounts.find(item => item.id === accountId); + if (!account) throw new Error('That mail account is no longer available.'); + store.activeId = account.id; + await saveAccountStore(store); + return publicAccount(account); +}); + +ipcMain.handle('mail:remove-account', async (_event, accountId) => { + const store = await readAccountStore(); + if (!store) return { accounts: [], activeId: null }; + store.accounts = store.accounts.filter(account => account.id !== accountId); + if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; + if (store.accounts.length) await saveAccountStore(store); + else await fs.rm(credentialsPath(), { force: true }); + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +}); + +ipcMain.handle('mail:connect', async (_event, input) => { + const account = normalizeAccount(input); + try { + const status = await connectMail(account); + const saved = await saveAccount(account); + return { ok: true, ...publicAccount(saved), ...status }; + } catch (error) { + throw new Error(`Could not connect to the mailbox: ${error.message}`); + } +}); + +ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before syncing.'); + const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']); + const folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox'; + return fetchMailbox(account, folder, offset); +}); + +ipcMain.handle('mail:update-message', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before changing messages.'); + const uid = Number(input?.uid); + const folder = String(input?.folder || 'Inbox'); + const action = String(input?.action || ''); + if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); + if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.'); + const client = imapClient(account); + try { + await client.connect(); + const sourcePath = await folderPath(client, folder); + if (!sourcePath) throw new Error('That mail folder could not be found.'); + const lock = await client.getMailboxLock(sourcePath); + try { + if (action === 'star') { + if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true }); + else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true }); + } else if (action === 'unread') { + if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true }); + else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true }); + } else { + const target = action === 'archive' + ? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive') + : await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash'); + if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true }); + else await client.messageMove(uid, target, { uid: true }); + } + } finally { + lock.release(); + } + return { ok: true }; + } finally { + if (client.usable) await client.logout().catch(() => {}); + } +}); + +ipcMain.handle('mail:save-attachment', async (event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before downloading attachments.'); + const uid = Number(input?.uid); + const folder = String(input?.folder || 'Inbox'); + const filename = String(input?.filename || 'attachment'); + const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_'); + if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); + const client = imapClient(account); + try { + await client.connect(); + const mailboxPath = await folderPath(client, folder); + if (!mailboxPath) throw new Error('That mail folder could not be found.'); + const lock = await client.getMailboxLock(mailboxPath); + try { + const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true }); + if (!item?.source) throw new Error('The message is no longer available.'); + const parsed = await simpleParser(item.source); + const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0]; + if (!attachment) throw new Error('No attachment was found in this message.'); + const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') }); + if (result.canceled || !result.filePath) return { canceled: true }; + await fs.writeFile(result.filePath, attachment.content); + return { saved: true }; + } finally { + lock.release(); + } + } finally { + if (client.usable) await client.logout().catch(() => {}); + } +}); + +ipcMain.handle('mail:sync-inbox', async () => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before syncing.'); + return fetchMailbox(account, 'Inbox'); +}); + +ipcMain.handle('mail:send', async (_event, message) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before sending.'); + const to = String(message?.to || '').trim(); + if (!to) throw new Error('Add at least one recipient.'); + const transport = smtpTransport(account); + const sentMessageId = `<${require('node:crypto').randomUUID()}@daybreak-mail.local>`; + const messageOptions = { + from: { name: account.email, address: account.email }, + to, + cc: String(message.cc || '').trim() || undefined, + subject: String(message.subject || '(no subject)').slice(0, 998), + text: String(message.text || '').slice(0, 500000), + messageId: sentMessageId + }; + try { + await transport.sendMail(messageOptions); + } finally { + transport.close(); + } + let savedToSent = false; + const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' }); + try { + const rendered = await copy.sendMail(messageOptions); + const client = imapClient(account); + try { + await client.connect(); + const sentPath = await findSentMailbox(client, true); + const lock = await client.getMailboxLock(sentPath); + try { + const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true }); + if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date()); + savedToSent = true; + } finally { + lock.release(); + } + } finally { + if (client.usable) await client.logout().catch(() => {}); + } + } catch { + // SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends. + } + return { ok: true, savedToSent }; +}); + +ipcMain.handle('mail:disconnect', async (_event, accountId) => { + const store = await readAccountStore(); + if (!store) return { accounts: [], activeId: null }; + if (accountId) { + store.accounts = store.accounts.filter(account => account.id !== accountId); + } else { + store.accounts = []; + } + if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true }); + else { + if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id; + await saveAccountStore(store); + } + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +}); function createWindow() { const window = new BrowserWindow({ @@ -12,6 +388,7 @@ function createWindow() { autoHideMenuBar: true, icon: path.join(__dirname, '..', 'icon.svg'), webPreferences: { + preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true @@ -23,7 +400,9 @@ function createWindow() { if (url.startsWith('https://') || url.startsWith('mailto:')) shell.openExternal(url); return { action: 'deny' }; }); - window.webContents.on('will-navigate', event => event.preventDefault()); + window.webContents.on('will-navigate', (event, url) => { + if (!url.startsWith('file:')) event.preventDefault(); + }); } app.whenReady().then(() => { diff --git a/desktop/preload.cjs b/desktop/preload.cjs new file mode 100644 index 0000000..d4592e3 --- /dev/null +++ b/desktop/preload.cjs @@ -0,0 +1,15 @@ +const { contextBridge, ipcRenderer } = require('electron'); + +contextBridge.exposeInMainWorld('daybreakMail', { + getAccount: () => ipcRenderer.invoke('mail:get-account'), + listAccounts: () => ipcRenderer.invoke('mail:list-accounts'), + selectAccount: id => ipcRenderer.invoke('mail:select-account', id), + removeAccount: id => ipcRenderer.invoke('mail:remove-account', id), + connect: details => ipcRenderer.invoke('mail:connect', details), + syncFolder: (folder, offset) => ipcRenderer.invoke('mail:sync-folder', folder, offset), + syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'), + updateMessage: details => ipcRenderer.invoke('mail:update-message', details), + saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details), + send: message => ipcRenderer.invoke('mail:send', message), + disconnect: id => ipcRenderer.invoke('mail:disconnect', id) +}); diff --git a/index.html b/index.html index 3e7f52b..70c6da4 100644 --- a/index.html +++ b/index.html @@ -5,6 +5,7 @@ + Daybreak Mail @@ -18,12 +19,12 @@
- +
-
⌕⌘ K
+
⌕⌘ K
-

Good morning, Mira ☀

-
1–8 of 24
+

Good morning, Mira ☀

+
1–8 of 24
-
All caught up with your mail
+
All caught up with your mail
@@ -61,5 +63,8 @@
+ + + diff --git a/mail-ui.js b/mail-ui.js new file mode 100644 index 0000000..2cb6fb3 --- /dev/null +++ b/mail-ui.js @@ -0,0 +1,156 @@ +let connectedMailAccount = null; +let mailPageOffset = 0; +let mailTotal = 0; + +function updateAccountCard(account) { + const card = $('#account-settings'); + if (!card) return; + const [name, domain] = account.email.split('@'); + card.querySelector('.account-avatar').textContent = (name[0] || 'M').toUpperCase(); + card.querySelector('.account-info strong').textContent = account.email; + card.querySelector('.account-info span').textContent = account.imapHost; + card.title = 'Mail account settings'; + card.querySelector('.online-dot').style.background = '#70ad7b'; +} + +function openMailAccount() { + const root = $('#modal-root'); + const current = {}; + root.innerHTML = ``; + const close = () => { root.innerHTML = ''; }; + $$('.modal-close').forEach(button => button.onclick = close); + $('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); + $('#disconnect-mail').onclick = async () => { + close(); + }; + $('#connect-mail').onclick = async () => { + const button = $('#connect-mail'); + const status = $('#mail-account-status'); + const password = $('#mail-account-password').value; + if (!password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; } + button.disabled = true; + button.textContent = 'Checking secure connections…'; + status.textContent = 'Checking IMAP and SMTP sign-in. This may take a moment.'; + try { + const account = await window.daybreakMail.connect({ + email: $('#mail-account-email').value, + password, + imapHost: $('#mail-account-imap').value, + smtpHost: $('#mail-account-smtp').value + }); + connectedMailAccount = account; + updateAccountCard(account); + close(); + toast('Mailbox connected securely'); + await syncMailbox(true); + } catch (error) { + status.textContent = error.message || 'Could not connect. Check the account details and try again.'; + button.disabled = false; + button.textContent = 'Test & connect'; + } + }; + $('#mail-account-email').focus(); +} + +async function syncMailbox(showToast, options = {}) { + if (!connectedMailAccount || !window.daybreakMail) { + openMailAccount(); + return; + } + const refresh = $('#refresh'); + if (refresh) refresh.disabled = true; + try { + const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); + const result = await window.daybreakMail.syncFolder(activeFolder, offset); + if (options.append) messages.push(...result.messages); + else messages.splice(0, messages.length, ...result.messages); + messages.forEach(message => { + try { + const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); + message.tags = [...new Set([...(message.tags || []), ...localTags])]; + } catch {} + }); + if (!options.append) mailPageOffset = offset; + mailTotal = result.total; + activeMessage = messages[0]?.id; + selectedIds.clear(); + const unread = messages.filter(message => message.unread).length; + const inboxCount = $('.folder[data-folder="Inbox"] .count'); + if (inboxCount) inboxCount.textContent = String(unread); + const pagination = $('#pagination'); + if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; + const loadMore = $('#load-more'); + if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); + renderList(); + if (activeMessage) { + openMessage(activeMessage); + const current = messages.find(message => message.id === activeMessage); + if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {}); + } + else $('#reader-pane').innerHTML = emptyReader(); + updateAccountCard(connectedMailAccount); + if (showToast) toast(`Synced ${messages.length} messages`); + } catch (error) { + toast(error.message || 'Could not sync the inbox'); + } finally { + if (refresh) refresh.disabled = false; + } +} + +if (window.daybreakMail) { + $('#account-settings').addEventListener('click', openMailAccount); + $('#account-settings').addEventListener('keydown', event => { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); } + }); + $('#settings-button').onclick = () => openPreferences(); + $('#refresh').onclick = () => syncMailbox(true); + $$('.folder').forEach(button => button.addEventListener('click', () => { + if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) { + mailPageOffset = 0; + syncMailbox(false, { offset: 0 }); + } + })); + $('#previous-page').onclick = () => { + if (mailPageOffset <= 0) return; + mailPageOffset = Math.max(0, mailPageOffset - 20); + syncMailbox(false, { offset: mailPageOffset }); + }; + $('#next-page').onclick = () => { + if (mailPageOffset + 20 >= mailTotal) return; + mailPageOffset += 20; + syncMailbox(false, { offset: mailPageOffset }); + }; + $('#load-more').onclick = () => syncMailbox(false, { append: true }); + document.addEventListener('click', async event => { + const sendButton = event.target.closest('#send'); + if (!sendButton || !connectedMailAccount) return; + event.preventDefault(); + event.stopImmediatePropagation(); + const recipient = $('#compose-to').value.trim(); + if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; } + sendButton.disabled = true; + sendButton.textContent = 'Sending…'; + try { + const result = await window.daybreakMail.send({ + to: recipient, + cc: $('#compose-cc').value, + subject: $('#compose-subject').value.trim(), + text: $('#compose-body').value + }); + $('#modal-root').innerHTML = ''; + toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); + if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); + } catch (error) { + sendButton.disabled = false; + sendButton.textContent = 'Send ↗'; + toast(error.message || 'Message could not be sent'); + } + }, true); + + window.daybreakMail.getAccount().then(account => { + if (!account) return; + connectedMailAccount = account; + updateAccountCard(account); + syncMailbox(false); + }).catch(() => {}); +} diff --git a/package-lock.json b/package-lock.json index c51c9e7..497d9cb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,11 @@ "": { "name": "daybreak-mail", "version": "0.1.0", + "dependencies": { + "imapflow": "2.2.1", + "mailparser": "3.9.33", + "nodemailer": "10.0.9" + }, "devDependencies": { "electron": "44.5.1", "electron-builder": "26.17.0" @@ -452,6 +457,28 @@ "node": ">=14.18.0" } }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, + "node_modules/@selderee/plugin-htmlparser2": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.12.0.tgz", + "integrity": "sha512-oELmoyA6ML9jDRMV3kgcMQFKxUfBU0yFVn6yTctVaLT5ygXnxH52I3TZEgV9EhXJC68/uFvE5Daj1/25c0Xa/A==", + "license": "MIT", + "dependencies": { + "domelementtype": "~2.3.0", + "domhandler": "~5.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + }, + "peerDependencies": { + "selderee": "~0.12.0" + } + }, "node_modules/@sindresorhus/is": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", @@ -565,6 +592,17 @@ "node": ">=10.0.0" } }, + "node_modules/@zone-eu/mailsplit": { + "version": "5.4.19", + "resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.19.tgz", + "integrity": "sha512-nDWzw+X3tqfwd7DpDThAjg3KqtrNA6bG2gkrf6m2j1JBaGyyKAZzu1TguzB4GEco+HYpXAbXZ7kbl4Sn8H1vXw==", + "license": "(MIT OR EUPL-1.1+)", + "dependencies": { + "libbase64": "1.3.1", + "libmime": "5.4.6", + "libqp": "2.1.2" + } + }, "node_modules/abbrev": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", @@ -847,6 +885,15 @@ "node": ">= 4.0.0" } }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/aws4": { "version": "1.13.2", "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", @@ -1253,6 +1300,25 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/deepmerge-ts": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-8.0.2.tgz", + "integrity": "sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==", + "funding": [ + { + "type": "ko-fi", + "url": "https://ko-fi.com/rebeccastevens" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/deepmerge-ts" + } + ], + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/defer-to-connect": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", @@ -1374,6 +1440,61 @@ "js-yaml": "^4.1.0" } }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, "node_modules/dotenv": { "version": "16.6.1", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", @@ -1587,6 +1708,15 @@ "dev": true, "license": "MIT" }, + "node_modules/encoding-japanese": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/encoding-japanese/-/encoding-japanese-2.4.0.tgz", + "integrity": "sha512-PE0KjlsDy9JSsoU4C2Q8NXb1kC4c+bZRac9ZvHXUE4q1Ht63gScKMdEy9jst9+Fi3M4eDkqzkEhBZvix4blP2A==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/end-of-stream": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", @@ -1597,6 +1727,18 @@ "once": "^1.4.0" } }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/env-paths": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", @@ -2103,6 +2245,15 @@ "node": ">= 0.4" } }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, "node_modules/hosted-git-info": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", @@ -2116,6 +2267,56 @@ "node": ">=10" } }, + "node_modules/html-to-text": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-10.0.1.tgz", + "integrity": "sha512-GiVhRI1BatGARSCmlXWNCjDT0cWrwBWoeduLoV0WSKAgaV/wa+hUWy5LiQLUs4UwiUrE52ZCMfBGiKD87TDPrg==", + "license": "MIT", + "dependencies": { + "@selderee/plugin-htmlparser2": "~0.12.0", + "deepmerge-ts": "^8.0.1", + "dom-serializer": "^2.0.0", + "htmlparser2": "^10.1.0", + "selderee": "~0.12.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + } + }, + "node_modules/htmlparser2": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", + "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "entities": "^7.0.1" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/http-cache-semantics": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz", @@ -2165,6 +2366,41 @@ "node": ">= 14" } }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/imapflow": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/imapflow/-/imapflow-2.2.1.tgz", + "integrity": "sha512-d7/sRGEtexA8e0Y71sN0rKfB2yWgZMHY8JqCbk17arRLGicjX1LpBuxPH+wowOIA5sVWs7U//B6S+mKfrBtT6w==", + "license": "MIT", + "dependencies": { + "@zone-eu/mailsplit": "5.4.19", + "encoding-japanese": "2.4.0", + "iconv-lite": "0.7.3", + "libbase64": "1.3.1", + "libmime": "5.4.6", + "libqp": "2.1.2", + "pino": "10.3.1", + "socks": "2.8.10" + }, + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -2184,6 +2420,15 @@ "dev": true, "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", + "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -2340,6 +2585,58 @@ "dev": true, "license": "MIT" }, + "node_modules/leac": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/leac/-/leac-0.7.0.tgz", + "integrity": "sha512-qMrZeyEekgdRQ9o6a4NAB2EQZrv827GJdn1vnapwSJ90hWRB4TzUSunvacPkxQ2TnNqHNI1/zSt0hlo0crG8Jw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + } + }, + "node_modules/libbase64": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.1.tgz", + "integrity": "sha512-1b9LXEjEtXj35YKOR9RqNKBootlb37qbIzmqiw4MsP52cjOsfR6i/AYU1Y8qN4kV2TJQmLJ5aiXn45qI6h+Szw==", + "license": "MIT" + }, + "node_modules/libmime": { + "version": "5.4.6", + "resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.6.tgz", + "integrity": "sha512-Cgx1vHd76GTwDaLNsl0K44CjNFfhkX/1bMcoruoWr8Ugcl0/zMw7x/8NpZERIOcpGyzlQo10tOEw9goGsv2Wlg==", + "license": "MIT", + "dependencies": { + "encoding-japanese": "2.4.0", + "iconv-lite": "0.7.3", + "libbase64": "1.3.1", + "libqp": "2.1.2" + } + }, + "node_modules/libqp": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.2.tgz", + "integrity": "sha512-rp+U80tl9Os4K7GnVbPzPRmghPu6eqB8rcF+ontvNAnoga0JhMFG/bkTD/reC8yoznKMgOc5/ttZHJasiWeFPw==", + "license": "MIT" + }, + "node_modules/linkify-it": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz", + "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, "node_modules/lodash": { "version": "4.18.1", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", @@ -2370,6 +2667,36 @@ "node": ">=10" } }, + "node_modules/mailparser": { + "version": "3.9.33", + "resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.9.33.tgz", + "integrity": "sha512-+ZYhApN4f7B8+jokb7VZeml8lxYHixVJ3tJTB5iPG9/MJpy8YmBHGdy+AWJ9dmtUX6t0xlu4rxwj1b7eWCvbDA==", + "license": "MIT", + "dependencies": { + "@zone-eu/mailsplit": "5.4.19", + "encoding-japanese": "2.4.0", + "he": "1.2.0", + "html-to-text": "10.0.1", + "iconv-lite": "0.7.3", + "libmime": "5.4.6", + "linkify-it": "5.0.2", + "nodemailer": "10.0.13", + "punycode.js": "2.3.1", + "tlds": "1.261.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/mailparser/node_modules/nodemailer": { + "version": "10.0.13", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.13.tgz", + "integrity": "sha512-SzG86OlvcW/NNhUFC6uROMwRTL4n7MswfQqC/T8mhkmnY1YVa23zUEMYi4ijSeXSl9GLz9ZeTJDUatEDuY5FeQ==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/matcher": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", @@ -2611,6 +2938,15 @@ "dev": true, "license": "MIT" }, + "node_modules/nodemailer": { + "version": "10.0.9", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.9.tgz", + "integrity": "sha512-BF0qcyplCwp+jMk6HCjFykBz/YhhZSsxrARhOldLwFWH+8kGjQsd2WIMIZhqEuyXRoGFi0ONbDeWDMDoL8MhLw==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/nopt": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", @@ -2651,6 +2987,15 @@ "node": ">= 0.4" } }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -2687,6 +3032,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parseley": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.13.1.tgz", + "integrity": "sha512-uNBJZzmb60l6p6VWLTmevizNAGnE0xoSf1n0B4q3ntegDNzcS68NRCcBDZTcyXHxt2XhBChsCuqj4M+nChvE/A==", + "license": "MIT", + "dependencies": { + "leac": "^0.7.0", + "peberminta": "^0.10.0" + }, + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + } + }, "node_modules/path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", @@ -2722,6 +3080,15 @@ "url": "https://github.com/sponsors/jet2jet" } }, + "node_modules/peberminta": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.10.0.tgz", + "integrity": "sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -2742,6 +3109,43 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pino": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", + "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, "node_modules/pkijs": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.1.tgz", @@ -2825,6 +3229,22 @@ "dev": true, "license": "MIT" }, + "node_modules/process-warning": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.0.tgz", + "integrity": "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, "node_modules/progress": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", @@ -2872,6 +3292,15 @@ "once": "^1.3.1" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/pvtsutils": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", @@ -2892,6 +3321,12 @@ "node": ">=16.0.0" } }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, "node_modules/quick-lru": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", @@ -2934,6 +3369,15 @@ "util-deprecate": "~1.0.1" } }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -3043,6 +3487,21 @@ "dev": true, "license": "MIT" }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/sanitize-filename": { "version": "1.6.4", "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.4.tgz", @@ -3063,6 +3522,18 @@ "node": ">=11.0.0" } }, + "node_modules/selderee": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/selderee/-/selderee-0.12.0.tgz", + "integrity": "sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==", + "license": "MIT", + "dependencies": { + "parseley": "~0.13.1" + }, + "funding": { + "url": "https://github.com/sponsors/KillyMXI" + } + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -3144,6 +3615,39 @@ "node": ">=10" } }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.10", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", + "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -3165,6 +3669,15 @@ "source-map": "^0.6.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/sprintf-js": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", @@ -3300,6 +3813,24 @@ "fs-extra": "^10.0.0" } }, + "node_modules/thread-stream": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", + "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==", + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/thread-stream/node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "license": "MIT" + }, "node_modules/tiny-async-pool": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", @@ -3337,6 +3868,15 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tlds": { + "version": "1.261.0", + "resolved": "https://registry.npmjs.org/tlds/-/tlds-1.261.0.tgz", + "integrity": "sha512-QXqwfEl9ddlGBaRFXIvNKK6OhipSiLXuRuLJX5DErz0o0Q0rYxulWLdFryTkV5PkdZct5iMInwYEGe/eR++1AA==", + "license": "MIT", + "bin": { + "tlds": "bin.js" + } + }, "node_modules/tmp": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", @@ -3388,6 +3928,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "license": "MIT" + }, "node_modules/undici": { "version": "7.30.0", "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", diff --git a/package.json b/package.json index 308ba6a..e98a4d3 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "start": "electron .", "dev": "electron .", "dist:win": "electron-builder --win", + "dist:win:installer": "electron-builder --win nsis", "dist:win:portable": "electron-builder --win portable", "dist:linux": "electron-builder --linux AppImage deb", "dist:linux:appimage": "electron-builder --linux AppImage", @@ -27,6 +28,9 @@ "index.html", "styles.css", "app.js", + "mail-ui.js", + "productivity.js", + "account-ui.js", "icon.svg", "manifest.webmanifest", "service-worker.js", @@ -60,5 +64,10 @@ "allowScripts": { "electron@44.5.1": true, "electron-winstaller@5.4.0": true + }, + "dependencies": { + "imapflow": "2.2.1", + "mailparser": "3.9.33", + "nodemailer": "10.0.9" } } diff --git a/productivity.js b/productivity.js new file mode 100644 index 0000000..499bfe1 --- /dev/null +++ b/productivity.js @@ -0,0 +1,28 @@ +// Persistent profile, calendar and contact tools, plus actions for the mail UI. +const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' }; +const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } }; +const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value)); +let profileSettings = productRead(productKeys.profile, { name: 'Mira Sol' }); +let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1); +const contactSeed = contacts.map(c => ({ name:c[0], email:c[1], note:c[2], initials:c[3], color:c[4] })); +let savedContacts = productRead(productKeys.contacts, contactSeed); +let savedEvents = productRead(productKeys.events, []); +let customLabels = productRead(productKeys.labels, []); +let snoozedIds = productRead(productKeys.snoozed, []); +function setProfileName(name) { profileSettings.name = name; productWrite(productKeys.profile, profileSettings); const first = name.trim().split(/\s+/)[0] || 'there'; $('#greeting-name').textContent = first; $$('.profile-button').forEach(b => b.textContent = name.trim().split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase()); const c=$('.account-info strong'); if (!connectedMailAccount && c) c.textContent=name; } +function openPreferences() { const root=$('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-profile').onclick=()=>{const n=$('#profile-name').value.trim(); if(!n){toast('Enter your name');return} setProfileName(n); close(); toast('Preferences saved')}; $('#profile-name').focus(); } +function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=()=>{savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); } +function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${esc(e.time?`${e.time} `:'')}${esc(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} +function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=()=>{savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} +function renderContacts(){const cards=savedContacts.map((c,i)=>`
${esc(c.initials)}
${esc(c.name)}${esc(c.email)}${esc(c.note)}
`).join('');$('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} +function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} +function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} +function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()} +async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} +document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openPreferences);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); +function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} +const baseMessageRenderer=renderList; +renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?snoozedIds.includes(m.id):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='
⌕

No messages here

Try another folder or label.

';return}baseMessageRenderer()}; +document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true); + + diff --git a/service-worker.js b/service-worker.js index b900927..76dce5a 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,5 +1,5 @@ -const CACHE='daybreak-mail-v1'; -const FILES=['./','./index.html','./styles.css','./app.js','./manifest.webmanifest','./icon.svg']; +const CACHE='daybreak-mail-v3'; +const FILES=['./','./index.html','./styles.css','./app.js','./mail-ui.js','./productivity.js','./account-ui.js','./manifest.webmanifest','./icon.svg']; self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); diff --git a/styles.css b/styles.css index 7485e52..3150c03 100644 --- a/styles.css +++ b/styles.css @@ -9,3 +9,5 @@ body.wasteland{--bg:#eee8db;--panel:#faf6ed;--line:#e6dccb;--text:#373129;--mute @media(max-width:1040px){.sidebar{width:205px;padding-inline:13px}.mail-layout{grid-template-columns:minmax(310px,47%) minmax(320px,1fr);padding:13px;gap:10px}.reader-pane{padding:0 17px 20px}.topbar{padding:0 16px}.message{gap:7px;padding-inline:9px}.list-heading{padding-inline:14px}} @media(max-width:800px){.sidebar{width:174px;padding-inline:10px}.mail-layout{grid-template-columns:minmax(290px,1fr) minmax(290px,1fr);padding:9px;gap:8px}.reader-pane{padding-inline:13px}.list-heading h2{font-size:17px}.search-wrap{width:170px}} .page-heading{display:flex;align-items:center;justify-content:space-between;margin:5px 0 20px}.page-heading h2{font-family:'DM Serif Display',Georgia,serif;font-size:28px;font-weight:400;margin:0 0 5px}.page-subtitle{font-size:11px;color:#929991;margin:0}.cal-actions{display:flex;align-items:center;gap:7px}.outline-button{border:1px solid #e3e8e2;background:#fff;border-radius:6px;padding:7px 10px;color:#69736a;font-size:10px}.calendar-card{background:var(--panel);border:1px solid var(--line);border-radius:11px;overflow:hidden;box-shadow:var(--shadow)}.calendar-week{height:38px;display:grid;grid-template-columns:repeat(7,1fr);border-bottom:1px solid var(--line);align-items:center;text-align:center;color:#969d95;font-size:9px;font-weight:600}.calendar-grid{display:grid;grid-template-columns:repeat(7,1fr)}.cal-cell{height:100px;border-right:1px solid #f0f1ee;border-bottom:1px solid #f0f1ee;padding:8px 7px;cursor:pointer;min-width:0}.cal-cell:nth-child(7n){border-right:0}.cal-cell:hover{background:#fafbf9}.cal-cell.outside{background:#fafbf9;color:#d3d7d1}.cal-number{display:grid;place-items:center;width:21px;height:21px;border-radius:50%;font-size:9px;color:#737c73;margin-bottom:4px}.cal-cell.today .cal-number{background:#5b8068;color:#fff}.event-chip{padding:4px 5px;margin:3px 0;border-radius:4px;font-size:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:#edf4ee;color:#5b8068}.event-chip.gold{background:#f7f1e4;color:#a28449}.event-chip.blue{background:#edf2f7;color:#6885a5}.upcoming{margin:20px 0 0}.upcoming h3{font-family:'DM Serif Display',Georgia,serif;font-size:17px;font-weight:400;margin:0 0 8px}.upcoming-row{display:flex;gap:12px;align-items:center;padding:10px 12px;border:1px solid var(--line);background:var(--panel);border-radius:8px;margin:6px 0;max-width:380px}.event-date{width:36px;height:38px;border-radius:7px;background:#edf4ee;color:#62816a;display:grid;place-content:center;text-align:center;font-size:8px;line-height:1.3}.event-date strong{font-size:14px}.gold-date{background:#f7f1e4;color:#a28449}.upcoming-row div{display:grid;gap:4px}.upcoming-row div strong{font-size:10px}.upcoming-row small{font-size:9px;color:#979e97}.contact-search{height:38px;max-width:370px;display:flex;align-items:center;gap:8px;padding:0 12px;background:var(--panel);border:1px solid var(--line);border-radius:8px;color:#8c958c;margin-bottom:15px}.contact-search input{border:0;background:transparent;outline:0;flex:1;font-size:10px}.contacts-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(245px,1fr));gap:10px}.contact-card{position:relative;display:flex;align-items:center;gap:11px;padding:14px;background:var(--panel);border:1px solid var(--line);border-radius:9px;box-shadow:var(--shadow)}.contact-card>.contact-avatar{height:39px;width:39px;font-size:11px;flex:none}.contact-card>div:nth-child(2){min-width:0;display:grid;gap:4px}.contact-card>div:nth-child(2) strong{font-size:10px}.contact-card>div:nth-child(2) span{font-size:9px;color:#838b83;overflow:hidden;text-overflow:ellipsis}.contact-card>div:nth-child(2) small{font-size:8px;color:#a0a69f}.contact-more{margin-left:auto;align-self:flex-start}.contact-email{position:absolute;right:12px;bottom:10px;border:0;background:transparent;color:#829386;font-size:12px}body.wasteland .outline-button,body.wasteland .upcoming-row{background:#faf6ed;border-color:#e6dccb}body.wasteland .calendar-card{background:#faf6ed;border-color:#e6dccb}body.wasteland .cal-cell:hover{background:#f7f0e4}body.wasteland .event-chip{background:#f2e9da;color:#996445}body.wasteland .cal-cell.today .cal-number{background:#a76645} +.account-card[role="button"]{cursor:pointer;appearance:none}.account-card[role="button"]:hover{border-color:#dce5dc}.account-card[role="button"]:focus-visible{outline:2px solid #7eae90;outline-offset:2px}.account-note{font-size:10px;line-height:1.5;color:#848c84;margin:7px 0 12px}.account-note+.compose-line{margin-top:1px}.account-status{font-size:10px;line-height:1.5;color:#9a6346;min-height:15px;margin:9px 0 2px} +.attachment{box-sizing:border-box;width:100%;max-width:420px;min-width:0}.attachment-info{min-width:0;overflow:hidden}.attachment-info strong{max-width:100%;overflow-wrap:anywhere;word-break:break-word;line-height:1.4}.attachment .download{flex:none}.account-list{max-height:55vh;overflow-y:auto}.account-row{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #edf0ec}.account-row-info{min-width:0;display:grid;gap:5px}.account-row-info strong{font-size:11px;overflow-wrap:anywhere}.account-row-info small{font-size:9px;color:#929991;overflow-wrap:anywhere}.account-row-actions{display:flex;align-items:center;gap:8px;flex:none}.account-current{font-size:9px;color:#61836a}.account-row .outline-button{padding:6px 9px}.account-row .discard{padding:6px}