aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/xtext/ModelGenerationService.ts
blob: 29a706237d6da3d7002e75960e439074eaf2cfb0 (plain) (blame)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import type { Transaction } from '@codemirror/state';

import type EditorStore from '../editor/EditorStore';

import type UpdateService from './UpdateService';
import { ModelGenerationResult } from './xtextServiceResults';

const INITIAL_RANDOM_SEED = 1;

export default class ModelGenerationService {
  private nextRandomSeed = INITIAL_RANDOM_SEED;

  constructor(
    private readonly store: EditorStore,
    private readonly updateService: UpdateService,
  ) {}

  onPush(push: unknown): void {
    const result = ModelGenerationResult.parse(push);
    if ('status' in result) {
      this.store.setGeneratedModelMessage(result.uuid, result.status);
    } else if ('error' in result) {
      this.store.setGeneratedModelError(result.uuid, result.error);
    } else {
      this.store.setGeneratedModelSemantics(result.uuid, result);
    }
  }

  onTransaction(transaction: Transaction): void {
    if (transaction.docChanged) {
      this.resetRandomSeed();
    }
  }

  onDisconnect(): void {
    this.store.modelGenerationCancelled();
    this.resetRandomSeed();
  }

  async start(randomSeed?: number): Promise<void> {
    const randomSeedOrNext = randomSeed ?? this.nextRandomSeed;
    this.nextRandomSeed = randomSeedOrNext + 1;
    const result =
      await this.updateService.startModelGeneration(randomSeedOrNext);
    if (!result.cancelled) {
      this.store.addGeneratedModel(result.data.uuid, randomSeedOrNext);
    }
  }

  async cancel(): Promise<void> {
    const result = await this.updateService.cancelModelGeneration();
    if (!result.cancelled) {
      this.store.modelGenerationCancelled();
    }
  }

  private resetRandomSeed() {
    this.nextRandomSeed = INITIAL_RANDOM_SEED;
  }
}