-
Notifications
You must be signed in to change notification settings - Fork 48
/
images.ts
34 lines (32 loc) · 1.35 KB
/
images.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import type { Plugin } from 'unified';
import type { Container, Paragraph, PhrasingContent, Image } from 'myst-spec';
import { select, selectAll } from 'unist-util-select';
import type { GenericParent } from 'myst-common';
import { toText } from 'myst-common';
/**
* Generate image alt text from figure caption
*/
export function imageAltTextTransform(tree: GenericParent) {
const containers = selectAll('container', tree) as Container[];
// Go through containers in reverse so subfigures captions are preferentially applied
containers.reverse().forEach((container) => {
const images = selectAll('image', container) as Image[];
images.forEach((image) => {
if (!image || image.alt) return;
// Only look at direct child captions
const para = select(
'paragraph',
container.children.find((child) => child.type === 'caption'),
) as Paragraph;
if (!para) return;
// Do not write the captionNumber to image alt text
const content = para.children?.filter((n) => (n.type as string) !== 'captionNumber');
if (!content || content.length < 1) return;
image.alt = toText(content as PhrasingContent[]);
(image.data ??= {}).altTextIsAutoGenerated = true;
});
});
}
export const imageAltTextPlugin: Plugin<[], GenericParent, GenericParent> = () => (tree) => {
imageAltTextTransform(tree);
};