import { useCallback } from 'react'; import type { ComponentProps, FC } from 'react'; import { Link } from 'react-router-dom'; import type { OnElementHandler } from '@/flavours/glitch/utils/html'; export interface HandledLinkProps { href: string; text: string; hashtagAccountId?: string; mentionAccountId?: string; } export const HandledLink: FC> = ({ href, text, hashtagAccountId, mentionAccountId, ...props }) => { // Handle hashtags if (text.startsWith('#')) { const hashtag = text.slice(1).trim(); return ( #{hashtag} ); } else if (text.startsWith('@')) { // Handle mentions const mention = text.slice(1).trim(); return ( @{mention} ); } // Non-absolute paths treated as internal links. if (href.startsWith('/')) { return ( {text} ); } try { const url = new URL(href); const [first, ...rest] = url.pathname.split('/').slice(1); // Start at 1 to skip the leading slash. return ( {url.protocol + '//'} {`${url.hostname}/${first ?? ''}`} {'/' + rest.join('/')} ); } catch { return text; } }; export const useElementHandledLink = ({ hashtagAccountId, hrefToMentionAccountId, }: { hashtagAccountId?: string; hrefToMentionAccountId?: (href: string) => string | undefined; } = {}) => { const onElement = useCallback( (element, { key, ...props }) => { if (element instanceof HTMLAnchorElement) { const mentionId = hrefToMentionAccountId?.(element.href); return ( ); } return undefined; }, [hashtagAccountId, hrefToMentionAccountId], ); return { onElement }; };