Untitled
unknown
javascript
2 years ago
3.6 kB
2
Indexable
Never
// Не забудьте перед отправкой изменить в module.exports = function(html, css) { export default function(html, css) { let css1 = css.map(cssRule => { let indexPlus = cssRule.selector.indexOf("+"); if (indexPlus !== -1) { return { tags: cssRule.selector.split("+").map(it => it.trim()), declarations: cssRule.declarations, op: "+", priority: 3, }; } let indexGt = cssRule.selector.indexOf(">"); if (indexGt !== -1) { return { tags: cssRule.selector.split(">").map(it => it.trim()), declarations: cssRule.declarations, op: ">", priority: 2, }; } let indexTilde = cssRule.selector.indexOf("~"); if (indexTilde !== -1) { return { tags: cssRule.selector.split("~").map(it => it.trim()), declarations: cssRule.declarations, op: "~", priority: 4, }; } let indexSpace = cssRule.selector.indexOf(" "); if (indexSpace !== -1) { return { tags: cssRule.selector.split(" ").map(it => it.trim()), declarations: cssRule.declarations, op: " ", priority: 1, }; } return { tags: [cssRule.selector], declarations: cssRule.declarations, op: null, priority: 100, }; }) css1.sort((e1, e2) => e1.priority - e2.priority); let applyRule = function(curStyles, cssRule) { Object.entries(cssRule.declarations).forEach(([key, value]) => { curStyles[key] = value; }); } // sibindex cur pos in sibList/ // siblist all bros in cur level function traverseTree(html, css, sibIndex, sibList, styles, parentTags) { if (html.type === "TEXT") { return; } const curStyles = Object.assign({}, styles); css.forEach(cssRule => { if (cssRule.op === null && cssRule.tags[0] === html.tag) { applyRule(curStyles, cssRule); } if (cssRule.op === " " && cssRule.tags[1] === html.tag && parentTags.includes(cssRule.tags[0])) { applyRule(curStyles, cssRule); } if (cssRule.op === ">" && cssRule.tags[1] === html.tag && parentTags[parentTags.length - 1] === cssRule.tags[0]) { applyRule(curStyles, cssRule); } if (cssRule.op === "+" && cssRule.tags[1] === html.tag && sibIndex > 0 && sibList[sibIndex - 1].tag === cssRule.tags[0]) { applyRule(curStyles, cssRule); } if (cssRule.op === "~" && cssRule.tags[1] === html.tag) { for (let i = 0; i < sibIndex; i++) { if (cssRule.tags[0] === sibList[i].tag) { applyRule(curStyles, cssRule); break; } } } }); html.styles = curStyles; parentTags.push(html.tag); html.children.forEach((child, i) => traverseTree(child, css, i, html.children, curStyles, parentTags)) parentTags.pop(); return; } traverseTree(html, css1, 0, [html], {}, []); return html; }