summaryrefslogtreecommitdiff
path: root/src/client/widgets/define.ts
blob: 50c9b10e8120762e548b0412743e13ce007c6562 (plain)
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
import Vue from 'vue';
import { Form } from '../scripts/form';

export default function <T extends Form>(data: {
	name: string;
	props?: () => T;
}) {
	return Vue.extend({
		props: {
			widget: {
				type: Object,
				required: false
			},
			isCustomizeMode: {
				type: Boolean,
				default: false
			}
		},

		computed: {
			id(): string {
				return this.widget ? this.widget.id : null;
			},

			props(): Record<string, any> {
				return this.widget ? this.widget.data : {};
			}
		},

		created() {
			this.mergeProps();

			this.$watch('props', () => {
				this.mergeProps();
			});
		},

		methods: {
			mergeProps() {
				if (data.props) {
					const defaultProps = data.props();
					for (const prop of Object.keys(defaultProps)) {
						if (this.props.hasOwnProperty(prop)) continue;
						Vue.set(this.props, prop, defaultProps[prop].default);
					}
				}
			},

			async setting() {
				const form = data.props();
				for (const item of Object.keys(form)) {
					form[item].default = this.props[item];
				}
				const { canceled, result } = await this.$root.form(data.name, form);
				if (canceled) return;

				for (const key of Object.keys(result)) {
					Vue.set(this.props, key, result[key]);
				}

				this.save();
			},

			save() {
				if (this.widget) {
					this.$store.commit('deviceUser/updateWidget', this.widget);
				}
			}
		}
	});
}