summaryrefslogtreecommitdiffstats
path: root/mobile/android/modules/Snackbars.jsm
blob: 066a28c567894d420a9c1eadac7a981e4f2a5a7f (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

this.EXPORTED_SYMBOLS = ["Snackbars"];

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, "Messaging", "resource://gre/modules/Messaging.jsm");

const LENGTH_INDEFINITE = -2;
const LENGTH_LONG = 0;
const LENGTH_SHORT = -1;

var Snackbars = {
  LENGTH_INDEFINITE: LENGTH_INDEFINITE,
  LENGTH_LONG: LENGTH_LONG,
  LENGTH_SHORT: LENGTH_SHORT,

  show: function(aMessage, aDuration, aOptions) {

    // Takes care of the deprecated toast calls
    if (typeof aDuration === "string") {
      [aDuration, aOptions] = migrateToastIfNeeded(aDuration, aOptions);
    }

    let msg = {
      type: 'Snackbar:Show',
      message: aMessage,
      duration: aDuration,
    };

    if (aOptions && aOptions.backgroundColor) {
      msg.backgroundColor = aOptions.backgroundColor;
    }

    if (aOptions && aOptions.action) {
      msg.action = {};

      if (aOptions.action.label) {
        msg.action.label = aOptions.action.label;
      }

      Messaging.sendRequestForResult(msg).then(result => aOptions.action.callback());
    } else {
      Messaging.sendRequest(msg);
    }
  }
};

function migrateToastIfNeeded(aDuration, aOptions) {
  let duration;
  if (aDuration === "long") {
    duration = LENGTH_LONG;
  }
  else {
    duration = LENGTH_SHORT;
  }

  let options = {};
  if (aOptions && aOptions.button) {
    options.action = {
      label: aOptions.button.label,
      callback: () => aOptions.button.callback(),
    };
  }
  return [duration, options];
}