/
mwc-radio-base.ts
320 lines (274 loc) · 8.51 KB
/
mwc-radio-base.ts
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
/**
@license
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import {addHasRemoveClass, FormElement, html, HTMLElementWithRipple, observer, property, query} from '@material/mwc-base/form-element.js';
import {ripple} from '@material/mwc-ripple/ripple-directive.js';
import {MDCRadioAdapter} from '@material/radio/adapter.js';
import MDCRadioFoundation from '@material/radio/foundation.js';
export class RadioBase extends FormElement {
@query('.mdc-radio') protected mdcRoot!: HTMLElementWithRipple;
@query('input') protected formElement!: HTMLInputElement;
private _checked = false;
@property({type: Boolean, reflect: true})
get checked() {
return this._checked;
}
/**
* We define our own getter/setter for `checked` because we need to track
* changes to it synchronously.
*
* The order in which the `checked` property is set across radio buttons
* within the same group is very important. However, we can't rely on
* UpdatingElement's `updated` callback to observe these changes (which is
* also what the `@observer` decorator uses), because it batches changes to
* all properties.
*
* Consider:
*
* radio1.disabled = true;
* radio2.checked = true;
* radio1.checked = true;
*
* In this case we'd first see all changes for radio1, and then for radio2,
* and we couldn't tell that radio1 was the most recently checked.
*/
set checked(checked: boolean) {
const oldValue = this._checked;
if (!!checked === !!oldValue) {
return;
}
this._checked = checked;
if (this.formElement) {
this.formElement.checked = checked;
}
if (this._selectionController) {
this._selectionController.update(this);
}
this.requestUpdate('checked', oldValue);
}
@property({type: Boolean})
@observer(function(this: RadioBase, disabled: boolean) {
this.mdcFoundation.setDisabled(disabled);
})
disabled = false;
@property({type: String})
@observer(function(this: RadioBase, value: string) {
this.formElement.value = value;
})
value = '';
@property({type: String}) name = '';
protected mdcFoundationClass = MDCRadioFoundation;
protected mdcFoundation!: MDCRadioFoundation;
private _selectionController: SelectionController|null = null;
constructor() {
super();
// Selection Controller is only needed for native ShadowDOM
if (!window['ShadyDOM'] || !window['ShadyDOM']['inUse']) {
this._selectionController = SelectionController.getController(this);
}
}
connectedCallback() {
super.connectedCallback();
if (this._selectionController) {
this._selectionController.register(this);
}
}
disconnectedCallback() {
if (this._selectionController) {
this._selectionController.unregister(this);
}
}
focusNative() {
this.formElement.focus();
}
get ripple() {
return this.mdcRoot.ripple;
}
protected createAdapter(): MDCRadioAdapter {
return {
...addHasRemoveClass(this.mdcRoot),
setNativeControlDisabled: (disabled: boolean) => {
this.formElement.disabled = disabled;
},
};
}
private _changeHandler() {
this.checked = this.formElement.checked;
if (this._selectionController) {
this._selectionController.update(this);
}
}
private _focusHandler() {
if (this._selectionController) {
this._selectionController.focus(this);
}
}
private _clickHandler() {
// Firefox has weird behavior with radios if they are not focused
this.formElement.focus();
}
render() {
return html`
<div class="mdc-radio" .ripple="${ripple()}">
<input
class="mdc-radio__native-control"
type="radio"
name="${this.name}"
.checked="${this.checked}"
.value="${this.value}"
@change="${this._changeHandler}"
@focus="${this._focusHandler}"
@click="${this._clickHandler}">
<div class="mdc-radio__background">
<div class="mdc-radio__outer-circle"></div>
<div class="mdc-radio__inner-circle"></div>
</div>
</div>`;
}
firstUpdated() {
super.firstUpdated();
// We might not have been able to synchronize this from the checked setter
// earlier, if checked was set before the input was stamped.
this.formElement.checked = this.checked;
if (this._selectionController) {
this._selectionController.update(this);
}
}
}
/**
* Unique symbol for marking roots
*/
const selectionController = Symbol('selection controller');
class SelectionSet {
selected: RadioBase|null = null;
ordered: RadioBase[]|null = null;
readonly set = new Set<RadioBase>();
}
export class SelectionController {
private sets: {[name: string]: SelectionSet} = {};
private focusedSet: SelectionSet|null = null;
private mouseIsDown = false;
private updating = false;
static getController(element: HTMLElement) {
const root = element.getRootNode() as Node &
{[selectionController]?: SelectionController};
if (!root[selectionController]) {
root[selectionController] = new SelectionController(root);
}
return root[selectionController] as SelectionController;
}
constructor(element: Node) {
element.addEventListener(
'keydown', (e: Event) => this.keyDownHandler(e as KeyboardEvent));
element.addEventListener('mousedown', () => this.mousedownHandler());
element.addEventListener('mouseup', () => this.mouseupHandler());
}
protected keyDownHandler(e: KeyboardEvent) {
if (!(e.target instanceof RadioBase)) {
return;
}
const element = e.target;
if (!this.has(element)) {
return;
}
if (e.key == 'ArrowRight' || e.key == 'ArrowDown') {
this.next(element);
} else if (e.key == 'ArrowLeft' || e.key == 'ArrowUp') {
this.previous(element);
}
}
protected mousedownHandler() {
this.mouseIsDown = true;
}
protected mouseupHandler() {
this.mouseIsDown = false;
}
has(element: RadioBase) {
const set = this.getSet(element.name);
return set.set.has(element);
}
previous(element: RadioBase) {
const order = this.getOrdered(element);
const i = order.indexOf(element);
this.select(order[i - 1] || order[order.length - 1]);
}
next(element: RadioBase) {
const order = this.getOrdered(element);
const i = order.indexOf(element);
this.select(order[i + 1] || order[0]);
}
select(element: RadioBase) {
element.click();
}
/**
* Helps to track the focused selection group and if it changes, focuses
* the selected item in the group. This matches native radio button behavior.
*/
focus(element: RadioBase) {
// Only manage focus state when using keyboard
if (this.mouseIsDown) {
return;
}
const set = this.getSet(element.name);
const currentFocusedSet = this.focusedSet;
this.focusedSet = set;
if (currentFocusedSet != set && set.selected && set.selected != element) {
set.selected!.focusNative();
}
}
getOrdered(element: RadioBase) {
const set = this.getSet(element.name);
if (!set.ordered) {
set.ordered = Array.from(set.set);
set.ordered.sort(
(a, b) =>
a.compareDocumentPosition(b) == Node.DOCUMENT_POSITION_PRECEDING ?
1 :
0);
}
return set.ordered;
}
getSet(name: string) {
if (!this.sets[name]) {
this.sets[name] = new SelectionSet();
}
return this.sets[name];
}
register(element: RadioBase) {
const set = this.getSet(element.name);
set.set.add(element);
set.ordered = null;
}
unregister(element: RadioBase) {
const set = this.getSet(element.name);
set.set.delete(element);
set.ordered = null;
if (set.selected == element) {
set.selected = null;
}
}
update(element: RadioBase) {
if (this.updating) {
return;
}
this.updating = true;
if (element.checked) {
const set = this.getSet(element.name);
for (const e of set.set) {
e.checked = (e == element);
}
set.selected = element;
}
this.updating = false;
}
}