Skip to content

Instantly share code, notes, and snippets.

@bellbind
Forked from anonymous/x
Created Jul 10, 2009
Embed
What would you like to do?
[Ubiquity] eval JS snippet then show result object
/* eval for Ubiquity 0.5 */
CmdUtils.CreateCommand({
names: ["eval"],
icon: "chrome://ubiquity/skin/icons/favicon.ico",
homepage: "http://d.hatena.ne.jp/bellbind/",
author: {name: "bellbind", email: "bellbind@gmail.com"},
license: "GPL",
description: "evaluate script",
help: "evaluate script",
arguments: [{role:"input", nountype: noun_arb_text}],
preview: function (pblock, args) {
var code = args.input.text;
var pnode = jQuery(pblock);
var pre = jQuery("<pre></pre>");
pre.css({overflow: "scroll"});
pre.width(450);
pre.height(450);
pre.text(this._eval(code));
pnode.empty().append(pre);
},
execute: function (args) {
var code = args.input.text;
CmdUtils.getWindow().alert(this._eval(code));
},
_eval: function (code) {
try {
return this._pp(eval(code));
} catch (ex) {
return this._pp(ex);
}
},
_pp: function (obj) {
return this._pplevel(obj, "", false, false, 2);
},
_pplevel: function (obj, indent, cont, flat, level) {
var itop = cont ? "" : indent;
switch (obj) {
case undefined: return itop + "undefined";
case null: return itop + "null";
case true: return itop + "true";
case false: return itop + "false";
}
if (level === 0) return itop + "...";
switch (typeof obj) {
case "number": return itop + obj.toString();
case "string": return itop +
(level < 2 ? "'...'" : this._ppstr(obj));
case "function": return itop +
(level < 2 ? "function ..." : obj.toSource().split("\n").join(indent + "\n"));
}
try {
var nlevel = level - 1;
var nflat = nlevel < 2;
var nindent = this._nest(indent);
var mindent = flat ? "": nindent;
var mcont = flat ? true : false;
var mjoin = flat ? ", " : ",\n";
var sjoin = flat ? "" : "\n";
switch (obj.constructor) {
case Array: return [
itop + "[",
[this._pplevel(item, nindent, mcont, nflat, nlevel)
for each (item in obj)].join(mjoin),
indent + "]"].join(sjoin);
}
var keys = [k for (k in obj)].sort();
var name = "";
try {
name = "/* " + obj.constructor.name + " */ ";
} catch (ex) {
;
}
return [
itop + "{" + name,
[mindent + this._ppstr(k) + ": " +
this._pplevel(obj[k], nindent, true, nflat, nlevel)
for each (k in keys)].join(mjoin),
indent + "}"].join(sjoin);
} catch (ex) {
return itop + obj.toSource();
}
},
_ppstr: function (obj) {
return "'" + obj.split("'").join("\\'") +"'";
},
_nest: function (indent) {return indent + " ";}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment