list_applet.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { dom_manager } from "./functions.js";
  2. class list_applet {
  3. #symbol;
  4. #target;
  5. #items;
  6. constructor(target, symbol = null) {
  7. if (!dom_manager.is_element(target)) {
  8. throw "Target list must be an HTML element.";
  9. }
  10. this.#items = new Object();
  11. this.#target = target;
  12. this.#symbol = null;
  13. if (symbol !== null) {
  14. this.#symbol = symbol.toString();
  15. }
  16. if (!this.#target.classList.contains("items-list")) {
  17. this.#target.classList.add("items-list");
  18. }
  19. this.clean();
  20. }
  21. clean() {
  22. while(this.#target.childElementCount) {
  23. this.#target.lastChild.remove();
  24. }
  25. }
  26. exists(name) {
  27. return this.#items.hasOwnProperty(name);
  28. }
  29. remove(name) {
  30. if (!this.exists(name)) {
  31. throw "Can not remove item. This item not exists on list.";
  32. }
  33. this.#items[name].remove();
  34. delete(this.#items[name]);
  35. }
  36. #new_symbol() {
  37. const symbol = document.createElement("span");
  38. symbol.classList.add("material-symbols-outlined");
  39. symbol.innerText = this.#symbol;
  40. return symbol;
  41. }
  42. append(name, action) {
  43. if (this.exists(name)) {
  44. throw "Items with this name already exists on list.";
  45. }
  46. name = name.trim();
  47. if (name.length === 0) {
  48. throw "Name for new item can not be empty.";
  49. }
  50. const new_item = document.createElement("div");
  51. new_item.classList.add("list-item");
  52. if (this.#symbol !== null) {
  53. new_item.appendChild(this.#new_symbol());
  54. }
  55. const nametag = document.createElement("p");
  56. nametag.innerText = name;
  57. new_item.appendChild(nametag);
  58. this.#target.appendChild(new_item);
  59. this.#items[name] = new_item;
  60. new_item.addEventListener("click", () => {
  61. action(this, name);
  62. });
  63. }
  64. }
  65. export { list_applet };