1 // Copyright (c) 2008-2013 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 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(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(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(ref => (ref.get() && ref.get() !== obj));
107 if (!this.refs.length) {
109 styles.hives = styles.hives.filter(h => h !== this);
113 cleanup: function cleanup() {
114 for (let sheet in values(this.sheets))
115 sheet.enabled = false;
118 __iterator__: function () Iterator(this.sheets),
120 get sites() array(this.sheets).map(s => s.sites)
125 * Add a new style sheet.
127 * @param {string} name The name given to the style sheet by
128 * which it may be later referenced.
129 * @param {string} filter The sites to which this sheet will
130 * apply. Can be a domain name or a URL. Any URL ending in
131 * "*" is matched as a prefix.
132 * @param {string} css The CSS to be applied.
133 * @param {boolean} agent If true, the sheet is installed as an
135 * @param {boolean} lazy If true, the sheet is not initially enabled.
138 add: function add(name, filter, css, agent, lazy) {
140 if (!isArray(filter))
141 filter = filter.split(",");
142 if (name && name in this.names) {
143 var sheet = this.names[name];
145 sheet.css = String(css);
146 sheet.sites = filter;
149 sheet = Sheet(name, styles._id++, filter.filter(util.identity), String(css), this, agent);
150 this.sheets.push(sheet);
153 styles.allSheets[sheet.id] = sheet;
156 sheet.enabled = true;
159 this.names[name] = sheet;
164 * Get a sheet with a given name or index.
166 * @param {string or number} sheet The sheet to retrieve. Strings indicate
167 * sheet names, while numbers indicate indices.
169 get: function get(sheet) {
170 if (typeof sheet === "number")
171 return this.sheets[sheet];
172 return this.names[sheet];
176 * Find sheets matching the parameters. See {@link #addSheet}
179 * @param {string} name
180 * @param {string} filter
181 * @param {string} css
182 * @param {number} index
184 find: function find(name, filter, css, index) {
185 // Grossly inefficient.
186 let matches = [k for ([k, v] in Iterator(this.sheets))];
188 matches = String(index).split(",").filter(i => i in this.sheets);
190 matches = matches.filter(i => this.sheets[i].name == name);
192 matches = matches.filter(i => this.sheets[i].css == css);
194 matches = matches.filter(i => this.sheets[i].sites.indexOf(filter) >= 0);
196 return matches.map(i => this.sheets[i]);
200 * Remove a style sheet. See {@link #addSheet} for parameters.
201 * In cases where *filter* is supplied, the given filters are removed from
202 * matching sheets. If any remain, the sheet is left in place.
204 * @param {string} name
205 * @param {string} filter
206 * @param {string} css
207 * @param {number} index
209 remove: function remove(name, filter, css, index) {
210 if (arguments.length == 1) {
211 var matches = [name];
215 if (filter && filter.indexOf(",") > -1)
216 return filter.split(",").reduce(
217 (n, f) => n + this.removeSheet(name, f, index), 0);
219 if (filter == undefined)
223 matches = this.findSheets(name, filter, css, index);
224 if (matches.length == 0)
227 for (let [, sheet] in Iterator(matches.reverse())) {
229 let sites = sheet.sites.filter(f => f != filter);
235 sheet.enabled = false;
237 delete this.names[sheet.name];
238 delete styles.allSheets[sheet.id];
240 this.sheets = this.sheets.filter(s => matches.indexOf(s) == -1);
241 return matches.length;
246 * Manages named and unnamed user style sheets, which apply to both
247 * chrome and content pages.
249 * @author Kris Maglione <maglione.k@gmail.com>
251 var Styles = Module("Styles", {
252 Local: function (dactyl, modules, window) ({
253 cleanup: function () {}
261 update(services["dactyl:"].providers, {
262 "style": function styleProvider(uri, path) {
263 let id = parseInt(path);
264 if (Set.has(styles.allSheets, id))
265 return ["text/css", styles.allSheets[id].fullCSS];
271 cleanup: function cleanup() {
272 for each (let hive in this.hives)
273 util.trapErrors("cleanup", hive);
275 this.user = this.addHive("user", this, true);
276 this.system = this.addHive("system", this, false);
279 addHive: function addHive(name, ref, persist) {
280 let hive = array.nth(this.hives, h => h.name === name,
283 hive = Hive(name, persist);
284 this.hives.push(hive);
286 hive.persist = persist;
292 __iterator__: function () Iterator(this.user.sheets.concat(this.system.sheets)),
294 _proxy: function (name, args)
295 let (obj = this[args[0] ? "system" : "user"])
296 obj[name].apply(obj, Array.slice(args, 1)),
298 addSheet: deprecated("Styles#{user,system}.add", function addSheet() this._proxy("add", arguments)),
299 findSheets: deprecated("Styles#{user,system}.find", function findSheets() this._proxy("find", arguments)),
300 get: deprecated("Styles#{user,system}.get", function get() this._proxy("get", arguments)),
301 removeSheet: deprecated("Styles#{user,system}.remove", function removeSheet() this._proxy("remove", arguments)),
303 userSheets: Class.Property({ get: deprecated("Styles#user.sheets", function userSheets() this.user.sheets) }),
304 systemSheets: Class.Property({ get: deprecated("Styles#system.sheets", function systemSheets() this.system.sheets) }),
305 userNames: Class.Property({ get: deprecated("Styles#user.names", function userNames() this.user.names) }),
306 systemNames: Class.Property({ get: deprecated("Styles#system.names", function systemNames() this.system.names) }),
307 sites: Class.Property({ get: deprecated("Styles#user.sites", function sites() this.user.sites) }),
309 list: function list(content, sites, name, hives) {
310 const { commandline, dactyl } = this.modules;
312 hives = hives || styles.hives.filter(h => (h.modifiable && h.sheets.length));
314 function sheets(group)
316 .filter(sheet => ((!name || sheet.name === name) &&
317 (!sites || sites.every(s => sheet.sites.indexOf(s) >= 0))))
318 .sort((a, b) => (a.name && b.name ? String.localeCompare(a.name, b.name)
319 : !!b.name - !!a.name || a.id - b.id));
321 let uris = util.visibleURIs(content);
323 let list = ["table", {},
324 ["tr", { highlight: "Title" },
327 ["td", { style: "padding-right: 1em;" }, _("title.Name")],
328 ["td", { style: "padding-right: 1em;" }, _("title.Filter")],
329 ["td", { style: "padding-right: 1em;" }, _("title.CSS")]],
330 ["col", { style: "min-width: 4em; padding-right: 1em;" }],
331 ["col", { style: "min-width: 1em; text-align: center; color: red; font-weight: bold;" }],
332 ["col", { style: "padding: 0 1em 0 1ex; vertical-align: top;" }],
333 ["col", { style: "padding: 0 1em 0 0; vertical-align: top;" }],
334 template.map(hives, hive => let (i = 0) [
335 ["tr", { style: "height: .5ex;" }],
336 template.map(sheets(hive), sheet =>
338 ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
339 ["td", {}, sheet.enabled ? "" : UTF8("×")],
340 ["td", {}, sheet.name || hive.sheets.indexOf(sheet)],
341 ["td", {}, sheet.formatSites(uris)],
342 ["td", {}, sheet.css]]),
343 ["tr", { style: "height: .5ex;" }]])];
346 // // TODO: Move this to an ItemList to show this automatically
347 // if (list.*.length() === list.text().length() + 5)
348 // dactyl.echomsg(_("style.none"));
350 commandline.commandOutput(list);
353 registerSheet: function registerSheet(url, agent, reload) {
354 let uri = services.io.newURI(url, null, null);
356 this.unregisterSheet(url, agent);
358 let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
359 if (reload || !services.stylesheet.sheetRegistered(uri, type))
360 services.stylesheet.loadAndRegisterSheet(uri, type);
363 unregisterSheet: function unregisterSheet(url, agent) {
364 let uri = services.io.newURI(url, null, null);
365 let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
366 if (services.stylesheet.sheetRegistered(uri, type))
367 services.stylesheet.unregisterSheet(uri, type);
370 append: function (dest, src, sort) {
372 for each (let str in [dest, src])
373 for (let prop in Styles.propertyIter(str))
374 props[prop.name] = prop.value;
376 let val = Object.keys(props)[sort ? "sort" : "slice"]()
377 .map(prop => prop + ": " + props[prop] + ";")
380 if (/^\s*(\/\*.*?\*\/)/.exec(src))
381 val = RegExp.$1 + " " + val;
385 completeSite: function (context, content, group = styles.user) {
386 context.anchored = false;
388 context.fork("current", 0, this, function (context) {
389 context.title = ["Current Site"];
390 context.completions = [
391 [content.location.host, /*L*/"Current Host"],
392 [content.location.href, /*L*/"Current URL"]
398 let uris = util.visibleURIs(content);
400 context.generate = () => values(group.sites);
402 context.keys.text = util.identity;
403 context.keys.description = function (site) this.sheets.length + /*L*/" sheet" + (this.sheets.length == 1 ? "" : "s") + ": " +
404 array.compact(this.sheets.map(s => s.name)).join(", ");
405 context.keys.sheets = site => group.sheets.filter(s => s.sites.indexOf(site) >= 0);
406 context.keys.active = site => uris.some(Styles.matchFilter(site));
408 Styles.splitContext(context, "Sites");
412 * A curried function which determines which host names match a
413 * given stylesheet filter. When presented with one argument,
414 * returns a matcher function which, given one nsIURI argument,
415 * returns true if that argument matches the given filter. When
416 * given two arguments, returns true if the second argument matches
419 * @param {string} filter The URI filter to match against.
420 * @param {nsIURI} uri The location to test.
421 * @returns {nsIURI -> boolean}
423 matchFilter: function (filter) {
424 filter = filter.trim();
427 var test = function test(uri) true;
428 else if (!/^(?:[a-z-]+:|[a-z-.]+$)/.test(filter)) {
429 let re = util.regexp(filter);
430 test = function test(uri) re.test(uri.spec);
432 else if (/[*]$/.test(filter)) {
433 let re = RegExp("^" + util.regexp.escape(filter.substr(0, filter.length - 1)));
434 test = function test(uri) re.test(uri.spec);
436 else if (/[\/:]/.test(filter))
437 test = function test(uri) uri.spec === filter;
439 test = function test(uri) { try { return util.isSubdomain(uri.host, filter); } catch (e) { return false; } };
440 test.toString = function toString() filter;
442 if (arguments.length < 2)
444 return test(arguments[1]);
447 splitContext: function splitContext(context, title) {
448 for (let item in Iterator({ Active: true, Inactive: false })) {
449 let [name, active] = item;
450 context.split(name, null, function (context) {
451 context.title[0] = /*L*/name + " " + (title || "Sheets");
452 context.filters.push(item => !!item.active == active);
457 propertyIter: function (str, always) {
459 for (let match in this.propertyPattern.iterate(str)) {
460 if (match.value || always && match.name || match.wholeMatch === match.preSpace && always && !i++)
462 if (!/;/.test(match.postSpace))
467 propertyPattern: util.regexp(literal(/*
469 (?P<preSpace> <space>*)
472 <space>* : \s* (?P<value>
477 (?: <string> | [^)]* )
488 (?P<postSpace> <space>* (?: ; | $) )
491 space: /(?: \s | \/\* .*? \*\/ )/,
492 string: /(?:" (?:[^\\"]|\\.)* (?:"|$) | '(?:[^\\']|\\.)* (?:'|$) )/
496 get property() util.regexp(literal(/*
498 (?P<preSpace> <space>*)
501 <space>* : \s* (?P<value>
506 (?P<postSpace> <space>* (?: ; | $) )
509 get function() util.regexp(literal(/*
512 (?: <string> | [^)]* )
517 space: /(?: \s | \/\* .*? \*\/ )/,
519 get string() util.regexp(literal(/*
521 " (?:[^\\"]|\\.)* (?:"|$) |
522 ' (?:[^\\']|\\.)* (?:'|$)
526 get token() util.regexp(literal(/*
531 | (?P<important> !important\b)
540 * Quotes a string for use in CSS stylesheets.
542 * @param {string} str
545 quote: function quote(str) {
546 return '"' + str.replace(/([\\"])/g, "\\$1").replace(/\n/g, "\\00000a") + '"';
549 commands: function initCommands(dactyl, modules, window) {
550 const { commands, contexts, styles } = modules;
552 function sheets(context, args, filter) {
553 let uris = util.visibleURIs(window.content);
554 context.compare = modules.CompletionContext.Sort.number;
555 context.generate = () => args["-group"].sheets;
556 context.keys.active = sheet => uris.some(sheet.closure.match);
557 context.keys.description = sheet => [sheet.formatSites(uris), ": ", sheet.css.replace("\n", "\\n")];
559 context.filters.push(({ item }) => filter(item));
560 Styles.splitContext(context);
563 function nameFlag(filter) ({
564 names: ["-name", "-n"],
565 description: "The name of this stylesheet",
566 type: modules.CommandOption.STRING,
567 completer: function (context, args) {
568 context.keys.text = sheet => sheet.name;
569 context.filters.unshift(({ item }) => item.name);
570 sheets(context, args, filter);
574 commands.add(["sty[le]"],
575 "Add or list user styles",
577 let [filter, css] = args;
580 styles.list(window.content, filter ? filter.split(",") : null, args["-name"], args.explicitOpts["-group"] ? [args["-group"]] : null);
582 util.assert(args["-group"].modifiable && args["-group"].hive.modifiable,
583 _("group.cantChangeBuiltin", _("style.styles")));
585 if (args["-append"]) {
586 let sheet = args["-group"].get(args["-name"]);
588 filter = array(sheet.sites).concat(filter).uniq().join(",");
589 css = sheet.css + " " + css;
592 let style = args["-group"].add(args["-name"], filter, css, args["-agent"]);
594 if (args["-nopersist"] || !args["-append"] || style.persist === undefined)
595 style.persist = !args["-nopersist"];
599 completer: function (context, args) {
601 let sheet = args["-group"].get(args["-name"]);
602 if (args.completeArg == 0) {
604 context.completions = [[sheet.sites.join(","), "Current Value"]];
605 context.fork("sites", 0, Styles, "completeSite", window.content, args["-group"]);
607 else if (args.completeArg == 1) {
609 context.completions = [
610 [sheet.css, _("option.currentValue")]
612 context.fork("css", 0, modules.completion, "css");
618 { names: ["-agent", "-A"], description: "Apply style as an Agent sheet" },
619 { names: ["-append", "-a"], description: "Append site filter and css to an existing, matching sheet" },
620 contexts.GroupFlag("styles"),
622 { names: ["-nopersist", "-N"], description: "Do not save this style to an auto-generated RC file" }
624 serialize: function ()
626 .filter(hive => hive.persist)
628 hive.sheets.filter(style => style.persist)
629 .sort((a, b) => String.localeCompare(a.name || "",
633 arguments: [style.sites.join(",")],
634 literalArg: style.css,
636 "-group": hive.name == "user" ? undefined : hive.name,
637 "-name": style.name || undefined
645 name: ["stylee[nable]", "stye[nable]"],
646 desc: "Enable a user style sheet",
647 action: function (sheet) sheet.enabled = true,
648 filter: function (sheet) !sheet.enabled
651 name: ["styled[isable]", "styd[isable]"],
652 desc: "Disable a user style sheet",
653 action: function (sheet) sheet.enabled = false,
654 filter: function (sheet) sheet.enabled
657 name: ["stylet[oggle]", "styt[oggle]"],
658 desc: "Toggle a user style sheet",
659 action: function (sheet) sheet.enabled = !sheet.enabled
662 name: ["dels[tyle]"],
663 desc: "Remove a user style sheet",
664 action: function (sheet) sheet.remove(),
666 ].forEach(function (cmd) {
667 commands.add(cmd.name, cmd.desc,
669 dactyl.assert(args.bang ^ !!(args[0] || args[1] || args["-name"] || args["-index"]),
670 _("error.argumentOrBang"));
672 args["-group"].find(args["-name"], args[0], args.literalArg, args["-index"])
673 .forEach(cmd.action);
676 completer: function (context, args) {
677 let uris = util.visibleURIs(window.content);
679 Styles.completeSite(context, window.content, args["-group"]);
681 context.filters.push(({ sheets }) => sheets.some(cmd.filter));
685 contexts.GroupFlag("styles"),
687 names: ["-index", "-i"],
688 type: modules.CommandOption.INT,
689 completer: function (context, args) {
690 context.keys.text = sheet => args["-group"].sheets.indexOf(sheet);
691 sheets(context, args, cmd.filter);
699 contexts: function initContexts(dactyl, modules, window) {
700 modules.contexts.Hives("styles",
701 Class("LocalHive", Contexts.Hive, {
702 init: function init(group) {
703 init.superapply(this, arguments);
704 this.hive = styles.addHive(group.name, this, this.persist);
707 get names() this.hive.names,
708 get sheets() this.hive.sheets,
709 get sites() this.hive.sites,
711 __noSuchMethod__: function __noSuchMethod__(meth, args) {
712 return this.hive[meth].apply(this.hive, args);
715 destroy: function () {
716 this.hive.dropRef(this);
720 completion: function initCompletion(dactyl, modules, window) {
721 const names = Array.slice(DOM(["div"], window.document).style);
722 modules.completion.css = function (context) {
723 context.title = ["CSS Property"];
724 context.keys = { text: function (p) p + ":",
725 description: function () "" };
727 for (let match in Styles.propertyIter(context.filter, true))
728 var lastMatch = match;
730 if (lastMatch != null && !lastMatch.value && !lastMatch.postSpace) {
731 context.advance(lastMatch.index + lastMatch.preSpace.length);
732 context.completions = names;
736 javascript: function initJavascript(dactyl, modules, window) {
737 modules.JavaScript.setCompleter(["get", "add", "remove", "find"].map(m => Hive.prototype[m]),
738 [ // Prototype: (name, filter, css, index)
739 function (context, obj, args) this.names,
740 (context, obj, args) => Styles.completeSite(context, window.content),
742 function (context, obj, args) this.sheets
745 template: function initTemplate() {
746 let patterns = Styles.patterns;
748 template.highlightCSS = function highlightCSS(css) {
749 return this.highlightRegexp(css, patterns.property, function (match) {
752 return ["", match.preSpace, template.filter(match.name), ": ",
754 template.highlightRegexp(match.value, patterns.token, function (match) {
756 return ["", template.filter(match.word),
757 template.highlightRegexp(match.function, patterns.string,
758 match => ["span", { highlight: "String" },
761 if (match.important == "!important")
762 return ["span", { highlight: "String" }, match.important];
764 return ["span", { highlight: "String" }, match.string];
765 return template._highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g,
767 ["span", { highlight: "Number" }, n],
768 ["span", { highlight: "Object" }, u || ""]
780 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
782 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: