diff --git a/.agents/skills/note-content/SKILL.md b/.agents/skills/note-content/SKILL.md index 15db5a8..e969256 100644 --- a/.agents/skills/note-content/SKILL.md +++ b/.agents/skills/note-content/SKILL.md @@ -1,55 +1,104 @@ --- name: note-content -description: Render plaintext Nostr note content (kind 1, 11, 1111) with linkified URLs, hashtags, and Nostr mentions (npub/nprofile/note/nevent). Turns raw event.content into React nodes with clickable links and @-mentions resolved via useAuthor. +description: Render plaintext Nostr note content (kind 1, 11, 1111) with linkified URLs, hashtags, Nostr mentions, custom emoji (NIP-30), flag-to-country links, inline images/video/audio, BOLT11 lightning invoices, embedded nevent/naddr cards, and link previews. --- # Rich Text Rendering for Nostr Notes -This skill provides the `NoteContent` component, which turns a Nostr event's plaintext `content` field into React nodes with: +This skill provides a full-featured `NoteContent` component that turns a Nostr event's plaintext `content` field into rich React output. It is adapted from the production implementation in the Ditto client and handles: -- URLs rendered as external `` links -- Hashtags rendered as internal links to `/t/` -- Nostr URIs (`nostr:npub1...`, `nostr:nprofile1...`, `nostr:note1...`, `nostr:nevent1...`) rendered as internal links; `npub`/`nprofile` become `@displayname` mentions resolved via `useAuthor` - -Use it whenever you display kind 1 (short text notes), kind 11 (threads), kind 1111 (comments), or any other event with a freeform plaintext `content` field. +- URLs — linkified, with trailing-punctuation stripping and line-end-aware rich preview cards (`LinkEmbed`) vs. inline links +- `wss://` / `ws://` relay URLs — internal links to `/r/` +- Image URLs — rendered inline as thumbnails, with consecutive images auto-grouped into a gallery and a shared lightbox +- Video/audio URLs — inline players; webxdc `.xdc` URLs — WebXDC app embeds (stub) +- NIP-94 `imeta`-declared media — appended at end when the content string doesn't reference them +- BOLT11 lightning invoices — rendered as `LightningInvoiceCard` +- Hashtags — internal links to `/t/`, with full Unicode letter support (`\p{L}\p{N}_`) +- Nostr mentions (`nostr:npub…`, `nostr:nprofile…`, bare `npub…`, `@npub…`) — resolved via `useAuthor`, rendered as `@DisplayName` links with optional `ProfileHoverCard` +- Embedded notes (`nostr:note1…`, `nostr:nevent1…`) — rendered as `EmbeddedNote` cards, enriched with relay/author hints from `q` tags +- Embedded addressable events (`nostr:naddr1…` or URLs containing an `naddr1` fragment) — rendered as `EmbeddedNaddr` cards +- Custom emoji (NIP-30 `:shortcode:`) — inline images from the event's own `emoji` tags, with the viewer's `useCustomEmojis` collection as fallback +- Flag emoji (🇺🇸, 🇵🇱, …) — linkified to `/i/iso3166:` pages +- "Emoji-only" posts — auto-detected and rendered at large size (`text-5xl`) +- Whitespace normalization — leading/trailing whitespace trimmed, redundant blank lines around block embeds collapsed +- Opt-out props — `disableEmbeds`, `disableMediaEmbeds`, `disableNoteEmbeds`, `hideEmbedImages` for preview contexts and recursive embed cards **This component is not included in the project by default.** When the user's app displays text notes or other plaintext event content, follow the setup instructions below to install it. ## Files Provided by This Skill +Install all files from `.agents/skills/note-content/files/` into their matching `src/` locations: + +### Core component & test + | Skill file | Copy to | |---|---| | `files/components/NoteContent.tsx` | `src/components/NoteContent.tsx` | | `files/components/NoteContent.test.tsx` | `src/components/NoteContent.test.tsx` | +### Library helpers + +| Skill file | Copy to | +|---|---| +| `files/lib/mediaUrls.ts` | `src/lib/mediaUrls.ts` | +| `files/lib/sanitizeUrl.ts` | `src/lib/sanitizeUrl.ts` | +| `files/lib/imeta.ts` | `src/lib/imeta.ts` | +| `files/lib/customEmoji.ts` | `src/lib/customEmoji.ts` | +| `files/lib/getDisplayName.ts` | `src/lib/getDisplayName.ts` | +| `files/lib/avatarShape.ts` | `src/lib/avatarShape.ts` | +| `files/lib/countries.ts` | `src/lib/countries.ts` | + +### Hooks + +| Skill file | Copy to | +|---|---| +| `files/hooks/useCustomEmojis.ts` | `src/hooks/useCustomEmojis.ts` | +| `files/hooks/useBlossomFallback.ts` | `src/hooks/useBlossomFallback.ts` | +| `files/hooks/useProfileUrl.ts` | `src/hooks/useProfileUrl.ts` | + +### Companion components (minimal stubs — replace with richer versions later) + +| Skill file | Copy to | Responsibility | +|---|---|---| +| `files/components/LinkEmbed.tsx` | `src/components/LinkEmbed.tsx` | Rich link preview card | +| `files/components/EmbeddedNote.tsx` | `src/components/EmbeddedNote.tsx` | `note1` / `nevent1` quote card | +| `files/components/EmbeddedNaddr.tsx` | `src/components/EmbeddedNaddr.tsx` | `naddr1` addressable-event card | +| `files/components/LightningInvoiceCard.tsx` | `src/components/LightningInvoiceCard.tsx` | BOLT11 invoice display / pay button | +| `files/components/VideoPlayer.tsx` | `src/components/VideoPlayer.tsx` | Inline video | +| `files/components/AudioVisualizer.tsx` | `src/components/AudioVisualizer.tsx` | Inline audio | +| `files/components/WebxdcEmbed.tsx` | `src/components/WebxdcEmbed.tsx` | WebXDC app launcher | +| `files/components/ImageGallery.tsx` | `src/components/ImageGallery.tsx` | Image grid + shared `Lightbox` | +| `files/components/ProfileHoverCard.tsx` | `src/components/ProfileHoverCard.tsx` | Hover profile preview | +| `files/components/CustomEmoji.tsx` | `src/components/CustomEmoji.tsx` | `CustomEmojiImg` + `EmojifiedText` | + +The companion component stubs are **functional** — they render something sensible for every embed type — but deliberately minimal. Read the comment at the top of each file for notes on how to replace them with production-grade versions (OpenGraph scrapers, blurhash placeholders, WebLN-backed invoice payment, etc.). + ## Setup Instructions ### 1. Dependencies -No extra npm packages are required. The component uses packages already present in the template: +No extra npm packages are required. The skill uses only packages already present in the template: -- `react`, `react-router-dom` (for internal `Link` navigation) -- `nostr-tools` (`nip19` for decoding `npub`/`nprofile` references) -- `@nostrify/nostrify` (`NostrEvent` type) +- `react`, `react-router-dom` (internal `Link`) +- `nostr-tools` (`nip19` decoding/encoding) +- `@nostrify/nostrify` (`NostrEvent`, `NostrMetadata`) ### 2. Copy the Skill Files Into `src/` -Copy both files from `.agents/skills/note-content/files/components/` into `src/components/`. The component imports: - -- `@/hooks/useAuthor` — resolves mention display names from pubkeys -- `@/lib/genUserName` — fallback deterministic name when a mentioned user has no profile metadata -- `@/lib/utils` — `cn()` class-merge helper - -All three are standard in the template; no extra work is needed beyond copying the files. +Copy every file listed in the tables above from `.agents/skills/note-content/files/` into its corresponding location under `src/`. Preserve the exact paths — everything uses `@/` imports that depend on these locations. ### 3. Routing Expectations -The component generates links that assume the host app has these routes wired up in `AppRouter.tsx`: +`NoteContent` generates links that assume these routes exist in `AppRouter.tsx`: | Generated link | Route expected | |---|---| -| `/` (e.g. `/npub1...`, `/note1...`, `/nevent1...`) | Handled by the template's NIP-19 page at `/:nip19` | -| `/t/` | **Not in the default template.** If you want hashtag pages to work, add a route like `} />` in `AppRouter.tsx`. If you don't add one, hashtag links will fall through to the 404 page. | +| `/` (e.g. `/npub1…`, `/note1…`, `/nevent1…`, `/naddr1…`) | Handled by the template's `NIP19Page` at `/:nip19` | +| `/t/` | **Not in the default template.** Add `} />` if you want hashtag pages. | +| `/r/` | **Not in the default template.** Add `} />` if you want relay pages. | +| `/i/iso3166:` | **Not in the default template.** Add `} />` if you want flag-emoji country pages. | + +Any unrouted link falls through to the 404 page — nothing breaks, but the affordance is inert. ## Usage @@ -67,32 +116,71 @@ function Post({ event }: { event: NostrEvent }) { } ``` -For events that may span multiple lines (any short text note), wrap with whitespace-preserving styles. `NoteContent` already applies `whitespace-pre-wrap break-words` internally, but you can pass additional classes via `className`. +### Props + +```ts +interface NoteContentProps { + event: NostrEvent; + className?: string; + /** Render URLs as inline links only — suppress LinkEmbed / image / video / audio / invoice previews. */ + disableEmbeds?: boolean; + /** Hide the thumbnail in LinkEmbed previews (useful when a cover image is already shown). */ + hideEmbedImages?: boolean; + /** Render nostr:nevent/note/naddr embeds as inline links, not cards. Use inside recursive quote cards. */ + disableNoteEmbeds?: boolean; + /** Suppress images, galleries, and video/audio players entirely. Used inside lightweight quote cards. */ + disableMediaEmbeds?: boolean; +} +``` + +### Preview contexts + +Inside a **recursive quote card** (e.g. when `EmbeddedNote` itself renders `NoteContent` for the quoted note), pass `disableNoteEmbeds disableMediaEmbeds` to prevent unbounded nesting and keep the card compact. + +Inside a **compose preview** or a **triple-dot menu preview**, pass `disableEmbeds` to show only linkified URLs without any heavy previews. + +## Upgrading the Companion Components + +The stubs shipped here are deliberately minimal so the skill works immediately and can be committed without dragging in hundreds of extra files. When your app needs richer behaviour, progressively upgrade individual components — the JSX surface in `NoteContent` stays the same. Common upgrade paths: + +- **`LinkEmbed`** → fetch OpenGraph metadata (title, description, thumbnail), detect YouTube/Twitter/Bluesky for embeddable players +- **`EmbeddedNote` / `EmbeddedNaddr`** → introduce a `useEvent(id, relays, author)` / `useAddrEvent({kind, pubkey, identifier}, relays)` hook and render the fetched event using a nested `` +- **`LightningInvoiceCard`** → pair with the `nwc` skill's `useWallet` / `useZaps` to pay directly, decode the BOLT11 for amount/description/expiry, render a QR code +- **`VideoPlayer` / `AudioVisualizer`** → show blurhash placeholders from `imeta`, add full-screen / background-playback controls, respect `dim` for correct aspect ratio on first paint +- **`ImageGallery` / `Lightbox`** → add pinch-zoom, swipe gestures, blurhash placeholders, alt-text overlays +- **`WebxdcEmbed`** → host the WebXDC app in a sandboxed iframe with a Nostr-backed `sendUpdate` / `setUpdateListener` bridge +- **`ProfileHoverCard`** → open a shadcn `HoverCard` with the author's avatar, display name, bio, follow count, follow/zap/DM actions +- **`useCustomEmojis`** → fetch the viewer's kind 10030 "Emoji List" event and any kind 30030 "Emoji Set" events it references, expose all shortcode→URL pairs +- **`useBlossomFallback`** → parse the URL's blossom hash, rotate through the viewer's BUD-03 "User Server List" (kind 10063) on `onError` +- **`useProfileUrl`** → route by the user's verified `nip05` handle when present (requires a `/:handle` route), fall back to `/` ## Supported Content Patterns | Pattern in `event.content` | Rendered as | |---|---| -| `https://example.com/...` | `` (blue link) | -| `nostr:npub1abc...` | `@DisplayName` link to `/npub1abc...` — blue if profile has a real name, gray if using generated fallback | -| `nostr:nprofile1...` | Same as `npub` — decoded to pubkey then resolved via `useAuthor` | -| `nostr:note1...` | Link to `/note1...` displaying the full `nostr:note1...` string | -| `nostr:nevent1...` | Link to `/nevent1...` displaying the full `nostr:nevent1...` string | -| `#hashtag` | Internal link to `/t/hashtag` | -| Plain text | Rendered as-is, preserving whitespace | +| `https://example.com/...` | Inline link if mid-line, or `LinkEmbed` card if URL ends a line | +| `https://…/image.jpg` (any `IMAGE_EXTS`) | Inline image; 2+ consecutive → `ImageGallery` | +| `https://…/video.mp4` (any `VIDEO_EXTS`) | `VideoPlayer` | +| `https://…/song.mp3` (any `AUDIO_EXTS`) | `AudioVisualizer` | +| `https://…/app.xdc` | `WebxdcEmbed` | +| `wss://relay…` | Internal `/r/` link | +| URL containing `naddr1…` | Paired URL + `EmbeddedNaddr` card | +| `lightning:lnbc…` / `lnbc…` / `lntb…` / `lnbcrt…` / `lntbs…` | `LightningInvoiceCard` | +| `nostr:npub1…` or `nostr:nprofile1…` or bare `npub1…` | `@DisplayName` mention link (through `ProfileHoverCard`) | +| `nostr:note1…` / `nostr:nevent1…` or bare | `EmbeddedNote` card (relay/author hints pulled from event's `q` tags) | +| `nostr:naddr1…` or bare | `EmbeddedNaddr` card | +| `#hashtag` (Unicode letters OK) | Internal `/t/hashtag` link | +| 🇺🇸 🇵🇱 🇧🇷 … | Internal `/i/iso3166:US` link | +| `:custom_emoji:` (with matching `["emoji", …]` tag or viewer collection) | `CustomEmojiImg` | +| Plain text | Rendered as-is with `whitespace-pre-wrap`, `dir="auto"` for RTL | ## Tests -`NoteContent.test.tsx` covers the core cases (URLs, hashtags, mentions with generated vs real names, plain text). It uses the project's `TestApp` wrapper. Run via the normal test script after copying the files. +`NoteContent.test.tsx` covers URL linkification (kinds 1 and 1111), plain text, hashtag linkification, and mention rendering with generated vs real display names. It uses the template's `TestApp` wrapper. Run via `npm run test` once the files are in `src/`. ## Related -- **`useAuthor`** — used internally for mention resolution; keep the default template implementation -- **`genUserName`** — used to generate deterministic fallback handles for users without `kind 0` metadata -- **`NIP19Page`** — the template's `/:nip19` route that handles links `NoteContent` generates for `npub1`/`note1`/`nevent1`/`nprofile1` - -## Customization Notes - -- **Image/video embeds:** `NoteContent` intentionally only *linkifies* URLs — it doesn't embed images or videos inline. If you want inline media, wrap or extend the component to detect media extensions / `imeta` tags and render ``/` e.stopPropagation()} + className={cn( + 'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm my-2.5', + className, + )} + > +
⚡ Lightning invoice
+
+ {invoice.slice(0, 24)}… +
+
+ ); +} diff --git a/.agents/skills/note-content/files/components/LinkEmbed.tsx b/.agents/skills/note-content/files/components/LinkEmbed.tsx new file mode 100644 index 0000000..f386cf8 --- /dev/null +++ b/.agents/skills/note-content/files/components/LinkEmbed.tsx @@ -0,0 +1,41 @@ +import { cn } from '@/lib/utils'; + +interface LinkEmbedProps { + url: string; + className?: string; + /** Hide the thumbnail image (e.g. when a cover image is already displayed above). */ + hideImage?: boolean; +} + +/** + * Minimal link preview card — renders the URL as a clickable block. + * + * Ditto's richer `LinkEmbed` fetches OpenGraph metadata (title, description, + * thumbnail, YouTube/Tweet/ogimage extraction) and renders a proper preview + * card. Replace this stub with a version that queries a metadata endpoint + * of your choice (oEmbed, OG scrapers, etc.) when you want rich previews. + */ +export function LinkEmbed({ url, className, hideImage: _hideImage }: LinkEmbedProps) { + let display = url; + try { + display = new URL(url).hostname.replace(/^www\./, ''); + } catch { + // keep raw url as display + } + + return ( + e.stopPropagation()} + className={cn( + 'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm', + className, + )} + > +
{display}
+
{url}
+
+ ); +} diff --git a/.agents/skills/note-content/files/components/NoteContent.test.tsx b/.agents/skills/note-content/files/components/NoteContent.test.tsx index a3244d1..0321817 100644 --- a/.agents/skills/note-content/files/components/NoteContent.test.tsx +++ b/.agents/skills/note-content/files/components/NoteContent.test.tsx @@ -5,14 +5,14 @@ import { NoteContent } from './NoteContent'; import type { NostrEvent } from '@nostrify/nostrify'; describe('NoteContent', () => { - it('linkifies URLs in kind 1 events', () => { + it('linkifies URLs in kind 1 events', async () => { const event: NostrEvent = { id: 'test-id', pubkey: 'test-pubkey', created_at: Math.floor(Date.now() / 1000), kind: 1, tags: [], - content: 'Check out this link: https://example.com', + content: 'Check out this link: https://example.com for more info', sig: 'test-sig', }; @@ -22,13 +22,13 @@ describe('NoteContent', () => { ); - const link = screen.getByRole('link', { name: 'https://example.com' }); + const link = await screen.findByRole('link', { name: 'https://example.com' }); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://example.com'); expect(link).toHaveAttribute('target', '_blank'); }); - it('linkifies URLs in kind 1111 events (comments)', () => { + it('linkifies URLs in kind 1111 events (comments)', async () => { const event: NostrEvent = { id: 'test-comment-id', pubkey: 'test-pubkey', @@ -39,7 +39,7 @@ describe('NoteContent', () => { ['k', '30040'], ['p', 'pubkey'], ], - content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111', + content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just be a kind 1111: https://nostrbook.dev/kinds/1111 as specified in the spec.', sig: 'test-sig', }; @@ -49,13 +49,13 @@ describe('NoteContent', () => { ); - const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' }); + const link = await screen.findByRole('link', { name: 'https://nostrbook.dev/kinds/1111' }); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111'); expect(link).toHaveAttribute('target', '_blank'); }); - it('handles text without URLs correctly', () => { + it('handles text without URLs correctly', async () => { const event: NostrEvent = { id: 'test-id', pubkey: 'test-pubkey', @@ -72,11 +72,11 @@ describe('NoteContent', () => { ); - expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument(); + expect(await screen.findByText('This is just plain text without any links.')).toBeInTheDocument(); expect(screen.queryByRole('link')).not.toBeInTheDocument(); }); - it('renders hashtags as links', () => { + it('renders hashtags as links', async () => { const event: NostrEvent = { id: 'test-id', pubkey: 'test-pubkey', @@ -93,7 +93,7 @@ describe('NoteContent', () => { ); - const nostrHashtag = screen.getByRole('link', { name: '#nostr' }); + const nostrHashtag = await screen.findByRole('link', { name: '#nostr' }); const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' }); expect(nostrHashtag).toBeInTheDocument(); @@ -102,7 +102,7 @@ describe('NoteContent', () => { expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin'); }); - it('generates deterministic names for users without metadata and styles them differently', () => { + it('generates deterministic names for users without metadata and styles them differently', async () => { // Use a valid npub for testing const event: NostrEvent = { id: 'test-id', @@ -121,12 +121,12 @@ describe('NoteContent', () => { ); // The mention should be rendered with a deterministic name - const mention = screen.getByRole('link'); + const mention = await screen.findByRole('link'); expect(mention).toBeInTheDocument(); - // Should have muted styling for generated names (gray instead of blue) - expect(mention).toHaveClass('text-gray-500'); - expect(mention).not.toHaveClass('text-blue-500'); + // Should have muted styling for generated names (muted-foreground instead of primary) + expect(mention).toHaveClass('text-muted-foreground'); + expect(mention).not.toHaveClass('text-primary'); // The text should start with @ and contain a generated name (not a truncated npub) const linkText = mention.textContent; diff --git a/.agents/skills/note-content/files/components/NoteContent.tsx b/.agents/skills/note-content/files/components/NoteContent.tsx index ffd364b..345ce36 100644 --- a/.agents/skills/note-content/files/components/NoteContent.tsx +++ b/.agents/skills/note-content/files/components/NoteContent.tsx @@ -1,142 +1,867 @@ -import { useMemo } from 'react'; +import { useMemo, useState, useCallback, type ReactNode } from 'react'; import { type NostrEvent } from '@nostrify/nostrify'; import { Link } from 'react-router-dom'; import { nip19 } from 'nostr-tools'; import { useAuthor } from '@/hooks/useAuthor'; import { genUserName } from '@/lib/genUserName'; +import { getDisplayName } from '@/lib/getDisplayName'; +import { getAvatarShape } from '@/lib/avatarShape'; +import { useProfileUrl } from '@/hooks/useProfileUrl'; +import { LinkEmbed } from '@/components/LinkEmbed'; +import { EmbeddedNote } from '@/components/EmbeddedNote'; +import { EmbeddedNaddr } from '@/components/EmbeddedNaddr'; +import { LightningInvoiceCard } from '@/components/LightningInvoiceCard'; +import { VideoPlayer } from '@/components/VideoPlayer'; +import { AudioVisualizer } from '@/components/AudioVisualizer'; +import { WebxdcEmbed } from '@/components/WebxdcEmbed'; +import { Lightbox, ImageGallery } from '@/components/ImageGallery'; +import { ProfileHoverCard } from '@/components/ProfileHoverCard'; +import { EmojifiedText, CustomEmojiImg } from '@/components/CustomEmoji'; +import { buildEmojiMap } from '@/lib/customEmoji'; +import { useCustomEmojis } from '@/hooks/useCustomEmojis'; +import { useBlossomFallback } from '@/hooks/useBlossomFallback'; +import { COUNTRIES } from '@/lib/countries'; +import { IMAGE_URL_REGEX, EMBED_MEDIA_URL_REGEX } from '@/lib/mediaUrls'; +import { parseImetaMap } from '@/lib/imeta'; +import { sanitizeUrl } from '@/lib/sanitizeUrl'; import { cn } from '@/lib/utils'; +/** Coordinates for an addressable event (naddr). */ +export interface AddrCoords { + kind: number; + pubkey: string; + identifier: string; +} + interface NoteContentProps { event: NostrEvent; className?: string; + /** When true, renders URLs as inline links instead of link preview cards / embeds. */ + disableEmbeds?: boolean; + /** When true, hides thumbnail images in link preview cards (useful when a cover image is already shown). */ + hideEmbedImages?: boolean; + /** When true, nested nostr:nevent/note/naddr embeds render as inline links instead of cards. + * Used inside embedded quote cards to prevent unbounded recursive nesting. */ + disableNoteEmbeds?: boolean; + /** When true, images, galleries, and video/audio players are suppressed (rendered as + * whitespace) while link preview cards and other non-media embeds are preserved. + * Used inside embedded quote cards to keep them lightweight. */ + disableMediaEmbeds?: boolean; } +/** Regex matching `:shortcode:` patterns in text. */ +const SHORTCODE_REGEX = /:([a-zA-Z0-9_-]+):/g; + +/** + * Replaces `:shortcode:` patterns in text with inline custom emoji images. + */ +function emojify( + text: string, + emojiMap: Map, + imgClassName?: string, +): ReactNode[] { + if (emojiMap.size === 0) return [text]; + + const result: ReactNode[] = []; + let lastIndex = 0; + let match: RegExpExecArray | null; + + SHORTCODE_REGEX.lastIndex = 0; + + while ((match = SHORTCODE_REGEX.exec(text)) !== null) { + const [fullMatch, shortcode] = match; + const url = emojiMap.get(shortcode); + + if (!url) continue; + + if (match.index > lastIndex) { + result.push(text.substring(lastIndex, match.index)); + } + + result.push( + , + ); + + lastIndex = match.index + fullMatch.length; + } + + if (lastIndex < text.length) { + result.push(text.substring(lastIndex)); + } + + return result.length > 0 ? result : [text]; +} + +/** Bech32 charset used by NIP-19 identifiers. */ +const BECH32_CHARS = '023456789acdefghjklmnpqrstuvwxyz'; + +/** Regex to extract an naddr1 identifier from a URL path. */ +const NADDR_IN_URL_REGEX = new RegExp(`naddr1[${BECH32_CHARS}]{10,}`, 'i'); + +/** Try to extract naddr coordinates from a URL containing an naddr1 identifier. */ +function extractNaddrFromUrl(url: string): AddrCoords | null { + const match = url.match(NADDR_IN_URL_REGEX); + if (!match) return null; + try { + const decoded = nip19.decode(match[0]); + if (decoded.type === 'naddr') { + return decoded.data as AddrCoords; + } + } catch { + // invalid naddr + } + return null; +} + +/** Regex matching flag emoji: pairs of Regional Indicator Symbol letters (U+1F1E6–U+1F1FF). */ +const FLAG_EMOJI_REGEX = /([\u{1F1E6}-\u{1F1FF}]{2})/gu; + +/** + * Convert a flag emoji (pair of Regional Indicator Symbols) to an ISO 3166-1 alpha-2 code. + * Returns the code if it maps to a known country, otherwise null. + */ +function flagToCountryCode(flag: string): string | null { + const codePoints = [...flag]; + if (codePoints.length !== 2) return null; + const a = codePoints[0].codePointAt(0)! - 0x1F1E6 + 65; + const b = codePoints[1].codePointAt(0)! - 0x1F1E6 + 65; + const code = String.fromCharCode(a) + String.fromCharCode(b); + return COUNTRIES[code] ? code : null; +} + +/** + * Process an array of ReactNodes (from emojify), splitting any string nodes + * to wrap flag emojis in elements pointing to /i/iso3166:. + */ +function linkifyFlags(nodes: ReactNode[]): ReactNode[] { + const result: ReactNode[] = []; + let keyIdx = 0; + + for (const node of nodes) { + if (typeof node !== 'string') { + result.push(node); + continue; + } + + let lastIndex = 0; + FLAG_EMOJI_REGEX.lastIndex = 0; + let match: RegExpExecArray | null; + + while ((match = FLAG_EMOJI_REGEX.exec(node)) !== null) { + const flag = match[1]; + const code = flagToCountryCode(flag); + if (!code) continue; + + if (match.index > lastIndex) { + result.push(node.substring(lastIndex, match.index)); + } + + result.push( + e.stopPropagation()} + > + {flag} + , + ); + + lastIndex = match.index + match[0].length; + } + + if (lastIndex < node.length) { + result.push(node.substring(lastIndex)); + } else if (lastIndex === 0) { + result.push(node); + } + } + + return result; +} + +/** A parsed token from note content. */ +type ContentToken = + | { type: 'text'; value: string } + | { type: 'image-embed'; url: string } + | { type: 'image-gallery'; urls: string[] } + | { type: 'media-embed'; url: string } + | { type: 'link-embed'; url: string } + | { type: 'inline-link'; url: string } + | { type: 'mention'; pubkey: string } + | { type: 'nevent-embed'; eventId: string; relays?: string[]; author?: string } + | { type: 'naddr-embed'; addr: AddrCoords; url?: string } + | { type: 'nostr-link'; id: string; raw: string } + | { type: 'hashtag'; tag: string; raw: string } + | { type: 'relay-link'; url: string } + | { type: 'lightning-invoice'; invoice: string }; + +/** + * Regex segment matching a single visual emoji unit, including: + * - ZWJ sequences (e.g. 👨‍👩‍👧‍👦, 👩‍💻) + * - Skin tone / hair style modifiers (e.g. 👋🏽) + * - Flag sequences (Regional Indicator pairs, e.g. 🇺🇸) + * - Keycap sequences (e.g. 1️⃣) + * - Tag sequences (e.g. 🏴󠁧󠁢󠁷󠁬󠁳󠁿) + * - Basic presentation emojis (with or without VS16) + */ +const EMOJI_UNIT = [ + // ZWJ sequences: emoji (+ optional modifier) joined by ZWJ, repeated + '(?:' + + '(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)' + // base emoji + '[\\u{1F3FB}-\\u{1F3FF}]?' + // optional skin tone + '(?:\\u200D(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)[\\u{1F3FB}-\\u{1F3FF}]?)+' + // ZWJ + next + ')', + // Flag sequences (two Regional Indicator symbols) + '(?:[\\u{1F1E6}-\\u{1F1FF}]{2})', + // Keycap sequences: digit/# /* + VS16 + combining enclosing keycap + '(?:[0-9#*]\\uFE0F\\u20E3)', + // Tag sequences (subdivision flags): 🏴 + tag chars + cancel tag + '(?:\\u{1F3F4}[\\u{E0020}-\\u{E007E}]+\\u{E007F})', + // Single emoji with optional skin tone modifier + '(?:(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)[\\u{1F3FB}-\\u{1F3FF}]?)', +].join('|'); + +/** NIP-30 custom emoji shortcode pattern. */ +const CUSTOM_EMOJI_SHORTCODE = ':([a-zA-Z0-9_-]+):'; + +/** Regex matching a string of only NIP-30 custom emoji shortcodes and/or unicode emojis (with optional whitespace). Max 10 visual emojis. */ +const EMOJI_OR_CUSTOM_ONLY_REGEX = new RegExp( + `^\\s*(?:(?:${CUSTOM_EMOJI_SHORTCODE}|${EMOJI_UNIT})\\s*){1,10}$`, + 'u', +); + +/** Check if a string contains only unicode emojis and/or NIP-30 custom emoji shortcodes (and whitespace). */ +function isOnlyEmojisOrCustom(text: string, emojiMap: Map): boolean { + if (!EMOJI_OR_CUSTOM_ONLY_REGEX.test(text)) return false; + // Verify all shortcodes in the text actually resolve to a custom emoji + const shortcodeMatches = text.matchAll(/:([a-zA-Z0-9_-]+):/g); + for (const m of shortcodeMatches) { + if (!emojiMap.has(m[1])) return false; + } + return true; +} + + /** Parses content of text note events so that URLs and hashtags are linkified. */ export function NoteContent({ - event, - className, -}: NoteContentProps) { - // Process the content to render mentions, links, etc. - const content = useMemo(() => { + event, + className, + disableEmbeds = false, + hideEmbedImages = false, + disableNoteEmbeds = false, + disableMediaEmbeds = false, +}: NoteContentProps) { + const tokens = useMemo(() => { const text = event.content; - - // Regex to find URLs, Nostr references, and hashtags - const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g; - - const parts: React.ReactNode[] = []; + // Match: BOLT11 invoices | URLs | nostr:-prefixed NIP-19 ids | @-prefixed or bare NIP-19 ids | hashtags + // BOLT11: optional "lightning:" prefix + lnbc/lntb/lnbcrt/lntbs + bech32 data (case-insensitive) + // NIP-19 ids can appear anywhere (with optional @ prefix that gets consumed) + const regex = /(?:lightning:)?(ln(?:bc|tb|bcrt|tbs)\d*[munp]?1[023456789acdefghjklmnpqrstuvwxyz]+)|((?:https?|wss?):\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+)|@?(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#[\p{L}\p{N}_]+)/giu; + + const result: ContentToken[] = []; let lastIndex = 0; let match: RegExpExecArray | null; - let keyCounter = 0; - + let hadMatches = false; + while ((match = regex.exec(text)) !== null) { - const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match; + let [fullMatch] = match; + const bolt11 = match[1]; + let url = match[2]; + const hashtag = match[7]; + const { 3: nostrPrefix, 4: nostrData, 5: barePrefix, 6: bareData } = match; const index = match.index; - + hadMatches = true; + // Add text before this match if (index > lastIndex) { - parts.push(text.substring(lastIndex, index)); + result.push({ type: 'text', value: text.substring(lastIndex, index) }); } - - if (url) { - // Handle URLs - parts.push( - - {url} - - ); - } else if (nostrPrefix && nostrData) { - // Handle Nostr references + + if (bolt11) { + result.push({ type: 'lightning-invoice', invoice: bolt11.toLowerCase() }); + } else if (url) { + // Strip common trailing punctuation that's likely not part of the URL + // This handles cases like "(https://example.com)" or "Check this: https://example.com." + const trailingPunctMatch = url.match(/^(.*?)([.,;:!?)\]]+)$/); + if (trailingPunctMatch) { + const [, urlWithoutPunct] = trailingPunctMatch; + // Only strip the punctuation if the URL without it is still valid + if (urlWithoutPunct && urlWithoutPunct.length > 10) { + url = urlWithoutPunct; + fullMatch = urlWithoutPunct; + // The punctuation will be part of the next text token + } + } + + // WebSocket relay URLs → link to internal relay page + if (/^wss?:\/\//i.test(url)) { + result.push({ type: 'relay-link', url }); + lastIndex = index + fullMatch.length; + continue; + } + + // Image URLs → render inline at their position in the text + if (IMAGE_URL_REGEX.test(url)) { + if (result.length > 0) { + const prev = result[result.length - 1]; + if (prev.type === 'text') { + prev.value = prev.value.replace(/\s+$/, ''); + } + } + result.push({ type: 'image-embed', url }); + lastIndex = index + fullMatch.length; + // Strip leading whitespace that follows the image URL + const remaining = text.substring(lastIndex); + const leadingWs = remaining.match(/^\s+/); + if (leadingWs) { + lastIndex += leadingWs[0].length; + } + continue; + } + + // Non-image media URLs (video, audio, webxdc) — render inline at their position. + if (EMBED_MEDIA_URL_REGEX.test(url)) { + if (result.length > 0) { + const prev = result[result.length - 1]; + if (prev.type === 'text') { + prev.value = prev.value.replace(/\s+$/, ''); + } + } + result.push({ type: 'media-embed', url }); + lastIndex = index + fullMatch.length; + // Strip leading whitespace that follows the media URL + const remaining = text.substring(lastIndex); + const leadingWs = remaining.match(/^\s+/); + if (leadingWs) { + lastIndex += leadingWs[0].length; + } + continue; + } + + // Determine if this URL ends a line (not followed by more text). + // A URL gets a preview card when nothing meaningful follows it on + // the same line (i.e., it ends the line or the content). + const afterUrl = text.substring(index + fullMatch.length); + const nextNewline = afterUrl.indexOf('\n'); + const lineSuffix = nextNewline === -1 ? afterUrl : afterUrl.substring(0, nextNewline); + const isEndOfLine = lineSuffix.trim() === ''; + + // Check if the URL contains an naddr1 identifier → embed as Nostr event + preserve link + const naddrFromUrl = extractNaddrFromUrl(url); + if (naddrFromUrl) { + result.push({ type: 'naddr-embed', addr: naddrFromUrl, url }); + } else if (isEndOfLine) { + // Standalone URL at end of line → rich embed (link preview) + result.push({ type: 'link-embed', url }); + } else { + // Inline URL mid-sentence → plain clickable link + result.push({ type: 'inline-link', url }); + } + } else if ((nostrPrefix && nostrData) || (barePrefix && bareData)) { + // Handle both nostr:-prefixed and bare NIP-19 identifiers + const prefix = nostrPrefix || barePrefix; + const data = nostrData || bareData; try { - const nostrId = `${nostrPrefix}${nostrData}`; + const nostrId = `${prefix}${data}`; const decoded = nip19.decode(nostrId); - + if (decoded.type === 'npub') { - const pubkey = decoded.data; - parts.push( - - ); + result.push({ type: 'mention', pubkey: decoded.data }); } else if (decoded.type === 'nprofile') { - const pubkey = decoded.data.pubkey; - parts.push( - - ); + result.push({ type: 'mention', pubkey: decoded.data.pubkey }); + } else if (decoded.type === 'note') { + result.push({ type: 'nevent-embed', eventId: decoded.data as string }); + } else if (decoded.type === 'nevent') { + result.push({ + type: 'nevent-embed', + eventId: decoded.data.id, + relays: decoded.data.relays, + author: decoded.data.author, + }); + } else if (decoded.type === 'naddr') { + result.push({ type: 'naddr-embed', addr: decoded.data as AddrCoords }); } else { - // For other types, just show as a link - parts.push( - - {fullMatch} - - ); + result.push({ type: 'nostr-link', id: nostrId, raw: fullMatch }); } } catch { - // If decoding fails, just render as text - parts.push(fullMatch); + result.push({ type: 'text', value: fullMatch }); } } else if (hashtag) { - // Handle hashtags - const tag = hashtag.slice(1); // Remove the # - parts.push( - - {hashtag} - - ); + const tag = hashtag.slice(1); + result.push({ type: 'hashtag', tag, raw: hashtag }); } - + lastIndex = index + fullMatch.length; } - + // Add any remaining text if (lastIndex < text.length) { - parts.push(text.substring(lastIndex)); + result.push({ type: 'text', value: text.substring(lastIndex) }); } - - // If no special content was found, just use the plain text - if (parts.length === 0) { - parts.push(text); + + if (result.length === 0 && !hadMatches) { + result.push({ type: 'text', value: text }); } - - return parts; + + // Enrich nevent-embed tokens with relay hints from `q` tags when the + // nevent URI itself didn't include any. This ensures quote posts whose + // inline nevent was encoded without relay hints can still resolve the + // quoted event via the relay hint stored in the q tag. + const qTagMap = new Map(); + for (const tag of event.tags) { + if (tag[0] === 'q' && tag[1]) { + qTagMap.set(tag[1], { relay: tag[2] || undefined, author: tag[3] || undefined }); + } + } + if (qTagMap.size > 0) { + for (const token of result) { + if (token.type === 'nevent-embed') { + const qInfo = qTagMap.get(token.eventId); + if (qInfo) { + if ((!token.relays || token.relays.length === 0) && qInfo.relay) { + token.relays = [qInfo.relay]; + } + if (!token.author && qInfo.author) { + token.author = qInfo.author; + } + } + } + } + } + + // Append media-embed tokens for imeta-declared media URLs not found in the content. + // Some clients attach audio/video/webxdc via imeta tags without including the URL in + // the content string. Without this, those attachments would be silently dropped. + // Only scan for text note kinds — other kinds (DMs, calendar events, etc.) may use + // imeta tags for different purposes. + const TEXT_NOTE_KINDS = new Set([1, 11, 1111]); + if (TEXT_NOTE_KINDS.has(event.kind)) { + const contentMediaUrls = new Set( + result.filter((t): t is { type: 'media-embed'; url: string } => t.type === 'media-embed').map((t) => t.url), + ); + for (const tag of event.tags) { + if (tag[0] !== 'imeta') continue; + let rawUrl: string | undefined; + let mime: string | undefined; + for (let j = 1; j < tag.length; j++) { + const sp = tag[j].indexOf(' '); + if (sp === -1) continue; + const key = tag[j].slice(0, sp); + if (key === 'url') rawUrl = tag[j].slice(sp + 1); + else if (key === 'm') mime = tag[j].slice(sp + 1); + } + const url = sanitizeUrl(rawUrl); + if (!url || contentMediaUrls.has(url)) continue; + const isEmbeddableMedia = mime?.startsWith('audio/') || mime?.startsWith('video/') + || mime === 'application/x-webxdc' || mime === 'application/vnd.webxdc+zip'; + if (isEmbeddableMedia) { + result.push({ type: 'media-embed', url }); + } + } + } + + // Collapse excessive whitespace around block-level tokens (link-preview, nevent embed, etc.) + // Preserve formatting but prevent too much stacking with the card's own spacing. + for (let i = 0; i < result.length; i++) { + const token = result[i]; + const isBlock = token.type === 'image-embed' || token.type === 'media-embed' || token.type === 'link-embed' || token.type === 'nevent-embed' + || (token.type === 'naddr-embed' && !token.url) || token.type === 'lightning-invoice'; + + if (isBlock) { + // Strip all trailing whitespace from the preceding text token. + // The block's own margin (my-2.5) handles spacing, so preserved + // newlines just add redundant blank lines under whitespace-pre-wrap. + if (i > 0) { + const prev = result[i - 1]; + if (prev.type === 'text') { + prev.value = prev.value.replace(/\s+$/, ''); + } + } + // Strip all leading whitespace from the following text token. + if (i < result.length - 1) { + const next = result[i + 1]; + if (next.type === 'text') { + next.value = next.value.replace(/^\s+/, ''); + } + } + } + } + + // Trim leading/trailing whitespace from edge text tokens + if (result.length > 0) { + const first = result[0]; + if (first.type === 'text') { + first.value = first.value.replace(/^\s+/, ''); + } + const last = result[result.length - 1]; + if (last.type === 'text') { + last.value = last.value.replace(/\s+$/, ''); + } + } + + // Filter out empty text tokens + return result.filter((t) => !(t.type === 'text' && t.value === '')); }, [event]); + // Build emoji map for NIP-30 custom emoji rendering. + // Merge the event's own emoji tags with the viewer's custom emoji collection + // so shortcodes render even when the published event omitted the tag. + const { emojis: viewerEmojis } = useCustomEmojis(); + const emojiMap = useMemo(() => { + const map = buildEmojiMap(event.tags); + // Viewer's collection is a fallback — event tags take priority + for (const e of viewerEmojis) { + if (!map.has(e.shortcode)) { + map.set(e.shortcode, e.url); + } + } + return map; + }, [event.tags, viewerEmojis]); + + // Parse imeta tags — used by ImageGallery (dim/blurhash) and inline media embeds + const imetaMap = useMemo(() => parseImetaMap(event.tags), [event.tags]); + + // Only fetch author data when there are media embeds that need it (video artist, audio avatar) + const hasMedia = tokens.some((t) => t.type === 'media-embed'); + const author = useAuthor(hasMedia ? event.pubkey : undefined); + const authorMetadata = author.data?.metadata; + const authorDisplayName = useMemo( + () => getDisplayName(authorMetadata, event.pubkey) ?? genUserName(event.pubkey), + [authorMetadata, event.pubkey], + ); + + // Group consecutive image-embed tokens (≥2) into image-gallery tokens + const groupedTokens = useMemo(() => { + const result: ContentToken[] = []; + let i = 0; + while (i < tokens.length) { + const token = tokens[i]; + if (token.type === 'image-embed') { + // Collect this and any immediately following image-embed tokens + const run: string[] = [token.url]; + let j = i + 1; + while (j < tokens.length && tokens[j].type === 'image-embed') { + run.push((tokens[j] as { type: 'image-embed'; url: string }).url); + j++; + } + if (run.length >= 2) { + result.push({ type: 'image-gallery', urls: run }); + } else { + result.push(token); + } + i = j; + } else { + result.push(token); + i++; + } + } + return result; + }, [tokens]); + + // Collect all inline image URLs (in order) for the shared lightbox + const allImages = useMemo( + () => groupedTokens.flatMap((t) => { + if (t.type === 'image-embed') return [t.url]; + if (t.type === 'image-gallery') return t.urls; + return []; + }), + [groupedTokens], + ); + + // Shared lightbox state for inline images + const [lightboxIndex, setLightboxIndex] = useState(null); + const closeLightbox = useCallback(() => setLightboxIndex(null), []); + const goNext = useCallback(() => setLightboxIndex((p) => (p !== null ? (p + 1) % allImages.length : null)), [allImages.length]); + const goPrev = useCallback(() => setLightboxIndex((p) => (p !== null ? (p - 1 + allImages.length) % allImages.length : null)), [allImages.length]); + + // Check if content is only emojis — unicode and/or NIP-30 custom emojis (single text token) + const isEmojiOnly = groupedTokens.length === 1 && groupedTokens[0].type === 'text' && isOnlyEmojisOrCustom(groupedTokens[0].value, emojiMap); + + // Build a map from grouped token index → starting image list index for lightbox positioning + const tokenImageIndex = useMemo(() => { + const map = new Map(); + let imgCount = 0; + groupedTokens.forEach((t, i) => { + if (t.type === 'image-embed') { + map.set(i, imgCount++); + } else if (t.type === 'image-gallery') { + map.set(i, imgCount); + imgCount += t.urls.length; + } + }); + return map; + }, [groupedTokens]); + return ( -
- {content.length > 0 ? content : event.content} +
+ {groupedTokens.map((token, i) => { + switch (token.type) { + case 'text': + return {linkifyFlags(emojify(token.value, emojiMap, isEmojiOnly ? 'inline h-12 w-12 object-contain align-text-bottom' : undefined))}; + case 'image-embed': { + if (disableEmbeds || disableMediaEmbeds) { + // In preview contexts, replace image URLs with a newline so + // text flow is preserved without showing raw URLs. + return {'\n'}; + } + const imgIndex = tokenImageIndex.get(i) ?? 0; + return ( + { e.stopPropagation(); setLightboxIndex(imgIndex); }} + /> + ); + } + case 'image-gallery': { + if (disableEmbeds || disableMediaEmbeds) { + return {token.urls.map(() => '\n').join('')}; + } + const galleryStartIndex = tokenImageIndex.get(i) ?? 0; + const galleryLightboxIndex = + lightboxIndex !== null && + lightboxIndex >= galleryStartIndex && + lightboxIndex < galleryStartIndex + token.urls.length + ? lightboxIndex - galleryStartIndex + : null; + return ( + { setLightboxIndex(galleryStartIndex + idx); }} + onLightboxClose={closeLightbox} + /> + ); + } + case 'link-embed': + if (disableEmbeds) { + return ( + e.stopPropagation()} + > + {token.url} + + ); + } + return ; + case 'inline-link': + return ( + e.stopPropagation()} + > + {token.url} + + ); + case 'media-embed': { + if (disableEmbeds || disableMediaEmbeds) { + return {'\n'}; + } + const imeta = imetaMap.get(token.url); + const mime = imeta?.mime ?? ''; + const isWebxdc = mime === 'application/x-webxdc' || mime === 'application/vnd.webxdc+zip' || token.url.endsWith('.xdc'); + const isAudio = mime.startsWith('audio/') || /\.(mp3|wav|ogg|flac|m4a|aac|opus)(\?[^\s]*)?$/i.test(token.url); + if (isWebxdc && imeta) { + return ; + } + if (isAudio) { + return ( + + ); + } + // Default: video + return ( + + ); + } + case 'nevent-embed': + if (disableNoteEmbeds) { + const neventId = nip19.neventEncode({ id: token.eventId, ...(token.author ? { author: token.author } : {}), ...(token.relays?.length ? { relays: token.relays } : {}) }); + return ( + e.stopPropagation()} + > + {neventId.slice(0, 16)}… + + ); + } + return ; + case 'naddr-embed': + if (disableNoteEmbeds) { + const naddrId = nip19.naddrEncode({ kind: token.addr.kind, pubkey: token.addr.pubkey, identifier: token.addr.identifier }); + return ( + e.stopPropagation()} + > + {naddrId.slice(0, 16)}… + + ); + } + return ( + + {token.url && ( + e.stopPropagation()} + > + {token.url} + + )} + + + ); + case 'mention': + return ; + case 'nostr-link': + return ( + e.stopPropagation()} + > + {token.raw} + + ); + case 'hashtag': + return ( + e.stopPropagation()} + > + {token.raw} + + ); + case 'relay-link': + return ( + e.stopPropagation()} + > + {token.url} + + ); + case 'lightning-invoice': + if (disableEmbeds) { + return {token.invoice}; + } + return ; + } + })} + + {/* Shared lightbox for standalone inline images (not gallery groups) */} + {lightboxIndex !== null && !groupedTokens.some( + (t, i) => + t.type === 'image-gallery' && + lightboxIndex >= (tokenImageIndex.get(i) ?? 0) && + lightboxIndex < (tokenImageIndex.get(i) ?? 0) + t.urls.length, + ) && ( + + )}
); } -// Helper component to display user mentions -function NostrMention({ pubkey }: { pubkey: string }) { - const author = useAuthor(pubkey); - const npub = nip19.npubEncode(pubkey); - const hasRealName = !!author.data?.metadata?.name; - const displayName = author.data?.metadata?.name ?? genUserName(pubkey); +/** Inline image thumbnail that opens the shared lightbox on click. + * Uses a min-height placeholder to prevent layout shifts while loading. */ +function InlineImage({ url, onClick }: { url: string; onClick: (e: React.MouseEvent) => void }) { + const { src, onError } = useBlossomFallback(url); + const [loaded, setLoaded] = useState(false); return ( - - @{displayName} - +
+ setLoaded(true)} + onError={() => { setLoaded(true); onError(); }} + /> +
+ ); -} \ No newline at end of file +} + +function NostrMention({ pubkey }: { pubkey: string }) { + const author = useAuthor(pubkey); + const hasRealName = !!author.data?.metadata?.name; + const displayName = author.data?.metadata?.name ?? genUserName(pubkey); + const profileUrl = useProfileUrl(pubkey, author.data?.metadata); + + return ( + + e.stopPropagation()} + > + @{author.data?.event ? ( + {displayName} + ) : displayName} + + + ); +} diff --git a/.agents/skills/note-content/files/components/ProfileHoverCard.tsx b/.agents/skills/note-content/files/components/ProfileHoverCard.tsx new file mode 100644 index 0000000..d6b5c52 --- /dev/null +++ b/.agents/skills/note-content/files/components/ProfileHoverCard.tsx @@ -0,0 +1,19 @@ +import type { ReactNode } from 'react'; + +interface ProfileHoverCardProps { + pubkey: string; + asChild?: boolean; + children: ReactNode; +} + +/** + * Minimal profile hover card — a passthrough wrapper. + * + * Ditto's richer `ProfileHoverCard` shows an avatar, display name, + * bio, follower count, and follow button on hover. To replicate, + * wrap with `@/components/ui/hover-card` and pull metadata via + * `useAuthor(pubkey)` inside the hover content. + */ +export function ProfileHoverCard({ children }: ProfileHoverCardProps) { + return <>{children}; +} diff --git a/.agents/skills/note-content/files/components/VideoPlayer.tsx b/.agents/skills/note-content/files/components/VideoPlayer.tsx new file mode 100644 index 0000000..a79bed7 --- /dev/null +++ b/.agents/skills/note-content/files/components/VideoPlayer.tsx @@ -0,0 +1,43 @@ +import { cn } from '@/lib/utils'; + +interface VideoPlayerProps { + src: string; + poster?: string; + /** Pixel dimensions from NIP-94 `dim` tag, e.g. "1280x720". */ + dim?: string; + /** Blurhash placeholder from NIP-94 `blurhash` tag. */ + blurhash?: string; + artist?: string; + className?: string; +} + +/** + * Minimal inline video player — renders a native `