frontispiece / packages / line-parser / src / line.spec.ts
line.spec.ts
Raw
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

import { describe, it, expect } from "vitest"
import { parseLineIntoTokens } from "./line"
import json5 from "json5"

const lines = [
	"Testing <<tag>>tagged<</tag>> items.",
	"Testing how [links](knot name) work.",
	"Testing ![endnotes](id-goes-here). They work like links.",
	"Testing [links that don't go anywhere]",
	"End notes! ![This content should link](test) to a footnote with a bigger test. (Still work in progress, exactly how the ~secondary~ content should be linked.)",
]

const errorLines = [
	"Testing a dangling [link",
	"Testing a [dangling url](unfinished",
	"Tag left <<open",
]

const expected = [
	json5.parse(`[
		{ type: 'text', text: 'Testing ' },
		{ type: 'tag', isClosingTag: false, param: 'tag' },
		{ type: 'text', text: 'tagged' },
		{ type: 'tag', isClosingTag: true, param: 'tag' },
		{ type: 'text', text: ' items.' }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'Testing how ' },
		{ type: 'link', target: 'knot name', text: 'links' },
		{ type: 'text', text: ' work.' }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'Testing ' },
		{ type: 'note', target: 'id-goes-here', text: 'endnotes' },
		{ type: 'text', text: '. They work like links.' }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'Testing ' },
		{ type: 'text', text: "[links that don't go anywhere]" }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'End notes! ' },
		{ type: 'note', target: 'test', text: 'This content should link' },
		{
		  type: 'text',
		  text: ' to a footnote with a bigger test. (Still work in progress, exactly how the ~secondary~ content should be linked.)'
		}
	  ]`),
]

const expectedError = [
	json5.parse(`[
		{ type: 'text', text: 'Testing a dangling ' },
		{ type: 'text', text: '[link' }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'Testing a ' },
		{ type: 'link', target: 'unfinished', text: 'dangling url' }
	  ]`),
	json5.parse(`[
		{ type: 'text', text: 'Tag left ' },
		{ type: 'tag', isClosingTag: false, param: 'open' }
	  ]`),
]

describe("parseLineIntoTokens", () => {
	it("should parse lines", () => {
		for (let i = 0; i < lines.length; i++) {
			const tokens = parseLineIntoTokens(lines[i])
			const expectedLine = expected[i]
			expect(tokens).toEqual(expectedLine)
		}
	})

	it("should handle errors", () => {
		for (let i = 0; i < errorLines.length; i++) {
			const tokens = parseLineIntoTokens(errorLines[i])
			const expectedLine = expectedError[i]
			expect(tokens).toEqual(expectedLine)
		}
	})
})