import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' import { computed, ref } from 'vue' import type { FormField } from '../../src/api/types' import { setBundle } from '../../src/app/i18n' import MailPreviewField from '../../src/components/form/fields/MailPreviewField.vue' import { FORM_VALUES } from '../../src/components/form/formContext' import { setCurrentUser } from '../../src/state/useAuth' import { clearToasts, toasts } from '../../src/state/useToasts' import { API, mockApi, profile, requestsTo, resetState, type Reply, wait } from '../helpers' import { langFixture } from '../fixtures/typed' const codeeditorBundle = { 'backend::lang.codeeditor.load_failed': { other: 'The code editor could not be loaded. You can still edit the text here.', }, 'backend::lang.codeeditor.toolbar': { other: 'Code editor tools' }, 'backend::lang.list.empty_value': { other: '—' }, } const mailPreviewBundle = { ...langFixture.data, 'backend::lang.mail.preview.html': { other: 'HTML' }, 'backend::lang.mail.preview.text': { other: 'Plain text' }, 'backend::lang.mail.preview.subject': { other: 'Subject' }, 'backend::lang.mail.preview.frame_title': { other: 'Preview of the HTML message' }, 'backend::lang.mail.preview.rendering': { other: 'Rendering preview…' }, 'backend::lang.mail.preview.empty': { other: 'Nothing to preview yet. Write the message first.' }, 'backend::lang.mail.preview.failed': { other: 'The draft cannot be rendered: :message The preview shows the last version that rendered.', }, 'backend::lang.mail.preview.failed_first': { other: 'The draft cannot be rendered: :message' }, 'backend::lang.mail.preview.unavailable': { other: 'Preview unavailable. It updates again with your next edit.' }, 'backend::lang.mail.preview.sample_note': { other: 'Variables are filled with sample values. A variable without a sample shows as [name].', }, 'backend::lang.mail.preview.sample_content_note': { other: 'Previewed with sample content.' }, 'backend::lang.mail.preview.test_send': { other: 'Send test to me' }, 'backend::lang.mail.preview.test_sending': { other: 'Sending…' }, 'backend::lang.mail.preview.test_hint': { other: 'Sends the current draft, unsaved changes included, to :email.', }, 'backend::lang.mail.preview.test_sent': { other: 'Test message sent to :email.' }, 'backend::lang.mail.preview.test_limited': { other: 'You have sent too many test messages. Try again in :seconds s.', }, 'backend::lang.mail.preview.test_invalid': { other: 'Fix the draft before sending a test: :message' }, 'backend::lang.mail.preview.test_failed': { other: 'The test message could not be sent. Check the mail settings and the application log.', }, } const PREVIEW = `${API}/mail/preview` const TEST_SEND = `${API}/mail/test-send` function previewField(mode = 'template'): FormField { return { name: '_preview', label: 'Preview', type: 'mailpreview', mode } as FormField } function okPreview(html = '

Hello

', subject = 'Welcome', text = 'Hello'): Reply { return { body: { data: { html, subject, text }, meta: {} } } } function mountPreview(values: Record, field: FormField = previewField(), recordId: number | null = 3) { const valuesRef = ref(values) return mount(MailPreviewField, { props: { field, modelValue: null, controlId: 'f-preview', recordId }, global: { provide: { [FORM_VALUES as symbol]: computed(() => valuesRef.value), }, }, attachTo: document.body, }) } beforeEach(() => { resetState() setBundle(mailPreviewBundle, 'en') clearToasts() setCurrentUser(profile.data) }) afterEach(() => { vi.useRealTimers() document.body.innerHTML = '' clearToasts() }) enableAutoUnmount(afterEach) describe('MailPreviewField', () => { it('binds a sandboxed srcdoc iframe to the server html only', async () => { const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview('

Rendered

') }) const wrapper = mountPreview({ body: 'hi' }) await flushPromises() const frame = wrapper.find('[data-mail-preview-frame]') expect(frame.exists()).toBe(true) expect(frame.attributes('sandbox')).toBe('') expect(frame.attributes('src')).toBeUndefined() expect(frame.attributes('srcdoc')).toBe('

Rendered

') expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(1) const body = await requestsTo(calls, 'POST', PREVIEW)[0]!.clone().json() expect(body).toEqual({ mode: 'template', id: 3, values: { body: 'hi' } }) }) it('drops a stale preview answer via the sequence guard', async () => { let resolveFirst!: (reply: Reply) => void const first = new Promise((resolve) => { resolveFirst = resolve }) let calls = 0 mockApi({ [`POST ${PREVIEW}`]: async () => { calls++ if (calls === 1) { return first } return okPreview('

Second

', 'Second') }, }) const values = ref({ body: 'one' }) const wrapper = mount(MailPreviewField, { props: { field: previewField(), modelValue: null, controlId: 'f-preview', recordId: 1 }, global: { provide: { [FORM_VALUES as symbol]: computed(() => values.value) } }, attachTo: document.body, }) await flushPromises() values.value = { body: 'two' } await wait(520) await flushPromises() resolveFirst(okPreview('

First

', 'First')) await flushPromises() expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('

Second

') expect(wrapper.find('[data-mail-preview-subject]').text()).toContain('Second') }) it('keeps the previous srcdoc after a 422 and shows the failed line', async () => { let n = 0 mockApi({ [`POST ${PREVIEW}`]: () => { n++ if (n === 1) { return okPreview('

Good

') } return { status: 422, body: { error: { code: 'validation_failed', message: 'Validation failed', details: { field: 'body', rule: 'unsafe', message: 'script refused' }, }, }, } }, }) const values = ref({ body: 'ok' }) const wrapper = mount(MailPreviewField, { props: { field: previewField(), modelValue: null, controlId: 'f-preview', recordId: 1 }, global: { provide: { [FORM_VALUES as symbol]: computed(() => values.value) } }, attachTo: document.body, }) await flushPromises() expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('

Good

') values.value = { body: 'bad' } await wait(520) await flushPromises() expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('

Good

') expect(wrapper.find('[data-mail-preview-error]').text()).toContain('script refused') }) it('disables the test-send button after a 429 with Retry-After', async () => { mockApi({ [`POST ${PREVIEW}`]: okPreview(), [`POST ${TEST_SEND}`]: { status: 429, headers: { 'Retry-After': '30' }, body: { error: { code: 'rate_limited', message: 'Too many', details: {} } }, }, }) const wrapper = mountPreview({ body: 'hi' }) await flushPromises() await wrapper.find('[data-mail-preview-test-send]').trigger('click') await flushPromises() const button = wrapper.find('[data-mail-preview-test-send]') expect(button.attributes('disabled')).toBeDefined() expect(wrapper.find('[data-mail-preview-test-error]').text()).toContain('30') }) it('sends nothing for an empty draft', async () => { const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview() }) const wrapper = mountPreview({ body: ' ' }) await flushPromises() expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(0) expect(wrapper.find('[data-mail-preview-empty]').exists()).toBe(true) expect(wrapper.find('[data-mail-preview-frame]').exists()).toBe(false) }) it('toasts the returned email on a successful test send', async () => { mockApi({ [`POST ${PREVIEW}`]: okPreview(), [`POST ${TEST_SEND}`]: { body: { data: { email: 'dev@example.test' }, meta: {} } }, }) const wrapper = mountPreview({ body: 'hi' }) await flushPromises() await wrapper.find('[data-mail-preview-test-send]').trigger('click') await flushPromises() expect(toasts.value[0]?.text).toContain('dev@example.test') }) }) function codeField(overrides: Partial = {}): FormField { return { name: 'content_html', label: 'HTML', type: 'codeeditor', language: 'html', size: 'large', ...overrides, } as FormField } describe('CodeEditorField loading and fallback', () => { beforeEach(() => { setBundle({ ...mailPreviewBundle, ...codeeditorBundle }, 'en') }) it('shows the bg-skel loading box at the size height while the chunk loads', async () => { // Hold the dynamic import open so the loading box stays visible. let release!: () => void const gate = new Promise((resolve) => { release = resolve }) vi.resetModules() vi.doMock('../../src/components/form/codeeditor/editor', async () => { await gate return await vi.importActual('../../src/components/form/codeeditor/editor') }) const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default const wrapper = mount(Field, { props: { field: codeField(), modelValue: '

