or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdmiddleware.mdparser.mdserialization.mdtokenization.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Helper functions for string manipulation, array operations, CSS processing constants, and utility operations used throughout the Stylis library.

3

4

## Capabilities

5

6

### Constants and Enumerations

7

8

#### Vendor Prefix Constants

9

10

```javascript { .api }

11

const MS: string; // '-ms-' - Microsoft vendor prefix

12

const MOZ: string; // '-moz-' - Mozilla vendor prefix

13

const WEBKIT: string; // '-webkit-' - WebKit vendor prefix

14

```

15

16

#### Node Type Constants

17

18

```javascript { .api }

19

const COMMENT: string; // 'comm' - Comment node type identifier

20

const RULESET: string; // 'rule' - Ruleset node type identifier

21

const DECLARATION: string; // 'decl' - Declaration node type identifier

22

```

23

24

#### At-Rule Constants

25

26

```javascript { .api }

27

const PAGE: string; // '@page' - Page at-rule identifier

28

const MEDIA: string; // '@media' - Media query at-rule identifier

29

const IMPORT: string; // '@import' - Import at-rule identifier

30

const CHARSET: string; // '@charset' - Charset at-rule identifier

31

const VIEWPORT: string; // '@viewport' - Viewport at-rule identifier

32

const SUPPORTS: string; // '@supports' - Supports at-rule identifier

33

const DOCUMENT: string; // '@document' - Document at-rule identifier

34

const NAMESPACE: string; // '@namespace' - Namespace at-rule identifier

35

const KEYFRAMES: string; // '@keyframes' - Keyframes at-rule identifier

36

const FONT_FACE: string; // '@font-face' - Font-face at-rule identifier

37

const COUNTER_STYLE: string; // '@counter-style' - Counter-style at-rule identifier

38

const FONT_FEATURE_VALUES: string; // '@font-feature-values' - Font feature values at-rule identifier

39

const LAYER: string; // '@layer' - Layer at-rule identifier

40

const SCOPE: string; // '@scope' - Scope at-rule identifier

41

```

42

43

### Mathematical and Conversion Functions

44

45

#### Basic Math Operations

46

47

```javascript { .api }

48

const abs: function; // Math.abs - Return absolute value of number

49

const from: function; // String.fromCharCode - Convert character code to string

50

const assign: function; // Object.assign - Copy properties between objects

51

```

52

53

**Usage Examples:**

54

55

```javascript

56

import { abs, from, assign } from 'stylis';

57

58

// Absolute value

59

const distance = abs(-10); // 10

60

61

// Character code conversion

62

const character = from(65); // 'A'

63

64

// Object property assignment

65

const merged = assign({}, { color: 'red' }, { fontSize: '14px' });

66

// { color: 'red', fontSize: '14px' }

67

```

68

69

### String Manipulation Functions

70

71

#### Hash Function

72

73

```javascript { .api }

74

/**

75

* Generate hash value from string based on first 4 characters

76

* @param value - String to hash

77

* @param length - Length context for hashing

78

* @returns Number hash value

79

*/

80

function hash(value: string, length: number): number;

81

```

82

83

#### String Processing Functions

84

85

```javascript { .api }

86

/**

87

* Remove whitespace from beginning and end of string

88

* @param value - String to trim

89

* @returns Trimmed string

90

*/

91

function trim(value: string): string;

92

93

/**

94

* Execute regular expression and return first match or null

95

* @param value - String to search

96

* @param pattern - Regular expression pattern

97

* @returns First match string or null

98

*/

99

function match(value: string, pattern: RegExp): string | null;

100

101

/**

102

* Replace substring or regex matches in string

103

* @param value - Source string

104

* @param pattern - String or RegExp to find

105

* @param replacement - Replacement string

106

* @returns String with replacements applied

107

*/

108

function replace(value: string, pattern: string | RegExp, replacement: string): string;

109

110

/**

111

* Find index of substring in string

112

* @param value - String to search

113

* @param search - Substring to find

114

* @param position - Starting position for search

115

* @returns Index of substring or -1 if not found

116

*/

117

function indexof(value: string, search: string, position?: number): number;

118

119

/**

120

* Get character code at specific index in string

121

* @param value - Source string

122

* @param index - Character index

123

* @returns Character code (0 if index out of bounds)

124

*/

125

function charat(value: string, index: number): number;

126

127

/**

128

* Extract substring between start and end indices

129

* @param value - Source string

130

* @param begin - Start index

131

* @param end - End index

132

* @returns Extracted substring

133

*/

134

function substr(value: string, begin: number, end: number): string;

135

136

/**

137

* Get length of string

138

* @param value - String to measure

139

* @returns String length

140

*/

141

function strlen(value: string): number;

142

```

143

144

**Usage Examples:**

145

146

```javascript

147

import { hash, trim, match, replace, indexof, charat, substr, strlen } from 'stylis';

148

149

// String hashing

150

const hashValue = hash('color', 5); // Numeric hash for 'color'

151

152

// String cleaning

153

const cleaned = trim(' padding: 20px '); // 'padding: 20px'

154

155

// Pattern matching

156

const found = match('color: red;', /color:\s*(\w+)/); // 'color: red'

157

158

// String replacement

159

const prefixed = replace('display: flex', 'flex', '-webkit-flex');

160

// 'display: -webkit-flex'

161

162

// Substring search

163

const colonIndex = indexof('color: red', ':'); // 5

164

165

// Character code extraction

166

const firstChar = charat('color', 0); // 99 (character code for 'c')

167

168

// Substring extraction

169

const property = substr('color: red;', 0, 5); // 'color'

170

171

// String length

172

const length = strlen('padding'); // 7

173

```

