@linaria/react 3.0.0-beta.2 → 3.0.0-beta.22

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img alt="Linaria" src="../../website/assets/linaria-logo@2x.png" width="496">
2
+ <img alt="Linaria" src="https://raw.githubusercontent.com/callstack/linaria/HEAD/website/assets/linaria-logo@2x.png" width="496">
3
3
  </p>
4
4
 
5
5
  <p align="center">
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,C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AC9B,OAAO2C,CAAC,CAAC2B,cAAF,CAAiBD,OAAjB,EAA0B1B,CAAC,CAAC4B,cAAF,CAAiBvE,KAAjB,CAA1B,CAAP;MACD;;MAED,MAAM4D,IAAI,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,22 +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 * as 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
12
 
11
- // Workaround for rest operator
12
- const restOp = (obj, keysToExclude) => Object.keys(obj).filter(prop => !keysToExclude.includes(prop)).reduce((acc, curr) => Object.assign(acc, {
13
- [curr]: obj[curr]
14
- }), {}); // rest operator workaround
13
+ const isCapital = ch => ch.toUpperCase() === ch;
14
+
15
+ const filterKey = keys => key => keys.indexOf(key) === -1;
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
+ });
22
+ return res;
23
+ };
15
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
+ }
16
39
 
17
40
  const warnIfInvalid = (value, componentName) => {
18
41
  if (process.env.NODE_ENV !== 'production') {
19
- 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
20
43
  typeof value === 'number' && isFinite(value)) {
21
44
  return;
22
45
  }
@@ -25,8 +48,7 @@ const warnIfInvalid = (value, componentName) => {
25
48
 
26
49
  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.`);
27
50
  }
28
- }; // If styled wraps custom component, that component should have className property
29
-
51
+ };
30
52
 
31
53
  function styled(tag) {
32
54
  return options => {
@@ -42,30 +64,15 @@ function styled(tag) {
42
64
  as: component = tag,
43
65
  class: className
44
66
  } = props;
45
- const rest = restOp(props, ['as', 'class']);
46
- let filteredProps; // Check if it's an HTML tag and not a custom element
47
-
48
- if (typeof component === 'string' && component.indexOf('-') === -1) {
49
- filteredProps = {}; // eslint-disable-next-line guard-for-in
50
-
51
- for (const key in rest) {
52
- if (key === 'as' || validAttr(key)) {
53
- // Don't pass through invalid attributes to HTML elements
54
- filteredProps[key] = rest[key];
55
- }
56
- }
57
- } else {
58
- filteredProps = rest;
59
- }
60
-
67
+ const filteredProps = filterProps(component, props, ['as', 'class']);
61
68
  filteredProps.ref = ref;
62
- 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);
63
70
  const {
64
71
  vars
65
72
  } = options;
66
73
 
67
74
  if (vars) {
68
- const style = {}; // eslint-disable-next-line guard-for-in
75
+ const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
69
76
 
70
77
  for (const name in vars) {
71
78
  const variable = vars[name];
@@ -76,7 +83,16 @@ function styled(tag) {
76
83
  style[`--${name}`] = `${value}${unit}`;
77
84
  }
78
85
 
79
- filteredProps.style = Object.assign(style, filteredProps.style);
86
+ const ownStyle = filteredProps.style || {};
87
+ const keys = Object.keys(ownStyle);
88
+
89
+ if (keys.length > 0) {
90
+ keys.forEach(key => {
91
+ style[key] = ownStyle[key];
92
+ });
93
+ }
94
+
95
+ filteredProps.style = style;
80
96
  }
81
97
 
82
98
  if (tag.__linaria && tag !== component) {
@@ -92,7 +108,7 @@ function styled(tag) {
92
108
  const Result = React.forwardRef ? /*#__PURE__*/React.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
93
109
  // Fallback to a innerRef prop in that case
94
110
  props => {
95
- const rest = restOp(props, ['innerRef']);
111
+ const rest = omit(props, ['innerRef']);
96
112
  return render(rest, props.innerRef);
97
113
  };
98
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","keysToExclude","Object","keys","filter","prop","includes","reduce","acc","curr","assign","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","indexOf","key","vars","style","name","variable","result","unit","__linaria","createElement","Result","forward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AKA,WAAOwB,MAAP;AACD,GApFD;AAqFD;;AA+CD,eAAgBnC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIsC,KAAJ,CAAU9B,MAAV,EAAkB;AAChB+B,EAAAA,GAAG,CAACC,CAAD,EAAInD,IAAJ,EAAuC;AACxC,WAAOmD,CAAC,CAACnD,IAAD,CAAR;AACD;;AAHe,CAAlB,CADY,GAMZmB,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 * as 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\n// Workaround for rest operator\nconst restOp = (\n obj: { [key: string]: any },\n keysToExclude: string[]\n): { [key: string]: any } =>\n Object.keys(obj)\n .filter((prop) => !keysToExclude.includes(prop))\n .reduce((acc, curr) => Object.assign(acc, { [curr]: obj[curr] }), {}); // rest operator workaround\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\n// If styled wraps custom component, that component should have className property\nfunction styled<TConstructor extends React.FunctionComponent<any>>(\n tag: TConstructor extends React.FunctionComponent<infer T>\n ? T extends { className?: string }\n ? TConstructor\n : never\n : never\n): ComponentStyledTag<TConstructor>;\nfunction styled<T>(\n tag: T extends { className?: string } ? React.ComponentType<T> : 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;\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 filteredProps.style = Object.assign(style, filteredProps.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 }\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\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\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;EA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ChB6B,GAAG,CAACC,CAAD,EAAIC,IAAJ,EAAuC;IACxC,OAAOD,CAAC,CAACC,IAAD,CAAR;EACD;;AAHe,CAAlB,CADY,GAMZ/B,MANJ"}
package/lib/index.js CHANGED
@@ -7,5 +7,4 @@ var _styled = _interopRequireDefault(require("./styled"));
7
7
 
8
8
  exports.styled = _styled.default;
9
9
 
10
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
- //# sourceMappingURL=index.js.map
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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;IACLC,QAAQ,EAAEN,KADL;IAELO,GAAG,EAAG,IAAGP,KAAM;EAFV;AAH4D,CAAnC,CAAlC;;AASe,MAAMQ,eAAN,SAA8BC,sBAA9B,CAA4C;EAGzDC,WAAW,CAAC,GAAGC,IAAJ,EAA2B;IAAA;;IACpC,MAAM,GAAGA,IAAT;IAEA,IAAIC,SAAJ;IACA,MAAM,CAACR,IAAD,EAAOJ,KAAP,EAAc,GAAGa,IAAjB,qBAAyB,KAAKC,MAAL,CAAY,CAAZ,CAAzB,yDAA2C,EAAjD;;IACA,IAAIV,IAAI,KAAK,MAAT,IAAmBS,IAAI,CAACE,MAAL,KAAgB,CAAvC,EAA0C;MACxC,MAAM,CAACC,MAAD,EAASC,IAAT,IAAiBjB,KAAvB;;MACA,IAAIiB,IAAI,CAACC,IAAL,CAAUd,IAAV,KAAmB,eAAvB,EAAwC;QACtCQ,SAAS,GAAGK,IAAI,CAACC,IAAL,CAAUlB,KAAtB;MACD,CAFD,MAEO,IACLiB,IAAI,CAACC,IAAL,CAAUd,IAAV,KAAmB,yBAAnB,IACAa,IAAI,CAACC,IAAL,CAAUd,IAAV,KAAmB,oBAFd,EAGL;QACA;QACA;QACAQ,SAAS,GAAG,qBAAZ;MACD,CAPM,MAOA;QACLA,SAAS,GAAG;UACVM,IAAI,EAAED,IAAI,CAACC,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IAAI,CAACA,KAAL,EAAY;QACV,OAAO,IAAP;MACD;;MAED,MAAMsE,OAAO,GAAG1B,CAAC,CAACW,UAAF,CAAac,GAAb,CAAhB;;MAEA,IAAI,OAAOrE,KAAP,KAAiB,QAArB,EAA+B;QAC7B,OAAO4C,CAAC,CAAC2B,cAAF,CAAiBD,OAAjB,EAA0B1B,CAAC,CAACoB,aAAF,CAAgBhE,KAAhB,CAA1B,CAAP;MACD;;MAED,IAAI,OAAOA,KAAP,KAAiB,SAArB,EAAgC;QAC9B,OAAO4C,CAAC,CAAC2B,cAAF,CAAiBD,OAAjB,EAA0B1B,CAAC,CAAC4B,cAAF,CAAiBxE,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,19 +1,17 @@
1
1
  "use strict";
2
2
 
3
3
  exports.__esModule = true;
4
- exports.default = void 0;
5
-
6
- var React = _interopRequireWildcard(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
- function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
15
-
16
- function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
14
+ /* eslint-disable @typescript-eslint/no-explicit-any */
17
15
 
18
16
  /**
19
17
  * This file contains an runtime version of `styled` component. Responsibilities of the component are:
@@ -21,25 +19,47 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
21
19
  * - injects classNames for the returned component
22
20
  * - injects CSS variables used to define dynamic styles based on props
23
21
  */
24
- // Workaround for rest operator
25
- const restOp = (obj, keysToExclude) => Object.keys(obj).filter(prop => !keysToExclude.includes(prop)).reduce((acc, curr) => Object.assign(acc, {
26
- [curr]: obj[curr]
27
- }), {}); // rest operator workaround
22
+ const isCapital = ch => ch.toUpperCase() === ch;
23
+
24
+ const filterKey = keys => key => keys.indexOf(key) === -1;
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
+ return res;
32
+ };
33
+
34
+ exports.omit = omit;
35
+
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
+ }
28
47
 
48
+ return filteredProps;
49
+ }
29
50
 
30
51
  const warnIfInvalid = (value, componentName) => {
31
52
  if (process.env.NODE_ENV !== 'production') {
32
- 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
33
54
  typeof value === 'number' && isFinite(value)) {
34
55
  return;
35
56
  }
36
57
 
37
58
  const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); // eslint-disable-next-line no-console
38
59
 
39
- 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.`);
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.");
40
61
  }
