simplestyle-js 3.1.2 → 3.1.4-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.
Files changed (61) hide show
  1. package/createStyles.d.ts +36 -0
  2. package/createStyles.js +170 -0
  3. package/createStyles.js.map +7 -0
  4. package/generateClassName.d.ts +3 -0
  5. package/generateClassName.js +47 -0
  6. package/generateClassName.js.map +7 -0
  7. package/index.cjs.js +255 -0
  8. package/index.d.ts +6 -0
  9. package/index.js +11 -0
  10. package/index.js.map +7 -0
  11. package/numToAlpha.d.ts +1 -0
  12. package/numToAlpha.js +8 -0
  13. package/numToAlpha.js.map +7 -0
  14. package/package.json +24 -21
  15. package/plugins.d.ts +3 -0
  16. package/plugins.js +12 -0
  17. package/plugins.js.map +7 -0
  18. package/react/index.cjs.js +268 -0
  19. package/{src/react/index.ts → react/index.d.ts} +0 -0
  20. package/react/index.js +2 -0
  21. package/react/index.js.map +7 -0
  22. package/react/package.json +6 -0
  23. package/react/useCreateStyles.d.ts +5 -0
  24. package/react/useCreateStyles.js +34 -0
  25. package/react/useCreateStyles.js.map +7 -0
  26. package/types.d.ts +7 -0
  27. package/types.js +1 -0
  28. package/types.js.map +7 -0
  29. package/util/deepEqual.d.ts +1 -0
  30. package/util/deepEqual.js +22 -0
  31. package/util/deepEqual.js.map +7 -0
  32. package/util/index.cjs.js +45 -0
  33. package/{src/util/index.ts → util/index.d.ts} +0 -0
  34. package/util/index.js +2 -0
  35. package/util/index.js.map +7 -0
  36. package/util/package.json +6 -0
  37. package/.coveralls.yml +0 -2
  38. package/.editorconfig +0 -7
  39. package/.eslintrc.json +0 -3
  40. package/.prettierrc +0 -7
  41. package/.travis.yml +0 -8
  42. package/.vscode/launch.json +0 -36
  43. package/jest.config.ts +0 -9
  44. package/scripts/preparePackageJson.js +0 -14
  45. package/src/createStyles.ts +0 -253
  46. package/src/generateClassName.ts +0 -43
  47. package/src/index.ts +0 -4
  48. package/src/numToAlpha.ts +0 -5
  49. package/src/plugins.ts +0 -11
  50. package/src/react/useCreateStyles.ts +0 -40
  51. package/src/types.ts +0 -7
  52. package/src/util/deepEqual.ts +0 -20
  53. package/test/createStyles.spec.ts +0 -328
  54. package/test/deepEqual.spec.ts +0 -95
  55. package/test/generateClassName.spec.ts +0 -46
  56. package/test/keyframes.spec.ts +0 -17
  57. package/test/plugins.spec.ts +0 -44
  58. package/test/react/useCreateStyles.spec.tsx +0 -64
  59. package/test/updateStyles.spec.ts +0 -39
  60. package/tsconfig.build.json +0 -4
  61. package/tsconfig.json +0 -29
