or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

components.mdcss-in-js.mdindex.mdstyle-functions.mdtheme-system.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Color manipulation, breakpoint handling, and other utility functions for advanced theming and responsive design. These utilities provide low-level functionality for theme management and color operations.

3

4

## Capabilities

5

6

### Color Manipulation

7

8

Comprehensive color manipulation utilities for adjusting colors, calculating contrast, and converting between color formats.

9

10

```typescript { .api }

11

/**

12

* Convert hexadecimal color to RGB format

13

* @param hex - Hexadecimal color string (e.g., '#1976d2')

14

* @returns RGB color string (e.g., 'rgb(25, 118, 210)')

15

*/

16

function hexToRgb(hex: string): string;

17

18

/**

19

* Convert RGB color to hexadecimal format

20

* @param color - RGB color string (e.g., 'rgb(25, 118, 210)')

21

* @returns Hexadecimal color string (e.g., '#1976d2')

22

*/

23

function rgbToHex(color: string): string;

24

25

/**

26

* Convert HSL color to RGB format

27

* @param color - HSL color string (e.g., 'hsl(210, 79%, 46%)')

28

* @returns RGB color string (e.g., 'rgb(25, 118, 210)')

29

*/

30

function hslToRgb(color: string): string;

31

32

/**

33

* Parse color string into type and component values

34

* @param color - Color string in any supported format

35

* @returns Color object with type and values

36

*/

37

function decomposeColor(color: string): ColorObject;

38

39

/**

40

* Reconstruct color string from decomposed components

41

* @param color - Color object with type and values

42

* @returns Color string in original format

43

*/

44

function recomposeColor(color: ColorObject): string;

45

46

interface ColorObject {

47

/** Color format type */

48

type: ColorFormat;

49

50

/** Color component values */

51

values: number[];

52

53

/** Color space (for color() format) */

54

colorSpace?: string;

55

}

56

57

type ColorFormat = 'rgb' | 'rgba' | 'hsl' | 'hsla' | 'color';

58

59

/**

60

* Calculate WCAG contrast ratio between two colors

61

* @param foreground - Foreground color string

62

* @param background - Background color string

63

* @returns Contrast ratio (1-21)

64

*/

65

function getContrastRatio(foreground: string, background: string): number;

66

67

/**

68

* Calculate relative luminance of a color

69

* @param color - Color string in any supported format

70

* @returns Relative luminance (0-1)

71

*/

72

function getLuminance(color: string): number;

73

74

/**

75

* Apply alpha transparency to a color

76

* @param color - Base color string

77

* @param value - Alpha value (0-1)

78

* @returns Color with applied alpha

79

*/

80

function alpha(color: string, value: number): string;

81

82

/**

83

* Darken a color by specified amount

84

* @param color - Base color string

85

* @param coefficient - Darkening amount (0-1)

86

* @returns Darkened color

87

*/

88

function darken(color: string, coefficient: number): string;

89

90

/**

91

* Lighten a color by specified amount

92

* @param color - Base color string

93

* @param coefficient - Lightening amount (0-1)

94

* @returns Lightened color

95

*/

96

function lighten(color: string, coefficient: number): string;

97

98

/**

99

* Emphasize a color (lighten or darken based on luminance)

100

* @param color - Base color string

101

* @param coefficient - Emphasis amount (0-1, default: 0.15)

102

* @returns Emphasized color

103

*/

104

function emphasize(color: string, coefficient?: number): string;

105

106

/**

107

* Blend overlay color onto background color

108

* @param background - Background color string

109

* @param overlay - Overlay color string

110

* @param opacity - Overlay opacity (0-1)

111

* @param gamma - Gamma correction factor (default: 1.0)

112

* @returns Blended color

113

*/

114

function blend(

115

background: string,

116

overlay: string,

117

opacity: number,

118

gamma?: number

119

): string;

120

121

/**

122

* Extract color channel from color string

123

* @param color - Color string in any supported format

124

* @returns Color channel string for CSS

125

*/

126

function colorChannel(color: string): string;

127

128

// Private/Safe variants with error handling

129

/**

130

* Safe alpha function with error handling

131

* @param color - Base color string

132

* @param value - Alpha value (0-1)

133

* @param warning - Optional warning message

134

* @returns Color with applied alpha or fallback

135

*/

136

function private_safeAlpha(color: string, value: number, warning?: string): string;

137

138

/**

139

* Safe darken function with error handling

140

* @param color - Base color string

141

* @param coefficient - Darkening amount (0-1)

142

* @param warning - Optional warning message

143

* @returns Darkened color or fallback

144

*/

145

function private_safeDarken(color: string, coefficient: number, warning?: string): string;

146

147

/**

148

* Safe lighten function with error handling

149

* @param color - Base color string

150

* @param coefficient - Lightening amount (0-1)

151

* @param warning - Optional warning message

152

* @returns Lightened color or fallback

153

*/

154

function private_safeLighten(color: string, coefficient: number, warning?: string): string;

155

156

/**

157

* Safe emphasize function with error handling

158

* @param color - Base color string

159

* @param coefficient - Emphasis amount (0-1)

160

* @param warning - Optional warning message

161

* @returns Emphasized color or fallback

162

*/

163

function private_safeEmphasize(color: string, coefficient?: number, warning?: string): string;

164

165

/**

166

* Safe color channel extraction with error handling

167

* @param color - Color string

168

* @param warning - Optional warning message

169

* @returns Color channel string or fallback

170

*/

171

function private_safeColorChannel(color: string, warning?: string): string;

172

```

