1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/stylesheet/style.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,81 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 +"use strict"; 1.8 + 1.9 +module.metadata = { 1.10 + "stability": "experimental" 1.11 +}; 1.12 + 1.13 +const { Cc, Ci } = require("chrome"); 1.14 +const { Class } = require("../core/heritage"); 1.15 +const { ns } = require("../core/namespace"); 1.16 +const { URL } = require('../url'); 1.17 +const events = require("../system/events"); 1.18 +const { loadSheet, removeSheet, isTypeValid } = require("./utils"); 1.19 +const { isString } = require("../lang/type"); 1.20 +const { attachTo, detachFrom, getTargetWindow } = require("../content/mod"); 1.21 + 1.22 +const { freeze, create } = Object; 1.23 +const LOCAL_URI_SCHEMES = ['resource', 'data']; 1.24 + 1.25 +function isLocalURL(item) { 1.26 + try { 1.27 + return LOCAL_URI_SCHEMES.indexOf(URL(item).scheme) > -1; 1.28 + } 1.29 + catch(e) {} 1.30 + 1.31 + return false; 1.32 +} 1.33 + 1.34 +function Style({ source, uri, type }) { 1.35 + source = source == null ? null : freeze([].concat(source)); 1.36 + uri = uri == null ? null : freeze([].concat(uri)); 1.37 + type = type == null ? "author" : type; 1.38 + 1.39 + if (source && !source.every(isString)) 1.40 + throw new Error('Style.source must be a string or an array of strings.'); 1.41 + 1.42 + if (uri && !uri.every(isLocalURL)) 1.43 + throw new Error('Style.uri must be a local URL or an array of local URLs'); 1.44 + 1.45 + if (type && !isTypeValid(type)) 1.46 + throw new Error('Style.type must be "agent", "user" or "author"'); 1.47 + 1.48 + return freeze(create(Style.prototype, { 1.49 + "source": { value: source, enumerable: true }, 1.50 + "uri": { value: uri, enumerable: true }, 1.51 + "type": { value: type, enumerable: true } 1.52 + })); 1.53 +}; 1.54 + 1.55 +exports.Style = Style; 1.56 + 1.57 +attachTo.define(Style, function (style, window) { 1.58 + if (style.uri) { 1.59 + for (let uri of style.uri) 1.60 + loadSheet(window, uri, style.type); 1.61 + } 1.62 + 1.63 + if (style.source) { 1.64 + let uri = "data:text/css;charset=utf-8,"; 1.65 + 1.66 + uri += encodeURIComponent(style.source.join("")); 1.67 + 1.68 + loadSheet(window, uri, style.type); 1.69 + } 1.70 +}); 1.71 + 1.72 +detachFrom.define(Style, function (style, window) { 1.73 + if (style.uri) 1.74 + for (let uri of style.uri) 1.75 + removeSheet(window, uri); 1.76 + 1.77 + if (style.source) { 1.78 + let uri = "data:text/css;charset=utf-8,"; 1.79 + 1.80 + uri += encodeURIComponent(style.source.join("")); 1.81 + 1.82 + removeSheet(window, uri, style.type); 1.83 + } 1.84 +});