|
| 1 | +import {visit} from 'unist-util-visit'; |
| 2 | + |
| 3 | +const SIZE_FROM_ALT_RE = /\s*=\s*(?:(\d+)\s*x\s*(\d+)|(\d+)\s*x|x\s*(\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 | + * Behavior: |
| 16 | + * - Extracts the trailing "=WxH" (width-only/height-only also supported). |
| 17 | + * - Cleans the ALT text by removing the size suffix. |
| 18 | + * - Adds numeric `width`/`height` attributes to the <img> element. |
| 19 | + */ |
| 20 | +export default function remarkImageResize() { |
| 21 | + return tree => |
| 22 | + visit(tree, {type: 'mdxJsxTextElement', name: 'img'}, node => { |
| 23 | + // Handle MDX JSX <img> produced by remark-mdx-images |
| 24 | + const altIndex = node.attributes.findIndex(a => a && a.name === 'alt'); |
| 25 | + const altValue = |
| 26 | + altIndex !== -1 && typeof node.attributes[altIndex].value === 'string' |
| 27 | + ? node.attributes[altIndex].value |
| 28 | + : null; |
| 29 | + if (altValue) { |
| 30 | + const sizeMatch = altValue.match(SIZE_FROM_ALT_RE); |
| 31 | + if (sizeMatch) { |
| 32 | + const [, wBoth, hBoth, wOnlyWithX, hOnlyWithX] = sizeMatch; |
| 33 | + const wStr = wBoth || wOnlyWithX || undefined; |
| 34 | + const hStr = hBoth || hOnlyWithX || undefined; |
| 35 | + const cleanedAlt = altValue.replace(SIZE_FROM_ALT_RE, '').trim(); |
| 36 | + // set cleaned alt |
| 37 | + node.attributes[altIndex] = { |
| 38 | + type: 'mdxJsxAttribute', |
| 39 | + name: 'alt', |
| 40 | + value: cleanedAlt, |
| 41 | + }; |
| 42 | + |
| 43 | + if (wStr) |
| 44 | + node.attributes.push({type: 'mdxJsxAttribute', name: 'width', value: wStr}); |
| 45 | + if (hStr) |
| 46 | + node.attributes.push({type: 'mdxJsxAttribute', name: 'height', value: hStr}); |
| 47 | + } |
| 48 | + } |
| 49 | + }); |
| 50 | +} |
0 commit comments