frontispiece / apps / frontispiece-editor / src / view / line-viewer.ts
line-viewer.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 { VisualInkLine } from "@a-morphous/frontispiece-ink-processor/src/types"
import { marked } from "marked"
import { html } from "../bootstrap/bootstrap"
import { parseLineIntoTokens } from "@a-morphous/frontispiece-line-parser"

type LineViewerProps = {
	line: VisualInkLine
	isActive?: boolean
}

export const LineViewer = (props: LineViewerProps) => {
	const renderTokens = () => {
		let str = ""
		let tokens = parseLineIntoTokens(props.line.text)
		if (!tokens) {
			str = props.line.text
		} else {
			for (let t of tokens) {
				switch (t.type) {
					case "text":
						str += t.text
						break
					case "tag":
						if (t.isClosingTag) {
							str += `</span>`
						} else {
							str += `<span class="ink-${t.param}">`
						}
						break
					case "link":
						str += `[${t.text}](${t.target})`
						break
					case "note":
						// we'll implement this later
						str += t.text
						break
				}
			}
		}

		// const parsedMarkdown = microdown.inlineBlock(str)
		const parsedMarkdown = marked.parseInline(str, {
			gfm: true,
		})
		return html`<span
			dangerouslySetInnerHTML=${{
				__html: parsedMarkdown,
			}}
		/>`
	}

	let classes: string[] = []
	if (props.line.meta?.classes) {
		classes = props.line.meta.classes
	}
	if (props.isActive) {
		classes.push("active")
	}

	return html`<p class=${classes.join(" ")}>${renderTokens()}</p>`
}