import { NDKKind } from '@nostr-dev-kit/ndk'
import { ProfileLink } from 'components/ProfileSection'
import { nip19 } from 'nostr-tools'
import { useMemo } from 'react'
import { Fragment } from 'react/jsx-runtime'
import { BlogPreview } from './internal/BlogPreview'
import { ModPreview } from './internal/ModPreview'
import { NoteWrapper } from './internal/NoteWrapper'
import { NIP05_REGEX } from 'nostr-tools/nip05'
import { isValidImageUrl, isValidUrl, isValidVideoUrl } from 'utils'
interface NoteRenderProps {
content: string
}
const link =
/(?:https?:\/\/|www\.)(?:[a-zA-Z0-9.-]+\.[a-zA-Z]+(?::\d+)?)(?:[/?#][\p{L}\p{N}\p{M}&.-/?=#\-@%+_,:!~*]*)?/gu
const nostrMention =
/(?:nostr:|@)?(?:npub|note|nprofile|nevent|naddr)1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58,}/gi
const nostrEntity =
/(npub|note|nprofile|nevent|naddr)1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58,}/gi
const nostrNip5Mention = /(?:nostr:|@)([^\s]{1,64}@[^\s]+\.[^\s]{2,})/gi
export const NoteRender = ({ content }: NoteRenderProps) => {
const _content = useMemo(() => {
if (!content) return
const parts = content.split(
new RegExp(
`(${link.source})|(${nostrMention.source})|${nostrNip5Mention.source}`,
'gui'
)
)
const _parts = parts.map((part, index) => {
if (link.test(part)) {
const [href] = part.match(link) || []
if (href && isValidUrl(href)) {
if (isValidImageUrl(href)) {
// Image
return
} else if (isValidVideoUrl(href)) {
// Video
return
}
}
// Link
return (
{href}
)
} else if (nostrMention.test(part)) {
const [encoded] = part.match(nostrEntity) || []
if (!encoded) return part
try {
const decoded = nip19.decode(encoded)
switch (decoded.type) {
case 'nprofile':
return
case 'npub':
return
case 'note':
return
case 'nevent':
return
case 'naddr':
return (
{handleNaddr(decoded.data, part)}
)
default:
return part
}
} catch (error) {
return part
}
} else if (NIP05_REGEX.test(part)) {
const [nip05] = part.match(NIP05_REGEX) || []
return
} else {
return part
}
})
return _parts
}, [content])
return _content
}
function handleNaddr(data: nip19.AddressPointer, original: string) {
const { kind } = data
if (kind === NDKKind.Article) {
return
} else if (kind === NDKKind.Classified) {
return
} else {
return <>{original}>
}
}