61 lignes
1.8 KiB

  1. 'use strict';
  2. import { Functions } from './system';
  3. import { commands, Disposable, TextEditor, window } from 'vscode';
  4. import { BuiltInCommands } from './constants';
  5. export class ActiveEditorTracker extends Disposable {
  6. private _disposable: Disposable;
  7. private _resolver: ((editor: TextEditor | undefined) => void) | undefined;
  8. constructor() {
  9. super(() => this.dispose());
  10. const fn = Functions.debounce((e: TextEditor | undefined) => this._resolver && this._resolver(e), 50);
  11. this._disposable = window.onDidChangeActiveTextEditor(fn);
  12. }
  13. dispose() {
  14. this._disposable && this._disposable.dispose();
  15. }
  16. async awaitClose(timeout: number = 500): Promise<TextEditor | undefined> {
  17. this.close();
  18. return this.wait(timeout);
  19. }
  20. async awaitNext(timeout: number = 500): Promise<TextEditor | undefined> {
  21. this.next();
  22. return this.wait(timeout);
  23. }
  24. async close(): Promise<{} | undefined> {
  25. return commands.executeCommand(BuiltInCommands.CloseActiveEditor);
  26. }
  27. async next(): Promise<{} | undefined> {
  28. return commands.executeCommand(BuiltInCommands.NextEditor);
  29. }
  30. async wait(timeout: number = 500): Promise<TextEditor | undefined> {
  31. const editor = await new Promise<TextEditor>((resolve, reject) => {
  32. let timer: any;
  33. this._resolver = (editor: TextEditor | undefined) => {
  34. if (timer) {
  35. clearTimeout(timer as any);
  36. timer = 0;
  37. resolve(editor);
  38. }
  39. };
  40. timer = setTimeout(() => {
  41. resolve(window.activeTextEditor);
  42. timer = 0;
  43. }, timeout) as any;
  44. });
  45. this._resolver = undefined;
  46. return editor;
  47. }
  48. }