-
Notifications
You must be signed in to change notification settings - Fork 5
/
Modal.svelte
87 lines (83 loc) · 2.2 KB
/
Modal.svelte
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
<script>
// from https://github.com/flekschas/svelte-simple-modal
import ModalBg from "./ModalBg.svelte";
import { setContext as baseSetContext } from "svelte";
export let key = "simple-modal";
export let closeOnEsc = true;
export let closeOnOuterClick = true;
export let styleBg = { top: 0, left: 0 };
export let styleWindow = {};
export let styleContent = {};
export let setContext = baseSetContext;
let Component = null;
let props = null;
let background;
let wrap;
let customStyleBg = {};
let customStyleWindow = {};
let customStyleContent = {};
const camelCaseToDash = str =>
str.replace(/([a-zA-Z])(?=[A-Z])/g, "$1-").toLowerCase();
const toCssString = props =>
Object.keys(props).reduce(
(str, key) => `${str}; ${camelCaseToDash(key)}: ${props[key]}`,
""
);
$: cssBg = toCssString(Object.assign({}, styleBg, customStyleBg));
$: cssWindow = toCssString(Object.assign({}, styleWindow, customStyleWindow));
$: cssContent = toCssString(
Object.assign({}, styleContent, customStyleContent)
);
const open = (
NewComponent,
newProps = {},
style = { bg: {}, window: {}, content: {} }
) => {
Component = NewComponent;
props = newProps;
customStyleBg = style.bg || {};
customStyleWindow = style.window || {};
customStyleContent = style.content || {};
};
const close = () => {
Component = null;
props = null;
customStyleBg = {};
customStyleWindow = {};
customStyleContent = {};
};
const handleKeyup = ({ key }) => {
if (closeOnEsc && Component && key === "Escape") {
event.preventDefault();
close();
}
};
const handleOuterClick = event => {
if (
closeOnOuterClick &&
(event.target === background || event.target === wrap)
) {
event.preventDefault();
close();
}
};
setContext(key, { open, close });
$: isOpen = !!Component;
</script>
<style>
* {
box-sizing: border-box;
}
</style>
<svelte:window on:keyup={handleKeyup} />
<div>
<svelte:component
this={isOpen ? ModalBg : null}
{handleOuterClick}
{background}
{wrap}
{Component}>
<svelte:component this={Component} {...props} />
</svelte:component>
<slot />
</div>