@prunellejs/cms 0.0.0-stage → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/render.ts ADDED
@@ -0,0 +1,583 @@
1
+ // RGAA-accessible HTML document and schema-driven form renderer for @prunellejs/cms.
2
+
3
+ import type { ContentCollectionDescriptor, ContentCollectionEntrySummary } from 'prunelle/config'
4
+ import type { CmsField } from './schema'
5
+ import { esc, escAttr } from 'prunelle/server'
6
+ import { serializeFrontmatterYaml } from './form-data'
7
+
8
+ export interface CollectionCardView {
9
+ readonly name: string
10
+ readonly entryCount: number
11
+ readonly editable: boolean
12
+ readonly localized: boolean
13
+ readonly defaultLocale: string
14
+ readonly hasSchema: boolean
15
+ }
16
+
17
+ export interface EditorViewModel {
18
+ readonly basePath: string
19
+ readonly collection: ContentCollectionDescriptor
20
+ readonly mode: 'new' | 'edit'
21
+ readonly slug: string
22
+ readonly locale?: string | undefined
23
+ readonly fields?: readonly CmsField[] | undefined
24
+ readonly data: Record<string, unknown>
25
+ readonly rawFrontmatterYaml?: string | undefined
26
+ readonly body: string
27
+ readonly errors: Readonly<Record<string, string>>
28
+ readonly formError?: string | undefined
29
+ readonly saved?: boolean | undefined
30
+ readonly schemaWarning?: string | undefined
31
+ }
32
+
33
+ export function fieldDomId(name: string): string {
34
+ return `cms-f-${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`
35
+ }
36
+
37
+ export function encodeSlugPath(slug: string): string {
38
+ return slug.split('/').map(seg => encodeURIComponent(seg)).join('/')
39
+ }
40
+
41
+ export function localeQueryString(locale: string | undefined, extra?: string): string {
42
+ const parts: string[] = []
43
+ if (locale !== undefined && locale.length > 0)
44
+ parts.push(`locale=${encodeURIComponent(locale)}`)
45
+ if (extra !== undefined && extra.length > 0)
46
+ parts.push(extra)
47
+ return parts.length > 0 ? `?${parts.join('&')}` : ''
48
+ }
49
+
50
+ function renderDocument(options: {
51
+ basePath: string
52
+ title: string
53
+ breadcrumb: string
54
+ content: string
55
+ includeScript?: boolean | undefined
56
+ }): string {
57
+ const cssHref = `${options.basePath}/_assets/cms.css`
58
+ const jsTag = options.includeScript
59
+ ? `<script src="${escAttr(`${options.basePath}/_assets/cms.js`)}" defer></script>`
60
+ : ''
61
+ return `<!DOCTYPE html>
62
+ <html lang="en" data-pru-cms>
63
+ <head>
64
+ <meta charset="utf-8">
65
+ <meta name="viewport" content="width=device-width, initial-scale=1">
66
+ <title>${esc(options.title)} — Prunelle CMS</title>
67
+ <link rel="stylesheet" href="${escAttr(cssHref)}">
68
+ ${jsTag}
69
+ </head>
70
+ <body>
71
+ <a class="cms-skip" href="#main">Skip to main content</a>
72
+ <header class="cms-header">
73
+ <div class="cms-header-inner">
74
+ <a class="cms-brand" href="${escAttr(options.basePath)}"><span class="cms-eye" aria-hidden="true"><i></i></span>Prunelle CMS <span data-ui="badge">dev</span></a>
75
+ <nav class="cms-nav" aria-label="CMS navigation">${options.breadcrumb}</nav>
76
+ </div>
77
+ </header>
78
+ <main id="main" class="cms-main" tabindex="-1">
79
+ ${options.content}
80
+ </main>
81
+ </body>
82
+ </html>`
83
+ }
84
+
85
+ /** Renders the root collection index page (`GET /_pru/cms`). */
86
+ export function renderCollectionsPage(
87
+ basePath: string,
88
+ collections: readonly CollectionCardView[],
89
+ missingService: boolean,
90
+ ): string {
91
+ let body: string
92
+ if (missingService) {
93
+ body = `<div class="cms-page-head"><h1>Collections</h1></div>
94
+ <div data-ui="notice" data-tone="error" role="alert">
95
+ <strong>No content service registered.</strong> Add <code>content()</code> from <code>@prunellejs/content</code> to <code>prunelle.config.ts</code>.
96
+ </div>`
97
+ }
98
+ else if (collections.length === 0) {
99
+ body = `<div class="cms-page-head"><h1>Collections</h1></div>
100
+ <div data-ui="notice" role="status">
101
+ No collections discovered yet. Define a collection with <code>defineCollection()</code> and register <code>content()</code> in <code>prunelle.config.ts</code>.
102
+ </div>`
103
+ }
104
+ else {
105
+ const cards = collections.map((col) => {
106
+ const colHref = `${basePath}/${encodeURIComponent(col.name)}`
107
+ const newHref = `${colHref}/new`
108
+ const badges = [
109
+ `<span data-ui="badge">${col.entryCount} ${col.entryCount === 1 ? 'entry' : 'entries'}</span>`,
110
+ ...(col.localized ? [`<span data-ui="badge">localized (${esc(col.defaultLocale)})</span>`] : []),
111
+ ...(!col.editable ? [`<span data-ui="badge">read-only</span>`] : []),
112
+ ].join(' ')
113
+ const newLink = col.editable
114
+ ? `<a data-ui="button" data-variant="primary" data-size="sm" href="${escAttr(newHref)}">+ New entry</a>`
115
+ : ''
116
+ return `<article data-ui="card">
117
+ <div class="cms-card-head">
118
+ <h2><a href="${escAttr(colHref)}">${esc(col.name)}</a></h2>
119
+ </div>
120
+ <div class="cms-locales">${badges}</div>
121
+ <div class="cms-card-actions">
122
+ <a data-ui="button" data-size="sm" href="${escAttr(colHref)}">Browse entries</a>
123
+ ${newLink}
124
+ </div>
125
+ </article>`
126
+ }).join('\n')
127
+ body = `<div class="cms-page-head"><h1>Collections</h1><p class="cms-muted">${collections.length} ${collections.length === 1 ? 'collection' : 'collections'}</p></div>
128
+ <section class="cms-grid" aria-label="Content collections">${cards}</section>`
129
+ }
130
+
131
+ return renderDocument({
132
+ basePath,
133
+ title: 'Collections',
134
+ breadcrumb: `<a href="${escAttr(basePath)}" aria-current="page">Collections</a>`,
135
+ content: body,
136
+ })
137
+ }
138
+
139
+ function entryDisplayTitle(entry: ContentCollectionEntrySummary): string {
140
+ const title = entry.data.title ?? entry.data.name
141
+ return typeof title === 'string' && title.trim().length > 0 ? title : entry.slug
142
+ }
143
+
144
+ function entryDisplayDate(entry: ContentCollectionEntrySummary): string {
145
+ const raw = entry.data.date ?? entry.data.publishedAt ?? entry.data.updatedAt
146
+ if (raw instanceof Date)
147
+ return raw.toISOString().slice(0, 10)
148
+ return typeof raw === 'string' ? raw : ''
149
+ }
150
+
151
+ /** Renders the entries list page for a collection (`GET /_pru/cms/:collection`). */
152
+ export function renderEntriesPage(options: {
153
+ basePath: string
154
+ collection: ContentCollectionDescriptor
155
+ entries: readonly ContentCollectionEntrySummary[]
156
+ activeLocale?: string | undefined
157
+ locales: readonly string[]
158
+ query: string
159
+ }): string {
160
+ const { basePath, collection, entries, activeLocale, locales, query } = options
161
+ const colHref = `${basePath}/${encodeURIComponent(collection.name)}`
162
+ const editable = collection.dir !== undefined
163
+ const newHref = `${colHref}/new${localeQueryString(activeLocale)}`
164
+
165
+ const localeNav = collection.localized
166
+ ? `<nav class="cms-locales" aria-label="Locales">
167
+ <span class="cms-muted">Locale:</span>
168
+ ${locales.map((loc) => {
169
+ const href = `${colHref}${localeQueryString(loc, query ? `q=${encodeURIComponent(query)}` : undefined)}`
170
+ const isCurrent = loc === activeLocale
171
+ return `<a data-ui="button" data-size="sm"${isCurrent ? ' data-variant="primary" aria-current="true"' : ''} href="${escAttr(href)}">${esc(loc)}</a>`
172
+ }).join('')}
173
+ </nav>`
174
+ : ''
175
+
176
+ const searchForm = `<form class="cms-search" method="get" action="${escAttr(colHref)}" role="search">
177
+ ${activeLocale !== undefined ? `<input type="hidden" name="locale" value="${escAttr(activeLocale)}">` : ''}
178
+ <label for="cms-q" class="cms-muted">Filter</label>
179
+ <input id="cms-q" type="search" name="q" value="${escAttr(query)}" placeholder="Search title or slug">
180
+ <button type="submit" data-ui="button" data-size="sm">Search</button>
181
+ ${query ? `<a data-ui="button" data-size="sm" href="${escAttr(`${colHref}${localeQueryString(activeLocale)}`)}">Clear</a>` : ''}
182
+ </form>`
183
+
184
+ const rows = entries.map((entry) => {
185
+ const editHref = `${colHref}/${encodeSlugPath(entry.slug)}${localeQueryString(activeLocale)}`
186
+ const draftBadge = entry.data.draft === true ? ' <span data-ui="badge">draft</span>' : ''
187
+ const dateText = entryDisplayDate(entry)
188
+ return `<tr>
189
+ <td><a href="${escAttr(editHref)}">${esc(entryDisplayTitle(entry))}</a>${draftBadge}</td>
190
+ <td><code>${esc(entry.slug)}</code></td>
191
+ <td>${dateText ? esc(dateText) : '<span class="cms-muted">—</span>'}</td>
192
+ <td><a data-ui="button" data-size="sm" href="${escAttr(editHref)}">${editable ? 'Edit' : 'View'}</a></td>
193
+ </tr>`
194
+ }).join('\n')
195
+
196
+ const tableHtml = entries.length === 0
197
+ ? `<div data-ui="notice" role="status">${query ? `No entries matching "${esc(query)}".` : 'No entries in this collection yet.'}</div>`
198
+ : `<table class="cms-table">
199
+ <thead>
200
+ <tr><th scope="col">Title</th><th scope="col">Slug</th><th scope="col">Date</th><th scope="col">Action</th></tr>
201
+ </thead>
202
+ <tbody>${rows}</tbody>
203
+ </table>`
204
+
205
+ const readOnlyNotice = !editable
206
+ ? `<div data-ui="notice" role="status">This collection is loader-backed and read-only in the dev CMS.</div>`
207
+ : ''
208
+
209
+ const content = `<div class="cms-page-head">
210
+ <div>
211
+ <h1>${esc(collection.name)}</h1>
212
+ <p class="cms-muted">${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}${activeLocale ? ` · locale ${esc(activeLocale)}` : ''}</p>
213
+ </div>
214
+ ${editable ? `<a data-ui="button" data-variant="primary" href="${escAttr(newHref)}">+ New entry</a>` : ''}
215
+ </div>
216
+ ${readOnlyNotice}
217
+ <div class="cms-toolbar">${localeNav}${searchForm}</div>
218
+ ${tableHtml}`
219
+
220
+ return renderDocument({
221
+ basePath,
222
+ title: collection.name,
223
+ breadcrumb: `<a href="${escAttr(basePath)}">Collections</a> <span aria-hidden="true">/</span> <a href="${escAttr(colHref)}" aria-current="page">${esc(collection.name)}</a>`,
224
+ content,
225
+ })
226
+ }
227
+
228
+ function formatInputValue(field: CmsField, value: unknown): string {
229
+ if (value === undefined || value === null)
230
+ return ''
231
+ if (value instanceof Date) {
232
+ if (field.kind === 'date')
233
+ return value.toISOString().slice(0, 10)
234
+ if (field.kind === 'datetime')
235
+ return value.toISOString().slice(0, 16)
236
+ return value.toISOString()
237
+ }
238
+ if (field.kind === 'tags')
239
+ return Array.isArray(value) ? value.map(String).join(', ') : String(value)
240
+ if (field.kind === 'date' && typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value))
241
+ return value.slice(0, 10)
242
+ if (field.kind === 'datetime' && typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(value))
243
+ return value.slice(0, 16)
244
+ return String(value)
245
+ }
246
+
247
+ function describedByAttr(id: string, hasHint: boolean, hasError: boolean): string {
248
+ const ids: string[] = []
249
+ if (hasHint)
250
+ ids.push(`${id}-hint`)
251
+ if (hasError)
252
+ ids.push(`${id}-err`)
253
+ return ids.length > 0 ? ` aria-describedby="${escAttr(ids.join(' '))}"` : ''
254
+ }
255
+
256
+ function renderFieldMeta(id: string, hint: string | undefined, error: string | undefined): string {
257
+ const hintHtml = hint !== undefined ? `<p id="${escAttr(`${id}-hint`)}" class="cms-hint">${esc(hint)}</p>` : ''
258
+ const errHtml = error !== undefined ? `<p id="${escAttr(`${id}-err`)}" class="cms-error" role="alert">${esc(error)}</p>` : ''
259
+ return `${hintHtml}${errHtml}`
260
+ }
261
+
262
+ function renderSwitchField(
263
+ field: CmsField,
264
+ name: string,
265
+ value: unknown,
266
+ error: string | undefined,
267
+ disabled: boolean,
268
+ ): string {
269
+ const id = fieldDomId(name)
270
+ const checked = value === true
271
+ const invalidAttr = error !== undefined ? ' aria-invalid="true"' : ''
272
+ const descAttr = describedByAttr(id, field.description !== undefined, error !== undefined)
273
+ const disAttr = disabled ? ' disabled' : ''
274
+ return `<div data-ui="field">
275
+ <label data-ui="switch" for="${escAttr(id)}">
276
+ <input type="checkbox" role="switch" id="${escAttr(id)}" name="${escAttr(name)}" value="true"${checked ? ' checked' : ''}${invalidAttr}${descAttr}${disAttr}>
277
+ <span data-part="track" aria-hidden="true"></span>
278
+ <span>${esc(field.label)}</span>
279
+ </label>
280
+ ${renderFieldMeta(id, field.description, error)}
281
+ </div>`
282
+ }
283
+
284
+ function renderEnumField(
285
+ field: CmsField,
286
+ name: string,
287
+ value: unknown,
288
+ error: string | undefined,
289
+ disabled: boolean,
290
+ ): string {
291
+ const id = fieldDomId(name)
292
+ const current = value === undefined || value === null ? '' : String(value)
293
+ const invalidAttr = error !== undefined ? ' aria-invalid="true"' : ''
294
+ const descAttr = describedByAttr(id, field.description !== undefined, error !== undefined)
295
+ const reqAttr = field.required ? ' required' : ''
296
+ const disAttr = disabled ? ' disabled' : ''
297
+ const emptyOption = !field.required ? `<option value=""${current === '' ? ' selected' : ''}>— Select —</option>` : ''
298
+ const optionsHtml = (field.options ?? []).map((opt) => {
299
+ const str = String(opt)
300
+ return `<option value="${escAttr(str)}"${str === current ? ' selected' : ''}>${esc(str)}</option>`
301
+ }).join('')
302
+ return `<div data-ui="field">
303
+ <label for="${escAttr(id)}">${esc(field.label)}${field.required ? '<span class="cms-req" aria-hidden="true">*</span>' : ''}</label>
304
+ <select id="${escAttr(id)}" name="${escAttr(name)}"${reqAttr}${invalidAttr}${descAttr}${disAttr}>${emptyOption}${optionsHtml}</select>
305
+ ${renderFieldMeta(id, field.description, error)}
306
+ </div>`
307
+ }
308
+
309
+ function scalarInputType(kind: CmsField['kind']): string {
310
+ if (kind === 'date')
311
+ return 'date'
312
+ if (kind === 'datetime')
313
+ return 'datetime-local'
314
+ if (kind === 'email')
315
+ return 'email'
316
+ if (kind === 'url')
317
+ return 'url'
318
+ if (kind === 'number' || kind === 'integer')
319
+ return 'number'
320
+ return 'text'
321
+ }
322
+
323
+ function renderScalarField(
324
+ field: CmsField,
325
+ name: string,
326
+ value: unknown,
327
+ error: string | undefined,
328
+ disabled: boolean,
329
+ ): string {
330
+ const id = fieldDomId(name)
331
+ const valStr = formatInputValue(field, value)
332
+ const hint = field.kind === 'tags'
333
+ ? (field.description ? `${field.description} (comma-separated)` : 'Comma-separated list of tags')
334
+ : field.description
335
+ const invalidAttr = error !== undefined ? ' aria-invalid="true"' : ''
336
+ const descAttr = describedByAttr(id, hint !== undefined, error !== undefined)
337
+ const reqAttr = field.required ? ' required' : ''
338
+ const disAttr = disabled ? ' disabled' : ''
339
+
340
+ let control: string
341
+ if (field.kind === 'textarea') {
342
+ control = `<textarea id="${escAttr(id)}" name="${escAttr(name)}"${reqAttr}${invalidAttr}${descAttr}${disAttr}>${esc(valStr)}</textarea>`
343
+ }
344
+ else {
345
+ const type = scalarInputType(field.kind)
346
+ const attrs: string[] = [
347
+ `type="${type}"`,
348
+ `id="${escAttr(id)}"`,
349
+ `name="${escAttr(name)}"`,
350
+ `value="${escAttr(valStr)}"`,
351
+ ]
352
+ if (field.min !== undefined)
353
+ attrs.push(`min="${escAttr(String(field.min))}"`)
354
+ if (field.max !== undefined)
355
+ attrs.push(`max="${escAttr(String(field.max))}"`)
356
+ if (field.step !== undefined)
357
+ attrs.push(`step="${escAttr(field.step)}"`)
358
+ if (field.minLength !== undefined)
359
+ attrs.push(`minlength="${escAttr(String(field.minLength))}"`)
360
+ if (field.maxLength !== undefined)
361
+ attrs.push(`maxlength="${escAttr(String(field.maxLength))}"`)
362
+ if (field.pattern !== undefined)
363
+ attrs.push(`pattern="${escAttr(field.pattern)}"`)
364
+ control = `<input ${attrs.join(' ')}${reqAttr}${invalidAttr}${descAttr}${disAttr}>`
365
+ }
366
+
367
+ return `<div data-ui="field">
368
+ <label for="${escAttr(id)}">${esc(field.label)}${field.required ? '<span class="cms-req" aria-hidden="true">*</span>' : ''}</label>
369
+ ${control}
370
+ ${renderFieldMeta(id, hint, error)}
371
+ </div>`
372
+ }
373
+
374
+ function renderObjectField(
375
+ field: CmsField,
376
+ name: string,
377
+ value: unknown,
378
+ errors: Readonly<Record<string, string>>,
379
+ disabled: boolean,
380
+ ): string {
381
+ const record = value !== null && typeof value === 'object' && !Array.isArray(value)
382
+ ? (value as Record<string, unknown>)
383
+ : {}
384
+ const err = errors[name]
385
+ const id = fieldDomId(name)
386
+ const children = (field.fields ?? [])
387
+ .map(child => renderField(child, `${name}.${child.key}`, record[child.key], errors, disabled))
388
+ .join('\n')
389
+ return `<fieldset class="cms-fieldset" id="${escAttr(id)}">
390
+ <legend>${esc(field.label)}${field.required ? '<span class="cms-req" aria-hidden="true">*</span>' : ''}</legend>
391
+ ${renderFieldMeta(id, field.description, err)}
392
+ ${children}
393
+ </fieldset>`
394
+ }
395
+
396
+ function renderObjectArrayField(
397
+ field: CmsField,
398
+ name: string,
399
+ value: unknown,
400
+ errors: Readonly<Record<string, string>>,
401
+ disabled: boolean,
402
+ ): string {
403
+ const rows = Array.isArray(value) ? value : []
404
+ const err = errors[name]
405
+ const id = fieldDomId(name)
406
+ const rowsHtml = rows.map((rowVal, idx) => {
407
+ const rowRecord = rowVal !== null && typeof rowVal === 'object' && !Array.isArray(rowVal)
408
+ ? (rowVal as Record<string, unknown>)
409
+ : {}
410
+ const rowFields = (field.fields ?? [])
411
+ .map(child => renderField(child, `${name}[${idx}].${child.key}`, rowRecord[child.key], errors, disabled))
412
+ .join('\n')
413
+ const controls = !disabled
414
+ ? `<div class="cms-row-controls">
415
+ <button type="submit" formnovalidate data-ui="button" data-size="sm" data-cms-row-move="up" name="__cms_action" value="${escAttr(`up:${name}:${idx}`)}"${idx === 0 ? ' disabled' : ''} aria-label="${escAttr(`Move ${field.label} row ${idx + 1} up`)}">Move up</button>
416
+ <button type="submit" formnovalidate data-ui="button" data-size="sm" data-cms-row-move="down" name="__cms_action" value="${escAttr(`down:${name}:${idx}`)}"${idx === rows.length - 1 ? ' disabled' : ''} aria-label="${escAttr(`Move ${field.label} row ${idx + 1} down`)}">Move down</button>
417
+ <button type="submit" formnovalidate data-ui="button" data-variant="danger" data-size="sm" name="__cms_action" value="${escAttr(`remove:${name}:${idx}`)}" aria-label="${escAttr(`Remove ${field.label} row ${idx + 1}`)}">Remove</button>
418
+ </div>`
419
+ : ''
420
+ return `<div class="cms-row" data-cms-row>
421
+ <div class="cms-row-head">
422
+ <strong data-cms-row-title>Row ${idx + 1}</strong>
423
+ ${controls}
424
+ </div>
425
+ ${rowFields}
426
+ </div>`
427
+ }).join('\n')
428
+
429
+ const addButton = !disabled
430
+ ? `<div><button type="submit" formnovalidate data-ui="button" data-size="sm" name="__cms_action" value="${escAttr(`add:${name}`)}">+ Add ${esc(field.label)} row</button></div>`
431
+ : ''
432
+
433
+ return `<fieldset class="cms-fieldset" id="${escAttr(id)}" data-cms-rows="${escAttr(name)}">
434
+ <legend>${esc(field.label)}${field.required ? '<span class="cms-req" aria-hidden="true">*</span>' : ''}</legend>
435
+ <input type="hidden" name="${escAttr(`__rows:${name}`)}" value="${rows.length}">
436
+ ${renderFieldMeta(id, field.description, err)}
437
+ ${rowsHtml}
438
+ ${addButton}
439
+ </fieldset>`
440
+ }
441
+
442
+ function renderField(
443
+ field: CmsField,
444
+ name: string,
445
+ value: unknown,
446
+ errors: Readonly<Record<string, string>>,
447
+ disabled: boolean,
448
+ ): string {
449
+ const error = errors[name]
450
+ if (field.kind === 'boolean')
451
+ return renderSwitchField(field, name, value, error, disabled)
452
+ if (field.kind === 'enum')
453
+ return renderEnumField(field, name, value, error, disabled)
454
+ if (field.kind === 'object')
455
+ return renderObjectField(field, name, value, errors, disabled)
456
+ if (field.kind === 'object-array')
457
+ return renderObjectArrayField(field, name, value, errors, disabled)
458
+ return renderScalarField(field, name, value, error, disabled)
459
+ }
460
+
461
+ function renderErrorSummary(errors: Readonly<Record<string, string>>, formError: string | undefined): string {
462
+ const entries = Object.entries(errors)
463
+ if (entries.length === 0 && formError === undefined)
464
+ return ''
465
+ const items = entries.map(([key, msg]) => {
466
+ const label = key === '' ? 'Frontmatter' : key
467
+ const link = key === '' ? esc(msg) : `<a href="#${escAttr(fieldDomId(key))}">${esc(label)}</a>: ${esc(msg)}`
468
+ return `<li>${link}</li>`
469
+ }).join('')
470
+ return `<div data-ui="notice" data-tone="error" role="alert">
471
+ <strong>Please fix the following errors:</strong>
472
+ ${formError !== undefined ? `<p>${esc(formError)}</p>` : ''}
473
+ ${items.length > 0 ? `<ul>${items}</ul>` : ''}
474
+ </div>`
475
+ }
476
+
477
+ function renderMarkdownEditor(basePath: string, body: string, disabled: boolean): string {
478
+ const previewUrl = `${basePath}/_preview`
479
+ return `<section data-ui="card" data-cms-md-editor data-preview-url="${escAttr(previewUrl)}">
480
+ <div class="cms-md-bar">
481
+ <label for="cms-f-__body"><strong>Markdown body</strong></label>
482
+ <button type="button" data-ui="button" data-size="sm" data-cms-md-toggle aria-pressed="false" hidden>Live preview</button>
483
+ </div>
484
+ <div class="cms-md-split" data-preview-open="false">
485
+ <div data-ui="field">
486
+ <textarea id="cms-f-__body" class="cms-md-input" name="__body"${disabled ? ' disabled' : ''}>${esc(body)}</textarea>
487
+ </div>
488
+ <div class="cms-md-preview" data-cms-md-preview aria-label="Markdown preview" hidden></div>
489
+ </div>
490
+ </section>`
491
+ }
492
+
493
+ /** Renders the create or edit entry page (`GET/POST /_pru/cms/:collection/new` and `/:collection/*slug`). */
494
+ export function renderEditorPage(vm: EditorViewModel): string {
495
+ const { basePath, collection, mode, slug, locale, fields, data, body, errors, formError, saved, schemaWarning } = vm
496
+ const editable = collection.dir !== undefined
497
+ const colHref = `${basePath}/${encodeURIComponent(collection.name)}`
498
+ const listHref = `${colHref}${localeQueryString(locale)}`
499
+ const actionUrl = mode === 'new'
500
+ ? `${colHref}/new${localeQueryString(locale)}`
501
+ : `${colHref}/${encodeSlugPath(slug)}${localeQueryString(locale)}`
502
+
503
+ const heading = mode === 'new' ? `New ${collection.name} entry` : `Edit ${slug}`
504
+ const savedNotice = saved
505
+ ? `<div data-ui="notice" data-tone="success" role="status">Saved to working tree.</div>`
506
+ : ''
507
+ const schemaNotice = schemaWarning !== undefined
508
+ ? `<div data-ui="notice" role="status">${esc(schemaWarning)}</div>`
509
+ : ''
510
+ const errorSummary = renderErrorSummary(errors, formError)
511
+
512
+ const slugError = errors.__slug
513
+ const slugField = mode === 'new'
514
+ ? `<div data-ui="field">
515
+ <label for="cms-f-__slug">Slug<span class="cms-req" aria-hidden="true">*</span></label>
516
+ <input type="text" id="cms-f-__slug" name="__slug" value="${escAttr(slug)}" required placeholder="my-new-entry"${slugError !== undefined ? ' aria-invalid="true"' : ''}${describedByAttr('cms-f-__slug', true, slugError !== undefined)}${!editable ? ' disabled' : ''}>
517
+ ${renderFieldMeta('cms-f-__slug', 'File path relative to the collection directory (without .md).', slugError)}
518
+ </div>`
519
+ : ''
520
+
521
+ const localeInput = locale !== undefined
522
+ ? `<input type="hidden" name="__locale" value="${escAttr(locale)}">`
523
+ : ''
524
+
525
+ let frontmatterSection: string
526
+ if (fields !== undefined) {
527
+ const renderedFields = fields
528
+ .map(f => renderField(f, f.key, data[f.key], errors, !editable))
529
+ .join('\n')
530
+ frontmatterSection = `<section data-ui="card" aria-label="Frontmatter fields">
531
+ <h2>Frontmatter</h2>
532
+ <div class="cms-form">${slugField}${renderedFields}</div>
533
+ </section>`
534
+ }
535
+ else {
536
+ const yamlText = vm.rawFrontmatterYaml ?? serializeFrontmatterYaml(data)
537
+ const yamlErr = errors.__frontmatter_yaml
538
+ frontmatterSection = `<section data-ui="card" aria-label="Frontmatter YAML">
539
+ <h2>Frontmatter (YAML)</h2>
540
+ <div class="cms-form">
541
+ ${slugField}
542
+ <div data-ui="field">
543
+ <label for="cms-f-__frontmatter_yaml">YAML fields</label>
544
+ <textarea id="cms-f-__frontmatter_yaml" class="cms-md-input" name="__frontmatter_yaml"${yamlErr !== undefined ? ' aria-invalid="true"' : ''}${describedByAttr('cms-f-__frontmatter_yaml', true, yamlErr !== undefined)}${!editable ? ' disabled' : ''}>${esc(yamlText)}</textarea>
545
+ ${renderFieldMeta('cms-f-__frontmatter_yaml', 'No JSON Schema detected for this collection; edit raw YAML frontmatter.', yamlErr)}
546
+ </div>
547
+ </div>
548
+ </section>`
549
+ }
550
+
551
+ const submitRow = editable
552
+ ? `<div class="cms-actions">
553
+ <button type="submit" data-ui="button" data-variant="primary">${mode === 'new' ? 'Create entry' : 'Save changes'}</button>
554
+ <a data-ui="button" href="${escAttr(listHref)}">Cancel</a>
555
+ </div>`
556
+ : `<div class="cms-actions"><a data-ui="button" href="${escAttr(listHref)}">Back to list</a></div>`
557
+
558
+ const content = `<div class="cms-page-head">
559
+ <div>
560
+ <h1>${esc(heading)}</h1>
561
+ ${locale !== undefined ? `<p class="cms-muted">Locale: <code>${esc(locale)}</code></p>` : ''}
562
+ </div>
563
+ <a data-ui="button" data-size="sm" href="${escAttr(listHref)}">← Back to ${esc(collection.name)}</a>
564
+ </div>
565
+ ${savedNotice}
566
+ ${schemaNotice}
567
+ ${errorSummary}
568
+ <form class="cms-form" method="post" action="${escAttr(actionUrl)}" novalidate>
569
+ ${localeInput}
570
+ ${frontmatterSection}
571
+ ${renderMarkdownEditor(basePath, body, !editable)}
572
+ ${submitRow}
573
+ </form>`
574
+
575
+ const currentCrumb = mode === 'new' ? 'New entry' : slug
576
+ return renderDocument({
577
+ basePath,
578
+ title: `${heading} · ${collection.name}`,
579
+ breadcrumb: `<a href="${escAttr(basePath)}">Collections</a> <span aria-hidden="true">/</span> <a href="${escAttr(colHref)}">${esc(collection.name)}</a> <span aria-hidden="true">/</span> <span aria-current="page">${esc(currentCrumb)}</span>`,
580
+ content,
581
+ includeScript: true,
582
+ })
583
+ }