-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset-data.js
136 lines (113 loc) · 2.47 KB
/
set-data.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import Backend from "https://madata.dev/src/index.js";
const SetData = {
props: {
value: {
required: true,
},
on: Object,
name: {
required: true,
type: String
},
once: Boolean,
// While normal Vue attribute inheritance should take care of this for most cases,
// it tends to produce warnings when the element's content is not a single element
hidden: Boolean,
},
emits: ["update"],
data() {
return {}
},
methods: {
isPrimitive,
watchValue () {
this.unwatchValue = this.$watch("value", (value, oldValue) => {
if (oldValue !== undefined) {
if (this.once) {
// You'd expect we'd never get here, since we call `unwatchValue()`
// but somehow this gets called once more after the unwatch.
this.unwatchValue?.();
return;
}
if (isPrimitive(value)) {
if (value === oldValue) {
return;
}
}
else {
console.log("slow code path")
if (JSON.stringify(value) === JSON.stringify(oldValue)) {
return;
}
}
}
if (this.once) {
this.unwatchValue?.();
}
this.setValue(value);
this.$emit("update", value);
}, {
immediate: true,
deep: true,
});
},
setValue (value) {
this.root[this.name] = undefined;
Object.defineProperty(this.root, this.name, {
value: value,
writable: true,
enumerable: false
});
}
},
computed: {
// Root object our property is on
root () {
return this.on ?? this.$parent;
},
storedValue () {
return this.root[this.name];
}
},
created () {
this.watchValue();
},
mounted () {
if (!this.once) {
this.watchValue();
}
},
unmounted () {
if (!this.once) {
this.unwatchValue?.();
this.setValue(undefined);
}
},
template: `<slot><span :hidden="hidden">{{ isPrimitive(storedValue)? storedValue : "" }}</span></slot>`,
fixupRoot,
}
// Make sure root properties in <set-data> become reactive
// by registering them on intiial data
export function fixupRoot (root, data) {
if (!root?.querySelectorAll) {
return;
}
for (let setData of [...root.querySelectorAll("set-data:not([\\:on], [v-bind\\:on])")]) {
let key = setData.getAttribute("name");
if (!(key in data)) {
data[key] = undefined;
}
}
}
function isPrimitive (value) {
return ["number", "string", "boolean"].includes(typeof value);
}
export default SetData;
export const meta = {
type: "component",
name: "set-data",
default: SetData,
}
if (globalThis.VApp) {
VApp.registerHelper(meta);
}