Skip to content

Commit db510a4

Browse files
committed
refactor: remove replacing links in readme parsing, intercept v-html clicks and handle redirects there
1 parent d43407c commit db510a4

2 files changed

Lines changed: 23 additions & 8 deletions

File tree

app/pages/[...package].vue

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,28 @@ defineOgImageComponent('Package', {
473473
downloads: () => (downloads.value ? formatNumber(downloads.value.downloads) : ''),
474474
license: () => pkg.value?.license ?? '',
475475
})
476+
477+
// We're using only @click because it catches touch events and enter hits
478+
function handleClick(evt: MouseEvent) {
479+
const target = evt?.target ? (evt.target as HTMLElement).closest('a') : undefined
480+
if (target) {
481+
const npmjsMatch = target
482+
.getAttribute('href')
483+
?.match(/^(?:https?:\/\/)?(?:www\.)?npmjs\.(?:com|org)\/(.+)/)
484+
if (npmjsMatch && npmjsMatch?.[1]) {
485+
const urlPath = npmjsMatch[1]
486+
const hasMatchedRoutes = router.resolve(urlPath)?.matched?.reduce(
487+
// omit matching the wildcard route
488+
(result: boolean, route) => result || route.path !== '/:package(.*)*',
489+
false,
490+
)
491+
if (hasMatchedRoutes) {
492+
evt.preventDefault()
493+
window.open(`https://npmx.dev/${urlPath}`, '_blank')
494+
}
495+
}
496+
}
497+
}
476498
</script>
477499

478500
<template>
@@ -1217,6 +1239,7 @@ defineOgImageComponent('Package', {
12171239
v-if="readmeData?.html"
12181240
class="readme-content prose prose-invert max-w-[70ch]"
12191241
v-html="readmeData.html"
1242+
@click="handleClick"
12201243
/>
12211244
<p v-else class="text-fg-subtle italic">
12221245
{{ $t('package.readme.no_readme') }}

server/utils/readme.ts

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -401,14 +401,6 @@ export async function renderReadmeHtml(
401401
if (attribs.href && hasProtocol(attribs.href, { acceptRelative: true })) {
402402
attribs.rel = 'nofollow noreferrer noopener'
403403
attribs.target = '_blank'
404-
405-
// Replace npmjs.com|npmjs.org urls with npmx.dev
406-
const npmjsMatch = attribs.href.match(
407-
/^(?:https?:\/\/)?(?:www\.)?npmjs\.(?:com|org)\/(.+)/,
408-
)
409-
if (npmjsMatch) {
410-
attribs.href = `https://npmx.dev/${npmjsMatch[1]}`
411-
}
412404
}
413405
return { tagName, attribs }
414406
},

0 commit comments

Comments
 (0)