widget.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import { types } from "assets/types.js";
  2. class widget {
  3. #node;
  4. constructor(node, classname, name) {
  5. types.check_html_element(node);
  6. types.check_string(name, true);
  7. types.check_string(classname);
  8. node.classList.add(classname);
  9. if (name !== undefined && name !== null) {
  10. types.block_strings(name, [" ", "#", "\t", "\n"]);
  11. node.classList.add(name);
  12. node.classList.add(classname + "-" + name);
  13. }
  14. this.#node = node;
  15. }
  16. get node() {
  17. if (!(this.#node instanceof HTMLElement)) {
  18. throw new ReferenceError("Widget had been removed.");
  19. }
  20. return this.#node;
  21. }
  22. _add_event(name, callback) {
  23. types.check_string(name);
  24. types.check_callback(callback);
  25. this.node.addEventListener(name, (event) => {
  26. callback(event, this);
  27. });
  28. }
  29. set _content(target) {
  30. types.check_string(target);
  31. const node = this.node;
  32. if (node instanceof HTMLInputElement) {
  33. node.value = target
  34. return;
  35. }
  36. if (node instanceof HTMLImageElement) {
  37. node.src = target;
  38. return;
  39. }
  40. node.innetText = target;
  41. }
  42. _drop_content() {
  43. const node = this.node;
  44. if (node instanceof HTMLInputElement) {
  45. node.value = "";
  46. return;
  47. }
  48. while (node.childElementCound) {
  49. node.lastChild.remove();
  50. }
  51. }
  52. place(target) {
  53. types.check_html_element(target);
  54. target.appendChild(this.node);
  55. }
  56. _append(target) {
  57. if (this.node instanceof HTMLInputElement) {
  58. throw new ReferenceError("Can not append into input element.");
  59. }
  60. if (target instanceof HTMLElement) {
  61. this.node.appendChild(target);
  62. return;
  63. }
  64. if (target instanceof widget) {
  65. this.node.appendChild(target.node);
  66. return;
  67. }
  68. throw new TypeError("New item must be HTML element or widget.");
  69. }
  70. add_click(callback) {
  71. this._add_event("click", callback);
  72. }
  73. get style() {
  74. return this.node.style;
  75. }
  76. }
  77. export { widget };