@stylexjs/stylex 0.1.0-beta.7 → 0.2.0-beta.11

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/README.md ADDED
@@ -0,0 +1,245 @@
1
+ # @stylexjs/stylex
2
+
3
+ ## Installation
4
+
5
+ To start playing with StyleX without having to set up any build settings you can install just two packages:
6
+
7
+ ```sh
8
+ npm install --save @stylexjs/stylex
9
+ ```
10
+
11
+ ### Compiler
12
+
13
+ StyleX is designed to extract styles to a static CSS style sheet during an app's build process. StyleX provides a Babel plugin along with plugin integrations for Webpack, Rollup and NextJS.
14
+
15
+ ```sh
16
+ npm install --save-dev @stylexjs/babel-plugin
17
+ ```
18
+
19
+ For more information on working with the compiler, please see the documentation for [`@stylexjs/babel-plugin`](https://www.npmjs.com/package/@stylexjs/babel-plugin).
20
+
21
+ ### Runtime compiler
22
+
23
+ The runtime compiler should only be used for development and testing purposes.
24
+
25
+ ```sh
26
+ npm install --save-dev @stylexjs/dev-runtime
27
+ ```
28
+
29
+ Import `@stylexjs/dev-runtime` in your JS entry-point to set everything up.
30
+
31
+ ```ts
32
+ import inject from '@stylexjs/dev-runtime';
33
+
34
+ if (process.env.NODE_ENV !== 'production') {
35
+ inject({
36
+ // configuration options
37
+ classNamePrefix: 'x-',
38
+ dev: true,
39
+ test: false,
40
+ });
41
+ }
42
+ ```
43
+
44
+ For more information on working with the compiler, please see the documentation for [`@stylexjs/dev-runtime`](https://www.npmjs.com/package/@stylexjs/dev-runtime).
45
+
46
+ ## API
47
+
48
+ ### stylex.create()
49
+
50
+ Styles are defined as a map of CSS rules using `stylex.create()`. In the example below, there are 2 different CSS rules. The names "root" and "highlighted" are arbitrary names given to the rules.
51
+
52
+ ```tsx
53
+ import stylex from '@stylexjs/stylex';
54
+
55
+ const styles = stylex.create({
56
+ root: {
57
+ width: '100%',
58
+ color: 'rgb(60,60,60)',
59
+ },
60
+ highlighted: {
61
+ color: 'yellow',
62
+ }
63
+ });
64
+ ```
65
+
66
+ Pseudo-classes and Media Queries can be nested within style definitions:
67
+
68
+ ```tsx
69
+ import stylex from '@stylexjs/stylex';
70
+
71
+ const styles = stylex.create({
72
+ root: {
73
+ width: '100%',
74
+ color: 'rgb(60,60,60)',
75
+ '@media (min-width: 800px)': {
76
+ maxWidth: '800px',
77
+ },
78
+ },
79
+ highlighted: {
80
+ color: 'yellow',
81
+ ':hover': {
82
+ opacity: '0.9',
83
+ }
84
+ }
85
+ });
86
+ ```
87
+
88
+ The compiler will extract the rules to CSS and replace the rules in the source code with a "compiled style" object.
89
+
90
+ ### stylex.spread()
91
+
92
+ Applying style rules to specific elements is done using `stylex.spread`. Each argument to this function must be a reference to a compiled style object, or an array of compiled style objects. The function merges styles from left to right.
93
+
94
+ ```tsx
95
+ <div {...stylex.spread(styles.root, styles.highlighted)} />
96
+ ```
97
+
98
+ The `stylex.spread` function returns React props as required to render an element. StyleX styles can still be passed to other components via props, but only the components rendering host platform elements will use `stylex.spread()`. For example:
99
+
100
+ ```tsx
101
+ const styles = stylex.create({
102
+ internalRoot: {
103
+ padding: 10
104
+ },
105
+ exportedRoot: {
106
+ position: 'relative'
107
+ }
108
+ });
109
+
110
+ function InternalComponent(props) {
111
+ return <div {...props} {...stylex.spread([ styles.internalRoot, props.style ])} />
112
+ }
113
+
114
+ export function ExportedComponent(props) {
115
+ return <InternalComponent style={[ styles.exportedRoot, props.style ]} />
116
+ }
117
+ ```
118
+
119
+ Styles can be conditionally included using standard JavaScript.
120
+
121
+ ```tsx
122
+ <div {...stylex.spread(styles.root, isHighlighted && styles.highlighted)} />
123
+ ```
124
+
125
+ And the local merging of styles can be used to control the relative priority of rules. For example, to allow a component's local styles to take priority over style property values passed in via props.
126
+
127
+ ```tsx
128
+ <div {...stylex.spread(props.style, styles.root)} />
129
+ ```
130
+
131
+ You can even mix compiled styles with inline styles
132
+
133
+ ```tsx
134
+ <div {...stylex.spread(styles.root, { opacity })} />
135
+ ```
136
+
137
+ ### stylex.firstThatWorks()
138
+
139
+ Defining fallback styles is done with `stylex.firstThatWorks()`. This is useful for engines that may not support a specific style property.
140
+
141
+ ```tsx
142
+ import stylex from '@stylexjs/stylex';
143
+
144
+ const styles = stylex.create({
145
+ header: {
146
+ position: stylex.firstThatWorks('sticky', '-webkit-sticky', 'fixed'),
147
+ },
148
+ });
149
+ ```
150
+
151
+ This is equivalent to defining CSS as follows:
152
+
153
+ ```css
154
+ .header {
155
+ position: fixed;
156
+ position: -webkit-sticky;
157
+ position: sticky;
158
+ }
159
+ ```
160
+
161
+ ## Types
162
+
163
+ StyleX comes with full support for Static Types.
164
+
165
+ ### `XStyle<>`
166
+
167
+ The most common type you might need to use is `XStyle<>`. This lets you accept an object of arbitrary StyleX styles.
168
+
169
+ ```tsx
170
+ type Props = {
171
+ ...
172
+ style?: XStyle<>,
173
+ };
174
+
175
+ function MyComponent({style, ...}: Props) {
176
+ return (
177
+ <div {...stylex.spread(localStyles.foo, localStyles.bar, style)} />
178
+ );
179
+ }
180
+ ```
181
+
182
+ ### `XStyleWithout<>`
183
+
184
+ To disallow specific style properties, use the `XStyleWithout<>` type.
185
+
186
+ ```tsx
187
+ type Props = {
188
+ // ...
189
+ style?: XStyleWithout<{
190
+ postion: unknown,
191
+ display: unknown
192
+ }>
193
+ };
194
+ ```
195
+
196
+ ### `XStyleValue<>`
197
+
198
+ To accept specific style properties only, use the `XStyle<{...}>` and `XStyleValue` types. For example, to allow only color-related style props:
199
+
200
+ ```tsx
201
+ type Props = {
202
+ // ...
203
+ style?: XStyle<{
204
+ color?: StyleXValue,
205
+ backgroundColor?: StyleXValue,
206
+ borderColor?: StyleXValue,
207
+ borderTopColor?: StyleXValue,
208
+ borderEndColor?: StyleXValue,
209
+ borderBottomColor?: StyleXValue,
210
+ borderStartColor?: StyleXValue,
211
+ }>,
212
+ };
213
+ ```
214
+
215
+ ### `XStyleValueFor<>`
216
+
217
+ To limit the possible values for style properties, use the `XStyleValueFor<>` type. Pass in a type argument with a union of literal types that provide the set of possible values that the style property can have. For example, if a component should accept `marginTop` but only accept one of `0`, `4`, or `8` pixels as values.
218
+
219
+ ```tsx
220
+ type Props = {
221
+ ...
222
+ style?: XStyle<{
223
+ marginTop: XStyleValueFor<0 | 4 | 8>
224
+ }>,
225
+ };
226
+ ```
227
+
228
+ ## How StyleX works
229
+
230
+ StyleX produces atomic styles, which means that each CSS rule contains only a single declaration and uses a unique class name. For example:
231
+
232
+ ```tsx
233
+ import stylex from '@stylexjs/stylex';
234
+
235
+ const styles = stylex.create({
236
+ root: {
237
+ width: '100%',
238
+ color: 'red',
239
+ }
240
+ }
241
+ ```
242
+
243
+ From this code, StyleX will generate 2 classes. One for the `width: '100%'` declaration, and one for the `color: 'red'` declaration. If you use the declaration `width: '100%'` anywhere else in your application, it will *reuse the same CSS class* rather than creating a new one.
244
+
245
+ One of the benefits of this approach is that the generated CSS file grows *logarithmically* as you add new styled components to your app. As more style declarations are added to components, they are more likely to already be in use elsehwere in the app. As a result of this CSS optimization, the generated CSS style sheet for an app is usually small enough to be contained in a single file and used across routes, avoiding style recalculation and layout thrashing as users navigate through your app.
@@ -15,7 +15,8 @@ Object.defineProperty(exports, "__esModule", {
15
15
  exports.styleSheet = exports.StyleXSheet = void 0;
16
16
  var _invariant = _interopRequireDefault(require("invariant"));
17
17
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
18
+ // import rtlDetect from 'rtl-detect';
19
+
19
20
  const LIGHT_MODE_CLASS_NAME = '__fb-light-mode';
20
21
  const DARK_MODE_CLASS_NAME = '__fb-dark-mode';
21
22
  /**
@@ -62,6 +63,8 @@ const VARIABLE_MATCH = /var\(--(.*?)\)/g;
62
63
  * CSS rules.
63
64
  */
64
65
  class StyleXSheet {
66
+ static LIGHT_MODE_CLASS_NAME = LIGHT_MODE_CLASS_NAME;
67
+ static DARK_MODE_CLASS_NAME = DARK_MODE_CLASS_NAME;
65
68
  constructor(opts) {
66
69
  this.tag = null;
67
70
  this.injected = false;
@@ -265,8 +268,6 @@ class StyleXSheet {
265
268
  * Adds an ancestor selector in a media-query-aware way.
266
269
  */
267
270
  exports.StyleXSheet = StyleXSheet;
268
- _defineProperty(StyleXSheet, "LIGHT_MODE_CLASS_NAME", LIGHT_MODE_CLASS_NAME);
269
- _defineProperty(StyleXSheet, "DARK_MODE_CLASS_NAME", DARK_MODE_CLASS_NAME);
270
271
  function addAncestorSelector(selector, ancestorSelector) {
271
272
  if (!selector.startsWith('@')) {
272
273
  return `${ancestorSelector} ${selector}`;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CSSCustomPropertyValue = void 0;
7
+ exports.isCustomPropertyValue = isCustomPropertyValue;
8
+ /**
9
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
10
+ *
11
+ * This source code is licensed under the MIT license found in the
12
+ * LICENSE file in the root directory of this source tree.
13
+ *
14
+ *
15
+ */
16
+
17
+ const CUSTOM_PROPERTY_REGEX = /^var\(--(.+)\)$/;
18
+ function camelize(s) {
19
+ return s.replace(/-./g, x => x.toUpperCase()[1]);
20
+ }
21
+ function isCustomPropertyValue(value) {
22
+ return typeof value === 'string' && CUSTOM_PROPERTY_REGEX.test(value);
23
+ }
24
+ class CSSCustomPropertyValue {
25
+ constructor(value) {
26
+ const found = value.match(CUSTOM_PROPERTY_REGEX);
27
+ if (found == null) {
28
+ throw new Error('[stylex]: Unable to find custom property reference in input string');
29
+ }
30
+ const [, kebabCasePropName] = found;
31
+ this.name = camelize(kebabCasePropName);
32
+ }
33
+ }
34
+ exports.CSSCustomPropertyValue = CSSCustomPropertyValue;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CSSLengthUnitValue = void 0;
7
+ /**
8
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
9
+ *
10
+ * This source code is licensed under the MIT license found in the
11
+ * LICENSE file in the root directory of this source tree.
12
+ *
13
+ *
14
+ */
15
+
16
+ const LENGTH_REGEX = /^([0-9]*[.]?[0-9]+)(em|px|rem|vh|vmax|vmin|vw)$/;
17
+ // TODO: this only works on simple values
18
+ class CSSLengthUnitValue {
19
+ static parse(inp) {
20
+ const match = inp.match(LENGTH_REGEX);
21
+ if (match == null) {
22
+ return null;
23
+ }
24
+ const [, value, unit] = match;
25
+ const parsedValue = parseFloat(value);
26
+ // $FlowFixMe
27
+ return new CSSLengthUnitValue(parsedValue, unit);
28
+ }
29
+ constructor(value, unit) {
30
+ this.value = value;
31
+ this.unit = unit;
32
+ }
33
+ resolvePixelValue(viewportWidth, viewportHeight, fontScale, inheritedFontSize) {
34
+ const unit = this.unit;
35
+ const value = this.value;
36
+ const valuePercent = value / 100;
37
+ switch (unit) {
38
+ case 'em':
39
+ {
40
+ if (inheritedFontSize == null) {
41
+ return fontScale * 16 * value;
42
+ } else {
43
+ return inheritedFontSize * value;
44
+ }
45
+ }
46
+ case 'px':
47
+ {
48
+ return value;
49
+ }
50
+ case 'rem':
51
+ {
52
+ return fontScale * 16 * value;
53
+ }
54
+ case 'vh':
55
+ {
56
+ return viewportHeight * valuePercent;
57
+ }
58
+ case 'vmin':
59
+ {
60
+ return Math.min(viewportWidth, viewportHeight) * valuePercent;
61
+ }
62
+ case 'vmax':
63
+ {
64
+ return Math.max(viewportWidth, viewportHeight) * valuePercent;
65
+ }
66
+ case 'vw':
67
+ {
68
+ return viewportWidth * valuePercent;
69
+ }
70
+ default:
71
+ {
72
+ console.error(`[stylex]: Unsupported unit of "${unit}"`);
73
+ return 0;
74
+ }
75
+ }
76
+ }
77
+ }
78
+ exports.CSSLengthUnitValue = CSSLengthUnitValue;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.CSSMediaQuery = void 0;
7
+ var _cssMediaquery = _interopRequireDefault(require("css-mediaquery"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ /**
10
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
11
+ *
12
+ * This source code is licensed under the MIT license found in the
13
+ * LICENSE file in the root directory of this source tree.
14
+ *
15
+ *
16
+ */
17
+
18
+ const MQ_PREFIX = '@media';
19
+ class CSSMediaQuery {
20
+ static isMediaQueryString(inp) {
21
+ return inp.startsWith(MQ_PREFIX);
22
+ }
23
+ static resolveMediaQueries(styleObj, matchObj) {
24
+ const mediaQueries = [];
25
+ const result = {};
26
+
27
+ // collect all the media queries
28
+ for (const [key, value] of Object.entries(styleObj)) {
29
+ if (value instanceof CSSMediaQuery) {
30
+ mediaQueries.push(value);
31
+ } else {
32
+ result[key] = value;
33
+ }
34
+ }
35
+
36
+ // check the media queries to see if any apply and if they do,
37
+ // merge their styles into the result
38
+ if (mediaQueries.length > 0) {
39
+ for (const mqInst of mediaQueries) {
40
+ const unresolvedMatchedStyle = mqInst.resolve(matchObj);
41
+ const resolvedMatchedStyle = this.resolveMediaQueries(unresolvedMatchedStyle, matchObj);
42
+ for (const propName in resolvedMatchedStyle) {
43
+ result[propName] = resolvedMatchedStyle[propName];
44
+ }
45
+ }
46
+ }
47
+ return result;
48
+ }
49
+ constructor(query, matchedStyle) {
50
+ this.query = query.replace(MQ_PREFIX, '');
51
+ this.matchedStyle = matchedStyle;
52
+ }
53
+ resolve(matchObject) {
54
+ const {
55
+ width,
56
+ height,
57
+ direction
58
+ } = matchObject;
59
+ const matches = _cssMediaquery.default.match(this.query, {
60
+ width,
61
+ height,
62
+ orientation: width > height ? 'landscape' : 'portrait',
63
+ 'aspect-ratio': width / height,
64
+ direction: direction
65
+ });
66
+ return matches ? this.matchedStyle : {};
67
+ }
68
+ }
69
+ exports.CSSMediaQuery = CSSMediaQuery;