192 lines
8.6 KiB
JavaScript
192 lines
8.6 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const vm = require('node:vm');
|
|
|
|
const root = path.resolve(__dirname, '..');
|
|
const mailSource = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
|
|
const pgpSource = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
|
|
const setupSource = mailSource.slice(mailSource.indexOf('function setupDraftComposer()'), mailSource.indexOf('\nasync function syncMailbox('));
|
|
|
|
function harness(initialDraft = null, reply = null, forward = false) {
|
|
const saved = [];
|
|
const deleted = [];
|
|
const toasts = [];
|
|
const elements = new Map();
|
|
const timers = new Map();
|
|
let nextTimer = 0;
|
|
let wrapped;
|
|
let saveDraft = async values => { saved.push(structuredClone(values)); return { id: values.id }; };
|
|
function node() {
|
|
const listeners = {};
|
|
return {
|
|
value: '', dataset: {}, isConnected: true, files: [], children: [],
|
|
classList: { contains: () => false },
|
|
append(...items) { this.children.push(...items); },
|
|
replaceChildren() { this.children = []; },
|
|
insertBefore(item) { this.children.push(item); },
|
|
setAttribute() {},
|
|
addEventListener(type, handler) { (listeners[type] ||= []).push(handler); },
|
|
dispatch(type, event = {}) { for (const handler of listeners[type] || []) handler(event); },
|
|
querySelector(selector) { return elements.get(selector); }
|
|
};
|
|
}
|
|
for (const name of ['#compose-to', '#compose-cc', '#compose-subject', '#compose-body', '#send', '#discard', '.modal-head span', '.compose-fields', '.compose-footer', '.modal-close', '.modal-overlay']) elements.set(name, node());
|
|
const modal = node();
|
|
const modalRoot = node();
|
|
modalRoot.querySelector = selector => selector === '.compose-modal' ? modal : elements.get(selector);
|
|
const context = {
|
|
appShell: { wrapShowCompose(fn) { wrapped = fn(() => {}); } },
|
|
selectMailUi: selector => selector === '#modal-root' ? modalRoot : elements.get(selector),
|
|
document: { createElement: node },
|
|
window: { epMailConversationThreads: require('../conversation-threads.js'), crypto: { randomUUID: () => 'new-id' }, daybreakMail: {
|
|
saveDraft: values => saveDraft(values),
|
|
async deleteDraft(id) { deleted.push(id); }
|
|
} },
|
|
rendererState: { activeFolder: 'Inbox' },
|
|
syncMailbox() {},
|
|
toastMailUi: message => toasts.push(message),
|
|
setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; },
|
|
clearTimeout(id) { timers.delete(id); },
|
|
btoa: value => Buffer.from(value, 'binary').toString('base64')
|
|
};
|
|
vm.runInNewContext(`${setupSource}\nsetupDraftComposer();`, context);
|
|
wrapped(reply, forward, initialDraft);
|
|
return {
|
|
modal, modalRoot, elements, saved, deleted, toasts,
|
|
setSave(fn) { saveDraft = fn; },
|
|
async runTimers() { for (const fn of [...timers.values()]) fn(); timers.clear(); await new Promise(resolve => setImmediate(resolve)); },
|
|
async settle() { await new Promise(resolve => setImmediate(resolve)); }
|
|
};
|
|
}
|
|
|
|
test('PGP composer forwards the complete draft to the wrapped composer', () => {
|
|
const start = pgpSource.indexOf('pgpMailUi.wrapShowCompose(');
|
|
const end = pgpSource.indexOf('\n// Called by the send handler', start);
|
|
let args;
|
|
const context = {
|
|
pgpMailUi: { wrapShowCompose(decorator) { decorator((...values) => { args = values; })(null, false, { id: 'existing', text: 'saved text' }); } },
|
|
selectPgpMailUi: () => null
|
|
};
|
|
vm.runInNewContext(pgpSource.slice(start, end), context);
|
|
assert.equal(args[2].id, 'existing');
|
|
assert.equal(args[2].text, 'saved text');
|
|
});
|
|
|
|
test('reopening a draft restores fields, attachments, and its identity', () => {
|
|
const draft = { id: 'existing', to: 'a@example.test', cc: 'b@example.test', subject: 'Subject', text: 'Message', attachments: [{ filename: 'note.txt' }] };
|
|
const h = harness(draft);
|
|
assert.equal(h.modal.dataset.draftId, draft.id);
|
|
for (const [field, value] of [['to', draft.to], ['cc', draft.cc], ['subject', draft.subject], ['body', draft.text]]) {
|
|
assert.equal(h.elements.get(`#compose-${field}`).value, value);
|
|
}
|
|
assert.equal(h.modal._composeAttachments[0].filename, 'note.txt');
|
|
assert.equal(h.elements.get('.modal-head span').textContent, 'Edit draft');
|
|
});
|
|
|
|
test('reply draft preserves thread headers when saved and restored; forwards do not inherit them', async () => {
|
|
const h = harness(null, { messageId: '<parent@example.test>', references: '<root@example.test>' });
|
|
h.elements.get('#compose-body').value = 'Reply';
|
|
h.modal.dispatch('input');
|
|
await h.runTimers();
|
|
assert.equal(h.saved[0].inReplyTo, '<parent@example.test>');
|
|
assert.equal(h.saved[0].references, '<root@example.test> <parent@example.test>');
|
|
const restored = harness(h.saved[0]);
|
|
assert.equal(restored.modal._replyHeaders.inReplyTo, '<parent@example.test>');
|
|
const forward = harness(null, { messageId: '<parent@example.test>' }, true);
|
|
assert.equal(forward.modal._replyHeaders.inReplyTo, '');
|
|
});
|
|
|
|
test('blank and whitespace-only new messages are not saved on close or manual save', async () => {
|
|
const h = harness();
|
|
h.elements.get('#compose-body').value = ' \n ';
|
|
h.modal.dispatch('input');
|
|
await h.runTimers();
|
|
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
|
|
await save.onclick();
|
|
assert.equal(h.toasts.at(-1), 'Nothing to save in this draft');
|
|
h.elements.get('.modal-close').dispatch('click');
|
|
await h.settle();
|
|
assert.equal(h.saved.length, 0);
|
|
assert.equal(h.modal.dataset.draftId, '');
|
|
});
|
|
|
|
test('closing via overlay or Escape saves meaningful unsaved text', async () => {
|
|
for (const method of ['overlay', 'escape']) {
|
|
const h = harness();
|
|
h.elements.get('#compose-subject').value = 'Saved subject';
|
|
if (method === 'overlay') h.elements.get('.modal-overlay').dispatch('click', { target: { classList: { contains: () => true } } });
|
|
else h.modal.dispatch('keydown', { key: 'Escape' });
|
|
await h.settle();
|
|
assert.equal(h.saved.length, 1);
|
|
assert.equal(h.saved[0].subject, 'Saved subject');
|
|
}
|
|
});
|
|
|
|
test('attachment-only drafts are saved and picker cancellation creates nothing', async () => {
|
|
const h = harness();
|
|
const attachmentRow = h.elements.get('.compose-fields').children[0];
|
|
const input = attachmentRow.children[1].children[1];
|
|
await input.onchange();
|
|
assert.equal(h.saved.length, 0);
|
|
input.files = [{ name: 'note.txt', type: 'text/plain', size: 3, async arrayBuffer() { return Uint8Array.from([97, 98, 99]).buffer; } }];
|
|
await input.onchange();
|
|
assert.equal(h.saved.length, 1);
|
|
assert.equal(h.saved[0].attachments[0].contentBase64, 'YWJj');
|
|
});
|
|
|
|
test('pending saves are serialized and discard waits before deleting', async () => {
|
|
const h = harness();
|
|
let finishFirst;
|
|
const calls = [];
|
|
h.setSave(values => {
|
|
calls.push(values.text);
|
|
if (calls.length === 1) return new Promise(resolve => { finishFirst = resolve; });
|
|
return Promise.resolve({ id: values.id });
|
|
});
|
|
h.elements.get('#compose-body').value = 'first';
|
|
h.modal.dispatch('input');
|
|
await h.runTimers();
|
|
h.elements.get('#compose-body').value = 'second';
|
|
h.modal.dispatch('input');
|
|
await h.runTimers();
|
|
const discard = h.elements.get('#discard').onclick();
|
|
assert.deepEqual(calls, ['first']);
|
|
assert.deepEqual(h.deleted, []);
|
|
finishFirst({ id: 'new-id' });
|
|
await discard;
|
|
assert.deepEqual(calls, ['first', 'second']);
|
|
assert.deepEqual(h.deleted, ['new-id']);
|
|
});
|
|
|
|
test('sent draft cleanup cancels unsaved timers and waits for in-flight saves', async () => {
|
|
const h = harness();
|
|
let finishSave;
|
|
h.setSave(() => new Promise(resolve => { finishSave = resolve; }));
|
|
h.elements.get('#compose-body').value = 'sent message';
|
|
h.modal.dispatch('input');
|
|
await h.runTimers();
|
|
h.elements.get('#compose-body').value = 'newer edit';
|
|
h.modal.dispatch('input');
|
|
const cleanup = h.modal._deleteSavedDraft();
|
|
await h.runTimers();
|
|
assert.deepEqual(h.deleted, []);
|
|
finishSave({ id: 'new-id' });
|
|
await cleanup;
|
|
assert.deepEqual(h.deleted, ['new-id']);
|
|
});
|
|
|
|
test('a failed save reports an error and a later save can retry', async () => {
|
|
const h = harness();
|
|
h.elements.get('#compose-body').value = 'message';
|
|
h.setSave(async () => { throw new Error('Storage unavailable'); });
|
|
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
|
|
await save.onclick();
|
|
assert.equal(h.toasts.at(-1), 'Storage unavailable');
|
|
h.setSave(async values => { h.saved.push(values); return { id: values.id }; });
|
|
await save.onclick();
|
|
assert.equal(h.saved.length, 1);
|
|
assert.equal(h.toasts.at(-1), 'Draft saved on this device');
|
|
});
|