Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions public/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -1508,6 +1508,22 @@ body {
gap: var(--UI-Spacing-spacing-xxs);
}

.tag.attachment--image {
height: auto;
min-height: var(--UI-Input-sm);
padding-block: var(--UI-Spacing-spacing-xxs);
padding-left: var(--UI-Spacing-spacing-xxs);
}

.attachment-thumb {
flex-shrink: 0;
width: 40px;
height: 40px;
object-fit: cover;
border-radius: var(--UI-Radius-tag-medium);
background: var(--Colors-Border-Subtle);
}

.composer__attachment-remove {
display: inline-flex;
align-items: center;
Expand Down Expand Up @@ -2112,6 +2128,14 @@ body {
padding-bottom: 0;
}

.attachment-preview-modal__image {
display: block;
max-width: 100%;
max-height: min(60vh, 28rem);
margin: 0 auto;
object-fit: contain;
}

.attachment-preview-modal__body {
margin: 0;
white-space: pre-wrap;
Expand Down
87 changes: 84 additions & 3 deletions public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1479,20 +1479,94 @@ function renderAttachmentList(attachments) {
for (const attachment of attachments) {
const name = attachment.name || t('Attachment');
const hasText = typeof attachment.text === 'string' && attachment.text.length > 0;
const chip = document.createElement(hasText ? 'button' : 'span');
const imageUrl = isImageAttachment(attachment) ? attachment.ref?.url || '' : '';
let canPreviewImage = Boolean(imageUrl);
const previewable = hasText || canPreviewImage;
const chip = document.createElement(previewable ? 'button' : 'span');
chip.className = 'tag outline email__attachment';
chip.textContent = name;
if (hasText) {
if (previewable) {
chip.type = 'button';
chip.classList.add('email__attachment--preview');
chip.setAttribute('aria-label', `${t('Preview attachment')}: ${name}`);
chip.addEventListener('click', () => openAttachmentPreview(attachment));
chip.addEventListener('click', () => {
if (canPreviewImage) openImagePreview(name, imageUrl);
else openAttachmentPreview(attachment);
});
}
// Upload URLs are presigned and expire; fall back to the plain name chip.
if (imageUrl) {
prependAttachmentThumb(chip, imageUrl, () => {
canPreviewImage = false;
if (!hasText) chip.replaceWith(Object.assign(document.createElement('span'), {
className: 'tag outline email__attachment',
textContent: name,
}));
});
}
list.appendChild(chip);
}
return list;
}

function isImageAttachment({ type, name } = {}) {
if (typeof type === 'string' && type.startsWith('image/')) return true;
return /\.(png|jpe?g|gif|webp)$/i.test(name || '');
}

function prependAttachmentThumb(chip, src, onError) {
if (!src) return;
const img = document.createElement('img');
img.className = 'attachment-thumb';
img.alt = '';
img.decoding = 'async';
img.addEventListener('error', () => {
img.remove();
chip.classList.remove('attachment--image');
onError?.();
}, { once: true });
img.src = src;
chip.classList.add('attachment--image');
chip.prepend(img);
}

const filePreviewUrls = new WeakMap();

function filePreviewUrl(file) {
if (!file || !isImageAttachment(file) || typeof URL.createObjectURL !== 'function') return '';
let url = filePreviewUrls.get(file);
if (!url) {
url = URL.createObjectURL(file);
filePreviewUrls.set(file, url);
}
return url;
}

function releaseFilePreview(file) {
const url = filePreviewUrls.get(file);
if (!url) return;
URL.revokeObjectURL(url);
filePreviewUrls.delete(file);
}

function openImagePreview(name, url) {
const modal = new Modal({
size: 'medium',
title: name,
content: `<img class="attachment-preview-modal__image" src="${escapeHtml(url)}" alt="${escapeHtml(name)}">`,
closeOnOverlayClick: true,
closeButtonLabel: t('Close'),
footerButtons: [
{
label: t('Close'),
type: 'secondary',
onClick: () => modal.close(),
},
],
});
modal.open();
}

// The original message carried by a forward, quoted under the cover note.
// The composer preview names its own scrolling container instead.
function renderForwardedBlock(forwarded, { labelled = true } = {}) {
Expand Down Expand Up @@ -2296,13 +2370,15 @@ function renderAttachmentPreview() {
const label = item.status === 'uploading' ? `${item.file.name} ${t('(uploading…)')}`
: item.status === 'error' ? `${item.file.name} ${t('(failed)')}` : item.file.name;
chip.innerHTML = `<span class="composer__attachment-name">${escapeHtml(label)}</span>`;
prependAttachmentThumb(chip, filePreviewUrl(item.file));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'composer__attachment-remove';
remove.setAttribute('aria-label', `${t('Remove')} ${item.file.name}`);
remove.innerHTML = '<span class="icon icon-trash icon-small" aria-hidden="true"></span>';
remove.addEventListener('click', () => {
state.attachments.splice(idx, 1);
releaseFilePreview(item.file);
renderAttachmentPreview();
});
chip.appendChild(remove);
Expand Down Expand Up @@ -2361,6 +2437,7 @@ function readyAttachments() {
}

function clearAttachments() {
for (const item of state.attachments) releaseFilePreview(item.file);
state.attachments = [];
renderAttachmentPreview();
}
Expand Down Expand Up @@ -4102,13 +4179,15 @@ function renderAssistantAttachments() {
const label = item.status === 'uploading' ? `${item.file.name} ${t('(uploading…)')}`
: item.status === 'error' ? `${item.file.name} ${t('(failed)')}` : item.file.name;
chip.innerHTML = `<span class="assistant__attachment-name">${escapeHtml(label)}</span>`;
prependAttachmentThumb(chip, filePreviewUrl(item.file));
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'composer__attachment-remove';
remove.setAttribute('aria-label', `${t('Remove')} ${item.file.name}`);
remove.innerHTML = '<span class="icon icon-trash icon-small" aria-hidden="true"></span>';
remove.addEventListener('click', () => {
state.assistant.attachments.splice(idx, 1);
releaseFilePreview(item.file);
renderAssistantAttachments();
syncAssistantBusyControls();
els.assistantInput?.focus();
Expand Down Expand Up @@ -4159,6 +4238,7 @@ async function handleAssistantFiles(files) {
}

function clearAssistantAttachments() {
for (const item of state.assistant.attachments) releaseFilePreview(item.file);
state.assistant.attachments = [];
renderAssistantAttachments();
}
Expand Down Expand Up @@ -4275,6 +4355,7 @@ export function mailAppTestHooks() {
sendEmail,
handleComposerFiles,
handleAssistantFiles,
renderAttachmentList,
sendAssistant,
scrollToEmail,
startReply,
Expand Down
61 changes: 61 additions & 0 deletions tests/a11y-mail.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1375,6 +1375,67 @@ describe('M13 failed upload', () => {
});
});

describe('Attachment thumbnails', () => {
const { createObjectURL, revokeObjectURL } = URL;
afterEach(() => {
URL.createObjectURL = createObjectURL;
URL.revokeObjectURL = revokeObjectURL;
});

it('shows a local preview for an image in the composer and revokes it on remove', async () => {
clickThread('thread-quote');
await nextFrame();
URL.createObjectURL = vi.fn(() => 'blob:photo');
URL.revokeObjectURL = vi.fn();
mail.state.config.attachments = { enabled: true, allowedTypes: ['.png', '.pdf'] };
mail.state.assistant.chat = { uploadFiles: vi.fn(async (files) => files.map((file) => ({ name: file.name }))) };

await mail.handleComposerFiles([
new File(['png'], 'photo.png', { type: 'image/png' }),
new File(['%PDF'], 'brief.pdf', { type: 'application/pdf' }),
]);

const [imageChip, pdfChip] = document.querySelectorAll('.composer__attachment');
const thumb = imageChip.querySelector('img.attachment-thumb');
expect(thumb.getAttribute('src')).toBe('blob:photo');
expect(thumb.alt).toBe('');
expect(pdfChip.querySelector('img')).toBeNull();
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);

imageChip.querySelector('.composer__attachment-remove').click();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:photo');
});

it('releases preview URLs when the composer is cleared', async () => {
clickThread('thread-quote');
await nextFrame();
URL.createObjectURL = vi.fn(() => 'blob:photo');
URL.revokeObjectURL = vi.fn();
mail.state.config.attachments = { enabled: true, allowedTypes: ['.png'] };
mail.state.assistant.chat = { uploadFiles: vi.fn(async (files) => files.map((file) => ({ name: file.name }))) };

await mail.handleComposerFiles([new File(['png'], 'photo.png', { type: 'image/png' })]);
mail.startCompose({ blank: true });

expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:photo');
});

it('shows a sent image thumbnail and falls back to the name when the URL fails', () => {
const list = mail.renderAttachmentList([
{ name: 'photo.png', type: 'image/png', ref: { url: 'https://files.test/photo.png' } },
]);
const chip = list.querySelector('.email__attachment--preview');
expect(computeAccessibleName(chip)).toBe(`${strings['Preview attachment']}: photo.png`);
const thumb = chip.querySelector('img.attachment-thumb');
expect(thumb.getAttribute('src')).toBe('https://files.test/photo.png');

thumb.dispatchEvent(new Event('error'));
expect(list.querySelector('img')).toBeNull();
expect(list.querySelector('button')).toBeNull();
expect(list.querySelector('.email__attachment').textContent).toBe('photo.png');
});
});

describe('Assistant chat attachments', () => {
const pdf = () => new File(['%PDF'], 'brief.pdf', { type: 'application/pdf' });
const docx = () => new File(['doc'], 'notes.docx', {
Expand Down
Loading