oncss 1.2.13 → 1.2.14

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 (2) hide show
  1. package/package.json +5 -4
  2. package/readme.md +796 -232
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oncss",
3
- "version": "1.2.13",
3
+ "version": "1.2.14",
4
4
  "description": "A CSS framework for modern web development.",
5
5
  "main": "./index.cjs",
6
6
  "module": "./index.js",
@@ -12,14 +12,15 @@
12
12
  "web development",
13
13
  "frontend"
14
14
  ],
15
- "author": "Your Name",
15
+ "author": "Naxrul Ahmed",
16
16
  "license": "MIT",
17
+ "homepage": "https://oncss.devnax.com",
17
18
  "repository": {
18
19
  "type": "git",
19
- "url": "https://github.com/yourusername/oncss.git"
20
+ "url": "https://github.com/devnax/oncss.git"
20
21
  },
21
22
  "bugs": {
22
- "url": "https://github.com/yourusername/oncss/issues"
23
+ "url": "https://github.com/devnax/oncss/issues"
23
24
  },
24
25
  "dependencies": {
25
26
  "youid": "^1.0.13"
package/readme.md CHANGED
@@ -1,376 +1,940 @@
1
1
  <p align="center">
2
- <img width="120" src="https://raw.githubusercontent.com/devnax/oncss/main/logo.png" alt="ONCSS Logo">
2
+ <img width="120" src="https://raw.githubusercontent.com/devnax/oncss/main/logo.png" alt="ONCSS logo">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">ONCSS</h1>
6
6
 
7
- `oncss` is a CSS-in-JS library that provides developers with a powerful `css` function to style their web applications. It enables modern styling techniques, including nested selectors, responsive design, and dynamic keyframes, all while offering seamless integration with JavaScript frameworks like React.
8
-
9
- ---
7
+ `oncss` is a small CSS-in-JS library that generates scoped CSS from JavaScript or
8
+ TypeScript style objects. It supports nested selectors, custom breakpoints, media
9
+ and container queries, keyframes, global rules, aliases, and custom
10
+ property/value transforms.
10
11
 
11
12
  ## Installation
12
13
 
13
- Install the `oncss` package via npm:
14
-
15
14
  ```bash
16
15
  npm install oncss
17
16
  ```
18
17
 
19
- Import the `css` function in your project:
18
+ ```ts
19
+ import { css } from 'oncss';
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ ```ts
25
+ import { css } from 'oncss';
26
+
27
+ const button = css({
28
+ display: 'inline-flex',
29
+ alignItems: 'center',
30
+ padding: '10px 18px',
31
+ color: 'white',
32
+ backgroundColor: '#2563eb',
33
+ border: 0,
34
+ borderRadius: 8,
35
+
36
+ '&:hover': {
37
+ backgroundColor: '#1d4ed8',
38
+ },
39
+ });
20
40
 
21
- ```javascript
22
- import css from 'oncss';
41
+ const element = document.querySelector('button');
42
+ element?.classList.add(button.classname);
23
43
  ```
24
44
 
25
- ---
45
+ `css()` returns a style factory. By default it generates a class name and injects
46
+ the resulting stylesheet into `document.head`.
47
+
48
+ ```ts
49
+ button.classname; // generated name, for example "x..."
50
+ button.css; // generated CSS string
51
+ button.cssraw; // original style object
52
+ ```
26
53
 
27
- ## Core Concept: The `css` Function
54
+ > Use `factory.classname` (or `classList.add(factory.classname)`) rather than
55
+ > treating the factory as a string.
28
56
 
29
- The `css` function is the heart of `oncss`, designed to dynamically generate and inject CSS into your application. It supports:
57
+ ## How style objects work
30
58
 
31
- - **CSS Properties**: Use standard CSS properties and values.
32
- - **Nested Selectors**: Apply styles to child elements or states using `&`.
33
- - **Media Queries**: Implement responsive designs with `@media` rules.
34
- - **Keyframes**: Create animations with `@keyframes`.
35
- - **Global Styles**: Apply styles globally with `@global`.
36
- - **Custom Breakpoints**: Define reusable breakpoints for responsiveness.
37
- - **Other At-Rules**: Utilize additional at-rules like `@container`, `@layer`, and `@supports`.
59
+ Properties use JavaScript CSS names such as `backgroundColor`, `fontSize`, and
60
+ `zIndex`. ONCSS converts camel-case names to CSS kebab-case names.
38
61
 
39
- ### Basic Example
62
+ ```ts
63
+ const card = css({
64
+ maxWidth: 480,
65
+ backgroundColor: '#fff',
66
+ boxShadow: '0 10px 30px rgba(0, 0, 0, 0.12)',
67
+ });
68
+ ```
69
+
70
+ Numeric values become pixels by default:
71
+
72
+ ```ts
73
+ css({
74
+ width: 320, // width:320px
75
+ marginTop: 16, // margin-top:16px
76
+ fontWeight: 700, // font-weight:700
77
+ opacity: 0.8, // opacity:0.8
78
+ zIndex: 10, // z-index:10
79
+ });
80
+ ```
81
+
82
+ Unitless handling also includes `line-height`, `flex`, `flex-grow`,
83
+ `flex-shrink`, `flex-basis`, `order`, `columns`, `perspective`, and
84
+ `stroke-dashoffset`. When a unit is not appropriate, provide an explicit string,
85
+ such as `'50%'`, `'1.5rem'`, or `'auto'`.
86
+
87
+ ## Selectors
88
+
89
+ Every nested selector starts with `&`. ONCSS replaces every `&` with the
90
+ generated class name before compiling the stylesheet.
91
+
92
+ ### Pseudo-classes and pseudo-elements
93
+
94
+ ```ts
95
+ const link = css({
96
+ color: '#2563eb',
40
97
 
41
- ```typescript
42
- const buttonStyles = css({
43
- backgroundColor: 'blue',
44
- color: 'white',
45
- padding: '10px 20px',
46
- borderRadius: '5px',
47
98
  '&:hover': {
48
- backgroundColor: 'darkblue',
99
+ color: '#1d4ed8',
49
100
  },
50
- '@media (min-width: 768px)': {
51
- padding: '15px 30px',
101
+
102
+ '&:focus-visible': {
103
+ outline: '2px solid #2563eb',
104
+ outlineOffset: 3,
105
+ },
106
+
107
+ '&::before': {
108
+ content: '"→ "',
109
+ },
110
+ });
111
+ ```
112
+
113
+ ### Descendants and combinators
114
+
115
+ Include a space, combinator, or attribute selector after `&` exactly as you
116
+ would in CSS:
117
+
118
+ ```ts
119
+ const article = css({
120
+ '& h2': {
121
+ marginTop: 0,
122
+ },
123
+
124
+ '& > img': {
125
+ display: 'block',
126
+ width: '100%',
127
+ },
128
+
129
+ '& input:checked + span': {
130
+ color: '#16a34a',
131
+ },
132
+
133
+ '&[data-size="large"]': {
134
+ padding: 32,
52
135
  },
53
136
  });
137
+ ```
138
+
139
+ ### Deep selector nesting
140
+
141
+ Selector blocks can contain other selector blocks. Nesting is useful for
142
+ component states that also affect descendants.
143
+
144
+ ```ts
145
+ const menu = css({
146
+ color: '#334155',
147
+
148
+ '&:hover': {
149
+ color: '#0f172a',
150
+
151
+ '& .icon': {
152
+ transform: 'translateX(4px)',
153
+ },
54
154
 
55
- console.log(buttonStyles);
155
+ '&::after': {
156
+ opacity: 1,
157
+ },
158
+ },
159
+ });
56
160
  ```
57
161
 
58
- ---
162
+ The nested `& .icon` rule is scoped beneath the parent component's `:hover`
163
+ state because nested levels continue from the current generated selector.
59
164
 
60
- ## Configuration Options
165
+ ### Selector mode
61
166
 
62
- The `css` function can be customized through an options object:
167
+ The `selector` option controls the prefix applied to the generated name. The
168
+ default is a class selector (`"."`).
63
169
 
64
- ### Available Properties
170
+ ```ts
171
+ const classStyle = css(
172
+ { color: 'red' },
173
+ { selector: '.' },
174
+ );
175
+ // .x... { color:red; }
65
176
 
66
- | Property | Type | Description |
67
- | ------------- | ---------- | ------------------------------------------------------------------------------------------------- |
68
- | `classPrefix` | `string` | Adds a prefix to generated class names. |
69
- | `breakpoints` | `object` | Custom breakpoints for responsive designs. |
70
- | `aliases` | `object` | Custom shorthand properties for CSS rules. |
71
- | `injectStyle` | `boolean` | Controls whether styles are auto-injected. |
72
- | `skipProps` | `function` | Filters out unwanted properties. Receives `prop`, `value`, and `dept` as arguments. |
73
- | `getValue` | `function` | Transforms property values dynamically. Receives `value`, `prop`, `css`, and `dept` as arguments. |
74
- | `getProps` | `function` | Customizes specific property handling. Receives `prop`, `value`, `css`, and `dept` as arguments. |
177
+ const idStyle = css(
178
+ { color: 'red' },
179
+ { selector: '#' },
180
+ );
181
+ // #x... { color:red; }
182
+ ```
75
183
 
76
- ### Example with Options
184
+ For ID mode, assign the generated name to `id`:
77
185
 
78
- ```typescript
79
- const styles = css({
80
- fontSize: 16,
81
- padding: 10,
82
- }, {
83
- classPrefix: 'myprefix',
84
- breakpoints: {
85
- sm: 480,
86
- md: 768,
87
- lg: 1024,
186
+ ```tsx
187
+ const panel = css({ padding: 20 }, { selector: '#' });
188
+
189
+ function Panel() {
190
+ return <section id={panel.classname}>Panel</section>;
191
+ }
192
+ ```
193
+
194
+ You can also provide another selector prefix:
195
+
196
+ ```ts
197
+ const dataStyle = css(
198
+ { color: 'rebeccapurple' },
199
+ { selector: 'section.' },
200
+ );
201
+ // section.x... { color:rebeccapurple; }
202
+ ```
203
+
204
+ Use this only when your final generated selector is valid; ONCSS performs no
205
+ selector validation. For ordinary styling, keep the default class mode.
206
+
207
+ ## Responsive values and breakpoints
208
+
209
+ A property value can be an object whose keys are numeric breakpoints or keys
210
+ from the `breakpoints` option. These values compile to `min-width` media
211
+ queries.
212
+
213
+ ```ts
214
+ const layout = css({
215
+ display: 'grid',
216
+ gridTemplateColumns: '1fr',
217
+ gap: 12,
218
+
219
+ gridColumn: {
220
+ 480: 'span 1',
221
+ 768: 'span 2',
88
222
  },
89
223
  });
90
224
  ```
91
225
 
92
- ### Using Breakpoints
226
+ This generates the equivalent of:
93
227
 
94
- You can use the defined breakpoints in your styles to create responsive designs:
228
+ ```css
229
+ .x... {
230
+ display: grid;
231
+ grid-template-columns: 1fr;
232
+ gap: 12px;
233
+ }
234
+
235
+ @media (min-width: 480px) {
236
+ .x... {
237
+ grid-column: span 1;
238
+ }
239
+ }
240
+ ```
95
241
 
96
- ```typescript
97
- const responsiveStyles = css({
98
- fontSize: 14,
99
- padding: {
100
- sm: 12,
101
- lg: 24
242
+ Named breakpoints are easier to reuse:
243
+
244
+ ```ts
245
+ const responsive = css(
246
+ {
247
+ fontSize: {
248
+ sm: 14,
249
+ md: 16,
250
+ lg: 18,
251
+ },
252
+ padding: {
253
+ sm: 12,
254
+ md: 20,
255
+ lg: 28,
256
+ },
102
257
  },
103
-
104
- }, {
105
- breakpoints: {
106
- sm: 480,
107
- md: 768,
108
- lg: 1024,
258
+ {
259
+ breakpoints: {
260
+ sm: 480,
261
+ md: 768,
262
+ lg: 1024,
263
+ },
109
264
  },
110
- });
265
+ );
111
266
  ```
112
267
 
113
- ---
268
+ Responsive value rules:
114
269
 
115
- ## React Integration
270
+ - Every breakpoint is a `min-width` query in pixels.
271
+ - Numeric keys are supported directly.
272
+ - A named key must exist in `options.breakpoints`.
273
+ - Keep breakpoints in ascending order in the object when possible. This makes
274
+ the source and emitted CSS easier to reason about.
275
+ - Responsive objects are values for one property. Use an `@media ...` block
276
+ when multiple properties need to change together.
116
277
 
117
- oncss integrates seamlessly with React. Simply pass the generated class name to your component.
278
+ ## Explicit media queries
118
279
 
119
- ### React Example
280
+ Use an `@media` key when an entire group of declarations should respond to a
281
+ condition:
120
282
 
121
- ```typescript
122
- import React from 'react';
123
- import css from 'oncss';
283
+ ```ts
284
+ const hero = css({
285
+ padding: 24,
286
+ textAlign: 'center',
124
287
 
125
- const buttonStyle = css({
126
- backgroundColor: 'green',
127
- color: 'white',
128
- padding: '10px 20px',
129
- borderRadius: '8px',
130
- '&:hover': {
131
- backgroundColor: 'darkgreen',
288
+ '@media (min-width: 768px)': {
289
+ padding: 48,
290
+ textAlign: 'left',
291
+ },
292
+
293
+ '@media (prefers-reduced-motion: reduce)': {
294
+ animation: 'none',
295
+ scrollBehavior: 'auto',
132
296
  },
133
297
  });
298
+ ```
134
299
 
135
- function Button() {
136
- return <button className={buttonStyle.toString()}>Click Me</button>;
137
- }
300
+ Media blocks can also include nested selectors:
301
+
302
+ ```ts
303
+ const navigation = css({
304
+ '& .links': {
305
+ display: 'none',
306
+ },
138
307
 
139
- export default Button;
308
+ '@media (min-width: 900px)': {
309
+ '& .links': {
310
+ display: 'flex',
311
+ gap: 20,
312
+ },
313
+
314
+ '& .menu-button': {
315
+ display: 'none',
316
+ },
317
+ },
318
+ });
319
+ ```
320
+
321
+ The at-rule type and condition become the emitted CSS key verbatim:
322
+
323
+ ```ts
324
+ '@media screen and (min-width: 1200px)'
140
325
  ```
141
326
 
142
- ---
327
+ ## Other at-rules
143
328
 
144
- ## Advanced Features
329
+ `@container`, `@layer`, and `@supports` blocks use the same shape as media
330
+ queries.
145
331
 
146
- ### Nested Selectors
332
+ ### Container queries
147
333
 
148
- Apply styles to child elements or pseudo-classes:
334
+ ```ts
335
+ const card = css({
336
+ containerType: 'inline-size',
149
337
 
150
- ```typescript
151
- const cardStyles = css({
152
- padding: '20px',
153
- border: '1px solid #ccc',
154
- '& h1': {
155
- fontSize: '24px',
156
- margin: 0,
338
+ '@container (min-width: 420px)': {
339
+ display: 'grid',
340
+ gridTemplateColumns: '120px 1fr',
157
341
  },
158
- '&:hover': {
159
- boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
342
+ });
343
+ ```
344
+
345
+ ### Feature queries
346
+
347
+ ```ts
348
+ const grid = css({
349
+ display: 'block',
350
+
351
+ '@supports (display: grid)': {
352
+ display: 'grid',
160
353
  },
161
354
  });
162
355
  ```
163
356
 
164
- ### Media Queries
357
+ ### Layers
165
358
 
166
- Easily add responsive styles:
359
+ ```ts
360
+ const component = css({
361
+ '@layer components': {
362
+ padding: 16,
363
+ borderRadius: 8,
364
+ },
365
+ });
366
+ ```
167
367
 
168
- ```typescript
169
- const responsiveStyles = css({
170
- fontSize: '14px',
171
- '@media (min-width: 768px)': {
172
- fontSize: '18px',
368
+ The supported TypeScript at-rule prefixes are `@media`, `@container`, `@layer`,
369
+ and `@supports`, each followed by a space and their condition or name.
370
+
371
+ ## Keyframes
372
+
373
+ Define animations with an `@keyframes <name>` key. Steps can use `from`, `to`,
374
+ or percentage keys.
375
+
376
+ ```ts
377
+ const toast = css({
378
+ '@keyframes toast-in': {
379
+ from: {
380
+ opacity: 0,
381
+ transform: 'translateY(12px)',
382
+ },
383
+ '60%': {
384
+ opacity: 1,
385
+ transform: 'translateY(-2px)',
386
+ },
387
+ to: {
388
+ opacity: 1,
389
+ transform: 'translateY(0)',
390
+ },
173
391
  },
392
+
393
+ animation: 'toast-in 240ms ease-out both',
174
394
  });
175
395
  ```
176
396
 
177
- ### Keyframes
397
+ Generated keyframes are included with each style factory. ONCSS does not scope
398
+ or rename the animation name automatically, so choose globally unique names in
399
+ shared applications.
178
400
 
179
- Define and use animations:
401
+ A keyframe step accepts regular CSS declarations but not responsive breakpoint
402
+ objects:
180
403
 
181
- ```typescript
182
- const animationStyles = css({
183
- '@keyframes fadeIn': {
184
- from: { opacity: 0 },
404
+ ```ts
405
+ const valid = css({
406
+ '@keyframes pulse': {
407
+ from: { opacity: 0.6 },
185
408
  to: { opacity: 1 },
186
409
  },
187
- animation: 'fadeIn 2s ease-in-out',
188
410
  });
189
411
  ```
190
412
 
191
- ### Global Styles
413
+ For more complex motion, combine an animation with a media preference:
414
+
415
+ ```ts
416
+ const spinner = css({
417
+ animation: 'spin 800ms linear infinite',
192
418
 
193
- Apply global styles effortlessly:
419
+ '@keyframes spin': {
420
+ to: {
421
+ transform: 'rotate(360deg)',
422
+ },
423
+ },
194
424
 
195
- ```typescript
196
- const globalStyles = css({
425
+ '@media (prefers-reduced-motion: reduce)': {
426
+ animationDuration: '0.001ms',
427
+ animationIterationCount: 1,
428
+ },
429
+ });
430
+ ```
431
+
432
+ ## Global styles
433
+
434
+ `@global` emits each child selector without class scoping. Use it for resets,
435
+ page-level defaults, and non-component styles.
436
+
437
+ ```ts
438
+ css({
197
439
  '@global': {
440
+ ':root': {
441
+ color: '#0f172a',
442
+ backgroundColor: '#ffffff',
443
+ fontFamily: 'system-ui, sans-serif',
444
+ },
445
+
446
+ '*, *::before, *::after': {
447
+ boxSizing: 'border-box',
448
+ },
449
+
198
450
  body: {
199
451
  margin: 0,
200
- fontFamily: 'Arial, sans-serif',
201
452
  },
202
- a: {
203
- color: 'blue',
204
- textDecoration: 'none',
453
+
454
+ 'a:hover': {
455
+ color: '#1d4ed8',
205
456
  },
206
457
  },
207
458
  });
208
459
  ```
209
460
 
210
- ---
461
+ Global selectors are literal CSS selectors; do not prefix them with `&`.
211
462
 
212
- ## Supported At-Rules
463
+ ## Aliases
213
464
 
214
- `oncss` supports various CSS at-rules to enhance your styling capabilities. Here is a list of supported at-rules with descriptions:
465
+ Aliases expand a custom property into one or more standard properties. The
466
+ alias receives the supplied value and returns a style object.
215
467
 
216
- | At-Rule | Description |
217
- | ------------ | ---------------------------------------------------------------------------- |
218
- | `@media` | Used for applying styles based on media queries for responsive design. |
219
- | `@keyframes` | Defines animations that can be applied to elements. |
220
- | `@global` | Applies styles globally across the entire application. |
221
- | `@container` | Used for container queries to apply styles based on container size. |
222
- | `@layer` | Defines style layers to control the order of style application. |
223
- | `@supports` | Applies styles based on the support of specific CSS features in the browser. |
468
+ ```ts
469
+ import { css, type OptionAliases } from 'oncss';
224
470
 
225
- ---
471
+ type Aliases = {
472
+ m: number;
473
+ px: number;
474
+ };
226
475
 
227
- ## Server-Side Styling
476
+ const aliases: OptionAliases<Aliases> = {
477
+ m: (value) => ({ margin: value }),
478
+ px: (value) => ({
479
+ paddingLeft: value,
480
+ paddingRight: value,
481
+ }),
482
+ };
228
483
 
229
- `oncss` supports server-side rendering (SSR) by utilizing the `CSSFactory` to store and manage generated CSS styles. This allows you to extract and inject styles into your server-rendered HTML.
484
+ const box = css(
485
+ {
486
+ m: 12,
487
+ px: 20,
488
+ backgroundColor: '#f8fafc',
489
+ },
490
+ { aliases },
491
+ );
492
+ ```
230
493
 
231
- ### Example with React
494
+ Aliases are expanded before normal declarations are emitted. The recursive
495
+ expansion disables aliases for the returned style object, so aliases should
496
+ return standard CSS properties or rules rather than other aliases.
232
497
 
233
- Here's an example of how to use `oncss` for server-side rendering with React:
498
+ ## Custom transforms
234
499
 
235
- ```tsx
236
- import React from 'react';
237
- import ReactDOMServer from 'react-dom/server';
238
- import css, { CSSFactory } from 'oncss';
500
+ The options hooks provide low-level control for integrating design tokens,
501
+ filtering properties, and adapting values.
239
502
 
240
- const buttonStyle = css({
241
- backgroundColor: 'blue',
242
- color: 'white',
243
- padding: '10px 20px',
244
- borderRadius: '5px',
245
- '&:hover': {
246
- backgroundColor: 'darkblue',
503
+ ### `getValue`
504
+
505
+ `getValue` receives `(property, value, fullStyleObject, depth)` and returns the
506
+ value ONCSS should emit:
507
+
508
+ ```ts
509
+ const themed = css(
510
+ {
511
+ color: 'text.primary',
512
+ padding: 'space.4',
247
513
  },
248
- });
514
+ {
515
+ getValue: (property, value) => {
516
+ if (property === 'color' && value === 'text.primary') {
517
+ return '#0f172a';
518
+ }
519
+ if (property === 'padding' && value === 'space.4') {
520
+ return 16;
521
+ }
522
+ return value;
523
+ },
524
+ },
525
+ );
526
+ ```
249
527
 
250
- function Button() {
251
- return <button className={buttonStyle}>Click Me</button>;
252
- }
528
+ Because numbers are transformed to pixels later, returning `16` produces
529
+ `padding:16px`.
530
+
531
+ ### `getProps`
253
532
 
254
- const App = () => (
255
- <div>
256
- <Button />
257
- </div>
533
+ `getProps` receives `(property, value, fullStyleObject, depth)`. Return a style
534
+ object to replace the handling of that property, or return `undefined` to use
535
+ normal processing.
536
+
537
+ ```ts
538
+ const layout = css(
539
+ {
540
+ inset: 24,
541
+ },
542
+ {
543
+ getProps: (property, value) => {
544
+ if (property === 'inset') {
545
+ return {
546
+ top: value,
547
+ right: value,
548
+ bottom: value,
549
+ left: value,
550
+ };
551
+ }
552
+ },
553
+ },
258
554
  );
555
+ ```
259
556
 
260
- // Render the component to a string
261
- const html = ReactDOMServer.renderToString(<App />);
557
+ When `getProps` returns an object, its recursive expansion does not call
558
+ `getProps` again.
262
559
 
263
- let styles: any = Array.from(CSSFactory.values()).map((style) => {
264
- return `<style data-href="${style.classname}">${style.css}</style>`
265
- });
560
+ ### `skipProps`
266
561
 
267
- // Inject the styles into the HTML
268
- const fullHtml = `
269
- <!DOCTYPE html>
270
- <html lang="en">
271
- <head>
272
- <meta charset="UTF-8">
273
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
274
- <title>SSR with oncss</title>
275
- ${styles}
276
- </head>
277
- <body>
278
- <div id="root">${html}</div>
279
- </body>
280
- </html>
281
- `;
562
+ Return `true` to omit a property. Skipped properties and the selector they
563
+ belonged to are available on the returned factory:
564
+
565
+ ```ts
566
+ const safeStyle = css(
567
+ {
568
+ color: 'red',
569
+ unsupportedExperimentalProperty: 'value',
570
+ },
571
+ {
572
+ skipProps: (property) =>
573
+ property.startsWith('unsupported'),
574
+ },
575
+ );
282
576
 
283
- console.log(fullHtml);
577
+ console.log(safeStyle.skiped);
284
578
  ```
285
579
 
286
- In this example, the `CSSFactory` is used to collect all generated CSS styles during the server-side rendering process. These styles are then injected into the HTML document, ensuring that the styles are applied correctly when the page is loaded in the browser.
580
+ All hooks receive a `dept` (depth) number. Root declarations start at `1`, and
581
+ the depth increases as nested selectors or at-rules are processed.
582
+
583
+ ## Configuration reference
287
584
 
288
- ---
585
+ The options object is the second argument to `css()`:
289
586
 
290
- ## Utility Functions
587
+ ```ts
588
+ const factory = css(styleObject, options);
589
+ ```
291
590
 
292
- ### CSSFactory
591
+ | Option | Type | Default | Purpose |
592
+ | --- | --- | --- | --- |
593
+ | `classPrefix` | `string` | `''` | Prefixes the generated `classname`. |
594
+ | `selector` | `string` | `'.'` | Prefix added before the generated name in CSS. |
595
+ | `breakpoints` | `Record<string, number>` | none | Resolves named responsive property values to pixel widths. |
596
+ | `aliases` | alias map | none | Expands custom properties into style objects. |
597
+ | `injectStyle` | `boolean` | `true` | Controls automatic style injection. |
598
+ | `container` | `Document \| HTMLElement` | `document` | Chooses where the style tag is inserted. |
599
+ | `cacheId` | `string` | `'global'` | Selects a named cache group. |
600
+ | `skipProps` | function | none | Omits selected declarations. |
601
+ | `getValue` | function | none | Transforms declaration values. |
602
+ | `getProps` | function | none | Replaces declaration handling with another style object. |
603
+
604
+ For class naming, `classPrefix` affects the generated name while `selector`
605
+ affects how that name is addressed by the stylesheet:
606
+
607
+ ```ts
608
+ const button = css(
609
+ { color: 'white' },
610
+ {
611
+ classPrefix: 'button-',
612
+ selector: '.',
613
+ },
614
+ );
293
615
 
294
- `CSSFactory` is a global cache for storing generated CSS styles. It helps in reusing styles and avoiding redundant style generation.
616
+ button.classname.startsWith('button-'); // true
617
+ ```
295
618
 
296
- ### formatCSSProp
619
+ ## Style factory API
297
620
 
298
- `formatCSSProp` is a utility function that converts camelCase CSS property names to kebab-case.
621
+ ```ts
622
+ const factory = css({ color: 'red' });
623
+ ```
299
624
 
300
- ```typescript
301
- import { formatCSSProp } from 'oncss';
625
+ | Property | Description |
626
+ | --- | --- |
627
+ | `classname` | Generated class or ID name. |
628
+ | `css` | Generated CSS string. |
629
+ | `cssraw` | Original style object. |
630
+ | `cachekey` | Key used to reuse the generated factory. |
631
+ | `cacheId` | Name of the cache containing the factory. |
632
+ | `cache` | `true` when a previous factory was reused for the request. |
633
+ | `skiped` | Properties omitted by `skipProps`, grouped by selector. |
634
+ | `inject()` | Append or populate the factory's style tag. |
635
+ | `refresh()` | Remove the current style tag and inject the CSS again. |
636
+ | `deleteStyle()` | Remove only the injected style tag. |
637
+ | `getStyleTag()` | Return the injected `style` element, or `null`. |
638
+ | `delete()` | Remove the factory from the cache and remove its style tag. |
639
+
640
+ ### Manual injection
641
+
642
+ Disable automatic injection when you need to collect or control CSS output:
643
+
644
+ ```ts
645
+ const button = css(
646
+ { backgroundColor: '#2563eb' },
647
+ { injectStyle: false },
648
+ );
302
649
 
303
- const formattedProp = formatCSSProp('backgroundColor');
304
- console.log(formattedProp); // 'background-color'
650
+ console.log(button.css);
651
+ button.inject();
305
652
  ```
306
653
 
307
- ### formatCSSValue
654
+ ### Target document or element
308
655
 
309
- `formatCSSValue` is a utility function that formats CSS values, adding units like `px` where necessary.
656
+ Use `container` to inject into an iframe document, a shadow-root host element,
657
+ or another owned HTML element.
310
658
 
311
- ```typescript
312
- import { formatCSSValue } from 'oncss';
659
+ ```ts
660
+ const iframe = document.querySelector('iframe');
661
+ const iframeDocument = iframe?.contentDocument;
313
662
 
314
- const formattedValue = formatCSSValue('width', 100);
315
- console.log(formattedValue); // '100px'
663
+ if (iframeDocument) {
664
+ css(
665
+ { color: 'tomato' },
666
+ { container: iframeDocument },
667
+ );
668
+ }
316
669
  ```
317
670
 
318
- ---
671
+ ```ts
672
+ const host = document.querySelector('#shadow-host') as HTMLElement;
319
673
 
320
- ## TypeScript Integration
674
+ css(
675
+ { color: 'tomato' },
676
+ { container: host },
677
+ );
678
+ ```
321
679
 
322
- `oncss` provides full TypeScript support, allowing you to define types for your CSS properties and options.
680
+ A `Document` injects into its `<head>`. An `HTMLElement` receives the style tag
681
+ directly, allowing styles to be placed in a specific container.
323
682
 
324
- ### Defining CSS Properties
683
+ ## Caching
325
684
 
326
- You can define the types for your CSS properties using the `CSSProps` type:
685
+ ONCSS caches factories by `cacheId` and a generated style key. The key includes
686
+ the source style object and `selector`. Repeated equivalent calls can therefore
687
+ reuse the same factory.
327
688
 
328
- ```typescript
329
- import { CSSProps } from 'oncss';
689
+ ```ts
690
+ const first = css({ color: 'red' }, { cacheId: 'dashboard' });
691
+ const second = css({ color: 'red' }, { cacheId: 'dashboard' });
330
692
 
331
- interface MyAliases {
332
- customColor?: string;
333
- }
693
+ first === second; // true
694
+ ```
334
695
 
335
- const styles: CSSProps<MyAliases, 'sm' | 'md' | 'lg'> = {
336
- backgroundColor: 'blue',
337
- customColor: 'red',
338
- '@media (min-width: 768px)': {
339
- backgroundColor: 'green',
696
+ Use different `cacheId` values to isolate groups of generated styles:
697
+
698
+ ```ts
699
+ const appStyle = css(
700
+ { color: 'red' },
701
+ { cacheId: 'main-app' },
702
+ );
703
+
704
+ const previewStyle = css(
705
+ { color: 'red' },
706
+ { cacheId: 'preview' },
707
+ );
708
+ ```
709
+
710
+ The cache API is exported for advanced use:
711
+
712
+ ```ts
713
+ import { ONCSS_CACHE } from 'oncss';
714
+
715
+ const group = ONCSS_CACHE.caches().get('main-app');
716
+
717
+ ONCSS_CACHE.delete('main-app', appStyle.cachekey);
718
+ ```
719
+
720
+ Changing options such as breakpoints, aliases, or transform hooks without
721
+ changing the style object or selector can still reuse the prior cache entry.
722
+ Use a distinct `cacheId` when the same style source is compiled with materially
723
+ different options.
724
+
725
+ ## Server-side rendering
726
+
727
+ With no browser `window`, ONCSS still generates factories and CSS but cannot
728
+ inject a style element. Collect the generated factories from the cache and
729
+ render their `css` into your document head.
730
+
731
+ ```tsx
732
+ import { renderToString } from 'react-dom/server';
733
+ import { css, ONCSS_CACHE } from 'oncss';
734
+
735
+ const button = css(
736
+ {
737
+ color: 'white',
738
+ backgroundColor: '#2563eb',
739
+ '&:hover': {
740
+ backgroundColor: '#1d4ed8',
741
+ },
340
742
  },
341
- };
743
+ {
744
+ cacheId: 'server-render',
745
+ injectStyle: false,
746
+ },
747
+ );
748
+
749
+ const html = renderToString(
750
+ <button className={button.classname}>Save</button>,
751
+ );
752
+
753
+ const styles = Array.from(
754
+ ONCSS_CACHE.caches().get('server-render')?.values() ?? [],
755
+ )
756
+ .map((factory) =>
757
+ `<style data-href="${factory.classname}">${factory.css}</style>`,
758
+ )
759
+ .join('');
760
+
761
+ const documentHtml = `
762
+ <!doctype html>
763
+ <html>
764
+ <head>${styles}</head>
765
+ <body><div id="root">${html}</div></body>
766
+ </html>
767
+ `;
768
+ ```
769
+
770
+ Use a request-specific or intentionally scoped `cacheId` if styles should not
771
+ leak between SSR requests. Also apply your existing HTML escaping policy before
772
+ inserting application-derived content into an HTML response.
773
+
774
+ ## React
775
+
776
+ Pass `factory.classname` to `className`:
777
+
778
+ ```tsx
779
+ import { css } from 'oncss';
780
+
781
+ const buttonStyle = css({
782
+ padding: '10px 18px',
783
+ color: 'white',
784
+ backgroundColor: '#2563eb',
785
+ border: 0,
786
+ borderRadius: 8,
787
+
788
+ '&:hover': {
789
+ backgroundColor: '#1d4ed8',
790
+ },
791
+ });
792
+
793
+ export function Button() {
794
+ return (
795
+ <button type="button" className={buttonStyle.classname}>
796
+ Save
797
+ </button>
798
+ );
799
+ }
342
800
  ```
343
801
 
344
- ### Using Options with Types
802
+ For styles generated at module scope, ONCSS injects and caches them once. For
803
+ dynamic styles, call `css()` in response to the relevant state and reuse cache
804
+ IDs where appropriate.
805
+
806
+ ## Utility functions
345
807
 
346
- You can also define types for the options object:
808
+ ### `formatCSSProp`
809
+
810
+ ```ts
811
+ import { formatCSSProp } from 'oncss';
812
+
813
+ formatCSSProp('backgroundColor'); // 'background-color'
814
+ ```
347
815
 
348
- ```typescript
349
- import { CSSOptionProps } from 'oncss';
816
+ ### `formatCSSValue`
350
817
 
351
- const options: CSSOptionProps<MyAliases, 'sm' | 'md' | 'lg'> = {
352
- classPrefix: 'myprefix',
818
+ ```ts
819
+ import { formatCSSValue } from 'oncss';
820
+
821
+ formatCSSValue('width', 100); // '100px'
822
+ formatCSSValue('opacity', 0.5); // 0.5
823
+ ```
824
+
825
+ ## TypeScript
826
+
827
+ The package exports the main CSS and option types:
828
+
829
+ ```ts
830
+ import {
831
+ css,
832
+ type CSSOptionProps,
833
+ type CSSProps,
834
+ type OptionAliases,
835
+ } from 'oncss';
836
+
837
+ type Aliases = {
838
+ m: number;
839
+ };
840
+
841
+ type Breakpoint = 'sm' | 'md' | 'lg';
842
+
843
+ const aliases: OptionAliases<Aliases> = {
844
+ m: (value) => ({ margin: value }),
845
+ };
846
+
847
+ const options: CSSOptionProps<Aliases, Breakpoint> = {
848
+ aliases,
353
849
  breakpoints: {
354
850
  sm: 480,
355
851
  md: 768,
356
852
  lg: 1024,
357
853
  },
358
- aliases: {
359
- customColor: (value) => ({ color: value }),
854
+ };
855
+
856
+ const styles: CSSProps<Aliases, Breakpoint> = {
857
+ m: 8,
858
+ color: 'red',
859
+ fontSize: {
860
+ sm: 14,
861
+ lg: 18,
360
862
  },
361
863
  };
362
864
 
363
- const styles = css({
364
- fontSize: 16,
365
- padding: 10,
366
- }, options);
865
+ const generated = css(styles, options);
367
866
  ```
368
867
 
369
- ---
868
+ ## Complete example
370
869
 
371
- ## Conclusion
870
+ ```tsx
871
+ import { css, type OptionAliases } from 'oncss';
372
872
 
373
- `oncss` simplifies styling for modern web applications. Its robust feature set, from responsive design to keyframe animations, makes it an invaluable tool for developers.
873
+ type Aliases = {
874
+ px: number;
875
+ radius: number;
876
+ };
877
+
878
+ const aliases: OptionAliases<Aliases> = {
879
+ px: (value) => ({
880
+ paddingLeft: value,
881
+ paddingRight: value,
882
+ }),
883
+ radius: (value) => ({
884
+ borderRadius: value,
885
+ }),
886
+ };
887
+
888
+ const notification = css(
889
+ {
890
+ px: 16,
891
+ radius: 10,
892
+ paddingTop: 12,
893
+ paddingBottom: 12,
894
+ color: '#0f172a',
895
+ backgroundColor: '#f8fafc',
896
+ boxShadow: '0 10px 30px rgba(15, 23, 42, 0.12)',
897
+ animation: 'notification-enter 220ms ease-out both',
898
+
899
+ '&:hover': {
900
+ backgroundColor: '#f1f5f9',
901
+ },
902
+
903
+ '@media (min-width: 768px)': {
904
+ px: 24,
905
+ '& .actions': {
906
+ display: 'flex',
907
+ },
908
+ },
909
+
910
+ '@keyframes notification-enter': {
911
+ from: {
912
+ opacity: 0,
913
+ transform: 'translateY(8px)',
914
+ },
915
+ to: {
916
+ opacity: 1,
917
+ transform: 'translateY(0)',
918
+ },
919
+ },
920
+ },
921
+ {
922
+ aliases,
923
+ breakpoints: {
924
+ md: 768,
925
+ },
926
+ },
927
+ );
928
+
929
+ export function Notification() {
930
+ return (
931
+ <div className={notification.classname}>
932
+ Saved successfully
933
+ <div className="actions">Actions</div>
934
+ </div>
935
+ );
936
+ }
937
+ ```
374
938
 
375
939
  ## Author
376
940
 
@@ -388,10 +952,10 @@ const styles = css({
388
952
  </tr>
389
953
  </table>
390
954
 
391
- <h2>⚡️ Where to find me</h2>
955
+ <h2>Where to find me</h2>
392
956
 
393
- <p><a target="_blank" href="mailto:devnaxrul@gmail.com" style="display: inline-block;"><img src="https://img.shields.io/badge/-Email-05122A?style=for-the-badge&logo=gmail&logoColor=white&color=orange" alt="gmail" /></a>
394
- <a target="_blank" href="https://twitter.com/devnaxx" style="display: inline-block;"><img src="https://img.shields.io/badge/twitter-x?style=for-the-badge&logo=x&logoColor=white&color=%230f1419" alt="twitter" /></a>
395
- <a target="_blank" href="https://www.linkedin.com/in/devnax" style="display: inline-block;"><img src="https://img.shields.io/badge/linkedin-logo?style=for-the-badge&logo=linkedin&logoColor=white&color=%230a77b6" alt="linkedin" /></a>
396
- <a target="_blank" href="https://www.facebook.com/devnax" style="display: inline-block;"><img src="https://img.shields.io/badge/facebook-logo?style=for-the-badge&logo=facebook&logoColor=white&color=%230866ff" alt="facebook" /></a>
397
- <a target="_blank" href="https://www.instagram.com/devnaxx" style="display: inline-block;"><img src="https://img.shields.io/badge/instagram-logo?style=for-the-badge&logo=instagram&logoColor=white&color=%23F35369" alt="instagram" /></a></p>
957
+ <p><a target="_blank" href="mailto:devnaxrul@gmail.com"><img src="https://img.shields.io/badge/-Email-05122A?style=for-the-badge&logo=gmail&logoColor=white&color=orange" alt="Email" /></a>
958
+ <a target="_blank" href="https://twitter.com/devnaxx"><img src="https://img.shields.io/badge/twitter-x?style=for-the-badge&logo=x&logoColor=white&color=%230f1419" alt="Twitter" /></a>
959
+ <a target="_blank" href="https://www.linkedin.com/in/devnax"><img src="https://img.shields.io/badge/linkedin-logo?style=for-the-badge&logo=linkedin&logoColor=white&color=%230a77b6" alt="LinkedIn" /></a>
960
+ <a target="_blank" href="https://www.facebook.com/devnax"><img src="https://img.shields.io/badge/facebook-logo?style=for-the-badge&logo=facebook&logoColor=white&color=%230866ff" alt="Facebook" /></a>
961
+ <a target="_blank" href="https://www.instagram.com/devnaxx"><img src="https://img.shields.io/badge/instagram-logo?style=for-the-badge&logo=instagram&logoColor=white&color=%23F35369" alt="Instagram" /></a></p>