history.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import { ArrayNavigator } from './navigator.js';
  6. export class HistoryNavigator {
  7. constructor(history = [], limit = 10) {
  8. this._initialize(history);
  9. this._limit = limit;
  10. this._onChange();
  11. }
  12. getHistory() {
  13. return this._elements;
  14. }
  15. add(t) {
  16. this._history.delete(t);
  17. this._history.add(t);
  18. this._onChange();
  19. }
  20. next() {
  21. if (this._currentPosition() !== this._elements.length - 1) {
  22. return this._navigator.next();
  23. }
  24. return null;
  25. }
  26. previous() {
  27. if (this._currentPosition() !== 0) {
  28. return this._navigator.previous();
  29. }
  30. return null;
  31. }
  32. current() {
  33. return this._navigator.current();
  34. }
  35. first() {
  36. return this._navigator.first();
  37. }
  38. last() {
  39. return this._navigator.last();
  40. }
  41. has(t) {
  42. return this._history.has(t);
  43. }
  44. _onChange() {
  45. this._reduceToLimit();
  46. const elements = this._elements;
  47. this._navigator = new ArrayNavigator(elements, 0, elements.length, elements.length);
  48. }
  49. _reduceToLimit() {
  50. const data = this._elements;
  51. if (data.length > this._limit) {
  52. this._initialize(data.slice(data.length - this._limit));
  53. }
  54. }
  55. _currentPosition() {
  56. const currentElement = this._navigator.current();
  57. if (!currentElement) {
  58. return -1;
  59. }
  60. return this._elements.indexOf(currentElement);
  61. }
  62. _initialize(history) {
  63. this._history = new Set();
  64. for (const entry of history) {
  65. this._history.add(entry);
  66. }
  67. }
  68. get _elements() {
  69. const elements = [];
  70. this._history.forEach(e => elements.push(e));
  71. return elements;
  72. }
  73. }