173

174

**Usage Examples:**

175

176

```typescript

177

import {

178

alpha,

179

darken,

180

lighten,

181

getContrastRatio,

182

hexToRgb

183

} from "@mui/system";

184

185

// Color manipulation

186

const primaryColor = '#1976d2';

187

const lightPrimary = lighten(primaryColor, 0.2);

188

const darkPrimary = darken(primaryColor, 0.2);

189

const transparentPrimary = alpha(primaryColor, 0.5);

190

191

// Contrast checking

192

const contrastRatio = getContrastRatio('#000000', '#ffffff'); // 21

193

const isAccessible = contrastRatio >= 4.5; // true

194

195

// Color conversion

196

const rgbColor = hexToRgb('#1976d2'); // 'rgb(25, 118, 210)'

197

198

// Theme usage

199

const theme = createTheme({

200

palette: {

201

primary: {

202

main: '#1976d2',

203

light: lighten('#1976d2', 0.2),

204

dark: darken('#1976d2', 0.2),

205

},

206

},

207

});

208

```

209

210

### Breakpoint Utilities

211

212

Utilities for handling responsive prop values and breakpoint-based styling.

213

214

```typescript { .api }

215

/**

216

* Handle responsive prop values across breakpoints

217

* @param prop - Responsive prop value or object

218

* @param transform - Value transformation function

219

* @param breakpoints - Breakpoints object

220

* @returns Processed breakpoint styles

221

*/

222

function handleBreakpoints<T>(

223

prop: T | Partial<Record<Breakpoint, T>>,

224

transform: (value: T) => any,

225

breakpoints?: Breakpoints

226

): any;

227

228

/**

229

* Merge breakpoint-specific styles in correct order

230

* @param breakpoints - Breakpoints object

231

* @param styles - Array of style objects with breakpoint keys

232

* @returns Merged styles object

233

*/

234

function mergeBreakpointsInOrder(

235

breakpoints: Breakpoints,

236

styles: Array<Record<string, any>>

237

): Record<string, any>;

238

239

/**

240

* Resolve responsive values to specific breakpoint values

241

* @param values - Responsive values object

242

* @param breakpoints - Breakpoints to resolve

243

* @returns Resolved values for each breakpoint

244

*/

245

function unstable_resolveBreakpointValues<T>(

246

values: T | Partial<Record<Breakpoint, T>>,

247

breakpoints?: Breakpoint[]

248

): Partial<Record<Breakpoint, T>>;

249

250

/**

251

* Responsive breakpoint style function

252

*/

253

const breakpoints: StyleFunction<{

254

[key in Breakpoint]?: any;

255

}>;

256

```

257

258

**Usage Examples:**

259

260

