UNPKG

tm-text

Version:

Trackmania and Maniaplanet text parser and formatter

51 lines (50 loc) 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.blockify = void 0; const options_1 = require("../utils/options"); const syntax_1 = require("../utils/syntax"); const tokenize_1 = require("./tokenize"); const blockify = (input, options) => { const opts = (0, options_1.withDefaultOptions)(options); const tokens = typeof input === 'string' ? (0, tokenize_1.tokenize)(input, opts) : input; const openBlockIndices = []; const blocks = []; tokens.forEach((token, index) => { if (token.kind === syntax_1.TOKEN.BLOCK_START) { openBlockIndices.push(index); } else if (token.kind === syntax_1.TOKEN.BLOCK_END || index === tokens.length - 1) { const startIndex = openBlockIndices.at(-1); if (startIndex === undefined) { return; } blocks.push({ startIndex, endIndex: index, tokens: tokens.filter((_, i) => i >= startIndex && i <= index), }); openBlockIndices.pop(); } }); blocks.sort((block1, block2) => (block1.startIndex < block2.startIndex ? 1 : -1)); blocks.push({ startIndex: 0, endIndex: tokens.length - 1, tokens, }); blocks.forEach((block, index) => { const tokenStartPositions = block.tokens.reduce((positions, token) => { positions.push(token.pos.start); return positions; }, []); blocks.forEach((otherBlock, otherBlockIndex) => { if (index === otherBlockIndex) { return; } otherBlock.tokens = otherBlock.tokens.filter((token) => !tokenStartPositions.includes(token.pos.start)); }); }); blocks.sort((block1, block2) => { var _a, _b; return ((((_a = block1.tokens.at(0)) === null || _a === void 0 ? void 0 : _a.pos.start) || 1) > (((_b = block2.tokens.at(0)) === null || _b === void 0 ? void 0 : _b.pos.start) || 1) ? 1 : -1); }); return blocks; }; exports.blockify = blockify;