package/.prettierrc DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "endOfLine": "lf",
3
- "printWidth": 180,
4
- "semi": true,
5
- "trailingComma": "all",
6
- "singleQuote": true
7
- }
package/.travis.yml DELETED
@@ -1,8 +0,0 @@
1
- language: node_js
2
- node_js:
3
- - 12
4
- install:
5
- - yarn
6
- script:
7
- - yarn test
8
- - yarn coveralls
@@ -1,36 +0,0 @@
1
- {
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
- "version": "0.2.0",
6
- "configurations": [
7
- {
8
- "name": "Attach",
9
- "port": 9229,
10
- "request": "attach",
11
- "skipFiles": [
12
- "<node_internals>/**"
13
- ],
14
- "type": "pwa-node"
15
- },
16
- {
17
- "type": "node",
18
- "request": "launch",
19
- "name": "Jest Current File",
20
- "program": "${workspaceFolder}/node_modules/.bin/jest",
21
- "args": [
22
- "${fileBasenameNoExtension}",
23
- "--config",
24
- "jest.config.js",
25
- "--env",
26
- "jsdom"
27
- ],
28
- "console": "integratedTerminal",
29
- "internalConsoleOptions": "neverOpen",
30
- "disableOptimisticBPs": true,
31
- "windows": {
32
- "program": "${workspaceFolder}/node_modules/jest/bin/jest",
33
- }
34
- }
35
- ]
36
- }
package/jest.config.ts DELETED
@@ -1,9 +0,0 @@
1
- import type { Config } from '@jest/types';
2
-
3
- const config: Config.InitialOptions = {
4
- testPathIgnorePatterns: ['./dist'],
5
- preset: 'ts-jest',
6
- testEnvironment: 'jsdom',
7
- };
8
-
9
- export default config;
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env node
2
- const fs = require('fs');
3
- const path = require('path');
4
-
5
- const pjsonPath = path.join(__dirname, '../package.json');
6
- const pjson = JSON.parse(fs.readFileSync(pjsonPath, 'utf8'));
7
-
8
- pjson.main = './commonjs/index.js';
9
- pjson.module = './esm/index.js';
10
- pjson.esnext = './esm/index.js';
11
- pjson.typings = './esm/index.d.ts';
12
- pjson.types = './esm/index.d.ts';
13
-
14
- fs.writeFileSync(path.join(__dirname, '../dist', 'package.json'), JSON.stringify(pjson, null, 2), 'utf8');
@@ -1,253 +0,0 @@
1
- import { Properties } from 'csstype';
2
- import merge from 'deepmerge';
3
-
4
- import { generateClassName } from './generateClassName';
5
- import { getPosthooks } from './plugins';
6
- import { SimpleStyleRules } from './types';
7
-
8
- export type CreateStylesOptions = Partial<{
9
- /**
10
- * If true, automatically renders generated styles
11
- * to the DOM in an injected <style /> tag
12
- */
13
- flush: boolean;
14
-
15
- /**
16
- * If set, along with flush: true,
17
- * will render the injected <style /> after this element
18
- */
19
- insertAfter?: HTMLElement;
20
- /**
21
- * If set, along with flush: true,
22
- * will render the injects <style /> before this element
23
- */
24
- insertBefore?: HTMLElement;
25
- }>;
26
-
27
- function isNestedSelector(r: string): boolean {
28
- return /&/g.test(r);
29
- }
30
-
31
- function isMedia(r: string): boolean {
32
- return r.toLowerCase().startsWith('@media');
33
- }
34
-
35
- function formatCSSRuleName(rule: string): string {
36
- return rule.replace(/([A-Z])/g, p1 => `-${p1.toLowerCase()}`);
37
- }
38
-
39
- function formatCSSRules(cssRules: Properties): string {
40
- return Object.entries(cssRules).reduce(
41
- (prev, [cssProp, cssVal]) => `${prev}${formatCSSRuleName(cssProp)}:${cssVal};`,
42
- '',
43
- );
44
- }
45
-
46
- function execCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(
47
- rules: T,
48
- options: CreateStylesOptions,
49
- parentSelector: string | null,
50
- noGenerateClassName: boolean = false,
51
- ): { classes: O; sheetBuffer: string; mediaQueriesBuffer: string } {
52
- const out = {} as O;
53
- let sheetBuffer = '';
54
- let mediaQueriesBuffer = '';
55
- const styleEntries = Object.entries(rules);
56
- let ruleWriteOpen = false;
57
- const guardCloseRuleWrite = () => {
58
- if (ruleWriteOpen) sheetBuffer += '}';
59
- ruleWriteOpen = false;
60
- };
61
- for (const [classNameOrCSSRule, classNameRules] of styleEntries) {
62
- // if the classNameRules is a string, we are dealing with a display: none; type rule
63
- if (isMedia(classNameOrCSSRule)) {
64
- if (typeof classNameRules !== 'object')
65
- throw new Error('Unable to map @media query because rules / props are an invalid type');
66
- guardCloseRuleWrite();
67
- mediaQueriesBuffer += `${classNameOrCSSRule}{`;
68
- const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
69
- classNameRules as T,
70
- options,
71
- parentSelector,
72
- );
73
- mediaQueriesBuffer += regularOutput;
74
- mediaQueriesBuffer += '}';
75
- mediaQueriesBuffer += mediaQueriesOutput;
76
- } else if (isNestedSelector(classNameOrCSSRule)) {
77
- if (!parentSelector) throw new Error('Unable to generate nested rule because parentSelector is missing');
78
- guardCloseRuleWrite();
79
- // format of { '& > span': { display: 'none' } } (or further nesting)
80
- const replaced = classNameOrCSSRule.replace(/&/g, parentSelector);
81
- for (const selector of replaced.split(/,\s*/)) {
82
- const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
83
- classNameRules as T,
84
- options,
85
- selector,
86
- );
87
- sheetBuffer += regularOutput;
88
- mediaQueriesBuffer += mediaQueriesOutput;
89
- }
90
- } else if (!parentSelector && typeof classNameRules === 'object') {
91
- guardCloseRuleWrite();
92
- const generated = noGenerateClassName ? classNameOrCSSRule : generateClassName(classNameOrCSSRule);
93
- (out as any)[classNameOrCSSRule] = generated;
94
- const generatedSelector = `${noGenerateClassName ? '' : '.'}${generated}`;
95
- const { mediaQueriesBuffer: mediaQueriesOutput, sheetBuffer: regularOutput } = execCreateStyles(
96
- classNameRules as T,
97
- options,
98
- generatedSelector,
99
- );
100
- sheetBuffer += regularOutput;
101
- mediaQueriesBuffer += mediaQueriesOutput;
102
- } else {
103
- if (!parentSelector) throw new Error('Unable to write css props because parent selector is null');
104
- if (!ruleWriteOpen) {
105
- sheetBuffer += `${parentSelector}{${formatCSSRules({ [classNameOrCSSRule]: classNameRules })}`;
106
- ruleWriteOpen = true;
107
- } else sheetBuffer += formatCSSRules({ [classNameOrCSSRule]: classNameRules });
108
- }
109
- }
110
- guardCloseRuleWrite();
111
- return {
112
- classes: out,
113
- sheetBuffer,
114
- mediaQueriesBuffer,
115
- };
116
- }
117
-
118
- function replaceBackReferences<O extends { [key: string]: string }>(out: O, sheetContents: string): string {
119
- let outputSheetContents = sheetContents;
120
- const toReplace: string[] = [];
121
- const toReplaceRegex = /\$\w([a-zA-Z0-9_-]+)?/gm;
122
- let matches = toReplaceRegex.exec(outputSheetContents);
123
- while (matches) {
124
- toReplace.push(matches[0].valueOf());
125
- matches = toReplaceRegex.exec(outputSheetContents);
126
- }
127
- for (const r of toReplace) {
128
- outputSheetContents = outputSheetContents.replace(r, `.${out[r.substring(1)]}`);
129
- }
130
- return getPosthooks().reduce((prev, hook) => hook(prev), outputSheetContents);
131
- }
132
-
133
- function createSheet(sheetContents: string) {
134
- if (
135
- typeof document !== 'undefined' &&
136
- document.head &&
137
- document.head.appendChild &&
138
- typeof document.createElement === 'function'
139
- ) {
140
- const styleTag = document.createElement('style');
141
- styleTag.innerHTML = sheetContents;
142
- return styleTag;
143
- }
144
- return null;
145
- }
146
-
147
- function flushSheetContents(sheetContents: string, options?: CreateStylesOptions) {
148
- // In case we're in come weird test environment that doesn't support JSDom
149
- const styleTag = createSheet(sheetContents);
150
- if (styleTag) {
151
- if (options?.insertAfter && options?.insertBefore) {
152
- throw new Error('Both insertAfter and insertBefore were provided. Please choose only one.');
153
- }
154
- if (options?.insertAfter?.after) options.insertAfter.after(styleTag as Node);
155
- else if (options?.insertBefore?.before) options.insertBefore.before(styleTag as Node);
156
- else document.head.appendChild(styleTag);
157
- }
158
- return styleTag;
159
- }
160
-
161
- function coerceCreateStylesOptions(options?: CreateStylesOptions): CreateStylesOptions {
162
- return {
163
- flush: options && typeof options.flush === 'boolean' ? options.flush : true,
164
- };
165
- }
166
-
167
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
168
- export function rawStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [key in K]: string }>(
169
- rules: T,
170
- options?: Partial<CreateStylesOptions>,
171
- ) {
172
- const coerced = coerceCreateStylesOptions(options);
173
- const { sheetBuffer: sheetContents, mediaQueriesBuffer: mediaQueriesContents } = execCreateStyles(
174
- rules,
175
- coerced,
176
- null,
177
- true,
178
- );
179
-
180
- const mergedContents = `${sheetContents}${mediaQueriesContents}`;
181
-
182
- if (coerced.flush) flushSheetContents(mergedContents, options);
183
- return mergedContents;
184
- }
185
-
186
- export function keyframes<T extends { [increment: string]: Properties }>(
187
- frames: T,
188
- options?: CreateStylesOptions,
189
- ): [string, string] {
190
- const coerced = coerceCreateStylesOptions(options);
191
- const keyframeName = generateClassName('keyframes_');
192
- const { sheetBuffer: keyframesContents } = execCreateStyles(frames, coerced, null, true);
193
- const sheetContents = `@keyframes ${keyframeName}{${keyframesContents}}`;
194
- if (coerced.flush) flushSheetContents(sheetContents);
195
- return [keyframeName, sheetContents];
196
- }
197
-
198
- export default function createStyles<
199
- T extends SimpleStyleRules,
200
- K extends keyof T,
201
- O extends { [classKey in K]: string },
202
- >(rules: T, options?: Partial<CreateStylesOptions>) {
203
- const coerced = coerceCreateStylesOptions(options);
204
- const {
205
- classes: out,
206
- sheetBuffer: sheetContents,
207
- mediaQueriesBuffer: mediaQueriesContents,
208
- } = execCreateStyles(rules, coerced, null);
209
-
210
- const mergedContents = `${sheetContents}${mediaQueriesContents}`;
211
-
212
- const replacedSheetContents = replaceBackReferences(out, mergedContents);
213
-
214
- let sheet: ReturnType<typeof flushSheetContents> = null;
215
-
216
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
217
- const updateSheet = <T2 extends SimpleStyleRules, K2 extends keyof T2, O2 extends { [classKey in K2]: string }>(
218
- updatedRules: Partial<T2>,
219
- ) => {
220
- if (((options?.flush && sheet) || !options?.flush) && updatedRules) {
221
- // We prefer the first set, and then we shallow merge
222
- const {
223
- classes: updatedOut,
224
- sheetBuffer: updatedSheetContents,
225
- mediaQueriesBuffer: updatedMediaQueriesContents,
226
- } = execCreateStyles(merge(rules, updatedRules), { flush: false }, null);
227
-
228
- const updatedMergedContents = `${updatedSheetContents}${updatedMediaQueriesContents}`;
229
-
230
- const updatedReplacedSheetContents = replaceBackReferences(out, updatedMergedContents);
231
- if (sheet) sheet.innerHTML = updatedReplacedSheetContents;
232
- return { classes: updatedOut, stylesheet: updatedSheetContents } as {
233
- classes: typeof updatedOut;
234
- stylesheet: string;
235
- };
236
- }
237
- return null;
238
- };
239
-
240
- if (coerced.flush) sheet = flushSheetContents(replacedSheetContents, options);
241
- // Need this TS cast to get solid code assist from the consumption-side
242
- return {
243
- classes: out as unknown,
244
- stylesheet: replacedSheetContents,
245
- updateSheet,
246
- } as {
247
- classes: O;
248
- stylesheet: string;
249
- updateSheet: typeof updateSheet;
250
- };
251
- }
252
-
253
- export type CreateStylesArgs = Parameters<typeof createStyles>;
@@ -1,43 +0,0 @@
1
- import numToAlpha from './numToAlpha';
2
-
3
- let inc = Date.now();
4
-
5
- export function setSeed(seed: number | null): void {
6
- if (seed === null) {
7
- inc = Date.now();
8
- return;
9
- }
10
- if (typeof seed !== 'number') throw Error('Unable to setSeed as provided seed was not a valid number');
11
- if (seed === Number.MAX_SAFE_INTEGER)
12
- throw Error('Unable to setSeed because the seed was already the maximum safe JavaScript number allowed');
13
- if (seed === Number.POSITIVE_INFINITY || seed === Number.NEGATIVE_INFINITY)
14
- throw new Error('Unable to setSeed. Positive or negative infinity is not allowed');
15
- if (seed < 0) throw new Error('Unable to setSeed. Seed must be a number >= 0');
16
- inc = seed;
17
- }
18
-
19
- const numPairsRegex = /(\d{1,2})/g;
20
-
21
- export function getUniqueSuffix(): string {
22
- const numPairs: string[] = [];
23
- const incStr = inc.toString();
24
- let result = numPairsRegex.exec(incStr);
25
- while (result) {
26
- numPairs.push(result[0]);
27
- result = numPairsRegex.exec(incStr);
28
- }
29
- let out = '_';
30
- numPairs.forEach(pair => {
31
- const val = +pair;
32
- if (val > 25) {
33
- const [first, second] = pair.split('');
34
- out += `${numToAlpha(+first)}${numToAlpha(+second)}`;
35
- } else out += numToAlpha(val);
36
- });
37
- inc += 1;
38
- return out;
39
- }
40
-
41
- export function generateClassName(c: string): string {
42
- return `${c}${getUniqueSuffix()}`;
43
- }
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export { default as createStyles, CreateStylesArgs, CreateStylesOptions, keyframes, rawStyles } from './createStyles';
2
- export { setSeed } from './generateClassName';
3
- export { PosthookPlugin, registerPosthook } from './plugins';
4
- export { SimpleStyleRules } from './types';
package/src/numToAlpha.ts DELETED
@@ -1,5 +0,0 @@
1
- const alphas = 'abcdefghijklmnopqrstuvwxyz'.split('');
2
-
3
- export default function numToAlpha(num: number): string {
4
- return alphas[num];
5
- }
package/src/plugins.ts DELETED
@@ -1,11 +0,0 @@
1
- export type PosthookPlugin = (sheetContents: string) => string;
2
-
3
- const posthooks: PosthookPlugin[] = [];
4
-
5
- export function getPosthooks(): PosthookPlugin[] {
6
- return posthooks;
7
- }
8
-
9
- export function registerPosthook(posthook: PosthookPlugin) {
10
- posthooks.push(posthook);
11
- }
@@ -1,40 +0,0 @@
1
- import { useEffect, useMemo, useRef, useState } from 'react';
2
-
3
- import createStyles, { CreateStylesOptions } from '../createStyles';
4
- import { SimpleStyleRules } from '../types';
5
- import { deepEqual } from '../util';
6
-
7
- export function useCreateStyles<T extends SimpleStyleRules, K extends keyof T, O extends { [classKey in K]: string }>(
8
- rules: T,
9
- options?: Partial<Omit<CreateStylesOptions, 'flush'>>,
10
- ) {
11
- const [cachedRules, setCachedRules] = useState(() => rules);
12
- const cachedOptions = useMemo(() => ({ ...options } as Partial<Omit<CreateStylesOptions, 'flush'>>), [options]);
13
- const didFirstWriteRef = useRef(false);
14
- const styleTagRef = useRef(document.createElement('style'));
15
-
16
- const [{ classes, stylesheet, updateSheet }, setCreateStyles] = useState(() =>
17
- createStyles<T, K, O>(rules, { ...cachedOptions, flush: false }),
18
- );
19
-
20
- useEffect(() => {
21
- const { current: s } = styleTagRef;
22
- document.head.appendChild(s);
23
- return () => s.remove();
24
- }, []);
25
- useEffect(() => {
26
- if (!didFirstWriteRef.current && !styleTagRef.current.innerHTML) {
27
- didFirstWriteRef.current = true;
28
- styleTagRef.current.innerHTML = stylesheet;
29
- return;
30
- } else if (!deepEqual(rules, cachedRules)) {
31
- setCachedRules(rules);
32
- const updated = updateSheet(rules);
33
- if (updated?.stylesheet) {
34
- styleTagRef.current.innerHTML = updated.stylesheet;
35
- setCreateStyles({ ...updated, updateSheet } as any);
36
- }
37
- }
38
- }, [cachedRules, rules, stylesheet, updateSheet]);
39
- return classes;
40
- }
package/src/types.ts DELETED
@@ -1,7 +0,0 @@
1
- import { Properties } from 'csstype';
2
-
3
- export interface SimpleStyleRules {
4
- [key: string]: Properties | SimpleStyleRules;
5
- }
6
-
7
- export type RenderableSimpleStyleRules = SimpleStyleRules & { [selector: string]: Properties[] };
@@ -1,20 +0,0 @@
1
- export function deepEqual<
2
- O1 extends Record<string | number | symbol, any>,
3
- O2 extends Record<string | number | symbol, any>,
4
- >(o1: O1, o2: O2): boolean {
5
- // We'll sort the keys, just in case the user kept things the same but the object is all wonky, order-wise
6
- const o1Keys = Object.keys(o1).sort();
7
- const o2Keys = Object.keys(o2).sort();
8
- if (o1Keys.length !== o2Keys.length) return false;
9
- if (o1Keys.some((key, i) => o2Keys[i] !== key)) return false;
10
- // Okay, the keys SHOULD be the same
11
- // so we need to test their values, recursively, to verify equality
12
- return o1Keys.reduce<boolean>((prev, key) => {
13
- if (!prev) return prev; // we've already failed equality checks here
14
- if (!(key in o2)) return false;
15
- if (typeof o1[key] !== 'object') {
16
- return prev && o1[key] === o2[key];
17
- }
18
- return prev && deepEqual(o1[key], o2[key]);
19
- }, true);
20
- }