UNPKG

@bonniernews/abbe-api-utils

Version:

Utilities for converting to Abbe article format

56 lines (55 loc) 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.objectIsEmpty = exports.removeUndefinedProperties = exports.validateStyle = exports.createInlineStyleRanges = exports.initBlock = void 0; const block_key_1 = require("./block-key"); const types_1 = require("./types/types"); const initBlock = () => ({ key: (0, block_key_1.blockKey)(), text: "", type: types_1.BlockType.UNSTYLED, depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }); exports.initBlock = initBlock; const validDraftJsStyles = [types_1.Style.BOLD, types_1.Style.ITALIC]; const isValidDraftJsStyles = (style) => validDraftJsStyles.includes(style.style); const mapStyleToBlock = (style) => ({ offset: style.position.offset, length: style.position.length, style: style.style, }); const createInlineStyleRanges = (styles) => { return styles.filter(isValidDraftJsStyles).map(mapStyleToBlock); }; exports.createInlineStyleRanges = createInlineStyleRanges; const validateStyle = (text, styles) => { styles.forEach((style) => { if (style.position.offset < 0) { throw new Error(`Style position start is negative: ${JSON.stringify(style)} for text: ${text}`); } if (style.position.length < 0) { throw new Error(`Style position length is negative: ${JSON.stringify(style)} for text: ${text}`); } if (style.position.offset + style.position.length > text.length) { throw new Error(`Style position out of range: ${JSON.stringify(style)} for text: ${text}`); } }); }; exports.validateStyle = validateStyle; const removeUndefinedProperties = (obj) => { if (obj === null) return; if (Array.isArray(obj)) obj.forEach(exports.removeUndefinedProperties); Object.keys(obj).forEach((key) => { if (typeof obj[key] === "object") (0, exports.removeUndefinedProperties)(obj[key]); if (obj[key] === undefined) delete obj[key]; }); }; exports.removeUndefinedProperties = removeUndefinedProperties; const objectIsEmpty = (obj) => Object.keys(obj || {}).length === 0; exports.objectIsEmpty = objectIsEmpty;