41
- }; // If styled wraps custom component, that component should have className property
42
-
62
+ };
43
63
 
44
64
  function styled(tag) {
45
65
  return options => {
@@ -55,30 +75,15 @@ function styled(tag) {
55
75
  as: component = tag,
56
76
  class: className
57
77
  } = props;
58
- const rest = restOp(props, ['as', 'class']);
59
- let filteredProps; // Check if it's an HTML tag and not a custom element
60
-
61
- if (typeof component === 'string' && component.indexOf('-') === -1) {
62
- filteredProps = {}; // eslint-disable-next-line guard-for-in
63
-
64
- for (const key in rest) {
65
- if (key === 'as' || (0, _isPropValid.default)(key)) {
66
- // Don't pass through invalid attributes to HTML elements
67
- filteredProps[key] = rest[key];
68
- }
69
- }
70
- } else {
71
- filteredProps = rest;
72
- }
73
-
78
+ const filteredProps = filterProps(component, props, ['as', 'class']);
74
79
  filteredProps.ref = ref;
75
- filteredProps.className = (0, _core.cx)(filteredProps.className || className, options.class);
80
+ filteredProps.className = options.atomic ? (0, _core.cx)(options.class, filteredProps.className || className) : (0, _core.cx)(filteredProps.className || className, options.class);
76
81
  const {
77
82
  vars
78
83
  } = options;
79
84
 
80
85
  if (vars) {
81
- const style = {}; // eslint-disable-next-line guard-for-in
86
+ const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
82
87
 
83
88
  for (const name in vars) {
84
89
  const variable = vars[name];
@@ -86,26 +91,35 @@ function styled(tag) {
86
91
  const unit = variable[1] || '';
87
92
  const value = typeof result === 'function' ? result(props) : result;
88
93
  warnIfInvalid(value, options.name);
89
- style[`--${name}`] = `${value}${unit}`;
94
+ style["--" + name] = "" + value + unit;
95
+ }
96
+
97
+ const ownStyle = filteredProps.style || {};
98
+ const keys = Object.keys(ownStyle);
99
+
100
+ if (keys.length > 0) {
101
+ keys.forEach(key => {
102
+ style[key] = ownStyle[key];
103
+ });
90
104
  }
91
105
 
92
- filteredProps.style = Object.assign(style, filteredProps.style);
106
+ filteredProps.style = style;
93
107
  }
94
108
 
95
109
  if (tag.__linaria && tag !== component) {
96
110
  // If the underlying tag is a styled component, forward the `as` prop
97
111
  // Otherwise the styles from the underlying component will be ignored
98
112
  filteredProps.as = component;
99
- return /*#__PURE__*/React.createElement(tag, filteredProps);
113
+ return /*#__PURE__*/_react.default.createElement(tag, filteredProps);
100
114
  }
101
115
 
102
- return /*#__PURE__*/React.createElement(component, filteredProps);
116
+ return /*#__PURE__*/_react.default.createElement(component, filteredProps);
103
117
  };
104
118
 
105
- const Result = React.forwardRef ? /*#__PURE__*/React.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
106
120
  // Fallback to a innerRef prop in that case
107
121
  props => {
108
- const rest = restOp(props, ['innerRef']);
122
+ const rest = omit(props, ['innerRef']);
109
123
  return render(rest, props.innerRef);
110
124
  };
111
125
  Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
@@ -125,5 +139,4 @@ var _default = process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
125
139
 
126
140
  }) : styled;