x

', controlId: 'f-html' }, attachTo: document.body, }) await flushPromises() const loading = wrapper.find('[data-codeeditor-loading]') expect(loading.exists()).toBe(true) expect(loading.attributes('aria-busy')).toBe('true') expect((loading.element as HTMLElement).style.height).toBe('320px') release() await flushPromises() wrapper.unmount() vi.doUnmock('../../src/components/form/codeeditor/editor') }) it('renders a read-only pre without loading CodeMirror', async () => { const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default const wrapper = mount(Field, { props: { field: codeField({ readOnly: true }), modelValue: 'layout {{ name }}', controlId: 'f-html', }, attachTo: document.body, }) await flushPromises() const pre = wrapper.find('pre') expect(pre.exists()).toBe(true) expect(pre.text()).toBe('layout {{ name }}') expect(wrapper.find('[data-codeeditor-loading]').exists()).toBe(false) expect(wrapper.find('.cm-editor').exists()).toBe(false) }) }) describe('insertImage', () => { it('escapes markdown, html, css and text snippets per UI-SPEC C4', async () => { const { insertImage } = await import('../../src/components/mail/insertImage') expect(insertImage('markdown', 'https://cdn.example.com/a b.png', 'Logo [x]')).toBe( '![Logo \\[x\\]](https://cdn.example.com/a%20b.png)', ) expect(insertImage('html', 'https://cdn.example.com/a"b.png', 'a "b" ')).toBe( 'a "b" <c>', ) expect(insertImage('css', 'https://cdn.example.com/a.png', 'ignored')).toBe( 'url("https://cdn.example.com/a.png")', ) expect(insertImage('text', 'https://cdn.example.com/a.png', 'ignored')).toBe( 'https://cdn.example.com/a.png', ) }) }) describe('ColorPickerField', () => { it('syncs a typed #rrggbb into the swatch and keeps the last valid on partial', async () => { const Field = (await import('../../src/components/form/fields/ColorPickerField.vue')).default setBundle( { ...mailPreviewBundle, 'backend::lang.colorpicker.pick': { other: 'Pick a colour for “:field”' }, 'backend::lang.colorpicker.not_set': { other: 'Not set' }, }, 'en', ) const wrapper = mount(Field, { props: { field: { name: 'body_bg', label: 'Body background', type: 'colorpicker' } as FormField, modelValue: '', controlId: 'f-color', }, attachTo: document.body, }) const text = wrapper.find('input[type="text"]') const swatch = wrapper.find('input[type="color"]') expect(swatch.element.value).toBe('#ffffff') await text.setValue('#D66829') expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['#D66829']) expect(swatch.element.value.toLowerCase()).toBe('#d66829') await text.setValue('#D66') expect(swatch.element.value.toLowerCase()).toBe('#d66829') }) }) // Last in the file: it replaces the editor chunk for the rest of the run. describe('CodeEditorField chunk failure', () => { afterEach(() => { vi.doUnmock('../../src/components/form/codeeditor/editor') }) it('shows the load_failed note and a monospace textarea that still emits', async () => { vi.resetModules() vi.doMock('../../src/components/form/codeeditor/editor', () => { throw new Error('chunk failed') }) ;(await import('../../src/app/i18n')).setBundle({ ...mailPreviewBundle, ...codeeditorBundle }, 'en') const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default const wrapper = mount(Field, { props: { field: codeField(), modelValue: '

Stored

', controlId: 'f-html' }, attachTo: document.body, }) await vi.waitFor(() => { expect(wrapper.find('[data-codeeditor-load-failed]').exists()).toBe(true) }) expect(wrapper.find('[data-codeeditor-load-failed]').text()).toContain('could not be loaded') const textarea = wrapper.find('textarea') expect(textarea.exists()).toBe(true) expect(textarea.element.value).toBe('

Stored

') expect(textarea.attributes('id')).toBe('f-html') await textarea.setValue('

Edited

') expect(wrapper.emitted('update:modelValue')).toEqual([['

Edited

']]) }) })