0
# Platform Utilities
1
2
Utilities for platform detection, configuration management, and platform-specific adaptations that enable responsive behavior across iOS, Android, and web platforms.
3
4
## Capabilities
5
6
### Platform Detection
7
8
Functions for detecting the current platform and adapting application behavior accordingly.
9
10
```typescript { .api }
11
/**
12
* Check if the current platform matches the specified platform type.
13
* Useful for conditional rendering and platform-specific behavior.
14
* @param platform - Platform type to check against
15
* @returns true if the current platform matches the specified platform
16
*/
17
function isPlatform(platform: Platforms): boolean;
18
19
/**
20
* Get all currently active platforms as an array of strings.
21
* A device can match multiple platforms (e.g., ['mobile', 'ios', 'pwa']).
22
* @returns Array of currently active platform names
23
*/
24
function getPlatforms(): string[];
25
26
/**
27
* Platform types that can be detected by isPlatform.
28
*/
29
type Platforms =
30
/** iOS platform (iPhone, iPad) */
31
| 'ios'
32
/** Android platform */
33
| 'android'
34
/** Progressive Web App */
35
| 'pwa'
36
/** Any mobile platform (iOS or Android) */
37
| 'mobile'
38
/** Mobile web browser */
39
| 'mobileweb'
40
/** Desktop/laptop computer */
41
| 'desktop'
42
/** Hybrid app (Capacitor/Cordova) */
43
| 'hybrid'
44
/** Tablet device */
45
| 'tablet'
46
/** Phone device */
47
| 'phone'
48
/** Electron app */
49
| 'electron';
50
```
51
52
### Animation Utilities
53
54
Utilities for creating custom animations and integrating with Ionic's animation system.
55
56
```typescript { .api }
57
/**
58
* Creates a new animation with Web Animations API integration
59
* @returns Animation instance for chaining
60
*/
61
function createAnimation(animationId?: string): Animation;
62
63
/**
64
* Animation builder function type for custom transitions
65
*/
66
type AnimationBuilder = (
67
baseEl: any,
68
opts?: any
69
) => Animation;
70
71
/**
72
* iOS-style transition animation
73
*/
74
function iosTransitionAnimation(
75
navEl: HTMLElement,
76
opts: TransitionOptions
77
): Animation;
78
79
/**
80
* Material Design transition animation
81
*/
82
function mdTransitionAnimation(
83
navEl: HTMLElement,
84
opts: TransitionOptions
85
): Animation;
86
87
/**
88
* Utility for animation timing calculations
89
*/
90
function getTimeGivenProgression(
91
p0: number,
92
p1: number,
93
p2: number,
94
p3: number,
95
progression: number
96
): number;
97
98
interface Animation {
99
/** Add one or more elements to the animation */
100
addElement(el: Element | Element[] | Node | Node[]): Animation;
101
/** Add CSS class to animation elements */
102
addClassNames(classNames: string[]): Animation;
103
/** Remove CSS class from animation elements */
104
removeClassNames(classNames: string[]): Animation;
105
/** Set animation properties */
106
duration(milliseconds: number): Animation;
107
easing(name: string): Animation;
108
from(property: string, value: any): Animation;
109
to(property: string, value: any): Animation;
110
/** Set keyframes for the animation */
111
keyframes(keyframes: any[]): Animation;
112
/** Control animation playback */
113
play(): Promise<void>;
114
pause(): Animation;
115
stop(): Animation;
116
destroy(): Animation;
117
/** Animation callbacks */
118
onFinish(callback: (didComplete: boolean, animation: Animation) => void): Animation;
119
beforeStyles(styles: { [property: string]: any }): Animation;
120
afterStyles(styles: { [property: string]: any }): Animation;
121
}
122
123
interface TransitionOptions {
124
mode?: string;
125
animated?: boolean;
126
direction?: 'forward' | 'back';
127
duration?: number;
128
easing?: string;
129
progressAnimation?: boolean;
130
}
131
```
132
133
### Gesture Utilities
134
135
Utilities for creating custom gestures and handling touch interactions.
136
137
```typescript { .api }
138
/**
139
* Creates a custom gesture with touch/mouse event handling
140
* @param options - Gesture configuration options
141
* @returns Gesture instance
142
*/
143
function createGesture(options: GestureConfig): Gesture;
144
145
interface GestureConfig {
146
/** Element to attach gesture to */
147
el: HTMLElement;
148
/** Gesture name/identifier */
149
gestureName: string;
150
/** Threshold before gesture starts */
151
threshold?: number;
152
/** Gesture priority */
153
gesturePriority?: number;
154
/** Whether gesture can start */
155
canStart?: (detail: GestureDetail) => boolean;
156
/** Gesture start callback */
157
onStart?: (detail: GestureDetail) => void;
158
/** Gesture move callback */
159
onMove?: (detail: GestureDetail) => void;
160
/** Gesture end callback */
161
onEnd?: (detail: GestureDetail) => void;
162
/** Whether to capture events */
163
capture?: boolean;
164
/** Passive event listeners */
165
passive?: boolean;
166
}
167
168
interface Gesture {
169
/** Enable the gesture */
170
enable(enable?: boolean): void;
171
/** Destroy the gesture */
172
destroy(): void;
173
}
174
175
interface GestureDetail {
176
/** Gesture type */
177
type: string;
178
/** Starting X coordinate */
179
startX: number;
180
/** Starting Y coordinate */
181
startY: number;
182
/** Current X coordinate */
183
currentX: number;
184
/** Current Y coordinate */
185
currentY: number;
186
/** Change in X from start */
187
deltaX: number;
188
/** Change in Y from start */
189
deltaY: number;
190
/** Time elapsed since start */
191
timeStamp: number;
192
/** Original event */
193
event: any;
194
/** Additional data */
195
data?: any;
196
}
197
```
198
199
### Swiper Integration
200
201
Integration with Swiper.js for advanced slider functionality.
202
203
```typescript { .api }
204
/**
205
* IonicSlides - Swiper integration for Ionic
206
* Configuration object for Swiper with Ionic-specific defaults
207
*/
208
const IonicSlides: {
209
/** Enable touch gestures */
210
touch?: boolean;
211
/** Enable keyboard navigation */
212
keyboard?: boolean;
213
/** Enable mouse wheel control */
214
mousewheel?: boolean;
215
/** Autoplay configuration */
216
autoplay?: boolean | object;
217
/** Loop slides */
218
loop?: boolean;
219
/** Number of slides per view */
220
slidesPerView?: number | 'auto';
221
/** Space between slides */
222
spaceBetween?: number;
223
/** Pagination configuration */
224
pagination?: boolean | object;
225
/** Navigation arrows */
226
navigation?: boolean | object;
227
/** Scrollbar */
228
scrollbar?: boolean | object;
229
/** Free mode */
230
freeMode?: boolean;
231
/** Effect transition */
232
effect?: 'slide' | 'fade' | 'cube' | 'coverflow' | 'flip';
233
};
234
```
235
236
### Utility Functions
237
238
Additional platform and navigation utilities.
239
240
```typescript { .api }
241
/**
242
* Get the IonPage element for the current view
243
*/
244
function getIonPageElement(element: HTMLElement): HTMLElement | null;
245
246
/**
247
* Open URL with appropriate handler for the platform
248
*/
249
function openURL(
250
url: string,
251
target?: string,
252
features?: string
253
): Promise<void>;
254
```
255
256
### Configuration Management
257
258
Functions for managing global Ionic configuration and retrieving current settings.
259
260
```typescript { .api }
261
/**
262
* Get the current Ionic configuration object.
263
* Returns the configuration set by setupIonicReact or platform defaults.
264
* @returns Current Ionic configuration or null if not initialized
265
*/
266
function getConfig(): IonicConfig | null;
267
268
/**
269
* Global configuration interface for Ionic React.
270
* These settings affect the behavior and appearance of all Ionic components.
271
*/
272
interface IonicConfig {
273
/** Enable/disable ripple effect on interactive elements globally */
274
rippleEffect?: boolean;
275
/** Global mode setting for all components */
276
mode?: 'ios' | 'android' | 'md';
277
/** Enable/disable swipe-to-go-back gesture */
278
swipeBackEnabled?: boolean;
279
/** Enable/disable animations globally */
280
animated?: boolean;
281
/** Animation duration in milliseconds */
282
animationDuration?: number;
283
/** Default spinner type for loading components */
284
spinner?: SpinnerTypes;
285
/** Platform-specific configuration overrides */
286
platforms?: {
287
[platform: string]: Partial<IonicConfig>;
288
};
289
/** Menu settings */
290
menuIcon?: string;
291
menuType?: 'overlay' | 'reveal' | 'push';
292
/** Back button settings */
293
backButtonIcon?: string;
294
backButtonText?: string;
295
/** Tab bar settings */
296
tabButtonLayout?: 'icon-top' | 'icon-start' | 'icon-end' | 'icon-bottom' | 'icon-hide' | 'label-hide';
297
/** Global color scheme */
298
darkMode?: boolean;
299
}
300
301
/**
302
* Available spinner types for loading indicators.
303
*/
304
type SpinnerTypes =
305
| 'bubbles'
306
| 'circles'
307
| 'circular'
308
| 'crescent'
309
| 'dots'
310
| 'lines'
311
| 'lines-small';
312
```
313
314
### Animation Utilities
315
316
Utilities for creating and managing animations with platform-specific behavior.
317
318
```typescript { .api }
319
/**
320
* Declarative animation component for creating complex animations.
321
* Provides a React wrapper around Ionic's createAnimation API.
322
*/
323
const CreateAnimation: React.FC<{
324
/** Animation delay in milliseconds */
325
delay?: number;
326
/** Animation direction */
327
direction?: 'normal' | 'reverse' | 'alternate' | 'alternate-reverse';
328
/** Animation duration in milliseconds */
329
duration?: number;
330
/** Animation easing function */
331
easing?: string;
332
/** End delay in milliseconds */
333
endDelay?: number;
334
/** Animation fill mode */
335
fill?: 'none' | 'forwards' | 'backwards' | 'both';
336
/** Number of iterations */
337
iterations?: number;
338
/** Animation keyframes */
339
keyframes?: any[];
340
/** Play state */
341
play?: boolean;
342
/** Animation builder function */
343
children?: (animation: Animation) => React.ReactNode;
344
/** Callback when animation starts */
345
onAnimationStart?: (animation: Animation) => void;
346
/** Callback when animation ends */
347
onAnimationEnd?: (animation: Animation) => void;
348
}>;
349
350
/**
351
* Animation instance interface for controlling animations.
352
*/
353
interface Animation {
354
/** Add CSS class to animated elements */
355
addElement(element: HTMLElement | HTMLElement[]): Animation;
356
/** Remove CSS class from animated elements */
357
removeElement(element: HTMLElement | HTMLElement[]): Animation;
358
/** Add CSS class during animation */
359
addClasses(classes: string[]): Animation;
360
/** Remove CSS class during animation */
361
removeClasses(classes: string[]): Animation;
362
/** Set CSS properties for animation */
363
css(property: string, value: string): Animation;
364
/** Set transform properties */
365
transform(transform: string): Animation;
366
/** Play the animation */
367
play(): Promise<void>;
368
/** Pause the animation */
369
pause(): Animation;
370
/** Stop the animation */
371
stop(): Animation;
372
/** Destroy the animation */
373
destroy(): Animation;
374
}
375
```
376
377
378
**Usage Examples:**
379
380
```typescript
381
import React from 'react';
382
import {
383
isPlatform,
384
getPlatforms,
385
getConfig,
386
CreateAnimation,
387
IonButton,
388
IonContent,
389
IonPage
390
} from '@ionic/react';
391
392
// Platform-specific rendering
393
const PlatformSpecificComponent: React.FC = () => {
394
const isIOS = isPlatform('ios');
395
const isAndroid = isPlatform('android');
396
const isMobile = isPlatform('mobile');
397
const platforms = getPlatforms();
398
399
return (
400
<IonContent>
401
<div>
402
<p>Current platforms: {platforms.join(', ')}</p>
403
404
{isIOS && (
405
<p>Welcome iOS user! Enjoy the native iOS experience.</p>
406
)}
407
408
{isAndroid && (
409
<p>Welcome Android user! Material Design at its finest.</p>
410
)}
411
412
{!isMobile && (
413
<p>You're using a desktop browser. Consider our mobile app!</p>
414
)}
415
416
<IonButton
417
fill={isIOS ? 'outline' : 'solid'}
418
color={isAndroid ? 'primary' : 'secondary'}
419
>
420
Platform-styled Button
421
</IonButton>
422
</div>
423
</IonContent>
424
);
425
};
426
427
// Configuration-based behavior
428
const ConfigAwareComponent: React.FC = () => {
429
const config = getConfig();
430
const isAnimated = config?.animated !== false;
431
const rippleEffect = config?.rippleEffect !== false;
432
433
return (
434
<IonButton
435
className={!rippleEffect ? 'no-ripple' : ''}
436
style={{
437
transition: isAnimated ? 'all 0.3s ease' : 'none'
438
}}
439
>
440
{isAnimated ? 'Animated Button' : 'Static Button'}
441
</IonButton>
442
);
443
};
444
445
// Animation example
446
const AnimatedComponent: React.FC = () => {
447
return (
448
<CreateAnimation
449
duration={1000}
450
iterations={1}
451
direction="normal"
452
fill="forwards"
453
keyframes={[
454
{ offset: 0, transform: 'scale(1) rotate(0deg)', opacity: '1' },
455
{ offset: 0.5, transform: 'scale(1.2) rotate(180deg)', opacity: '0.8' },
456
{ offset: 1, transform: 'scale(1) rotate(360deg)', opacity: '1' }
457
]}
458
onAnimationEnd={(animation) => console.log('Animation completed')}
459
>
460
{(animation) => (
461
<div
462
ref={(el) => el && animation.addElement(el)}
463
style={{
464
width: '100px',
465
height: '100px',
466
backgroundColor: 'var(--ion-color-primary)'
467
}}
468
>
469
Animated Element
470
</div>
471
)}
472
</CreateAnimation>
473
);
474
};
475
476
// Responsive design with platform detection
477
const ResponsiveLayout: React.FC = () => {
478
const isTablet = isPlatform('tablet');
479
const isDesktop = isPlatform('desktop');
480
const isMobile = isPlatform('mobile');
481
482
const getColumnSize = () => {
483
if (isDesktop) return '4';
484
if (isTablet) return '6';
485
return '12';
486
};
487
488
return (
489
<IonGrid>
490
<IonRow>
491
<IonCol size={getColumnSize()}>
492
<IonCard>
493
<IonCardContent>
494
Content optimized for {
495
isDesktop ? 'desktop' :
496
isTablet ? 'tablet' :
497
'mobile'
498
}
499
</IonCardContent>
500
</IonCard>
501
</IonCol>
502
</IonRow>
503
</IonGrid>
504
);
505
};
506
507
// Custom hook for platform-specific logic
508
const usePlatformSpecificBehavior = () => {
509
const isIOS = isPlatform('ios');
510
const isAndroid = isPlatform('android');
511
const config = getConfig();
512
513
const getButtonStyle = () => ({
514
borderRadius: isIOS ? '8px' : '4px',
515
padding: isIOS ? '12px 24px' : '10px 20px',
516
fontWeight: isIOS ? '600' : '500'
517
});
518
519
const getTransitionDuration = () => {
520
if (config?.animated === false) return '0ms';
521
return isIOS ? '300ms' : '250ms';
522
};
523
524
return {
525
isIOS,
526
isAndroid,
527
getButtonStyle,
528
getTransitionDuration,
529
hapticFeedbackEnabled: isIOS || (isAndroid && isPlatform('hybrid'))
530
};
531
};
532
533
// Usage of custom hook
534
const PlatformAwareButton: React.FC<{ children: React.ReactNode }> = ({ children }) => {
535
const { getButtonStyle, getTransitionDuration, hapticFeedbackEnabled } = usePlatformSpecificBehavior();
536
537
const handleClick = () => {
538
if (hapticFeedbackEnabled) {
539
// Trigger haptic feedback on supported platforms
540
// This would require Capacitor Haptics plugin
541
}
542
console.log('Button clicked');
543
};
544
545
return (
546
<IonButton
547
style={{
548
...getButtonStyle(),
549
transition: `all ${getTransitionDuration()} ease`
550
}}
551
onClick={handleClick}
552
>
553
{children}
554
</IonButton>
555
);
556
};
557
```
558
559
## Platform Detection Reference
560
561
| Platform | Description | When it matches |
562
|----------|-------------|-----------------|
563
| `ios` | iOS devices | iPhone, iPad running iOS |
564
| `android` | Android devices | Devices running Android OS |
565
| `mobile` | Mobile devices | Any mobile device (iOS or Android) |
566
| `tablet` | Tablet devices | iPad or Android tablets |
567
| `phone` | Phone devices | iPhone or Android phones |
568
| `desktop` | Desktop browsers | Desktop/laptop browsers |
569
| `pwa` | Progressive Web App | App installed as PWA |
570
| `hybrid` | Hybrid app | Capacitor or Cordova app |
571
| `electron` | Electron app | App running in Electron |
572
| `mobileweb` | Mobile web | Mobile browser (not hybrid) |
573
574
## Best Practices
575
576
1. **Responsive Design**: Use platform detection for responsive layouts and component behavior
577
2. **Performance**: Check platform capabilities to enable/disable features appropriately
578
3. **User Experience**: Adapt animations and transitions to platform conventions
579
4. **Testing**: Test platform-specific code paths across different devices and browsers
580
5. **Progressive Enhancement**: Use platform detection to enhance experiences rather than restrict them