search.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import { database } from "./database.js";
  2. import { lang } from "./lang.js";
  3. import { items_list } from "./items_list.js";
  4. class search {
  5. #container;
  6. #hint;
  7. #input;
  8. #last_content;
  9. #store;
  10. #list;
  11. constructor(store) {
  12. if (!(store instanceof database)) {
  13. throw "Store must be instance of database";
  14. }
  15. this.#last_content = "";
  16. this.#store = store;
  17. this.#container = document.createElement("div");
  18. this.#container.className = "search";
  19. this.#hint = document.createElement("div");
  20. this.#hint.className = "hint";
  21. this.#input = document.createElement("input");
  22. this.#input.type = "text";
  23. this.#input.placeholder = lang.search.type;
  24. const submit = document.createElement("input");
  25. submit.type = "submit";
  26. submit.value = lang.search.find;
  27. const form = document.createElement("form");
  28. this.#list = new items_list(this.#hint, this.click);
  29. form.addEventListener("submit", (action) => {
  30. action.preventDefault();
  31. this.find();
  32. });
  33. this.#input.addEventListener("keypress", () => {
  34. this.refresh();
  35. });
  36. this.#input.addEventListener("keyup", () => {
  37. this.refresh();
  38. });
  39. this.#input.addEventListener("change", () => {
  40. this.refresh();
  41. });
  42. form.appendChild(this.#input);
  43. form.appendChild(submit);
  44. this.#container.appendChild(form);
  45. this.#container.appendChild(this.#hint);
  46. }
  47. click(item) {
  48. console.log(item.name);
  49. }
  50. get content() {
  51. return this.#input.value.trim();
  52. }
  53. get changed() {
  54. if (this.content === this.#last_content) {
  55. return false;
  56. }
  57. this.#last_content = this.content;
  58. return true;
  59. }
  60. get results() {
  61. if (this.content.length === 0) {
  62. return [];
  63. }
  64. return this.#store.search(this.content);
  65. }
  66. find() {
  67. if (!this.changed) {
  68. return;
  69. }
  70. this.#list.update(this.results);
  71. }
  72. refresh() {
  73. if (!this.changed) {
  74. return;
  75. }
  76. this.#list.update(this.results);
  77. }
  78. get ui() {
  79. return this.#container;
  80. }
  81. }
  82. export { search };