suggestCommitCharacters.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 { isNonEmptyArray } from '../../../base/common/arrays.js';
  6. import { DisposableStore } from '../../../base/common/lifecycle.js';
  7. import { CharacterSet } from '../../common/core/characterClassifier.js';
  8. export class CommitCharacterController {
  9. constructor(editor, widget, accept) {
  10. this._disposables = new DisposableStore();
  11. this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
  12. this._disposables.add(widget.onDidFocus(this._onItem, this));
  13. this._disposables.add(widget.onDidHide(this.reset, this));
  14. this._disposables.add(editor.onWillType(text => {
  15. if (this._active && !widget.isFrozen()) {
  16. const ch = text.charCodeAt(text.length - 1);
  17. if (this._active.acceptCharacters.has(ch) && editor.getOption(0 /* acceptSuggestionOnCommitCharacter */)) {
  18. accept(this._active.item);
  19. }
  20. }
  21. }));
  22. }
  23. _onItem(selected) {
  24. if (!selected || !isNonEmptyArray(selected.item.completion.commitCharacters)) {
  25. // no item or no commit characters
  26. this.reset();
  27. return;
  28. }
  29. if (this._active && this._active.item.item === selected.item) {
  30. // still the same item
  31. return;
  32. }
  33. // keep item and its commit characters
  34. const acceptCharacters = new CharacterSet();
  35. for (const ch of selected.item.completion.commitCharacters) {
  36. if (ch.length > 0) {
  37. acceptCharacters.add(ch.charCodeAt(0));
  38. }
  39. }
  40. this._active = { acceptCharacters, item: selected };
  41. }
  42. reset() {
  43. this._active = undefined;
  44. }
  45. dispose() {
  46. this._disposables.dispose();
  47. }
  48. }