0
# Utilities & Hooks
1
2
React hooks, utility functions, color transformations, and helper methods for enhanced functionality, state management, browser APIs, and design system integration. These utilities provide the foundational logic for building robust Polaris applications.
3
4
## Capabilities
5
6
### Core React Hooks
7
8
Essential React hooks for accessing Polaris context, theme configuration, and application state.
9
10
```typescript { .api }
11
/**
12
* Access Frame context and utilities for frame-related functionality
13
* @returns Frame context object with utilities and state
14
*/
15
function useFrame(): FrameContext;
16
17
interface FrameContext {
18
/** Show toast notification */
19
showToast(toast: ToastProps): void;
20
/** Hide toast notification */
21
hideToast(id: string): void;
22
/** Set context bar content */
23
setContextualSaveBar(contextualSaveBar: React.ReactNode): void;
24
/** Remove context bar */
25
removeContextualSaveBar(): void;
26
/** Start loading state */
27
startLoading(): void;
28
/** Stop loading state */
29
stopLoading(): void;
30
/** Navigation state */
31
navigationOpen: boolean;
32
/** Toggle navigation */
33
toggleNavigation(): void;
34
}
35
36
/**
37
* Access current theme configuration and design tokens
38
* @returns Current theme object with tokens and configuration
39
*/
40
function useTheme(): Theme;
41
42
interface Theme {
43
/** Color tokens */
44
colors: ThemeColors;
45
/** Spacing tokens */
46
space: ThemeSpace;
47
/** Typography tokens */
48
font: ThemeFont;
49
/** Border radius tokens */
50
borderRadius: ThemeBorderRadius;
51
/** Shadow tokens */
52
shadows: ThemeShadows;
53
/** Z-index tokens */
54
zIndex: ThemeZIndex;
55
}
56
```
57
58
### Responsive & Media Hooks
59
60
Hooks for responsive design, breakpoint matching, and media query integration.
61
62
```typescript { .api }
63
/**
64
* Responsive breakpoint matching hook with SSR support
65
* @param options - Configuration options for defaults
66
* @returns Object with boolean values for each breakpoint
67
*/
68
function useBreakpoints(options?: UseBreakpointsOptions): BreakpointsMatches;
69
70
interface UseBreakpointsOptions {
71
/** Default values for SSR */
72
defaults?: Partial<BreakpointsMatches>;
73
}
74
75
interface BreakpointsMatches {
76
/** Extra small screen and up */
77
xsUp: boolean;
78
/** Small screen and up */
79
smUp: boolean;
80
/** Medium screen and up */
81
mdUp: boolean;
82
/** Large screen and up */
83
lgUp: boolean;
84
/** Extra large screen and up */
85
xlUp: boolean;
86
/** Extra small screen only */
87
xsOnly: boolean;
88
/** Small screen only */
89
smOnly: boolean;
90
/** Medium screen only */
91
mdOnly: boolean;
92
/** Large screen only */
93
lgOnly: boolean;
94
/** Extra small screen and down */
95
xsDown: boolean;
96
/** Small screen and down */
97
smDown: boolean;
98
/** Medium screen and down */
99
mdDown: boolean;
100
/** Large screen and down */
101
lgDown: boolean;
102
}
103
104
/**
105
* Media query matching hook for custom queries
106
* @param query - CSS media query string
107
* @returns Boolean indicating if query matches
108
*/
109
function useMediaQuery(query: string): boolean;
110
```
111
112
### Resource & Selection Hooks
113
114
Hooks for managing resource selection state, bulk operations, and data management.
115
116
```typescript { .api }
117
/**
118
* Resource selection state management for IndexTable and ResourceList
119
* @param resources - Array of resources to manage
120
* @param options - Configuration options
121
* @returns Resource state management object
122
*/
123
function useIndexResourceState<T>(
124
resources: T[],
125
options?: IndexResourceStateOptions<T>
126
): IndexResourceState<T>;
127
128
interface IndexResourceStateOptions<T> {
129
/** Function to extract unique ID from resource */
130
resourceIDResolver?: (resource: T) => string;
131
/** Initial resource filter */
132
resourceFilter?: (resource: T) => boolean;
133
}
134
135
interface IndexResourceState<T> {
136
/** Currently selected resource IDs */
137
selectedResources: string[];
138
/** All resources selected state */
139
allResourcesSelected: boolean;
140
/** Handle selection change */
141
handleSelectionChange: (
142
selectionType: SelectionType,
143
isSelecting: boolean,
144
selection?: string | string[]
145
) => void;
146
/** Clear all selections */
147
clearSelection: () => void;
148
/** Remove specific resources from selection */
149
removeSelectedResources: (removeResources: string[]) => void;
150
}
151
152
enum SelectionType {
153
All = 'all',
154
Page = 'page',
155
Range = 'range',
156
Single = 'single',
157
}
158
```
159
160
### IndexTable Specific Hooks
161
162
Specialized hooks for IndexTable row interactions, hover states, and scroll management.
163
164
```typescript { .api }
165
/**
166
* Hook for managing IndexTable row hover state
167
* @returns Object with hover state and handlers
168
*/
169
function useIndexTableRowHovered(): {
170
hoveredRowIndex: number | undefined;
171
onRowHover: (index: number) => void;
172
onRowOut: () => void;
173
};
174
175
/**
176
* Hook for managing IndexTable row selection state
177
* @returns Object with selection state and handlers
178
*/
179
function useIndexTableRowSelected(): {
180
selectedRowIndex: number | undefined;
181
onRowSelect: (index: number) => void;
182
onRowDeselect: () => void;
183
};
184
185
/**
186
* Hook for managing IndexTable container scroll behavior
187
* @returns Object with scroll state and utilities
188
*/
189
function useIndexTableContainerScroll(): {
190
scrollableContainer: React.RefObject<HTMLDivElement>;
191
canScrollLeft: boolean;
192
canScrollRight: boolean;
193
scrollLeft: () => void;
194
scrollRight: () => void;
195
};
196
```
197
198
### Browser API Hooks
199
200
Hooks for browser interactions, event handling, and user interface management.
201
202
```typescript { .api }
203
/**
204
* Event listener lifecycle management hook
205
* @param event - Event type to listen for
206
* @param handler - Event handler function
207
* @param target - Event target (defaults to window)
208
* @param options - Event listener options
209
*/
210
function useEventListener<K extends keyof WindowEventMap>(
211
event: K,
212
handler: (event: WindowEventMap[K]) => void,
213
target?: EventTarget,
214
options?: AddEventListenerOptions
215
): void;
216
217
/**
218
* Focus state management hook
219
* @returns Object with focus state and utilities
220
*/
221
function useFocus(): {
222
focused: boolean;
223
onFocus: () => void;
224
onBlur: () => void;
225
};
226
227
/**
228
* Focus-in event handling hook for tracking focus within containers
229
* @param onFocusIn - Callback when focus enters container
230
* @param onFocusOut - Callback when focus leaves container
231
* @returns Ref object to attach to container
232
*/
233
function useFocusIn(
234
onFocusIn?: () => void,
235
onFocusOut?: () => void
236
): React.RefObject<HTMLElement>;
237
238
/**
239
* Hover state management hook
240
* @returns Object with hover state and handlers
241
*/
242
function useHover(): {
243
hovered: boolean;
244
onMouseEnter: () => void;
245
onMouseLeave: () => void;
246
onMouseOver: () => void;
247
onMouseOut: () => void;
248
};
249
250
/**
251
* Clipboard copy functionality hook
252
* @returns Copy function that returns success boolean
253
*/
254
function useCopyToClipboard(): (text: string) => Promise<boolean>;
255
256
/**
257
* Ephemeral presence manager hook for tracking focus and presence state
258
* @returns Read-only ephemeral presence manager instance
259
*/
260
function useEphemeralPresenceManager(): EphemeralPresenceManager;
261
262
interface EphemeralPresenceManager {
263
/** Add presence listener */
264
addPresenceListener(handler: PresenceHandler): void;
265
/** Remove presence listener */
266
removePresenceListener(handler: PresenceHandler): void;
267
}
268
269
type PresenceHandler = (isPresent: boolean) => void;
270
```
271
272
### Filter Management Hooks
273
274
Hooks for managing filter states and configurations in data tables and resource lists.
275
276
```typescript { .api }
277
/**
278
* Hook for managing IndexFilters mode state
279
* @param initialMode - Initial filter mode
280
* @returns Filter mode state and setter
281
*/
282
function useSetIndexFiltersMode(
283
initialMode?: IndexFiltersMode
284
): [IndexFiltersMode, (mode: IndexFiltersMode) => void];
285
286
enum IndexFiltersMode {
287
Default = 'default',
288
Filtering = 'filtering',
289
Disabled = 'disabled',
290
}
291
```
292
293
## Color Utility Functions
294
295
Comprehensive color transformation and manipulation utilities for design system integration.
296
297
```typescript { .api }
298
/**
299
* Convert RGB color to hexadecimal string
300
* @param color - RGB color object
301
* @returns Hexadecimal color string (e.g., "#FF0000")
302
*/
303
function rgbToHex(color: RGBColor): string;
304
305
/**
306
* Convert RGB color to HSB color space
307
* @param color - RGB color object
308
* @returns HSB color object
309
*/
310
function rgbToHsb(color: RGBColor): HSBColor;
311
312
/**
313
* Convert RGB color to HSL color space
314
* @param color - RGB color object
315
* @returns HSL color object
316
*/
317
function rgbToHsl(color: RGBColor): HSLColor;
318
319
/**
320
* Convert HSB color to RGB color space
321
* @param color - HSB color object
322
* @returns RGB color object
323
*/
324
function hsbToRgb(color: HSBColor): RGBColor;
325
326
/**
327
* Convert HSB color to hexadecimal string
328
* @param color - HSB color object
329
* @returns Hexadecimal color string
330
*/
331
function hsbToHex(color: HSBColor): string;
332
333
/**
334
* Convert HSL color to RGB color space
335
* @param color - HSL color object
336
* @returns RGB color object
337
*/
338
function hslToRgb(color: HSLColor): RGBColor;
339
340
/**
341
* Convert RGB/RGBA color to CSS color string
342
* @param color - RGB or RGBA color object
343
* @returns CSS color string (e.g., "rgb(255, 0, 0)" or "rgba(255, 0, 0, 0.5)")
344
*/
345
function rgbString(color: RGBColor | RGBAColor): string;
346
347
/**
348
* Alias for rgbString function
349
* @param color - RGBA color object
350
* @returns CSS rgba color string
351
*/
352
function rgbaString(color: RGBAColor): string;
353
354
/**
355
* Convert hexadecimal color string to RGB color
356
* @param hex - Hexadecimal color string
357
* @returns RGB color object or null if invalid
358
*/
359
function hexToRgb(hex: string): RGBColor | null;
360
```
361
362
## Color Type Definitions
363
364
```typescript { .api }
365
/** RGB color interface */
366
interface RGBColor {
367
/** Red component (0-255) */
368
red: number;
369
/** Green component (0-255) */
370
green: number;
371
/** Blue component (0-255) */
372
blue: number;
373
}
374
375
/** RGBA color interface extending RGB with alpha */
376
interface RGBAColor extends RGBColor {
377
/** Alpha component (0-1) */
378
alpha: number;
379
}
380
381
/** HSB color interface */
382
interface HSBColor {
383
/** Hue component (0-360) */
384
hue: number;
385
/** Saturation component (0-1) */
386
saturation: number;
387
/** Brightness component (0-1) */
388
brightness: number;
389
}
390
391
/** HSBA color interface extending HSB with alpha */
392
interface HSBAColor extends HSBColor {
393
/** Alpha component (0-1) */
394
alpha: number;
395
}
396
397
/** HSL color interface */
398
interface HSLColor {
399
/** Hue component (0-360) */
400
hue: number;
401
/** Saturation component (0-1) */
402
saturation: number;
403
/** Lightness component (0-1) */
404
lightness: number;
405
}
406
407
/** HSLA color interface extending HSL with alpha */
408
interface HSLAColor extends HSLColor {
409
/** Alpha component (0-1) */
410
alpha: number;
411
}
412
413
/** Combined HSBA and HSLA color type */
414
type HSBLAColor = HSBAColor | HSLAColor;
415
```
416
417
## Breakpoint Utilities
418
419
Utility functions for working with responsive breakpoints and media queries.
420
421
```typescript { .api }
422
/**
423
* Get breakpoint query entries for responsive behavior
424
* @param breakpoints - Breakpoint configuration
425
* @returns Array of media query entries
426
*/
427
function getBreakpointsQueryEntries(
428
breakpoints: BreakpointsConfig
429
): Array<[string, string]>;
430
431
/**
432
* Get media query for collapsed navigation state
433
* @returns CSS media query string
434
*/
435
function navigationBarCollapsed(): string;
436
437
/**
438
* Get media query for stacked content layout
439
* @returns CSS media query string
440
*/
441
function stackedContent(): string;
442
443
interface BreakpointsConfig {
444
/** Extra small breakpoint */
445
xs: string;
446
/** Small breakpoint */
447
sm: string;
448
/** Medium breakpoint */
449
md: string;
450
/** Large breakpoint */
451
lg: string;
452
/** Extra large breakpoint */
453
xl: string;
454
}
455
456
/** Directional breakpoint aliases */
457
type BreakpointsDirectionAlias =
458
| 'xsUp' | 'smUp' | 'mdUp' | 'lgUp' | 'xlUp'
459
| 'xsDown' | 'smDown' | 'mdDown' | 'lgDown'
460
| 'xsOnly' | 'smOnly' | 'mdOnly' | 'lgOnly';
461
```
462
463
## Localization Constants
464
465
Constants for internationalization and localization support.
466
467
```typescript { .api }
468
/** Default locale for Polaris applications */
469
const DEFAULT_LOCALE: string = 'en';
470
471
/** Array of supported locale codes */
472
const SUPPORTED_LOCALES: string[] = [
473
'cs', 'da', 'de', 'en', 'es', 'fi', 'fr', 'it', 'ja', 'ko',
474
'nb', 'nl', 'pl', 'pt-BR', 'pt-PT', 'sv', 'th', 'tr', 'vi',
475
'zh-CN', 'zh-TW'
476
];
477
```
478
479
## Internal Context & Management
480
481
Internal contexts and management utilities for advanced use cases and library internals.
482
483
```typescript { .api }
484
/**
485
* Internal scroll lock management context (read-only)
486
* @internal
487
*/
488
const _SECRET_INTERNAL_SCROLL_LOCK_MANAGER_CONTEXT: React.Context<any>;
489
490
/**
491
* Internal content context for nested components (read-only)
492
* @internal
493
*/
494
const _SECRET_INTERNAL_WITHIN_CONTENT_CONTEXT: React.Context<boolean>;
495
496
/**
497
* Ephemeral presence manager hook for temporary UI states (read-only)
498
* @returns Presence manager utilities
499
*/
500
function useEphemeralPresenceManager(): EphemeralPresenceManager;
501
502
interface EphemeralPresenceManager {
503
/** Add ephemeral presence */
504
addPresence(id: string, presence: any): void;
505
/** Remove ephemeral presence */
506
removePresence(id: string): void;
507
/** Check if presence exists */
508
hasPresence(id: string): boolean;
509
}
510
```
511
512
## Shared Data Attributes
513
514
Shared data attribute utilities for overlay and layer management.
515
516
```typescript { .api }
517
/** Shared data attribute constants for component coordination */
518
const DATA_ATTRIBUTE: {
519
/** Portal container data attribute */
520
Portal: string;
521
/** Overlay data attribute */
522
Overlay: string;
523
/** Popover data attribute */
524
Popover: string;
525
/** Modal data attribute */
526
Modal: string;
527
/** Sheet data attribute */
528
Sheet: string;
529
};
530
```
531
532
**Usage Example:**
533
534
```typescript
535
import React, { useState } from 'react';
536
import {
537
useBreakpoints,
538
useFrame,
539
useTheme,
540
useIndexResourceState,
541
rgbToHex,
542
hexToRgb
543
} from '@shopify/polaris';
544
545
function UtilitiesExample() {
546
const breakpoints = useBreakpoints();
547
const frame = useFrame();
548
const theme = useTheme();
549
550
const [resources] = useState([
551
{ id: '1', name: 'Product A' },
552
{ id: '2', name: 'Product B' },
553
{ id: '3', name: 'Product C' },
554
]);
555
556
const {
557
selectedResources,
558
handleSelectionChange,
559
clearSelection
560
} = useIndexResourceState(resources, {
561
resourceIDResolver: (resource) => resource.id
562
});
563
564
// Color transformations
565
const primaryColor = hexToRgb(theme.colors.primary);
566
const hexColor = primaryColor ? rgbToHex(primaryColor) : '#000000';
567
568
const showToast = () => {
569
frame.showToast({
570
content: `Selected ${selectedResources.length} items`,
571
onDismiss: () => {},
572
});
573
};
574
575
return (
576
<div>
577
{/* Responsive behavior */}
578
{breakpoints.smUp ? (
579
<p>Desktop layout</p>
580
) : (
581
<p>Mobile layout</p>
582
)}
583
584
{/* Selection management */}
585
<button onClick={clearSelection}>
586
Clear Selection ({selectedResources.length})
587
</button>
588
589
<button onClick={showToast}>
590
Show Toast
591
</button>
592
593
{/* Color information */}
594
<div style={{ color: hexColor }}>
595
Primary color: {hexColor}
596
</div>
597
</div>
598
);
599
}
600
```
601
602
### IndexFilters
603
604
Advanced filtering system for index pages with search, filters, and sorting controls integrated into a unified interface.
605
606
```typescript { .api }
607
/**
608
* Comprehensive filtering system for index pages
609
* @param sortOptions - Available sorting options
610
* @param sortSelected - Currently selected sort option
611
* @param queryValue - Current search query
612
* @param filters - Available filter options
613
* @returns JSX element with index filtering interface
614
*/
615
function IndexFilters(props: IndexFiltersProps): JSX.Element;
616
617
interface IndexFiltersProps {
618
/** The sort options for the index */
619
sortOptions: SortButtonChoice[];
620
/** The selected sort option */
621
sortSelected: number;
622
/** The query value */
623
queryValue?: string;
624
/** Placeholder text for the query field */
625
queryPlaceholder?: string;
626
/** Available filters */
627
filters: FilterInterface[];
628
/** Applied filters */
629
appliedFilters?: AppliedFilterInterface[];
630
/** Mode of the index filters */
631
mode: IndexFiltersMode;
632
/** Whether the cancel button is disabled */
633
canCreateNewView?: boolean;
634
/** The tabs for the index */
635
tabs?: Tab[];
636
/** The selected tab */
637
selected?: number;
638
/** Callback when the query is changed */
639
onQueryChange?(queryValue: string): void;
640
/** Callback when the query is cleared */
641
onQueryClear?(): void;
642
/** Callback when the sort is changed */
643
onSort?(sortSelected: string): void;
644
/** Callback when filters are changed */
645
onFiltersChange?(appliedFilters: AppliedFilterInterface[]): void;
646
/** Callback when the view is created */
647
onCreateNewView?(name: string): void;
648
/** Callback when filters are cleared */
649
onClearAll?(): void;
650
}
651
652
interface SortButtonChoice {
653
/** Unique identifier for the sort option */
654
label: string;
655
/** Sort direction */
656
value: string;
657
/** Sort direction ascending/descending */
658
directionLabel: string;
659
}
660
661
enum IndexFiltersMode {
662
Filtering = 'FILTERING',
663
Default = 'DEFAULT',
664
}
665
666
/**
667
* Hook for managing IndexFilters mode state
668
* @returns Mode management utilities
669
*/
670
function useSetIndexFiltersMode(): {
671
mode: IndexFiltersMode;
672
setMode: (mode: IndexFiltersMode) => void;
673
};
674
```