@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,378 @@
1
+ import * as stylis from 'stylis';
2
+ import { Stringifier } from '../types';
3
+ import {
4
+ ASTERISK,
5
+ BACKSLASH,
6
+ CLOSE_BRACE,
7
+ CLOSE_PAREN,
8
+ DOUBLE_QUOTE,
9
+ NEWLINE,
10
+ OPEN_BRACE,
11
+ OPEN_PAREN,
12
+ SEMICOLON,
13
+ SINGLE_QUOTE,
14
+ SLASH,
15
+ } from './charCodes';
16
+ import { EMPTY_ARRAY, EMPTY_OBJECT } from './empties';
17
+ import throwStyledError from './error';
18
+ import { SEED, phash } from './hash';
19
+
20
+ const AMP_REGEX = /&/g;
21
+
22
+ /**
23
+ * Check if a quote at position i is escaped. A quote is escaped when preceded
24
+ * by an ODD number of backslashes (\", \\\", etc.). An even number means the
25
+ * backslashes themselves are escaped and the quote is real (\\", \\\\", etc.).
26
+ */
27
+ export function isEscaped(css: string, i: number): boolean {
28
+ let backslashes = 0;
29
+ while (--i >= 0 && css.charCodeAt(i) === BACKSLASH) backslashes++;
30
+ return (backslashes & 1) === 1;
31
+ }
32
+
33
+ /**
34
+ * Unified CSS preprocessor: strips JS-style line comments (//) and validates
35
+ * brace balance in a single pass. Handles strings, parenthesized expressions
36
+ * (any function call), and block comments with one shared state machine.
37
+ *
38
+ * Fast paths:
39
+ * - No // and no } → return unchanged (zero work)
40
+ * - No // but has } → brace-only validation (lightweight single pass)
41
+ * - Has // → full unified pass (strip comments + count braces simultaneously)
42
+ */
43
+ export function preprocessCSS(css: string): string {
44
+ const hasLineComments = css.indexOf('//') !== -1;
45
+ const hasCloseBrace = css.indexOf('}') !== -1;
46
+
47
+ if (!hasLineComments && !hasCloseBrace) return css;
48
+
49
+ if (!hasLineComments) return sanitizeBraces(css);
50
+
51
+ const len = css.length;
52
+ let out = '';
53
+ let start = 0;
54
+ let i = 0;
55
+ let inString = 0;
56
+ let parenDepth = 0;
57
+ let braceDepth = 0;
58
+ let modified = false;
59
+
60
+ while (i < len) {
61
+ const code = css.charCodeAt(i);
62
+
63
+ if ((code === DOUBLE_QUOTE || code === SINGLE_QUOTE) && !isEscaped(css, i)) {
64
+ if (inString === 0) {
65
+ inString = code;
66
+ } else if (inString === code) {
67
+ inString = 0;
68
+ }
69
+ i++;
70
+ continue;
71
+ }
72
+
73
+ if (inString !== 0) {
74
+ i++;
75
+ continue;
76
+ }
77
+
78
+ if (code === SLASH && i + 1 < len && css.charCodeAt(i + 1) === ASTERISK) {
79
+ i += 2;
80
+ while (i + 1 < len && !(css.charCodeAt(i) === ASTERISK && css.charCodeAt(i + 1) === SLASH)) {
81
+ i++;
82
+ }
83
+ i += 2;
84
+ continue;
85
+ }
86
+
87
+ if (code === OPEN_PAREN) {
88
+ parenDepth++;
89
+ i++;
90
+ continue;
91
+ }
92
+
93
+ if (code === CLOSE_PAREN) {
94
+ if (parenDepth > 0) parenDepth--;
95
+ i++;
96
+ continue;
97
+ }
98
+
99
+ // Inside parentheses (any function call), skip comment/brace detection
100
+ // so that url(https://...), image-set(), etc. are preserved
101
+ if (parenDepth > 0) {
102
+ i++;
103
+ continue;
104
+ }
105
+
106
+ if (code === ASTERISK && i + 1 < len && css.charCodeAt(i + 1) === SLASH) {
107
+ out += css.substring(start, i);
108
+ i += 2;
109
+ start = i;
110
+ modified = true;
111
+ continue;
112
+ }
113
+
114
+ if (code === SLASH && i + 1 < len && css.charCodeAt(i + 1) === SLASH) {
115
+ out += css.substring(start, i);
116
+ while (i < len && css.charCodeAt(i) !== NEWLINE) {
117
+ i++;
118
+ }
119
+ start = i;
120
+ modified = true;
121
+ continue;
122
+ }
123
+
124
+ if (code === OPEN_BRACE) {
125
+ braceDepth++;
126
+ } else if (code === CLOSE_BRACE) {
127
+ braceDepth--;
128
+ }
129
+
130
+ i++;
131
+ }
132
+
133
+ if (!modified) {
134
+ if (braceDepth === 0) return css;
135
+ return sanitizeBraces(css);
136
+ }
137
+
138
+ if (start < len) out += css.substring(start);
139
+
140
+ if (braceDepth === 0) return out;
141
+ return sanitizeBraces(out);
142
+ }
143
+
144
+ /**
145
+ * Removes declarations with unbalanced braces from CSS.
146
+ * Only called when preprocessCSS detects brace imbalance.
147
+ */
148
+ function sanitizeBraces(css: string): string {
149
+ const len = css.length;
150
+ let result = '';
151
+ let declStart = 0;
152
+ let braceDepth = 0;
153
+ let inString = 0;
154
+ let inComment = false;
155
+ let imbalanced = false;
156
+
157
+ for (let i = 0; i < len; i++) {
158
+ const code = css.charCodeAt(i);
159
+
160
+ if (inString === 0 && !inComment && code === SLASH && css.charCodeAt(i + 1) === ASTERISK) {
161
+ inComment = true;
162
+ i++;
163
+ continue;
164
+ }
165
+ if (inComment) {
166
+ if (code === ASTERISK && css.charCodeAt(i + 1) === SLASH) {
167
+ inComment = false;
168
+ i++;
169
+ }
170
+ continue;
171
+ }
172
+
173
+ if ((code === DOUBLE_QUOTE || code === SINGLE_QUOTE) && !isEscaped(css, i)) {
174
+ if (inString === 0) {
175
+ inString = code;
176
+ } else if (inString === code) {
177
+ inString = 0;
178
+ }
179
+ continue;
180
+ }
181
+ if (inString !== 0) continue;
182
+
183
+ if (code === OPEN_BRACE) {
184
+ braceDepth++;
185
+ } else if (code === CLOSE_BRACE) {
186
+ braceDepth--;
187
+
188
+ if (braceDepth < 0) {
189
+ imbalanced = true;
190
+ let skipEnd = i + 1;
191
+ while (skipEnd < len) {
192
+ const skipCode = css.charCodeAt(skipEnd);
193
+ if (skipCode === SEMICOLON || skipCode === NEWLINE) break;
194
+ skipEnd++;
195
+ }
196
+ if (skipEnd < len && css.charCodeAt(skipEnd) === SEMICOLON) skipEnd++;
197
+
198
+ braceDepth = 0;
199
+ i = skipEnd - 1;
200
+ declStart = skipEnd;
201
+ continue;
202
+ }
203
+
204
+ if (braceDepth === 0) {
205
+ result += css.substring(declStart, i + 1);
206
+ declStart = i + 1;
207
+ }
208
+ } else if (code === SEMICOLON && braceDepth === 0) {
209
+ result += css.substring(declStart, i + 1);
210
+ declStart = i + 1;
211
+ }
212
+ }
213
+
214
+ if (!imbalanced && braceDepth === 0 && inString === 0) return css;
215
+
216
+ if (declStart < len && braceDepth === 0 && inString === 0) {
217
+ result += css.substring(declStart);
218
+ }
219
+
220
+ return result;
221
+ }
222
+
223
+ export type ICreateStylisInstance = {
224
+ options?: { namespace?: string | undefined; prefix?: boolean | undefined } | undefined;
225
+ plugins?: stylis.Middleware[] | undefined;
226
+ };
227
+
228
+ /**
229
+ * Takes an element and recurses through it's rules added the namespace to the start of each selector.
230
+ * Takes into account media queries by recursing through child rules if they are present.
231
+ */
232
+ function recursivelySetNamespace(compiled: stylis.Element[], namespace: string): stylis.Element[] {
233
+ // Stylis AST can share `props` arrays between a top-level rule and a nested
234
+ // copy of the same rule inside @media, so we must allocate a replacement
235
+ // array rather than mutating in place. Hoist the concat operands to save
236
+ // a per-rule/per-prop string alloc.
237
+ const prefix = namespace + ' ';
238
+ const commaReplace = ',' + prefix;
239
+ for (let i = 0; i < compiled.length; i++) {
240
+ const rule = compiled[i];
241
+ if (rule.type === 'rule') {
242
+ rule.value = (prefix + rule.value).replaceAll(',', commaReplace);
243
+ const props = rule.props as string[];
244
+ const newProps: string[] = [];
245
+ for (let j = 0; j < props.length; j++) {
246
+ newProps[j] = prefix + props[j];
247
+ }
248
+ rule.props = newProps;
249
+ }
250
+
251
+ if (Array.isArray(rule.children) && rule.type !== '@keyframes') {
252
+ recursivelySetNamespace(rule.children, namespace);
253
+ }
254
+ }
255
+ return compiled;
256
+ }
257
+
258
+ export default function createStylisInstance(
259
+ {
260
+ options = EMPTY_OBJECT as object,
261
+ plugins = EMPTY_ARRAY as unknown as stylis.Middleware[],
262
+ }: ICreateStylisInstance = EMPTY_OBJECT as object,
263
+ ) {
264
+ let _componentId: string;
265
+ let _selector: string;
266
+ let _selectorRegexp: RegExp | undefined;
267
+
268
+ const selfReferenceReplacer = (match: string, offset: number, string: string) => {
269
+ if (
270
+ /**
271
+ * We only want to refer to the static class directly if the selector is part of a
272
+ * self-reference selector `& + & { color: red; }`
273
+ */
274
+ string.startsWith(_selector) &&
275
+ string.endsWith(_selector) &&
276
+ string.replaceAll(_selector, '').length > 0
277
+ ) {
278
+ return `.${_componentId}`;
279
+ }
280
+
281
+ return match;
282
+ };
283
+
284
+ /**
285
+ * When writing a style like
286
+ *
287
+ * & + & {
288
+ * color: red;
289
+ * }
290
+ *
291
+ * The second ampersand should be a reference to the static component class. stylis
292
+ * has no knowledge of static class so we have to intelligently replace the base selector.
293
+ *
294
+ * https://github.com/thysultan/stylis.js/tree/v4.0.2#abstract-syntax-structure
295
+ */
296
+ const selfReferenceReplacementPlugin: stylis.Middleware = (element) => {
297
+ if (element.type === stylis.RULESET && element.value.includes('&')) {
298
+ // Lazy RegExp creation: only allocate when self-reference pattern is actually used
299
+ if (!_selectorRegexp) {
300
+ _selectorRegexp = new RegExp(`\\${_selector}\\b`, 'g');
301
+ }
302
+
303
+ (element.props as string[])[0] = element.props[0]
304
+ // catch any hanging references that stylis missed
305
+ .replace(AMP_REGEX, _selector)
306
+ .replace(_selectorRegexp, selfReferenceReplacer);
307
+ }
308
+ };
309
+
310
+ const middlewares = plugins.slice();
311
+
312
+ middlewares.push(selfReferenceReplacementPlugin);
313
+
314
+ /**
315
+ * Enables automatic vendor-prefixing for styles.
316
+ */
317
+ if (options.prefix) {
318
+ middlewares.push(stylis.prefixer);
319
+ }
320
+
321
+ middlewares.push(stylis.stringify);
322
+
323
+ // Pre-build the middleware chain once to avoid allocating closures,
324
+ // arrays, and middleware wrappers on every stringifyRules call.
325
+ // Safe because JS is single-threaded and _stack is consumed before next call.
326
+ let _stack: string[] = [];
327
+ const _middleware = stylis.middleware(
328
+ middlewares.concat(stylis.rulesheet((value) => _stack.push(value))),
329
+ );
330
+
331
+ const stringifyRules: Stringifier = (
332
+ css: string,
333
+ selector = '',
334
+ /**
335
+ * This "prefix" referes to a _selector_ prefix.
336
+ */
337
+ prefix = '',
338
+ componentId = '&',
339
+ ) => {
340
+ // stylis has no concept of state to be passed to plugins
341
+ // but since JS is single-threaded, we can rely on that to ensure
342
+ // these properties stay in sync with the current stylis run
343
+ _componentId = componentId;
344
+ _selector = selector;
345
+ _selectorRegexp = undefined; // Reset for lazy creation per call
346
+
347
+ const flatCSS = preprocessCSS(css);
348
+ let compiled = stylis.compile(
349
+ prefix || selector ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS,
350
+ );
351
+
352
+ if (options.namespace) {
353
+ compiled = recursivelySetNamespace(compiled, options.namespace);
354
+ }
355
+
356
+ _stack = [];
357
+ stylis.serialize(compiled, _middleware);
358
+
359
+ return _stack;
360
+ };
361
+
362
+ // Hash includes plugins + options so different stylis configs produce
363
+ // different class names and cache keys.
364
+ const o = options as ICreateStylisInstance['options'];
365
+ let h = SEED;
366
+ for (let i = 0; i < plugins.length; i++) {
367
+ // Upstream 6.4.3 calls the error factory here without `throw`ing its
368
+ // result, so unnamed plugins silently collide. The octane port enforces
369
+ // the documented error-15 contract.
370
+ if (!plugins[i].name) throw throwStyledError(15);
371
+ h = phash(h, plugins[i].name);
372
+ }
373
+ if (o?.namespace) h = phash(h, o.namespace);
374
+ if (o?.prefix) h = phash(h, 'p');
375
+ stringifyRules.hash = h !== SEED ? h.toString() : '';
376
+
377
+ return stringifyRules;
378
+ }