1 | ;
|
2 |
|
3 | /**
|
4 | * Copyright (c) 2013-present, Facebook, Inc.
|
5 | *
|
6 | * This source code is licensed under the MIT license found in the
|
7 | * LICENSE file in the root directory of this source tree.
|
8 | *
|
9 | * @typechecks
|
10 | */
|
11 |
|
12 | /**
|
13 | * The CSSCore module specifies the API (and implements most of the methods)
|
14 | * that should be used when dealing with the display of elements (via their
|
15 | * CSS classes and visibility on screen. It is an API focused on mutating the
|
16 | * display and not reading it as no logical state should be encoded in the
|
17 | * display of elements.
|
18 | */
|
19 |
|
20 | var CSSCore = {
|
21 | /**
|
22 | * Adds the class passed in to the element if it doesn't already have it.
|
23 | *
|
24 | * @param {DOMElement} element the element to set the class on
|
25 | * @param {string} className the CSS className
|
26 | * @return {DOMElement} the element passed in
|
27 | */
|
28 | addClass: function addClass(element, className) {
|
29 | if (className) {
|
30 | if (element.classList) {
|
31 | element.classList.add(className);
|
32 | } else if (!CSSCore.hasClass(element, className)) {
|
33 | element.className = element.className + ' ' + className;
|
34 | }
|
35 | }
|
36 | return element;
|
37 | },
|
38 |
|
39 | /**
|
40 | * Removes the class passed in from the element
|
41 | *
|
42 | * @param {DOMElement} element the element to set the class on
|
43 | * @param {string} className the CSS className
|
44 | * @return {DOMElement} the element passed in
|
45 | */
|
46 | removeClass: function removeClass(element, className) {
|
47 | if (className) {
|
48 | if (element.classList) {
|
49 | element.classList.remove(className);
|
50 | } else if (CSSCore.hasClass(element, className)) {
|
51 | element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
|
52 | .replace(/^\s*|\s*$/g, ''); // trim the ends
|
53 | }
|
54 | }
|
55 | return element;
|
56 | },
|
57 |
|
58 | /**
|
59 | * Tests whether the element has the class specified.
|
60 | *
|
61 | * @param {DOMNode|DOMWindow} element the element to check the class on
|
62 | * @param {string} className the CSS className
|
63 | * @return {boolean} true if the element has the class, false if not
|
64 | */
|
65 | hasClass: function hasClass(element, className) {
|
66 | if (element.classList) {
|
67 | return !!className && element.classList.contains(className);
|
68 | }
|
69 | return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
|
70 | }
|
71 | };
|
72 |
|
73 | module.exports = CSSCore;
|