feat(admin): codeeditor field on CodeMirror 6, loaded lazily

- Pin the seven approved CodeMirror/lezer packages exactly; lockfile integrity matches the decision note
- Lazy createCodeEditor with Go {{ }} highlighting, form hotkeys kept, Tab unbound
- Loading skeleton, chunk-failure textarea fallback, read-only pre

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-13 13:28:02 +01:00
parent 7e2c01172f
commit 9975cf4b52
6 changed files with 597 additions and 26 deletions

View File

@@ -1,21 +1,170 @@
// Stub for TDD RED (35-03 Task 4): real CodeMirror factory lands in GREEN.
// CodeMirror 6 setup for the codeeditor field (Phase 35, D-09). CodeEditorField
// loads this module with a dynamic import, so CodeMirror is its own chunk and a
// form without a codeeditor never downloads it. Decision note:
// .planning/notes/2026-11-06-admin-code-editor-codemirror.md
import { EditorState } from '@codemirror/state'
import {
EditorView,
keymap,
lineNumbers,
Decoration,
MatchDecorator,
ViewPlugin,
type ViewUpdate,
} from '@codemirror/view'
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands'
import { bracketMatching, HighlightStyle, syntaxHighlighting } from '@codemirror/language'
import { html } from '@codemirror/lang-html'
import { css } from '@codemirror/lang-css'
import { tags } from '@lezer/highlight'
export type CodeEditorLanguage = 'html' | 'css' | 'text'
export interface CodeEditorOptions {
parent: HTMLElement
doc: string
language: 'html' | 'css' | 'text'
language: CodeEditorLanguage
height: number
attributes: Record<string, string>
onChange: (doc: string) => void
}
export interface CodeEditorHandle {
view: unknown
view: EditorView
insert(text: string): void
destroy(): void
setDoc(doc: string): void
}
/** Builds the field's CodeMirror editor on options.parent. */
export function createCodeEditor(_options: CodeEditorOptions): CodeEditorHandle {
throw new Error('codeeditor not implemented')
const actionMatcher = new MatchDecorator({
regexp: /\{\{[\s\S]*?\}\}/g,
decoration: () => Decoration.mark({ class: 'cm-summer-action' }),
})
const goActions = ViewPlugin.fromClass(
class {
decorations
constructor(view: EditorView) {
this.decorations = actionMatcher.createDeco(view)
}
update(update: ViewUpdate) {
this.decorations = actionMatcher.updateDeco(update, this.decorations)
}
},
{ decorations: (v) => v.decorations },
)
const syntaxColors = HighlightStyle.define([
{ tag: [tags.tagName, tags.propertyName, tags.keyword], color: 'var(--c-primary)', fontStyle: 'normal', fontWeight: '400' },
{ tag: [tags.string, tags.attributeValue], color: 'var(--c-ok-text)', fontStyle: 'normal', fontWeight: '400' },
{ tag: [tags.attributeName, tags.name, tags.variableName], color: 'var(--c-text)', fontStyle: 'normal', fontWeight: '400' },
{ tag: [tags.comment, tags.punctuation, tags.bracket, tags.paren], color: 'var(--c-muted)', fontStyle: 'normal', fontWeight: '400' },
])
function languageExtension(language: CodeEditorLanguage) {
if (language === 'html') {
return html()
}
if (language === 'css') {
return css()
}
return []
}
function theme(height: number) {
return EditorView.theme({
'&': {
height: `${height}px`,
fontFamily: 'var(--font-mono)',
fontSize: '13px',
lineHeight: '1.5',
color: 'var(--c-text)',
backgroundColor: 'var(--c-surface)',
},
'.cm-scroller': { overflow: 'auto', fontFamily: 'inherit' },
'.cm-content': {
padding: '10px 14px',
caretColor: 'var(--c-text)',
fontFamily: 'inherit',
},
'.cm-gutters': {
backgroundColor: 'var(--c-subtle)',
color: 'var(--c-muted)',
border: 'none',
},
'.cm-activeLine': { backgroundColor: 'var(--c-hover)' },
'.cm-activeLineGutter': { backgroundColor: 'var(--c-hover)' },
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': {
backgroundColor: 'var(--c-sel)',
},
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--c-text)' },
'.cm-summer-action': {
color: 'var(--c-primary)',
backgroundColor: 'var(--c-subtle)',
borderRadius: '4px',
},
})
}
/** Builds the field's CodeMirror editor on options.parent. */
export function createCodeEditor(options: CodeEditorOptions): CodeEditorHandle {
// Pitfall 5: drop Mod-Enter so the form's save hotkey still fires.
const keys = keymap.of([...historyKeymap, ...defaultKeymap.filter((binding) => binding.key !== 'Mod-Enter')])
// No indentWithTab: Tab moves focus out (WCAG 2.1.2).
let hadFocus = false
const view = new EditorView({
parent: options.parent,
state: EditorState.create({
doc: options.doc,
extensions: [
lineNumbers(),
bracketMatching(),
history(),
languageExtension(options.language),
goActions,
syntaxHighlighting(syntaxColors),
theme(options.height),
keys,
...(options.language === 'text' ? [EditorView.lineWrapping] : []),
EditorView.contentAttributes.of(options.attributes),
EditorView.updateListener.of((update) => {
if (update.view.hasFocus) {
hadFocus = true
}
if (update.docChanged) {
options.onChange(update.state.doc.toString())
}
}),
],
}),
})
return {
view,
insert(text: string) {
const { state } = view
const selection = hadFocus ? state.selection.main : null
const from = selection ? selection.from : state.doc.length
const to = selection ? selection.to : state.doc.length
view.dispatch({
changes: { from, to, insert: text },
selection: { anchor: from + text.length },
})
view.focus()
},
destroy() {
view.destroy()
},
setDoc(doc: string) {
if (view.state.doc.toString() === doc) {
return
}
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: doc },
})
},
}
}

