-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathcreateOverlayComponent.ts
100 lines (91 loc) · 2.53 KB
/
createOverlayComponent.ts
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
import Vue, { CreateElement, VueConstructor } from 'vue';
export interface OverlayElement extends HTMLElement {
present: () => Promise<void>;
dismiss: (data?: any, role?: string | undefined) => Promise<boolean>;
}
export interface Data<T> {
overlay: T | null;
}
export interface Methods {
present: () => Promise<void>;
}
export interface Props {
isOpen: boolean;
}
export function createOverlayComponent<T extends OverlayElement>(
name: string,
controller: { create: (opts: any) => Promise<T> }
): VueConstructor<Data<T> & Methods & Props & Vue> {
const coreTag = name.charAt(0).toLowerCase() + name.slice(1);
const eventHandlers = Object.entries({
[`${coreTag}WillPresent`]: 'onWillPresent',
[`${coreTag}DidPresent`]: 'onDidPresent',
[`${coreTag}WillDismiss`]: 'onWillDismiss',
[`${coreTag}DidDismiss`]: 'onDidDismiss',
});
return Vue.extend<Data<T>, Methods, {}, Props>({
name: `${name}Vue`,
data() {
return {
overlay: null,
};
},
props: {
isOpen: {
type: Boolean,
required: true,
},
},
watch: {
async isOpen(newVal: boolean) {
console.log(newVal);
if (newVal) {
if (this.overlay) {
await this.overlay.present();
} else {
await this.present();
}
} else {
await this.overlay?.dismiss();
this.overlay = null;
}
}
},
async mounted() {
console.log(this.isOpen);
this.isOpen && await this.present();
},
async beforeDestroy() {
console.log('bye');
await this.overlay?.dismiss();
},
render(h: CreateElement) {
for (const [eventName, handler] of eventHandlers) {
console.log(eventName, handler);
if (this.$listeners[handler]) {
this.overlay?.addEventListener(eventName, (e: Event) => {
const handlers = this.$listeners[handler];
if (Array.isArray(handlers)) {
handlers.map(f => f(e));
return;
}
handlers(e);
});
}
}
return h('div', [h('div', { ref: 'overlay' }, this.overlay ? this.$slots.default : null)]);
},
methods: {
async present() {
// const children = this.$slots.default;
this.overlay = await controller.create({
...this.$attrs,
component: this.$refs.overlay,
componentProps: { parent: this },
});
console.log(this.overlay);
await this.overlay.present();
}
}
});
}