@octanejs/styled-components 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +103 -0
  3. package/package.json +60 -0
  4. package/src/constants.ts +46 -0
  5. package/src/constructors/constructWithOptions.ts +171 -0
  6. package/src/constructors/createGlobalStyle.ts +165 -0
  7. package/src/constructors/createTheme.ts +233 -0
  8. package/src/constructors/css.ts +64 -0
  9. package/src/constructors/keyframes.ts +36 -0
  10. package/src/constructors/styled.ts +52 -0
  11. package/src/hoc/withTheme.ts +40 -0
  12. package/src/index.ts +111 -0
  13. package/src/models/ComponentStyle.ts +171 -0
  14. package/src/models/GlobalStyle.ts +129 -0
  15. package/src/models/Keyframes.ts +66 -0
  16. package/src/models/ServerStyleSheet.ts +92 -0
  17. package/src/models/StyleSheetManager.ts +210 -0
  18. package/src/models/StyledComponent.ts +346 -0
  19. package/src/models/ThemeProvider.ts +124 -0
  20. package/src/secretInternals.ts +7 -0
  21. package/src/sheet/GroupIDAllocator.ts +45 -0
  22. package/src/sheet/GroupedTag.ts +125 -0
  23. package/src/sheet/Rehydration.ts +188 -0
  24. package/src/sheet/RuleOutput.ts +66 -0
  25. package/src/sheet/Sheet.ts +162 -0
  26. package/src/sheet/Tag.ts +135 -0
  27. package/src/sheet/dom.ts +64 -0
  28. package/src/sheet/index.ts +2 -0
  29. package/src/sheet/octaneChannel.ts +57 -0
  30. package/src/sheet/types.ts +56 -0
  31. package/src/types.ts +294 -0
  32. package/src/utils/addUnitIfNeeded.ts +59 -0
  33. package/src/utils/charCodes.ts +18 -0
  34. package/src/utils/checkDynamicCreation.ts +28 -0
  35. package/src/utils/createWarnTooManyClasses.ts +33 -0
  36. package/src/utils/cssTagged.ts +3 -0
  37. package/src/utils/determineTheme.ts +10 -0
  38. package/src/utils/domElements.ts +7 -0
  39. package/src/utils/empties.ts +4 -0
  40. package/src/utils/error.ts +41 -0
  41. package/src/utils/errors.ts +20 -0
  42. package/src/utils/escape.ts +11 -0
  43. package/src/utils/flatten.ts +175 -0
  44. package/src/utils/generateAlphabeticName.ts +21 -0
  45. package/src/utils/generateComponentId.ts +6 -0
  46. package/src/utils/generateDisplayName.ts +7 -0
  47. package/src/utils/getComponentName.ts +10 -0
  48. package/src/utils/hash.ts +26 -0
  49. package/src/utils/hoist.ts +83 -0
  50. package/src/utils/hyphenateStyleName.ts +33 -0
  51. package/src/utils/interleave.ts +14 -0
  52. package/src/utils/isFunction.ts +3 -0
  53. package/src/utils/isKeyframes.ts +9 -0
  54. package/src/utils/isPlainObject.ts +11 -0
  55. package/src/utils/isStatelessFunction.ts +5 -0
  56. package/src/utils/isStaticRules.ts +17 -0
  57. package/src/utils/isStyledComponent.ts +19 -0
  58. package/src/utils/isTag.ts +10 -0
  59. package/src/utils/joinStrings.ts +26 -0
  60. package/src/utils/mixinDeep.ts +34 -0
  61. package/src/utils/nonce.ts +33 -0
  62. package/src/utils/setToString.ts +19 -0
  63. package/src/utils/stylis.ts +378 -0
