UNPKG

datocms-structured-text-utils

Version:

A set of Typescript types and helpers to work with DatoCMS Structured Text fields.

73 lines 3.13 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; import { flatten } from 'array-flatten'; import { hasChildren, isDocument, isNode, isStructuredText } from './guards'; var RenderError = /** @class */ (function (_super) { __extends(RenderError, _super); function RenderError(message, node) { var _this = _super.call(this, message) || this; _this.node = node; Object.setPrototypeOf(_this, RenderError.prototype); return _this; } return RenderError; }(Error)); export { RenderError }; export var renderRule = function (guard, transform) { return ({ appliable: guard, apply: function (ctx) { return transform(ctx); }, }); }; export function transformNode(adapter, node, key, ancestors, renderRules) { var children = hasChildren(node) ? flatten(node.children .map(function (innerNode, index) { return transformNode(adapter, innerNode, "t-" + index, __spreadArrays([node], ancestors), renderRules); }) .filter(function (x) { return !!x; })) : undefined; var matchingTransform = renderRules.find(function (transform) { return transform.appliable(node); }); if (matchingTransform) { return matchingTransform.apply({ adapter: adapter, node: node, children: children, key: key, ancestors: ancestors }); } throw new RenderError("Don't know how to render a node with type \"" + node.type + "\". Please specify a custom renderRule for it!", node); } export function render(adapter, structuredTextOrNode, renderRules) { if (!structuredTextOrNode) { return null; } var node = isStructuredText(structuredTextOrNode) && isDocument(structuredTextOrNode.value) ? structuredTextOrNode.value.document : isDocument(structuredTextOrNode) ? structuredTextOrNode.document : isNode(structuredTextOrNode) ? structuredTextOrNode : undefined; if (!node) { throw new Error('Passed object is neither null, a Structured Text value, a DAST document or a DAST node'); } var result = transformNode(adapter, node, 't-0', [], renderRules); return result; } //# sourceMappingURL=render.js.map