UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

77 lines (75 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ts = require("typescript"); const textChecks_1 = require("./../textChecks"); const insertIntoCreatableSyntaxList_1 = require("./insertIntoCreatableSyntaxList"); /** * Used to insert non-comma separated nodes into braces or a source file. */ function insertIntoBracesOrSourceFile(opts) { const { parent, index, childCodes, separator, children } = opts; const sourceFile = parent.getSourceFile(); const insertPos = getInsertPosition(index, parent, children); const newLineChar = sourceFile.global.manipulationSettings.getNewLineKind(); let newText = ""; for (let i = 0; i < childCodes.length; i++) { if (i > 0) { newText += separator; if (opts.separatorNewlineWhen != null && opts.separatorNewlineWhen(opts.structures[i - 1], opts.structures[i])) newText += newLineChar; } newText += childCodes[i]; } if (index !== 0) newText = separator + newText; else if (insertPos !== 0) newText = newLineChar + newText; else if (parent.getFullWidth() > 0) newText = newText + separator; if (opts.previousBlanklineWhen != null) { const previousMember = children[index - 1]; const firstStructure = opts.structures[0]; if (previousMember != null && opts.previousBlanklineWhen(previousMember, firstStructure)) newText = newLineChar + newText; } const nextMember = children[index]; if (opts.nextBlanklineWhen != null) { const lastStructure = opts.structures[opts.structures.length - 1]; if (nextMember != null && opts.nextBlanklineWhen(nextMember, lastStructure)) { if (!textChecks_1.isBlankLineAtPos(sourceFile, insertPos)) newText = newText + newLineChar; } } if (parent.isSourceFile() && nextMember == null && !newText.endsWith(newLineChar) && !sourceFile.getFullText().endsWith("\n")) newText = newText + newLineChar; insertIntoCreatableSyntaxList_1.insertIntoCreatableSyntaxList({ parent, insertPos, newText, syntaxList: parent.getChildSyntaxListOrThrow(), childIndex: index, insertItemsCount: childCodes.length }); } exports.insertIntoBracesOrSourceFile = insertIntoBracesOrSourceFile; function getInsertPosition(index, parent, children) { if (index === 0) { if (parent.isSourceFile()) return 0; else { const parentContainer = getParentContainer(parent); const openBraceToken = parentContainer.getFirstChildByKindOrThrow(ts.SyntaxKind.OpenBraceToken); return openBraceToken.getEnd(); } } return children[index - 1].getEnd(); } function getParentContainer(parent) { if (parent.isBodiedNode()) return parent.getBody(); if (parent.isBodyableNode()) return parent.getBodyOrThrow(); else return parent; } //# sourceMappingURL=insertIntoBracesOrSourceFile.js.map