0
# UI Interaction APIs
1
2
Browser-based user interface interaction APIs including toast messages, modals, loading indicators, and action sheets for providing native-like user interface components in web environments.
3
4
## Capabilities
5
6
### Toast Messages
7
8
Display temporary notification messages with customizable appearance and duration.
9
10
```typescript { .api }
11
/**
12
* Show toast notification message
13
* @param options - Toast configuration options
14
* @returns Promise that resolves when toast is displayed
15
*/
16
function showToast(options: ToastOption): Promise<void>;
17
18
/**
19
* Hide currently displayed toast message
20
* @param options - Optional callback configuration
21
* @returns Promise that resolves when toast is hidden
22
*/
23
function hideToast(options?: CallbackOptions): Promise<void>;
24
25
interface ToastOption extends CallbackOptions {
26
/** Toast message text (required) */
27
title: string;
28
/** Icon type to display with message */
29
icon?: 'success' | 'error' | 'loading' | 'none';
30
/** Custom image URL (overrides icon) */
31
image?: string;
32
/** Display duration in milliseconds (default: 1500) */
33
duration?: number;
34
/** Whether to show overlay mask preventing interaction (default: false) */
35
mask?: boolean;
36
}
37
```
38
39
**Usage Examples:**
40
41
```typescript
42
import { showToast, hideToast } from "@tarojs/taro-h5";
43
44
// Success toast
45
await showToast({
46
title: 'Saved successfully!',
47
icon: 'success',
48
duration: 2000
49
});
50
51
// Error toast
52
await showToast({
53
title: 'Network error occurred',
54
icon: 'error',
55
duration: 3000
56
});
57
58
// Loading toast with mask
59
await showToast({
60
title: 'Processing...',
61
icon: 'loading',
62
mask: true,
63
duration: 0 // Show indefinitely
64
});
65
66
// Hide loading toast manually
67
setTimeout(() => {
68
hideToast();
69
}, 5000);
70
71
// Text-only toast
72
await showToast({
73
title: 'This is a simple message',
74
icon: 'none',
75
duration: 2000
76
});
77
78
// Custom image toast
79
await showToast({
80
title: 'Achievement unlocked!',
81
image: '/path/to/custom-icon.png',
82
duration: 2500
83
});
84
85
// With callbacks
86
showToast({
87
title: 'Operation completed',
88
icon: 'success',
89
success: () => {
90
console.log('Toast displayed');
91
},
92
complete: () => {
93
console.log('Toast operation finished');
94
}
95
});
96
```
97
98
### Loading Indicators
99
100
Display loading indicators with customizable messages and overlay behavior.
101
102
```typescript { .api }
103
/**
104
* Show loading indicator
105
* @param options - Loading configuration options
106
* @returns Promise that resolves when loading indicator is displayed
107
*/
108
function showLoading(options: LoadingOption): Promise<void>;
109
110
/**
111
* Hide currently displayed loading indicator
112
* @param options - Optional callback configuration
113
* @returns Promise that resolves when loading indicator is hidden
114
*/
115
function hideLoading(options?: CallbackOptions): Promise<void>;
116
117
interface LoadingOption extends CallbackOptions {
118
/** Loading message text (default: 'Loading...') */
119
title?: string;
120
/** Whether to show overlay mask preventing interaction (default: true) */
121
mask?: boolean;
122
}
123
```
124
125
**Usage Examples:**
126
127
```typescript
128
import { showLoading, hideLoading } from "@tarojs/taro-h5";
129
130
// Basic loading indicator
131
await showLoading({
132
title: 'Loading...'
133
});
134
135
// Simulate async operation
136
setTimeout(async () => {
137
await hideLoading();
138
await showToast({
139
title: 'Data loaded!',
140
icon: 'success'
141
});
142
}, 3000);
143
144
// Loading with custom message
145
await showLoading({
146
title: 'Uploading files...',
147
mask: true
148
});
149
150
// Loading without mask (allows user interaction)
151
await showLoading({
152
title: 'Syncing in background',
153
mask: false
154
});
155
156
// Async operation with loading
157
async function fetchUserData() {
158
try {
159
await showLoading({ title: 'Fetching user data...' });
160
161
const userData = await request({
162
url: '/api/user/profile',
163
method: 'GET'
164
});
165
166
await hideLoading();
167
return userData;
168
169
} catch (error) {
170
await hideLoading();
171
await showToast({
172
title: 'Failed to load user data',
173
icon: 'error'
174
});
175
throw error;
176
}
177
}
178
```
179
180
### Modal Dialogs
181
182
Display modal dialog boxes with customizable buttons and content for user confirmations and alerts.
183
184
```typescript { .api }
185
/**
186
* Show modal dialog
187
* @param options - Modal configuration options
188
* @returns Promise resolving to user's choice
189
*/
190
function showModal(options: ModalOption): Promise<ModalResult>;
191
192
interface ModalOption extends CallbackOptions {
193
/** Modal title text */
194
title?: string;
195
/** Modal body content text (required) */
196
content: string;
197
/** Whether to show cancel button (default: true) */
198
showCancel?: boolean;
199
/** Cancel button text (default: 'Cancel') */
200
cancelText?: string;
201
/** Cancel button text color (default: '#000000') */
202
cancelColor?: string;
203
/** Confirm button text (default: 'OK') */
204
confirmText?: string;
205
/** Confirm button text color (default: '#576B95') */
206
confirmColor?: string;
207
/** Whether to enable HTML content (default: false) */
208
editable?: boolean;
209
/** Placeholder text for editable input */
210
placeholderText?: string;
211
}
212
213
interface ModalResult {
214
/** Whether confirm button was clicked */
215
confirm: boolean;
216
/** Whether cancel button was clicked */
217
cancel: boolean;
218
/** Input text content (if editable is true) */
219
content?: string;
220
}
221
```
222
223
**Usage Examples:**
224
225
```typescript
226
import { showModal } from "@tarojs/taro-h5";
227
228
// Basic confirmation dialog
229
const confirmResult = await showModal({
230
title: 'Confirm Delete',
231
content: 'Are you sure you want to delete this item?',
232
showCancel: true,
233
confirmText: 'Delete',
234
confirmColor: '#ff4444'
235
});
236
237
if (confirmResult.confirm) {
238
console.log('User confirmed deletion');
239
// Proceed with deletion
240
} else {
241
console.log('User cancelled deletion');
242
}
243
244
// Alert dialog (no cancel button)
245
await showModal({
246
title: 'Information',
247
content: 'Your data has been saved successfully.',
248
showCancel: false,
249
confirmText: 'Got it'
250
});
251
252
// Custom styled modal
253
const customResult = await showModal({
254
title: 'Warning',
255
content: 'This action cannot be undone. Continue?',
256
showCancel: true,
257
cancelText: 'Go Back',
258
cancelColor: '#666666',
259
confirmText: 'Continue',
260
confirmColor: '#ff6600'
261
});
262
263
// Input modal (if supported)
264
const inputResult = await showModal({
265
title: 'Enter Name',
266
content: 'Please enter your name:',
267
editable: true,
268
placeholderText: 'Your name',
269
confirmText: 'Submit'
270
});
271
272
if (inputResult.confirm && inputResult.content) {
273
console.log('User entered:', inputResult.content);
274
}
275
276
// Error confirmation
277
async function confirmDangerousAction() {
278
const result = await showModal({
279
title: 'Danger Zone',
280
content: 'This will permanently delete all your data. This action cannot be undone.',
281
showCancel: true,
282
cancelText: 'Keep Data',
283
confirmText: 'Delete All',
284
confirmColor: '#ff0000'
285
});
286
287
return result.confirm;
288
}
289
```
290
291
### Action Sheets
292
293
Display action sheets with multiple selectable options for user choice scenarios.
294
295
```typescript { .api }
296
/**
297
* Show action sheet with multiple options
298
* @param options - Action sheet configuration
299
* @returns Promise resolving to user's selection
300
*/
301
function showActionSheet(options: ActionSheetOption): Promise<ActionSheetResult>;
302
303
interface ActionSheetOption extends CallbackOptions {
304
/** List of button text options (required) */
305
itemList: string[];
306
/** Button text colors (optional, matches itemList length) */
307
itemColor?: string[];
308
/** Alert text displayed above options */
309
alertText?: string;
310
}
311
312
interface ActionSheetResult {
313
/** Index of selected item (0-based) */
314
tapIndex: number;
315
}
316
```
317
318
**Usage Examples:**
319
320
```typescript
321
import { showActionSheet } from "@tarojs/taro-h5";
322
323
// Basic action sheet
324
const actionResult = await showActionSheet({
325
itemList: ['Take Photo', 'Choose from Album', 'Cancel']
326
});
327
328
switch (actionResult.tapIndex) {
329
case 0:
330
console.log('User chose to take photo');
331
// Open camera
332
break;
333
case 1:
334
console.log('User chose to select from album');
335
// Open photo picker
336
break;
337
case 2:
338
console.log('User cancelled');
339
break;
340
}
341
342
// Action sheet with custom colors
343
const colorResult = await showActionSheet({
344
itemList: ['Delete', 'Archive', 'Share', 'Cancel'],
345
itemColor: ['#ff4444', '#666666', '#0066cc', '#999999'],
346
alertText: 'Choose an action for this item'
347
});
348
349
// Share action sheet
350
async function showShareOptions() {
351
const shareResult = await showActionSheet({
352
itemList: [
353
'Share to WeChat',
354
'Share to Weibo',
355
'Copy Link',
356
'More Options',
357
'Cancel'
358
],
359
alertText: 'Share this content'
360
});
361
362
const actions = ['wechat', 'weibo', 'copylink', 'more', 'cancel'];
363
const selectedAction = actions[shareResult.tapIndex];
364
365
console.log('Selected share action:', selectedAction);
366
return selectedAction;
367
}
368
369
// Settings action sheet
370
async function showSettingsMenu() {
371
const settingsResult = await showActionSheet({
372
itemList: [
373
'Edit Profile',
374
'Privacy Settings',
375
'Notification Settings',
376
'Help & Support',
377
'Sign Out',
378
'Cancel'
379
],
380
itemColor: [
381
'#333333', // Edit Profile
382
'#333333', // Privacy Settings
383
'#333333', // Notification Settings
384
'#0066cc', // Help & Support
385
'#ff4444', // Sign Out (red)
386
'#999999' // Cancel (gray)
387
]
388
});
389
390
const menuActions = [
391
'editProfile',
392
'privacy',
393
'notifications',
394
'help',
395
'signOut',
396
'cancel'
397
];
398
399
return menuActions[settingsResult.tapIndex];
400
}
401
```
402
403
### Advanced Usage Patterns
404
405
Complex interaction patterns and best practices for UI components.
406
407
```typescript
408
// Chained interactions
409
async function deleteItemWithConfirmation(itemId: string) {
410
// First show action sheet
411
const actionResult = await showActionSheet({
412
itemList: ['Edit', 'Share', 'Delete', 'Cancel'],
413
itemColor: ['#333', '#0066cc', '#ff4444', '#999'],
414
alertText: 'Choose an action'
415
});
416
417
if (actionResult.tapIndex === 2) { // Delete selected
418
// Show confirmation modal
419
const confirmResult = await showModal({
420
title: 'Confirm Delete',
421
content: 'This item will be permanently deleted. Continue?',
422
confirmText: 'Delete',
423
confirmColor: '#ff4444'
424
});
425
426
if (confirmResult.confirm) {
427
// Show loading
428
await showLoading({ title: 'Deleting...' });
429
430
try {
431
await deleteItem(itemId);
432
await hideLoading();
433
434
// Show success toast
435
await showToast({
436
title: 'Item deleted',
437
icon: 'success'
438
});
439
440
return true;
441
} catch (error) {
442
await hideLoading();
443
await showToast({
444
title: 'Delete failed',
445
icon: 'error'
446
});
447
return false;
448
}
449
}
450
}
451
452
return false;
453
}
454
455
// Progress feedback pattern
456
async function uploadWithProgress(file: File) {
457
await showLoading({ title: 'Preparing upload...' });
458
459
try {
460
// Prepare upload
461
await new Promise(resolve => setTimeout(resolve, 1000));
462
463
await hideLoading();
464
await showLoading({ title: 'Uploading...' });
465
466
// Simulate upload progress
467
for (let i = 1; i <= 5; i++) {
468
await new Promise(resolve => setTimeout(resolve, 500));
469
await hideLoading();
470
await showLoading({ title: `Uploading... ${i * 20}%` });
471
}
472
473
await hideLoading();
474
await showToast({
475
title: 'Upload completed!',
476
icon: 'success',
477
duration: 2000
478
});
479
480
} catch (error) {
481
await hideLoading();
482
await showModal({
483
title: 'Upload Failed',
484
content: 'The file could not be uploaded. Please try again.',
485
showCancel: false
486
});
487
}
488
}
489
490
// Smart error handling
491
class UIInteractionHelper {
492
static async showError(message: string, details?: string): Promise<boolean> {
493
if (details) {
494
return (await showModal({
495
title: 'Error',
496
content: `${message}\n\nDetails: ${details}`,
497
showCancel: true,
498
cancelText: 'Dismiss',
499
confirmText: 'Retry'
500
})).confirm;
501
} else {
502
await showToast({
503
title: message,
504
icon: 'error',
505
duration: 3000
506
});
507
return false;
508
}
509
}
510
511
static async showSuccess(message: string): Promise<void> {
512
await showToast({
513
title: message,
514
icon: 'success',
515
duration: 2000
516
});
517
}
518
519
static async confirmAction(
520
title: string,
521
message: string,
522
actionText: string = 'Confirm'
523
): Promise<boolean> {
524
const result = await showModal({
525
title,
526
content: message,
527
confirmText: actionText,
528
confirmColor: '#0066cc'
529
});
530
return result.confirm;
531
}
532
533
static async selectOption(
534
title: string,
535
options: string[],
536
colors?: string[]
537
): Promise<number | null> {
538
try {
539
const result = await showActionSheet({
540
itemList: options,
541
itemColor: colors,
542
alertText: title
543
});
544
return result.tapIndex;
545
} catch {
546
return null; // User cancelled
547
}
548
}
549
}
550
551
// Usage of helper
552
async function handleUserAction() {
553
const option = await UIInteractionHelper.selectOption(
554
'Choose action',
555
['Save', 'Discard', 'Cancel'],
556
['#0066cc', '#ff6600', '#999']
557
);
558
559
switch (option) {
560
case 0: // Save
561
const confirmed = await UIInteractionHelper.confirmAction(
562
'Save Changes',
563
'Save your changes?',
564
'Save'
565
);
566
if (confirmed) {
567
await UIInteractionHelper.showSuccess('Changes saved!');
568
}
569
break;
570
571
case 1: // Discard
572
const shouldDiscard = await UIInteractionHelper.confirmAction(
573
'Discard Changes',
574
'All unsaved changes will be lost. Continue?',
575
'Discard'
576
);
577
if (shouldDiscard) {
578
await UIInteractionHelper.showSuccess('Changes discarded');
579
}
580
break;
581
582
default: // Cancel or null
583
console.log('Action cancelled');
584
}
585
}
586
```
587
588
## Types
589
590
```typescript { .api }
591
interface CallbackOptions {
592
success?: (res: any) => void;
593
fail?: (err: any) => void;
594
complete?: (res: any) => void;
595
}
596
597
type ToastIcon = 'success' | 'error' | 'loading' | 'none';
598
type ButtonColor = string; // CSS color value
599
```