history.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. add(t) {
  13. this._history.delete(t);
  14. this._history.add(t);
  15. this._onChange();
  16. }
  17. next() {
  18. if (this._currentPosition() !== this._elements.length - 1) {
  19. return this._navigator.next();
  20. }
  21. return null;
  22. }
  23. previous() {
  24. if (this._currentPosition() !== 0) {
  25. return this._navigator.previous();
  26. }
  27. return null;
  28. }
  29. current() {
  30. return this._navigator.current();
  31. }
  32. first() {
  33. return this._navigator.first();
  34. }
  35. last() {
  36. return this._navigator.last();
  37. }
  38. has(t) {
  39. return this._history.has(t);
  40. }
  41. _onChange() {
  42. this._reduceToLimit();
  43. const elements = this._elements;
  44. this._navigator = new ArrayNavigator(elements, 0, elements.length, elements.length);
  45. }
  46. _reduceToLimit() {
  47. const data = this._elements;
  48. if (data.length > this._limit) {
  49. this._initialize(data.slice(data.length - this._limit));
  50. }
  51. }
  52. _currentPosition() {
  53. const currentElement = this._navigator.current();
  54. if (!currentElement) {
  55. return -1;
  56. }
  57. return this._elements.indexOf(currentElement);
  58. }
  59. _initialize(history) {
  60. this._history = new Set();
  61. for (const entry of history) {
  62. this._history.add(entry);
  63. }
  64. }
  65. get _elements() {
  66. const elements = [];
  67. this._history.forEach(e => elements.push(e));
  68. return elements;
  69. }
  70. }