-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (39 loc) · 1.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const jss = require('jss').default;
const { SheetsManager, SheetsRegistry } = require('jss');
const { onDestroy } = require('svelte');
// SETUP
const SSR_TAG_NAME = 'svelte-jss-ssr';
const registry = new SheetsRegistry();
const manager = new SheetsManager();
// HELPERS
const addSheet = (styles) => {
let sheet = manager.get(styles);
if (!sheet) {
sheet = jss.createStyleSheet(styles);
registry.add(sheet);
manager.add(styles, sheet);
}
return sheet;
};
const manageStyles = (styles) => {
const sheet = addSheet(styles);
// Attach sheet once + increment ref count
manager.manage(styles);
onDestroy(() => {
// Decrement ref count + detach sheet if 0
manager.unmanage(styles);
});
return sheet;
};
// PUBLIC API
exports.useStyles = (styles) => {
if (!styles) throw new Error(`Cannot manage these styles: ${styles}`);
return manageStyles(styles).classes;
};
exports.getSSRStyleTag = () => {
return `<style id="${SSR_TAG_NAME}">${registry.toString()}</style>`;
};
exports.removeSSRStyleTag = () => {
const ssrStyles = document.getElementById(SSR_TAG_NAME);
ssrStyles.parentNode.removeChild(ssrStyles);
};