Skip to content

Commit

Permalink
🔨 Create sheet singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
danieldelcore committed Oct 25, 2020
1 parent 41b98f4 commit 8dab695
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
22 changes: 14 additions & 8 deletions packages/react/src/jsx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import React, {
import { Collector, process, isBrowser } from '@trousers/core';
import sheet from '@trousers/sheet';

let styleSheet: ReturnType<typeof sheet> | null = null;
if (isBrowser()) {
const headElement = document.getElementsByTagName('head')[0];
styleSheet = sheet(headElement, 'data-trousers');
}

const jsx = <
Props extends {
css: ReturnType<Collector>;
Expand Down Expand Up @@ -66,16 +72,16 @@ const jsx = <

// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => {
const headElement = document.getElementsByTagName('head')[0];
const styleSheet = sheet(headElement, 'data-trousers');

definitions
.filter(({ className }) => !styleSheet.has(className))
.filter(
({ className }) =>
styleSheet && !styleSheet.has(`.${className}`),
)
.forEach(({ className, styles }) => {
Object.entries(
process(`.${className}`, styles),
).forEach(([key, value]) =>
styleSheet.mount(key, `${key}{${value}}`, false),
Object.entries(process(`.${className}`, styles)).forEach(
([key, value]) =>
styleSheet &&
styleSheet.mount(key, `${key}{${value}}`, false),
);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
3 changes: 1 addition & 2 deletions packages/sheet/src/sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const getSheet = (tag: HTMLStyleElement): CSSStyleSheet => {

const sheet = (targetEl: HTMLElement, attributeId: string) => {
let styleEl = getElement(targetEl, attributeId);
const styleMap = new Map(); // TODO: this causes duplicates
const styleMap = new Map();

if (styleEl === null) {
styleEl = createStyleElement(attributeId);
Expand All @@ -37,7 +37,6 @@ const sheet = (targetEl: HTMLElement, attributeId: string) => {
const has = (id: string) => styleMap.has(id);

const mount = (id: string, styles: string, isGlobal?: boolean) => {
// TODO: maybe a map isn't the best thing to use here
styleMap.set(id, '');

try {
Expand Down

0 comments on commit 8dab695

Please sign in to comment.