UNPKG

decca

Version:

Render interfaces using pure functions and virtual DOM, kinda

63 lines (47 loc) 2.23 kB
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _id = require('./id'); var _id2 = _interopRequireDefault(_id); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function render(el, context) { if (typeof el === 'string') return el; if (typeof el === 'number') return '' + el; if (Array.isArray(el)) return el.map(function (_el) { return render(_el, context); }); if (typeof el === 'undefined' || el === null) return ''; var tag = el.tag; var props = el.props; var children = el.children; if (typeof tag === 'string') { var open = '<' + tag + toProps(props) + '>'; var close = '</' + tag + '>'; return open + (children || []).map(function (_el) { return render(_el, context); }).join('') + close; } if ((typeof tag === 'undefined' ? 'undefined' : _typeof(tag)) === 'object') { if (!tag.render) throw new Error('component has no render()'); return render(tag.render({ props: _extends({}, props, { children: children }), path: (0, _id2.default)(), context: context }), context); } if (typeof tag === 'function') { // Pure components return render(tag({ props: _extends({}, props, { children: children }), path: (0, _id2.default)(), context: context }), context); } } /* * { class: 'foo', id: 'box' } => ' class="foo" id="box"' */ function toProps(props) { if (!props) return ''; var result = []; Object.keys(props).forEach(function (attr) { if (/^on[A-Za-z]/.test(attr)) return; var val = props[attr]; if (typeof val === 'undefined' || val === null) return; result.push(attr + '=' + JSON.stringify(val)); }); return result.length ? ' ' + result.join(' ') : ''; } module.exports = { render: render };