Last active
October 14, 2017 18:39
-
-
Save pomber/c63bd22dbfa6c4af86ba2cae0a863064 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isEvent = name => name.startsWith("on"); | |
const isAttribute = name => | |
!isEvent(name) && name != "children" && name != "style"; | |
const isNew = (prev, next) => key => prev[key] !== next[key]; | |
const isGone = (prev, next) => key => !(key in next); | |
function updateDomProperties(dom, prevProps, nextProps) { | |
// Remove event listeners | |
Object.keys(prevProps) | |
.filter(isEvent) | |
.filter(key => !(key in nextProps) || isNew(prevProps, nextProps)(key)) | |
.forEach(name => { | |
const eventType = name.toLowerCase().substring(2); | |
dom.removeEventListener(eventType, prevProps[name]); | |
}); | |
// Remove attributes | |
Object.keys(prevProps) | |
.filter(isAttribute) | |
.filter(isGone(prevProps, nextProps)) | |
.forEach(name => { | |
dom[name] = null; | |
}); | |
// Set attributes | |
Object.keys(nextProps) | |
.filter(isAttribute) | |
.filter(isNew(prevProps, nextProps)) | |
.forEach(name => { | |
dom[name] = nextProps[name]; | |
}); | |
// Set style | |
prevProps.style = prevProps.style || {}; | |
nextProps.style = nextProps.style || {}; | |
Object.keys(nextProps.style) | |
.filter(isNew(prevProps.style, nextProps.style)) | |
.forEach(key => { | |
dom.style[key] = nextProps.style[key]; | |
}); | |
Object.keys(prevProps.style) | |
.filter(isGone(prevProps.style, nextProps.style)) | |
.forEach(key => { | |
dom.style[key] = ""; | |
}); | |
// Add event listeners | |
Object.keys(nextProps) | |
.filter(isEvent) | |
.filter(isNew(prevProps, nextProps)) | |
.forEach(name => { | |
const eventType = name.toLowerCase().substring(2); | |
dom.addEventListener(eventType, nextProps[name]); | |
}); | |
} | |
function createDomElement(fiber) { | |
const isTextElement = fiber.type === TEXT_ELEMENT; | |
const dom = isTextElement | |
? document.createTextNode("") | |
: document.createElement(fiber.type); | |
updateDomProperties(dom, [], fiber.props); | |
return dom; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment