@linaria/react 4.0.0-beta.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
  ```
@@ -1,6 +1,4 @@
1
- import BaseProcessor from '@linaria/core/processors/BaseProcessor';
2
- import { ValueType } from '@linaria/core/processors/types';
3
- import hasMeta from '@linaria/core/processors/utils/hasMeta';
1
+ import { TaggedTemplateProcessor, ValueType, hasMeta, validateParams } from '@linaria/tags';
4
2
 
5
3
  const isNotNull = x => x !== null;
6
4
 
@@ -13,16 +11,19 @@ const singleQuotedStringLiteral = value => ({
13
11
  }
14
12
  });
15
13
 
16
- export default class StyledProcessor extends BaseProcessor {
14
+ export default class StyledProcessor extends TaggedTemplateProcessor {
17
15
  #variableIdx = 0;
18
16
  #variablesCache = new Map();
19
17
 
20
- constructor(...args) {
21
- super(...args);
18
+ constructor(params, ...args) {
19
+ validateParams(params, ['tag', ['call', 'member'], 'template'], 'Invalid usage of `styled` tag');
20
+ const [tag, tagOp, template] = params;
21
+ super([tag, template], ...args);
22
22
  let component;
23
- const [type, value, ...rest] = this.params[0] ?? [];
24
23
 
25
- if (type === 'call' && rest.length === 0) {
24
+ if (tagOp[0] === 'call' && tagOp.length === 2) {
25
+ const value = tagOp[1];
26
+
26
27
  if (value.kind === ValueType.FUNCTION) {
27
28
  component = 'FunctionalComponent';
28
29
  } else {
@@ -34,11 +35,11 @@ export default class StyledProcessor extends BaseProcessor {
34
35
  }
35
36
  }
36
37
 
37
- if (type === 'member') {
38
- component = value;
38
+ if (tagOp[0] === 'member') {
39
+ [, component] = tagOp;
39
40
  }
40
41
 
41
- if (!component || this.params.length > 1) {
42
+ if (!component) {
42
43
  throw new Error('Invalid usage of `styled` tag');
43
44
  }
44
45
 
@@ -108,7 +109,7 @@ export default class StyledProcessor extends BaseProcessor {
108
109
 
109
110
  get tagExpression() {
110
111
  const t = this.astService;
111
- return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
112
+ return t.callExpression(this.tag, [this.tagExpressionArgument]);
112
113
  }
113
114
 
114
115
  get value() {
@@ -117,6 +118,20 @@ export default class StyledProcessor extends BaseProcessor {
117
118
  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())]))]);
118
119
  }
119
120
 
121
+ toString() {
122
+ const res = arg => `${this.tagSourceCode()}(${arg})\`…\``;
123
+
124
+ if (typeof this.component === 'string') {
125
+ if (this.component === 'FunctionalComponent') {
126
+ return res('() => {…}');
127
+ }
128
+
129
+ return res(`'${this.component}'`);
130
+ }
131
+
132
+ return res(this.component.source);
133
+ }
134
+
120
135
  getProps() {
121
136
  const propsObj = {
122
137
  name: this.displayName,
@@ -1 +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 type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';\nimport BaseProcessor from '@linaria/core/processors/BaseProcessor';\nimport type {\n Rules,\n WrappedNode,\n ValueCache,\n} from '@linaria/core/processors/types';\nimport { ValueType } from '@linaria/core/processors/types';\nimport hasMeta from '@linaria/core/processors/utils/hasMeta';\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":"AASA,OAAOA,aAAP,MAA0B,wCAA1B;AAMA,SAASC,SAAT,QAA0B,gCAA1B;AACA,OAAOC,OAAP,MAAoB,wCAApB;;AAEA,MAAMC,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;;AASA,eAAe,MAAMK,eAAN,SAA8BX,aAA9B,CAA4C;EAGzD,CAACY,WAAD,GAAe,CAAf;EAEA,CAACC,cAA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,KAAP,KAAiB,SAArB,EAAgC;QAC9B,OAAO+B,CAAC,CAAC4B,cAAF,CAAiBa,OAAjB,EAA0BzC,CAAC,CAAC0C,cAAF,CAAiBzE,KAAjB,CAA1B,CAAP;MACD;;MAED,MAAMgE,IAAI,GAAGI,MAAM,CAACC,OAAP,CAAerE,KAAf,EAAsBsE,GAAtB,CAA0B,CAAC,CAACI,QAAD,EAAWC,SAAX,CAAD,KAA2B;QAChE,OAAO5C,CAAC,CAAC4B,cAAF,CACL5B,CAAC,CAAC6B,aAAF,CAAgBc,QAAhB,CADK,EAEL3C,CAAC,CAAC6C,eAAF,CAAkBD,SAAlB,CAFK,CAAP;MAID,CALY,CAAb;MAOA,OAAO5C,CAAC,CAAC4B,cAAF,CAAiBa,OAAjB,EAA0BzC,CAAC,CAAC2B,gBAAF,CAAmBM,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBa,MAzBqB,CAyBdhF,SAzBc,CAAxB;IA2BA,OAAOkC,CAAC,CAAC2B,gBAAF,CAAmBS,eAAnB,CAAP;EACD,CA3MwD,CA6MzD;;;EACUzC,aAAa,CAAC1B,KAAD,EAAwB;IAC7C,IAAI,CAAC,KAAK,CAACO,cAAN,CAAqBuE,GAArB,CAAyB9E,KAAzB,CAAL,EAAsC;MACpC;MACA;MACA,KAAK,CAACO,cAAN,CAAqBwE,GAArB,CAAyB/E,KAAzB,EAAiC,GAAE,KAAKgF,IAAK,IAAG,KAAK,CAAC1E,WAAN,EAAoB,EAApE;IACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqBsC,GAArB,CAAyB7C,KAAzB,CAAP;EACD;;AAtNwD"}
1
+ {"version":3,"file":"styled.js","names":["TaggedTemplateProcessor","ValueType","hasMeta","validateParams","isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","variableIdx","variablesCache","Map","constructor","params","args","tag","tagOp","template","component","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","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","toString","res","arg","tagSourceCode","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 type {\n Rules,\n WrappedNode,\n ValueCache,\n Params,\n TailProcessorParams,\n} from '@linaria/tags';\nimport {\n TaggedTemplateProcessor,\n ValueType,\n hasMeta,\n validateParams,\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 TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], 'template'],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n super([tag, template], ...args);\n\n let component: WrappedNode | undefined;\n if (tagOp[0] === 'call' && tagOp.length === 2) {\n const value = tagOp[1];\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 (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\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.tag, [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 public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\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":"AAeA,SACEA,uBADF,EAEEC,SAFF,EAGEC,OAHF,EAIEC,cAJF,QAKO,eALP;;AAOA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AAC4B,aAAF,CAAgBkB,QAAhB,CADK,EAEL9C,CAAC,CAACgD,eAAF,CAAkBD,SAAlB,CAFK,CAAP;MAID,CALY,CAAb;MAOA,OAAO/C,CAAC,CAAC2B,cAAF,CAAiBiB,OAAjB,EAA0B5C,CAAC,CAAC0B,gBAAF,CAAmBU,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBa,MAzBqB,CAyBdrF,SAzBc,CAAxB;IA2BA,OAAOoC,CAAC,CAAC0B,gBAAF,CAAmBa,eAAnB,CAAP;EACD,CAjOkE,CAmOnE;;;EACU5C,aAAa,CAAC5B,KAAD,EAAwB;IAC7C,IAAI,CAAC,KAAK,CAACO,cAAN,CAAqB4E,GAArB,CAAyBnF,KAAzB,CAAL,EAAsC;MACpC;MACA;MACA,KAAK,CAACO,cAAN,CAAqB6E,GAArB,CAAyBpF,KAAzB,EAAiC,GAAE,KAAKqF,IAAK,IAAG,KAAK,CAAC/E,WAAN,EAAoB,EAApE;IACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqBwC,GAArB,CAAyB/C,KAAzB,CAAP;EACD;;AA5OkE"}
package/esm/styled.js.map CHANGED
@@ -1 +1 @@
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;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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AAG,KAAKlB,SAAtC,EAAiD;QAC/C;QACA;QACAG,aAAa,CAACsB,EAAd,GAAmBzB,SAAnB;QAEA,oBAAOhB,KAAK,CAACsD,aAAN,CAAoBpB,GAApB,EAAyBf,aAAzB,CAAP;MACD;;MACD,oBAAOnB,KAAK,CAACsD,aAAN,CAAoBtC,SAApB,EAA+BG,aAA/B,CAAP;IACD,CAhDD;;IAkDA,MAAMoC,MAAM,GAAGvD,KAAK,CAACwD,UAAN,gBACXxD,KAAK,CAACwD,UAAN,CAAiBjB,MAAjB,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"}
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;AACA,OAAOC,KAAP,MAAkB,OAAlB;AAEA,SAASC,EAAT,QAAmB,eAAnB;;AAwBA,MAAMC,SAAS,GAAIC,EAAD,IAAyBA,EAAE,CAACC,WAAH,OAAqBD,EAAhE;;AACA,MAAME,SAAS,GACgBC,IAA7B,IACyBC,GAAzB,IACED,IAAI,CAACE,OAAL,CAAaD,GAAb,MAA6B,CAAC,CAHlC;;AAKA,OAAO,MAAME,IAAI,GAAG,CAClBC,GADkB,EAElBJ,IAFkB,KAGC;EACnB,MAAMK,GAAG,GAAG,EAAZ;EACAC,MAAM,CAACN,IAAP,CAAYI,GAAZ,EACGG,MADH,CACUR,SAAS,CAACC,IAAD,CADnB,EAEGQ,OAFH,CAEYP,GAAD,IAAS;IAChBI,GAAG,CAACJ,GAAD,CAAH,GAAWG,GAAG,CAACH,GAAD,CAAd;EACD,CAJH;EAMA,OAAOI,GAAP;AACD,CAZM;;AAcP,SAASI,WAAT,CACEC,SADF,EAEEC,KAFF,EAGEC,QAHF,EA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;;AAHe,CAAlB,CADY,GAMZ/B,MANJ"}
package/lib/index.js CHANGED
@@ -7,4 +7,5 @@ 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 }; }
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+ //# sourceMappingURL=index.js.map
@@ -5,13 +5,7 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
 
8
- var _BaseProcessor = _interopRequireDefault(require("@linaria/core/processors/BaseProcessor"));
9
-
10
- var _types = require("@linaria/core/processors/types");
11
-
12
- var _hasMeta = _interopRequireDefault(require("@linaria/core/processors/utils/hasMeta"));
13
-
14
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
8
+ var _tags = require("@linaria/tags");
15
9
 
16
10
  const isNotNull = x => x !== null;
17
11
 
@@ -24,19 +18,20 @@ const singleQuotedStringLiteral = value => ({
24
18
  }
25
19
  });
