UNPKG

myst-to-jats

Version:
47 lines (46 loc) 1.81 kB
import { selectBlockParts } from 'myst-common'; import { remove } from 'unist-util-remove'; import { selectAll } from 'unist-util-select'; import { ABSTRACT_PARTS, ACKNOWLEDGMENT_PARTS } from '../types.js'; function blocksToKeep(tree, opts) { const keepParts = [...ACKNOWLEDGMENT_PARTS]; if (opts.extractAbstract) { keepParts.push(...(opts.abstractParts?.map(({ part }) => part).flat() ?? ABSTRACT_PARTS)); } if (opts.backSections) { keepParts.push(...opts.backSections.map(({ part }) => part).flat()); } return selectBlockParts(tree, keepParts); } /** * This transform does the following: * - Removes hidden or removed blocks from the tree except those that are consumed as front/backmatter parts * - Removes hidden or removed outputs from the tree */ export function blockTransform(tree, opts) { // Collect blocks that will be used as parts to make sure they are not deleted const doNotDelete = blocksToKeep(tree, opts); // This could also be an output, etc. selectAll('[visibility=remove],[visibility=hide]', tree).forEach((node) => { if (node.visibility === 'remove' || node.visibility === 'hide') { node.type = '__delete__'; } }); // Blocks are converted to sections - avoid doing this for part blocks doNotDelete.forEach((node) => { node.type = 'block-part'; }); const removed = remove(tree, '__delete__'); if (removed === null) { // remove is unhappy if all children are removed - this forces it through tree.children = []; } } export const blockPlugin = (opts) => (tree) => { blockTransform(tree, opts); }; export function restoreBlockPartTypeTransform(tree) { selectAll('block-part', tree).forEach((node) => { node.type = 'block'; }); }