-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
105 lines (90 loc) · 2.19 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
const resolved = new Map();
const useStylesheet = ({ href, media = 'all' }) => {
const sheets = document.getElementsByClassName('bulma-swatch');
const currentSheet = sheets[sheets.length - 1];
// Target styleSheet is the last on so it has loaded.
if (currentSheet && currentSheet.href === href) {
return;
}
// Style has already loaded so we can just add it to the end
if (resolved.has(href)) {
const link = resolved.get(href);
return document.body.appendChild(link);
}
throw new Promise((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
link.media = media;
link.className = 'bulma-swatch';
resolved.set(href, link);
const removeListeners = () => {
link.removeEventListener('load', load);
link.removeEventListener('error', error);
};
const error = () => {
removeListeners();
reject();
};
const load = () => {
removeListeners();
resolve();
};
link.addEventListener('error', error);
link.addEventListener('load', load);
document.body.appendChild(link);
});
};
const swatches = [
'default',
'cerulean',
'cosmo',
'cyborg',
'darkly',
'flatly',
'journal',
'litera',
'lumen',
'lux',
'materia',
'minty',
'nuclear',
'pulse',
'sandstone',
'simplex',
'slate',
'solar',
'spacelab',
'superhero',
'united',
'yeti'
];
export const getRandomSwatch = () =>
swatches[Math.floor(Math.random() * swatches.length)];
export const useBulmaSwatch = (swatch = 'default') => {
if (swatch === 'random') {
swatch = getRandomSwatch();
}
useStylesheet({
href: `https://jenil.github.io/bulmaswatch/${swatch}/bulmaswatch.min.css`
});
};
export const BulmaApp = ({ swatch, random, children }) => {
if (random) {
useBulmaSwatch();
} else {
useBulmaSwatch(swatch);
}
return <Fragment>{children}</Fragment>;
};
BulmaApp.propTypes = {
children: PropTypes.node.isRequired,
random: PropTypes.bool,
swatch: PropTypes.oneOf([...swatches, 'random'])
};
BulmaApp.defaultProps = {
random: false,
swatch: 'default'
};