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.
7 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("template", {
9 exports: ["Binding", "Template", "template"],
11 use: ["messages", "services"]
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, handler, 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"];
157 for (let [event, handler] in Iterator(events))
158 node.addEventListener(event, obj.closure(handler), false);
163 bookmarkDescription: function (item, text)
166 !(item.extra && item.extra.length) ? "" :
167 <span highlight="URLExtra">
169 template.map(item.extra, function (e)
170 <>{e[0]}: <span highlight={e[2]}>{e[1]}</span></>,
174 <a xmlns:dactyl={NS} identifier={item.id || ""} dactyl:command={item.command || ""}
175 href={item.item.url} highlight="URL">{text || ""}</a>
178 filter: function (str) <span highlight="Filter">{str}</span>,
180 completionRow: function completionRow(item, highlightGroup) {
181 if (typeof icon == "function")
184 if (highlightGroup) {
185 var text = item[0] || "";
186 var desc = item[1] || "";
189 var text = this.processor[0].call(this, item, item.result);
190 var desc = this.processor[1].call(this, item, item.description);
193 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
195 return <div highlight={highlightGroup || "CompItem"} style="white-space: nowrap">
196 <!-- The non-breaking spaces prevent empty elements
197 - from pushing the baseline down and enlarging
200 <li highlight="CompResult">{text} </li>
201 <li highlight="CompDesc">{desc} </li>
206 helpLink: function (token, text, type) {
207 if (!services["dactyl:"].initialized)
208 util.dactyl.initHelp();
210 let topic = token; // FIXME: Evil duplication!
211 if (/^\[.*\]$/.test(topic))
212 topic = topic.slice(1, -1);
213 else if (/^n_/.test(topic))
214 topic = topic.slice(2);
216 if (services["dactyl:"].initialized && !set.has(services["dactyl:"].HELP_TAGS, topic))
217 return <span highlight={type || ""}>{text || token}</span>;
219 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
220 type = type || (/^'.*'$/.test(token) ? "HelpOpt" :
221 /^\[.*\]$|^E\d{3}$/.test(token) ? "HelpTopic" :
222 /^:\w/.test(token) ? "HelpEx" : "HelpKey");
224 return <a highlight={"InlineHelpLink " + type} tag={topic} href={"dactyl://help-tag/" + topic} dactyl:command="dactyl.help" xmlns:dactyl={NS}>{text || topic}</a>;
226 HelpLink: function (token) {
227 if (!services["dactyl:"].initialized)
228 util.dactyl.initHelp();
230 let topic = token; // FIXME: Evil duplication!
231 if (/^\[.*\]$/.test(topic))
232 topic = topic.slice(1, -1);
233 else if (/^n_/.test(topic))
234 topic = topic.slice(2);
236 if (services["dactyl:"].initialized && !set.has(services["dactyl:"].HELP_TAGS, topic))
239 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
240 let tag = (/^'.*'$/.test(token) ? "o" :
241 /^\[.*\]$|^E\d{3}$/.test(token) ? "t" :
242 /^:\w/.test(token) ? "ex" : "k");
244 topic = topic.replace(/^'(.*)'$/, "$1");
245 return <{tag} xmlns={NS}>{topic}</{tag}>;
247 linkifyHelp: function linkifyHelp(str, help) {
248 let re = util.regexp(<![CDATA[
250 (?P<tag> '[\w-]+' | :(?:[\w-]+!?|!) | (?:._)?<[\w-]+>\w* | [a-zA-Z]_\w+ | \[[\w-]+\] | E\d{3} )
253 return this.highlightSubstrings(str, (function () {
254 for (let res in re.iterate(str))
255 yield [res.index + res.pre.length, res.tag.length];
256 })(), template[help ? "HelpLink" : "helpLink"]);
259 // if "processStrings" is true, any passed strings will be surrounded by " and
260 // any line breaks are displayed as \n
261 highlight: function highlight(arg, processStrings, clip) {
262 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
263 // some objects like window.JSON or getBrowsers()._browsers need the try/catch
265 let str = clip ? util.clip(String(arg), clip) : String(arg);
266 switch (arg == null ? "undefined" : typeof arg) {
268 return <span highlight="Number">{str}</span>;
272 return <span highlight="String">{str}</span>;
274 return <span highlight="Boolean">{str}</span>;
276 // Vim generally doesn't like /foo*/, because */ looks like a comment terminator.
277 // Using /foo*(:?)/ instead.
279 return <span highlight="Function">{str.replace(/\{(.|\n)*(?:)/g, "{ ... }")}</span>;
283 return <span highlight="Null">{arg}</span>;
285 if (arg instanceof Ci.nsIDOMElement)
286 return util.objectToString(arg, false);
287 // for java packages value.toString() would crash so badly
288 // that we cannot even try/catch it
289 if (/^\[JavaPackage.*\]$/.test(arg))
290 return <>[JavaPackage]</>;
291 if (processStrings && false)
292 str = template.highlightFilter(str, "\n", function () <span highlight="NonText">^J</span>);
293 return <span highlight="Object">{str}</span>;
297 return <![CDATA[<unknown type>]]>;
301 return <![CDATA[<unknown>]]>;
305 highlightFilter: function highlightFilter(str, filter, highlight) {
306 return this.highlightSubstrings(str, (function () {
307 if (filter.length == 0)
309 let lcstr = String.toLowerCase(str);
310 let lcfilter = filter.toLowerCase();
312 while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
313 yield [start, filter.length];
314 start += filter.length;
316 })(), highlight || template.filter);
319 highlightRegexp: function highlightRegexp(str, re, highlight) {
320 return this.highlightSubstrings(str, (function () {
321 for (let res in util.regexp.iterate(re, str))
322 yield [res.index, res[0].length, res.wholeMatch ? [res] : res];
323 })(), highlight || template.filter);
326 highlightSubstrings: function highlightSubstrings(str, iter, highlight) {
327 XML.ignoreWhitespace = XML.prettyPrinting = false;
328 if (typeof str == "xml")
333 str = String(str).replace(" ", "\u00a0");
337 for (let [i, length, args] in iter) {
338 if (i == _i || i < _i)
342 XML.ignoreWhitespace = false;
343 s += <>{str.substring(start, i)}</>;
344 s += highlight.apply(this, Array.concat(args || str.substr(i, length)));
347 return s + <>{str.substr(start)}</>;
350 highlightURL: function highlightURL(str, force) {
351 if (force || /^[a-zA-Z]+:\/\//.test(str))
352 return <a highlight="URL" href={str}>{str}</a>;
357 icon: function (item, text) <>
358 <span highlight="CompIcon">{item.icon ? <img src={item.icon}/> : <></>}</span><span class="td-strut"/>{text}
361 jumps: function jumps(index, elems) {
362 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
365 <tr style="text-align: left;" highlight="Title">
366 <th colspan="2">jump</th><th>title</th><th>URI</th>
369 this.map(Iterator(elems), function ([idx, val])
371 <td class="indicator">{idx == index ? ">" : ""}</td>
372 <td>{Math.abs(idx - index)}</td>
373 <td style="width: 250px; max-width: 500px; overflow: hidden;">{val.title}</td>
374 <td><a href={val.URI.spec} highlight="URL jump-list">{val.URI.spec}</a></td>
381 options: function options(title, opts, verbose) {
382 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
385 <tr highlight="Title" align="left">
386 <th>--- {title} ---</th>
389 this.map(opts, function (opt)
392 <div highlight="Message"
393 ><span style={opt.isDefault ? "" : "font-weight: bold"}>{opt.pre}{opt.name}</span><span>{opt.value}</span>{
394 opt.isDefault || opt.default == null ? "" : <span class="extra-info"> (default: {opt.default})</span>
396 verbose && opt.setFrom ? <div highlight="Message"> Last set from {template.sourceLink(opt.setFrom)}</div> : <></>
405 sourceLink: function (frame) {
406 let url = util.fixURI(frame.filename || "unknown");
407 let path = util.urlPath(url);
409 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
410 return <a xmlns:dactyl={NS} dactyl:command="buffer.viewSource"
411 href={url} path={path} line={frame.lineNumber}
413 path + ":" + frame.lineNumber
417 table: function table(title, data, indent) {
418 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
421 <tr highlight="Title" align="left">
422 <th colspan="2">{title}</th>
425 this.map(data, function (datum)
427 <td style={"font-weight: bold; min-width: 150px; padding-left: " + (indent || "2ex")}>{datum[0]}</td>
433 if (table.tr.length() > 1)
437 tabular: function tabular(headings, style, iter) {
438 // TODO: This might be mind-bogglingly slow. We'll see.
439 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
442 <tr highlight="Title" align="left">
444 this.map(headings, function (h)
449 this.map(iter, function (row)
452 template.map(Iterator(row), function ([i, d])
453 <td style={style[i] || ""}>{d}</td>)
461 usage: function usage(iter, format) {
462 XML.ignoreWhitespace = false; XML.prettyPrinting = false;
463 format = format || {};
464 let desc = format.description || function (item) template.linkifyHelp(item.description);
465 let help = format.help || function (item) item.name;
466 function sourceLink(frame) {
467 let source = template.sourceLink(frame);
468 source.@NS::hint = source.text();
474 <thead highlight="UsageHead">
475 <tr highlight="Title" align="left">
477 this.map(format.headings, function (h) <th>{h}</th>)
485 this.map(format.columns, function (c) <col style={c}/>)
489 <tbody highlight="UsageBody">{
490 this.map(iter, function (item)
491 <tr highlight="UsageItem">
492 <td style="padding-right: 2em;">
493 <span highlight="Usage Link">{
494 let (name = item.name || item.names[0], frame = item.definedAt)
496 template.helpLink(help(item), name, "Title") +
497 <span highlight="LinkInfo" xmlns:dactyl={NS}>Defined at {sourceLink(frame)}</span>
500 { item.columns ? template.map(item.columns, function (c) <td>{c}</td>) : "" }
501 <td>{desc(item)}</td>
511 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: