Skip to content

Commit

Permalink
fix: matched css selectors
Browse files Browse the repository at this point in the history
  • Loading branch information
surunzi committed May 4, 2020
1 parent 10310d5 commit 8954cfa
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
21 changes: 16 additions & 5 deletions target/domains/CSS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,11 @@ export function getInlineStylesForNode(params: any) {
}

export function getMatchedStylesForNode(params: any) {
const matchedCSSRules = stylesheet.getMatchedCssRules(getNode(params.nodeId));
const node = getNode(params.nodeId);
const matchedCSSRules = stylesheet.getMatchedCssRules(node);

return {
matchedCSSRules: map(matchedCSSRules, formatMatchedCssRule),
matchedCSSRules: map(matchedCSSRules, matchedCSSRule => formatMatchedCssRule(node, matchedCSSRule)),
...getInlineStylesForNode(params),
};
}
Expand Down Expand Up @@ -135,19 +136,29 @@ export function setStyleTexts(params: any) {
};
}

function formatMatchedCssRule(matchedCssRule: any) {
function formatMatchedCssRule(node: any, matchedCssRule: any) {
const { selectorText } = matchedCssRule;
const selectors = map(selectorText.split(','), trim);

const rule: any = {
styleSheetId: matchedCssRule.styleSheetId,
selectorList: {
selectors: [{ text: matchedCssRule.selectorText }],
text: matchedCssRule.selectorText,
selectors: map(selectors, selector => ({ text: selector })),
text: selectorText,
},
style: {
cssProperties: toCssProperties(matchedCssRule.style),
shorthandEntries: [],
},
};

const matchingSelectors: number[] = [];
each(selectors, (selector, idx) => {
if (stylesheet.matchesSelector(node, selector)) {
matchingSelectors.push(idx);
}
});

return {
matchingSelectors: [0],
rule,
Expand Down
6 changes: 5 additions & 1 deletion target/lib/stylesheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ if (elProto.webkitMatchesSelector) {
matchesSel = (el: any, selText: string) => el.mozMatchesSelector(selText);
}

export function matchesSelector(el: any, selText: string) {
return matchesSel(el, selText);
}

const emitter = new Emitter();
export function onStyleSheetAdded(fn: any) {
emitter.on('styleSheetAdded', fn);
Expand Down Expand Up @@ -47,7 +51,7 @@ export function getMatchedCssRules(node: any) {

// Mobile safari will throw DOM Exception 12 error, need to try catch it.
try {
matchesEl = matchesSel(node, cssRule.selectorText);
matchesEl = matchesSelector(node, cssRule.selectorText);
/* eslint-disable no-empty */
} catch (e) {}

Expand Down

0 comments on commit 8954cfa

Please sign in to comment.