UNPKG

textlint-rule-helper

Version:
86 lines • 3.1 kB
// MIT © 2018 azu "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapReportHandler = wrapReportHandler; var textlint_rule_helper_1 = __importDefault(require("./textlint-rule-helper")); var SourceLocation_1 = require("./SourceLocation"); var includes_type_1 = require("./includes-type"); var SortedRanges_1 = require("./SortedRanges"); /** * * @param context * @param options * @param handler */ function wrapReportHandler(context, options, handler) { var ignoreNodeTypes = options.ignoreNodeTypes || []; // Ranges of the ignored nodes var ignoredRanges = new SortedRanges_1.SortedRanges(); var ruleHelper = new textlint_rule_helper_1.default(context); var text = context.getSource(); var sourceLocation = new SourceLocation_1.SourceLocation(text); var reportIfUnignored = function reportIfUnignored(node, ruleError) { var index = sourceLocation.toAbsoluteLocation(node, ruleError); if (ignoredRanges.has(index)) { return; } return context.report(node, ruleError); }; // Roots of the subtrees that have already been searched for `ignoreNodeTypes`. // The AST does not change while linting, so searching the same subtree again adds nothing. // Without this, every handler call walks the whole subtree of the node. var searchedRoots = new WeakSet(); var isSearched = function (node) { var current = node; while (current != null) { if (searchedRoots.has(current)) { return true; } current = current.parent; } return false; }; var search = function (node) { if ((0, includes_type_1.includesType)(ignoreNodeTypes, node.type)) { ignoredRanges.add(node.range[0], node.range[1]); } var children = node.children; if (children) { for (var i = 0; i < children.length; i++) { search(children[i]); } } }; var ignoreChildrenByTypes = function (node) { if (isSearched(node)) { return; } searchedRoots.add(node); search(node); }; var handlers = handler(reportIfUnignored); Object.keys(handlers).forEach(function (nodeType) { var nodeHandler = handlers[nodeType]; var wrappedNodeHandler = function (node) { if (ignoreNodeTypes.length > 0) { // child nodes ignoreChildrenByTypes(node); // parent node if (ruleHelper.isChildNode(node, ignoreNodeTypes)) { return; } } if (!nodeHandler) { return; } return nodeHandler(node); }; // @ts-expect-error: ignore handlers[nodeType] = wrappedNodeHandler; }); return handlers; } //# sourceMappingURL=wrap-report-handler.js.map