-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathelement.ts
More file actions
688 lines (644 loc) · 22 KB
/
element.ts
File metadata and controls
688 lines (644 loc) · 22 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
import './global.js';
import {
Mutation,
createProxy,
addObserver,
removeObserver,
swapObserver,
hasObserver,
isProxy,
getTarget
} from './proxy.js';
interface CustomElementConfig {
selector?: string;
template?: string;
style?: CSSStyleSheet;
useShadow?: boolean;
}
interface Constructor {
symbols: object,
observedAttributes: string[]
}
class PropError extends Error {
constructor(message: string, ignore: any) {
super(message);
this.name = 'PropError';
// @ts-ignore
if (Error.captureStackTrace) {
// @ts-ignore
Error.captureStackTrace(this, ignore);
}
}
}
export const index = Symbol('index');
const init = Symbol('init');
const template = Symbol('template');
const style = Symbol('style');
const parent = Symbol('parent');
const renderList = Symbol('renderList');
export function getProxyValue(obj: any) {
return obj[isProxy] && obj[getTarget];
}
function extendTemplate(base: string, append: string | null) {
if (append && append.match(/<parent\/>/)) {
return append.replace(/<parent\/>/, base);
} else if (base.match(/<child\/>/)) {
return base.replace(/<child\/>/, append || '');
} else {
return `${base}${append || ''}`;
}
}
function camelToDash(str: string): string {
return str.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase()
}
function dashToCamel(str: string): string {
return str.replace(/-([a-z])/g, m => m[1].toUpperCase());
}
export function Component(config: CustomElementConfig = {}) {
return function (cls: any, context?: any) {
if (context.kind !== 'class') {
throw new Error('@Component() can only decorate a class');
}
// webpack removes class names, override name
Reflect.defineProperty(cls, 'name', {
value: config.selector,
writable: false,
configurable: false,
});
// ToDo: Clean up naming. cls is not used only render
if (cls[parent]) {
cls[parent] = [...cls[parent], cls];
if (cls.prototype.render) {
cls[renderList] = [...cls[renderList], cls.prototype.render];
}
if (config.style) {
cls[style] = [...cls[style], config.style];
}
cls[template] = extendTemplate(
cls[parent][cls[parent].length - 1][template],
config.template || null
);
} else if (cls.prototype instanceof HTMLElement) {
cls[parent] = [cls];
cls[renderList] = cls.prototype.render ? [cls.prototype.render] : [];
cls[style] = config.style ? [config.style] : [];
cls[template] = config.template || '';
} else {
throw new Error(`Must extend from HTMLElement`);
}
const connectedCallback = cls.prototype.connectedCallback || (() => { });
const disconnectedCallback = cls.prototype.disconnectedCallback || (() => { });
cls.prototype.connectedCallback = function () {
if (!this[init] && config.template === undefined && config.style === undefined) {
if (config.useShadow === false) {
// Base class with no template
} else {
this.attachShadow({ mode: 'open' });
}
} else if (!this[init]) {
if (config.useShadow === false) {
throw new Error('unsupported');
} else {
const $template = document.createElement('template');
$template.innerHTML = cls[template] || '';
const $node = document.importNode($template.content, true);
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.adoptedStyleSheets = cls[style].reduce((acc: any[], value: any) => {
if (!value) {
return acc;
}
if (value instanceof CSSStyleSheet) {
acc.push(value);
return acc;
}
var s = new CSSStyleSheet();
s.replaceSync(value.toString());
acc.push(s);
return acc;
}, []);
shadowRoot.appendChild($node);
}
} else if (this[init] && config.style) {
/*if (this.shadowRoot) {
const style = document.createElement('style');
style.appendChild(document.createTextNode(config.style));
this.appendChild(style);
}*/
// } else if (this[init] && config.template) {
// This is allowed now via <parent/>
// throw new Error('template from base class cannot be overriden. Fix: remove template from @Component');
} else if (this[init] && config.selector && !config.template) {
throw new Error('You need to pass a template for an extended element.');
}
const tags = new Set<string>();
for (const ele of this.shadowRoot.querySelectorAll('*')) {
if (ele.localName.indexOf('-') !== -1) {
tags.add(ele.localName);
}
}
const promises = Array.from(tags.values()).map(tag => {
return customElements.get(tag)
? Promise.resolve()
: customElements.whenDefined(tag);
});
const render = () => {
this.constructor[renderList].map((renderFn: any) => {
renderFn.call(
this,
cls.observedAttributes
? cls.observedAttributes.reduce((a: any, c: string) => {
const n = dashToCamel(c);
a[n] = true;
return a;
}, {})
: {}
);
});
}
if (promises.length === 0) {
this[init] = true;
connectedCallback.call(this);
render();
} else {
Promise.all(promises).then(() => {
this[init] = true;
connectedCallback.call(this);
// dispatch slotchange
for (const slot of this.shadowRoot.querySelectorAll('slot')) {
slot.dispatchEvent(new CustomEvent('slotchange'));
}
render();
});
}
};
cls.prototype.disconnectedCallback = function () {
disconnectedCallback.call(this);
};
cls.prototype.attributeChangedCallback = function (name: string, oldValue: string | null, newValue: string | null) {
const normalizedName = dashToCamel(name);
this[normalizedName] = newValue;
};
// Base components may not define a selector
context.addInitializer(function (this: any) {
if (config.selector) {
if (window.customElements.get(config.selector)) {
throw new Error(`@Component() ${context.name} duplicate selector '${config.selector}'`);
}
window.customElements.define(config.selector, cls);
}
});
};
}
const transmute = Symbol('transmute');
export function TransmutePart(part: string, selector: string) {
return function (cls: any) {
if (cls.prototype[transmute]) {
cls.prototype[transmute][part] = selector;
} else {
cls.prototype[transmute] = { [part]: selector };
}
};
}
function isArray(a: any) {
return (!!a) && (a.constructor === Array);
}
function isObject(a: any) {
return (!!a) && (a.constructor === Object);
}
function render(self: any, propertyKey: string) {
if (self[init]) {
self.constructor[renderList].map((renderFn: any) => {
renderFn.call(self, { [propertyKey]: true });
});
}
}
function getSymbolType(value: any) {
if (value === null) { return 'null' }
return isArray(value) ? 'array' : typeof value;
}
export function Prop(normalize?: (value: any) => any): any {
return function <C, V>(_: Object, context: ClassFieldDecoratorContext<C, V>) {
const propertyKey = context.name as string;
const symbol = Symbol(propertyKey);
const symbolType = Symbol(`${propertyKey}:type`);
const symbolMeta = Symbol(`${propertyKey}:meta`);
context.addInitializer(function (this: any) {
Reflect.defineProperty(this, propertyKey, {
get: () => {
if (this[symbolType] === 'object') {
if (this[symbol][isProxy]) {
return this[symbol];
} else {
return createProxy(this[symbol]);
}
}
if (this[symbolType] === 'array') {
if (this[symbol][isProxy]) {
return this[symbol];
} else {
return createProxy(this[symbol]);
}
}
return this[symbol];
},
set: (value) => {
// ToDo: cleanup
const newSymbolType = getSymbolType(normalize ? normalize(value) : value);
if (
propertyKey !== 'index' && this[symbolType] !== newSymbolType
&& this[symbolType] !== 'null' && newSymbolType !== 'null'
) {
throw new Error(`@Prop() ${propertyKey} with type '${this[symbolType]}' cannot be set to ${newSymbolType}.`);
}
if (this[symbolType] === 'array') {
if (!isArray(value)) {
throw new PropError(`Array "${propertyKey}" (Prop) initialized already. Reassignments must be array type.`, Object.getOwnPropertyDescriptor(this, propertyKey)?.set);
}
if (this[symbol] === value) {
throw new Error('Setting an array to itself is not allowed.');
}
const proxified = createProxy(this[symbol]);
if (proxified[hasObserver](this)) {
const unproxyValue = value[isProxy] ? value[getTarget] : value;
proxified[swapObserver](this, unproxyValue);
this[symbol] = value;
// render(this, propertyKey); // do we need to trigger this for arrays being remapped?
} else {
this[symbol] = value;
}
}
else {
this[symbol] = normalize ? normalize(value) : value;
render(this, propertyKey);
}
}
});
});
return function (this: any, initialValue: any) {
if (initialValue === undefined && propertyKey !== 'index') {
throw new Error(`@Prop() ${propertyKey} must have an initial value defined.`);
} else if (initialValue !== undefined && propertyKey === 'index') {
throw new Error(`@Prop() index must not have an initial value defined.`);
}
if (initialValue === true) {
throw new Error(`@Prop() ${propertyKey} boolean must initialize to false.`);
}
// Web Component, todo: refactor to only be called once
if (!context.private) {
const { constructor } = this as any;
constructor.observedAttributes ??= [];
if (!constructor.symbols) {
constructor.symbols = {};
}
const { symbols } = constructor;
const normalizedPropertyKey = camelToDash(propertyKey);
if (!symbols[propertyKey]) {
constructor.observedAttributes.push(normalizedPropertyKey);
symbols[propertyKey] = symbol;
}
}
// Rest
this[symbolType] = getSymbolType(initialValue);
if (this[symbolType] === 'array') {
this[symbol] = initialValue;
return new Proxy(initialValue, {
get: (target, key) => {
if (key === meta) {
return this[symbolMeta];
}
console.log('errr???')
return Reflect.get(this[symbol], key);
},
set: (target, key, v) => {
if (key === meta) {
this[symbolMeta] = v;
return true;
}
const x = Reflect.set(target, key, v);
if (!(key === 'length' && this[symbol].length === v)) {
render(this, propertyKey);
}
this[symbol] = v;
return x;
}
});
}
// todo watch objects???
this[symbol] = normalize
? normalize(this.getAttribute(propertyKey) ?? initialValue)
: this.getAttribute(propertyKey) ?? initialValue;
return this[symbol];
};
};
}
export function Part(): any {
return function (_: Object, context: ClassFieldDecoratorContext) {
const propertyKey = context.name as string;
const key = propertyKey.replace(/^\$/, '');
context.addInitializer(function (this: any) {
let cache: any = null;
Reflect.defineProperty(this, propertyKey, {
get() {
return cache ?? (cache = this.shadowRoot?.querySelector(`[part~=${key}]`));
}
})
});
};
}
/**
* Store data via a Map into LocalStorage
* @param key String
* @returns Value
*/
export function Local(key: string): any {
return function (_: any, context: ClassFieldDecoratorContext) {
const propertyKey = context.name as string;
return function (initialValue: Map<string, any>) {
if (!(initialValue instanceof Map)) {
throw new Error('@Local(key) property must be type Map');
}
return new Proxy(initialValue, {
get(target, prop: string) {
switch (prop) {
case 'get':
return (k: string) => {
if (!initialValue.has(k)) {
throw new Error(`@Local(key) missing key ${k}`);
}
const storeKey = `${key}:${k}`;
if (window.localStorage.getItem(storeKey) === null) {
return initialValue.get(k);
} else {
return JSON.parse(window.localStorage.getItem(storeKey) ?? 'null');
}
};
case 'set':
return (k: string, v: any) => {
if (!initialValue.has(k)) {
throw new Error(`@Local(key) missing key ${k}`);
}
const storeKey = `${key}:${k}`;
if (v === null || JSON.stringify(v) === JSON.stringify(initialValue.get(k))) {
// todo? Reset to initial value
window.localStorage.removeItem(storeKey);
} else {
window.localStorage.setItem(storeKey, JSON.stringify(v));
}
};
default:
throw new Error(`@Local(key) supported method ${prop}`);
}
}
});
};
};
}
// Utils
interface TemplateAttribute {
[part: string]: Function | string | number | null
}
interface TemplatePart {
[part: string]: TemplateAttribute
}
export function node<T>(template: string, init: TemplatePart): T {
const $template = document.createElement('template');
$template.innerHTML = template;
const $node = document.importNode($template.content, true);
for (const [part, attributes] of Object.entries(init)) {
const $part = $node.querySelector<any>(`[part~="${part}"]`);
if ($part) {
for (const [prop, value] of Object.entries(attributes)) {
if (value instanceof Function) {
const val = value();
if (val === null) {
$part.removeAttribute(prop);
} else {
$part.setAttribute(prop, value());
}
} else {
$part[prop] = value;
}
}
}
}
return $node as any;
}
export function normalizeInt(value: any): number {
return parseInt(`${value}`, 10);
}
export function normalizeFloat(value: any): number {
return parseFloat(`${value}`);
}
export function normalizeBoolean(value: any): boolean {
return value === '' || value === true
? true
: value === null || value === false
? false
: value || true;
}
export function normalizeString(value: any): string {
return `${value}`;
}
export type Changes = {
[key: string]: boolean
}
const trackProxy = Symbol('hasProxy');
function hasProxy(obj: any) {
if (obj === null || typeof obj !== "object") return false;
return obj[trackProxy];
}
const meta = Symbol('meta');
interface ArrayWithMetaAndBind extends Array<any> {
[key: number]: any;
[meta]?: Map<HTMLElement, any>;
}
type ForEach = {
container: HTMLElement;
items: any;
type: (item: any) => any;
create?: ($item: HTMLElement, item: any) => void;
update?: ($item: HTMLElement, item: any) => void;
connect?: ($item: HTMLElement, item: any) => void;
disconnect?: ($item: HTMLElement, item: any) => void;
}
function intersect(arr1: string[], arr2: string[]) {
const set1 = new Set(arr1);
return arr2.filter(item => set1.has(item));
}
function difference(arr1: string[], arr2: string[]) {
return arr1.filter(str => !arr2.includes(str));
}
export function forEach({ container, items, type, create, connect, disconnect, update }: ForEach) {
if (!Array.isArray(items)) {
throw new Error('forEach `items` must be an array');
}
function newItem(item: any, itemIndex: number) {
const comp = type(item);
const $new = document.createElement(camelToDash(comp.name), comp);
//const observedAttributes = comp.observedAttributes ?? [];
const allProps = Object.keys(comp.symbols);
const props = intersect(Object.keys(item), allProps);
if (allProps.includes('index')) {
//@ts-ignore
$new['index'] = itemIndex;
}
props.forEach((attr: string) => {
// index is already written
if (attr === 'index') { return; }
//@ts-ignore
$new[attr] = item[attr];
});
create && create($new, createProxy(item));
items[itemIndex][addObserver]($new, (prop: string, value: string) => {
// @ts-ignore
$new[prop] = value;
});
return $new;
}
// Add initial items
items.forEach((item: any, i: number) => {
const $new = newItem(item, i);
container.appendChild($new);
connect && connect($new, createProxy(item));
});
// Handle each mutation
items[addObserver as any](container, (target: any, prop: any, args: any[]) => {
if (prop === Mutation.swap) {
const oldLength = items.length;
items = createProxy(args[0]);
// re-use splice to delete old nodes and add new ones (performance?)
prop = Mutation.splice;
args = [0, oldLength, ...args[0]];
}
switch(prop) {
case Mutation.fill:
// this could be optimized more, but would need the previous items keys
const [value, start, end] = args;
for (let i = start || 0; i < (end || items.length); i++) {
Object.keys(value).forEach((key) => {
// @ts-ignore
container.children[i][key] = value[key];
});
}
break;
case Mutation.pop:
const count = container.children.length;
if (count > 0) {
container.children[count - 1].remove();
}
break;
case Mutation.push:
const last = container.children.length;
[...args].forEach((item: any, i) => {
const $new = newItem(item, last + i);
container.appendChild($new);
connect && connect($new, createProxy(item));
});
break;
case Mutation.reverse:
for (var i = 1; i < container.children.length; i++){
container.insertBefore(container.children[i], container.children[0]);
}
break;
case Mutation.shift:
if (container.children.length) {
container.children[0].remove();
}
// update every index
for (let i = 0; i < container.children.length; i++) {
// @ts-ignore
container.children[i].index = i;
}
break;
case Mutation.sort:
throw new Error('ToDo... write sort.')
break;
case Mutation.splice:
const [startIndex, deleteCount, ...newItems] = args;
if (deleteCount > 0) {
for (let i = deleteCount + startIndex - 1; i >= startIndex; i--) {
container.children[i].remove();
}
}
let newCount = newItems.length || 0;
if (newCount > 0) {
const nItems = newItems.map((item: any, i: number) => {
return newItem(item, startIndex + i);
});
if (startIndex === 0) {
container.prepend(...nItems);
} else {
container.children[startIndex - 1].after(...nItems);
}
for (let i = startIndex - deleteCount + newCount; i < container.children.length; i++) {
// @ts-ignore
container.children[i].index = i;
}
nItems.forEach(($new) => {
connect && connect($new, newItems[i]);
});
} else {
for (let i = startIndex; i < container.children.length; i++) {
// @ts-ignore
container.children[i].index = i;
}
}
break;
case Mutation.unshift:
const first = container.children.length && container.children[0];
const newUnshifts = [...args].length;
[...args].forEach((item: any, i) => {
if (first) {
first.before(newItem(item, i));
} else {
container.appendChild(newItem(item, i));
}
});
// update all index values after
for (let i = newUnshifts; i < container.children.length; i++) {
// @ts-ignore
container.children[i].index = i;
}
break;
}
});
}
// JEST
export function selectComponent<T>(tagName: string): T {
const component = document.querySelector(tagName) as any;
const tags = new Set<string>();
let shadowRoot;
try {
shadowRoot = component.shadowRoot;
} catch (error: any) {
throw new Error('Add the component via document.body.appendChild(...) before selectComponent.');
}
for (const ele of shadowRoot.querySelectorAll('*')) {
if (ele.localName.indexOf('-') !== -1) {
tags.add(ele.localName);
}
}
for (var it = tags.values(), tag = null; tag = it.next().value;) {
if (!customElements.get(tag)) {
const namespaceMatch = tag.match(/^([^-]+)/);
if (namespaceMatch === null || namespaceMatch.length > 1) {
throw new Error('Failed to parse namespace.');
}
const namespace = namespaceMatch[1];
const componentMatch = tag.match(/^[^-]+-(.+)/);
if (componentMatch === null || componentMatch.length > 1) {
throw new Error('Failed to parse component name.');
}
const componentName = dashToCamel(componentMatch[1]);
throw new Error(`Missing \`import '../${componentName}/${componentName}';\` in spec.ts file.`);
}
}
return component;
}
export function selectPart<T>(component: HTMLElement, name: string): T {
return component.shadowRoot!.querySelector(`[part=${name}]`) as any;
}
export function getProps(tag: string): string[] {
const { symbols } = customElements.get(tag) as any;
return Object.keys(symbols ?? {});
}