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 c431c70
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 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
2 changes: 2 additions & 0 deletions packages/sheet/src/sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ const sheet = (targetEl: HTMLElement, attributeId: string) => {

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

styleMap.set(id, '');

try {
Expand Down

0 comments on commit c431c70

Please sign in to comment.