@ruinosus/dna-render 0.0.0-stage → 0.2.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.
package/index.mjs ADDED
@@ -0,0 +1,400 @@
1
+ // @ruinosus/dna-render — reads a DNA file, checks it against its Kind and draws it. Like Mermaid in how it behaves
2
+ // (a text block becomes a drawing, the error says its line), without using Mermaid. The Kinds come from packs:
3
+ //
4
+ // import { use, check, render, toMermaid } from '@ruinosus/dna-render'
5
+ // import keepforge from '@ruinosus/keepforge-kinds'
6
+ // use(keepforge)
7
+ // check(text, { file }) -> { doc, kind, errors: [{ line, msg }] } every error at once, each with its line
8
+ // render(text, { file }) -> { ok, kind, html, errors }
9
+ // toMermaid(text) -> Mermaid text, for where only Mermaid is drawn (GitHub), or null
10
+ // register(kind, { apiVersion, schema, rules?, draw?, mermaid? })
11
+ // run() -> in a page: every <pre class="dna"> and <code class="language-dna"> becomes its drawing
12
+ import { LineCounter, isMap, isSeq, parseDocument } from 'yaml'
13
+
14
+ export const version = '0.2.0'
15
+ const kinds = {}
16
+ const HEADER = ['apiVersion', 'kind', 'metadata', 'spec']
17
+ const NAME = /^[a-z0-9-]+$/
18
+
19
+ export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
20
+
21
+ export function register(kind, def) {
22
+ if (!def?.apiVersion || !def?.schema) throw new Error(`register(${kind}): apiVersion and schema are required`)
23
+ kinds[kind] = def
24
+ }
25
+
26
+ /** A pack: { apiVersion, kinds: { Kind: { schema, rules?, draw?, mermaid? } } }. */
27
+ export function use(pack) {
28
+ for (const [kind, def] of Object.entries(pack.kinds)) register(kind, { apiVersion: pack.apiVersion, ...def })
29
+ }
30
+
31
+ export const known = () => Object.keys(kinds)
32
+
33
+ // The core's one Kind: a pack's manifest, dna-pack.yaml in the pack's folder — its name, the Kinds' owners it uses
34
+ // (apiVersion), and the files it exports for a game, each as <Kind>/<metadata.name> to a path, in luau or json.
35
+ export const PACK_FILE = 'dna-pack.yaml'
36
+ register('Pack', {
37
+ apiVersion: 'github.com/ruinosus/dna/v1',
38
+ schema: {
39
+ type: 'object', additionalProperties: false, required: ['title', 'uses'],
40
+ properties: {
41
+ title: { type: 'string', minLength: 1 },
42
+ uses: { type: 'array', minItems: 1, uniqueItems: true, items: { type: 'string', pattern: '^[a-z0-9.-]+(/[A-Za-z0-9._-]+)+/v\\d+$' } },
43
+ exports: {
44
+ type: 'array',
45
+ items: {
46
+ type: 'object', additionalProperties: false, required: ['file', 'to', 'format'],
47
+ properties: {
48
+ file: { type: 'string', pattern: '^[A-Z][A-Za-z]+/([a-z0-9_-]+|\\*)$', description: '<Kind>/<metadata.name>, or <Kind>/* for every file of the Kind' },
49
+ to: { type: 'string', minLength: 1 },
50
+ format: { type: 'string', enum: ['luau', 'json'] },
51
+ shape: { type: 'string', minLength: 1, description: "the Kind's export shape (Pesca: misticos, nivel…)" },
52
+ },
53
+ },
54
+ },
55
+ },
56
+ },
57
+ refs: (s) => (s.exports || []).map((x, i) => (x.file.endsWith('/*') ? null : { path: ['spec', 'exports', i, 'file'], kind: x.file.split('/')[0], id: x.file.split('/')[1] })).filter(Boolean),
58
+ })
59
+
60
+ // ---- the JSON Schema subset the Kinds use ------------------------------------------------------------------------
61
+ const show = (v) => JSON.stringify(v)
62
+ function validate(s, v, path, out) {
63
+ const at = path.join('.')
64
+ if (s.oneOf) {
65
+ const fits = s.oneOf.filter((alt) => { const e = []; validate(alt, v, path, e); return !e.length })
66
+ if (fits.length !== 1) out.push({ path, msg: `${at}: ${show(v)} does not fit${s.description ? `; expected ${s.description}` : ''}` })
67
+ return
68
+ }
69
+ const t = s.type
70
+ const typeOk = !t || (t === 'object' ? v !== null && typeof v === 'object' && !Array.isArray(v)
71
+ : t === 'array' ? Array.isArray(v) : t === 'integer' ? Number.isInteger(v) : t === 'number' ? typeof v === 'number'
72
+ : t === 'boolean' ? typeof v === 'boolean' : t === 'string' ? typeof v === 'string' : true)
73
+ if (!typeOk) { out.push({ path, msg: `${at}: must be ${t === 'object' ? 'a map' : t === 'array' ? 'a list' : `a ${t}`}, not ${show(v)}` }); return }
74
+ if (s.enum && !s.enum.includes(v)) out.push({ path, msg: `${at}: ${show(v)} is not one of ${s.enum.join(', ')}` })
75
+ if (typeof v === 'string') {
76
+ if (s.minLength && v.length < s.minLength) out.push({ path, msg: `${at}: empty` })
77
+ if (s.pattern && !new RegExp(s.pattern).test(v)) out.push({ path, msg: `${at}: ${show(v)} is not in the form ${s.pattern}` })
78
+ }
79
+ if (typeof v === 'number') {
80
+ if (s.minimum !== undefined && v < s.minimum) out.push({ path, msg: `${at}: at least ${s.minimum}` })
81
+ if (s.maximum !== undefined && v > s.maximum) out.push({ path, msg: `${at}: at most ${s.maximum}` })
82
+ if (s.exclusiveMinimum !== undefined && v <= s.exclusiveMinimum) out.push({ path, msg: `${at}: above ${s.exclusiveMinimum}` })
83
+ }
84
+ if (Array.isArray(v)) {
85
+ if (s.minItems && v.length < s.minItems) out.push({ path, msg: `${at}: at least ${s.minItems} item${s.minItems > 1 ? 's' : ''}` })
86
+ if (s.uniqueItems && new Set(v.map(show)).size !== v.length) out.push({ path, msg: `${at}: an item is repeated` })
87
+ if (s.items) v.forEach((x, i) => validate(s.items, x, [...path, i], out))
88
+ }
89
+ if (t === 'object') {
90
+ for (const r of s.required || []) if (!(r in v)) out.push({ path, msg: `${at}: \`${r}\` is missing` })
91
+ for (const [k, x] of Object.entries(v)) {
92
+ if (s.properties?.[k]) validate(s.properties[k], x, [...path, k], out)
93
+ else if (s.additionalProperties && typeof s.additionalProperties === 'object') validate(s.additionalProperties, x, [...path, k], out)
94
+ else if (s.additionalProperties === false) out.push({ path: [...path, k], msg: `${at}: unknown field \`${k}\`${s.properties ? ` (the fields: ${Object.keys(s.properties).join(', ')})` : ''}` })
95
+ }
96
+ }
97
+ }
98
+
99
+ // the line of a path (spec.phases.2.camera): the deepest node of it that is in the text
100
+ function lineOf(yamlDoc, lc, path) {
101
+ let node = yamlDoc.contents, line = 1
102
+ for (const p of path) {
103
+ if (isMap(node)) {
104
+ const pair = node.items.find((it) => it.key?.value === p)
105
+ if (!pair) break
106
+ line = lc.linePos(pair.key.range[0]).line
107
+ node = pair.value
108
+ } else if (isSeq(node) && node.items[p]) {
109
+ node = node.items[p]
110
+ line = lc.linePos(node.range[0]).line
111
+ } else break
112
+ }
113
+ return line
114
+ }
115
+
116
+ /** Checks a DNA text (and, given, its file name): every error at once, each with the line to fix. */
117
+ export function check(text, { file } = {}) {
118
+ const lc = new LineCounter()
119
+ const yamlDoc = parseDocument(text, { lineCounter: lc, prettyErrors: false })
120
+ const lines = text.split('\n')
121
+ // the commonest break: a sentence with ': ' or ', ' left without quotes, read as more keys
122
+ const QUOTE = ' — a sentence with ": " or ", " in it goes in quotes: key: "…"'
123
+ const sentence = (n) => { const l = lines[n - 1] ?? ''; return /:\s.*:\s/.test(l) || (/[{[]/.test(l) && /:\s[^,{}[\]]*,\s[^:]*[,}]/.test(l)) }
124
+ if (yamlDoc.errors.length) {
125
+ return { errors: yamlDoc.errors.map((e) => { const line = lc.linePos(e.pos[0]).line; return { line, msg: `YAML: ${e.message.split('\n')[0]}${sentence(line) ? QUOTE : ''}` } }) }
126
+ }
127
+ const doc = yamlDoc.toJS()
128
+ const at = (path) => lineOf(yamlDoc, lc, path)
129
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return { errors: [{ line: 1, msg: `a DNA file is a map with ${HEADER.join(', ')}` }] }
130
+ const errors = []
131
+ const keys = Object.keys(doc)
132
+ if (keys.join() !== HEADER.join()) {
133
+ const missing = HEADER.filter((k) => !keys.includes(k)), extra = keys.filter((k) => !HEADER.includes(k))
134
+ errors.push({ line: extra.length ? at([extra[0]]) : 1, msg: `the top keys are ${HEADER.join(', ')}, in this order, and nothing else${missing.length ? ` — missing: ${missing.join(', ')}` : ''}${extra.length ? ` — not one: ${extra.join(', ')}` : ''}${!missing.length && !extra.length ? ` — the order here: ${keys.join(', ')}` : ''}` })
135
+ }
136
+ const def = kinds[doc.kind]
137
+ if (!def) errors.push({ line: at(['kind']), msg: `kind ${show(doc.kind)}: unknown (the Kinds: ${known().join(', ') || 'none — no pack in use'})` })
138
+ else if (doc.apiVersion !== def.apiVersion) errors.push({ line: at(['apiVersion']), msg: `apiVersion ${show(doc.apiVersion)}: ${doc.kind} is ${def.apiVersion}` })
139
+ const name = doc.metadata?.name
140
+ if (typeof name !== 'string' || !NAME.test(name)) errors.push({ line: at(['metadata', 'name']), msg: 'metadata.name: lowercase letters, digits and hyphens' })
141
+ if (file !== undefined) {
142
+ const base = String(file).split(/[\\/]/).pop()
143
+ const m = /^([a-z0-9-]+)\.([a-z0-9-]+)\.dna\.yaml$/.exec(base)
144
+ const want = def && typeof name === 'string' && NAME.test(name) ? `${name}.${doc.kind.toLowerCase()}.dna.yaml` : '<metadata.name>.<kind>.dna.yaml'
145
+ if (!m) errors.push({ line: 1, msg: `file name ${base}: it is ${want}${/\.dna$/.test(base) ? ' (the bare .dna is another format)' : ''}` })
146
+ else if (def && base !== want) errors.push({ line: 1, msg: `file name ${base}: it is ${want} (metadata.name, then the kind in lowercase)` })
147
+ }
148
+ if (def) {
149
+ const out = []
150
+ validate(def.schema, doc.spec, ['spec'], out)
151
+ // the rules between fields run on a broken spec too (every error at once); one that trips on a shape the
152
+ // schema already refused adds nothing
153
+ if (def.rules) try { out.push(...def.rules(doc.spec)) } catch {}
154
+ for (const e of out) {
155
+ const line = at(e.path)
156
+ // an «unknown field» that is half a sentence: the rest of a value cut at ', ' or ': '
157
+ const cut = /unknown field `[^`]*\s[^`]*`/.test(e.msg) && sentence(line)
158
+ errors.push({ line, msg: cut ? `${e.msg}${QUOTE}` : e.msg })
159
+ }
160
+ }
161
+ errors.sort((a, b) => a.line - b.line)
162
+ return { doc, kind: doc.kind, errors, at }
163
+ }
164
+
165
+ // ---- a pack: many files, and what one says of another -----------------------------------------------------------
166
+ // A Kind may say what its file holds for the others (`ids(spec)` -> { collection: [id…] }) and what it points at
167
+ // (`refs(spec)` -> [{ path, kind, name? , collection?, id, in?, soft? }]): a ref with `collection` is an id inside a
168
+ // file of `kind` (the file named `in`, or any); without it, the `metadata.name` of a file of `kind`. A `soft` ref is
169
+ // checked only when the pack has a file of that kind.
170
+
171
+ /** Checks every file and what each says of the others: [{ file, text }] (dna-pack.yaml among them, when the pack has
172
+ * one) -> { files: [{ file, doc, kind, at }], errors: [{ file, line, msg }], manifest }. */
173
+ export function checkPack(sources) {
174
+ const errors = [], files = []
175
+ for (const { file, text } of sources) {
176
+ const isManifest = String(file).split(/[\\/]/).pop() === PACK_FILE
177
+ const r = check(text, isManifest ? {} : { file })
178
+ if (isManifest && r.doc && r.kind !== 'Pack') r.errors.push({ line: 1, msg: `${PACK_FILE} is a Pack (apiVersion github.com/ruinosus/dna/v1, kind: Pack)` })
179
+ for (const e of r.errors) errors.push({ file, ...e })
180
+ if (r.doc && !r.errors.length) files.push({ file, doc: r.doc, kind: r.kind, at: r.at })
181
+ }
182
+ const manifest = files.find((f) => f.kind === 'Pack')?.doc
183
+ if (manifest) {
184
+ const uses = manifest.spec.uses
185
+ for (const f of files) if (f.kind !== 'Pack' && !uses.includes(f.doc.apiVersion)) errors.push({ file: f.file, line: f.at(['apiVersion']), msg: `apiVersion ${f.doc.apiVersion}: the pack ${manifest.metadata?.name} uses ${uses.join(', ')} (dna-pack.yaml)` })
186
+ }
187
+ const byKind = {}
188
+ for (const f of files) {
189
+ const k = (byKind[f.kind] ||= {})
190
+ if (k[f.doc.metadata.name]) errors.push({ file: f.file, line: f.at(['metadata', 'name']), msg: `metadata.name ${f.doc.metadata.name}: another ${f.kind} has it (${k[f.doc.metadata.name].file})` })
191
+ else k[f.doc.metadata.name] = f
192
+ }
193
+ for (const f of files) {
194
+ for (const r of kinds[f.kind].refs?.(f.doc.spec) ?? []) {
195
+ const pool = byKind[r.kind] ?? {}
196
+ const where = r.in ? (pool[r.in] ? [pool[r.in]] : []) : Object.values(pool)
197
+ if (!Object.keys(pool).length && r.soft) continue
198
+ if (r.in && !where.length) { errors.push({ file: f.file, line: f.at(r.path), msg: `${r.kind} ${JSON.stringify(r.in)}: no such file in the pack (${Object.keys(pool).join(', ') || `no ${r.kind}`})` }); continue }
199
+ const found = r.collection ? where.some((t) => (kinds[r.kind].ids?.(t.doc.spec)[r.collection] ?? []).includes(r.id)) : where.some((t) => t.doc.metadata.name === r.id)
200
+ if (!found) errors.push({ file: f.file, line: f.at(r.path), msg: `${JSON.stringify(r.id)}: ${r.collection ? `not one of the ${r.collection} of ${r.in ?? `any ${r.kind}`}` : `no ${r.kind} has this name`} in the pack` })
201
+ }
202
+ // what a Kind says of another file beyond an id (an album page's zones against its fish's zones…)
203
+ const find = (kind, name) => (name ? byKind[kind]?.[name]?.doc : Object.values(byKind[kind] ?? {})[0]?.doc)
204
+ for (const e of kinds[f.kind].packRules?.(f.doc.spec, find) ?? []) errors.push({ file: f.file, line: f.at(e.path), msg: e.msg })
205
+ }
206
+ errors.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1))
207
+ return { files, errors, manifest }
208
+ }
209
+
210
+ // ---- export: a file as the data a game reads ---------------------------------------------------------------------
211
+ const LUAU_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
212
+ function luau(v, ind = '') {
213
+ if (v === null || v === undefined) return 'nil'
214
+ if (typeof v === 'string') return JSON.stringify(v)
215
+ if (typeof v !== 'object') return String(v)
216
+ const inner = ind + '\t'
217
+ if (Array.isArray(v)) {
218
+ if (!v.length) return '{}'
219
+ if (v.every((x) => x === null || typeof x !== 'object')) return `{ ${v.map((x) => luau(x)).join(', ')} }`
220
+ return `{\n${v.map((x) => `${inner}${luau(x, inner)},`).join('\n')}\n${ind}}`
221
+ }
222
+ const keys = Object.keys(v).filter((k) => v[k] !== undefined)
223
+ if (!keys.length) return '{}'
224
+ return `{\n${keys.map((k) => `${inner}${LUAU_NAME.test(k) ? k : `[${JSON.stringify(k)}]`} = ${luau(v[k], inner)},`).join('\n')}\n${ind}}`
225
+ }
226
+
227
+ function serialize(data, format, from) {
228
+ const head = `GENERATED from ${from} by dna-render ${version}. Edit the DNA, not this file.`
229
+ return format === 'luau' ? `--!strict\n-- ${head}\nreturn ${luau(data)}\n` : `${JSON.stringify(data, null, 2)}\n`
230
+ }
231
+ const dataOf = (doc, shape) => (kinds[doc.kind].export ? kinds[doc.kind].export(doc.spec, doc, { shape }) : doc.spec)
232
+
233
+ /** A checked file as the game's data: { ok, data, text, errors }. format: 'json' | 'luau'; shape: the Kind's export
234
+ * shape (Pesca: misticos, nivel…). A Kind without `export` gives its spec as it is. */
235
+ export function exportDoc(text, { format = 'json', file, shape } = {}) {
236
+ const { doc, errors } = check(text, { file })
237
+ if (errors.length) return { ok: false, errors }
238
+ const data = dataOf(doc, shape)
239
+ return { ok: true, errors: [], data, text: serialize(data, format, file ? String(file).split(/[\\/]/).pop() : `${doc.metadata.name}.${doc.kind.toLowerCase()}.dna.yaml`) }
240
+ }
241
+
242
+ /** One export of dna-pack.yaml ({ file: 'Kind/name' or 'Kind/*', format, shape }) from checkPack's files: { data, text }. */
243
+ export function exportPack(files, { file, format = 'json', shape }) {
244
+ const [kind, name] = file.split('/')
245
+ const docs = files.filter((f) => f.kind === kind && (name === '*' || f.doc.metadata.name === name)).map((f) => f.doc)
246
+ if (!docs.length) throw new Error(`no ${file} in the pack`)
247
+ const def = kinds[kind]
248
+ const data = name === '*' ? (def.exportAll ? def.exportAll(docs, { shape }) : docs.map((d) => dataOf(d, shape))) : dataOf(docs[0], shape)
249
+ return { data, text: serialize(data, format, name === '*' ? `every ${kind} of the pack` : `${docs[0].metadata.name}.${kind.toLowerCase()}.dna.yaml`) }
250
+ }
251
+
252
+ export function errorsHtml(errors) {
253
+ return `<div class="dna-err"><b>✗ DNA refused the text</b><ul>${errors.map((e) => `<li><code>line ${e.line}</code> ${esc(e.msg)}</li>`).join('')}</ul></div>`
254
+ }
255
+
256
+ function addStyle() {
257
+ if (typeof document === 'undefined' || document.getElementById('dna-render-css')) return
258
+ const st = document.createElement('style')
259
+ st.id = 'dna-render-css'
260
+ st.textContent = css
261
+ document.head.appendChild(st)
262
+ }
263
+
264
+ /** In a page it also puts the drawings' CSS in <head>, once; elsewhere (Node) the page takes `css` itself. */
265
+ export function render(text, opts) {
266
+ addStyle()
267
+ const { doc, errors } = check(text, opts)
268
+ if (errors.length) return { ok: false, errors, html: errorsHtml(errors) }
269
+ const d = kinds[doc.kind]
270
+ const body = d.draw ? d.draw(doc.spec, doc, esc) : `<div class="dna-mut">✓ ${esc(doc.kind)} checked. This Kind has no drawing yet.</div>`
271
+ return { ok: true, kind: doc.kind, errors: [], html: `<div class="dna-out dna-${doc.kind.toLowerCase()}">${body}</div>` }
272
+ }
273
+
274
+ export function toMermaid(text) {
275
+ const { doc, errors } = check(text)
276
+ return errors.length || !kinds[doc.kind].mermaid ? null : kinds[doc.kind].mermaid(doc.spec, doc)
277
+ }
278
+
279
+ export const css = `.dna-block,.dna-out{--dna-line:color-mix(in srgb,currentColor 22%,transparent);--dna-fill:color-mix(in srgb,currentColor 5%,transparent);--dna-acc:#0b7fb0;--dna-bad:#d93a6a;font:15px/1.45 system-ui,sans-serif}
280
+ .dna-title{font-weight:800;font-size:18px;margin:0 0 8px}.dna-mut{opacity:.7;font-size:14px}.dna-scroll{overflow-x:auto}
281
+ .dna-svg text{fill:currentColor}.dna-node rect{fill:var(--dna-fill);stroke:var(--dna-line);stroke-width:1.5}.dna-start rect{stroke:var(--dna-acc);stroke-width:2.5}.dna-end rect{stroke-width:3}
282
+ .dna-t{font-weight:700;font-size:15px}.dna-s{font-size:13px;fill:var(--dna-acc)!important;font-weight:700}.dna-m{font-size:13px;opacity:.8}.dna-edge{fill:none;stroke:var(--dna-acc);stroke-width:1.8}.dna-head{fill:var(--dna-acc)}
283
+ .dna-quest{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.dna-col{display:flex;flex-direction:column;gap:6px}.dna-lab{font-size:12px;opacity:.7}.dna-arrow{font-size:22px;color:var(--dna-acc)}
284
+ .dna-chip{display:inline-block;margin:2px 0;border:1px dashed var(--dna-line);border-radius:99px;padding:2px 10px;font-size:13px}.dna-card{border:1.5px solid var(--dna-line);background:var(--dna-fill);border-radius:12px;padding:14px;min-width:240px;flex:1}
285
+ .dna-steps{list-style:none;margin:10px 0;padding:0;display:flex;flex-direction:column;gap:6px}.dna-steps li{display:flex;gap:10px;align-items:center}.dna-steps li>b{display:inline-grid;place-items:center;width:24px;height:24px;border-radius:50%;background:var(--dna-acc);color:#fff;font-size:13px}
286
+ .dna-reward{border-top:1px solid var(--dna-line);padding-top:8px;font-weight:700}
287
+ .dna-h{font-size:15px;margin:16px 0 8px}.dna-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px;margin-top:10px}.dna-grid .dna-card{min-width:0}.dna-row{display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:8px}
288
+ .dna-table{border-collapse:collapse;width:100%;margin-top:10px}.dna-table th{text-align:left;font-weight:700;padding:8px 10px 8px 0;white-space:nowrap;vertical-align:top}.dna-table td{padding:8px 0;border-top:1px solid var(--dna-line)}.dna-table th{border-top:1px solid var(--dna-line)}.dna-table .dna-chip{display:inline-block;margin:2px 0}
289
+ .dna-dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:6px}.dna-steps-row{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
290
+ .dna-stickers{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}.dna-sticker{border:1px solid var(--dna-line);border-radius:8px;padding:6px;font-size:12px;display:flex;flex-direction:column;gap:2px;overflow-wrap:anywhere}.dna-sticker b{color:var(--dna-acc)}
291
+ .dna-locked{border-style:dashed}.dna-soon{opacity:.5}
292
+ .dna-stepping .dna-node,.dna-stepping .dna-steps li,.dna-stepping .dna-grid>.dna-card,.dna-stepping .dna-table tr{opacity:.35;transition:opacity .2s}.dna-stepping .dna-lit{opacity:1!important}.dna-stepping .dna-node.dna-lit rect{stroke-width:3.5}
293
+ .dna-note{margin-top:20px;font-size:clamp(17px,2.4vw,22px);font-weight:700;overflow-wrap:anywhere}.dna-slide-title{font-size:28px;margin:0 0 20px}
294
+ .dna-present{position:fixed;inset:0;z-index:2147483000;display:flex;flex-direction:column;background:Canvas;color:CanvasText;font:18px/1.45 system-ui,sans-serif;outline:0}
295
+ .dna-present .dna-slide{flex:1;min-width:0;width:100%;box-sizing:border-box;overflow:auto;padding:max(24px,env(safe-area-inset-top)) max(16px,4vw) 16px}
296
+ .dna-present footer{display:flex;gap:12px;justify-content:center;align-items:center;padding:10px 10px max(10px,env(safe-area-inset-bottom))}
297
+ .dna-present footer button,.dna-present-button{min-width:44px;min-height:44px;font:600 16px system-ui,sans-serif;border:1px solid var(--dna-line,#8888);border-radius:8px;background:transparent;color:inherit;cursor:pointer}
298
+ .dna-present-button{min-height:36px;padding:0 12px;margin-bottom:8px}
299
+ .dna-err{border-left:3px solid var(--dna-bad);padding:8px 12px;background:color-mix(in srgb,var(--dna-bad) 8%,transparent);border-radius:0 8px 8px 0}.dna-err ul{margin:6px 0 0;padding-left:18px}.dna-err code{color:var(--dna-bad);font-weight:700}`
300
+
301
+ // ---- present: a block as slides --------------------------------------------------------------------------------
302
+ // The whole drawing first, then one slide per item a Kind tells (`present: { items, selector, say }`: a Fluxo's phases,
303
+ // a Quest's steps…), the same drawing with that item lit and told below. A text the checker refuses is one slide with
304
+ // its lines to fix. Pure: the VS Code extension and a page build the same slides.
305
+
306
+ /** [{ title?, text }] (or one text) -> [{ title, html, lit?: [selector, n], note?, at?: [n, of] }] */
307
+ export function slides(blocks) {
308
+ const out = []
309
+ for (const b of typeof blocks === 'string' ? [{ text: blocks }] : blocks) {
310
+ const { html } = render(b.text)
311
+ out.push({ title: b.title ?? '', html })
312
+ const { doc, errors } = check(b.text)
313
+ const p = doc && !errors.length && kinds[doc.kind].present
314
+ if (!p) continue
315
+ const items = p.items(doc.spec) || []
316
+ items.forEach((x, i) => out.push({ title: b.title ?? '', html, lit: [p.selector, i], note: p.say(x, i, doc.spec), at: [i + 1, items.length] }))
317
+ }
318
+ return out
319
+ }
320
+
321
+ /** Paints slide `s` into `el` (lit item, its note). For a page or a webview that keeps its own frame. */
322
+ export function paint(el, s) {
323
+ el.innerHTML = s ? s.html : '<p class="dna-mut">No DNA block.</p>'
324
+ if (s?.title) { const h = document.createElement('h1'); h.className = 'dna-slide-title'; h.textContent = s.title; el.prepend(h) }
325
+ el.classList.toggle('dna-stepping', !!s?.lit)
326
+ if (s?.lit) {
327
+ el.querySelectorAll(s.lit[0])[s.lit[1]]?.classList.add('dna-lit')
328
+ const p = document.createElement('p')
329
+ p.className = 'dna-note'
330
+ p.textContent = s.note ?? ''
331
+ el.append(p)
332
+ }
333
+ }
334
+
335
+ /** Presents in the page, full screen: an element (its DNA text), a text, or blocks [{ title, text }].
336
+ * ← → (space, PageUp/PageDown) move, Esc closes, F full screen, a swipe on a phone. -> { show(n), update(blocks), close() } */
337
+ export function present(what, { start = 0 } = {}) {
338
+ addStyle()
339
+ const textOf = (x) => (typeof x === 'string' ? x : x.dataset?.dnaText ?? x.textContent)
340
+ let list = slides(Array.isArray(what) ? what : textOf(what)), at = start
341
+ const box = document.createElement('div')
342
+ box.className = 'dna-present'
343
+ box.setAttribute('role', 'dialog')
344
+ box.setAttribute('aria-label', 'DNA presentation')
345
+ box.tabIndex = -1
346
+ box.innerHTML = '<main class="dna-slide"></main><footer><button data-go="-1" aria-label="Previous">←</button><span class="dna-count"></span><button data-go="1" aria-label="Next">→</button><button data-full aria-label="Full screen">⛶</button><button data-close aria-label="Close">✕</button></footer>'
347
+ const slide = box.querySelector('.dna-slide'), count = box.querySelector('.dna-count')
348
+ const show = (n = at) => {
349
+ at = Math.max(0, Math.min(n, list.length - 1))
350
+ paint(slide, list[at])
351
+ count.textContent = list.length ? `${at + 1} / ${list.length}` : ''
352
+ }
353
+ const full = () => { try { document.fullscreenElement ? document.exitFullscreen() : box.requestFullscreen?.() } catch {} }
354
+ const close = () => { document.removeEventListener('keydown', key, true); try { if (document.fullscreenElement === box) document.exitFullscreen() } catch {} box.remove() }
355
+ const key = (e) => {
356
+ if (['ArrowRight', 'PageDown', ' '].includes(e.key)) show(at + 1)
357
+ else if (['ArrowLeft', 'PageUp'].includes(e.key)) show(at - 1)
358
+ else if (e.key === 'Escape') close()
359
+ else if (e.key === 'f' || e.key === 'F') full()
360
+ else return
361
+ e.preventDefault()
362
+ }
363
+ box.addEventListener('click', (e) => {
364
+ const b = e.target.closest?.('button')
365
+ if (!b) return
366
+ if (b.dataset.go) show(at + Number(b.dataset.go))
367
+ else if ('full' in b.dataset) full()
368
+ else if ('close' in b.dataset) close()
369
+ })
370
+ let x0 = null
371
+ box.addEventListener('touchstart', (e) => { x0 = e.touches[0].clientX }, { passive: true })
372
+ box.addEventListener('touchend', (e) => { if (x0 === null) return; const dx = e.changedTouches[0].clientX - x0; if (Math.abs(dx) > 40) show(at + (dx < 0 ? 1 : -1)); x0 = null })
373
+ document.addEventListener('keydown', key, true)
374
+ document.body.appendChild(box)
375
+ box.focus()
376
+ show()
377
+ return { show, close, update(blocks) { list = slides(blocks); show() }, get at() { return at }, get count() { return list.length } }
378
+ }
379
+
380
+ /** In a page: every <pre class="dna"> and <code class="language-dna"> (a ```dna fence) becomes its drawing; one with
381
+ * data-present (on it or its <pre>) gets a ▶ button that presents it. Run once at load by the global script
382
+ * (window.DNA_AUTORUN = false, or data-autorun="false" on the script, turns that off); again for what comes later. */
383
+ export function run({ querySelector = 'pre.dna, code.language-dna' } = {}) {
384
+ for (const el of document.querySelectorAll(querySelector)) {
385
+ const host = el.tagName === 'CODE' && el.parentElement?.tagName === 'PRE' ? el.parentElement : el
386
+ const text = el.textContent
387
+ const div = document.createElement('div')
388
+ div.className = 'dna-block'
389
+ div.dataset.dnaText = text
390
+ div.innerHTML = render(text).html
391
+ if (el.hasAttribute('data-present') || host.hasAttribute('data-present')) {
392
+ const b = document.createElement('button')
393
+ b.className = 'dna-present-button'
394
+ b.textContent = '▶ Present'
395
+ b.addEventListener('click', () => present(text))
396
+ div.prepend(b)
397
+ }
398
+ host.replaceWith(div)
399
+ }
400
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@ruinosus/dna-render",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Reads a DNA file, checks it against its Kind (every error at once, each with its line) and draws it — like Mermaid in how it behaves, without Mermaid. The Kinds come from packs, such as @ruinosus/keepforge-kinds.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./index.mjs",
8
+ "./global": "./dist/dna-render.global.js"
9
+ },
10
+ "files": [
11
+ "index.mjs",
12
+ "dist/",
13
+ "play.html",
14
+ "README.md"
15
+ ],
16
+ "dependencies": {
17
+ "yaml": "2.6.1"
18
+ },
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "license": "MIT",
23
+ "author": "ruinosus",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/ruinosus/dna.git",
27
+ "directory": "npm/dna-render"
28
+ },
29
+ "keywords": [
30
+ "dna",
31
+ "notation",
32
+ "yaml",
33
+ "diagram",
34
+ "renderer"
35
+ ],
36
+ "scripts": {
37
+ "prepack": "node ../../dev/dna-notation/tools/assets.mjs"
38
+ }
39
+ }