aboutsummaryrefslogtreecommitdiffstats
path: root/vanilla/node_modules/@acemir/cssom/lib/CSSStyleSheet.js
blob: 364607fb374efc4733523d3866d9034446bcb688 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//.CommonJS
var CSSOM = {
	MediaList: require("./MediaList").MediaList,
	StyleSheet: require("./StyleSheet").StyleSheet,
	CSSRuleList: require("./CSSRuleList").CSSRuleList,
	CSSStyleRule: require("./CSSStyleRule").CSSStyleRule,
};
var errorUtils = require("./errorUtils").errorUtils;
///CommonJS


/**
 * @constructor
 * @param {CSSStyleSheetInit} [opts] - CSSStyleSheetInit options.
 * @param {string} [opts.baseURL] - The base URL of the stylesheet.
 * @param {boolean} [opts.disabled] - The disabled attribute of the stylesheet.
 * @param {MediaList | string} [opts.media] - The media attribute of the stylesheet.
 * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet
 */
CSSOM.CSSStyleSheet = function CSSStyleSheet(opts) {
	CSSOM.StyleSheet.call(this);
	this.__constructed = true;
	this.__cssRules = new CSSOM.CSSRuleList();
	this.__ownerRule = null; 

	if (opts && typeof opts === "object") {
		if (opts.baseURL && typeof opts.baseURL === "string") {
			this.__baseURL = opts.baseURL;
		}
		if (opts.media && typeof opts.media === "string") {
			this.media.mediaText = opts.media;
		}
		if (typeof opts.disabled === "boolean") {
			this.disabled = opts.disabled;
		}
	}
};


CSSOM.CSSStyleSheet.prototype = Object.create(CSSOM.StyleSheet.prototype);
CSSOM.CSSStyleSheet.prototype.constructor = CSSOM.CSSStyleSheet;

Object.setPrototypeOf(CSSOM.CSSStyleSheet, CSSOM.StyleSheet);

Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "cssRules", {
	get: function() {
		return this.__cssRules;
	}
});

Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "rules", {
	get: function() {
		return this.__cssRules;
	}
});

Object.defineProperty(CSSOM.CSSStyleSheet.prototype, "ownerRule", {
	get: function() {
		return this.__ownerRule;
	}
});

/**
 * Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade.
 *
 *   sheet = new Sheet("body {margin: 0}")
 *   sheet.toString()
 *   -> "body{margin:0;}"
 *   sheet.insertRule("img {border: none}", 0)
 *   -> 0
 *   sheet.toString()
 *   -> "img{border:none;}body{margin:0;}"
 *
 * @param {string} rule
 * @param {number} [index=0]
 * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-insertRule
 * @return {number} The index within the style sheet's rule collection of the newly inserted rule.
 */
