-
Notifications
You must be signed in to change notification settings - Fork 4
/
controls.js
89 lines (80 loc) · 1.97 KB
/
controls.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
/**
* Provide common functions to controls to use.
* Controls file can only provide UI function to render control
*/
class Controls {
el = wp.element.createElement;
components = wp.components;
data = wp.data;
i18n = wp.i18n;
timeout = null;
/**
* Build control UI. Control function provide UI options
* and optionally a state object to stop UI flickering with
* every API update
*
* @param {function} buildUI
* @param {object} state
*/
constructor(buildUI, state = {}) {
let compose = wp.compose;
const { withState } = compose;
const { withSelect, withDispatch } = wp.data;
return compose.compose(
withDispatch(this.dispatchMeta.bind(this)),
withSelect(this.updateSelect.bind(this)),
withState(state)
)(buildUI.bind(this));
}
/**
* Update user meta data on selection
*/
dispatchMeta(dispatch, props) {
return {
setMetaValue: (metaValue) => {
const userData = this.data.select('core').getCurrentUser();
const user = this.data.select('core').getEntityRecord('root', 'user', userData.id);
let meta = {
[props.metaKey]: metaValue,
};
dispatch('core').saveUser({
id: user.id,
meta: { ...user.meta, ...meta },
});
},
};
}
/**
* Debounce function
*
* @param {function} func Callback function
* @param {int} wait Timeout time. Default to 1 second
*/
debounce(func, wait = 1000) {
return (...args) => {
const later = () => {
clearTimeout(this.timeout);
func(...args);
};
clearTimeout(this.timeout);
this.timeout = setTimeout(later, wait);
};
}
/**
* Update user selection
*
* @param {object} select WP object
* @param {object} props WP object
*/
updateSelect(select, props) {
const userData = this.data.select('core').getCurrentUser();
if (Object.keys(userData).length == 0) return {};
const user = select('core').getEntityRecord('root', 'user', userData.id);
if (user === undefined) {
return {};
}
return {
metaValue: user.meta[props.metaKey],
};
}
}