Skip to content

Commit

Permalink
fix: give a default baseUrl on markdown links (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
Xstoudi authored Mar 23, 2024
1 parent af837c2 commit ab3d5af
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
29 changes: 28 additions & 1 deletion app/services/markdown_renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,37 @@ export class MarkdownRenderer {
})
}

/**
* Rewrite markdown link tokens to include
* baseUrl when there isn't one.
*/
#rewrite(tokens: any[], baseUrl: string) {
for (const token of tokens) {
if (token.type === 'link_open') {
for (const attr of token.attrs) {
if (attr[0] === 'href') {
const value: string = attr[1]
try {
new URL(value)
} catch (_) {
attr[1] = new URL(value, `${baseUrl}/`).href
}
}
}
}
if (token.children !== null) {
this.#rewrite(token.children, baseUrl)
}
}
}

/**
* Render the markdown to HTML
*/
render(markdown: string): string {
render(markdown: string, baseUrl: string): string {
this.#renderer.core.ruler.push('baseurl', (state) => {
this.#rewrite(state.tokens, baseUrl)
})
const unsanitized = this.#renderer.render(markdown)
return this.#sanitize(unsanitized)
}
Expand Down
2 changes: 1 addition & 1 deletion app/services/packages_fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export class PackagesFetcher {

return {
package: this.#mergePackageStatsAndInfo(pkg, stats),
readme: this.#markdownRenderer.render(readme),
readme: this.#markdownRenderer.render(readme, pkg.github),
}
}
}

0 comments on commit ab3d5af

Please sign in to comment.