```typescript

261

import { handleBreakpoints, createTheme } from "@mui/system";

262

263

const theme = createTheme();

264

265

// Handle responsive prop

266

const responsiveStyles = handleBreakpoints(

267

{ xs: 1, md: 2, lg: 3 },

268

(value) => ({ padding: theme.spacing(value) }),

269

theme.breakpoints

270

);

271

272

// Results in:

273

// {

274

// padding: '8px',

275

// '@media (min-width: 900px)': { padding: '16px' },

276

// '@media (min-width: 1200px)': { padding: '24px' }

277

// }

278

```

279

280

### Container Query Utilities

281

282

Utilities for CSS container queries and responsive design based on container size.

283

284

```typescript { .api }

285

/**

286

* Add container queries support to theme

287

* @param theme - Base theme object

288

* @returns Theme with container queries

289

*/

290

function cssContainerQueries<T extends Theme>(theme: T): T & CssContainerQueries;

291

292

interface CssContainerQueries {

293

/** Container queries helper methods */

294

containerQueries: ContainerQueries;

295

}

296

297

interface ContainerQueries {

298

/** Generate container query for minimum width */

299

up(key: string | number): string;

300

301

/** Generate container query for maximum width */

302

down(key: string | number): string;

303

304

/** Generate container query between two sizes */

305

between(start: string | number, end: string | number): string;

306

307

/** Generate container query for specific size only */

308

only(key: string): string;

309

}

310

311

/**

312

* Sort container queries by size

313

* @param queries - Container query objects

314

* @returns Sorted queries array

315

*/

316

function sortContainerQueries(queries: Array<{ key: string; value: number }>): Array<{ key: string; value: number }>;

317

318

/**

319

* Get container query string from shorthand

320

* @param shorthand - Container query shorthand

321

* @returns Full container query string

322

*/

323

function getContainerQuery(shorthand: string): string;

324

325

/**

326

* Check if value is container query shorthand

327

* @param value - Value to check

328

* @returns True if container query shorthand

329

*/

330

function isCqShorthand(value: any): boolean;

331

```

332

333

### Media Query Hook

334

335

React hook for responsive breakpoint matching with SSR support.

336

337

```typescript { .api }

338

/**

339

* Hook for responsive breakpoint matching

340

* @param queryInput - Media query string or function

341

* @param options - Hook configuration options

342

* @returns Boolean indicating if query matches

343

*/

344

function useMediaQuery<Theme = Theme>(

345

queryInput: string | ((theme: Theme) => string),

346

options?: UseMediaQueryOptions

347

): boolean;

348

349

interface UseMediaQueryOptions {

350

/** Default match state (used during SSR) */

351

defaultMatches?: boolean;

352

353

/** Custom matchMedia implementation */

354

matchMedia?: (query: string) => MediaQueryList;

355

356

/** Disable server-side rendering hydration mismatch */

357

noSsr?: boolean;

358

359

/** Server-side media query matcher */

360

ssrMatchMedia?: (query: string) => { matches: boolean };

361

}

362

363

/**

364

* Factory for creating custom useMediaQuery hook

365

* @param matchMedia - Custom matchMedia implementation

366

* @returns Custom useMediaQuery hook

367

*/

368

function unstable_createUseMediaQuery(

369

matchMedia: (query: string) => MediaQueryList

370

): typeof useMediaQuery;

371

```

372

373

**Usage Examples:**

374

375

```typescript

376

import { useMediaQuery, useTheme } from "@mui/system";

377

378

function ResponsiveComponent() {

379

const theme = useTheme();

380

const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

381

const isDesktop = useMediaQuery('(min-width: 1200px)');

382

383

return (

384

<div>

385

{isMobile ? 'Mobile view' : 'Desktop view'}

386

{isDesktop && <div>Large screen content</div>}

387

</div>

388

);

389

}

390

391

// With options

392

function SSRComponent() {

393

const matches = useMediaQuery('(min-width: 600px)', {

394

defaultMatches: true, // Assume match during SSR

395

noSsr: false,

396

});

397

398

return <div>{matches ? 'Wide' : 'Narrow'}</div>;

399

}

400

```

401

402

### Advanced Utilities

403

404

Additional utility functions for theme management and value processing.

405

406

