Skip to content
Snippets Groups Projects
api.ts 1.45 KiB
Newer Older
import peg from 'pegjs';
import { MfmNode, MfmPlainNode } from './node';
import { stringifyNode, stringifyTree } from './util';

const parser: peg.Parser = require('./parser');

marihachi's avatar
marihachi committed
/**
marihachi's avatar
marihachi committed
 * Generates a MfmNode tree from the MFM string.
marihachi's avatar
marihachi committed
*/
export function parse(input: string): MfmNode[] {
	const nodes = parser.parse(input, { startRule: 'fullParser' });
	return nodes;
}

marihachi's avatar
marihachi committed
/**
marihachi's avatar
marihachi committed
 * Generates a MfmNode tree of plain from the MFM string.
marihachi's avatar
marihachi committed
*/
export function parsePlain(input: string): MfmPlainNode[] {
	const nodes = parser.parse(input, { startRule: 'plainParser' });
	return nodes;
}

marihachi's avatar
marihachi committed
/**
marihachi's avatar
marihachi committed
 * Generates a MFM string from the MfmNode tree.
marihachi's avatar
marihachi committed
*/
export function toString(tree: MfmNode[]): string
export function toString(node: MfmNode): string
export function toString(node: MfmNode | MfmNode[]): string {
	if (Array.isArray(node)) {
		return stringifyTree(node);
	}
	else {
		return stringifyNode(node);
	}
}

marihachi's avatar
marihachi committed
/**
marihachi's avatar
marihachi committed
 * Inspects the MfmNode tree.
marihachi's avatar
marihachi committed
*/
marihachi's avatar
marihachi committed
export function inspect(nodes: MfmNode[], action: (node: MfmNode) => void): void {
	for (const node of nodes) {
		action(node);
		if (node.children != null) {
			inspect(node.children, action);
		}
	}
}

marihachi's avatar
marihachi committed
/**
marihachi's avatar
marihachi committed
 * Inspects the MfmNode tree and returns as an array the nodes that match the conditions
marihachi's avatar
marihachi committed
 * of the predicate function.
*/
export function extract(nodes: MfmNode[], predicate: (node: MfmNode) => boolean): MfmNode[] {
marihachi's avatar
marihachi committed
	const dest = [] as MfmNode[];

	inspect(nodes, (node) => {
		if (predicate(node)) {
			dest.push(node);
marihachi's avatar
marihachi committed
	});