174

175

### Array and Collection Functions

176

177

#### Array Size and Manipulation

178

179

```javascript { .api }

180

/**

181

* Get length of array

182

* @param value - Array to measure

183

* @returns Array length

184

*/

185

function sizeof(value: any[]): number;

186

187

/**

188

* Push value to array and return the value

189

* @param value - Value to append

190

* @param array - Target array

191

* @returns The appended value

192

*/

193

function append(value: any, array: any[]): any;

194

195

/**

196

* Map array through callback and join results into string

197

* @param array - Source array

198

* @param callback - Function to apply to each element

199

* @returns Joined string result

200

*/

201

function combine(array: string[], callback: function): string;

202

203

/**

204

* Filter array by removing items that match regex pattern

205

* @param array - Source array

206

* @param pattern - RegExp pattern to exclude

207

* @returns Filtered array (items that don't match pattern)

208

*/

209

function filter(array: string[], pattern: RegExp): string[];

210

```

211

212

**Usage Examples:**

213

214

```javascript

215

import { sizeof, append, combine, filter } from 'stylis';

216

217

// Array length

218

const selectors = ['h1', 'h2', 'h3'];

219

const count = sizeof(selectors); // 3

220

221

// Array append with return value

222

const rules = [];

223

const newRule = append('color: red;', rules);

224

console.log(newRule); // 'color: red;'

225

console.log(rules); // ['color: red;']

226

227

// Array transformation and joining

228

const properties = ['margin', 'padding', 'border'];

229

const cssBlock = combine(properties, (prop) => `${prop}: 0;`);

230

// 'margin: 0;padding: 0;border: 0;'

231

232

// Array filtering (removes matches)

233

const declarations = ['color: red;', '/* comment */', 'font-size: 14px;'];

234

const withoutComments = filter(declarations, /\/\*/);

235

// ['color: red;', 'font-size: 14px;']

236

```

237

238

## Utility Function Patterns

239

240

### String Processing Pipeline

241

242

```javascript

243

import { trim, replace, indexof, substr } from 'stylis';

244

245

function processProperty(declaration) {

246

// Clean whitespace

247

const cleaned = trim(declaration);

248

249

// Find property-value separator

250

const colonIndex = indexof(cleaned, ':');

251

if (colonIndex === -1) return null;

252

253

// Extract property and value

254

const property = trim(substr(cleaned, 0, colonIndex));

255

const value = trim(substr(cleaned, colonIndex + 1, cleaned.length));

256

257

// Add vendor prefix if needed

258

const prefixed = replace(property, /^(transform|transition)/, '-webkit-$1');

259

260

return { property: prefixed, value };

261

}

262

263

// Usage

264

const result = processProperty(' transform: scale(1.2) ');

265

// { property: '-webkit-transform', value: 'scale(1.2)' }

266

```

267

268

### Array Processing Chain

269

270

```javascript

271

import { filter, combine, sizeof } from 'stylis';

272

273

function processSelectors(selectors, namespace) {

274

// Remove empty selectors

275

const cleaned = filter(selectors, /^\s*$/);

276

277

// Add namespace prefix

278

const namespaced = cleaned.map(selector => `${namespace} ${selector}`);

279

280

// Combine into CSS selector string

281

const combined = combine(namespaced, (sel) => sel);

282

283

return {

284

selectors: namespaced,

285

css: combined,

286

count: sizeof(namespaced)

287

};

288

}

289

290

// Usage

291

const result = processSelectors(['h1', '', 'p'], '.component');

292

// {

293

// selectors: ['.component h1', '.component p'],

294

// css: '.component h1.component p',

295

// count: 2

296

// }

297

```

298

299

### Hash-based Property Detection

300

301

```javascript

302

import { hash } from 'stylis';

303

304

function needsPrefix(property, length) {

305

const propertyHash = hash(property, length);

306

307

// Hash values for properties that need prefixes

308

const prefixHashes = [

309

5349, // appearance

310

4246, // user-select

311

4810, // transform

312

6968, // hyphens

313

2756 // text-size-adjust

314

];

315

316

return prefixHashes.includes(propertyHash);

317

}

318

319

// Usage

320

const shouldPrefix = needsPrefix('user-select', 11); // true

321

```

322

323

## Performance Considerations

324

325

The utility functions are optimized for performance in CSS processing contexts:

326

327

- **String functions**: Use native JavaScript methods with minimal overhead

328

- **Array functions**: Designed for small arrays typical in CSS processing

329

- **Hash function**: Fast character-based hashing for property identification

330

- **Character operations**: Work directly with character codes for speed

331

332

## Memory Management

333

334

- **Immutable operations**: Most functions return new values rather than modifying inputs

335

- **Minimal allocations**: Reuse of built-in JavaScript functions where possible

336

- **String interning**: Character-based operations avoid unnecessary string creation