simplestyle-js 3.2.2 → 3.2.3-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/createStyles.d.ts +2 -2
- package/createStyles.js +25 -5
- package/createStyles.js.map +1 -1
- package/generateClassName.js.map +1 -1
- package/index.cjs.js +33 -6
- package/index.js.map +2 -2
- package/numToAlpha.js.map +1 -1
- package/package.json +41 -40
- package/plugins.d.ts +1 -1
- package/plugins.js.map +1 -1
- package/react/index.cjs.js +54 -20
- package/react/index.js.map +4 -4
- package/react/useCreateStyles.d.ts +5 -1
- package/react/useCreateStyles.js +25 -13
- package/react/useCreateStyles.js.map +3 -3
- package/types.d.ts +1 -1
- package/util/deepEqual.js.map +1 -1
- package/util/index.js.map +1 -1
package/createStyles.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Properties } from 'csstype';
|
|
2
2
|
import { SimpleStyleRules } from './types';
|
|
3
|
-
export
|
|
3
|
+
export type CreateStylesOptions = Partial<{
|
|
4
4
|
/**
|
|
5
5
|
* If true, automatically renders generated styles
|
|
6
6
|
* to the DOM in an injected <style /> tag
|
|
@@ -33,4 +33,4 @@ export default function createStyles<T extends SimpleStyleRules, K extends keyof
|
|
|
33
33
|
stylesheet: string;
|
|
34
34
|
} | null;
|
|
35
35
|
};
|
|
36
|
-
export
|
|
36
|
+
export type CreateStylesArgs = Parameters<typeof createStyles>;
|
package/createStyles.js
CHANGED
|
@@ -11,7 +11,10 @@ function formatCSSRuleName(rule) {
|
|
|
11
11
|
return rule.replace(/([A-Z])/g, (p1) => `-${p1.toLowerCase()}`);
|
|
12
12
|
}
|
|
13
13
|
function formatCSSRules(cssRules) {
|
|
14
|
-
return Object.entries(cssRules).reduce(
|
|
14
|
+
return Object.entries(cssRules).reduce(
|
|
15
|
+
(prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,
|
|
16
|
+
""
|
|
17
|
+
);
|
|
15
18
|
}
|
|
16
19
|
function execCreateStyles(rules, options, parentSelector, noGenerateClassName = false) {
|
|
17
20
|
const out = {};
|
|
@@ -30,7 +33,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
30
33
|
throw new Error("Unable to map @media query because rules / props are an invalid type");
|
|
31
34
|
guardCloseRuleWrite();
|
|
32
35
|
mediaQueriesBuffer += `${classNameOrCSSRule}{`;
|
|
33
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
36
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
37
|
+
classNameRules,
|
|
38
|
+
options,
|
|
39
|
+
parentSelector
|
|
40
|
+
);
|
|
34
41
|
mediaQueriesBuffer += regularOutput;
|
|
35
42
|
mediaQueriesBuffer += "}";
|
|
36
43
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
@@ -40,7 +47,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
40
47
|
guardCloseRuleWrite();
|
|
41
48
|
const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);
|
|
42
49
|
for (const selector of replaced.split(/,\s*/)) {
|
|
43
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
50
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
51
|
+
classNameRules,
|
|
52
|
+
options,
|
|
53
|
+
selector
|
|
54
|
+
);
|
|
44
55
|
sheetBuffer += regularOutput;
|
|
45
56
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
46
57
|
}
|
|
@@ -49,7 +60,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
49
60
|
const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);
|
|
50
61
|
out[classNameOrCSSRule] = generated;
|
|
51
62
|
const generatedSelector = `${noGenerateClassName ? "" : "."}${generated}`;
|
|
52
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
63
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
64
|
+
classNameRules,
|
|
65
|
+
options,
|
|
66
|
+
generatedSelector
|
|
67
|
+
);
|
|
53
68
|
sheetBuffer += regularOutput;
|
|
54
69
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
55
70
|
} else {
|
|
@@ -116,7 +131,12 @@ function coerceCreateStylesOptions(options) {
|
|
|
116
131
|
}
|
|
117
132
|
function rawStyles(rules, options) {
|
|
118
133
|
const coerced = coerceCreateStylesOptions(options);
|
|
119
|
-
const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(
|
|
134
|
+
const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(
|
|
135
|
+
rules,
|
|
136
|
+
coerced,
|
|
137
|
+
null,
|
|
138
|
+
true
|
|
139
|
+
);
|
|
120
140
|
const mergedContents = `${sheetContents}${mediaQueriesContents}`;
|
|
121
141
|
if (coerced.flush)
|
|
122
142
|
flushSheetContents(mergedContents, options);
|
package/createStyles.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/createStyles.ts"],
|
|
4
4
|
"sourcesContent": ["import { Properties } from 'csstype';\nimport merge from 'deepmerge';\n\nimport { generateClassName } from './generateClassName';\nimport { getPosthooks } from './plugins';\nimport { SimpleStyleRules } from './types';\n\nexport type CreateStylesOptions = Partial<{\n /**\n * If true, automatically renders generated styles\n * to the DOM in an injected <style /> tag\n */\n flush: boolean;\n\n /**\n * If set, along with flush: true,\n * will render the injected <style /> after this element\n */\n insertAfter?: HTMLElement;\n /**\n * If set, along with flush: true,\n * will render the injects <style /> before this element\n */\n insertBefore?: HTMLElement;\n}>;\n\nfunction isNestedSelector(r: string): boolean {\n return /&/g.test(r);\n}\n\nfunction isMedia(r: string): boolean {\n return r.toLowerCase().startsWith('@media');\n}\n\nfunction formatCSSRuleName(rule: string): string {\n return rule.replace(/([A-Z])/g, p1 => `-${p1.toLowerCase()}`);\n}\n\nfunction formatCSSRules(cssRules: Properties): string {\n return Object.entries(cssRules).reduce(\n (prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,\n '',\n );\n}\n\nfunction execCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options: CreateStylesOptions,\n parentSelector: string | null,\n noGenerateClassName: boolean = false,\n): { classes: O; sheetBuffer: string; mediaQueriesBuffer: string } {\n const out = {} as O;\n let sheetBuffer = '';\n let mediaQueriesBuffer = '';\n const styleEntries = Object.entries(rules);\n let ruleWriteOpen = false;\n const guardCloseRuleWrite = () => {\n if (ruleWriteOpen) sheetBuffer += '}';\n ruleWriteOpen = false;\n };\n for (const [classNameOrCSSRule, classNameRules] of styleEntries) {\n // if the classNameRules is a string, we are dealing with a display: none; type rule\n if (isMedia(classNameOrCSSRule)) {\n if (typeof classNameRules !== 'object')\n throw new Error('Unable to map @media query because rules / props are an invalid type');\n guardCloseRuleWrite();\n mediaQueriesBuffer += `${classNameOrCSSRule}{`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n parentSelector,\n );\n mediaQueriesBuffer += regularOutput;\n mediaQueriesBuffer += '}';\n mediaQueriesBuffer += mediaQueriesOutput;\n } else if (isNestedSelector(classNameOrCSSRule)) {\n if (!parentSelector) throw new Error('Unable to generate nested rule because parentSelector is missing');\n guardCloseRuleWrite();\n // format of { '& > span': { display: 'none' } } (or further nesting)\n const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);\n for (const selector of replaced.split(/,\\s*/)) {\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n selector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n }\n } else if (!parentSelector && typeof classNameRules === 'object') {\n guardCloseRuleWrite();\n const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);\n (out as any)[classNameOrCSSRule] = generated;\n const generatedSelector = `${noGenerateClassName ? '' : '.'}${generated}`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n generatedSelector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n } else {\n if (!parentSelector) throw new Error('Unable to write css props because parent selector is null');\n if (!ruleWriteOpen) {\n sheetBuffer += `${parentSelector}{${formatCSSRules({ [classNameOrCSSRule]: classNameRules })}`;\n ruleWriteOpen = true;\n } else sheetBuffer += formatCSSRules({ [classNameOrCSSRule]: classNameRules });\n }\n }\n guardCloseRuleWrite();\n return {\n classes: out,\n sheetBuffer,\n mediaQueriesBuffer,\n };\n}\n\nfunction replaceBackReferences<O extends { [key: string]: string }>(out: O, sheetContents: string): string {\n let outputSheetContents = sheetContents;\n const toReplace: string[] = [];\n const toReplaceRegex = /\\$\\w([a-zA-Z0-9_-]+)?/gm;\n let matches = toReplaceRegex.exec(outputSheetContents);\n while (matches) {\n toReplace.push(matches[0].valueOf());\n matches = toReplaceRegex.exec(outputSheetContents);\n }\n for (const r of toReplace) {\n outputSheetContents = outputSheetContents.replace(r, `.${out[r.substring(1)]}`);\n }\n return getPosthooks().reduce((prev, hook) => hook(prev), outputSheetContents);\n}\n\nfunction createSheet(sheetContents: string) {\n if (typeof document === 'undefined') return null;\n if (typeof document?.head?.appendChild !== 'function' || typeof document?.createElement !== 'function') return null;\n const styleTag = document.createElement('style');\n styleTag.innerHTML = sheetContents;\n return styleTag;\n}\n\nfunction flushSheetContents(sheetContents: string, options?: CreateStylesOptions) {\n // In case we're in come weird test environment that doesn't support JSDom\n const styleTag = createSheet(sheetContents);\n if (styleTag) {\n if (options?.insertAfter && options?.insertBefore) {\n throw new Error('Both insertAfter and insertBefore were provided. Please choose only one.');\n }\n if (options?.insertAfter?.after) options.insertAfter.after(styleTag as Node);\n else if (options?.insertBefore?.before) options.insertBefore.before(styleTag as Node);\n else document.head.appendChild(styleTag);\n }\n return styleTag;\n}\n\nfunction coerceCreateStylesOptions(options?: CreateStylesOptions): CreateStylesOptions {\n return {\n flush: options && typeof options.flush === 'boolean' ? options.flush : true,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function rawStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [key in K]: string }>(\n rules: T,\n options?: Partial<CreateStylesOptions>,\n) {\n const coerced = coerceCreateStylesOptions(options);\n const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(\n rules,\n coerced,\n null,\n true,\n );\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n if (coerced.flush) flushSheetContents(mergedContents, options);\n return mergedContents;\n}\n\nexport function keyframes<T extends { [increment: string]: Properties }>(\n frames: T,\n options?: CreateStylesOptions,\n): [string, string] {\n const coerced = coerceCreateStylesOptions(options);\n const keyframeName = generateClassName('keyframes_');\n const { sheetBuffer: keyframesContents } = execCreateStyles(frames, coerced, null, true);\n const sheetContents = `@keyframes ${keyframeName}{${keyframesContents}}`;\n if (coerced.flush) flushSheetContents(sheetContents);\n return [keyframeName, sheetContents];\n}\n\nexport default function createStyles<\n T extends SimpleStyleRules,\n K extends keyof T,\n O extends { [classKey in K]: string },\n>(rules: T, options?: Partial<CreateStylesOptions>) {\n const coerced = coerceCreateStylesOptions(options);\n const {\n classes: out,\n sheetBuffer: sheetContents,\n mediaQueriesBuffer: mediaQueriesContents,\n } = execCreateStyles(rules, coerced, null);\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n const replacedSheetContents = replaceBackReferences(out, mergedContents);\n\n let sheet: ReturnType<typeof flushSheetContents> = null;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const updateSheet = <T2 extends SimpleStyleRules, K2 extends keyof T2, O2 extends { [classKey in K2]: string }>(\n updatedRules: Partial<T2>,\n ) => {\n if (((options?.flush && sheet) || !options?.flush) && updatedRules) {\n // We prefer the first set, and then we shallow merge\n const {\n classes: updatedOut,\n sheetBuffer: updatedSheetContents,\n mediaQueriesBuffer: updatedMediaQueriesContents,\n } = execCreateStyles(merge(rules, updatedRules), { flush: false }, null);\n\n const updatedMergedContents = `${updatedSheetContents}${updatedMediaQueriesContents}`;\n\n const updatedReplacedSheetContents = replaceBackReferences(out, updatedMergedContents);\n if (sheet) sheet.innerHTML = updatedReplacedSheetContents;\n return { classes: updatedOut, stylesheet: updatedSheetContents } as {\n classes: typeof updatedOut;\n stylesheet: string;\n };\n }\n return null;\n };\n\n if (coerced.flush) sheet = flushSheetContents(replacedSheetContents, options);\n // Need this TS cast to get solid code assist from the consumption-side\n return {\n classes: out as unknown,\n stylesheet: replacedSheetContents,\n updateSheet,\n } as {\n classes: O;\n stylesheet: string;\n updateSheet: typeof updateSheet;\n };\n}\n\nexport type CreateStylesArgs = Parameters<typeof createStyles>;\n"],
|
|
5
|
-
"mappings": "AACA;
|
|
5
|
+
"mappings": "AACA,OAAO,WAAW;AAElB,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAsB7B,SAAS,iBAAiB,GAAoB;AAC5C,SAAO,KAAK,KAAK,CAAC;AACpB;AAEA,SAAS,QAAQ,GAAoB;AACnC,SAAO,EAAE,YAAY,EAAE,WAAW,QAAQ;AAC5C;AAEA,SAAS,kBAAkB,MAAsB;AAC/C,SAAO,KAAK,QAAQ,YAAY,QAAM,IAAI,GAAG,YAAY,GAAG;AAC9D;AAEA,SAAS,eAAe,UAA8B;AACpD,SAAO,OAAO,QAAQ,QAAQ,EAAE;AAAA,IAC9B,CAAC,MAAM,CAAC,SAAS,MAAM,MAAM,GAAG,OAA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AAU,cAAc;AAElE,YAAM;AAAA,QACJ,SAAS;AAAA,QACT,aAAa;AAAA,QACb,oBAAoB;AAAA,MACtB,IAAI,iBAAiB,MAAM,OAAO,YAAY,GAAG,EAAE,OAAO,MAAM,GAAG,IAAI;AAEvE,YAAM,wBAAwB,GAAG,uBAAuB;AAExD,YAAM,+BAA+B,sBAAsB,KAAK,qBAAqB;AACrF,UAAI;AAAO,cAAM,YAAY;AAC7B,aAAO,EAAE,SAAS,YAAY,YAAY,qBAAqB;AAAA,IAIjE;AACA,WAAO;AAAA,EACT;AAEA,MAAI,QAAQ;AAAO,YAAQ,mBAAmB,uBAAuB,OAAO;AAE5E,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ;AAAA,EACF;AAKF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/generateClassName.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/generateClassName.ts"],
|
|
4
4
|
"sourcesContent": ["import numToAlpha from './numToAlpha';\n\nlet inc = Date.now();\n\nexport function setSeed(seed: number | null): void {\n if (seed === null) {\n inc = Date.now();\n return;\n }\n if (typeof seed !== 'number') throw Error('Unable to setSeed as provided seed was not a valid number');\n if (seed === Number.MAX_SAFE_INTEGER)\n throw Error('Unable to setSeed because the seed was already the maximum safe JavaScript number allowed');\n if (seed === Number.POSITIVE_INFINITY || seed === Number.NEGATIVE_INFINITY)\n throw new Error('Unable to setSeed. Positive or negative infinity is not allowed');\n if (seed < 0) throw new Error('Unable to setSeed. Seed must be a number >= 0');\n inc = seed;\n}\n\nconst numPairsRegex = /(\\d{1,2})/g;\n\nexport function getUniqueSuffix(): string {\n const numPairs: string[] = [];\n const incStr = inc.toString();\n let result = numPairsRegex.exec(incStr);\n while (result) {\n numPairs.push(result[0]);\n result = numPairsRegex.exec(incStr);\n }\n let out = '_';\n numPairs.forEach(pair => {\n const val = +pair;\n if (val > 25) {\n const [first, second] = pair.split('');\n out += `${numToAlpha(+first)}${numToAlpha(+second)}`;\n } else out += numToAlpha(val);\n });\n inc += 1;\n return out;\n}\n\nexport function generateClassName(c: string): string {\n return `${c}${getUniqueSuffix()}`;\n}\n"],
|
|
5
|
-
"mappings": "AAAA;
|
|
5
|
+
"mappings": "AAAA,OAAO,gBAAgB;AAEvB,IAAI,MAAM,KAAK,IAAI;AAEZ,SAAS,QAAQ,MAA2B;AACjD,MAAI,SAAS,MAAM;AACjB,UAAM,KAAK,IAAI;AACf;AAAA,EACF;AACA,MAAI,OAAO,SAAS;AAAU,UAAM,MAAM,2DAA2D;AACrG,MAAI,SAAS,OAAO;AAClB,UAAM,MAAM,2FAA2F;AACzG,MAAI,SAAS,OAAO,qBAAqB,SAAS,OAAO;AACvD,UAAM,IAAI,MAAM,iEAAiE;AACnF,MAAI,OAAO;AAAG,UAAM,IAAI,MAAM,+CAA+C;AAC7E,QAAM;AACR;AAEA,MAAM,gBAAgB;AAEf,SAAS,kBAA0B;AACxC,QAAM,WAAqB,CAAC;AAC5B,QAAM,SAAS,IAAI,SAAS;AAC5B,MAAI,SAAS,cAAc,KAAK,MAAM;AACtC,SAAO,QAAQ;AACb,aAAS,KAAK,OAAO,CAAC,CAAC;AACvB,aAAS,cAAc,KAAK,MAAM;AAAA,EACpC;AACA,MAAI,MAAM;AACV,WAAS,QAAQ,UAAQ;AACvB,UAAM,MAAM,CAAC;AACb,QAAI,MAAM,IAAI;AACZ,YAAM,CAAC,OAAO,MAAM,IAAI,KAAK,MAAM,EAAE;AACrC,aAAO,GAAG,WAAW,CAAC,KAAK,IAAI,WAAW,CAAC,MAAM;AAAA,IACnD;AAAO,aAAO,WAAW,GAAG;AAAA,EAC9B,CAAC;AACD,SAAO;AACP,SAAO;AACT;AAEO,SAAS,kBAAkB,GAAmB;AACnD,SAAO,GAAG,IAAI,gBAAgB;AAChC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/index.cjs.js
CHANGED
|
@@ -17,7 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
17
|
}
|
|
18
18
|
return to;
|
|
19
19
|
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
21
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
22
29
|
|
|
23
30
|
// src/index.ts
|
|
@@ -102,7 +109,10 @@ function formatCSSRuleName(rule) {
|
|
|
102
109
|
return rule.replace(/([A-Z])/g, (p1) => `-${p1.toLowerCase()}`);
|
|
103
110
|
}
|
|
104
111
|
function formatCSSRules(cssRules) {
|
|
105
|
-
return Object.entries(cssRules).reduce(
|
|
112
|
+
return Object.entries(cssRules).reduce(
|
|
113
|
+
(prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,
|
|
114
|
+
""
|
|
115
|
+
);
|
|
106
116
|
}
|
|
107
117
|
function execCreateStyles(rules, options, parentSelector, noGenerateClassName = false) {
|
|
108
118
|
const out = {};
|
|
@@ -121,7 +131,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
121
131
|
throw new Error("Unable to map @media query because rules / props are an invalid type");
|
|
122
132
|
guardCloseRuleWrite();
|
|
123
133
|
mediaQueriesBuffer += `${classNameOrCSSRule}{`;
|
|
124
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
134
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
135
|
+
classNameRules,
|
|
136
|
+
options,
|
|
137
|
+
parentSelector
|
|
138
|
+
);
|
|
125
139
|
mediaQueriesBuffer += regularOutput;
|
|
126
140
|
mediaQueriesBuffer += "}";
|
|
127
141
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
@@ -131,7 +145,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
131
145
|
guardCloseRuleWrite();
|
|
132
146
|
const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);
|
|
133
147
|
for (const selector of replaced.split(/,\s*/)) {
|
|
134
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
148
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
149
|
+
classNameRules,
|
|
150
|
+
options,
|
|
151
|
+
selector
|
|
152
|
+
);
|
|
135
153
|
sheetBuffer += regularOutput;
|
|
136
154
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
137
155
|
}
|
|
@@ -140,7 +158,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
140
158
|
const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);
|
|
141
159
|
out[classNameOrCSSRule] = generated;
|
|
142
160
|
const generatedSelector = `${noGenerateClassName ? "" : "."}${generated}`;
|
|
143
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
161
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
162
|
+
classNameRules,
|
|
163
|
+
options,
|
|
164
|
+
generatedSelector
|
|
165
|
+
);
|
|
144
166
|
sheetBuffer += regularOutput;
|
|
145
167
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
146
168
|
} else {
|
|
@@ -207,7 +229,12 @@ function coerceCreateStylesOptions(options) {
|
|
|
207
229
|
}
|
|
208
230
|
function rawStyles(rules, options) {
|
|
209
231
|
const coerced = coerceCreateStylesOptions(options);
|
|
210
|
-
const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(
|
|
232
|
+
const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(
|
|
233
|
+
rules,
|
|
234
|
+
coerced,
|
|
235
|
+
null,
|
|
236
|
+
true
|
|
237
|
+
);
|
|
211
238
|
const mergedContents = `${sheetContents}${mediaQueriesContents}`;
|
|
212
239
|
if (coerced.flush)
|
|
213
240
|
flushSheetContents(mergedContents, options);
|
package/index.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/index.ts", "../../src/createStyles.ts", "../../src/numToAlpha.ts", "../../src/generateClassName.ts", "../../src/plugins.ts"],
|
|
4
4
|
"sourcesContent": ["export type { CreateStylesArgs, CreateStylesOptions } from './createStyles';\nexport { default as createStyles, keyframes, rawStyles } from './createStyles';\nexport { setSeed } from './generateClassName';\nexport type { PosthookPlugin } from './plugins';\nexport { registerPosthook } from './plugins';\nexport type { SimpleStyleRules } from './types';\n", "import { Properties } from 'csstype';\nimport merge from 'deepmerge';\n\nimport { generateClassName } from './generateClassName';\nimport { getPosthooks } from './plugins';\nimport { SimpleStyleRules } from './types';\n\nexport type CreateStylesOptions = Partial<{\n /**\n * If true, automatically renders generated styles\n * to the DOM in an injected <style /> tag\n */\n flush: boolean;\n\n /**\n * If set, along with flush: true,\n * will render the injected <style /> after this element\n */\n insertAfter?: HTMLElement;\n /**\n * If set, along with flush: true,\n * will render the injects <style /> before this element\n */\n insertBefore?: HTMLElement;\n}>;\n\nfunction isNestedSelector(r: string): boolean {\n return /&/g.test(r);\n}\n\nfunction isMedia(r: string): boolean {\n return r.toLowerCase().startsWith('@media');\n}\n\nfunction formatCSSRuleName(rule: string): string {\n return rule.replace(/([A-Z])/g, p1 => `-${p1.toLowerCase()}`);\n}\n\nfunction formatCSSRules(cssRules: Properties): string {\n return Object.entries(cssRules).reduce(\n (prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,\n '',\n );\n}\n\nfunction execCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options: CreateStylesOptions,\n parentSelector: string | null,\n noGenerateClassName: boolean = false,\n): { classes: O; sheetBuffer: string; mediaQueriesBuffer: string } {\n const out = {} as O;\n let sheetBuffer = '';\n let mediaQueriesBuffer = '';\n const styleEntries = Object.entries(rules);\n let ruleWriteOpen = false;\n const guardCloseRuleWrite = () => {\n if (ruleWriteOpen) sheetBuffer += '}';\n ruleWriteOpen = false;\n };\n for (const [classNameOrCSSRule, classNameRules] of styleEntries) {\n // if the classNameRules is a string, we are dealing with a display: none; type rule\n if (isMedia(classNameOrCSSRule)) {\n if (typeof classNameRules !== 'object')\n throw new Error('Unable to map @media query because rules / props are an invalid type');\n guardCloseRuleWrite();\n mediaQueriesBuffer += `${classNameOrCSSRule}{`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n parentSelector,\n );\n mediaQueriesBuffer += regularOutput;\n mediaQueriesBuffer += '}';\n mediaQueriesBuffer += mediaQueriesOutput;\n } else if (isNestedSelector(classNameOrCSSRule)) {\n if (!parentSelector) throw new Error('Unable to generate nested rule because parentSelector is missing');\n guardCloseRuleWrite();\n // format of { '& > span': { display: 'none' } } (or further nesting)\n const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);\n for (const selector of replaced.split(/,\\s*/)) {\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n selector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n }\n } else if (!parentSelector && typeof classNameRules === 'object') {\n guardCloseRuleWrite();\n const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);\n (out as any)[classNameOrCSSRule] = generated;\n const generatedSelector = `${noGenerateClassName ? '' : '.'}${generated}`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n generatedSelector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n } else {\n if (!parentSelector) throw new Error('Unable to write css props because parent selector is null');\n if (!ruleWriteOpen) {\n sheetBuffer += `${parentSelector}{${formatCSSRules({ [classNameOrCSSRule]: classNameRules })}`;\n ruleWriteOpen = true;\n } else sheetBuffer += formatCSSRules({ [classNameOrCSSRule]: classNameRules });\n }\n }\n guardCloseRuleWrite();\n return {\n classes: out,\n sheetBuffer,\n mediaQueriesBuffer,\n };\n}\n\nfunction replaceBackReferences<O extends { [key: string]: string }>(out: O, sheetContents: string): string {\n let outputSheetContents = sheetContents;\n const toReplace: string[] = [];\n const toReplaceRegex = /\\$\\w([a-zA-Z0-9_-]+)?/gm;\n let matches = toReplaceRegex.exec(outputSheetContents);\n while (matches) {\n toReplace.push(matches[0].valueOf());\n matches = toReplaceRegex.exec(outputSheetContents);\n }\n for (const r of toReplace) {\n outputSheetContents = outputSheetContents.replace(r, `.${out[r.substring(1)]}`);\n }\n return getPosthooks().reduce((prev, hook) => hook(prev), outputSheetContents);\n}\n\nfunction createSheet(sheetContents: string) {\n if (typeof document === 'undefined') return null;\n if (typeof document?.head?.appendChild !== 'function' || typeof document?.createElement !== 'function') return null;\n const styleTag = document.createElement('style');\n styleTag.innerHTML = sheetContents;\n return styleTag;\n}\n\nfunction flushSheetContents(sheetContents: string, options?: CreateStylesOptions) {\n // In case we're in come weird test environment that doesn't support JSDom\n const styleTag = createSheet(sheetContents);\n if (styleTag) {\n if (options?.insertAfter && options?.insertBefore) {\n throw new Error('Both insertAfter and insertBefore were provided. Please choose only one.');\n }\n if (options?.insertAfter?.after) options.insertAfter.after(styleTag as Node);\n else if (options?.insertBefore?.before) options.insertBefore.before(styleTag as Node);\n else document.head.appendChild(styleTag);\n }\n return styleTag;\n}\n\nfunction coerceCreateStylesOptions(options?: CreateStylesOptions): CreateStylesOptions {\n return {\n flush: options && typeof options.flush === 'boolean' ? options.flush : true,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function rawStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [key in K]: string }>(\n rules: T,\n options?: Partial<CreateStylesOptions>,\n) {\n const coerced = coerceCreateStylesOptions(options);\n const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(\n rules,\n coerced,\n null,\n true,\n );\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n if (coerced.flush) flushSheetContents(mergedContents, options);\n return mergedContents;\n}\n\nexport function keyframes<T extends { [increment: string]: Properties }>(\n frames: T,\n options?: CreateStylesOptions,\n): [string, string] {\n const coerced = coerceCreateStylesOptions(options);\n const keyframeName = generateClassName('keyframes_');\n const { sheetBuffer: keyframesContents } = execCreateStyles(frames, coerced, null, true);\n const sheetContents = `@keyframes ${keyframeName}{${keyframesContents}}`;\n if (coerced.flush) flushSheetContents(sheetContents);\n return [keyframeName, sheetContents];\n}\n\nexport default function createStyles<\n T extends SimpleStyleRules,\n K extends keyof T,\n O extends { [classKey in K]: string },\n>(rules: T, options?: Partial<CreateStylesOptions>) {\n const coerced = coerceCreateStylesOptions(options);\n const {\n classes: out,\n sheetBuffer: sheetContents,\n mediaQueriesBuffer: mediaQueriesContents,\n } = execCreateStyles(rules, coerced, null);\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n const replacedSheetContents = replaceBackReferences(out, mergedContents);\n\n let sheet: ReturnType<typeof flushSheetContents> = null;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const updateSheet = <T2 extends SimpleStyleRules, K2 extends keyof T2, O2 extends { [classKey in K2]: string }>(\n updatedRules: Partial<T2>,\n ) => {\n if (((options?.flush && sheet) || !options?.flush) && updatedRules) {\n // We prefer the first set, and then we shallow merge\n const {\n classes: updatedOut,\n sheetBuffer: updatedSheetContents,\n mediaQueriesBuffer: updatedMediaQueriesContents,\n } = execCreateStyles(merge(rules, updatedRules), { flush: false }, null);\n\n const updatedMergedContents = `${updatedSheetContents}${updatedMediaQueriesContents}`;\n\n const updatedReplacedSheetContents = replaceBackReferences(out, updatedMergedContents);\n if (sheet) sheet.innerHTML = updatedReplacedSheetContents;\n return { classes: updatedOut, stylesheet: updatedSheetContents } as {\n classes: typeof updatedOut;\n stylesheet: string;\n };\n }\n return null;\n };\n\n if (coerced.flush) sheet = flushSheetContents(replacedSheetContents, options);\n // Need this TS cast to get solid code assist from the consumption-side\n return {\n classes: out as unknown,\n stylesheet: replacedSheetContents,\n updateSheet,\n } as {\n classes: O;\n stylesheet: string;\n updateSheet: typeof updateSheet;\n };\n}\n\nexport type CreateStylesArgs = Parameters<typeof createStyles>;\n", "const alphas = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\nexport default function numToAlpha(num: number): string {\n return alphas[num];\n}\n", "import numToAlpha from './numToAlpha';\n\nlet inc = Date.now();\n\nexport function setSeed(seed: number | null): void {\n if (seed === null) {\n inc = Date.now();\n return;\n }\n if (typeof seed !== 'number') throw Error('Unable to setSeed as provided seed was not a valid number');\n if (seed === Number.MAX_SAFE_INTEGER)\n throw Error('Unable to setSeed because the seed was already the maximum safe JavaScript number allowed');\n if (seed === Number.POSITIVE_INFINITY || seed === Number.NEGATIVE_INFINITY)\n throw new Error('Unable to setSeed. Positive or negative infinity is not allowed');\n if (seed < 0) throw new Error('Unable to setSeed. Seed must be a number >= 0');\n inc = seed;\n}\n\nconst numPairsRegex = /(\\d{1,2})/g;\n\nexport function getUniqueSuffix(): string {\n const numPairs: string[] = [];\n const incStr = inc.toString();\n let result = numPairsRegex.exec(incStr);\n while (result) {\n numPairs.push(result[0]);\n result = numPairsRegex.exec(incStr);\n }\n let out = '_';\n numPairs.forEach(pair => {\n const val = +pair;\n if (val > 25) {\n const [first, second] = pair.split('');\n out += `${numToAlpha(+first)}${numToAlpha(+second)}`;\n } else out += numToAlpha(val);\n });\n inc += 1;\n return out;\n}\n\nexport function generateClassName(c: string): string {\n return `${c}${getUniqueSuffix()}`;\n}\n", "export type PosthookPlugin = (sheetContents: string) => string;\n\nconst posthooks: PosthookPlugin[] = [];\n\nexport function getPosthooks(): PosthookPlugin[] {\n return posthooks;\n}\n\nexport function registerPosthook(posthook: PosthookPlugin) {\n posthooks.push(posthook);\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": []
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,uBAAkB;;;ACDlB,IAAM,SAAS,6BAA6B,MAAM,EAAE;AAErC,SAAR,WAA4B,KAAqB;AACtD,SAAO,OAAO,GAAG;AACnB;;;ACFA,IAAI,MAAM,KAAK,IAAI;AAEZ,SAAS,QAAQ,MAA2B;AACjD,MAAI,SAAS,MAAM;AACjB,UAAM,KAAK,IAAI;AACf;AAAA,EACF;AACA,MAAI,OAAO,SAAS;AAAU,UAAM,MAAM,2DAA2D;AACrG,MAAI,SAAS,OAAO;AAClB,UAAM,MAAM,2FAA2F;AACzG,MAAI,SAAS,OAAO,qBAAqB,SAAS,OAAO;AACvD,UAAM,IAAI,MAAM,iEAAiE;AACnF,MAAI,OAAO;AAAG,UAAM,IAAI,MAAM,+CAA+C;AAC7E,QAAM;AACR;AAEA,IAAM,gBAAgB;AAEf,SAAS,kBAA0B;AACxC,QAAM,WAAqB,CAAC;AAC5B,QAAM,SAAS,IAAI,SAAS;AAC5B,MAAI,SAAS,cAAc,KAAK,MAAM;AACtC,SAAO,QAAQ;AACb,aAAS,KAAK,OAAO,CAAC,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AAO;AAAA,EACT;AAEA,MAAI,QAAQ;AAAO,YAAQ,mBAAmB,uBAAuB,OAAO;AAE5E,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ;AAAA,EACF;AAKF;",
|
|
6
|
+
"names": ["merge"]
|
|
7
7
|
}
|
package/numToAlpha.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/numToAlpha.ts"],
|
|
4
4
|
"sourcesContent": ["const alphas = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\nexport default function numToAlpha(num: number): string {\n return alphas[num];\n}\n"],
|
|
5
|
-
"mappings": "AAAA,MAAM,SAAS,6BAA6B,MAAM,EAAE;AAErC,
|
|
5
|
+
"mappings": "AAAA,MAAM,SAAS,6BAA6B,MAAM,EAAE;AAErC,SAAR,WAA4B,KAAqB;AACtD,SAAO,OAAO,GAAG;AACnB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "simplestyle-js",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.3-beta.1",
|
|
4
4
|
"description": "An incredibly straightforward and simple CSS-in-JS solution with zero runtime dependencies, and out-of-the-box TypeScript support",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/benduran/simplestyle.git"
|
|
8
8
|
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "run-s clean build:package copy",
|
|
11
|
+
"build:package": "package-bundler -c -r -t ./tsconfig.build.json",
|
|
12
|
+
"clean": "rm -rf ./dist",
|
|
13
|
+
"copy": "cp ./README.md ./dist && cp ./LICENSE ./dist",
|
|
14
|
+
"coveralls": "run-s test:coverage coverage:pipe",
|
|
15
|
+
"coverage:pipe": "cat ./coverage/lcov.info | coveralls",
|
|
16
|
+
"lint": "eslint './src/**/*.ts'",
|
|
17
|
+
"lint:fixall": "eslint './src/**/*.ts' --fix",
|
|
18
|
+
"setup": "npm install -g pnpm@$(cat pnpm-version) && pnpm install",
|
|
19
|
+
"test:coverage": "jest --coverage",
|
|
20
|
+
"test": "jest --env jsdom",
|
|
21
|
+
"test:watch": "jest --watch --env jsdom",
|
|
22
|
+
"test:debug": "node --inspect-brk ./node_modules/.bin/jest",
|
|
23
|
+
"git-pre-commit": "pnpm lint && pnpm test"
|
|
24
|
+
},
|
|
9
25
|
"keywords": [
|
|
10
26
|
"CSS-in-JS",
|
|
11
27
|
"CSS",
|
|
@@ -16,57 +32,42 @@
|
|
|
16
32
|
"author": "Benjamin Duran <stratodyne@gmail.com>",
|
|
17
33
|
"license": "MIT",
|
|
18
34
|
"devDependencies": {
|
|
19
|
-
"@better-builds/package-bundler": "^1.
|
|
20
|
-
"@jest/types": "^
|
|
21
|
-
"@testing-library/react": "^
|
|
35
|
+
"@better-builds/package-bundler": "^1.5.0",
|
|
36
|
+
"@jest/types": "^29.5.0",
|
|
37
|
+
"@testing-library/react": "^14.0.0",
|
|
22
38
|
"@types/autoprefixer": "^10.2.0",
|
|
23
|
-
"@types/jest": "^
|
|
24
|
-
"@types/jsdom": "^
|
|
25
|
-
"@types/react": "^18.0.
|
|
26
|
-
"@types/react-dom": "^18.0.
|
|
27
|
-
"@
|
|
28
|
-
"autoprefixer": "^10.4.
|
|
29
|
-
"babel-jest": "^
|
|
39
|
+
"@types/jest": "^29.5.0",
|
|
40
|
+
"@types/jsdom": "^21.1.1",
|
|
41
|
+
"@types/react": "^18.0.35",
|
|
42
|
+
"@types/react-dom": "^18.0.11",
|
|
43
|
+
"@vercel/git-hooks": "^1.0.0",
|
|
44
|
+
"autoprefixer": "^10.4.14",
|
|
45
|
+
"babel-jest": "^29.5.0",
|
|
30
46
|
"coveralls": "^3.1.1",
|
|
31
|
-
"eslint-config-react-yas": "^
|
|
32
|
-
"jest": "^
|
|
33
|
-
"jest-environment-jsdom": "^
|
|
34
|
-
"jsdom": "^
|
|
47
|
+
"eslint-config-react-yas": "^4.0.0",
|
|
48
|
+
"jest": "^29.5.0",
|
|
49
|
+
"jest-environment-jsdom": "^29.5.0",
|
|
50
|
+
"jsdom": "^21.1.1",
|
|
35
51
|
"npm-run-all": "^4.1.5",
|
|
36
|
-
"postcss": "^8.4.
|
|
52
|
+
"postcss": "^8.4.21",
|
|
37
53
|
"react": "^18.2.0",
|
|
38
54
|
"react-dom": "^18.2.0",
|
|
39
|
-
"ts-jest": "^
|
|
40
|
-
"ts-node": "^10.
|
|
41
|
-
"typescript": "^
|
|
55
|
+
"ts-jest": "^29.1.0",
|
|
56
|
+
"ts-node": "^10.9.1",
|
|
57
|
+
"typescript": "^5.0.4"
|
|
42
58
|
},
|
|
43
59
|
"dependencies": {
|
|
44
|
-
"csstype": "^3.1.
|
|
45
|
-
"deepmerge": "^4.
|
|
60
|
+
"csstype": "^3.1.2",
|
|
61
|
+
"deepmerge": "^4.3.1"
|
|
46
62
|
},
|
|
47
63
|
"peerDependencies": {
|
|
48
64
|
"react": ">=16.8"
|
|
49
65
|
},
|
|
50
|
-
"
|
|
51
|
-
"
|
|
66
|
+
"engines": {
|
|
67
|
+
"node": "^18.15.0",
|
|
68
|
+
"npm": "^9.2.0"
|
|
52
69
|
},
|
|
53
70
|
"main": "./index.cjs.js",
|
|
54
71
|
"module": "./index.js",
|
|
55
|
-
"types": "./index.d.ts"
|
|
56
|
-
"scripts": {
|
|
57
|
-
"build": "run-s clean build:package copy",
|
|
58
|
-
"build:package": "package-bundler -c -r -t ./tsconfig.build.json",
|
|
59
|
-
"clean": "rm -rf ./dist",
|
|
60
|
-
"copy": "cp ./README.md ./dist && cp ./LICENSE ./dist",
|
|
61
|
-
"coveralls": "run-s test:coverage coverage:pipe",
|
|
62
|
-
"coverage:pipe": "cat ./coverage/lcov.info | coveralls",
|
|
63
|
-
"lint": "eslint './src/**/*.ts'",
|
|
64
|
-
"lint:fixall": "eslint './src/**/*.ts' --fix",
|
|
65
|
-
"setup": "npm install -g pnpm@$(cat pnpm-version) && pnpm install",
|
|
66
|
-
"test:coverage": "jest --coverage",
|
|
67
|
-
"test": "jest",
|
|
68
|
-
"test:watch": "jest --watch",
|
|
69
|
-
"test:debug": "node --inspect-brk ./node_modules/.bin/jest",
|
|
70
|
-
"git-pre-commit": "pnpm lint && pnpm test"
|
|
71
|
-
}
|
|
72
|
+
"types": "./index.d.ts"
|
|
72
73
|
}
|
package/plugins.d.ts
CHANGED
package/plugins.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plugins.ts"],
|
|
4
4
|
"sourcesContent": ["export type PosthookPlugin = (sheetContents: string) => string;\n\nconst posthooks: PosthookPlugin[] = [];\n\nexport function getPosthooks(): PosthookPlugin[] {\n return posthooks;\n}\n\nexport function registerPosthook(posthook: PosthookPlugin) {\n posthooks.push(posthook);\n}\n"],
|
|
5
|
-
"mappings": "AAEA,MAAM,YAA8B,CAAC;AAE9B,
|
|
5
|
+
"mappings": "AAEA,MAAM,YAA8B,CAAC;AAE9B,SAAS,eAAiC;AAC/C,SAAO;AACT;AAEO,SAAS,iBAAiB,UAA0B;AACzD,YAAU,KAAK,QAAQ;AACzB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/react/index.cjs.js
CHANGED
|
@@ -17,7 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
17
|
}
|
|
18
18
|
return to;
|
|
19
19
|
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
21
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
22
29
|
|
|
23
30
|
// src/react/index.ts
|
|
@@ -27,8 +34,8 @@ __export(react_exports, {
|
|
|
27
34
|
});
|
|
28
35
|
module.exports = __toCommonJS(react_exports);
|
|
29
36
|
|
|
30
|
-
// src/react/useCreateStyles.
|
|
31
|
-
var import_react = require("react");
|
|
37
|
+
// src/react/useCreateStyles.tsx
|
|
38
|
+
var import_react = __toESM(require("react"));
|
|
32
39
|
|
|
33
40
|
// src/createStyles.ts
|
|
34
41
|
var import_deepmerge = __toESM(require("deepmerge"));
|
|
@@ -83,7 +90,10 @@ function formatCSSRuleName(rule) {
|
|
|
83
90
|
return rule.replace(/([A-Z])/g, (p1) => `-${p1.toLowerCase()}`);
|
|
84
91
|
}
|
|
85
92
|
function formatCSSRules(cssRules) {
|
|
86
|
-
return Object.entries(cssRules).reduce(
|
|
93
|
+
return Object.entries(cssRules).reduce(
|
|
94
|
+
(prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,
|
|
95
|
+
""
|
|
96
|
+
);
|
|
87
97
|
}
|
|
88
98
|
function execCreateStyles(rules, options, parentSelector, noGenerateClassName = false) {
|
|
89
99
|
const out = {};
|
|
@@ -102,7 +112,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
102
112
|
throw new Error("Unable to map @media query because rules / props are an invalid type");
|
|
103
113
|
guardCloseRuleWrite();
|
|
104
114
|
mediaQueriesBuffer += `${classNameOrCSSRule}{`;
|
|
105
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
115
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
116
|
+
classNameRules,
|
|
117
|
+
options,
|
|
118
|
+
parentSelector
|
|
119
|
+
);
|
|
106
120
|
mediaQueriesBuffer += regularOutput;
|
|
107
121
|
mediaQueriesBuffer += "}";
|
|
108
122
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
@@ -112,7 +126,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
112
126
|
guardCloseRuleWrite();
|
|
113
127
|
const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);
|
|
114
128
|
for (const selector of replaced.split(/,\s*/)) {
|
|
115
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
129
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
130
|
+
classNameRules,
|
|
131
|
+
options,
|
|
132
|
+
selector
|
|
133
|
+
);
|
|
116
134
|
sheetBuffer += regularOutput;
|
|
117
135
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
118
136
|
}
|
|
@@ -121,7 +139,11 @@ function execCreateStyles(rules, options, parentSelector, noGenerateClassName =
|
|
|
121
139
|
const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);
|
|
122
140
|
out[classNameOrCSSRule] = generated;
|
|
123
141
|
const generatedSelector = `${noGenerateClassName ? "" : "."}${generated}`;
|
|
124
|
-
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
142
|
+
const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
|
|
143
|
+
classNameRules,
|
|
144
|
+
options,
|
|
145
|
+
generatedSelector
|
|
146
|
+
);
|
|
125
147
|
sheetBuffer += regularOutput;
|
|
126
148
|
mediaQueriesBuffer += mediaQueriesOutput;
|
|
127
149
|
} else {
|
|
@@ -240,36 +262,48 @@ function deepEqual(o1, o2) {
|
|
|
240
262
|
}, true);
|
|
241
263
|
}
|
|
242
264
|
|
|
243
|
-
// src/react/useCreateStyles.
|
|
265
|
+
// src/react/useCreateStyles.tsx
|
|
244
266
|
function useCreateStyles(rules, options) {
|
|
245
|
-
const [cachedRules, setCachedRules] =
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const
|
|
250
|
-
|
|
267
|
+
const [cachedRules, setCachedRules] = import_react.default.useState(() => rules);
|
|
268
|
+
const [{ classes, stylesheet, updateSheet }, setCreateStyles] = import_react.default.useState(
|
|
269
|
+
() => createStyles(rules, { ...options, flush: false })
|
|
270
|
+
);
|
|
271
|
+
const didFirstWriteRef = import_react.default.useRef(false);
|
|
272
|
+
const styleTagRef = import_react.default.useRef(typeof document !== "undefined" ? document.createElement("style") : null);
|
|
273
|
+
const rulesRef = import_react.default.useRef(rules);
|
|
274
|
+
const cachedRulesRef = import_react.default.useRef(cachedRules);
|
|
275
|
+
rulesRef.current = rules;
|
|
276
|
+
cachedRulesRef.current = cachedRules;
|
|
277
|
+
const rulesChanged = !deepEqual(rulesRef.current, cachedRulesRef.current);
|
|
278
|
+
const styleTag = import_react.default.useMemo(() => {
|
|
279
|
+
if (styleTagRef.current)
|
|
280
|
+
return null;
|
|
281
|
+
return /* @__PURE__ */ import_react.default.createElement("style", { dangerouslySetInnerHTML: { __html: stylesheet } });
|
|
282
|
+
}, [stylesheet]);
|
|
283
|
+
import_react.default.useEffect(() => {
|
|
251
284
|
if (!styleTagRef.current)
|
|
252
285
|
return;
|
|
253
286
|
const { current: s } = styleTagRef;
|
|
254
287
|
document.head.appendChild(s);
|
|
255
288
|
return () => s.remove();
|
|
256
289
|
}, []);
|
|
257
|
-
|
|
290
|
+
import_react.default.useEffect(() => {
|
|
258
291
|
if (!styleTagRef.current)
|
|
259
292
|
return;
|
|
260
293
|
if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {
|
|
261
294
|
didFirstWriteRef.current = true;
|
|
262
295
|
styleTagRef.current.innerHTML = stylesheet;
|
|
263
296
|
return;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
|
|
297
|
+
}
|
|
298
|
+
if (rulesChanged) {
|
|
299
|
+
setCachedRules(rulesRef.current);
|
|
300
|
+
const updated = updateSheet(rulesRef.current);
|
|
267
301
|
if (updated == null ? void 0 : updated.stylesheet) {
|
|
268
302
|
styleTagRef.current.innerHTML = updated.stylesheet;
|
|
269
303
|
setCreateStyles({ ...updated, updateSheet });
|
|
270
304
|
}
|
|
271
305
|
}
|
|
272
|
-
}, [
|
|
273
|
-
return classes;
|
|
306
|
+
}, [rulesChanged, stylesheet, updateSheet]);
|
|
307
|
+
return import_react.default.useMemo(() => ({ classes, styleTag }), [classes, styleTag]);
|
|
274
308
|
}
|
|
275
309
|
//# sourceMappingURL=index.js.map
|
package/react/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/react/index.ts", "../../../src/react/useCreateStyles.
|
|
4
|
-
"sourcesContent": ["export * from './useCreateStyles';\n", "import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport createStyles, { CreateStylesOptions } from '../createStyles';\nimport { SimpleStyleRules } from '../types';\nimport { deepEqual } from '../util';\n\nexport function useCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options?: Partial<Omit<CreateStylesOptions, 'flush'>>,\n) {\n const [cachedRules, setCachedRules] = useState(() => rules);\n const cachedOptions = useMemo(() => ({ ...options } as Partial<Omit<CreateStylesOptions, 'flush'>>), [options]);\n const didFirstWriteRef = useRef(false);\n const styleTagRef = useRef(typeof document !== 'undefined' ? document.createElement('style') : null);\n\n const [{ classes, stylesheet, updateSheet }, setCreateStyles] = useState(() =>\n createStyles<T, K, O>(rules, { ...cachedOptions, flush: false }),\n );\n\n useEffect(() => {\n if (!styleTagRef.current) return;\n const { current: s } = styleTagRef;\n document.head.appendChild(s);\n return () => s.remove();\n }, []);\n useEffect(() => {\n if (!styleTagRef.current) return;\n if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {\n didFirstWriteRef.current = true;\n styleTagRef.current.innerHTML = stylesheet;\n return;\n } else if (!deepEqual(rules, cachedRules)) {\n setCachedRules(rules);\n const updated = updateSheet(rules);\n if (updated?.stylesheet) {\n styleTagRef.current.innerHTML = updated.stylesheet;\n setCreateStyles({ ...updated, updateSheet } as any);\n }\n }\n }, [cachedRules, rules, stylesheet, updateSheet]);\n return classes;\n}\n", "import { Properties } from 'csstype';\nimport merge from 'deepmerge';\n\nimport { generateClassName } from './generateClassName';\nimport { getPosthooks } from './plugins';\nimport { SimpleStyleRules } from './types';\n\nexport type CreateStylesOptions = Partial<{\n /**\n * If true, automatically renders generated styles\n * to the DOM in an injected <style /> tag\n */\n flush: boolean;\n\n /**\n * If set, along with flush: true,\n * will render the injected <style /> after this element\n */\n insertAfter?: HTMLElement;\n /**\n * If set, along with flush: true,\n * will render the injects <style /> before this element\n */\n insertBefore?: HTMLElement;\n}>;\n\nfunction isNestedSelector(r: string): boolean {\n return /&/g.test(r);\n}\n\nfunction isMedia(r: string): boolean {\n return r.toLowerCase().startsWith('@media');\n}\n\nfunction formatCSSRuleName(rule: string): string {\n return rule.replace(/([A-Z])/g, p1 => `-${p1.toLowerCase()}`);\n}\n\nfunction formatCSSRules(cssRules: Properties): string {\n return Object.entries(cssRules).reduce(\n (prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,\n '',\n );\n}\n\nfunction execCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options: CreateStylesOptions,\n parentSelector: string | null,\n noGenerateClassName: boolean = false,\n): { classes: O; sheetBuffer: string; mediaQueriesBuffer: string } {\n const out = {} as O;\n let sheetBuffer = '';\n let mediaQueriesBuffer = '';\n const styleEntries = Object.entries(rules);\n let ruleWriteOpen = false;\n const guardCloseRuleWrite = () => {\n if (ruleWriteOpen) sheetBuffer += '}';\n ruleWriteOpen = false;\n };\n for (const [classNameOrCSSRule, classNameRules] of styleEntries) {\n // if the classNameRules is a string, we are dealing with a display: none; type rule\n if (isMedia(classNameOrCSSRule)) {\n if (typeof classNameRules !== 'object')\n throw new Error('Unable to map @media query because rules / props are an invalid type');\n guardCloseRuleWrite();\n mediaQueriesBuffer += `${classNameOrCSSRule}{`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n parentSelector,\n );\n mediaQueriesBuffer += regularOutput;\n mediaQueriesBuffer += '}';\n mediaQueriesBuffer += mediaQueriesOutput;\n } else if (isNestedSelector(classNameOrCSSRule)) {\n if (!parentSelector) throw new Error('Unable to generate nested rule because parentSelector is missing');\n guardCloseRuleWrite();\n // format of { '& > span': { display: 'none' } } (or further nesting)\n const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);\n for (const selector of replaced.split(/,\\s*/)) {\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n selector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n }\n } else if (!parentSelector && typeof classNameRules === 'object') {\n guardCloseRuleWrite();\n const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);\n (out as any)[classNameOrCSSRule] = generated;\n const generatedSelector = `${noGenerateClassName ? '' : '.'}${generated}`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n generatedSelector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n } else {\n if (!parentSelector) throw new Error('Unable to write css props because parent selector is null');\n if (!ruleWriteOpen) {\n sheetBuffer += `${parentSelector}{${formatCSSRules({ [classNameOrCSSRule]: classNameRules })}`;\n ruleWriteOpen = true;\n } else sheetBuffer += formatCSSRules({ [classNameOrCSSRule]: classNameRules });\n }\n }\n guardCloseRuleWrite();\n return {\n classes: out,\n sheetBuffer,\n mediaQueriesBuffer,\n };\n}\n\nfunction replaceBackReferences<O extends { [key: string]: string }>(out: O, sheetContents: string): string {\n let outputSheetContents = sheetContents;\n const toReplace: string[] = [];\n const toReplaceRegex = /\\$\\w([a-zA-Z0-9_-]+)?/gm;\n let matches = toReplaceRegex.exec(outputSheetContents);\n while (matches) {\n toReplace.push(matches[0].valueOf());\n matches = toReplaceRegex.exec(outputSheetContents);\n }\n for (const r of toReplace) {\n outputSheetContents = outputSheetContents.replace(r, `.${out[r.substring(1)]}`);\n }\n return getPosthooks().reduce((prev, hook) => hook(prev), outputSheetContents);\n}\n\nfunction createSheet(sheetContents: string) {\n if (typeof document === 'undefined') return null;\n if (typeof document?.head?.appendChild !== 'function' || typeof document?.createElement !== 'function') return null;\n const styleTag = document.createElement('style');\n styleTag.innerHTML = sheetContents;\n return styleTag;\n}\n\nfunction flushSheetContents(sheetContents: string, options?: CreateStylesOptions) {\n // In case we're in come weird test environment that doesn't support JSDom\n const styleTag = createSheet(sheetContents);\n if (styleTag) {\n if (options?.insertAfter && options?.insertBefore) {\n throw new Error('Both insertAfter and insertBefore were provided. Please choose only one.');\n }\n if (options?.insertAfter?.after) options.insertAfter.after(styleTag as Node);\n else if (options?.insertBefore?.before) options.insertBefore.before(styleTag as Node);\n else document.head.appendChild(styleTag);\n }\n return styleTag;\n}\n\nfunction coerceCreateStylesOptions(options?: CreateStylesOptions): CreateStylesOptions {\n return {\n flush: options && typeof options.flush === 'boolean' ? options.flush : true,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function rawStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [key in K]: string }>(\n rules: T,\n options?: Partial<CreateStylesOptions>,\n) {\n const coerced = coerceCreateStylesOptions(options);\n const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(\n rules,\n coerced,\n null,\n true,\n );\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n if (coerced.flush) flushSheetContents(mergedContents, options);\n return mergedContents;\n}\n\nexport function keyframes<T extends { [increment: string]: Properties }>(\n frames: T,\n options?: CreateStylesOptions,\n): [string, string] {\n const coerced = coerceCreateStylesOptions(options);\n const keyframeName = generateClassName('keyframes_');\n const { sheetBuffer: keyframesContents } = execCreateStyles(frames, coerced, null, true);\n const sheetContents = `@keyframes ${keyframeName}{${keyframesContents}}`;\n if (coerced.flush) flushSheetContents(sheetContents);\n return [keyframeName, sheetContents];\n}\n\nexport default function createStyles<\n T extends SimpleStyleRules,\n K extends keyof T,\n O extends { [classKey in K]: string },\n>(rules: T, options?: Partial<CreateStylesOptions>) {\n const coerced = coerceCreateStylesOptions(options);\n const {\n classes: out,\n sheetBuffer: sheetContents,\n mediaQueriesBuffer: mediaQueriesContents,\n } = execCreateStyles(rules, coerced, null);\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n const replacedSheetContents = replaceBackReferences(out, mergedContents);\n\n let sheet: ReturnType<typeof flushSheetContents> = null;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const updateSheet = <T2 extends SimpleStyleRules, K2 extends keyof T2, O2 extends { [classKey in K2]: string }>(\n updatedRules: Partial<T2>,\n ) => {\n if (((options?.flush && sheet) || !options?.flush) && updatedRules) {\n // We prefer the first set, and then we shallow merge\n const {\n classes: updatedOut,\n sheetBuffer: updatedSheetContents,\n mediaQueriesBuffer: updatedMediaQueriesContents,\n } = execCreateStyles(merge(rules, updatedRules), { flush: false }, null);\n\n const updatedMergedContents = `${updatedSheetContents}${updatedMediaQueriesContents}`;\n\n const updatedReplacedSheetContents = replaceBackReferences(out, updatedMergedContents);\n if (sheet) sheet.innerHTML = updatedReplacedSheetContents;\n return { classes: updatedOut, stylesheet: updatedSheetContents } as {\n classes: typeof updatedOut;\n stylesheet: string;\n };\n }\n return null;\n };\n\n if (coerced.flush) sheet = flushSheetContents(replacedSheetContents, options);\n // Need this TS cast to get solid code assist from the consumption-side\n return {\n classes: out as unknown,\n stylesheet: replacedSheetContents,\n updateSheet,\n } as {\n classes: O;\n stylesheet: string;\n updateSheet: typeof updateSheet;\n };\n}\n\nexport type CreateStylesArgs = Parameters<typeof createStyles>;\n", "const alphas = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\nexport default function numToAlpha(num: number): string {\n return alphas[num];\n}\n", "import numToAlpha from './numToAlpha';\n\nlet inc = Date.now();\n\nexport function setSeed(seed: number | null): void {\n if (seed === null) {\n inc = Date.now();\n return;\n }\n if (typeof seed !== 'number') throw Error('Unable to setSeed as provided seed was not a valid number');\n if (seed === Number.MAX_SAFE_INTEGER)\n throw Error('Unable to setSeed because the seed was already the maximum safe JavaScript number allowed');\n if (seed === Number.POSITIVE_INFINITY || seed === Number.NEGATIVE_INFINITY)\n throw new Error('Unable to setSeed. Positive or negative infinity is not allowed');\n if (seed < 0) throw new Error('Unable to setSeed. Seed must be a number >= 0');\n inc = seed;\n}\n\nconst numPairsRegex = /(\\d{1,2})/g;\n\nexport function getUniqueSuffix(): string {\n const numPairs: string[] = [];\n const incStr = inc.toString();\n let result = numPairsRegex.exec(incStr);\n while (result) {\n numPairs.push(result[0]);\n result = numPairsRegex.exec(incStr);\n }\n let out = '_';\n numPairs.forEach(pair => {\n const val = +pair;\n if (val > 25) {\n const [first, second] = pair.split('');\n out += `${numToAlpha(+first)}${numToAlpha(+second)}`;\n } else out += numToAlpha(val);\n });\n inc += 1;\n return out;\n}\n\nexport function generateClassName(c: string): string {\n return `${c}${getUniqueSuffix()}`;\n}\n", "export type PosthookPlugin = (sheetContents: string) => string;\n\nconst posthooks: PosthookPlugin[] = [];\n\nexport function getPosthooks(): PosthookPlugin[] {\n return posthooks;\n}\n\nexport function registerPosthook(posthook: PosthookPlugin) {\n posthooks.push(posthook);\n}\n", "export function deepEqual<\n O1 extends Record<string | number | symbol, any>,\n O2 extends Record<string | number | symbol, any>,\n>(o1: O1, o2: O2): boolean {\n // We'll sort the keys, just in case the user kept things the same but the object is all wonky, order-wise\n const o1Keys = Object.keys(o1).sort();\n const o2Keys = Object.keys(o2).sort();\n if (o1Keys.length !== o2Keys.length) return false;\n if (o1Keys.some((key, i) => o2Keys[i] !== key)) return false;\n // Okay, the keys SHOULD be the same\n // so we need to test their values, recursively, to verify equality\n return o1Keys.reduce<boolean>((prev, key) => {\n if (!prev) return prev; // we've already failed equality checks here\n if (!(key in o2)) return false;\n if (typeof o1[key] !== 'object') {\n return prev && o1[key] === o2[key];\n }\n return prev && deepEqual(o1[key], o2[key]);\n }, true);\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": []
|
|
3
|
+
"sources": ["../../../src/react/index.ts", "../../../src/react/useCreateStyles.tsx", "../../../src/createStyles.ts", "../../../src/numToAlpha.ts", "../../../src/generateClassName.ts", "../../../src/plugins.ts", "../../../src/util/deepEqual.ts"],
|
|
4
|
+
"sourcesContent": ["export * from './useCreateStyles';\n", "import React from 'react';\n\nimport createStyles, { CreateStylesOptions } from '../createStyles';\nimport { SimpleStyleRules } from '../types';\nimport { deepEqual } from '../util';\n\nexport function useCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options?: Partial<Omit<CreateStylesOptions, 'flush'>>,\n) {\n // state\n const [cachedRules, setCachedRules] = React.useState(() => rules);\n const [{ classes, stylesheet, updateSheet }, setCreateStyles] = React.useState(() =>\n createStyles<T, K, O>(rules, { ...options, flush: false }),\n );\n\n // refs\n const didFirstWriteRef = React.useRef(false);\n const styleTagRef = React.useRef(typeof document !== 'undefined' ? document.createElement('style') : null);\n const rulesRef = React.useRef(rules);\n const cachedRulesRef = React.useRef(cachedRules);\n\n // we leverage refs for these objects, as their referential equality is likely always changing.\n // this prevent unnecessary executions of the effects below\n rulesRef.current = rules;\n cachedRulesRef.current = cachedRules;\n\n // local variables\n const rulesChanged = !deepEqual(rulesRef.current, cachedRulesRef.current);\n\n // memos\n const styleTag = React.useMemo(() => {\n if (styleTagRef.current) return null;\n\n return <style dangerouslySetInnerHTML={{ __html: stylesheet }} />;\n }, [stylesheet]);\n\n // effects\n React.useEffect(() => {\n if (!styleTagRef.current) return;\n\n const { current: s } = styleTagRef;\n document.head.appendChild(s);\n return () => s.remove();\n }, []);\n React.useEffect(() => {\n if (!styleTagRef.current) return;\n\n if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {\n didFirstWriteRef.current = true;\n styleTagRef.current.innerHTML = stylesheet;\n return;\n }\n if (rulesChanged) {\n setCachedRules(rulesRef.current);\n const updated = updateSheet(rulesRef.current);\n if (updated?.stylesheet) {\n styleTagRef.current.innerHTML = updated.stylesheet;\n setCreateStyles({ ...updated, updateSheet } as any);\n }\n }\n }, [rulesChanged, stylesheet, updateSheet]);\n return React.useMemo(() => ({ classes, styleTag }), [classes, styleTag]);\n}\n", "import { Properties } from 'csstype';\nimport merge from 'deepmerge';\n\nimport { generateClassName } from './generateClassName';\nimport { getPosthooks } from './plugins';\nimport { SimpleStyleRules } from './types';\n\nexport type CreateStylesOptions = Partial<{\n /**\n * If true, automatically renders generated styles\n * to the DOM in an injected <style /> tag\n */\n flush: boolean;\n\n /**\n * If set, along with flush: true,\n * will render the injected <style /> after this element\n */\n insertAfter?: HTMLElement;\n /**\n * If set, along with flush: true,\n * will render the injects <style /> before this element\n */\n insertBefore?: HTMLElement;\n}>;\n\nfunction isNestedSelector(r: string): boolean {\n return /&/g.test(r);\n}\n\nfunction isMedia(r: string): boolean {\n return r.toLowerCase().startsWith('@media');\n}\n\nfunction formatCSSRuleName(rule: string): string {\n return rule.replace(/([A-Z])/g, p1 => `-${p1.toLowerCase()}`);\n}\n\nfunction formatCSSRules(cssRules: Properties): string {\n return Object.entries(cssRules).reduce(\n (prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,\n '',\n );\n}\n\nfunction execCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options: CreateStylesOptions,\n parentSelector: string | null,\n noGenerateClassName: boolean = false,\n): { classes: O; sheetBuffer: string; mediaQueriesBuffer: string } {\n const out = {} as O;\n let sheetBuffer = '';\n let mediaQueriesBuffer = '';\n const styleEntries = Object.entries(rules);\n let ruleWriteOpen = false;\n const guardCloseRuleWrite = () => {\n if (ruleWriteOpen) sheetBuffer += '}';\n ruleWriteOpen = false;\n };\n for (const [classNameOrCSSRule, classNameRules] of styleEntries) {\n // if the classNameRules is a string, we are dealing with a display: none; type rule\n if (isMedia(classNameOrCSSRule)) {\n if (typeof classNameRules !== 'object')\n throw new Error('Unable to map @media query because rules / props are an invalid type');\n guardCloseRuleWrite();\n mediaQueriesBuffer += `${classNameOrCSSRule}{`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n parentSelector,\n );\n mediaQueriesBuffer += regularOutput;\n mediaQueriesBuffer += '}';\n mediaQueriesBuffer += mediaQueriesOutput;\n } else if (isNestedSelector(classNameOrCSSRule)) {\n if (!parentSelector) throw new Error('Unable to generate nested rule because parentSelector is missing');\n guardCloseRuleWrite();\n // format of { '& > span': { display: 'none' } } (or further nesting)\n const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);\n for (const selector of replaced.split(/,\\s*/)) {\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n selector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n }\n } else if (!parentSelector && typeof classNameRules === 'object') {\n guardCloseRuleWrite();\n const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);\n (out as any)[classNameOrCSSRule] = generated;\n const generatedSelector = `${noGenerateClassName ? '' : '.'}${generated}`;\n const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(\n classNameRules as T,\n options,\n generatedSelector,\n );\n sheetBuffer += regularOutput;\n mediaQueriesBuffer += mediaQueriesOutput;\n } else {\n if (!parentSelector) throw new Error('Unable to write css props because parent selector is null');\n if (!ruleWriteOpen) {\n sheetBuffer += `${parentSelector}{${formatCSSRules({ [classNameOrCSSRule]: classNameRules })}`;\n ruleWriteOpen = true;\n } else sheetBuffer += formatCSSRules({ [classNameOrCSSRule]: classNameRules });\n }\n }\n guardCloseRuleWrite();\n return {\n classes: out,\n sheetBuffer,\n mediaQueriesBuffer,\n };\n}\n\nfunction replaceBackReferences<O extends { [key: string]: string }>(out: O, sheetContents: string): string {\n let outputSheetContents = sheetContents;\n const toReplace: string[] = [];\n const toReplaceRegex = /\\$\\w([a-zA-Z0-9_-]+)?/gm;\n let matches = toReplaceRegex.exec(outputSheetContents);\n while (matches) {\n toReplace.push(matches[0].valueOf());\n matches = toReplaceRegex.exec(outputSheetContents);\n }\n for (const r of toReplace) {\n outputSheetContents = outputSheetContents.replace(r, `.${out[r.substring(1)]}`);\n }\n return getPosthooks().reduce((prev, hook) => hook(prev), outputSheetContents);\n}\n\nfunction createSheet(sheetContents: string) {\n if (typeof document === 'undefined') return null;\n if (typeof document?.head?.appendChild !== 'function' || typeof document?.createElement !== 'function') return null;\n const styleTag = document.createElement('style');\n styleTag.innerHTML = sheetContents;\n return styleTag;\n}\n\nfunction flushSheetContents(sheetContents: string, options?: CreateStylesOptions) {\n // In case we're in come weird test environment that doesn't support JSDom\n const styleTag = createSheet(sheetContents);\n if (styleTag) {\n if (options?.insertAfter && options?.insertBefore) {\n throw new Error('Both insertAfter and insertBefore were provided. Please choose only one.');\n }\n if (options?.insertAfter?.after) options.insertAfter.after(styleTag as Node);\n else if (options?.insertBefore?.before) options.insertBefore.before(styleTag as Node);\n else document.head.appendChild(styleTag);\n }\n return styleTag;\n}\n\nfunction coerceCreateStylesOptions(options?: CreateStylesOptions): CreateStylesOptions {\n return {\n flush: options && typeof options.flush === 'boolean' ? options.flush : true,\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function rawStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [key in K]: string }>(\n rules: T,\n options?: Partial<CreateStylesOptions>,\n) {\n const coerced = coerceCreateStylesOptions(options);\n const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(\n rules,\n coerced,\n null,\n true,\n );\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n if (coerced.flush) flushSheetContents(mergedContents, options);\n return mergedContents;\n}\n\nexport function keyframes<T extends { [increment: string]: Properties }>(\n frames: T,\n options?: CreateStylesOptions,\n): [string, string] {\n const coerced = coerceCreateStylesOptions(options);\n const keyframeName = generateClassName('keyframes_');\n const { sheetBuffer: keyframesContents } = execCreateStyles(frames, coerced, null, true);\n const sheetContents = `@keyframes ${keyframeName}{${keyframesContents}}`;\n if (coerced.flush) flushSheetContents(sheetContents);\n return [keyframeName, sheetContents];\n}\n\nexport default function createStyles<\n T extends SimpleStyleRules,\n K extends keyof T,\n O extends { [classKey in K]: string },\n>(rules: T, options?: Partial<CreateStylesOptions>) {\n const coerced = coerceCreateStylesOptions(options);\n const {\n classes: out,\n sheetBuffer: sheetContents,\n mediaQueriesBuffer: mediaQueriesContents,\n } = execCreateStyles(rules, coerced, null);\n\n const mergedContents = `${sheetContents}${mediaQueriesContents}`;\n\n const replacedSheetContents = replaceBackReferences(out, mergedContents);\n\n let sheet: ReturnType<typeof flushSheetContents> = null;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const updateSheet = <T2 extends SimpleStyleRules, K2 extends keyof T2, O2 extends { [classKey in K2]: string }>(\n updatedRules: Partial<T2>,\n ) => {\n if (((options?.flush && sheet) || !options?.flush) && updatedRules) {\n // We prefer the first set, and then we shallow merge\n const {\n classes: updatedOut,\n sheetBuffer: updatedSheetContents,\n mediaQueriesBuffer: updatedMediaQueriesContents,\n } = execCreateStyles(merge(rules, updatedRules), { flush: false }, null);\n\n const updatedMergedContents = `${updatedSheetContents}${updatedMediaQueriesContents}`;\n\n const updatedReplacedSheetContents = replaceBackReferences(out, updatedMergedContents);\n if (sheet) sheet.innerHTML = updatedReplacedSheetContents;\n return { classes: updatedOut, stylesheet: updatedSheetContents } as {\n classes: typeof updatedOut;\n stylesheet: string;\n };\n }\n return null;\n };\n\n if (coerced.flush) sheet = flushSheetContents(replacedSheetContents, options);\n // Need this TS cast to get solid code assist from the consumption-side\n return {\n classes: out as unknown,\n stylesheet: replacedSheetContents,\n updateSheet,\n } as {\n classes: O;\n stylesheet: string;\n updateSheet: typeof updateSheet;\n };\n}\n\nexport type CreateStylesArgs = Parameters<typeof createStyles>;\n", "const alphas = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\nexport default function numToAlpha(num: number): string {\n return alphas[num];\n}\n", "import numToAlpha from './numToAlpha';\n\nlet inc = Date.now();\n\nexport function setSeed(seed: number | null): void {\n if (seed === null) {\n inc = Date.now();\n return;\n }\n if (typeof seed !== 'number') throw Error('Unable to setSeed as provided seed was not a valid number');\n if (seed === Number.MAX_SAFE_INTEGER)\n throw Error('Unable to setSeed because the seed was already the maximum safe JavaScript number allowed');\n if (seed === Number.POSITIVE_INFINITY || seed === Number.NEGATIVE_INFINITY)\n throw new Error('Unable to setSeed. Positive or negative infinity is not allowed');\n if (seed < 0) throw new Error('Unable to setSeed. Seed must be a number >= 0');\n inc = seed;\n}\n\nconst numPairsRegex = /(\\d{1,2})/g;\n\nexport function getUniqueSuffix(): string {\n const numPairs: string[] = [];\n const incStr = inc.toString();\n let result = numPairsRegex.exec(incStr);\n while (result) {\n numPairs.push(result[0]);\n result = numPairsRegex.exec(incStr);\n }\n let out = '_';\n numPairs.forEach(pair => {\n const val = +pair;\n if (val > 25) {\n const [first, second] = pair.split('');\n out += `${numToAlpha(+first)}${numToAlpha(+second)}`;\n } else out += numToAlpha(val);\n });\n inc += 1;\n return out;\n}\n\nexport function generateClassName(c: string): string {\n return `${c}${getUniqueSuffix()}`;\n}\n", "export type PosthookPlugin = (sheetContents: string) => string;\n\nconst posthooks: PosthookPlugin[] = [];\n\nexport function getPosthooks(): PosthookPlugin[] {\n return posthooks;\n}\n\nexport function registerPosthook(posthook: PosthookPlugin) {\n posthooks.push(posthook);\n}\n", "export function deepEqual<\n O1 extends Record<string | number | symbol, any>,\n O2 extends Record<string | number | symbol, any>,\n>(o1: O1, o2: O2): boolean {\n // We'll sort the keys, just in case the user kept things the same but the object is all wonky, order-wise\n const o1Keys = Object.keys(o1).sort();\n const o2Keys = Object.keys(o2).sort();\n if (o1Keys.length !== o2Keys.length) return false;\n if (o1Keys.some((key, i) => o2Keys[i] !== key)) return false;\n // Okay, the keys SHOULD be the same\n // so we need to test their values, recursively, to verify equality\n return o1Keys.reduce<boolean>((prev, key) => {\n if (!prev) return prev; // we've already failed equality checks here\n if (!(key in o2)) return false;\n if (typeof o1[key] !== 'object') {\n return prev && o1[key] === o2[key];\n }\n return prev && deepEqual(o1[key], o2[key]);\n }, true);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAkB;;;ACClB,uBAAkB;;;ACDlB,IAAM,SAAS,6BAA6B,MAAM,EAAE;AAErC,SAAR,WAA4B,KAAqB;AACtD,SAAO,OAAO,GAAG;AACnB;;;ACFA,IAAI,MAAM,KAAK,IAAI;AAgBnB,IAAM,gBAAgB;AAEf,SAAS,kBAA0B;AACxC,QAAM,WAAqB,CAAC;AAC5B,QAAM,SAAS,IAAI,SAAS;AAC5B,MAAI,SAAS,cAAc,KAAK,MAAM;AACtC,SAAO,QAAQ;AACb,aAAS,KAAK,OAAO,CAAC,CAAC;AACvB,aAAS,cAAc,KAAK,MAAM;AAAA,EACpC;AACA,MAAI,MAAM;AACV,WAAS,QAAQ,UAAQ;AACvB,UAAM,MAAM,CAAC;AACb,QAAI,MAAM,IAAI;AACZ,YAAM,CAAC,OAAO,MAAM,IAAI,KAAK,MAAM,EAAE;AACrC,aAAO,GAAG,WAA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AAAA,EACF,GAAG,CAAC,cAAc,YAAY,WAAW,CAAC;AAC1C,SAAO,aAAAA,QAAM,QAAQ,OAAO,EAAE,SAAS,SAAS,IAAI,CAAC,SAAS,QAAQ,CAAC;AACzE;",
|
|
6
|
+
"names": ["merge", "React"]
|
|
7
7
|
}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
1
2
|
import { CreateStylesOptions } from '../createStyles';
|
|
2
3
|
import { SimpleStyleRules } from '../types';
|
|
3
4
|
export declare function useCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends {
|
|
4
5
|
[classKey in K]: string;
|
|
5
|
-
}>(rules: T, options?: Partial<Omit<CreateStylesOptions, 'flush'>>):
|
|
6
|
+
}>(rules: T, options?: Partial<Omit<CreateStylesOptions, 'flush'>>): {
|
|
7
|
+
classes: O;
|
|
8
|
+
styleTag: JSX.Element | null;
|
|
9
|
+
};
|
package/react/useCreateStyles.js
CHANGED
|
@@ -1,36 +1,48 @@
|
|
|
1
|
-
import
|
|
1
|
+
import React from "react";
|
|
2
2
|
import createStyles from "../createStyles";
|
|
3
3
|
import { deepEqual } from "../util";
|
|
4
4
|
function useCreateStyles(rules, options) {
|
|
5
|
-
const [cachedRules, setCachedRules] = useState(() => rules);
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
5
|
+
const [cachedRules, setCachedRules] = React.useState(() => rules);
|
|
6
|
+
const [{ classes, stylesheet, updateSheet }, setCreateStyles] = React.useState(
|
|
7
|
+
() => createStyles(rules, { ...options, flush: false })
|
|
8
|
+
);
|
|
9
|
+
const didFirstWriteRef = React.useRef(false);
|
|
10
|
+
const styleTagRef = React.useRef(typeof document !== "undefined" ? document.createElement("style") : null);
|
|
11
|
+
const rulesRef = React.useRef(rules);
|
|
12
|
+
const cachedRulesRef = React.useRef(cachedRules);
|
|
13
|
+
rulesRef.current = rules;
|
|
14
|
+
cachedRulesRef.current = cachedRules;
|
|
15
|
+
const rulesChanged = !deepEqual(rulesRef.current, cachedRulesRef.current);
|
|
16
|
+
const styleTag = React.useMemo(() => {
|
|
17
|
+
if (styleTagRef.current)
|
|
18
|
+
return null;
|
|
19
|
+
return /* @__PURE__ */ React.createElement("style", { dangerouslySetInnerHTML: { __html: stylesheet } });
|
|
20
|
+
}, [stylesheet]);
|
|
21
|
+
React.useEffect(() => {
|
|
11
22
|
if (!styleTagRef.current)
|
|
12
23
|
return;
|
|
13
24
|
const { current: s } = styleTagRef;
|
|
14
25
|
document.head.appendChild(s);
|
|
15
26
|
return () => s.remove();
|
|
16
27
|
}, []);
|
|
17
|
-
useEffect(() => {
|
|
28
|
+
React.useEffect(() => {
|
|
18
29
|
if (!styleTagRef.current)
|
|
19
30
|
return;
|
|
20
31
|
if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {
|
|
21
32
|
didFirstWriteRef.current = true;
|
|
22
33
|
styleTagRef.current.innerHTML = stylesheet;
|
|
23
34
|
return;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
35
|
+
}
|
|
36
|
+
if (rulesChanged) {
|
|
37
|
+
setCachedRules(rulesRef.current);
|
|
38
|
+
const updated = updateSheet(rulesRef.current);
|
|
27
39
|
if (updated == null ? void 0 : updated.stylesheet) {
|
|
28
40
|
styleTagRef.current.innerHTML = updated.stylesheet;
|
|
29
41
|
setCreateStyles({ ...updated, updateSheet });
|
|
30
42
|
}
|
|
31
43
|
}
|
|
32
|
-
}, [
|
|
33
|
-
return classes;
|
|
44
|
+
}, [rulesChanged, stylesheet, updateSheet]);
|
|
45
|
+
return React.useMemo(() => ({ classes, styleTag }), [classes, styleTag]);
|
|
34
46
|
}
|
|
35
47
|
export {
|
|
36
48
|
useCreateStyles
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../src/react/useCreateStyles.
|
|
4
|
-
"sourcesContent": ["import
|
|
5
|
-
"mappings": "AAAA;
|
|
3
|
+
"sources": ["../../src/react/useCreateStyles.tsx"],
|
|
4
|
+
"sourcesContent": ["import React from 'react';\n\nimport createStyles, { CreateStylesOptions } from '../createStyles';\nimport { SimpleStyleRules } from '../types';\nimport { deepEqual } from '../util';\n\nexport function useCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(\n rules: T,\n options?: Partial<Omit<CreateStylesOptions, 'flush'>>,\n) {\n // state\n const [cachedRules, setCachedRules] = React.useState(() => rules);\n const [{ classes, stylesheet, updateSheet }, setCreateStyles] = React.useState(() =>\n createStyles<T, K, O>(rules, { ...options, flush: false }),\n );\n\n // refs\n const didFirstWriteRef = React.useRef(false);\n const styleTagRef = React.useRef(typeof document !== 'undefined' ? document.createElement('style') : null);\n const rulesRef = React.useRef(rules);\n const cachedRulesRef = React.useRef(cachedRules);\n\n // we leverage refs for these objects, as their referential equality is likely always changing.\n // this prevent unnecessary executions of the effects below\n rulesRef.current = rules;\n cachedRulesRef.current = cachedRules;\n\n // local variables\n const rulesChanged = !deepEqual(rulesRef.current, cachedRulesRef.current);\n\n // memos\n const styleTag = React.useMemo(() => {\n if (styleTagRef.current) return null;\n\n return <style dangerouslySetInnerHTML={{ __html: stylesheet }} />;\n }, [stylesheet]);\n\n // effects\n React.useEffect(() => {\n if (!styleTagRef.current) return;\n\n const { current: s } = styleTagRef;\n document.head.appendChild(s);\n return () => s.remove();\n }, []);\n React.useEffect(() => {\n if (!styleTagRef.current) return;\n\n if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {\n didFirstWriteRef.current = true;\n styleTagRef.current.innerHTML = stylesheet;\n return;\n }\n if (rulesChanged) {\n setCachedRules(rulesRef.current);\n const updated = updateSheet(rulesRef.current);\n if (updated?.stylesheet) {\n styleTagRef.current.innerHTML = updated.stylesheet;\n setCreateStyles({ ...updated, updateSheet } as any);\n }\n }\n }, [rulesChanged, stylesheet, updateSheet]);\n return React.useMemo(() => ({ classes, styleTag }), [classes, style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I,mCAAS,YAAY;AACvB,oBAAY,QAAQ,YAAY,QAAQ;AACxC,wBAAgB,EAAE,GAAG,SAAS,YAAY,CAAQ;AAAA,MACpD;AAAA,IACF;AAAA,EACF,GAAG,CAAC,cAAc,YAAY,WAAW,CAAC;AAC1C,SAAO,MAAM,QAAQ,OAAO,EAAE,SAAS,SAAS,IAAI,CAAC,SAAS,QAAQ,CAAC;AACzE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/types.d.ts
CHANGED
|
@@ -2,6 +2,6 @@ import { Properties } from 'csstype';
|
|
|
2
2
|
export interface SimpleStyleRules {
|
|
3
3
|
[key: string]: Properties | SimpleStyleRules;
|
|
4
4
|
}
|
|
5
|
-
export
|
|
5
|
+
export type RenderableSimpleStyleRules = SimpleStyleRules & {
|
|
6
6
|
[selector: string]: Properties[];
|
|
7
7
|
};
|
package/util/deepEqual.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/util/deepEqual.ts"],
|
|
4
4
|
"sourcesContent": ["export function deepEqual<\n O1 extends Record<string | number | symbol, any>,\n O2 extends Record<string | number | symbol, any>,\n>(o1: O1, o2: O2): boolean {\n // We'll sort the keys, just in case the user kept things the same but the object is all wonky, order-wise\n const o1Keys = Object.keys(o1).sort();\n const o2Keys = Object.keys(o2).sort();\n if (o1Keys.length !== o2Keys.length) return false;\n if (o1Keys.some((key, i) => o2Keys[i] !== key)) return false;\n // Okay, the keys SHOULD be the same\n // so we need to test their values, recursively, to verify equality\n return o1Keys.reduce<boolean>((prev, key) => {\n if (!prev) return prev; // we've already failed equality checks here\n if (!(key in o2)) return false;\n if (typeof o1[key] !== 'object') {\n return prev && o1[key] === o2[key];\n }\n return prev && deepEqual(o1[key], o2[key]);\n }, true);\n}\n"],
|
|
5
|
-
"mappings": "AAAO,
|
|
5
|
+
"mappings": "AAAO,SAAS,UAGd,IAAQ,IAAiB;AAEzB,QAAM,SAAS,OAAO,KAAK,EAAE,EAAE,KAAK;AACpC,QAAM,SAAS,OAAO,KAAK,EAAE,EAAE,KAAK;AACpC,MAAI,OAAO,WAAW,OAAO;AAAQ,WAAO;AAC5C,MAAI,OAAO,KAAK,CAAC,KAAK,MAAM,OAAO,CAAC,MAAM,GAAG;AAAG,WAAO;AAGvD,SAAO,OAAO,OAAgB,CAAC,MAAM,QAAQ;AAC3C,QAAI,CAAC;AAAM,aAAO;AAClB,QAAI,EAAE,OAAO;AAAK,aAAO;AACzB,QAAI,OAAO,GAAG,GAAG,MAAM,UAAU;AAC/B,aAAO,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG;AAAA,IACnC;AACA,WAAO,QAAQ,UAAU,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAAA,EAC3C,GAAG,IAAI;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/util/index.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/util/index.ts", "../../../src/util/deepEqual.ts"],
|
|
4
4
|
"sourcesContent": ["export * from './deepEqual';\n", "export function deepEqual<\n O1 extends Record<string | number | symbol, any>,\n O2 extends Record<string | number | symbol, any>,\n>(o1: O1, o2: O2): boolean {\n // We'll sort the keys, just in case the user kept things the same but the object is all wonky, order-wise\n const o1Keys = Object.keys(o1).sort();\n const o2Keys = Object.keys(o2).sort();\n if (o1Keys.length !== o2Keys.length) return false;\n if (o1Keys.some((key, i) => o2Keys[i] !== key)) return false;\n // Okay, the keys SHOULD be the same\n // so we need to test their values, recursively, to verify equality\n return o1Keys.reduce<boolean>((prev, key) => {\n if (!prev) return prev; // we've already failed equality checks here\n if (!(key in o2)) return false;\n if (typeof o1[key] !== 'object') {\n return prev && o1[key] === o2[key];\n }\n return prev && deepEqual(o1[key], o2[key]);\n }, true);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,SAAS,UAGd,IAAQ,IAAiB;AAEzB,QAAM,SAAS,OAAO,KAAK,EAAE,EAAE,KAAK;AACpC,QAAM,SAAS,OAAO,KAAK,EAAE,EAAE,KAAK;AACpC,MAAI,OAAO,WAAW,OAAO;AAAQ,WAAO;AAC5C,MAAI,OAAO,KAAK,CAAC,KAAK,MAAM,OAAO,CAAC,MAAM,GAAG;AAAG,WAAO;AAGvD,SAAO,OAAO,OAAgB,CAAC,MAAM,QAAQ;AAC3C,QAAI,CAAC;AAAM,aAAO;AAClB,QAAI,EAAE,OAAO;AAAK,aAAO;AACzB,QAAI,OAAO,GAAG,GAAG,MAAM,UAAU;AAC/B,aAAO,QAAQ,GAAG,GAAG,MAAM,GAAG,GAAG;AAAA,IACnC;AACA,WAAO,QAAQ,UAAU,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAAA,EAC3C,GAAG,IAAI;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|