oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1package markup
2
3import (
4 "amadan.net/oficina/mapa/internal/mapa/locale"
5
6 "bytes"
7 "encoding/json"
8 "flag"
9 "fmt"
10 "hash/fnv"
11 "io/fs"
12 "net/url"
13 "os"
14 "path/filepath"
15 "sort"
16 "strings"
17 "testing"
18)
19
20// The golden file is gate L4's Go half (spec §7): for every corpus body,
21// what Parse, Spans and RenderPage give. editor/parity.test.mjs holds
22// markup.mjs and the schema's toDOM to it. Rewrite it with make golden.
23var update = flag.Bool("update", false, "rewrite testdata/golden.json")
24
25const goldenPath = "testdata/golden.json"
26
27type corpusBody struct {
28 Name string `json:"name"`
29 Body string `json:"body"`
30}
31
32type goldenBody struct {
33 Name string `json:"name"`
34 Body string `json:"body"`
35 Blocks []goldenBlock `json:"blocks"`
36 Links []goldenLink `json:"links"`
37 // Images is each image's fixed answer (images spec §2.3, L4):
38 // available with a width and height, or not.
39 Images []goldenImage `json:"images"`
40 HTML string `json:"html"`
41}
42
43type goldenImage struct {
44 ID string `json:"id"`
45 Available bool `json:"available"`
46 Width int `json:"width"`
47 Height int `json:"height"`
48}
49
50type goldenBlock struct {
51 Kind string `json:"kind"`
52 Level int `json:"level"`
53 Ordered bool `json:"ordered"`
54 Marker string `json:"marker"`
55 Start int `json:"start"`
56 End int `json:"end"`
57 Source string `json:"source"`
58 // Column is a block's column in a layout; 0, and so absent, outside
59 // one (columns and icons spec §1.4).
60 Column int `json:"column,omitempty"`
61 Plain string `json:"plain"`
62 Spans []goldenSpan `json:"spans"`
63}
64
65type goldenSpan struct {
66 Kind string `json:"kind"`
67 Text string `json:"text"`
68 Target string `json:"target"`
69 Anchor string `json:"anchor"`
70 URL string `json:"url"`
71 Source string `json:"source"`
72}
73
74// goldenLink is one [[link]]'s answer: what the editor's data island
75// carries for it (spec §6.8).
76type goldenLink struct {
77 Target string `json:"target"`
78 Anchor string `json:"anchor"`
79 Href string `json:"href"`
80 Pending bool `json:"pending"`
81 Broken bool `json:"broken"`
82 BlockGone bool `json:"blockGone"`
83 Title string `json:"title"`
84 Alias bool `json:"alias"`
85 Day string `json:"day"`
86 // Icon is the page's icon, when the resolver gives one (columns and
87 // icons spec §2.4).
88 Icon *ChipIcon `json:"icon,omitempty"`
89}
90
91// corpusResolver answers every link the same way on every run, and
92// reaches every kind of chip across the corpus. A date is labelled in
93// dates's locale, the default's when nil, as of 2026.
94type corpusResolver struct{ dates *locale.Locale }
95
96func (answer corpusResolver) Resolve(target, anchor string) Resolution {
97 if IsDateShaped(target) {
98 if !IsDate(target) {
99 return Resolution{Broken: true}
100 }
101 return Resolution{Href: "/d/" + target,
102 Day: answer.dates.Day(target, 2026)}
103 }
104 sum := hashOf(target)
105 if sum%4 == 0 {
106 return Resolution{Href: "/new?title=" + url.QueryEscape(target),
107 Pending: true}
108 }
109 found := Resolution{Href: fmt.Sprintf("/p/%08x", sum), Title: target}
110 if sum%4 == 1 {
111 found.Title, found.Alias = "Renamed "+target, true
112 }
113 switch sum % 16 {
114 case 2:
115 found.Icon = ChipIcon{Emoji: "🧭"}
116 case 3:
117 found.Icon = ChipIcon{Image: "icon" + fmt.Sprint(sum%97)}
118 }
119 switch {
120 case anchor == "":
121 case hashOf(anchor)%3 == 0:
122 found.BlockGone = true
123 default:
124 found.Href += "#b-" + anchor
125 }
126 return found
127}
128
129// Image answers by the id's hash: a third of the corpus's images are
130// not available, and the rest have sizes of their own.
131func (corpusResolver) Image(id string) ImageAnswer {
132 sum := hashOf("image " + id)
133 if sum%3 == 0 {
134 return ImageAnswer{}
135 }
136 return ImageAnswer{Available: true, Width: 40 + int(sum%600),
137 Height: 30 + int(sum/600%400)}
138}
139
140func hashOf(text string) uint32 {
141 sum := fnv.New32a()
142 sum.Write([]byte(text))
143 return sum.Sum32()
144}
145
146func TestGolden(t *testing.T) {
147 encoded := encodeGolden(goldenOf(loadCorpus(t), corpusResolver{nil}))
148 if *update {
149 if err := os.WriteFile(goldenPath, encoded, 0o644); err != nil {
150 t.Fatal(err)
151 }
152 return
153 }
154 committed, err := os.ReadFile(goldenPath)
155 if err != nil {
156 t.Fatal(err)
157 }
158 if !bytes.Equal(committed, encoded) {
159 t.Fatalf("%s is stale: run make golden and commit it (%s)",
160 goldenPath, firstDifference(committed, encoded))
161 }
162}
163
164// TestGoldenReachesEveryChip keeps the corpus honest: L4 compares every
165// kind of chip only if the corpus draws every kind.
166func TestGoldenReachesEveryChip(t *testing.T) {
167 var drawn strings.Builder
168 for _, body := range goldenOf(loadCorpus(t), corpusResolver{nil}) {
169 drawn.WriteString(body.HTML)
170 }
171 for _, kind := range []string{"team", "pending", "date", "block",
172 "block gone", "broken", "embed"} {
173 if !strings.Contains(drawn.String(), `mapa-chip="`+kind+`"`) {
174 t.Errorf("no corpus body draws a %s chip", kind)
175 }
176 }
177 for _, image := range []string{`<img src="/i/`,
178 `mapa-image="unavailable"`, `class="alone"`} {
179 if !strings.Contains(drawn.String(), image) {
180 t.Errorf("no corpus body draws %s", image)
181 }
182 }
183 if !strings.Contains(drawn.String(), `title="Now called `) {
184 t.Error("no corpus body draws a link through an alias")
185 }
186}
187
188// TestCorpusLocal is make corpus-local: the golden file for Markdown read
189// in place from MAPA_CORPUS_DIR, written to MAPA_CORPUS_OUT, outside the
190// repository. Nothing it reads is committed.
191func TestCorpusLocal(t *testing.T) {
192 dir, out := os.Getenv("MAPA_CORPUS_DIR"), os.Getenv("MAPA_CORPUS_OUT")
193 if dir == "" || out == "" {
194 t.Skip("make corpus-local DIR=... sets MAPA_CORPUS_DIR")
195 }
196 bodies, err := markdownIn(dir)
197 if err != nil {
198 t.Fatal(err)
199 }
200 if len(bodies) == 0 {
201 t.Fatalf("no .md files under %s", dir)
202 }
203 encoded := encodeGolden(goldenOf(bodies, corpusResolver{nil}))
204 if err := os.WriteFile(out, encoded, 0o600); err != nil {
205 t.Fatal(err)
206 }
207 t.Logf("%d Markdown files from %s", len(bodies), dir)
208}
209
210func markdownIn(dir string) ([]corpusBody, error) {
211 var bodies []corpusBody
212 err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry,
213 err error) error {
214 if err != nil {
215 return err
216 }
217 name := entry.Name()
218 if entry.IsDir() && path != dir && (name == "node_modules" ||
219 strings.HasPrefix(name, ".")) {
220 return filepath.SkipDir
221 }
222 if entry.IsDir() || !strings.HasSuffix(name, ".md") {
223 return nil
224 }
225 text, err := os.ReadFile(path)
226 bodies = append(bodies, corpusBody{Name: path, Body: string(text)})
227 return err
228 })
229 return bodies, err
230}
231
232func loadCorpus(t *testing.T) []corpusBody {
233 t.Helper()
234 var bodies []corpusBody
235 // import.json is the Notion import's goldens (notionmd's gate I1),
236 // so L1 to L4 hold the editor to every body the import writes.
237 // columns.json is the column layouts' cases (columns and icons spec
238 // §9, COL2): each shape recognised, and each that is not.
239 for _, name := range []string{"edge.json", "synthetic.json",
240 "import.json", "columns.json"} {
241 var some []corpusBody
242 readJSON(t, filepath.Join("testdata", "corpus", name), &some)
243 bodies = append(bodies, some...)
244 }
245 var examples []struct {
246 Markdown string `json:"markdown"`
247 Example int `json:"example"`
248 }
249 readJSON(t, "testdata/corpus/commonmark-0.31.2.json", &examples)
250 for _, example := range examples {
251 bodies = append(bodies, corpusBody{Body: example.Markdown,
252 Name: fmt.Sprintf("commonmark/%03d", example.Example)})
253 }
254 notes, err := filepath.Glob("testdata/corpus/notes/*.md")
255 if err != nil {
256 t.Fatal(err)
257 }
258 sort.Strings(notes)
259 for _, path := range notes {
260 text, err := os.ReadFile(path)
261 if err != nil {
262 t.Fatal(err)
263 }
264 name := "notes/" + filepath.Base(path)
265 bodies = append(bodies, corpusBody{Name: name, Body: string(text)})
266 }
267 return bodies
268}
269
270func readJSON(t *testing.T, path string, into any) {
271 t.Helper()
272 text, err := os.ReadFile(path)
273 if err != nil {
274 t.Fatal(err)
275 }
276 if err := json.Unmarshal(text, into); err != nil {
277 t.Fatalf("%s: %v", path, err)
278 }
279}
280
281func goldenOf(bodies []corpusBody, resolver Resolver) []goldenBody {
282 out := make([]goldenBody, len(bodies))
283 for at, body := range bodies {
284 blocks := Parse(body.Body)
285 out[at] = goldenBody{Name: body.Name, Body: body.Body,
286 Blocks: goldenBlocks(blocks),
287 Links: goldenLinks(blocks, resolver),
288 Images: goldenImages(body.Body),
289 HTML: string(RenderPage(blocks, resolver))}
290 }
291 return out
292}
293
294func goldenBlocks(blocks []Block) []goldenBlock {
295 out := make([]goldenBlock, len(blocks))
296 for at, block := range blocks {
297 out[at] = goldenBlock{Kind: block.Kind, Level: block.Level,
298 Ordered: block.Ordered, Marker: block.Marker,
299 Start: block.Start, End: block.End, Source: block.Source,
300 Column: block.Column, Plain: Strip(block), Spans: []goldenSpan{}}
301 if block.Kind == Code {
302 continue
303 }
304 for _, span := range Spans(Strip(block)) {
305 out[at].Spans = append(out[at].Spans, goldenSpan{
306 Kind: span.Kind, Text: span.Text, Target: span.Target,
307 Anchor: span.Anchor, URL: span.URL, Source: span.Source})
308 }
309 }
310 return out
311}
312
313// goldenLinks is each distinct link the renderer resolves, in order.
314func goldenLinks(blocks []Block, resolver Resolver) []goldenLink {
315 out := []goldenLink{}
316 seen := map[[2]string]bool{}
317 for _, block := range blocks {
318 if block.Kind == Code {
319 continue
320 }
321 for _, span := range Spans(Strip(block)) {
322 key := [2]string{span.Target, span.Anchor}
323 if span.Kind != WikiLink || seen[key] {
324 continue
325 }
326 seen[key] = true
327 answer := resolver.Resolve(span.Target, span.Anchor)
328 out = append(out, goldenLink{Target: span.Target,
329 Anchor: span.Anchor, Href: answer.Href,
330 Pending: answer.Pending, Broken: answer.Broken,
331 BlockGone: answer.BlockGone, Title: answer.Title,
332 Alias: answer.Alias, Day: answer.Day,
333 Icon: chipIcon(answer.Icon)})
334 }
335 }
336 return out
337}
338
339// goldenImages is each distinct image's answer, in order.
340func goldenImages(body string) []goldenImage {
341 out := []goldenImage{}
342 seen := map[string]bool{}
343 for _, ref := range Images(body) {
344 if seen[ref.ID] {
345 continue
346 }
347 seen[ref.ID] = true
348 answer := corpusResolver{}.Image(ref.ID)
349 out = append(out, goldenImage{ID: ref.ID,
350 Available: answer.Available, Width: answer.Width,
351 Height: answer.Height})
352 }
353 return out
354}
355
356// encodeGolden writes one body per line, so a change reads as a diff of
357// the bodies it touched.
358func encodeGolden(bodies []goldenBody) []byte {
359 var out bytes.Buffer
360 out.WriteString("[\n")
361 for at, body := range bodies {
362 var line bytes.Buffer
363 encoder := json.NewEncoder(&line)
364 encoder.SetEscapeHTML(false)
365 if err := encoder.Encode(body); err != nil {
366 panic(err)
367 }
368 out.Write(bytes.TrimSuffix(line.Bytes(), []byte("\n")))
369 if at < len(bodies)-1 {
370 out.WriteString(",")
371 }
372 out.WriteString("\n")
373 }
374 out.WriteString("]\n")
375 return out.Bytes()
376}
377
378func firstDifference(committed, fresh []byte) string {
379 old := strings.Split(string(committed), "\n")
380 for number, line := range strings.Split(string(fresh), "\n") {
381 if number >= len(old) || old[number] != line {
382 return fmt.Sprintf("first difference at line %d", number+1)
383 }
384 }
385 return "the committed file is longer"
386}
387
388func chipIcon(icon ChipIcon) *ChipIcon {
389 if icon == (ChipIcon{}) {
390 return nil
391 }
392 return &icon
393}
394