treestyletab/modules/lib/confirmWithPopup.js

324 lines
9.3 KiB
JavaScript
Raw Permalink Normal View History

/**
* @fileOverview Popup Notification (Door Hanger) Based Confirmation Library for Firefox 31 or later
2012-10-13 14:31:06 -04:00
* @author YUKI "Piro" Hiroshi
2014-11-11 05:56:58 -05:00
* @version 8
* Basic usage:
*
* @example
2012-01-20 09:58:22 -05:00
* Usage:
* Components.utils.import('resource://my-modules/confirmWithPopup.js');
*
2012-01-20 09:58:22 -05:00
* confirmWithPopup({
* browser : gBrowser.selectedBrowser, // the related browser
* label : 'Ara you ready?', // the message
* value : 'treestyletab-undo-close-tree', // the internal key (optional)
* anchor : '....', // the ID of the anchor element (optional)
* image : 'chrome://....png', // the icon (optional)
* buttons : ['Yes', 'Yes forever', 'No forever], // button labels
* // Native options for PopupNotifications.show() :
* // persistence (integer)
* // timeout (integer)
* // persistWhileVisible (boolean)
* // dismissed (boolean)
* // eventCallback (function)
* // neverShow (boolean)
* // popupIconURL (string) : will be used instead of "image" option.
* });
*
* ES6 Promise style:
2012-01-20 09:58:22 -05:00
* confirmWithPopup(...)
* .then(function(aButtonIndex) {
2012-01-20 09:58:22 -05:00
* // the next callback receives the index of the clicked button.
* switch (aButtonIndex) {
* case 0: return YesAction();
* case 1: return YesForeverAction();
* case 2: return NoForeverAction();
* }
* })
* .catch(function(aError) {
2012-01-20 09:58:22 -05:00
* // dismissed or removed (not called if any button is chosen)
* ...
* });
*
* without Promise:
2012-01-20 09:58:22 -05:00
* confirmWithPopup({ ...,
* // Yes, Yes Forever, or No Forever
* callback : function(aButtonIndex) { ... },
* // dismissed or removed (not called if any button is chosen)
* onerror : function(aError) { ... }
* });
*
* @license
* The MIT License, Copyright (c) 2011-2014 YUKI "Piro" Hiroshi
2014-04-02 06:38:32 -04:00
* @url http://github.com/piroor/fxaddonlib-confirm-popup
*/
if (typeof window == 'undefined')
this.EXPORTED_SYMBOLS = ['confirmWithPopup'];
// var namespace;
if (typeof namespace == 'undefined') {
// If namespace.jsm is available, export symbols to the shared namespace.
// See: http://github.com/piroor/fxaddonlibs/blob/master/namespace.jsm
try {
let ns = {};
Components.utils.import('resource://treestyletab-modules/lib/namespace.jsm', ns);
namespace = ns.getNamespaceFor('piro.sakura.ne.jp');
}
catch(e) {
namespace = (typeof window != 'undefined' ? window : null ) || {};
}
}
var available = false;
try {
Components.utils.import('resource://gre/modules/PopupNotifications.jsm');
available = true;
}
catch(e) {
}
var confirmWithPopup;
2014-04-02 06:38:32 -04:00
(function(global) {
2014-11-11 05:56:58 -05:00
const currentRevision = 8;
var loadedRevision = 'confirmWithPopup' in namespace ?
namespace.confirmWithPopup.revision :
0 ;
if (loadedRevision && loadedRevision > currentRevision) {
confirmWithPopup = namespace.confirmWithPopup;
return;
}
if (!available)
2014-04-02 06:38:32 -04:00
return global.confirmWithPopup = undefined;
2012-01-20 09:58:22 -05:00
const Cc = Components.classes;
const Ci = Components.interfaces;
const DEFAULT_ANCHOR_ICON = 'default-notification-icon';
2012-01-20 09:58:22 -05:00
const NATIVE_OPTIONS = 'persistence,timeout,persistWhileVisible,dismissed,eventCallback,neverShow,popupIconURL'.split(',');
const OPTIONS = 'browser,tab,label,value,anchor,image,imageWidth,imageHeight,button,buttons,callback,onerror'.split(',');
var { Promise } = Components.utils.import('resource://gre/modules/Promise.jsm', {});
function setTimeout(aCallback, aDelay) {
2012-01-20 09:58:22 -05:00
Cc['@mozilla.org/timer;1']
.createInstance(Ci.nsITimer)
.init(aCallback, aDelay, Ci.nsITimer.TYPE_ONE_SHOT);
}
2012-01-18 12:56:55 -05:00
// We have to use a custom stylesheet to show the anchor element.
function addStyleSheet(aDocument, aOptions) {
var uri = 'data:text/css,'+encodeURIComponent(
2012-01-20 09:58:22 -05:00
(aOptions.image ?
'.popup-notification-icon[popupid="'+aOptions.id+'"] {'+
' list-style-image: url("'+aOptions.image+'");'+
2012-01-20 10:33:19 -05:00
(aOptions.imageWidth ? 'width: '+aOptions.imageWidth+'px;' : '' )+
(aOptions.imageHeight ? 'height: '+aOptions.imageHeight+'px;' : '' )+
2012-01-20 09:58:22 -05:00
'}' :
''
)+
'#notification-popup-box[anchorid="'+aOptions.anchor+'"] > #'+aOptions.anchor+' {'+
' display: -moz-box;'+
2014-04-02 06:38:32 -04:00
'}' +
(aOptions.label.indexOf('\n') > -1 ?
'popupnotification[id="'+aOptions.id+'-notification"] .popup-notification-description {' +
' white-space: pre-wrap;' +
'}' :
''
)
);
var styleSheets = aDocument.styleSheets;
for (var i = 0, maxi = styleSheets.length; i < maxi; i++) {
if (styleSheets[i].href == uri)
return styleSheets[i].ownerNode;
}
var style = aDocument.createProcessingInstruction('xml-stylesheet',
'type="text/css" href="'+uri+'"'
);
aDocument.insertBefore(style, aDocument.documentElement);
return style;
}
2012-01-20 09:58:22 -05:00
function normalizeOptions(aOptions) {
var options = collectNativeOptions(aOptions);
OPTIONS.forEach(function(aOption) {
options[aOption] = aOptions[aOption] ;
});
options.image = options.popupIconURL || options.image ;
// we should accept single button type popup
if (!options.buttons && options.button)
options.buttons = [options.button];
if (!options.browser && options.tab)
options.browser = options.tab.linkedBrowser;
if (!options.anchor)
options.anchor = DEFAULT_ANCHOR_ICON;
return options;
}
function collectNativeOptions(aOptions) {
var options = {};
NATIVE_OPTIONS.forEach(function(aOption) {
options[aOption] = aOptions.option && aOptions.option[aOption] || aOptions[aOption] ;
});
return options;
}
confirmWithPopup = function confirmWithPopup(aOptions)
{
2012-01-20 09:58:22 -05:00
var options = normalizeOptions(aOptions);
var nativeOptions = collectNativeOptions(options);
2012-01-18 13:23:06 -05:00
if (!options.buttons)
return Promise.reject(new Error('confirmWithPopup requires any button!'));
2014-04-02 06:38:32 -04:00
var b = options.browser;
if (!b && options.window)
b = options.window.gBrowser;
if (!b)
return Promise.reject(new Error('confirmWithPopup requires a <xul:browser/>!'));
2014-04-02 06:38:32 -04:00
if (b.localName == 'tabbrowser')
b = b.selectedBrowser;
var doc = b.ownerDocument;
var style;
2012-01-20 09:58:22 -05:00
var done = false;
2012-01-20 10:10:57 -05:00
var postProcess = function() {
2014-04-02 06:38:32 -04:00
if (doc && style && style.parentNode) {
2012-01-20 10:10:57 -05:00
doc.removeChild(style);
style = null;
}
2012-01-20 09:58:22 -05:00
};
return new Promise((function(aResolve, aReject) {
var showPopup = function() {
var accessKeys = [];
var numericAccessKey = 0;
2012-01-20 09:58:22 -05:00
var buttons = options.buttons.map(function(aLabel, aIndex) {
2012-02-07 13:23:10 -05:00
// see resource://gre/modules/CommonDialog.jsm
var accessKey;
2012-02-07 13:23:10 -05:00
var match;
if (match = aLabel.match(/^\s*(.*?)\s*\(\&([^&])\)(:)?$/)) {
aLabel = (match[1] + (match[3] || '')).replace(/\&\&/g, '&');
accessKey = match[2];
}
else if (match = aLabel.match(/^\s*(.*[^&])?\&(([^&]).*$)/)) {
2012-02-08 12:22:25 -05:00
aLabel = ((match[1] || '') + match[2]).replace(/\&\&/g, '&');
2012-02-07 13:23:10 -05:00
accessKey = match[3];
}
else {
let lastUniqueKey;
let sanitizedLabel = [];
for (let i = 0, maxi = aLabel.length; i < maxi; i++)
{
let possibleAccessKey = aLabel.charAt(i);
2012-02-07 13:23:10 -05:00
if (!lastUniqueKey &&
accessKeys.indexOf(possibleAccessKey) < 0) {
lastUniqueKey = possibleAccessKey;
}
sanitizedLabel.push(possibleAccessKey);
}
if (!accessKey)
accessKey = lastUniqueKey;
if (!accessKey || !/[0-9a-z]/i.test(accessKey))
accessKey = ++numericAccessKey;
2012-02-07 13:23:10 -05:00
aLabel = sanitizedLabel.join('').replace(/\&\&/g, '&');
}
accessKeys.push(accessKey);
return {
label : aLabel,
accessKey : accessKey,
callback : function() {
2012-01-20 09:58:22 -05:00
done = true;
2012-01-20 10:10:57 -05:00
try {
aResolve(aIndex);
2012-01-20 10:10:57 -05:00
}
finally {
postProcess();
}
}
};
});
var primaryAction = buttons[0];
var secondaryActions = buttons.length > 1 ? buttons.slice(1) : null ;
2012-01-20 09:58:22 -05:00
options.id = options.value || 'confirmWithPopup-'+encodeURIComponent(options.label);
2014-04-02 06:38:32 -04:00
options.label = options.label.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
2012-01-20 09:58:22 -05:00
style = addStyleSheet(doc, options);
try {
doc.defaultView.PopupNotifications.show(
2014-04-02 06:38:32 -04:00
b,
2012-01-20 09:58:22 -05:00
options.id,
options.label,
options.anchor,
primaryAction,
secondaryActions,
2014-04-02 06:38:32 -04:00
Object.create(nativeOptions, {
2014-11-11 05:56:58 -05:00
eventCallback : {
2014-04-02 06:38:32 -04:00
writable : true,
configurable : true,
enumerable : true,
2014-11-11 05:56:58 -05:00
value : function(aEventType) {
try {
if (!done && (aEventType == 'removed' || aEventType == 'dismissed'))
aReject(aEventType);
if (options.eventCallback)
options.eventCallback.call(aOptions.options || aOptions, aEventType);
}
finally {
if (aEventType == 'removed')
postProcess();
}
}
2014-04-02 06:38:32 -04:00
}
})
);
}
catch(e) {
aReject(e);
}
};
2012-01-20 09:58:22 -05:00
if (options.image && (!options.imageWidth || !options.imageHeight)) {
let loader = new doc.defaultView.Image();
loader.src = options.image;
loader.onload = function() {
options.imageWidth = loader.width;
options.imageHeight = loader.height;
showPopup();
};
loader.onerror = function() {
showPopup();
};
}
2014-11-11 05:56:58 -05:00
else {
setTimeout(showPopup, 0);
}
}).bind(this));
};
2014-04-02 06:38:32 -04:00
confirmWithPopup.version = currentRevision;
global.confirmWithPopup = namespace.confirmWithPopup = confirmWithPopup;
})(this);
2014-04-02 06:38:32 -04:00
if (typeof exports == 'object')
exports.confirmWithPopup = confirmWithPopup;