summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/ide/lib/diff/controller.js
blob: 046e562ba2bb90e5210634b9efaae2fde745ff3a (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Range } from 'monaco-editor';
import { throttle } from 'underscore';
import DirtyDiffWorker from './diff_worker';
import Disposable from '../common/disposable';

export const getDiffChangeType = change => {
  if (change.modified) {
    return 'modified';
  } else if (change.added) {
    return 'added';
  } else if (change.removed) {
    return 'removed';
  }

  return '';
};

export const getDecorator = change => ({
  range: new Range(change.lineNumber, 1, change.endLineNumber, 1),
  options: {
    isWholeLine: true,
    linesDecorationsClassName: `dirty-diff dirty-diff-${getDiffChangeType(change)}`,
  },
});

export default class DirtyDiffController {
  constructor(modelManager, decorationsController) {
    this.disposable = new Disposable();
    this.models = new Map();
    this.editorSimpleWorker = null;
    this.modelManager = modelManager;
    this.decorationsController = decorationsController;
    this.dirtyDiffWorker = new DirtyDiffWorker();
    this.throttledComputeDiff = throttle(this.computeDiff, 250);
    this.decorate = this.decorate.bind(this);

    this.dirtyDiffWorker.addEventListener('message', this.decorate);
  }

  attachModel(model) {
    if (this.models.has(model.url)) return;

    model.onChange(() => this.throttledComputeDiff(model));
    model.onDispose(() => {
      this.decorationsController.removeDecorations(model);
      this.models.delete(model.url);
    });

    this.models.set(model.url, model);
  }

  computeDiff(model) {
    this.dirtyDiffWorker.postMessage({
      path: model.path,
      originalContent: model.getOriginalModel().getValue(),
      newContent: model.getModel().getValue(),
    });
  }

  reDecorate(model) {
    if (this.decorationsController.hasDecorations(model)) {
      this.decorationsController.decorate(model);
    } else {
      this.computeDiff(model);
    }
  }

  decorate({ data }) {
    const decorations = data.changes.map(change => getDecorator(change));
    const model = this.modelManager.getModel(data.path);
    this.decorationsController.addDecorations(model, 'dirtyDiff', decorations);
  }

  dispose() {
    this.disposable.dispose();
    this.models.clear();

    this.dirtyDiffWorker.removeEventListener('message', this.decorate);
    this.dirtyDiffWorker.terminate();
  }
}