searcher.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. "barcode": _("barcode-category"),
  40. }
  41. }
  42. #selector_complete() {
  43. const category = this.#category;
  44. const categories = this.categories;
  45. Object.keys(categories).forEach(name => {
  46. const option = document.createElement("option");
  47. option.value = name;
  48. option.innerText = categories[name];
  49. category.appendChild(option);
  50. });
  51. }
  52. get #loader() {
  53. return {
  54. "name": products_loader.search_name,
  55. "author": products_loader.search_author,
  56. "barcode": products_loader.search_barcode,
  57. }[this.category];
  58. }
  59. get category() {
  60. return this.#category.value;
  61. }
  62. get phrase() {
  63. return this.#input.value.trim();
  64. }
  65. get #result_title() {
  66. return this.#result.innerText;
  67. }
  68. set #result_title(target) {
  69. this.#result.innerText = target;
  70. }
  71. async update() {
  72. if (this.phrase.length === 0) {
  73. this.show_all();
  74. return;
  75. }
  76. this.#insert(await this.#loader(this.phrase));
  77. }
  78. #insert(list) {
  79. if (list.length === 0) {
  80. this.#result_title = _("not-found-anything");
  81. } else {
  82. this.#result_title = _("browse-our-products");
  83. }
  84. this.#manager
  85. .clean()
  86. .add_list(list)
  87. .update();
  88. }
  89. async show_all() {
  90. this.#insert(await products_loader.all())
  91. }
  92. }