-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathvaadin-app-layout-mixin.js
More file actions
527 lines (459 loc) · 16.3 KB
/
vaadin-app-layout-mixin.js
File metadata and controls
527 lines (459 loc) · 16.3 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/**
* @license
* Copyright (c) 2018 - 2026 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { AriaModalController } from '@vaadin/a11y-base/src/aria-modal-controller.js';
import { FocusTrapController } from '@vaadin/a11y-base/src/focus-trap-controller.js';
import { isKeyboardActive } from '@vaadin/a11y-base/src/focus-utils.js';
import { animationFrame } from '@vaadin/component-base/src/async.js';
import { Debouncer } from '@vaadin/component-base/src/debounce.js';
import { I18nMixin } from '@vaadin/component-base/src/i18n-mixin.js';
/**
* @typedef {import('./vaadin-app-layout.js').AppLayoutI18n} AppLayoutI18n
*/
const DEFAULT_I18N = {
drawer: 'Drawer',
};
/**
* @polymerMixin
* @mixes I18nMixin
*/
export const AppLayoutMixin = (superclass) =>
class AppLayoutMixinClass extends I18nMixin(DEFAULT_I18N, superclass) {
static get properties() {
return {
/**
* Defines whether navbar or drawer will come first visually.
* - By default (`primary-section="navbar"`), the navbar takes the full available width and moves the drawer down.
* - If `primary-section="drawer"` is set, then the drawer will move the navbar, taking the full available height.
* @attr {navbar|drawer} primary-section
*/
primarySection: {
type: String,
value: 'navbar',
notify: true,
reflectToAttribute: true,
observer: '__primarySectionChanged',
sync: true,
},
/**
* Controls whether the drawer is opened (visible) or not.
* Its default value depends on the viewport:
* - `true`, for desktop size views
* - `false`, for mobile size views
* @attr {boolean} drawer-opened
*/
drawerOpened: {
type: Boolean,
notify: true,
value: true,
reflectToAttribute: true,
observer: '__drawerOpenedChanged',
sync: true,
},
/**
* Drawer is an overlay on top of the content
* Controlled via CSS using `--vaadin-app-layout-drawer-overlay: true|false`;
*/
overlay: {
type: Boolean,
notify: true,
readOnly: true,
value: false,
reflectToAttribute: true,
observer: '__overlayChanged',
sync: true,
},
/**
* A global event that causes the drawer to close (be hidden) when it is in overlay mode.
* - The default is `vaadin-router-location-changed` dispatched by Vaadin Router
*
* @attr {string} close-drawer-on
*/
closeDrawerOn: {
type: String,
value: 'vaadin-router-location-changed',
observer: '_closeDrawerOnChanged',
},
};
}
static get observers() {
return ['__i18nChanged(__effectiveI18n)'];
}
/**
* Helper static method that dispatches a `close-overlay-drawer` event
*/
static dispatchCloseOverlayDrawerEvent() {
window.dispatchEvent(new CustomEvent('close-overlay-drawer'));
}
/**
* The object used to localize this component. To change the default
* localization, replace this with an object that provides all properties, or
* just the individual properties you want to change.
*
* The object has the following structure and default values:
* ```js
* {
* drawer: 'Drawer'
* }
* ```
* @type {!AppLayoutI18n}
*/
get i18n() {
return super.i18n;
}
set i18n(value) {
super.i18n = value;
}
constructor() {
super();
// TODO(jouni): might want to debounce
this.__drawerToggleClickListener = this._drawerToggleClick.bind(this);
this.__onDrawerKeyDown = this.__onDrawerKeyDown.bind(this);
this.__closeOverlayDrawerListener = this.__closeOverlayDrawer.bind(this);
this.__trapFocusInDrawer = this.__trapFocusInDrawer.bind(this);
this.__releaseFocusFromDrawer = this.__releaseFocusFromDrawer.bind(this);
// Hide all the elements except the drawer toggle and drawer content
this.__ariaModalController = new AriaModalController(this, () => [
...this.querySelectorAll('vaadin-drawer-toggle, [slot="drawer"]'),
]);
this.__focusTrapController = new FocusTrapController(this);
}
/** @protected */
connectedCallback() {
super.connectedCallback();
this.__resizeObserver = new ResizeObserver((entries) => this.__onResize(entries));
this.__resizeObserver.observe(this);
this.__resizeObserver.observe(this.$.drawer);
this.__resizeObserver.observe(this.$.navbarTop);
this.__resizeObserver.observe(this.$.navbarBottom);
this.addEventListener('drawer-toggle-click', this.__drawerToggleClickListener);
window.addEventListener('close-overlay-drawer', this.__closeOverlayDrawerListener);
window.addEventListener('keydown', this.__onDrawerKeyDown);
}
/** @protected */
ready() {
super.ready();
this.addController(this.__focusTrapController);
this.__setAriaExpanded();
this.$.drawer.addEventListener('transitionstart', () => {
this.__isDrawerAnimating = true;
});
this.$.drawer.addEventListener('transitionend', () => {
this.__isDrawerAnimating = false;
this.__scheduleResize(this.$.drawer);
});
}
/** @protected */
disconnectedCallback() {
super.disconnectedCallback();
this.__resizeObserver.disconnect();
this.removeEventListener('drawer-toggle-click', this.__drawerToggleClickListener);
window.removeEventListener('close-overlay-drawer', this.__drawerToggleClickListener);
window.removeEventListener('keydown', this.__onDrawerKeyDown);
}
/** @private */
__onNavbarSlotChange() {
this.__scheduleResize(this.$.navbarTop);
this.__scheduleResize(this.$.navbarBottom);
this.toggleAttribute('has-navbar', !!this.querySelector('[slot="navbar"]'));
}
/** @private */
__onDrawerSlotChange() {
this.__scheduleResize(this.$.drawer);
this.__updateDrawerSize();
this.toggleAttribute('has-drawer', !!this.querySelector('[slot="drawer"]'));
}
/** @private */
__onResize(entries) {
cancelAnimationFrame(this.__resizeRaf);
const isHostResized = entries.some(({ target }) => target === this);
const isNavbarResized = entries.some(({ target }) => [this.$.navbarTop, this.$.navbarBottom].includes(target));
const overlayMode = this._getCustomPropertyValue('--vaadin-app-layout-drawer-overlay') === 'true';
const touchOptimized = this._getCustomPropertyValue('--vaadin-app-layout-touch-optimized') === 'true';
const drawerRect = this.$.drawer.getBoundingClientRect();
const navbarTopRect = this.$.navbarTop.getBoundingClientRect();
const navbarBottomRect = this.$.navbarBottom.getBoundingClientRect();
const isDrawerAnimating = this.__isDrawerAnimating;
this.__resizeRaf = requestAnimationFrame(() => {
if (isHostResized) {
this._blockAnimationUntilAfterNextRender();
this.__setOverlayMode(overlayMode);
}
if (isHostResized || isNavbarResized) {
this.__setTouchOptimized(touchOptimized);
}
if (!isDrawerAnimating) {
this.__setOffsetSize({
drawerRect,
navbarTopRect,
navbarBottomRect,
});
}
});
}
/**
* A callback for the `primarySection` property observer.
*
* Ensures the property is set to its default value `navbar`
* whenever the new value is not one of the valid values: `navbar`, `drawer`.
*
* @param {string} value
* @private
*/
__primarySectionChanged(value) {
const isValid = ['navbar', 'drawer'].includes(value);
if (!isValid) {
this.primarySection = 'navbar';
}
}
/**
* A callback for the `drawerOpened` property observer.
*
* When the drawer opens, the method ensures the drawer has a proper height and sets focus on it.
* As long as the drawer is open, the focus is trapped within the drawer.
*
* When the drawer closes, the method releases focus from the drawer, setting focus on the drawer toggle.
*
* @param {boolean} drawerOpened
* @param {boolean} oldDrawerOpened
* @private
*/
__drawerOpenedChanged(drawerOpened, oldDrawerOpened) {
if (this.overlay) {
if (drawerOpened) {
this.__trapFocusInDrawer();
} else if (oldDrawerOpened) {
this.__releaseFocusFromDrawer();
}
}
this.__setAriaExpanded();
}
/**
* A callback for the `overlay` property observer.
*
* When layout resizes while in the overlay mode, drawer opened state
* is not changed, but focus trap needs to be removed.
*
* @param {boolean} overlay
* @param {boolean} oldOverlay
* @private
*/
__overlayChanged(_overlay, oldOverlay) {
if (oldOverlay) {
this.__restoreFocus();
}
}
/**
* A callback for the `i18n` property observer.
*
* The method ensures the drawer has ARIA attributes updated
* once the `i18n` property changes.
*
* @private
*/
__i18nChanged() {
this.__updateDrawerAriaAttributes();
}
/** @private */
_drawerToggleClick(e) {
e.stopPropagation();
this.drawerOpened = !this.drawerOpened;
}
/** @private */
__closeOverlayDrawer() {
if (this.overlay) {
this.drawerOpened = false;
}
}
/** @private */
__setAriaExpanded() {
const toggle = this.querySelector('vaadin-drawer-toggle');
if (toggle) {
toggle.setAttribute('aria-expanded', this.drawerOpened);
}
}
/** @private */
__updateDrawerSize() {
const childCount = this.querySelectorAll('[slot=drawer]').length;
if (childCount === 0) {
this.$.drawer.setAttribute('hidden', '');
this.style.setProperty('--_vaadin-app-layout-drawer-width', 0);
} else {
this.$.drawer.removeAttribute('hidden');
this.style.removeProperty('--_vaadin-app-layout-drawer-width');
}
}
/** @private */
__setOffsetSize({ drawerRect, navbarTopRect, navbarBottomRect }) {
this.style.setProperty('--_vaadin-app-layout-drawer-offset-size', `${drawerRect.width}px`);
this.style.setProperty('--_vaadin-app-layout-navbar-offset-size', `${navbarTopRect.height}px`);
this.style.setProperty('--_vaadin-app-layout-navbar-offset-size-bottom', `${navbarBottomRect.height}px`);
}
/** @private */
__setOverlayMode(overlay) {
if (!this.overlay && overlay) {
// Changed from not overlay to overlay
this._drawerStateSaved = this.drawerOpened;
this.drawerOpened = false;
}
this._setOverlay(overlay);
if (!this.overlay && this._drawerStateSaved) {
this.drawerOpened = this._drawerStateSaved;
this._drawerStateSaved = null;
}
this.__updateDrawerAriaAttributes();
}
/**
* Updates ARIA attributes on the drawer depending on the drawer mode.
*
* - In the overlay mode, the method marks the drawer with ARIA attributes as a dialog
* labelled with the `i18n.drawer` property.
* - In the normal mode, the method removes the ARIA attributes that has been set for the overlay mode.
*
* @private
*/
__updateDrawerAriaAttributes() {
const drawer = this.$.drawer;
if (this.overlay) {
drawer.setAttribute('role', 'dialog');
drawer.setAttribute('aria-modal', 'true');
drawer.setAttribute('aria-label', this.__effectiveI18n.drawer);
} else {
drawer.removeAttribute('role');
drawer.removeAttribute('aria-modal');
drawer.removeAttribute('aria-label');
}
}
/**
* Returns a promise that resolves when the drawer opening/closing CSS transition ends.
*
* @return {Promise}
* @private
*/
__drawerTransitionComplete() {
return Promise.all(this.$.drawer.getAnimations().map((animation) => animation.finished));
}
/** @private */
async __trapFocusInDrawer() {
// Wait for the drawer CSS transition before focusing the drawer
// in order for VoiceOver to have a proper outline.
await this.__drawerTransitionComplete();
if (!this.drawerOpened) {
// The drawer has been closed during the CSS transition.
return;
}
this.$.drawer.setAttribute('tabindex', '0');
this.__ariaModalController.showModal();
this.__focusTrapController.trapFocus(this.$.drawer);
}
/** @private */
async __releaseFocusFromDrawer() {
// Wait for the drawer CSS transition in order to restore focus to the toggle
// only after `visibility` becomes `hidden`, that is, the drawer becomes inaccessible by the tabbing navigation.
await this.__drawerTransitionComplete();
if (this.drawerOpened) {
// The drawer has been opened during the CSS transition.
return;
}
this.__restoreFocus();
// Move focus to the drawer toggle when closing the drawer.
const toggle = this.querySelector('vaadin-drawer-toggle');
if (toggle) {
toggle.focus({ focusVisible: isKeyboardActive() });
}
}
/** @private */
__restoreFocus() {
this.__ariaModalController.close();
this.__focusTrapController.releaseFocus();
this.$.drawer.removeAttribute('tabindex');
}
/**
* Closes the drawer on Escape press if it has been opened in the overlay mode.
*
* @param {KeyboardEvent} event
* @private
*/
__onDrawerKeyDown(event) {
if (event.key === 'Escape' && this.overlay) {
this.drawerOpened = false;
}
}
/** @private */
_closeDrawerOnChanged(closeDrawerOn, oldCloseDrawerOn) {
if (oldCloseDrawerOn) {
window.removeEventListener(oldCloseDrawerOn, this.__closeOverlayDrawerListener);
}
if (closeDrawerOn) {
window.addEventListener(closeDrawerOn, this.__closeOverlayDrawerListener);
}
}
/** @private */
_onBackdropClick() {
this._close();
}
/** @private */
_onBackdropTouchend(event) {
// Prevent the click event from being fired
// on clickable element behind the backdrop
event.preventDefault();
this._close();
}
/** @protected */
_close() {
this.drawerOpened = false;
}
/** @private */
_getCustomPropertyValue(customProperty) {
const customPropertyValue = getComputedStyle(this).getPropertyValue(customProperty);
return (customPropertyValue || '').trim().toLowerCase();
}
/** @private */
__setTouchOptimized(touchOptimized) {
const navbarItems = this.querySelectorAll('[slot*="navbar"]');
if (navbarItems.length > 0) {
Array.from(navbarItems).forEach((navbar) => {
if (navbar.getAttribute('slot').indexOf('touch-optimized') > -1) {
navbar.__touchOptimized = true;
}
if (touchOptimized && navbar.__touchOptimized) {
navbar.setAttribute('slot', 'navbar-bottom');
} else {
navbar.setAttribute('slot', 'navbar');
}
});
}
if (this.$.navbarTop.querySelector('[name=navbar]').assignedNodes().length === 0) {
this.$.navbarTop.setAttribute('hidden', '');
} else {
this.$.navbarTop.removeAttribute('hidden');
}
if (this.$.navbarBottom.querySelector('[name=navbar-bottom]').assignedNodes().length === 0) {
this.$.navbarBottom.setAttribute('hidden', '');
} else {
this.$.navbarBottom.removeAttribute('hidden');
}
}
/** @protected */
_blockAnimationUntilAfterNextRender() {
this.setAttribute('no-anim', '');
this.__debounceAnimation = Debouncer.debounce(this.__debounceAnimation, animationFrame, () => {
setTimeout(() => {
this.removeAttribute('no-anim');
});
});
}
/**
* Forces the ResizeObserver to re-report the size of the given element,
* scheduling a new {@link __onResize} callback even if the size hasn't changed.
*
* @param {Element} element
* @private
*/
__scheduleResize(element) {
this.__resizeObserver.unobserve(element);
this.__resizeObserver.observe(element);
}
};