hippofish/src/client/app/common/define-widget.ts

84 lines
1.3 KiB
TypeScript
Raw Normal View History

2018-02-14 17:07:09 +01:00
import Vue from 'vue';
2018-02-14 17:41:31 +01:00
export default function<T extends object>(data: {
2018-02-14 17:07:09 +01:00
name: string;
2018-02-21 07:30:03 +01:00
props?: () => T;
2018-02-14 17:07:09 +01:00
}) {
return Vue.extend({
props: {
2018-02-18 15:51:41 +01:00
widget: {
type: Object
2018-02-23 18:46:09 +01:00
},
isMobile: {
type: Boolean,
default: false
2018-02-25 14:50:26 +01:00
},
isCustomizeMode: {
type: Boolean,
default: false
2018-02-14 17:07:09 +01:00
}
},
2018-04-29 10:17:15 +02:00
2018-02-14 17:07:09 +01:00
computed: {
id(): string {
2018-02-18 15:51:41 +01:00
return this.widget.id;
2018-04-29 10:17:15 +02:00
},
props(): T {
return this.widget.data;
2018-02-14 17:07:09 +01:00
}
},
2018-04-29 10:17:15 +02:00
2018-02-14 17:07:09 +01:00
data() {
return {
2018-04-29 10:17:15 +02:00
bakedOldProps: null
2018-02-14 17:07:09 +01:00
};
},
2018-04-29 10:17:15 +02:00
2018-02-14 17:07:09 +01:00
created() {
2018-04-29 10:17:15 +02:00
this.mergeProps();
this.$watch('props', () => {
this.mergeProps();
});
2018-02-21 07:30:03 +01:00
2018-02-23 23:49:03 +01:00
this.bakeProps();
2018-04-29 10:17:15 +02:00
},
methods: {
bakeProps() {
this.bakedOldProps = JSON.stringify(this.props);
},
2018-02-23 23:49:03 +01:00
2018-04-29 10:17:15 +02:00
mergeProps() {
if (data.props) {
const defaultProps = data.props();
Object.keys(defaultProps).forEach(prop => {
if (!this.props.hasOwnProperty(prop)) {
Vue.set(this.props, prop, defaultProps[prop]);
}
});
2018-02-23 23:49:03 +01:00
}
2018-04-29 10:17:15 +02:00
},
save() {
if (this.bakedOldProps == JSON.stringify(this.props)) return;
2018-02-23 23:49:03 +01:00
this.bakeProps();
2018-02-23 18:46:09 +01:00
if (this.isMobile) {
(this as any).api('i/update_mobile_home', {
id: this.id,
2018-04-29 10:17:15 +02:00
data: this.props
2018-02-23 18:46:09 +01:00
});
} else {
(this as any).api('i/update_home', {
id: this.id,
2018-04-29 10:17:15 +02:00
data: this.props
2018-02-23 18:46:09 +01:00
});
}
2018-02-23 23:49:03 +01:00
}
2018-02-14 17:07:09 +01:00
}
});
}