26
20
 
27
- class StyledProcessor extends _BaseProcessor.default {
21
+ class StyledProcessor extends _tags.TaggedTemplateProcessor {
28
22
  #variableIdx = 0;
29
23
  #variablesCache = new Map();
30
24
 
31
- constructor(...args) {
32
- var _this$params$;
33
-
34
- super(...args);
25
+ constructor(params, ...args) {
26
+ (0, _tags.validateParams)(params, ['tag', ['call', 'member'], 'template'], 'Invalid usage of `styled` tag');
27
+ const [tag, tagOp, template] = params;
28
+ super([tag, template], ...args);
35
29
  let component;
36
- const [type, value, ...rest] = (_this$params$ = this.params[0]) !== null && _this$params$ !== void 0 ? _this$params$ : [];
37
30
 
38
- if (type === 'call' && rest.length === 0) {
39
- if (value.kind === _types.ValueType.FUNCTION) {
31
+ if (tagOp[0] === 'call' && tagOp.length === 2) {
32
+ const value = tagOp[1];
33
+
34
+ if (value.kind === _tags.ValueType.FUNCTION) {
40
35
  component = 'FunctionalComponent';
41
36
  } else {
42
37
  component = {
@@ -47,11 +42,11 @@ class StyledProcessor extends _BaseProcessor.default {
47
42
  }
48
43
  }
49
44
 
50
- if (type === 'member') {
51
- component = value;
45
+ if (tagOp[0] === 'member') {
46
+ [, component] = tagOp;
52
47
  }
53
48
 
54
- if (!component || this.params.length > 1) {
49
+ if (!component) {
55
50
  throw new Error('Invalid usage of `styled` tag');
56
51
  }
57
52
 
@@ -89,7 +84,7 @@ class StyledProcessor extends _BaseProcessor.default {
89
84
 
90
85
  let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node.name);
91
86
 
92
- while ((0, _hasMeta.default)(value)) {
87
+ while ((0, _tags.hasMeta)(value)) {
93
88
  selector += `.${value.__linaria.className}`;
94
89
  value = value.__linaria.extends;
95
90
  }
@@ -123,7 +118,7 @@ class StyledProcessor extends _BaseProcessor.default {
123
118
 
124
119
  get tagExpression() {
125
120
  const t = this.astService;
126
- return t.callExpression(this.tagExp, [this.tagExpressionArgument]);
121
+ return t.callExpression(this.tag, [this.tagExpressionArgument]);
127
122
  }
128
123
 
129
124
  get value() {
@@ -132,6 +127,20 @@ class StyledProcessor extends _BaseProcessor.default {
132
127
  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())]))]);
133
128
  }
134
129
 
130
+ toString() {
131
+ const res = arg => `${this.tagSourceCode()}(${arg})\`…\``;
132
+
133
+ if (typeof this.component === 'string') {
134
+ if (this.component === 'FunctionalComponent') {
135
+ return res('() => {…}');
136
+ }
137
+
138
+ return res(`'${this.component}'`);
139
+ }
140
+
141
+ return res(this.component.source);
142
+ }
143
+
135
144
  getProps() {
136
145
  const propsObj = {
137
146
  name: this.displayName,
@@ -1 +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 type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';\nimport BaseProcessor from '@linaria/core/processors/BaseProcessor';\nimport type {\n Rules,\n WrappedNode,\n ValueCache,\n} from '@linaria/core/processors/types';\nimport { ValueType } from '@linaria/core/processors/types';\nimport hasMeta from '@linaria/core/processors/utils/hasMeta';\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":";;;;;;;AASA;;AAMA;;AACA;;;;AAEA,MAAMA,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIC,KAAD,KAAmC;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ACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqBuC,GAArB,CAAyB/C,KAAzB,CAAP;EACD;;AAtNwD"}
1
+ {"version":3,"file":"styled.js","names":["isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","TaggedTemplateProcessor","variableIdx","variablesCache","Map","constructor","params","args","validateParams","tag","tagOp","template","component","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","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","toString","res","arg","tagSourceCode","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 type {\n Rules,\n WrappedNode,\n ValueCache,\n Params,\n TailProcessorParams,\n} from '@linaria/tags';\nimport {\n TaggedTemplateProcessor,\n ValueType,\n hasMeta,\n validateParams,\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 TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], 'template'],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n super([tag, template], ...args);\n\n let component: WrappedNode | undefined;\n if (tagOp[0] === 'call' && tagOp.length === 2) {\n const value = tagOp[1];\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 (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\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.tag, [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 public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\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":";;;;;;;AAeA;;AAOA,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,6BAA9B,CAAsD;EAGnE,CAACC,WAAD,GAAe,CAAf;EAEA,CAACC,cAAD,GAAkB,IAAIC,GAAJ,EAAlB;;EAEAC,WAAW,CAACC,MAAD,EAAiB,GAAGC,IAApB,EAA+C;IACxD,IAAAC,oBAAA,EACEF,MADF,EAEE,CAAC,KAAD,EAAQ,CAAC,MAAD,EAAS,QAAT,CAAR,EAA4B,UAA5B,CAFF,EAGE,+BAHF;IAMA,MAAM,CAACG,GAAD,EAAMC,KAAN,EAAaC,QAAb,IAAyBL,MAA/B;IAEA,MAAM,CAACG,GAAD,EAAME,QAAN,CAAN,EAAuB,GAAGJ,IAA1B;IAEA,IAAIK,SAAJ;;IACA,IAAIF,KAAK,CAAC,CAAD,CAAL,KAAa,MAAb,IAAuBA,KAAK,CAACG,MAAN,KAAiB,CAA5C,EAA+C;MAC7C,MAAMlB,KAAK,GAAGe,KAAK,CAAC,CAAD,CAAnB;;MACA,IAAIf,KAAK,CAACmB,IAAN,KAAeC,eAAA,CAAUC,QAA7B,EAAuC;QACrCJ,SAAS,GAAG,qBAAZ;MACD,CAFD,MAEO;QACLA,SAAS,GAAG;UACVK,IAA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9B,OAAOoC,CAAC,CAAC4B,cAAF,CAAiBiB,OAAjB,EAA0B7C,CAAC,CAAC8C,cAAF,CAAiBlF,KAAjB,CAA1B,CAAP;MACD;;MAED,MAAMyE,IAAI,GAAGI,MAAM,CAACC,OAAP,CAAe9E,KAAf,EAAsB+E,GAAtB,CAA0B,CAAC,CAACI,QAAD,EAAWC,SAAX,CAAD,KAA2B;QAChE,OAAOhD,CAAC,CAAC4B,cAAF,CACL5B,CAAC,CAAC6B,aAAF,CAAgBkB,QAAhB,CADK,EAEL/C,CAAC,CAACiD,eAAF,CAAkBD,SAAlB,CAFK,CAAP;MAID,CALY,CAAb;MAOA,OAAOhD,CAAC,CAAC4B,cAAF,CAAiBiB,OAAjB,EAA0B7C,CAAC,CAAC2B,gBAAF,CAAmBU,IAAnB,CAA1B,CAAP;IACD,CAxBqB,EAyBrBa,MAzBqB,CAyBdzF,SAzBc,CAAxB;IA2BA,OAAOuC,CAAC,CAAC2B,gBAAF,CAAmBa,eAAnB,CAAP;EACD,CAjOkE,CAmOnE;;;EACU7C,aAAa,CAAC/B,KAAD,EAAwB;IAC7C,IAAI,CAAC,KAAK,CAACQ,cAAN,CAAqB+E,GAArB,CAAyBvF,KAAzB,CAAL,EAAsC;MACpC;MACA;MACA,KAAK,CAACQ,cAAN,CAAqBgF,GAArB,CAAyBxF,KAAzB,EAAiC,GAAE,KAAKyF,IAAK,IAAG,KAAK,CAAClF,WAAN,EAAoB,EAApE;IACD;;IAED,OAAO,KAAK,CAACC,cAAN,CAAqB0C,GAArB,CAAyBlD,KAAzB,CAAP;EACD;;AA5OkE"}
package/lib/styled.js CHANGED
@@ -139,4 +139,5 @@ var _default = process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
139
139
 
140
140
  }) : styled;
141
141
 
142
- exports.default = _default;
142
+ exports.default = _default;
143
+ //# sourceMappingURL=styled.js.map
package/lib/styled.js.map CHANGED
@@ -1 +1 @@
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,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;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,CAACC,CAAD,EAAIC,IAAJ,EAAuC;IACxC,OAAOD,CAAC,CAACC,IAAD,CAAR;EACD;;AAHe,CAAlB,CADY,GAMZjC,M"}
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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E5B;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,15 +1,16 @@
1
1
  {
2
2
  "name": "@linaria/react",
3
3
  "description": "Blazing fast zero-runtime CSS in JS library",
4
- "version": "4.0.0-beta.0",
4
+ "version": "4.1.0",
5
5
  "bugs": "https://github.com/callstack/linaria/issues",
6
6
  "dependencies": {
7
7
  "@emotion/is-prop-valid": "^0.8.8",
8
- "@linaria/core": "^4.0.0-beta.0",
8
+ "@linaria/core": "^4.1.0",
9
+ "@linaria/tags": "^4.1.0",
9
10
  "ts-invariant": "^0.10.3"
10
11
  },
11
12
  "devDependencies": {
12
- "@babel/types": "^7.18.4",
13
+ "@babel/types": "^7.18.9",
13
14
  "@types/babel__core": "^7.1.19",
14
15
  "@types/node": "^17.0.39",
15
16
  "@types/react": ">=16",
@@ -1,17 +1,16 @@
1
1
  import type { CallExpression, Expression, ObjectExpression, SourceLocation } from '@babel/types';
2
- import type { ProcessorParams } from '@linaria/core/processors/BaseProcessor';
3
- import BaseProcessor from '@linaria/core/processors/BaseProcessor';
4
- import type { Rules, WrappedNode, ValueCache } from '@linaria/core/processors/types';
2
+ import type { Rules, WrappedNode, ValueCache, Params, TailProcessorParams } from '@linaria/tags';
3
+ import { TaggedTemplateProcessor } from '@linaria/tags';
5
4
  export interface IProps {
6
5
  atomic?: boolean;
7
6
  class?: string;
8
7
  name: string;
9
8
  vars?: Record<string, Expression[]>;
10
9
  }
11
- export default class StyledProcessor extends BaseProcessor {
10
+ export default class StyledProcessor extends TaggedTemplateProcessor {
12
11
  #private;
13
12
  component: WrappedNode;
14
- constructor(...args: ProcessorParams);
13
+ constructor(params: Params, ...args: TailProcessorParams);
15
14
  addInterpolation(node: Expression, source: string, unit?: string): string;
16
15
  doEvaltimeReplacement(): void;
17
16
  doRuntimeReplacement(): void;
@@ -20,6 +19,7 @@ export default class StyledProcessor extends BaseProcessor {
20
19
  protected get tagExpressionArgument(): Expression;
21
20
  protected get tagExpression(): CallExpression;
22
21
  get value(): ObjectExpression;
22
+ toString(): string;
23
23
  protected getProps(): IProps;
24
24
  protected getTagComponentProps(props: IProps): ObjectExpression;
25
25
  protected getVariableId(value: string): string;
package/types/styled.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import React from 'react';
2
- import type { CSSProperties, StyledMeta } from '@linaria/core';
2
+ import type { CSSProperties } from '@linaria/core';
3
+ import type { StyledMeta } from '@linaria/tags';
3
4
  export declare type NoInfer<A> = [A][A extends any ? 0 : never];
4
5
  declare type Component<TProps> = ((props: TProps) => unknown) | {
5
6
  new (props: TProps): unknown;