```typescript { .api }

407

/**

408

* Get value from theme using dot notation path

409

* @param theme - Theme object

410

* @param path - Dot notation path (e.g., 'palette.primary.main')

411

* @returns Value at theme path

412

*/

413

function unstable_getThemeValue(theme: Theme, path: string): any;

414

415

/**

416

* Memoize theme object for performance optimization

417

* @param theme - Theme object to memoize

418

* @returns Memoized theme object

419

*/

420

function unstable_memoTheme<T extends Theme>(theme: T): T;

421

422

/**

423

* PropTypes validator for responsive props

424

*/

425

const responsivePropType: any;

426

427

/**

428

* Provider for RTL (right-to-left) support

429

*/

430

declare const RtlProvider: React.ComponentType<RtlProviderProps>;

431

432

interface RtlProviderProps {

433

/** Child components */

434

children: React.ReactNode;

435

436

/** RTL value (true for RTL, false for LTR) */

437

value: boolean;

438

}

439

440

/**

441

* Hook to access RTL context

442

* @returns RTL boolean value

443

*/

444

function useRtl(): boolean;

445

446

/**

447

* Legacy sx function (deprecated, throws error)

448

* @deprecated Use theme.unstable_sx instead

449

*/

450

function experimental_sx(): never;

451

```

452

453

### CSS Variable Support (Unstable)

454

455

Advanced CSS custom properties integration for dynamic theming.

456

457

```typescript { .api }

458

/**

459

* Create CSS variables provider component

460

* @param options - Provider configuration

461

* @returns CSS variables provider result

462

*/

463

function unstable_createCssVarsProvider<Theme extends Record<string, any>>(

464

options: CssVarsProviderConfig<Theme>

465

): CreateCssVarsProviderResult<Theme>;

466

467

interface CssVarsProviderConfig<Theme> {

468

/** Theme creation function */

469

theme: Theme | ((colorScheme: string) => Theme);

470

471

/** Default color scheme */

472

defaultColorScheme?: string;

473

474

/** Storage key for color scheme preference */

475

storageKey?: string;

476

477

/** Available color schemes */

478

colorSchemes?: string[];

479

480

/** CSS variable prefix */

481

prefix?: string;

482

}

483

484

interface CreateCssVarsProviderResult<Theme> {

485

/** CSS variables provider component */

486

CssVarsProvider: React.ComponentType<any>;

487

488

/** Hook to access theme with CSS variables */

489

useTheme: () => Theme;

490

491

/** Hook to access color scheme context */

492

useColorScheme: () => ColorSchemeContextValue;

493

}

494

495

interface ColorSchemeContextValue {

496

/** Current color scheme */

497

colorScheme: string;

498

499

/** Set color scheme */

500

setColorScheme: (scheme: string) => void;

501

}

502

503

/**

504

* Create CSS variable getter function

505

* @param prefix - CSS variable prefix

506

* @returns CSS variable getter function

507

*/

508

function unstable_createGetCssVar(prefix?: string): (field: string) => string;

509

510

/**

511

* Parse theme values into CSS custom properties

512

* @param theme - Theme object

513

* @param options - Parsing options

514

* @returns CSS variables object

515

*/

516

function unstable_cssVarsParser<Theme>(

517

theme: Theme,

518

options?: { prefix?: string }

519

): Record<string, string>;

520

521

/**

522

* Prepare theme for CSS custom properties

523

* @param theme - Theme object

524

* @param options - Preparation options

525

* @returns Theme with CSS variables support

526

*/

527

function unstable_prepareCssVars<Theme>(

528

theme: Theme,

529

options?: { prefix?: string }

530

): Theme & { cssVars: Record<string, string> };

531

532

/**

533

* Create theme optimized for CSS custom properties

534

* @param options - Theme options with CSS variables support

535

* @returns CSS variables-enabled theme

536

*/

537

function unstable_createCssVarsTheme<Theme>(

538

options: any

539

): Theme & { cssVars: Record<string, string> };

540

```

541

542

### Color Scheme Initialization

543

544

Script component for initializing color scheme on page load to prevent flash of unstyled content.

545

546