View File

@@ -1,13 +1,215 @@
<script setup lang="ts">
// Stub for TDD RED (35-03 Task 4): loading, lazy CodeMirror, fallback and
// read-only rendering land in GREEN. Emits nothing and shows an empty box so
// the planned behavior assertions fail intentionally.
import type { FieldControlProps } from '../control'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
import { Info } from '@lucide/vue'
import { t } from '../../../app/i18n'
import { controlClass, type FieldControlProps } from '../control'
import type { CodeEditorHandle, CodeEditorLanguage } from '../codeeditor/editor'
defineProps<FieldControlProps>()
defineEmits<{ 'update:modelValue': [value: string] }>()
// type: codeeditor (D-09, UI-SPEC C1): HTML/CSS/plain-text source on CodeMirror 6,
// loaded as its own chunk (skeleton meanwhile; when the chunk fails, a monospace
// textarea with codeeditor.load_failed). Value is a string sent unchanged until
// the administrator edits. Read-only shows a pre and loads no CodeMirror.
const props = defineProps<FieldControlProps>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
type EditorModule = typeof import('../codeeditor/editor')
type Status = 'loading' | 'ready' | 'failed'
const SIZE_HEIGHT: Record<string, number> = {
tiny: 128,
small: 192,
large: 320,
huge: 480,
giant: 640,
}
const readOnly = computed(() => !!props.field.readOnly)
const stored = computed(() => (props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue)))
const language = computed<CodeEditorLanguage>(() => {
const value = props.field.language
return value === 'html' || value === 'css' || value === 'text' ? value : 'html'
})
const height = computed(() => SIZE_HEIGHT[props.field.size ?? ''] ?? 320)
const mailImages = computed(() => !!props.field.mailImages)
const labelId = computed(() => `${props.controlId}-label`)
const status = ref<Status>('loading')
const fallbackText = ref('')
const mountEl = ref<HTMLElement | null>(null)
const editor = shallowRef<CodeEditorHandle | null>(null)
let module: EditorModule | null = null
let disposed = false
let lastEmitted: string | null = null
let suppressChange = false
const wrapperClass = computed(() => [
'rounded-control border bg-surface overflow-hidden',
'focus-within:border-primary focus-within:shadow-[0_0_0_3px_var(--c-ring)]',
props.invalid ? 'border-danger' : 'border-border-strong',
])
function contentAttributes(): Record<string, string> {
const out: Record<string, string> = {
id: props.controlId,
'aria-labelledby': labelId.value,
'aria-multiline': 'true',
}
if (props.describedBy) {
out['aria-describedby'] = props.describedBy
}
if (props.invalid) {
out['aria-invalid'] = 'true'
}
return out
}
function setValue(value: string): void {
lastEmitted = value
emit('update:modelValue', value)
}
function onEditorChange(doc: string): void {
if (suppressChange) {
return
}
setValue(doc)
}
onMounted(async () => {
if (readOnly.value) {
return
}
try {
module = await import('../codeeditor/editor')
if (disposed) {
return
}
status.value = 'ready'
await nextTick()
if (disposed || !mountEl.value || !module) {
return
}
editor.value = module.createCodeEditor({
parent: mountEl.value,
doc: stored.value,
language: language.value,
height: height.value,
attributes: contentAttributes(),
onChange: onEditorChange,
})
} catch {
if (disposed) {
return
}
editor.value?.destroy()
editor.value = null
status.value = 'failed'
fallbackText.value = stored.value
}
})
onBeforeUnmount(() => {
disposed = true
editor.value?.destroy()
editor.value = null
})
watch(stored, (value) => {
if (value === lastEmitted) {
return
}
lastEmitted = null
if (status.value === 'failed') {
fallbackText.value = value
return
}
if (editor.value) {
suppressChange = true
editor.value.setDoc(value)
suppressChange = false
}
})
function onFallbackInput(event: Event): void {
const value = (event.target as HTMLTextAreaElement).value
fallbackText.value = value
setValue(value)
}
/** Inserts text at the selection (or appends); used by the mail image toolbar. */
function insert(text: string): void {
if (editor.value) {
editor.value.insert(text)
return
}
if (status.value === 'failed') {
const el = document.getElementById(props.controlId) as HTMLTextAreaElement | null
if (!el) {
fallbackText.value = fallbackText.value + text
setValue(fallbackText.value)
return
}
const start = el.selectionStart ?? fallbackText.value.length
const end = el.selectionEnd ?? start
const next = fallbackText.value.slice(0, start) + text + fallbackText.value.slice(end)
fallbackText.value = next
setValue(next)
void nextTick(() => {
el.focus()
const caret = start + text.length
el.setSelectionRange(caret, caret)
})
}
}
defineExpose({ insert })
</script>
<template>
<div data-codeeditor-stub class="rounded-control border border-border bg-surface" />
<pre
v-if="readOnly"
:id="controlId"
data-codeeditor-readonly
class="max-h-[480px] overflow-auto rounded-control border border-border bg-subtle px-3.5 py-2.5 font-mono text-[13px] whitespace-pre-wrap"
>{{ stored !== '' ? stored : t('backend::lang.list.empty_value') }}</pre>
<div
v-else-if="status === 'loading'"
data-codeeditor-loading
aria-busy="true"
class="rounded-control bg-skel"
:style="{ height: `${height}px` }"
/>
<div v-else-if="status === 'failed'" class="flex flex-col gap-1.5">
<p data-codeeditor-load-failed class="flex items-center gap-2 text-[13px] text-muted">
<Info :size="14" aria-hidden="true" />
{{ t('backend::lang.codeeditor.load_failed') }}
</p>
<textarea
:id="controlId"
data-codeeditor-fallback
:value="fallbackText"
:aria-labelledby="labelId"
:aria-describedby="describedBy"
:aria-invalid="invalid ? 'true' : undefined"
spellcheck="false"
:class="[controlClass(invalid), 'font-mono text-[13px] resize-y px-3.5 py-2.5']"
:style="{ height: `${height}px` }"
@input="onFallbackInput"
/>
</div>
<div v-else :data-codeeditor="field.name" :class="wrapperClass">
<div
v-if="mailImages"
role="toolbar"
:aria-label="t('backend::lang.codeeditor.toolbar')"
:aria-controls="controlId"
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" />
</div>
<div ref="mountEl" data-codeeditor-mount />
</div>
</template>

View File

@@ -57,6 +57,7 @@ import TextField from './fields/TextField.vue'
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 MoneyField from './fields/MoneyField.vue'
import TaglistField from './fields/TaglistField.vue'
import MLTextField from './fields/MLTextField.vue'
@@ -103,6 +104,7 @@ const renderers = new Map<string, Component>([
['money', MoneyField],
['taglist', TaglistField],
['mailpreview', MailPreviewField],
['codeeditor', CodeEditorField],
])
/** Types whose control shows the label itself (toggle cards, relation manager). */