oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1// testkit.mjs — what the fidelity gates share: the corpus from Go's
2// golden file, a seeded generator, and an editor without a DOM. The
3// gates drive EditorState transactions directly, with the same plugins
4// the page will run; no view is needed, so none is made. Not bundled.
5
6import { readFileSync } from 'node:fs'
7import { dirname, join } from 'node:path'
8import { fileURLToPath } from 'node:url'
9import { EditorState } from 'prosemirror-state'
10import { history } from 'prosemirror-history'
11import { createSchema } from './schema.mjs'
12import { mount, fidelityPlugin } from './fidelity.mjs'
13
14const here = dirname(fileURLToPath(import.meta.url))
15export const goldenPath = process.env.MAPA_GOLDEN ||
16 join(here, '..', 'internal', 'mapa', 'markup', 'testdata', 'golden.json')
17export const localCorpus = Boolean(process.env.MAPA_GOLDEN)
18
19// corpus is every golden body, read a line at a time (parity.test.mjs).
20export function corpus () {
21 const bytes = readFileSync(goldenPath)
22 const bodies = []
23 for (let start = 0; start < bytes.length;) {
24 let end = bytes.indexOf(10, start)
25 if (end < 0) end = bytes.length
26 const line = bytes.toString('utf8', start, end).replace(/,$/u, '')
27 start = end + 1
28 if (line !== '[' && line !== ']' && line !== '') {
29 const { name, body } = JSON.parse(line)
30 bodies.push({ name, body })
31 }
32 }
33 return bodies
34}
35
36// random is mulberry32, seeded from a string, so each body has its own
37// fixed sequence.
38export function random (seedText) {
39 let seed = 2166136261
40 for (const char of seedText) seed = Math.imul(seed ^ char.codePointAt(0), 16777619)
41 const next = () => {
42 seed = (seed + 0x6d2b79f5) | 0
43 let value = Math.imul(seed ^ (seed >>> 15), 1 | seed)
44 value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value
45 return ((value ^ (value >>> 14)) >>> 0) / 4294967296
46 }
47 next.int = n => Math.floor(next() * n)
48 next.pick = list => list[next.int(list.length)]
49 return next
50}
51
52export const schema = createSchema()
53
54// editor is a mounted body in an EditorState with history and the
55// fidelity plugin, behind the small part of EditorView's interface the
56// fidelity functions use (state and dispatch).
57export function editor (body, options = {}) {
58 const { doc, fidelity } = mount(schema, body)
59 const state = EditorState.create({
60 doc,
61 plugins: [
62 history(), fidelityPlugin(fidelity, { composing: options.composing ?? (() => false) }),
63 ...(options.plugins?.(fidelity) ?? [])
64 ]
65 })
66 const view = {
67 state,
68 dispatch (tr) { this.state = this.state.apply(tr) },
69 // run is a prosemirror command against this view.
70 run (command) { return command(this.state, tr => this.dispatch(tr)) }
71 }
72 return { view, fidelity }
73}
74