a JSX renderer that outputs Cheerio elements
/** @jsx h */
import h from '@quarterto/jsx-cheerio';
const $ = cheerio.load('<div>');
$('div').append(<h1>hello world</h1>);
var flatMap = require('@quarterto/flatmap'); | |
function textToCheerio(text) { | |
return { | |
type: 'text', | |
data: text | |
} | |
} | |
function tagToCheerio(tagName, attrs) { | |
var children = [].slice.call(arguments, 2); | |
var parent = { | |
type: 'tag', | |
name: tagName, | |
attribs: attrs | |
}; | |
parent.children = flatMap(children, toCheerio).map(function(child, i, children) { | |
child.next = children[i + 1] || null; | |
child.prev = children[i - 1] || null; | |
child.parent = parent; | |
return child; | |
}); | |
return parent; | |
} | |
function toCheerio(it) { | |
if(it.type) return [it]; | |
if(Array.isArray(it)) return flatMap(it, toCheerio); | |
if(typeof it === 'string') return [textToCheerio(it)]; | |
if(!it) return []; | |
throw new TypeError('Invalid JSX child, expected element, string, array, or falsy, got ' + it); | |
} | |
module.exports = tagToCheerio; | |
module.exports.cheerioRoot = function(node) { | |
return { | |
type: 'root', | |
name: 'root', | |
attribs: {}, | |
children: toCheerio(node), | |
} | |
}; |