Skip to content

Commit

Permalink
updateStyle(): use setProperty() only when css vars
Browse files Browse the repository at this point in the history
This will improve the performance of “mutate styles/properties” and reduce the amount of code a little.

Also, it turns out that the CSSStyleDeclaration interface also supports stuff like elem.style["font-size"] as well as the equivalent elem.style.fontSize.
https://drafts.csswg.org/cssom/#dom-cssstyleproperties-dashed-attribute
  • Loading branch information
kfule authored and dead-claudia committed Nov 7, 2024
1 parent 50c580b commit c6ffa18
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 17 deletions.
18 changes: 8 additions & 10 deletions render/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -778,13 +778,6 @@ module.exports = function() {
}

//style
var uppercaseRegex = /[A-Z]/g
function toLowerCase(capital) { return "-" + capital.toLowerCase() }
function normalizeKey(key) {
return key[0] === "-" && key[1] === "-" ? key :
key === "cssFloat" ? "float" :
key.replace(uppercaseRegex, toLowerCase)
}
function updateStyle(element, old, style) {
if (old === style) {
// Styles are equivalent, do nothing.
Expand All @@ -800,21 +793,26 @@ module.exports = function() {
// Add new style properties
for (var key in style) {
var value = style[key]
if (value != null) element.style.setProperty(normalizeKey(key), String(value))
if (value != null) {
if (key[0] === "-" && key[1] === "-") element.style.setProperty(key, String(value))
else element.style[key] = String(value)
}
}
} else {
// Both old & new are (different) objects.
// Update style properties that have changed
for (var key in style) {
var value = style[key]
if (value != null && (value = String(value)) !== String(old[key])) {
element.style.setProperty(normalizeKey(key), value)
if (key[0] === "-" && key[1] === "-") element.style.setProperty(key, value)
else element.style[key] = value
}
}
// Remove style properties that no longer exist
for (var key in old) {
if (old[key] != null && style[key] == null) {
element.style.removeProperty(normalizeKey(key))
if (key[0] === "-" && key[1] === "-") element.style.removeProperty(key)
else element.style[key] = ""
}
}
}
Expand Down
7 changes: 0 additions & 7 deletions render/tests/test-createElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,6 @@ o.spec("createElement", function() {

o(vnode.dom.style["--cssVar"]).equals("red")
})
o("censors cssFloat to float", function() {
var vnode = m("a", {style: {cssFloat: "left"}})

render(root, vnode)

o(vnode.dom.style.float).equals("left")
})
o("creates children", function() {
var vnode = m("div", m("a"), m("b"))
render(root, vnode)
Expand Down

0 comments on commit c6ffa18

Please sign in to comment.