summaryrefslogtreecommitdiffstats
path: root/polygerrit-ui/app/elements/plugins/gr-suggestions-api/gr-suggestions-api.ts
blob: 400684900e45a163f0aad5cd2ac8012d1cef1a17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import {PluginApi} from '../../../api/plugin';
import {ReportingService} from '../../../services/gr-reporting/gr-reporting';
import {PluginsModel} from '../../../models/plugins/plugins-model';
import {
  SuggestionsPluginApi,
  SuggestionsProvider,
} from '../../../api/suggestions';

enum State {
  NOT_REGISTERED,
  REGISTERED,
}

/**
 * Plugin API for suggestions.
 *
 * This object is returned to plugins that want to provide suggestions data.
 * Plugins normally just call register() once at startup and then wait for
 * suggestCode() being called on the provider interface.
 */
export class GrSuggestionsApi implements SuggestionsPluginApi {
  private state = State.NOT_REGISTERED;

  constructor(
    private readonly reporting: ReportingService,
    private readonly pluginsModel: PluginsModel,
    readonly plugin: PluginApi
  ) {
    this.reporting.trackApi(this.plugin, 'suggestions', 'constructor');
  }

  register(provider: SuggestionsProvider): void {
    this.reporting.trackApi(this.plugin, 'suggestions', 'register');
    if (this.state === State.REGISTERED) {
      throw new Error('Only one provider can be registered per plugin.');
    }
    this.state = State.REGISTERED;
    this.pluginsModel.suggestionsRegister({
      pluginName: this.plugin.getPluginName(),
      provider,
    });
  }
}