option.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { types } from "assets/types.js";
  2. class option {
  3. #name;
  4. #options;
  5. #default;
  6. constructor(name) {
  7. types.check_string(name);
  8. name = name.trim();
  9. if (name.length === 0) {
  10. throw new TypeError("Name can not be blank.");
  11. }
  12. this.#name = name;
  13. this.#default = undefined;
  14. this.#options = new Set();
  15. }
  16. #sanitize_option(option) {
  17. types.check_string(option);
  18. option = option.trim();
  19. if (option.length === 0) {
  20. throw new TypeError("Option could not be blank.");
  21. }
  22. return option;
  23. }
  24. set _default(option) {
  25. option = this.#sanitize_option(option);
  26. this.#default = option;
  27. this.#options.add(option);
  28. }
  29. _add_option(option) {
  30. this.#options.add(this.#sanitize_option(option));
  31. }
  32. get options() {
  33. return Array.from(this.#options.values());
  34. }
  35. get default() {
  36. if (this.#default === undefined) {
  37. throw new ReferenceError("Default option is not setup yet.");
  38. }
  39. return this.#default;
  40. }
  41. select(option) {
  42. if (!this.#options.has(option)) {
  43. throw new Error("Setting has not option \"" + option + "\".");
  44. }
  45. if (this.default === option) {
  46. localStorage.removeItem(this.#name);
  47. return;
  48. }
  49. localStorage.setItem(this.#name, option);
  50. }
  51. get selected() {
  52. const read = localStorage.getItem(this.#name);
  53. if (read === null) {
  54. return this.default;
  55. }
  56. if (!this.#options.has(read)) {
  57. return this.default;
  58. }
  59. return read;
  60. }
  61. }
  62. export { option };