frontispiece / packages / ink-processor / src / data / line.ts
line.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/.
 */

// A series of functions that manipulate a single ink line, and produce tokens that can
// create markup.
// In particular, uses a bbcode-esque tag system and custom work with links and image syntax
// to allow the engine to do different things with them.

import { CommandParams, VisualInkCommand, VisualInkLine } from "../types"
import { parseAtShorthandLine } from "@a-morphous/at-shorthand"
import { InkParserConfigParams } from "../config"
import * as LINEAR from "@a-morphous/linear"

export const createVisualInkCommand = (
	line: string,
	config?: InkParserConfigParams
): VisualInkCommand | undefined => {
	const identifier = config?.commandIdentifier || ">> "
	if (line.startsWith(identifier)) {
		const tokens = line.slice(identifier.length).split(" ")
		const commandName = tokens.shift().trim()

		const params: CommandParams = LINEAR.parse(tokens.join(" "), {
			separator: ",",
		})
		if (!params._) {
			params._ = []
		}

		return {
			type: "command",
			command: commandName,
			params: params,
			text: line,
		}
	}
	return undefined
}

export const createVisualInkLine = (line: string): VisualInkLine => {
	const atShorthand = parseAtShorthandLine(line)

	const lineObj: VisualInkLine = {
		text: atShorthand.text,
		type: "line",
	}

	if (atShorthand.primary) {
		lineObj.meta = {
			primary: atShorthand.primary,
			classes: atShorthand.classes,
		}
	}

	return lineObj
}