summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/repo/lib/diff/worker.js
blob: 93d94f8d1389436e1ce80c0f86863e24d080f3a6 (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
/* global monaco */
export default class DirtyDiffWorker {
  constructor() {
    this.editorSimpleWorker = null;
    this.models = new Map();
    this.actions = new Set();

    // eslint-disable-next-line promise/catch-or-return
    monaco.editor.createWebWorker({
      moduleId: 'vs/editor/common/services/editorSimpleWorker',
    }).getProxy().then((editorSimpleWorker) => {
      this.editorSimpleWorker = editorSimpleWorker;
      this.ready();
    });
  }

  // loop through all the previous cached actions
  // this way we don't block the user from editing the file
  ready() {
    this.actions.forEach((action) => {
      const methodName = Object.keys(action)[0];
      this[methodName](...action[methodName]);
    });

    this.actions.clear();
  }

  attachModel(model) {
    if (this.editorSimpleWorker && !this.models.has(model.url)) {
      this.editorSimpleWorker.acceptNewModel(model);

      this.models.set(model.url, model);
    } else if (!this.editorSimpleWorker) {
      this.actions.add({
        attachModel: [model],
      });
    }
  }

  modelChanged(model, e) {
    if (this.editorSimpleWorker) {
      this.editorSimpleWorker.acceptModelChanged(
        model.getModel().uri.toString(),
        e,
      );
    } else {
      this.actions.add({
        modelChanged: [model, e],
      });
    }
  }

  compute(model, cb) {
    if (this.editorSimpleWorker) {
      // eslint-disable-next-line promise/catch-or-return
      this.editorSimpleWorker.computeDiff(
        model.getOriginalModel().uri.toString(),
        model.getModel().uri.toString(),
      ).then(cb);
    } else {
      this.actions.add({
        compute: [model, cb],
      });
    }
  }

  dispose() {
    this.models.forEach(model =>
      this.editorSimpleWorker.acceptRemovedModel(model.url),
    );
    this.models.clear();

    this.actions.clear();

    this.editorSimpleWorker.dispose();
    this.editorSimpleWorker = null;
  }
}