aboutsummaryrefslogtreecommitdiffstats
path: root/src/webview/badge.js
blob: 6be4cf6096e5607bc108f47df2f38e544a9dbf45 (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
const { ipcRenderer } = require('electron');

const debug = require('debug')('Ferdi:Plugin:BadgeHandler');

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

  _normalizeNumber(count) {
    // Parse number to integer
    // This will correct errors that recipes may introduce, e.g.
    // by sending a String instead of an integer
    const parsedNumber = parseInt(count, 10);
    const adjustedNumber = Number.isNaN(parsedNumber) ? 0 : parsedNumber;
    return Math.max(adjustedNumber, 0);
  }

  setBadge(direct, indirect) {
    if (this.countCache.direct === direct
        && this.countCache.indirect === indirect) return;

    const count = {
      direct: this._normalizeNumber(direct),
      indirect: this._normalizeNumber(indirect),
    };

    ipcRenderer.sendToHost('message-counts', count);
    Object.assign(this.countCache, count);

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