Skip to content

Commit

Permalink
Fix nested selectors returning the same hash
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed Apr 29, 2020
1 parent 5e73ea7 commit 116bf7b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
18 changes: 9 additions & 9 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,23 +368,23 @@ describe("free style", () => {
expect(Style.getStyles()).toEqual("@media print{body{color:red}}");
});

it("should de-dupe across styles and rules", () => {
it("should create a different hash for nested css rules", () => {
const Style = create();
let changeId = Style.changeId;

const className1 = Style.registerStyle({
color: "red",
});

expect(Style.changeId).not.toEqual(changeId);
changeId = Style.changeId;

Style.registerRule(".test", {
color: "red",
const className2 = Style.registerStyle({
"&:first-child": {
color: "red",
},
});

expect(Style.changeId).not.toEqual(changeId);
expect(Style.getStyles()).toEqual(`.${className1},.test{color:red}`);
expect(className1).not.toEqual(className2);
expect(Style.getStyles()).toEqual(
`.${className1}{color:red}.${className2}:first-child{color:red}`
);
});

it("should retain insertion order", () => {
Expand Down
15 changes: 9 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ type StylizeRule = {
function stylize(
rulesList: StylizeRule[],
stylesList: StylizeStyle[],
className: string,
key: string,
styles: Styles,
parentClassName: string
) {
Expand All @@ -207,35 +207,38 @@ function stylize(
const style = stringifyProperties(sortTuples(properties));
let pid = style;

if (className.charCodeAt(0) === 64 /* @ */) {
if (key.charCodeAt(0) === 64 /* @ */) {
const childRules: StylizeRule[] = [];
const childStyles: StylizeStyle[] = [];

// Nested styles support (e.g. `.foo > @media`).
if (parent && style) {
pid += `:${parent}`;
childStyles.push({ selector: parent, style, isUnique });
}

for (const [name, value] of nested) {
pid += stylize(childRules, childStyles, name, value, parent);
pid += `:${stylize(childRules, childStyles, name, value, parent)}`;
}

// Add new rule to parent.
rulesList.push({
selector: className,
selector: key,
rules: childRules,
styles: childStyles,
style: parent ? "" : style,
});
} else {
const selector = parent ? child(className, parent) : className;
const selector = parent ? child(key, parent) : key;

pid += `:${selector}`;

if (style) {
stylesList.push({ selector, style, isUnique });
}

for (const [name, value] of nested) {
pid += stylize(rulesList, stylesList, name, value, selector);
pid += `:${stylize(rulesList, stylesList, name, value, selector)}`;
}
}

Expand Down

0 comments on commit 116bf7b

Please sign in to comment.