0
# Utility Functions
1
2
Helper functions for CSS value conversion, dynamic style extraction, rule creation, and browser capability detection.
3
4
## Capabilities
5
6
### CSS Value Conversion
7
8
Convert JavaScript values to valid CSS strings with proper formatting and units.
9
10
```javascript { .api }
11
/**
12
* Convert JavaScript values to CSS strings
13
* @param value - JavaScript value to convert
14
* @returns CSS string representation
15
*/
16
function toCssValue(value: JssValue): string;
17
18
type JssValue =
19
| (string & {})
20
| (number & {})
21
| Array<string | number | Array<string | number> | '!important'>
22
| null
23
| false;
24
```
25
26
**Usage Examples:**
27
28
```javascript
29
import { toCssValue } from "jss";
30
31
// String values
32
console.log(toCssValue('red')); // "red"
33
console.log(toCssValue('10px')); // "10px"
34
35
// Number values
36
console.log(toCssValue(42)); // "42"
37
console.log(toCssValue(0)); // "0"
38
39
// Array values (space-separated)
40
console.log(toCssValue(['10px', '20px'])); // "10px 20px"
41
console.log(toCssValue([0, 'auto'])); // "0 auto"
42
43
// Nested arrays (comma-separated groups)
44
console.log(toCssValue([['10px', '20px'], ['30px', '40px']]));
45
// "10px 20px, 30px 40px"
46
47
// Important flag
48
console.log(toCssValue(['red', '!important'])); // "red !important"
49
50
// Falsy values
51
console.log(toCssValue(null)); // ""
52
console.log(toCssValue(false)); // ""
53
```
54
55
### Dynamic Style Extraction
56
57
Extract function-based styles from style objects for dynamic styling support.
58
59
```javascript { .api }
60
/**
61
* Extract function-based styles from a styles object
62
* @param styles - Styles object potentially containing functions
63
* @returns Object with only function-based styles, or null if none found
64
*/
65
function getDynamicStyles(styles: Styles): Styles | null;
66
67
type Styles<
68
Name extends string | number | symbol = string,
69
Props = unknown,
70
Theme = undefined
71
> = Record<
72
Name,
73
| JssStyle<Props, Theme>
74
| Array<JssStyle<Props, Theme>>
75
| string
76
| Func<Props, Theme, JssStyle<undefined, undefined> | string | null | undefined>
77
| MinimalObservable<JssStyle | string | null | undefined>
78
>;
79
```
80
81
**Usage Examples:**
82
83
```javascript
84
import { getDynamicStyles } from "jss";
85
86
// Mixed static and dynamic styles
87
const styles = {
88
button: {
89
padding: '10px', // static
90
background: 'blue' // static
91
},
92
text: (data) => ({ // dynamic function
93
color: data.theme === 'dark' ? 'white' : 'black',
94
fontSize: data.size || '14px'
95
}),
96
header: {
97
fontSize: '24px' // static
98
},
99
dynamic: (props) => ({ // dynamic function
100
width: props.width,
101
height: props.height
102
})
103
};
104
105
// Extract only dynamic styles
106
const dynamicOnly = getDynamicStyles(styles);
107
console.log(dynamicOnly);
108
// {
109
// text: (data) => ({ color: ..., fontSize: ... }),
110
// dynamic: (props) => ({ width: ..., height: ... })
111
// }
112
113
// No dynamic styles
114
const staticStyles = {
115
button: { background: 'red' },
116
text: { color: 'black' }
117
};
118
119
const noDynamic = getDynamicStyles(staticStyles);
120
console.log(noDynamic); // null
121
```
122
123
### Rule Creation Utility
124
125
Create individual CSS rules with specified options and configuration.
126
127
```javascript { .api }
128
/**
129
* Create a CSS rule with specified options
130
* @param name - Rule name/selector
131
* @param decl - Style declaration object
132
* @param options - Rule configuration options
133
* @returns Created Rule instance
134
*/
135
function createRule<D>(name: string, decl: JssStyle, options: RuleOptions): Rule;
136
137
interface RuleOptions {
138
selector?: string;
139
sheet?: StyleSheet;
140
index?: number;
141
parent?: ContainerRule | StyleSheet;
142
classes: Classes;
143
jss: Jss;
144
generateId: GenerateId;
145
Renderer: Renderer;
146
}
147
```
148
149
**Usage Example:**
150
151
```javascript
152
import { createRule } from "jss";
153
import jss from "jss";
154
155
// Create rule with basic options
156
const rule = createRule('myButton', {
157
background: 'blue',
158
color: 'white',
159
'&:hover': {
160
background: 'red'
161
}
162
}, {
163
classes: {},
164
jss: jss,
165
generateId: jss.generateId,
166
Renderer: jss.options.Renderer
167
});
168
169
console.log(rule.toString());
170
// Output: CSS string for the rule
171
```
172
173
### ID Generation
174
175
Create custom class name generators with configurable options.
176
177
```javascript { .api }
178
/**
179
* Create a function that generates unique identifiers for CSS rules
180
* @param options - ID generation configuration
181
* @returns Function that generates IDs for rules
182
*/
183
function createGenerateId(options?: CreateGenerateIdOptions): GenerateId;
184
185
interface CreateGenerateIdOptions {
186
/** Whether to minify generated class names */
187
minify?: boolean;
188
}
189
190
type GenerateId = (rule: Rule, sheet?: StyleSheet<string>) => string;
191
```
192
193
**Usage Examples:**
194
195
```javascript
196
import { createGenerateId } from "jss";
197
198
// Default ID generator
199
const generateId = createGenerateId();
200
201
// Minified ID generator
202
const minifiedGenerator = createGenerateId({ minify: true });
203
204
// Custom JSS instance with custom ID generator
205
import { create } from "jss";
206
207
const customJss = create({
208
createGenerateId: () => createGenerateId({ minify: true })
209
});
210
211
// Use with stylesheet
212
const sheet = customJss.createStyleSheet({
213
button: { background: 'blue' }
214
});
215
216
console.log(sheet.classes.button); // Minified class name like "a0"
217
```
218
219
### Browser Capability Detection
220
221
Detect browser support for CSS Typed Object Model (CSS-in-JS optimizations).
222
223
```javascript { .api }
224
/**
225
* Boolean constant indicating if browser supports CSS Typed Object Model
226
* @type True if CSSOM is supported, false otherwise
227
*/
228
const hasCSSTOMSupport: boolean;
229
```
230
231
**Usage Example:**
232
233
```javascript
234
import { hasCSSTOMSupport } from "jss";
235
236
// Check for CSSOM support
237
if (hasCSSTOMSupport) {
238
console.log('Browser supports CSS Typed Object Model');
239
// Can use optimized CSS value setting
240
} else {
241
console.log('Fallback to string-based CSS manipulation');
242
// Use traditional string-based CSS manipulation
243
}
244
245
// Conditional optimization
246
const sheet = jss.createStyleSheet({
247
optimized: {
248
// Styles that benefit from CSSOM
249
transform: hasCSSTOMSupport ?
250
'translateX(100px)' :
251
'translate(100px, 0)'
252
}
253
});
254
```
255
256
### Value Type Definitions
257
258
Type definitions for values accepted by JSS utility functions.
259
260
```javascript { .api }
261
/** Base type for CSS values in JSS */
262
type JssValue =
263
| (string & {}) // CSS strings
264
| (number & {}) // Numeric values
265
| Array<string | number | Array<string | number> | '!important'> // Arrays for multi-value
266
| null // Null removes property
267
| false; // False removes property
268
269
/** Function type for dynamic styles */
270
type Func<P, T, R> = T extends undefined ?
271
(data: P) => R :
272
(data: P & {theme: T}) => R;
273
274
/** Observable interface for reactive values */
275
interface MinimalObservable<T> {
276
subscribe(nextOrObserver: ((value: T) => void) | {next: (value: T) => void}): {
277
unsubscribe: () => void
278
}
279
}
280
```
281
282
### Advanced Utility Usage
283
284
Complex scenarios combining multiple utilities for advanced functionality.
285
286
**Custom CSS Processor:**
287
288
```javascript
289
import { toCssValue, getDynamicStyles, createGenerateId } from "jss";
290
291
function processCssValues(styles) {
292
const processed = {};
293
294
for (const [key, value] of Object.entries(styles)) {
295
if (typeof value === 'object' && !Array.isArray(value)) {
296
// Recursively process nested objects
297
processed[key] = processCssValues(value);
298
} else {
299
// Convert to CSS value
300
processed[key] = toCssValue(value);
301
}
302
}
303
304
return processed;
305
}
306
307
// Usage
308
const rawStyles = {
309
button: {
310
margin: [10, 20, 10, 20],
311
color: null, // Will be removed
312
border: ['1px', 'solid', 'red']
313
}
314
};
315
316
const processedStyles = processCssValues(rawStyles);
317
console.log(processedStyles);
318
// {
319
// button: {
320
// margin: "10 20 10 20",
321
// border: "1px solid red"
322
// // color omitted (was null)
323
// }
324
// }
325
```
326
327
**Dynamic Style Handler:**
328
329
```javascript
330
import { getDynamicStyles } from "jss";
331
332
class StylesManager {
333
constructor(jss, initialStyles) {
334
this.jss = jss;
335
this.staticStyles = { ...initialStyles };
336
this.dynamicStyles = getDynamicStyles(initialStyles);
337
this.sheet = null;
338
this.currentData = {};
339
}
340
341
update(data) {
342
this.currentData = { ...this.currentData, ...data };
343
344
if (this.dynamicStyles) {
345
// Compute dynamic styles with current data
346
const computedDynamic = {};
347
for (const [key, styleFn] of Object.entries(this.dynamicStyles)) {
348
computedDynamic[key] = styleFn(this.currentData);
349
}
350
351
// Merge with static styles
352
const allStyles = { ...this.staticStyles, ...computedDynamic };
353
354
// Update or create stylesheet
355
if (this.sheet) {
356
this.sheet.update(this.currentData);
357
} else {
358
this.sheet = this.jss.createStyleSheet(allStyles);
359
this.sheet.attach();
360
}
361
}
362
}
363
364
getClasses() {
365
return this.sheet ? this.sheet.classes : {};
366
}
367
}
368
369
// Usage
370
const stylesManager = new StylesManager(jss, {
371
button: {
372
padding: '10px' // static
373
},
374
text: (data) => ({ // dynamic
375
color: data.theme === 'dark' ? 'white' : 'black'
376
})
377
});
378
379
stylesManager.update({ theme: 'dark' });
380
const classes = stylesManager.getClasses();
381
```