mirror of https://github.com/sveltejs/svelte
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
1.6 KiB
82 lines
1.6 KiB
6 years ago
|
<script>
|
||
5 years ago
|
import { createEventDispatcher, onDestroy } from 'svelte';
|
||
6 years ago
|
|
||
|
const dispatch = createEventDispatcher();
|
||
5 years ago
|
const close = () => dispatch('close');
|
||
|
|
||
|
let modal;
|
||
|
|
||
|
const handle_keydown = e => {
|
||
|
if (e.key === 'Escape') {
|
||
|
close();
|
||
|
return;
|
||
5 years ago
|
}
|
||
|
|
||
5 years ago
|
if (e.key === 'Tab') {
|
||
|
// trap focus
|
||
|
const nodes = modal.querySelectorAll('*');
|
||
|
const tabbable = Array.from(nodes).filter(n => n.tabIndex >= 0);
|
||
5 years ago
|
|
||
5 years ago
|
let index = tabbable.indexOf(document.activeElement);
|
||
|
if (index === -1 && e.shiftKey) index = 0;
|
||
|
|
||
|
index += tabbable.length + (e.shiftKey ? -1 : 1);
|
||
|
index %= tabbable.length;
|
||
|
|
||
|
tabbable[index].focus();
|
||
|
e.preventDefault();
|
||
|
}
|
||
|
};
|
||
|
|
||
|
const previously_focused = typeof document !== 'undefined' && document.activeElement;
|
||
|
|
||
|
if (previously_focused) {
|
||
|
onDestroy(() => {
|
||
|
previously_focused.focus();
|
||
|
});
|
||
|
}
|
||
5 years ago
|
</script>
|
||
6 years ago
|
|
||
5 years ago
|
<svelte:window on:keydown={handle_keydown}/>
|
||
|
|
||
|
<div class="modal-background" on:click={close}></div>
|
||
|
|
||
|
<div class="modal" role="dialog" aria-modal="true" bind:this={modal}>
|
||
|
<slot name="header"></slot>
|
||
|
<hr>
|
||
|
<slot></slot>
|
||
|
<hr>
|
||
|
|
||
|
<!-- svelte-ignore a11y-autofocus -->
|
||
|
<button autofocus on:click={close}>close modal</button>
|
||
|
</div>
|
||
|
|
||
6 years ago
|
<style>
|
||
|
.modal-background {
|
||
|
position: fixed;
|
||
|
top: 0;
|
||
|
left: 0;
|
||
|
width: 100%;
|
||
|
height: 100%;
|
||
|
background: rgba(0,0,0,0.3);
|
||
|
}
|
||
|
|
||
|
.modal {
|
||
|
position: absolute;
|
||
5 years ago
|
left: 50%;
|
||
|
top: 50%;
|
||
6 years ago
|
width: calc(100vw - 4em);
|
||
|
max-width: 32em;
|
||
|
max-height: calc(100vh - 4em);
|
||
|
overflow: auto;
|
||
|
transform: translate(-50%,-50%);
|
||
|
padding: 1em;
|
||
|
border-radius: 0.2em;
|
||
|
background: white;
|
||
|
}
|
||
|
|
||
|
button {
|
||
|
display: block;
|
||
|
}
|
||
5 years ago
|
</style>
|