@@ -42,4 +42,43 @@ export const getExampleCode = async (exampleId: string): Promise<string> => {
4242} ;
4343
4444export const removeNestedReferencePaths = ( route : string ) : string =>
45- route . replace ( / c o n s t a n t s \/ | t y p e s \/ / , "" )
45+ route . replace ( / c o n s t a n t s \/ | t y p e s \/ / , "" )
46+
47+ export const rewriteRelativeLink = ( url : string ) : string => {
48+ let updatedUrl : string ;
49+
50+ if ( / ^ ( ( h t t p s ? : \/ ) ? ) \/ / . exec ( url ) || url . startsWith ( 'mailto:' ) ) {
51+ // Leave absolute paths alone
52+ updatedUrl = url ;
53+ } else if ( url . startsWith ( '#' ) ) {
54+ // Leave links to headings alone
55+ updatedUrl = url ;
56+ } else {
57+ // Convert relative paths to '../' (because pages that started as files in the same directory
58+ // get turned into directories themselves, we need to go up a directory in the link)
59+ if ( url . startsWith ( './' ) ) {
60+ updatedUrl = `.${ url } ` ;
61+ } else if ( ! url . startsWith ( '../' ) ) {
62+ updatedUrl = `../${ url } ` ;
63+ } else {
64+ updatedUrl = url ;
65+ }
66+
67+ // Relative links to md files should be turned into pages
68+ if ( updatedUrl . endsWith ( '.md' ) ) {
69+ updatedUrl = updatedUrl . replace ( / \. m d $ / , '' ) ;
70+ }
71+ }
72+
73+ // Add a trailing / if the link isn't to a file and does not have query params or a hash reference
74+ if (
75+ ! updatedUrl . endsWith ( '/' ) &&
76+ ! / ( \. \w + ) $ / . exec ( updatedUrl ) &&
77+ ! updatedUrl . includes ( '?' ) &&
78+ ! / # ( [ \w \- ] + ) $ / . exec ( updatedUrl )
79+ ) {
80+ updatedUrl += '/' ;
81+ }
82+
83+ return updatedUrl ;
84+ } ;
0 commit comments