@linaria/react 3.0.0-beta.4 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,11 +25,11 @@ Zero-runtime CSS in JS library.
25
25
  ## Installation
26
26
 
27
27
  ```sh
28
- npm install @linaria/core @linaria/react @linaria/babel-preset @linaria/shaker
28
+ npm install @linaria/core @linaria/react @linaria/babel-preset
29
29
  ```
30
30
 
31
31
  or
32
32
 
33
33
  ```sh
34
- yarn add @linaria/core @linaria/react @linaria/babel-preset @linaria/shaker
34
+ yarn add @linaria/core @linaria/react @linaria/babel-preset
35
35
  ```
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,181 @@
1
+ import { BaseProcessor, ValueType, hasMeta } from '@linaria/tags';
2
+
3
+ const isNotNull = x => x !== null;
4
+
5
+ const singleQuotedStringLiteral = value => ({
6
+ type: 'StringLiteral',
7
+ value,
8
+ extra: {
9
+ rawValue: value,
10
+ raw: `'${value}'`
11
+ }
12
+ });
13
+
14
+ export default class StyledProcessor extends BaseProcessor {
15
+ #variableIdx = 0;
16
+ #variablesCache = new Map();
17
+
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
+ if (value.kind === ValueType.FUNCTION) {
25
+ component = 'FunctionalComponent';
26
+ } else {
27
+ component = {
28
+ node: value.ex,
29
+ source: value.source
30
+ };
31
+ this.dependencies.push(value);
32
+ }
33
+ }
34
+
35
+ if (type === 'member') {
36
+ component = value;
37
+ }
38
+
39
+ if (!component || this.params.length > 1) {
40
+ throw new Error('Invalid usage of `styled` tag');
41
+ }
42
+
43
+ this.component = component;
44
+ }
45
+
46
+ addInterpolation(node, source, unit = '') {
47
+ const id = this.getVariableId(source + unit);
48
+ this.interpolations.push({
49
+ id,
50
+ node,
51
+ source,
52
+ unit
53
+ });
54
+ return id;
55
+ }
56
+
57
+ doEvaltimeReplacement() {
58
+ this.replacer(this.value, false);
59
+ }
60
+
61
+ doRuntimeReplacement() {
62
+ const t = this.astService;
63
+ const props = this.getProps();
64
+ this.replacer(t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true);
65
+ }
66
+
67
+ extractRules(valueCache, cssText, loc) {
68
+ const rules = {};
69
+ let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
70
+ // get its class name to create a more specific selector
71
+ // it'll ensure that styles are overridden properly
72
+
73
+ let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node.name);
74
+
75
+ while (hasMeta(value)) {
76
+ selector += `.${value.__linaria.className}`;
77
+ value = value.__linaria.extends;
78
+ }
79
+
80
+ rules[selector] = {
81
+ cssText,
82
+ className: this.className,
83
+ displayName: this.displayName,
84
+ start: loc?.start ?? null
85
+ };
86
+ return rules;
87
+ }
88
+
89
+ get asSelector() {
90
+ return `.${this.className}`;
91
+ }
92
+
93
+ get tagExpressionArgument() {
94
+ const t = this.astService;
95
+
96
+ if (typeof this.component === 'string') {
97
+ if (this.component === 'FunctionalComponent') {
98
+ return t.arrowFunctionExpression([], t.blockStatement([]));
99
+ }
100
+
101
+ return singleQuotedStringLiteral(this.component);
102
+ }
103
+
104
+ return t.callExpression(t.identifier(this.component.node.name), []);
105
+ }
106
+
107
+ get tagExpression() {
108
+ const t = this.astService;
109
+ return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
110
+ }
111
+
112
+ get value() {
113
+ const t = this.astService;
114
+ const extendsNode = typeof this.component === 'string' ? null : this.component.node.name;
115
+ return t.objectExpression([t.objectProperty(t.stringLiteral('displayName'), t.stringLiteral(this.displayName)), t.objectProperty(t.stringLiteral('__linaria'), t.objectExpression([t.objectProperty(t.stringLiteral('className'), t.stringLiteral(this.className)), t.objectProperty(t.stringLiteral('extends'), extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral())]))]);
116
+ }
117
+
118
+ getProps() {
119
+ const propsObj = {
120
+ name: this.displayName,
121
+ class: this.className
122
+ }; // If we found any interpolations, also pass them, so they can be applied
123
+
124
+ if (this.interpolations.length) {
125
+ propsObj.vars = {};
126
+ this.interpolations.forEach(({
127
+ id,
128
+ unit,
129
+ node
130
+ }) => {
131
+ const items = [this.astService.callExpression(node, [])];
132
+
133
+ if (unit) {
134
+ items.push(this.astService.stringLiteral(unit));
135
+ }
136
+
137
+ propsObj.vars[id] = items;
138
+ });
139
+ }
140
+
141
+ return propsObj;
142
+ }
143
+
144
+ getTagComponentProps(props) {
145
+ const t = this.astService;
146
+ const propExpressions = Object.entries(props).map(([key, value]) => {
147
+ if (!value) {
148
+ return null;
149
+ }
150
+
151
+ const keyNode = t.identifier(key);
152
+
153
+ if (typeof value === 'string') {
154
+ return t.objectProperty(keyNode, t.stringLiteral(value));
155
+ }
156
+
157
+ if (typeof value === 'boolean') {
158
+ return t.objectProperty(keyNode, t.booleanLiteral(value));
159
+ }
160
+
161
+ const vars = Object.entries(value).map(([propName, propValue]) => {
162
+ return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
163
+ });
164
+ return t.objectProperty(keyNode, t.objectExpression(vars));
165
+ }).filter(isNotNull);
166
+ return t.objectExpression(propExpressions);
167
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
168
+
169
+
170
+ getVariableId(value) {
171
+ if (!this.#variablesCache.has(value)) {
172
+ // make the variable unique to this styled component
173
+ // eslint-disable-next-line no-plusplus
174
+ this.#variablesCache.set(value, `${this.slug}-${this.#variableIdx++}`);
175
+ }
176
+
177
+ return this.#variablesCache.get(value);
178
+ }
179
+
180
+ }
181
+ //# sourceMappingURL=styled.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styled.js","names":["BaseProcessor","ValueType","hasMeta","isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","variableIdx","variablesCache","Map","constructor","args","component","rest","params","length","kind","FUNCTION","node","ex","source","dependencies","push","Error","addInterpolation","unit","id","getVariableId","interpolations","doEvaltimeReplacement","replacer","doRuntimeReplacement","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","extractRules","valueCache","cssText","loc","rules","selector","className","get","name","__linaria","extends","displayName","start","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","tagExp","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","propsObj","class","vars","forEach","items","propExpressions","Object","entries","map","key","keyNode","booleanLiteral","propName","propValue","arrayExpression","filter","has","set","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 { BaseProcessor, ValueType, hasMeta } from '@linaria/tags';\nimport type {\n Rules,\n WrappedNode,\n ValueCache,\n ProcessorParams,\n} from '@linaria/tags';\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 #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\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 if (value.kind === ValueType.FUNCTION) {\n component = 'FunctionalComponent';\n } else {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (type === 'member') {\n component = value;\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(\n node: Expression,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source + unit);\n\n this.interpolations.push({\n id,\n node,\n source,\n unit,\n });\n\n return id;\n }\n\n public override doEvaltimeReplacement(): void {\n this.replacer(this.value, false);\n }\n\n public override doRuntimeReplacement(): void {\n const t = this.astService;\n\n const props = this.getProps();\n\n this.replacer(\n t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),\n true\n );\n }\n\n public override extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): Rules {\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.name);\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;\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.callExpression(t.identifier(this.component.node.name), []);\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 value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n protected getProps(): 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 this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(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 if (!this.#variablesCache.has(value)) {\n // make the variable unique to this styled component\n // eslint-disable-next-line no-plusplus\n this.#variablesCache.set(value, `${this.slug}-${this.#variableIdx++}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":"AAQA,SAASA,aAAT,EAAwBC,SAAxB,EAAmCC,OAAnC,QAAk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KgF,IAAK,IAAG,KAAK,CAAC1E,WAAN,EAAoB,EAApE;IACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqBsC,GAArB,CAAyB7C,KAAzB,CAAP;EACD;;AAtNwD"}
package/esm/styled.js CHANGED
@@ -1,23 +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.indexOf(prop) === -1).reduce((acc, curr) => {
13
- acc[curr] = obj[curr];
14
- return acc;
15
- }, {}); // 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
+ };
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
+ }
16
36
 
