Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@linaria/react

Package Overview
Dependencies
Maintainers
4
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@linaria/react - npm Package Compare versions

Comparing version
4.1.5
to
4.2.0
+132
dist/index.js
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
styled: () => styled_default
});
module.exports = __toCommonJS(src_exports);
// src/styled.ts
var import_is_prop_valid = __toESM(require("@emotion/is-prop-valid"));
var import_react = __toESM(require("react"));
var import_core = require("@linaria/core");
var isCapital = (ch) => ch.toUpperCase() === ch;
var filterKey = (keys) => (key) => keys.indexOf(key) === -1;
var omit = (obj, keys) => {
const res = {};
Object.keys(obj).filter(filterKey(keys)).forEach((key) => {
res[key] = obj[key];
});
return res;
};
function filterProps(component, props, omitKeys) {
const filteredProps = omit(props, omitKeys);
if (typeof component === "string" && component.indexOf("-") === -1 && !isCapital(component[0])) {
Object.keys(filteredProps).forEach((key) => {
if (!(0, import_is_prop_valid.default)(key)) {
delete filteredProps[key];
}
});
}
return filteredProps;
}
var warnIfInvalid = (value, componentName) => {
if (process.env.NODE_ENV !== "production") {
if (typeof value === "string" || typeof value === "number" && isFinite(value)) {
return;
}
const stringified = typeof value === "object" ? JSON.stringify(value) : String(value);
console.warn(
`An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`
);
}
};
function styled(tag) {
return (options) => {
if (process.env.NODE_ENV !== "production") {
if (Array.isArray(options)) {
throw new Error(
'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'
);
}
}
const render = (props, ref) => {
const { as: component = tag, class: className } = props;
const filteredProps = filterProps(component, props, [
"as",
"class"
]);
filteredProps.ref = ref;
filteredProps.className = options.atomic ? (0, import_core.cx)(options.class, filteredProps.className || className) : (0, import_core.cx)(filteredProps.className || className, options.class);
const { vars } = options;
if (vars) {
const style = {};
for (const name in vars) {
const variable = vars[name];
const result = variable[0];
const unit = variable[1] || "";
const value = typeof result === "function" ? result(props) : result;
warnIfInvalid(value, options.name);
style[`--${name}`] = `${value}${unit}`;
}
const ownStyle = filteredProps.style || {};
const keys = Object.keys(ownStyle);
if (keys.length > 0) {
keys.forEach((key) => {
style[key] = ownStyle[key];
});
}
filteredProps.style = style;
}
if (tag.__linaria && tag !== component) {
filteredProps.as = component;
return import_react.default.createElement(tag, filteredProps);
}
return import_react.default.createElement(component, filteredProps);
};
const Result = import_react.default.forwardRef ? import_react.default.forwardRef(render) : (props) => {
const rest = omit(props, ["innerRef"]);
return render(rest, props.innerRef);
};
Result.displayName = options.name;
Result.__linaria = {
className: options.class,
extends: tag
};
return Result;
};
}
var styled_default = process.env.NODE_ENV !== "production" ? new Proxy(styled, {
get(o, prop) {
return o(prop);
}
}) : styled;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
styled
});
//# sourceMappingURL=index.js.map
{"version":3,"sources":["../src/index.ts","../src/styled.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type { StyledJSXIntrinsics, Styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\nexport type { StyledMeta } from '@linaria/tags';\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/tags';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\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;AAwBnB,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,WACA,OACA,UACyB;AACzB,QAAM,gBAAgB,KAAK,OAAO,QAAQ;AAG1C,MACE,OAAO,cAAc,YACrB,UAAU,QAAQ,GAAG,MAAM,MAC3B,CAAC,UAAU,UAAU,EAAE,GACvB;AACA,WAAO,KAAK,aAAa,EAAE,QAAQ,CAAC,QAAQ;AAC1C,UAAI,KAAC,qBAA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AAM,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,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,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;AAAA,MACnB,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"]}
// src/styled.ts
import validAttr from "@emotion/is-prop-valid";
import React from "react";
import { cx } from "@linaria/core";
var isCapital = (ch) => ch.toUpperCase() === ch;
var filterKey = (keys) => (key) => keys.indexOf(key) === -1;
var omit = (obj, keys) => {
const res = {};
Object.keys(obj).filter(filterKey(keys)).forEach((key) => {
res[key] = obj[key];
});
return res;
};
function filterProps(component, props, omitKeys) {
const filteredProps = omit(props, omitKeys);
if (typeof component === "string" && component.indexOf("-") === -1 && !isCapital(component[0])) {
Object.keys(filteredProps).forEach((key) => {
if (!validAttr(key)) {
delete filteredProps[key];
}
});
}
return filteredProps;
}
var warnIfInvalid = (value, componentName) => {
if (process.env.NODE_ENV !== "production") {
if (typeof value === "string" || typeof value === "number" && isFinite(value)) {
return;
}
const stringified = typeof value === "object" ? JSON.stringify(value) : String(value);
console.warn(
`An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`
);
}
};
function styled(tag) {
return (options) => {
if (process.env.NODE_ENV !== "production") {
if (Array.isArray(options)) {
throw new Error(
'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'
);
}
}
const render = (props, ref) => {
const { as: component = tag, class: className } = props;
const filteredProps = filterProps(component, props, [
"as",
"class"
]);
filteredProps.ref = ref;
filteredProps.className = options.atomic ? cx(options.class, filteredProps.className || className) : cx(filteredProps.className || className, options.class);
const { vars } = options;
if (vars) {
const style = {};
for (const name in vars) {
const variable = vars[name];
const result = variable[0];
const unit = variable[1] || "";
const value = typeof result === "function" ? result(props) : result;
warnIfInvalid(value, options.name);
style[`--${name}`] = `${value}${unit}`;
}
const ownStyle = filteredProps.style || {};
const keys = Object.keys(ownStyle);
if (keys.length > 0) {
keys.forEach((key) => {
style[key] = ownStyle[key];
});
}
filteredProps.style = style;
}
if (tag.__linaria && tag !== component) {
filteredProps.as = component;
return React.createElement(tag, filteredProps);
}
return React.createElement(component, filteredProps);
};
const Result = React.forwardRef ? React.forwardRef(render) : (props) => {
const rest = omit(props, ["innerRef"]);
return render(rest, props.innerRef);
};
Result.displayName = options.name;
Result.__linaria = {
className: options.class,
extends: tag
};
return Result;
};
}
var styled_default = process.env.NODE_ENV !== "production" ? new Proxy(styled, {
get(o, prop) {
return o(prop);
}
}) : styled;
export {
styled_default as styled
};
//# sourceMappingURL=index.mjs.map
{"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/tags';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\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;AAwBnB,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,WACA,OACA,UACyB;AACzB,QAAM,gBAAgB,KAAK,OAAO,QAAQ;AAG1C,MACE,OAAO,cAAc,YACrB,UAAU,QAAQ,GAAG,MAAM,MAC3B,CAAC,UAAU,UAAU,EAAE,GACvB;AACA,WAAO,KAAK,aAAa,EAAE,QAAQ,CAAC,QAAQ;AAC1C,UAAI,CAAC,UAAU,GAAG,GAAG;AAEnB,eAAO,cAAc;AAAA,MACvB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAEA,IAAM,gBAAgB,CAAC,OAAgB,kBAA0B;AAC/D,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,QACE,OAAO,UAAU,YAEhB,OAAO,UAAU,YAAY,SAAS,KAAK,GAC5C;AACA;AAAA,IACF;AAEA,UAAM,cACJ,O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AO,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;AAAA,MACnB,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":[]}
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/processors/styled.ts
var styled_exports = {};
__export(styled_exports, {
default: () => StyledProcessor
});
module.exports = __toCommonJS(styled_exports);
var import_tags = require("@linaria/tags");
var import_utils = require("@linaria/utils");
var isNotNull = (x) => x !== null;
var singleQuotedStringLiteral = (value) => ({
type: "StringLiteral",
value,
extra: {
rawValue: value,
raw: `'${value}'`
}
});
var _variableIdx, _variablesCache;
var StyledProcessor = class extends import_tags.TaggedTemplateProcessor {
constructor(params, ...args) {
(0, import_tags.validateParams)(
params,
["tag", ["call", "member"], ["template", "call"]],
"Invalid usage of `styled` tag"
);
const [tag, tagOp, template] = params;
if (template[0] === "call") {
throw import_tags.TaggedTemplateProcessor.SKIP;
}
super([tag, template], ...args);
__publicField(this, "component");
__privateAdd(this, _variableIdx, 0);
__privateAdd(this, _variablesCache, /* @__PURE__ */ new Map());
let component;
if (tagOp[0] === "call" && tagOp.length === 2) {
const value = tagOp[1];
if (value.kind === import_tags.ValueType.FUNCTION) {
component = "FunctionalComponent";
} else {
component = {
node: value.ex,
source: value.source
};
this.dependencies.push(value);
}
}
if (tagOp[0] === "member") {
[, component] = tagOp;
}
if (!component) {
throw new Error("Invalid usage of `styled` tag");
}
this.component = component;
}
addInterpolation(node, precedingCss, source, unit = "") {
const id = this.getVariableId(source, unit, precedingCss);
this.interpolations.push({
id,
node,
source,
unit
});
return id;
}
doEvaltimeReplacement() {
this.replacer(this.value, false);
}
doRuntimeReplacement() {
const t = this.astService;
const props = this.getProps();
this.replacer(
t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),
true
);
}
extractRules(valueCache, cssText, loc) {
const rules = {};
let selector = `.${this.className}`;
let value = typeof this.component === "string" ? null : valueCache.get(this.component.node.name);
while ((0, import_tags.hasMeta)(value)) {
selector += `.${value.__linaria.className}`;
value = value.__linaria.extends;
}
rules[selector] = {
cssText,
className: this.className,
displayName: this.displayName,
start: (loc == null ? void 0 : loc.start) ?? null
};
return rules;
}
get asSelector() {
return `.${this.className}`;
}
get tagExpressionArgument() {
const t = this.astService;
if (typeof this.component === "string") {
if (this.component === "FunctionalComponent") {
return t.arrowFunctionExpression([], t.blockStatement([]));
}
return singleQuotedStringLiteral(this.component);
}
return t.callExpression(t.identifier(this.component.node.name), []);
}
get tagExpression() {
const t = this.astService;
return t.callExpression(this.tag, [this.tagExpressionArgument]);
}
get value() {
const t = this.astService;
const extendsNode = typeof this.component === "string" ? null : this.component.node.name;
return t.objectExpression([
t.objectProperty(
t.stringLiteral("displayName"),
t.stringLiteral(this.displayName)
),
t.objectProperty(
t.stringLiteral("__linaria"),
t.objectExpression([
t.objectProperty(
t.stringLiteral("className"),
t.stringLiteral(this.className)
),
t.objectProperty(
t.stringLiteral("extends"),
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
)
])
)
]);
}
toString() {
const res = (arg) => `${this.tagSourceCode()}(${arg})\`\u2026\``;
if (typeof this.component === "string") {
if (this.component === "FunctionalComponent") {
return res("() => {\u2026}");
}
return res(`'${this.component}'`);
}
return res(this.component.source);
}
getCustomVariableId(source, unit, precedingCss) {
const context = this.getVariableContext(source, unit, precedingCss);
const customSlugFn = this.options.variableNameSlug;
if (!customSlugFn) {
return void 0;
}
return typeof customSlugFn === "function" ? customSlugFn(context) : (0, import_tags.buildSlug)(customSlugFn, context);
}
getProps() {
const propsObj = {
name: this.displayName,
class: this.className
};
if (this.interpolations.length) {
propsObj.vars = {};
this.interpolations.forEach(({ id, unit, node }) => {
const items = [this.astService.callExpression(node, [])];
if (unit) {
items.push(this.astService.stringLiteral(unit));
}
propsObj.vars[id] = items;
});
}
return propsObj;
}
getTagComponentProps(props) {
const t = this.astService;
const propExpressions = Object.entries(props).map(([key, value]) => {
if (!value) {
return null;
}
const keyNode = t.identifier(key);
if (typeof value === "string") {
return t.objectProperty(keyNode, t.stringLiteral(value));
}
if (typeof value === "boolean") {
return t.objectProperty(keyNode, t.booleanLiteral(value));
}
const vars = Object.entries(value).map(([propName, propValue]) => {
return t.objectProperty(
t.stringLiteral(propName),
t.arrayExpression(propValue)
);
});
return t.objectProperty(keyNode, t.objectExpression(vars));
}).filter(isNotNull);
return t.objectExpression(propExpressions);
}
getVariableContext(source, unit, precedingCss) {
const getIndex = () => {
return __privateWrapper(this, _variableIdx)._++;
};
return {
componentName: this.displayName,
componentSlug: this.slug,
get index() {
return getIndex();
},
precedingCss,
processor: this.constructor.name,
source,
unit,
valueSlug: (0, import_utils.slugify)(source + unit)
};
}
getVariableId(source, unit, precedingCss) {
const value = source + unit;
if (!__privateGet(this, _variablesCache).has(value)) {
const id = this.getCustomVariableId(source, unit, precedingCss);
if (id) {
return (0, import_tags.toValidCSSIdentifier)(id);
}
const context = this.getVariableContext(source, unit, precedingCss);
__privateGet(this, _variablesCache).set(value, `${this.slug}-${context.index}`);
}
return __privateGet(this, _variablesCache).get(value);
}
};
_variableIdx = new WeakMap();
_variablesCache = new WeakMap();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
//# sourceMappingURL=styled.js.map
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n hasMeta,\n TaggedTemplateProcessor,\n validateParams,\n ValueType,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { slugify } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], ['template', '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 {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(\n node: Expression,\n 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'\n ? null\n : valueCache.get(this.component.node.name);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return rules;\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.callExpression(t.identifier(this.component.node.name), []);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tag, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\n }\n\n protected 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 };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(node, [])];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n 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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,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;AAnSE;AAEA;","names":[]}
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/processors/styled.ts
import {
buildSlug,
hasMeta,
TaggedTemplateProcessor,
validateParams,
ValueType,
toValidCSSIdentifier
} from "@linaria/tags";
import { slugify } from "@linaria/utils";
var isNotNull = (x) => x !== null;
var singleQuotedStringLiteral = (value) => ({
type: "StringLiteral",
value,
extra: {
rawValue: value,
raw: `'${value}'`
}
});
var _variableIdx, _variablesCache;
var StyledProcessor = class extends TaggedTemplateProcessor {
constructor(params, ...args) {
validateParams(
params,
["tag", ["call", "member"], ["template", "call"]],
"Invalid usage of `styled` tag"
);
const [tag, tagOp, template] = params;
if (template[0] === "call") {
throw TaggedTemplateProcessor.SKIP;
}
super([tag, template], ...args);
__publicField(this, "component");
__privateAdd(this, _variableIdx, 0);
__privateAdd(this, _variablesCache, /* @__PURE__ */ new Map());
let component;
if (tagOp[0] === "call" && tagOp.length === 2) {
const value = tagOp[1];
if (value.kind === ValueType.FUNCTION) {
component = "FunctionalComponent";
} else {
component = {
node: value.ex,
source: value.source
};
this.dependencies.push(value);
}
}
if (tagOp[0] === "member") {
[, component] = tagOp;
}
if (!component) {
throw new Error("Invalid usage of `styled` tag");
}
this.component = component;
}
addInterpolation(node, precedingCss, source, unit = "") {
const id = this.getVariableId(source, unit, precedingCss);
this.interpolations.push({
id,
node,
source,
unit
});
return id;
}
doEvaltimeReplacement() {
this.replacer(this.value, false);
}
doRuntimeReplacement() {
const t = this.astService;
const props = this.getProps();
this.replacer(
t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]),
true
);
}
extractRules(valueCache, cssText, loc) {
const rules = {};
let selector = `.${this.className}`;
let value = typeof this.component === "string" ? null : valueCache.get(this.component.node.name);
while (hasMeta(value)) {
selector += `.${value.__linaria.className}`;
value = value.__linaria.extends;
}
rules[selector] = {
cssText,
className: this.className,
displayName: this.displayName,
start: (loc == null ? void 0 : loc.start) ?? null
};
return rules;
}
get asSelector() {
return `.${this.className}`;
}
get tagExpressionArgument() {
const t = this.astService;
if (typeof this.component === "string") {
if (this.component === "FunctionalComponent") {
return t.arrowFunctionExpression([], t.blockStatement([]));
}
return singleQuotedStringLiteral(this.component);
}
return t.callExpression(t.identifier(this.component.node.name), []);
}
get tagExpression() {
const t = this.astService;
return t.callExpression(this.tag, [this.tagExpressionArgument]);
}
get value() {
const t = this.astService;
const extendsNode = typeof this.component === "string" ? null : this.component.node.name;
return t.objectExpression([
t.objectProperty(
t.stringLiteral("displayName"),
t.stringLiteral(this.displayName)
),
t.objectProperty(
t.stringLiteral("__linaria"),
t.objectExpression([
t.objectProperty(
t.stringLiteral("className"),
t.stringLiteral(this.className)
),
t.objectProperty(
t.stringLiteral("extends"),
extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral()
)
])
)
]);
}
toString() {
const res = (arg) => `${this.tagSourceCode()}(${arg})\`\u2026\``;
if (typeof this.component === "string") {
if (this.component === "FunctionalComponent") {
return res("() => {\u2026}");
}
return res(`'${this.component}'`);
}
return res(this.component.source);
}
getCustomVariableId(source, unit, precedingCss) {
const context = this.getVariableContext(source, unit, precedingCss);
const customSlugFn = this.options.variableNameSlug;
if (!customSlugFn) {
return void 0;
}
return typeof customSlugFn === "function" ? customSlugFn(context) : buildSlug(customSlugFn, context);
}
getProps() {
const propsObj = {
name: this.displayName,
class: this.className
};
if (this.interpolations.length) {
propsObj.vars = {};
this.interpolations.forEach(({ id, unit, node }) => {
const items = [this.astService.callExpression(node, [])];
if (unit) {
items.push(this.astService.stringLiteral(unit));
}
propsObj.vars[id] = items;
});
}
return propsObj;
}
getTagComponentProps(props) {
const t = this.astService;
const propExpressions = Object.entries(props).map(([key, value]) => {
if (!value) {
return null;
}
const keyNode = t.identifier(key);
if (typeof value === "string") {
return t.objectProperty(keyNode, t.stringLiteral(value));
}
if (typeof value === "boolean") {
return t.objectProperty(keyNode, t.booleanLiteral(value));
}
const vars = Object.entries(value).map(([propName, propValue]) => {
return t.objectProperty(
t.stringLiteral(propName),
t.arrayExpression(propValue)
);
});
return t.objectProperty(keyNode, t.objectExpression(vars));
}).filter(isNotNull);
return t.objectExpression(propExpressions);
}
getVariableContext(source, unit, precedingCss) {
const getIndex = () => {
return __privateWrapper(this, _variableIdx)._++;
};
return {
componentName: this.displayName,
componentSlug: this.slug,
get index() {
return getIndex();
},
precedingCss,
processor: this.constructor.name,
source,
unit,
valueSlug: slugify(source + unit)
};
}
getVariableId(source, unit, precedingCss) {
const value = source + unit;
if (!__privateGet(this, _variablesCache).has(value)) {
const id = this.getCustomVariableId(source, unit, precedingCss);
if (id) {
return toValidCSSIdentifier(id);
}
const context = this.getVariableContext(source, unit, precedingCss);
__privateGet(this, _variablesCache).set(value, `${this.slug}-${context.index}`);
}
return __privateGet(this, _variablesCache).get(value);
}
};
_variableIdx = new WeakMap();
_variablesCache = new WeakMap();
export {
StyledProcessor as default
};
//# sourceMappingURL=styled.mjs.map
{"version":3,"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n hasMeta,\n TaggedTemplateProcessor,\n validateParams,\n ValueType,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { slugify } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], ['template', '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 {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(\n node: Expression,\n 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'\n ? null\n : valueCache.get(this.component.node.name);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return rules;\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.callExpression(t.identifier(this.component.node.name), []);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tag, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\n }\n\n protected 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 };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(node, [])];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe;AAExB,IAAM,YAAY,CAAI,MAAwB,MAAM;AASpD,IAAM,4BAA4B,CAAC,WAAkC;AAAA,EACnE,MAAM;AAAA,EACN;AAAA,EACA,OAAO;AAAA,IACL,UAAU;AAAA,IACV,KAAK,IAAI;AAAA,EACX;AACF;AA1CA;AA4CA,IAAqB,kBAArB,cAA6C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ACvB,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;AAnSE;AAEA;","names":[]}
+21
-14
{
"name": "@linaria/react",
"description": "Blazing fast zero-runtime CSS in JS library",
"version": "4.1.5",
"version": "4.2.0",
"bugs": "https://github.com/callstack/linaria/issues",
"dependencies": {
"@emotion/is-prop-valid": "^0.8.8",
"@linaria/core": "^4.1.4",
"@linaria/core": "^4.2.0",
"@linaria/tags": "^4.1.4",

@@ -28,14 +28,13 @@ "@linaria/utils": "^4.2.2",

"types": "./types/index.d.ts",
"import": "./esm/index.js",
"default": "./lib/index.js"
"import": "./dist/index.mjs",
"default": "./dist/index.js"
},
"./*": {
"types": "./types/*.d.ts",
"import": "./esm/*.js",
"default": "./lib/*.js"
"import": "./dist/*.mjs",
"default": "./dist/*.js"
}
},
"files": [
"esm/",
"lib/",
"dist/",
"processors/",

@@ -55,7 +54,7 @@ "types/"

"tags": {
"styled": "./lib/processors/styled.js"
"styled": "./dist/processors/styled.js"
}
},
"main": "lib/index.js",
"module": "esm/index.js",
"main": "dist/index.js",
"module": "dist/index.mjs",
"peerDependencies": {

@@ -69,2 +68,11 @@ "react": ">=16"

"sideEffects": false,
"tsup": {
"entry": [
"src/index.ts",
"src/processors/styled.ts"
],
"splitting": false,
"sourcemap": true,
"clean": true
},
"types": "types/index.d.ts",

@@ -79,7 +87,6 @@ "typesVersions": {

"scripts": {
"build": "npm run build:lib && npm run build:esm && npm run build:declarations",
"build": "npm run build:dist && npm run build:declarations",
"build:corejs-test": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --ignore \"src/processors/**/*\"",
"build:declarations": "tsc --emitDeclarationOnly --outDir types",
"build:esm": "babel src --out-dir esm --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:lib": "cross-env NODE_ENV=legacy babel src --out-dir lib --extensions '.js,.jsx,.ts,.tsx' --source-maps --delete-dir-on-start",
"build:dist": "tsup --format cjs,esm",
"test": "jest --config ../../jest.config.js --rootDir .",

@@ -86,0 +93,0 @@ "test:dts": "dtslint --localTs ../../node_modules/typescript/lib __dtslint__",

+1
-1

@@ -5,2 +5,2 @@ Object.defineProperty(exports, '__esModule', {

exports.default = require('../lib/processors/styled').default;
exports.default = require('../dist/processors/styled').default;
export { default as styled } from './styled';
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","names":["default","styled"],"sources":["../src/index.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type { StyledJSXIntrinsics, Styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\nexport type { StyledMeta } from '@linaria/tags';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,MAApB,QAAkC,UAAlC"}
import { buildSlug, hasMeta, TaggedTemplateProcessor, validateParams, ValueType, toValidCSSIdentifier } from '@linaria/tags';
import { slugify } from '@linaria/utils';
const isNotNull = x => x !== null;
const singleQuotedStringLiteral = value => ({
type: 'StringLiteral',
value,
extra: {
rawValue: value,
raw: `'${value}'`
}
});
export default class StyledProcessor extends TaggedTemplateProcessor {
#variableIdx = 0;
#variablesCache = new Map();
constructor(params, ...args) {
validateParams(params, ['tag', ['call', 'member'], ['template', 'call']], 'Invalid usage of `styled` tag');
const [tag, tagOp, template] = params;
if (template[0] === 'call') {
// It is already transformed styled-literal. Skip it.
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw TaggedTemplateProcessor.SKIP;
}
super([tag, template], ...args);
let component;
if (tagOp[0] === 'call' && tagOp.length === 2) {
const value = tagOp[1];
if (value.kind === ValueType.FUNCTION) {
component = 'FunctionalComponent';
} else {
component = {
node: value.ex,
source: value.source
};
this.dependencies.push(value);
}
}
if (tagOp[0] === 'member') {
[, component] = tagOp;
}
if (!component) {
throw new Error('Invalid usage of `styled` tag');
}
this.component = component;
}
addInterpolation(node, precedingCss, source, unit = '') {
const id = this.getVariableId(source, unit, precedingCss);
this.interpolations.push({
id,
node,
source,
unit
});
return id;
}
doEvaltimeReplacement() {
this.replacer(this.value, false);
}
doRuntimeReplacement() {
const t = this.astService;
const props = this.getProps();
this.replacer(t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true);
}
extractRules(valueCache, cssText, loc) {
const rules = {};
let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
// get its class name to create a more specific selector
// it'll ensure that styles are overridden properly
let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node.name);
while (hasMeta(value)) {
selector += `.${value.__linaria.className}`;
value = value.__linaria.extends;
}
rules[selector] = {
cssText,
className: this.className,
displayName: this.displayName,
start: loc?.start ?? null
};
return rules;
}
get asSelector() {
return `.${this.className}`;
}
get tagExpressionArgument() {
const t = this.astService;
if (typeof this.component === 'string') {
if (this.component === 'FunctionalComponent') {
return t.arrowFunctionExpression([], t.blockStatement([]));
}
return singleQuotedStringLiteral(this.component);
}
return t.callExpression(t.identifier(this.component.node.name), []);
}
get tagExpression() {
const t = this.astService;
return t.callExpression(this.tag, [this.tagExpressionArgument]);
}
get value() {
const t = this.astService;
const extendsNode = typeof this.component === 'string' ? null : this.component.node.name;
return t.objectExpression([t.objectProperty(t.stringLiteral('displayName'), t.stringLiteral(this.displayName)), t.objectProperty(t.stringLiteral('__linaria'), t.objectExpression([t.objectProperty(t.stringLiteral('className'), t.stringLiteral(this.className)), t.objectProperty(t.stringLiteral('extends'), extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral())]))]);
}
toString() {
const res = arg => `${this.tagSourceCode()}(${arg})\`…\``;
if (typeof this.component === 'string') {
if (this.component === 'FunctionalComponent') {
return res('() => {…}');
}
return res(`'${this.component}'`);
}
return res(this.component.source);
}
getCustomVariableId(source, unit, precedingCss) {
const context = this.getVariableContext(source, unit, precedingCss);
const customSlugFn = this.options.variableNameSlug;
if (!customSlugFn) {
return undefined;
}
return typeof customSlugFn === 'function' ? customSlugFn(context) : buildSlug(customSlugFn, context);
}
getProps() {
const propsObj = {
name: this.displayName,
class: this.className
}; // If we found any interpolations, also pass them, so they can be applied
if (this.interpolations.length) {
propsObj.vars = {};
this.interpolations.forEach(({
id,
unit,
node
}) => {
const items = [this.astService.callExpression(node, [])];
if (unit) {
items.push(this.astService.stringLiteral(unit));
}
propsObj.vars[id] = items;
});
}
return propsObj;
}
getTagComponentProps(props) {
const t = this.astService;
const propExpressions = Object.entries(props).map(([key, value]) => {
if (!value) {
return null;
}
const keyNode = t.identifier(key);
if (typeof value === 'string') {
return t.objectProperty(keyNode, t.stringLiteral(value));
}
if (typeof value === 'boolean') {
return t.objectProperty(keyNode, t.booleanLiteral(value));
}
const vars = Object.entries(value).map(([propName, propValue]) => {
return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
});
return t.objectProperty(keyNode, t.objectExpression(vars));
}).filter(isNotNull);
return t.objectExpression(propExpressions);
}
getVariableContext(source, unit, precedingCss) {
const getIndex = () => {
// eslint-disable-next-line no-plusplus
return this.#variableIdx++;
};
return {
componentName: this.displayName,
componentSlug: this.slug,
get index() {
return getIndex();
},
precedingCss,
processor: this.constructor.name,
source,
unit,
valueSlug: slugify(source + unit)
};
}
getVariableId(source, unit, precedingCss) {
const value = source + unit;
if (!this.#variablesCache.has(value)) {
const id = this.getCustomVariableId(source, unit, precedingCss);
if (id) {
return toValidCSSIdentifier(id);
}
const context = this.getVariableContext(source, unit, precedingCss); // make the variable unique to this styled component
this.#variablesCache.set(value, `${this.slug}-${context.index}`);
}
return this.#variablesCache.get(value);
}
}
//# sourceMappingURL=styled.js.map
{"version":3,"file":"styled.js","names":["buildSlug","hasMeta","TaggedTemplateProcessor","validateParams","ValueType","toValidCSSIdentifier","slugify","isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","variableIdx","variablesCache","Map","constructor","params","args","tag","tagOp","template","SKIP","component","length","kind","FUNCTION","node","ex","source","dependencies","push","Error","addInterpolation","precedingCss","unit","id","getVariableId","interpolations","doEvaltimeReplacement","replacer","doRuntimeReplacement","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","extractRules","valueCache","cssText","loc","rules","selector","className","get","name","__linaria","extends","displayName","start","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","toString","res","arg","tagSourceCode","getCustomVariableId","context","getVariableContext","customSlugFn","options","variableNameSlug","undefined","propsObj","class","vars","forEach","items","propExpressions","Object","entries","map","key","keyNode","booleanLiteral","propName","propValue","arrayExpression","filter","getIndex","componentName","componentSlug","slug","index","processor","valueSlug","has","set"],"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n hasMeta,\n TaggedTemplateProcessor,\n validateParams,\n ValueType,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { slugify } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], ['template', '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 {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(\n node: Expression,\n 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'\n ? null\n : valueCache.get(this.component.node.name);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return rules;\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.callExpression(t.identifier(this.component.node.name), []);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tag, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\n }\n\n protected 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 };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(node, [])];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n 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":"AAeA,SACEA,SADF,EAEEC,OAFF,EAGEC,uBAHF,EAIEC,cAJF,EAKEC,SALF,EAMEC,oBANF,QAOO,eAPP;AASA,SAASC,OAAT,QAAwB,gBAAxB;;AAEA,MAAMC,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIC,KAAD,KAAmC;EACnEC,IAAI,EAAE,eAD6D;EAEnED,KAFmE;EAGnEE,KAAK,EAAE;I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R,MADqB,EAErBM,IAFqB,EAGrBD,YAHqB,EAIb;IACR,MAAM3B,KAAK,GAAGsB,MAAM,GAAGM,IAAvB;;IACA,IAAI,CAAC,KAAK,CAACrB,cAAN,CAAqB4F,GAArB,CAAyBnG,KAAzB,CAAL,EAAsC;MACpC,MAAM6B,EAAE,GAAG,KAAKwC,mBAAL,CAAyB/C,MAAzB,EAAiCM,IAAjC,EAAuCD,YAAvC,CAAX;;MACA,IAAIE,EAAJ,EAAQ;QACN,OAAOlC,oBAAoB,CAACkC,EAAD,CAA3B;MACD;;MAED,MAAMyC,OAAO,GAAG,KAAKC,kBAAL,CAAwBjD,MAAxB,EAAgCM,IAAhC,EAAsCD,YAAtC,CAAhB,CANoC,CAQpC;;MACA,KAAK,CAACpB,cAAN,CAAqB6F,GAArB,CAAyBpG,KAAzB,EAAiC,GAAE,KAAK+F,IAAK,IAAGzB,OAAO,CAAC0B,KAAM,EAA9D;IACD;;IAED,OAAO,KAAK,CAACzF,cAAN,CAAqB0C,GAArB,CAAyBjD,KAAzB,CAAP;EACD;;AArSkE"}
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* This file contains an runtime version of `styled` component. Responsibilities of the component are:
* - returns ReactElement based on HTML tag used with `styled` or custom React Component
* - injects classNames for the returned component
* - injects CSS variables used to define dynamic styles based on props
*/
import validAttr from '@emotion/is-prop-valid';
import React from 'react';
import { cx } from '@linaria/core';
const isCapital = ch => ch.toUpperCase() === ch;
const filterKey = keys => key => keys.indexOf(key) === -1;
export const omit = (obj, keys) => {
const res = {};
Object.keys(obj).filter(filterKey(keys)).forEach(key => {
res[key] = obj[key];
});
return res;
};
function filterProps(component, props, omitKeys) {
const filteredProps = omit(props, omitKeys); // Check if it's an HTML tag and not a custom element
if (typeof component === 'string' && component.indexOf('-') === -1 && !isCapital(component[0])) {
Object.keys(filteredProps).forEach(key => {
if (!validAttr(key)) {
// Don't pass through invalid attributes to HTML elements
delete filteredProps[key];
}
});
}
return filteredProps;
}
const warnIfInvalid = (value, componentName) => {
if (process.env.NODE_ENV !== 'production') {
if (typeof value === 'string' || // eslint-disable-next-line no-self-compare,no-restricted-globals
typeof value === 'number' && isFinite(value)) {
return;
}
const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); // eslint-disable-next-line no-console
console.warn(`An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`);
}
};
function styled(tag) {
return options => {
if (process.env.NODE_ENV !== 'production') {
if (Array.isArray(options)) {
// We received a strings array since it's used as a tag
throw new Error('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');
}
}
const render = (props, ref) => {
const {
as: component = tag,
class: className
} = props;
const filteredProps = filterProps(component, props, ['as', 'class']);
filteredProps.ref = ref;
filteredProps.className = options.atomic ? cx(options.class, filteredProps.className || className) : cx(filteredProps.className || className, options.class);
const {
vars
} = options;
if (vars) {
const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
for (const name in vars) {
const variable = vars[name];
const result = variable[0];
const unit = variable[1] || '';
const value = typeof result === 'function' ? result(props) : result;
warnIfInvalid(value, options.name);
style[`--${name}`] = `${value}${unit}`;
}
const ownStyle = filteredProps.style || {};
const keys = Object.keys(ownStyle);
if (keys.length > 0) {
keys.forEach(key => {
style[key] = ownStyle[key];
});
}
filteredProps.style = style;
}
if (tag.__linaria && tag !== component) {
// If the underlying tag is a styled component, forward the `as` prop
// Otherwise the styles from the underlying component will be ignored
filteredProps.as = component;
return /*#__PURE__*/React.createElement(tag, filteredProps);
}
return /*#__PURE__*/React.createElement(component, filteredProps);
};
const Result = React.forwardRef ? /*#__PURE__*/React.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
// Fallback to a innerRef prop in that case
props => {
const rest = omit(props, ['innerRef']);
return render(rest, props.innerRef);
};
Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
Result.__linaria = {
className: options.class,
extends: tag
};
return Result;
};
}
export default process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
get(o, prop) {
return o(prop);
}
}) : styled;
//# sourceMappingURL=styled.js.map
{"version":3,"file":"styled.js","names":["validAttr","React","cx","isCapital","ch","toUpperCase","filterKey","keys","key","indexOf","omit","obj","res","Object","filter","forEach","filterProps","component","props","omitKeys","filteredProps","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","ref","as","class","className","atomic","vars","style","name","variable","result","unit","ownStyle","length","__linaria","createElement","Result","forwardRef","rest","innerRef","displayName","extends","Proxy","get","o","prop"],"sources":["../src/styled.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport validAttr from '@emotion/is-prop-valid';\nimport React from 'react';\n\nimport { cx } from '@linaria/core';\nimport type { CSSProperties } from '@linaria/core';\nimport type { StyledMeta } from '@linaria/tags';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\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;;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAOA,SAAP,MAAsB,wBAAtB;AACA,OAAOC,KAAP,MAAkB,OAAlB;AAEA,SAASC,EAAT,QAAmB,eAAnB;;AAwBA,MAAMC,SAAS,GAAIC,EAAD,IAAyBA,EAAE,CAACC,WAAH,OAAqBD,EAAhE;;AACA,MAAME,SAAS,GACgBC,IAA7B,IACyBC,GAAzB,IACED,IAAI,CAACE,OAAL,CAAaD,GAAb,MAA6B,CAAC,CAHlC;;AAKA,OAAO,MAAME,IAAI,GAAG,CAClBC,GADkB,EAElBJ,IAFkB,K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;MAC1BV,SAAS,EAAER,OAAO,CAACO,KADO;MAE1BkB,OAAO,EAAE1B;IAFiB,CAA5B;IAKA,OAAOqB,MAAP;EACD,CA9ED;AA+ED;;AAgDD,eAAgBhC,OAAO,CAACC,GAAR,CAAYC,QAAZ,KAAyB,YAAzB,GACZ,IAAIoC,KAAJ,CAAU5B,MAAV,EAAkB;EAChB6B,GAAG,CAACC,CAAD,EAAIC,IAAJ,EAAuC;IACxC,OAAOD,CAAC,CAACC,IAAD,CAAR;EACD;;AAHe,CAAlB,CADY,GAMZ/B,MANJ"}
"use strict";
exports.__esModule = true;
exports.styled = void 0;
var _styled = _interopRequireDefault(require("./styled"));
exports.styled = _styled.default;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export { default as styled } from './styled';\nexport type { StyledJSXIntrinsics, Styled } from './styled';\nexport type { CSSProperties } from '@linaria/core';\nexport type { StyledMeta } from '@linaria/tags';\n"],"mappings":";;;;;AAAA"}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _tags = require("@linaria/tags");
var _utils = require("@linaria/utils");
const isNotNull = x => x !== null;
const singleQuotedStringLiteral = value => ({
type: 'StringLiteral',
value,
extra: {
rawValue: value,
raw: `'${value}'`
}
});
class StyledProcessor extends _tags.TaggedTemplateProcessor {
#variableIdx = 0;
#variablesCache = new Map();
constructor(params, ...args) {
(0, _tags.validateParams)(params, ['tag', ['call', 'member'], ['template', 'call']], 'Invalid usage of `styled` tag');
const [tag, tagOp, template] = params;
if (template[0] === 'call') {
// It is already transformed styled-literal. Skip it.
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw _tags.TaggedTemplateProcessor.SKIP;
}
super([tag, template], ...args);
let component;
if (tagOp[0] === 'call' && tagOp.length === 2) {
const value = tagOp[1];
if (value.kind === _tags.ValueType.FUNCTION) {
component = 'FunctionalComponent';
} else {
component = {
node: value.ex,
source: value.source
};
this.dependencies.push(value);
}
}
if (tagOp[0] === 'member') {
[, component] = tagOp;
}
if (!component) {
throw new Error('Invalid usage of `styled` tag');
}
this.component = component;
}
addInterpolation(node, precedingCss, source, unit = '') {
const id = this.getVariableId(source, unit, precedingCss);
this.interpolations.push({
id,
node,
source,
unit
});
return id;
}
doEvaltimeReplacement() {
this.replacer(this.value, false);
}
doRuntimeReplacement() {
const t = this.astService;
const props = this.getProps();
this.replacer(t.callExpression(this.tagExpression, [this.getTagComponentProps(props)]), true);
}
extractRules(valueCache, cssText, loc) {
var _loc$start;
const rules = {};
let selector = `.${this.className}`; // If `styled` wraps another component and not a primitive,
// get its class name to create a more specific selector
// it'll ensure that styles are overridden properly
let value = typeof this.component === 'string' ? null : valueCache.get(this.component.node.name);
while ((0, _tags.hasMeta)(value)) {
selector += `.${value.__linaria.className}`;
value = value.__linaria.extends;
}
rules[selector] = {
cssText,
className: this.className,
displayName: this.displayName,
start: (_loc$start = loc === null || loc === void 0 ? void 0 : loc.start) !== null && _loc$start !== void 0 ? _loc$start : null
};
return rules;
}
get asSelector() {
return `.${this.className}`;
}
get tagExpressionArgument() {
const t = this.astService;
if (typeof this.component === 'string') {
if (this.component === 'FunctionalComponent') {
return t.arrowFunctionExpression([], t.blockStatement([]));
}
return singleQuotedStringLiteral(this.component);
}
return t.callExpression(t.identifier(this.component.node.name), []);
}
get tagExpression() {
const t = this.astService;
return t.callExpression(this.tag, [this.tagExpressionArgument]);
}
get value() {
const t = this.astService;
const extendsNode = typeof this.component === 'string' ? null : this.component.node.name;
return t.objectExpression([t.objectProperty(t.stringLiteral('displayName'), t.stringLiteral(this.displayName)), t.objectProperty(t.stringLiteral('__linaria'), t.objectExpression([t.objectProperty(t.stringLiteral('className'), t.stringLiteral(this.className)), t.objectProperty(t.stringLiteral('extends'), extendsNode ? t.callExpression(t.identifier(extendsNode), []) : t.nullLiteral())]))]);
}
toString() {
const res = arg => `${this.tagSourceCode()}(${arg})\`…\``;
if (typeof this.component === 'string') {
if (this.component === 'FunctionalComponent') {
return res('() => {…}');
}
return res(`'${this.component}'`);
}
return res(this.component.source);
}
getCustomVariableId(source, unit, precedingCss) {
const context = this.getVariableContext(source, unit, precedingCss);
const customSlugFn = this.options.variableNameSlug;
if (!customSlugFn) {
return undefined;
}
return typeof customSlugFn === 'function' ? customSlugFn(context) : (0, _tags.buildSlug)(customSlugFn, context);
}
getProps() {
const propsObj = {
name: this.displayName,
class: this.className
}; // If we found any interpolations, also pass them, so they can be applied
if (this.interpolations.length) {
propsObj.vars = {};
this.interpolations.forEach(({
id,
unit,
node
}) => {
const items = [this.astService.callExpression(node, [])];
if (unit) {
items.push(this.astService.stringLiteral(unit));
}
propsObj.vars[id] = items;
});
}
return propsObj;
}
getTagComponentProps(props) {
const t = this.astService;
const propExpressions = Object.entries(props).map(([key, value]) => {
if (!value) {
return null;
}
const keyNode = t.identifier(key);
if (typeof value === 'string') {
return t.objectProperty(keyNode, t.stringLiteral(value));
}
if (typeof value === 'boolean') {
return t.objectProperty(keyNode, t.booleanLiteral(value));
}
const vars = Object.entries(value).map(([propName, propValue]) => {
return t.objectProperty(t.stringLiteral(propName), t.arrayExpression(propValue));
});
return t.objectProperty(keyNode, t.objectExpression(vars));
}).filter(isNotNull);
return t.objectExpression(propExpressions);
}
getVariableContext(source, unit, precedingCss) {
const getIndex = () => {
// eslint-disable-next-line no-plusplus
return this.#variableIdx++;
};
return {
componentName: this.displayName,
componentSlug: this.slug,
get index() {
return getIndex();
},
precedingCss,
processor: this.constructor.name,
source,
unit,
valueSlug: (0, _utils.slugify)(source + unit)
};
}
getVariableId(source, unit, precedingCss) {
const value = source + unit;
if (!this.#variablesCache.has(value)) {
const id = this.getCustomVariableId(source, unit, precedingCss);
if (id) {
return (0, _tags.toValidCSSIdentifier)(id);
}
const context = this.getVariableContext(source, unit, precedingCss); // make the variable unique to this styled component
this.#variablesCache.set(value, `${this.slug}-${context.index}`);
}
return this.#variablesCache.get(value);
}
}
exports.default = StyledProcessor;
//# sourceMappingURL=styled.js.map
{"version":3,"file":"styled.js","names":["isNotNull","x","singleQuotedStringLiteral","value","type","extra","rawValue","raw","StyledProcessor","TaggedTemplateProcessor","variableIdx","variablesCache","Map","constructor","params","args","validateParams","tag","tagOp","template","SKIP","component","length","kind","ValueType","FUNCTION","node","ex","source","dependencies","push","Error","addInterpolation","precedingCss","unit","id","getVariableId","interpolations","doEvaltimeReplacement","replacer","doRuntimeReplacement","t","astService","props","getProps","callExpression","tagExpression","getTagComponentProps","extractRules","valueCache","cssText","loc","rules","selector","className","get","name","hasMeta","__linaria","extends","displayName","start","asSelector","tagExpressionArgument","arrowFunctionExpression","blockStatement","identifier","extendsNode","objectExpression","objectProperty","stringLiteral","nullLiteral","toString","res","arg","tagSourceCode","getCustomVariableId","context","getVariableContext","customSlugFn","options","variableNameSlug","undefined","buildSlug","propsObj","class","vars","forEach","items","propExpressions","Object","entries","map","key","keyNode","booleanLiteral","propName","propValue","arrayExpression","filter","getIndex","componentName","componentSlug","slug","index","processor","valueSlug","slugify","has","toValidCSSIdentifier","set"],"sources":["../../src/processors/styled.ts"],"sourcesContent":["import type {\n CallExpression,\n Expression,\n ObjectExpression,\n SourceLocation,\n StringLiteral,\n} from '@babel/types';\n\nimport type {\n Params,\n Rules,\n TailProcessorParams,\n ValueCache,\n WrappedNode,\n} from '@linaria/tags';\nimport {\n buildSlug,\n hasMeta,\n TaggedTemplateProcessor,\n validateParams,\n ValueType,\n toValidCSSIdentifier,\n} from '@linaria/tags';\nimport type { IVariableContext } from '@linaria/utils';\nimport { slugify } from '@linaria/utils';\n\nconst isNotNull = <T>(x: T | null): x is T => x !== null;\n\nexport interface IProps {\n atomic?: boolean;\n class?: string;\n name: string;\n vars?: Record<string, Expression[]>;\n}\n\nconst singleQuotedStringLiteral = (value: string): StringLiteral => ({\n type: 'StringLiteral',\n value,\n extra: {\n rawValue: value,\n raw: `'${value}'`,\n },\n});\n\nexport default class StyledProcessor extends TaggedTemplateProcessor {\n public component: WrappedNode;\n\n #variableIdx = 0;\n\n #variablesCache = new Map<string, string>();\n\n constructor(params: Params, ...args: TailProcessorParams) {\n validateParams(\n params,\n ['tag', ['call', 'member'], ['template', '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 {\n component = {\n node: value.ex,\n source: value.source,\n };\n\n this.dependencies.push(value);\n }\n }\n\n if (tagOp[0] === 'member') {\n [, component] = tagOp;\n }\n\n if (!component) {\n throw new Error('Invalid usage of `styled` tag');\n }\n\n this.component = component;\n }\n\n public override addInterpolation(\n node: Expression,\n 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'\n ? null\n : valueCache.get(this.component.node.name);\n while (hasMeta(value)) {\n selector += `.${value.__linaria.className}`;\n value = value.__linaria.extends;\n }\n\n rules[selector] = {\n cssText,\n className: this.className,\n displayName: this.displayName,\n start: loc?.start ?? null,\n };\n\n return rules;\n }\n\n public override get asSelector(): string {\n return `.${this.className}`;\n }\n\n protected get tagExpressionArgument(): Expression {\n const t = this.astService;\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return t.arrowFunctionExpression([], t.blockStatement([]));\n }\n\n return singleQuotedStringLiteral(this.component);\n }\n\n return t.callExpression(t.identifier(this.component.node.name), []);\n }\n\n protected get tagExpression(): CallExpression {\n const t = this.astService;\n return t.callExpression(this.tag, [this.tagExpressionArgument]);\n }\n\n public override get value(): ObjectExpression {\n const t = this.astService;\n const extendsNode =\n typeof this.component === 'string' ? null : this.component.node.name;\n\n return t.objectExpression([\n t.objectProperty(\n t.stringLiteral('displayName'),\n t.stringLiteral(this.displayName)\n ),\n t.objectProperty(\n t.stringLiteral('__linaria'),\n t.objectExpression([\n t.objectProperty(\n t.stringLiteral('className'),\n t.stringLiteral(this.className)\n ),\n t.objectProperty(\n t.stringLiteral('extends'),\n extendsNode\n ? t.callExpression(t.identifier(extendsNode), [])\n : t.nullLiteral()\n ),\n ])\n ),\n ]);\n }\n\n public override toString(): string {\n const res = (arg: string) => `${this.tagSourceCode()}(${arg})\\`…\\``;\n\n if (typeof this.component === 'string') {\n if (this.component === 'FunctionalComponent') {\n return res('() => {…}');\n }\n\n return res(`'${this.component}'`);\n }\n\n return res(this.component.source);\n }\n\n protected 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 };\n\n // If we found any interpolations, also pass them, so they can be applied\n if (this.interpolations.length) {\n propsObj.vars = {};\n this.interpolations.forEach(({ id, unit, node }) => {\n const items: Expression[] = [this.astService.callExpression(node, [])];\n\n if (unit) {\n items.push(this.astService.stringLiteral(unit));\n }\n\n propsObj.vars![id] = items;\n });\n }\n\n return propsObj;\n }\n\n protected getTagComponentProps(props: IProps): ObjectExpression {\n const t = this.astService;\n\n const propExpressions = Object.entries(props)\n .map(([key, value]: [key: string, value: IProps[keyof IProps]]) => {\n if (!value) {\n return null;\n }\n\n const keyNode = t.identifier(key);\n\n if (typeof value === 'string') {\n return t.objectProperty(keyNode, t.stringLiteral(value));\n }\n\n if (typeof value === 'boolean') {\n return t.objectProperty(keyNode, t.booleanLiteral(value));\n }\n\n const vars = Object.entries(value).map(([propName, propValue]) => {\n return t.objectProperty(\n t.stringLiteral(propName),\n t.arrayExpression(propValue)\n );\n });\n\n return t.objectProperty(keyNode, t.objectExpression(vars));\n })\n .filter(isNotNull);\n\n return t.objectExpression(propExpressions);\n }\n\n 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":";;;;;;;AAeA;;AASA;;AAEA,MAAMA,SAAS,GAAOC,CAAJ,IAA4BA,CAAC,KAAK,IAApD;;AASA,MAAMC,yBAAyB,GAAIC,KAAD,KAAmC;EACnEC,IAAI,EAAE,eAD6D;EAEnED,KAFmE;EAGnEE,KAAK,EAAE;IACLC,QAAQ,EAAEH,KADL;IAELI,GAA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EAYD;;EAESE,aAAa,CACrBR,MADqB,EAErBM,IAFqB,EAGrBD,YAHqB,EAIb;IACR,MAAM9B,KAAK,GAAGyB,MAAM,GAAGM,IAAvB;;IACA,IAAI,CAAC,KAAK,CAACvB,cAAN,CAAqBiG,GAArB,CAAyBzG,KAAzB,CAAL,EAAsC;MACpC,MAAMgC,EAAE,GAAG,KAAKyC,mBAAL,CAAyBhD,MAAzB,EAAiCM,IAAjC,EAAuCD,YAAvC,CAAX;;MACA,IAAIE,EAAJ,EAAQ;QACN,OAAO,IAAA0E,0BAAA,EAAqB1E,EAArB,CAAP;MACD;;MAED,MAAM0C,OAAO,GAAG,KAAKC,kBAAL,CAAwBlD,MAAxB,EAAgCM,IAAhC,EAAsCD,YAAtC,CAAhB,CANoC,CAQpC;;MACA,KAAK,CAACtB,cAAN,CAAqBmG,GAArB,CAAyB3G,KAAzB,EAAiC,GAAE,KAAKoG,IAAK,IAAG1B,OAAO,CAAC2B,KAAM,EAA9D;IACD;;IAED,OAAO,KAAK,CAAC7F,cAAN,CAAqB4C,GAArB,CAAyBpD,KAAzB,CAAP;EACD;;AArSkE"}
"use strict";
exports.__esModule = true;
exports.omit = exports.default = void 0;
var _isPropValid = _interopRequireDefault(require("@emotion/is-prop-valid"));
var _react = _interopRequireDefault(require("react"));
var _core = require("@linaria/core");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* This file contains an runtime version of `styled` component. Responsibilities of the component are:
* - returns ReactElement based on HTML tag used with `styled` or custom React Component
* - injects classNames for the returned component
* - injects CSS variables used to define dynamic styles based on props
*/
const isCapital = ch => ch.toUpperCase() === ch;
const filterKey = keys => key => keys.indexOf(key) === -1;
const omit = (obj, keys) => {
const res = {};
Object.keys(obj).filter(filterKey(keys)).forEach(key => {
res[key] = obj[key];
});
return res;
};
exports.omit = omit;
function filterProps(component, props, omitKeys) {
const filteredProps = omit(props, omitKeys); // Check if it's an HTML tag and not a custom element
if (typeof component === 'string' && component.indexOf('-') === -1 && !isCapital(component[0])) {
Object.keys(filteredProps).forEach(key => {
if (!(0, _isPropValid.default)(key)) {
// Don't pass through invalid attributes to HTML elements
delete filteredProps[key];
}
});
}
return filteredProps;
}
const warnIfInvalid = (value, componentName) => {
if (process.env.NODE_ENV !== 'production') {
if (typeof value === 'string' || // eslint-disable-next-line no-self-compare,no-restricted-globals
typeof value === 'number' && isFinite(value)) {
return;
}
const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); // eslint-disable-next-line no-console
console.warn("An interpolation evaluated to '" + stringified + "' in the component '" + componentName + "', which is probably a mistake. You should explicitly cast or transform the value to a string.");
}
};
function styled(tag) {
return options => {
if (process.env.NODE_ENV !== 'production') {
if (Array.isArray(options)) {
// We received a strings array since it's used as a tag
throw new Error('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');
}
}
const render = (props, ref) => {
const {
as: component = tag,
class: className
} = props;
const filteredProps = filterProps(component, props, ['as', 'class']);
filteredProps.ref = ref;
filteredProps.className = options.atomic ? (0, _core.cx)(options.class, filteredProps.className || className) : (0, _core.cx)(filteredProps.className || className, options.class);
const {
vars
} = options;
if (vars) {
const style = {}; // eslint-disable-next-line guard-for-in,no-restricted-syntax
for (const name in vars) {
const variable = vars[name];
const result = variable[0];
const unit = variable[1] || '';
const value = typeof result === 'function' ? result(props) : result;
warnIfInvalid(value, options.name);
style["--" + name] = "" + value + unit;
}
const ownStyle = filteredProps.style || {};
const keys = Object.keys(ownStyle);
if (keys.length > 0) {
keys.forEach(key => {
style[key] = ownStyle[key];
});
}
filteredProps.style = style;
}
if (tag.__linaria && tag !== component) {
// If the underlying tag is a styled component, forward the `as` prop
// Otherwise the styles from the underlying component will be ignored
filteredProps.as = component;
return /*#__PURE__*/_react.default.createElement(tag, filteredProps);
}
return /*#__PURE__*/_react.default.createElement(component, filteredProps);
};
const Result = _react.default.forwardRef ? /*#__PURE__*/_react.default.forwardRef(render) : // React.forwardRef won't available on older React versions and in Preact
// Fallback to a innerRef prop in that case
props => {
const rest = omit(props, ['innerRef']);
return render(rest, props.innerRef);
};
Result.displayName = options.name; // These properties will be read by the babel plugin for interpolation
Result.__linaria = {
className: options.class,
extends: tag
};
return Result;
};
}
var _default = process.env.NODE_ENV !== 'production' ? new Proxy(styled, {
get(o, prop) {
return o(prop);
}
}) : styled;
exports.default = _default;
//# sourceMappingURL=styled.js.map
{"version":3,"file":"styled.js","names":["isCapital","ch","toUpperCase","filterKey","keys","key","indexOf","omit","obj","res","Object","filter","forEach","filterProps","component","props","omitKeys","filteredProps","validAttr","warnIfInvalid","value","componentName","process","env","NODE_ENV","isFinite","stringified","JSON","stringify","String","console","warn","styled","tag","options","Array","isArray","Error","render","ref","as","class","className","atomic","cx","vars","style","name","variable","result","unit","ownStyle","length","__linaria","React","createElement","Result","forwardRef","rest","innerRef","displayName","extends","Proxy","get","o","prop"],"sources":["../src/styled.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * This file contains an runtime version of `styled` component. Responsibilities of the component are:\n * - returns ReactElement based on HTML tag used with `styled` or custom React Component\n * - injects classNames for the returned component\n * - injects CSS variables used to define dynamic styles based on props\n */\nimport validAttr from '@emotion/is-prop-valid';\nimport React from 'react';\n\nimport { cx } from '@linaria/core';\nimport type { CSSProperties } from '@linaria/core';\nimport type { StyledMeta } from '@linaria/tags';\n\nexport type NoInfer<A> = [A][A extends any ? 0 : never];\n\ntype Component<TProps> =\n | ((props: TProps) => unknown)\n | { new (props: TProps): unknown };\n\ntype Has<T, TObj> = [T] extends [TObj] ? T : T & TObj;\n\ntype Options = {\n name: string;\n class: string;\n atomic?: boolean;\n vars?: {\n [key: string]: [\n string | number | ((props: unknown) => string | number),\n string | void\n ];\n };\n};\n\nconst isCapital = (ch: string): boolean => ch.toUpperCase() === ch;\nconst filterKey =\n <TExclude extends keyof any>(keys: TExclude[]) =>\n <TAll extends keyof any>(key: TAll): key is Exclude<TAll, TExclude> =>\n keys.indexOf(key as any) === -1;\n\nexport const omit = <T extends Record<string, unknown>, TKeys extends keyof T>(\n obj: T,\n keys: TKeys[]\n): Omit<T, TKeys> => {\n const res = {} as Omit<T, TKeys>;\n Object.keys(obj)\n .filter(filterKey(keys))\n .forEach((key) => {\n res[key] = obj[key];\n });\n\n return res;\n};\n\nfunction filterProps<T extends Record<string, unknown>, TKeys extends keyof T>(\n component: string | unknown,\n props: T,\n omitKeys: TKeys[]\n): Partial<Omit<T, TKeys>> {\n const filteredProps = omit(props, omitKeys) as Partial<T>;\n\n // Check if it's an HTML tag and not a custom element\n if (\n typeof component === 'string' &&\n component.indexOf('-') === -1 &&\n !isCapital(component[0])\n ) {\n Object.keys(filteredProps).forEach((key) => {\n if (!validAttr(key)) {\n // Don't pass through invalid attributes to HTML elements\n delete filteredProps[key];\n }\n });\n }\n\n return filteredProps;\n}\n\nconst warnIfInvalid = (value: unknown, componentName: string) => {\n if (process.env.NODE_ENV !== 'production') {\n if (\n typeof value === 'string' ||\n // eslint-disable-next-line no-self-compare,no-restricted-globals\n (typeof value === 'number' && isFinite(value))\n ) {\n return;\n }\n\n const stringified =\n typeof value === 'object' ? JSON.stringify(value) : String(value);\n\n // eslint-disable-next-line no-console\n console.warn(\n `An interpolation evaluated to '${stringified}' in the component '${componentName}', which is probably a mistake. You should explicitly cast or transform the value to a string.`\n );\n }\n};\n\ninterface IProps {\n className?: string;\n style?: Record<string, string>;\n [props: string]: unknown;\n}\n\n// Property-based interpolation is allowed only if `style` property exists\nfunction styled<\n TProps extends Has<TMustHave, { style?: React.CSSProperties }>,\n TMustHave extends { style?: React.CSSProperties },\n TConstructor extends Component<TProps>\n>(\n componentWithStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithInterpolation<TProps, TConstructor>;\n// If styled wraps custom component, that component should have className property\nfunction styled<\n TProps extends Has<TMustHave, { className?: string }>,\n TMustHave extends { className?: string },\n TConstructor extends Component<TProps>\n>(\n componentWithoutStyle: TConstructor & Component<TProps>\n): ComponentStyledTagWithoutInterpolation<TConstructor>;\nfunction styled<TName extends keyof JSX.IntrinsicElements>(\n tag: TName\n): HtmlStyledTag<TName>;\nfunction styled(\n component: 'The target component should have a className prop'\n): never;\nfunction styled(tag: any): any {\n return (options: Options) => {\n if (process.env.NODE_ENV !== 'production') {\n if (Array.isArray(options)) {\n // We received a strings array since it's used as a tag\n throw new Error(\n 'Using the \"styled\" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly. See https://github.com/callstack/linaria#setup'\n );\n }\n }\n\n const render = (props: any, ref: any) => {\n const { as: component = tag, class: className } = props;\n const filteredProps: IProps = filterProps(component, props, [\n 'as',\n 'class',\n ]);\n\n filteredProps.ref = ref;\n filteredProps.className = options.atomic\n ? cx(options.class, filteredProps.className || className)\n : cx(filteredProps.className || className, options.class);\n\n const { vars } = options;\n\n if (vars) {\n const style: { [key: string]: string } = {};\n\n // eslint-disable-next-line guard-for-in,no-restricted-syntax\n for (const name in vars) {\n const variable = vars[name];\n const result = variable[0];\n const unit = variable[1] || '';\n const value = typeof result === 'function' ? result(props) : result;\n\n warnIfInvalid(value, options.name);\n\n style[`--${name}`] = `${value}${unit}`;\n }\n\n const ownStyle = filteredProps.style || {};\n const keys = Object.keys(ownStyle);\n if (keys.length > 0) {\n keys.forEach((key) => {\n style[key] = ownStyle[key];\n });\n }\n\n filteredProps.style = style;\n }\n\n if ((tag as any).__linaria && tag !== component) {\n // If the underlying tag is a styled component, forward the `as` prop\n // Otherwise the styles from the underlying component will be ignored\n filteredProps.as = component;\n\n return React.createElement(tag, filteredProps);\n }\n return React.createElement(component, filteredProps);\n };\n\n const Result = React.forwardRef\n ? React.forwardRef(render)\n : // React.forwardRef won't available on older React versions and in Preact\n // Fallback to a innerRef prop in that case\n (props: any) => {\n const rest = omit(props, ['innerRef']);\n return render(rest, props.innerRef);\n };\n\n (Result as any).displayName = options.name;\n\n // These properties will be read by the babel plugin for interpolation\n (Result as any).__linaria = {\n className: options.class,\n extends: tag,\n };\n\n return Result;\n };\n}\n\ntype StyledComponent<T> = StyledMeta &\n ([T] extends [React.FunctionComponent<any>]\n ? T\n : React.FunctionComponent<T & { as?: React.ElementType }>);\n\ntype StaticPlaceholder = string | number | CSSProperties | StyledMeta;\n\ntype HtmlStyledTag<TName extends keyof JSX.IntrinsicElements> = <\n TAdditionalProps = Record<string, unknown>\n>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((\n // Without Omit here TS tries to infer TAdditionalProps\n // from a component passed for interpolation\n props: JSX.IntrinsicElements[TName] & Omit<TAdditionalProps, never>\n ) => string | number)\n >\n) => StyledComponent<JSX.IntrinsicElements[TName] & TAdditionalProps>;\n\ntype ComponentStyledTagWithoutInterpolation<TOrigCmp> = (\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: 'The target component should have a style prop') => never)\n >\n) => StyledMeta & TOrigCmp;\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype ComponentStyledTagWithInterpolation<TTrgProps, TOrigCmp> = <OwnProps = {}>(\n strings: TemplateStringsArray,\n ...exprs: Array<\n | StaticPlaceholder\n | ((props: NoInfer<OwnProps & TTrgProps>) => string | number)\n >\n) => keyof OwnProps extends never\n ? StyledMeta & TOrigCmp\n : StyledComponent<OwnProps & TTrgProps>;\n\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;;AACA;;AAEA;;;;AAVA;;AACA;AACA;AACA;AACA;AACA;AACA;AA4BA,MAAMA,SAAS,GAAIC,EAAD,IAAyBA,EAAE,CAACC,WAAH,OAAqBD,EAAhE;;AACA,MAAME,SAAS,GACgBC,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