This repository was archived by the owner on Mar 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathComponent.js
More file actions
55 lines (53 loc) · 1.93 KB
/
Component.js
File metadata and controls
55 lines (53 loc) · 1.93 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
// viper.Component() 🍻
// An overly-simplified Component class.
module.exports = render => class Component {
static for(context, id) {
const info = children.get(context) || set(context);
return get(this, info, context, id == null ? 'default' : id);
}
handleEvent() { /* noop by default */ }
get html() { return (this.html = render.bind(this)); }
set html(value) { defineValue(this, 'html', value); }
get svg() { return (this.svg = render.bind(this)); }
set svg(value) { defineValue(this, 'svg', value); }
get state() { return (this.state = this.defaultState); }
set state(value) { defineValue(this, 'state', value); }
get defaultState() { return {}; }
dispatch() { return true; }
setState(state, render) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) target[key] = source[key];
if (render !== false) this.render();
return this;
}
// the render must be defined when extending hyper.Component
// the render **must** return either comp.html or comp.svg wire
// render() { return this.html`<p>that's it</p>`; }
};
// directly from hyperHTML Component
const children = new WeakMap;
const create = Object.create;
const createEntry = (wm, id, component) => {
wm.set(id, component);
return component;
};
const get = (Class, info, context, id) => {
switch (typeof id) {
case 'object':
case 'function':
const wm = info.w || (info.w = new WeakMap);
return wm.get(id) || createEntry(wm, id, new Class(context));
default:
const sm = info.p || (info.p = create(null));
return sm[id] || (sm[id] = new Class(context));
}
};
const set = context => {
const info = {w: null, p: null};
children.set(context, info);
return info;
};
// set a configurable, non enumerable, non writable property
const defineValue = (self, key, value) =>
Object.defineProperty(self, key, {configurable: true, value: value});