Skip to content

Commit

Permalink
Add selectorSplit
Browse files Browse the repository at this point in the history
  • Loading branch information
lauriro committed Jan 4, 2025
1 parent 1b70296 commit 27d68a6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
22 changes: 22 additions & 0 deletions css.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

/*! litejs.com/MIT-LICENSE.txt */

exports.selectorSplit = selectorSplit
exports.CSSStyleDeclaration = CSSStyleDeclaration
exports.CSSStyleSheet = CSSStyleSheet

Expand Down Expand Up @@ -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
}


3 changes: 2 additions & 1 deletion dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions test/css.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
})
})

0 comments on commit 27d68a6

Please sign in to comment.