CSSOM.CSSStyleSheet.prototype.insertRule = function(rule, index) {
	if (rule === undefined && index === undefined) {
		errorUtils.throwMissingArguments(this, 'insertRule', this.constructor.name);
	}
	if (index === void 0) {
		index = 0;
	}
	index = Number(index);
	if (index < 0) {
		index = 4294967296 + index;
	}
	if (index > this.cssRules.length) {
		errorUtils.throwIndexError(this, 'insertRule', this.constructor.name, index, this.cssRules.length);
	}
	
	var ruleToParse = String(rule);
	var parseErrors = [];
	var parsedSheet = CSSOM.parse(ruleToParse, undefined, function(err) {
		parseErrors.push(err);
	} );
	if (parsedSheet.cssRules.length !== 1) {
		errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError');
	}
	var cssRule = parsedSheet.cssRules[0];
	
	// Helper function to find the last index of a specific rule constructor
	function findLastIndexOfConstructor(rules, constructorName) {
		for (var i = rules.length - 1; i >= 0; i--) {
			if (rules[i].constructor.name === constructorName) {
				return i;
			}
		}
		return -1;
	}
	
	// Helper function to find the first index of a rule that's NOT of specified constructors
	function findFirstNonConstructorIndex(rules, constructorNames) {
		for (var i = 0; i < rules.length; i++) {
			if (constructorNames.indexOf(rules[i].constructor.name) === -1) {
				return i;
			}
		}
		return rules.length;
	}
	
	// Validate rule ordering based on CSS specification
	if (cssRule.constructor.name === 'CSSImportRule') {
		if (this.__constructed === true) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Can't insert @import rules into a constructed stylesheet.",
				'SyntaxError');
		}
		// @import rules cannot be inserted after @layer rules that already exist
		// They can only be inserted at the beginning or after other @import rules
		var firstLayerIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']);
		if (firstLayerIndex < this.cssRules.length && this.cssRules[firstLayerIndex].constructor.name === 'CSSLayerStatementRule' && index > firstLayerIndex) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'HierarchyRequestError');
		}
		
		// Also cannot insert after @namespace or other rules
		var firstNonImportIndex = findFirstNonConstructorIndex(this.cssRules, ['CSSImportRule']);
		if (index > firstNonImportIndex && firstNonImportIndex < this.cssRules.length && 
		    this.cssRules[firstNonImportIndex].constructor.name !== 'CSSLayerStatementRule') {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'HierarchyRequestError');
		}
	} else if (cssRule.constructor.name === 'CSSNamespaceRule') {
		// @namespace rules can come after @layer and @import, but before any other rules
		// They cannot come before @import rules
		var firstImportIndex = -1;
		for (var i = 0; i < this.cssRules.length; i++) {
			if (this.cssRules[i].constructor.name === 'CSSImportRule') {
				firstImportIndex = i;
				break;
			}
		}
		var firstNonImportNamespaceIndex = findFirstNonConstructorIndex(this.cssRules, [
			'CSSLayerStatementRule', 
			'CSSImportRule', 
			'CSSNamespaceRule'
		]);
		
		// Cannot insert before @import rules
		if (firstImportIndex !== -1 && index <= firstImportIndex) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'HierarchyRequestError');
		}
		
		// Cannot insert if there are already non-special rules
		if (firstNonImportNamespaceIndex < this.cssRules.length) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'InvalidStateError');
		}
		
		// Cannot insert after other types of rules
		if (index > firstNonImportNamespaceIndex) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'HierarchyRequestError');
		}

		
	} else if (cssRule.constructor.name === 'CSSLayerStatementRule') {
		// @layer statement rules can be inserted anywhere before @import and @namespace
		// No additional restrictions beyond what's already handled
	} else {
		// Any other rule cannot be inserted before @import and @namespace
		var firstNonSpecialRuleIndex = findFirstNonConstructorIndex(this.cssRules, [
			'CSSLayerStatementRule',
			'CSSImportRule',
			'CSSNamespaceRule'
		]);
		
		if (index < firstNonSpecialRuleIndex) {
			errorUtils.throwError(this, 'DOMException',
				"Failed to execute 'insertRule' on '" + this.constructor.name + "': Failed to insert the rule.",
				'HierarchyRequestError');
		}

		if (parseErrors.filter(function(error) { return !error.isNested; }).length !== 0) {
			errorUtils.throwParseError(this, 'insertRule', this.constructor.name, ruleToParse, 'SyntaxError');
		}
	}
	
	cssRule.__parentStyleSheet = this;
	this.cssRules.splice(index, 0, cssRule);
	return index;
};

CSSOM.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index) {
	if (index === void 0) {
		index = this.cssRules.length;
	}
	this.insertRule(selector + "{" + styleBlock + "}", index);
	return -1;
};

/**
 * Used to delete a rule from the style sheet.
 *
 *   sheet = new Sheet("img{border:none} body{margin:0}")
 *   sheet.toString()
 *   -> "img{border:none;}body{margin:0;}"
 *   sheet.deleteRule(0)
 *   sheet.toString()
 *   -> "body{margin:0;}"
 *
 * @param {number} index within the style sheet's rule list of the rule to remove.
 * @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleSheet-deleteRule
 */
