@@ -6,6 +6,7 @@ import { h } from 'hastscript';
6
6
import type { Transformer } from 'unified' ;
7
7
import { SKIP , visit } from 'unist-util-visit' ;
8
8
import type { HookParameters , StarlightConfig } from '../types' ;
9
+ import { resolveCollectionPath } from '../utils/collection' ;
9
10
10
11
const AnchorLinkIcon = h (
11
12
'span' ,
@@ -24,10 +25,14 @@ const AnchorLinkIcon = h(
24
25
* Add anchor links to headings.
25
26
*/
26
27
export default function rehypeAutolinkHeadings (
27
- useTranslationsForLang : HookParameters < 'config:setup' > [ 'useTranslations' ] ,
28
- absolutePathToLang : HookParameters < 'config:setup' > [ 'absolutePathToLang' ]
28
+ docsCollectionPath : string ,
29
+ useTranslationsForLang : AutolinkHeadingsOptions [ 'useTranslations' ] ,
30
+ absolutePathToLang : AutolinkHeadingsOptions [ 'absolutePathToLang' ]
29
31
) {
30
32
const transformer : Transformer < Root > = ( tree , file ) => {
33
+ // If the document is not part of the Starlight docs collection, skip it.
34
+ if ( ! normalizePath ( file . path ) . startsWith ( docsCollectionPath ) ) return ;
35
+
31
36
const pageLang = absolutePathToLang ( file . path ) ;
32
37
const t = useTranslationsForLang ( pageLang ) ;
33
38
@@ -67,7 +72,9 @@ export default function rehypeAutolinkHeadings(
67
72
68
73
interface AutolinkHeadingsOptions {
69
74
starlightConfig : Pick < StarlightConfig , 'markdown' > ;
70
- astroConfig : { experimental : Pick < AstroConfig [ 'experimental' ] , 'headingIdCompat' > } ;
75
+ astroConfig : Pick < AstroConfig , 'srcDir' > & {
76
+ experimental : Pick < AstroConfig [ 'experimental' ] , 'headingIdCompat' > ;
77
+ } ;
71
78
useTranslations : HookParameters < 'config:setup' > [ 'useTranslations' ] ;
72
79
absolutePathToLang : HookParameters < 'config:setup' > [ 'absolutePathToLang' ] ;
73
80
}
@@ -85,10 +92,24 @@ export const starlightAutolinkHeadings = ({
85
92
rehypeHeadingIds ,
86
93
{ experimentalHeadingIdCompat : astroConfig . experimental ?. headingIdCompat } ,
87
94
] ,
88
- rehypeAutolinkHeadings ( useTranslations , absolutePathToLang ) ,
95
+ rehypeAutolinkHeadings (
96
+ normalizePath ( resolveCollectionPath ( 'docs' , astroConfig . srcDir ) ) ,
97
+ useTranslations ,
98
+ absolutePathToLang
99
+ ) ,
89
100
]
90
101
: [ ] ;
91
102
103
+ /**
104
+ * File path separators seems to be inconsistent on Windows when the rehype plugin is used on
105
+ * Markdown vs MDX files.
106
+ * For the time being, we normalize the path to unix style path.
107
+ */
108
+ const backSlashRegex = / \\ / g;
109
+ function normalizePath ( path : string ) {
110
+ return path . replace ( backSlashRegex , '/' ) ;
111
+ }
112
+
92
113
// This utility is inlined from https://github.com/syntax-tree/hast-util-heading-rank
93
114
// Copyright (c) 2020 Titus Wormer <[email protected] >
94
115
// MIT License: https://github.com/syntax-tree/hast-util-heading-rank/blob/main/license
0 commit comments