forked from squizlabs/HTML_CodeSniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTMLCS.js
1412 lines (1243 loc) · 50.9 KB
/
HTMLCS.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
/**
* +--------------------------------------------------------------------+
* | This HTML_CodeSniffer file is Copyright (c) |
* | Squiz Pty Ltd (ABN 77 084 670 600) |
* +--------------------------------------------------------------------+
* | IMPORTANT: Your use of this Software is subject to the terms of |
* | the Licence provided in the file licence.txt. If you cannot find |
* | this file please contact Squiz (www.squiz.com.au) so we may |
* | provide you a copy. |
* +--------------------------------------------------------------------+
*
*/
var HTMLCS = new function()
{
var _standards = {};
var _sniffs = [];
var _tags = {};
var _standard = null;
var _currentSniff = null;
var _messages = [];
var _msgOverrides = {};
/*
Message type constants.
*/
this.ERROR = 1;
this.WARNING = 2;
this.NOTICE = 3;
/**
* Loads the specifid standard and run the sniffs.
*
* @param {String} standard The name of the standard to load.
* @param {String|Node} An HTML string or a DOM node object.
* @param {Function} The function that will be called when the testing is completed.
*/
this.process = function(standard, content, callback) {
// Clear previous runs.
_standards = {};
_sniffs = [];
_tags = {};
_standard = null;
if (!content) {
return false;
}
if (_standards[_getStandardPath(standard)]) {
HTMLCS.run(callback, content);
} else {
this.loadStandard(standard, function() {
HTMLCS.run(callback, content);
});
}
};
/**
* Loads the specified standard and its sniffs.
*
* @param {String} standard The name of the standard to load.
* @param {Function} callback The function to call once the standard is loaded.
*/
this.loadStandard = function(standard, callback) {
if (!standard) {
return false;
}
_includeStandard(standard, function() {
_standard = standard;
callback.call(this);
});
};
/**
* Runs the sniffs for the loaded standard.
*
* @param {Function} callback The function to call once all sniffs are completed.
* @param {String|Node} content An HTML string or a DOM node object.
*/
this.run = function(callback, content) {
var element = null;
var loadingFrame = false;
if (typeof content === 'string') {
loadingFrame = true;
var elementFrame = document.createElement('iframe');
elementFrame.style.display = 'none';
elementFrame = document.body.insertBefore(elementFrame, null);
if (elementFrame.contentDocument) {
element = elementFrame.contentDocument;
} else if (element.contentWindow) {
element = elementFrame.contentWindow.document;
}
elementFrame.load = function() {
this.onreadystatechange = null;
this.onload = null;
if (HTMLCS.isFullDoc(content) === false) {
element = element.getElementsByTagName('body')[0];
var div = element.getElementsByTagName('div')[0];
if (div && (div.id === '__HTMLCS-source-wrap')) {
div.id = '';
element = div;
}
}
var elements = _getAllTags(element);
elements.unshift(element);
_run(elements, element, callback);
}
// Satisfy IE which doesn't like onload being set dynamically.
elementFrame.onreadystatechange = function() {
if (/^(complete|loaded)$/.test(this.readyState) === true) {
this.onreadystatechange = null;
this.load();
}
}
elementFrame.onload = elementFrame.load;
if ((HTMLCS.isFullDoc(content) === false) && (content.indexOf('<body') === -1)) {
element.write('<div id="__HTMLCS-source-wrap">' + content + '</div>');
} else {
element.write(content);
}
element.close();
} else {
element = content;
}
if (!element) {
callback.call(this);
return;
}
callback = callback || function() {};
_messages = [];
// Get all the elements in the parent element.
// Add the parent element too, which will trigger "_top" element codes.
var elements = _getAllTags(element);
elements.unshift(element);
// Run the sniffs.
if (loadingFrame === false) {
_run(elements, element, callback);
}
};
/**
* Returns true if the content passed appears to be from a full document.
*
* With string content, we consider a full document as the presence of <html>,
* or <head> + <body> elements. For an element, only the 'html' element (the
* document element) is accepted.
*
* @param {String|Node} content An HTML string or a DOM node object.
*
* @returns {Boolean}
*/
this.isFullDoc = function(content) {
var fullDoc = false;
if (typeof content === 'string') {
if (content.toLowerCase().indexOf('<html') !== -1) {
fullDoc = true;
} else if ((content.toLowerCase().indexOf('<head') !== -1) && (content.toLowerCase().indexOf('<body') !== -1)) {
fullDoc = true;
}
} else {
// If we are the document, or the document element.
if ((content.nodeName.toLowerCase() === 'html') || (content.documentElement)) {
fullDoc = true;
}
}
return fullDoc;
}
/**
* Adds a message.
*
* @param {Number} type The type of the message.
* @param {Node} element The element that the message is related to.
* @param {String} msg The message string.
* @param {String} code Unique code for the message.
* @param {Object} [data] Extra data to store for the message.
*/
this.addMessage = function(type, element, msg, code, data) {
code = _getMessageCode(code);
_messages.push({
type: type,
element: element,
msg: _msgOverrides[code] || msg,
code: code,
data: data
});
};
/**
* Returns all the messages for the last run.
*
* Return a copy of the array so the class variable doesn't get modified by
* future modification (eg. splicing).
*
* @returns {Array} Array of message objects.
*/
this.getMessages = function() {
return _messages.concat([]);
};
/**
* Runs the sniffs in the loaded standard for the specified element.
*
* @param {Node} element The element to test.
* @param {Node} topElement The top element of the processing.
* @param {Function} [callback] The function to call once all tests are run.
*/
var _run = function(elements, topElement, callback) {
var topMsgs = [];
while (elements.length > 0) {
var element = elements.shift();
if (element === topElement) {
var tagName = '_top';
} else {
var tagName = element.tagName.toLowerCase();
}
// First check whether any "top" messages need to be shifted off for this
// element. If so, dump off into the main messages.
for (var i = 0; i < topMsgs.length;) {
if (element === topMsgs[i].element) {
_messages.push(topMsgs[i]);
topMsgs.splice(i, 1);
} else {
i++;
}
}//end for
if (_tags[tagName] && _tags[tagName].length > 0) {
_processSniffs(element, _tags[tagName].concat([]), topElement);
// Save "top" messages, and reset the messages array.
if (tagName === '_top') {
topMsgs = _messages;
_messages = [];
}
}
}//end while
if (callback instanceof Function === true) {
callback.call(this);
}
};
/**
* Process the sniffs.
*
* @param {Node} element The element to test.
* @param {Array} sniffs Array of sniffs.
* @param {Node} topElement The top element of the processing.
* @param {Function} [callback] The function to call once the processing is completed.
*/
var _processSniffs = function(element, sniffs, topElement, callback) {
while (sniffs.length > 0) {
var sniff = sniffs.shift();
_currentSniff = sniff;
if (sniff.useCallback === true) {
// If the useCallback property is set:
// - Process the sniff.
// - Recurse into ourselves with remaining sniffs, with no callback.
// - Clear out the list of sniffs (so they aren't run again), so the
// callback (if not already recursed) can run afterwards.
sniff.process(element, topElement, function() {
_processSniffs(element, sniffs, topElement);
sniffs = [];
});
} else {
// Process the sniff.
sniff.process(element, topElement);
}
}//end while
if (callback instanceof Function === true) {
callback.call(this);
}
};
/**
* Includes the specified standard file.
*
* @param {String} standard The name of the standard.
* @param {Function} callback The function to call once the standard is included.
* @param {Object} options The options for the standard (e.g. exclude sniffs).
*/
var _includeStandard = function(standard, callback, options) {
if (standard.indexOf('http') !== 0) {
standard = _getStandardPath(standard);
}//end id
// See if the ruleset object is already included (eg. if minified).
var parts = standard.split('/');
var ruleSet = window['HTMLCS_' + parts[(parts.length - 2)]];
if (ruleSet) {
// Already included.
_registerStandard(standard, callback, options);
} else {
_includeScript(standard, function() {
// Script is included now register the standard.
_registerStandard(standard, callback, options);
});
}//end if
};
/**
* Registers the specified standard and its sniffs.
*
* @param {String} standard The name of the standard.
* @param {Function} callback The function to call once the standard is registered.
* @param {Object} options The options for the standard (e.g. exclude sniffs).
*/
var _registerStandard = function(standard, callback, options) {
// Get the object name.
var parts = standard.split('/');
// Get a copy of the ruleset object.
var oldRuleSet = window['HTMLCS_' + parts[(parts.length - 2)]];
var ruleSet = {};
for (var x in oldRuleSet) {
if (oldRuleSet.hasOwnProperty(x) === true) {
ruleSet[x] = oldRuleSet[x];
}
}
if (!ruleSet) {
return false;
}
_standards[standard] = ruleSet;
// Process the options.
if (options) {
if (options.include && options.include.length > 0) {
// Included sniffs.
ruleSet.sniffs = options.include;
} else if (options.exclude) {
// Excluded sniffs.
for (var i = 0; i < options.exclude.length; i++) {
var index = ruleSet.sniffs.find(options.exclude[i]);
if (index >= 0) {
ruleSet.sniffs.splice(index, 1);
}
}
}
}//end if
// Register the sniffs for this standard.
var sniffs = ruleSet.sniffs.slice(0, ruleSet.sniffs.length);
_registerSniffs(standard, sniffs, callback);
};
/**
* Registers the sniffs for the specified standard.
*
* @param {String} standard The name of the standard.
* @param {Array} sniffs List of sniffs to register.
* @param {Function} callback The function to call once the sniffs are registered.
*/
var _registerSniffs = function(standard, sniffs, callback) {
if (sniffs.length === 0) {
callback.call(this);
return;
}
// Include and register sniffs.
var sniff = sniffs.shift();
_loadSniffFile(standard, sniff, function() {
_registerSniffs(standard, sniffs, callback);
});
};
/**
* Includes the sniff's JS file and registers it.
*
* @param {String} standard The name of the standard.
* @param {String|Object} sniff The sniff to register, can be a string or
* and object specifying another standard.
* @param {Function} callback The function to call once the sniff is included and registered.
*/
var _loadSniffFile = function(standard, sniff, callback) {
if (typeof sniff === 'string') {
var sniffObj = _getSniff(standard, sniff);
var cb = function() {
_registerSniff(standard, sniff);
callback.call(this);
}
// Already loaded.
if (sniffObj) {
cb();
} else {
_includeScript(_getSniffPath(standard, sniff), cb);
}
} else {
// Including a whole other standard.
_includeStandard(sniff.standard, function() {
if (sniff.messages) {
// Add message overrides.
for (var msg in sniff.messages) {
_msgOverrides[msg] = sniff.messages[msg];
}
}
callback.call(this);
}, {
exclude: sniff.exclude,
include: sniff.include
});
}
};
/**
* Registers the specified sniff.
*
* @param {String} standard The name of the standard.
* @param {String} sniff The name of the sniff.
*/
var _registerSniff = function(standard, sniff) {
// Get the sniff object.
var sniffObj = _getSniff(standard, sniff);
if (!sniffObj) {
return false;
}
// Call the register method of the sniff, it should return an array of tags.
if (sniffObj.register) {
var watchedTags = sniffObj.register();
}
if (watchedTags && watchedTags.length > 0) {
for (var i = 0; i < watchedTags.length; i++) {
if (!_tags[watchedTags[i]]) {
_tags[watchedTags[i]] = [];
}
_tags[watchedTags[i]].push(sniffObj);
}
}
_sniffs.push(sniffObj);
};
/**
* Returns the path to the sniff file.
*
* @param {String} standard The name of the standard.
* @param {String} sniff The name of the sniff.
*
* @returns {String} The path to the JS file of the sniff.
*/
var _getSniffPath = function(standard, sniff) {
var parts = standard.split('/');
parts.pop();
var path = parts.join('/') + '/Sniffs/' + sniff.replace(/\./g, '/') + '.js';
return path;
};
/**
* Returns the path to a local standard.
*
* @param {String} standard The name of the standard.
*
* @returns {String} The path to the local standard.
*/
var _getStandardPath = function(standard)
{
// Get the include path of a local standard.
var scripts = document.getElementsByTagName('script');
var path = null;
// Loop through all the script tags that exist in the document and find the one
// that has included this file.
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src) {
if (scripts[i].src.match(/HTMLCS\.js/)) {
// We have found our appropriate <script> tag that includes
// this file, we can extract the path.
path = scripts[i].src.replace(/HTMLCS\.js/,'');
break;
}
}
}
return path + 'Standards/' + standard + '/ruleset.js';
};
/**
* Returns the sniff object.
*
* @param {String} standard The name of the standard.
* @param {String} sniff The name of the sniff.
*
* @returns {Object} The sniff object.
*/
var _getSniff = function(standard, sniff) {
var name = 'HTMLCS_';
name += _standards[standard].name + '_Sniffs_';
name += sniff.split('.').join('_');
if (!window[name]) {
return null;
}
window[name]._name = sniff;
return window[name];
};
/**
* Returns the full message code.
*
* A full message code includes the standard name, the sniff name and the given code.
*
* @returns {String} The full message code.
*/
var _getMessageCode = function(code) {
code = _standard + '.' + _currentSniff._name + '.' + code;
return code;
};
/**
* Includes the specified JS file.
*
* @param {String} src The URL to the JS file.
* @param {Function} callback The function to call once the script is loaded.
*/
var _includeScript = function(src, callback) {
var script = document.createElement('script');
script.onload = function() {
script.onload = null;
script.onreadystatechange = null;
callback.call(this);
};
script.onreadystatechange = function() {
if (/^(complete|loaded)$/.test(this.readyState) === true) {
script.onreadystatechange = null;
script.onload();
}
}
script.src = src;
if (document.head) {
document.head.appendChild(script);
} else {
document.getElementsByTagName('head')[0].appendChild(script);
}
};
/**
* Returns all the child elements in the given element.
*
* @param {Node|Document} [element=document] The parent element.
*
* @returns {Array} Array of Node objects.
*/
var _getAllTags = function(element) {
element = element || document;
var elements = element.getElementsByTagName('*');
// Convert to array. We can't use array features on a NodeList.
var elArray = [];
for (var i = 0; i < elements.length; i++) {
elArray.push(elements[i]);
}
return elArray;
};
this.util = new function() {
/**
* Trim off excess spaces on either side.
*
* @param {String} string The string with potentially extraneous whitespace.
*
* @returns {String}
*/
this.trim = function(string) {
return string.replace(/^\s*(.*)\s*$/g, '$1');
};
/**
* Returns true if the string is "empty" according to WCAG standards.
*
* We can test for whether the string is entirely composed of whitespace, but
* WCAG standards explicitly state that non-breaking spaces ( ,  )
* are not considered "empty". So we need this function to filter out that
* situation.
*
* @param {String} string The potentially empty string.
*
* @returns {Boolean}
*/
this.isStringEmpty = function(string) {
if (typeof string !== 'string') {
return true;
}
var empty = true;
if (string.indexOf(String.fromCharCode(160)) !== -1) {
// Has an NBSP, therefore cannot be empty.
empty = false;
} else if (/^\s*$/.test(string) === false) {
// Not spacing.
empty = false;
}
return empty;
};
/**
* Get the window object relating to the passed element.
*
* @param {Node|Document} element The element (or document) to pass.
*
* @returns {Window}
*/
this.getElementWindow = function(element)
{
if (element.ownerDocument) {
var doc = element.ownerDocument;
} else {
var doc = element;
}
var window = null;
if (doc.defaultView) {
window = doc.defaultView;
} else {
window = doc.parentWindow;
}
return window;
};
/**
* Return the appropriate computed style object for an element.
*
* It's accessed in different ways depending on whether it's IE or not.
*
* @param {Node} element An element with style.
*
* @returns {Object}
*/
this.style = function(element) {
var computedStyle = null;
var window = this.getElementWindow(element);
if (element.currentStyle) {
computedStyle = element.currentStyle;
} else if (window.getComputedStyle) {
computedStyle = window.getComputedStyle(element, null);
}
return computedStyle;
};
/**
* Return true if an element is hidden.
*
* If the computed style of an element cannot be determined for some reason,
* it is presumed it is NOT hidden.
*
* @param {Node} element The element that is hiding, or not.
*
* @returns {Boolean}
*/
this.isHidden = function(element) {
var hidden = false;
// Do not point to elem if its hidden. Use computed styles.
var style = this.style(element);
if (style !== null) {
if ((style.visibility === 'hidden') || (style.display === 'none')) {
hidden = true;
}
if ((parseInt(style.left, 10) + parseInt(style.width, 10)) < 0) {
hidden = true;
}
if ((parseInt(style.top, 10) + parseInt(style.height, 10)) < 0) {
hidden = true;
}
}
return hidden;
};
/**
* Return true if an element is in a document.
*
* @param {Node} element The element that is in a doc, or not.
*
* @returns {Boolean}
*/
this.isInDocument = function(element) {
// Check whether the element is in the document, by looking up its
// DOM tree for a document object.
var parent = element.parentNode;
while (parent && parent.ownerDocument) {
parent = parent.parentNode;
}//end while
// If we didn't hit a document, the element must not be in there.
if (parent === null) {
return false;
}
return true;
};
/**
* Returns true if the passed child is contained by the passed parent.
*
* Uses either the IE contains() method or the W3C compareDocumentPosition()
* method, as appropriate.
*
* @param {Node|Document} parent The parent element or document.
* @param {Node|Document} child The child.
*
* @returns {Boolean}
*/
this.contains = function(parent, child) {
var contained = false;
// If the parent and the child are the same, they can't contain each
// other.
if (parent !== child) {
if (!parent.ownerDocument) {
// Parent is the document. Short-circuiting because contains()
// doesn't exist on the document element.
// We check whether the child can be contained, and whether the
// child is in the same document as the parent.
if ((child.ownerDocument) && (child.ownerDocument === parent)) {
contained = true;
}
} else {
if ((parent.contains) && (parent.contains(child) === true)) {
contained = true;
} else if ((parent.compareDocumentPosition) && ((parent.compareDocumentPosition(child) & 16) > 0)) {
contained = true;
}
}//end if
}//end if
return contained;
};
/**
* Returns true if the table passed is a layout table.
*
* If the passed table contains headings - through the use of the th
* element - HTML_CodeSniffer will assume it is a data table. This is in line
* with most other online checkers.
*
* @param {Node} table The table to check.
*
* @returns {Boolean}
*/
this.isLayoutTable = function(table) {
var th = table.querySelector('th');
if (th === null) {
return true;
}
return false;
};
/**
* Calculate the contrast ratio between two colours.
*
* Colours should be in rgb() or 3/6-digit hex format; order does not matter
* (ie. it doesn't matter which is the lighter and which is the darker).
* Values should be in the range [1.0, 21.0]... a ratio of 1.0 means "they're
* exactly the same contrast", 21.0 means it's white-on-black or v.v.
* Formula as per WCAG 2.0 definitions.
*
* @param {String} colour1 The first colour to compare.
* @param {String} colour2 The second colour to compare.
*
* @returns {Number}
*/
this.contrastRatio = function(colour1, colour2) {
var ratio = (0.05 + this.relativeLum(colour1)) / (0.05 + this.relativeLum(colour2));
if (ratio < 1) {
ratio = 1 / ratio;
}
return ratio;
};
/**
* Calculate relative luminescence for a colour in the sRGB colour profile.
*
* Supports rgb() and hex colours. rgba() also supported but the alpha
* channel is currently ignored.
* Hex colours can have an optional "#" at the front, which is stripped.
* Relative luminescence formula is defined in the definitions of WCAG 2.0.
* It can be either three or six hex digits, as per CSS conventions.
* It should return a value in the range [0.0, 1.0].
*
* @param {String} colour The colour to calculate from.
*
* @returns {Number}
*/
this.relativeLum = function(colour) {
if (colour.charAt) {
var colour = this.colourStrToRGB(colour);
}
var transformed = {};
for (var x in colour) {
if (colour[x] <= 0.03928) {
transformed[x] = colour[x] / 12.92;
} else {
transformed[x] = Math.pow(((colour[x] + 0.055) / 1.055), 2.4);
}
}//end for
var lum = ((transformed.red * 0.2126) + (transformed.green * 0.7152) + (transformed.blue * 0.0722));
return lum;
}
/**
* Convert a colour string to a structure with red/green/blue elements.
*
* Supports rgb() and hex colours (3 or 6 hex digits, optional "#").
* rgba() also supported but the alpha channel is currently ignored.
* Each red/green/blue element is in the range [0.0, 1.0].
*
* @param {String} colour The colour to convert.
*
* @returns {Object}
*/
this.colourStrToRGB = function(colour) {
colour = colour.toLowerCase();
if (colour.substring(0, 3) === 'rgb') {
// rgb[a](0, 0, 0[, 0]) format.
var matches = /^rgba?\s*\((\d+),\s*(\d+),\s*(\d+)([^)]*)\)$/.exec(colour);
colour = {
red: (matches[1] / 255),
green: (matches[2] / 255),
blue: (matches[3] / 255)
}
} else {
// Hex digit format.
if (colour.charAt(0) === '#') {
colour = colour.substr(1);
}
if (colour.length === 3) {
colour = colour.replace(/^(.)(.)(.)$/, '$1$1$2$2$3$3');
}
colour = {
red: (parseInt(colour.substr(0, 2), 16) / 255),
green: (parseInt(colour.substr(2, 2), 16) / 255),
blue: (parseInt(colour.substr(4, 2), 16) / 255)
};
}
return colour;
};
/**
* Convert an RGB colour structure to a hex colour.
*
* The red/green/blue colour elements should be on a [0.0, 1.0] scale.
* Colours that can be converted into a three Hex-digit string will be
* converted as such (eg. rgb(34,34,34) => #222). Others will be converted
* to a six-digit string (eg. rgb(48,48,48) => #303030).
*
* @param {Object} colour Structure with "red", "green" and "blue" elements.
*
* @returns {String}
*/
this.RGBtoColourStr = function(colour) {
colourStr = '#';
colour.red = Math.round(colour.red * 255);
colour.green = Math.round(colour.green * 255);
colour.blue = Math.round(colour.blue * 255);
if ((colour.red % 17 === 0) && (colour.green % 17 === 0) && (colour.blue % 17 === 0)) {
// Reducible to three hex digits.
colourStr += (colour.red / 17).toString(16);
colourStr += (colour.green / 17).toString(16);
colourStr += (colour.blue / 17).toString(16);
} else {
if (colour.red < 16) {
colourStr += '0';
}
colourStr += colour.red.toString(16);
if (colour.green < 16) {
colourStr += '0';
}
colourStr += colour.green.toString(16);
if (colour.blue < 16) {
colourStr += '0';
}
colourStr += colour.blue.toString(16);
}
return colourStr;
};
/**
* Convert an RGB colour into hue-saturation-value.
*
* This is used for calculations changing the colour (for colour contrast
* purposes) to ensure that the hue is maintained.
* The parameter accepts either a string (hex or rgb() format) or a
* red/green/blue structure.
* The returned structure has hue, saturation, and value components: the
* latter two are in the range [0.0, 1.0]; hue is in degrees,
* range [0.0, 360.0).
* If there is no saturation then hue is technically undefined.
*
* @param {String|Object} colour A colour to convert.
*
* @returns {Object}
*/
this.sRGBtoHSV = function(colour) {
// If this is a string, then convert to a colour structure.
if (colour.charAt) {
colour = this.colourStrToRGB(colour);
}
var hsvColour = {
hue: 0,
saturation: 0,
value: 0
};
var maxColour = Math.max(colour.red, colour.green, colour.blue);
var minColour = Math.min(colour.red, colour.green, colour.blue);
var chroma = maxColour - minColour;
if (chroma === 0) {
hsvColour.value = colour.red;
} else {
hsvColour.value = maxColour;
if (maxColour === colour.red) {
hsvColour.hue = ((colour.green - colour.blue) / chroma);
} else if (maxColour === colour.green) {
hsvColour.hue = (2.0 + ((colour.blue - colour.red) / chroma));
} else {
hsvColour.hue = (4.0 + ((colour.red - colour.green) / chroma));
}//end if
hsvColour.hue = (hsvColour.hue * 60.0);
if (hsvColour.hue >= 360.0) {
hsvColour.hue -= 360.0;
}
hsvColour.saturation = chroma / hsvColour.value;
}//end if
return hsvColour;
};
/**
* Convert a hue-saturation-value structure into an RGB structure.
*
* The hue element should be a degree value in the region of [0.0, 360.0).
* The saturation and value elements should be in the range [0.0, 1.0].
* Use RGBtoColourStr to convert back into a hex colour.
*
* @param {Object} hsvColour A HSV structure to convert.
*
* @returns {Object}
*/
this.HSVtosRGB = function(hsvColour) {
var colour = {
red: 0,
green: 0,