UNPKG

@bookbox/core

Version:

Bookbox — e-book format

81 lines (80 loc) 3.2 kB
import { getIterableBook } from './iterableBook'; export function getResources(schema) { const result = []; for (const item of getIterableBook(schema)) { if (typeof item === 'string') continue; if (!isValidResource(item)) continue; result.push(item); } return result; } export function isValidResource(resource) { if (resource.name !== 'resource') return false; const { path, src } = resource.props; return Boolean(path) && Boolean(src); } export function getResourceKey({ path, type }) { return `${type ? `${type}:` : ''}${path}`; } /** * @example * * ```ts * getPathWithPrefix('dir', 'path'); // 'dir/path' * getPathWithPrefix('dir', '/path'); // 'dir/path' * getPathWithPrefix('dir', './path'); // 'dir/path' * getPathWithPrefix('dir', '../path'); // 'dir/../path' * getPathWithPrefix('dir/', 'path'); // 'dir/path' * getPathWithPrefix('dir/', '/path'); // 'dir/path' * getPathWithPrefix('dir/', './path'); // 'dir/path' * getPathWithPrefix('dir/', '../path'); // 'dir/../path' * ``` */ export function getPathWithPrefix(src, prefix) { return `${prefix.replace(/\/$/, '')}/${src.replace(/^\.?\//, '')}`; } export function getActualResourceMap({ schema, resourceOptions, }) { const { prefix, pathMap, rawPrefix } = resourceOptions !== null && resourceOptions !== void 0 ? resourceOptions : {}; const resources = getResources(schema); const actualMap = new Map(); for (const resource of resources) { const { path, src, type } = resource.props; const key = getResourceKey({ path, type }); let settings = { src }; const customSettings = pathMap === null || pathMap === void 0 ? void 0 : pathMap.get(key); if (customSettings) { settings = customSettings; } else if (prefix) { settings = { src: getPathWithPrefix(src, prefix) }; } else if (rawPrefix) { settings = { src: `${rawPrefix}${src}` }; } actualMap.set(key, settings); } return actualMap; } export function calculateResources(schema, resourceMap = new Map()) { var _a, _b, _c; for (const item of schema) { if (typeof item === 'string') continue; if ('src' in item.props && typeof item.props.src === 'string' && item.props.src.startsWith('/')) { // локальный путь const localPath = item.props.src; const resourcePath = getResourceKey({ type: item.name, path: localPath }); const typeSrc = (_a = resourceMap.get(resourcePath)) === null || _a === void 0 ? void 0 : _a.src; const src = (_b = resourceMap.get(localPath)) === null || _b === void 0 ? void 0 : _b.src; if (!src && !typeSrc) { // FIXME: добавить предупреждения в книгу console.error(`Unknown resource ${item.props.src}`); } item.props.src = (_c = typeSrc !== null && typeSrc !== void 0 ? typeSrc : src) !== null && _c !== void 0 ? _c : item.props.src; } calculateResources(item.children, resourceMap); } }