UNPKG

2.61 kBJavaScriptView Raw
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2015 - present Instructure, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25import { isEmpty } from '@instructure/ui-utils'
26
27import { formatVariableNames } from './formatVariableNames'
28import { pickOverrides } from './pickOverrides'
29
30/**
31 * ---
32 * category: utilities/themes
33 * ---
34 * Apply theme variables to a DOM node (as CSS variables, with polyfill)
35 * @module applyVariablesToNode
36 * @param {Element} domNode HTML element to apply variables to using the style attribute
37 * @param {Object} variables JS variables
38 * @param {Object} defaults Default JS variables
39 * @param {String} prefix A variable prefix/namespace
40 */
41function applyVariablesToNode(domNode, variables, defaults, prefix) {
42 if (!domNode || isEmpty(variables)) {
43 return
44 }
45
46 clearCustomProperties(domNode, prefix)
47
48 const overrides = pickOverrides(defaults, variables)
49
50 if (overrides && !isEmpty(overrides)) {
51 setCustomProperties(domNode, formatVariableNames(overrides, prefix))
52 }
53}
54
55function clearCustomProperties(domNode, prefix) {
56 const styles = domNode.style
57 for (let i = styles.length - 1; i >= 0; i--) {
58 const prop = styles[i]
59 if (prop.indexOf(`--${prefix}-`) >= 0) {
60 domNode.style.removeProperty(prop)
61 }
62 }
63}
64
65function setCustomProperties(domNode, properties) {
66 Object.keys(properties).forEach((propertyName) => {
67 const value = properties[propertyName]
68
69 if (value) {
70 domNode.style.setProperty(propertyName, value)
71 }
72 })
73}
74
75export default applyVariablesToNode
76export { applyVariablesToNode }