history.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Phoenix Shell.
  5. *
  6. * Phoenix Shell is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. export class HistoryManager {
  20. constructor({ enableLogging = false } = {}) {
  21. this.items = [];
  22. this.index_ = 0;
  23. this.listeners_ = {};
  24. this.enableLogging_ = enableLogging;
  25. }
  26. log(...a) {
  27. // TODO: Command line option for configuring logging
  28. if ( this.enableLogging_ ) {
  29. console.log('[HistoryManager]', ...a);
  30. }
  31. }
  32. get index() {
  33. return this.index_;
  34. }
  35. set index(v) {
  36. this.log('setting index', v);
  37. this.index_ = v;
  38. }
  39. get() {
  40. return this.items[this.index];
  41. }
  42. // Save, overwriting the current history item
  43. save(data, { opt_debug } = {}) {
  44. this.log('saving', data, 'at', this.index,
  45. ...(opt_debug ? [ 'from', opt_debug ] : []));
  46. this.items[this.index] = data;
  47. if (this.listeners_.hasOwnProperty('add')) {
  48. for (const listener of this.listeners_.add) {
  49. listener(data);
  50. }
  51. }
  52. }
  53. append(data) {
  54. if (
  55. this.items.length !== 0 &&
  56. this.index !== this.items.length
  57. ) {
  58. this.log('POP');
  59. // remove last item
  60. this.items.pop();
  61. }
  62. this.index = this.items.length;
  63. this.save(data, { opt_debug: 'append' });
  64. this.index++;
  65. }
  66. on(topic, listener) {
  67. if (!this.listeners_.hasOwnProperty(topic)) {
  68. this.listeners_[topic] = [];
  69. }
  70. this.listeners_[topic].push(listener);
  71. }
  72. }