1 // Copyright (c) 2008-2012 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 defineModule("styles", {
8 exports: ["Style", "Styles", "styles"],
9 require: ["services", "util"]
12 lazyRequire("contexts", ["Contexts"]);
13 lazyRequire("template", ["template"]);
15 function cssUri(css) "chrome-data:text/css," + encodeURI(css);
16 var namespace = "@namespace html " + XHTML.quote() + ";\n" +
17 "@namespace xul " + XUL.quote() + ";\n" +
18 "@namespace dactyl " + NS.quote() + ";\n";
20 var Sheet = Struct("name", "id", "sites", "css", "hive", "agent");
21 Sheet.liveProperty = function (name) {
22 let i = this.prototype.members[name];
23 this.prototype.__defineGetter__(name, function () this[i]);
24 this.prototype.__defineSetter__(name, function (val) {
26 val = Array.slice(val);
30 this.enabled = this.enabled;
33 Sheet.liveProperty("agent");
34 Sheet.liveProperty("css");
35 Sheet.liveProperty("sites");
36 update(Sheet.prototype, {
37 formatSites: function (uris)
38 template.map(this.sites,
39 function (filter) ["span", { highlight: uris.some(Styles.matchFilter(filter)) ? "Filter" : "" }, filter],
42 remove: function () { this.hive.remove(this); },
44 get uri() "dactyl://style/" + this.id + "/" + this.hive.name + "/" + (this.name || ""),
46 get enabled() this._enabled,
48 if (on != this._enabled || this.fullCSS != this._fullCSS) {
51 else if (!this._fullCSS)
54 let meth = on ? "registerSheet" : "unregisterSheet";
55 styles[meth](this.uri, on ? this.agent : this._agent);
57 this._agent = this.agent;
58 this._enabled = Boolean(on);
59 this._fullCSS = this.fullCSS;
63 match: function (uri) {
65 uri = util.newURI(uri);
66 return this.sites.some(function (site) Styles.matchFilter(site, uri));
70 let filter = this.sites;
73 let preamble = "/* " + this.uri + (this.agent ? " (agent)" : "") + " */\n\n" + namespace + "\n";
75 return preamble + css;
77 let selectors = filter.map(function (part)
78 !/^(?:[a-z-]+[:*]|[a-z-.]+$)/i.test(part) ? "regexp(" + Styles.quote(".*(?:" + part + ").*") + ")" :
79 (/[*]$/.test(part) ? "url-prefix" :
80 /[\/:]/.test(part) ? "url"
82 + '(' + Styles.quote(part.replace(/\*$/, "")) + ')')
85 return preamble + "@-moz-document " + selectors + " {\n\n" + css + "\n\n}\n";
89 var Hive = Class("Hive", {
90 init: function (name, persist) {
95 this.persist = persist;
98 get modifiable() this.name !== "system",
100 addRef: function (obj) {
101 this.refs.push(util.weakReference(obj));
104 dropRef: function (obj) {
105 this.refs = this.refs.filter(function (ref) ref.get() && ref.get() !== obj);
106 if (!this.refs.length) {
108 styles.hives = styles.hives.filter(function (h) h !== this, this);
112 cleanup: function cleanup() {
113 for (let sheet in values(this.sheets))
114 sheet.enabled = false;
117 __iterator__: function () Iterator(this.sheets),
119 get sites() array(this.sheets).map(function (s) s.sites).flatten().uniq().array,
122 * Add a new style sheet.
124 * @param {string} name The name given to the style sheet by
125 * which it may be later referenced.
126 * @param {string} filter The sites to which this sheet will
127 * apply. Can be a domain name or a URL. Any URL ending in
128 * "*" is matched as a prefix.
129 * @param {string} css The CSS to be applied.
130 * @param {boolean} agent If true, the sheet is installed as an
132 * @param {boolean} lazy If true, the sheet is not initially enabled.
135 add: function add(name, filter, css, agent, lazy) {
137 if (!isArray(filter))
138 filter = filter.split(",");
139 if (name && name in this.names) {
140 var sheet = this.names[name];
142 sheet.css = String(css);
143 sheet.sites = filter;
146 sheet = Sheet(name, styles._id++, filter.filter(util.identity), String(css), this, agent);
147 this.sheets.push(sheet);
150 styles.allSheets[sheet.id] = sheet;
153 sheet.enabled = true;
156 this.names[name] = sheet;
161 * Get a sheet with a given name or index.
163 * @param {string or number} sheet The sheet to retrieve. Strings indicate
164 * sheet names, while numbers indicate indices.
166 get: function get(sheet) {
167 if (typeof sheet === "number")
168 return this.sheets[sheet];
169 return this.names[sheet];
173 * Find sheets matching the parameters. See {@link #addSheet}
176 * @param {string} name
177 * @param {string} filter
178 * @param {string} css
179 * @param {number} index
181 find: function find(name, filter, css, index) {
182 // Grossly inefficient.
183 let matches = [k for ([k, v] in Iterator(this.sheets))];
185 matches = String(index).split(",").filter(function (i) i in this.sheets, this);
187 matches = matches.filter(function (i) this.sheets[i].name == name, this);
189 matches = matches.filter(function (i) this.sheets[i].css == css, this);
191 matches = matches.filter(function (i) this.sheets[i].sites.indexOf(filter) >= 0, this);
192 return matches.map(function (i) this.sheets[i], this);
196 * Remove a style sheet. See {@link #addSheet} for parameters.
197 * In cases where *filter* is supplied, the given filters are removed from
198 * matching sheets. If any remain, the sheet is left in place.
200 * @param {string} name
201 * @param {string} filter
202 * @param {string} css
203 * @param {number} index
205 remove: function remove(name, filter, css, index) {
207 if (arguments.length == 1) {
208 var matches = [name];
212 if (filter && filter.indexOf(",") > -1)
213 return filter.split(",").reduce(
214 function (n, f) n + self.removeSheet(name, f, index), 0);
216 if (filter == undefined)
220 matches = this.findSheets(name, filter, css, index);
221 if (matches.length == 0)
224 for (let [, sheet] in Iterator(matches.reverse())) {
226 let sites = sheet.sites.filter(function (f) f != filter);
232 sheet.enabled = false;
234 delete this.names[sheet.name];
235 delete styles.allSheets[sheet.id];
237 this.sheets = this.sheets.filter(function (s) matches.indexOf(s) == -1);
238 return matches.length;
243 * Manages named and unnamed user style sheets, which apply to both
244 * chrome and content pages.
246 * @author Kris Maglione <maglione.k@gmail.com>
248 var Styles = Module("Styles", {
249 Local: function (dactyl, modules, window) ({
250 cleanup: function () {}
258 update(services["dactyl:"].providers, {
259 "style": function styleProvider(uri, path) {
260 let id = parseInt(path);
261 if (Set.has(styles.allSheets, id))
262 return ["text/css", styles.allSheets[id].fullCSS];
268 cleanup: function cleanup() {
269 for each (let hive in this.hives)
270 util.trapErrors("cleanup", hive);
272 this.user = this.addHive("user", this, true);
273 this.system = this.addHive("system", this, false);
276 addHive: function addHive(name, ref, persist) {
277 let hive = array.nth(this.hives, function (h) h.name === name, 0);
279 hive = Hive(name, persist);
280 this.hives.push(hive);
282 hive.persist = persist;
288 __iterator__: function () Iterator(this.user.sheets.concat(this.system.sheets)),
290 _proxy: function (name, args)
291 let (obj = this[args[0] ? "system" : "user"])
292 obj[name].apply(obj, Array.slice(args, 1)),
294 addSheet: deprecated("Styles#{user,system}.add", function addSheet() this._proxy("add", arguments)),
295 findSheets: deprecated("Styles#{user,system}.find", function findSheets() this._proxy("find", arguments)),
296 get: deprecated("Styles#{user,system}.get", function get() this._proxy("get", arguments)),
297 removeSheet: deprecated("Styles#{user,system}.remove", function removeSheet() this._proxy("remove", arguments)),
299 userSheets: Class.Property({ get: deprecated("Styles#user.sheets", function userSheets() this.user.sheets) }),
300 systemSheets: Class.Property({ get: deprecated("Styles#system.sheets", function systemSheets() this.system.sheets) }),
301 userNames: Class.Property({ get: deprecated("Styles#user.names", function userNames() this.user.names) }),
302 systemNames: Class.Property({ get: deprecated("Styles#system.names", function systemNames() this.system.names) }),
303 sites: Class.Property({ get: deprecated("Styles#user.sites", function sites() this.user.sites) }),
305 list: function list(content, sites, name, hives) {
306 const { commandline, dactyl } = this.modules;
308 hives = hives || styles.hives.filter(function (h) h.modifiable && h.sheets.length);
310 function sheets(group)
312 .filter(function (sheet) (!name || sheet.name === name) &&
313 (!sites || sites.every(function (s) sheet.sites.indexOf(s) >= 0)))
314 .sort(function (a, b) a.name && b.name ? String.localeCompare(a.name, b.name)
315 : !!b.name - !!a.name || a.id - b.id);
317 let uris = util.visibleURIs(content);
319 let list = ["table", {},
320 ["tr", { highlight: "Title" },
323 ["td", { style: "padding-right: 1em;" }, _("title.Name")],
324 ["td", { style: "padding-right: 1em;" }, _("title.Filter")],
325 ["td", { style: "padding-right: 1em;" }, _("title.CSS")]],
326 ["col", { style: "min-width: 4em; padding-right: 1em;" }],
327 ["col", { style: "min-width: 1em; text-align: center; color: red; font-weight: bold;" }],
328 ["col", { style: "padding: 0 1em 0 1ex; vertical-align: top;" }],
329 ["col", { style: "padding: 0 1em 0 0; vertical-align: top;" }],
330 template.map(hives, function (hive) let (i = 0) [
331 ["tr", { style: "height: .5ex;" }],
332 template.map(sheets(hive), function (sheet)
334 ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
335 ["td", {}, sheet.enabled ? "" : UTF8("×")],
336 ["td", {}, sheet.name || hive.sheets.indexOf(sheet)],
337 ["td", {}, sheet.formatSites(uris)],
338 ["td", {}, sheet.css]]),
339 ["tr", { style: "height: .5ex;" }]])];
342 // // TODO: Move this to an ItemList to show this automatically
343 // if (list.*.length() === list.text().length() + 5)
344 // dactyl.echomsg(_("style.none"));
346 commandline.commandOutput(list);
349 registerSheet: function registerSheet(url, agent, reload) {
350 let uri = services.io.newURI(url, null, null);
352 this.unregisterSheet(url, agent);
354 let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
355 if (reload || !services.stylesheet.sheetRegistered(uri, type))
356 services.stylesheet.loadAndRegisterSheet(uri, type);
359 unregisterSheet: function unregisterSheet(url, agent) {
360 let uri = services.io.newURI(url, null, null);
361 let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
362 if (services.stylesheet.sheetRegistered(uri, type))
363 services.stylesheet.unregisterSheet(uri, type);
366 append: function (dest, src, sort) {
368 for each (let str in [dest, src])
369 for (let prop in Styles.propertyIter(str))
370 props[prop.name] = prop.value;
372 let val = Object.keys(props)[sort ? "sort" : "slice"]()
373 .map(function (prop) prop + ": " + props[prop] + ";")
376 if (/^\s*(\/\*.*?\*\/)/.exec(src))
377 val = RegExp.$1 + " " + val;
381 completeSite: function (context, content, group) {
382 group = group || styles.user;
383 context.anchored = false;
385 context.fork("current", 0, this, function (context) {
386 context.title = ["Current Site"];
387 context.completions = [
388 [content.location.host, /*L*/"Current Host"],
389 [content.location.href, /*L*/"Current URL"]
395 let uris = util.visibleURIs(content);
397 context.generate = function () values(group.sites);
399 context.keys.text = util.identity;
400 context.keys.description = function (site) this.sheets.length + /*L*/" sheet" + (this.sheets.length == 1 ? "" : "s") + ": " +
401 array.compact(this.sheets.map(function (s) s.name)).join(", ");
402 context.keys.sheets = function (site) group.sheets.filter(function (s) s.sites.indexOf(site) >= 0);
403 context.keys.active = function (site) uris.some(Styles.matchFilter(site));
405 Styles.splitContext(context, "Sites");
409 * A curried function which determines which host names match a
410 * given stylesheet filter. When presented with one argument,
411 * returns a matcher function which, given one nsIURI argument,
412 * returns true if that argument matches the given filter. When
413 * given two arguments, returns true if the second argument matches
416 * @param {string} filter The URI filter to match against.
417 * @param {nsIURI} uri The location to test.
418 * @returns {nsIURI -> boolean}
420 matchFilter: function (filter) {
421 filter = filter.trim();
424 var test = function test(uri) true;
425 else if (!/^(?:[a-z-]+:|[a-z-.]+$)/.test(filter)) {
426 let re = util.regexp(filter);
427 test = function test(uri) re.test(uri.spec);
429 else if (/[*]$/.test(filter)) {
430 let re = RegExp("^" + util.regexp.escape(filter.substr(0, filter.length - 1)));
431 test = function test(uri) re.test(uri.spec);
433 else if (/[\/:]/.test(filter))
434 test = function test(uri) uri.spec === filter;
436 test = function test(uri) { try { return util.isSubdomain(uri.host, filter); } catch (e) { return false; } };
437 test.toString = function toString() filter;
439 if (arguments.length < 2)
441 return test(arguments[1]);
444 splitContext: function splitContext(context, title) {
445 for (let item in Iterator({ Active: true, Inactive: false })) {
446 let [name, active] = item;
447 context.split(name, null, function (context) {
448 context.title[0] = /*L*/name + " " + (title || "Sheets");
449 context.filters.push(function (item) !!item.active == active);
454 propertyIter: function (str, always) {
456 for (let match in this.propertyPattern.iterate(str)) {
457 if (match.value || always && match.name || match.wholeMatch === match.preSpace && always && !i++)
459 if (!/;/.test(match.postSpace))
464 propertyPattern: util.regexp(literal(/*
466 (?P<preSpace> <space>*)
469 <space>* : \s* (?P<value>
474 (?: <string> | [^)]* )
485 (?P<postSpace> <space>* (?: ; | $) )
488 space: /(?: \s | \/\* .*? \*\/ )/,
489 string: /(?:" (?:[^\\"]|\\.)* (?:"|$) | '(?:[^\\']|\\.)* (?:'|$) )/
493 get property() util.regexp(literal(/*
495 (?P<preSpace> <space>*)
498 <space>* : \s* (?P<value>
503 (?P<postSpace> <space>* (?: ; | $) )
506 get function() util.regexp(literal(/*
509 (?: <string> | [^)]* )
514 space: /(?: \s | \/\* .*? \*\/ )/,
516 get string() util.regexp(literal(/*
518 " (?:[^\\"]|\\.)* (?:"|$) |
519 ' (?:[^\\']|\\.)* (?:'|$)
523 get token() util.regexp(literal(/*
528 | (?P<important> !important\b)
537 * Quotes a string for use in CSS stylesheets.
539 * @param {string} str
542 quote: function quote(str) {
543 return '"' + str.replace(/([\\"])/g, "\\$1").replace(/\n/g, "\\00000a") + '"';
546 commands: function initCommands(dactyl, modules, window) {
547 const { commands, contexts, styles } = modules;
549 function sheets(context, args, filter) {
550 let uris = util.visibleURIs(window.content);
551 context.compare = modules.CompletionContext.Sort.number;
552 context.generate = function () args["-group"].sheets;
553 context.keys.active = function (sheet) uris.some(sheet.closure.match);
554 context.keys.description = function (sheet) [sheet.formatSites(uris), ": ", sheet.css.replace("\n", "\\n")];
556 context.filters.push(function ({ item }) filter(item));
557 Styles.splitContext(context);
560 function nameFlag(filter) ({
561 names: ["-name", "-n"],
562 description: "The name of this stylesheet",
563 type: modules.CommandOption.STRING,
564 completer: function (context, args) {
565 context.keys.text = function (sheet) sheet.name;
566 context.filters.unshift(function ({ item }) item.name);
567 sheets(context, args, filter);
571 commands.add(["sty[le]"],
572 "Add or list user styles",
574 let [filter, css] = args;
577 styles.list(window.content, filter ? filter.split(",") : null, args["-name"], args.explicitOpts["-group"] ? [args["-group"]] : null);
579 util.assert(args["-group"].modifiable && args["-group"].hive.modifiable,
580 _("group.cantChangeBuiltin", _("style.styles")));
582 if (args["-append"]) {
583 let sheet = args["-group"].get(args["-name"]);
585 filter = array(sheet.sites).concat(filter).uniq().join(",");
586 css = sheet.css + " " + css;
589 let style = args["-group"].add(args["-name"], filter, css, args["-agent"]);
591 if (args["-nopersist"] || !args["-append"] || style.persist === undefined)
592 style.persist = !args["-nopersist"];
596 completer: function (context, args) {
598 let sheet = args["-group"].get(args["-name"]);
599 if (args.completeArg == 0) {
601 context.completions = [[sheet.sites.join(","), "Current Value"]];
602 context.fork("sites", 0, Styles, "completeSite", window.content, args["-group"]);
604 else if (args.completeArg == 1) {
606 context.completions = [
607 [sheet.css, _("option.currentValue")]
609 context.fork("css", 0, modules.completion, "css");
615 { names: ["-agent", "-A"], description: "Apply style as an Agent sheet" },
616 { names: ["-append", "-a"], description: "Append site filter and css to an existing, matching sheet" },
617 contexts.GroupFlag("styles"),
619 { names: ["-nopersist", "-N"], description: "Do not save this style to an auto-generated RC file" }
621 serialize: function ()
623 .filter(function (hive) hive.persist)
625 hive.sheets.filter(function (style) style.persist)
626 .sort(function (a, b) String.localeCompare(a.name || "", b.name || ""))
627 .map(function (style) ({
629 arguments: [style.sites.join(",")],
630 literalArg: style.css,
632 "-group": hive.name == "user" ? undefined : hive.name,
633 "-name": style.name || undefined
641 name: ["stylee[nable]", "stye[nable]"],
642 desc: "Enable a user style sheet",
643 action: function (sheet) sheet.enabled = true,
644 filter: function (sheet) !sheet.enabled
647 name: ["styled[isable]", "styd[isable]"],
648 desc: "Disable a user style sheet",
649 action: function (sheet) sheet.enabled = false,
650 filter: function (sheet) sheet.enabled
653 name: ["stylet[oggle]", "styt[oggle]"],
654 desc: "Toggle a user style sheet",
655 action: function (sheet) sheet.enabled = !sheet.enabled
658 name: ["dels[tyle]"],
659 desc: "Remove a user style sheet",
660 action: function (sheet) sheet.remove(),
662 ].forEach(function (cmd) {
663 commands.add(cmd.name, cmd.desc,
665 dactyl.assert(args.bang ^ !!(args[0] || args[1] || args["-name"] || args["-index"]),
666 _("error.argumentOrBang"));
668 args["-group"].find(args["-name"], args[0], args.literalArg, args["-index"])
669 .forEach(cmd.action);
672 completer: function (context, args) {
673 let uris = util.visibleURIs(window.content);
675 Styles.completeSite(context, window.content, args["-group"]);
677 context.filters.push(function ({ sheets }) sheets.some(cmd.filter));
681 contexts.GroupFlag("styles"),
683 names: ["-index", "-i"],
684 type: modules.CommandOption.INT,
685 completer: function (context, args) {
686 context.keys.text = function (sheet) args["-group"].sheets.indexOf(sheet);
687 sheets(context, args, cmd.filter);
695 contexts: function initContexts(dactyl, modules, window) {
696 modules.contexts.Hives("styles",
697 Class("LocalHive", Contexts.Hive, {
698 init: function init(group) {
699 init.superapply(this, arguments);
700 this.hive = styles.addHive(group.name, this, this.persist);
703 get names() this.hive.names,
704 get sheets() this.hive.sheets,
705 get sites() this.hive.sites,
707 __noSuchMethod__: function __noSuchMethod__(meth, args) {
708 return this.hive[meth].apply(this.hive, args);
711 destroy: function () {
712 this.hive.dropRef(this);
716 completion: function initCompletion(dactyl, modules, window) {
717 const names = Array.slice(DOM(["div"], window.document).style);
718 modules.completion.css = function (context) {
719 context.title = ["CSS Property"];
720 context.keys = { text: function (p) p + ":", description: function () "" };
722 for (let match in Styles.propertyIter(context.filter, true))
723 var lastMatch = match;
725 if (lastMatch != null && !lastMatch.value && !lastMatch.postSpace) {
726 context.advance(lastMatch.index + lastMatch.preSpace.length);
727 context.completions = names;
731 javascript: function initJavascript(dactyl, modules, window) {
732 modules.JavaScript.setCompleter(["get", "add", "remove", "find"].map(function (m) Hive.prototype[m]),
733 [ // Prototype: (name, filter, css, index)
734 function (context, obj, args) this.names,
735 function (context, obj, args) Styles.completeSite(context, window.content),
737 function (context, obj, args) this.sheets
740 template: function initTemplate() {
741 let patterns = Styles.patterns;
743 template.highlightCSS = function highlightCSS(css) {
744 return this.highlightRegexp(css, patterns.property, function (match) {
747 return ["", match.preSpace, template.filter(match.name), ": ",
749 template.highlightRegexp(match.value, patterns.token, function (match) {
751 return ["", template.filter(match.word),
752 template.highlightRegexp(match.function, patterns.string,
753 function (match) ["span", { highlight: "String" }, match.string])
755 if (match.important == "!important")
756 return ["span", { highlight: "String" }, match.important];
758 return ["span", { highlight: "String" }, match.string];
759 return template._highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g,
761 ["span", { highlight: "Number" }, n],
762 ["span", { highlight: "Object" }, u || ""]
774 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
776 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: