Created
October 3, 2016 17:56
-
-
Save sranso/85f6ded573088e5cf5f5780e5b88a7f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 1. describe virtual dom | |
// (as obj / list; start with list, expand as nec) | |
// node : obj attributes : list html | |
const rootNode = [ | |
'div', { | |
'style': { | |
'textAlign': 'center', | |
'color': 'blue', | |
'margin': '20px' | |
} | |
}, | |
['hello world'] | |
]; | |
const nestedNode = [ | |
'div', { | |
'style': { | |
'textAlign': 'center', | |
'color': 'blue', | |
'margin': '20px' | |
} | |
}, | |
[ | |
'p', { | |
'style': { | |
'color': 'black' | |
} | |
}, | |
['hello world'] | |
] | |
]; | |
// 2. and take it to real dom (convert to html) | |
const render = (node) => { | |
if (node.length !== 3) { | |
throw new Error('Please pass a valid node.'); | |
} | |
return parseNode(node); | |
}; | |
const parseNode = (node, isTextNode = false) => { | |
const elType = node[0]; | |
return node.reduce((acc, el, index) => { | |
if (isTextNode) { | |
return `${acc}${el}`; | |
} else if (index === 0) { | |
return `${acc}<${elType}`; | |
} else if (Array.isArray(el)) { | |
// handle children | |
if (el.length > 1) { | |
return `${acc}${parseNode(el)}</${elType}>`; | |
} else { | |
return `${acc}${parseNode(el, true)}</${elType}>`; | |
} | |
} else if (!Array.isArray(el) && typeof el === 'object') { | |
// handle styles | |
const styles = parseStyles(el); | |
return `${acc} ${styles}>`; | |
} else { | |
// handle ??? nothing goes here rn | |
return acc; | |
} | |
}, ''); | |
}; | |
const parseStyles = (stylesNode) => { | |
if (!stylesNode.hasOwnProperty('style')) { | |
throw new Error('Please pass a valid styles node.'); | |
} | |
const styles = Object.keys(stylesNode.style).map((key) => { | |
return `${key}: ${stylesNode.style[key]}`; | |
}); | |
return `style="${styles.join('; ')}"`; | |
}; | |
const app = document.getElementById('app'); | |
console.log(render(nestedNode)); | |
console.log(render(rootNode)); | |
app.innerHTML = render(nestedNode); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment