-
Notifications
You must be signed in to change notification settings - Fork 343
/
css.js
2000 lines (1778 loc) · 49.3 KB
/
css.js
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* See license.txt for terms of usage */
/*global define:1, Components:1, Firebug:1, CSSRule:1, CSSStyleRule:1, CSSImportRule:1, Node:1*/
define([
"firebug/lib/trace",
"firebug/lib/array",
"firebug/lib/url",
"firebug/lib/options",
"firebug/lib/xml",
"firebug/lib/http",
"firebug/lib/xpath",
"firebug/chrome/window",
],
function(FBTrace, Arr, Url, Options, Xml, Http, Xpath, Win) {
// ********************************************************************************************* //
// Constants
var Ci = Components.interfaces;
var Cc = Components.classes;
var TraceError = FBTrace.toError();
var Trace = FBTrace.to("DBG_CSS");
// ********************************************************************************************* //
// Module Implementation
var Css = {};
// ********************************************************************************************* //
// CSS
var cssKeywordMap = null;
var cachedPropNames = null;
var domUtils = Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils);
var universalValues = new Set(["initial", "inherit", "unset"]);
function expandKeywordList(list)
{
var res = [];
for (var prop of list)
{
var keywords = Css.cssKeywords[prop];
if (keywords)
res.push.apply(res, keywords);
else
res.push(prop);
}
return res;
}
function initPropertyData()
{
if (cssKeywordMap)
return;
cssKeywordMap = {};
// Create the list of property names through the help of inIDOMUtils.
// This includes also SVG presentational attributes, so filter the names
// into two groups based on that. Also remove -moz-math-display and
// -moz-script-level from the list, as they are impossible to set (they are
// internal helpers for MathML).
var props = new Set(domUtils.getCSSPropertyNames(domUtils.INCLUDE_ALIASES));
props.delete("-moz-math-display");
props.delete("-moz-script-level");
var htmlProps = [], svgProps = [];
for (let prop of props)
{
let html = !svgPresentationalProperties.has(prop);
let svg = !html || svgInheritedFromHtml.has(prop);
if (html)
htmlProps.push(prop);
if (svg)
svgProps.push(prop);
}
cachedPropNames = {
html: htmlProps.sort(),
svg: svgProps.sort(),
mathml: []
};
// Set up a map of property values. Let's start with some helpers for
// munging the property data given to us by the API.
// We block initial, inherit and unset from appearing in results, instead
// we manually add them to auto-completion when they constitute the only
// value in an editor. Some prexed values are also removed in favor of
// standardized equivalents.
var forbiddenValues = new Set(universalValues.values());
forbiddenValues.add("-moz-calc");
forbiddenValues.add("-moz-linear-gradient");
forbiddenValues.add("-moz-radial-gradient");
forbiddenValues.add("-moz-repeating-linear-gradient");
forbiddenValues.add("-moz-repeating-radial-gradient");
var filterValues = function(list)
{
return list.filter((value) => !forbiddenValues.has(value));
};
// The API doesn't indicate whether a value represents a function or not,
// so we hard-code a list and add parens to any known returned function.
// We also camel-case some SVG property values to make them more readable.
var functionNames = new Set([
"url", "calc", "rect", "hsl", "hsla", "rgb", "rgba",
"-moz-element", "-moz-image-rect",
"linear-gradient", "radial-gradient",
"repeating-linear-gradient", "repeating-radial-gradient",
"cubic-bezier", "steps", "attr", "counter", "counters",
"matrix", "matrix3d", "rotate", "rotateX", "rotateY", "rotateZ",
"scale", "scaleX", "scaleY", "scaleZ", "scale3d", "skewX", "skewY",
"translate", "translateX", "translateY", "translateZ",
]);
var convertCase = new Map();
for (let value of ["linearRGB", "sRGB", "geometricPrecision",
"optimizeQuality", "optimizeSpeed", "optimizeLegibility", "crispEdges",
"visibleFill", "visiblePainted", "visibleStroke"])
{
convertCase.set(value.toLowerCase(), value);
}
var transformPropertyValue = function(value)
{
if (functionNames.has(value))
value += "()";
if (convertCase.has(value))
return convertCase.get(value);
return value;
};
// Some values are simply missing from the API. Add those when detected.
var addMissingValues = function(values, propName)
{
if (propName === "transition" || propName === "transition-property")
values = values.concat(animatableProperties);
// "currentColor", system colors, Mozilla-specific colors, see bug 927367
if (values.indexOf("aqua") !== -1)
values = values.concat(extraColors);
// Gradients, see bug 973345
// xxxsz: Can be removed when Firefox 31 is the minimum supported version
if (values.indexOf("-moz-element()") !== -1)
values = values.concat(extraImages);
return values;
};
// Set up part of the data tables.
Css.cssKeywords.color = getColorValues();
for (let prop of props)
{
var values;
// See if the property is special-cased due to missing or incorrect values.
if (cssDataExceptions.hasOwnProperty(prop))
{
values = expandKeywordList(cssDataExceptions[prop]);
}
else
{
values = domUtils.getCSSValuesForProperty(prop);
values = filterValues(values);
values = values.map(transformPropertyValue);
values = addMissingValues(values, prop);
}
cssKeywordMap[prop] = Arr.sortUnique(values);
}
}
Css.getCSSKeywordsByProperty = function(nodeType, propName, avoid)
{
initPropertyData();
// CSS isn't supported for MathML elements.
if (nodeType === "mathml")
return [];
// For other kinds of elements, return keywords from the global pool of
// properties, not just the ones specific to the nodeType, since:
// a) it's simpler,
// b) technically the CSS is still valid.
propName = propName.toLowerCase();
if (!cssKeywordMap.hasOwnProperty(propName))
return [];
// Special case: most "pointer-events" values are only supported for SVG.
if (nodeType === "html" && propName === "pointer-events")
return ["auto", "none"];
if (avoid)
return getCSSPropertyKeywordsExcludingCategories(propName, avoid);
return cssKeywordMap[propName];
};
function assertShorthand(propName)
{
// Currently getCSSPropertyKeywordsExcludingCategories and getCSSShorthandCategory
// only support background, border and font, assert that nothing else gets passed
// in so we don't get subtle failures. Ideally this would be extended to any
// shorthand property in the future. (See also css/autoCompleter.js.)
if (["background", "border", "font"].indexOf(propName) === -1)
throw new Error("invalid shorthand name " + propName);
}
function getCSSPropertyKeywordsExcludingCategories(propName, avoid)
{
assertShorthand(propName);
var list = [];
var types = cssDataExceptions[propName];
for (var i = 0; i < types.length; ++i)
{
var type = types[i];
if (avoid.indexOf(type) !== -1)
continue;
var keywords = Css.cssKeywords[type];
if (keywords)
list.push.apply(list, keywords);
else
list.push(type);
}
return list;
}
Css.getCSSPropertyNames = function(nodeType)
{
initPropertyData();
return cachedPropNames[nodeType];
};
Css.getCSSShorthandCategory = function(nodeType, shorthandProp, keyword)
{
initPropertyData();
assertShorthand(shorthandProp);
var category = null;
var types = cssDataExceptions[shorthandProp];
for (var i = 0; i < types.length; ++i)
{
var type = types[i], matches;
if (type in Css.cssKeywords)
matches = (Css.cssKeywords[type].indexOf(keyword) !== -1);
else
matches = (type === keyword);
if (matches)
{
// Set this as the matched category, or if there is one already
// bail out (we don't have a unique one).
if (category)
return null;
category = type;
}
}
return category;
};
/**
* Parses the CSS properties of a CSSStyleRule
* @param {Object} style CSSStyleRule to get the properties of
* @param {Object} element Element to which the style applies. Needed for parsing
* shorthand properties correctly.
*
* @returns {Array} Properties represented by {name, value, priority, longhandProps}
*/
Css.parseCSSProps = function(style, element)
{
var props = [];
if (!element)
{
for (var i = 0, len = style.length; i < len; ++i)
{
var prop = style.item(i);
props.push({name: prop,
value: style.getPropertyValue(prop),
priority: style.getPropertyPriority(longhandProp)});
}
}
else
{
var lineRE = /(?:[^;\(]*(?:\([^\)]*?\))?[^;\(]*)*;?/g;
var propRE = /\s*([^:\s]*)\s*:\s*(.*?)\s*(?:! (important))?;?$/;
var lines = style.cssText.match(lineRE);
for (var i = 0, len = lines.length; i < len; ++i)
{
var match = propRE.exec(lines[i]);
if (!match)
continue;
if (match[2])
{
var prop = {name: match[1], value: match[2], priority: match[3] || ""};
// Add longhand properties to shorthand property
var doc = element.ownerDocument;
var dummyElement = doc.createElementNS(element.namespaceURI, element.tagName);
var dummyStyle = dummyElement.style;
dummyStyle.cssText = "";
dummyStyle.setProperty(prop.name, prop.value, prop.priority);
if (dummyStyle.length > 1)
{
prop.longhandProps = [];
for (var j = 0, propLen = dummyStyle.length; j < propLen; ++j)
{
var longhandProp = dummyStyle.item(j);
prop.longhandProps.push({name: longhandProp,
value: dummyStyle.getPropertyValue(longhandProp),
priority: dummyStyle.getPropertyPriority(longhandProp)});
}
}
props.push(prop);
}
}
}
return props;
};
function getColorValues()
{
return domUtils.getCSSValuesForProperty("color")
.filter((value) => !universalValues.has(value))
.concat(extraColors);
}
var colorKeywordSet = null;
Css.isColorKeyword = function(keyword)
{
if (keyword == "transparent")
return false;
if (!colorKeywordSet)
colorKeywordSet = new Set(getColorValues().map((color) => color.toLowerCase()));
return colorKeywordSet.has(keyword.toLowerCase());
};
var reImageProperty = /(^background|image)$/;
Css.isImageProperty = function(propName)
{
return reImageProperty.test(propName);
};
Css.copyTextStyles = function(fromNode, toNode, style)
{
var view = fromNode ? fromNode.ownerDocument.defaultView : null;
if (view)
{
if (!style)
style = view.getComputedStyle(fromNode, "");
toNode.style.fontFamily = style.fontFamily;
toNode.style.fontSize = style.fontSize;
toNode.style.fontWeight = style.fontWeight;
toNode.style.fontStyle = style.fontStyle;
toNode.style.fontSizeAdjust = style.fontSizeAdjust;
toNode.style.fontStretch = style.fontStretch;
toNode.style.fontVariant = style.fontVariant;
toNode.style.MozFontFeatureSettings = style.MozFontFeatureSettings;
return style;
}
};
Css.copyBoxStyles = function(fromNode, toNode, style)
{
var view = fromNode.ownerDocument.defaultView;
if (view)
{
if (!style)
style = view.getComputedStyle(fromNode, "");
toNode.style.marginTop = style.marginTop;
toNode.style.marginRight = style.marginRight;
toNode.style.marginBottom = style.marginBottom;
toNode.style.marginLeft = style.marginLeft;
toNode.style.borderTopWidth = style.borderTopWidth;
toNode.style.borderRightWidth = style.borderRightWidth;
toNode.style.borderBottomWidth = style.borderBottomWidth;
toNode.style.borderLeftWidth = style.borderLeftWidth;
toNode.style.unicodeBidi = style.unicodeBidi;
return style;
}
};
Css.readBoxStyles = function(style)
{
const styleNames = {
"margin-top": "marginTop", "margin-right": "marginRight",
"margin-left": "marginLeft", "margin-bottom": "marginBottom",
"border-top-width": "borderTop", "border-right-width": "borderRight",
"border-left-width": "borderLeft", "border-bottom-width": "borderBottom",
"padding-top": "paddingTop", "padding-right": "paddingRight",
"padding-left": "paddingLeft", "padding-bottom": "paddingBottom",
"z-index": "zIndex"
};
var styles = {};
for (var styleName in styleNames)
styles[styleNames[styleName]] = parseInt(style.getPropertyCSSValue(styleName).cssText) || 0;
Trace.sysout("css.readBoxStyles;", styles);
return styles;
};
Css.getBoxFromStyles = function(style, element)
{
var args = Css.readBoxStyles(style);
args.width = element.offsetWidth
- (args.paddingLeft+args.paddingRight+args.borderLeft+args.borderRight);
args.height = element.offsetHeight
- (args.paddingTop+args.paddingBottom+args.borderTop+args.borderBottom);
return args;
};
Css.getElementCSSSelector = function(element)
{
if (!element || !element.localName)
return "null";
var label = Xml.getLocalName(element);
if (element.id)
label += "#" + element.id;
if (element.classList)
{
for (var i=0, len=element.classList.length; i<len; ++i)
label += "." + element.classList[i];
}
return label;
};
Css.getElementCSSPath = function(element)
{
var paths = [];
for (; element && element.nodeType == Node.ELEMENT_NODE; element = element.parentNode)
{
var selector = Css.getElementCSSSelector(element);
paths.splice(0, 0, selector);
}
return paths.length ? paths.join(" ") : null;
};
// ********************************************************************************************* //
// CSS classes
var classNameReCache = {};
Css.hasClass = function(node, name)
{
if (!node || node.nodeType != Node.ELEMENT_NODE || !node.className ||
typeof(node.className) != "string" || !name)
{
return false;
}
if (name.indexOf(" ") != -1)
{
var classes = name.split(" ");
var len = classes.length;
var found = false;
for (var i = 0; i < len; i++)
{
var cls = classes[i].trim();
if (cls != "")
{
if (Css.hasClass(node, cls) == false)
return false;
found = true;
}
}
return found;
}
var re;
if (name.indexOf("-") == -1)
{
re = classNameReCache[name] = classNameReCache[name] ||
new RegExp('(^|\\s)' + name + '(\\s|$)', "g");
}
else
{
// XXXsroussey don't cache these, they are often setting values.
// Should be using setUserData/getUserData???
re = new RegExp('(^|\\s)' + name + '(\\s|$)', "g");
}
return node.className.search(re) != -1;
};
Css.setClass = function(node, name)
{
if (!node || node.nodeType != Node.ELEMENT_NODE || name == '')
return;
if (name.indexOf(" ") != -1)
{
var classes = name.split(" "), len = classes.length;
for (var i = 0; i < len; i++)
{
var cls = classes[i].trim();
if (cls != "")
{
Css.setClass(node, cls);
}
}
return;
}
if (!Css.hasClass(node, name))
node.className = node.className.trim() + " " + name;
};
Css.getClassValue = function(node, name)
{
var re = new RegExp(name+"-([^ ]+)");
var m = re.exec(node.className);
return m ? m[1] : "";
};
Css.removeClass = function(node, name)
{
if (!node || node.nodeType != Node.ELEMENT_NODE || node.className == '' || name == '')
return;
if (name.indexOf(" ") != -1)
{
var classes = name.split(" "), len = classes.length;
for (var i = 0; i < len; i++)
{
var cls = classes[i].trim();
if (cls != "")
{
if (Css.hasClass(node, cls) == false)
Css.removeClass(node, cls);
}
}
return;
}
var re;
if (name.indexOf("-") == -1)
re = classNameReCache[name] = classNameReCache[name] || new RegExp('(^|\\s)' + name + '(\\s|$)', "g");
else // XXXsroussey don't cache these, they are often setting values. Should be using setUserData/getUserData???
re = new RegExp('(^|\\s)' + name + '(\\s|$)', "g");
node.className = node.className.replace(re, " ");
};
Css.toggleClass = function(elt, name)
{
if (Css.hasClass(elt, name))
Css.removeClass(elt, name);
else
Css.setClass(elt, name);
};
Css.obscure = function(elt, obscured)
{
if (obscured)
Css.setClass(elt, "obscured");
else
Css.removeClass(elt, "obscured");
};
Css.setClassTimed = function(elt, name, context, timeout)
{
if (Trace.active)
{
Trace.sysout("css.setClassTimed; elt.__setClassTimeout: " + elt.__setClassTimeout +
" Xml.isVisible(elt): " + Xml.isVisible(elt) +
" elt.__invisibleAtSetPoint: " + elt.__invisibleAtSetPoint);
}
if (!timeout)
timeout = 1300;
if (elt.__setClassTimeout) // then we are already waiting to remove the class mark
context.clearTimeout(elt.__setClassTimeout); // reset the timer
else // then we are not waiting to remove the mark
Css.setClass(elt, name);
if (!Xml.isVisible(elt))
{
if (elt.__invisibleAtSetPoint)
elt.__invisibleAtSetPoint--;
else
elt.__invisibleAtSetPoint = 5;
}
else
{
delete elt.__invisibleAtSetPoint;
}
elt.__setClassTimeout = context.setTimeout(function()
{
delete elt.__setClassTimeout;
if (elt.__invisibleAtSetPoint) // then user can't see it, try again later
Css.setClassTimed(elt, name, context, timeout);
else
{
delete elt.__invisibleAtSetPoint; // may be zero
Css.removeClass(elt, name);
}
}, timeout);
};
Css.cancelClassTimed = function(elt, name, context)
{
if (elt.__setClassTimeout)
{
Css.removeClass(elt, name);
context.clearTimeout(elt.__setClassTimeout);
delete elt.__setClassTimeout;
}
};
Css.safeGetCSSRules = function(styleSheet)
{
try
{
return styleSheet.cssRules;
}
catch (e)
{
TraceError.sysout("css.safeGetCSSRules; EXCEPTION " + e, e);
}
return null;
};
Css.isValidStylesheet = function(styleSheet)
{
try
{
// See if the getter triggers an exception. "void" is there to silence jshint.
void styleSheet.cssRules;
return true;
}
catch (exc)
{
TraceError.sysout("css.isValidStylesheet; EXCEPTION " + exc, exc);
}
return false;
};
// ********************************************************************************************* //
// Stylesheet API
Css.shouldIgnoreSheet = function(sheet)
{
// Ignore by the regular method, except for default stylesheets that are
// used in case there is no other stylesheet.
if (sheet.defaultStylesheet)
return false;
return (sheet.ownerNode && Firebug.shouldIgnore(sheet.ownerNode));
};
Css.createStyleSheet = function(doc, url)
{
var style = doc.createElementNS("http://www.w3.org/1999/xhtml", "style");
style.setAttribute("charset", "utf-8");
style.setAttribute("type", "text/css");
var cssText = url ? Http.getResource(url, true) : null;
if (cssText)
{
var index = url.lastIndexOf("/");
var absURL = url.substr(0, index+1);
// Replace all relative URLs with absolute (using the passed url).
// Note that stylesheets can come from various extensions and the source can
// be even used in a browser env where relative URLs make more sense.
var expr = /url\(([\'"]?)(?![\'"]?(?:[a-z]+:|\/))/gi;
cssText = cssText.replace(expr, "url($1" + absURL);
style.textContent = cssText;
}
Firebug.setIgnored(style);
return style;
};
Css.addStyleSheet = function(doc, style)
{
var heads = doc.getElementsByTagName("head");
if (heads.length)
{
heads[0].appendChild(style);
}
else if (doc.documentElement)
{
doc.documentElement.appendChild(style);
}
else
{
TraceError.sysout("css.addStyleSheet; ERROR to append a stylesheet");
}
};
Css.appendStylesheet = function(doc, uri)
{
// Make sure the stylesheet is not appended twice.
var styleSheet = doc.getElementById(uri);
if (styleSheet)
return styleSheet;
styleSheet = Css.createStyleSheet(doc, uri);
styleSheet.setAttribute("id", uri);
Css.addStyleSheet(doc, styleSheet);
return styleSheet;
};
Css.getStyleSheetByHref = function(url, context)
{
if (!context.styleSheetMap)
Css.createStyleSheetMap(context); // fill cache
// hasOwnProperty is called to prevent possible conflicts with prototype extensions
// and strict mode warnings
return context.styleSheetMap.hasOwnProperty(url) ? context.styleSheetMap[url] : undefined;
};
Css.createStyleSheetMap = function(context)
{
context.styleSheetMap = {};
function addSheet(sheet)
{
var sheetURL = Css.getURLForStyleSheet(sheet);
context.styleSheetMap[sheetURL] = sheet;
// recurse for imported sheets
for (var i = 0; i < sheet.cssRules.length; ++i)
{
var rule = sheet.cssRules[i];
if (rule instanceof CSSStyleRule)
{
if (rule.type == CSSRule.STYLE_RULE) // once we get here no more imports
return;
}
else if (rule instanceof CSSImportRule)
{
addSheet(rule.styleSheet);
}
}
}
Win.iterateWindows(context.window, function(subwin)
{
var rootSheets = subwin.document.styleSheets;
if (!rootSheets)
return; // XUL?
for (var i = 0; i < rootSheets.length; ++i)
{
try
{
addSheet(rootSheets[i]);
}
catch (err)
{
//TraceError.sysout("css.createStyleSheetMap; EXCEPTION " + err, err);
}
}
});
Trace.sysout("css.createStyleSheetMap; for " + context.getName(), context.styleSheetMap);
return context.styleSheetMap;
};
Css.getAllStyleSheets = function(context)
{
if (!context)
return [];
var styleSheets = [];
var showUACSS = Options.get("showUserAgentCSS");
function addSheet(sheet)
{
var sheetLocation = Css.getURLForStyleSheet(sheet);
if (!showUACSS && Url.isSystemURL(sheetLocation))
return;
if (Css.shouldIgnoreSheet(sheet))
return;
styleSheets.push(sheet);
try
{
for (var i = 0; i < sheet.cssRules.length; ++i)
{
var rule = sheet.cssRules[i];
if (rule instanceof CSSImportRule)
addSheet(rule.styleSheet);
}
}
catch (e)
{
TraceError.sysout("css.getAllStyleSheets; sheet.cssRules FAILS for " +
(sheet ? sheet.href : "null sheet") + e, e);
}
}
Win.iterateWindows(context.window, function(subwin)
{
var rootSheets = subwin.document.styleSheets;
for (var i = 0; i < rootSheets.length; ++i)
addSheet(rootSheets[i]);
});
return styleSheets;
};
Css.getURLForStyleSheet = function(styleSheet)
{
// http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheet.
// For inline style sheets, the value of this attribute is null.
if (!styleSheet.href && !styleSheet.ownerNode)
return null;
return (styleSheet.href ? styleSheet.href : styleSheet.ownerNode.ownerDocument.documentURI);
};
/**
* Retrieves the instance number for a given style sheet. The instance number
* is sheet's index within the set of all other sheets whose URL is the same.
*/
Css.getInstanceForStyleSheet = function(styleSheet, ownerDocument)
{
// ownerDocument is an optional hint for performance
if (Trace.active)
{
Trace.sysout("css.getInstanceForStyleSheet; href:" + styleSheet.href + " mediaText:" +
styleSheet.media.mediaText + " path to ownerNode" +
(styleSheet.ownerNode && Xpath.getElementXPath(styleSheet.ownerNode)), ownerDocument);
}
ownerDocument = ownerDocument || Css.getDocumentForStyleSheet(styleSheet);
if (!ownerDocument)
return;
var ret = 0,
styleSheets = ownerDocument.styleSheets,
href = styleSheet.href;
for (var i = 0; i < styleSheets.length; i++)
{
var curSheet = styleSheets[i];
if (Trace.active)
{
Trace.sysout("css.getInstanceForStyleSheet; compare href " + i +
" " + curSheet.href + " " + curSheet.media.mediaText + " " +
(curSheet.ownerNode && Xpath.getElementXPath(curSheet.ownerNode)));
}
if (Css.shouldIgnoreSheet(curSheet))
break;
if (curSheet == styleSheet)
break;
if (curSheet.href == href)
ret++;
}
return ret;
};
Css.getDocumentForStyleSheet = function(styleSheet)
{
if (!styleSheet)
return;
while (styleSheet.parentStyleSheet && !styleSheet.ownerNode)
styleSheet = styleSheet.parentStyleSheet;
if (styleSheet.ownerNode)
return styleSheet.ownerNode.ownerDocument;
};
// ********************************************************************************************* //
Css.stripUnits = function(value)
{
// remove units from '0px', '0em' etc. leave non-zero units in-tact.
return value.replace(/(url\(.*?\)|[^0]\S*\s*)|0(%|em|ex|px|in|cm|mm|pt|pc)(\s|$)/gi,
function(_, skip, remove, whitespace)
{
return skip || ('0' + whitespace);
}
);
};
Css.extractURLs = function(value)
{
var urls = [];
var urlValues = value.match(/url\((["']).*?\1\)/g);
for (var i in urlValues)
urls.push(urlValues[i].replace(/url\((["'])(.*?)\1\)/, "$2"));
return urls;
};
Css.colorNameToRGB = function(value)
{
if (!domUtils.colorNameToRGB)
return value;
var reSplit = /(\(|,|\)|\s)/;
var parts = value.split(reSplit);
var newValue = "";
for (var i=0, len=parts.length; i<len; ++i)
{
var part = parts[i];
if (part === "transparent")
{
newValue += "rgba(0, 0, 0, 0)";
}
else
{
if (Css.isColorKeyword(part))
{
try
{
var rgbValue = domUtils.colorNameToRGB(part);
newValue += "rgb(" + rgbValue.r + ", " + rgbValue.g + ", " + rgbValue.b + ")";
}
catch(e)
{
// Color keyword is a system color, which can't be resolved by
// domUtils.colorNameToRGB(), so just return the keyword itself
// (see issue 6753)
newValue += part;
}
}
else
{
newValue += part;
}
}
}
return newValue;
};
Css.rgbToHex = function(value)
{
function convertRGBToHex(r, g, b)
{
return "#" + ((1 << 24) + (r << 16) + (g << 8) + (b << 0)).
toString(16).substr(-6);
}
value = Css.colorNameToRGB(value);
return value.replace(/\brgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi,
function(_, r, g, b) {
return convertRGBToHex(r, g, b);
});
};
Css.rgbToHSL = function(value)
{
function convertRGBToHSL(r, g, b, a)
{
r = parseInt(r);
g = parseInt(g);
b = parseInt(b);
var gray = (r == g && g == b);
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b);