|
| 1 | +import {visit} from 'unist-util-visit'; |
| 2 | + |
| 3 | +const SIZE_FROM_ALT_RE = /\s*=\s*(\d+)?x?(\d+)?\s*$/; |
| 4 | +/** |
| 5 | + * remark plugin to parse width/height hints from the image ALT text. |
| 6 | + * |
| 7 | + * This plugin is intended to run AFTER `remark-mdx-images`, so it processes |
| 8 | + * mdxJsxTextElement nodes named `img` (i.e., <img /> in MDX). |
| 9 | + * |
| 10 | + * Supported ALT suffixes (trailing in ALT text): |
| 11 | + *  |
| 12 | + *  |
| 13 | + *  |
| 14 | + *  |
| 15 | + * |
| 16 | + * Behavior: |
| 17 | + * - Extracts the trailing "=WxH" (width-only/height-only also supported). |
| 18 | + * - Cleans the ALT text by removing the size suffix. |
| 19 | + * - Adds numeric `width`/`height` attributes to the <img> element. |
| 20 | + */ |
| 21 | +export default function remarkImageResize() { |
| 22 | + return tree => |
| 23 | + visit(tree, {type: 'mdxJsxTextElement', name: 'img'}, node => { |
| 24 | + |
| 25 | + // Handle MDX JSX <img> produced by remark-mdx-images |
| 26 | + const altIndex = node.attributes.findIndex(a => a && a.name === 'alt'); |
| 27 | + const altValue = altIndex !== -1 && typeof node.attributes[altIndex].value === 'string' |
| 28 | + ? node.attributes[altIndex].value |
| 29 | + : null; |
| 30 | + if (altValue) { |
| 31 | + const m = altValue.match(SIZE_FROM_ALT_RE); |
| 32 | + if (m) { |
| 33 | + const [, wStr, hStr] = m; |
| 34 | + const cleanedAlt = altValue.replace(SIZE_FROM_ALT_RE, '').trim(); |
| 35 | + // set cleaned alt |
| 36 | + node.attributes[altIndex] = {type: 'mdxJsxAttribute', name: 'alt', value: cleanedAlt}; |
| 37 | + // remove any pre-existing width/height attributes to avoid duplicates |
| 38 | + node.attributes = node.attributes.filter(a => !(a && (a.name === 'width' || a.name === 'height'))); |
| 39 | + if (wStr) node.attributes.push({type: 'mdxJsxAttribute', name: 'width', value: wStr}); |
| 40 | + if (hStr) node.attributes.push({type: 'mdxJsxAttribute', name: 'height', value: hStr}); |
| 41 | + } |
| 42 | + } |
| 43 | + }); |
| 44 | +} |
0 commit comments