diff --git a/admin/tests/browser/codeeditor.test.ts b/admin/tests/browser/codeeditor.test.ts new file mode 100644 index 00000000..5dedb25f --- /dev/null +++ b/admin/tests/browser/codeeditor.test.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import type { FormField } from '../../src/api/types' +import { installHotkeys } from '../../src/app/hotkeys' +import { setBundle } from '../../src/app/i18n' +import CodeEditorField from '../../src/components/form/fields/CodeEditorField.vue' +import { langFixture } from '../fixtures/typed' +import { press } from '../helpers' + +enableAutoUnmount(afterEach) + +const bundle = { + ...langFixture.data, + '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: '—' }, +} + +function field(overrides: Partial = {}): FormField { + return { + name: 'content_html', + label: 'HTML', + type: 'codeeditor', + language: 'html', + size: 'large', + ...overrides, + } as FormField +} + +async function editorReady(root: HTMLElement): Promise { + return vi.waitFor( + () => { + const content = root.querySelector('.cm-content') + expect(content, root.innerHTML.slice(0, 500)).not.toBeNull() + return content! + }, + { timeout: 15000 }, + ) +} + +beforeEach(() => { + setBundle(bundle, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +describe('codeeditor keyboard and wrap (browser)', () => { + it('Tab leaves; Mod+S and Mod+Enter save; Esc does not cancel', async () => { + const uninstall = installHotkeys() + const saveClicks: string[] = [] + const cancelClicks: string[] = [] + + const form = document.createElement('form') + form.setAttribute('role', 'form') + document.body.appendChild(form) + + const next = document.createElement('input') + next.id = 'next-control' + next.type = 'text' + + const save = document.createElement('button') + save.type = 'button' + save.setAttribute('data-hotkey', 'mod+s mod+enter') + save.addEventListener('click', () => saveClicks.push('save')) + + const cancel = document.createElement('button') + cancel.type = 'button' + cancel.setAttribute('data-hotkey', 'escape') + cancel.addEventListener('click', () => cancelClicks.push('cancel')) + + const host = document.createElement('div') + form.append(host, next, save, cancel) + + const wrapper = mount(CodeEditorField, { + props: { field: field(), modelValue: 'Hello {{ .Name }}', controlId: 'f-html' }, + attachTo: host, + }) + await flushPromises() + const content = await editorReady(form) + content.focus() + + content.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true })) + next.focus() + expect(document.activeElement).toBe(next) + + content.focus() + expect(press(content, 's', { ctrlKey: true }).defaultPrevented).toBe(true) + expect(saveClicks).toEqual(['save']) + + saveClicks.length = 0 + expect(press(content, 'Enter', { ctrlKey: true }).defaultPrevented).toBe(true) + expect(saveClicks).toEqual(['save']) + + expect(press(content, 'Escape').defaultPrevented).toBe(false) + expect(cancelClicks).toEqual([]) + + // Go action decoration on {{ .Name }} + expect(form.querySelector('.cm-editor')?.textContent).toContain('{{ .Name }}') + + uninstall() + wrapper.unmount() + }) + + it('text wraps; html does not enable line wrapping', async () => { + const textHost = document.createElement('div') + document.body.appendChild(textHost) + const text = mount(CodeEditorField, { + props: { field: field({ language: 'text', size: 'small' }), modelValue: 'a'.repeat(200), controlId: 'f-text' }, + attachTo: textHost, + }) + await flushPromises() + await editorReady(textHost) + expect(textHost.querySelector('.cm-lineWrapping')).not.toBeNull() + text.unmount() + + const htmlHost = document.createElement('div') + document.body.appendChild(htmlHost) + const html = mount(CodeEditorField, { + props: { field: field({ language: 'html' }), modelValue: '
' + 'x'.repeat(200) + '
', controlId: 'f-html' }, + attachTo: htmlHost, + }) + await flushPromises() + await editorReady(htmlHost) + expect(htmlHost.querySelector('.cm-lineWrapping')).toBeNull() + html.unmount() + }) + + it('undo and redo restore history through the contenteditable surface', async () => { + const wrapper = mount(CodeEditorField, { + props: { field: field({ language: 'text' }), modelValue: 'start', controlId: 'f-text' }, + attachTo: document.body, + }) + await flushPromises() + const content = await editorReady(document.body) + content.focus() + const selection = window.getSelection() + const range = document.createRange() + range.selectNodeContents(content) + selection?.removeAllRanges() + selection?.addRange(range) + document.execCommand('insertText', false, 'changed') + await flushPromises() + await vi.waitFor(() => { + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['changed']) + }) + expect(press(content, 'z', { ctrlKey: true }).defaultPrevented).toBe(true) + await flushPromises() + await vi.waitFor(() => { + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['start']) + }) + expect(press(content, 'z', { ctrlKey: true, shiftKey: true }).defaultPrevented).toBe(true) + await flushPromises() + await vi.waitFor(() => { + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['changed']) + }) + }) +}) diff --git a/admin/tests/form/CodeEditorField.test.ts b/admin/tests/form/CodeEditorField.test.ts new file mode 100644 index 00000000..de0dbd5f --- /dev/null +++ b/admin/tests/form/CodeEditorField.test.ts @@ -0,0 +1,119 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import type { FormField } from '../../src/api/types' +import { setBundle } from '../../src/app/i18n' +import { langFixture } from '../fixtures/typed' +import { resetState } from '../helpers' + +const bundle = { + ...langFixture.data, + '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: '—' }, +} + +function field(overrides: Partial = {}): FormField { + return { + name: 'content_html', + label: 'HTML', + type: 'codeeditor', + language: 'html', + size: 'large', + ...overrides, + } as FormField +} + +beforeEach(() => { + resetState() + setBundle(bundle, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' + vi.doUnmock('../../src/components/form/codeeditor/load') + vi.resetModules() +}) + +enableAutoUnmount(afterEach) + +describe('CodeEditorField', () => { + it('shows the loading box at the size height while the chunk loads', async () => { + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + vi.resetModules() + vi.doMock('../../src/components/form/codeeditor/load', () => ({ + importCodeEditor: 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: field(), 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() + }) + + 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: field({ readOnly: true }), + modelValue: 'layout {{ name }}', + controlId: 'f-html', + }, + attachTo: document.body, + }) + await flushPromises() + expect(wrapper.find('pre').text()).toBe('layout {{ name }}') + expect(wrapper.find('.cm-editor').exists()).toBe(false) + }) + + it('falls back to a monospace textarea when the chunk fails', async () => { + vi.resetModules() + vi.doMock('../../src/components/form/codeeditor/load', () => ({ + importCodeEditor: async () => { + throw new Error('chunk failed') + }, + })) + const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default + const wrapper = mount(Field, { + props: { field: field(), modelValue: '

Stored

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

Stored

') + await textarea.setValue('

Edited

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

Edited

']]) + }) + + it('replaces an external modelValue without emitting', async () => { + const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default + const wrapper = mount(Field, { + props: { + field: field({ language: 'text', size: 'small' }), + modelValue: 'one', + controlId: 'f-text', + }, + attachTo: document.body, + }) + await flushPromises() + await wrapper.setProps({ modelValue: 'two' }) + await flushPromises() + expect(wrapper.emitted('update:modelValue') ?? []).toEqual([]) + }) +}) diff --git a/admin/tests/form/ColorPickerField.test.ts b/admin/tests/form/ColorPickerField.test.ts new file mode 100644 index 00000000..1eb1dd67 --- /dev/null +++ b/admin/tests/form/ColorPickerField.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { enableAutoUnmount, mount } from '@vue/test-utils' +import type { FormField } from '../../src/api/types' +import { setBundle } from '../../src/app/i18n' +import ColorPickerField from '../../src/components/form/fields/ColorPickerField.vue' +import { langFixture } from '../fixtures/typed' +import { resetState } from '../helpers' + +const bundle = { + ...langFixture.data, + 'backend::lang.colorpicker.pick': { other: 'Pick a colour for “:field”' }, + 'backend::lang.colorpicker.not_set': { other: 'Not set' }, +} + +beforeEach(() => { + resetState() + setBundle(bundle, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +enableAutoUnmount(afterEach) + +describe('ColorPickerField (UI-SPEC C2)', () => { + it('syncs a typed #rrggbb into the swatch and keeps the last valid on partial', async () => { + const wrapper = mount(ColorPickerField, { + 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') + }) + + it('clears to empty when the text is blank', async () => { + const wrapper = mount(ColorPickerField, { + props: { + field: { name: 'body_bg', label: 'Body background', type: 'colorpicker' } as FormField, + modelValue: '#112233', + controlId: 'f-color', + }, + attachTo: document.body, + }) + await wrapper.find('input[type="text"]').setValue('') + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['']) + }) +}) diff --git a/admin/tests/form/FormViewMail.test.ts b/admin/tests/form/FormViewMail.test.ts new file mode 100644 index 00000000..61c5277f --- /dev/null +++ b/admin/tests/form/FormViewMail.test.ts @@ -0,0 +1,143 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { enableAutoUnmount, flushPromises } from '@vue/test-utils' +import { setBundle } from '../../src/app/i18n' +import { toasts } from '../../src/state/useToasts' +import { clone, formSchemaFixture, langFixture, recordFixture } from '../fixtures/typed' +import { API, mountApp, resetState, type Reply, type Route } from '../helpers' + +const BASE = `${API}/summercms/cabana/mailtemplates` +const RECORD = `${BASE}/7` + +const strings = { + 'backend::lang.form.action_confirm': { other: 'Run “:action” on this record?' }, + 'backend::lang.form.action_done': { other: 'Action completed.' }, + 'backend::lang.form.action_stale': { other: 'This action no longer applies to this record.' }, + 'backend::lang.list.action_forbidden': { other: 'You do not have permission to run this action.' }, + 'backend::lang.extension.action_failed': { other: 'The action could not be completed.' }, + 'backend::lang.form.delete_confirm': { other: 'Delete this record?' }, +} + +function mailSchema() { + const envelope = clone(formSchemaFixture) + envelope.data.fields = [ + { name: 'subject', label: 'Subject', type: 'text' }, + { name: 'body', label: 'Body', type: 'textarea' }, + ] as typeof envelope.data.fields + return { body: envelope } +} + +function mailRecord(meta: Record = {}): Reply { + const envelope = clone(recordFixture) + envelope.data = { id: 7, subject: 'Hello', body: 'Body' } + envelope.meta = { + ...envelope.meta, + actions: [{ name: 'reset', label: 'Reset to file', confirm: 'Discard customizations?', danger: true }], + deletable: false, + ...meta, + } + return { body: envelope } +} + +function routes(overrides: Record = {}): Record { + return { + [`GET ${BASE}/schema/form`]: mailSchema(), + [`GET ${RECORD}`]: mailRecord(), + ...overrides, + } +} + +beforeEach(() => { + resetState() + setBundle({ ...langFixture.data, ...strings }, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +enableAutoUnmount(afterEach) + +describe('FormView mail footer actions and meta.deletable', () => { + it('offers reset with a danger confirm, then toasts and reloads', async () => { + let gets = 0 + const { wrapper } = await mountApp( + '/summercms/cabana/mailtemplates/7', + routes({ + [`GET ${RECORD}`]: () => { + gets++ + if (gets === 1) { + return mailRecord() + } + return mailRecord({ actions: [] }) + }, + [`POST ${RECORD}/actions/reset`]: { body: { data: { message: 'Restored from file.', fill: {} }, meta: {} } }, + }), + ) + expect(wrapper.find('[data-record-action="reset"]').exists()).toBe(true) + expect(wrapper.find('[data-action="delete"]').exists()).toBe(false) + + await wrapper.find('[data-record-action="reset"]').trigger('click') + await flushPromises() + const dialog = document.body.querySelector('[data-confirm-dialog]') + expect(dialog?.textContent).toContain('Discard customizations?') + dialog!.querySelector('[data-action="confirm"]')!.click() + await flushPromises() + expect(toasts.value.some((toast) => toast.text.includes('Restored from file.'))).toBe(true) + }) + + it('honours meta.deletable true and absent (default true for non-mail fixtures)', async () => { + const deletable = await mountApp( + '/summercms/cabana/mailtemplates/7', + routes({ [`GET ${RECORD}`]: mailRecord({ deletable: true, actions: [] }) }), + ) + expect(deletable.wrapper.find('[data-action="delete"]').exists()).toBe(true) + + const absent = await mountApp( + '/summercms/cabana/mailtemplates/7', + routes({ + [`GET ${RECORD}`]: (() => { + const envelope = clone(recordFixture) + envelope.data = { id: 7, subject: 'Hello', body: 'Body' } + envelope.meta = { ...(envelope.meta ?? {}), actions: [] } + delete (envelope.meta as { deletable?: boolean }).deletable + return { body: envelope } + })(), + }), + ) + expect(absent.wrapper.find('[data-action="delete"]').exists()).toBe(true) + }) + + it('toasts 403 and 409 paths from record actions', async () => { + const forbidden = await mountApp( + '/summercms/cabana/mailtemplates/7', + routes({ + [`POST ${RECORD}/actions/reset`]: { + status: 403, + body: { error: { code: 'forbidden', message: '', details: {} } }, + }, + }), + ) + await forbidden.wrapper.find('[data-record-action="reset"]').trigger('click') + await flushPromises() + document.body.querySelector('[data-action="confirm"]')!.click() + await flushPromises() + expect(toasts.value.some((toast) => toast.text.includes('permission'))).toBe(true) + + resetState() + setBundle({ ...langFixture.data, ...strings }, 'en') + const stale = await mountApp( + '/summercms/cabana/mailtemplates/7', + routes({ + [`POST ${RECORD}/actions/reset`]: { + status: 409, + body: { error: { code: 'conflict', message: 'gone', details: {} } }, + }, + }), + ) + await stale.wrapper.find('[data-record-action="reset"]').trigger('click') + await flushPromises() + document.body.querySelector('[data-action="confirm"]')!.click() + await flushPromises() + expect(toasts.value.some((toast) => toast.text.includes('no longer applies'))).toBe(true) + }) +}) diff --git a/admin/tests/form/MailImageField.test.ts b/admin/tests/form/MailImageField.test.ts new file mode 100644 index 00000000..7c95b8c5 --- /dev/null +++ b/admin/tests/form/MailImageField.test.ts @@ -0,0 +1,73 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import type { FormField } from '../../src/api/types' +import { setBundle } from '../../src/app/i18n' +import MailImageField from '../../src/components/form/fields/MailImageField.vue' +import { langFixture } from '../fixtures/typed' +import { API, mockApi, resetState } from '../helpers' + +const bundle = { + ...langFixture.data, + 'backend::lang.mailimage.empty': { other: 'No image chosen' }, + 'backend::lang.mailimage.choose': { other: 'Choose image' }, + 'backend::lang.mailimage.change': { other: 'Change image' }, + 'backend::lang.mailimage.remove': { other: 'Remove image' }, + 'backend::lang.mailimage.missing': { + other: 'This image is no longer in the library. Choose another one.', + }, + 'backend::lang.mail.picker.choose_title': { other: 'Choose an image' }, + 'backend::lang.mail.picker.search': { other: 'Search images' }, + 'backend::lang.mail.picker.use': { other: 'Use this image' }, + 'backend::lang.mail.picker.upload': { other: 'Upload image' }, + 'backend::lang.mail.picker.empty_title': { other: 'No images yet' }, + 'backend::lang.mail.picker.empty_pick_only': { other: 'Images are added in Settings.' }, + 'backend::lang.mail.picker.load_failed': { other: 'The image library could not be loaded.' }, + 'backend::lang.form.cancel': { other: 'Cancel' }, +} + +beforeEach(() => { + resetState() + setBundle(bundle, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +enableAutoUnmount(afterEach) + +describe('MailImageField (UI-SPEC C11)', () => { + it('shows the missing line when the stored id is gone', async () => { + mockApi({ + [`GET ${API}/mail/images/3`]: { + status: 404, + body: { error: { code: 'not_found', message: 'gone', details: {} } }, + }, + }) + const wrapper = mount(MailImageField, { + props: { + field: { name: 'logo', label: 'Logo', type: 'mailimage' } as FormField, + modelValue: 3, + controlId: 'f-logo', + }, + attachTo: document.body, + }) + await flushPromises() + expect(wrapper.find('[data-mailimage-missing]').exists()).toBe(true) + expect(wrapper.find('[data-mailimage-missing]').text()).toContain('no longer in the library') + }) + + it('shows empty copy when no image is chosen', async () => { + const wrapper = mount(MailImageField, { + props: { + field: { name: 'logo', label: 'Logo', type: 'mailimage' } as FormField, + modelValue: null, + controlId: 'f-logo', + }, + attachTo: document.body, + }) + await flushPromises() + expect(wrapper.text()).toContain('No image chosen') + expect(wrapper.find('[data-mailimage-missing]').exists()).toBe(false) + }) +}) diff --git a/admin/tests/form/MailImagePicker.test.ts b/admin/tests/form/MailImagePicker.test.ts new file mode 100644 index 00000000..7511e0d7 --- /dev/null +++ b/admin/tests/form/MailImagePicker.test.ts @@ -0,0 +1,128 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils' +import { setBundle } from '../../src/app/i18n' +import MailImagePicker from '../../src/components/mail/MailImagePicker.vue' +import { langFixture } from '../fixtures/typed' +import { API, mockApi, resetState, type Reply } from '../helpers' + +const bundle = { + ...langFixture.data, + 'backend::lang.mail.picker.insert_button': { other: 'Insert image' }, + 'backend::lang.mail.picker.insert_title': { other: 'Insert an image from the library' }, + 'backend::lang.mail.picker.choose_title': { other: 'Choose an image' }, + 'backend::lang.mail.picker.search': { other: 'Search images' }, + 'backend::lang.mail.picker.insert': { other: 'Insert image' }, + 'backend::lang.mail.picker.use': { other: 'Use this image' }, + 'backend::lang.mail.picker.upload': { other: 'Upload image' }, + 'backend::lang.mail.picker.uploading': { other: 'Uploading…' }, + 'backend::lang.mail.picker.empty_title': { other: 'No images yet' }, + 'backend::lang.mail.picker.empty_upload': { other: 'Upload an image to use it in mail.' }, + 'backend::lang.mail.picker.empty_pick_only': { other: 'Images are added in Settings.' }, + 'backend::lang.mail.picker.no_results': { other: 'No images match “:query”.' }, + 'backend::lang.mail.picker.load_failed': { other: 'The image library could not be loaded.' }, + 'backend::lang.mail.picker.alt': { other: 'Alternative text' }, + 'backend::lang.mail.picker.alt_comment': { other: 'Describes the image.' }, + 'backend::lang.form.cancel': { other: 'Cancel' }, +} + +function listReply(opts: { + canUpload?: boolean + data?: unknown[] + status?: number + message?: string +} = {}): Reply { + if (opts.status && opts.status >= 400) { + return { + status: opts.status, + body: { error: { code: 'x', message: opts.message ?? 'failed', details: {} } }, + } + } + return { + body: { + data: opts.data ?? [], + meta: { canUpload: opts.canUpload ?? false, total: (opts.data ?? []).length, page: 1, perPage: 40 }, + }, + } +} + +beforeEach(() => { + resetState() + setBundle(bundle, 'en') +}) + +afterEach(() => { + document.body.innerHTML = '' +}) + +enableAutoUnmount(afterEach) + +async function openPicker(mode: 'insert' | 'choose') { + const wrapper = mount(MailImagePicker, { + props: { open: false, mode }, + attachTo: document.body, + }) + await flushPromises() + await wrapper.setProps({ open: true }) + await flushPromises() + return wrapper +} + +describe('MailImagePicker', () => { + it('shows the upload row only when meta.canUpload is true', async () => { + mockApi({ [`GET ${API}/mail/images`]: listReply({ canUpload: false }) }) + const wrapper = await openPicker('insert') + expect(document.querySelector('[data-mail-image-upload]')).toBeNull() + expect(document.body.textContent).toContain('Images are added in Settings.') + + mockApi({ [`GET ${API}/mail/images`]: listReply({ canUpload: true }) }) + await wrapper.setProps({ open: false }) + await flushPromises() + await wrapper.setProps({ open: true }) + await flushPromises() + expect(document.querySelector('[data-mail-image-upload]')).not.toBeNull() + expect(document.body.textContent).toContain('Upload an image to use it in mail.') + }) + + it('shows load failed copy when the library request fails', async () => { + mockApi({ [`GET ${API}/mail/images`]: listReply({ status: 500, message: 'boom' }) }) + await openPicker('choose') + expect(document.querySelector('[data-mail-image-load-failed]')?.textContent).toContain( + 'The image library could not be loaded.', + ) + }) + + it('disables primary until a tile is chosen; insert prefills alt from title', async () => { + mockApi({ + [`GET ${API}/mail/images`]: listReply({ + canUpload: false, + data: [{ id: 9, fileName: 'logo.png', title: 'Logo', url: 'https://cdn.example.com/logo.png' }], + }), + }) + const wrapper = await openPicker('insert') + const confirm = document.querySelector('[data-mail-image-confirm]') + expect(confirm?.disabled).toBe(true) + document.querySelector('[data-mail-image-id="9"]')!.click() + await flushPromises() + expect(confirm?.disabled).toBe(false) + const alt = document.querySelector('[data-mail-image-alt]') + expect(alt?.value).toBe('Logo') + confirm!.click() + await flushPromises() + expect(wrapper.emitted('insert')?.at(-1)).toEqual([{ url: 'https://cdn.example.com/logo.png', alt: 'Logo' }]) + }) + + it('choose mode emits the id and has no alt field', async () => { + mockApi({ + [`GET ${API}/mail/images`]: listReply({ + data: [{ id: 4, fileName: 'a.png', title: 'A', url: 'https://cdn.example.com/a.png' }], + }), + }) + const wrapper = await openPicker('choose') + expect(document.querySelector('[data-mail-image-alt]')).toBeNull() + document.querySelector('[data-mail-image-id="4"]')!.click() + await flushPromises() + document.querySelector('[data-mail-image-confirm]')!.click() + await flushPromises() + expect(wrapper.emitted('choose')?.at(-1)).toEqual([4]) + }) +}) diff --git a/admin/tests/form/MailPreviewField.test.ts b/admin/tests/form/MailPreviewField.test.ts new file mode 100644 index 00000000..67f0d0d0 --- /dev/null +++ b/admin/tests/form/MailPreviewField.test.ts @@ -0,0 +1,237 @@ +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 PREVIEW = `${API}/mail/preview` +const TEST_SEND = `${API}/mail/test-send` + +const bundle = { + ...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.', + }, +} + +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(bundle, 'en') + clearToasts() + setCurrentUser(profile.data) +}) + +afterEach(() => { + vi.useRealTimers() + document.body.innerHTML = '' + clearToasts() +}) + +enableAutoUnmount(afterEach) + +describe('MailPreviewField', () => { + it('uses an empty sandbox and srcdoc only, never src', async () => { + mockApi({ [`POST ${PREVIEW}`]: okPreview('

Rendered

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

Rendered

') + }) + + 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

') + }) + + it('shows failed_first when the first render fails', async () => { + mockApi({ + [`POST ${PREVIEW}`]: { + status: 422, + body: { + error: { + code: 'validation_failed', + message: 'Validation failed', + details: { field: 'body', rule: 'parse', message: 'unclosed' }, + }, + }, + }, + }) + const wrapper = mountPreview({ body: 'bad' }) + await flushPromises() + expect(wrapper.find('[data-mail-preview-error]').text()).toContain('unclosed') + expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc') ?? '').toBe('') + }) + + it('shows unavailable on a 5xx preview', async () => { + mockApi({ + [`POST ${PREVIEW}`]: { status: 503, body: { error: { code: 'x', message: 'down', details: {} } } }, + }) + const wrapper = mountPreview({ body: 'hi' }) + await flushPromises() + expect(wrapper.find('[data-mail-preview-error]').text()).toContain('Preview unavailable') + }) + + it('sends nothing for an empty draft or when the preview is off-screen', async () => { + const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview() }) + mountPreview({ body: ' ' }) + await flushPromises() + expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(0) + + const callbacks: IntersectionObserverCallback[] = [] + const Original = globalThis.IntersectionObserver + globalThis.IntersectionObserver = class { + constructor(cb: IntersectionObserverCallback) { + callbacks.push(cb) + } + observe() { + callbacks.at(-1)?.( + [{ isIntersecting: false, target: document.body } as unknown as IntersectionObserverEntry], + this as unknown as IntersectionObserver, + ) + } + unobserve() {} + disconnect() {} + takeRecords() { + return [] + } + root = null + rootMargin = '' + thresholds = [] + } as typeof IntersectionObserver + + const calls2 = mockApi({ [`POST ${PREVIEW}`]: okPreview() }) + mountPreview({ body: 'visible draft' }) + await flushPromises() + expect(requestsTo(calls2, 'POST', PREVIEW)).toHaveLength(0) + globalThis.IntersectionObserver = Original + }) + + it('branding mode has no subject row and no test send', async () => { + mockApi({ [`POST ${PREVIEW}`]: okPreview('', '', '') }) + const wrapper = mountPreview({ button_primary_bg: '#112233' }, previewField('branding'), null) + await flushPromises() + expect(wrapper.find('[data-mail-preview-subject]').exists()).toBe(false) + expect(wrapper.find('[data-mail-preview-test-send]').exists()).toBe(false) + }) + + it('toasts on 2xx test send; disables after 429; shows 422 inline', 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') + + mockApi({ + [`POST ${PREVIEW}`]: okPreview(), + [`POST ${TEST_SEND}`]: { + status: 429, + headers: { 'Retry-After': '30' }, + body: { error: { code: 'rate_limited', message: 'Too many', details: {} } }, + }, + }) + const limited = mountPreview({ body: 'hi' }) + await flushPromises() + await limited.find('[data-mail-preview-test-send]').trigger('click') + await flushPromises() + expect(limited.find('[data-mail-preview-test-send]').attributes('disabled')).toBeDefined() + expect(limited.find('[data-mail-preview-test-error]').text()).toContain('30') + + mockApi({ + [`POST ${PREVIEW}`]: okPreview(), + [`POST ${TEST_SEND}`]: { + status: 422, + body: { + error: { + code: 'validation_failed', + message: 'Validation failed', + details: { field: 'body', rule: 'unsafe', message: 'script' }, + }, + }, + }, + }) + const invalid = mountPreview({ body: 'hi' }) + await flushPromises() + await invalid.find('[data-mail-preview-test-send]').trigger('click') + await flushPromises() + expect(invalid.find('[data-mail-preview-test-error]').text()).toContain('script') + }) +}) diff --git a/admin/tests/form/insertImage.test.ts b/admin/tests/form/insertImage.test.ts new file mode 100644 index 00000000..62c312a4 --- /dev/null +++ b/admin/tests/form/insertImage.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { insertImage } from '../../src/components/mail/insertImage' + +describe('insertImage (UI-SPEC C4)', () => { + it.each([ + [ + 'markdown', + 'https://cdn.example.com/a b(c).png', + 'Logo [x]', + '![Logo \\[x\\]](https://cdn.example.com/a%20b%28c%29.png)', + ], + [ + 'html', + 'https://cdn.example.com/a"b.png', + 'a "b" ', + 'a "b" <c>', + ], + ['css', 'https://cdn.example.com/a.png', 'ignored', 'url("https://cdn.example.com/a.png")'], + ['text', 'https://cdn.example.com/a.png', 'ignored', 'https://cdn.example.com/a.png'], + ] as const)('builds %s snippets with escaping', (language, url, alt, want) => { + expect(insertImage(language, url, alt)).toBe(want) + }) + + it('handles empty alt and parentheses in markdown URLs', () => { + expect(insertImage('markdown', 'https://cdn.example.com/x(y).png', '')).toBe( + '![](https://cdn.example.com/x%28y%29.png)', + ) + expect(insertImage('html', 'https://cdn.example.com/x.png', '')).toBe( + '', + ) + }) +}) diff --git a/admin/tests/form/registry.test.ts b/admin/tests/form/registry.test.ts index af54a34b..6a8be7fe 100644 --- a/admin/tests/form/registry.test.ts +++ b/admin/tests/form/registry.test.ts @@ -59,7 +59,9 @@ describe('field renderer registry (D-05)', () => { expect(isRegistered('codeeditor')).toBe(true) expect(needsRecord('codeeditor')).toBe(false) expect(rendererFor('codeeditor')).not.toBe(UnsupportedField) - expect(rendererFor('codeeditor').__name).toBe('CodeEditorField') + expect((rendererFor('codeeditor') as { name?: string; __name?: string }).name ?? (rendererFor('codeeditor') as { __name?: string }).__name).toBe( + 'CodeEditorField', + ) }) it.each(['notatype', '', 'TEXT', 'constructor'])('falls back to UnsupportedField for %j', (type) => { diff --git a/admin/tests/list/RowStateBadges.test.ts b/admin/tests/list/RowStateBadges.test.ts index 38b9258e..e2370448 100644 --- a/admin/tests/list/RowStateBadges.test.ts +++ b/admin/tests/list/RowStateBadges.test.ts @@ -4,7 +4,13 @@ import { describe, expect, it } from 'vitest' import { mount } from '@vue/test-utils' import RowStateBadges from '../../src/components/list/RowStateBadges.vue' -const labels = { deleted: 'Deleted', negative: 'Blocked', disabled: 'Not active' } +const labels = { + deleted: 'Deleted', + negative: 'Blocked', + disabled: 'Not active', + customized: 'Customized', + outdated: 'File changed', +} const badges = (states: readonly string[], use: Record = labels) => mount(RowStateBadges, { props: { states, labels: use } }) @@ -13,6 +19,8 @@ describe('row state badges (UI-SPEC S4, D-12)', () => { ['deleted', 'Deleted', ['border', 'border-border-strong', 'text-muted']], ['negative', 'Blocked', ['bg-danger-soft', 'text-danger']], ['disabled', 'Not active', ['bg-subtle', 'text-muted']], + ['customized', 'Customized', ['border', 'border-border-strong', 'text-text']], + ['outdated', 'File changed', ['bg-sel', 'text-text']], ])('renders %s as a text badge with its own classes', (state, text, classes) => { const wrapper = badges([state]) const all = wrapper.findAll('[data-row-state]') @@ -25,14 +33,20 @@ describe('row state badges (UI-SPEC S4, D-12)', () => { expect(all[0]!.classes()).not.toContain('line-through') }) - it('renders combined states in the fixed order deleted, negative, disabled', () => { + it('renders combined states in the fixed order deleted, negative, disabled, customized, outdated', () => { for (const input of [ - ['disabled', 'negative', 'deleted'], - ['negative', 'deleted', 'disabled'], - ['deleted', 'negative', 'disabled'], + ['outdated', 'customized', 'disabled', 'negative', 'deleted'], + ['customized', 'outdated', 'deleted', 'disabled', 'negative'], + ['deleted', 'negative', 'disabled', 'customized', 'outdated'], ]) { const wrapper = badges(input) - expect(wrapper.findAll('[data-row-state]').map((badge) => badge.attributes('data-row-state'))).toEqual(['deleted', 'negative', 'disabled']) + expect(wrapper.findAll('[data-row-state]').map((badge) => badge.attributes('data-row-state'))).toEqual([ + 'deleted', + 'negative', + 'disabled', + 'customized', + 'outdated', + ]) } expect(badges(['disabled', 'deleted']).findAll('[data-row-state]').map((badge) => badge.text())).toEqual(['Deleted', 'Not active']) }) diff --git a/admin/tests/views/SettingsFormView.test.ts b/admin/tests/views/SettingsFormView.test.ts index a4c59f3b..702e60ef 100644 --- a/admin/tests/views/SettingsFormView.test.ts +++ b/admin/tests/views/SettingsFormView.test.ts @@ -3,7 +3,10 @@ // appear in framework tests. import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { enableAutoUnmount, flushPromises, type VueWrapper } from '@vue/test-utils' +import { isRef, type Ref } from 'vue' import { setBundle } from '../../src/app/i18n' +import { FORM_LOCALE, FORM_VALUES } from '../../src/components/form/formContext' +import SettingsFormView from '../../src/views/SettingsFormView.vue' import { setSettings } from '../../src/state/useSettings' import { clone, langFixture, settingsFixture } from '../fixtures/typed' import { API, mountApp, requestsTo, resetState, type Reply, type Route } from '../helpers' @@ -68,6 +71,22 @@ afterEach(() => { enableAutoUnmount(afterEach) +describe('settings form context (Phase 35 mail branding)', () => { + it('provides FORM_VALUES and FORM_LOCALE to nested fields', async () => { + const { wrapper } = await openPage() + const view = wrapper.findComponent(SettingsFormView) + expect(view.exists()).toBe(true) + const provides = (view.vm.$ as { provides?: Record }).provides ?? {} + const values = provides[FORM_VALUES as symbol] as Ref> | undefined + const locale = provides[FORM_LOCALE as symbol] as Ref | undefined + expect(values && isRef(values)).toBe(true) + expect(locale && isRef(locale)).toBe(true) + expect(values!.value).toMatchObject({ use_engine: expect.anything() }) + expect(typeof locale!.value).toBe('string') + expect(locale!.value.length).toBeGreaterThan(0) + }) +}) + describe('settings tabs (UI-SPEC F4)', () => { it('renders no tab strip for an untabbed schema', async () => { const { wrapper } = await openPage({ [`GET ${PAGE}/schema`]: { body: settingsFixture.schema } }) diff --git a/scripts/check-phase35.sh b/scripts/check-phase35.sh index cb7a8d56..fde6e495 100755 --- a/scripts/check-phase35.sh +++ b/scripts/check-phase35.sh @@ -101,10 +101,24 @@ DOCKER_TESTS=( ) # admin stage: vitest files that must pass. -ADMIN_FILES=(tests/form/mail-smoke.test.ts) +ADMIN_FILES=( + tests/form/mail-smoke.test.ts + tests/form/CodeEditorField.test.ts + tests/form/MailPreviewField.test.ts + tests/form/insertImage.test.ts + tests/form/MailImagePicker.test.ts + tests/form/ColorPickerField.test.ts + tests/form/MailImageField.test.ts + tests/form/FormViewMail.test.ts + tests/list/RowStateBadges.test.ts + tests/views/SettingsFormView.test.ts +) # admin stage: browser vitest files that must pass. -ADMIN_BROWSER_FILES=(tests/browser/codeeditor-smoke.test.ts) +ADMIN_BROWSER_FILES=( + tests/browser/codeeditor-smoke.test.ts + tests/browser/codeeditor.test.ts +) # consumers: # sm-user-plugin and sm-paymentgateway-plugin mail tests.