forked from ionic-team/ionic-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoggle.tsx
435 lines (375 loc) · 12.9 KB
/
toggle.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Component, Element, Event, Host, Prop, State, Watch, h } from '@stencil/core';
import { renderHiddenInput, inheritAriaAttributes } from '@utils/helpers';
import type { Attributes } from '@utils/helpers';
import { hapticSelection } from '@utils/native/haptic';
import { isPlatform } from '@utils/platform';
import { isRTL } from '@utils/rtl';
import { createColorClasses, hostContext } from '@utils/theme';
import { checkmarkOutline, removeOutline, ellipseOutline } from 'ionicons/icons';
import { config } from '../../global/config';
import { getIonMode } from '../../global/ionic-global';
import type { Color, Gesture, GestureDetail, Mode } from '../../interface';
import type { ToggleChangeEventDetail } from './toggle-interface';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - The label text to associate with the toggle. Use the "labelPlacement" property to control where the label is placed relative to the toggle.
*
* @part track - The background track of the toggle.
* @part handle - The toggle handle, or knob, used to change the checked state.
* @part label - The label text describing the toggle.
* @part supporting-text - Supporting text displayed beneath the toggle label.
* @part helper-text - Supporting text displayed beneath the toggle label when the toggle is valid.
* @part error-text - Supporting text displayed beneath the toggle label when the toggle is invalid and touched.
*/
@Component({
tag: 'ion-toggle',
styleUrls: {
ios: 'toggle.ios.scss',
md: 'toggle.md.scss',
},
shadow: true,
})
export class Toggle implements ComponentInterface {
private inputId = `ion-tg-${toggleIds++}`;
private helperTextId = `${this.inputId}-helper-text`;
private errorTextId = `${this.inputId}-error-text`;
private gesture?: Gesture;
private focusEl?: HTMLElement;
private lastDrag = 0;
private inheritedAttributes: Attributes = {};
private toggleTrack?: HTMLElement;
private didLoad = false;
@Element() el!: HTMLIonToggleElement;
@State() activated = false;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop({ reflect: true }) color?: Color;
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name: string = this.inputId;
/**
* If `true`, the toggle is selected.
*/
@Prop({ mutable: true }) checked = false;
/**
* If `true`, the user cannot interact with the toggle.
*/
@Prop() disabled = false;
/**
* Text that is placed under the toggle label and displayed when an error is detected.
*/
@Prop() errorText?: string;
/**
* Text that is placed under the toggle label and displayed when no error is detected.
*/
@Prop() helperText?: string;
/**
* The value of the toggle does not mean if it's checked or not, use the `checked`
* property for that.
*
* The value of a toggle is analogous to the value of a `<input type="checkbox">`,
* it's only used when the toggle participates in a native `<form>`.
*/
@Prop() value?: string | null = 'on';
/**
* Enables the on/off accessibility switch labels within the toggle.
*/
@Prop() enableOnOffLabels: boolean | undefined = config.get('toggleOnOffLabels');
/**
* Where to place the label relative to the input.
* `"start"`: The label will appear to the left of the toggle in LTR and to the right in RTL.
* `"end"`: The label will appear to the right of the toggle in LTR and to the left in RTL.
* `"fixed"`: The label has the same behavior as `"start"` except it also has a fixed width. Long text will be truncated with ellipses ("...").
* `"stacked"`: The label will appear above the toggle regardless of the direction. The alignment of the label can be controlled with the `alignment` property.
*/
@Prop() labelPlacement: 'start' | 'end' | 'fixed' | 'stacked' = 'start';
/**
* How to pack the label and toggle within a line.
* `"start"`: The label and toggle will appear on the left in LTR and
* on the right in RTL.
* `"end"`: The label and toggle will appear on the right in LTR and
* on the left in RTL.
* `"space-between"`: The label and toggle will appear on opposite
* ends of the line with space between the two elements.
* Setting this property will change the toggle `display` to `block`.
*/
@Prop() justify?: 'start' | 'end' | 'space-between';
/**
* How to control the alignment of the toggle and label on the cross axis.
* `"start"`: The label and control will appear on the left of the cross axis in LTR, and on the right side in RTL.
* `"center"`: The label and control will appear at the center of the cross axis in both LTR and RTL.
* Setting this property will change the toggle `display` to `block`.
*/
@Prop() alignment?: 'start' | 'center';
/**
* If true, screen readers will announce it as a required field. This property
* works only for accessibility purposes, it will not prevent the form from
* submitting if the value is invalid.
*/
@Prop() required = false;
/**
* Emitted when the user switches the toggle on or off.
*
* This event will not emit when programmatically setting the `checked` property.
*/
@Event() ionChange!: EventEmitter<ToggleChangeEventDetail>;
/**
* Emitted when the toggle has focus.
*/
@Event() ionFocus!: EventEmitter<void>;
/**
* Emitted when the toggle loses focus.
*/
@Event() ionBlur!: EventEmitter<void>;
@Watch('disabled')
disabledChanged() {
if (this.gesture) {
this.gesture.enable(!this.disabled);
}
}
private toggleChecked() {
const { checked, value } = this;
const isNowChecked = !checked;
this.checked = isNowChecked;
this.setFocus();
this.ionChange.emit({
checked: isNowChecked,
value,
});
}
async connectedCallback() {
/**
* If we have not yet rendered
* ion-toggle, then toggleTrack is not defined.
* But if we are moving ion-toggle via appendChild,
* then toggleTrack will be defined.
*/
if (this.didLoad) {
this.setupGesture();
}
}
componentDidLoad() {
this.setupGesture();
this.didLoad = true;
}
private setupGesture = async () => {
const { toggleTrack } = this;
if (toggleTrack) {
this.gesture = (await import('../../utils/gesture')).createGesture({
el: toggleTrack,
gestureName: 'toggle',
gesturePriority: 100,
threshold: 5,
passive: false,
onStart: () => this.onStart(),
onMove: (ev) => this.onMove(ev),
onEnd: (ev) => this.onEnd(ev),
});
this.disabledChanged();
}
};
disconnectedCallback() {
if (this.gesture) {
this.gesture.destroy();
this.gesture = undefined;
}
}
componentWillLoad() {
this.inheritedAttributes = {
...inheritAriaAttributes(this.el),
};
}
private onStart() {
this.activated = true;
// touch-action does not work in iOS
this.setFocus();
}
private onMove(detail: GestureDetail) {
if (shouldToggle(isRTL(this.el), this.checked, detail.deltaX, -10)) {
this.toggleChecked();
hapticSelection();
}
}
private onEnd(ev: GestureDetail) {
this.activated = false;
this.lastDrag = Date.now();
ev.event.preventDefault();
ev.event.stopImmediatePropagation();
}
private getValue() {
return this.value || '';
}
private setFocus() {
if (this.focusEl) {
this.focusEl.focus();
}
}
private onClick = (ev: MouseEvent) => {
/**
* The haptics for the toggle on tap is
* an iOS-only feature. As such, it should
* only trigger on iOS.
*/
const enableHaptics = isPlatform('ios');
if (this.disabled) {
return;
}
ev.preventDefault();
if (this.lastDrag + 300 < Date.now()) {
this.toggleChecked();
enableHaptics && hapticSelection();
}
};
private onFocus = () => {
this.ionFocus.emit();
};
private onBlur = () => {
this.ionBlur.emit();
};
private getSwitchLabelIcon = (mode: Mode, checked: boolean) => {
if (mode === 'md') {
return checked ? checkmarkOutline : removeOutline;
}
return checked ? removeOutline : ellipseOutline;
};
private renderOnOffSwitchLabels(mode: Mode, checked: boolean) {
const icon = this.getSwitchLabelIcon(mode, checked);
return (
<ion-icon
class={{
'toggle-switch-icon': true,
'toggle-switch-icon-checked': checked,
}}
icon={icon}
aria-hidden="true"
></ion-icon>
);
}
private renderToggleControl() {
const mode = getIonMode(this);
const { enableOnOffLabels, checked } = this;
return (
<div class="toggle-icon" part="track" ref={(el) => (this.toggleTrack = el)}>
{/* The iOS on/off labels are rendered outside of .toggle-icon-wrapper,
since the wrapper is translated when the handle is interacted with and
this would move the on/off labels outside of the view box */}
{enableOnOffLabels &&
mode === 'ios' && [this.renderOnOffSwitchLabels(mode, true), this.renderOnOffSwitchLabels(mode, false)]}
<div class="toggle-icon-wrapper">
<div class="toggle-inner" part="handle">
{enableOnOffLabels && mode === 'md' && this.renderOnOffSwitchLabels(mode, checked)}
</div>
</div>
</div>
);
}
private get hasLabel() {
return this.el.textContent !== '';
}
private getHintTextID(): string | undefined {
const { el, helperText, errorText, helperTextId, errorTextId } = this;
if (el.classList.contains('ion-touched') && el.classList.contains('ion-invalid') && errorText) {
return errorTextId;
}
if (helperText) {
return helperTextId;
}
return undefined;
}
/**
* Responsible for rendering helper text and error text.
* This element should only be rendered if hint text is set.
*/
private renderHintText() {
const { helperText, errorText, helperTextId, errorTextId } = this;
/**
* undefined and empty string values should
* be treated as not having helper/error text.
*/
const hasHintText = !!helperText || !!errorText;
if (!hasHintText) {
return;
}
return (
<div class="toggle-bottom">
<div id={helperTextId} class="helper-text" part="supporting-text helper-text">
{helperText}
</div>
<div id={errorTextId} class="error-text" part="supporting-text error-text">
{errorText}
</div>
</div>
);
}
render() {
const { activated, color, checked, disabled, el, justify, labelPlacement, inputId, name, alignment, required } =
this;
const mode = getIonMode(this);
const value = this.getValue();
const rtl = isRTL(el) ? 'rtl' : 'ltr';
renderHiddenInput(true, el, name, checked ? value : '', disabled);
return (
<Host
aria-describedby={this.getHintTextID()}
aria-invalid={this.getHintTextID() === this.errorTextId}
onClick={this.onClick}
class={createColorClasses(color, {
[mode]: true,
'in-item': hostContext('ion-item', el),
'toggle-activated': activated,
'toggle-checked': checked,
'toggle-disabled': disabled,
[`toggle-justify-${justify}`]: justify !== undefined,
[`toggle-alignment-${alignment}`]: alignment !== undefined,
[`toggle-label-placement-${labelPlacement}`]: true,
[`toggle-${rtl}`]: true,
})}
>
<label class="toggle-wrapper">
{/*
The native control must be rendered
before the visible label text due to https://bugs.webkit.org/show_bug.cgi?id=251951
*/}
<input
type="checkbox"
role="switch"
aria-checked={`${checked}`}
checked={checked}
disabled={disabled}
id={inputId}
onFocus={() => this.onFocus()}
onBlur={() => this.onBlur()}
ref={(focusEl) => (this.focusEl = focusEl)}
required={required}
{...this.inheritedAttributes}
/>
<div
class={{
'label-text-wrapper': true,
'label-text-wrapper-hidden': !this.hasLabel,
}}
part="label"
>
<slot></slot>
{this.renderHintText()}
</div>
<div class="native-wrapper">{this.renderToggleControl()}</div>
</label>
</Host>
);
}
}
const shouldToggle = (rtl: boolean, checked: boolean, deltaX: number, margin: number): boolean => {
if (checked) {
return (!rtl && margin > deltaX) || (rtl && -margin < deltaX);
} else {
return (!rtl && -margin < deltaX) || (rtl && margin > deltaX);
}
};
let toggleIds = 0;