feat(admin): colour picker, mail image field and the image picker with insert

- insertImage escapes markdown/html/css/text snippets per UI-SPEC C4
- MailImagePicker with canUpload-gated upload, radiogroup tiles, insert/choose modes
- ColorPickerField, MailImageField, markdown/codeeditor Insert image wiring

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-13 13:34:54 +01:00
parent 48e87b7543
commit 68e1d36fd5
8 changed files with 734 additions and 35 deletions

View File

@@ -1,7 +1,9 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import { Info } from '@lucide/vue'
import { ImagePlus, Info } from '@lucide/vue'
import { t } from '../../../app/i18n'
import MailImagePicker from '../../mail/MailImagePicker.vue'
import { insertImage } from '../../mail/insertImage'
import { controlClass, type FieldControlProps } from '../control'
import type { CodeEditorHandle, CodeEditorLanguage } from '../codeeditor/editor'
@@ -37,6 +39,7 @@ const status = ref<Status>('loading')
const fallbackText = ref('')
const mountEl = ref<HTMLElement | null>(null)
const editor = shallowRef<CodeEditorHandle | null>(null)
const pickerOpen = ref(false)
let module: EditorModule | null = null
let disposed = false
@@ -163,6 +166,10 @@ function insert(text: string): void {
}
}
function onInsert(payload: { url: string; alt: string }): void {
insert(insertImage(language.value, payload.url, payload.alt))
}
defineExpose({ insert })
</script>
@@ -207,9 +214,17 @@ defineExpose({ insert })
class="flex flex-wrap items-center gap-1 border-b border-border bg-subtle p-1"
data-codeeditor-toolbar
>
<!-- Insert image button wired in Task 5 -->
<slot name="toolbar" :insert="insert" />
<button
type="button"
data-codeeditor-insert-image
class="inline-flex h-8 items-center gap-1.5 rounded-pager px-2 text-[13px] text-muted transition-colors duration-150 ease-out hover:bg-hover hover:text-text"
@click="pickerOpen = true"
>
<ImagePlus :size="16" aria-hidden="true" />
{{ t('backend::lang.mail.picker.insert_button') }}
</button>
</div>
<div ref="mountEl" data-codeeditor-mount />
<MailImagePicker v-if="mailImages" v-model:open="pickerOpen" mode="insert" @insert="onInsert" />
</div>
</template>

View File

@@ -1,11 +1,63 @@
<script setup lang="ts">
// Stub for TDD RED (35-03 Task 5).
import type { FieldControlProps } from '../control'
import { computed, ref, watch } from 'vue'
import { t } from '../../../app/i18n'
import { controlClass, type FieldControlProps } from '../control'
defineProps<FieldControlProps>()
defineEmits<{ 'update:modelValue': [value: string] }>()
// type: colorpicker (UI-SPEC C2): native swatch plus #rrggbb text. The server
// validates; the client only syncs a full #rrggbb into the swatch.
const props = defineProps<FieldControlProps>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
const HEX = /^#[0-9a-fA-F]{6}$/
const text = computed(() => (props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue)))
const lastValid = ref(HEX.test(text.value) ? text.value.toLowerCase() : '#ffffff')
watch(text, (value) => {
if (HEX.test(value)) {
lastValid.value = value.toLowerCase()
}
})
const swatch = computed(() => (HEX.test(text.value) ? text.value.toLowerCase() : lastValid.value))
function onSwatch(event: Event): void {
const value = (event.target as HTMLInputElement).value
lastValid.value = value.toLowerCase()
emit('update:modelValue', value)
}
function onText(event: Event): void {
const value = (event.target as HTMLInputElement).value
if (HEX.test(value)) {
lastValid.value = value.toLowerCase()
}
emit('update:modelValue', value)
}
</script>
<template>
<div data-colorpicker-stub />
<div class="flex items-center gap-2" data-colorpicker>
<input
type="color"
data-colorpicker-swatch
:value="swatch"
:aria-label="t('backend::lang.colorpicker.pick', { field: field.label ?? field.name })"
class="size-input shrink-0 cursor-pointer rounded-control border border-border-strong bg-surface p-1"
@input="onSwatch"
/>
<input
:id="controlId"
type="text"
data-colorpicker-text
:value="text"
maxlength="7"
spellcheck="false"
:placeholder="t('backend::lang.colorpicker.not_set')"
:aria-describedby="describedBy || undefined"
:aria-invalid="invalid ? 'true' : undefined"
:class="[controlClass(invalid), 'h-input font-mono text-[13px]']"
@input="onText"
/>
</div>
</template>

