recital / core / src / pipeline / 01-strings / plugins / trim.ts
trim.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * 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 http://mozilla.org/MPL/2.0/.
 */

import eol from 'eol'
import { createTrimWhitespaceTokens } from '../../../tools/split-preserve-whitespace'
import { StringParserPlugin } from '../../../types'

export const parseTrimLines: StringParserPlugin = (raw: string): string => {
	const trimmedContentTokens = createTrimWhitespaceTokens(raw)

	let finalString = ''

	for (let token of trimmedContentTokens) {
		switch (token.type) {
			case 'none':
				finalString += trimLinesOfSection(token.text).trim() + '\n\n'
				break
			default:
				if (token.startTag) {
					finalString += token.startTag + '\n'
				}
				finalString += token.text
				if (token.endTag) {
					finalString += token.endTag + '\n'
				}
		}
	}

	return finalString.trim()
}

const trimLinesOfSection = (text: string): string => {
	const lines = eol.split(text)
	let finalString = ''
	for (let line of lines) {
		finalString += line.trim() + '\n'
	}
	return finalString
}