CSSOM.CSSStyleSheet.prototype.deleteRule = function(index) {
	if (index === undefined) {
		errorUtils.throwMissingArguments(this, 'deleteRule', this.constructor.name);
	}
	index = Number(index);
	if (index < 0) {
		index = 4294967296 + index;
	}
	if (index >= this.cssRules.length) {
		errorUtils.throwIndexError(this, 'deleteRule', this.constructor.name, index, this.cssRules.length);
	}
	if (this.cssRules[index]) {		
		if (this.cssRules[index].constructor.name == "CSSNamespaceRule") {
			var shouldContinue = this.cssRules.every(function (rule) {
				return ['CSSImportRule','CSSLayerStatementRule','CSSNamespaceRule'].indexOf(rule.constructor.name) !== -1
			});
			if (!shouldContinue) {
				errorUtils.throwError(this, 'DOMException', "Failed to execute 'deleteRule' on '" + this.constructor.name + "': Failed to delete rule.", "InvalidStateError");
			}
		}
		if (this.cssRules[index].constructor.name == "CSSImportRule") {
			this.cssRules[index].styleSheet.__parentStyleSheet = null;
		}

		this.cssRules[index].__parentStyleSheet = null;
	}
	this.cssRules.splice(index, 1);
};

CSSOM.CSSStyleSheet.prototype.removeRule = function(index) {
	if (index === void 0) {
		index = 0;
	}
	this.deleteRule(index);
};


/**
 * Replaces the rules of a {@link CSSStyleSheet}
 * 
 * @returns a promise
 * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replace
 */
CSSOM.CSSStyleSheet.prototype.replace = function(text) {
	var _Promise;
	if (this.__globalObject && this.__globalObject['Promise']) {
		_Promise = this.__globalObject['Promise'];
	} else {
		_Promise = Promise;
	}
	var _setTimeout;
	if (this.__globalObject && this.__globalObject['setTimeout']) {
		_setTimeout = this.__globalObject['setTimeout'];
	} else {
		_setTimeout = setTimeout;
	}
	var sheet = this;
	return new _Promise(function (resolve, reject) {
		// If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
		if (!sheet.__constructed || sheet.__disallowModification) {
			reject(errorUtils.createError(sheet, 'DOMException',
				"Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.",
				'NotAllowedError'));
		}
		// Set the disallow modification flag.
		sheet.__disallowModification = true;

		// In parallel, do these steps:
		_setTimeout(function() {
			// Let rules be the result of running parse a stylesheet's contents from text.
			var rules = new CSSOM.CSSRuleList();
			CSSOM.parse(text, { styleSheet: sheet, cssRules: rules });
			// If rules contains one or more @import rules, remove those rules from rules.
			var i = 0;
			while (i < rules.length) {
				if (rules[i].constructor.name === 'CSSImportRule') {
					rules.splice(i, 1);
				} else {
					i++;
				}
			}
			// Set sheet's CSS rules to rules.
			sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules));
			// Unset sheet’s disallow modification flag.
			delete sheet.__disallowModification;
			// Resolve promise with sheet.
			resolve(sheet);
		})
	});
}

/**
 * Synchronously replaces the rules of a {@link CSSStyleSheet}
 * 
 * @see https://www.w3.org/TR/cssom-1/#dom-cssstylesheet-replacesync
 */
CSSOM.CSSStyleSheet.prototype.replaceSync = function(text) {
	var sheet = this;
	// If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
	if (!sheet.__constructed || sheet.__disallowModification) {
		errorUtils.throwError(sheet, 'DOMException',
			"Failed to execute 'replaceSync' on '" + sheet.constructor.name + "': Not allowed.",
			'NotAllowedError');
	}
	// Let rules be the result of running parse a stylesheet's contents from text.
	var rules = new CSSOM.CSSRuleList();
	CSSOM.parse(text, { styleSheet: sheet, cssRules: rules });
	// If rules contains one or more @import rules, remove those rules from rules.
	var i = 0;
	while (i < rules.length) {
		if (rules[i].constructor.name === 'CSSImportRule') {
			rules.splice(i, 1);
		} else {
			i++;
		}
	}
	// Set sheet's CSS rules to rules.
	sheet.__cssRules.splice.apply(sheet.__cssRules, [0, sheet.__cssRules.length].concat(rules));
}

/**
 * NON-STANDARD
 * @return {string} serialize stylesheet
 */
CSSOM.CSSStyleSheet.prototype.toString = function() {
	var result = "";
	var rules = this.cssRules;
	for (var i=0; i<rules.length; i++) {
		result += rules[i].cssText + "\n";
	}
	return result;
};


//.CommonJS
exports.CSSStyleSheet = CSSOM.CSSStyleSheet;
CSSOM.parse = require('./parse').parse; // Cannot be included sooner due to the mutual dependency between parse.js and CSSStyleSheet.js
///CommonJS