@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,188 @@
1
+ import {
2
+ OCTANE_CHUNK_PREFIX,
3
+ SC_ATTR,
4
+ SC_ATTR_ACTIVE,
5
+ SC_ATTR_VERSION,
6
+ SC_VERSION,
7
+ SPLITTER,
8
+ } from '../constants';
9
+ import { InsertionTarget } from '../types';
10
+ import { getGroupForId, getIdForGroup, setGroupForId } from './GroupIDAllocator';
11
+ import { Sheet } from './types';
12
+
13
+ const SELECTOR = `style[${SC_ATTR}][${SC_ATTR_VERSION}="${SC_VERSION}"]`;
14
+ const OCTANE_SELECTOR = `style[data-octane^="${OCTANE_CHUNK_PREFIX}"]`;
15
+ const MARKER_RE = new RegExp(`^${SC_ATTR}\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)`);
16
+
17
+ /**
18
+ * Type guard to check if a node is a ShadowRoot.
19
+ * Uses instanceof when available, with duck-typing fallback for cross-realm scenarios.
20
+ */
21
+ const isShadowRoot = (node: InsertionTarget | Node): node is ShadowRoot => {
22
+ return (
23
+ (typeof ShadowRoot !== 'undefined' && node instanceof ShadowRoot) ||
24
+ ('host' in node &&
25
+ // https://dom.spec.whatwg.org/#dom-node-document_fragment_node
26
+ node.nodeType === 11)
27
+ );
28
+ };
29
+
30
+ /**
31
+ * Extract the container (Document or ShadowRoot) from an InsertionTarget.
32
+ * If the target is a ShadowRoot, return it directly.
33
+ * If the target is an HTMLElement, return its root node if it's a ShadowRoot, otherwise return document.
34
+ */
35
+ export const getRehydrationContainer = (
36
+ target?: InsertionTarget | undefined,
37
+ ): Document | ShadowRoot => {
38
+ if (!target) {
39
+ return document;
40
+ }
41
+
42
+ // Check if target is a ShadowRoot
43
+ if (isShadowRoot(target)) {
44
+ return target;
45
+ }
46
+
47
+ // Check if target is an HTMLElement inside a ShadowRoot
48
+ if ('getRootNode' in target) {
49
+ const root = (target as HTMLElement).getRootNode();
50
+ if (isShadowRoot(root)) {
51
+ return root;
52
+ }
53
+ }
54
+
55
+ return document;
56
+ };
57
+
58
+ export const outputSheet = (sheet: Sheet) => {
59
+ const tag = sheet.getTag();
60
+ const { length } = tag;
61
+
62
+ let css = '';
63
+ for (let group = 0; group < length; group++) {
64
+ const id = getIdForGroup(group);
65
+ if (id === undefined) continue;
66
+
67
+ const names = sheet.names.get(id);
68
+ if (names === undefined || !names.size) continue;
69
+
70
+ const rules = tag.getGroup(group);
71
+ if (rules.length === 0) continue;
72
+
73
+ const selector = SC_ATTR + '.g' + group + '[id="' + id + '"]';
74
+
75
+ let content = '';
76
+ for (const name of names) {
77
+ if (name.length > 0) {
78
+ content += name + ',';
79
+ }
80
+ }
81
+
82
+ // NOTE: It's easier to collect rules and have the marker
83
+ // after the actual rules to simplify the rehydration
84
+ css += rules + selector + '{content:"' + content + '"}' + SPLITTER;
85
+ }
86
+
87
+ return css;
88
+ };
89
+
90
+ const rehydrateNamesFromContent = (sheet: Sheet, id: string, content: string) => {
91
+ const names = content.split(',');
92
+ let name;
93
+
94
+ for (let i = 0, l = names.length; i < l; i++) {
95
+ if ((name = names[i])) {
96
+ sheet.registerName(id, name);
97
+ }
98
+ }
99
+ };
100
+
101
+ const rehydrateSheetFromTag = (sheet: Sheet, style: HTMLStyleElement) => {
102
+ const parts = (style.textContent ?? '').split(SPLITTER);
103
+ const rules: string[] = [];
104
+
105
+ for (let i = 0, l = parts.length; i < l; i++) {
106
+ const part = parts[i].trim();
107
+ if (!part) continue;
108
+
109
+ const marker = part.match(MARKER_RE);
110
+
111
+ if (marker) {
112
+ const group = parseInt(marker[1], 10) | 0;
113
+ const id = marker[2];
114
+
115
+ if (group !== 0) {
116
+ // Rehydrate componentId to group index mapping
117
+ setGroupForId(id, group);
118
+ // Rehydrate names and rules
119
+ // looks like: data-styled.g11[id="idA"]{content:"nameA,"}
120
+ rehydrateNamesFromContent(sheet, id, marker[3]);
121
+ sheet.getTag().insertRules(group, rules);
122
+ }
123
+
124
+ rules.length = 0;
125
+ } else {
126
+ rules.push(part);
127
+ }
128
+ }
129
+ };
130
+
131
+ /**
132
+ * Octane addition: adopt the chunk tags octane's SSR css channel emitted
133
+ * (`<style data-octane="sc.<componentId>.<name>">`) into the grouped client
134
+ * engine, then remove them — mirroring the upstream data-styled rehydration
135
+ * semantics. Group numbers are allocated fresh on the client; chunk ids only
136
+ * carry the (componentId, name) pair, which is all dedup needs.
137
+ *
138
+ * createGlobalStyle chunks (`sc.sc-global-…`) are left in the DOM: their
139
+ * rules must enter the engine through the owning component instance (which
140
+ * supports theme rewrites and unmount removal), so that component swaps them
141
+ * out pre-paint in its first layout effect instead.
142
+ */
143
+ const rehydrateOctaneChunk = (sheet: Sheet, style: HTMLStyleElement) => {
144
+ const chunkId = style.getAttribute('data-octane');
145
+ if (!chunkId) return;
146
+
147
+ // Parse from the RIGHT: the name segment is a generated token that never
148
+ // contains `.`, while the componentId is emitted verbatim and may (via a
149
+ // user `withConfig`) contain dots — the raw id must round-trip so
150
+ // `hasNameForId` sees the same id the runtime inserts under.
151
+ const raw = chunkId.slice(OCTANE_CHUNK_PREFIX.length);
152
+ const lastDot = raw.lastIndexOf('.');
153
+ if (lastDot <= 0 || lastDot === raw.length - 1) return;
154
+ const id = raw.slice(0, lastDot);
155
+ const name = raw.slice(lastDot + 1);
156
+ if (id.startsWith('sc-global-')) return;
157
+
158
+ const rules = (style.textContent ?? '').split(SPLITTER).filter(Boolean);
159
+ if (rules.length) {
160
+ sheet.registerName(id, name);
161
+ sheet.getTag().insertRules(getGroupForId(id), rules);
162
+ }
163
+
164
+ if (style.parentNode) {
165
+ style.parentNode.removeChild(style);
166
+ }
167
+ };
168
+
169
+ export const rehydrateSheet = (sheet: Sheet) => {
170
+ const container = getRehydrationContainer(sheet.options.target);
171
+ const nodes = container.querySelectorAll(SELECTOR);
172
+
173
+ for (let i = 0, l = nodes.length; i < l; i++) {
174
+ const node = nodes[i] as any as HTMLStyleElement;
175
+ if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) {
176
+ rehydrateSheetFromTag(sheet, node);
177
+
178
+ if (node.parentNode) {
179
+ node.parentNode.removeChild(node);
180
+ }
181
+ }
182
+ }
183
+
184
+ const octaneNodes = container.querySelectorAll(OCTANE_SELECTOR);
185
+ for (let i = 0, l = octaneNodes.length; i < l; i++) {
186
+ rehydrateOctaneChunk(sheet, octaneNodes[i] as any as HTMLStyleElement);
187
+ }
188
+ };
@@ -0,0 +1,66 @@
1
+ import { GroupedTag, RuleOutput, SheetOptions } from './types';
2
+ import { makeGroupedTag } from './GroupedTag';
3
+ import { makeTag, VirtualTag } from './Tag';
4
+ import { emitChunk } from './octaneChannel';
5
+
6
+ /** A persistent grouped rule destination (browser DOM or virtual server tag). */
7
+ class GroupedRuleOutput implements RuleOutput {
8
+ readonly persistent = true;
9
+ private tag: GroupedTag | undefined;
10
+
11
+ constructor(private readonly options: SheetOptions) {}
12
+
13
+ getTag() {
14
+ return this.tag || (this.tag = makeGroupedTag(makeTag(this.options)));
15
+ }
16
+
17
+ insertRules(_id: string, _name: string, group: number, rules: string[]): void {
18
+ this.getTag().insertRules(group, rules);
19
+ }
20
+
21
+ clearGroup(group: number): void {
22
+ this.getTag().clearGroup(group);
23
+ }
24
+
25
+ reset(): void {
26
+ this.tag = undefined;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The default server destination is deliberately stateless. Octane's active
32
+ * render owns collection and deduplication, so module state cannot cross a
33
+ * request boundary.
34
+ */
35
+ class OctaneChannelRuleOutput implements RuleOutput {
36
+ readonly persistent = false;
37
+ private inspectionTag: GroupedTag | undefined;
38
+
39
+ getTag() {
40
+ return this.inspectionTag || (this.inspectionTag = makeGroupedTag(new VirtualTag()));
41
+ }
42
+
43
+ insertRules(id: string, name: string, _group: number, rules: string[]): void {
44
+ emitChunk(id, name, rules);
45
+ }
46
+
47
+ clearGroup(_group: number): void {}
48
+
49
+ reset(): void {
50
+ this.inspectionTag = undefined;
51
+ }
52
+ }
53
+
54
+ /** Server compatibility output: emit automatically and retain for serialization. */
55
+ class CapturingServerRuleOutput extends GroupedRuleOutput {
56
+ insertRules(id: string, name: string, group: number, rules: string[]): void {
57
+ emitChunk(id, name, rules);
58
+ super.insertRules(id, name, group, rules);
59
+ }
60
+ }
61
+
62
+ export function createRuleOutput(options: SheetOptions): RuleOutput {
63
+ if (!options.isServer) return new GroupedRuleOutput(options);
64
+ if (options.capture) return new CapturingServerRuleOutput(options);
65
+ return new OctaneChannelRuleOutput();
66
+ }
@@ -0,0 +1,162 @@
1
+ import { DISABLE_SPEEDY, IS_BROWSER, KEYFRAMES_ID_PREFIX } from '../constants';
2
+ import { InsertionTarget } from '../types';
3
+ import { EMPTY_OBJECT } from '../utils/empties';
4
+ import { setToString } from '../utils/setToString';
5
+ import { getGroupForId } from './GroupIDAllocator';
6
+ import { getRehydrationContainer, outputSheet, rehydrateSheet } from './Rehydration';
7
+ import { createRuleOutput } from './RuleOutput';
8
+ import { RuleOutput, Sheet, SheetOptions } from './types';
9
+
10
+ let SHOULD_REHYDRATE = IS_BROWSER;
11
+
12
+ type SheetConstructorArgs = {
13
+ isServer?: boolean;
14
+ nonce?: string | undefined;
15
+ useCSSOMInjection?: boolean;
16
+ target?: InsertionTarget | undefined;
17
+ capture?: boolean;
18
+ };
19
+
20
+ type GlobalStylesAllocationMap = {
21
+ [key: string]: number;
22
+ };
23
+ type NamesAllocationMap = Map<string, Set<string>>;
24
+
25
+ const defaultOptions: SheetOptions = {
26
+ isServer: !IS_BROWSER,
27
+ useCSSOMInjection: !DISABLE_SPEEDY,
28
+ };
29
+
30
+ /** Contains the main stylesheet logic for stringification and caching */
31
+ export default class StyleSheet implements Sheet {
32
+ gs: GlobalStylesAllocationMap;
33
+ /** Keyframe component IDs for efficient RSC rendering (avoids scanning all names) */
34
+ keyframeIds: Set<string>;
35
+ names: NamesAllocationMap;
36
+ options: SheetOptions;
37
+ server: boolean;
38
+ private readonly output: RuleOutput;
39
+
40
+ /** Register a group ID to give it an index */
41
+ static registerId(id: string): number {
42
+ return getGroupForId(id);
43
+ }
44
+
45
+ constructor(
46
+ options: SheetConstructorArgs = EMPTY_OBJECT as Object,
47
+ globalStyles: GlobalStylesAllocationMap = {},
48
+ names?: NamesAllocationMap | undefined,
49
+ ) {
50
+ this.options = {
51
+ ...defaultOptions,
52
+ ...options,
53
+ };
54
+
55
+ this.gs = globalStyles;
56
+ this.keyframeIds = new Set();
57
+ this.names = new Map(names as NamesAllocationMap);
58
+ // Read from the MERGED options: the zero-arg main sheet must pick up the
59
+ // `isServer: !IS_BROWSER` default (upstream reads the raw argument here and
60
+ // instead relies on a `__SERVER__` build define this port doesn't have).
61
+ this.server = !!this.options.isServer;
62
+ this.output = createRuleOutput(this.options);
63
+
64
+ // We rehydrate only once and use the sheet that is created first
65
+ if (!this.server && IS_BROWSER && SHOULD_REHYDRATE) {
66
+ SHOULD_REHYDRATE = false;
67
+ rehydrateSheet(this);
68
+ }
69
+
70
+ setToString(this, () => outputSheet(this));
71
+ }
72
+
73
+ rehydrate(): void {
74
+ if (!this.server && IS_BROWSER) {
75
+ rehydrateSheet(this);
76
+ }
77
+ }
78
+
79
+ reconstructWithOptions(options: SheetConstructorArgs, withNames = true) {
80
+ const newSheet = new StyleSheet(
81
+ { ...this.options, ...options },
82
+ this.gs,
83
+ (withNames && this.names) || undefined,
84
+ );
85
+
86
+ newSheet.keyframeIds = new Set(this.keyframeIds);
87
+
88
+ // If we're reconstructing with a new target on the client, check if the container changed
89
+ // This handles the case where StyleSheetManager's target prop changes (e.g., from undefined to shadowRoot)
90
+ // We only rehydrate if the container (Document or ShadowRoot) actually changes
91
+ if (!this.server && IS_BROWSER && options.target !== this.options.target) {
92
+ const oldContainer = getRehydrationContainer(this.options.target);
93
+ const newContainer = getRehydrationContainer(options.target);
94
+
95
+ if (oldContainer !== newContainer) {
96
+ rehydrateSheet(newSheet);
97
+ }
98
+ }
99
+
100
+ return newSheet;
101
+ }
102
+
103
+ allocateGSInstance(id: string) {
104
+ return (this.gs[id] = (this.gs[id] || 0) + 1);
105
+ }
106
+
107
+ /** Lazily initialises a GroupedTag for when it's actually needed */
108
+ getTag() {
109
+ return this.output.getTag();
110
+ }
111
+
112
+ /** Check whether a name is known for caching */
113
+ hasNameForId(id: string, name: string): boolean {
114
+ if (!this.output.persistent) return false;
115
+ return this.names.get(id)?.has(name) ?? false;
116
+ }
117
+
118
+ /** Mark a group's name as known for caching */
119
+ registerName(id: string, name: string) {
120
+ getGroupForId(id);
121
+
122
+ if (id.startsWith(KEYFRAMES_ID_PREFIX)) {
123
+ this.keyframeIds.add(id);
124
+ }
125
+
126
+ const existing = this.names.get(id);
127
+ if (existing) {
128
+ existing.add(name);
129
+ } else {
130
+ this.names.set(id, new Set([name]));
131
+ }
132
+ }
133
+
134
+ /** Insert new rules which also marks the name as known */
135
+ insertRules(id: string, name: string, rules: string[]) {
136
+ const group = getGroupForId(id);
137
+ this.output.insertRules(id, name, group, rules);
138
+ if (!this.output.persistent) return;
139
+ this.registerName(id, name);
140
+ }
141
+
142
+ /** Clears all cached names for a given group ID */
143
+ clearNames(id: string) {
144
+ if (this.names.has(id)) {
145
+ (this.names.get(id) as any).clear();
146
+ }
147
+ }
148
+
149
+ /** Clears all rules for a given group ID */
150
+ clearRules(id: string) {
151
+ if (!this.output.persistent) return;
152
+ this.output.clearGroup(getGroupForId(id));
153
+ this.clearNames(id);
154
+ }
155
+
156
+ /** Clears the entire tag which deletes all rules but not its names */
157
+ clearTag() {
158
+ // NOTE: This does not clear the names, since it's only used during SSR
159
+ // so that we can continuously output only new rules
160
+ this.output.reset();
161
+ }
162
+ }
@@ -0,0 +1,135 @@
1
+ import { InsertionTarget } from '../types';
2
+ import { getSheet, makeStyleTag } from './dom';
3
+ import { SheetOptions, Tag } from './types';
4
+
5
+ /** Create a CSSStyleSheet-like tag depending on the environment */
6
+ export const makeTag = ({ isServer, useCSSOMInjection, target, nonce }: SheetOptions) => {
7
+ if (isServer) {
8
+ return new VirtualTag(target);
9
+ } else if (useCSSOMInjection) {
10
+ return new CSSOMTag(target, nonce);
11
+ } else {
12
+ return new TextTag(target, nonce);
13
+ }
14
+ };
15
+
16
+ export const CSSOMTag = class CSSOMTag implements Tag {
17
+ element: HTMLStyleElement;
18
+
19
+ sheet: CSSStyleSheet;
20
+
21
+ length: number;
22
+
23
+ constructor(target?: InsertionTarget | undefined, nonce?: string | undefined) {
24
+ this.element = makeStyleTag(target, nonce);
25
+
26
+ // Avoid Edge bug where empty style elements don't create sheets
27
+ this.element.appendChild(document.createTextNode(''));
28
+
29
+ this.sheet = getSheet(this.element);
30
+ this.length = 0;
31
+ }
32
+
33
+ insertRule(index: number, rule: string): boolean {
34
+ try {
35
+ this.sheet.insertRule(rule, index);
36
+ this.length++;
37
+ return true;
38
+ } catch (_error) {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ deleteRule(index: number): void {
44
+ this.sheet.deleteRule(index);
45
+ this.length--;
46
+ }
47
+
48
+ getRule(index: number): string {
49
+ const rule = this.sheet.cssRules[index];
50
+
51
+ // Avoid IE11 quirk where cssText is inaccessible on some invalid rules
52
+ if (rule && rule.cssText) {
53
+ return rule.cssText;
54
+ } else {
55
+ return '';
56
+ }
57
+ }
58
+ };
59
+
60
+ /** A Tag that emulates the CSSStyleSheet API but uses text nodes */
61
+ export const TextTag = class TextTag implements Tag {
62
+ element: HTMLStyleElement;
63
+ nodes: NodeListOf<Node>;
64
+ length: number;
65
+
66
+ constructor(target?: InsertionTarget | undefined, nonce?: string | undefined) {
67
+ this.element = makeStyleTag(target, nonce);
68
+ this.nodes = this.element.childNodes;
69
+ this.length = 0;
70
+ }
71
+
72
+ insertRule(index: number, rule: string) {
73
+ if (index <= this.length && index >= 0) {
74
+ const node = document.createTextNode(rule);
75
+ const refNode = this.nodes[index];
76
+ this.element.insertBefore(node, refNode || null);
77
+ this.length++;
78
+ return true;
79
+ } else {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ deleteRule(index: number) {
85
+ this.element.removeChild(this.nodes[index]);
86
+ this.length--;
87
+ }
88
+
89
+ getRule(index: number) {
90
+ if (index < this.length) {
91
+ return this.nodes[index].textContent as string;
92
+ } else {
93
+ return '';
94
+ }
95
+ }
96
+ };
97
+
98
+ /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */
99
+ export const VirtualTag = class VirtualTag implements Tag {
100
+ rules: string[];
101
+
102
+ length: number;
103
+
104
+ constructor(_target?: InsertionTarget | undefined) {
105
+ this.rules = [];
106
+ this.length = 0;
107
+ }
108
+
109
+ insertRule(index: number, rule: string) {
110
+ if (index <= this.length) {
111
+ if (index === this.length) {
112
+ this.rules.push(rule);
113
+ } else {
114
+ this.rules.splice(index, 0, rule);
115
+ }
116
+ this.length++;
117
+ return true;
118
+ } else {
119
+ return false;
120
+ }
121
+ }
122
+
123
+ deleteRule(index: number) {
124
+ this.rules.splice(index, 1);
125
+ this.length--;
126
+ }
127
+
128
+ getRule(index: number) {
129
+ if (index < this.length) {
130
+ return this.rules[index];
131
+ } else {
132
+ return '';
133
+ }
134
+ }
135
+ };
@@ -0,0 +1,64 @@
1
+ import { SC_ATTR, SC_ATTR_ACTIVE, SC_ATTR_VERSION, SC_VERSION } from '../constants';
2
+ import { InsertionTarget } from '../types';
3
+ import styledError from '../utils/error';
4
+ import getNonce from '../utils/nonce';
5
+
6
+ /** Find last style element if any inside target */
7
+ const findLastStyleTag = (target: InsertionTarget): void | HTMLStyleElement => {
8
+ const arr = Array.from(target.querySelectorAll<HTMLStyleElement>(`style[${SC_ATTR}]`));
9
+
10
+ return arr[arr.length - 1];
11
+ };
12
+
13
+ /** Create a style element inside `target` or <head> after the last */
14
+ export const makeStyleTag = (
15
+ target?: InsertionTarget | undefined,
16
+ nonce?: string | undefined,
17
+ ): HTMLStyleElement => {
18
+ const head = document.head;
19
+ const parent = target || head;
20
+ const style = document.createElement('style');
21
+ const prevStyle = findLastStyleTag(parent);
22
+ const nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null;
23
+
24
+ style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
25
+ style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
26
+
27
+ const resolvedNonce = nonce || getNonce();
28
+
29
+ if (resolvedNonce) style.setAttribute('nonce', resolvedNonce);
30
+
31
+ parent.insertBefore(style, nextSibling);
32
+
33
+ return style;
34
+ };
35
+
36
+ /** Get the CSSStyleSheet instance for a given style element */
37
+ export const getSheet = (tag: HTMLStyleElement): CSSStyleSheet => {
38
+ if (tag.sheet) {
39
+ return tag.sheet as any as CSSStyleSheet;
40
+ }
41
+
42
+ // Avoid Firefox quirk where the style element might not have a sheet property.
43
+ // Use the tag's root node to find styleSheets - document.styleSheets doesn't
44
+ // include sheets inside shadow roots.
45
+ const root = tag.getRootNode() as Document | ShadowRoot;
46
+ const styleSheets = root.styleSheets ?? document.styleSheets;
47
+ for (let i = 0, l = styleSheets.length; i < l; i++) {
48
+ const sheet = styleSheets[i];
49
+ if (sheet.ownerNode === tag) {
50
+ return sheet as any as CSSStyleSheet;
51
+ }
52
+ }
53
+
54
+ throw styledError(17);
55
+ };
56
+
57
+ /** Remove a GlobalStyle's SSR-rendered inline style tag(s) from the DOM */
58
+ export const removeGlobalStyleTag = (componentId: string, target?: InsertionTarget): void => {
59
+ if (typeof document === 'undefined') return;
60
+
61
+ const container = target ?? document;
62
+ const styleTags = container.querySelectorAll(`style[data-styled-global="${componentId}"]`);
63
+ styleTags.forEach((tag) => tag.remove());
64
+ };
@@ -0,0 +1,2 @@
1
+ export { default } from './Sheet';
2
+ export type { GroupedTag, Sheet, SheetOptions, Tag } from './types';
@@ -0,0 +1,57 @@
1
+ // Octane addition (not part of upstream styled-components): the bridge between
2
+ // the ported sheet engine and octane's SSR css channel.
3
+ //
4
+ // On the server every inserted (componentId, name) chunk is forwarded to
5
+ // octane's `injectStyle`, which collects into the per-request css map that
6
+ // `renderToString`/streaming serialize as `<style data-octane="<id>">` tags.
7
+ // Chunk ids are `sc.<componentId>.<name>`; `name` is always derived from the
8
+ // chunk's css content, so an id can never change content across streaming
9
+ // passes (octane emits each id at most once per stream).
10
+ import { injectStyle } from 'octane';
11
+
12
+ import { IS_BROWSER, OCTANE_CHUNK_PREFIX, SPLITTER } from '../constants';
13
+
14
+ const DOT_RE = /\./g;
15
+
16
+ /**
17
+ * The name segment must stay dot-free so the LAST dot in a chunk id always
18
+ * delimits componentId from name. Names are generated alphabetic/hash tokens
19
+ * that never contain `.` — this is defensive only. The componentId is kept
20
+ * VERBATIM (user `withConfig` ids may contain dots): rehydration parses from
21
+ * the right, so the raw id round-trips and `hasNameForId` lookups after
22
+ * adoption hit the same id the runtime inserts under.
23
+ */
24
+ export function sanitizeChunkPart(part: string): string {
25
+ return part.replace(DOT_RE, '-');
26
+ }
27
+
28
+ export function scChunkId(componentId: string, name: string): string {
29
+ return OCTANE_CHUNK_PREFIX + componentId + '.' + sanitizeChunkPart(name);
30
+ }
31
+
32
+ export function emitChunk(componentId: string, name: string, rules: string[]): void {
33
+ // Browser-constructed server sheets (a ServerStyleSheet created in a test or
34
+ // a client bundle) accumulate in-memory only; the client `injectStyle` has
35
+ // append-to-head semantics that would duplicate what the sheet engine owns.
36
+ if (IS_BROWSER) return;
37
+ injectStyle(scChunkId(componentId, name), rules.join(SPLITTER));
38
+ }
39
+
40
+ /**
41
+ * Removes the server-emitted css-channel tags for one createGlobalStyle
42
+ * component. Called from the component's first layout effect right after it
43
+ * inserted its own rules into the client sheet (synchronous pre-paint, so
44
+ * there is no unstyled flash), because global styles must live in the grouped
45
+ * client engine to support theme-driven rewrites and unmount removal.
46
+ */
47
+ export function removeServerGlobalTags(componentId: string): void {
48
+ if (!IS_BROWSER) return;
49
+ const prefix = OCTANE_CHUNK_PREFIX + componentId + '.';
50
+ const nodes = document.querySelectorAll(`style[data-octane^="${prefix}"]`);
51
+ for (let i = 0; i < nodes.length; i++) {
52
+ const node = nodes[i];
53
+ if (node.parentNode) node.parentNode.removeChild(node);
54
+ }
55
+ }
56
+
57
+ export { SPLITTER };