1
0
mirror of https://github.com/gryf/pentadactyl-pm.git synced 2026-02-12 12:45:44 +01:00

Promisify some callbackish functions, and remove spaces around = in default arguments, per Python conventions.

This commit is contained in:
Kris Maglione
2014-02-15 20:35:27 -08:00
parent fd20535999
commit bb7486da6c
22 changed files with 250 additions and 115 deletions

View File

@@ -257,8 +257,9 @@ var Bookmarks = Module("bookmarks", {
let engine = hasOwnProperty(this.searchEngines, engineName) && this.searchEngines[engineName];
if (engine && engine.supportsResponseType(responseType))
var queryURI = engine.getSubmission(query, responseType).uri.spec;
if (!queryURI)
return (callback || util.identity)([]);
return promises.fail();
function parse(req) JSON.parse(req.responseText)[1].filter(isString);
return this.makeSuggestions(queryURI, parse, callback);
@@ -271,25 +272,25 @@ var Bookmarks = Module("bookmarks", {
* @param {string} url The URL to fetch.
* @param {function(XMLHttpRequest):[string]} parser The function which
* parses the response.
* @returns {Promise<Array>}
*/
makeSuggestions: function makeSuggestions(url, parser, callback) {
function process(req) {
makeSuggestions: function makeSuggestions(url, parser) {
let deferred = Promise.defer();
let req = util.fetchUrl(url);
req.then(function process(req) {
let results = [];
try {
results = parser(req);
}
catch (e) {
util.reportError(e);
return deferred.reject(e);
}
if (callback)
return callback(results);
return results;
}
deferred.resolve(results);
}, Cu.reportError);
let req = util.httpGet(url, callback && process);
if (callback)
return req;
return process(req);
promises.oncancel(deferred, r => promises.cancel(req, reason));
return deferred.promise;
},
suggestionProviders: {},
@@ -536,7 +537,7 @@ var Bookmarks = Module("bookmarks", {
"Delete a bookmark",
function (args) {
if (args.bang)
commandline.input(_("bookmark.prompt.deleteAll") + " ",
commandline.input(_("bookmark.prompt.deleteAll") + " ").then(
function (resp) {
if (resp && resp.match(/^y(es)?$/i)) {
bookmarks.remove(Object.keys(bookmarkcache.bookmarks));
@@ -628,7 +629,7 @@ var Bookmarks = Module("bookmarks", {
},
completion: function initCompletion() {
completion.bookmark = function bookmark(context, tags, extra = {}) {
completion.bookmark = function bookmark(context, tags, extra={}) {
context.title = ["Bookmark", "Title"];
context.format = bookmarks.format;
iter(extra).forEach(function ([k, v]) {
@@ -721,11 +722,12 @@ var Bookmarks = Module("bookmarks", {
ctxt.hasItems = ctxt.completions.length;
ctxt.incomplete = true;
ctxt.cache.request = bookmarks.getSuggestions(name, ctxt.filter, function (compl) {
ctxt.cache.request = bookmarks.getSuggestions(name, ctxt.filter);
ctxt.cache.request.then(function (compl) {
ctxt.incomplete = false;
ctxt.completions = array.uniq(ctxt.completions.filter(c => compl.indexOf(c) >= 0)
.concat(compl), true);
});
}, Cu.reportError);
});
};

View File

@@ -1,6 +1,6 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
// Copyright (c) 2008-2014 Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
@@ -845,7 +845,6 @@ var CommandLine = Module("commandline", {
* pop at any time to close the prompt.
*
* @param {string} prompt The input prompt to use.
* @param {function(string)} callback
* @param {Object} extra
* @... {function} onChange - A function to be called with the current
* input every time it changes.
@@ -856,15 +855,16 @@ var CommandLine = Module("commandline", {
* @... {string} default - The initial value that will be returned
* if the user presses <CR> straightaway. @default ""
*/
input: function _input(prompt, callback, extra = {}) {
CommandPromptMode(prompt, update({ onSubmit: callback }, extra)).open();
},
input: promises.withCallbacks(function _input([callback, reject], prompt, extra={}, thing={}) {
if (callable(extra))
// Deprecated.
[callback, extra] = [extra, thing];
CommandPromptMode(prompt, update({ onSubmit: callback, onCancel: reject }, extra)).open();
}),
readHeredoc: function readHeredoc(end) {
let args;
commandline.inputMultiline(end, function (res) { args = res; });
util.waitFor(() => args !== undefined);
return args;
return util.waitFor(commandline.inputMultiline(end));
},
/**
@@ -873,10 +873,10 @@ var CommandLine = Module("commandline", {
* callback with that string as a parameter.
*
* @param {string} end
* @param {function(string)} callback
* @returns {Promise<string>}
*/
// FIXME: Buggy, especially when pasting.
inputMultiline: function inputMultiline(end, callback) {
inputMultiline: promises.withCallbacks(function inputMultiline([callback], end) {
let cmd = this.command;
let self = {
end: "\n" + end + "\n",
@@ -902,7 +902,7 @@ var CommandLine = Module("commandline", {
this._autosizeMultilineInputWidget();
this.timeout(function () { dactyl.focus(this.widgets.multilineInput); }, 10);
},
}),
get commandMode() this.commandSession && isinstance(modes.main, modes.COMMAND_LINE),
@@ -1384,7 +1384,7 @@ var CommandLine = Module("commandline", {
* @default {@link #selected}
* @returns {object}
*/
getItem: function getItem(tuple = this.selected)
getItem: function getItem(tuple=this.selected)
tuple && tuple[0] && tuple[0].items[tuple[1]],
/**
@@ -1499,7 +1499,7 @@ var CommandLine = Module("commandline", {
* @default false
* @private
*/
select: function select(idx, count = 1, fromTab = false) {
select: function select(idx, count=1, fromTab=false) {
switch (idx) {
case this.UP:
case this.DOWN:

View File

@@ -538,7 +538,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
* @param {boolean} silent Whether the command should be echoed on the
* command line.
*/
execute: function execute(str, modifiers = {}, silent = false) {
execute: function execute(str, modifiers={}, silent=false) {
// skip comments and blank lines
if (/^\s*("|$)/.test(str))
return;
@@ -890,13 +890,13 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
* tabs.
* @returns {boolean}
*/
open: function open(urls, params = {}, force = false) {
open: function open(urls, params={}, force=false) {
if (typeof urls == "string")
urls = dactyl.parseURLs(urls);
if (urls.length > prefs.get("browser.tabs.maxOpenBeforeWarn", 20) && !force)
return commandline.input(_("dactyl.prompt.openMany", urls.length) + " ",
function (resp) {
return commandline.input(_("dactyl.prompt.openMany", urls.length) + " ")
.then(function (resp) {
if (resp && resp.match(/^y(es)?$/i))
dactyl.open(urls, params, true);
});
@@ -1184,7 +1184,7 @@ var Dactyl = Module("dactyl", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
return [];
}
},
wrapCallback: function wrapCallback(callback, self = this) {
wrapCallback: function wrapCallback(callback, self=this) {
let save = ["forceOpen"];
let saved = save.map(p => dactyl[p]);
return function wrappedCallback() {

View File

@@ -386,8 +386,8 @@ var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
let keepFocus = modes.stack.some(m => isinstance(m.main, modes.COMMAND_LINE));
if (!forceEditing && textBox && textBox.type == "password") {
commandline.input(_("editor.prompt.editPassword") + " ",
function (resp) {
commandline.input(_("editor.prompt.editPassword") + " ")
.then(function (resp) {
if (resp && resp.match(/^y(es)?$/i))
editor.editFieldExternally(true);
});
@@ -424,7 +424,7 @@ var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
column = 1 + pre.replace(/[^]*\n/, "").length;
let origGroup = DOM(textBox).highlight.toString();
let cleanup = util.yieldable(function cleanup(error) {
let cleanup = promises.task(function cleanup(error) {
if (timer)
timer.cancel();
@@ -443,9 +443,11 @@ var Editor = Module("editor", XPCOM(Ci.nsIEditActionListener, ModuleBase), {
DOM(textBox).highlight.remove("EditorEditing");
if (!keepFocus)
dactyl.focus(textBox);
for (let group in values(blink.concat(blink, ""))) {
highlight.highlightNode(textBox, origGroup + " " + group);
yield 100;
yield promises.sleep(100);
}
}
});

View File

@@ -212,7 +212,7 @@ var Events = Module("events", {
/**
* Wraps an event listener to ensure that errors are reported.
*/
wrapListener: function wrapListener(method, self = this) {
wrapListener: function wrapListener(method, self=this) {
method.wrapper = wrappedListener;
wrappedListener.wrapped = method;
function wrappedListener(event) {

View File

@@ -1,6 +1,6 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
// Copyright (c) 2008-2014 Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
@@ -12,7 +12,7 @@
var HintSession = Class("HintSession", CommandMode, {
get extendedMode() modes.HINTS,
init: function init(mode, opts = {}) {
init: function init(mode, opts={}) {
init.supercall(this);
if (!opts.window)
@@ -1054,11 +1054,11 @@ var Hints = Module("hints", {
return null;
}, //}}}
open: function open(mode, opts = {}) {
open: function open(mode, opts={}) {
this._extendedhintCount = opts.count;
mappings.pushCommand();
commandline.input(["Normal", mode], null, {
commandline.input(["Normal", mode], {
autocomplete: false,
completer: function (context) {
context.compare = () => 0;

View File

@@ -1,6 +1,6 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
// Copyright (c) 2008-2014 Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
@@ -13,7 +13,7 @@ var History = Module("history", {
get service() services.history,
get: function get(filter, maxItems, sort = this.SORT_DEFAULT) {
get: function get(filter, maxItems, sort=this.SORT_DEFAULT) {
if (isString(filter))
filter = { searchTerms: filter };

View File

@@ -187,7 +187,7 @@ var MapHive = Class("MapHive", Contexts.Hive, {
* @param {Object} extra An optional extra configuration hash.
* @optional
*/
add: function (modes, keys, description, action, extra = {}) {
add: function (modes, keys, description, action, extra={}) {
modes = Array.concat(modes);
if (!modes.every(util.identity))
throw TypeError(/*L*/"Invalid modes: " + modes);
@@ -817,7 +817,7 @@ var Mappings = Module("mappings", {
});
},
completion: function initCompletion(dactyl, modules, window) {
completion.userMapping = function userMapping(context, modes_ = [modes.NORMAL], hive = mappings.user) {
completion.userMapping = function userMapping(context, modes_=[modes.NORMAL], hive=mappings.user) {
context.keys = { text: function (m) m.names[0],
description: function (m) m.description + ": " + m.action };
context.completions = hive.iterate(modes_);

View File

@@ -1,6 +1,6 @@
// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2013 Kris Maglione <maglione.k@gmail.com>
// Copyright (c) 2008-2014 Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
@@ -34,7 +34,7 @@ var Marks = Module("marks", {
get localURI() buffer.focusedFrame.document.documentURI.replace(/#.*/, ""),
Mark: function Mark(params = {}) {
Mark: function Mark(params={}) {
let win = buffer.focusedFrame;
let doc = win.document;

View File

@@ -505,7 +505,7 @@ var Modes = Module("modes", {
return StackElement;
})(),
cacheId: 0,
boundProperty: function BoundProperty(desc = {}) {
boundProperty: function BoundProperty(desc={}) {
let id = this.cacheId++;
let value;

View File

@@ -406,7 +406,7 @@ var Tabs = Module("tabs", {
* @param {number} count How many tabs to remove.
* @param {boolean} focusLeftTab Focus the tab to the left of the removed tab.
*/
remove: function remove(tab, count = 1, focusLeftTab = false) {
remove: function remove(tab, count=1, focusLeftTab=false) {
let res = this.count > count;
let tabs = this.visibleTabs;