This repository has been archived by the owner on Aug 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialogs.js
116 lines (92 loc) · 2.13 KB
/
dialogs.js
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
import { Class } from './api';
import { InitialRender } from './initial-render';
import { FocusLocking, SubtreeFocus } from './focus';
import stack from './page-stack';
/**
* Dialog class and mixin. Provides an API similiar to the `<dialog>` element
* with an `open` and `close` method.
*
* The attribute `open` reflects if the dialog is open or not.
*/
export const Dialog = Class(ParentClass => class extends ParentClass
.with(SubtreeFocus, FocusLocking, InitialRender) {
static get observedAttributes() {
return [ 'open', ...super.observedAttributes ];
}
get open() {
return this.hasAttribute('open');
}
set open(v) {
if(v) {
this.setAttribute('open', '');
} else {
this.removeAttribute('open');
}
}
attributeChangedCallback(name, oldValue, newValue) {
super.attributeChangedCallback();
switch(name) {
case 'open':
if(newValue !== null) {
if(oldValue === null) {
this.dialogOpenCallback();
}
} else {
this.dialogCloseCallback();
}
break;
}
}
initialRenderCallback() {
super.initialRenderCallback();
// Make sure the dialog has the correct tole
this.setAttribute('role', 'dialog');
// Add listener to handle closing on escape
this.addEventListener('keyup', e => {
if(e.key === 'Escape') {
this.close({ default: true });
}
});
}
disconnectedCallback() {
super.disconnectedCallback();
if(this.open) {
this.dialogCloseCallback();
}
}
close(options = {}) {
if(options.default) {
this.dialogDefaultCloseCallback();
return;
}
this.open = false;
}
show() {
this.open = true;
}
dialogOpenCallback() {
this.grabFocus();
}
dialogCloseCallback() {
this.releaseFocus();
}
dialogDefaultCloseCallback() {
this.close();
}
});
export const ModalDialog = Class(ParentClass => class extends ParentClass.with(Dialog) {
initialRenderCallback() {
super.initialRenderCallback();
this.setAttribute('aria-modal', 'true');
}
dialogOpenCallback() {
super.dialogOpenCallback();
stack.show(this, () => {
this.close({ default: true });
});
}
dialogCloseCallback() {
stack.hide(this);
super.dialogCloseCallback();
}
});