aboutsummaryrefslogtreecommitdiffstats
path: root/src/webview/spellchecker.js
blob: a504a4039f99f74d26db7a07b887e1f5d98f9ccb (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
import { SpellCheckHandler } from 'electron-spellchecker';

import { isMac } from '../environment';

export default class Spellchecker {
  isInitialized = false;
  handler = null;
  initRetries = 0;
  DOMCheckInterval = null;

  get inputs() {
    return document.querySelectorAll('input[type="text"], [contenteditable="true"], textarea');
  }

  initialize() {
    this.handler = new SpellCheckHandler();

    if (!isMac) {
      this.attach();
    } else {
      this.isInitialized = true;
    }
  }

  attach() {
    let initFailed = false;

    if (this.initRetries > 3) {
      console.error('Could not initialize spellchecker');
      return;
    }

    try {
      this.handler.attachToInput();
      this.handler.switchLanguage(navigator.language);
    } catch (err) {
      initFailed = true;
      this.initRetries = +1;
      setTimeout(() => { this.attach(); console.warn('Spellchecker init failed, trying again in 5s'); }, 5000);
    }

    if (!initFailed) {
      this.isInitialized = true;
    }
  }

  toggleSpellchecker(enable = false) {
    this.inputs.forEach((input) => {
      input.setAttribute('spellcheck', enable);
    });

    this.intervalHandler(enable);
  }

  intervalHandler(enable) {
    clearInterval(this.DOMCheckInterval);

    if (enable) {
      this.DOMCheckInterval = setInterval(() => this.toggleSpellchecker(enable), 30000);
    }
  }
}