@bonniernews/abbe-api-utils
Version:
Utilities for converting to Abbe article format
98 lines (97 loc) • 3.21 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const contentUtils_1 = require("../contentUtils");
const utils_1 = require("../utils");
const types_1 = require("./types");
class Content {
constructor() {
this._blocks = [];
}
static initialize() {
const content = new Content();
content._blocks = [];
content._entityMap = {};
return content;
}
addTitle(text) {
var _a;
if (((_a = this._blocks[0]) === null || _a === void 0 ? void 0 : _a.type) === types_1.BlockType.TITLE) {
this._blocks[0].text = text;
return this;
}
this._blocks.unshift((0, contentUtils_1.createTitleBlock)(text));
return this;
}
addSubtitle(text) {
this._blocks.push((0, contentUtils_1.createHeadlineBlock)(text));
return this;
}
addPreamble(text) {
this._blocks.push((0, contentUtils_1.createPreambleBlock)(text));
return this;
}
addText(text) {
this._blocks.push((0, contentUtils_1.createTextBlock)(text));
return this;
}
addStyledText(text, styles) {
const nextEntityMapIndex = Object.keys(this._entityMap).length;
const { block, entityMap } = (0, contentUtils_1.createStyledText)(text, styles, nextEntityMapIndex);
this._blocks.push(block);
this._entityMap = { ...this._entityMap, ...entityMap };
return this;
}
addImage(image) {
this._blocks.push((0, contentUtils_1.createImage)(image));
return this;
}
addImageCollection(images) {
this._blocks.push((0, contentUtils_1.createImageCollection)(images));
return this;
}
addEmbed(embed) {
this._blocks.push((0, contentUtils_1.createEmbed)(embed));
return this;
}
addQuote(text, author) {
this._blocks.push(...(0, contentUtils_1.createQuote)(text, author));
return this;
}
addBlock(block) {
this._blocks.push(block);
return this;
}
addTitleIfMissing(articleHeadline) {
var _a;
if (!this._blocks.length)
return this;
if (((_a = this._blocks[0]) === null || _a === void 0 ? void 0 : _a.type) === types_1.BlockType.TITLE)
return this;
if (!articleHeadline)
return this;
this._blocks.unshift((0, contentUtils_1.createTitleBlock)(articleHeadline));
return this;
}
validate() {
if (this._blocks.length === 0) {
throw new Error("Content is empty");
}
if (this._blocks.every((block) => block.text === "")) {
throw new Error("Content is empty");
}
if (this._blocks[0].type !== types_1.BlockType.TITLE) {
throw new Error("Content must have a title block as the first block");
}
}
finalize({ validate = true } = { validate: true }) {
if (validate)
this.validate();
const content = {
blocks: this._blocks,
entityMap: this._entityMap,
};
(0, utils_1.removeUndefinedProperties)(content);
return content;
}
}
exports.default = Content;