View File

@@ -0,0 +1,94 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Image } from '@lucide/vue'
import { api } from '../../../api/client'
import type { AdminMailImage } from '../../../api/types'
import { t } from '../../../app/i18n'
import MailImagePicker from '../../mail/MailImagePicker.vue'
import Button from '../../ui/Button.vue'
import type { FieldControlProps } from '../control'
// type: mailimage (UI-SPEC C11): library image id or null for branding logo.
const props = defineProps<FieldControlProps>()
const emit = defineEmits<{ 'update:modelValue': [value: number | null] }>()
const pickerOpen = ref(false)
const image = ref<AdminMailImage | null>(null)
const missing = ref(false)
const loading = ref(false)
const id = computed(() => {
const value = props.modelValue
if (value === null || value === undefined || value === '') {
return null
}
const n = Number(value)
return Number.isInteger(n) && n > 0 ? n : null
})
async function load(): Promise<void> {
const current = id.value
if (current === null) {
image.value = null
missing.value = false
return
}
loading.value = true
missing.value = false
try {
const { data, response } = await api.GET('/mail/images/{id}', { params: { path: { id: current } } })
if (data) {
image.value = data.data
missing.value = false
} else {
image.value = null
missing.value = response.status === 404
}
} catch {
image.value = null
missing.value = true
} finally {
loading.value = false
}
}
watch(id, () => {
void load()
}, { immediate: true })
function onChoose(chosenId: number): void {
emit('update:modelValue', chosenId)
}
function onRemove(): void {
emit('update:modelValue', null)
}
</script>
<template>
<div class="flex items-center gap-4" data-mailimage>
<div class="flex size-[96px] shrink-0 items-center justify-center overflow-hidden rounded-inner border border-border bg-subtle">
<img
v-if="image"
:src="image.thumbUrl || image.url"
:alt="image.title || image.fileName"
class="size-full object-contain"
/>
<Image v-else :size="24" class="text-muted" aria-hidden="true" />
</div>
<div class="flex flex-col gap-2">
<p v-if="image" class="text-[14px]">{{ image.fileName }}</p>
<p v-else class="text-[13px] text-muted">{{ t('backend::lang.mailimage.empty') }}</p>
<div class="flex gap-2">
<Button variant="outline" size="sm" data-mailimage-choose @click="pickerOpen = true">
{{ image ? t('backend::lang.mailimage.change') : t('backend::lang.mailimage.choose') }}
</Button>
<Button v-if="image || id !== null" variant="ghost" size="sm" data-mailimage-remove @click="onRemove">
{{ t('backend::lang.mailimage.remove') }}
</Button>
</div>
<p v-if="missing" data-mailimage-missing class="text-[13px] text-danger">{{ t('backend::lang.mailimage.missing') }}</p>
</div>
<MailImagePicker v-model:open="pickerOpen" mode="choose" @choose="onChoose" />
</div>
</template>

View File

