Skip to content

Commit

Permalink
fix: rule replacement for dynamic styles
Browse files Browse the repository at this point in the history
  • Loading branch information
kripod committed Apr 2, 2020
1 parent 47a1f93 commit 5b3ba81
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions packages/glaze/src/StyleInjector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,30 @@ export class OptimizedStyleInjector implements StyleInjector {
private freeIndexes: number[] = [];

addRule(cssText: string): number {
const index = this.freeIndexes.length
? this.freeIndexes.pop()
: this.ruleCount++; // eslint-disable-line no-plusplus
return this.sheet.insertRule(cssText, index);
if (this.freeIndexes.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.replaceRule(this.freeIndexes.pop()!, cssText);
}

// eslint-disable-next-line no-plusplus
return this.sheet.insertRule(cssText, this.ruleCount++);
}

nullifyRule(index: number): void {
this.sheet.deleteRule(index);

if (index === this.ruleCount - 1) {
this.ruleCount -= 1;
// eslint-disable-next-line no-plusplus
this.sheet.deleteRule(--this.ruleCount);
} else {
// Only allow replacements to prevent modification of existing indexes
const dummyRule = '#_{}';
this.sheet.insertRule(dummyRule, index);
this.freeIndexes.push(index);
this.freeIndexes.push(this.replaceRule(index, dummyRule));
}
}

replaceRule(index: number, cssText: string): number {
this.sheet.deleteRule(index);
return this.sheet.insertRule(cssText, index);
}
}

export class DebuggableStyleInjector implements StyleInjector {
Expand All @@ -99,7 +105,12 @@ export class DebuggableStyleInjector implements StyleInjector {
}

addRule(cssText: string): number {
const index = this.freeIndexes.pop() ?? this.nodes.length;
if (this.freeIndexes.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.replaceRule(this.freeIndexes.pop()!, cssText);
}

const index = this.nodes.length;

if (index === MAX_RULE_COUNT) {
// eslint-disable-next-line no-console
Expand All @@ -120,9 +131,13 @@ export class DebuggableStyleInjector implements StyleInjector {
this.styleEl.removeChild(this.nodes.pop()!);
} else {
// Only allow replacements to prevent modification of existing indexes
this.freeIndexes.push(index);
const dummyRule = '';
this.nodes[index].textContent = dummyRule;
this.freeIndexes.push(this.replaceRule(index, dummyRule));
}
}

replaceRule(index: number, cssText: string): number {
this.nodes[index].textContent = cssText;
return index;
}
}

0 comments on commit 5b3ba81

Please sign in to comment.