1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| function createVDOM(type, props, contArg) { let content, args; args = arguments - 2; if (typeof type !== 'string') { if(args == 1){ content = contArg; } } else { if (args > 1) { args = Array(len); for (i = 0; i < len; i++) { args[i] = arguments[i + 2]; } content = maybeFlatten(args, false); } if (args < 1) { content = {}; } content = [{ _text: contArg == null ? "" : contArg }]; } return { vDom: true, type, key: props.key || null, props: props || {}, content } }
function maybeFlatten(arr) { for (var i = 0; i < arr.length; i++) { var ch = arr[i]; if (!ch.vDom) { arr[i] = { _text: ch == null ? "" : ch }; } } return arr; }
function render(vDOM) { const node; if(vDOM.text) { node = document.createTextNode(vDOM.text); } else if (vDOM.vDom) { let {vDom, type, key, props, content} = vDOM; if(typeof type === 'string') { node = document.createElement(type); if(_.isArray("content")){ appendChildren(node, render(content)); } } else { var vnode = type(props, content); node = mount(vnode); vDOM.text = vnode; } } return node; }
function appendChildren( parent, children, start = 0, end = children.length - 1, beforeNode ) { while (start <= end) { var ch = children[start++]; parent.insertBefore(mount(ch), beforeNode); } }
function Box(props, content) { return createVDOM('div', null, createVDOM('h1', null, props.title), createVDOM('p', null, content)); }
const vnode = createVDOM('div', null, createVDOM(Box, { title: 'Fancy Box' }, 'content')); document.getElelment('root').appendChild(render(vnode));
|