@react-slate/core
Version:
Write interactive CLI apps with React
77 lines • 2.95 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_reconciler_1 = __importDefault(require("react-reconciler"));
const util_1 = require("util");
const reconcilerConfig_1 = __importDefault(require("./host/reconcilerConfig"));
const View_1 = __importDefault(require("./host/nodes/View"));
const Text_1 = __importDefault(require("./host/nodes/Text"));
const utils_1 = require("./utils");
const Paragraph_1 = __importDefault(require("./host/nodes/Paragraph"));
function traverse(node, layout) {
if (node instanceof View_1.default) {
return {
node: 'View',
children: node.children.map((child, index) => traverse(child, layout.child(index))),
width: layout.width,
height: layout.height,
x: layout.x,
y: layout.y,
style: node.style,
};
}
else if (node instanceof Text_1.default) {
return {
node: 'Text',
body: node.getBody(),
width: layout.width,
height: layout.height,
x: layout.x,
y: layout.y,
style: node.style,
};
}
else if (node instanceof Paragraph_1.default) {
return {
node: 'Paragraph',
children: node.children.map((child, index) => traverse(child, layout.child(index))),
width: layout.width,
height: layout.height,
x: layout.x,
y: layout.y,
style: node.style,
};
}
throw new Error(`Unknown instance of node: ${util_1.inspect(node)}`);
}
function renderToJson(element, { width, height, maxRenders, } = {}) {
let currentSnapshot;
const asyncIterator = new utils_1.AsyncIterator(maxRenders);
const container = new View_1.default();
container.setLayoutStyle({ width: '100%', height: '100%' });
const reconciler = react_reconciler_1.default(reconcilerConfig_1.default(container, () => {
const layout = container.layoutNode.computeLayout({
width: width || null,
height: height || null,
});
container.notifyOnLayoutHook(layout, { offsetX: 0, offsetY: 0 });
currentSnapshot = traverse(container, layout);
asyncIterator.nextValue(currentSnapshot);
}));
const node = reconciler.createContainer(container, false, false);
reconciler.updateContainer(element, node, null, () => undefined);
return {
get snapshot() {
return currentSnapshot;
},
start: () => asyncIterator.makeIterator({}),
stop: () => {
asyncIterator.finish(undefined);
reconciler.updateContainer(null, node, null, () => undefined);
},
};
}
exports.default = renderToJson;
//# sourceMappingURL=renderToJson.js.map