This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/ui/web/ListView.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-02-21 04:18:16 +05:30
import * as html from "./html.js";
class UIView {
2019-02-27 03:15:58 +05:30
mount() {}
unmount() {}
update(_value) {}
// can only be called between a call to mount and unmount
root() {}
}
2019-02-21 04:18:16 +05:30
2019-02-27 03:15:58 +05:30
function insertAt(parentNode, idx, childNode) {
2019-02-27 03:57:34 +05:30
const isLast = idx === parentNode.childElementCount;
2019-02-27 03:15:58 +05:30
if (isLast) {
parentNode.appendChild(childNode);
} else {
2019-02-27 03:57:34 +05:30
const nextDomNode = parentNode.children[idx];
2019-02-27 03:15:58 +05:30
parentNode.insertBefore(childNode, nextDomNode);
2019-02-21 04:18:16 +05:30
}
}
export default class ListView {
constructor(collection, childCreator) {
this._collection = collection;
this._root = null;
this._subscription = null;
this._childCreator = childCreator;
this._childInstances = null;
}
2019-02-27 03:15:58 +05:30
root() {
2019-02-21 04:18:16 +05:30
return this._root;
}
2019-02-27 03:15:58 +05:30
update() {}
2019-02-21 04:18:16 +05:30
mount() {
this._subscription = this._collection.subscribe(this);
this._root = html.ul({className: "ListView"});
2019-02-27 03:57:34 +05:30
this._childInstances = [];
2019-02-21 04:18:16 +05:30
for (let item of this._collection) {
const child = this._childCreator(item);
this._childInstances.push(child);
const childDomNode = child.mount();
this._root.appendChild(childDomNode);
}
return this._root;
}
unmount() {
this._subscription = this._subscription();
for (let child of this._childInstances) {
child.unmount();
}
this._childInstances = null;
}
2019-02-27 03:15:58 +05:30
onAdd(idx, value) {
2019-02-21 04:18:16 +05:30
const child = this._childCreator(value);
2019-02-27 03:15:58 +05:30
this._childInstances.splice(idx, 0, child);
insertAt(this._root, idx, child.mount());
2019-02-21 04:18:16 +05:30
}
2019-02-27 03:15:58 +05:30
onRemove(idx, _value) {
const [child] = this._childInstances.splice(idx, 1);
child.root().remove();
2019-02-21 04:18:16 +05:30
child.unmount();
}
onMove(fromIdx, toIdx, value) {
2019-02-27 03:15:58 +05:30
const [child] = this._childInstances.splice(fromIdx, 1);
this._childInstances.splice(toIdx, 0, child);
child.root().remove();
insertAt(this._root, toIdx, child.root());
2019-02-21 04:18:16 +05:30
}
2019-02-27 03:15:58 +05:30
onUpdate(i, value) {
2019-02-21 04:18:16 +05:30
this._childInstances[i].update(value);
}
}