```typescript { .api }

547

/**

548

* Inline script for color scheme initialization

549

* @param options - Configuration options

550

* @returns Script element for color scheme initialization

551

*/

552

function InitColorSchemeScript(options?: InitColorSchemeScriptProps): React.ReactElement;

553

554

interface InitColorSchemeScriptProps {

555

/** Default mode when storage is empty */

556

defaultMode?: 'system' | 'light' | 'dark';

557

558

/** Default color scheme for light mode */

559

defaultLightColorScheme?: string;

560

561

/** Default color scheme for dark mode */

562

defaultDarkColorScheme?: string;

563

564

/** DOM node for color scheme attribute */

565

colorSchemeNode?: string;

566

567

/** localStorage key for mode */

568

modeStorageKey?: string;

569

570

/** localStorage key for color scheme */

571

colorSchemeStorageKey?: string;

572

573

/** DOM attribute for color scheme */

574

attribute?: 'class' | 'data' | string;

575

576

/** CSP nonce for inline script */

577

nonce?: string;

578

}

579

580

// Constants for default storage keys

581

const DEFAULT_MODE_STORAGE_KEY: string;

582

const DEFAULT_COLOR_SCHEME_STORAGE_KEY: string;

583

const DEFAULT_ATTRIBUTE: string;

584

```

585

586

**Usage Examples:**

587

588

```typescript

589

import { InitColorSchemeScript } from "@mui/system";

590

591

// In your _document.js (Next.js) or index.html

592

function Document() {

593

return (

594

<html>

595

<head>

596

<InitColorSchemeScript />

597

</head>

598

<body>

599

<Main />

600

</body>

601

</html>

602

);

603

}

604

605

// With custom configuration

606

<InitColorSchemeScript

607

defaultMode="system"

608

defaultLightColorScheme="blue"

609

defaultDarkColorScheme="dark-blue"

610

attribute="data-color-scheme"

611

modeStorageKey="my-mode"

612

/>

613

614

// For class-based color scheme

615

<InitColorSchemeScript

616

attribute="class"

617

defaultLightColorScheme="light-theme"

618

defaultDarkColorScheme="dark-theme"

619

/>

620

```

621

622

### Version Information

623

624

Package version information for compatibility checking.

625

626

```typescript { .api }

627

/**

628

* Current package version string

629

*/

630

const version: string;

631

```

632

633

**Usage Examples:**

634

635

```typescript

636

import { version } from "@mui/system";

637

638

console.log(`MUI System version: ${version}`); // "7.3.2"

639

640

// Conditional logic based on version

641

if (version.startsWith('7.')) {

642

// Version 7.x specific code

643

}

644

```

645

646

### RTL Support

647

648

Right-to-left (RTL) language support with context provider and hook for directional styling.

649

650

```typescript { .api }

651

/**

652

* RTL context provider component

653

* @param props - RTL provider props

654

* @returns Provider component

655

*/

656

declare const RtlProvider: React.ComponentType<RtlProviderProps>;

657

658

interface RtlProviderProps {

659

/** Child components */

660

children?: React.ReactNode;

661

662

/** Whether RTL mode is enabled (default: false) */

663

value?: boolean;

664

}

665

666

/**

667

* Hook to access current RTL state

668

* @returns Boolean indicating if RTL mode is active

669

*/

670

function useRtl(): boolean;

671

```

672

673

**Usage Examples:**

674

675

```typescript

676

import { RtlProvider, useRtl } from "@mui/system";

677

678

// App with RTL support

679

function App() {

680

const [isRtl, setIsRtl] = useState(false);

681

682

return (

683

<div dir={isRtl ? 'rtl' : 'ltr'}>

684

<RtlProvider value={isRtl}>

685

<MyComponent />

686

<button onClick={() => setIsRtl(!isRtl)}>

687

Toggle RTL

688

</button>

689

</RtlProvider>

690

</div>

691

);

692

}

693

694

// Component using RTL state

695

function DirectionalComponent() {

696

const isRtl = useRtl();

697

698

return (

699

<Box

700

sx={{

701

marginLeft: isRtl ? 0 : 2,

702

marginRight: isRtl ? 2 : 0,

703

textAlign: isRtl ? 'right' : 'left',

704

}}

705

>

706

Directional content

707

</Box>

708

);

709

}

710

711

// Styled component with RTL support

712

const StyledBox = styled(Box)(({ theme }) => {

713

const isRtl = useRtl();

714

715

return {

716

paddingLeft: isRtl ? 0 : theme.spacing(2),

717

paddingRight: isRtl ? theme.spacing(2) : 0,

718

borderLeftWidth: isRtl ? 0 : 1,

719

borderRightWidth: isRtl ? 1 : 0,

720

};

721

});

722

```