127
141
 
128
- exports.default = _default;
129
- //# sourceMappingURL=styled.js.map
142
+ exports.default = _default;
package/lib/styled.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/styled.ts"],"names":["restOp","obj","keysToExclude","Object","keys","filter","prop","includes","reduce","acc","curr","assign","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","indexOf","key","vars","style","name","variable","result","unit","__linaria","React","createElement","Result","forwardRef","innerRef","displayName","extends","Proxy","get","o"],"mappings":";;;;;AAMA;;AACA;;AACA;;;;;;;;AARA;AACA;AACA;AACA;AACA;AACA;AAmBA;AACA,MAAMA,MAAM,GAAG,CACbC,GADa,EAEbC,aAFa,KAIbC,MAAM,CAACC,IAAP,CAAYH,GAAZ,EACGI,MADH,CACWC,IAAD,IAAU,CAACJ,aAAa,CAACK,QAAd,CAAuBD,IAAvB,CADrB,EAEGE,MAFH,CAEU,CAACC,GAAD,EAAMC,IAAN,KAAeP,MAAM,CAACQ,MAAP,CAAcF,GAAd,EAAmB;AAAE,GAACC,IAAD,GAAQT,GAAG,CAACS,IAAD;AAAb,CAAnB,CAFzB,EAEoE,EAFpE,CAJF,C,CAM2E;;;AAE3E,MAAME,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,WAAOA,KAAP,KAAiB,QAAjB,IAA6BK,QAAQ,CAACL,KAAD,CAHxC,E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N,CAAiBrB,MAAjB,CADW,GAEX;AACA;AACCC,IAAAA,KAAD,IAAgB;AACd,YAAMM,IAAI,GAAGtC,MAAM,CAACgC,KAAD,EAAQ,CAAC,UAAD,CAAR,CAAnB;AACA,aAAOD,MAAM,CAACO,IAAD,EAAON,KAAK,CAACqB,QAAb,CAAb;AACD,KAPL;AASCF,IAAAA,MAAD,CAAgBG,WAAhB,GAA8B3B,OAAO,CAACiB,IAAtC,CA3E2B,CA6E3B;;AACCO,IAAAA,MAAD,CAAgBH,SAAhB,GAA4B;AAC1BX,MAAAA,SAAS,EAAEV,OAAO,CAACS,KADO;AAE1BmB,MAAAA,OAAO,EAAE7B;AAFiB,KAA5B;AAKA,WAAOyB,MAAP;AACD,GApFD;AAqFD;;eA+CepC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIuC,KAAJ,CAAU/B,MAAV,EAAkB;AAChBgC,EAAAA,GAAG,CAACC,CAAD,EAAIpD,IAAJ,EAAuC;AACxC,WAAOoD,CAAC,CAACpD,IAAD,CAAR;AACD;;AAHe,CAAlB,CADY,GAMZmB,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 * as 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\n// Workaround for rest operator\nconst restOp = (\n obj: { [key: string]: any },\n keysToExclude: string[]\n): { [key: string]: any } =>\n Object.keys(obj)\n .filter((prop) => !keysToExclude.includes(prop))\n .reduce((acc, curr) => Object.assign(acc, { [curr]: obj[curr] }), {}); // rest operator workaround\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\n// If styled wraps custom component, that component should have className property\nfunction styled<TConstructor extends React.FunctionComponent<any>>(\n tag: TConstructor extends React.FunctionComponent<infer T>\n ? T extends { className?: string }\n ? TConstructor\n : never\n : never\n): ComponentStyledTag<TConstructor>;\nfunction styled<T>(\n tag: T extends { className?: string } ? React.ComponentType<T> : 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;\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 filteredProps.style = Object.assign(style, filteredProps.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 }\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\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\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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D,CAAgBI,WAAhB,GAA8B1B,OAAO,CAACa,IAAtC,CArE2B,CAuE3B;;IACCS,MAAD,CAAgBH,SAAhB,GAA4B;MAC1BX,SAAS,EAAER,OAAO,CAACO,KADO;MAE1BoB,OAAO,EAAE5B;IAFiB,CAA5B;IAKA,OAAOuB,MAAP;EACD,CA9ED;AA+ED;;eAgDelC,OAAO,CAACC,GAAR,CAAYC,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,54 +1,84 @@
1
1
  {
2
2
  "name": "@linaria/react",
3
- "version": "3.0.0-beta.2",
4
- "publishConfig": {
5
- "access": "public"
6
- },
7
3
  "description": "Blazing fast zero-runtime CSS in JS library",
8
- "sideEffects": false,
9
- "main": "lib/index.js",
10
- "module": "esm/index.js",
11
- "types": "types",
4
+ "version": "3.0.0-beta.22",
5
+ "bugs": "https://github.com/callstack/linaria/issues",
6
+ "dependencies": {
7
+ "@emotion/is-prop-valid": "^0.8.8",
8
+ "@linaria/core": "^3.0.0-beta.22",
9
+ "ts-invariant": "^0.10.3"
10
+ },
11
+ "devDependencies": {
12
+ "@babel/types": "^7.18.4",
13
+ "@types/babel__core": "^7.1.19",
14
+ "@types/node": "^17.0.39",
15
+ "@types/react": ">=16",
16
+ "react": "^16.14.0",
17
+ "react-test-renderer": "^16.8.3"
18
+ },
19
+ "engines": {
20
+ "node": "^12.16.0 || >=13.7.0"
21
+ },
22
+ "exports": {
23
+ "./package.json": "./package.json",
24
+ ".": {
25
+ "types": "./types/index.d.ts",
26
+ "import": "./esm/index.js",
27
+ "default": "./lib/index.js"
28
+ },
29
+ "./*": {
30
+ "types": "./types/*.d.ts",
31
+ "import": "./esm/*.js",
32
+ "default": "./lib/*.js"
33
+ }
34
+ },
12
35
  "files": [
13
- "types/",
36
+ "esm/",
14
37
  "lib/",
15
- "esm/"
38
+ "processors/",
39
+ "types/"
16
40
  ],
17
- "license": "MIT",
18
- "repository": "git@github.com:callstack/linaria.git",
19
- "bugs": {
20
- "url": "https://github.com/callstack/linaria/issues"
21
- },
22
41
  "homepage": "https://github.com/callstack/linaria#readme",
23
42
  "keywords": [
24
- "react",
25
- "linaria",
26
43
  "css",
27
44
  "css-in-js",
45
+ "linaria",
46
+ "react",
28
47
  "styled-components"
29
48
  ],
49
+ "license": "MIT",
50
+ "linaria": {
51
+ "tags": {
52
+ "styled": "./lib/processors/styled.js"
53
+ }
54
+ },
55
+ "main": "lib/index.js",
56
+ "module": "esm/index.js",
57
+ "peerDependencies": {
58
+ "react": ">=16"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public"
62
+ },
63
+ "repository": "git@github.com:callstack/linaria.git",
64
+ "sideEffects": false,
65
+ "types": "types/index.d.ts",
66
+ "typesVersions": {
67
+ "*": {
68
+ "processors/*": [
69
+ "./types/processors/*.d.ts"
70
+ ]
71
+ }
72
+ },
30
73
  "scripts": {
31
- "build:lib": "NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
32
- "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
33
- "build": "yarn build:lib && yarn build:esm",
74
+ "build": "npm run build:lib && npm run build:esm && npm run build:declarations",
75
+ "build:corejs-test": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --ignore \"src/processors/**/*\"",
34
76
  "build:declarations": "tsc --emitDeclarationOnly --outDir types",
35
- "prepare": "yarn build && yarn build:declarations",
77
+ "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
78
+ "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
36
79
  "test": "jest --config ../../jest.config.js --rootDir .",
37
80
  "test:dts": "dtslint --localTs ../../node_modules/typescript/lib __dtslint__",
38
81
  "typecheck": "tsc --noEmit --composite false",
39
- "watch": "yarn build --watch"
40
- },
41
- "devDependencies": {
42
- "@types/react": ">=16",
43
- "react": "^16.13.1",
44
- "react-test-renderer": "^16.8.3"
45
- },
46
- "dependencies": {
47
- "@emotion/is-prop-valid": "^0.8.8",
48
- "@linaria/core": "^3.0.0-beta.2"
49
- },
50
- "peerDependencies": {
51
- "react": ">=16"
52
- },
53
- "gitHead": "37c459ce01662a9b3df606e00db519f1db8c0665"
54
- }
82
+ "watch": "npm run build --watch"
83
+ }
84
+ }
@@ -0,0 +1,5 @@
1
+ Object.defineProperty(exports, '__esModule', {
2
+ value: true,
3
+ });
4
+
5
+ exports.default = require('../lib/processors/styled').default;
@@ -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,27 +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
- import * as React from 'react';
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
- declare function styled<TConstructor extends React.FunctionComponent<any>>(tag: TConstructor extends React.FunctionComponent<infer T> ? T extends {
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, {
11
15
  className?: string;
12
- } ? TConstructor : never : never): ComponentStyledTag<TConstructor>;
13
- declare function styled<T>(tag: T extends {
16
+ }>, TMustHave extends {
14
17
  className?: string;
15
- } ? React.ComponentType<T> : never): ComponentStyledTag<T>;
18
+ }, TConstructor extends Component<TProps>>(componentWithoutStyle: TConstructor & Component<TProps>): ComponentStyledTagWithoutInterpolation<TConstructor>;
16
19
  declare function styled<TName extends keyof JSX.IntrinsicElements>(tag: TName): HtmlStyledTag<TName>;
