-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.ts
More file actions
312 lines (261 loc) · 10.9 KB
/
Copy pathindex.ts
File metadata and controls
312 lines (261 loc) · 10.9 KB
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
import {
html, unsafeCSS, nothing, type PropertyValues,
} from 'lit';
import { html as staticHtml, unsafeStatic } from 'lit/static-html.js';
import { PieElement } from '@justeattakeaway/pie-webc-core/src/internals/PieElement';
import { property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import 'element-internals-polyfill';
import {
validPropertyValues,
FormControlMixin,
DelegatesFocusMixin,
AssociatedLabelMixin,
wrapNativeEvent,
safeCustomElement,
type PIEInputElement,
} from '@justeattakeaway/pie-webc-core';
import '@justeattakeaway/pie-icons-webc/dist/IconCheck.js';
import styles from './switch.scss?inline';
import { type SwitchProps, labelPlacements, defaultProps } from './defs';
// Valid values available to consumers
export * from './defs';
const componentSelector = 'pie-switch';
/**
* @tagname pie-switch
* @event {CustomEvent} change - when the switch checked state is changed.
*/
@safeCustomElement('pie-switch')
export class PieSwitch extends AssociatedLabelMixin(FormControlMixin(DelegatesFocusMixin(PieElement))) implements SwitchProps, PIEInputElement {
@property({ type: String })
public label: SwitchProps['label'];
@property({ type: String })
@validPropertyValues(componentSelector, labelPlacements, defaultProps.labelPlacement)
public labelPlacement = defaultProps.labelPlacement;
@property({ type: Object })
public aria: SwitchProps['aria'];
@property({ type: Boolean, reflect: true })
public checked = defaultProps.checked;
@property({ type: Boolean, reflect: true })
public defaultChecked = defaultProps.defaultChecked;
@property({ type: Boolean, reflect: true })
public required = defaultProps.required;
@property({ type: String })
public value = defaultProps.value;
@property({ type: String, reflect: true })
public name: SwitchProps['name'];
@property({ type: Boolean, reflect: true })
public disabled = defaultProps.disabled;
@query('input[type="checkbox"]')
private input!: HTMLInputElement;
@query('.c-switch')
private switchBody!: HTMLElement;
@query('label, input[type="checkbox"]')
public focusTarget!: HTMLElement;
private _abortController!: AbortController;
@state()
private _isAnimationAllowed = false;
protected firstUpdated (changedProperties: PropertyValues): void {
super.firstUpdated(changedProperties);
const { signal } = this._abortController;
this.handleFormAssociation();
// This ensures that invalid events triggered by checkValidity() are propagated to the custom element
// for consumers to listen to: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity
this.input.addEventListener('invalid', (event) => {
this.dispatchEvent(new Event('invalid', event));
}, { signal });
}
connectedCallback (): void {
super.connectedCallback();
this._abortController = new AbortController();
const { signal } = this._abortController;
this.addEventListener('click', (event: Event) => {
const [source] = event.composedPath();
if (this.disabled || source === this.input) {
return;
}
// Only programmatically click the input if the explicit target
// of the click was the host element itself (e.g., via an external label).
// This ignores clicks bubbling up from the internal shadow DOM and prevents loops.
// Also forward clicks from the visual switch body when no internal label exists.
const isInsideSwitchBody = !this.label && event.composedPath().includes(this.switchBody);
if (source === this || isInsideSwitchBody) {
this.input.click();
}
}, { signal });
}
disconnectedCallback () : void {
super.disconnectedCallback();
this._abortController?.abort();
}
protected updated (): void {
this.handleFormAssociation();
}
static styles = unsafeCSS(styles);
/**
* Ensures that the form value and validation state are in sync with the component.
*/
private handleFormAssociation () : void {
const isFormAssociated = !!this._internals.form && !!this.name && !!this.value;
if (isFormAssociated) {
if (this.disabled) {
this._internals.setFormValue(null);
this._internals.setValidity({});
} else if (this.checked) {
this._internals.setFormValue(this.value);
this._internals.setValidity({});
} else {
this._internals.setFormValue(null);
this._internals.setValidity(this.validity, this.validationMessage, this.input);
}
}
}
/**
* The handleChange function updates the checkbox state and emits an event for consumers.
* @param {Event} event - This should be the change event that was listened for on an input element with `type="checkbox"`.
*/
private handleChange (event: Event) {
const { checked } = event?.currentTarget as HTMLInputElement;
this.checked = checked;
const changedEvent = wrapNativeEvent(event);
if (!this._isAnimationAllowed) {
this._isAnimationAllowed = true;
}
this.dispatchEvent(changedEvent);
this.handleFormAssociation();
}
/**
* Returns a boolean value which indicates validity of the value of the component. If the value is invalid, this method also fires the invalid event on the component.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity
* @returns boolean
*/
public checkValidity (): boolean {
return this.input.checkValidity();
}
/**
* If the value is invalid, this method also fires the invalid event on the element, and (if the event isn't canceled) reports the problem to the user.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/reportValidity
* @returns boolean
*/
public reportValidity (): boolean {
return this.input.reportValidity();
}
/**
* Allows a consumer to set a custom validation message on the switch. An empty string counts as valid.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity
*/
public setCustomValidity (message: string): void {
this.input.setCustomValidity(message);
this._internals.setValidity(this.validity, this.validationMessage, this.input);
}
/**
* Called when the containing form is reset.
* Resets checked state back to defaultChecked and emits a change event when needed.
*/
public formResetCallback () : void {
if (this.checked === this.defaultChecked) {
return;
}
this.checked = this.defaultChecked;
const changeEvent = new Event('change', { bubbles: true, composed: true });
this.dispatchEvent(changeEvent);
this.handleFormAssociation();
}
/**
* (Read-only) returns a ValidityState with the validity states that this element is in.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/validity
*/
public get validity (): ValidityState {
return this.input.validity;
}
/**
* (Read-only) Returns a string representing a localized message that describes the validation constraints that the control does not satisfy (if any).
* This string is empty if the component is valid.
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/validationMessage
*/
public get validationMessage (): string {
return this.input.validationMessage;
}
private renderAriaDescription () {
if (!this.aria?.describedBy) {
return nothing;
}
// we apply aria-hidden to the element containing the description because it prevents some screen readers such as Apple VoiceOver from announcing the description once
// on the input and again separately. The description is still announced once, when the input is focused/selected.
return html`
<div
aria-hidden="true"
id="switch-description"
data-test-id="switch-description"
class="c-switch-description">
${this.aria.describedBy}
</div>`;
}
private renderSwitchLabel () {
const { label, labelPlacement } = this;
if (!label) {
return nothing;
}
// Using aria-hidden here to prevent the label from potentially being narrated twice by screen readers such as Apple VoiceOver.
// Instead, we apply the label as an aria-label attribute on the input (if no aria.label prop is provided).
return html`
<span
aria-hidden="true"
data-test-id="switch-label-${labelPlacement}"
class="c-switch-label">
${label}
</span>`;
}
render () {
const {
label,
labelPlacement,
aria,
checked,
disabled,
required,
_isAnimationAllowed,
associatedLabelText,
} = this;
const ariaLabel = aria?.label || label || associatedLabelText;
const classes = {
'c-switch-wrapper': true,
'c-switch-wrapper--allow-animation': _isAnimationAllowed,
[`c-switch-wrapper--label-${labelPlacement}`]: true,
};
const tag = unsafeStatic(label ? 'label' : 'div');
return staticHtml`
<${tag}
class="${classMap(classes)}"
?disabled=${disabled}>
<div
data-test-id="switch-component"
class="c-switch"
?checked=${checked}>
<input
data-test-id="switch-input"
role="switch"
type="checkbox"
class="c-switch-input"
?required=${required}
.checked="${live(checked)}"
?disabled="${disabled}"
@change="${this.handleChange}"
aria-label="${ifDefined(ariaLabel)}"
aria-describedby="${aria?.describedBy ? 'switch-description' : nothing}">
<div class="c-switch-control">
${checked ? html`<icon-check></icon-check>` : nothing}
</div>
</div>
${this.renderSwitchLabel()}
${this.renderAriaDescription()}
</${tag}>`;
}
}
declare global {
interface HTMLElementTagNameMap {
[componentSelector]: PieSwitch;
}
}