@@ -2,6 +2,17 @@ import type { Properties, Root } from 'hast';
22import { visit } from 'unist-util-visit' ;
33import type { VFile } from 'vfile' ;
44
5+ /**
6+ * HAST properties to preserve on the node
7+ */
8+ const HAST_PRESERVED_PROPERTIES = [
9+ // HAST: className -> HTML: class
10+ 'className' ,
11+
12+ // HAST: htmlFor -> HTML: for
13+ 'htmlFor' ,
14+ ] ;
15+
516export function rehypeImages ( ) {
617 return function ( tree : Root , file : VFile ) {
718 if ( ! file . data . astro ?. localImagePaths ?. length && ! file . data . astro ?. remoteImagePaths ?. length ) {
@@ -16,13 +27,13 @@ export function rehypeImages() {
1627 if ( typeof node . properties ?. src !== 'string' ) return ;
1728
1829 const src = decodeURI ( node . properties . src ) ;
19- let newProperties : Properties ;
30+ let imageProperties : Properties ;
2031
2132 if ( file . data . astro ?. localImagePaths ?. includes ( src ) ) {
2233 // Override the original `src` with the new, decoded `src` that Astro will better understand.
23- newProperties = { ...node . properties , src } ;
34+ imageProperties = { ...node . properties , src } ;
2435 } else if ( file . data . astro ?. remoteImagePaths ?. includes ( src ) ) {
25- newProperties = {
36+ imageProperties = {
2637 // By default, markdown images won't have width and height set. However, just in case another user plugin does set these, we should respect them.
2738 inferSize : 'width' in node . properties && 'height' in node . properties ? undefined : true ,
2839 ...node . properties ,
@@ -33,12 +44,21 @@ export function rehypeImages() {
3344 return ;
3445 }
3546
47+ // Separate HAST-only properties from image processing properties
48+ const hastProperties : Properties = { } ;
49+ for ( const key of HAST_PRESERVED_PROPERTIES ) {
50+ if ( key in imageProperties ) {
51+ hastProperties [ key ] = imageProperties [ key ] ;
52+ delete imageProperties [ key ] ;
53+ }
54+ }
55+
3656 // Initialize or increment occurrence count for this image
3757 const index = imageOccurrenceMap . get ( node . properties . src ) || 0 ;
3858 imageOccurrenceMap . set ( node . properties . src , index + 1 ) ;
3959
4060 // Set a special property on the image so later Astro code knows to process this image.
41- node . properties = { __ASTRO_IMAGE_ : JSON . stringify ( { ...newProperties , index } ) } ;
61+ node . properties = { ... hastProperties , __ASTRO_IMAGE_ : JSON . stringify ( { ...imageProperties , index } ) } ;
4262 } ) ;
4363 } ;
4464}
0 commit comments