myst-to-jats
Version:
Export from MyST Markdown to JATS
60 lines (59 loc) • 2.55 kB
JavaScript
import { select, selectAll } from 'unist-util-select';
import { remove } from 'unist-util-remove';
import { normalizeLabel } from 'myst-common';
function liftCaptionNumber(container) {
// TODO: this won't work for multi-panel figures?
const caption = select('caption', container);
const captionNumber = select('captionNumber', container);
if (caption)
remove(caption, 'captionNumber');
if (captionNumber)
container.children.splice(0, 0, captionNumber);
}
export function containerTransform(mdast) {
const figures = selectAll('container', mdast);
figures.forEach((container) => {
liftCaptionNumber(container);
if (container.kind === 'quote') {
const caption = select('caption > paragraph', container);
const blockquote = select('blockquote', container);
if (blockquote && caption) {
const newContainer = container;
newContainer.type = 'blockquote';
newContainer.children = blockquote.children;
caption.type = 'attrib'; // Change the caption to attribution for JATS
newContainer.children.push(caption);
}
}
const caption = (select('caption', container) ?? { type: 'caption', children: [] });
const legends = selectAll('legend', container);
if (legends.length) {
const legendChildren = legends.map((leg) => leg.children).flat();
caption.children.push(...legendChildren);
remove(container, 'legend');
}
const { identifier } = normalizeLabel(container.source?.label) ?? {};
if (identifier && container.source) {
caption.children.push({
type: 'supplementaryMaterial',
enumerator: container.enumerator,
figIdentifier: container.identifier,
sourceUrl: container.source.url,
sourceSlug: container.source.slug,
embedIdentifier: identifier,
});
}
if (caption.children?.length && !select('caption', container)) {
container.children.push(caption);
}
if (container.kind === 'figure') {
container.children = [
...container.children.filter((child) => child.type.startsWith('caption')),
...container.children.filter((child) => !child.type.startsWith('caption')),
];
}
});
}
export const containerPlugin = () => (tree) => {
containerTransform(tree);
};