UNPKG

stylelint

Version:
92 lines (81 loc) 2.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = styleTagsFromHtmlExtracter; exports.iterateCodeForStyleTags = iterateCodeForStyleTags; var _htmlparser = require("htmlparser2"); var _htmlparser2 = _interopRequireDefault(_htmlparser); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Extract styles from html markup, returning the exctacted * code with line and indentation mappings. * * @param {string} code * @return {object} { map, code } */ function styleTagsFromHtmlExtracter(code) { var map = []; var resultCode = ""; var lineNumber = 1; var relativeLineNumber = 1; var isStructureHTML = iterateCodeForStyleTags(code, function (previousCode, styleCode) { var indentMatch = /[\n\r]+([ \t]*)/.exec(styleCode); var indent = indentMatch ? indentMatch[1] : ""; var previousCodeLines = previousCode.match(/\n|\r/g); // Preserve line numbers and indentation mapping if (previousCodeLines) { lineNumber += previousCodeLines.length; } resultCode += styleCode.replace(/(\n|\r)([ \t]*)(.*)/g, function (_, newLineChar, lineIndent, lineText) { map[relativeLineNumber++] = { indent: indent.length, line: lineNumber++ }; return newLineChar + lineIndent.slice(indent.length) + lineText; }).replace(/[ \t]*$/, ""); // Remove spaces on the last line }); return { map: map, code: isStructureHTML ? resultCode : code }; } /** * Iterate through style tags. Extracting content of code * with onStyle callback * * @param {string} code * @param {function} onStyle */ function iterateCodeForStyleTags(code, onStyle) { var index = 0; var currentStyle = null; var isStructureHTML = false; var parser = new _htmlparser2.default.Parser({ onopentag: function onopentag(name) { // Found a tag, the structure is now confirmed as HTML isStructureHTML = true; // Test if current tag is a valid <style> tag. if (name !== "style") { return; } currentStyle = ""; }, onclosetag: function onclosetag(name) { if (name !== "style" || currentStyle === null) { return; } onStyle(code.slice(index, parser.startIndex - currentStyle.length), currentStyle); index = parser.startIndex; currentStyle = null; }, ontext: function ontext(data) { if (currentStyle === null) { return; } currentStyle += data; } }); parser.parseComplete(code); return isStructureHTML; }