aboutsummaryrefslogtreecommitdiffstats
path: root/src/webview/lib/RecipeWebview.js
blob: 74d05fc2df3ced1feb1314b929451da09434dde0 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const { ipcRenderer } = require('electron');
const fs = require('fs-extra');

const debug = require('debug')('Franz:Plugin:RecipeWebview');

class RecipeWebview {
  constructor() {
    this.countCache = {
      direct: 0,
      indirect: 0,
    };

    ipcRenderer.on('poll', () => {
      this.loopFunc();

      debug('Poll event');
    });
  }

  loopFunc = () => null;

  /**
   * Initialize the loop
   *
   * @param {Function}        Function that will be executed
   */
  loop(fn) {
    this.loopFunc = fn;
  }

  /**
   * Set the unread message badge
   *
   * @param {int} direct      Set the count of direct messages
   *                          eg. Slack direct mentions, or a
   *                          message to @channel
   * @param {int} indirect    Set a badge that defines there are
   *                          new messages but they do not involve
   *                          me directly to me eg. in a channel
   */
  setBadge(direct = 0, indirect = 0) {
    if (this.countCache.direct === direct
      && this.countCache.indirect === indirect) return;

    // Parse number to integer
    // This will correct errors that recipes may introduce, e.g.
    // by sending a String instead of an integer
    const directInt = parseInt(direct, 10);
    const indirectInt = parseInt(indirect, 10);

    const count = {
      direct: directInt > 0 ? directInt : 0,
      indirect: indirectInt > 0 ? indirectInt : 0,
    };


    ipcRenderer.sendToHost('messages', count);
    Object.assign(this.countCache, count);

    debug('Sending badge count to host', count);
  }

  /**
   * Injects the contents of a CSS file into the current webview
   *
   * @param {Array} files     CSS files that should be injected. This must
   *                          be an absolute path to the file
   */
  injectCSS(...files) {
    files.forEach((file) => {
      const data = fs.readFileSync(file);
      const styles = document.createElement('style');
      styles.innerHTML = data.toString();

      document.querySelector('head').appendChild(styles);

      debug('Append styles', styles);
    });
  }

  onNotify(fn) {
    if (typeof fn === 'function') {
      window.Notification.prototype.onNotify = fn;
    }
  }

  initialize(fn) {
    if (typeof fn === 'function') {
      fn();
    }
  }
}

module.exports = RecipeWebview;