1 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
8 Components.utils.import("resource://dactyl/bootstrap.jsm");
9 defineModule("template", {
10 exports: ["Binding", "Template", "template"],
14 default xml namespace = XHTML;
16 var Binding = Class("Binding", {
17 init: function (node, nodes) {
20 node.dactylBinding = this;
22 Object.defineProperties(node, this.constructor.properties);
24 for (let [event, handler] in values(this.constructor.events))
25 node.addEventListener(event, util.wrapCallback(handler, true), false);
28 set collapsed(collapsed) {
30 this.setAttribute("collapsed", "true");
32 this.removeAttribute("collapsed");
34 get collapsed() !!this.getAttribute("collapsed"),
36 __noSuchMethod__: Class.Property({
39 value: function __noSuchMethod__(meth, args) {
40 return this.node[meth].apply(this.node, args);
45 let bindingProto = Object.getPrototypeOf(Binding.prototype);
46 for (let obj = this.prototype; obj !== bindingProto; obj = Object.getPrototypeOf(obj))
50 bind: function bind(func) function bound() {
52 return func.apply(this.dactylBinding, arguments);
60 events: Class.Memoize(function () {
62 for (let obj in this.bindings)
63 if (Object.getOwnPropertyDescriptor(obj, "events"))
64 for (let [event, handler] in Iterator(obj.events))
65 res.push([event, this.bind(handler)]);
69 properties: Class.Memoize(function () {
71 for (let obj in this.bindings)
72 for (let prop in properties(obj)) {
73 let desc = Object.getOwnPropertyDescriptor(obj, prop);
74 if (desc.enumerable) {
75 for (let k in values(["get", "set", "value"]))
76 if (typeof desc[k] === "function")
77 desc[k] = this.bind(desc[k]);
85 var Template = Module("Template", {
86 add: function add(a, b) a + b,
87 join: function join(c) function (a, b) a + c + b,
89 map: function map(iter, func, sep, interruptable) {
90 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
91 if (iter.length) // FIXME: Kludge?
92 iter = array.iterValues(iter);
95 for each (let i in Iterator(iter)) {
101 if (interruptable && n % interruptable == 0)
102 util.threadYield(true, true);
109 Button: Class("Button", Binding, {
110 init: function init(node, params) {
111 init.supercall(this, node);
113 this.target = params.commandTarget;
116 get command() this.getAttribute("command") || this.getAttribute("key"),
119 "click": function onClick(event) {
120 event.preventDefault();
121 if (this.commandAllowed) {
122 if (Set.has(this.target.commands || {}, this.command))
123 this.target.commands[this.command].call(this.target);
125 this.target.command(this.command);
130 get commandAllowed() {
131 if (Set.has(this.target.allowedCommands || {}, this.command))
132 return this.target.allowedCommands[this.command];
133 if ("commandAllowed" in this.target)
134 return this.target.commandAllowed(this.command);
138 update: function update() {
139 let collapsed = this.collapsed;
140 this.collapsed = !this.commandAllowed;
142 if (collapsed == this.commandAllowed) {
143 let event = this.node.ownerDocument.createEvent("Events");
144 event.initEvent("dactyl-commandupdate", true, false);
145 this.node.ownerDocument.dispatchEvent(event);
150 Events: Class("Events", Binding, {
151 init: function init(node, params) {
152 init.supercall(this, node);
154 let obj = params.eventTarget;
155 let events = obj[this.getAttribute("events") || "events"];
156 if (Set.has(events, "input"))
157 events["dactyl-input"] = events["input"];
159 for (let [event, handler] in Iterator(events))
160 node.addEventListener(event, util.wrapCallback(obj.closure(handler), true), false);
165 bookmarkDescription: function (item, text)
168 !(item.extra && item.extra.length) ? "" :
169 <span highlight="URLExtra">
171 template.map(item.extra, function (e)
172 <>{e[0]}: <span highlight={e[2]}>{e[1]}</span></>,
176 <a xmlns:dactyl={NS} identifier={item.id == null ? "" : item.id} dactyl:command={item.command || ""}
177 href={item.item.url} highlight="URL">{text || ""}</a>
180 filter: function (str) <span highlight="Filter">{str}</span>,
182 completionRow: function completionRow(item, highlightGroup) {
183 if (typeof icon == "function")
186 if (highlightGroup) {
187 var text = item[0] || "";
188 var desc = item[1] || "";
191 var text = this.processor[0].call(this, item, item.result);
192 var desc = this.processor[1].call(this, item, item.description);
195 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
197 return <div highlight={highlightGroup || "CompItem"} style="white-space: nowrap">
198 <!-- The non-breaking spaces prevent empty elements
199 - from pushing the baseline down and enlarging
202 <li highlight={"CompResult " + item.highlight}>{text} </li>
203 <li highlight="CompDesc">{desc} </li>
208 helpLink: function (token, text, type) {
209 if (!help.initialized)
210 util.dactyl.initHelp();
212 let topic = token; // FIXME: Evil duplication!
213 if (/^\[.*\]$/.test(topic))
214 topic = topic.slice(1, -1);
215 else if (/^n_/.test(topic))
216 topic = topic.slice(2);
218 if (help.initialized && !Set.has(help.tags, topic))
219 return <span highlight={type || ""}>{text || token}</span>;
221 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
222 type = type || (/^'.*'$/.test(token) ? "HelpOpt" :
223 /^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" :
224 /^:\w/.test(token) ? "HelpEx" : "HelpKey");
226 return <a highlight={"InlineHelpLink " + type} tag={topic} href={"dactyl://help-tag/" + topic} dactyl:command="dactyl.help" xmlns:dactyl={NS}>{text || topic}</a>;
228 HelpLink: function (token) {
229 if (!help.initialized)
230 util.dactyl.initHelp();
232 let topic = token; // FIXME: Evil duplication!
233 if (/^\[.*\]$/.test(topic))
234 topic = topic.slice(1, -1);
235 else if (/^n_/.test(topic))
236 topic = topic.slice(2);
238 if (help.initialized && !Set.has(help.tags, topic))
241 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
242 let tag = (/^'.*'$/.test(token) ? "o" :
243 /^\[.*\]$|^E\d{3}$/.test(token) ? "t" :
244 /^:\w/.test(token) ? "ex" : "k");
246 topic = topic.replace(/^'(.*)'$/, "$1");
247 return <{tag} xmlns={NS}>{topic}</{tag}>;
249 linkifyHelp: function linkifyHelp(str, help) {
250 let re = util.regexp(<![CDATA[
252 (?P<tag> '[\w-]+' | :(?:[\w-]+!?|!) | (?:._)?<[\w-]+>\w* | \b[a-zA-Z]_(?:\w+|.) | \[[\w-]+\] | E\d{3} )
255 return this.highlightSubstrings(str, (function () {
256 for (let res in re.iterate(str))
257 yield [res.index + res.pre.length, res.tag.length];
258 })(), template[help ? "HelpLink" : "helpLink"]);
261 // Fixes some strange stack rewinds on NS_ERROR_OUT_OF_MEMORY
262 // exceptions that we can't catch.
263 stringify: function stringify(arg) {
268 this._sandbox.arg = arg;
269 return Cu.evalInSandbox("String(arg)", this._sandbox);
272 this._sandbox.arg = null;
276 _sandbox: Class.Memoize(function () Cu.Sandbox(global, { wantXrays: false })),
278 // if "processStrings" is true, any passed strings will be surrounded by " and
279 // any line breaks are displayed as \n
280 highlight: function highlight(arg, processStrings, clip, bw) {
281 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
282 // some objects like window.JSON or getBrowsers()._browsers need the try/catch
284 let str = this.stringify(arg);
286 str = util.clip(str, clip);
287 switch (arg == null ? "undefined" : typeof arg) {
289 return <span highlight="Number">{str}</span>;
293 return <span highlight="String">{str}</span>;
295 return <span highlight="Boolean">{str}</span>;
297 if (arg instanceof Ci.nsIDOMElement) // wtf?
298 return util.objectToString(arg, !bw);
300 str = str.replace("/* use strict */ \n", "/* use strict */ ");
302 return <span highlight="Function">{str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>;
304 arg = String(arg).replace("/* use strict */ \n", "/* use strict */ ");
307 return <span highlight="Null">{arg}</span>;
309 if (arg instanceof Ci.nsIDOMElement)
310 return util.objectToString(arg, !bw);
312 // for java packages value.toString() would crash so badly
313 // that we cannot even try/catch it
314 if (/^\[JavaPackage.*\]$/.test(arg))
315 return <>[JavaPackage]</>;
316 if (processStrings && false)
317 str = template.highlightFilter(str, "\n", function () <span highlight="NonText">^J</span>);
318 return <span highlight="Object">{str}</span>;
322 return <![CDATA[<unknown type>]]>;
326 return <![CDATA[<unknown>]]>;
330 highlightFilter: function highlightFilter(str, filter, highlight, isURI) {
332 str = util.losslessDecodeURI(str);
334 return this.highlightSubstrings(str, (function () {
335 if (filter.length == 0)
337 let lcstr = String.toLowerCase(str);
338 let lcfilter = filter.toLowerCase();
340 while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
341 yield [start, filter.length];
342 start += filter.length;
344 })(), highlight || template.filter);
347 highlightRegexp: function highlightRegexp(str, re, highlight) {
348 return this.highlightSubstrings(str, (function () {
349 for (let res in util.regexp.iterate(re, str))
350 yield [res.index, res[0].length, res.wholeMatch ? [res] : res];
351 })(), highlight || template.filter);
354 highlightSubstrings: function highlightSubstrings(str, iter, highlight) {
355 XML.ignoreWhitespace = XML.prettyPrinting = false;
356 if (typeof str == "xml")
361 str = String(str).replace(" ", "\u00a0");
365 for (let [i, length, args] in iter) {
366 if (i == _i || i < _i)
370 XML.ignoreWhitespace = false;
371 s += <>{str.substring(start, i)}</>;
372 s += highlight.apply(this, Array.concat(args || str.substr(i, length)));
375 return s + <>{str.substr(start)}</>;
378 highlightURL: function highlightURL(str, force) {
379 if (force || /^[a-zA-Z]+:\/\//.test(str))
380 return <a highlight="URL" href={str}>{util.losslessDecodeURI(str)}</a>;
385 icon: function (item, text) <>
386 <span highlight="CompIcon">{item.icon ? <img src={item.icon}/> : <></>}</span><span class="td-strut"/>{text}
389 jumps: function jumps(index, elems) {
390 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
393 <tr style="text-align: left;" highlight="Title">
394 <th colspan="2">{_("title.Jump")}</th>
395 <th>{_("title.HPos")}</th>
396 <th>{_("title.VPos")}</th>
397 <th>{_("title.Title")}</th>
398 <th>{_("title.URI")}</th>
401 this.map(Iterator(elems), function ([idx, val])
403 <td class="indicator">{idx == index ? ">" : ""}</td>
404 <td>{Math.abs(idx - index)}</td>
405 <td>{val.offset ? val.offset.x : ""}</td>
406 <td>{val.offset ? val.offset.y : ""}</td>
407 <td style="width: 250px; max-width: 500px; overflow: hidden;">{val.title}</td>
408 <td><a href={val.URI.spec} highlight="URL jump-list">{util.losslessDecodeURI(val.URI.spec)}</a></td>
415 options: function options(title, opts, verbose) {
416 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
419 <tr highlight="Title" align="left">
420 <th>--- {title} ---</th>
423 this.map(opts, function (opt)
426 <div highlight="Message"
427 ><span style={opt.isDefault ? "" : "font-weight: bold"}>{opt.pre}{opt.name}</span><span>{opt.value}</span>{
428 opt.isDefault || opt.default == null ? "" : <span class="extra-info"> (default: {opt.default})</span>
430 verbose && opt.setFrom ? <div highlight="Message"> Last set from {template.sourceLink(opt.setFrom)}</div> : <></>
439 sourceLink: function (frame) {
440 let url = util.fixURI(frame.filename || "unknown");
441 let path = util.urlPath(url);
443 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
444 return <a xmlns:dactyl={NS} dactyl:command="buffer.viewSource"
445 href={url} path={path} line={frame.lineNumber}
447 path + ":" + frame.lineNumber
451 table: function table(title, data, indent) {
452 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
455 <tr highlight="Title" align="left">
456 <th colspan="2">{title}</th>
459 this.map(data, function (datum)
461 <td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td>
467 if (table.tr.length() > 1)
471 tabular: function tabular(headings, style, iter) {
472 // TODO: This might be mind-bogglingly slow. We'll see.
473 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
476 <tr highlight="Title" align="left">
478 this.map(headings, function (h)
483 this.map(iter, function (row)
486 template.map(Iterator(row), function ([i, d])
487 <td style={style[i] || ""}>{d}</td>)
495 usage: function usage(iter, format) {
496 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
497 format = format || {};
498 let desc = format.description || function (item) template.linkifyHelp(item.description);
499 let help = format.help || function (item) item.name;
500 function sourceLink(frame) {
501 let source = template.sourceLink(frame);
502 source.@NS::hint = source.text();
508 <thead highlight="UsageHead">
509 <tr highlight="Title" align="left">
511 this.map(format.headings, function (h) <th>{h}</th>)
519 this.map(format.columns, function (c) <col style={c}/>)
523 <tbody highlight="UsageBody">{
524 this.map(iter, function (item)
525 <tr highlight="UsageItem">
526 <td style="padding-right: 2em;">
527 <span highlight="Usage Link">{
528 let (name = item.name || item.names[0], frame = item.definedAt)
530 template.helpLink(help(item), name, "Title") +
531 <span highlight="LinkInfo" xmlns:dactyl={NS}>{_("io.definedAt")} {sourceLink(frame)}</span>
534 { item.columns ? template.map(item.columns, function (c) <td>{c}</td>) : "" }
535 <td>{desc(item)}</td>
545 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: