@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,171 @@
1
+ import { SC_VERSION } from '../constants';
2
+ import StyleSheet from '../sheet';
3
+ import type { AnyComponent } from '../types';
4
+ import { ExecutionContext, RuleSet, Stringifier } from '../types';
5
+ import flatten from '../utils/flatten';
6
+ import generateName from '../utils/generateAlphabeticName';
7
+ import getComponentName from '../utils/getComponentName';
8
+ import { LIMIT as TOO_MANY_CLASSES_LIMIT } from '../utils/createWarnTooManyClasses';
9
+ import { hash, phash } from '../utils/hash';
10
+ import isKeyframes from '../utils/isKeyframes';
11
+ import isPlainObject from '../utils/isPlainObject';
12
+ import isStaticRules from '../utils/isStaticRules';
13
+ import isStatelessFunction from '../utils/isStatelessFunction';
14
+ import isStyledComponent from '../utils/isStyledComponent';
15
+ import { joinStringArray, joinStrings } from '../utils/joinStrings';
16
+
17
+ const SEED = hash(SC_VERSION);
18
+
19
+ /**
20
+ * Upper bound on dynamicNameCache entries per ComponentStyle instance.
21
+ * Without this cap, components with free-form string interpolations
22
+ * (e.g. `color: ${p => p.$color}` where $color is unbounded user input)
23
+ * leak memory for the lifetime of the component definition. Aligned to
24
+ * the warnTooManyClasses dev threshold so the warning and the eviction
25
+ * share a single source of truth: by the time you start dropping cache
26
+ * entries, the dev warning has already told you why.
27
+ */
28
+ const MAX_DYNAMIC_NAME_CACHE = TOO_MANY_CLASSES_LIMIT;
29
+
30
+ /**
31
+ * ComponentStyle is all the CSS-specific stuff, not the framework-specific stuff.
32
+ */
33
+ export default class ComponentStyle {
34
+ baseHash: number;
35
+ baseStyle: ComponentStyle | null | undefined;
36
+ componentId: string;
37
+ isStatic: boolean;
38
+ rules: RuleSet<any>;
39
+ /**
40
+ * Shared client fast path for proven-static styles. Weak sheet/stylis keys
41
+ * avoid retaining custom manager configurations after their trees unmount.
42
+ */
43
+ private staticClassNameCache: WeakMap<StyleSheet, WeakMap<Stringifier, string>> | undefined;
44
+ dynamicNameCache: Map<string, string> | undefined;
45
+ /**
46
+ * Octane addition: content-addressed cache of compiled stylis output. The
47
+ * stateless server output re-emits into every active request, so without
48
+ * this every server render would re-run stylis for the same css. Keyed
49
+ * identically to dynamicNameCache (stylis hash + raw css), so entries are
50
+ * immutable and safe to share across requests.
51
+ */
52
+ compiledRulesCache: Map<string, string[]> | undefined;
53
+
54
+ constructor(rules: RuleSet<any>, componentId: string, baseStyle?: ComponentStyle | undefined) {
55
+ this.rules = rules;
56
+ this.componentId = componentId;
57
+ this.baseHash = phash(SEED, componentId);
58
+ this.baseStyle = baseStyle;
59
+ this.isStatic = isStaticRules(rules) && (!baseStyle || baseStyle.isStatic);
60
+
61
+ // NOTE: This registers the componentId, which ensures a consistent order
62
+ // for this component's styles compared to others
63
+ StyleSheet.registerId(componentId);
64
+ }
65
+
66
+ generateAndInjectStyles(
67
+ executionContext: ExecutionContext,
68
+ styleSheet: StyleSheet,
69
+ stylis: Stringifier,
70
+ ): string {
71
+ if (this.isStatic && !styleSheet.server) {
72
+ const cached = this.staticClassNameCache?.get(styleSheet)?.get(stylis);
73
+ if (cached !== undefined) return cached;
74
+ }
75
+
76
+ let names = this.baseStyle
77
+ ? this.baseStyle.generateAndInjectStyles(executionContext, styleSheet, stylis)
78
+ : '';
79
+
80
+ {
81
+ let css = '';
82
+
83
+ for (let i = 0; i < this.rules.length; i++) {
84
+ const partRule = this.rules[i];
85
+
86
+ if (typeof partRule === 'string') {
87
+ css += partRule;
88
+ } else if (partRule) {
89
+ // Fast path: inline function call for the common case (interpolation
90
+ // returning a string). Avoids flatten's type dispatch and array alloc.
91
+ // OCTANE: styled components are plain functions — exclude them here
92
+ // (flatten resolves them to their class selector) so a component is
93
+ // never invoked as a style function.
94
+ if (isStatelessFunction(partRule) && !isStyledComponent(partRule)) {
95
+ const fnResult = partRule(executionContext);
96
+ if (typeof fnResult === 'string') {
97
+ css += fnResult;
98
+ } else if (fnResult !== undefined && fnResult !== null && fnResult !== false) {
99
+ if (
100
+ process.env.NODE_ENV !== 'production' &&
101
+ typeof fnResult === 'object' &&
102
+ !Array.isArray(fnResult) &&
103
+ !isKeyframes(fnResult) &&
104
+ !isPlainObject(fnResult)
105
+ ) {
106
+ console.error(
107
+ `${getComponentName(
108
+ partRule as AnyComponent,
109
+ )} 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.`,
110
+ );
111
+ }
112
+
113
+ css += joinStringArray(
114
+ flatten(fnResult, executionContext, styleSheet, stylis) as string[],
115
+ );
116
+ }
117
+ } else {
118
+ css += joinStringArray(
119
+ flatten(partRule, executionContext, styleSheet, stylis) as string[],
120
+ );
121
+ }
122
+ }
123
+ }
124
+
125
+ if (css) {
126
+ // Cache css->name to skip phash+generateName for repeat CSS strings.
127
+ // The CSS string fully determines the class name for a given component,
128
+ // so a Map lookup replaces O(cssLen) hashing on cache hit.
129
+ if (!this.dynamicNameCache) this.dynamicNameCache = new Map();
130
+ const cacheKey = stylis.hash ? stylis.hash + css : css;
131
+ let name = this.dynamicNameCache.get(cacheKey);
132
+ if (!name) {
133
+ name = generateName(phash(phash(this.baseHash, stylis.hash), css) >>> 0);
134
+ if (this.dynamicNameCache.size >= MAX_DYNAMIC_NAME_CACHE) {
135
+ const oldest = this.dynamicNameCache.keys().next().value;
136
+ if (oldest !== undefined) this.dynamicNameCache.delete(oldest);
137
+ }
138
+ this.dynamicNameCache.set(cacheKey, name);
139
+ }
140
+
141
+ if (!styleSheet.hasNameForId(this.componentId, name)) {
142
+ let cssFormatted = this.compiledRulesCache?.get(cacheKey);
143
+ if (!cssFormatted) {
144
+ cssFormatted = stylis(css, '.' + name, undefined, this.componentId);
145
+ if (!this.compiledRulesCache) this.compiledRulesCache = new Map();
146
+ if (this.compiledRulesCache.size >= MAX_DYNAMIC_NAME_CACHE) {
147
+ const oldest = this.compiledRulesCache.keys().next().value;
148
+ if (oldest !== undefined) this.compiledRulesCache.delete(oldest);
149
+ }
150
+ this.compiledRulesCache.set(cacheKey, cssFormatted);
151
+ }
152
+ styleSheet.insertRules(this.componentId, name, cssFormatted);
153
+ }
154
+
155
+ names = joinStrings(names, name);
156
+ }
157
+ }
158
+
159
+ if (this.isStatic && !styleSheet.server) {
160
+ let byStylis = this.staticClassNameCache?.get(styleSheet);
161
+ if (!byStylis) {
162
+ byStylis = new WeakMap();
163
+ if (!this.staticClassNameCache) this.staticClassNameCache = new WeakMap();
164
+ this.staticClassNameCache.set(styleSheet, byStylis);
165
+ }
166
+ byStylis.set(stylis, names);
167
+ }
168
+
169
+ return names;
170
+ }
171
+ }
@@ -0,0 +1,129 @@
1
+ import StyleSheet from '../sheet';
2
+ import { ExecutionContext, RuleSet, Stringifier } from '../types';
3
+ import flatten from '../utils/flatten';
4
+ import generateName from '../utils/generateAlphabeticName';
5
+ import { hash } from '../utils/hash';
6
+ import isStaticRules from '../utils/isStaticRules';
7
+ import { joinRules, joinStringArray } from '../utils/joinStrings';
8
+
9
+ type InstanceEntry = { name: string; rules: string[] };
10
+
11
+ export default class GlobalStyle<Props extends object> {
12
+ componentId: string;
13
+ isStatic: boolean;
14
+ rules: RuleSet<Props>;
15
+
16
+ /** @internal Per-instance rule cache for shared-group rebuild. */
17
+ instanceRules: Map<number, InstanceEntry> = new Map();
18
+
19
+ constructor(rules: RuleSet<Props>, componentId: string) {
20
+ this.rules = rules;
21
+ this.componentId = componentId;
22
+ this.isStatic = isStaticRules(rules);
23
+
24
+ // Pre-register the shared group so global styles defined before
25
+ // components always appear before them in the stylesheet.
26
+ StyleSheet.registerId(this.componentId);
27
+ }
28
+
29
+ removeStyles(instance: number, styleSheet: StyleSheet): void {
30
+ this.instanceRules.delete(instance);
31
+ this.rebuildGroup(styleSheet);
32
+ }
33
+
34
+ /**
35
+ * Server rendering is content-addressed and has no component-instance
36
+ * lifecycle. The output backend decides whether to retain a compatibility
37
+ * copy; the default Octane backend writes only to the active request.
38
+ */
39
+ renderServerStyles(
40
+ executionContext: ExecutionContext & Props,
41
+ styleSheet: StyleSheet,
42
+ stylis: Stringifier,
43
+ ): void {
44
+ const rules = this.compileRules(executionContext, styleSheet, stylis);
45
+ const name = this.componentId + '-' + generateName(hash(joinRules(rules)) >>> 0);
46
+
47
+ if (!styleSheet.hasNameForId(this.componentId, name)) {
48
+ styleSheet.insertRules(this.componentId, name, rules);
49
+ }
50
+ }
51
+
52
+ renderStyles(
53
+ instance: number,
54
+ executionContext: ExecutionContext & Props,
55
+ styleSheet: StyleSheet,
56
+ stylis: Stringifier,
57
+ ): void {
58
+ const id = this.componentId;
59
+
60
+ if (this.isStatic) {
61
+ // The component/instance name is the client dedup key, so compute it
62
+ // before checking the persistent output.
63
+ const entry =
64
+ this.instanceRules.get(instance) ??
65
+ this.computeRules(instance, executionContext, styleSheet, stylis);
66
+ if (!styleSheet.hasNameForId(id, entry.name)) {
67
+ styleSheet.insertRules(id, entry.name, entry.rules);
68
+ }
69
+ return;
70
+ }
71
+
72
+ // Compute new rules; skip the client CSSOM rebuild if CSS is unchanged.
73
+ const prev = this.instanceRules.get(instance);
74
+ this.computeRules(instance, executionContext, styleSheet, stylis);
75
+ if (prev) {
76
+ const a = prev.rules;
77
+ const b = this.instanceRules.get(instance)!.rules;
78
+ if (a.length === b.length) {
79
+ let same = true;
80
+ for (let i = 0; i < a.length; i++) {
81
+ if (a[i] !== b[i]) {
82
+ same = false;
83
+ break;
84
+ }
85
+ }
86
+ if (same) return;
87
+ }
88
+ }
89
+ this.rebuildGroup(styleSheet);
90
+ }
91
+
92
+ private computeRules(
93
+ instance: number,
94
+ executionContext: ExecutionContext & Props,
95
+ styleSheet: StyleSheet,
96
+ stylis: Stringifier,
97
+ ): InstanceEntry {
98
+ const rules = this.compileRules(executionContext, styleSheet, stylis);
99
+ const entry: InstanceEntry = {
100
+ name: this.componentId + instance,
101
+ rules,
102
+ };
103
+ this.instanceRules.set(instance, entry);
104
+ return entry;
105
+ }
106
+
107
+ private compileRules(
108
+ executionContext: ExecutionContext & Props,
109
+ styleSheet: StyleSheet,
110
+ stylis: Stringifier,
111
+ ): string[] {
112
+ const flatCSS = joinStringArray(
113
+ flatten(this.rules as RuleSet<object>, executionContext, styleSheet, stylis) as string[],
114
+ );
115
+ return stylis(flatCSS, '');
116
+ }
117
+
118
+ /**
119
+ * Clear all CSS rules in the shared group and re-insert from surviving instances.
120
+ * Must run synchronously - no yielding between clear and re-insert.
121
+ */
122
+ private rebuildGroup(styleSheet: StyleSheet): void {
123
+ const id = this.componentId;
124
+ styleSheet.clearRules(id);
125
+ for (const entry of this.instanceRules.values()) {
126
+ styleSheet.insertRules(id, entry.name, entry.rules);
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,66 @@
1
+ import { KEYFRAMES_ID_PREFIX } from '../constants';
2
+ import StyleSheet from '../sheet';
3
+ import { getGroupForId } from '../sheet/GroupIDAllocator';
4
+ import { Keyframes as KeyframesType, Stringifier } from '../types';
5
+ import styledError from '../utils/error';
6
+ import generateAlphabeticName from '../utils/generateAlphabeticName';
7
+ import { KEYFRAMES_SYMBOL } from '../utils/isKeyframes';
8
+ import { setToString } from '../utils/setToString';
9
+ import { mainStylis } from './StyleSheetManager';
10
+
11
+ /**
12
+ * Content-addressed cache of compiled keyframe CSS per stylis hash. Octane's
13
+ * stateless server output re-emits into every active request, so this skips
14
+ * re-running stylis for the same keyframes on every server render. Entries are
15
+ * immutable, so sharing across requests is safe.
16
+ */
17
+ const kfCompiledCache: WeakMap<Keyframes, Map<string, string[]>> = new WeakMap();
18
+
19
+ export default class Keyframes implements KeyframesType {
20
+ readonly [KEYFRAMES_SYMBOL] = true as const;
21
+
22
+ id: string;
23
+ name: string;
24
+ rules: string;
25
+
26
+ constructor(name: string, rules: string) {
27
+ this.name = name;
28
+ this.id = KEYFRAMES_ID_PREFIX + name;
29
+ this.rules = rules;
30
+
31
+ // Eagerly register the group so keyframes defined before components
32
+ // get a lower group ID and appear before them in the stylesheet.
33
+ // Uses getGroupForId directly (not StyleSheet.registerId) because
34
+ // GroupIDAllocator is pure JS - safe for native builds.
35
+ getGroupForId(this.id);
36
+
37
+ setToString(this, () => {
38
+ throw styledError(12, String(this.name));
39
+ });
40
+ }
41
+
42
+ inject = (styleSheet: StyleSheet, stylisInstance: Stringifier = mainStylis): void => {
43
+ const resolvedName = this.getName(stylisInstance);
44
+
45
+ if (!styleSheet.hasNameForId(this.id, resolvedName)) {
46
+ const cacheKey = stylisInstance.hash || '';
47
+ let compiled = kfCompiledCache.get(this)?.get(cacheKey);
48
+ if (!compiled) {
49
+ compiled = stylisInstance(this.rules, resolvedName, '@keyframes');
50
+ let map = kfCompiledCache.get(this);
51
+ if (!map) {
52
+ map = new Map();
53
+ kfCompiledCache.set(this, map);
54
+ }
55
+ map.set(cacheKey, compiled);
56
+ }
57
+ styleSheet.insertRules(this.id, resolvedName, compiled);
58
+ }
59
+ };
60
+
61
+ getName(stylisInstance: Stringifier = mainStylis): string {
62
+ return stylisInstance.hash
63
+ ? this.name + generateAlphabeticName(+stylisInstance.hash >>> 0)
64
+ : this.name;
65
+ }
66
+ }
@@ -0,0 +1,92 @@
1
+ // Ported from styled-components 6.4.3 (MIT), adapted for octane.
2
+ //
3
+ // On octane, SSR style collection is AUTOMATIC: every server-side style insert
4
+ // forwards to octane's per-request css channel, so `renderToString` returns
5
+ // `{ html, css }` and streaming interleaves styles without any setup. This
6
+ // class is a compatibility shim for upstream-style code: its capture sheet
7
+ // additionally accumulates rules in-memory so `getStyleTags()` /
8
+ // `getStyleElement()` keep working. `interleaveWithNodeStream` is not
9
+ // supported — octane's `renderToPipeableStream` already streams styles.
10
+ import { createElement } from 'octane';
11
+
12
+ import { SC_ATTR, SC_ATTR_VERSION, SC_VERSION } from '../constants';
13
+ import StyleSheet from '../sheet';
14
+ import styledError from '../utils/error';
15
+ import { joinStringArray } from '../utils/joinStrings';
16
+ import getNonce from '../utils/nonce';
17
+ import { StyleSheetManager } from './StyleSheetManager';
18
+
19
+ export default class ServerStyleSheet {
20
+ instance: StyleSheet;
21
+ sealed: boolean;
22
+
23
+ constructor({ nonce }: { nonce?: string } = {}) {
24
+ this.instance = new StyleSheet({ isServer: true, capture: true, nonce });
25
+ this.sealed = false;
26
+ }
27
+
28
+ _emitSheetCSS = (): string => {
29
+ const css = this.instance.toString();
30
+ if (!css) return '';
31
+ const nonce = this.instance.options.nonce || getNonce();
32
+ const attrs = [
33
+ nonce && `nonce="${nonce}"`,
34
+ `${SC_ATTR}="true"`,
35
+ `${SC_ATTR_VERSION}="${SC_VERSION}"`,
36
+ ];
37
+ const htmlAttr = joinStringArray(attrs.filter(Boolean) as string[], ' ');
38
+
39
+ return `<style ${htmlAttr}>${css}</style>`;
40
+ };
41
+
42
+ collectStyles(children: any): unknown {
43
+ if (this.sealed) {
44
+ throw styledError(2);
45
+ }
46
+
47
+ return createElement(StyleSheetManager as any, { sheet: this.instance, children });
48
+ }
49
+
50
+ getStyleTags = (): string => {
51
+ if (this.sealed) {
52
+ throw styledError(2);
53
+ }
54
+
55
+ return this._emitSheetCSS();
56
+ };
57
+
58
+ getStyleElement = () => {
59
+ if (this.sealed) {
60
+ throw styledError(2);
61
+ }
62
+
63
+ const css = this.instance.toString();
64
+ if (!css) return [];
65
+
66
+ const props: Record<string, any> = {
67
+ [SC_ATTR]: '',
68
+ [SC_ATTR_VERSION]: SC_VERSION,
69
+ dangerouslySetInnerHTML: {
70
+ __html: css,
71
+ },
72
+ };
73
+
74
+ const nonce = this.instance.options.nonce || getNonce();
75
+ if (nonce) {
76
+ props.nonce = nonce;
77
+ }
78
+
79
+ // v4 returned an array for this fn, so we'll do the same for v5 for backward compat
80
+ return [createElement('style', { ...props, key: 'sc-0-0' })];
81
+ };
82
+
83
+ interleaveWithNodeStream(_input: unknown): never {
84
+ // OCTANE DIVERGENCE: octane's renderToPipeableStream already emits each
85
+ // pass's style chunks ahead of its html, so there is nothing to interleave.
86
+ throw styledError(3);
87
+ }
88
+
89
+ seal = (): void => {
90
+ this.sealed = true;
91
+ };
92
+ }
@@ -0,0 +1,210 @@
1
+ // Ported from styled-components 6.4.3 (MIT), adapted for octane. The RSC
2
+ // branches are dropped (octane has no RSC); context is provided via a
3
+ // `createElement(Provider, …)` descriptor so the same code runs on the client
4
+ // and server runtimes. The module-level server sheet uses a stateless output
5
+ // backend: Octane's active render owns every emitted chunk, so nothing
6
+ // request-specific is retained here.
7
+ import { createContext, createElement, isChildrenBlock, useContext, useMemo } from 'octane';
8
+ import type stylis from 'stylis';
9
+
10
+ import StyleSheet from '../sheet';
11
+ import { InsertionTarget, ShouldForwardProp, Stringifier } from '../types';
12
+ import createStylisInstance from '../utils/stylis';
13
+
14
+ export const mainSheet: StyleSheet = new StyleSheet();
15
+ export const mainStylis: Stringifier = createStylisInstance();
16
+
17
+ const SLOT_SSM_SHEET = Symbol.for('@octanejs/styled-components:ssm-sheet');
18
+ const SLOT_SSM_STYLIS = Symbol.for('@octanejs/styled-components:ssm-stylis');
19
+ const SLOT_SSM_VALUE = Symbol.for('@octanejs/styled-components:ssm-value');
20
+
21
+ export type IStyleSheetContext = {
22
+ shouldForwardProp?: ShouldForwardProp<'web'> | undefined;
23
+ styleSheet: StyleSheet;
24
+ stylis: Stringifier;
25
+ /** Preserved for inheritance - inner SSMs that set namespace/vendorPrefixes
26
+ * but not stylisPlugins can still inherit the parent's plugins. */
27
+ stylisPlugins?: stylis.Middleware[] | undefined;
28
+ };
29
+
30
+ const defaultContextValue: IStyleSheetContext = {
31
+ shouldForwardProp: undefined,
32
+ styleSheet: mainSheet,
33
+ stylis: mainStylis,
34
+ stylisPlugins: undefined,
35
+ };
36
+
37
+ export const StyleSheetContext = createContext<IStyleSheetContext>(defaultContextValue);
38
+
39
+ /**
40
+ * Upstream's `StyleSheetContext.Consumer` as a component: expects a single
41
+ * function child which is called with the current sheet context.
42
+ */
43
+ export function StyleSheetConsumer(props: { children?: any }): unknown {
44
+ const value = useContext(StyleSheetContext);
45
+ const render = props.children;
46
+
47
+ // Compiled element children arrive as children-block functions — only a
48
+ // genuine render-prop function child receives the sheet context (same
49
+ // guard as ThemeConsumer).
50
+ if (typeof render === 'function' && !isChildrenBlock(render)) {
51
+ return (render as (value: IStyleSheetContext) => unknown)(value);
52
+ }
53
+
54
+ if (process.env.NODE_ENV !== 'production' && render != null) {
55
+ console.warn(
56
+ 'StyleSheetConsumer expects a single function child which receives the sheet context.',
57
+ );
58
+ }
59
+
60
+ return null;
61
+ }
62
+
63
+ export type IStylisContext = Stringifier | void;
64
+
65
+ export function useStyleSheetContext() {
66
+ return useContext(StyleSheetContext);
67
+ }
68
+
69
+ export type IStyleSheetManager = {
70
+ children?: any;
71
+ /**
72
+ * If desired, you can pass this prop to disable "speedy" insertion mode, which
73
+ * uses the browser [CSSOM APIs](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet).
74
+ * When disabled, rules are inserted as simple text into style blocks.
75
+ */
76
+ disableCSSOMInjection?: undefined | boolean;
77
+ /**
78
+ * If you are working exclusively with modern browsers, vendor prefixes can often be omitted
79
+ * to reduce the weight of CSS on the page.
80
+ */
81
+ enableVendorPrefixes?: undefined | boolean;
82
+ /**
83
+ * Provide an optional selector to be prepended to all generated style rules.
84
+ */
85
+ namespace?: undefined | string;
86
+ /**
87
+ * Create and provide your own `StyleSheet` if necessary for advanced SSR scenarios.
88
+ * When provided, `target` and `nonce` props are ignored (configure them on the sheet directly).
89
+ */
90
+ sheet?: undefined | StyleSheet;
91
+ /**
92
+ * Starting in v6, styled-components no longer does its own prop validation
93
+ * and recommends use of transient props "$prop" to pass style-only props to
94
+ * components. If for some reason you are not able to use transient props, a
95
+ * prop validation function can be provided via `StyleSheetManager`, such as
96
+ * `@emotion/is-prop-valid`.
97
+ *
98
+ * When the return value is `true`, props will be forwarded to the DOM/underlying
99
+ * component. If return value is `false`, the prop will be discarded after styles
100
+ * are calculated.
101
+ *
102
+ * Manually composing `styled.{element}.withConfig({shouldForwardProp})` will
103
+ * override this default.
104
+ *
105
+ * When nested inside another `StyleSheetManager`, omitting this prop inherits
106
+ * the parent's function. Pass `undefined` explicitly or a passthrough function
107
+ * to disable inherited behavior for a subtree.
108
+ */
109
+ shouldForwardProp?: undefined | IStyleSheetContext['shouldForwardProp'];
110
+ /**
111
+ * An array of plugins to be run by stylis (style processor) during compilation.
112
+ * Check out [what's available on npm*](https://www.npmjs.com/search?q=keywords%3Astylis).
113
+ *
114
+ * \* The plugin(s) must be compatible with stylis v4 or above.
115
+ *
116
+ * When nested inside another `StyleSheetManager`, omitting this prop inherits
117
+ * the parent's plugins. Pass an empty array (`[]`) to explicitly disable
118
+ * inherited plugins for a subtree.
119
+ */
120
+ stylisPlugins?: undefined | stylis.Middleware[];
121
+ /**
122
+ * CSP nonce to attach to injected `<style>` tags. Overrides auto-detection
123
+ * from `<meta name="sc-nonce">`, `<meta property="csp-nonce">`, or `__webpack_nonce__`.
124
+ */
125
+ nonce?: undefined | string;
126
+ /**
127
+ * Provide an alternate DOM node to host generated styles; useful for iframes.
128
+ */
129
+ target?: undefined | InsertionTarget;
130
+ };
131
+
132
+ /** Configure style injection for descendant styled components (target element, stylis plugins, prop forwarding). */
133
+ export function StyleSheetManager(props: IStyleSheetManager): unknown {
134
+ const parentContext = useStyleSheetContext();
135
+ const { styleSheet } = parentContext;
136
+
137
+ const resolvedStyleSheet = useMemo(
138
+ () => {
139
+ let sheet = styleSheet;
140
+
141
+ if (props.sheet) {
142
+ sheet = props.sheet;
143
+ } else if (props.target) {
144
+ sheet = sheet.reconstructWithOptions(
145
+ props.nonce !== undefined
146
+ ? { target: props.target, nonce: props.nonce }
147
+ : { target: props.target },
148
+ false,
149
+ );
150
+ } else if (props.nonce !== undefined) {
151
+ sheet = sheet.reconstructWithOptions({ nonce: props.nonce });
152
+ }
153
+
154
+ if (props.disableCSSOMInjection) {
155
+ sheet = sheet.reconstructWithOptions({ useCSSOMInjection: false });
156
+ }
157
+
158
+ return sheet;
159
+ },
160
+ [props.disableCSSOMInjection, props.nonce, props.sheet, props.target, styleSheet],
161
+ SLOT_SSM_SHEET,
162
+ );
163
+
164
+ // Inherit parent stylis when no stylis-related props are provided.
165
+ // When any stylis option (namespace, vendorPrefixes) changes, create a new
166
+ // instance but still inherit plugins from the parent if stylisPlugins is omitted.
167
+ // An explicit empty array disables inherited plugins.
168
+ const stylisInstance = useMemo(
169
+ () =>
170
+ props.stylisPlugins === undefined &&
171
+ props.namespace === undefined &&
172
+ props.enableVendorPrefixes === undefined
173
+ ? parentContext.stylis
174
+ : createStylisInstance({
175
+ options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
176
+ plugins: props.stylisPlugins ?? parentContext.stylisPlugins,
177
+ }),
178
+ [
179
+ props.enableVendorPrefixes,
180
+ props.namespace,
181
+ props.stylisPlugins,
182
+ parentContext.stylis,
183
+ parentContext.stylisPlugins,
184
+ ],
185
+ SLOT_SSM_STYLIS,
186
+ );
187
+
188
+ // Inherit parent shouldForwardProp when not provided.
189
+ const shouldForwardProp =
190
+ 'shouldForwardProp' in props ? props.shouldForwardProp : parentContext.shouldForwardProp;
191
+
192
+ // Resolve which plugins to propagate: own > parent > none
193
+ const resolvedPlugins = props.stylisPlugins ?? parentContext.stylisPlugins;
194
+
195
+ const styleSheetContextValue = useMemo(
196
+ () => ({
197
+ shouldForwardProp,
198
+ styleSheet: resolvedStyleSheet,
199
+ stylis: stylisInstance,
200
+ stylisPlugins: resolvedPlugins,
201
+ }),
202
+ [shouldForwardProp, resolvedStyleSheet, stylisInstance, resolvedPlugins],
203
+ SLOT_SSM_VALUE,
204
+ );
205
+
206
+ return createElement(StyleSheetContext.Provider as any, {
207
+ value: styleSheetContextValue,
208
+ children: props.children,
209
+ });
210
+ }