37
+ return filteredProps;
38
+ }
17
39
 
18
40
  const warnIfInvalid = (value, componentName) => {
19
41
  if (process.env.NODE_ENV !== 'production') {
20
- 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
21
43
  typeof value === 'number' && isFinite(value)) {
22
44
  return;
23
45
  }
@@ -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];
@@ -101,7 +108,7 @@ function styled(tag) {
101
108
  const Result = React.forwardRef ? /*#__PURE__*/React.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
102
109
  // Fallback to a innerRef prop in that case
103
110
  props => {
104
- const rest = restOp(props, ['innerRef']);
111
+ const rest = omit(props, ['innerRef']);
105
112
  return render(rest, props.innerRef);
106
113
  };
107
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","indexOf","reduce","acc","curr","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","key","vars","style","name","variable","result","unit","ownStyle","length","forEach","__linaria","createElement","Result","forwardRef","innerRef","displayName","extends","Proxy","get","o"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,OAAOC,SAAP,MAAsB,wBAAtB;AACA,SAASC,EAAT,QAAmB,eAAnB;;AAgBA;AACA,MAAMC,MAAM,GAAG,CACbC,GADa,EAEbC,aAFa,KAIbC,MAAM,CAACC,IAAP,CAAYH,GAAZ,EACGI,MADH,CACWC,IAAD,IAAUJ,aAAa,CAACK,OAAd,CAAsBD,IAAtB,MAAgC,CAAC,CADrD,EAEGE,MAFH,CAEU,CAACC,GAAD,EAAMC,IAAN,KAAe;AACrBD,EAAAA,GAAG,CAACC,IAAD,CAAH,GAAYT,GAAG,CAACS,IAAD,CAAf;AACA,SAAOD,GAAP;AACD,CALH,EAKK,EALL,CAJF,C,CASuC;;;AAEvC,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,EAIE;AACA;AACD;;AAED,UAAMM,WAAW,GACf,OAAON,KAAP,KAAiB,QAAjB,GAA4BO,IAAI,CAACC,SAAL,CAAeR,KAAf,CAA5B,GAAoDS,MAAM,CAACT,KAAD,CAD5D,CATyC,CAYzC;;AACAU,IAAAA,OAAO,CAACC,IAAR,CACG,kCAAiCL,WAAY,uBAAsBL,aAAc,gGADpF;AAGD;AACF,CAlBD;;AAwCA,SAASW,MAAT,CAAgBC,GAAhB,EAA+B;AAC7B,SAAQC,OAAD,IAAsB;AAC3B,QAAIZ,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,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AAM,CAAC+B,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,CAACgB,IAAtC,CAnF2B,CAqF3B;;AACCS,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,EAAIpD,IAAJ,EAAuC;AACxC,WAAOoD,CAAC,CAACpD,IAAD,CAAR;AACD;;AAHe,CAAlB,CADY,GAMZkB,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: Record<string, unknown>,\n keysToExclude: string[]\n): Record<string, unknown> =>\n Object.keys(obj)\n .filter((prop) => keysToExclude.indexOf(prop) === -1)\n .reduce((acc, curr) => {\n acc[curr] = obj[curr];\n return acc;\n }, {} as Record<string, unknown>); // 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\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.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: 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 }\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 } from '@linaria/core';\nimport type { StyledMeta } from '@linaria/tags';\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;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AAjB,CADW,GAEX;IACA;IACCtB,KAAD,IAAgB;MACd,MAAMwC,IAAI,GAAGhD,IAAI,CAACQ,KAAD,EAAQ,CAAC,UAAD,CAAR,CAAjB;MACA,OAAOsB,MAAM,CAACkB,IAAD,EAAOxC,KAAK,CAACyC,QAAb,CAAb;IACD,CAPL;IASCH,MAAD,CAAgBI,WAAhB,GAA8BxB,OAAO,CAACY,IAAtC,CArE2B,CAuE3B;;IACCQ,MAAD,CAAgBF,SAAhB,GAA4B;MAC1BV,SAAS,EAAER,OAAO,CAACO,KADO;MAE1BkB,OAAO,EAAE1B;IAFiB,CAA5B;IAKA,OAAOqB,MAAP;EACD,CA9ED;AA+ED;;AAgDD,eAAgBhC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIoC,KAAJ,CAAU5B,MAAV,EAAkB;EAChB6B,GAAG,CAACC,CAAD,EAAIC,IAAJ,EAAuC;IACxC,OAAOD,CAAC,CAACC,IAAD,CAAR;EACD;;AAHe,CAAlB,CADY,GAMZ/B,MANJ"}
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,194 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _tags = require("@linaria/tags");
9
+
10
+ const isNotNull = x => x !== null;
11
+
12
+ const singleQuotedStringLiteral = value => ({
13
+ type: 'StringLiteral',
14
+ value,
15
+ extra: {
16
+ rawValue: value,
17
+ raw: `'${value}'`
18
+ }
19
+ });
20
+
21
+ class StyledProcessor extends _tags.BaseProcessor {
22
+ #variableIdx = 0;
23
+ #variablesCache = new Map();
24
+
25
+ constructor(...args) {
26
+ var _this$params$;
27
+
28
+ super(...args);
29
+ let component;
30
+ const [type, value, ...rest] = (_this$params$ = this.params[0]) !== null && _this$params$ !== void 0 ? _this$params$ : [];
31
+
32
+ if (type === 'call' && rest.length === 0) {
33
+ if (value.kind === _tags.ValueType.FUNCTION) {
34
+ component = 'FunctionalComponent';
35
+ } else {
36
+ component = {
37
+ node: value.ex,
38
+ source: value.source
39
+ };
40
+ this.dependencies.push(value);
41
+ }
42
+ }
43
+
44
+ if (type === 'member') {
45
+ component = value;
46
+ }
47
+
48
+ if (!component || this.params.length > 1) {
49
+ throw new Error('Invalid usage of `styled` tag');
50
+ }
51
+
52
+ this.component = component;
53
+ }
54
+
55
+ addInterpolation(node, source, unit = '') {
56
+ const id = this.getVariableId(source + unit);
57
+ this.interpolations.push({
58
+ id,
59
+ node,
60
+ source,
61
+ unit
62
+ });
63
+ return id;
64
+ }
65
+
66
+ doEvaltimeReplacement() {
67
+ this.replacer(this.value, false);
68
+ }
69
+
70
+ doRuntimeReplacement() {
71
+ const t = this.astService;
72
+ const props = this.getProps();
73
+ this.replacer(t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true);
74
+ }
75
+
76
+ extractRules(valueCache, cssText, loc) {
77
+ var _loc$start;
78
+
79
+ const rules = {};
80
+ let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
81
+ // get its class name to create a more specific selector
82
+ // it'll ensure that styles are overridden properly
83
+
84
+ let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node.name);
85
+
86
+ while ((0, _tags.hasMeta)(value)) {
87
+ selector += `.${value.__linaria.className}`;
88
+ value = value.__linaria.extends;
89
+ }
90
+
91
+ rules[selector] = {
92
+ cssText,
93
+ className: this.className,
94
+ displayName: this.displayName,
95
+ start: (_loc$start = loc === null || loc === void 0 ? void 0 : loc.start) !== null && _loc$start !== void 0 ? _loc$start : null
96
+ };
97
+ return rules;
98
+ }
99
+
100
+ get asSelector() {
101
+ return `.${this.className}`;
102
+ }
103
+
104
+ get tagExpressionArgument() {
105
+ const t = this.astService;
106
+
107
+ if (typeof this.component === 'string') {
108
+ if (this.component === 'FunctionalComponent') {
109
+ return t.arrowFunctionExpression([], t.blockStatement([]));
110
+ }
111
+
112
+ return singleQuotedStringLiteral(this.component);
113
+ }
114
+
115
+ return t.callExpression(t.identifier(this.component.node.name), []);
116
+ }
117
+
118
+ get tagExpression() {
119
+ const t = this.astService;
120
+ return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
121
+ }
122
+
123
+ get value() {
124
+ const t = this.astService;
125
+ const extendsNode = typeof this.component === 'string' ? null : this.component.node.name;
126
+ return t.objectExpression([t.objectProperty(t.stringLiteral('displayName'), t.stringLiteral(this.displayName)), t.objectProperty(t.stringLiteral('__linaria'), t.objectExpression([t.objectProperty(t.stringLiteral('className'), t.stringLiteral(this.className)), t.objectProperty(t.stringLiteral('extends'), extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral())]))]);
127
+ }
128
+
129
+ getProps() {
130
+ const propsObj = {
131
+ name: this.displayName,
132
+ class: this.className
133
+ }; // If we found any interpolations, also pass them, so they can be applied
134
+
135
+ if (this.interpolations.length) {
136
+ propsObj.vars = {};
137
+ this.interpolations.forEach(({
138
+ id,
139
+ unit,
140
+ node
141
+ }) => {
142
+ const items = [this.astService.callExpression(node, [])];
143
+
144
+ if (unit) {
145
+ items.push(this.astService.stringLiteral(unit));
146
+ }
147
+
148
+ propsObj.vars[id] = items;
149
+ });
150
+ }
151
+
152
+ return propsObj;
153
+ }
154
+
155
+ getTagComponentProps(props) {
156
+ const t = this.astService;
157
+ const propExpressions = Object.entries(props).map(([key, value]) => {
158
+ if (!value) {
159
+ return null;
160
+ }
161
+
162
+ const keyNode = t.identifier(key);
163
+
164
+ if (typeof value === 'string') {
165
+ return t.objectProperty(keyNode, t.stringLiteral(value));
166
+ }
167
+
168
+ if (typeof value === 'boolean') {
169
+ return t.objectProperty(keyNode, t.booleanLiteral(value));
170
+ }
171
+
172
+ const vars = Object.entries(value).map(([propName, propValue]) => {
173
+ return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
174
+ });
175
+ return t.objectProperty(keyNode, t.objectExpression(vars));
176
+ }).filter(isNotNull);
177
+ return t.objectExpression(propExpressions);
178
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
179
+
180
+
181
+ getVariableId(value) {
182
+ if (!this.#variablesCache.has(value)) {
183
+ // make the variable unique to this styled component
184
+ // eslint-disable-next-line no-plusplus
185
+ this.#variablesCache.set(value, `${this.slug}-${this.#variableIdx++}`);
186
+ }
187
+
188
+ return this.#variablesCache.get(value);
189
+ }
190
+
191
+ }
192
+
193
+ exports.default = StyledProcessor;
194
+ //# sourceMappingURL=styled.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styled.js","names":["isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","BaseProcessor","variableIdx","variablesCache","Map","constructor","args","component","rest","params","length","kind","ValueType","FUNCTION","node","ex","source","dependencies","push","Error","addInterpolation","unit","id","getVariableId","interpolations","doEvaltimeReplacement","replacer","doRuntimeReplacement","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","extractRules","valueCache","cssText","loc","rules","selector","className","get","name","hasMeta","__linaria","extends","displayName","start","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","tagExp","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","propsObj","class","vars","forEach","items","propExpressions","Object","entries","map","key","keyNode","booleanLiteral","propName","propValue","arrayExpression","filter","has","set","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 { BaseProcessor, ValueType, hasMeta } from '@linaria/tags';\nimport type {\n Rules,\n WrappedNode,\n ValueCache,\n ProcessorParams,\n} from '@linaria/tags';\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 #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\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 if (value.kind === ValueType.FUNCTION) {\n component = 'FunctionalComponent';\n } else {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (type === 'member') {\n component = value;\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(\n node: Expression,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source + unit);\n\n this.interpolations.push({\n id,\n node,\n source,\n unit,\n });\n\n return id;\n }\n\n public override doEvaltimeReplacement(): void {\n this.replacer(this.value, false);\n }\n\n public override doRuntimeReplacement(): void {\n const t = this.astService;\n\n const props = this.getProps();\n\n this.replacer(\n t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),\n true\n );\n }\n\n public override extractRules(\n valueCache: ValueCache,\n cssText: string,\n loc?: SourceLocation | null\n ): Rules {\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.name);\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;\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.callExpression(t.identifier(this.component.node.name), []);\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 value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n protected getProps(): 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 this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(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 if (!this.#variablesCache.has(value)) {\n // make the variable unique to this styled component\n // eslint-disable-next-line no-plusplus\n this.#variablesCache.set(value, `${this.slug}-${this.#variableIdx++}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":";;;;;;;AAQA;;AAQA,MAAMA,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIC,KAAD,KAAmC;EACnEC,IAAI,EAAE,eAD6D;EAEnED,KAFmE;EAGnEE,KAAK,EAAE;IACLC,QAAQ,EAAEH,KADL;IAELI,GAAG,EAAG,IAAGJ,KAAM;EAFV;AAH4D,CAAnC,CAAlC;;AASe,MAAMK,eAAN,SAA8BC,mBAA9B,CAA4C;EAGzD,CAACC,WAAD,GAAe,CAAf;EAEA,CAACC,cAAD,GAAkB,IAAIC,GAAJ,EAAlB;;EAEAC,WAAW,CAAC,GAAGC,IAAJ,EAA2B;IAAA;;IACpC,MAAM,GAAGA,IAAT;IAEA,IAAIC,SAAJ;IACA,MAAM,CAACX,IAAD,EAAOD,KAAP,EAAc,GAAGa,IAAjB,qBAAyB,KAAKC,MAAL,CAAY,CAAZ,CAAzB,yDAA2C,EAAjD;;IACA,IAAIb,IAAI,KAAK,MAAT,IAAmBY,IAAI,CAACE,MAAL,KAAgB,CAAvC,EAA0C;MACxC,IAAIf,KAAK,CAACgB,IAAN,KAAeC,eAAA,CAAUC,QAA7B,EAAuC;QACrCN,SAAS,GAAG,qBAAZ;MACD,CAFD,MAEO;QACLA,SAAS,GAAG;UACVO,IAAI,EAAEnB,KAAK,CAACoB,EADF;UAEVC,MAAM,EAAErB,KAAK,CAACqB;QAFJ,CAAZ;Q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B,EAA0B1C,CAAC,CAAC4B,gBAAF,CAAmBM,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBa,MAzBqB,CAyBdnF,SAzBc,CAAxB;IA2BA,OAAOoC,CAAC,CAAC4B,gBAAF,CAAmBS,eAAnB,CAAP;EACD,CA3MwD,CA6MzD;;;EACU1C,aAAa,CAAC5B,KAAD,EAAwB;IAC7C,IAAI,CAAC,KAAK,CAACQ,cAAN,CAAqByE,GAArB,CAAyBjF,KAAzB,CAAL,EAAsC;MACpC;MACA;MACA,KAAK,CAACQ,cAAN,CAAqB0E,GAArB,CAAyBlF,KAAzB,EAAiC,GAAE,KAAKmF,IAAK,IAAG,KAAK,CAAC5E,WAAN,EAAoB,EAApE;IACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqBuC,GAArB,CAAyB/C,KAAzB,CAAP;EACD;;AAtNwD"}
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 _getRequireWildcardCache() { 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,32 +19,50 @@ 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
- var restOp = function restOp(obj, keysToExclude) {
26
- return Object.keys(obj).filter(function (prop) {
27
- return keysToExclude.indexOf(prop) === -1;
28
- }).reduce(function (acc, curr) {
29
- acc[curr] = obj[curr];
30
- return acc;
31
- }, {});
32
- }; // rest operator workaround
33
-
34
-
35
- var warnIfInvalid = function warnIfInvalid(value, componentName) {
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
+ }
47
+
48
+ return filteredProps;
49
+ }
50
+
51
+ const warnIfInvalid = (value, componentName) => {
36
52
  if (process.env.NODE_ENV !== 'production') {
37
- 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
38
54
  typeof value === 'number' && isFinite(value)) {
39
55
  return;
40
56
  }
41
57
 
42
- 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
43
59
 
44
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.");
45
61
  }
