@bookbox/generator-js
Version:
Bookbox generator for js code
87 lines (86 loc) • 2.81 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { defaultBookApi } from "./defaultApi";
function isBookResult(x) {
return typeof x === "object" && x !== null && "schema" in x;
}
/**
* Составление дерева с учётом границ
*/
export function getPureSchema(schema) {
const result = [];
const stack = [];
const getTarget = () => stack.length > 0 ? stack[stack.length - 1].children : result;
for (const item of schema) {
// куда класть текущие элементы
const target = getTarget();
if (typeof item === "string") {
target.push(item);
}
else if (typeof item === "number") {
target.push(`${item}`);
}
else if (item === null) {
target.push("");
}
else if (typeof item === "boolean") {
target.push(`${+item}`);
}
else if (isBookResult(item)) {
// вложенные книги
target.push(...getPureSchema(item.schema));
}
else if ((typeof item === "object" &&
item.prototype &&
item instanceof Proxy) ||
typeof item === "function") {
target.push(...getPureSchema([item()]));
}
else if ("__start" in item) {
// текущая область
stack.push({
name: item.__start,
props: item.props,
children: [],
});
}
else if ("__end" in item) {
const elem = stack.pop();
if (elem) {
const parentTarget = getTarget();
parentTarget.push(elem);
}
}
else {
item.children = getPureSchema(item.children);
target.push(item);
}
}
// замыкаем остатки стека
while (stack.length > 0) {
const elem = stack.pop();
const target = getTarget();
target.push(elem);
}
return result;
}
export function getBookSchema(_a) {
var { api = defaultBookApi } = _a, params = __rest(_a, ["api"]);
let rawSchema;
if ("rawSchema" in params) {
rawSchema = params.rawSchema;
}
else {
rawSchema = params.book(api).schema;
}
return { schema: getPureSchema(rawSchema) };
}