aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/xtext/HighlightingService.ts
blob: b8ceed2033695ffbec03d91ea9151d52ef011cea (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
import { Decoration } from '@codemirror/view';
import { Range, RangeSet } from '@codemirror/rangeset';

import type { EditorStore } from '../editor/EditorStore';
import type { UpdateService } from './UpdateService';
import { getLogger } from '../utils/logger';
import { isHighlightingResult } from './xtextServiceResults';

const log = getLogger('xtext.ValidationService');

export class HighlightingService {
  private store: EditorStore;

  private updateService: UpdateService;

  constructor(store: EditorStore, updateService: UpdateService) {
    this.store = store;
    this.updateService = updateService;
  }

  onPush(push: unknown): void {
    if (!isHighlightingResult(push)) {
      log.error('Invalid highlighting result', push);
      return;
    }
    const allChanges = this.updateService.computeChangesSinceLastUpdate();
    const decorations: Range<Decoration>[] = [];
    push.regions.forEach(({ offset, length, styleClasses }) => {
      if (styleClasses.length === 0) {
        return;
      }
      const from = allChanges.mapPos(offset);
      const to = allChanges.mapPos(offset + length);
      if (to <= from) {
        return;
      }
      decorations.push(Decoration.mark({
        class: styleClasses.map((c) => `cmt-problem-${c}`).join(' '),
      }).range(from, to));
    });
    this.store.updateSemanticHighlighting(RangeSet.of(decorations, true));
  }
}