46
62
  };
47
63
 
48
64
  function styled(tag) {
49
- return function (options) {
65
+ return options => {
50
66
  if (process.env.NODE_ENV !== 'production') {
51
67
  if (Array.isArray(options)) {
52
68
  // We received a strings array since it's used as a tag
@@ -54,47 +70,35 @@ function styled(tag) {
54
70
  }
55
71
  }
56
72
 
57
- var render = function render(props, ref) {
58
- var _props$as = props.as,
59
- component = _props$as === void 0 ? tag : _props$as,
60
- className = props.class;
61
- var rest = restOp(props, ['as', 'class']);
62
- var filteredProps; // Check if it's an HTML tag and not a custom element
63
-
64
- if (typeof component === 'string' && component.indexOf('-') === -1) {
65
- filteredProps = {}; // eslint-disable-next-line guard-for-in
66
-
67
- for (var _key in rest) {
68
- if (_key === 'as' || (0, _isPropValid.default)(_key)) {
69
- // Don't pass through invalid attributes to HTML elements
70
- filteredProps[_key] = rest[_key];
71
- }
72
- }
73
- } else {
74
- filteredProps = rest;
75
- }
76
-
73
+ const render = (props, ref) => {
74
+ const {
75
+ as: component = tag,
76
+ class: className
77
+ } = props;
78
+ const filteredProps = filterProps(component, props, ['as', 'class']);
77
79
  filteredProps.ref = ref;
78
- filteredProps.className = (0, _core.cx)(filteredProps.className || className, options.class);
79
- 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;
80
84
 
81
85
  if (vars) {
82
- var style = {}; // eslint-disable-next-line guard-for-in
86
+ const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
83
87
 
84
- for (var name in vars) {
85
- var variable = vars[name];
86
- var result = variable[0];
87
- var unit = variable[1] || '';
88
- 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;
89
93
  warnIfInvalid(value, options.name);
90
94
  style["--" + name] = "" + value + unit;
91
95
  }
92
96
 
93
- var ownStyle = filteredProps.style || {};
94
- var keys = Object.keys(ownStyle);
97
+ const ownStyle = filteredProps.style || {};
98
+ const keys = Object.keys(ownStyle);
95
99
 
96
100
  if (keys.length > 0) {
97
- keys.forEach(function (key) {
101
+ keys.forEach(key => {
98
102
  style[key] = ownStyle[key];
99
103
  });
100
104
  }
@@ -106,16 +110,16 @@ function styled(tag) {
106
110
  // If the underlying tag is a styled component, forward the `as` prop
107
111
  // Otherwise the styles from the underlying component will be ignored
108
112
  filteredProps.as = component;
109
- return /*#__PURE__*/React.createElement(tag, filteredProps);
113
+ return /*#__PURE__*/_react.default.createElement(tag, filteredProps);
110
114
  }
111
115
 
112
- return /*#__PURE__*/React.createElement(component, filteredProps);
116
+ return /*#__PURE__*/_react.default.createElement(component, filteredProps);
113
117
  };
114
118
 
115
- var 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
116
120
  // Fallback to a innerRef prop in that case
117
- function (props) {
118
- var rest = restOp(props, ['innerRef']);
121
+ props => {
122
+ const rest = omit(props, ['innerRef']);
119
123
  return render(rest, props.innerRef);
120
124
  };
121
125
  Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
@@ -129,9 +133,10 @@ function styled(tag) {
129
133
  }
130
134
 
131
135
  var _default = process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
132
- get: function get(o, prop) {
136
+ get(o, prop) {
133
137
  return o(prop);
134
138
  }
139
+
135
140
  }) : styled;
136
141
 
137
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","indexOf","reduce","acc","curr","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","key","vars","style","name","variable","result","unit","ownStyle","length","forEach","__linaria","React","createElement","Result","forwardRef","innerRef","displayName","extends","Proxy","get","o"],"mappings":";;;;;AAMA;;AACA;;AACA;;;;;;;;AARA;AACA;AACA;AACA;AACA;AACA;AAmBA;AACA,IAAMA,MAAM,GAAG,SAATA,MAAS,CACbC,GADa,EAEbC,aAFa;AAAA,SAIbC,MAAM,CAACC,IAAP,CAAYH,GAAZ,EACGI,MADH,CACU,UAACC,IAAD;AAAA,WAAUJ,aAAa,CAACK,OAAd,CAAsBD,IAAtB,MAAgC,CAAC,CAA3C;AAAA,GADV,EAEGE,MAFH,CAEU,UAACC,GAAD,EAAMC,IAAN,EAAe;AACrBD,IAAAA,GAAG,CAACC,IAAD,CAAH,GAAYT,GAAG,CAACS,IAAD,CAAf;AACA,WAAOD,GAAP;AACD,GALH,EAKK,EALL,CAJa;AAAA,CAAf,C,CASuC;;;AAEvC,IAAME,aAAa,GAAG,SAAhBA,aAAgB,CAACC,KAAD,EAAaC,aAAb,EAAuC;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,EAIE;AACA;AACD;;AAED,QAAMM,WAAW,GACf,OAAON,KAAP,KAAiB,QAAjB,GAA4BO,IAAI,CAACC,SAAL,CAA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,CAAP;AACD;;AACD,0BAAOY,KAAK,CAACC,aAAN,CAAoBjB,SAApB,EAA+BI,aAA/B,CAAP;AACD,KA9DD;;AAgEA,QAAMc,MAAM,GAAGF,KAAK,CAACG,UAAN,gBACXH,KAAK,CAACG,UAAN,CAAiBvB,MAAjB,CADW,GAEX;AACA;AACA,cAACC,KAAD,EAAgB;AACd,UAAMM,IAAI,GAAGrC,MAAM,CAAC+B,KAAD,EAAQ,CAAC,UAAD,CAAR,CAAnB;AACA,aAAOD,MAAM,CAACO,IAAD,EAAON,KAAK,CAACuB,QAAb,CAAb;AACD,KAPL;AASCF,IAAAA,MAAD,CAAgBG,WAAhB,GAA8B7B,OAAO,CAACgB,IAAtC,CAnF2B,CAqF3B;;AACCU,IAAAA,MAAD,CAAgBH,SAAhB,GAA4B;AAC1Bd,MAAAA,SAAS,EAAET,OAAO,CAACU,KADO;AAE1BoB,MAAAA,OAAO,EAAE/B;AAFiB,KAA5B;AAKA,WAAO2B,MAAP;AACD,GA5FD;AA6FD;;eA+CetC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIyC,KAAJ,CAAUjC,MAAV,EAAkB;AAChBkC,EAAAA,GADgB,eACZC,CADY,EACTrD,IADS,EAC0B;AACxC,WAAOqD,CAAC,CAACrD,IAAD,CAAR;AACD;AAHe,CAAlB,CADY,GAMZkB,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: Record<string, unknown>,\n keysToExclude: string[]\n): Record<string, unknown> =>\n Object.keys(obj)\n .filter((prop) => keysToExclude.indexOf(prop) === -1)\n .reduce((acc, curr) => {\n acc[curr] = obj[curr];\n return acc;\n }, {} as Record<string, unknown>); // 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\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.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: 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 }\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 } from '@linaria/core';\nimport type { StyledMeta } from '@linaria/tags';\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;AA4BA,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,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,IACE,OAAOF,SAAP,KAAqB,QAArB,IACAA,SAAS,CAACR,OAAV,CAAkB,GAAlB,MAA2B,CAAC,CAD5B,IAEA,CAACN,SAAS,CAACc,SAAS,CAAC,CAAD,CAAV,CAHZ,EAIE;IACAJ,MAAM,CAACN,IAAP,CAAYa,aAAZ,EAA2BL,OAA3B,CAAoCP,GAAD,IAAS;MAC1C,IAAI,CAAC,IAAAa,oBAAA,EAAUb,GAAV,CAAL,EAAqB;QACnB;QACA,OAAOY,aAAa,CAACZ,GAAD,CAApB;MACD;IACF,CALD;EAMD;;EAED,OAAOY,a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,CAAoBzC,SAApB,EAA+BG,aAA/B,CAAP;IACD,CAhDD;;IAkDA,MAAMuC,MAAM,GAAGF,cAAA,CAAMG,UAAN,gBACXH,cAAA,CAAMG,UAAN,CAAiBnB,MAAjB,CADW,GAEX;IACA;IACCvB,KAAD,IAAgB;MACd,MAAM2C,IAAI,GAAGnD,IAAI,CAACQ,KAAD,EAAQ,CAAC,UAAD,CAAR,CAAjB;MACA,OAAOuB,MAAM,CAACoB,IAAD,EAAO3C,KAAK,CAAC4C,QAAb,CAAb;IACD,CAPL;IASCH,MAAD,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,85 @@
1
1
  {
2
2
  "name": "@linaria/react",
3
- "version": "3.0.0-beta.4",
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/index.d.ts",
4
+ "version": "4.0.0-beta.1",
5
+ "bugs": "https://github.com/callstack/linaria/issues",
6
+ "dependencies": {
7
+ "@emotion/is-prop-valid": "^0.8.8",
8
+ "@linaria/core": "^4.0.0-beta.1",
9
+ "@linaria/tags": "^4.0.0-beta.1",
10
+ "ts-invariant": "^0.10.3"
11
+ },
12
+ "devDependencies": {
13
+ "@babel/types": "^7.18.9",
14
+ "@types/babel__core": "^7.1.19",
15
+ "@types/node": "^17.0.39",
16
+ "@types/react": ">=16",
17
+ "react": "^16.14.0",
18
+ "react-test-renderer": "^16.8.3"
19
+ },
20
+ "engines": {
21
+ "node": "^12.16.0 || >=13.7.0"
22
+ },
23
+ "exports": {
24
+ "./package.json": "./package.json",
25
+ ".": {
26
+ "types": "./types/index.d.ts",
27
+ "import": "./esm/index.js",
28
+ "default": "./lib/index.js"
29
+ },
30
+ "./*": {
31
+ "types": "./types/*.d.ts",
32
+ "import": "./esm/*.js",
33
+ "default": "./lib/*.js"
34
+ }
35
+ },
12
36
  "files": [
13
- "types/",
37
+ "esm/",
14
38
  "lib/",
15
- "esm/"
39
+ "processors/",
40
+ "types/"
16
41
  ],
17
- "license": "MIT",
18
- "repository": "git@github.com:callstack/linaria.git",
19
- "bugs": {
20
- "url": "https://github.com/callstack/linaria/issues"
21
- },
22
42
  "homepage": "https://github.com/callstack/linaria#readme",
23
43
  "keywords": [
24
- "react",
25
- "linaria",
26
44
  "css",
27
45
  "css-in-js",
46
+ "linaria",
47
+ "react",
28
48
  "styled-components"
29
49
  ],
50
+ "license": "MIT",
51
+ "linaria": {
52
+ "tags": {
53
+ "styled": "./lib/processors/styled.js"
54
+ }
55
+ },
56
+ "main": "lib/index.js",
57
+ "module": "esm/index.js",
58
+ "peerDependencies": {
59
+ "react": ">=16"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "repository": "git@github.com:callstack/linaria.git",
65
+ "sideEffects": false,
66
+ "types": "types/index.d.ts",
67
+ "typesVersions": {
68
+ "*": {
69
+ "processors/*": [
70
+ "./types/processors/*.d.ts"
71
+ ]
72
+ }
73
+ },
30
74
  "scripts": {
31
- "build:lib": "cross-env 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",
75
+ "build": "npm run build:lib && npm run build:esm && npm run build:declarations",
76
+ "build:corejs-test": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --ignore \"src/processors/**/*\"",
34
77
  "build:declarations": "tsc --emitDeclarationOnly --outDir types",
35
- "prepare": "yarn build && yarn build:declarations",
78
+ "build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
79
+ "build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
36
80
  "test": "jest --config ../../jest.config.js --rootDir .",
37
81
  "test:dts": "dtslint --localTs ../../node_modules/typescript/lib __dtslint__",
38
82
  "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.4"
49
- },
50
- "peerDependencies": {
51
- "react": ">=16"
52
- },
53
- "gitHead": "20e1ba5f60d06b2399bd54d723be91364b8acea3"
54
- }
83
+ "watch": "npm run build --watch"
84
+ }
85
+ }
@@ -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,25 @@
1
+ import type { CallExpression, Expression, ObjectExpression, SourceLocation } from '@babel/types';
2
+ import { BaseProcessor } from '@linaria/tags';
3
+ import type { Rules, WrappedNode, ValueCache, ProcessorParams } from '@linaria/tags';
4
+ export interface IProps {
5
+ atomic?: boolean;
6
+ class?: string;
7
+ name: string;
8
+ vars?: Record<string, Expression[]>;
9
+ }
10
+ export default class StyledProcessor extends BaseProcessor {
11
+ #private;
12
+ component: WrappedNode;
13
+ constructor(...args: ProcessorParams);
14
+ addInterpolation(node: Expression, source: string, unit?: string): string;
15
+ doEvaltimeReplacement(): void;
16
+ doRuntimeReplacement(): void;
17
+ extractRules(valueCache: ValueCache, cssText: string, loc?: SourceLocation | null): Rules;
18
+ get asSelector(): string;
19
+ protected get tagExpressionArgument(): Expression;
20
+ protected get tagExpression(): CallExpression;
21
+ get value(): ObjectExpression;
22
+ protected getProps(): IProps;
23
+ protected getTagComponentProps(props: IProps): ObjectExpression;
24
+ protected getVariableId(value: string): string;
25
+ }
package/types/styled.d.ts CHANGED
@@ -1,27 +1,31 @@
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';
8
- 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 {
1
+ import React from 'react';
2
+ import type { CSSProperties } from '@linaria/core';
3
+ import type { StyledMeta } from '@linaria/tags';
4
+ export declare type NoInfer<A> = [A][A extends any ? 0 : never];
5
+ declare type Component<TProps> = ((props: TProps) => unknown) | {
6
+ new (props: TProps): unknown;
7
+ };
8
+ declare type Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;
9
+ export declare const omit: <T extends Record<string, unknown>, TKeys extends keyof T>(obj: T, keys: TKeys[]) => Omit<T, TKeys>;
10
+ declare function styled<TProps extends Has<TMustHave, {
11
+ style?: React.CSSProperties;
12
+ }>, TMustHave extends {
13
+ style?: React.CSSProperties;
14
+ }, TConstructor extends Component<TProps>>(componentWithStyle: TConstructor & Component<TProps>): ComponentStyledTagWithInterpolation<TProps, TConstructor>;
15
+ declare function styled<TProps extends Has<TMustHave, {
11
16
  className?: string;
12
- } ? TConstructor : never : never): ComponentStyledTag<TConstructor>;
13
- declare function styled<T>(tag: T extends {
17
+ }>, TMustHave extends {
14
18
  className?: string;
15
- } ? React.ComponentType<T> : never): ComponentStyledTag<T>;
19
+ }, TConstructor extends Component<TProps>>(componentWithoutStyle: TConstructor & Component<TProps>): ComponentStyledTagWithoutInterpolation<TConstructor>;
16
20
  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 & {
21
+ declare function styled(component: 'The target component should have a className prop'): never;
22
+ declare type StyledComponent<T> = StyledMeta & ([T] extends [React.FunctionComponent<any>] ? T : React.FunctionComponent<T & {
18
23
  as?: React.ElementType;
19
24
  }>);
20
25
  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>;
26
+ 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>;
27
+ declare type ComponentStyledTagWithoutInterpolation<TOrigCmp> = (strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: 'The target component should have a style prop') => never)>) => StyledMeta & TOrigCmp;
28
+ 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
29
  declare type StyledJSXIntrinsics = {
26
30
  readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;
27
31
  };
package/CHANGELOG.md DELETED
@@ -1,27 +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.4](https://github.com/callstack/linaria/compare/v3.0.0-beta.3...v3.0.0-beta.4) (2021-05-07)
7
-
8
- **Note:** Version bump only for package @linaria/react
9
-
10
-
11
-
12
-
13
-
14
- # [3.0.0-beta.3](https://github.com/callstack/linaria/compare/v3.0.0-beta.2...v3.0.0-beta.3) (2021-04-20)
15
-
16
-
17
- ### Bug Fixes
18
-
19
- * **core,react:** make IE 11 compatible (fixes [#746](https://github.com/callstack/linaria/issues/746)) ([#750](https://github.com/callstack/linaria/issues/750)) ([922df95](https://github.com/callstack/linaria/commit/922df9576a430cdfe9b27aed5dc45c4f75917607))
20
-
21
-
22
-
23
-
24
-
25
- # [3.0.0-beta.2](https://github.com/callstack/linaria/compare/v3.0.0-beta.1...v3.0.0-beta.2) (2021-04-11)
26
-
27
- **Note:** Version bump only for package @linaria/react