-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp.ts
351 lines (306 loc) · 10.4 KB
/
p.ts
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import {XtallatX, lispToCamel} from 'xtal-element/xtal-latx.js';
import {PropAction} from 'xtal-element/types.d.js';
import {hydrate} from 'trans-render/hydrate.js';
import {createNestedProp} from 'xtal-element/createNestedProp.js';
import {WithPath, with_path} from 'xtal-element/with-path.js';
import {PProps} from './types.d.js';
function getProp(val: any, pathTokens: (string | [string, string[]])[], src: HTMLElement){
let context = val;
let first = true;
pathTokens.forEach(token => {
if(context && token!=='') {
if(first && token==='target' && context['target'] === null){
context = (<any>src)._trigger;
}else{
switch(typeof token){
case 'string':
context = context[token];
break;
default:
context = context[token[0]].apply(context, token[1]);
}
}
first = false;
}
});
return context;
}
export abstract class P extends WithPath(XtallatX(hydrate(HTMLElement))) implements PProps{
//* region props
/**
* The event name to monitor for, from previous non-petalian element.
* @attr
*/
on!: string;
/**
* css pattern to match for from downstream siblings.
* @attr
*/
to!: string;
/**
* CSS Selector to use to select single child within the destination element.
* @attr care-of
*
*/
careOf!: string;
/**
* Don't block event propagation.
* @attr
*/
noblock!: boolean;
/**
* Only act on event if target element css-matches the expression specified by this attribute.
* @attr
*/
ifTargetMatches!: string;
/**
* Name of property to set on matching (downstream) siblings.
* @attr
*/
prop!: string;
/**
* Dynamically determined name of property to set on matching (downstream) siblings from event object.
* @attr prop-from-event
*/
propFromEvent: string | undefined;
proxyId: string | undefined;
/**
* Specifies path to JS object from event, that should be passed to downstream siblings. Value of '.' passes entire entire object.
* @attr
*/
val!: string;
/**
* Specifies element to latch on to, and listen for events.
* Searches previous siblings, parent, previous siblings of parent, etc.
* Stops at Shadow DOM boundary.
* @attr
*/
observe!: string;
/**
* Artificially fire event on target element whose name is specified by this attribute.
* @attr fire-event
*/
fireEvent!: string;
/**
* Don't raise a "fake" event when attaching to element.
* @attr skip-init
*/
skipInit!: boolean;
debug!: boolean;
log!: boolean;
async!: boolean;
parseValAs: 'int' | 'float' | 'bool' | 'date' | 'truthy' | 'falsy' | undefined;
/**
* A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
*/
capture!: boolean;
_s: (string | [string, string[]])[] | null = null; // split prop using '.' as delimiter
getSplit(newVal: string){
if(newVal === '.'){
return [];
}else{
return newVal.split('.') as any;
}
}
propActions = [
({val, self} : P) =>{
if(val !== null){
self._s = self.getSplit(val);
}
}
] as PropAction[];
/**
* get previous sibling
*/
getPreviousSib() : Element | null{
const obs = this.observe;
let prevSib = this as Element | null;
while(prevSib && ( (obs!=undefined && !prevSib.matches(obs)) || prevSib.hasAttribute('on'))){
prevSib = prevSib.previousElementSibling!;
if(prevSib === null) {
prevSib = this.parentElement;
}
}
return prevSib;
}
connectedCallback(){
this.style.display = 'none';
super.connectedCallback();
}
_trigger: HTMLElement | undefined;
init(){
this.attchEvListnrs();
this.doFake();
};
nudge(prevSib: Element){
const da = prevSib.getAttribute('disabled');
if(da !== null){
if(da.length === 0 ||da==="1"){
prevSib.removeAttribute('disabled');
}else{
prevSib.setAttribute('disabled', (parseInt(da) - 1).toString());
}
}
}
attchEvListnrs(){
if(this._bndHndlEv){
return;
}else{
this._bndHndlEv = this._hndEv.bind(this);
}
const prevSib = this._trigger === undefined ? this.getPreviousSib() : this._trigger;
if(!prevSib) return;
this._trigger = prevSib as HTMLElement;
prevSib.addEventListener(this.on, this._bndHndlEv, {capture: this.capture});
if(prevSib === this.parentElement && this.ifTargetMatches){
prevSib.querySelectorAll(this.ifTargetMatches).forEach(publisher =>{
this.nudge(publisher);
})
}else{
this.nudge(prevSib);
}
}
doFake(){
if(!this.ifTargetMatches && !this.skipInit){
let lastEvent = this._lastEvent;
if(!lastEvent){
lastEvent = <any>{
target: this.getPreviousSib(),
isFake: true
} as Event;
}
if(this._hndEv) this._hndEv(lastEvent);
}
}
_bndHndlEv!: any;
abstract pass(e: Event) : void;
_lastEvent: Event | null = null;
filterEvent(e: Event) : boolean{
if(this.ifTargetMatches === undefined) return true;
return (e.target as HTMLElement).matches(this.ifTargetMatches);
}
_hndEv(e: Event){
if(this.log){
console.log('handlingEvent', this, e);
}
if(this.debug) debugger;
if(!e) return;
if(!this.filterEvent(e)) return;
if(e.stopPropagation && !this.noblock) e.stopPropagation();
this._lastEvent = e;
if(this.async){
setTimeout(() => {
Object.assign(e, {isFake: true, target: this.getPreviousSib()});
this.pass(e);
});
}else{
this.pass(e);
}
}
_destIsNA!: boolean;
valFromEvent(e: Event){
let val = this._s !== null ? getProp(e, this._s, this) : getProp(e, ['target', 'value'], this);
if(val === undefined && (typeof(this.val) ==='string') && (e.target as HTMLElement).hasAttribute(this.val)) {
val = (e.target as HTMLElement).getAttribute(this.val);
}
switch(this.parseValAs){
case 'bool':
val = val === 'true';
break;
case 'int':
val = parseInt(val);
break;
case 'float':
val = parseFloat(val);
break;
case 'date':
val = new Date(val);
break;
case 'truthy':
val = !!val;
break;
case 'falsy':
val = !val;
break;
}
return val;
}
injectVal(e: Event, target: any){
this.commit(target, this.valFromEvent(e), e);
}
setVal(target: HTMLElement, valx: any, attr: string | undefined, prop: string | symbol){
switch(typeof prop){
case 'symbol':
this.setProp(target, prop, valx);
break;
default:
if (prop.startsWith('.')) {
const cssClass = prop.substr(1);
const method = (valx === undefined && valx === null) ? 'remove' : 'add';
target.classList[method](cssClass);
} else if (this.withPath !== undefined){
const currentVal = (<any>target)[prop];
const wrappedVal = this.wrap(valx, {});
(<any>target)[prop] = (typeof(currentVal) === 'object' && currentVal !== null) ? {...currentVal, ...wrappedVal} : wrappedVal;
} else if(attr !== undefined && this.hasAttribute('as-attr')){
this.setAttr(target, attr, valx);
}else {
this.setProp(target, prop, valx);
}
}
}
setAttr(target: HTMLElement, attr: string, valx: any){
target.setAttribute(attr, valx.toString());
}
setProp(target: HTMLElement, prop: string | symbol, valx: any){
(<any>target)[prop] = valx;
}
commit(target: HTMLElement, valx: any, e: Event){
if(valx===undefined) return;
let prop = this.prop;
let attr: string | undefined;
if(prop === undefined){
//TODO: optimize (cache, etc)
if(this.propFromEvent !== undefined){
prop = getProp(e, this.propFromEvent.split('.'), target);
}else{
const thingToSplit = this.careOf || this.to;
const toSplit = thingToSplit.split('[');
const len = toSplit.length;
if(len > 1){
const last = toSplit[len - 1].replace(']', '');
if(last.startsWith('-') || last.startsWith('data-')){
attr = last.split('-').slice(1).join('-');
prop = lispToCamel(attr);
}
}
}
}
if(target.hasAttribute !== undefined && target.hasAttribute('debug')) debugger;
let realTarget = target as any;
if(this.proxyId){
const sym = Symbol.for(this.proxyId);
if(realTarget[sym] === undefined){
realTarget[sym] = {};
}
realTarget = realTarget[sym];
}
this.setVal(realTarget, valx, attr, prop);
if(this.fireEvent){
target.dispatchEvent(new CustomEvent(this.fireEvent, {
detail: this.getDetail(valx),
bubbles: true
}));
}
}
getDetail(val: any){
return {value: val};
}
detach(pS: Element){
pS.removeEventListener(this.on, this._bndHndlEv);
}
disconnectedCallback(){
const pS = this.getPreviousSib();
if(pS && this._bndHndlEv) this.detach(pS);
}
}