summaryrefslogtreecommitdiff
path: root/src/client/app/common/define-widget.ts
blob: 1efdbb1880b45f9fa5d50ba42b7313774de578a5 (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
72
73
74
75
76
77
78
79
80
81
82
83
import Vue from 'vue';

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

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

			props(): T {
				return this.widget.data;
			}
		},

		data() {
			return {
				bakedOldProps: null
			};
		},

		created() {
			this.mergeProps();

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

			this.bakeProps();
		},

		methods: {
			bakeProps() {
				this.bakedOldProps = JSON.stringify(this.props);
			},

			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]);
					}
				}
			},

			save() {
				if (this.bakedOldProps == JSON.stringify(this.props)) return;

				this.bakeProps();

				if (this.platform == 'deck') {
					this.$store.commit('device/updateDeckColumn', this.column);
				} else {
					this.$root.api('i/update_widget', {
						id: this.id,
						data: this.props
					});
				}
			}
		}
	});
}