-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathguide_render.js
More file actions
436 lines (388 loc) · 17.3 KB
/
guide_render.js
File metadata and controls
436 lines (388 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/* ═══════════════════════════════════════════════════════════════════════
guide_render.js — Retro Guide Panel Renderer v3.0
Shared by guide_engine.js and builder.js.
Styles are in guide_render.css — link that in your HTML.
Usage:
const ctx = { save: (id,v)=>..., load: (id)=>..., preview: false };
const el = GuideRender.panel(panelDef, ctx);
container.appendChild(el);
Internal links in text content:
[text](2) → link to tab 2 (1-based)
[text](2, 3) → link to panel 3 on tab 2 (both 1-based)
The host page is responsible for handling click events on .gr-internal-link.
Exports: window.GuideRender = { panel, injectStyles, md, uid }
═══════════════════════════════════════════════════════════════════════ */
(function (global) {
'use strict';
/** No-op stub — styles are now in guide_render.css. */
function injectStyles() {}
// ── UTILITIES ─────────────────────────────────────────────────────────
function esc(s) {
return String(s ?? '')
.replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}
/** Minimal markdown → HTML. Input is plain text (not pre-escaped). */
function md(s) {
if (!s) return '';
let h = esc(s);
// Headers
h = h.replace(/^### (.+)$/gm, '<h3 class="gr-h3">$1</h3>');
h = h.replace(/^## (.+)$/gm, '<h3 class="gr-h3">$1</h3>');
// Horizontal rules (before inline processing)
h = h.replace(/^---$/gm, '<hr class="gr-hr">');
h = h.replace(/^===$/gm, '<hr class="gr-hr2">');
// Bold / italic
h = h.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
h = h.replace(/\*(.+?)\*/g, '<em>$1</em>');
// Inline code
h = h.replace(/`(.+?)`/g, '<code class="gr-code">$1</code>');
// Internal links — must run before external link regex.
// Tab + panel: [text](tab, panel) — both 1-based.
h = h.replace(
/\[(.+?)\]\(\s*(\d+)\s*,\s*(\d+)\s*\)/g,
'<span class="gr-internal-link" tab="$2" panel="$3">$1</span>'
);
// Tab only: [text](tab) — 1-based.
h = h.replace(
/\[(.+?)\]\(\s*(\d+)\s*\)/g,
'<span class="gr-internal-link" tab="$2" panel="none">$1</span>'
);
// External links
h = h.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2" class="gr-link" target="_blank" rel="noopener">$1</a>');
// Blockquotes — > is escaped to > by esc()
h = h.replace(/((?:^> .+$\n?)+)/gm, (block) => {
const inner = block.trim().split('\n')
.map(l => l.replace(/^> /, '')).join('<br>');
return `<blockquote class="gr-blockquote">${inner}</blockquote>`;
});
// Unordered lists (collect consecutive li items)
h = h.replace(/((?:^- .+$\n?)+)/gm, (block) => {
const items = block.trim().split('\n').map(l => `<li>${l.replace(/^- /, '')}</li>`).join('');
return `<ul class="gr-ul">${items}</ul>`;
});
// Collapsible boxes: [label]{content} — runs before paragraph wrapper
h = h.replace(/\[([^\]]+)\]\{([\s\S]*?)\}/g, (_, label, content) => {
const body = content.trim().replace(/\n/g, '<br>');
return `<div class="gr-box gr-collapsed"><div class="gr-box-header"><span class="gr-box-toggle">▾</span> ${label}</div><div class="gr-box-body">${body}</div></div>`;
});
// Paragraphs — split on blank lines, skip block elements
const blocks = h.split(/\n\n+/);
return blocks.map(b => {
b = b.trim();
if (!b) return '';
if (/^<(h3|ul|ol|hr|blockquote|div)/.test(b)) return b;
return `<p class="gr-p">${b.replace(/\n/g, '<br>')}</p>`;
}).join('');
}
/** Collision-resistant ID for new items. */
function uid(prefix) {
return (prefix || 'id') + '_' + Math.random().toString(36).slice(2, 9);
}
// ── PANEL ENTRY POINT ─────────────────────────────────────────────────
function panel(def, ctx) {
ctx = Object.assign({ save: () => {}, load: () => false, preview: true }, ctx);
const wrap = document.createElement('div');
wrap.className = 'gr-panel-wrap';
if (def.id) wrap.dataset.panelId = def.id;
const card = document.createElement('div');
card.className = 'gr-card';
const header = document.createElement('div');
header.className = 'gr-card-header';
const titleSpan = document.createElement('span');
titleSpan.className = 'gr-card-title';
titleSpan.textContent = def.title || '(Untitled Panel)';
const toggle = document.createElement('span');
toggle.className = 'gr-card-toggle';
toggle.textContent = '▾';
header.append(titleSpan, toggle);
// Collapse state: default collapsed. Persist per panel id.
const colKey = def.id ? '__c_' + def.id : null;
const isExpanded = colKey ? ctx.load(colKey) : false;
if (!isExpanded) card.classList.add('gr-collapsed');
const body = document.createElement('div');
body.className = 'gr-card-body';
try {
body.appendChild(renderContent(def, ctx));
} catch (e) {
body.innerHTML = `<div style="color:#c04040;padding:8px;font-size:12px">⚠️ Render error: ${esc(e.message)}</div>`;
}
card.append(header, body);
// Add click handler for collapse/expand
header.addEventListener('click', () => {
const nowCollapsed = card.classList.toggle('gr-collapsed');
if (colKey) ctx.save(colKey, !nowCollapsed);
});
wrap.appendChild(card);
return wrap;
}
// ── CONTENT DISPATCH ─────────────────────────────────────────────────
function renderContent(def, ctx) {
switch (def.panelType) {
case 'text': return renderText(def);
case 'keyvalue': return renderKeyValue(def);
case 'checklist': return renderChecklist(def, ctx);
case 'table': return renderTable(def);
case 'cards': return renderCards(def);
case 'cardgrid': return renderCardGrid(def);
default: {
const d = document.createElement('div');
d.style.cssText = 'padding:8px;font-size:12px;color:var(--textMuted)';
d.textContent = 'Unknown panel type: ' + (def.panelType || '(none)');
return d;
}
}
}
// ── TEXT ──────────────────────────────────────────────────────────────
function renderText(def) {
const wrap = document.createElement('div');
if (def.infobox) {
const ib = document.createElement('div');
ib.className = 'gr-infobox';
ib.innerHTML = md(def.infobox);
wrap.appendChild(ib);
}
const content = document.createElement('div');
content.className = 'gr-text';
content.innerHTML = md(def.content || '');
wrap.appendChild(content);
return wrap;
}
// ── KEY-VALUE ─────────────────────────────────────────────────────────
function renderKeyValue(def) {
const rows = def.rows || [];
const tw = document.createElement('div');
tw.className = 'gr-table-wrap';
const table = document.createElement('table');
table.className = 'gr-kv-table';
rows.forEach(row => {
const tr = document.createElement('tr');
const k = document.createElement('td');
k.className = 'gr-kv-key';
k.textContent = row.key || '';
const v = document.createElement('td');
v.className = 'gr-kv-val';
v.innerHTML = md(String(row.value ?? ''));
tr.append(k, v);
table.appendChild(tr);
});
tw.appendChild(table);
return tw;
}
// ── CHECKLIST ─────────────────────────────────────────────────────────
function renderChecklist(def, ctx) {
const entryKey = Object.keys(def).find(k => k.startsWith('entry_'));
const items = (entryKey ? def[entryKey] : def.items) || [];
const columns = def.columns || [];
const wrap = document.createElement('div');
if (def.infobox) {
const ib = document.createElement('div');
ib.className = 'gr-infobox';
ib.innerHTML = md(def.infobox);
wrap.appendChild(ib);
}
// Progress bar (live mode only)
let progressWrap = null;
if (!ctx.preview && items.length) {
const total = items.length;
const done = items.filter(it => ctx.load(it.id)).length;
const pct = Math.round(done / total * 100);
progressWrap = document.createElement('div');
progressWrap.className = 'gr-progress-wrap';
progressWrap.innerHTML = `
<div class="gr-progress-bar"><div class="gr-progress-fill" style="width:${pct}%"></div></div>
<div class="gr-progress-label"><span class="gr-progress-count">${done}</span> / ${total}</div>`;
wrap.appendChild(progressWrap);
}
const tw = document.createElement('div');
tw.className = 'gr-table-wrap';
const table = document.createElement('table');
table.className = 'gr-check-table';
// Header row
const thead = document.createElement('thead');
const htr = document.createElement('tr');
const cbTh = document.createElement('th'); cbTh.style.width = '36px';
const numTh = document.createElement('th'); numTh.style.width = '36px'; numTh.textContent = '#';
htr.append(cbTh, numTh);
columns.forEach(col => {
const th = document.createElement('th');
th.textContent = col.label || '';
htr.appendChild(th);
});
thead.appendChild(htr);
table.appendChild(thead);
// Rows
const tbody = document.createElement('tbody');
items.forEach((item, index) => {
const checked = ctx.load(item.id);
const tr = document.createElement('tr');
tr.className = 'gr-check-row' + (checked ? ' gr-checked' : '');
tr.dataset.itemId = item.id;
const cbTd = document.createElement('td');
cbTd.className = 'gr-cb-col';
const cb = document.createElement('span');
cb.className = 'gr-checkbox' + (checked ? ' gr-checked' : '');
if (checked) cb.textContent = '✓';
cbTd.appendChild(cb);
tr.appendChild(cbTd);
const numTd = document.createElement('td');
numTd.className = 'gr-check-num';
numTd.textContent = (index + 1).toString();
tr.appendChild(numTd);
columns.forEach(col => {
const td = document.createElement('td');
td.className = 'gr-check-cell ' + (col.style === 'accent' ? 'gr-accent' : col.style === 'dim' ? 'gr-dim' : '');
td.textContent = item[col.key] || '';
if (item.note && col.key === columns[0]?.key) {
const note = document.createElement('div');
note.className = 'gr-check-note';
note.textContent = item.note;
td.appendChild(note);
}
tr.appendChild(td);
});
tr.addEventListener('click', e => {
e.stopPropagation();
const now = tr.classList.toggle('gr-checked');
cb.classList.toggle('gr-checked', now);
cb.textContent = now ? '✓' : '';
ctx.save(item.id, now);
if (progressWrap) {
const total = items.length;
const done = items.filter(it => ctx.load(it.id)).length;
const fill = progressWrap.querySelector('.gr-progress-fill');
const count = progressWrap.querySelector('.gr-progress-count');
if (fill) fill.style.width = Math.round(done / total * 100) + '%';
if (count) count.textContent = done;
}
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
tw.appendChild(table);
wrap.appendChild(tw);
return wrap;
}
// ── TABLE ─────────────────────────────────────────────────────────────
function renderTable(def) {
const columns = def.columns || [];
const rows = def.rows || [];
const tw = document.createElement('div');
tw.className = 'gr-table-wrap';
const table = document.createElement('table');
if (columns.length) {
const thead = document.createElement('thead');
const htr = document.createElement('tr');
columns.forEach(col => {
const th = document.createElement('th');
th.textContent = typeof col === 'string' ? col : (col.label || col.key || '');
htr.appendChild(th);
});
thead.appendChild(htr);
table.appendChild(thead);
}
const tbody = document.createElement('tbody');
rows.forEach(row => {
const tr = document.createElement('tr');
const cells = Array.isArray(row)
? row
: columns.map(c => row[typeof c === 'string' ? c : (c.key || c.label || '')] ?? '');
cells.forEach(cell => {
const td = document.createElement('td');
td.innerHTML = md(String(cell ?? ''));
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
tw.appendChild(table);
return tw;
}
// ── CARDS ─────────────────────────────────────────────────────────────
function renderCards(def) {
const cardFields = def.cardFields || [];
const cards = def.cards || [];
const wrap = document.createElement('div');
wrap.className = 'gr-cards';
cards.forEach(card => {
const el = document.createElement('div');
el.className = 'gr-card-item';
cardFields.forEach((field, idx) => {
const val = card[field.key];
if (!val && val !== 0) return;
if (idx === 0) {
const name = document.createElement('div');
name.className = 'gr-card-name';
name.textContent = String(val);
el.appendChild(name);
} else {
const row = document.createElement('div');
row.className = 'gr-card-row';
const lbl = document.createElement('span');
lbl.className = 'gr-card-label';
lbl.textContent = (field.label || field.key) + ': ';
const valSpan = document.createElement('span');
valSpan.className = 'gr-card-value';
valSpan.innerHTML = md(String(val));
row.append(lbl, valSpan);
el.appendChild(row);
}
});
wrap.appendChild(el);
});
return wrap;
}
// ── CARD GRID ─────────────────────────────────────────────────────────
function renderCardGrid(def) {
const entryKey = Object.keys(def).find(k => k.startsWith('entry_'));
const items = (entryKey ? def[entryKey] : def.items) || [];
const regions = def.regions || [];
const grid = def.grid || { cols: 1, rows: 1 };
const cardCols = def.cardColumns || 1;
const outer = document.createElement('div');
outer.className = 'cg-outer';
outer.style.setProperty('--cg-card-cols', String(cardCols));
if (!items.length) {
const empty = document.createElement('div');
empty.style.cssText = 'padding:16px;font-size:12px;color:var(--textMuted);text-align:center';
empty.textContent = 'No cards added yet.';
outer.appendChild(empty);
return outer;
}
items.forEach(item => {
const card = document.createElement('div');
card.className = 'cg-card';
card.style.gridTemplateColumns = `repeat(${grid.cols}, 1fr)`;
regions.forEach(region => {
const cell = document.createElement('div');
cell.className = 'cg-cell';
cell.style.gridColumn = `${region.col} / span ${region.colSpan}`;
cell.style.gridRow = `${region.row} / span ${region.rowSpan}`;
if (region.type === 'image') {
const src = region.field ? item[region.field] : null;
if (src) {
const img = document.createElement('img');
img.src = src;
img.className = 'cg-img';
cell.appendChild(img);
}
} else {
if (region.source === 'constant') {
cell.classList.add('cg-text', 'cg-constant');
if (region.align === 'right') cell.classList.add('cg-text-right');
cell.textContent = region.value || '';
} else {
const val = region.field ? item[region.field] : '';
cell.classList.add('cg-text', 'cg-field');
cell.textContent = val != null ? String(val) : '';
}
}
card.appendChild(cell);
});
outer.appendChild(card);
});
return outer;
}
// ── EXPORTS ───────────────────────────────────────────────────────────
global.GuideRender = { panel, injectStyles, md, uid };
})(window);