@workday/canvas-kit-styling 10.0.0-alpha.538-next.0

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/LICENSE ADDED
@@ -0,0 +1,51 @@
1
+ Apache License, Version 2.0 Apache License Version 2.0, January 2004
2
+
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
9
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
10
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
11
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
12
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
13
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
14
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
15
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
16
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
17
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
18
+
19
+ 2. Grant of Copyright License.
20
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
21
+
22
+ 3. Grant of Patent License.
23
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
24
+
25
+ 4. Redistribution.
26
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
27
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
28
+
29
+ 5. Submission of Contributions.
30
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
31
+
32
+ 6. Trademarks.
33
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
34
+
35
+ 7. Disclaimer of Warranty.
36
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
37
+
38
+ 8. Limitation of Liability.
39
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
40
+
41
+ 9. Accepting Warranty or Additional Liability.
42
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
43
+
44
+ END OF TERMS AND CONDITIONS
45
+
46
+ ©2020. Workday, Inc. All rights reserved. Workday and the Workday logo are registered trademarks of Workday, Inc. All other brand and product names are trademarks or registered trademarks of their respective holders.
47
+
48
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
49
+ http://www.apache.org/licenses/LICENSE-2.0
50
+
51
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # Canvas Kit Styling
2
+
3
+ This package contains everything needed to create CSS styling. This styling package contains a
4
+ runtime for development and a static parsing process for build time. For more information, visit
5
+ https://workday.github.io/canvas-kit/?path=/docs/features-styling-welcome--page
@@ -0,0 +1,3 @@
1
+ export * from './lib/cs';
2
+ export * from './lib/slugify';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC"}
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./lib/cs"), exports);
14
+ __exportStar(require("./lib/slugify"), exports);
@@ -0,0 +1,216 @@
1
+ import React from 'react';
2
+ import { Keyframes, SerializedStyles, CSSObject } from '@emotion/serialize';
3
+ /**
4
+ * Style properties in a JavaScript camelCase. Everything Emotion allows is also
5
+ * allowed here.
6
+ */
7
+ export declare type StyleProps = undefined | boolean | number | string | Keyframes | SerializedStyles | CSSObject;
8
+ export declare type CS = string | Record<string, string>;
9
+ /**
10
+ * CSS variable map type. In developer/dynamic mode, we don't know what the hash is going to be. All
11
+ * variables will look like `--{hash}-{name}`. But the static optimizers generates the name based on
12
+ * the AST, so the `id` will be known. Instead of something like `--abc123-color`, the `ID` is set
13
+ * by the optimizer.
14
+ *
15
+ * For example:
16
+ * ```ts
17
+ * // dynamic
18
+ * const myVars = createVars('color') // type is `Record<'color', string>`
19
+ *
20
+ * // optimizer rewrites the code
21
+ * const myVars = createVars<'color', 'myVars'>('color')
22
+ * // type is now `{color: "--myVars-color"}`
23
+ *
24
+ * myVars.color // type is `--myVars-color`
25
+ * ```
26
+ *
27
+ * This is so optimized variables can be used directly by the static parser downstream. The variable
28
+ * names become statically analyzable.
29
+ */
30
+ export declare type CsVarsMap<T extends string, ID extends string | never> = [ID] extends [never] ? Record<T, string> : {
31
+ [K in T]: `--${ID}-${K}`;
32
+ };
33
+ export declare type CsVars<T extends string, ID extends string | never> = CsVarsMap<T, ID> & {
34
+ (input: Partial<Record<T, string>>): Record<T, string>;
35
+ };
36
+ /**
37
+ * Take a CSS Variable name and return a variable property
38
+ *
39
+ * ```ts
40
+ * const myVars = createVars('color')
41
+ *
42
+ * const myStyles = createStyles({
43
+ * color: cssVar(myVars.color) // color: 'var(--{hash}-color)'
44
+ * })
45
+ * ```
46
+ *
47
+ * It can also support an optional fallback. Fallbacks should only be used if it is reasonable to
48
+ * expect a CSS variable isn't defined.
49
+ * ```ts
50
+ * const myStyles = createStyles({
51
+ * color: cssVar(myVars.color, 'red') // color: 'var(--{hash}-color, red)'
52
+ * })
53
+ * ```
54
+ *
55
+ * If the project is set up for parsing with fallback files, a fallback will automatically be filled
56
+ * during the parsing phase. This is helpful for cases when CSS variables are expected, but not set
57
+ * in the environment.
58
+ */
59
+ export declare function cssVar(input: string, fallback?: string): string;
60
+ /**
61
+ * Create temporary CSS variables to use in components. The CSS variable names will
62
+ * be unique at runtime to avoid collisions. The return value is a function and a
63
+ * Map. The function can be used to pass in values from JavaScript. The function will
64
+ * return a map of variable keys to CSS Variable names.
65
+ *
66
+ * ```ts
67
+ * // creates a `color` and `background` CSS variable
68
+ * const myVars = createVars('color', 'background')
69
+ *
70
+ * // 'color' is a typed property. The type is `string`
71
+ * console.log(myVars.color) // `'var(--{hash}-color)'`
72
+ *
73
+ * // 'color' is a typed property. The type is `string?`
74
+ * // The returned object can be assigned to the `style` property of an element
75
+ * console.log(myVars({ color: 'red' })) // `{'--{hash}-color': 'red'}`
76
+ *
77
+ * const div = document.createElement('div')
78
+ * div.style = myVars({ color: 'red' }) // <div style="--{hash}-color: red;" />
79
+ * ```
80
+ */
81
+ export declare function createVars<T extends string, ID extends string>(input: {
82
+ id: ID;
83
+ args: T[];
84
+ }): CsVars<T, ID>;
85
+ export declare function createVars<T extends string>(...args: T[]): CsVars<T, never>;
86
+ declare type ModifierConfig = Record<string, Record<string, CS>>;
87
+ declare type ModifierValues<T extends ModifierConfig> = {
88
+ [P in keyof T]: keyof T[P];
89
+ };
90
+ declare type ModifierReturn<T extends ModifierConfig> = T & ((modifiers: Partial<ModifierValues<T>>) => string);
91
+ /**
92
+ * Creates a modifier function that takes in a modifier config and will return a CSS class name that
93
+ * matches the result. Modifiers can be thought as `if` or `switch` statements when conditionally
94
+ * changing the styles of a component based on props. This function can be thought of as a helper
95
+ * function that makes it easier to work with modifiers. Without it, you would have to implement
96
+ * if/switch/ternary for each option.
97
+ *
98
+ * ```tsx
99
+ * const myModifiers = createModifiers({
100
+ * // a modifier called 'size'
101
+ * size: {
102
+ * small: createStyles({ fontSize: 12 }),
103
+ * medium: createStyles({ fontSize: 14 })
104
+ * }
105
+ * })
106
+ *
107
+ * // with the modifier function
108
+ * myModifiers({ size: 'medium' }) // returns the medium class name
109
+ *
110
+ * // manually without the function
111
+ * size === 'small' ? myModifiers.size.small : size === 'medium' ? myModifiers.size.medium : ''
112
+ * ```
113
+ */
114
+ export declare function createModifiers<T extends ModifierConfig>(input: T): ModifierReturn<T>;
115
+ /**
116
+ * All acceptable values of the `cs` prop. It can be a CSS class name, any CSS properties, an object
117
+ * with a `className` and `styles`, or an array of these
118
+ */
119
+ export declare type CSToPropsInput = undefined | CS | CsToPropsReturn | React.CSSProperties | CSToPropsInput[];
120
+ export declare type CsToPropsReturn = {
121
+ className?: string;
122
+ style?: React.CSSProperties;
123
+ };
124
+ /**
125
+ * A function that takes in a single input, or an array. The type of the input is either:
126
+ *
127
+ * - `string` - it represents a CSS class name
128
+ * - `undefined` - there is no value. This is provided for convenience for developers to not have to
129
+ * filter out undefined
130
+ * - `{--{hash}-{varName}: {value}}` - a `Map` of CSS variable to values
131
+ * - `{style: ..., className: ...}` an object already returned by another `csToProps` function call
132
+ * (for nesting)
133
+ * - An array containing any of the above. This will recurse over each entry to produce a single,
134
+ * reduced `{style: ..., className: ...}` object
135
+ * @param input
136
+ * @returns
137
+ */
138
+ export declare function csToProps(input: CSToPropsInput): CsToPropsReturn;
139
+ export interface CSProps {
140
+ /** The `cs` prop takes in a single value or an array of values. You can pass the CSS class name
141
+ * returned by {@link createStyles}, or the result of {@link createVars} and
142
+ * {@link createModifiers}. If you're extending a component already using `cs`, you can merge that
143
+ * prop in as well.
144
+ *
145
+ * ```tsx
146
+ * cs={[
147
+ * cs, // from the prop list
148
+ * myStyles,
149
+ * myModifiers({ size: 'medium' }),
150
+ * myVars({ backgroundColor: 'red' })
151
+ * ]}
152
+ * ```
153
+ */
154
+ cs?: CSToPropsInput;
155
+ }
156
+ /**
157
+ * Creates CSS styles based on object-style input. It has a side-effect of adding CSS to the page
158
+ * and will return a space-delimitated string of CSS class names meant to be added to an element.
159
+ *
160
+ * It can take a number of inputs of various types. The simplest is object-styles.
161
+ *
162
+ * ```ts
163
+ * const myStyles = createStyles({
164
+ * backgroundColor: 'red'
165
+ * })
166
+ * ```
167
+ *
168
+ * The `createStyles` function is curried into 2 parts. The first function could be done at build
169
+ * time. The returned function combines CSS class names and will remain as a small runtime.
170
+ *
171
+ * > **Note:** The order of calling `createStyles` is important. Each call will make a single CSS
172
+ * > class selector and will be injected into the document's
173
+ * > [StyleSheetList](https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList). Style
174
+ * > properties will be merge by the rules of [CSS
175
+ * > specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). If two selectors
176
+ * > have the same specificity, the last defined wins. Always make sure that the properties you want
177
+ * > to win are last in your file.
178
+ */
179
+ export declare function createStyles(...args: (StyleProps | string)[]): string;
180
+ /**
181
+ * React utility function to apply CSS class names and dynamic CSS variables
182
+ *
183
+ * ```tsx
184
+ * const MyComponent = (props: any) => {
185
+ * return <div {...handleCsProp(props)} />
186
+ * }
187
+ * ```
188
+ *
189
+ * It will return an object with `className` and `style` attributes. If a `className` is provided to
190
+ * the component, it will merge the class names. If a `style` is provided to the component, it will
191
+ * merge the styles.
192
+ *
193
+ * ```tsx
194
+ * const vars = createVars('background')
195
+ * const styles = createStyles({
196
+ * color: vars.color
197
+ * })
198
+ * <MyComponent
199
+ * className="foobar"
200
+ * style={{ padding: 10 }}
201
+ * cs={styles}
202
+ * />
203
+ *
204
+ * // Output
205
+ * <div
206
+ * className="foobar {hashedClassName}"
207
+ * style="padding: 10px; --{hash}-background: red;"
208
+ * />
209
+ * ```
210
+ */
211
+ export declare function handleCsProp<T extends CSProps & {
212
+ className?: string | undefined;
213
+ style?: React.CSSProperties | undefined;
214
+ }>({ cs, style, className, ...props }: T): Omit<T, "cs">;
215
+ export {};
216
+ //# sourceMappingURL=cs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cs.d.ts","sourceRoot":"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rE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,YAAY,CAC1B,CAAC,SAAS,OAAO,GAAG;IAClB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE/B,KAAK,CAAC,EAAE,KAAK,CAAC,aAAa,GAAG,SAAS,CAAC;CACzC,EACD,EAAC,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,KAAK,EAAC,EAAE,CAAC,iBAKpC"}
@@ -0,0 +1,255 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleCsProp = exports.createStyles = exports.csToProps = exports.createModifiers = exports.createVars = exports.cssVar = void 0;
4
+ const uniqueId_1 = require("./uniqueId");
5
+ // eslint-disable-next-line @emotion/no-vanilla
6
+ const css_1 = require("@emotion/css");
7
+ const serialize_1 = require("@emotion/serialize");
8
+ const slugify_1 = require("./slugify");
9
+ function convertProperty(value) {
10
+ // Handle the case where the value is a variable without the `var()` wrapping function. It happens
11
+ // enough that it makes sense to automatically wrap.
12
+ if (typeof value === 'string' && value.startsWith('--')) {
13
+ return `var(${value})`;
14
+ }
15
+ return value;
16
+ }
17
+ /**
18
+ * Walks through all the properties and values of a style and converts properties and/or values that
19
+ * need special processing. An example might be using a CSS variable without a `var()` wrapping.
20
+ */
21
+ function convertAllProperties(obj) {
22
+ if (typeof obj === 'object') {
23
+ const converted = {};
24
+ for (const key in obj) {
25
+ if (obj.hasOwnProperty(key)) {
26
+ converted[key] = convertAllProperties(obj[key]);
27
+ }
28
+ }
29
+ return converted;
30
+ }
31
+ return convertProperty(obj);
32
+ }
33
+ /**
34
+ * Take a CSS Variable name and return a variable property
35
+ *
36
+ * ```ts
37
+ * const myVars = createVars('color')
38
+ *
39
+ * const myStyles = createStyles({
40
+ * color: cssVar(myVars.color) // color: 'var(--{hash}-color)'
41
+ * })
42
+ * ```
43
+ *
44
+ * It can also support an optional fallback. Fallbacks should only be used if it is reasonable to
45
+ * expect a CSS variable isn't defined.
46
+ * ```ts
47
+ * const myStyles = createStyles({
48
+ * color: cssVar(myVars.color, 'red') // color: 'var(--{hash}-color, red)'
49
+ * })
50
+ * ```
51
+ *
52
+ * If the project is set up for parsing with fallback files, a fallback will automatically be filled
53
+ * during the parsing phase. This is helpful for cases when CSS variables are expected, but not set
54
+ * in the environment.
55
+ */
56
+ function cssVar(input, fallback) {
57
+ return fallback
58
+ ? `var(${input}, ${fallback.startsWith('--') ? `var(${fallback})` : fallback})`
59
+ : `var(${input})`;
60
+ }
61
+ exports.cssVar = cssVar;
62
+ function createVars(...args) {
63
+ const id = args[0].id || uniqueId_1.generateUniqueId(); //?
64
+ // eslint-disable-next-line no-param-reassign
65
+ args = args[0].args || args;
66
+ const result = (input) => {
67
+ const vars = {};
68
+ args.forEach(key => {
69
+ if (input[key]) {
70
+ // @ts-ignore TS complains about `key` not in object `{}`
71
+ vars[result[key]] = input[key];
72
+ }
73
+ });
74
+ return vars;
75
+ };
76
+ args.forEach(key => {
77
+ // @ts-ignore
78
+ result[key] = `--${id}-${slugify_1.slugify(key)}`;
79
+ }, {});
80
+ return result;
81
+ }
82
+ exports.createVars = createVars;
83
+ /**
84
+ * Creates a modifier function that takes in a modifier config and will return a CSS class name that
85
+ * matches the result. Modifiers can be thought as `if` or `switch` statements when conditionally
86
+ * changing the styles of a component based on props. This function can be thought of as a helper
87
+ * function that makes it easier to work with modifiers. Without it, you would have to implement
88
+ * if/switch/ternary for each option.
89
+ *
90
+ * ```tsx
91
+ * const myModifiers = createModifiers({
92
+ * // a modifier called 'size'
93
+ * size: {
94
+ * small: createStyles({ fontSize: 12 }),
95
+ * medium: createStyles({ fontSize: 14 })
96
+ * }
97
+ * })
98
+ *
99
+ * // with the modifier function
100
+ * myModifiers({ size: 'medium' }) // returns the medium class name
101
+ *
102
+ * // manually without the function
103
+ * size === 'small' ? myModifiers.size.small : size === 'medium' ? myModifiers.size.medium : ''
104
+ * ```
105
+ */
106
+ function createModifiers(input) {
107
+ const modifierFn = (modifiers) => {
108
+ return Object.keys(modifiers)
109
+ .filter(key => input[key] && input[key][modifiers[key]])
110
+ .map(key => input[key][modifiers[key]])
111
+ .join(' ');
112
+ };
113
+ Object.keys(input).forEach(key => {
114
+ // @ts-ignore TypeScript makes it a pain to deal with index types
115
+ modifierFn[key] = input[key];
116
+ });
117
+ return modifierFn;
118
+ }
119
+ exports.createModifiers = createModifiers;
120
+ function isCsPropsReturn(input) {
121
+ return input.hasOwnProperty('style') || input.hasOwnProperty('className');
122
+ }
123
+ /**
124
+ * A function that takes in a single input, or an array. The type of the input is either:
125
+ *
126
+ * - `string` - it represents a CSS class name
127
+ * - `undefined` - there is no value. This is provided for convenience for developers to not have to
128
+ * filter out undefined
129
+ * - `{--{hash}-{varName}: {value}}` - a `Map` of CSS variable to values
130
+ * - `{style: ..., className: ...}` an object already returned by another `csToProps` function call
131
+ * (for nesting)
132
+ * - An array containing any of the above. This will recurse over each entry to produce a single,
133
+ * reduced `{style: ..., className: ...}` object
134
+ * @param input
135
+ * @returns
136
+ */
137
+ function csToProps(input) {
138
+ // input is a string, so it must only be a class name
139
+ if (typeof input === 'string') {
140
+ return { className: input };
141
+ }
142
+ // input isn't defined, so we'll return an empty object
143
+ if (!input) {
144
+ return {};
145
+ }
146
+ // A nested `csToProps`, we'll simply return with no modification
147
+ if (isCsPropsReturn(input)) {
148
+ return input;
149
+ }
150
+ // At this point, `input` is either an array or a `Record<T, string>`. If it isn't an array, it
151
+ // must be a style object for setting CSS variables. So set the `style` attribute
152
+ if (!Array.isArray(input)) {
153
+ return { style: input };
154
+ }
155
+ // An array. it is the only thing left. We iterate and recurse over the array to produce a single
156
+ // object with `style` and `className` attributes to spread on an element
157
+ return input.map(csToProps).reduce((result, val) => {
158
+ return {
159
+ className: [result.className, val.className].filter(v => v).join(' '),
160
+ style: { ...result.style, ...val.style },
161
+ };
162
+ }, {});
163
+ }
164
+ exports.csToProps = csToProps;
165
+ /**
166
+ * Creates CSS styles based on object-style input. It has a side-effect of adding CSS to the page
167
+ * and will return a space-delimitated string of CSS class names meant to be added to an element.
168
+ *
169
+ * It can take a number of inputs of various types. The simplest is object-styles.
170
+ *
171
+ * ```ts
172
+ * const myStyles = createStyles({
173
+ * backgroundColor: 'red'
174
+ * })
175
+ * ```
176
+ *
177
+ * The `createStyles` function is curried into 2 parts. The first function could be done at build
178
+ * time. The returned function combines CSS class names and will remain as a small runtime.
179
+ *
180
+ * > **Note:** The order of calling `createStyles` is important. Each call will make a single CSS
181
+ * > class selector and will be injected into the document's
182
+ * > [StyleSheetList](https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList). Style
183
+ * > properties will be merge by the rules of [CSS
184
+ * > specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). If two selectors
185
+ * > have the same specificity, the last defined wins. Always make sure that the properties you want
186
+ * > to win are last in your file.
187
+ */
188
+ function createStyles(...args) {
189
+ return args
190
+ .map(input => {
191
+ if (typeof input === 'string') {
192
+ return input;
193
+ }
194
+ const convertedStyles = convertAllProperties(input);
195
+ // We want to call `serializeStyles` directly and ignore the hash generated so we can have
196
+ // more predictable style merging. If 2 different files define the same style properties, the
197
+ // hash will be the same and using the default hash functionality of Emotion will mean the
198
+ // merge order will be unpredictable. For example, `BaseButton` and `TertiaryButton` define
199
+ // different modifiers for padding. The BaseButton's `extraSmall` modifier contains the same
200
+ // styling as TertiaryButton's `large` modifier. Emotion would hash these two declarations as
201
+ // the same hash and only inject the one from `BaseButton`. If `TertiaryButton` defines
202
+ // `padding` in its base styles, and uses the large size modifier, the base padding will
203
+ // override the `TertiaryButton` `large` size modifier because `BaseButton.small` modifier was
204
+ // injected into the document's style sheets before `TertiaryButton.base` styles. This is due
205
+ // to CSS specificity. If everything has the same specificity, last defined wins. More info:
206
+ // https://codesandbox.io/s/stupefied-bartik-9c2jtd?file=/src/App.tsx
207
+ const { styles } = serialize_1.serializeStyles([convertedStyles]);
208
+ // use `css.call()` instead of `css()` to trick Emotion's babel plugin to not rewrite our code
209
+ // to remove our generated Id for the name:
210
+ // https://github.com/emotion-js/emotion/blob/f3b268f7c52103979402da919c9c0dd3f9e0e189/packages/babel-plugin/src/utils/transform-expression-with-styles.js#L81-L82
211
+ // Without this "fix", anyone using the Emotion babel plugin would get different results than
212
+ // intended when styles are merged.
213
+ return css_1.css.call(null, { name: uniqueId_1.generateUniqueId(), styles }); //?
214
+ })
215
+ .join(' ');
216
+ }
217
+ exports.createStyles = createStyles;
218
+ /**
219
+ * React utility function to apply CSS class names and dynamic CSS variables
220
+ *
221
+ * ```tsx
222
+ * const MyComponent = (props: any) => {
223
+ * return <div {...handleCsProp(props)} />
224
+ * }
225
+ * ```
226
+ *
227
+ * It will return an object with `className` and `style` attributes. If a `className` is provided to
228
+ * the component, it will merge the class names. If a `style` is provided to the component, it will
229
+ * merge the styles.
230
+ *
231
+ * ```tsx
232
+ * const vars = createVars('background')
233
+ * const styles = createStyles({
234
+ * color: vars.color
235
+ * })
236
+ * <MyComponent
237
+ * className="foobar"
238
+ * style={{ padding: 10 }}
239
+ * cs={styles}
240
+ * />
241
+ *
242
+ * // Output
243
+ * <div
244
+ * className="foobar {hashedClassName}"
245
+ * style="padding: 10px; --{hash}-background: red;"
246
+ * />
247
+ * ```
248
+ */
249
+ function handleCsProp({ cs, style, className, ...props }) {
250
+ return {
251
+ ...csToProps([cs, className, style]),
252
+ ...props,
253
+ };
254
+ }
255
+ exports.handleCsProp = handleCsProp;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Function that takes a string and returns a "slug" which can be used in HTML
3
+ */
4
+ export declare function slugify(input: string): string;
5
+ //# sourceMappingURL=slugify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"slugify.d.ts","sourceRoot":"","sources":["../../../lib/slugify.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAU7C"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.slugify = void 0;
4
+ /**
5
+ * Function that takes a string and returns a "slug" which can be used in HTML
6
+ */
7
+ function slugify(input) {
8
+ return input
9
+ .trim()
10
+ .replace(/[\.\s_-]+/g, '-')
11
+ .replace(/[^\w\s-]/g, '')
12
+ .replace(/([A-Z])/g, m => {
13
+ return '-' + m.toLowerCase();
14
+ })
15
+ .replace(/^-+|-+$/g, '')
16
+ .toLowerCase();
17
+ }
18
+ exports.slugify = slugify;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Generates a unique and HTML5 compliant identifier every time it is called. Internally it uses a 4
3
+ * character random seed starting with a letter. This seed is unique to each instance of this
4
+ * package meaning different versions of Canvas Kit on the page will have a different seed. Each
5
+ * call will use a Base 36 string (10 numbers + 26 letters) based on an incremented number. The
6
+ * incremented number always starts at 0 and can be reset for testing purposes using
7
+ * [resetUniqueIdCount](#resetuniqueidcount). [setUniqueSeed](#setuniqueseed) can also be used for
8
+ * testing or server side rendering to get the same results during hydration.
9
+ */
10
+ export declare const generateUniqueId: () => string;
11
+ /**
12
+ * Update the seed used by the id generator. This is useful for snapshot tests to help stabilize ids
13
+ * generated each run. This could also be used for server-side hydration - if you choose the same
14
+ * seed for server and set that on the client before components are rendered, the ids generated will
15
+ * be the same.
16
+ * @example
17
+ * // set in a script tag from the server
18
+ * setSeed(window.__ID_SEED); // set in a script tag from the server
19
+ *
20
+ * // jest setup
21
+ * before(() => {
22
+ * setSeed('a')
23
+ * })
24
+ */
25
+ export declare const setUniqueSeed: (s: string) => void;
26
+ /**
27
+ * This should only be called for tests in an `beforeEach`
28
+ */
29
+ export declare const resetUniqueIdCount: () => void;
30
+ //# sourceMappingURL=uniqueId.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uniqueId.d.ts","sourceRoot":"","sources":["../../../lib/uniqueId.ts"],"names":[],"mappings":"AASA;;;;;;;;GAQG;AACH,eAAO,MAAM,gBAAgB,cAAkC,CAAC;AAEhE;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,aAAa,MAAO,MAAM,SAEtC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB,YAE9B,CAAC"}