aboutsummaryrefslogtreecommitdiff
path: root/src/z/z.js
blob: a5a1b923164a0990a82f1f371e1fd0960a5c297d (plain)
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
class ZComponent extends HTMLElement {
	constructor() {
		super();
		this.attachShadow({ mode: 'open' });
	}

	connectedCallback() {
		const type = this.getAttribute('type');

		if (type == null) {
			throw `component without any type given.`;
		}

		const template = document.getElementById(`@${type}`);

		if (template == null) {
			throw `component '${type}' does not exist.`;
		}

		const node = document.importNode(template.content, true);
		this.shadowRoot.appendChild(node);

		Zenv.constructors[`component__${type}`](new Zenv(this));
	}
}

class Zenv {
	static constructors = {};

	constructor(doc) {
		this.document = doc;
	}

	component(type, slots) {
		const element = document.createElement('z-component');
		element.setAttribute('type', type);

		for (const name in slots) {
			const slot = slots[name];
			slot.setAttribute('slot', name);
			element.appendChild(slot);
		}

		return element;
	}

	populate_attributes(obj, attrs) {
		for (const attr in attrs) {
			if (typeof(obj[attr]) == 'object' && typeof(attrs[attr]) == 'object') {
				populate_attributes(obj[attr], attrs[attr]);
			} else {
				obj[attr] = attrs[attr];
			}
		}
	}

	native(name, options) {
		const element = document.createElement(name);
		Zenv.populate_attributes(element, options);
		return element;
	}

	by_id(id) {
		return this.document.shadowRoot.getElementById(id);
	}

	by_selector(query) {
		return this.document.shadowRoot.querySelector(query);
	}

	by_selector_all(query) {
		return this.document.shadowRoot.querySelectorAll(query);
	}
}

Z = new Zenv(document.body);

customElements.define("z-component", ZComponent);