From 27d68a682ef784ce3ef7d65ba05ac984ac517d0f Mon Sep 17 00:00:00 2001 From: Lauri Rooden Date: Sat, 4 Jan 2025 12:55:13 +0200 Subject: [PATCH] Add selectorSplit --- css.js | 22 ++++++++++++++++++++++ dom.js | 3 ++- test/css.js | 9 +++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/css.js b/css.js index 4c15579..68d0826 100644 --- a/css.js +++ b/css.js @@ -1,6 +1,7 @@ /*! litejs.com/MIT-LICENSE.txt */ +exports.selectorSplit = selectorSplit exports.CSSStyleDeclaration = CSSStyleDeclaration exports.CSSStyleSheet = CSSStyleSheet @@ -185,4 +186,25 @@ CSSStyleSheet.prototype = { } } +function selectorSplit(text) { + for (var char, inQuote, depth = 0, start = 0, pos = 0, len = text.length, out = []; pos < len; ) { + char = text[pos++] + if (char === "\\") { + pos++ + } else if (inQuote) { + if (char === inQuote) inQuote = "" + } else if (char === "'" || char === "\"") { + inQuote = char + } else if (char === "(" || char === "[") { + depth++ + } else if (char === ")" || char === "]") { + depth-- + } else if (char === "," && depth === 0) { + out.push(text.slice(start, (start = pos) - 1).trim()) + } + } + out.push(text.slice(start).trim()) + return out +} + diff --git a/dom.js b/dom.js index a849e11..d49a657 100644 --- a/dom.js +++ b/dom.js @@ -16,7 +16,7 @@ var boolAttrs = { , rawTextElements = { SCRIPT: /<(?=\/script)/i, STYLE: /<(?=\/style)/i } , rawTextEscape = { SCRIPT: /<(?=\/script|!--)/ig, STYLE: /<(?=\/style|!--)/ig } , hasOwn = voidElements.hasOwnProperty -, { CSSStyleDeclaration, CSSStyleSheet } = require("./css.js") +, { selectorSplit, CSSStyleDeclaration, CSSStyleSheet } = require("./css.js") , selector = require("./selector.js") , Node = { ELEMENT_NODE: 1, @@ -488,6 +488,7 @@ function getSibling(node, step, type) { exports.document = new Document() exports.entities = entities +exports.selectorSplit = selectorSplit exports.CSSStyleDeclaration = CSSStyleDeclaration exports.CSSStyleSheet = CSSStyleSheet exports.DOMParser = DOMParser diff --git a/test/css.js b/test/css.js index ef16cd5..46222f4 100644 --- a/test/css.js +++ b/test/css.js @@ -8,6 +8,7 @@ describe("css.js {0}", describe.env === "browser" ? [["mock", exports], ["native", native]] : [["mock", require("../css.js")]], (name, env) => { require("@litejs/cli/snapshot") const { + selectorSplit, CSSStyleSheet, CSSStyleDeclaration, } = env @@ -109,5 +110,13 @@ describe("css.js {0}", describe.env === "browser" ? [["mock", exports], ["native }) assert.end() }) + + it("split selectors {0}", selectorSplit && [ + [ "html", ["html"] ], + [ "[a]", ["[a]"] ], + [ ".a,b:not(.b,.c) , .d[a='a,\\'b][c']:focus", [".a", "b:not(.b,.c)", ".d[a='a,\\'b][c']:focus"] ], + ], function(sel, arr, assert) { + assert.equal(selectorSplit(sel), arr).end() + }) })