searcher.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { products_loader } from "./products_loader.js";
  2. import { product_containers } from "./product_containers.js";
  3. export class searcher {
  4. #input;
  5. #category;
  6. #manager;
  7. #result;
  8. static #instances;
  9. static #add(instance) {
  10. if (typeof(searcher.#instances) !== "object") {
  11. searcher.#instances = new Array();
  12. }
  13. searcher.#instances.push(instance);
  14. }
  15. static reload() {
  16. if (typeof(searcher.#instances) !== "object") {
  17. return ;
  18. }
  19. searcher.#instances.forEach(instance => {
  20. instance.update();
  21. });
  22. }
  23. constructor(search_form, manager, result) {
  24. this.#input = search_form.querySelector("input[type=\"text\"]");
  25. this.#category = search_form.querySelector("select");
  26. this.#manager = manager;
  27. this.#result = result;
  28. this.#selector_complete();
  29. search_form.addEventListener("submit", (target) => {
  30. target.preventDefault();
  31. this.update();
  32. });
  33. searcher.#add(this);
  34. }
  35. get categories() {
  36. return {
  37. "name": _("name-category"),
  38. "author": _("author-category")
  39. }
  40. }
  41. #selector_complete() {
  42. const category = this.#category;
  43. const categories = this.categories;
  44. Object.keys(categories).forEach(name => {
  45. const option = document.createElement("option");
  46. option.value = name;
  47. option.innerText = categories[name];
  48. category.appendChild(option);
  49. });
  50. }
  51. get #loader() {
  52. return {
  53. "name": products_loader.search_name,
  54. "author": products_loader.search_author
  55. }[this.category];
  56. }
  57. get category() {
  58. return this.#category.value;
  59. }
  60. get phrase() {
  61. return this.#input.value.trim();
  62. }
  63. get #result_title() {
  64. return this.#result.innerText;
  65. }
  66. set #result_title(target) {
  67. this.#result.innerText = target;
  68. }
  69. async update() {
  70. if (this.phrase.length === 0) {
  71. this.show_all();
  72. return;
  73. }
  74. this.#insert(await this.#loader(this.phrase));
  75. }
  76. #insert(list) {
  77. if (list.length === 0) {
  78. this.#result_title = _("not-found-anything");
  79. } else {
  80. this.#result_title = _("browse-our-products");
  81. }
  82. this.#manager
  83. .clean()
  84. .add_list(list)
  85. .update();
  86. }
  87. async show_all() {
  88. this.#insert(await products_loader.all())
  89. }
  90. }