search.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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.#hint.style.display = "none";
  22. this.#input = document.createElement("input");
  23. this.#input.type = "text";
  24. this.#input.placeholder = lang.search.type;
  25. const submit = document.createElement("input");
  26. submit.type = "submit";
  27. submit.value = lang.search.find;
  28. const form = document.createElement("form");
  29. this.#list = new items_list(this.#hint, this.click);
  30. form.addEventListener("submit", (action) => {
  31. action.preventDefault();
  32. this.find();
  33. });
  34. this.#input.addEventListener("keypress", () => {
  35. this.refresh();
  36. });
  37. this.#input.addEventListener("keyup", () => {
  38. this.refresh();
  39. });
  40. this.#input.addEventListener("change", () => {
  41. this.refresh();
  42. });
  43. form.appendChild(this.#input);
  44. form.appendChild(submit);
  45. this.#container.appendChild(form);
  46. this.#container.appendChild(this.#hint);
  47. }
  48. click(item) {
  49. console.log(item.name);
  50. }
  51. get content() {
  52. return this.#input.value.trim();
  53. }
  54. get changed() {
  55. if (this.content === this.#last_content) {
  56. return false;
  57. }
  58. this.#last_content = this.content;
  59. return true;
  60. }
  61. get results() {
  62. if (this.content.length === 0) {
  63. return [];
  64. }
  65. return this.#store.search(this.content);
  66. }
  67. find() {
  68. this.refresh();
  69. }
  70. refresh() {
  71. if (!this.changed) {
  72. return;
  73. }
  74. const results = this.results;
  75. this.#list.update(results);
  76. if (results.length === 0) {
  77. this.#hint.style.display = "none";
  78. } else {
  79. this.#hint.style.display = "";
  80. }
  81. }
  82. get ui() {
  83. return this.#container;
  84. }
  85. }
  86. export { search };