@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,346 @@
1
+ // Ported from styled-components 6.4.3 (MIT), adapted for octane:
2
+ // - No forwardRef: the generated component is a plain octane function
3
+ // component and `ref` arrives as an ordinary prop, which is always forwarded
4
+ // to the created element (octane attaches refs from props natively).
5
+ // - No RSC/`__SERVER__` build flags: server output is selected by the active
6
+ // stylesheet backend at runtime.
7
+ // - `defaultProps` is resolved by this factory at render time (octane's
8
+ // compiled call sites do not apply component defaultProps).
9
+ import isPropValid from '@emotion/is-prop-valid';
10
+ import { createElement, useContext } from 'octane';
11
+
12
+ import type {
13
+ AnyComponent,
14
+ Attrs,
15
+ BaseObject,
16
+ Dict,
17
+ ExecutionContext,
18
+ ExecutionProps,
19
+ IStyledComponent,
20
+ IStyledComponentFactory,
21
+ IStyledStatics,
22
+ OmitNever,
23
+ RuleSet,
24
+ StyledOptions,
25
+ WebTarget,
26
+ } from '../types';
27
+ import { checkDynamicCreation } from '../utils/checkDynamicCreation';
28
+ import createWarnTooManyClasses from '../utils/createWarnTooManyClasses';
29
+ import determineTheme from '../utils/determineTheme';
30
+ import { EMPTY_ARRAY, EMPTY_OBJECT } from '../utils/empties';
31
+ import escape from '../utils/escape';
32
+ import generateComponentId from '../utils/generateComponentId';
33
+ import generateDisplayName from '../utils/generateDisplayName';
34
+ import hoist from '../utils/hoist';
35
+ import isFunction from '../utils/isFunction';
36
+ import isStyledComponent, { STYLED_COMPONENT_BRAND } from '../utils/isStyledComponent';
37
+ import isTag from '../utils/isTag';
38
+ import { joinStrings } from '../utils/joinStrings';
39
+ import merge from '../utils/mixinDeep';
40
+ import { setToString } from '../utils/setToString';
41
+ import { SC_VERSION } from '../constants';
42
+ import ComponentStyle from './ComponentStyle';
43
+ import { useStyleSheetContext } from './StyleSheetManager';
44
+ import { DefaultTheme, ThemeContext } from './ThemeProvider';
45
+
46
+ const identifiers: { [key: string]: number } = {};
47
+
48
+ /** Test-only: clear the per-displayName counter so component IDs stay stable
49
+ * across tests. Not for production use. */
50
+ export const resetIdentifiers = (): void => {
51
+ for (const k in identifiers) delete identifiers[k];
52
+ };
53
+
54
+ /* We depend on components having unique IDs */
55
+ function generateId(
56
+ displayName?: string | undefined,
57
+ parentComponentId?: string | undefined,
58
+ ): string {
59
+ const name = typeof displayName !== 'string' ? 'sc' : escape(displayName);
60
+ // Ensure that no displayName can lead to duplicate componentIds
61
+ identifiers[name] = (identifiers[name] || 0) + 1;
62
+
63
+ const componentId =
64
+ name +
65
+ '-' +
66
+ generateComponentId(
67
+ // SC_VERSION gives us isolation between multiple runtimes on the page at once
68
+ SC_VERSION + name + identifiers[name],
69
+ );
70
+
71
+ return parentComponentId ? parentComponentId + '-' + componentId : componentId;
72
+ }
73
+
74
+ type StyleContext<Props extends BaseObject> = ExecutionContext &
75
+ Props & {
76
+ className?: string | undefined;
77
+ style?: Dict<any> | undefined;
78
+ [key: string]: any;
79
+ };
80
+
81
+ function resolveContext<Props extends BaseObject>(
82
+ attrs: Attrs<Props>[],
83
+ props: ExecutionProps & Props,
84
+ theme: DefaultTheme | undefined,
85
+ ): StyleContext<Props> {
86
+ const context: StyleContext<Props> = {
87
+ ...props,
88
+ // unset, add `props.className` back at the end so props always "wins"
89
+ className: undefined,
90
+ theme,
91
+ } as StyleContext<Props>;
92
+
93
+ const needsCopy = attrs.length > 1;
94
+ for (let i = 0; i < attrs.length; i++) {
95
+ const attrDef = attrs[i];
96
+ const resolvedAttrDef = isFunction(attrDef)
97
+ ? (attrDef as Function)(needsCopy ? { ...context } : context)
98
+ : attrDef;
99
+
100
+ for (const key in resolvedAttrDef) {
101
+ if (key === 'className') {
102
+ context.className = joinStrings(context.className, resolvedAttrDef[key] as string);
103
+ } else if (key === 'style') {
104
+ context.style = { ...context.style, ...(resolvedAttrDef[key] as Dict<any>) };
105
+ } else if (!(key in props && (props as any)[key] === undefined)) {
106
+ // Apply attr value unless the user explicitly passed undefined for this prop,
107
+ // which signals intent to reset the value.
108
+ (context as any)[key] = resolvedAttrDef[key];
109
+ }
110
+ }
111
+ }
112
+
113
+ if ('className' in props && typeof (props as any).className === 'string') {
114
+ context.className = joinStrings(context.className, (props as any).className);
115
+ }
116
+
117
+ return context;
118
+ }
119
+
120
+ let seenUnknownProps: Set<string> | undefined;
121
+
122
+ function buildPropsForElement(
123
+ context: Record<string, any>,
124
+ elementToBeCreated: WebTarget,
125
+ theme: DefaultTheme | undefined,
126
+ shouldForwardProp: ((prop: string, el: WebTarget) => boolean) | undefined,
127
+ ): Dict<any> {
128
+ const propsForElement: Dict<any> = {};
129
+
130
+ for (const key in context) {
131
+ if (context[key] === undefined) {
132
+ // Omit undefined values from props passed to wrapped element.
133
+ } else if (key[0] === '$' || key === 'as' || (key === 'theme' && context.theme === theme)) {
134
+ // Omit transient props and execution props.
135
+ } else if (key === 'forwardedAs') {
136
+ propsForElement.as = context.forwardedAs;
137
+ } else if (key === 'ref') {
138
+ // octane refs are plain props; a ref always attaches to the created
139
+ // element and is never subject to shouldForwardProp filtering.
140
+ propsForElement.ref = context.ref;
141
+ } else if (!shouldForwardProp || shouldForwardProp(key, elementToBeCreated)) {
142
+ propsForElement[key] = context[key];
143
+
144
+ if (
145
+ !shouldForwardProp &&
146
+ process.env.NODE_ENV === 'development' &&
147
+ !isPropValid(key) &&
148
+ !(seenUnknownProps || (seenUnknownProps = new Set())).has(key) &&
149
+ isTag(elementToBeCreated) &&
150
+ !elementToBeCreated.includes('-')
151
+ ) {
152
+ seenUnknownProps.add(key);
153
+ console.warn(
154
+ `styled-components: it looks like an unknown prop "${key}" is being sent through to the DOM, which will likely trigger a console error. If you would like automatic filtering of unknown props, you can opt-into that behavior via \`<StyleSheetManager shouldForwardProp={...}>\` (connect an API like \`@emotion/is-prop-valid\`) or consider using transient props (\`$\` prefix for automatic filtering.)`,
155
+ );
156
+ }
157
+ }
158
+ }
159
+
160
+ return propsForElement;
161
+ }
162
+
163
+ function useStyledComponentImpl<Props extends BaseObject>(
164
+ forwardedComponent: IStyledComponent<'web', Props>,
165
+ props: ExecutionProps & Props,
166
+ ) {
167
+ const {
168
+ attrs: componentAttrs,
169
+ componentStyle,
170
+ defaultProps,
171
+ foldedComponentIds,
172
+ styledComponentId,
173
+ target,
174
+ } = forwardedComponent;
175
+
176
+ const contextTheme = useContext(ThemeContext);
177
+ const ssc = useStyleSheetContext();
178
+ const shouldForwardProp = forwardedComponent.shouldForwardProp || ssc.shouldForwardProp;
179
+
180
+ const theme = determineTheme(props, contextTheme, defaultProps) || EMPTY_OBJECT;
181
+
182
+ // Attrs are render functions, so always resolve them on an actual component
183
+ // render. Dynamic styles are evaluated for the same reason. ComponentStyle
184
+ // shares only proven-static client results by sheet and stylis identity;
185
+ // server outputs are always revisited for the active request.
186
+ const context = resolveContext<Props>(componentAttrs, props, theme);
187
+ const generatedClassName = componentStyle.generateAndInjectStyles(
188
+ context,
189
+ ssc.styleSheet,
190
+ ssc.stylis,
191
+ );
192
+
193
+ if (process.env.NODE_ENV !== 'production' && forwardedComponent.warnTooManyClasses) {
194
+ forwardedComponent.warnTooManyClasses(generatedClassName);
195
+ }
196
+
197
+ const elementToBeCreated: WebTarget = (context.as as WebTarget) || target;
198
+ const propsForElement = buildPropsForElement(
199
+ context,
200
+ elementToBeCreated,
201
+ theme,
202
+ shouldForwardProp,
203
+ );
204
+
205
+ let classString = joinStrings(foldedComponentIds, styledComponentId);
206
+ if (generatedClassName) {
207
+ classString += ' ' + generatedClassName;
208
+ }
209
+ if (context.className) {
210
+ classString += ' ' + context.className;
211
+ }
212
+
213
+ propsForElement[
214
+ isTag(elementToBeCreated) && elementToBeCreated.includes('-') ? 'class' : 'className'
215
+ ] = classString;
216
+
217
+ return createElement(elementToBeCreated as any, propsForElement);
218
+ }
219
+
220
+ function createStyledComponent<
221
+ Target extends WebTarget,
222
+ OuterProps extends BaseObject,
223
+ Statics extends BaseObject = BaseObject,
224
+ >(
225
+ target: Target,
226
+ options: StyledOptions<'web', OuterProps>,
227
+ rules: RuleSet<OuterProps>,
228
+ ): ReturnType<IStyledComponentFactory<'web', Target, OuterProps, Statics>> {
229
+ const isTargetStyledComp = isStyledComponent(target);
230
+ const styledComponentTarget = target as IStyledComponent<'web', OuterProps>;
231
+ const isCompositeComponent = !isTag(target);
232
+
233
+ const {
234
+ attrs = EMPTY_ARRAY,
235
+ componentId = generateId(options.displayName, options.parentComponentId),
236
+ displayName = generateDisplayName(target),
237
+ } = options;
238
+
239
+ const styledComponentId =
240
+ options.displayName && options.componentId
241
+ ? escape(options.displayName) + '-' + options.componentId
242
+ : options.componentId || componentId;
243
+
244
+ // fold the underlying StyledComponent attrs up (implicit extend)
245
+ const finalAttrs =
246
+ isTargetStyledComp && styledComponentTarget.attrs
247
+ ? styledComponentTarget.attrs.concat(attrs as unknown as Attrs<OuterProps>[]).filter(Boolean)
248
+ : (attrs as Attrs<OuterProps>[]);
249
+
250
+ let { shouldForwardProp } = options;
251
+
252
+ if (isTargetStyledComp && styledComponentTarget.shouldForwardProp) {
253
+ const shouldForwardPropFn = styledComponentTarget.shouldForwardProp;
254
+
255
+ if (options.shouldForwardProp) {
256
+ const passedShouldForwardPropFn = options.shouldForwardProp;
257
+
258
+ // compose nested shouldForwardProp calls
259
+ shouldForwardProp = (prop, elementToBeCreated) =>
260
+ shouldForwardPropFn(prop, elementToBeCreated) &&
261
+ passedShouldForwardPropFn(prop, elementToBeCreated);
262
+ } else {
263
+ shouldForwardProp = shouldForwardPropFn;
264
+ }
265
+ }
266
+
267
+ const componentStyle = new ComponentStyle(
268
+ rules,
269
+ styledComponentId,
270
+ isTargetStyledComp ? (styledComponentTarget.componentStyle as ComponentStyle) : undefined,
271
+ );
272
+
273
+ function StyledComponentRender(props: ExecutionProps & OuterProps, _scope?: any) {
274
+ return useStyledComponentImpl<OuterProps>(
275
+ WrappedStyledComponent,
276
+ props as ExecutionProps & OuterProps,
277
+ );
278
+ }
279
+
280
+ StyledComponentRender.displayName = displayName;
281
+
282
+ let WrappedStyledComponent = StyledComponentRender as unknown as IStyledComponent<'web', any> &
283
+ Statics;
284
+ (WrappedStyledComponent as any)[STYLED_COMPONENT_BRAND] = true;
285
+ WrappedStyledComponent.attrs = finalAttrs;
286
+ WrappedStyledComponent.componentStyle = componentStyle;
287
+ WrappedStyledComponent.displayName = displayName;
288
+ WrappedStyledComponent.shouldForwardProp = shouldForwardProp;
289
+
290
+ // this static is used to preserve the cascade of static classes for component selector
291
+ // purposes; this is especially important with usage of the css prop
292
+ WrappedStyledComponent.foldedComponentIds = isTargetStyledComp
293
+ ? joinStrings(styledComponentTarget.foldedComponentIds, styledComponentTarget.styledComponentId)
294
+ : '';
295
+
296
+ WrappedStyledComponent.styledComponentId = styledComponentId;
297
+
298
+ // fold the underlying StyledComponent target up since we folded the styles
299
+ WrappedStyledComponent.target = isTargetStyledComp ? styledComponentTarget.target : target;
300
+
301
+ Object.defineProperty(WrappedStyledComponent, 'defaultProps', {
302
+ get() {
303
+ return this._foldedDefaultProps;
304
+ },
305
+
306
+ set(obj) {
307
+ this._foldedDefaultProps = isTargetStyledComp
308
+ ? merge({}, styledComponentTarget.defaultProps, obj)
309
+ : obj;
310
+ },
311
+ });
312
+
313
+ if (process.env.NODE_ENV !== 'production') {
314
+ checkDynamicCreation(displayName, styledComponentId);
315
+
316
+ WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(
317
+ displayName,
318
+ styledComponentId,
319
+ );
320
+ }
321
+
322
+ setToString(WrappedStyledComponent, () => `.${WrappedStyledComponent.styledComponentId}`);
323
+
324
+ if (isCompositeComponent) {
325
+ const compositeComponentTarget = target as AnyComponent;
326
+
327
+ hoist<typeof WrappedStyledComponent, typeof compositeComponentTarget>(
328
+ WrappedStyledComponent,
329
+ compositeComponentTarget,
330
+ {
331
+ // all SC-specific things should not be hoisted
332
+ attrs: true,
333
+ componentStyle: true,
334
+ displayName: true,
335
+ foldedComponentIds: true,
336
+ shouldForwardProp: true,
337
+ styledComponentId: true,
338
+ target: true,
339
+ } as { [key in keyof OmitNever<IStyledStatics<'web', OuterProps>>]: true },
340
+ );
341
+ }
342
+
343
+ return WrappedStyledComponent;
344
+ }
345
+
346
+ export default createStyledComponent;
@@ -0,0 +1,124 @@
1
+ // Ported from styled-components 6.4.3 (MIT), adapted for octane: contexts are
2
+ // provided through `createElement(Ctx.Provider, …)` descriptors (works on both
3
+ // the client and server runtimes), and the Consumer components are hand-built
4
+ // because octane's React-19-shaped contexts have no `.Consumer`.
5
+ import { createContext, createElement, isChildrenBlock, useContext, useMemo } from 'octane';
6
+
7
+ import styledError from '../utils/error';
8
+ import isFunction from '../utils/isFunction';
9
+
10
+ // Helper type for the `DefaultTheme` interface that enforces an object type & exclusively allows
11
+ // for typed keys.
12
+ type DefaultThemeAsObject<T = object> = Record<keyof T, any>;
13
+
14
+ /**
15
+ * Override DefaultTheme to get accurate typings for your project.
16
+ *
17
+ * ```
18
+ * // create styled-components.d.ts in your project source
19
+ * // if it isn't being picked up, check tsconfig compilerOptions.types
20
+ * import Theme from './theme';
21
+ *
22
+ * type ThemeType = typeof Theme;
23
+ *
24
+ * declare module '@octanejs/styled-components' {
25
+ * export interface DefaultTheme extends ThemeType {}
26
+ * }
27
+ * ```
28
+ */
29
+ export interface DefaultTheme extends DefaultThemeAsObject {}
30
+
31
+ type ThemeFn = (outerTheme?: DefaultTheme | undefined) => DefaultTheme;
32
+ type ThemeArgument = DefaultTheme | ThemeFn;
33
+
34
+ type Props = {
35
+ children?: any;
36
+ theme: ThemeArgument;
37
+ };
38
+
39
+ const SLOT_THEME_MEMO = Symbol.for('@octanejs/styled-components:theme-memo');
40
+
41
+ export const ThemeContext = createContext<DefaultTheme | undefined>(undefined);
42
+
43
+ /**
44
+ * Upstream's `ThemeContext.Consumer` as a component: expects a single function
45
+ * child which is called with the current theme.
46
+ */
47
+ export function ThemeConsumer(props: { children?: any }): unknown {
48
+ const theme = useContext(ThemeContext);
49
+ const render = props.children;
50
+
51
+ if (isFunction(render) && !isChildrenBlock(render)) {
52
+ return (render as (theme?: DefaultTheme | undefined) => unknown)(theme);
53
+ }
54
+
55
+ if (process.env.NODE_ENV !== 'production' && render != null) {
56
+ console.warn('ThemeConsumer expects a single function child which receives the theme.');
57
+ }
58
+
59
+ return null;
60
+ }
61
+
62
+ function mergeTheme(theme: ThemeArgument, outerTheme?: DefaultTheme | undefined): DefaultTheme {
63
+ if (!theme) {
64
+ throw styledError(14);
65
+ }
66
+
67
+ if (isFunction(theme)) {
68
+ const themeFn = theme as ThemeFn;
69
+ const mergedTheme = themeFn(outerTheme);
70
+
71
+ if (
72
+ process.env.NODE_ENV !== 'production' &&
73
+ (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')
74
+ ) {
75
+ throw styledError(7);
76
+ }
77
+
78
+ return mergedTheme;
79
+ }
80
+
81
+ if (Array.isArray(theme) || typeof theme !== 'object') {
82
+ throw styledError(8);
83
+ }
84
+
85
+ return outerTheme ? { ...outerTheme, ...theme } : theme;
86
+ }
87
+
88
+ /**
89
+ * Returns the current theme (as provided by the closest ancestor `ThemeProvider`.)
90
+ *
91
+ * If no `ThemeProvider` is found, the function will error. If you need access to the theme in an
92
+ * uncertain composition scenario, `useContext(ThemeContext)` will not emit an error if there
93
+ * is no `ThemeProvider` ancestor.
94
+ */
95
+ export function useTheme(): DefaultTheme {
96
+ const theme = useContext(ThemeContext);
97
+
98
+ if (!theme) {
99
+ throw styledError(18);
100
+ }
101
+
102
+ return theme;
103
+ }
104
+
105
+ /**
106
+ * Provide a theme to an entire octane component tree via context
107
+ */
108
+ export default function ThemeProvider(props: Props): unknown {
109
+ const outerTheme = useContext(ThemeContext);
110
+ const themeContext = useMemo(
111
+ () => mergeTheme(props.theme, outerTheme),
112
+ [props.theme, outerTheme],
113
+ SLOT_THEME_MEMO,
114
+ );
115
+
116
+ if (!props.children) {
117
+ return null;
118
+ }
119
+
120
+ return createElement(ThemeContext.Provider as any, {
121
+ value: themeContext,
122
+ children: props.children,
123
+ });
124
+ }
@@ -0,0 +1,7 @@
1
+ import { mainSheet } from './models/StyleSheetManager';
2
+ import StyleSheet from './sheet';
3
+
4
+ export const __PRIVATE__ = {
5
+ StyleSheet,
6
+ mainSheet,
7
+ };
@@ -0,0 +1,45 @@
1
+ import styledError from '../utils/error';
2
+
3
+ const MAX_SMI = 1 << (31 - 1);
4
+
5
+ let groupIDRegister: Map<string, number> = new Map();
6
+ let reverseRegister: Map<number, string> = new Map();
7
+ let nextFreeGroup = 1;
8
+
9
+ export const resetGroupIds = () => {
10
+ groupIDRegister = new Map();
11
+ reverseRegister = new Map();
12
+ nextFreeGroup = 1;
13
+ };
14
+
15
+ export const getGroupForId = (id: string): number => {
16
+ if (groupIDRegister.has(id)) {
17
+ return groupIDRegister.get(id) as any;
18
+ }
19
+
20
+ while (reverseRegister.has(nextFreeGroup)) {
21
+ nextFreeGroup++;
22
+ }
23
+
24
+ const group = nextFreeGroup++;
25
+
26
+ if (process.env.NODE_ENV !== 'production' && ((group | 0) < 0 || group > MAX_SMI)) {
27
+ throw styledError(16, `${group}`);
28
+ }
29
+
30
+ groupIDRegister.set(id, group);
31
+ reverseRegister.set(group, id);
32
+ return group;
33
+ };
34
+
35
+ export const getIdForGroup = (group: number): void | string => {
36
+ return reverseRegister.get(group);
37
+ };
38
+
39
+ export const setGroupForId = (id: string, group: number) => {
40
+ // move pointer
41
+ nextFreeGroup = group + 1;
42
+
43
+ groupIDRegister.set(id, group);
44
+ reverseRegister.set(group, id);
45
+ };
@@ -0,0 +1,125 @@
1
+ import { SPLITTER } from '../constants';
2
+ import styledError from '../utils/error';
3
+ import { GroupedTag, Tag } from './types';
4
+
5
+ /** Create a GroupedTag with an underlying Tag implementation */
6
+ export const makeGroupedTag = (tag: Tag) => {
7
+ return new DefaultGroupedTag(tag);
8
+ };
9
+
10
+ const BASE_SIZE = 1 << 9;
11
+
12
+ const DefaultGroupedTag = class DefaultGroupedTag implements GroupedTag {
13
+ groupSizes: Uint32Array;
14
+ length: number;
15
+ tag: Tag;
16
+
17
+ // Cached position for O(1) sequential indexOfGroup lookups.
18
+ // Avoids the O(n) linear scan on every call by remembering the last
19
+ // computed (group → absoluteIndex) pair and scanning incrementally.
20
+ _cGroup: number;
21
+ _cIndex: number;
22
+
23
+ constructor(tag: Tag) {
24
+ this.groupSizes = new Uint32Array(BASE_SIZE);
25
+ this.length = BASE_SIZE;
26
+ this.tag = tag;
27
+ this._cGroup = 0;
28
+ this._cIndex = 0;
29
+ }
30
+
31
+ indexOfGroup(group: number) {
32
+ if (group === this._cGroup) return this._cIndex;
33
+
34
+ let index = this._cIndex;
35
+
36
+ if (group > this._cGroup) {
37
+ for (let i = this._cGroup; i < group; i++) {
38
+ index += this.groupSizes[i];
39
+ }
40
+ } else {
41
+ for (let i = this._cGroup - 1; i >= group; i--) {
42
+ index -= this.groupSizes[i];
43
+ }
44
+ }
45
+
46
+ this._cGroup = group;
47
+ this._cIndex = index;
48
+ return index;
49
+ }
50
+
51
+ insertRules(group: number, rules: string[]) {
52
+ if (group >= this.groupSizes.length) {
53
+ const oldBuffer = this.groupSizes;
54
+ const oldSize = oldBuffer.length;
55
+
56
+ let newSize = oldSize;
57
+ while (group >= newSize) {
58
+ newSize <<= 1;
59
+ if (newSize < 0) {
60
+ throw styledError(16, `${group}`);
61
+ }
62
+ }
63
+
64
+ this.groupSizes = new Uint32Array(newSize);
65
+ this.groupSizes.set(oldBuffer);
66
+ this.length = newSize;
67
+
68
+ for (let i = oldSize; i < newSize; i++) {
69
+ this.groupSizes[i] = 0;
70
+ }
71
+ }
72
+
73
+ let ruleIndex = this.indexOfGroup(group + 1);
74
+ let insertedCount = 0;
75
+
76
+ for (let i = 0, l = rules.length; i < l; i++) {
77
+ if (this.tag.insertRule(ruleIndex, rules[i])) {
78
+ this.groupSizes[group]++;
79
+ ruleIndex++;
80
+ insertedCount++;
81
+ }
82
+ }
83
+
84
+ // Keep cache consistent: groups after the insertion point shift forward
85
+ if (insertedCount > 0 && this._cGroup > group) {
86
+ this._cIndex += insertedCount;
87
+ }
88
+ }
89
+
90
+ clearGroup(group: number) {
91
+ if (group < this.length) {
92
+ const length = this.groupSizes[group];
93
+ const startIndex = this.indexOfGroup(group);
94
+ const endIndex = startIndex + length;
95
+
96
+ this.groupSizes[group] = 0;
97
+
98
+ for (let i = startIndex; i < endIndex; i++) {
99
+ this.tag.deleteRule(startIndex);
100
+ }
101
+
102
+ // Keep cache consistent: groups after the cleared group shift backward
103
+ if (length > 0 && this._cGroup > group) {
104
+ this._cIndex -= length;
105
+ }
106
+ }
107
+ }
108
+
109
+ getGroup(group: number) {
110
+ let css = '';
111
+ if (group >= this.length || this.groupSizes[group] === 0) {
112
+ return css;
113
+ }
114
+
115
+ const length = this.groupSizes[group];
116
+ const startIndex = this.indexOfGroup(group);
117
+ const endIndex = startIndex + length;
118
+
119
+ for (let i = startIndex; i < endIndex; i++) {
120
+ css += this.tag.getRule(i) + SPLITTER;
121
+ }
122
+
123
+ return css;
124
+ }
125
+ };