cyp/app/js/search.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2019-03-31 06:15:32 +08:00
import * as html from "./html.js";
2020-03-10 05:24:31 +08:00
import * as conf from "./conf.js";
2019-03-31 06:15:32 +08:00
2019-04-01 04:02:26 +08:00
const OPEN = "open";
2019-04-01 21:26:14 +08:00
const collator = new Intl.Collator(conf.locale, {usage:"search", sensitivity:"base"});
2019-03-31 06:15:32 +08:00
export default class Search extends EventTarget {
constructor(parent) {
super();
2019-04-01 04:02:26 +08:00
this._node = html.node("label", {className:"search"});
this._input = html.node("input", {type:"text"}, "", this._node);
html.icon("magnify", this._node);
this._node.addEventListener("click", e => {
if (e.target == this._input) { return; }
if (this._node.classList.contains(OPEN)) {
2019-04-01 21:16:39 +08:00
this.reset();
2020-03-10 05:24:31 +08:00
this.dispatchEvent(new Event("input"));
2019-04-01 04:02:26 +08:00
} else {
this._node.classList.add(OPEN);
}
});
2019-04-01 21:16:39 +08:00
this._input.addEventListener("input", e => {
this.dispatchEvent(new Event("input"));
});
2019-03-31 06:15:32 +08:00
}
getNode() { return this._node; }
2019-04-01 21:16:39 +08:00
match(str) {
2019-04-01 21:26:14 +08:00
let q = this._input.value.trim();
2019-04-01 21:16:39 +08:00
if (!q) { return true; }
2019-04-01 21:26:14 +08:00
let len = q.length;
return str.split(" ").some(str => collator.compare(q, str.substring(0, len)) == 0);
2019-04-01 21:16:39 +08:00
}
2019-03-31 06:15:32 +08:00
2019-04-01 04:02:26 +08:00
reset() {
this._input.value = "";
this._node.classList.remove(OPEN);
}
2019-03-31 06:15:32 +08:00
}