@linaria/react 3.0.0-beta.15 → 3.0.0-beta.19

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/CHANGELOG.md CHANGED
@@ -3,6 +3,43 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.0.0-beta.19](https://github.com/callstack/linaria/compare/v3.0.0-beta.18...v3.0.0-beta.19) (2022-06-03)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **react:** support UpperCamelCase custom elements [#968](https://github.com/callstack/linaria/issues/968) ([#970](https://github.com/callstack/linaria/issues/970)) ([59800db](https://github.com/callstack/linaria/commit/59800dba540e09c0c43b1f0ec1d4b2c46d8a4672))
12
+
13
+
14
+ ### Features
15
+
16
+ * **atomic:** add support for atomic using styled API ([#966](https://github.com/callstack/linaria/issues/966)) ([f59860b](https://github.com/callstack/linaria/commit/f59860b09c5f91b0423dbf188e5f8aaaef38a6b5))
17
+ * **babel:** api for custom tags ([#976](https://github.com/callstack/linaria/issues/976)) ([3285ccc](https://github.com/callstack/linaria/commit/3285ccc1d00449b78b3fc74087528cd38cbdd116))
18
+ * **babel:** new way for detecting tag imports ([#974](https://github.com/callstack/linaria/issues/974)) ([3305cfb](https://github.com/callstack/linaria/commit/3305cfb0c0f65abdacceeb7e6bad118c59f7d551))
19
+
20
+
21
+
22
+
23
+
24
+ # [3.0.0-beta.18](https://github.com/callstack/linaria/compare/v3.0.0-beta.17...v3.0.0-beta.18) (2022-04-01)
25
+
26
+ **Note:** Version bump only for package @linaria/react
27
+
28
+
29
+
30
+
31
+
32
+ # [3.0.0-beta.17](https://github.com/callstack/linaria/compare/v3.0.0-beta.16...v3.0.0-beta.17) (2021-12-27)
33
+
34
+
35
+ ### Bug Fixes
36
+
37
+ * **react:** refactored types for styled function (fixes [#872](https://github.com/callstack/linaria/issues/872)) ([#887](https://github.com/callstack/linaria/issues/887)) ([7b8b129](https://github.com/callstack/linaria/commit/7b8b12937f9a0d1730d908e7cebad1684ccb03c3))
38
+
39
+
40
+
41
+
42
+
6
43
  # [3.0.0-beta.15](https://github.com/callstack/linaria/compare/v3.0.0-beta.14...v3.0.0-beta.15) (2021-11-29)
7
44
 
8
45
 
package/esm/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["default","styled"],"mappings":"AAAA,SAASA,OAAO,IAAIC,MAApB,QAAkC,UAAlC","sourcesContent":["export { default as styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\n"],"file":"index.js"}
1
+ {"version":3,"file":"index.js","names":["default","styled"],"sources":["../src/index.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,MAApB,QAAkC,UAAlC"}
@@ -0,0 +1,190 @@
1
+ import BaseProcessor from '@linaria/core/processors/BaseProcessor';
2
+ export function hasMeta(value) {
3
+ return typeof value === 'object' && value !== null && '__linaria' in value;
4
+ }
5
+
6
+ const isNotNull = x => x !== null;
7
+
8
+ const singleQuotedStringLiteral = value => ({
9
+ type: 'StringLiteral',
10
+ value,
11
+ extra: {
12
+ rawValue: value,
13
+ raw: `'${value}'`
14
+ }
15
+ });
16
+
17
+ export default class StyledProcessor extends BaseProcessor {
18
+ constructor(...args) {
19
+ super(...args);
20
+ let component;
21
+ const [type, value, ...rest] = this.params[0] ?? [];
22
+
23
+ if (type === 'call' && rest.length === 0) {
24
+ const [source, path] = value;
25
+
26
+ if (path.node.type === 'StringLiteral') {
27
+ component = path.node.value;
28
+ } else if (path.node.type === 'ArrowFunctionExpression' || path.node.type === 'FunctionExpression') {
29
+ // Special case when styled wraps a function
30
+ // It's actually the same as wrapping a built-in tag
31
+ component = 'FunctionalComponent';
32
+ } else {
33
+ component = {
34
+ node: path.node,
35
+ source
36
+ };
37
+ this.dependencies.push({
38
+ ex: path,
39
+ source
40
+ });
41
+ }
42
+ }
43
+
44
+ if (type === 'member') {
45
+ if (value.node.type === 'Identifier') {
46
+ component = value.node.name;
47
+ } else if (value.node.type === 'StringLiteral') {
48
+ component = value.node.value;
49
+ }
50
+ }
51
+
52
+ if (!component || this.params.length > 1) {
53
+ throw new Error('Invalid usage of `styled` tag');
54
+ }
55
+
56
+ this.component = component;
57
+ }
58
+
59
+ addInterpolation(node, source) {
60
+ const id = this.getVariableId(source);
61
+ this.interpolations.push({
62
+ id,
63
+ node,
64
+ source,
65
+ unit: ''
66
+ });
67
+ return `var(--${id})`;
68
+ }
69
+
70
+ extractRules(valueCache, cssText, loc) {
71
+ const rules = {};
72
+ let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
73
+ // get its class name to create a more specific selector
74
+ // it'll ensure that styles are overridden properly
75
+
76
+ let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node);
77
+
78
+ while (hasMeta(value)) {
79
+ selector += `.${value.__linaria.className}`;
80
+ value = value.__linaria.extends;
81
+ }
82
+
83
+ rules[selector] = {
84
+ cssText,
85
+ className: this.className,
86
+ displayName: this.displayName,
87
+ start: loc?.start ?? null
88
+ };
89
+ return [rules, this.className];
90
+ }
91
+
92
+ getRuntimeReplacement(classes, uniqInterpolations) {
93
+ const t = this.astService;
94
+ const props = this.getProps(classes, uniqInterpolations);
95
+ return [t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true];
96
+ }
97
+
98
+ get asSelector() {
99
+ return `.${this.className}`;
100
+ }
101
+
102
+ get tagExpressionArgument() {
103
+ const t = this.astService;
104
+
105
+ if (typeof this.component === 'string') {
106
+ if (this.component === 'FunctionalComponent') {
107
+ return t.arrowFunctionExpression([], t.blockStatement([]));
108
+ }
109
+
110
+ return singleQuotedStringLiteral(this.component);
111
+ }
112
+
113
+ return t.identifier(this.component.source);
114
+ }
115
+
116
+ get tagExpression() {
117
+ const t = this.astService;
118
+ return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
119
+ }
120
+
121
+ get valueSource() {
122
+ const extendsNode = typeof this.component === 'string' ? null : this.component.source;
123
+ return `{
124
+ displayName: "${this.displayName}",
125
+ __linaria: {
126
+ className: "${this.className}",
127
+ extends: ${extendsNode}
128
+ }
129
+ }`;
130
+ }
131
+
132
+ getProps(classes, uniqInterpolations) {
133
+ const propsObj = {
134
+ name: this.displayName,
135
+ class: this.className
136
+ }; // If we found any interpolations, also pass them, so they can be applied
137
+
138
+ if (this.interpolations.length) {
139
+ propsObj.vars = {};
140
+ uniqInterpolations.forEach(({
141
+ id,
142
+ unit,
143
+ node
144
+ }) => {
145
+ const items = [node];
146
+
147
+ if (unit) {
148
+ items.push(this.astService.stringLiteral(unit));
149
+ }
150
+
151
+ propsObj.vars[id] = items;
152
+ });
153
+ }
154
+
155
+ return propsObj;
156
+ }
157
+
158
+ getTagComponentProps(props) {
159
+ const t = this.astService;
160
+ const propExpressions = Object.entries(props).map(([key, value]) => {
161
+ if (!value) {
162
+ return null;
163
+ }
164
+
165
+ const keyNode = t.identifier(key);
166
+
167
+ if (typeof value === 'string') {
168
+ return t.objectProperty(keyNode, t.stringLiteral(value));
169
+ }
170
+
171
+ if (typeof value === 'boolean') {
172
+ return t.objectProperty(keyNode, t.booleanLiteral(value));
173
+ }
174
+
175
+ const vars = Object.entries(value).map(([propName, propValue]) => {
176
+ return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
177
+ });
178
+ return t.objectProperty(keyNode, t.objectExpression(vars));
179
+ }).filter(isNotNull);
180
+ return t.objectExpression(propExpressions);
181
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
182
+
183
+
184
+ getVariableId(value) {
185
+ // make the variable unique to this styled component
186
+ return `${this.slug}-${this.interpolations.length}`;
187
+ }
188
+
189
+ }
190
+ //# sourceMappingURL=styled.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styled.js","names":["BaseProcessor","hasMeta","value","isNotNull","x","singleQuotedStringLiteral","type","extra","rawValue","raw","StyledProcessor","constructor","args","component","rest","params","length","source","path","node","dependencies","push","ex","name","Error","addInterpolation","id","getVariableId","interpolations","unit","extractRules","valueCache","cssText","loc","rules","selector","className","get","__linaria","extends","displayName","start","getRuntimeReplacement","classes","uniqInterpolations","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","tagExp","valueSource","extendsNode","propsObj","class","vars","forEach","items","stringLiteral","propExpressions","Object","entries","map","key","keyNode","objectProperty","booleanLiteral","propName","propValue","arrayExpression","objectExpression","filter","slug"],"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type { StyledMeta } from '@linaria/core';\nimport type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';\nimport BaseProcessor from '@linaria/core/processors/BaseProcessor';\nimport type {\n Rules,\n WrappedNode,\n IInterpolation,\n ValueCache,\n} from '@linaria/core/processors/types';\n\nexport function hasMeta(value: unknown): value is StyledMeta {\n return typeof value === 'object' && value !== null && '__linaria' in value;\n}\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends BaseProcessor {\n public component: WrappedNode;\n\n constructor(...args: ProcessorParams) {\n super(...args);\n\n let component: WrappedNode | undefined;\n const [type, value, ...rest] = this.params[0] ?? [];\n if (type === 'call' && rest.length === 0) {\n const [source, path] = value;\n if (path.node.type === 'StringLiteral') {\n component = path.node.value;\n } else if (\n path.node.type === 'ArrowFunctionExpression' ||\n path.node.type === 'FunctionExpression'\n ) {\n // Special case when styled wraps a function\n // It's actually the same as wrapping a built-in tag\n component = 'FunctionalComponent';\n } else {\n component = {\n node: path.node,\n source,\n };\n this.dependencies.push({\n ex: path,\n source,\n });\n }\n }\n\n if (type === 'member') {\n if (value.node.type === 'Identifier') {\n component = value.node.name;\n } else if (value.node.type === 'StringLiteral') {\n component = value.node.value;\n }\n }\n\n if (!component || this.params.length > 1) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(node: Expression, source: string) {\n const id = this.getVariableId(source);\n\n this.interpolations.push({\n id,\n node,\n source,\n unit: '',\n });\n\n return `var(--${id})`;\n }\n\n public override extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): [Rules, string] {\n const rules: Rules = {};\n\n let selector = `.${this.className}`;\n\n // If `styled` wraps another component and not a primitive,\n // get its class name to create a more specific selector\n // it'll ensure that styles are overridden properly\n let value =\n typeof this.component === 'string'\n ? null\n : valueCache.get(this.component.node);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return [rules, this.className];\n }\n\n public override getRuntimeReplacement(\n classes: string,\n uniqInterpolations: IInterpolation[]\n ): [Expression, boolean] {\n const t = this.astService;\n\n const props = this.getProps(classes, uniqInterpolations);\n\n return [\n t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),\n true,\n ];\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.identifier(this.component.source);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tagExp, [this.tagExpressionArgument]);\n }\n\n public override get valueSource(): string {\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.source;\n return `{\n displayName: \"${this.displayName}\",\n __linaria: {\n className: \"${this.className}\",\n extends: ${extendsNode}\n }\n }`;\n }\n\n protected getProps(\n classes: string,\n uniqInterpolations: IInterpolation[]\n ): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n uniqInterpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [node];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected getVariableId(value: string): string {\n // make the variable unique to this styled component\n return `${this.slug}-${this.interpolations.length}`;\n }\n}\n"],"mappings":"AAUA,OAAOA,aAAP,MAA0B,wCAA1B;AAQA,OAAO,SAASC,OAAT,CAAiBC,KAAjB,EAAsD;EAC3D,OAAO,OAAOA,KAAP,KAAiB,QAAjB,IAA6BA,KAAK,KAAK,IAAvC,IAA+C,eAAeA,KAArE;AACD;;AAED,MAAMC,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIH,KAAD,KAAmC;EACnEI,IAAI,EAAE,eAD6D;EAEnEJ,KAFmE;EAGnEK,KAAK,EA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,GAAGK,MAAM,CAACC,OAAP,CAAelE,KAAf,EAAsBmE,GAAtB,CAA0B,CAAC,CAACK,QAAD,EAAWC,SAAX,CAAD,KAA2B;QAChE,OAAO9B,CAAC,CAAC2B,cAAF,CACL3B,CAAC,CAACoB,aAAF,CAAgBS,QAAhB,CADK,EAEL7B,CAAC,CAAC+B,eAAF,CAAkBD,SAAlB,CAFK,CAAP;MAID,CALY,CAAb;MAOA,OAAO9B,CAAC,CAAC2B,cAAF,CAAiBD,OAAjB,EAA0B1B,CAAC,CAACgC,gBAAF,CAAmBf,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBgB,MAzBqB,CAyBd3E,SAzBc,CAAxB;IA2BA,OAAO0C,CAAC,CAACgC,gBAAF,CAAmBX,eAAnB,CAAP;EACD,CAnMwD,CAqMzD;;;EACUvC,aAAa,CAACzB,KAAD,EAAwB;IAC7C;IACA,OAAQ,GAAE,KAAK6E,IAAK,IAAG,KAAKnD,cAAL,CAAoBZ,MAAO,EAAlD;EACD;;AAzMwD"}
package/esm/styled.js CHANGED
@@ -1,29 +1,45 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
1
3
  /**
2
4
  * This file contains an runtime version of `styled` component. Responsibilities of the component are:
3
5
  * - returns ReactElement based on HTML tag used with `styled` or custom React Component
4
6
  * - injects classNames for the returned component
5
7
  * - injects CSS variables used to define dynamic styles based on props
6
8
  */
7
- import React from 'react';
8
9
  import validAttr from '@emotion/is-prop-valid';
10
+ import React from 'react';
9
11
  import { cx } from '@linaria/core';
10
- // Workaround for rest operator
11
- export const restOp = (obj, keys) => {
12
- const res = {};
13
- let key;
14
12
 
15
- for (key in obj) {
16
- if (keys.indexOf(key) === -1) {
17
- res[key] = obj[key];
18
- }
19
- }
13
+ const isCapital = ch => ch.toUpperCase() === ch;
14
+
15
+ const filterKey = keys => key => keys.indexOf(key) === -1;
20
16
 
17
+ export const omit = (obj, keys) => {
18
+ const res = {};
19
+ Object.keys(obj).filter(filterKey(keys)).forEach(key => {
20
+ res[key] = obj[key];
21
+ });
21
22
  return res;
22
23
  };
23
24
 
25
+ function filterProps(component, props, omitKeys) {
26
+ const filteredProps = omit(props, omitKeys); // Check if it's an HTML tag and not a custom element
27
+
28
+ if (typeof component === 'string' && component.indexOf('-') === -1 && !isCapital(component[0])) {
29
+ Object.keys(filteredProps).forEach(key => {
30
+ if (!validAttr(key)) {
31
+ // Don't pass through invalid attributes to HTML elements
32
+ delete filteredProps[key];
33
+ }
34
+ });
35
+ }
36
+
37
+ return filteredProps;
38
+ }
39
+
24
40
  const warnIfInvalid = (value, componentName) => {
25
41
  if (process.env.NODE_ENV !== 'production') {
26
- if (typeof value === 'string' || // eslint-disable-next-line no-self-compare
42
+ if (typeof value === 'string' || // eslint-disable-next-line no-self-compare,no-restricted-globals
27
43
  typeof value === 'number' && isFinite(value)) {
28
44
  return;
29
45
  }
@@ -48,30 +64,15 @@ function styled(tag) {
48
64
  as: component = tag,
49
65
  class: className
50
66
  } = props;
51
- const rest = restOp(props, ['as', 'class']);
52
- let filteredProps; // Check if it's an HTML tag and not a custom element
53
-
54
- if (typeof component === 'string' && component.indexOf('-') === -1) {
55
- filteredProps = {}; // eslint-disable-next-line guard-for-in
56
-
57
- for (const key in rest) {
58
- if (key === 'as' || validAttr(key)) {
59
- // Don't pass through invalid attributes to HTML elements
60
- filteredProps[key] = rest[key];
61
- }
62
- }
63
- } else {
64
- filteredProps = rest;
65
- }
66
-
67
+ const filteredProps = filterProps(component, props, ['as', 'class']);
67
68
  filteredProps.ref = ref;
68
- filteredProps.className = cx(filteredProps.className || className, options.class);
69
+ filteredProps.className = options.atomic ? cx(options.class, filteredProps.className || className) : cx(filteredProps.className || className, options.class);
69
70
  const {
70
71
  vars
71
72
  } = options;
72
73
 
73
74
  if (vars) {
74
- const style = {}; // eslint-disable-next-line guard-for-in
75
+ const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
75
76
 
76
77
  for (const name in vars) {
77
78
  const variable = vars[name];
@@ -107,7 +108,7 @@ function styled(tag) {
107
108
  const Result = React.forwardRef ? /*#__PURE__*/React.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
108
109
  // Fallback to a innerRef prop in that case
109
110
  props => {
110
- const rest = restOp(props, ['innerRef']);
111
+ const rest = omit(props, ['innerRef']);
111
112
  return render(rest, props.innerRef);
112
113
  };
113
114
  Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
package/esm/styled.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/styled.ts"],"names":["React","validAttr","cx","restOp","obj","keys","res","key","indexOf","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","props","ref","as","component","class","className","rest","filteredProps","vars","style","name","variable","result","unit","ownStyle","Object","length","forEach","__linaria","createElement","Result","forwardRef","innerRef","displayName","extends","Proxy","get","o","prop"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,KAAP,MAAkB,OAAlB;AACA,OAAOC,SAAP,MAAsB,wBAAtB;AACA,SAASC,EAAT,QAAmB,eAAnB;AAsBA;AACA,OAAO,MAAMC,MAAkB,GAAG,CAACC,GAAD,EAAMC,IAAN,KAAe;AAC/C,QAAMC,GAAG,GAAG,EAAZ;AACA,MAAIC,GAAJ;;AACA,OAAKA,GAAL,IAAYH,GAAZ,EAAiB;AACf,QAAIC,IAAI,CAACG,OAAL,CAAaD,GAAb,MAAsB,CAAC,CAA3B,EAA8B;AAC5BD,MAAAA,GAAG,CAACC,GAAD,CAAH,GAAWH,GAAG,CAACG,GAAD,CAAd;AACD;AACF;;AACD,SAAOD,GAAP;AACD,CATM;;AAWP,MAAMG,aAAa,GAAG,CAACC,KAAD,EAAaC,aAAb,KAAuC;AAC3D,MAAIC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAA7B,EAA2C;AACzC,QACE,OAAOJ,KAAP,KAAiB,QAAjB,IACA;AACC,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;;AAED,UAAKf,GAAD,CAAawB,SAAb,IAA0BxB,GAAG,KAAKS,SAAtC,EAAiD;AAC/C;AACA;AACAI,QAAAA,aAAa,CAACL,EAAd,GAAmBC,SAAnB;AAEA,4BAAOhC,KAAK,CAACgD,aAAN,CAAoBzB,GAApB,EAAyBa,aAAzB,CAAP;AACD;;AACD,0BAAOpC,KAAK,CAACgD,aAAN,CAAoBhB,SAApB,EAA+BI,aAA/B,CAAP;AACD,KA9DD;;AAgEA,UAAMa,MAAM,GAAGjD,KAAK,CAACkD,UAAN,gBACXlD,KAAK,CAACkD,UAAN,CAAiBtB,MAAjB,CADW,GAEX;AACA;AACCC,IAAAA,KAAD,IAAgB;AACd,YAAMM,IAAI,GAAGhC,MAAM,CAAC0B,KAAD,EAAQ,CAAC,UAAD,CAAR,CAAnB;AACA,aAAOD,MAAM,CAACO,IAAD,EAAON,KAAK,CAACsB,QAAb,CAAb;AACD,KAPL;AASCF,IAAAA,MAAD,CAAgBG,WAAhB,GAA8B5B,OAAO,CAACe,IAAtC,CAnF2B,CAqF3B;;AACCU,IAAAA,MAAD,CAAgBF,SAAhB,GAA4B;AAC1Bb,MAAAA,SAAS,EAAEV,OAAO,CAACS,KADO;AAE1BoB,MAAAA,OAAO,EAAE9B;AAFiB,KAA5B;AAKA,WAAO0B,MAAP;AACD,GA5FD;AA6FD;;AA+CD,eAAgBrC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIwC,KAAJ,CAAUhC,MAAV,EAAkB;AAChBiC,EAAAA,GAAG,CAACC,CAAD,EAAIC,IAAJ,EAAuC;AACxC,WAAOD,CAAC,CAACC,IAAD,CAAR;AACD;;AAHe,CAAlB,CADY,GAMZnC,MANJ","sourcesContent":["/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport React from 'react';\nimport validAttr from '@emotion/is-prop-valid';\nimport { cx } from '@linaria/core';\nimport type { CSSProperties, StyledMeta } from '@linaria/core';\n\nexport type NoInfer<A extends any> = [A][A extends any ? 0 : never];\n\ntype Options = {\n name: string;\n class: string;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\ninterface CustomOmit {\n <T extends object, K extends [...(keyof T)[]]>(obj: T, keys: K): {\n [K2 in Exclude<keyof T, K[number]>]: T[K2];\n };\n}\n\n// Workaround for rest operator\nexport const restOp: CustomOmit = (obj, keys) => {\n const res = {} as { [K in keyof typeof obj]: typeof obj[K] };\n let key: keyof typeof obj;\n for (key in obj) {\n if (keys.indexOf(key) === -1) {\n res[key] = obj[key];\n }\n }\n return res;\n};\n\nconst warnIfInvalid = (value: any, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// If styled wraps custom component, that component should have className property\nfunction styled<TConstructor extends React.ComponentType<any>>(\n tag: TConstructor extends React.ComponentType<infer T>\n ? [T] extends [{ className?: string | undefined }]\n ? TConstructor\n : never\n : never\n): ComponentStyledTag<TConstructor>;\nfunction styled<T>(\n tag: [T] extends [{ className?: string | undefined }]\n ? React.ComponentType<T>\n : never\n): ComponentStyledTag<T>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const rest = restOp(props, ['as', 'class']);\n let filteredProps: IProps;\n\n // Check if it's an HTML tag and not a custom element\n if (typeof component === 'string' && component.indexOf('-') === -1) {\n filteredProps = {} as { [key: string]: any };\n\n // eslint-disable-next-line guard-for-in\n for (const key in rest) {\n if (key === 'as' || validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n filteredProps[key] = rest[key];\n }\n }\n } else {\n filteredProps = rest;\n }\n\n filteredProps.ref = ref;\n filteredProps.className = cx(\n filteredProps.className || className,\n options.class\n );\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = restOp(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = {}\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTag<T> = <\n OwnProps = {},\n TrgProps = [T] extends [React.FunctionComponent<infer TProps>] ? TProps : T\n>(\n strings: TemplateStringsArray,\n // Expressions can contain functions only if wrapped component has style property\n ...exprs: TrgProps extends { style?: React.CSSProperties | undefined }\n ? Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TrgProps>) => string | number)\n >\n : StaticPlaceholder[]\n) => keyof OwnProps extends never\n ? [T] extends [React.FunctionComponent<any>]\n ? StyledMeta & T\n : StyledComponent<TrgProps>\n : StyledComponent<OwnProps & TrgProps>;\n\ntype StyledJSXIntrinsics = {\n readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;\n};\n\nexport type Styled = typeof styled & StyledJSXIntrinsics;\n\nexport default (process.env.NODE_ENV !== 'production'\n ? new Proxy(styled, {\n get(o, prop: keyof JSX.IntrinsicElements) {\n return o(prop);\n },\n })\n : styled) as Styled;\n"],"file":"styled.js"}
1
+ {"version":3,"file":"styled.js","names":["validAttr","React","cx","isCapital","ch","toUpperCase","filterKey","keys","key","indexOf","omit","obj","res","Object","filter","forEach","filterProps","component","props","omitKeys","filteredProps","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","ref","as","class","className","atomic","vars","style","name","variable","result","unit","ownStyle","length","__linaria","createElement","Result","forwardRef","rest","innerRef","displayName","extends","Proxy","get","o","prop"],"sources":["../src/styled.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport validAttr from '@emotion/is-prop-valid';\nimport React from 'react';\n\nimport { cx } from '@linaria/core';\nimport type { CSSProperties, StyledMeta } from '@linaria/core';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <\n OwnProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\ntype StyledJSXIntrinsics = {\n readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;\n};\n\nexport type Styled = typeof styled & StyledJSXIntrinsics;\n\nexport default (process.env.NODE_ENV !== 'production'\n ? new Proxy(styled, {\n get(o, prop: keyof JSX.IntrinsicElements) {\n return o(prop);\n },\n })\n : styled) as Styled;\n"],"mappings":"AAAA;;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,SAAP,MAAsB,wBAAtB;AACA,OAAOC,KAAP,MAAkB,OAAlB;AAEA,SAASC,EAAT,QAAmB,eAAnB;;AAuBA,MAAMC,SAAS,GAAIC,EAAD,IAAyBA,EAAE,CAACC,WAAH,OAAqBD,EAAhE;;AACA,MAAME,SAAS,GACgBC,IAA7B,IACyBC,GAAzB,IACED,IAAI,CAACE,OAAL,CAAaD,GAAb,MAA6B,CAAC,CAHlC;;AAKA,OAAO,MAAME,IAAI,GAAG,CAClBC,GADkB,EAElBJ,IAFkB,KAGC;EACnB,MAAMK,GAAG,GAAG,EAAZ;EACAC,MAAM,CAACN,IAAP,CAAYI,GAAZ,EACGG,MADH,CACUR,SAAS,CAACC,IAAD,CADnB,EAEGQ,OAFH,CAEYP,GAAD,IAAS;IAChBI,GAAG,CAACJ,GAAD,CAAH,GAAWG,GAAG,CAACH,GAAD,CAAd;EACD,CAJH;EAMA,OAAOI,GAAP;AACD,CAZM;;AAcP,SAASI,WAAT,CACEC,SADF,EAEEC,KAFF,EAGEC,QAHF,EAI2B;EACzB,MAAMC,aAAa,GAAGV,IAAI,CAACQ,KAAD,EAAQC,QAAR,CAA1B,CADyB,CAGzB;;EACA,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src/index.ts"],"names":[],"mappings":";;;;;AAAA","sourcesContent":["export { default as styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\n"],"file":"index.js"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\n"],"mappings":";;;;;AAAA"}
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ exports.hasMeta = hasMeta;
8
+
9
+ var _BaseProcessor = _interopRequireDefault(require("@linaria/core/processors/BaseProcessor"));
10
+
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+
13
+ function hasMeta(value) {
14
+ return typeof value === 'object' && value !== null && '__linaria' in value;
15
+ }
16
+
17
+ const isNotNull = x => x !== null;
18
+
19
+ const singleQuotedStringLiteral = value => ({
20
+ type: 'StringLiteral',
21
+ value,
22
+ extra: {
23
+ rawValue: value,
24
+ raw: `'${value}'`
25
+ }
26
+ });
27
+
28
+ class StyledProcessor extends _BaseProcessor.default {
29
+ constructor(...args) {
30
+ var _this$params$;
31
+
32
+ super(...args);
33
+ let component;
34
+ const [type, value, ...rest] = (_this$params$ = this.params[0]) !== null && _this$params$ !== void 0 ? _this$params$ : [];
35
+
36
+ if (type === 'call' && rest.length === 0) {
37
+ const [source, path] = value;
38
+
39
+ if (path.node.type === 'StringLiteral') {
40
+ component = path.node.value;
41
+ } else if (path.node.type === 'ArrowFunctionExpression' || path.node.type === 'FunctionExpression') {
42
+ // Special case when styled wraps a function
43
+ // It's actually the same as wrapping a built-in tag
44
+ component = 'FunctionalComponent';
45
+ } else {
46
+ component = {
47
+ node: path.node,
48
+ source
49
+ };
50
+ this.dependencies.push({
51
+ ex: path,
52
+ source
53
+ });
54
+ }
55
+ }
56
+
57
+ if (type === 'member') {
58
+ if (value.node.type === 'Identifier') {
59
+ component = value.node.name;
60
+ } else if (value.node.type === 'StringLiteral') {
61
+ component = value.node.value;
62
+ }
63
+ }
64
+
65
+ if (!component || this.params.length > 1) {
66
+ throw new Error('Invalid usage of `styled` tag');
67
+ }
68
+
69
+ this.component = component;
70
+ }
71
+
72
+ addInterpolation(node, source) {
73
+ const id = this.getVariableId(source);
74
+ this.interpolations.push({
75
+ id,
76
+ node,
77
+ source,
78
+ unit: ''
79
+ });
80
+ return `var(--${id})`;
81
+ }
82
+
83
+ extractRules(valueCache, cssText, loc) {
84
+ var _loc$start;
85
+
86
+ const rules = {};
87
+ let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
88
+ // get its class name to create a more specific selector
89
+ // it'll ensure that styles are overridden properly
90
+
91
+ let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node);
92
+
93
+ while (hasMeta(value)) {
94
+ selector += `.${value.__linaria.className}`;
95
+ value = value.__linaria.extends;
96
+ }
97
+
98
+ rules[selector] = {
99
+ cssText,
100
+ className: this.className,
101
+ displayName: this.displayName,
102
+ start: (_loc$start = loc === null || loc === void 0 ? void 0 : loc.start) !== null && _loc$start !== void 0 ? _loc$start : null
103
+ };
104
+ return [rules, this.className];
105
+ }
106
+
107
+ getRuntimeReplacement(classes, uniqInterpolations) {
108
+ const t = this.astService;
109
+ const props = this.getProps(classes, uniqInterpolations);
110
+ return [t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true];
111
+ }
112
+
113
+ get asSelector() {
114
+ return `.${this.className}`;
115
+ }
116
+
117
+ get tagExpressionArgument() {
118
+ const t = this.astService;
119
+
120
+ if (typeof this.component === 'string') {
121
+ if (this.component === 'FunctionalComponent') {
122
+ return t.arrowFunctionExpression([], t.blockStatement([]));
123
+ }
124
+
125
+ return singleQuotedStringLiteral(this.component);
126
+ }
127
+
128
+ return t.identifier(this.component.source);
129
+ }
130
+
131
+ get tagExpression() {
132
+ const t = this.astService;
133
+ return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
134
+ }
135
+
136
+ get valueSource() {
137
+ const extendsNode = typeof this.component === 'string' ? null : this.component.source;
138
+ return `{
139
+ displayName: "${this.displayName}",
140
+ __linaria: {
141
+ className: "${this.className}",
142
+ extends: ${extendsNode}
143
+ }
144
+ }`;
145
+ }
146
+
147
+ getProps(classes, uniqInterpolations) {
148
+ const propsObj = {
149
+ name: this.displayName,
150
+ class: this.className
151
+ }; // If we found any interpolations, also pass them, so they can be applied
152
+
153
+ if (this.interpolations.length) {
154
+ propsObj.vars = {};
155
+ uniqInterpolations.forEach(({
156
+ id,
157
+ unit,
158
+ node
159
+ }) => {
160
+ const items = [node];
161
+
162
+ if (unit) {
163
+ items.push(this.astService.stringLiteral(unit));
164
+ }
165
+
166
+ propsObj.vars[id] = items;
167
+ });
168
+ }
169
+
170
+ return propsObj;
171
+ }
172
+
173
+ getTagComponentProps(props) {
174
+ const t = this.astService;
175
+ const propExpressions = Object.entries(props).map(([key, value]) => {
176
+ if (!value) {
177
+ return null;
178
+ }
179
+
180
+ const keyNode = t.identifier(key);
181
+
182
+ if (typeof value === 'string') {
183
+ return t.objectProperty(keyNode, t.stringLiteral(value));
184
+ }
185
+
186
+ if (typeof value === 'boolean') {
187
+ return t.objectProperty(keyNode, t.booleanLiteral(value));
188
+ }
189
+
190
+ const vars = Object.entries(value).map(([propName, propValue]) => {
191
+ return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
192
+ });
193
+ return t.objectProperty(keyNode, t.objectExpression(vars));
194
+ }).filter(isNotNull);
195
+ return t.objectExpression(propExpressions);
196
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
197
+
198
+
199
+ getVariableId(value) {
200
+ // make the variable unique to this styled component
201
+ return `${this.slug}-${this.interpolations.length}`;
202
+ }
203
+
204
+ }
205
+
206
+ exports.default = StyledProcessor;
207
+ //# sourceMappingURL=styled.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styled.js","names":["hasMeta","value","isNotNull","x","singleQuotedStringLiteral","type","extra","rawValue","raw","StyledProcessor","BaseProcessor","constructor","args","component","rest","params","length","source","path","node","dependencies","push","ex","name","Error","addInterpolation","id","getVariableId","interpolations","unit","extractRules","valueCache","cssText","loc","rules","selector","className","get","__linaria","extends","displayName","start","getRuntimeReplacement","classes","uniqInterpolations","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","tagExp","valueSource","extendsNode","propsObj","class","vars","forEach","items","stringLiteral","propExpressions","Object","entries","map","key","keyNode","objectProperty","booleanLiteral","propName","propValue","arrayExpression","objectExpression","filter","slug"],"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type { StyledMeta } from '@linaria/core';\nimport type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';\nimport BaseProcessor from '@linaria/core/processors/BaseProcessor';\nimport type {\n Rules,\n WrappedNode,\n IInterpolation,\n ValueCache,\n} from '@linaria/core/processors/types';\n\nexport function hasMeta(value: unknown): value is StyledMeta {\n return typeof value === 'object' && value !== null && '__linaria' in value;\n}\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends BaseProcessor {\n public component: WrappedNode;\n\n constructor(...args: ProcessorParams) {\n super(...args);\n\n let component: WrappedNode | undefined;\n const [type, value, ...rest] = this.params[0] ?? [];\n if (type === 'call' && rest.length === 0) {\n const [source, path] = value;\n if (path.node.type === 'StringLiteral') {\n component = path.node.value;\n } else if (\n path.node.type === 'ArrowFunctionExpression' ||\n path.node.type === 'FunctionExpression'\n ) {\n // Special case when styled wraps a function\n // It's actually the same as wrapping a built-in tag\n component = 'FunctionalComponent';\n } else {\n component = {\n node: path.node,\n source,\n };\n this.dependencies.push({\n ex: path,\n source,\n });\n }\n }\n\n if (type === 'member') {\n if (value.node.type === 'Identifier') {\n component = value.node.name;\n } else if (value.node.type === 'StringLiteral') {\n component = value.node.value;\n }\n }\n\n if (!component || this.params.length > 1) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(node: Expression, source: string) {\n const id = this.getVariableId(source);\n\n this.interpolations.push({\n id,\n node,\n source,\n unit: '',\n });\n\n return `var(--${id})`;\n }\n\n public override extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): [Rules, string] {\n const rules: Rules = {};\n\n let selector = `.${this.className}`;\n\n // If `styled` wraps another component and not a primitive,\n // get its class name to create a more specific selector\n // it'll ensure that styles are overridden properly\n let value =\n typeof this.component === 'string'\n ? null\n : valueCache.get(this.component.node);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return [rules, this.className];\n }\n\n public override getRuntimeReplacement(\n classes: string,\n uniqInterpolations: IInterpolation[]\n ): [Expression, boolean] {\n const t = this.astService;\n\n const props = this.getProps(classes, uniqInterpolations);\n\n return [\n t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),\n true,\n ];\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.identifier(this.component.source);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tagExp, [this.tagExpressionArgument]);\n }\n\n public override get valueSource(): string {\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.source;\n return `{\n displayName: \"${this.displayName}\",\n __linaria: {\n className: \"${this.className}\",\n extends: ${extendsNode}\n }\n }`;\n }\n\n protected getProps(\n classes: string,\n uniqInterpolations: IInterpolation[]\n ): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n uniqInterpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [node];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected getVariableId(value: string): string {\n // make the variable unique to this styled component\n return `${this.slug}-${this.interpolations.length}`;\n }\n}\n"],"mappings":";;;;;;;;AAUA;;;;AAQO,SAASA,OAAT,CAAiBC,KAAjB,EAAsD;EAC3D,OAAO,OAAOA,KAAP,KAAiB,QAAjB,IAA6BA,KAAK,KAAK,IAAvC,IAA+C,eAAeA,KAArE;AACD;;AAED,MAAMC,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIH,KAAD,KAAmC;EACnEI,IAAI,EAAE,eAD6D;EAEnEJ,KAFmE;EAGnEK,KAAK,EAAE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AiBxE,KAAjB,CAA1B,CAAP;MACD;;MAED,MAAM6D,IAAI,GAAGK,MAAM,CAACC,OAAP,CAAenE,KAAf,EAAsBoE,GAAtB,CAA0B,CAAC,CAACK,QAAD,EAAWC,SAAX,CAAD,KAA2B;QAChE,OAAO9B,CAAC,CAAC2B,cAAF,CACL3B,CAAC,CAACoB,aAAF,CAAgBS,QAAhB,CADK,EAEL7B,CAAC,CAAC+B,eAAF,CAAkBD,SAAlB,CAFK,CAAP;MAID,CALY,CAAb;MAOA,OAAO9B,CAAC,CAAC2B,cAAF,CAAiBD,OAAjB,EAA0B1B,CAAC,CAACgC,gBAAF,CAAmBf,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBgB,MAzBqB,CAyBd5E,SAzBc,CAAxB;IA2BA,OAAO2C,CAAC,CAACgC,gBAAF,CAAmBX,eAAnB,CAAP;EACD,CAnMwD,CAqMzD;;;EACUvC,aAAa,CAAC1B,KAAD,EAAwB;IAC7C;IACA,OAAQ,GAAE,KAAK8E,IAAK,IAAG,KAAKnD,cAAL,CAAoBZ,MAAO,EAAlD;EACD;;AAzMwD"}
package/lib/styled.js CHANGED
@@ -1,53 +1,68 @@
1
1
  "use strict";
2
2
 
3
3
  exports.__esModule = true;
4
- exports.default = exports.restOp = void 0;
5
-
6
- var _react = _interopRequireDefault(require("react"));
4
+ exports.omit = exports.default = void 0;
7
5
 
8
6
  var _isPropValid = _interopRequireDefault(require("@emotion/is-prop-valid"));
9
7
 
8
+ var _react = _interopRequireDefault(require("react"));
9
+
10
10
  var _core = require("@linaria/core");
11
11
 
12
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
13
 
14
+ /* eslint-disable @typescript-eslint/no-explicit-any */
15
+
14
16
  /**
15
17
  * This file contains an runtime version of `styled` component. Responsibilities of the component are:
16
18
  * - returns ReactElement based on HTML tag used with `styled` or custom React Component
17
19
  * - injects classNames for the returned component
18
20
  * - injects CSS variables used to define dynamic styles based on props
19
21
  */
20
- // Workaround for rest operator
21
- var restOp = function restOp(obj, keys) {
22
- var res = {};
23
- var key;
24
-
25
- for (key in obj) {
26
- if (keys.indexOf(key) === -1) {
27
- res[key] = obj[key];
28
- }
29
- }
22
+ const isCapital = ch => ch.toUpperCase() === ch;
23
+
24
+ const filterKey = keys => key => keys.indexOf(key) === -1;
30
25
 
26
+ const omit = (obj, keys) => {
27
+ const res = {};
28
+ Object.keys(obj).filter(filterKey(keys)).forEach(key => {
29
+ res[key] = obj[key];
30
+ });
31
31
  return res;
32
32
  };
33
33
 
34
- exports.restOp = restOp;
34
+ exports.omit = omit;
35
35
 
36
- var warnIfInvalid = function warnIfInvalid(value, componentName) {
36
+ function filterProps(component, props, omitKeys) {
37
+ const filteredProps = omit(props, omitKeys); // Check if it's an HTML tag and not a custom element
38
+
39
+ if (typeof component === 'string' && component.indexOf('-') === -1 && !isCapital(component[0])) {
40
+ Object.keys(filteredProps).forEach(key => {
41
+ if (!(0, _isPropValid.default)(key)) {
42
+ // Don't pass through invalid attributes to HTML elements
43
+ delete filteredProps[key];
44
+ }
45
+ });
46
+ }
47
+
48
+ return filteredProps;
49
+ }
50
+
51
+ const warnIfInvalid = (value, componentName) => {
37
52
  if (process.env.NODE_ENV !== 'production') {
38
- if (typeof value === 'string' || // eslint-disable-next-line no-self-compare
53
+ if (typeof value === 'string' || // eslint-disable-next-line no-self-compare,no-restricted-globals
39
54
  typeof value === 'number' && isFinite(value)) {
40
55
  return;
41
56
  }
42
57
 
43
- var stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); // eslint-disable-next-line no-console
58
+ const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); // eslint-disable-next-line no-console
44
59
 
45
60
  console.warn("An interpolation evaluated to '" + stringified + "' in the component '" + componentName + "', which is probably a mistake. You should explicitly cast or transform the value to a string.");
46
61
  }
47
62
  };
48
63
 
49
64
  function styled(tag) {
50
- return function (options) {
65
+ return options => {
51
66
  if (process.env.NODE_ENV !== 'production') {
52
67
  if (Array.isArray(options)) {
53
68
  // We received a strings array since it's used as a tag
@@ -55,48 +70,35 @@ function styled(tag) {
55
70
  }
56
71
  }
57
72
 
58
- var render = function render(props, ref) {
59
- var _props$as = props.as,
60
- component = _props$as === void 0 ? tag : _props$as,
61
- className = props.class;
62
- var rest = restOp(props, ['as', 'class']);
63
- var filteredProps; // Check if it's an HTML tag and not a custom element
64
-
65
- if (typeof component === 'string' && component.indexOf('-') === -1) {
66
- filteredProps = {}; // eslint-disable-next-line guard-for-in
67
-
68
- for (var _key in rest) {
69
- if (_key === 'as' || (0, _isPropValid.default)(_key)) {
70
- // Don't pass through invalid attributes to HTML elements
71
- filteredProps[_key] = rest[_key];
72
- }
73
- }
74
- } else {
75
- filteredProps = rest;
76
- }
77
-
73
+ const render = (props, ref) => {
74
+ const {
75
+ as: component = tag,
76
+ class: className
77
+ } = props;
78
+ const filteredProps = filterProps(component, props, ['as', 'class']);
78
79
  filteredProps.ref = ref;
79
- filteredProps.className = (0, _core.cx)(filteredProps.className || className, options.class);
80
- var vars = options.vars;
80
+ filteredProps.className = options.atomic ? (0, _core.cx)(options.class, filteredProps.className || className) : (0, _core.cx)(filteredProps.className || className, options.class);
81
+ const {
82
+ vars
83
+ } = options;
81
84
 
82
85
  if (vars) {
83
- var style = {}; // eslint-disable-next-line guard-for-in
86
+ const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
84
87
 
85
- for (var name in vars) {
86
- var variable = vars[name];
87
- var result = variable[0];
88
- var unit = variable[1] || '';
89
- var value = typeof result === 'function' ? result(props) : result;
88
+ for (const name in vars) {
89
+ const variable = vars[name];
90
+ const result = variable[0];
91
+ const unit = variable[1] || '';
92
+ const value = typeof result === 'function' ? result(props) : result;
90
93
  warnIfInvalid(value, options.name);
91
94
  style["--" + name] = "" + value + unit;
92
95
  }
93
96
 
94
- var ownStyle = filteredProps.style || {};
97
+ const ownStyle = filteredProps.style || {};
98
+ const keys = Object.keys(ownStyle);
95
99
 
96
- var _keys = Object.keys(ownStyle);
97
-
98
- if (_keys.length > 0) {
99
- _keys.forEach(function (key) {
100
+ if (keys.length > 0) {
101
+ keys.forEach(key => {
100
102
  style[key] = ownStyle[key];
101
103
  });
102
104
  }
@@ -114,10 +116,10 @@ function styled(tag) {
114
116
  return /*#__PURE__*/_react.default.createElement(component, filteredProps);
115
117
  };
116
118
 
117
- var Result = _react.default.forwardRef ? /*#__PURE__*/_react.default.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
119
+ const Result = _react.default.forwardRef ? /*#__PURE__*/_react.default.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
118
120
  // Fallback to a innerRef prop in that case
119
- function (props) {
120
- var rest = restOp(props, ['innerRef']);
121
+ props => {
122
+ const rest = omit(props, ['innerRef']);
121
123
  return render(rest, props.innerRef);
122
124
  };
123
125
  Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
@@ -131,9 +133,10 @@ function styled(tag) {
131
133
  }
132
134
 
133
135
  var _default = process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
134
- get: function get(o, prop) {
136
+ get(o, prop) {
135
137
  return o(prop);
136
138
  }
139
+
137
140
  }) : styled;
138
141
 
139
142
  exports.default = _default;
package/lib/styled.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/styled.ts"],"names":["restOp","obj","keys","res","key","indexOf","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","props","ref","as","component","className","class","rest","filteredProps","vars","style","name","variable","result","unit","ownStyle","Object","length","forEach","__linaria","React","createElement","Result","forwardRef","innerRef","displayName","extends","Proxy","get","o","prop"],"mappings":";;;;;AAMA;;AACA;;AACA;;;;AARA;AACA;AACA;AACA;AACA;AACA;AAyBA;AACO,IAAMA,MAAkB,GAAG,SAArBA,MAAqB,CAACC,GAAD,EAAMC,IAAN,EAAe;AAC/C,MAAMC,GAAG,GAAG,EAAZ;AACA,MAAIC,GAAJ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AYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIyC,KAAJ,CAAUjC,MAAV,EAAkB;AAChBkC,EAAAA,GADgB,eACZC,CADY,EACTC,IADS,EAC0B;AACxC,WAAOD,CAAC,CAACC,IAAD,CAAR;AACD;AAHe,CAAlB,CADY,GAMZpC,M","sourcesContent":["/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport React from 'react';\nimport validAttr from '@emotion/is-prop-valid';\nimport { cx } from '@linaria/core';\nimport type { CSSProperties, StyledMeta } from '@linaria/core';\n\nexport type NoInfer<A extends any> = [A][A extends any ? 0 : never];\n\ntype Options = {\n name: string;\n class: string;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\ninterface CustomOmit {\n <T extends object, K extends [...(keyof T)[]]>(obj: T, keys: K): {\n [K2 in Exclude<keyof T, K[number]>]: T[K2];\n };\n}\n\n// Workaround for rest operator\nexport const restOp: CustomOmit = (obj, keys) => {\n const res = {} as { [K in keyof typeof obj]: typeof obj[K] };\n let key: keyof typeof obj;\n for (key in obj) {\n if (keys.indexOf(key) === -1) {\n res[key] = obj[key];\n }\n }\n return res;\n};\n\nconst warnIfInvalid = (value: any, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// If styled wraps custom component, that component should have className property\nfunction styled<TConstructor extends React.ComponentType<any>>(\n tag: TConstructor extends React.ComponentType<infer T>\n ? [T] extends [{ className?: string | undefined }]\n ? TConstructor\n : never\n : never\n): ComponentStyledTag<TConstructor>;\nfunction styled<T>(\n tag: [T] extends [{ className?: string | undefined }]\n ? React.ComponentType<T>\n : never\n): ComponentStyledTag<T>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const rest = restOp(props, ['as', 'class']);\n let filteredProps: IProps;\n\n // Check if it's an HTML tag and not a custom element\n if (typeof component === 'string' && component.indexOf('-') === -1) {\n filteredProps = {} as { [key: string]: any };\n\n // eslint-disable-next-line guard-for-in\n for (const key in rest) {\n if (key === 'as' || validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n filteredProps[key] = rest[key];\n }\n }\n } else {\n filteredProps = rest;\n }\n\n filteredProps.ref = ref;\n filteredProps.className = cx(\n filteredProps.className || className,\n options.class\n );\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = restOp(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = {}\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTag<T> = <\n OwnProps = {},\n TrgProps = [T] extends [React.FunctionComponent<infer TProps>] ? TProps : T\n>(\n strings: TemplateStringsArray,\n // Expressions can contain functions only if wrapped component has style property\n ...exprs: TrgProps extends { style?: React.CSSProperties | undefined }\n ? Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TrgProps>) => string | number)\n >\n : StaticPlaceholder[]\n) => keyof OwnProps extends never\n ? [T] extends [React.FunctionComponent<any>]\n ? StyledMeta & T\n : StyledComponent<TrgProps>\n : StyledComponent<OwnProps & TrgProps>;\n\ntype StyledJSXIntrinsics = {\n readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;\n};\n\nexport type Styled = typeof styled & StyledJSXIntrinsics;\n\nexport default (process.env.NODE_ENV !== 'production'\n ? new Proxy(styled, {\n get(o, prop: keyof JSX.IntrinsicElements) {\n return o(prop);\n },\n })\n : styled) as Styled;\n"],"file":"styled.js"}
1
+ {"version":3,"file":"styled.js","names":["isCapital","ch","toUpperCase","filterKey","keys","key","indexOf","omit","obj","res","Object","filter","forEach","filterProps","component","props","omitKeys","filteredProps","validAttr","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","ref","as","class","className","atomic","cx","vars","style","name","variable","result","unit","ownStyle","length","__linaria","React","createElement","Result","forwardRef","rest","innerRef","displayName","extends","Proxy","get","o","prop"],"sources":["../src/styled.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport validAttr from '@emotion/is-prop-valid';\nimport React from 'react';\n\nimport { cx } from '@linaria/core';\nimport type { CSSProperties, StyledMeta } from '@linaria/core';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <\n OwnProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\ntype StyledJSXIntrinsics = {\n readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;\n};\n\nexport type Styled = typeof styled & StyledJSXIntrinsics;\n\nexport default (process.env.NODE_ENV !== 'production'\n ? new Proxy(styled, {\n get(o, prop: keyof JSX.IntrinsicElements) {\n return o(prop);\n },\n })\n : styled) as Styled;\n"],"mappings":";;;;;AAOA;;AACA;;AAEA;;;;AAVA;;AACA;AACA;AACA;AACA;AACA;AACA;AA2BA,MAAMA,SAAS,GAAIC,EAAD,IAAyBA,EAAE,CAACC,WAAH,OAAqBD,EAAhE;;AACA,MAAME,SAAS,GACgBC,IAA7B,IACyBC,GAAzB,IACED,IAAI,CAACE,OAAL,CAAaD,GAAb,MAA6B,CAAC,CAHlC;;AAKO,MAAME,IAAI,GAAG,CAClBC,GADkB,EAElBJ,IAFkB,KAGC;EACnB,MAAMK,GAAG,GAAG,EAAZ;EACAC,MAAM,CAACN,IAAP,CAAYI,GAAZ,EACGG,MADH,CACUR,SAAS,CAACC,IAAD,CADnB,EAEGQ,OAFH,CA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C,QAAZ,KAAyB,YAAzB,GACZ,IAAIsC,KAAJ,CAAU9B,MAAV,EAAkB;EAChB+B,GAAG,CAACC,CAAD,EAAIC,IAAJ,EAAuC;IACxC,OAAOD,CAAC,CAACC,IAAD,CAAR;EACD;;AAHe,CAAlB,CADY,GAMZjC,M"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linaria/react",
3
- "version": "3.0.0-beta.15",
3
+ "version": "3.0.0-beta.19",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -14,8 +14,16 @@
14
14
  "lib/",
15
15
  "esm/"
16
16
  ],
17
+ "linaria": {
18
+ "tags": {
19
+ "styled": "./lib/processors/styled.js"
20
+ }
21
+ },
17
22
  "license": "MIT",
18
23
  "repository": "git@github.com:callstack/linaria.git",
24
+ "engines": {
25
+ "node": "^12.16.0 || >=13.7.0"
26
+ },
19
27
  "bugs": {
20
28
  "url": "https://github.com/callstack/linaria/issues"
21
29
  },
@@ -29,6 +37,7 @@
29
37
  ],
30
38
  "scripts": {
31
39
  "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
40
+ "build:corejs-test": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --ignore \"src/processors/**/*\"",
32
41
  "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
33
42
  "build": "yarn build:lib && yarn build:esm",
34
43
  "build:declarations": "tsc --emitDeclarationOnly --outDir types",
@@ -45,10 +54,31 @@
45
54
  },
46
55
  "dependencies": {
47
56
  "@emotion/is-prop-valid": "^0.8.8",
48
- "@linaria/core": "^3.0.0-beta.15"
57
+ "@linaria/core": "^3.0.0-beta.19",
58
+ "ts-invariant": "^0.10.3"
49
59
  },
50
60
  "peerDependencies": {
51
61
  "react": ">=16"
52
62
  },
53
- "gitHead": "a8ada3794c6e13231f70711d92b516d57677a5b1"
63
+ "exports": {
64
+ "./package.json": "./package.json",
65
+ ".": {
66
+ "types": "./types/index.d.ts",
67
+ "import": "./esm/index.js",
68
+ "default": "./lib/index.js"
69
+ },
70
+ "./*": {
71
+ "types": "./types/*.d.ts",
72
+ "import": "./esm/*.js",
73
+ "default": "./lib/*.js"
74
+ }
75
+ },
76
+ "typesVersions": {
77
+ "*": {
78
+ "processors/*": [
79
+ "./types/processors/*.d.ts"
80
+ ]
81
+ }
82
+ },
83
+ "gitHead": "73aab0a3908325333e452b9cbd5e438a0f1de463"
54
84
  }
@@ -0,0 +1,26 @@
1
+ import type { CallExpression, Expression, ObjectExpression, SourceLocation } from '@babel/types';
2
+ import type { StyledMeta } from '@linaria/core';
3
+ import type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';
4
+ import BaseProcessor from '@linaria/core/processors/BaseProcessor';
5
+ import type { Rules, WrappedNode, IInterpolation, ValueCache } from '@linaria/core/processors/types';
6
+ export declare function hasMeta(value: unknown): value is StyledMeta;
7
+ export interface IProps {
8
+ atomic?: boolean;
9
+ class?: string;
10
+ name: string;
11
+ vars?: Record<string, Expression[]>;
12
+ }
13
+ export default class StyledProcessor extends BaseProcessor {
14
+ component: WrappedNode;
15
+ constructor(...args: ProcessorParams);
16
+ addInterpolation(node: Expression, source: string): string;
17
+ extractRules(valueCache: ValueCache, cssText: string, loc?: SourceLocation | null): [Rules, string];
18
+ getRuntimeReplacement(classes: string, uniqInterpolations: IInterpolation[]): [Expression, boolean];
19
+ get asSelector(): string;
20
+ protected get tagExpressionArgument(): Expression;
21
+ protected get tagExpression(): CallExpression;
22
+ get valueSource(): string;
23
+ protected getProps(classes: string, uniqInterpolations: IInterpolation[]): IProps;
24
+ protected getTagComponentProps(props: IProps): ObjectExpression;
25
+ protected getVariableId(value: string): string;
26
+ }
package/types/styled.d.ts CHANGED
@@ -1,33 +1,30 @@
1
- /**
2
- * This file contains an runtime version of `styled` component. Responsibilities of the component are:
3
- * - returns ReactElement based on HTML tag used with `styled` or custom React Component
4
- * - injects classNames for the returned component
5
- * - injects CSS variables used to define dynamic styles based on props
6
- */
7
1
  import React from 'react';
8
2
  import type { CSSProperties, StyledMeta } from '@linaria/core';
9
- export declare type NoInfer<A extends any> = [A][A extends any ? 0 : never];
10
- interface CustomOmit {
11
- <T extends object, K extends [...(keyof T)[]]>(obj: T, keys: K): {
12
- [K2 in Exclude<keyof T, K[number]>]: T[K2];
13
- };
14
- }
15
- export declare const restOp: CustomOmit;
16
- declare function styled<TConstructor extends React.ComponentType<any>>(tag: TConstructor extends React.ComponentType<infer T> ? [T] extends [{
17
- className?: string | undefined;
18
- }] ? TConstructor : never : never): ComponentStyledTag<TConstructor>;
19
- declare function styled<T>(tag: [T] extends [{
20
- className?: string | undefined;
21
- }] ? React.ComponentType<T> : never): ComponentStyledTag<T>;
3
+ export declare type NoInfer<A> = [A][A extends any ? 0 : never];
4
+ declare type Component<TProps> = ((props: TProps) => unknown) | {
5
+ new (props: TProps): unknown;
6
+ };
7
+ declare type Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;
8
+ export declare const omit: <T extends Record<string, unknown>, TKeys extends keyof T>(obj: T, keys: TKeys[]) => Omit<T, TKeys>;
9
+ declare function styled<TProps extends Has<TMustHave, {
10
+ style?: React.CSSProperties;
11
+ }>, TMustHave extends {
12
+ style?: React.CSSProperties;
13
+ }, TConstructor extends Component<TProps>>(componentWithStyle: TConstructor & Component<TProps>): ComponentStyledTagWithInterpolation<TProps, TConstructor>;
14
+ declare function styled<TProps extends Has<TMustHave, {
15
+ className?: string;
16
+ }>, TMustHave extends {
17
+ className?: string;
18
+ }, TConstructor extends Component<TProps>>(componentWithoutStyle: TConstructor & Component<TProps>): ComponentStyledTagWithoutInterpolation<TConstructor>;
22
19
  declare function styled<TName extends keyof JSX.IntrinsicElements>(tag: TName): HtmlStyledTag<TName>;
20
+ declare function styled(component: 'The target component should have a className prop'): never;
23
21
  declare type StyledComponent<T> = StyledMeta & ([T] extends [React.FunctionComponent<any>] ? T : React.FunctionComponent<T & {
24
22
  as?: React.ElementType;
25
23
  }>);
26
24
  declare type StaticPlaceholder = string | number | CSSProperties | StyledMeta;
27
- declare type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <TAdditionalProps = {}>(strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>) => string | number)>) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;
28
- declare type ComponentStyledTag<T> = <OwnProps = {}, TrgProps = [T] extends [React.FunctionComponent<infer TProps>] ? TProps : T>(strings: TemplateStringsArray, ...exprs: TrgProps extends {
29
- style?: React.CSSProperties | undefined;
30
- } ? Array<StaticPlaceholder | ((props: NoInfer<OwnProps & TrgProps>) => string | number)> : StaticPlaceholder[]) => keyof OwnProps extends never ? [T] extends [React.FunctionComponent<any>] ? StyledMeta & T : StyledComponent<TrgProps> : StyledComponent<OwnProps & TrgProps>;
25
+ declare type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <TAdditionalProps = Record<string, unknown>>(strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>) => string | number)>) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;
26
+ declare type ComponentStyledTagWithoutInterpolation<TOrigCmp> = (strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: 'The target component should have a style prop') => never)>) => StyledMeta & TOrigCmp;
27
+ declare type ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = Record<string, unknown>>(strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)>) => keyof OwnProps extends never ? StyledMeta & TOrigCmp : StyledComponent<OwnProps & TTrgProps>;
31
28
  declare type StyledJSXIntrinsics = {
32
29
  readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;
33
30
  };