17
- declare type StyledComponent<T> = StyledMeta & (T extends React.FunctionComponent<any> ? T : React.FunctionComponent<T & {
20
+ declare function styled(component: 'The target component should have a className prop'): never;
21
+ declare type StyledComponent<T> = StyledMeta & ([T] extends [React.FunctionComponent<any>] ? T : React.FunctionComponent<T & {
18
22
  as?: React.ElementType;
19
23
  }>);
20
24
  declare type StaticPlaceholder = string | number | CSSProperties | StyledMeta;
21
- 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>;
22
- declare type ComponentStyledTag<T> = <OwnProps = {}, TrgProps = T extends React.FunctionComponent<infer TProps> ? TProps : T>(strings: TemplateStringsArray, ...exprs: TrgProps extends {
23
- style?: React.CSSProperties;
24
- } ? 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 = {}>(strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)>) => keyof OwnProps extends never ? StyledMeta & TOrigCmp : StyledComponent<OwnProps & TTrgProps>;
25
28
  declare type StyledJSXIntrinsics = {
26
29
  readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;
27
30
  };
package/CHANGELOG.md DELETED
@@ -1,8 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- # [3.0.0-beta.2](https://github.com/callstack/linaria/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-04-11)
7
-
8
- **Note:** Version bump only for package @linaria/react