Fix issue with popover on full sn links (#1216)

* Fix issue with popover on full sn links

* allow custom text for internal links

---------

Co-authored-by: keyan <keyan.kousha+huumn@gmail.com>
This commit is contained in:
Tom 2024-06-03 18:05:31 +01:00 committed by GitHub
parent 86b857b8d4
commit d454bbdb72
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 3 deletions

View File

@ -186,6 +186,7 @@ export default memo(function Text ({ rel, imgproxyUrls, children, tab, itemId, o
} catch { } catch {
// ignore invalid URLs // ignore invalid URLs
} }
const internalURL = process.env.NEXT_PUBLIC_URL const internalURL = process.env.NEXT_PUBLIC_URL
if (!!text && !/^https?:\/\//.test(text)) { if (!!text && !/^https?:\/\//.test(text)) {
if (props['data-footnote-ref'] || typeof props['data-footnote-backref'] !== 'undefined') { if (props['data-footnote-ref'] || typeof props['data-footnote-backref'] !== 'undefined') {
@ -210,6 +211,19 @@ export default memo(function Text ({ rel, imgproxyUrls, children, tab, itemId, o
</UserPopover> </UserPopover>
) )
} else if (href.startsWith('/') || url?.origin === internalURL) { } else if (href.startsWith('/') || url?.origin === internalURL) {
try {
const linkText = parseInternalLinks(href)
if (linkText) {
return (
<ItemPopover id={linkText.replace('#', '').split('/')[0]}>
<Link href={href}>{text}</Link>
</ItemPopover>
)
}
} catch {
// ignore errors like invalid URLs
}
return ( return (
<Link <Link
id={props.id} id={props.id}

View File

@ -26,14 +26,22 @@ export function removeTracking (value) {
/** /**
* parse links like https://stacker.news/items/123456 as #123456 * parse links like https://stacker.news/items/123456 as #123456
*/ */
export function isItemPath (pathname) {
if (!pathname) return false
const [page, id] = pathname.split('/').filter(part => !!part)
return page === 'items' && /^[0-9]+$/.test(id)
}
export function parseInternalLinks (href) { export function parseInternalLinks (href) {
const url = new URL(href) const url = new URL(href)
const internalURL = process.env.NEXT_PUBLIC_URL const internalURL = process.env.NEXT_PUBLIC_URL
const { pathname, searchParams } = url const { pathname, searchParams } = url
// ignore empty parts which exist due to pathname starting with '/' // ignore empty parts which exist due to pathname starting with '/'
const emptyPart = part => !!part if (isItemPath(pathname) && url.origin === internalURL) {
const parts = pathname.split('/').filter(emptyPart) const parts = pathname.split('/').filter(part => !!part)
if (parts[0] === 'items' && /^[0-9]+$/.test(parts[1]) && url.origin === internalURL) {
const itemId = parts[1] const itemId = parts[1]
// check for valid item page due to referral links like /items/123456/r/ekzyis // check for valid item page due to referral links like /items/123456/r/ekzyis
const itemPages = ['edit', 'ots', 'related'] const itemPages = ['edit', 'ots', 'related']