@prunellejs/cms 0.0.0-stage → 0.7.0

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.
@@ -0,0 +1,166 @@
1
+ // DOM discovery helpers (HTML comment body anchors & matching frontmatter text nodes)
2
+ // for @prunellejs/cms in-page editing.
3
+
4
+ export const INLINE_DOM_JS = `
5
+ function entryId(ref) {
6
+ return ref.collection + '\\0' + (ref.locale || '') + '\\0' + ref.slug;
7
+ }
8
+
9
+ function decodePart(s) {
10
+ try { return decodeURIComponent(s); } catch (_err) { return s; }
11
+ }
12
+
13
+ // Discover <!--pru-cms:col:slug:locale:__body--> ... <!--/pru-cms--> comment anchors
14
+ function findBodyAnchors() {
15
+ const anchors = [];
16
+ const stack = [];
17
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT);
18
+ let node;
19
+ while ((node = walker.nextNode())) {
20
+ const text = (node.nodeValue || '').trim();
21
+ if (text.startsWith('pru-cms:')) {
22
+ const parts = text.slice('pru-cms:'.length).split(':');
23
+ if (parts.length === 4 && parts[3] === '__body') {
24
+ stack.push({
25
+ start: node,
26
+ collection: decodePart(parts[0]),
27
+ slug: decodePart(parts[1]),
28
+ locale: decodePart(parts[2]) || undefined,
29
+ });
30
+ }
31
+ } else if (text === '/pru-cms' && stack.length > 0) {
32
+ const opened = stack.pop();
33
+ if (opened.start.parentNode === node.parentNode) {
34
+ anchors.push({ ...opened, end: node });
35
+ }
36
+ }
37
+ }
38
+ return anchors;
39
+ }
40
+
41
+ function isNodeInsideBodyAnchor(node, anchors) {
42
+ for (const a of anchors) {
43
+ const parent = a.start.parentNode;
44
+ if (!parent) continue;
45
+ let cur = a.start.nextSibling;
46
+ while (cur && cur !== a.end) {
47
+ if (cur === node || (cur.nodeType === 1 && cur.contains(node))) return true;
48
+ cur = cur.nextSibling;
49
+ }
50
+ }
51
+ return false;
52
+ }
53
+
54
+ function measureAnchorRect(anchor) {
55
+ let top = Infinity, left = Infinity, right = -Infinity, bottom = -Infinity;
56
+ let found = false;
57
+ let cur = anchor.start.nextSibling;
58
+ while (cur && cur !== anchor.end) {
59
+ if (cur.nodeType === 1) {
60
+ const r = cur.getBoundingClientRect();
61
+ if (r.width > 0 || r.height > 0) {
62
+ found = true;
63
+ top = Math.min(top, r.top);
64
+ left = Math.min(left, r.left);
65
+ right = Math.max(right, r.right);
66
+ bottom = Math.max(bottom, r.bottom);
67
+ }
68
+ }
69
+ cur = cur.nextSibling;
70
+ }
71
+ if (!found && anchor.start.parentElement) {
72
+ const pr = anchor.start.parentElement.getBoundingClientRect();
73
+ return { top: pr.top, left: pr.left, width: Math.max(pr.width, 40), height: Math.max(pr.height, 28) };
74
+ }
75
+ if (!found) return null;
76
+ return { top, left, width: Math.max(right - left, 24), height: Math.max(bottom - top, 24) };
77
+ }
78
+
79
+ function captureAnchorHtml(anchor) {
80
+ const tmp = document.createElement('div');
81
+ let cur = anchor.start.nextSibling;
82
+ while (cur && cur !== anchor.end) {
83
+ tmp.appendChild(cur.cloneNode(true));
84
+ cur = cur.nextSibling;
85
+ }
86
+ return tmp.innerHTML;
87
+ }
88
+
89
+ function replaceAnchorHtml(anchor, html) {
90
+ const parent = anchor.start.parentNode;
91
+ if (!parent) return;
92
+ let cur = anchor.start.nextSibling;
93
+ while (cur && cur !== anchor.end) {
94
+ const next = cur.nextSibling;
95
+ parent.removeChild(cur);
96
+ cur = next;
97
+ }
98
+ const tpl = document.createElement('template');
99
+ tpl.innerHTML = html;
100
+ parent.insertBefore(tpl.content, anchor.end);
101
+ }
102
+
103
+ function collectStringFieldDefs(entry, data) {
104
+ const defs = [];
105
+ if (Array.isArray(entry.fields)) {
106
+ const walk = (fields, prefix) => {
107
+ for (const f of fields) {
108
+ const path = prefix ? prefix + '.' + f.key : f.key;
109
+ if (f.kind === 'object' && Array.isArray(f.fields)) {
110
+ walk(f.fields, path);
111
+ } else if (f.kind === 'text' || f.kind === 'textarea' || f.kind === 'email' || f.kind === 'url') {
112
+ defs.push({ path, label: f.label, multiline: f.kind === 'textarea' });
113
+ }
114
+ }
115
+ };
116
+ walk(entry.fields, '');
117
+ } else if (data && typeof data === 'object') {
118
+ for (const [k, v] of Object.entries(data)) {
119
+ if (typeof v === 'string') defs.push({ path: k, label: k, multiline: v.includes('\\n') });
120
+ }
121
+ }
122
+ return defs;
123
+ }
124
+
125
+ function findMatchingFieldTargets(entry, data, anchors) {
126
+ const defs = collectStringFieldDefs(entry, data);
127
+ const scope = document.querySelector('main') || document.body;
128
+ const targets = [];
129
+ const claimed = new Set();
130
+
131
+ const walkElements = (root) => {
132
+ const matched = [];
133
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
134
+ let tn;
135
+ while ((tn = walker.nextNode())) {
136
+ const parent = tn.parentElement;
137
+ if (!parent || SKIP_TAGS.has(parent.tagName) || parent.closest('pru-cms-overlay')) continue;
138
+ if (isNodeInsideBodyAnchor(parent, anchors)) continue;
139
+ const txt = (tn.nodeValue || '').trim();
140
+ if (txt.length < 2) continue;
141
+ matched.push({ el: parent, text: txt });
142
+ }
143
+ return matched;
144
+ };
145
+
146
+ const candidates = walkElements(scope);
147
+ const allCandidates = scope === document.body ? candidates : null;
148
+
149
+ for (const def of defs) {
150
+ const raw = getNestedValue(data, def.path);
151
+ if (typeof raw !== 'string') continue;
152
+ const needle = raw.trim();
153
+ if (needle.length < 2) continue;
154
+ let hit = candidates.find(c => !claimed.has(c.el) && c.el.textContent.trim() === needle);
155
+ if (!hit && allCandidates === null) {
156
+ const fallback = walkElements(document.body);
157
+ hit = fallback.find(c => !claimed.has(c.el) && c.el.textContent.trim() === needle);
158
+ }
159
+ if (hit) {
160
+ claimed.add(hit.el);
161
+ targets.push({ ...def, el: hit.el, originalText: hit.el.textContent });
162
+ }
163
+ }
164
+ return targets;
165
+ }
166
+ `
@@ -0,0 +1,465 @@
1
+ // Client-side schema-driven form builder fragment for @prunellejs/cms in-page slide-over drawer.
2
+ // Uses DOM APIs (createElement / textContent) exclusively so user content is never interpolated into innerHTML.
3
+
4
+ export const INLINE_FORM_JS = `
5
+ function el(tag, attrs, text) {
6
+ const node = document.createElement(tag);
7
+ if (attrs) {
8
+ for (const [k, v] of Object.entries(attrs)) {
9
+ if (v === undefined || v === null || v === false) continue;
10
+ if (v === true) node.setAttribute(k, '');
11
+ else node.setAttribute(k, String(v));
12
+ }
13
+ }
14
+ if (text !== undefined && text !== null) node.textContent = String(text);
15
+ return node;
16
+ }
17
+
18
+ function cloneVal(val) {
19
+ if (val === null || val === undefined || typeof val !== 'object') return val;
20
+ if (Array.isArray(val)) return val.map(cloneVal);
21
+ const out = {};
22
+ for (const [k, v] of Object.entries(val)) out[k] = cloneVal(v);
23
+ return out;
24
+ }
25
+
26
+ function formatFieldValue(field, value) {
27
+ if (value === undefined || value === null) return '';
28
+ if (field.kind === 'tags') return Array.isArray(value) ? value.map(String).join(', ') : String(value);
29
+ const str = String(value);
30
+ if (field.kind === 'date' && /^\\d{4}-\\d{2}-\\d{2}T/.test(str)) return str.slice(0, 10);
31
+ if (field.kind === 'datetime' && /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}/.test(str)) return str.slice(0, 16);
32
+ return str;
33
+ }
34
+
35
+ function scalarInputType(kind) {
36
+ if (kind === 'date') return 'date';
37
+ if (kind === 'datetime') return 'datetime-local';
38
+ if (kind === 'email') return 'email';
39
+ if (kind === 'url') return 'url';
40
+ if (kind === 'number' || kind === 'integer') return 'number';
41
+ return 'text';
42
+ }
43
+
44
+ function parseScalarInput(field, raw) {
45
+ if (field.kind === 'number' || field.kind === 'integer') {
46
+ const t = raw.trim();
47
+ if (t === '') return undefined;
48
+ const n = Number(t);
49
+ return Number.isFinite(n) ? n : raw;
50
+ }
51
+ if (field.kind === 'tags') {
52
+ const items = raw.split(/[,\\r\\n]+/).map(s => s.trim()).filter(Boolean);
53
+ return items;
54
+ }
55
+ if (field.kind === 'enum') {
56
+ if (raw === '' && !field.required) return undefined;
57
+ if (field.enumType === 'number') {
58
+ const n = Number(raw);
59
+ return Number.isFinite(n) ? n : raw;
60
+ }
61
+ return raw;
62
+ }
63
+ if (raw === '' && !field.required) return undefined;
64
+ return raw;
65
+ }
66
+
67
+ function setNestedValue(obj, path, value) {
68
+ const parts = [];
69
+ const re = /([^.[\\]]+)|\\[(\\d+)\\]/g;
70
+ let m;
71
+ while ((m = re.exec(path)) !== null) {
72
+ parts.push(m[1] !== undefined ? m[1] : Number(m[2]));
73
+ }
74
+ if (parts.length === 0) return;
75
+ let cur = obj;
76
+ for (let i = 0; i < parts.length - 1; i++) {
77
+ const key = parts[i];
78
+ const nextKey = parts[i + 1];
79
+ if (cur[key] === undefined || cur[key] === null || typeof cur[key] !== 'object') {
80
+ cur[key] = typeof nextKey === 'number' ? [] : {};
81
+ }
82
+ cur = cur[key];
83
+ }
84
+ const last = parts[parts.length - 1];
85
+ if (value === undefined) delete cur[last];
86
+ else cur[last] = value;
87
+ }
88
+
89
+ function getNestedValue(obj, path) {
90
+ const parts = [];
91
+ const re = /([^.[\\]]+)|\\[(\\d+)\\]/g;
92
+ let m;
93
+ while ((m = re.exec(path)) !== null) {
94
+ parts.push(m[1] !== undefined ? m[1] : Number(m[2]));
95
+ }
96
+ let cur = obj;
97
+ for (const key of parts) {
98
+ if (cur === null || cur === undefined || typeof cur !== 'object') return undefined;
99
+ cur = cur[key];
100
+ }
101
+ return cur;
102
+ }
103
+
104
+ function buildSchemaForm(container, entry, draftData, errors, onFieldChange, onRerender) {
105
+ container.textContent = '';
106
+
107
+ if (entry.schemaWarning) {
108
+ container.appendChild(el('div', { class: 'pru-notice', role: 'status' }, entry.schemaWarning));
109
+ }
110
+
111
+ const errEntries = Object.entries(errors || {});
112
+ if (errEntries.length > 0) {
113
+ const notice = el('div', { class: 'pru-notice', 'data-tone': 'error', role: 'alert' });
114
+ notice.appendChild(el('strong', null, 'Please fix the following errors:'));
115
+ const list = el('ul', { class: 'pru-err-list' });
116
+ for (const [k, msg] of errEntries) {
117
+ list.appendChild(el('li', null, k ? k + ': ' + msg : msg));
118
+ }
119
+ notice.appendChild(list);
120
+ container.appendChild(notice);
121
+ }
122
+
123
+ if (!entry.fields) {
124
+ const wrap = el('div', { class: 'pru-field' });
125
+ wrap.appendChild(el('label', { for: 'pru-raw-yaml' }, 'Frontmatter (YAML)'));
126
+ const ta = el('textarea', {
127
+ id: 'pru-raw-yaml',
128
+ class: 'pru-textarea pru-md-textarea',
129
+ 'aria-invalid': errors && errors.__frontmatter_yaml ? 'true' : undefined,
130
+ });
131
+ ta.value = entry.rawFrontmatterYaml || '';
132
+ ta.addEventListener('input', () => onFieldChange('__frontmatter_yaml', ta.value));
133
+ wrap.appendChild(ta);
134
+ if (errors && errors.__frontmatter_yaml) {
135
+ wrap.appendChild(el('p', { class: 'pru-err', role: 'alert' }, errors.__frontmatter_yaml));
136
+ }
137
+ container.appendChild(wrap);
138
+ return;
139
+ }
140
+
141
+ function appendMeta(parent, id, hint, err) {
142
+ if (hint) parent.appendChild(el('p', { id: id + '-hint', class: 'pru-hint' }, hint));
143
+ if (err) parent.appendChild(el('p', { id: id + '-err', class: 'pru-err', role: 'alert' }, err));
144
+ }
145
+
146
+ function renderFieldNode(field, path, value) {
147
+ const id = 'pru-f-' + path.replace(/[^a-zA-Z0-9_-]/g, '_');
148
+ const err = errors ? errors[path] : undefined;
149
+
150
+ if (field.kind === 'boolean') {
151
+ const wrap = el('div', { class: 'pru-field' });
152
+ const lbl = el('label', { class: 'pru-switch', for: id });
153
+ const cb = el('input', {
154
+ type: 'checkbox',
155
+ role: 'switch',
156
+ id,
157
+ 'aria-invalid': err ? 'true' : undefined,
158
+ });
159
+ cb.checked = value === true;
160
+ cb.addEventListener('change', () => onFieldChange(path, cb.checked));
161
+ lbl.appendChild(cb);
162
+ lbl.appendChild(el('span', null, field.label));
163
+ wrap.appendChild(lbl);
164
+ appendMeta(wrap, id, field.description, err);
165
+ return wrap;
166
+ }
167
+
168
+ if (field.kind === 'enum') {
169
+ const wrap = el('div', { class: 'pru-field' });
170
+ const lbl = el('label', { for: id }, field.label);
171
+ if (field.required) lbl.appendChild(el('span', { class: 'pru-req', 'aria-hidden': 'true' }, '*'));
172
+ wrap.appendChild(lbl);
173
+ const sel = el('select', {
174
+ id,
175
+ class: 'pru-select',
176
+ required: field.required,
177
+ 'aria-invalid': err ? 'true' : undefined,
178
+ });
179
+ const cur = value === undefined || value === null ? '' : String(value);
180
+ if (!field.required) {
181
+ const opt = el('option', { value: '' }, '— Select —');
182
+ opt.selected = cur === '';
183
+ sel.appendChild(opt);
184
+ }
185
+ for (const o of field.options || []) {
186
+ const s = String(o);
187
+ const opt = el('option', { value: s }, s);
188
+ opt.selected = s === cur;
189
+ sel.appendChild(opt);
190
+ }
191
+ sel.addEventListener('change', () => onFieldChange(path, parseScalarInput(field, sel.value)));
192
+ wrap.appendChild(sel);
193
+ appendMeta(wrap, id, field.description, err);
194
+ return wrap;
195
+ }
196
+
197
+ if (field.kind === 'object') {
198
+ const fs = el('fieldset', { class: 'pru-fieldset', id });
199
+ const leg = el('legend', null, field.label);
200
+ if (field.required) leg.appendChild(el('span', { class: 'pru-req', 'aria-hidden': 'true' }, '*'));
201
+ fs.appendChild(leg);
202
+ appendMeta(fs, id, field.description, err);
203
+ const rec = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
204
+ for (const child of field.fields || []) {
205
+ fs.appendChild(renderFieldNode(child, path + '.' + child.key, rec[child.key]));
206
+ }
207
+ return fs;
208
+ }
209
+
210
+ if (field.kind === 'object-array') {
211
+ const fs = el('fieldset', { class: 'pru-fieldset', id });
212
+ const leg = el('legend', null, field.label);
213
+ if (field.required) leg.appendChild(el('span', { class: 'pru-req', 'aria-hidden': 'true' }, '*'));
214
+ fs.appendChild(leg);
215
+ appendMeta(fs, id, field.description, err);
216
+ const rows = Array.isArray(value) ? value : [];
217
+ rows.forEach((rowVal, idx) => {
218
+ const card = el('div', { class: 'pru-row-card' });
219
+ const head = el('div', { class: 'pru-row-head' });
220
+ head.appendChild(el('strong', null, 'Row ' + (idx + 1)));
221
+ const btns = el('div', { class: 'pru-row-btns' });
222
+ const upBtn = el('button', { type: 'button', class: 'pru-btn pru-btn-sm', disabled: idx === 0 }, '↑');
223
+ upBtn.setAttribute('aria-label', 'Move ' + field.label + ' row ' + (idx + 1) + ' up');
224
+ upBtn.addEventListener('click', () => {
225
+ const next = rows.slice();
226
+ [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
227
+ onFieldChange(path, next);
228
+ onRerender();
229
+ });
230
+ const dnBtn = el('button', { type: 'button', class: 'pru-btn pru-btn-sm', disabled: idx === rows.length - 1 }, '↓');
231
+ dnBtn.setAttribute('aria-label', 'Move ' + field.label + ' row ' + (idx + 1) + ' down');
232
+ dnBtn.addEventListener('click', () => {
233
+ const next = rows.slice();
234
+ [next[idx + 1], next[idx]] = [next[idx], next[idx + 1]];
235
+ onFieldChange(path, next);
236
+ onRerender();
237
+ });
238
+ const rmBtn = el('button', { type: 'button', class: 'pru-btn pru-btn-sm pru-btn-danger' }, 'Remove');
239
+ rmBtn.addEventListener('click', () => {
240
+ const next = rows.slice();
241
+ next.splice(idx, 1);
242
+ onFieldChange(path, next);
243
+ onRerender();
244
+ });
245
+ btns.append(upBtn, dnBtn, rmBtn);
246
+ head.appendChild(btns);
247
+ card.appendChild(head);
248
+ const rec = rowVal && typeof rowVal === 'object' && !Array.isArray(rowVal) ? rowVal : {};
249
+ for (const child of field.fields || []) {
250
+ card.appendChild(renderFieldNode(child, path + '[' + idx + '].' + child.key, rec[child.key]));
251
+ }
252
+ fs.appendChild(card);
253
+ });
254
+ const addBtn = el('button', { type: 'button', class: 'pru-btn pru-btn-sm' }, '+ Add ' + field.label + ' row');
255
+ addBtn.addEventListener('click', () => {
256
+ onFieldChange(path, [...rows, {}]);
257
+ onRerender();
258
+ });
259
+ fs.appendChild(addBtn);
260
+ return fs;
261
+ }
262
+
263
+ const wrap = el('div', { class: 'pru-field' });
264
+ const lbl = el('label', { for: id }, field.label);
265
+ if (field.required) lbl.appendChild(el('span', { class: 'pru-req', 'aria-hidden': 'true' }, '*'));
266
+ wrap.appendChild(lbl);
267
+ const valStr = formatFieldValue(field, value);
268
+ let control;
269
+ if (field.kind === 'textarea') {
270
+ control = el('textarea', {
271
+ id,
272
+ class: 'pru-textarea',
273
+ required: field.required,
274
+ 'aria-invalid': err ? 'true' : undefined,
275
+ });
276
+ control.value = valStr;
277
+ } else {
278
+ control = el('input', {
279
+ type: scalarInputType(field.kind),
280
+ id,
281
+ class: 'pru-input',
282
+ required: field.required,
283
+ min: field.min,
284
+ max: field.max,
285
+ step: field.step,
286
+ minlength: field.minLength,
287
+ maxlength: field.maxLength,
288
+ pattern: field.pattern,
289
+ 'aria-invalid': err ? 'true' : undefined,
290
+ });
291
+ control.value = valStr;
292
+ }
293
+ control.addEventListener('input', () => {
294
+ onFieldChange(path, parseScalarInput(field, control.value));
295
+ });
296
+ wrap.appendChild(control);
297
+ const hint = field.kind === 'tags'
298
+ ? (field.description ? field.description + ' (comma-separated)' : 'Comma-separated list of tags')
299
+ : field.description;
300
+ appendMeta(wrap, id, hint, err);
301
+ return wrap;
302
+ }
303
+
304
+ for (const field of entry.fields) {
305
+ container.appendChild(renderFieldNode(field, field.key, draftData[field.key]));
306
+ }
307
+ }
308
+
309
+ function createDrawerController(deps) {
310
+ const { drawer, state, saveSessionState, renderToolbar, renderHighlights, matchingBodyAnchors, replaceAnchorHtml, scheduleBodyPreview, setDirty, persistInline } = deps;
311
+ let footerEl = null;
312
+
313
+ function renderFooter() {
314
+ if (!footerEl) return;
315
+ footerEl.textContent = '';
316
+
317
+ const fullLink = state.entry && state.entry.editUrl
318
+ ? el('a', { class: 'pru-btn pru-btn-ghost pru-btn-sm', href: state.entry.editUrl }, 'Open full CMS')
319
+ : el('span', { class: 'pru-hint' }, '');
320
+
321
+ const actions = el('div', { class: 'pru-foot-actions' });
322
+ const revertBtn = el('button', {
323
+ type: 'button',
324
+ class: 'pru-btn pru-btn-sm',
325
+ disabled: !state.dirty || state.saving,
326
+ }, 'Revert');
327
+ revertBtn.addEventListener('click', () => {
328
+ if (!state.entry) return;
329
+ state.draftData = cloneVal(state.entry.data || {});
330
+ state.draftYaml = state.entry.rawFrontmatterYaml || '';
331
+ state.draftBody = state.entry.body || '';
332
+ state.errors = {};
333
+ for (const t of state.fieldTargets) t.el.textContent = t.originalText;
334
+ for (const a of matchingBodyAnchors()) {
335
+ const orig = state.originalBodyHtml.get(a);
336
+ if (orig !== undefined) replaceAnchorHtml(a, orig);
337
+ }
338
+ setDirty(false);
339
+ render();
340
+ renderHighlights();
341
+ });
342
+
343
+ const saveBtn = el('button', {
344
+ type: 'button',
345
+ class: 'pru-btn pru-btn-sm pru-btn-primary',
346
+ disabled: !state.dirty || state.saving,
347
+ }, state.saving ? 'Saving…' : 'Save changes');
348
+ saveBtn.addEventListener('click', () => void save());
349
+
350
+ actions.append(revertBtn, saveBtn);
351
+ footerEl.append(fullLink, actions);
352
+ }
353
+
354
+ async function save() {
355
+ if (!state.entry) return;
356
+ const payload = {
357
+ collection: state.activeRef.collection,
358
+ slug: state.activeRef.slug,
359
+ locale: state.activeRef.locale,
360
+ body: state.draftBody,
361
+ ...(state.entry.fields ? { data: state.draftData } : { rawFrontmatterYaml: state.draftYaml }),
362
+ };
363
+ await persistInline(payload);
364
+ }
365
+
366
+ function render() {
367
+ drawer.hidden = !state.drawerOpen;
368
+ if (!state.drawerOpen) return;
369
+ drawer.textContent = '';
370
+
371
+ const head = el('div', { class: 'pru-drawer-head' });
372
+ const titleWrap = el('div', { class: 'pru-drawer-title-wrap' });
373
+ const titleText = (state.draftData && typeof state.draftData.title === 'string' && state.draftData.title.trim())
374
+ ? state.draftData.title
375
+ : state.activeRef.slug;
376
+ titleWrap.appendChild(el('h2', { class: 'pru-drawer-title' }, titleText));
377
+ titleWrap.appendChild(el('p', { class: 'pru-drawer-sub' },
378
+ state.activeRef.collection + '/' + state.activeRef.slug + (state.activeRef.locale ? ' · ' + state.activeRef.locale : ''),
379
+ ));
380
+ const closeBtn = el('button', { type: 'button', class: 'pru-btn pru-btn-sm', 'aria-label': 'Close CMS panel' }, 'Close');
381
+ closeBtn.addEventListener('click', () => {
382
+ state.drawerOpen = false;
383
+ saveSessionState();
384
+ renderToolbar();
385
+ render();
386
+ });
387
+ head.append(titleWrap, closeBtn);
388
+
389
+ const tabs = el('div', { class: 'pru-tabs', role: 'tablist', 'aria-label': 'Editor sections' });
390
+ const fieldsTab = el('button', {
391
+ type: 'button',
392
+ role: 'tab',
393
+ class: 'pru-tab',
394
+ 'aria-selected': state.tab === 'fields' ? 'true' : 'false',
395
+ }, 'Frontmatter');
396
+ fieldsTab.addEventListener('click', () => {
397
+ state.tab = 'fields';
398
+ saveSessionState();
399
+ render();
400
+ });
401
+ const mdTab = el('button', {
402
+ type: 'button',
403
+ role: 'tab',
404
+ class: 'pru-tab',
405
+ 'aria-selected': state.tab === 'markdown' ? 'true' : 'false',
406
+ }, 'Markdown body');
407
+ mdTab.addEventListener('click', () => {
408
+ state.tab = 'markdown';
409
+ saveSessionState();
410
+ render();
411
+ });
412
+ tabs.append(fieldsTab, mdTab);
413
+
414
+ const body = el('div', { class: 'pru-drawer-body', role: 'tabpanel' });
415
+ if (!state.entry) {
416
+ body.appendChild(el('p', { class: 'pru-hint' }, 'Loading entry…'));
417
+ } else if (state.tab === 'fields') {
418
+ buildSchemaForm(
419
+ body,
420
+ state.entry,
421
+ state.draftData,
422
+ state.errors,
423
+ (path, value) => {
424
+ if (path === '__frontmatter_yaml') {
425
+ state.draftYaml = String(value);
426
+ } else {
427
+ setNestedValue(state.draftData, path, value);
428
+ if (typeof value === 'string') {
429
+ for (const t of state.fieldTargets) {
430
+ if (t.path === path) t.el.textContent = value;
431
+ }
432
+ if (state.editMode) deps.scheduleHighlights();
433
+ }
434
+ }
435
+ setDirty(true);
436
+ },
437
+ () => render(),
438
+ );
439
+ } else {
440
+ const wrap = el('div', { class: 'pru-field pru-field-grow' });
441
+ wrap.appendChild(el('label', { for: 'pru-drawer-body' }, 'Markdown content'));
442
+ wrap.appendChild(el('p', { class: 'pru-hint' },
443
+ matchingBodyAnchors().length > 0
444
+ ? 'Changes preview live inside the page as you type. Press Save to write the .md file.'
445
+ : 'Edit Markdown below and press Save to update the .md file.',
446
+ ));
447
+ const ta = el('textarea', { id: 'pru-drawer-body', class: 'pru-textarea pru-md-textarea' });
448
+ ta.value = state.draftBody;
449
+ ta.addEventListener('input', () => {
450
+ state.draftBody = ta.value;
451
+ setDirty(true);
452
+ scheduleBodyPreview(ta.value);
453
+ });
454
+ wrap.appendChild(ta);
455
+ body.appendChild(wrap);
456
+ }
457
+
458
+ footerEl = el('div', { class: 'pru-drawer-foot' });
459
+ renderFooter();
460
+ drawer.append(head, tabs, body, footerEl);
461
+ }
462
+
463
+ return { render, renderFooter, save };
464
+ }
465
+ `