@ruinosus/dna-render 0.1.0 → 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/README.md +36 -8
- package/dist/demo.html +25 -0
- package/dist/dna-render.global.js +116 -93
- package/index.mjs +233 -7
- package/package.json +1 -1
- package/play.html +118 -94
package/index.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// run() -> in a page: every <pre class="dna"> and <code class="language-dna"> becomes its drawing
|
|
12
12
|
import { LineCounter, isMap, isSeq, parseDocument } from 'yaml'
|
|
13
13
|
|
|
14
|
-
export const version = '0.
|
|
14
|
+
export const version = '0.2.0'
|
|
15
15
|
const kinds = {}
|
|
16
16
|
const HEADER = ['apiVersion', 'kind', 'metadata', 'spec']
|
|
17
17
|
const NAME = /^[a-z0-9-]+$/
|
|
@@ -30,6 +30,33 @@ export function use(pack) {
|
|
|
30
30
|
|
|
31
31
|
export const known = () => Object.keys(kinds)
|
|
32
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
|
+
|
|
33
60
|
// ---- the JSON Schema subset the Kinds use ------------------------------------------------------------------------
|
|
34
61
|
const show = (v) => JSON.stringify(v)
|
|
35
62
|
function validate(s, v, path, out) {
|
|
@@ -63,6 +90,7 @@ function validate(s, v, path, out) {
|
|
|
63
90
|
for (const r of s.required || []) if (!(r in v)) out.push({ path, msg: `${at}: \`${r}\` is missing` })
|
|
64
91
|
for (const [k, x] of Object.entries(v)) {
|
|
65
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)
|
|
66
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(', ')})` : ''}` })
|
|
67
95
|
}
|
|
68
96
|
}
|
|
@@ -89,8 +117,12 @@ function lineOf(yamlDoc, lc, path) {
|
|
|
89
117
|
export function check(text, { file } = {}) {
|
|
90
118
|
const lc = new LineCounter()
|
|
91
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)) }
|
|
92
124
|
if (yamlDoc.errors.length) {
|
|
93
|
-
return { errors: yamlDoc.errors.map((e) =>
|
|
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 : ''}` } }) }
|
|
94
126
|
}
|
|
95
127
|
const doc = yamlDoc.toJS()
|
|
96
128
|
const at = (path) => lineOf(yamlDoc, lc, path)
|
|
@@ -119,10 +151,102 @@ export function check(text, { file } = {}) {
|
|
|
119
151
|
// the rules between fields run on a broken spec too (every error at once); one that trips on a shape the
|
|
120
152
|
// schema already refused adds nothing
|
|
121
153
|
if (def.rules) try { out.push(...def.rules(doc.spec)) } catch {}
|
|
122
|
-
for (const e of out)
|
|
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
|
+
}
|
|
123
160
|
}
|
|
124
161
|
errors.sort((a, b) => a.line - b.line)
|
|
125
|
-
return { doc, kind: doc.kind, errors }
|
|
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`) }
|
|
126
250
|
}
|
|
127
251
|
|
|
128
252
|
export function errorsHtml(errors) {
|
|
@@ -157,18 +281,120 @@ export const css = `.dna-block,.dna-out{--dna-line:color-mix(in srgb,currentColo
|
|
|
157
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}
|
|
158
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)}
|
|
159
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)}
|
|
160
|
-
.dna-chip{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}
|
|
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}
|
|
161
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}
|
|
162
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}
|
|
163
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}`
|
|
164
300
|
|
|
165
|
-
|
|
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. */
|
|
166
383
|
export function run({ querySelector = 'pre.dna, code.language-dna' } = {}) {
|
|
167
384
|
for (const el of document.querySelectorAll(querySelector)) {
|
|
168
385
|
const host = el.tagName === 'CODE' && el.parentElement?.tagName === 'PRE' ? el.parentElement : el
|
|
386
|
+
const text = el.textContent
|
|
169
387
|
const div = document.createElement('div')
|
|
170
388
|
div.className = 'dna-block'
|
|
171
|
-
div.
|
|
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
|
+
}
|
|
172
398
|
host.replaceWith(div)
|
|
173
399
|
}
|
|
174
400
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ruinosus/dna-render",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"exports": {
|