-
Notifications
You must be signed in to change notification settings - Fork 81
/
KModal.vue
453 lines (420 loc) · 12.9 KB
/
KModal.vue
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
<template>
<!-- Accessibility properties for the overlay -->
<transition name="modal-fade" appear>
<div
id="modal-window"
ref="modal-overlay"
class="modal-overlay"
@keyup.esc.stop="emitCancelEvent"
@keyup.enter="handleEnter"
>
<!-- KeenUiSelect targets modal by using div.modal selector -->
<div
ref="modal"
class="modal"
:tabindex="0"
role="dialog"
aria-labelledby="modal-title"
:style="[
modalSizeStyles,
{ background: $themeTokens.surface },
containsKSelect ? { overflowY: 'unset' } : { overflowY: 'auto' }
]"
>
<!-- Modal Title -->
<h1
id="modal-title"
ref="title"
class="title"
>
{{ title }}
<!-- Accessible error reporting per @radina -->
<span
v-if="hasError"
class="visuallyhidden"
>
{{ errorMessage }}
</span>
</h1>
<!-- Stop propagation of enter key to prevent the submit event from being emitted twice -->
<form
class="form"
@submit.prevent="emitSubmitEvent"
@keyup.enter.stop
>
<!-- Wrapper for main content -->
<div
ref="content"
class="content"
:style="[ contentSectionMaxHeight, scrollShadow ? {
borderTop: `1px solid ${$themeTokens.fineLine}`,
borderBottom: `1px solid ${$themeTokens.fineLine}`,
} : {} ]"
:class="{
'scroll-shadow': scrollShadow,
'contains-kselect': containsKSelect
}"
>
<!-- @slot Main content of modal -->
<slot></slot>
</div>
<div
ref="actions"
class="actions"
>
<!-- @slot Alternative buttons and actions below main content -->
<slot
v-if="$slots.actions"
name="actions"
>
</slot>
<template v-else>
<KButton
v-if="cancelText"
name="cancel"
:text="cancelText"
appearance="flat-button"
:disabled="cancelDisabled || $attrs.disabled"
@click="emitCancelEvent"
/>
<KButton
v-if="submitText"
name="submit"
:text="submitText"
:primary="true"
:disabled="submitDisabled || $attrs.disabled"
type="submit"
/>
</template>
</div>
</form>
</div>
</div>
</transition>
</template>
<script>
import debounce from 'lodash/debounce';
import KResponsiveWindowMixin from './KResponsiveWindowMixin';
const SIZE_SM = 'small';
const SIZE_MD = 'medium';
const SIZE_LG = 'large';
const SIZE_STRINGS = [SIZE_SM, SIZE_MD, SIZE_LG];
// check for Nuxt.js SSR
const nuxtServerSideRendering = process && process.server;
/**
* Used to focus attention on a singular action/task
*/
export default {
name: 'KModal',
mixins: [KResponsiveWindowMixin],
props: {
/**
* The title of the modal
*/
title: {
type: String,
required: true,
},
/**
* If provided, text of the submit button
*/
submitText: {
type: String,
default: null,
},
/**
* If provided, text of the cancel button
*/
cancelText: {
type: String,
default: null,
},
/**
* Disable the submit button
*/
submitDisabled: {
type: Boolean,
default: false,
},
/**
* Disable the cancel button
*/
cancelDisabled: {
type: Boolean,
default: false,
},
/**
* Width of modal. For consistency use the strings `'small'`, `'medium'`, or `'large'`.
* For more precise control use an integer number of pixels.
*/
size: {
type: [String, Number],
default: 'medium',
validator(val) {
if (typeof val === 'string') {
if (!SIZE_STRINGS.includes(val)) {
console.error(`'${val}' is not one of: ${SIZE_STRINGS}`);
return false;
}
return true;
}
return val > 0;
},
},
/**
* Toggles error message indicator in title
*/
hasError: {
type: Boolean,
default: false,
},
errorMessage: {
type: String,
default: null,
required: false,
},
},
data() {
return {
lastFocus: null,
maxContentHeight: '1000',
contentHeight: 0,
containsKSelect: false,
scrollShadow: false,
delayedEnough: false,
};
},
computed: {
modalContentHeight() {
// if modal contains KSelect, the correct value of its content.scrollHeight is overwritten by the height of the
// KSelect options once KSelect is opened & the modal will elongate after KSelect is closed.
// in that case, getBoundingClientRect().height is a better reflection of content height but during the loading
// state it is temporarily 0 and fallback content.scrollHeight is accurate, as KSelect has not yet been opened
return this.$refs.content.getBoundingClientRect().height || this.$refs.content.scrollHeight;
},
modalSizeStyles() {
return {
'max-width': `${this.maxModalWidth - 32}px`,
'max-height': `${this.windowHeight - 32}px`,
width: this.modalWidth,
};
},
modalWidth() {
if (this.size === SIZE_SM) return '300px';
if (this.size === SIZE_MD) return '450px';
if (this.size === SIZE_LG) return '100%';
return `${this.size}px`;
},
maxModalWidth() {
if (this.windowWidth < 1000) {
return this.windowWidth;
}
return 1000;
},
contentSectionMaxHeight() {
return {
'max-height': `${this.maxContentHeight}px`,
height: `${this.contentHeight}px`,
};
},
},
created() {
if (this.$props.cancelText && !this.$listeners.cancel) {
console.error(
'A "cancelText" has been set, but there is no "cancel" listener. The "cancel" button may not work correctly.'
);
}
if (this.$props.submitText && !this.$listeners.submit) {
console.error(
'A "submitText" has been set, but there is no "submit" listener. The "submit" button may not work correctly.'
);
}
},
beforeMount() {
this.lastFocus = document.activeElement;
},
mounted() {
if (nuxtServerSideRendering) {
return;
}
// Remove scrollbars from the <html> tag, so user's can't scroll while modal is open
window.document.documentElement.style['overflow'] = 'hidden';
this.$nextTick(() => {
if (this.$refs.modal && !this.$refs.modal.contains(document.activeElement)) {
this.focusModal();
}
});
window.addEventListener('focus', this.focusElementTest, true);
window.setTimeout(() => (this.delayedEnough = true), 500);
// if modal contains KSelect, special classes & styles will be applied
const kSelectCheck = document.querySelector('div.modal div.ui-select');
this.containsKSelect = !!kSelectCheck;
},
updated() {
this.updateContentSectionStyle();
},
destroyed() {
if (nuxtServerSideRendering) {
return;
}
// Restore scrollbars to <html> tag
window.document.documentElement.style['overflow'] = '';
window.removeEventListener('focus', this.focusElementTest, true);
// Wait for events to finish propagating before changing the focus.
// Otherwise the `lastFocus` item receives events such as 'enter'.
window.setTimeout(() => this.lastFocus.focus());
},
methods: {
/**
* Calculate the max-height of the content section of the modal
* If there is not enough vertical space, create a vertically scrollable area and a
* scroll shadow
*/
updateContentSectionStyle: debounce(function() {
if (this.$refs.title && this.$refs.actions) {
if (Math.abs(this.$refs.content.scrollHeight - this.contentHeight) >= 8) {
// if there's dropdown & it is opened, the new scrollHeight detected shouldn't be applied,
// or else the modal will elongate after the dropdown content has been closed
this.contentHeight = this.containsKSelect
? this.modalContentHeight
: this.$refs.content.scrollHeight;
}
const maxContentHeightCheck =
this.windowHeight -
this.$refs.title.clientHeight -
this.$refs.actions.clientHeight -
32;
// to prevent max height from toggling between pixels
// we set a threshold of how many pixels the height should change before we update
if (Math.abs(maxContentHeightCheck - this.maxContentHeight) >= 8) {
this.maxContentHeight = maxContentHeightCheck;
this.scrollShadow = this.maxContentHeight < this.$refs.content.scrollHeight;
}
// make sure that overflow-y won't be updated to 'auto' if this function is running for the first time
// (otherwise Firefox would add a vertical scrollbar right away) + don't apply if modal contains KSelect
// (otherwise KSelect will be trapped inside modal if KSelect is opened a second time)
if (this.$refs.content.clientHeight !== 0 && !this.containsKSelect) {
// add a vertical scrollbar if content doesn't fit
if (this.$refs.content.scrollHeight > this.$refs.content.clientHeight) {
this.$refs.content.style.overflowY = 'auto';
}
}
}
}, 50),
emitCancelEvent() {
if (!this.cancelDisabled) {
/**
* Emitted when the cancel button is clicked or the esc key is pressed
*/
this.$emit('cancel');
}
},
emitSubmitEvent() {
if (!this.submitDisabled) {
/**
* Emitted when the submit button or the enter key is pressed
*/
this.$emit('submit');
}
},
handleEnter() {
if (this.delayedEnough) {
this.emitSubmitEvent();
}
},
focusModal() {
this.$refs.modal.focus();
},
focusElementTest(event) {
const { target } = event;
const noopOnFocus =
target === window || // switching apps
!this.$refs.modal || // if $refs.modal isn't available
target === this.$refs.modal || // addresses #3824
this.$refs.modal.contains(target.activeElement);
if (noopOnFocus) {
return;
}
// Fixes possible infinite recursion when disconnection snackbars appear
// along with KModal (#6301)
const $coreSnackbar = document.getElementById('coresnackbar');
if ($coreSnackbar && $coreSnackbar.contains(target)) {
return;
}
// focus has escaped the modal - put it back!
if (!this.$refs.modal.contains(target)) {
this.focusModal();
}
},
},
};
</script>
<style lang="scss" scoped>
@import './styles/definitions';
.modal-overlay {
position: fixed;
top: 0;
left: 0;
z-index: 24;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
background-attachment: fixed;
transition: opacity $core-time ease;
}
// TODO: margins for stacked buttons.
.modal {
@extend %dropshadow-16dp;
position: absolute;
top: 50%;
left: 50%;
margin: 0 auto;
border-radius: $radius;
transform: translate(-50%, -50%);
&:focus {
outline: none;
}
}
.form {
@extend %momentum-scroll;
}
.modal-fade-enter-active,
.modal-fade-leave-active {
transition: all $core-time ease;
}
.modal-fade-enter,
.modal-fade-leave-active {
opacity: 0;
}
.title {
padding: 24px;
margin: 0;
font-size: 24px;
}
.content {
padding: 0 24px;
overflow-x: hidden;
}
.scroll-shadow {
background: linear-gradient(white 30%, hsla(0, 0%, 100%, 0)),
linear-gradient(hsla(0, 0%, 100%, 0) 10px, white 70%) bottom,
radial-gradient(at top, rgba(0, 0, 0, 0.2), transparent 70%),
radial-gradient(at bottom, rgba(0, 0, 0, 0.2), transparent 70%) bottom;
background-repeat: no-repeat;
background-attachment: local, local, scroll, scroll;
background-size: 100% 20px, 100% 20px, 100% 10px, 100% 10px;
}
.contains-kselect {
overflow: unset;
}
.actions {
padding: 24px;
text-align: right;
button {
margin: 0;
}
}
.actions button:last-of-type {
margin-left: 16px;
}
</style>