@@ -0,0 +1,56 @@
1
+ import type { InsertionTarget } from '../types';
2
+
3
+ /** CSSStyleSheet-like Tag abstraction for CSS rules */
4
+ export interface Tag {
5
+ insertRule(index: number, rule: string): boolean;
6
+ deleteRule(index: number): void;
7
+ getRule(index: number): string;
8
+ length: number;
9
+ }
10
+
11
+ /** Group-aware Tag that sorts rules by indices */
12
+ export interface GroupedTag {
13
+ clearGroup(group: number): void;
14
+ getGroup(group: number): string;
15
+ groupSizes: Uint32Array;
16
+ insertRules(group: number, rules: string[]): void;
17
+ length: number;
18
+ tag: Tag;
19
+ }
20
+
21
+ export type SheetOptions = {
22
+ isServer: boolean;
23
+ nonce?: string | undefined;
24
+ target?: InsertionTarget | undefined;
25
+ useCSSOMInjection: boolean;
26
+ /** Retain a server copy for the `ServerStyleSheet` compatibility API. */
27
+ capture?: boolean;
28
+ };
29
+
30
+ /**
31
+ * Destination for compiled rules. The sheet owns names and component order;
32
+ * an output owns only where rules go and whether they survive an insertion.
33
+ */
34
+ export interface RuleOutput {
35
+ readonly persistent: boolean;
36
+ clearGroup(group: number): void;
37
+ getTag(): GroupedTag;
38
+ insertRules(id: string, name: string, group: number, rules: string[]): void;
39
+ reset(): void;
40
+ }
41
+
42
+ export interface Sheet {
43
+ allocateGSInstance(id: string): number;
44
+ clearNames(id: string): void;
45
+ clearRules(id: string): void;
46
+ clearTag(): void;
47
+ getTag(): GroupedTag;
48
+ hasNameForId(id: string, name: string): boolean;
49
+ insertRules(id: string, name: string, rules: string[]): void;
50
+ options: SheetOptions;
51
+ names: Map<string, Set<string>>;
52
+ registerName(id: string, name: string): void;
53
+ rehydrate(): void;
54
+ server: boolean;
55
+ toString(): string;
56
+ }
package/src/types.ts ADDED
@@ -0,0 +1,294 @@
1
+ // Ported from styled-components 6.4.3 (MIT), adapted for octane.
2
+ //
3
+ // Octane divergences from the upstream type surface:
4
+ // - No React: `AnyComponent` is any octane component function (`(props, scope?)`),
5
+ // refs are plain props, and there is no `forwardRef` exotic-component machinery.
6
+ // - No per-tag `JSX.IntrinsicElements` introspection: the polymorphic call
7
+ // surface is pragmatic — declared own props are fully typed, everything else
8
+ // (DOM attributes, `as`-target props) flows through a permissive prop bag.
9
+ // - The `native` runtime does not exist; the `Runtime` generic is retained so
10
+ // ported internals keep their upstream shape.
11
+ import type * as CSS from 'csstype';
12
+
13
+ import type ComponentStyle from './models/ComponentStyle';
14
+ import type { DefaultTheme } from './models/ThemeProvider';
15
+ import type createWarnTooManyClasses from './utils/createWarnTooManyClasses';
16
+ import type { SupportedHTMLElements } from './utils/domElements';
17
+
18
+ export type { CSS, DefaultTheme, SupportedHTMLElements };
19
+
20
+ /**
21
+ * Use this type to disambiguate between a styled-component instance
22
+ * and a StyleFunction or any other type of function.
23
+ */
24
+ export type StyledComponentBrand = {
25
+ readonly _sc: symbol;
26
+ };
27
+
28
+ export type BaseObject = {};
29
+
30
+ export type OmitNever<T> = {
31
+ [K in keyof T as T[K] extends never ? never : K]: T[K];
32
+ };
33
+
34
+ export type FastOmit<T extends BaseObject, U extends string | number | symbol> = {
35
+ [K in keyof T as K extends U ? never : K]: T[K];
36
+ };
37
+
38
+ export type Runtime = 'web';
39
+
40
+ /** Any octane component function. Refs arrive as a plain `ref` prop. */
41
+ export type AnyComponent<P extends BaseObject = any> = ((props: P, scope?: any) => unknown) & {
42
+ displayName?: string | undefined;
43
+ defaultProps?: Partial<P> | undefined;
44
+ };
45
+
46
+ export type KnownTarget = SupportedHTMLElements | AnyComponent;
47
+
48
+ /**
49
+ * Octane replacement for `React.ComponentPropsWithRef<Target>`: infer a
50
+ * component target's props from its function signature; host-tag strings have
51
+ * no introspectable prop map and resolve to the permissive base.
52
+ */
53
+ export type TargetProps<Target> = Target extends AnyComponent<infer P> ? P : BaseObject;
54
+ export type WebTarget =
55
+ | (string & {}) // allow custom elements, etc.
56
+ | KnownTarget;
57
+
58
+ export type StyledTarget<R extends Runtime> = R extends 'web' ? WebTarget : never;
59
+
60
+ export interface StyledOptions<R extends Runtime, Props extends BaseObject> {
61
+ attrs?: Attrs<Props>[] | undefined;
62
+ componentId?: (R extends 'web' ? string : never) | undefined;
63
+ displayName?: string | undefined;
64
+ parentComponentId?: (R extends 'web' ? string : never) | undefined;
65
+ shouldForwardProp?: ShouldForwardProp<R> | undefined;
66
+ }
67
+
68
+ export type Dict<T = any> = { [key: string]: T };
69
+
70
+ /**
71
+ * This type is intended for when data attributes are composed via
72
+ * the `.attrs` API:
73
+ *
74
+ * ```tsx
75
+ * styled.div.attrs<DataAttributes>({ 'data-testid': 'foo' })``
76
+ * ```
77
+ */
78
+ export type DataAttributes = { [key: `data-${string}`]: any };
79
+
80
+ export type ExecutionProps = {
81
+ /**
82
+ * Dynamically adjust the rendered component or HTML tag, e.g.
83
+ * ```
84
+ * const StyledButton = styled.button``
85
+ *
86
+ * <StyledButton as="a" href="/foo">
87
+ * I'm an anchor now
88
+ * </StyledButton>
89
+ * ```
90
+ */
91
+ as?: KnownTarget | undefined;
92
+ forwardedAs?: KnownTarget | undefined;
93
+ theme?: DefaultTheme | undefined;
94
+ };
95
+
96
+ /**
97
+ * ExecutionProps but with `theme` narrowed from optional to required.
98
+ */
99
+ export interface ExecutionContext extends ExecutionProps {
100
+ theme: DefaultTheme;
101
+ }
102
+
103
+ export interface StyleFunction<Props extends BaseObject> {
104
+ (executionContext: ExecutionContext & Props): Interpolation<Props>;
105
+ }
106
+
107
+ export type Interpolation<Props extends BaseObject> =
108
+ | StyleFunction<Props>
109
+ | StyledObject<Props>
110
+ | TemplateStringsArray
111
+ | string
112
+ | number
113
+ | false
114
+ | undefined
115
+ | null
116
+ | Keyframes
117
+ | StyledComponentBrand
118
+ | RuleSet<Props>
119
+ | Interpolation<Props>[];
120
+
121
+ /**
122
+ * Attr objects/functions may provide any DOM prop alongside the declared
123
+ * ones (octane has no per-tag prop map to introspect, so the DOM surface is
124
+ * a permissive bag — declared prop types still win inside the intersection).
125
+ */
126
+ export type AttrsResultShape<Props extends BaseObject = BaseObject> = ExecutionProps &
127
+ Partial<Props> & { [key: string]: any };
128
+
129
+ export type Attrs<Props extends BaseObject = BaseObject> =
130
+ | AttrsResultShape<Props>
131
+ | ((props: ExecutionContext & Props) => AttrsResultShape<Props>);
132
+
133
+ export type RuleSet<Props extends BaseObject = BaseObject> = Interpolation<Props>[];
134
+
135
+ export type Styles<Props extends BaseObject> =
136
+ | TemplateStringsArray
137
+ | StyledObject<Props>
138
+ | StyleFunction<Props>;
139
+
140
+ export type NameGenerator = (hash: number) => string;
141
+
142
+ export interface StyleSheet {
143
+ create: Function;
144
+ }
145
+
146
+ export interface Keyframes {
147
+ id: string;
148
+ name: string;
149
+ rules: string;
150
+ }
151
+
152
+ export interface Flattener<Props extends BaseObject> {
153
+ (
154
+ chunks: Interpolation<Props>[],
155
+ executionContext: object | null | undefined,
156
+ styleSheet: StyleSheet | null | undefined,
157
+ ): Interpolation<Props>[];
158
+ }
159
+
160
+ export interface Stringifier {
161
+ (
162
+ css: string,
163
+ selector?: string | undefined,
164
+ prefix?: string | undefined,
165
+ componentId?: string | undefined,
166
+ ): string[];
167
+ hash: string;
168
+ }
169
+
170
+ export interface ShouldForwardProp<R extends Runtime> {
171
+ (prop: string, elementToBeCreated: StyledTarget<R>): boolean;
172
+ }
173
+
174
+ export interface CommonStatics<R extends Runtime, Props extends BaseObject> {
175
+ attrs: Attrs<Props>[];
176
+ target: StyledTarget<R>;
177
+ shouldForwardProp?: ShouldForwardProp<R> | undefined;
178
+ }
179
+
180
+ export interface IStyledStatics<
181
+ R extends Runtime,
182
+ OuterProps extends BaseObject,
183
+ > extends CommonStatics<R, OuterProps> {
184
+ componentStyle: ComponentStyle;
185
+ foldedComponentIds: string;
186
+ target: StyledTarget<R>;
187
+ styledComponentId: string;
188
+ warnTooManyClasses?: ReturnType<typeof createWarnTooManyClasses> | undefined;
189
+ }
190
+
191
+ /**
192
+ * The pragmatic octane polymorphic call surface: declared own props are fully
193
+ * typed; `as`/`forwardedAs` retarget rendering; all remaining DOM/`as`-target
194
+ * props flow through a permissive prop bag (octane has no per-tag
195
+ * `JSX.IntrinsicElements` map to introspect).
196
+ */
197
+ export type PolymorphicCallProps<BaseProps extends BaseObject> = FastOmit<
198
+ BaseProps,
199
+ 'as' | 'forwardedAs'
200
+ > &
201
+ ExecutionProps & {
202
+ className?: string | undefined;
203
+ style?: CSSPropertiesWithVars | (string & {}) | undefined;
204
+ children?: any;
205
+ ref?: any;
206
+ } & { [key: string]: any };
207
+
208
+ export interface PolymorphicComponent<R extends Runtime, BaseProps extends BaseObject> {
209
+ (props: PolymorphicCallProps<WidenUntypedProps<BaseProps>>, scope?: any): unknown;
210
+ displayName?: string | undefined;
211
+ }
212
+
213
+ /**
214
+ * Targets whose props can't be introspected collapse to `{}`; fall back to a
215
+ * permissive prop bag so such components stay usable at the call site.
216
+ */
217
+ export type WidenUntypedProps<Props extends BaseObject> = (
218
+ Props extends unknown ? (keyof Props extends never ? true : false) : never
219
+ ) extends true
220
+ ? Props & { [key: string]: unknown }
221
+ : Props;
222
+
223
+ export interface IStyledComponentBase<R extends Runtime, Props extends BaseObject = BaseObject>
224
+ extends PolymorphicComponent<R, Props>, IStyledStatics<R, Props>, StyledComponentBrand {
225
+ defaultProps?: (ExecutionProps & Partial<Props>) | undefined;
226
+ toString: () => string;
227
+ }
228
+
229
+ /**
230
+ * Intersected with `string` so styled components can be used as computed
231
+ * property keys in object styles: `{ [MyComponent]: { ... } }`.
232
+ */
233
+ export type IStyledComponent<
234
+ R extends Runtime,
235
+ Props extends BaseObject = BaseObject,
236
+ > = IStyledComponentBase<R, Props> & string;
237
+
238
+ export interface IStyledComponentFactory<
239
+ R extends Runtime,
240
+ Target extends StyledTarget<R>,
241
+ OuterProps extends BaseObject,
242
+ OuterStatics extends BaseObject = BaseObject,
243
+ > {
244
+ <Props extends BaseObject = BaseObject, Statics extends BaseObject = BaseObject>(
245
+ target: Target,
246
+ options: StyledOptions<R, OuterProps & Props>,
247
+ rules: RuleSet<OuterProps & Props>,
248
+ ): IStyledComponent<R, Substitute<OuterProps, Props>> & OuterStatics & Statics;
249
+ }
250
+
251
+ export type CSSProperties = CSS.Properties<number | (string & {})>;
252
+
253
+ export type CSSPropertiesWithVars = CSSProperties & {
254
+ [key: `--${string}`]: string | number | undefined;
255
+ };
256
+
257
+ export type CSSPseudos = { [K in CSS.Pseudos]?: CSSObject };
258
+
259
+ export type CSSKeyframes = object & { [key: string]: CSSObject };
260
+
261
+ export type CSSObject<Props extends BaseObject = BaseObject> = StyledObject<Props>;
262
+
263
+ export interface StyledObject<Props extends BaseObject = BaseObject>
264
+ extends CSSProperties, CSSPseudos {
265
+ [key: string]:
266
+ | StyledObject<Props>
267
+ | string
268
+ | number
269
+ | StyleFunction<Props>
270
+ | RuleSet<any>
271
+ | undefined;
272
+ }
273
+
274
+ /**
275
+ * The babel `css` prop is not supported by the octane port; the type is kept
276
+ * so shared upstream code and annotations continue to compile.
277
+ */
278
+ export type CSSProp = Interpolation<any>;
279
+
280
+ export type NoInfer<T> = [T][T extends any ? 0 : never];
281
+
282
+ export type Substitute<A extends BaseObject, B extends BaseObject> = keyof B extends never
283
+ ? A
284
+ : FastOmit<A, keyof B> & B;
285
+
286
+ /**
287
+ * Makes keys in K optional while keeping all others required.
288
+ * Used to make attrs-provided props optional on the final component.
289
+ */
290
+ export type MakeAttrsOptional<P extends BaseObject, K extends keyof any> = keyof K extends never
291
+ ? P
292
+ : FastOmit<P, K & keyof P> & Partial<Pick<P, K & keyof P>>;
293
+
294
+ export type InsertionTarget = HTMLElement | ShadowRoot;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * CSS properties that accept unitless numeric values.
3
+ * Inlined from @emotion/unitless with IE-only entries removed
4
+ * (boxFlex, boxFlexGroup, boxOrdinalGroup, flexPositive, flexNegative,
5
+ * flexOrder, msGridRow, msGridRowSpan, msGridColumn, msGridColumnSpan).
6
+ */
7
+ const unitless: Record<string, 1> = {
8
+ animationIterationCount: 1,
9
+ aspectRatio: 1,
10
+ borderImageOutset: 1,
11
+ borderImageSlice: 1,
12
+ borderImageWidth: 1,
13
+ columnCount: 1,
14
+ columns: 1,
15
+ flex: 1,
16
+ flexGrow: 1,
17
+ flexShrink: 1,
18
+ gridRow: 1,
19
+ gridRowEnd: 1,
20
+ gridRowSpan: 1,
21
+ gridRowStart: 1,
22
+ gridColumn: 1,
23
+ gridColumnEnd: 1,
24
+ gridColumnSpan: 1,
25
+ gridColumnStart: 1,
26
+ fontWeight: 1,
27
+ lineHeight: 1,
28
+ opacity: 1,
29
+ order: 1,
30
+ orphans: 1,
31
+ scale: 1,
32
+ tabSize: 1,
33
+ widows: 1,
34
+ zIndex: 1,
35
+ zoom: 1,
36
+ WebkitLineClamp: 1,
37
+ fillOpacity: 1,
38
+ floodOpacity: 1,
39
+ stopOpacity: 1,
40
+ strokeDasharray: 1,
41
+ strokeDashoffset: 1,
42
+ strokeMiterlimit: 1,
43
+ strokeOpacity: 1,
44
+ strokeWidth: 1,
45
+ };
46
+
47
+ // Taken from https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/shared/dangerousStyleValue.js
48
+ export default function addUnitIfNeeded(name: string, value: any) {
49
+ // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133
50
+ if (value == null || typeof value === 'boolean' || value === '') {
51
+ return '';
52
+ }
53
+
54
+ if (typeof value === 'number' && value !== 0 && !(name in unitless) && !name.startsWith('--')) {
55
+ return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers except for CSS variables
56
+ }
57
+
58
+ return String(value).trim();
59
+ }
@@ -0,0 +1,18 @@
1
+ // Shared character-code constants for fast charCodeAt comparisons.
2
+ // Inlined at call sites by V8 after the first optimization pass.
3
+ export const DOUBLE_QUOTE = 34; // "
4
+ export const SINGLE_QUOTE = 39; // '
5
+ export const SLASH = 47; // /
6
+ export const ASTERISK = 42; // *
7
+ export const BACKSLASH = 92; // \
8
+ export const OPEN_BRACE = 123; // {
9
+ export const CLOSE_BRACE = 125; // }
10
+ export const SEMICOLON = 59; // ;
11
+ export const NEWLINE = 10; // \n
12
+ export const OPEN_PAREN = 40; // (
13
+ export const CLOSE_PAREN = 41; // )
14
+ export const HYPHEN = 45; // -
15
+ export const UPPER_A = 65; // A
16
+ export const UPPER_Z = 90; // Z
17
+ /** Offset from an ASCII uppercase letter to its lowercase counterpart. */
18
+ export const UPPER_TO_LOWER = 32;
@@ -0,0 +1,28 @@
1
+ // Octane adaptation: upstream detects styled() calls made during render by
2
+ // probing the React hook dispatcher (monkey-patching console.error around a
3
+ // throwaway useState call). Octane has no equivalent probe, so this uses a
4
+ // counting heuristic instead: constructing many components that share one
5
+ // displayName is the observable signature of in-render creation. The
6
+ // threshold matches warnTooManyClasses so both warnings describe the same
7
+ // runaway pattern.
8
+ const CREATION_LIMIT = 200;
9
+
10
+ const creationCounts: Map<string, number> = new Map();
11
+ const warned: Set<string> = new Set();
12
+
13
+ export const checkDynamicCreation = (displayName: string, componentId?: string | undefined) => {
14
+ if (process.env.NODE_ENV !== 'production') {
15
+ const count = (creationCounts.get(displayName) || 0) + 1;
16
+ creationCounts.set(displayName, count);
17
+
18
+ if (count >= CREATION_LIMIT && !warned.has(displayName)) {
19
+ warned.add(displayName);
20
+ const parsedIdString = componentId ? ` with the id of "${componentId}"` : '';
21
+ console.warn(
22
+ `The component ${displayName}${parsedIdString} has been created dynamically.\n` +
23
+ "You may see this warning because you've called styled inside another component.\n" +
24
+ 'To resolve this only create new StyledComponents outside of any render method and function component.',
25
+ );
26
+ }
27
+ }
28
+ };
@@ -0,0 +1,33 @@
1
+ import { Dict } from '../types';
2
+
3
+ export const LIMIT = 200;
4
+
5
+ export default (displayName: string, componentId: string) => {
6
+ let generatedClasses: Dict<any> = {};
7
+ let warningSeen = false;
8
+
9
+ return (className: string) => {
10
+ if (!warningSeen) {
11
+ generatedClasses[className] = true;
12
+ if (Object.keys(generatedClasses).length >= LIMIT) {
13
+ // Unable to find latestRule in test environment.
14
+
15
+ const parsedIdString = componentId ? ` with the id of "${componentId}"` : '';
16
+
17
+ console.warn(
18
+ `Over ${LIMIT} classes were generated for component ${displayName}${parsedIdString}.\n` +
19
+ 'Consider using the attrs method, together with a style object for frequently changed styles.\n' +
20
+ 'Example:\n' +
21
+ ' const Component = styled.div.attrs(props => ({\n' +
22
+ ' style: {\n' +
23
+ ' background: props.background,\n' +
24
+ ' },\n' +
25
+ ' }))`width: 100%;`\n\n' +
26
+ ' <Component />',
27
+ );
28
+ warningSeen = true;
29
+ generatedClasses = {};
30
+ }
31
+ }
32
+ };
33
+ };
@@ -0,0 +1,3 @@
1
+ import type { RuleSet } from '../types';
2
+
3
+ export const cssTagged = new WeakSet<RuleSet<any>>();
@@ -0,0 +1,10 @@
1
+ import { DefaultTheme, ExecutionProps } from '../types';
2
+ import { EMPTY_OBJECT } from './empties';
3
+
4
+ export default function determineTheme(
5
+ props: ExecutionProps,
6
+ providedTheme?: DefaultTheme | undefined,
7
+ defaultProps: { theme?: DefaultTheme | undefined } = EMPTY_OBJECT,
8
+ ): DefaultTheme | undefined {
9
+ return (props.theme !== defaultProps.theme && props.theme) || providedTheme || defaultProps.theme;
10
+ }
@@ -0,0 +1,7 @@
1
+ // prettier-ignore
2
+ const elements = [
3
+ 'a','abbr','address','area','article','aside','audio','b','bdi','bdo','blockquote','body','button','br','canvas','caption','cite','code','col','colgroup','data','datalist','dd','del','details','dfn','dialog','div','dl','dt','em','embed','fieldset','figcaption','figure','footer','form','h1','h2','h3','h4','h5','h6','header','hgroup','hr','html','i','iframe','img','input','ins','kbd','label','legend','li','main','map','mark','menu','meter','nav','object','ol','optgroup','option','output','p','picture','pre','progress','q','rp','rt','ruby','s','samp','search','section','select','slot','small','span','strong','sub','summary','sup','table','tbody','td','template','textarea','tfoot','th','thead','time','tr','u','ul','var','video','wbr','circle','clipPath','defs','ellipse','feBlend','feColorMatrix','feComponentTransfer','feComposite','feConvolveMatrix','feDiffuseLighting','feDisplacementMap','feDistantLight','feDropShadow','feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur','feImage','feMerge','feMergeNode','feMorphology','feOffset','fePointLight','feSpecularLighting','feSpotLight','feTile','feTurbulence','filter','foreignObject','g','image','line','linearGradient','marker','mask','path','pattern','polygon','polyline','radialGradient','rect','stop','svg','switch','symbol','text','textPath','tspan','use',
4
+ ] as const;
5
+
6
+ export default new Set(elements);
7
+ export type SupportedHTMLElements = (typeof elements)[number];
@@ -0,0 +1,4 @@
1
+ import { Dict } from '../types';
2
+
3
+ export const EMPTY_ARRAY = Object.freeze([]) as Readonly<any[]>;
4
+ export const EMPTY_OBJECT = Object.freeze({}) as Readonly<Dict<any>>;
@@ -0,0 +1,41 @@
1
+ import { Dict } from '../types';
2
+ import errorMap from './errors';
3
+
4
+ const ERRORS: Dict<any> = process.env.NODE_ENV !== 'production' ? errorMap : {};
5
+
6
+ /**
7
+ * super basic version of sprintf
8
+ */
9
+ function format(...args: [string, ...any]) {
10
+ let a = args[0];
11
+ const b = [];
12
+
13
+ for (let c = 1, len = args.length; c < len; c += 1) {
14
+ b.push(args[c]);
15
+ }
16
+
17
+ b.forEach((d) => {
18
+ a = a.replace(/%[a-z]/, d);
19
+ });
20
+
21
+ return a;
22
+ }
23
+
24
+ /**
25
+ * Create an error file out of errors.md for development and a simple web link to the full errors
26
+ * in production mode.
27
+ */
28
+ export default function throwStyledComponentsError(
29
+ code: string | number,
30
+ ...interpolations: any[]
31
+ ) {
32
+ if (process.env.NODE_ENV === 'production') {
33
+ return new Error(
34
+ `An error occurred. See https://github.com/styled-components/styled-components/blob/main/packages/styled-components/src/utils/errors.md#${code} for more information.${
35
+ interpolations.length > 0 ? ` Args: ${interpolations.join(', ')}` : ''
36
+ }`,
37
+ );
38
+ } else {
39
+ return new Error(format(ERRORS[code], ...interpolations).trim());
40
+ }
41
+ }
@@ -0,0 +1,20 @@
1
+ export default {
2
+ '1': 'Cannot create styled-component for component: %s.\n\n',
3
+ '2': "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
4
+ '3': 'Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n',
5
+ '4': 'The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n',
6
+ '5': 'The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n',
7
+ '6': "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
8
+ '7': 'ThemeProvider: Please return an object from your "theme" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n',
9
+ '8': 'ThemeProvider: Please make your "theme" prop an object.\n\n',
10
+ '9': 'Missing document `<head>`\n\n',
11
+ '10': 'Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n',
12
+ '11': '_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n',
13
+ '12': 'It seems you are interpolating a keyframe declaration (%s) into an untagged string. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://styled-components.com/docs/api#css\n\n',
14
+ '13': '%s is not a styled component and cannot be referred to via component selector. See https://styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n',
15
+ '14': 'ThemeProvider: "theme" prop is required.\n\n',
16
+ '15': "A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",
17
+ '16': "Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",
18
+ '17': "CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n\n",
19
+ '18': "Accessing `useTheme` hook outside of a `<ThemeProvider>` element.\n\n```jsx\nimport { useTheme } from 'styled-components';\nexport function StyledCompoent({ children }) {\n const theme = useTheme();\n return <div style={{ width: theme.sizes.full }}>{children}</div>;\n}\n\nimport { StyledComponent } from './StyledComponent';\nimport { theme } from './theme';\nexport function App() {\n return (\n <ThemeProvider theme={theme}>\n <StyledComponent />\n </ThemeProvider>\n );\n}\n```\n\nIf you need access to the theme in an uncertain composition scenario, `React.useContext(ThemeContext)` will not emit an error if there is no `ThemeProvider` ancestor.\n",
20
+ };
@@ -0,0 +1,11 @@
1
+ // Source: https://www.w3.org/TR/cssom-1/#serialize-an-identifier
2
+ // Control characters and non-letter first symbols are not supported
3
+ const escapeRegex = /[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~-]+/g;
4
+
5
+ const dashesAtEnds = /(^-|-$)/g;
6
+
7
+ export default function escape(str: string) {
8
+ return str // Replace all possible CSS selectors
9
+ .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end
10
+ .replace(dashesAtEnds, '');
11
+ }