forked from polylib/polylib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
property-mixin.js
138 lines (125 loc) · 5.45 KB
/
property-mixin.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
137
138
import {getProp, normalizePath, setAttrValue} from "./common.js";
let wmh = 0;
const toKebab = string => string.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
const PlPropertiesMixin = s => class plPropMixin extends s {
_props = {};
wmh = {};
constructor() {
super();
let inst = this.constructor;
let pi = [];
while ( inst ) {
if (inst.hasOwnProperty('properties')) pi.unshift(inst.properties);
inst = inst.__proto__ ;
}
this._dp = Object.assign({}, ...pi);
Object.keys(this._dp).forEach( p => {
// возможно значение уже назначено снаружи или задано в атрибуте, запоминаем и используем его вместо дефолтного
let attrVal = this.getAttribute(toKebab(p));
// убираем атрибуты для свойств, если они не отображаются в атрибуты
if (attrVal !== null && !this._dp[p].reflectToAttribute) this.removeAttribute(toKebab(p));
let val = (this.hasOwnProperty(p) ? this[p] : undefined) ?? (this._dp[p].type === Boolean ? (attrVal !== null ? attrVal !== 'false' : undefined) : attrVal);
Object.defineProperty(this, p, {
get: () => this._props[p],
set: (value) => {
let oldValue = this._props[p];
this._props[p] = value;
if (oldValue !== value) this.notifyChange({ action: 'upd', path: p, value, oldValue });
},
});
let value = this._dp[p].value;
if (typeof value === 'function') value = value();
this._props[p] = val ?? value;
if (this._dp[p].reflectToAttribute) {
this.addEventListener(p+'-changed', () => this.reflectToAttribute(p, this._props[p]) );
}
if (val) setTimeout( () => this.notifyChange({ action: 'upd', path: p, value: val, init: true }), 0);
});
this.addEventListener('property-change', event => {
// запускаем эффекты для всех кого может затронуть изменение
this._ti?.applyEffects(event.detail)
});
}
connectedCallback() {
super.connectedCallback?.();
Object.keys(this._dp).forEach( p => {
if (this._dp[p].reflectToAttribute) {
//TODO: думается надо делать property effect
this.reflectToAttribute(p,this._props[p]);
}
});
}
reflectToAttribute(name, val) {
if (this.constructor.properties[name].type === Boolean)
val = !!val;
setAttrValue(/** @type HTMLElement */this,toKebab(name),val);
}
set(path, value, wmh) {
let xpath = normalizePath(path);
let xl = xpath.length;
let x = xpath.pop();
let obj = getProp(this, xpath);
let oldValue = obj[x];
(obj._props || obj)[x] = value;
if (value === oldValue && xl === 1) return;
this.notifyChange({ action: 'upd', path, value, oldValue, wmh});
}
get(path) {
path = normalizePath(path);
return getProp(this, path);
}
push(path,value) {
let target = this.get(path);
if (Array.isArray(target)) {
if (!Array.isArray(value)) value = [value]
target.push(...value);
this.notifyChange({ action: 'splice', path, target, index: target.length - 1, addedCount: value.length, added: value });
}
}
splice(path, index, deletedCount, ...added) {
let target = this.get(path);
let deleted = target.splice(index, deletedCount, ...added);
this.notifyChange({ action: 'splice', path, target, index: index, deletedCount, addedCount: added?.length, added, deleted });
}
/** @typedef {Object} DataMutation
* @property {String} action
* @property {String} path - path to change relative to data host
* @property {any} value - new value
* @property {any} oldValue - value before mutation
* @property {Number} [wmh] - watermark for change loop detection
* @property {Number} [index] - start for splice mutation
* @property {Number} [addedCount]
* @property {Number} [deletedCount]
* @property {Object[]} [added]
* @property {Object[]} [deleted]
*/
/**
*
* @param {DataMutation} m
*/
notifyChange(m) {
let path = normalizePath(m.path);
m.wmh = m.wmh || wmh++;
if ( this.wmh[path[0]] >= m.wmh ) return;
this.wmh[path[0]] = m.wmh;
if (m.value === m.oldValue && m.action === 'upd' && path.length === 1) return;
let [name] = m.path.split('.');
let inst = this.constructor;
if (inst.properties[name]?.observer) {
this[inst.properties[name].observer](this._props[name], undefined, m);
}
this.dispatchEvent(new CustomEvent('property-change', { detail: m }));
// Polymer notify
this.dispatchEvent(new CustomEvent(name + '-changed', { detail: m }));
}
forwardNotify(mutation, from, to) {
let r = new RegExp(`^(${from})(\..)?`)
let translatedPath = mutation.path.replace(r, to+'$2');
mutation = {...mutation, path: translatedPath};
this.notifyChange(mutation);
}
hasProp(name) {
return name in this;
}
}
export {PlPropertiesMixin};