2
0
mirror of https://github.com/tenrok/BBob.git synced 2026-05-21 13:24:05 +03:00
Files
bbob/packages/bbob-html/src/index.js
T
2018-10-12 00:43:20 +02:00

56 lines
1.5 KiB
JavaScript

import core from '@bbob/core';
import { attrValue } from '@bbob/plugin-helper';
/**
* Transforms attrs to html params string
* @param values
*/
const attrs = values =>
Object.keys(values)
.reduce((arr, key) => [...arr, attrValue(key, values[key])], [''])
.join(' ');
const SELFCLOSE_END_TAG = '/>';
const CLOSE_START_TAG = '</';
const START_TAG = '<';
const END_TAG = '>';
const renderNode = (node, { stripTags = false }) => {
if (!node) return '';
const type = typeof node;
if (type === 'string' || type === 'number') {
return node;
}
if (type === 'object') {
if (stripTags === true) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node.content, { stripTags });
}
if (node.content === null) {
return [START_TAG, node.tag, attrs(node.attrs), SELFCLOSE_END_TAG].join('');
}
// eslint-disable-next-line no-use-before-define
return [START_TAG, node.tag, attrs(node.attrs), END_TAG, renderNodes(node.content), CLOSE_START_TAG, node.tag, END_TAG].join('');
}
if (Array.isArray(node)) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node, { stripTags });
}
return '';
};
const renderNodes = (nodes, { stripTags = false } = {}) => []
.concat(nodes)
.reduce((r, node) => r + renderNode(node, { stripTags }), '');
const toHTML = (source, plugins) => core(plugins).process(source, { render: renderNodes }).html;
export const render = renderNodes;
export default toHTML;