723

724

### Container Queries

725

726

CSS container query support for responsive design based on container size rather than viewport size.

727

728

```typescript { .api }

729

/**

730

* CSS container queries theme extension

731

* @param theme - Theme object to extend

732

* @returns Theme with container query support

733

*/

734

function cssContainerQueries<T extends Theme>(theme: T): T & CssContainerQueries;

735

736

interface CssContainerQueries {

737

/** Container query methods */

738

containerQueries: ((name: string) => ContainerQueries) & ContainerQueries;

739

}

740

741

interface ContainerQueries {

742

/** Generate min-width container query */

743

up(key: string | number): string;

744

745

/** Generate max-width container query */

746

down(key: string | number): string;

747

748

/** Generate container query between two breakpoints */

749

between(start: string | number, end: string | number): string;

750

751

/** Generate container query for specific breakpoint only */

752

only(key: string): string;

753

754

/** Generate container query excluding specific breakpoint */

755

not(key: string): string;

756

}

757

758

/**

759

* Sort container queries from low to high for consistent CSS order

760

* @param theme - Theme with container queries

761

* @param css - CSS object with container queries

762

* @returns Sorted CSS object

763

*/

764

function sortContainerQueries(

765

theme: Partial<CssContainerQueries>,

766

css: Record<string, any>

767

): Record<string, any>;

768

769

/**

770

* Check if value is a container query shorthand

771

* @param breakpointKeys - Available breakpoint keys

772

* @param value - Value to check

773

* @returns Boolean indicating if value is CQ shorthand

774

*/

775

function isCqShorthand(breakpointKeys: string[], value: string): boolean;

776

777

/**

778

* Get container query string for breakpoint

779

* @param theme - Theme with container queries

780

* @param breakpoint - Breakpoint key or value

781

* @param container - Container name (optional)

782

* @returns Container query string

783

*/

784

function getContainerQuery(

785

theme: CssContainerQueries,

786

breakpoint: string | number,

787

container?: string

788

): string;

789

```

790

791

**Usage Examples:**

792

793

```typescript

794

import { cssContainerQueries, createTheme } from "@mui/system";

795

796

// Create theme with container queries

797

const theme = createTheme();

798

const themeWithCq = cssContainerQueries(theme);

799

800

// Using container queries in sx prop

801

<Box

802

sx={{

803

padding: 1,

804

[themeWithCq.containerQueries.up('md')]: {

805

padding: 2,

806

},

807

[themeWithCq.containerQueries.between('sm', 'lg')]: {

808

backgroundColor: 'grey.100',

809

},

810

}}

811

>

812

Container-responsive content

813

</Box>

814

815

// Named container queries

816

<Box

817

sx={{

818

containerType: 'inline-size',

819

containerName: 'sidebar',

820

}}

821

>

822

<Box

823

sx={{

824

fontSize: '14px',

825

[themeWithCq.containerQueries('sidebar').up('300px')]: {

826

fontSize: '16px',

827

},

828

[themeWithCq.containerQueries('sidebar').up('500px')]: {

829

fontSize: '18px',

830

},

831

}}

832

>

833

Sidebar content

834

</Box>

835

</Box>

836

837

// Styled component with container queries

838

const ResponsiveCard = styled(Box)(({ theme }) => {

839

const cqTheme = cssContainerQueries(theme);

840

841

return {

842

padding: theme.spacing(1),

843

[cqTheme.containerQueries.up('200px')]: {

844

padding: theme.spacing(2),

845

},

846

[cqTheme.containerQueries.up('400px')]: {

847

padding: theme.spacing(3),

848

display: 'grid',

849

gridTemplateColumns: '1fr 1fr',

850

},

851

};

852

});

853

```

854

855

## Utility Integration

856

857

These utilities integrate with the broader MUI System ecosystem:

858

859

- **Theme System**: Color utilities work with theme palette values

860

- **Breakpoint System**: Responsive utilities handle breakpoint-based styling

861

- **Components**: All utilities can be used in component styling and sx props

862

- **CSS-in-JS**: Integration with styled components and CSS generation

863

- **TypeScript**: Full type safety for all utility functions and their parameters