@@ -1,6 +1,10 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { ImagePlus } from '@lucide/vue'
import { api } from '../../../api/client'
import { t } from '../../../app/i18n'
import MailImagePicker from '../../mail/MailImagePicker.vue'
import { insertImage } from '../../mail/insertImage'
import { controlAttributes, controlClass, type FieldControlProps } from '../control'
// Source editor for type: markdown (and, through MLMarkdownField, for the
@@ -10,6 +14,7 @@ import { controlAttributes, controlClass, type FieldControlProps } from '../cont
// 422 and is shown as a text notice. The pane's raw-HTML binding reads
// sanitizedHtml, which is assigned only from a 2xx answer's data.html; the
// markdown source is never bound as HTML.
// Phase 35: mailImages replaces the Preview toggle with Insert image (C3).
const props = defineProps<FieldControlProps>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
@@ -20,10 +25,13 @@ const rowsBySize: Record<string, number> = { tiny: 2, small: 4, large: 8, huge:
const rows = computed(() => rowsBySize[props.field.size ?? ''] ?? 8)
const text = computed(() => (props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue)))
const attrs = computed(() => controlAttributes(props.field))
const mailImages = computed(() => !!props.field.mailImages)
const preview = ref(false)
const sanitizedHtml = ref('')
const previewError = ref('')
const loading = ref(false)
const pickerOpen = ref(false)
const area = ref<HTMLTextAreaElement | null>(null)
let sequence = 0
let previewTimer: ReturnType<typeof setTimeout> | null = null
@@ -84,12 +92,29 @@ function togglePreview() {
if (preview.value) {
void renderPreview()
} else {
// Drop any answer still in flight for the closed pane.
sequence++
loading.value = false
}
}
function onInsert(payload: { url: string; alt: string }): void {
const snippet = insertImage('markdown', payload.url, payload.alt)
const el = area.value
const current = text.value
const start = el?.selectionStart ?? current.length
const end = el?.selectionEnd ?? start
const next = current.slice(0, start) + snippet + current.slice(end)
emit('update:modelValue', next)
void nextTick(() => {
if (!el) {
return
}
el.focus()
const caret = start + snippet.length
el.setSelectionRange(caret, caret)
})
}
watch(text, () => {
if (!preview.value) {
return
@@ -109,16 +134,29 @@ onBeforeUnmount(() => {
<template>
<div class="flex flex-col gap-1.5">
<button
type="button"
data-markdown-preview
class="self-start rounded-pager px-2 py-1 text-[13px] text-muted hover:bg-hover hover:text-text"
:aria-pressed="preview ? 'true' : 'false'"
@click="togglePreview"
>
Preview
</button>
<div v-if="preview" class="flex flex-col gap-1.5">
<div class="flex items-center gap-2">
<button
v-if="mailImages"
type="button"
data-markdown-insert-image
class="inline-flex h-8 items-center gap-1.5 rounded-pager px-2 text-[13px] text-muted transition-colors duration-150 ease-out hover:bg-hover hover:text-text"
@click="pickerOpen = true"
>
<ImagePlus :size="16" aria-hidden="true" />
{{ t('backend::lang.mail.picker.insert_button') }}
</button>
<button
v-else
type="button"
data-markdown-preview
class="self-start rounded-pager px-2 py-1 text-[13px] text-muted hover:bg-hover hover:text-text"
:aria-pressed="preview ? 'true' : 'false'"
@click="togglePreview"
>
Preview
</button>
</div>
<div v-if="preview && !mailImages" class="flex flex-col gap-1.5">
<p v-if="previewError" data-markdown-preview-error role="status" class="text-[13px] text-danger">{{ previewError }}</p>
<div
data-markdown-preview-pane
@@ -131,6 +169,7 @@ onBeforeUnmount(() => {
<textarea
v-else
:id="controlId"
ref="area"
v-bind="attrs"
:name="field.name"
:rows="rows"
@@ -143,5 +182,6 @@ onBeforeUnmount(() => {
class="min-h-input resize-y py-2.5"
@input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
/>
<MailImagePicker v-if="mailImages" v-model:open="pickerOpen" mode="insert" @insert="onInsert" />
</div>
</template>

View File

@@ -58,6 +58,8 @@ import TextareaField from './fields/TextareaField.vue'
import MarkdownField from './fields/MarkdownField.vue'
import MailPreviewField from './fields/MailPreviewField.vue'
import CodeEditorField from './fields/CodeEditorField.vue'
import ColorPickerField from './fields/ColorPickerField.vue'
import MailImageField from './fields/MailImageField.vue'
import MoneyField from './fields/MoneyField.vue'
import TaglistField from './fields/TaglistField.vue'
import MLTextField from './fields/MLTextField.vue'
@@ -105,6 +107,8 @@ const renderers = new Map<string, Component>([
['taglist', TaglistField],
['mailpreview', MailPreviewField],
['codeeditor', CodeEditorField],
['colorpicker', ColorPickerField],
['mailimage', MailImageField],
])
/** Types whose control shows the label itself (toggle cards, relation manager). */
@@ -134,6 +138,7 @@ const groupLabelledTypes = new Set<string>([
'mlmarkdown',
'repeater',
'mailpreview',
'mailimage',
])
export function rendererFor(type: string): Component {

View File

@@ -0,0 +1,357 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import {
DialogClose,
DialogContent,
DialogOverlay,
DialogPortal,
DialogRoot,
DialogTitle,
} from 'reka-ui'
import { Check, Search, Upload, X } from '@lucide/vue'
import { api } from '../../api/client'
import type { AdminMailImage, AdminMailImagesMeta } from '../../api/types'
import { t } from '../../app/i18n'
import Button from '../ui/Button.vue'
// Mail image library picker (UI-SPEC C4): insert mode returns {url, alt};
// choose mode returns the image id. Upload shows only when meta.canUpload.
const props = defineProps<{
open: boolean
mode: 'insert' | 'choose'
}>()
const emit = defineEmits<{
'update:open': [open: boolean]
insert: [payload: { url: string; alt: string }]
choose: [id: number]
}>()
const SEARCH_DEBOUNCE = 300
const search = ref('')
const images = ref<AdminMailImage[]>([])
const meta = ref<AdminMailImagesMeta | null>(null)
const loading = ref(false)
const loadFailed = ref(false)
const loadFailedMessage = ref('')
const uploading = ref(false)
const uploadError = ref('')
const chosen = ref<AdminMailImage | null>(null)
const alt = ref('')
const fileInput = ref<HTMLInputElement | null>(null)
const grid = ref<HTMLElement | null>(null)
let searchTimer: ReturnType<typeof setTimeout> | null = null
let generation = 0
const title = computed(() =>
props.mode === 'insert' ? t('backend::lang.mail.picker.insert_title') : t('backend::lang.mail.picker.choose_title'),
)
const primaryLabel = computed(() =>
props.mode === 'insert' ? t('backend::lang.mail.picker.insert') : t('backend::lang.mail.picker.use'),
)
const canUpload = computed(() => meta.value?.canUpload === true)
const empty = computed(() => !loading.value && !loadFailed.value && images.value.length === 0 && search.value.trim() === '')
const noResults = computed(() => !loading.value && !loadFailed.value && images.value.length === 0 && search.value.trim() !== '')
const hasMore = computed(() => {
if (!meta.value) {
return false
}
return images.value.length < meta.value.total
})
function setOpen(open: boolean): void {
emit('update:open', open)
}
function reset(): void {
search.value = ''
images.value = []
meta.value = null
loading.value = false
loadFailed.value = false
loadFailedMessage.value = ''
uploading.value = false
uploadError.value = ''
chosen.value = null
alt.value = ''
generation++
}
async function load(page: number, append: boolean): Promise<void> {
const current = ++generation
loading.value = true
loadFailed.value = false
loadFailedMessage.value = ''
try {
const { data, error, response } = await api.GET('/mail/images', {
params: { query: { q: search.value.trim() || undefined, page } },
})
if (current !== generation) {
return
}
if (!data) {
loadFailed.value = true
const message =
(error as { error?: { message?: string } } | undefined)?.error?.message ??
t('backend::lang.mail.picker.load_failed')
loadFailedMessage.value = response.status === 409 ? message : t('backend::lang.mail.picker.load_failed')
if (!append) {
images.value = []
meta.value = null
}
return
}
images.value = append ? [...images.value, ...data.data] : data.data
meta.value = data.meta
} catch {
if (current !== generation) {
return
}
loadFailed.value = true
loadFailedMessage.value = t('backend::lang.mail.picker.load_failed')
} finally {
if (current === generation) {
loading.value = false
}
}
}
function onSearch(event: Event): void {
search.value = (event.target as HTMLInputElement).value
if (searchTimer !== null) {
clearTimeout(searchTimer)
}
searchTimer = setTimeout(() => {
searchTimer = null
void load(1, false)
}, SEARCH_DEBOUNCE)
}
function select(image: AdminMailImage): void {
chosen.value = image
if (props.mode === 'insert') {
alt.value = image.title || ''
}
}
function onGridKeydown(event: KeyboardEvent): void {
if (!chosen.value || images.value.length === 0) {
return
}
const index = images.value.findIndex((image) => image.id === chosen.value!.id)
if (index < 0) {
return
}
let next = index
if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
next = Math.min(index + 1, images.value.length - 1)
} else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
next = Math.max(index - 1, 0)
} else {
return
}
event.preventDefault()
select(images.value[next]!)
}
function onScroll(event: Event): void {
const el = event.target as HTMLElement
if (!hasMore.value || loading.value) {
return
}
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 48) {
void load((meta.value?.page ?? 1) + 1, true)
}
}
async function onUpload(event: Event): Promise<void> {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) {
return
}
uploading.value = true
uploadError.value = ''
try {
const body = new FormData()
body.append('file', file)
const { data, error } = await api.POST('/mail/images', { body: body as never })
if (!data) {
const details = (error as { error?: { message?: string; details?: { message?: string } } } | undefined)?.error
uploadError.value = details?.details?.message || details?.message || t('backend::lang.mail.picker.load_failed')
return
}
images.value = [data.data, ...images.value.filter((image) => image.id !== data.data.id)]
if (meta.value) {
meta.value = { ...meta.value, total: meta.value.total + 1, canUpload: meta.value.canUpload }
}
select(data.data)
} catch {
uploadError.value = t('backend::lang.mail.picker.load_failed')
} finally {
uploading.value = false
}
}
function confirm(): void {
if (!chosen.value) {
return
}
if (props.mode === 'insert') {
emit('insert', { url: chosen.value.url, alt: alt.value })
} else {
emit('choose', chosen.value.id)
}
setOpen(false)
}
watch(
() => props.open,
(open) => {
if (open) {
reset()
void load(1, false)
void nextTick(() => grid.value?.focus())
} else if (searchTimer !== null) {
clearTimeout(searchTimer)
searchTimer = null
}
},
)
onBeforeUnmount(() => {
if (searchTimer !== null) {
clearTimeout(searchTimer)
}
generation++
})
</script>
<template>
<DialogRoot :open="open" @update:open="setOpen">
<DialogPortal>
<DialogOverlay class="fixed inset-0 z-40 bg-overlay" />
<DialogContent
data-mail-image-picker
class="fixed top-1/2 left-1/2 z-50 flex max-h-[calc(100vh-32px)] w-[calc(100%-32px)] max-w-[560px] -translate-x-1/2 -translate-y-1/2 flex-col gap-4 rounded-modal bg-surface p-6 text-text shadow-pop"
>
<div class="flex items-start justify-between gap-3">
<DialogTitle class="text-[20px] font-bold tracking-[-0.01em]">{{ title }}</DialogTitle>
<DialogClose
type="button"
class="flex size-[34px] shrink-0 items-center justify-center rounded-tab bg-subtle text-muted hover:bg-hover hover:text-text"
:aria-label="t('backend::lang.form.cancel')"
>
<X :size="16" aria-hidden="true" />
</DialogClose>
</div>
<label class="relative block">
<span class="sr-only">{{ t('backend::lang.mail.picker.search') }}</span>
<Search :size="18" class="pointer-events-none absolute top-1/2 left-3.5 -translate-y-1/2 text-muted" aria-hidden="true" />
<input
type="search"
data-mail-image-search
:value="search"
:placeholder="t('backend::lang.mail.picker.search')"
class="h-input w-full rounded-control border border-border-strong bg-surface pr-3.5 pl-10"
@input="onSearch"
/>
</label>
<div v-if="canUpload" class="flex flex-col gap-1.5">
<input
ref="fileInput"
type="file"
class="sr-only"
accept="image/jpeg,image/png,image/gif,image/webp"
@change="onUpload"
/>
<Button
variant="outline"
size="sm"
data-mail-image-upload
:disabled="uploading"
:icon="Upload"
@click="fileInput?.click()"
>
{{ uploading ? t('backend::lang.mail.picker.uploading') : t('backend::lang.mail.picker.upload') }}
</Button>
<p v-if="uploadError" role="alert" data-mail-image-upload-error class="text-[13px] text-danger">{{ uploadError }}</p>
</div>
<div
ref="grid"
role="radiogroup"
:aria-label="title"
tabindex="0"
data-mail-image-grid
class="grid min-h-0 grid-cols-4 gap-2 overflow-y-auto"
@keydown="onGridKeydown"
@scroll="onScroll"
>
<template v-if="loading && images.length === 0">
<div v-for="n in 12" :key="n" class="aspect-square rounded-inner bg-skel" aria-hidden="true" />
</template>
<p v-else-if="loadFailed" role="alert" data-mail-image-load-failed class="col-span-4 text-[13px] text-danger">
{{ loadFailedMessage }}
</p>
<div v-else-if="empty" class="col-span-4 flex flex-col items-center gap-1 px-2 py-6 text-center">
<p class="text-[14px] font-semibold">{{ t('backend::lang.mail.picker.empty_title') }}</p>
<p class="text-[13px] text-muted">
{{ canUpload ? t('backend::lang.mail.picker.empty_upload') : t('backend::lang.mail.picker.empty_pick_only') }}
</p>
</div>
<p v-else-if="noResults" data-mail-image-no-results class="col-span-4 px-2 py-6 text-center text-[13px] text-muted">
{{ t('backend::lang.mail.picker.no_results', { query: search.trim() }) }}
</p>
<button
v-for="image in images"
:key="image.id"
type="button"
role="radio"
:aria-checked="chosen?.id === image.id ? 'true' : 'false'"
:data-mail-image-id="image.id"
:class="
chosen?.id === image.id
? 'border-[#e0b020] bg-sel'
: 'border-border hover:bg-hover'
"
class="relative flex flex-col gap-1 rounded-inner border p-1 text-left transition-colors duration-150 ease-out"
@click="select(image)"
>
<span class="relative block aspect-square w-full overflow-hidden rounded-pager bg-subtle">
<img :src="image.thumbUrl || image.url" :alt="image.title || image.fileName" class="size-full object-cover" />
<span
v-if="chosen?.id === image.id"
class="absolute top-1 right-1 flex size-5 items-center justify-center rounded-full bg-primary text-on-primary"
aria-hidden="true"
>
<Check :size="14" />
</span>
</span>
<span class="truncate text-[13px] text-muted">{{ image.fileName }}</span>
</button>
</div>
<div v-if="mode === 'insert' && chosen" class="flex flex-col gap-1.5">
<label class="text-[13px] font-semibold" for="mail-image-alt">{{ t('backend::lang.mail.picker.alt') }}</label>
<p class="text-[13px] text-muted">{{ t('backend::lang.mail.picker.alt_comment') }}</p>
<input
id="mail-image-alt"
v-model="alt"
type="text"
data-mail-image-alt
class="h-input w-full rounded-control border border-border-strong bg-surface px-3.5"
/>
</div>
<div class="flex justify-end gap-2.5">
<Button variant="ghost" data-mail-image-cancel @click="setOpen(false)">{{ t('backend::lang.form.cancel') }}</Button>
<Button variant="primary" data-mail-image-confirm :disabled="!chosen" @click="confirm">{{ primaryLabel }}</Button>
</div>
</DialogContent>
</DialogPortal>
</DialogRoot>
</template>

View File

@@ -1,7 +1,34 @@
// Stub for TDD RED (35-03 Task 5): real escaping lands in GREEN.
// Pure snippet builder for mail image insertion (UI-SPEC C4, D-19/D-20).
// The SPA never builds image URLs; callers pass the absolute URL the server returned.
export type InsertImageLanguage = 'markdown' | 'html' | 'css' | 'text'
/** Builds the snippet inserted into a mail body or code editor. */
export function insertImage(_language: InsertImageLanguage, _url: string, _alt: string): string {
return ''
function escapeMarkdownAlt(alt: string): string {
return alt.replace(/\\/g, '\\\\').replace(/\[/g, '\\[').replace(/\]/g, '\\]')
}
/** Percent-encode spaces and parentheses in Markdown URLs (research Pitfall 4). */
function encodeMarkdownUrl(url: string): string {
return url.replace(/[ ()]/g, (ch) => encodeURIComponent(ch))
}
function escapeHtmlAttr(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
/** Builds the snippet inserted into a mail body or code editor. */
export function insertImage(language: InsertImageLanguage, url: string, alt: string): string {
switch (language) {
case 'markdown':
return `![${escapeMarkdownAlt(alt)}](${encodeMarkdownUrl(url)})`
case 'html':
return `<img src="${escapeHtmlAttr(url)}" alt="${escapeHtmlAttr(alt)}">`
case 'css':
return `url("${url.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}")`
case 'text':
return url
}
}

View File

@@ -298,17 +298,38 @@ describe('insertImage', () => {
})
})
const pickerBundle = {
...mailPreviewBundle,
...codeeditorBundle,
'backend::lang.colorpicker.pick': { other: 'Pick a colour for “:field”' },
'backend::lang.colorpicker.not_set': { other: 'Not set' },
'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.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.form.cancel': { other: 'Cancel' },
}
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',
)
setBundle(pickerBundle, 'en')
const wrapper = mount(Field, {
props: {
field: { name: 'body_bg', label: 'Body background', type: 'colorpicker' } as FormField,
@@ -328,17 +349,105 @@ describe('ColorPickerField', () => {
})
})
describe('MailImagePicker and MarkdownField mailImages', () => {
beforeEach(() => {
setBundle(pickerBundle, 'en')
})
it('shows the upload row only when meta.canUpload is true', async () => {
const Picker = (await import('../../src/components/mail/MailImagePicker.vue')).default
mockApi({
[`GET ${API}/mail/images`]: {
body: { data: [], meta: { canUpload: false, total: 0, page: 1, perPage: 40 } },
},
})
const wrapper = mount(Picker, {
props: { open: true, mode: 'insert' },
attachTo: document.body,
})
await flushPromises()
expect(document.querySelector('[data-mail-image-upload]')).toBeNull()
mockApi({
[`GET ${API}/mail/images`]: {
body: { data: [], meta: { canUpload: true, total: 0, page: 1, perPage: 40 } },
},
})
await wrapper.setProps({ open: false })
await flushPromises()
await wrapper.setProps({ open: true })
await flushPromises()
expect(document.querySelector('[data-mail-image-upload]')).not.toBeNull()
})
it('hides Preview and inserts markdown at the caret when mailImages is set', async () => {
const Field = (await import('../../src/components/form/fields/MarkdownField.vue')).default
mockApi({
[`GET ${API}/mail/images`]: {
body: {
data: [{ id: 9, fileName: 'logo.png', title: 'Logo', url: 'https://cdn.example.com/logo.png' }],
meta: { canUpload: false, total: 1, page: 1, perPage: 40 },
},
},
})
const wrapper = mount(Field, {
props: {
field: { name: 'body', label: 'Body', type: 'markdown', mailImages: true } as FormField,
modelValue: 'Hello ',
controlId: 'f-body',
},
attachTo: document.body,
})
expect(wrapper.find('[data-markdown-preview]').exists()).toBe(false)
expect(wrapper.find('[data-markdown-insert-image]').exists()).toBe(true)
await wrapper.find('[data-markdown-insert-image]').trigger('click')
await flushPromises()
const tile = document.querySelector<HTMLElement>('[data-mail-image-id="9"]')
expect(tile).not.toBeNull()
tile!.click()
await flushPromises()
document.querySelector<HTMLElement>('[data-mail-image-confirm]')!.click()
await flushPromises()
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['Hello ![Logo](https://cdn.example.com/logo.png)'])
})
})
describe('MailImageField', () => {
it('shows the missing line when the stored id is gone', async () => {
;(await import('../../src/app/i18n')).setBundle(pickerBundle, 'en')
const Field = (await import('../../src/components/form/fields/MailImageField.vue')).default
mockApi({
[`GET ${API}/mail/images/3`]: { status: 404, body: { error: { code: 'not_found', message: 'gone', details: {} } } },
})
const wrapper = mount(Field, {
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')
})
})
// 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')
vi.resetModules()
})
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')
})
vi.unmock('../../src/components/form/codeeditor/editor')
vi.doMock('../../src/components/form/codeeditor/editor', () => ({
createCodeEditor: () => {
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, {