@linaria/react 4.5.4 → 5.0.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/dist/index.js +15 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +11 -7
- package/dist/index.mjs.map +1 -1
- package/dist/processors/styled.js +55 -89
- package/dist/processors/styled.js.map +1 -1
- package/dist/processors/styled.mjs +52 -89
- package/dist/processors/styled.mjs.map +1 -1
- package/package.json +7 -7
- package/types/processors/styled.d.ts +4 -4
- package/types/styled.d.ts +10 -10
package/dist/index.js
CHANGED
|
@@ -18,6 +18,10 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
return to;
|
|
19
19
|
};
|
|
20
20
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
21
25
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
26
|
mod
|
|
23
27
|
));
|
|
@@ -57,7 +61,8 @@ function filterProps(asIs, props, omitKeys) {
|
|
|
57
61
|
}
|
|
58
62
|
var warnIfInvalid = (value, componentName) => {
|
|
59
63
|
if (process.env.NODE_ENV !== "production") {
|
|
60
|
-
if (typeof value === "string" ||
|
|
64
|
+
if (typeof value === "string" || // eslint-disable-next-line no-self-compare,no-restricted-globals
|
|
65
|
+
typeof value === "number" && isFinite(value)) {
|
|
61
66
|
return;
|
|
62
67
|
}
|
|
63
68
|
const stringified = typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
@@ -68,11 +73,10 @@ var warnIfInvalid = (value, componentName) => {
|
|
|
68
73
|
};
|
|
69
74
|
var idx = 0;
|
|
70
75
|
function styled(tag) {
|
|
71
|
-
var _a;
|
|
72
76
|
let mockedClass = "";
|
|
73
77
|
if (process.env.NODE_ENV === "test") {
|
|
74
78
|
mockedClass += `mocked-styled-${idx++}`;
|
|
75
|
-
if (
|
|
79
|
+
if (tag?.__linaria?.className) {
|
|
76
80
|
mockedClass += ` ${tag.__linaria.className}`;
|
|
77
81
|
}
|
|
78
82
|
}
|
|
@@ -119,10 +123,14 @@ function styled(tag) {
|
|
|
119
123
|
}
|
|
120
124
|
return import_react.default.createElement(component, filteredProps);
|
|
121
125
|
};
|
|
122
|
-
const Result = import_react.default.forwardRef ? import_react.default.forwardRef(render) : (
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
+
const Result = import_react.default.forwardRef ? import_react.default.forwardRef(render) : (
|
|
127
|
+
// React.forwardRef won't available on older React versions and in Preact
|
|
128
|
+
// Fallback to a innerRef prop in that case
|
|
129
|
+
(props) => {
|
|
130
|
+
const rest = omit(props, ["innerRef"]);
|
|
131
|
+
return render(rest, props.innerRef);
|
|
132
|
+
}
|
|
133
|
+
);
|
|
126
134
|
Result.displayName = options.name;
|
|
127
135
|
Result.__linaria = {
|
|
128
136
|
className: options.class || mockedClass,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/styled.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type {\n HtmlStyledTag,\n StyledComponent,\n StyledJSXIntrinsics,\n Styled,\n} from './styled';\nexport type { CSSProperties } from '@linaria/core';\nexport type { StyledMeta } from '@linaria/utils';\n","/* 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/utils';\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 atomic?: boolean;\n class: string;\n name: string;\n propsAsIs: 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 asIs: boolean,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n if (!asIs) {\n /**\n * A failsafe check for esModule import issues\n * if validAttr !== 'function' then it is an object of { default: Fn }\n */\n const interopValidAttr =\n typeof validAttr === 'function' ? { default: validAttr } : validAttr;\n\n Object.keys(filteredProps).forEach((key) => {\n if (!interopValidAttr.default(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\nlet idx = 0;\n\n// Components with props are not allowed\nfunction styled(\n componentWithStyle: () => any\n): (error: 'The target component should have a className prop') => void;\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 let mockedClass = '';\n\n if (process.env.NODE_ENV === 'test') {\n // eslint-disable-next-line no-plusplus\n mockedClass += `mocked-styled-${idx++}`;\n if (tag?.__linaria?.className) {\n mockedClass += ` ${tag.__linaria.className}`;\n }\n }\n\n return (options: Options) => {\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.NODE_ENV !== 'test'\n ) {\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 = mockedClass } = props;\n const shouldKeepProps =\n options.propsAsIs === undefined\n ? !(\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n )\n : options.propsAsIs;\n const filteredProps: IProps = filterProps(shouldKeepProps, 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: Record<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 || mockedClass,\n extends: tag,\n };\n\n return Result;\n };\n}\n\nexport type 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\nexport type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<never, 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\nexport type 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;AAAA;AAAA;AAAA;AAAA;;;ACOA,2BAAsB;AACtB,mBAAkB;AAElB,kBAAmB;AAyBnB,IAAM,YAAY,CAAC,OAAwB,GAAG,YAAY,MAAM;AAChE,IAAM,YACJ,CAA6B,SAC7B,CAAyB,QACvB,KAAK,QAAQ,GAAU,MAAM;AAE1B,IAAM,OAAO,CAClB,KACA,SACmB;AACnB,QAAM,MAAM,CAAC;AACb,SAAO,KAAK,GAAG,EACZ,OAAO,UAAU,IAAI,CAAC,EACtB,QAAQ,CAAC,QAAQ;AAChB,QAAI,OAAO,IAAI;AAAA,EACjB,CAAC;AAEH,SAAO;AACT;AAEA,SAAS,YACP,MACA,OACA,UACyB;AACzB,QAAM,gBAAgB,KAAK,OAAO,QAAQ;AAE1C,MAAI,CAAC,MAAM;AAKT,UAAM,mBACJ,OAAO,qBAAAA,YAAc,aAAa,EAAE,SAAS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MAAM,QAAQ;AAAA,EAChB,IAAI,GAAG,MAAmC;AACxC,WAAO,EAAE,IAAI;AAAA,EACf;AACF,CAAC,IACD;","names":["validAttr","React"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/styled.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type {\n HtmlStyledTag,\n StyledComponent,\n StyledJSXIntrinsics,\n Styled,\n} from './styled';\nexport type { CSSProperties } from '@linaria/core';\nexport type { StyledMeta } from '@linaria/utils';\n","/* 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/utils';\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 atomic?: boolean;\n class: string;\n name: string;\n propsAsIs: 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 asIs: boolean,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n if (!asIs) {\n /**\n * A failsafe check for esModule import issues\n * if validAttr !== 'function' then it is an object of { default: Fn }\n */\n const interopValidAttr =\n typeof validAttr === 'function' ? { default: validAttr } : validAttr;\n\n Object.keys(filteredProps).forEach((key) => {\n if (!interopValidAttr.default(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 [props: string]: unknown;\n className?: string;\n style?: Record<string, string>;\n}\n\nlet idx = 0;\n\n// Components with props are not allowed\nfunction styled(\n componentWithStyle: () => any\n): (error: 'The target component should have a className prop') => void;\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 let mockedClass = '';\n\n if (process.env.NODE_ENV === 'test') {\n // eslint-disable-next-line no-plusplus\n mockedClass += `mocked-styled-${idx++}`;\n if (tag?.__linaria?.className) {\n mockedClass += ` ${tag.__linaria.className}`;\n }\n }\n\n return (options: Options) => {\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.NODE_ENV !== 'test'\n ) {\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 = mockedClass } = props;\n const shouldKeepProps =\n options.propsAsIs === undefined\n ? !(\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n )\n : options.propsAsIs;\n const filteredProps: IProps = filterProps(shouldKeepProps, 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: Record<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 || mockedClass,\n extends: tag,\n };\n\n return Result;\n };\n}\n\nexport type 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\nexport type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<never, 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\nexport type 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":";;;;;;;;;;;;;;;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,CAAC,QAAQ;AACpB,kBAAM,GAAG,IAAI,SAAS,GAAG;AAAA,UAC3B,CAAC;AAAA,QACH;AAEA,sBAAc,QAAQ;AAAA,MACxB;AAEA,UAAK,IAAY,aAAa,QAAQ,WAAW;AAG/C,sBAAc,KAAK;AAEnB,eAAO,aAAAC,QAAM,cAAc,KAAK,aAAa;AAAA,MAC/C;AACA,aAAO,aAAAA,QAAM,cAAc,WAAW,aAAa;AAAA,IACrD;AAEA,UAAM,SAAS,aAAAA,QAAM,aACjB,aAAAA,QAAM,WAAW,MAAM;AAAA;AAAA;AAAA,MAGvB,CAAC,UAAe;AACd,cAAM,OAAO,KAAK,OAAO,CAAC,UAAU,CAAC;AACrC,eAAO,OAAO,MAAM,MAAM,QAAQ;AAAA,MACpC;AAAA;AAEJ,IAAC,OAAe,cAAc,QAAQ;AAGtC,IAAC,OAAe,YAAY;AAAA,MAC1B,WAAW,QAAQ,SAAS;AAAA,MAC5B,SAAS;AAAA,IACX;AAEA,WAAO;AAAA,EACT;AACF;AAgDA,IAAO,iBAAS,QAAQ,IAAI,aAAa,eACrC,IAAI,MAAM,QAAQ;AAAA,EAChB,IAAI,GAAG,MAAmC;AACxC,WAAO,EAAE,IAAI;AAAA,EACf;AACF,CAAC,IACD;","names":["validAttr","React"]}
|
package/dist/index.mjs
CHANGED
|
@@ -25,7 +25,8 @@ function filterProps(asIs, props, omitKeys) {
|
|
|
25
25
|
}
|
|
26
26
|
var warnIfInvalid = (value, componentName) => {
|
|
27
27
|
if (process.env.NODE_ENV !== "production") {
|
|
28
|
-
if (typeof value === "string" ||
|
|
28
|
+
if (typeof value === "string" || // eslint-disable-next-line no-self-compare,no-restricted-globals
|
|
29
|
+
typeof value === "number" && isFinite(value)) {
|
|
29
30
|
return;
|
|
30
31
|
}
|
|
31
32
|
const stringified = typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
@@ -36,11 +37,10 @@ var warnIfInvalid = (value, componentName) => {
|
|
|
36
37
|
};
|
|
37
38
|
var idx = 0;
|
|
38
39
|
function styled(tag) {
|
|
39
|
-
var _a;
|
|
40
40
|
let mockedClass = "";
|
|
41
41
|
if (process.env.NODE_ENV === "test") {
|
|
42
42
|
mockedClass += `mocked-styled-${idx++}`;
|
|
43
|
-
if (
|
|
43
|
+
if (tag?.__linaria?.className) {
|
|
44
44
|
mockedClass += ` ${tag.__linaria.className}`;
|
|
45
45
|
}
|
|
46
46
|
}
|
|
@@ -87,10 +87,14 @@ function styled(tag) {
|
|
|
87
87
|
}
|
|
88
88
|
return React.createElement(component, filteredProps);
|
|
89
89
|
};
|
|
90
|
-
const Result = React.forwardRef ? React.forwardRef(render) : (
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
const Result = React.forwardRef ? React.forwardRef(render) : (
|
|
91
|
+
// React.forwardRef won't available on older React versions and in Preact
|
|
92
|
+
// Fallback to a innerRef prop in that case
|
|
93
|
+
(props) => {
|
|
94
|
+
const rest = omit(props, ["innerRef"]);
|
|
95
|
+
return render(rest, props.innerRef);
|
|
96
|
+
}
|
|
97
|
+
);
|
|
94
98
|
Result.displayName = options.name;
|
|
95
99
|
Result.__linaria = {
|
|
96
100
|
className: options.class || mockedClass,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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/utils';\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 atomic?: boolean;\n class: string;\n name: string;\n propsAsIs: 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 asIs: boolean,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n if (!asIs) {\n /**\n * A failsafe check for esModule import issues\n * if validAttr !== 'function' then it is an object of { default: Fn }\n */\n const interopValidAttr =\n typeof validAttr === 'function' ? { default: validAttr } : validAttr;\n\n Object.keys(filteredProps).forEach((key) => {\n if (!interopValidAttr.default(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\nlet idx = 0;\n\n// Components with props are not allowed\nfunction styled(\n componentWithStyle: () => any\n): (error: 'The target component should have a className prop') => void;\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 let mockedClass = '';\n\n if (process.env.NODE_ENV === 'test') {\n // eslint-disable-next-line no-plusplus\n mockedClass += `mocked-styled-${idx++}`;\n if (tag?.__linaria?.className) {\n mockedClass += ` ${tag.__linaria.className}`;\n }\n }\n\n return (options: Options) => {\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.NODE_ENV !== 'test'\n ) {\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 = mockedClass } = props;\n const shouldKeepProps =\n options.propsAsIs === undefined\n ? !(\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n )\n : options.propsAsIs;\n const filteredProps: IProps = filterProps(shouldKeepProps, 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: Record<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 || mockedClass,\n extends: tag,\n };\n\n return Result;\n };\n}\n\nexport type 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\nexport type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<never, 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\nexport type 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,OAAO,eAAe;AACtB,OAAO,WAAW;AAElB,SAAS,UAAU;AAyBnB,IAAM,YAAY,CAAC,OAAwB,GAAG,YAAY,MAAM;AAChE,IAAM,YACJ,CAA6B,SAC7B,CAAyB,QACvB,KAAK,QAAQ,GAAU,MAAM;AAE1B,IAAM,OAAO,CAClB,KACA,SACmB;AACnB,QAAM,MAAM,CAAC;AACb,SAAO,KAAK,GAAG,EACZ,OAAO,UAAU,IAAI,CAAC,EACtB,QAAQ,CAAC,QAAQ;AAChB,QAAI,OAAO,IAAI;AAAA,EACjB,CAAC;AAEH,SAAO;AACT;AAEA,SAAS,YACP,MACA,OACA,UACyB;AACzB,QAAM,gBAAgB,KAAK,OAAO,QAAQ;AAE1C,MAAI,CAAC,MAAM;AAKT,UAAM,mBACJ,OAAO,cAAc,aAAa,EAAE,SAAS,UAAU,IAAI;AAE7D,WAAO,KAAK,aAAa,EAAE,QAAQ,CAAC,QAAQ;AAC1C,UAAI,CAAC,iBAAiB,QAAQ,GAAG,GAAG;AAElC,eAAO,cAAc;AAAA,MACvB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAEA,IAAM,gBAA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,QAAQ,MAAM;AACvB,gBAAM,WAAW,KAAK;AACtB,gBAAM,SAAS,SAAS;AACxB,gBAAM,OAAO,SAAS,MAAM;AAC5B,gBAAM,QAAQ,OAAO,WAAW,aAAa,OAAO,KAAK,IAAI;AAE7D,wBAAc,OAAO,QAAQ,IAAI;AAEjC,gBAAM,KAAK,UAAU,GAAG,QAAQ;AAAA,QAClC;AAEA,cAAM,WAAW,cAAc,SAAS,CAAC;AACzC,cAAM,OAAO,OAAO,KAAK,QAAQ;AACjC,YAAI,KAAK,SAAS,GAAG;AACnB,eAAK,QAAQ,CAAC,QAAQ;AACpB,kBAAM,OAAO,SAAS;AAAA,UACxB,CAAC;AAAA,QACH;AAEA,sBAAc,QAAQ;AAAA,MACxB;AAEA,UAAK,IAAY,aAAa,QAAQ,WAAW;AAG/C,sBAAc,KAAK;AAEnB,eAAO,MAAM,cAAc,KAAK,aAAa;AAAA,MAC/C;AACA,aAAO,MAAM,cAAc,WAAW,aAAa;AAAA,IACrD;AAEA,UAAM,SAAS,MAAM,aACjB,MAAM,WAAW,MAAM,IAGvB,CAAC,UAAe;AACd,YAAM,OAAO,KAAK,OAAO,CAAC,UAAU,CAAC;AACrC,aAAO,OAAO,MAAM,MAAM,QAAQ;AAAA,IACpC;AAEJ,IAAC,OAAe,cAAc,QAAQ;AAGtC,IAAC,OAAe,YAAY;AAAA,MAC1B,WAAW,QAAQ,SAAS;AAAA,MAC5B,SAAS;AAAA,IACX;AAEA,WAAO;AAAA,EACT;AACF;AAgDA,IAAO,iBAAS,QAAQ,IAAI,aAAa,eACrC,IAAI,MAAM,QAAQ;AAAA,EAChB,IAAI,GAAG,MAAmC;AACxC,WAAO,EAAE,IAAI;AAAA,EACf;AACF,CAAC,IACD;","names":[]}
|
|
1
|
+
{"version":3,"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/utils';\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 atomic?: boolean;\n class: string;\n name: string;\n propsAsIs: 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 asIs: boolean,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n if (!asIs) {\n /**\n * A failsafe check for esModule import issues\n * if validAttr !== 'function' then it is an object of { default: Fn }\n */\n const interopValidAttr =\n typeof validAttr === 'function' ? { default: validAttr } : validAttr;\n\n Object.keys(filteredProps).forEach((key) => {\n if (!interopValidAttr.default(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 [props: string]: unknown;\n className?: string;\n style?: Record<string, string>;\n}\n\nlet idx = 0;\n\n// Components with props are not allowed\nfunction styled(\n componentWithStyle: () => any\n): (error: 'The target component should have a className prop') => void;\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 let mockedClass = '';\n\n if (process.env.NODE_ENV === 'test') {\n // eslint-disable-next-line no-plusplus\n mockedClass += `mocked-styled-${idx++}`;\n if (tag?.__linaria?.className) {\n mockedClass += ` ${tag.__linaria.className}`;\n }\n }\n\n return (options: Options) => {\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.NODE_ENV !== 'test'\n ) {\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 = mockedClass } = props;\n const shouldKeepProps =\n options.propsAsIs === undefined\n ? !(\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n )\n : options.propsAsIs;\n const filteredProps: IProps = filterProps(shouldKeepProps, 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: Record<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 || mockedClass,\n extends: tag,\n };\n\n return Result;\n };\n}\n\nexport type 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\nexport type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<never, 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\nexport type 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,OAAO,eAAe;AACtB,OAAO,WAAW;AAElB,SAAS,UAAU;AAyBnB,IAAM,YAAY,CAAC,OAAwB,GAAG,YAAY,MAAM;AAChE,IAAM,YACJ,CAA6B,SAC7B,CAAyB,QACvB,KAAK,QAAQ,GAAU,MAAM;AAE1B,IAAM,OAAO,CAClB,KACA,SACmB;AACnB,QAAM,MAAM,CAAC;AACb,SAAO,KAAK,GAAG,EACZ,OAAO,UAAU,IAAI,CAAC,EACtB,QAAQ,CAAC,QAAQ;AAChB,QAAI,GAAG,IAAI,IAAI,GAAG;AAAA,EACpB,CAAC;AAEH,SAAO;AACT;AAEA,SAAS,YACP,MACA,OACA,UACyB;AACzB,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GtC,IAAC,OAAe,YAAY;AAAA,MAC1B,WAAW,QAAQ,SAAS;AAAA,MAC5B,SAAS;AAAA,IACX;AAEA,WAAO;AAAA,EACT;AACF;AAgDA,IAAO,iBAAS,QAAQ,IAAI,aAAa,eACrC,IAAI,MAAM,QAAQ;AAAA,EAChB,IAAI,GAAG,MAAmC;AACxC,WAAO,EAAE,IAAI;AAAA,EACf;AACF,CAAC,IACD;","names":[]}
|
|
@@ -5,7 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
8
|
var __export = (target, all) => {
|
|
10
9
|
for (var name in all)
|
|
11
10
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -19,40 +18,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
19
18
|
return to;
|
|
20
19
|
};
|
|
21
20
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
25
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
26
|
mod
|
|
24
27
|
));
|
|
25
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
26
|
-
var __publicField = (obj, key, value) => {
|
|
27
|
-
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
28
|
-
return value;
|
|
29
|
-
};
|
|
30
|
-
var __accessCheck = (obj, member, msg) => {
|
|
31
|
-
if (!member.has(obj))
|
|
32
|
-
throw TypeError("Cannot " + msg);
|
|
33
|
-
};
|
|
34
|
-
var __privateGet = (obj, member, getter) => {
|
|
35
|
-
__accessCheck(obj, member, "read from private field");
|
|
36
|
-
return getter ? getter.call(obj) : member.get(obj);
|
|
37
|
-
};
|
|
38
|
-
var __privateAdd = (obj, member, value) => {
|
|
39
|
-
if (member.has(obj))
|
|
40
|
-
throw TypeError("Cannot add the same private member more than once");
|
|
41
|
-
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
42
|
-
};
|
|
43
|
-
var __privateSet = (obj, member, value, setter) => {
|
|
44
|
-
__accessCheck(obj, member, "write to private field");
|
|
45
|
-
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
46
|
-
return value;
|
|
47
|
-
};
|
|
48
|
-
var __privateWrapper = (obj, member, setter, getter) => ({
|
|
49
|
-
set _(value) {
|
|
50
|
-
__privateSet(obj, member, value, setter);
|
|
51
|
-
},
|
|
52
|
-
get _() {
|
|
53
|
-
return __privateGet(obj, member, getter);
|
|
54
|
-
}
|
|
55
|
-
});
|
|
56
29
|
|
|
57
30
|
// src/processors/styled.ts
|
|
58
31
|
var styled_exports = {};
|
|
@@ -76,10 +49,11 @@ var singleQuotedStringLiteral = (value) => ({
|
|
|
76
49
|
raw: `'${value}'`
|
|
77
50
|
}
|
|
78
51
|
});
|
|
79
|
-
var _variableIdx, _variablesCache;
|
|
80
52
|
var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
53
|
+
component;
|
|
54
|
+
#variableIdx = 0;
|
|
55
|
+
#variablesCache = /* @__PURE__ */ new Map();
|
|
81
56
|
constructor(params, ...args) {
|
|
82
|
-
var _a;
|
|
83
57
|
(0, import_tags.validateParams)(
|
|
84
58
|
params,
|
|
85
59
|
["callee", "*", "..."],
|
|
@@ -95,9 +69,6 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
95
69
|
throw import_tags.TaggedTemplateProcessor.SKIP;
|
|
96
70
|
}
|
|
97
71
|
super([tag, template], ...args);
|
|
98
|
-
__publicField(this, "component");
|
|
99
|
-
__privateAdd(this, _variableIdx, 0);
|
|
100
|
-
__privateAdd(this, _variablesCache, /* @__PURE__ */ new Map());
|
|
101
72
|
let component;
|
|
102
73
|
if (tagOp[0] === "call" && tagOp.length === 2) {
|
|
103
74
|
const value = tagOp[1];
|
|
@@ -106,17 +77,16 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
106
77
|
} else if (value.kind === import_utils.ValueType.CONST) {
|
|
107
78
|
component = typeof value.value === "string" ? value.value : void 0;
|
|
108
79
|
} else {
|
|
109
|
-
if (
|
|
80
|
+
if (value.importedFrom?.length) {
|
|
110
81
|
const selfPkg = (0, import_utils.findPackageJSON)(".", this.context.filename);
|
|
111
82
|
const isSomeMatched = value.importedFrom.some((importedFrom) => {
|
|
112
|
-
var _a2;
|
|
113
83
|
const importedPkg = (0, import_utils.findPackageJSON)(
|
|
114
84
|
importedFrom,
|
|
115
85
|
this.context.filename
|
|
116
86
|
);
|
|
117
87
|
if (importedPkg) {
|
|
118
88
|
const packageJSON = JSON.parse((0, import_fs.readFileSync)(importedPkg, "utf8"));
|
|
119
|
-
let mask =
|
|
89
|
+
let mask = packageJSON?.linaria?.components;
|
|
120
90
|
if (importedPkg === selfPkg && mask === void 0) {
|
|
121
91
|
mask = "**/*";
|
|
122
92
|
}
|
|
@@ -157,6 +127,46 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
157
127
|
}
|
|
158
128
|
this.component = component;
|
|
159
129
|
}
|
|
130
|
+
get asSelector() {
|
|
131
|
+
return `.${this.className}`;
|
|
132
|
+
}
|
|
133
|
+
get value() {
|
|
134
|
+
const t = this.astService;
|
|
135
|
+
const extendsNode = typeof this.component === "string" || this.component.nonLinaria ? null : this.component.node.name;
|
|
136
|
+
return t.objectExpression([
|
|
137
|
+
t.objectProperty(
|
|
138
|
+
t.stringLiteral("displayName"),
|
|
139
|
+
t.stringLiteral(this.displayName)
|
|
140
|
+
),
|
|
141
|
+
t.objectProperty(
|
|
142
|
+
t.stringLiteral("__linaria"),
|
|
143
|
+
t.objectExpression([
|
|
144
|
+
t.objectProperty(
|
|
145
|
+
t.stringLiteral("className"),
|
|
146
|
+
t.stringLiteral(this.className)
|
|
147
|
+
),
|
|
148
|
+
t.objectProperty(
|
|
149
|
+
t.stringLiteral("extends"),
|
|
150
|
+
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
|
|
151
|
+
)
|
|
152
|
+
])
|
|
153
|
+
)
|
|
154
|
+
]);
|
|
155
|
+
}
|
|
156
|
+
get tagExpression() {
|
|
157
|
+
const t = this.astService;
|
|
158
|
+
return t.callExpression(this.callee, [this.tagExpressionArgument]);
|
|
159
|
+
}
|
|
160
|
+
get tagExpressionArgument() {
|
|
161
|
+
const t = this.astService;
|
|
162
|
+
if (typeof this.component === "string") {
|
|
163
|
+
if (this.component === "FunctionalComponent") {
|
|
164
|
+
return t.arrowFunctionExpression([], t.blockStatement([]));
|
|
165
|
+
}
|
|
166
|
+
return singleQuotedStringLiteral(this.component);
|
|
167
|
+
}
|
|
168
|
+
return t.callExpression(t.identifier(this.component.node.name), []);
|
|
169
|
+
}
|
|
160
170
|
addInterpolation(node, precedingCss, source, unit = "") {
|
|
161
171
|
const id = this.getVariableId(source, unit, precedingCss);
|
|
162
172
|
this.interpolations.push({
|
|
@@ -190,50 +200,10 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
190
200
|
cssText,
|
|
191
201
|
className: this.className,
|
|
192
202
|
displayName: this.displayName,
|
|
193
|
-
start:
|
|
203
|
+
start: loc?.start ?? null
|
|
194
204
|
};
|
|
195
205
|
return rules;
|
|
196
206
|
}
|
|
197
|
-
get asSelector() {
|
|
198
|
-
return `.${this.className}`;
|
|
199
|
-
}
|
|
200
|
-
get tagExpressionArgument() {
|
|
201
|
-
const t = this.astService;
|
|
202
|
-
if (typeof this.component === "string") {
|
|
203
|
-
if (this.component === "FunctionalComponent") {
|
|
204
|
-
return t.arrowFunctionExpression([], t.blockStatement([]));
|
|
205
|
-
}
|
|
206
|
-
return singleQuotedStringLiteral(this.component);
|
|
207
|
-
}
|
|
208
|
-
return t.callExpression(t.identifier(this.component.node.name), []);
|
|
209
|
-
}
|
|
210
|
-
get tagExpression() {
|
|
211
|
-
const t = this.astService;
|
|
212
|
-
return t.callExpression(this.callee, [this.tagExpressionArgument]);
|
|
213
|
-
}
|
|
214
|
-
get value() {
|
|
215
|
-
const t = this.astService;
|
|
216
|
-
const extendsNode = typeof this.component === "string" || this.component.nonLinaria ? null : this.component.node.name;
|
|
217
|
-
return t.objectExpression([
|
|
218
|
-
t.objectProperty(
|
|
219
|
-
t.stringLiteral("displayName"),
|
|
220
|
-
t.stringLiteral(this.displayName)
|
|
221
|
-
),
|
|
222
|
-
t.objectProperty(
|
|
223
|
-
t.stringLiteral("__linaria"),
|
|
224
|
-
t.objectExpression([
|
|
225
|
-
t.objectProperty(
|
|
226
|
-
t.stringLiteral("className"),
|
|
227
|
-
t.stringLiteral(this.className)
|
|
228
|
-
),
|
|
229
|
-
t.objectProperty(
|
|
230
|
-
t.stringLiteral("extends"),
|
|
231
|
-
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
|
|
232
|
-
)
|
|
233
|
-
])
|
|
234
|
-
)
|
|
235
|
-
]);
|
|
236
|
-
}
|
|
237
207
|
toString() {
|
|
238
208
|
const res = (arg) => `${this.tagSourceCode()}(${arg})\`\u2026\``;
|
|
239
209
|
if (typeof this.component === "string") {
|
|
@@ -250,7 +220,7 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
250
220
|
if (!customSlugFn) {
|
|
251
221
|
return void 0;
|
|
252
222
|
}
|
|
253
|
-
return typeof customSlugFn === "function" ? customSlugFn(context) : (0, import_tags.buildSlug)(customSlugFn, context);
|
|
223
|
+
return typeof customSlugFn === "function" ? customSlugFn(context) : (0, import_tags.buildSlug)(customSlugFn, { ...context });
|
|
254
224
|
}
|
|
255
225
|
getProps() {
|
|
256
226
|
const propsObj = {
|
|
@@ -298,7 +268,7 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
298
268
|
}
|
|
299
269
|
getVariableContext(source, unit, precedingCss) {
|
|
300
270
|
const getIndex = () => {
|
|
301
|
-
return
|
|
271
|
+
return this.#variableIdx++;
|
|
302
272
|
};
|
|
303
273
|
return {
|
|
304
274
|
componentName: this.displayName,
|
|
@@ -315,19 +285,15 @@ var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
|
|
|
315
285
|
}
|
|
316
286
|
getVariableId(source, unit, precedingCss) {
|
|
317
287
|
const value = source + unit;
|
|
318
|
-
if (!
|
|
288
|
+
if (!this.#variablesCache.has(value)) {
|
|
319
289
|
const id = this.getCustomVariableId(source, unit, precedingCss);
|
|
320
290
|
if (id) {
|
|
321
291
|
return (0, import_tags.toValidCSSIdentifier)(id);
|
|
322
292
|
}
|
|
323
293
|
const context = this.getVariableContext(source, unit, precedingCss);
|
|
324
|
-
|
|
294
|
+
this.#variablesCache.set(value, `${this.slug}-${context.index}`);
|
|
325
295
|
}
|
|
326
|
-
return
|
|
296
|
+
return this.#variablesCache.get(value);
|
|
327
297
|
}
|
|
328
298
|
};
|
|
329
|
-
_variableIdx = new WeakMap();
|
|
330
|
-
_variablesCache = new WeakMap();
|
|
331
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
332
|
-
0 && (module.exports = {});
|
|
333
299
|
//# sourceMappingURL=styled.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import { readFileSync } from 'fs';\nimport { dirname, join, sep } from 'path';\n\nimport type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\nimport { minimatch } from 'minimatch';\nimport html from 'react-html-attributes';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n TaggedTemplateProcessor,\n validateParams,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { findPackageJSON, hasMeta, slugify, ValueType } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nconst allTagsSet = new Set([...html.elements.html, html.elements.svg]);\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n propsAsIs: boolean;\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 // Should have at least two params and the first one should be a callee.\n validateParams(\n params,\n ['callee', '*', '...'],\n TaggedTemplateProcessor.SKIP\n );\n\n validateParams(\n params,\n ['callee', ['call', 'member'], ['template', 'call']],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n if (template[0] === 'call') {\n // It is already transformed styled-literal. Skip it.\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw TaggedTemplateProcessor.SKIP;\n }\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 if (value.kind === ValueType.CONST) {\n component = typeof value.value === 'string' ? value.value : undefined;\n } else {\n if (value.importedFrom?.length) {\n const selfPkg = findPackageJSON('.', this.context.filename);\n\n // Check if at least one used identifier is a Linaria component.\n const isSomeMatched = value.importedFrom.some((importedFrom) => {\n const importedPkg = findPackageJSON(\n importedFrom,\n this.context.filename\n );\n\n if (importedPkg) {\n const packageJSON = JSON.parse(readFileSync(importedPkg, 'utf8'));\n let mask: string | undefined = packageJSON?.linaria?.components;\n if (importedPkg === selfPkg && mask === undefined) {\n // If mask is not specified for the local package, all components are treated as styled.\n mask = '**/*';\n }\n\n if (mask) {\n const packageDir = dirname(importedPkg);\n const normalizedMask = mask.replace(/\\//g, sep);\n const fullMask = join(packageDir, normalizedMask);\n const fileWithComponent = require.resolve(importedFrom, {\n paths: [dirname(this.context.filename!)],\n });\n\n return minimatch(fileWithComponent, fullMask);\n }\n }\n\n return false;\n });\n\n if (!isSomeMatched) {\n component = {\n node: value.ex,\n nonLinaria: true,\n source: value.source,\n };\n }\n }\n\n if (component === undefined) {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\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 precedingCss: string,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source, unit, precedingCss);\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' || this.component.nonLinaria\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.callee, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' || this.component.nonLinaria\n ? null\n : 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 getCustomVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ) {\n const context = this.getVariableContext(source, unit, precedingCss);\n const customSlugFn = this.options.variableNameSlug;\n if (!customSlugFn) {\n return undefined;\n }\n\n return typeof customSlugFn === 'function'\n ? customSlugFn(context)\n : buildSlug(customSlugFn, context);\n }\n\n protected getProps(): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n propsAsIs:\n typeof this.component !== 'string' || !allTagsSet.has(this.component),\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 === undefined) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (value === null) {\n return t.objectProperty(keyNode, t.nullLiteral());\n }\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 protected getVariableContext(\n source: string,\n unit: string,\n precedingCss: string\n ): IVariableContext {\n const getIndex = () => {\n // eslint-disable-next-line no-plusplus\n return this.#variableIdx++;\n };\n\n return {\n componentName: this.displayName,\n componentSlug: this.slug,\n get index() {\n return getIndex();\n },\n precedingCss,\n processor: this.constructor.name,\n source,\n unit,\n valueSlug: slugify(source + unit),\n };\n }\n\n protected getVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ): string {\n const value = source + unit;\n if (!this.#variablesCache.has(value)) {\n const id = this.getCustomVariableId(source, unit, precedingCss);\n if (id) {\n return toValidCSSIdentifier(id);\n }\n\n const context = this.getVariableContext(source, unit, precedingCss);\n\n // make the variable unique to this styled component\n this.#variablesCache.set(value, `${this.slug}-${context.index}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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gB,SAAS;AAAA,QAC7B;AAAA,MACF,CAAC;AAED,aAAO,EAAE,eAAe,SAAS,EAAE,iBAAiB,IAAI,CAAC;AAAA,IAC3D,CAAC,EACA,OAAO,SAAS;AAEnB,WAAO,EAAE,iBAAiB,eAAe;AAAA,EAC3C;AAAA,EAEU,mBACR,QACA,MACA,cACkB;AAClB,UAAM,WAAW,MAAM;AAErB,aAAO,uBAAK,cAAL;AAAA,IACT;AAEA,WAAO;AAAA,MACL,eAAe,KAAK;AAAA,MACpB,eAAe,KAAK;AAAA,MACpB,IAAI,QAAQ;AACV,eAAO,SAAS;AAAA,MAClB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,YAAY;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,eAAW,sBAAQ,SAAS,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEU,cACR,QACA,MACA,cACQ;AACR,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,mBAAK,iBAAgB,IAAI,KAAK,GAAG;AACpC,YAAM,KAAK,KAAK,oBAAoB,QAAQ,MAAM,YAAY;AAC9D,UAAI,IAAI;AACN,mBAAO,kCAAqB,EAAE;AAAA,MAChC;AAEA,YAAM,UAAU,KAAK,mBAAmB,QAAQ,MAAM,YAAY;AAGlE,yBAAK,iBAAgB,IAAI,OAAO,GAAG,KAAK,QAAQ,QAAQ,OAAO;AAAA,IACjE;AAEA,WAAO,mBAAK,iBAAgB,IAAI,KAAK;AAAA,EACvC;AACF;AAhWE;AAEA;","names":["html","_a"]}
|
|
1
|
+
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import { readFileSync } from 'fs';\nimport { dirname, join, sep } from 'path';\n\nimport type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\nimport { minimatch } from 'minimatch';\nimport html from 'react-html-attributes';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n TaggedTemplateProcessor,\n validateParams,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { findPackageJSON, hasMeta, slugify, ValueType } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nconst allTagsSet = new Set([...html.elements.html, html.elements.svg]);\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n propsAsIs: boolean;\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 // Should have at least two params and the first one should be a callee.\n validateParams(\n params,\n ['callee', '*', '...'],\n TaggedTemplateProcessor.SKIP\n );\n\n validateParams(\n params,\n ['callee', ['call', 'member'], ['template', 'call']],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n if (template[0] === 'call') {\n // It is already transformed styled-literal. Skip it.\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw TaggedTemplateProcessor.SKIP;\n }\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 if (value.kind === ValueType.CONST) {\n component = typeof value.value === 'string' ? value.value : undefined;\n } else {\n if (value.importedFrom?.length) {\n const selfPkg = findPackageJSON('.', this.context.filename);\n\n // Check if at least one used identifier is a Linaria component.\n const isSomeMatched = value.importedFrom.some((importedFrom) => {\n const importedPkg = findPackageJSON(\n importedFrom,\n this.context.filename\n );\n\n if (importedPkg) {\n const packageJSON = JSON.parse(readFileSync(importedPkg, 'utf8'));\n let mask: string | undefined = packageJSON?.linaria?.components;\n if (importedPkg === selfPkg && mask === undefined) {\n // If mask is not specified for the local package, all components are treated as styled.\n mask = '**/*';\n }\n\n if (mask) {\n const packageDir = dirname(importedPkg);\n const normalizedMask = mask.replace(/\\//g, sep);\n const fullMask = join(packageDir, normalizedMask);\n const fileWithComponent = require.resolve(importedFrom, {\n paths: [dirname(this.context.filename!)],\n });\n\n return minimatch(fileWithComponent, fullMask);\n }\n }\n\n return false;\n });\n\n if (!isSomeMatched) {\n component = {\n node: value.ex,\n nonLinaria: true,\n source: value.source,\n };\n }\n }\n\n if (component === undefined) {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\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 get asSelector(): string {\n return `.${this.className}`;\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' || this.component.nonLinaria\n ? null\n : 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 get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.callee, [this.tagExpressionArgument]);\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 public override addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source, unit, precedingCss);\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' || this.component.nonLinaria\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 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 getCustomVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ) {\n const context = this.getVariableContext(source, unit, precedingCss);\n const customSlugFn = this.options.variableNameSlug;\n if (!customSlugFn) {\n return undefined;\n }\n\n return typeof customSlugFn === 'function'\n ? customSlugFn(context)\n : buildSlug(customSlugFn, { ...context });\n }\n\n protected getProps(): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n propsAsIs:\n typeof this.component !== 'string' || !allTagsSet.has(this.component),\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 === undefined) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (value === null) {\n return t.objectProperty(keyNode, t.nullLiteral());\n }\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 protected getVariableContext(\n source: string,\n unit: string,\n precedingCss: string\n ): IVariableContext {\n const getIndex = () => {\n // eslint-disable-next-line no-plusplus\n return this.#variableIdx++;\n };\n\n return {\n componentName: this.displayName,\n componentSlug: this.slug,\n get index() {\n return getIndex();\n },\n precedingCss,\n processor: this.constructor.name,\n source,\n unit,\n valueSlug: slugify(source + unit),\n };\n }\n\n protected getVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ): string {\n const value = source + unit;\n if (!this.#variablesCache.has(value)) {\n const id = this.getCustomVariableId(source, unit, precedingCss);\n if (id) {\n return toValidCSSIdentifier(id);\n }\n\n const context = this.getVariableContext(source, unit, precedingCss);\n\n // make the variable unique to this styled component\n this.#variablesCache.set(value, `${this.slug}-${context.index}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA6B;AAC7B,kBAAmC;AASnC,uBAA0B;AAC1B,mCAAiB;AASjB,kBAKO;AAEP,mBAA6D;AAE7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3D,CAAC,EACA,OAAO,SAAS;AAEnB,WAAO,EAAE,iBAAiB,eAAe;AAAA,EAC3C;AAAA,EAEU,mBACR,QACA,MACA,cACkB;AAClB,UAAM,WAAW,MAAM;AAErB,aAAO,KAAK;AAAA,IACd;AAEA,WAAO;AAAA,MACL,eAAe,KAAK;AAAA,MACpB,eAAe,KAAK;AAAA,MACpB,IAAI,QAAQ;AACV,eAAO,SAAS;AAAA,MAClB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,YAAY;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,eAAW,sBAAQ,SAAS,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEU,cACR,QACA,MACA,cACQ;AACR,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,KAAK,gBAAgB,IAAI,KAAK,GAAG;AACpC,YAAM,KAAK,KAAK,oBAAoB,QAAQ,MAAM,YAAY;AAC9D,UAAI,IAAI;AACN,mBAAO,kCAAqB,EAAE;AAAA,MAChC;AAEA,YAAM,UAAU,KAAK,mBAAmB,QAAQ,MAAM,YAAY;AAGlE,WAAK,gBAAgB,IAAI,OAAO,GAAG,KAAK,IAAI,IAAI,QAAQ,KAAK,EAAE;AAAA,IACjE;AAEA,WAAO,KAAK,gBAAgB,IAAI,KAAK;AAAA,EACvC;AACF;","names":["html"]}
|
|
@@ -1,41 +1,9 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
1
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
2
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
3
|
}) : x)(function(x) {
|
|
6
4
|
if (typeof require !== "undefined")
|
|
7
5
|
return require.apply(this, arguments);
|
|
8
|
-
throw
|
|
9
|
-
});
|
|
10
|
-
var __publicField = (obj, key, value) => {
|
|
11
|
-
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
12
|
-
return value;
|
|
13
|
-
};
|
|
14
|
-
var __accessCheck = (obj, member, msg) => {
|
|
15
|
-
if (!member.has(obj))
|
|
16
|
-
throw TypeError("Cannot " + msg);
|
|
17
|
-
};
|
|
18
|
-
var __privateGet = (obj, member, getter) => {
|
|
19
|
-
__accessCheck(obj, member, "read from private field");
|
|
20
|
-
return getter ? getter.call(obj) : member.get(obj);
|
|
21
|
-
};
|
|
22
|
-
var __privateAdd = (obj, member, value) => {
|
|
23
|
-
if (member.has(obj))
|
|
24
|
-
throw TypeError("Cannot add the same private member more than once");
|
|
25
|
-
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
26
|
-
};
|
|
27
|
-
var __privateSet = (obj, member, value, setter) => {
|
|
28
|
-
__accessCheck(obj, member, "write to private field");
|
|
29
|
-
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
30
|
-
return value;
|
|
31
|
-
};
|
|
32
|
-
var __privateWrapper = (obj, member, setter, getter) => ({
|
|
33
|
-
set _(value) {
|
|
34
|
-
__privateSet(obj, member, value, setter);
|
|
35
|
-
},
|
|
36
|
-
get _() {
|
|
37
|
-
return __privateGet(obj, member, getter);
|
|
38
|
-
}
|
|
6
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
39
7
|
});
|
|
40
8
|
|
|
41
9
|
// src/processors/styled.ts
|
|
@@ -60,10 +28,11 @@ var singleQuotedStringLiteral = (value) => ({
|
|
|
60
28
|
raw: `'${value}'`
|
|
61
29
|
}
|
|
62
30
|
});
|
|
63
|
-
var _variableIdx, _variablesCache;
|
|
64
31
|
var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
32
|
+
component;
|
|
33
|
+
#variableIdx = 0;
|
|
34
|
+
#variablesCache = /* @__PURE__ */ new Map();
|
|
65
35
|
constructor(params, ...args) {
|
|
66
|
-
var _a;
|
|
67
36
|
validateParams(
|
|
68
37
|
params,
|
|
69
38
|
["callee", "*", "..."],
|
|
@@ -79,9 +48,6 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
79
48
|
throw TaggedTemplateProcessor.SKIP;
|
|
80
49
|
}
|
|
81
50
|
super([tag, template], ...args);
|
|
82
|
-
__publicField(this, "component");
|
|
83
|
-
__privateAdd(this, _variableIdx, 0);
|
|
84
|
-
__privateAdd(this, _variablesCache, /* @__PURE__ */ new Map());
|
|
85
51
|
let component;
|
|
86
52
|
if (tagOp[0] === "call" && tagOp.length === 2) {
|
|
87
53
|
const value = tagOp[1];
|
|
@@ -90,17 +56,16 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
90
56
|
} else if (value.kind === ValueType.CONST) {
|
|
91
57
|
component = typeof value.value === "string" ? value.value : void 0;
|
|
92
58
|
} else {
|
|
93
|
-
if (
|
|
59
|
+
if (value.importedFrom?.length) {
|
|
94
60
|
const selfPkg = findPackageJSON(".", this.context.filename);
|
|
95
61
|
const isSomeMatched = value.importedFrom.some((importedFrom) => {
|
|
96
|
-
var _a2;
|
|
97
62
|
const importedPkg = findPackageJSON(
|
|
98
63
|
importedFrom,
|
|
99
64
|
this.context.filename
|
|
100
65
|
);
|
|
101
66
|
if (importedPkg) {
|
|
102
67
|
const packageJSON = JSON.parse(readFileSync(importedPkg, "utf8"));
|
|
103
|
-
let mask =
|
|
68
|
+
let mask = packageJSON?.linaria?.components;
|
|
104
69
|
if (importedPkg === selfPkg && mask === void 0) {
|
|
105
70
|
mask = "**/*";
|
|
106
71
|
}
|
|
@@ -141,6 +106,46 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
141
106
|
}
|
|
142
107
|
this.component = component;
|
|
143
108
|
}
|
|
109
|
+
get asSelector() {
|
|
110
|
+
return `.${this.className}`;
|
|
111
|
+
}
|
|
112
|
+
get value() {
|
|
113
|
+
const t = this.astService;
|
|
114
|
+
const extendsNode = typeof this.component === "string" || this.component.nonLinaria ? null : this.component.node.name;
|
|
115
|
+
return t.objectExpression([
|
|
116
|
+
t.objectProperty(
|
|
117
|
+
t.stringLiteral("displayName"),
|
|
118
|
+
t.stringLiteral(this.displayName)
|
|
119
|
+
),
|
|
120
|
+
t.objectProperty(
|
|
121
|
+
t.stringLiteral("__linaria"),
|
|
122
|
+
t.objectExpression([
|
|
123
|
+
t.objectProperty(
|
|
124
|
+
t.stringLiteral("className"),
|
|
125
|
+
t.stringLiteral(this.className)
|
|
126
|
+
),
|
|
127
|
+
t.objectProperty(
|
|
128
|
+
t.stringLiteral("extends"),
|
|
129
|
+
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
|
|
130
|
+
)
|
|
131
|
+
])
|
|
132
|
+
)
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
get tagExpression() {
|
|
136
|
+
const t = this.astService;
|
|
137
|
+
return t.callExpression(this.callee, [this.tagExpressionArgument]);
|
|
138
|
+
}
|
|
139
|
+
get tagExpressionArgument() {
|
|
140
|
+
const t = this.astService;
|
|
141
|
+
if (typeof this.component === "string") {
|
|
142
|
+
if (this.component === "FunctionalComponent") {
|
|
143
|
+
return t.arrowFunctionExpression([], t.blockStatement([]));
|
|
144
|
+
}
|
|
145
|
+
return singleQuotedStringLiteral(this.component);
|
|
146
|
+
}
|
|
147
|
+
return t.callExpression(t.identifier(this.component.node.name), []);
|
|
148
|
+
}
|
|
144
149
|
addInterpolation(node, precedingCss, source, unit = "") {
|
|
145
150
|
const id = this.getVariableId(source, unit, precedingCss);
|
|
146
151
|
this.interpolations.push({
|
|
@@ -174,50 +179,10 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
174
179
|
cssText,
|
|
175
180
|
className: this.className,
|
|
176
181
|
displayName: this.displayName,
|
|
177
|
-
start:
|
|
182
|
+
start: loc?.start ?? null
|
|
178
183
|
};
|
|
179
184
|
return rules;
|
|
180
185
|
}
|
|
181
|
-
get asSelector() {
|
|
182
|
-
return `.${this.className}`;
|
|
183
|
-
}
|
|
184
|
-
get tagExpressionArgument() {
|
|
185
|
-
const t = this.astService;
|
|
186
|
-
if (typeof this.component === "string") {
|
|
187
|
-
if (this.component === "FunctionalComponent") {
|
|
188
|
-
return t.arrowFunctionExpression([], t.blockStatement([]));
|
|
189
|
-
}
|
|
190
|
-
return singleQuotedStringLiteral(this.component);
|
|
191
|
-
}
|
|
192
|
-
return t.callExpression(t.identifier(this.component.node.name), []);
|
|
193
|
-
}
|
|
194
|
-
get tagExpression() {
|
|
195
|
-
const t = this.astService;
|
|
196
|
-
return t.callExpression(this.callee, [this.tagExpressionArgument]);
|
|
197
|
-
}
|
|
198
|
-
get value() {
|
|
199
|
-
const t = this.astService;
|
|
200
|
-
const extendsNode = typeof this.component === "string" || this.component.nonLinaria ? null : this.component.node.name;
|
|
201
|
-
return t.objectExpression([
|
|
202
|
-
t.objectProperty(
|
|
203
|
-
t.stringLiteral("displayName"),
|
|
204
|
-
t.stringLiteral(this.displayName)
|
|
205
|
-
),
|
|
206
|
-
t.objectProperty(
|
|
207
|
-
t.stringLiteral("__linaria"),
|
|
208
|
-
t.objectExpression([
|
|
209
|
-
t.objectProperty(
|
|
210
|
-
t.stringLiteral("className"),
|
|
211
|
-
t.stringLiteral(this.className)
|
|
212
|
-
),
|
|
213
|
-
t.objectProperty(
|
|
214
|
-
t.stringLiteral("extends"),
|
|
215
|
-
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
|
|
216
|
-
)
|
|
217
|
-
])
|
|
218
|
-
)
|
|
219
|
-
]);
|
|
220
|
-
}
|
|
221
186
|
toString() {
|
|
222
187
|
const res = (arg) => `${this.tagSourceCode()}(${arg})\`\u2026\``;
|
|
223
188
|
if (typeof this.component === "string") {
|
|
@@ -234,7 +199,7 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
234
199
|
if (!customSlugFn) {
|
|
235
200
|
return void 0;
|
|
236
201
|
}
|
|
237
|
-
return typeof customSlugFn === "function" ? customSlugFn(context) : buildSlug(customSlugFn, context);
|
|
202
|
+
return typeof customSlugFn === "function" ? customSlugFn(context) : buildSlug(customSlugFn, { ...context });
|
|
238
203
|
}
|
|
239
204
|
getProps() {
|
|
240
205
|
const propsObj = {
|
|
@@ -282,7 +247,7 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
282
247
|
}
|
|
283
248
|
getVariableContext(source, unit, precedingCss) {
|
|
284
249
|
const getIndex = () => {
|
|
285
|
-
return
|
|
250
|
+
return this.#variableIdx++;
|
|
286
251
|
};
|
|
287
252
|
return {
|
|
288
253
|
componentName: this.displayName,
|
|
@@ -299,19 +264,17 @@ var StyledProcessor = class extends TaggedTemplateProcessor {
|
|
|
299
264
|
}
|
|
300
265
|
getVariableId(source, unit, precedingCss) {
|
|
301
266
|
const value = source + unit;
|
|
302
|
-
if (!
|
|
267
|
+
if (!this.#variablesCache.has(value)) {
|
|
303
268
|
const id = this.getCustomVariableId(source, unit, precedingCss);
|
|
304
269
|
if (id) {
|
|
305
270
|
return toValidCSSIdentifier(id);
|
|
306
271
|
}
|
|
307
272
|
const context = this.getVariableContext(source, unit, precedingCss);
|
|
308
|
-
|
|
273
|
+
this.#variablesCache.set(value, `${this.slug}-${context.index}`);
|
|
309
274
|
}
|
|
310
|
-
return
|
|
275
|
+
return this.#variablesCache.get(value);
|
|
311
276
|
}
|
|
312
277
|
};
|
|
313
|
-
_variableIdx = new WeakMap();
|
|
314
|
-
_variablesCache = new WeakMap();
|
|
315
278
|
export {
|
|
316
279
|
StyledProcessor as default
|
|
317
280
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import { readFileSync } from 'fs';\nimport { dirname, join, sep } from 'path';\n\nimport type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\nimport { minimatch } from 'minimatch';\nimport html from 'react-html-attributes';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n TaggedTemplateProcessor,\n validateParams,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { findPackageJSON, hasMeta, slugify, ValueType } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nconst allTagsSet = new Set([...html.elements.html, html.elements.svg]);\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n propsAsIs: boolean;\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 // Should have at least two params and the first one should be a callee.\n validateParams(\n params,\n ['callee', '*', '...'],\n TaggedTemplateProcessor.SKIP\n );\n\n validateParams(\n params,\n ['callee', ['call', 'member'], ['template', 'call']],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n if (template[0] === 'call') {\n // It is already transformed styled-literal. Skip it.\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw TaggedTemplateProcessor.SKIP;\n }\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 if (value.kind === ValueType.CONST) {\n component = typeof value.value === 'string' ? value.value : undefined;\n } else {\n if (value.importedFrom?.length) {\n const selfPkg = findPackageJSON('.', this.context.filename);\n\n // Check if at least one used identifier is a Linaria component.\n const isSomeMatched = value.importedFrom.some((importedFrom) => {\n const importedPkg = findPackageJSON(\n importedFrom,\n this.context.filename\n );\n\n if (importedPkg) {\n const packageJSON = JSON.parse(readFileSync(importedPkg, 'utf8'));\n let mask: string | undefined = packageJSON?.linaria?.components;\n if (importedPkg === selfPkg && mask === undefined) {\n // If mask is not specified for the local package, all components are treated as styled.\n mask = '**/*';\n }\n\n if (mask) {\n const packageDir = dirname(importedPkg);\n const normalizedMask = mask.replace(/\\//g, sep);\n const fullMask = join(packageDir, normalizedMask);\n const fileWithComponent = require.resolve(importedFrom, {\n paths: [dirname(this.context.filename!)],\n });\n\n return minimatch(fileWithComponent, fullMask);\n }\n }\n\n return false;\n });\n\n if (!isSomeMatched) {\n component = {\n node: value.ex,\n nonLinaria: true,\n source: value.source,\n };\n }\n }\n\n if (component === undefined) {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\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 precedingCss: string,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source, unit, precedingCss);\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' || this.component.nonLinaria\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.callee, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' || this.component.nonLinaria\n ? null\n : 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 getCustomVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ) {\n const context = this.getVariableContext(source, unit, precedingCss);\n const customSlugFn = this.options.variableNameSlug;\n if (!customSlugFn) {\n return undefined;\n }\n\n return typeof customSlugFn === 'function'\n ? customSlugFn(context)\n : buildSlug(customSlugFn, context);\n }\n\n protected getProps(): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n propsAsIs:\n typeof this.component !== 'string' || !allTagsSet.has(this.component),\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 === undefined) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (value === null) {\n return t.objectProperty(keyNode, t.nullLiteral());\n }\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 protected getVariableContext(\n source: string,\n unit: string,\n precedingCss: string\n ): IVariableContext {\n const getIndex = () => {\n // eslint-disable-next-line no-plusplus\n return this.#variableIdx++;\n };\n\n return {\n componentName: this.displayName,\n componentSlug: this.slug,\n get index() {\n return getIndex();\n },\n precedingCss,\n processor: this.constructor.name,\n source,\n unit,\n valueSlug: slugify(source + unit),\n };\n }\n\n protected getVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ): string {\n const value = source + unit;\n if (!this.#variablesCache.has(value)) {\n const id = this.getCustomVariableId(source, unit, precedingCss);\n if (id) {\n return toValidCSSIdentifier(id);\n }\n\n const context = this.getVariableContext(source, unit, precedingCss);\n\n // make the variable unique to this styled component\n this.#variablesCache.set(value, `${this.slug}-${context.index}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,MAAM,WAAW;AASnC,SAAS,iB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aAAO,EAAE,eAAe,SAAS,EAAE,iBAAiB,IAAI,CAAC;AAAA,IAC3D,CAAC,EACA,OAAO,SAAS;AAEnB,WAAO,EAAE,iBAAiB,eAAe;AAAA,EAC3C;AAAA,EAEU,mBACR,QACA,MACA,cACkB;AAClB,UAAM,WAAW,MAAM;AAErB,aAAO,uBAAK,cAAL;AAAA,IACT;AAEA,WAAO;AAAA,MACL,eAAe,KAAK;AAAA,MACpB,eAAe,KAAK;AAAA,MACpB,IAAI,QAAQ;AACV,eAAO,SAAS;AAAA,MAClB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,YAAY;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,WAAW,QAAQ,SAAS,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEU,cACR,QACA,MACA,cACQ;AACR,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,mBAAK,iBAAgB,IAAI,KAAK,GAAG;AACpC,YAAM,KAAK,KAAK,oBAAoB,QAAQ,MAAM,YAAY;AAC9D,UAAI,IAAI;AACN,eAAO,qBAAqB,EAAE;AAAA,MAChC;AAEA,YAAM,UAAU,KAAK,mBAAmB,QAAQ,MAAM,YAAY;AAGlE,yBAAK,iBAAgB,IAAI,OAAO,GAAG,KAAK,QAAQ,QAAQ,OAAO;AAAA,IACjE;AAEA,WAAO,mBAAK,iBAAgB,IAAI,KAAK;AAAA,EACvC;AACF;AAhWE;AAEA;","names":["_a"]}
|
|
1
|
+
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import { readFileSync } from 'fs';\nimport { dirname, join, sep } from 'path';\n\nimport type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\nimport { minimatch } from 'minimatch';\nimport html from 'react-html-attributes';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n TaggedTemplateProcessor,\n validateParams,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { findPackageJSON, hasMeta, slugify, ValueType } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nconst allTagsSet = new Set([...html.elements.html, html.elements.svg]);\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n propsAsIs: boolean;\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 // Should have at least two params and the first one should be a callee.\n validateParams(\n params,\n ['callee', '*', '...'],\n TaggedTemplateProcessor.SKIP\n );\n\n validateParams(\n params,\n ['callee', ['call', 'member'], ['template', 'call']],\n 'Invalid usage of `styled` tag'\n );\n\n const [tag, tagOp, template] = params;\n\n if (template[0] === 'call') {\n // It is already transformed styled-literal. Skip it.\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw TaggedTemplateProcessor.SKIP;\n }\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 if (value.kind === ValueType.CONST) {\n component = typeof value.value === 'string' ? value.value : undefined;\n } else {\n if (value.importedFrom?.length) {\n const selfPkg = findPackageJSON('.', this.context.filename);\n\n // Check if at least one used identifier is a Linaria component.\n const isSomeMatched = value.importedFrom.some((importedFrom) => {\n const importedPkg = findPackageJSON(\n importedFrom,\n this.context.filename\n );\n\n if (importedPkg) {\n const packageJSON = JSON.parse(readFileSync(importedPkg, 'utf8'));\n let mask: string | undefined = packageJSON?.linaria?.components;\n if (importedPkg === selfPkg && mask === undefined) {\n // If mask is not specified for the local package, all components are treated as styled.\n mask = '**/*';\n }\n\n if (mask) {\n const packageDir = dirname(importedPkg);\n const normalizedMask = mask.replace(/\\//g, sep);\n const fullMask = join(packageDir, normalizedMask);\n const fileWithComponent = require.resolve(importedFrom, {\n paths: [dirname(this.context.filename!)],\n });\n\n return minimatch(fileWithComponent, fullMask);\n }\n }\n\n return false;\n });\n\n if (!isSomeMatched) {\n component = {\n node: value.ex,\n nonLinaria: true,\n source: value.source,\n };\n }\n }\n\n if (component === undefined) {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\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 get asSelector(): string {\n return `.${this.className}`;\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' || this.component.nonLinaria\n ? null\n : 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 get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.callee, [this.tagExpressionArgument]);\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 public override addInterpolation(\n node: Expression,\n precedingCss: string,\n source: string,\n unit = ''\n ): string {\n const id = this.getVariableId(source, unit, precedingCss);\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' || this.component.nonLinaria\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 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 getCustomVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ) {\n const context = this.getVariableContext(source, unit, precedingCss);\n const customSlugFn = this.options.variableNameSlug;\n if (!customSlugFn) {\n return undefined;\n }\n\n return typeof customSlugFn === 'function'\n ? customSlugFn(context)\n : buildSlug(customSlugFn, { ...context });\n }\n\n protected getProps(): IProps {\n const propsObj: IProps = {\n name: this.displayName,\n class: this.className,\n propsAsIs:\n typeof this.component !== 'string' || !allTagsSet.has(this.component),\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 === undefined) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (value === null) {\n return t.objectProperty(keyNode, t.nullLiteral());\n }\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 protected getVariableContext(\n source: string,\n unit: string,\n precedingCss: string\n ): IVariableContext {\n const getIndex = () => {\n // eslint-disable-next-line no-plusplus\n return this.#variableIdx++;\n };\n\n return {\n componentName: this.displayName,\n componentSlug: this.slug,\n get index() {\n return getIndex();\n },\n precedingCss,\n processor: this.constructor.name,\n source,\n unit,\n valueSlug: slugify(source + unit),\n };\n }\n\n protected getVariableId(\n source: string,\n unit: string,\n precedingCss: string\n ): string {\n const value = source + unit;\n if (!this.#variablesCache.has(value)) {\n const id = this.getCustomVariableId(source, unit, precedingCss);\n if (id) {\n return toValidCSSIdentifier(id);\n }\n\n const context = this.getVariableContext(source, unit, precedingCss);\n\n // make the variable unique to this styled component\n this.#variablesCache.set(value, `${this.slug}-${context.index}`);\n }\n\n return this.#variablesCache.get(value)!;\n }\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,MAAM,WAAW;AASnC,SAAS,iBAAiB;AAC1B,OAAO,UAAU;AASjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,iBAAiB,SAAS,SAAS,iBAAiB;AAE7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nB,WAAO,EAAE,iBAAiB,eAAe;AAAA,EAC3C;AAAA,EAEU,mBACR,QACA,MACA,cACkB;AAClB,UAAM,WAAW,MAAM;AAErB,aAAO,KAAK;AAAA,IACd;AAEA,WAAO;AAAA,MACL,eAAe,KAAK;AAAA,MACpB,eAAe,KAAK;AAAA,MACpB,IAAI,QAAQ;AACV,eAAO,SAAS;AAAA,MAClB;AAAA,MACA;AAAA,MACA,WAAW,KAAK,YAAY;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,WAAW,QAAQ,SAAS,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEU,cACR,QACA,MACA,cACQ;AACR,UAAM,QAAQ,SAAS;AACvB,QAAI,CAAC,KAAK,gBAAgB,IAAI,KAAK,GAAG;AACpC,YAAM,KAAK,KAAK,oBAAoB,QAAQ,MAAM,YAAY;AAC9D,UAAI,IAAI;AACN,eAAO,qBAAqB,EAAE;AAAA,MAChC;AAEA,YAAM,UAAU,KAAK,mBAAmB,QAAQ,MAAM,YAAY;AAGlE,WAAK,gBAAgB,IAAI,OAAO,GAAG,KAAK,IAAI,IAAI,QAAQ,KAAK,EAAE;AAAA,IACjE;AAEA,WAAO,KAAK,gBAAgB,IAAI,KAAK;AAAA,EACvC;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linaria/react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.1",
|
|
4
4
|
"description": "Blazing fast zero-runtime CSS in JS library",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"css",
|
|
@@ -52,13 +52,13 @@
|
|
|
52
52
|
"minimatch": "^9.0.3",
|
|
53
53
|
"react-html-attributes": "^1.4.6",
|
|
54
54
|
"ts-invariant": "^0.10.3",
|
|
55
|
-
"@linaria/core": "^
|
|
56
|
-
"@linaria/tags": "^
|
|
57
|
-
"@linaria/utils": "^
|
|
55
|
+
"@linaria/core": "^5.0.1",
|
|
56
|
+
"@linaria/tags": "^5.0.1",
|
|
57
|
+
"@linaria/utils": "^5.0.1"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
|
-
"@babel/types": "^7.22.
|
|
61
|
-
"@types/babel__core": "^7.1
|
|
60
|
+
"@babel/types": "^7.22.15",
|
|
61
|
+
"@types/babel__core": "^7.20.1",
|
|
62
62
|
"@types/node": "^17.0.39",
|
|
63
63
|
"@types/react": ">=16",
|
|
64
64
|
"react": "^16.14.0",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"react": ">=16"
|
|
69
69
|
},
|
|
70
70
|
"engines": {
|
|
71
|
-
"node": "
|
|
71
|
+
"node": ">=16.0.0"
|
|
72
72
|
},
|
|
73
73
|
"publishConfig": {
|
|
74
74
|
"access": "public"
|
|
@@ -13,14 +13,14 @@ export default class StyledProcessor extends TaggedTemplateProcessor {
|
|
|
13
13
|
#private;
|
|
14
14
|
component: WrappedNode;
|
|
15
15
|
constructor(params: Params, ...args: TailProcessorParams);
|
|
16
|
+
get asSelector(): string;
|
|
17
|
+
get value(): ObjectExpression;
|
|
18
|
+
protected get tagExpression(): CallExpression;
|
|
19
|
+
protected get tagExpressionArgument(): Expression;
|
|
16
20
|
addInterpolation(node: Expression, precedingCss: string, source: string, unit?: string): string;
|
|
17
21
|
doEvaltimeReplacement(): void;
|
|
18
22
|
doRuntimeReplacement(): void;
|
|
19
23
|
extractRules(valueCache: ValueCache, cssText: string, loc?: SourceLocation | null): Rules;
|
|
20
|
-
get asSelector(): string;
|
|
21
|
-
protected get tagExpressionArgument(): Expression;
|
|
22
|
-
protected get tagExpression(): CallExpression;
|
|
23
|
-
get value(): ObjectExpression;
|
|
24
24
|
toString(): string;
|
|
25
25
|
protected getCustomVariableId(source: string, unit: string, precedingCss: string): string | undefined;
|
|
26
26
|
protected getProps(): IProps;
|
package/types/styled.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
2
|
import type { CSSProperties } from '@linaria/core';
|
|
3
3
|
import type { StyledMeta } from '@linaria/utils';
|
|
4
|
-
export
|
|
5
|
-
|
|
4
|
+
export type NoInfer<A> = [A][A extends any ? 0 : never];
|
|
5
|
+
type Component<TProps> = ((props: TProps) => unknown) | {
|
|
6
6
|
new (props: TProps): unknown;
|
|
7
7
|
};
|
|
8
|
-
|
|
8
|
+
type Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;
|
|
9
9
|
export declare const omit: <T extends Record<string, unknown>, TKeys extends keyof T>(obj: T, keys: TKeys[]) => Omit<T, TKeys>;
|
|
10
10
|
declare function styled(componentWithStyle: () => any): (error: 'The target component should have a className prop') => void;
|
|
11
11
|
declare function styled<TProps extends Has<TMustHave, {
|
|
@@ -20,16 +20,16 @@ declare function styled<TProps extends Has<TMustHave, {
|
|
|
20
20
|
}, TConstructor extends Component<TProps>>(componentWithoutStyle: TConstructor & Component<TProps>): ComponentStyledTagWithoutInterpolation<TConstructor>;
|
|
21
21
|
declare function styled<TName extends keyof JSX.IntrinsicElements>(tag: TName): HtmlStyledTag<TName>;
|
|
22
22
|
declare function styled(component: 'The target component should have a className prop'): never;
|
|
23
|
-
export
|
|
23
|
+
export type StyledComponent<T> = StyledMeta & ([T] extends [React.FunctionComponent<any>] ? T : React.FunctionComponent<T & {
|
|
24
24
|
as?: React.ElementType;
|
|
25
25
|
}>);
|
|
26
|
-
|
|
27
|
-
export
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
export
|
|
26
|
+
type StaticPlaceholder = string | number | CSSProperties | StyledMeta;
|
|
27
|
+
export type HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <TAdditionalProps = Record<never, unknown>>(strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>) => string | number)>) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;
|
|
28
|
+
type ComponentStyledTagWithoutInterpolation<TOrigCmp> = (strings: TemplateStringsArray, ...exprs: Array<StaticPlaceholder | ((props: 'The target component should have a style prop') => never)>) => StyledMeta & TOrigCmp;
|
|
29
|
+
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>;
|
|
30
|
+
export type StyledJSXIntrinsics = {
|
|
31
31
|
readonly [P in keyof JSX.IntrinsicElements]: HtmlStyledTag<P>;
|
|
32
32
|
};
|
|
33
|
-
export
|
|
33
|
+
export type Styled = typeof styled & StyledJSXIntrinsics;
|
|
34
34
|
declare const _default: Styled;
|
|
35
35
|
export default _default;
|