mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Upgrade note-content skill with advancements from Ditto
Replaces the minimal NoteContent component with the full-featured version from ~/Projects/ditto, and bundles the helper modules and minimal companion stubs needed to make it work standalone. New capabilities: - BOLT11 lightning-invoice detection (renders LightningInvoiceCard) - Inline image / video / audio / webxdc embeds with MIME detection - Consecutive images grouped into an ImageGallery with shared Lightbox - NIP-94 imeta-declared media appended when absent from content - Embedded nevent / naddr cards, with relay and author hints pulled from q tags; supports naddr1 fragments embedded in external URLs - Bare and @-prefixed NIP-19 identifiers (no nostr: prefix required) - Line-end-aware link rendering: URLs at the end of a line become preview cards, mid-sentence URLs stay inline - Trailing-punctuation stripping on URLs so 'see https://x.com.' links correctly - wss:// relay URLs routed to /r/<encoded> - Unicode-aware hashtag regex (matches non-ASCII letters) - NIP-30 custom emoji via :shortcode: with per-event and viewer-wide fallback collections (useCustomEmojis) - Flag emoji linkified to /i/iso3166:<CC> - 'Emoji-only' posts auto-rendered at large size - dir="auto" for RTL content - Whitespace normalization around block embeds - disableEmbeds / disableMediaEmbeds / disableNoteEmbeds / hideEmbedImages props for recursive embed cards and preview contexts New bundled files: - lib/: mediaUrls.ts, sanitizeUrl.ts, imeta.ts, customEmoji.ts, getDisplayName.ts, avatarShape.ts, countries.ts - hooks/: useCustomEmojis.ts (stub), useBlossomFallback.ts (stub), useProfileUrl.ts (stub) - components/: LinkEmbed, EmbeddedNote, EmbeddedNaddr, LightningInvoiceCard, VideoPlayer, AudioVisualizer, WebxdcEmbed, ImageGallery + Lightbox, ProfileHoverCard, CustomEmoji \u2014 all minimal but functional stubs; each file documents how to upgrade to a richer implementation SKILL.md rewritten with full file list, upgrade paths for each stub, routing expectations, and a patterns-to-render table. Validated: tsc --noEmit clean, vitest run passes all 5 NoteContent tests, vite build succeeds \u2014 when all skill files are staged into src/ alongside the component.
This commit is contained in:
23 files changed
+2166
-147
No files matched your search
@@ -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 `<a target="_blank">` links
|
||||
- Hashtags rendered as internal links to `/t/<tag>`
|
||||
- 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/<encoded-url>`
|
||||
- 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/<tag>`, 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:<CC>` 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 |
|
||||
|---|---|
|
||||
| `/<nip19-identifier>` (e.g. `/npub1...`, `/note1...`, `/nevent1...`) | Handled by the template's NIP-19 page at `/:nip19` |
|
||||
| `/t/<hashtag>` | **Not in the default template.** If you want hashtag pages to work, add a route like `<Route path="/t/:hashtag" element={<HashtagPage />} />` in `AppRouter.tsx`. If you don't add one, hashtag links will fall through to the 404 page. |
|
||||
| `/<nip19-identifier>` (e.g. `/npub1…`, `/note1…`, `/nevent1…`, `/naddr1…`) | Handled by the template's `NIP19Page` at `/:nip19` |
|
||||
| `/t/<hashtag>` | **Not in the default template.** Add `<Route path="/t/:hashtag" element={<HashtagPage />} />` if you want hashtag pages. |
|
||||
| `/r/<encoded-wss-url>` | **Not in the default template.** Add `<Route path="/r/:relayUrl" element={<RelayPage />} />` if you want relay pages. |
|
||||
| `/i/iso3166:<CC>` | **Not in the default template.** Add `<Route path="/i/iso3166::code" element={<CountryPage />} />` 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 `<NoteContent disableNoteEmbeds disableMediaEmbeds>`
|
||||
- **`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 `/<npub>`
|
||||
|
||||
## Supported Content Patterns
|
||||
|
||||
| Pattern in `event.content` | Rendered as |
|
||||
|---|---|
|
||||
| `https://example.com/...` | `<a href target="_blank" rel="noopener noreferrer">` (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/<encoded>` 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 `<img>`/`<video>` elements.
|
||||
- **NIP-94 `imeta` tags:** This component doesn't read tags. For rendering attached files from `imeta` tags (e.g. DM kind 15 files), you'd pair this with a separate media renderer.
|
||||
- **Colors:** The blue link color is hard-coded (`text-blue-500`). Swap to your theme's `text-primary` or similar if you want the links to follow your design system.
|
||||
- **`useAuthor`** — used internally for mention resolution and for audio-embed author avatar. Core template.
|
||||
- **`genUserName`** — fallback deterministic name when a mentioned user has no kind 0 metadata. Core template.
|
||||
- **`NIP19Page`** — the template's `/:nip19` route that handles every kind of NIP-19 link this component generates.
|
||||
- **`nwc` skill** — pair with `LightningInvoiceCard` for one-tap invoice payment via WebLN/NWC.
|
||||
@@ -0,0 +1,46 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface AudioVisualizerProps {
|
||||
src: string;
|
||||
mime?: string;
|
||||
avatarUrl?: string;
|
||||
avatarFallback?: string;
|
||||
avatarShape?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal inline audio player — renders a native `<audio controls>`
|
||||
* alongside the author's avatar.
|
||||
*
|
||||
* Ditto's richer `AudioVisualizer` renders a waveform visualization,
|
||||
* applies `avatarShape` as a CSS mask, and supports background playback
|
||||
* state. Replace this stub with a richer player (e.g. using WebAudio +
|
||||
* Canvas visualization) when desired.
|
||||
*/
|
||||
export function AudioVisualizer({
|
||||
src,
|
||||
avatarUrl,
|
||||
avatarFallback,
|
||||
avatarShape: _avatarShape,
|
||||
className,
|
||||
}: AudioVisualizerProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-3 border rounded-lg px-3 py-2 my-2.5',
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-muted flex items-center justify-center overflow-hidden">
|
||||
{avatarUrl ? (
|
||||
<img src={avatarUrl} alt="" className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<span className="text-sm font-medium">{avatarFallback ?? '?'}</span>
|
||||
)}
|
||||
</div>
|
||||
<audio src={src} controls preload="metadata" className="flex-1 min-w-0" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { type ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface CustomEmojiImgProps {
|
||||
/** Shortcode without surrounding colons. */
|
||||
name: string;
|
||||
/** The emoji image URL from a NIP-30 `emoji` tag. */
|
||||
url: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline NIP-30 custom emoji image.
|
||||
*/
|
||||
export function CustomEmojiImg({ name, url, className }: CustomEmojiImgProps) {
|
||||
return (
|
||||
<img
|
||||
src={url}
|
||||
alt={`:${name}:`}
|
||||
title={`:${name}:`}
|
||||
draggable={false}
|
||||
loading="lazy"
|
||||
className={cn(
|
||||
'inline h-[1.2em] w-[1.2em] object-contain align-text-bottom',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface EmojifiedTextProps {
|
||||
/** Event tags containing NIP-30 `emoji` entries used to resolve shortcodes. */
|
||||
tags: string[][];
|
||||
children: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a string, replacing `:shortcode:` patterns with inline
|
||||
* custom emoji images sourced from the provided `emoji` tags.
|
||||
* Used inside usernames, reaction displays, etc.
|
||||
*/
|
||||
export function EmojifiedText({ tags, children, className }: EmojifiedTextProps) {
|
||||
const emojiMap = new Map<string, string>();
|
||||
for (const tag of tags) {
|
||||
if (tag[0] === 'emoji' && tag[1] && tag[2]) {
|
||||
emojiMap.set(tag[1], tag[2]);
|
||||
}
|
||||
}
|
||||
|
||||
if (emojiMap.size === 0) {
|
||||
return <span className={className}>{children}</span>;
|
||||
}
|
||||
|
||||
const parts: ReactNode[] = [];
|
||||
const regex = /:([a-zA-Z0-9_-]+):/g;
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = regex.exec(children)) !== null) {
|
||||
const [full, shortcode] = match;
|
||||
const url = emojiMap.get(shortcode);
|
||||
if (!url) continue;
|
||||
|
||||
if (match.index > lastIndex) {
|
||||
parts.push(children.substring(lastIndex, match.index));
|
||||
}
|
||||
parts.push(
|
||||
<CustomEmojiImg
|
||||
key={`emoji-${match.index}`}
|
||||
name={shortcode}
|
||||
url={url}
|
||||
/>,
|
||||
);
|
||||
lastIndex = match.index + full.length;
|
||||
}
|
||||
|
||||
if (lastIndex < children.length) {
|
||||
parts.push(children.substring(lastIndex));
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={className}>
|
||||
{parts.length > 0 ? parts : children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AddrCoords } from '@/components/NoteContent';
|
||||
|
||||
interface EmbeddedNaddrProps {
|
||||
addr: AddrCoords;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal embedded-naddr card — renders a link to the referenced
|
||||
* addressable event (kind:pubkey:identifier).
|
||||
*
|
||||
* Ditto's richer `EmbeddedNaddr` fetches the addressable event (long-form
|
||||
* article, marketplace listing, etc.) and renders a preview card with
|
||||
* title, author, cover image, and summary. Replace this stub with a
|
||||
* version that uses `useAddrEvent({kind, pubkey, identifier})` to fetch
|
||||
* and render the target event.
|
||||
*/
|
||||
export function EmbeddedNaddr({ addr, className }: EmbeddedNaddrProps) {
|
||||
const naddrId = nip19.naddrEncode({
|
||||
kind: addr.kind,
|
||||
pubkey: addr.pubkey,
|
||||
identifier: addr.identifier,
|
||||
});
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/${naddrId}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={cn(
|
||||
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">Addressable event</div>
|
||||
<div className="text-xs text-muted-foreground font-mono truncate">
|
||||
kind:{addr.kind} · {addr.identifier || '(no identifier)'}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface EmbeddedNoteProps {
|
||||
eventId: string;
|
||||
relays?: string[];
|
||||
authorHint?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal embedded-note card — renders a link to the referenced event.
|
||||
*
|
||||
* Ditto's richer `EmbeddedNote` fetches the quoted event, renders its
|
||||
* author, timestamp, and (recursively) its content inside a card.
|
||||
* Replace this stub with a version that uses a `useEvent(id, relays, author)`
|
||||
* hook to fetch and render the quoted note.
|
||||
*/
|
||||
export function EmbeddedNote({ eventId, relays, authorHint, className }: EmbeddedNoteProps) {
|
||||
const neventId = nip19.neventEncode({
|
||||
id: eventId,
|
||||
...(authorHint ? { author: authorHint } : {}),
|
||||
...(relays?.length ? { relays } : {}),
|
||||
});
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/${neventId}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={cn(
|
||||
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">Quoted note</div>
|
||||
<div className="text-xs text-muted-foreground font-mono truncate">
|
||||
{neventId.slice(0, 24)}…
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ImetaEntry } from '@/lib/imeta';
|
||||
|
||||
interface ImageGalleryProps {
|
||||
images: string[];
|
||||
/** Max images to show in the grid before "+ more" overflow. */
|
||||
maxVisible?: number;
|
||||
maxGridHeight?: string;
|
||||
/** imeta metadata keyed by URL (dim, blurhash, etc.). Unused in this stub. */
|
||||
imetaMap?: Map<string, ImetaEntry>;
|
||||
lightboxIndex?: number | null;
|
||||
onLightboxOpen?: (index: number) => void;
|
||||
onLightboxClose?: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal image gallery grid.
|
||||
*
|
||||
* Ditto's richer `ImageGallery` uses `imetaMap` for precise aspect ratios,
|
||||
* blurhash placeholders, CSS-grid masonry, pinch-to-zoom on mobile, and
|
||||
* keyboard navigation. Replace this stub with a richer gallery as needed.
|
||||
*/
|
||||
export function ImageGallery({
|
||||
images,
|
||||
maxVisible = 4,
|
||||
maxGridHeight,
|
||||
lightboxIndex,
|
||||
onLightboxOpen,
|
||||
onLightboxClose,
|
||||
className,
|
||||
}: ImageGalleryProps) {
|
||||
const shown = images.slice(0, maxVisible);
|
||||
const extra = Math.max(0, images.length - maxVisible);
|
||||
|
||||
// Two-column grid for 2+ images
|
||||
const gridCols = shown.length === 1 ? 'grid-cols-1' : 'grid-cols-2';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-2 my-2.5 rounded-lg overflow-hidden',
|
||||
gridCols,
|
||||
className,
|
||||
)}
|
||||
style={maxGridHeight ? { maxHeight: maxGridHeight } : undefined}
|
||||
>
|
||||
{shown.map((url, idx) => (
|
||||
<button
|
||||
key={idx}
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onLightboxOpen?.(idx);
|
||||
}}
|
||||
className="block relative overflow-hidden rounded-md bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className="block w-full h-full object-cover hover:opacity-90 transition-opacity"
|
||||
/>
|
||||
{idx === maxVisible - 1 && extra > 0 && (
|
||||
<div className="absolute inset-0 bg-black/50 text-white flex items-center justify-center text-xl font-semibold">
|
||||
+{extra}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{lightboxIndex !== null && lightboxIndex !== undefined && (
|
||||
<Lightbox
|
||||
images={images}
|
||||
currentIndex={lightboxIndex}
|
||||
onClose={onLightboxClose ?? (() => { /* noop */ })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface LightboxProps {
|
||||
images: string[];
|
||||
currentIndex: number;
|
||||
onClose: () => void;
|
||||
onNext?: () => void;
|
||||
onPrev?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal fullscreen lightbox — click-outside-to-close, arrow-key navigation.
|
||||
*
|
||||
* Ditto's richer `Lightbox` supports pinch-zoom, swipe gestures, download,
|
||||
* and alt-text overlays. Replace this stub with a richer viewer as needed.
|
||||
*/
|
||||
export function Lightbox({ images, currentIndex, onClose, onNext, onPrev }: LightboxProps) {
|
||||
const handleKey = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
else if (e.key === 'ArrowRight') onNext?.();
|
||||
else if (e.key === 'ArrowLeft') onPrev?.();
|
||||
},
|
||||
[onClose, onNext, onPrev],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener('keydown', handleKey);
|
||||
return () => window.removeEventListener('keydown', handleKey);
|
||||
}, [handleKey]);
|
||||
|
||||
const url = images[currentIndex];
|
||||
if (!url) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
}}
|
||||
className="absolute top-4 right-4 text-white text-3xl leading-none hover:opacity-70"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{onPrev && images.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onPrev();
|
||||
}}
|
||||
className="absolute left-4 top-1/2 -translate-y-1/2 text-white text-4xl leading-none hover:opacity-70"
|
||||
aria-label="Previous"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
)}
|
||||
{onNext && images.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onNext();
|
||||
}}
|
||||
className="absolute right-4 top-1/2 -translate-y-1/2 text-white text-4xl leading-none hover:opacity-70"
|
||||
aria-label="Next"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
)}
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
className="max-w-full max-h-full object-contain"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface LightningInvoiceCardProps {
|
||||
invoice: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal Lightning invoice card — renders a `lightning:` link that
|
||||
* opens in any installed wallet.
|
||||
*
|
||||
* Ditto's richer `LightningInvoiceCard` decodes the BOLT11 invoice,
|
||||
* shows the amount, description, expiry, pays via WebLN/NWC, renders
|
||||
* a QR code, and tracks payment state. To replicate, pair with the
|
||||
* `nwc` skill's `useWallet` / `useZaps` hooks and a bolt11 decoder
|
||||
* such as `light-bolt11-decoder`.
|
||||
*/
|
||||
export function LightningInvoiceCard({ invoice, className }: LightningInvoiceCardProps) {
|
||||
return (
|
||||
<a
|
||||
href={`lightning:${invoice}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={cn(
|
||||
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm my-2.5',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="font-medium">⚡ Lightning invoice</div>
|
||||
<div className="text-xs text-muted-foreground font-mono truncate">
|
||||
{invoice.slice(0, 24)}…
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={cn(
|
||||
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="font-medium truncate">{display}</div>
|
||||
<div className="text-xs text-muted-foreground truncate">{url}</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -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', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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;
|
||||
|
||||
@@ -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<string, string>,
|
||||
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(
|
||||
<CustomEmojiImg
|
||||
key={`emoji-${match.index}`}
|
||||
name={shortcode}
|
||||
url={url}
|
||||
className={imgClassName}
|
||||
/>,
|
||||
);
|
||||
|
||||
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 <Link> elements pointing to /i/iso3166:<CODE>.
|
||||
*/
|
||||
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(
|
||||
<Link
|
||||
key={`flag-${keyIdx++}`}
|
||||
to={`/i/iso3166:${code}`}
|
||||
className="hover:opacity-70 transition-opacity"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{flag}
|
||||
</Link>,
|
||||
);
|
||||
|
||||
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<string, string>): 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(
|
||||
<a
|
||||
key={`url-${keyCounter++}`}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:underline break-all"
|
||||
>
|
||||
{url}
|
||||
</a>
|
||||
);
|
||||
} 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(
|
||||
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
||||
);
|
||||
result.push({ type: 'mention', pubkey: decoded.data });
|
||||
} else if (decoded.type === 'nprofile') {
|
||||
const pubkey = decoded.data.pubkey;
|
||||
parts.push(
|
||||
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
||||
);
|
||||
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(
|
||||
<Link
|
||||
key={`nostr-${keyCounter++}`}
|
||||
to={`/${nostrId}`}
|
||||
className="text-blue-500 hover:underline break-all"
|
||||
>
|
||||
{fullMatch}
|
||||
</Link>
|
||||
);
|
||||
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(
|
||||
<Link
|
||||
key={`hashtag-${keyCounter++}`}
|
||||
to={`/t/${tag}`}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
{hashtag}
|
||||
</Link>
|
||||
);
|
||||
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<string, { relay?: string; author?: string }>();
|
||||
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<number | null>(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<number, number>();
|
||||
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 (
|
||||
<div className={cn("whitespace-pre-wrap break-words", className)}>
|
||||
{content.length > 0 ? content : event.content}
|
||||
<div dir="auto" className={cn('whitespace-pre-wrap break-words overflow-hidden', className, isEmojiOnly && 'text-5xl leading-tight')}>
|
||||
{groupedTokens.map((token, i) => {
|
||||
switch (token.type) {
|
||||
case 'text':
|
||||
return <span key={i}>{linkifyFlags(emojify(token.value, emojiMap, isEmojiOnly ? 'inline h-12 w-12 object-contain align-text-bottom' : undefined))}</span>;
|
||||
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 <span key={i}>{'\n'}</span>;
|
||||
}
|
||||
const imgIndex = tokenImageIndex.get(i) ?? 0;
|
||||
return (
|
||||
<InlineImage
|
||||
key={i}
|
||||
url={token.url}
|
||||
onClick={(e) => { e.stopPropagation(); setLightboxIndex(imgIndex); }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'image-gallery': {
|
||||
if (disableEmbeds || disableMediaEmbeds) {
|
||||
return <span key={i}>{token.urls.map(() => '\n').join('')}</span>;
|
||||
}
|
||||
const galleryStartIndex = tokenImageIndex.get(i) ?? 0;
|
||||
const galleryLightboxIndex =
|
||||
lightboxIndex !== null &&
|
||||
lightboxIndex >= galleryStartIndex &&
|
||||
lightboxIndex < galleryStartIndex + token.urls.length
|
||||
? lightboxIndex - galleryStartIndex
|
||||
: null;
|
||||
return (
|
||||
<ImageGallery
|
||||
key={i}
|
||||
images={token.urls}
|
||||
maxVisible={4}
|
||||
maxGridHeight="480px"
|
||||
imetaMap={imetaMap}
|
||||
lightboxIndex={galleryLightboxIndex}
|
||||
onLightboxOpen={(idx) => { setLightboxIndex(galleryStartIndex + idx); }}
|
||||
onLightboxClose={closeLightbox}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'link-embed':
|
||||
if (disableEmbeds) {
|
||||
return (
|
||||
<a
|
||||
key={i}
|
||||
href={token.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.url}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return <LinkEmbed key={i} url={token.url} className="my-2.5" hideImage={hideEmbedImages} />;
|
||||
case 'inline-link':
|
||||
return (
|
||||
<a
|
||||
key={i}
|
||||
href={token.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.url}
|
||||
</a>
|
||||
);
|
||||
case 'media-embed': {
|
||||
if (disableEmbeds || disableMediaEmbeds) {
|
||||
return <span key={i}>{'\n'}</span>;
|
||||
}
|
||||
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 <WebxdcEmbed key={i} url={token.url} uuid={imeta.webxdc} name={imeta.summary} icon={imeta.thumbnail} />;
|
||||
}
|
||||
if (isAudio) {
|
||||
return (
|
||||
<AudioVisualizer
|
||||
key={i}
|
||||
src={token.url}
|
||||
mime={imeta?.mime}
|
||||
avatarUrl={authorMetadata?.picture}
|
||||
avatarFallback={authorDisplayName[0]?.toUpperCase() ?? '?'}
|
||||
avatarShape={getAvatarShape(authorMetadata)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
// Default: video
|
||||
return (
|
||||
<VideoPlayer
|
||||
key={i}
|
||||
src={token.url}
|
||||
poster={imeta?.thumbnail}
|
||||
dim={imeta?.dim}
|
||||
blurhash={imeta?.blurhash}
|
||||
artist={authorDisplayName}
|
||||
/>
|
||||
);
|
||||
}
|
||||
case 'nevent-embed':
|
||||
if (disableNoteEmbeds) {
|
||||
const neventId = nip19.neventEncode({ id: token.eventId, ...(token.author ? { author: token.author } : {}), ...(token.relays?.length ? { relays: token.relays } : {}) });
|
||||
return (
|
||||
<Link
|
||||
key={i}
|
||||
to={`/${neventId}`}
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{neventId.slice(0, 16)}…
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return <EmbeddedNote key={i} eventId={token.eventId} relays={token.relays} authorHint={token.author} className="my-2.5" />;
|
||||
case 'naddr-embed':
|
||||
if (disableNoteEmbeds) {
|
||||
const naddrId = nip19.naddrEncode({ kind: token.addr.kind, pubkey: token.addr.pubkey, identifier: token.addr.identifier });
|
||||
return (
|
||||
<Link
|
||||
key={i}
|
||||
to={`/${naddrId}`}
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{naddrId.slice(0, 16)}…
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span key={i}>
|
||||
{token.url && (
|
||||
<a
|
||||
href={token.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.url}
|
||||
</a>
|
||||
)}
|
||||
<EmbeddedNaddr addr={token.addr} className="my-2.5" />
|
||||
</span>
|
||||
);
|
||||
case 'mention':
|
||||
return <NostrMention key={i} pubkey={token.pubkey} />;
|
||||
case 'nostr-link':
|
||||
return (
|
||||
<Link
|
||||
key={i}
|
||||
to={`/${token.id}`}
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.raw}
|
||||
</Link>
|
||||
);
|
||||
case 'hashtag':
|
||||
return (
|
||||
<Link
|
||||
key={i}
|
||||
to={`/t/${token.tag}`}
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.raw}
|
||||
</Link>
|
||||
);
|
||||
case 'relay-link':
|
||||
return (
|
||||
<Link
|
||||
key={i}
|
||||
to={`/r/${encodeURIComponent(token.url)}`}
|
||||
className="text-primary hover:underline break-all"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{token.url}
|
||||
</Link>
|
||||
);
|
||||
case 'lightning-invoice':
|
||||
if (disableEmbeds) {
|
||||
return <span key={i} className="text-primary break-all">{token.invoice}</span>;
|
||||
}
|
||||
return <LightningInvoiceCard key={i} invoice={token.invoice} />;
|
||||
}
|
||||
})}
|
||||
|
||||
{/* 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,
|
||||
) && (
|
||||
<Lightbox
|
||||
images={allImages}
|
||||
currentIndex={lightboxIndex}
|
||||
onClose={closeLightbox}
|
||||
onNext={goNext}
|
||||
onPrev={goPrev}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<Link
|
||||
to={`/${npub}`}
|
||||
className={cn(
|
||||
"font-medium hover:underline",
|
||||
hasRealName
|
||||
? "text-blue-500"
|
||||
: "text-gray-500 hover:text-gray-700"
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="block my-2 rounded-lg overflow-hidden w-full cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||
onClick={onClick}
|
||||
>
|
||||
@{displayName}
|
||||
</Link>
|
||||
<div className={cn('relative w-full rounded-lg overflow-hidden', !loaded && 'bg-muted')} style={!loaded ? { minHeight: 200 } : undefined}>
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className="block w-full h-auto rounded-lg hover:opacity-90 transition-opacity"
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => { setLoaded(true); onError(); }}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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 (
|
||||
<ProfileHoverCard pubkey={pubkey} asChild>
|
||||
<Link
|
||||
to={profileUrl}
|
||||
className={cn(
|
||||
'font-medium hover:underline',
|
||||
hasRealName
|
||||
? 'text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
@{author.data?.event ? (
|
||||
<EmojifiedText tags={author.data.event.tags}>{displayName}</EmojifiedText>
|
||||
) : displayName}
|
||||
</Link>
|
||||
</ProfileHoverCard>
|
||||
);
|
||||
}
|
||||
@@ -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}</>;
|
||||
}
|
||||
@@ -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 `<video controls>`.
|
||||
*
|
||||
* Ditto's richer `VideoPlayer` renders a blurhash placeholder, respects
|
||||
* `dim` for correct aspect ratio, supports background scrubbing, picture-in-picture,
|
||||
* and lightbox playback. Replace this stub with a richer player as needed.
|
||||
*/
|
||||
export function VideoPlayer({ src, poster, dim, blurhash: _blurhash, artist: _artist, className }: VideoPlayerProps) {
|
||||
// Compute aspect ratio from "WxH" if provided
|
||||
let aspectRatio: string | undefined;
|
||||
if (dim) {
|
||||
const match = dim.match(/^(\d+)x(\d+)$/);
|
||||
if (match) {
|
||||
aspectRatio = `${match[1]} / ${match[2]}`;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<video
|
||||
src={src}
|
||||
poster={poster}
|
||||
controls
|
||||
preload="metadata"
|
||||
playsInline
|
||||
className={cn('block rounded-lg my-2.5 w-full max-h-[480px] bg-black', className)}
|
||||
style={aspectRatio ? { aspectRatio } : undefined}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface WebxdcEmbedProps {
|
||||
url: string;
|
||||
uuid?: string;
|
||||
name?: string;
|
||||
icon?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal WebXDC app embed — renders a download/launch link.
|
||||
*
|
||||
* WebXDC is a self-contained interactive app packaged as a .xdc zip.
|
||||
* Ditto's richer `WebxdcEmbed` renders the app in an iframe with a
|
||||
* message-passing bridge to Nostr for state sync. Replace this stub
|
||||
* with a full WebXDC host when needed; see https://webxdc.org for the spec.
|
||||
*/
|
||||
export function WebxdcEmbed({ url, name, icon, className }: WebxdcEmbedProps) {
|
||||
return (
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={cn(
|
||||
'flex items-center gap-3 border rounded-lg px-3 py-2 my-2.5 hover:bg-muted/50 transition-colors text-sm',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{icon && (
|
||||
<img src={icon} alt="" className="w-10 h-10 rounded object-cover flex-shrink-0" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-medium truncate">{name ?? 'WebXDC app'}</div>
|
||||
<div className="text-xs text-muted-foreground truncate">{url}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
/**
|
||||
* Blossom-server fallback hook.
|
||||
*
|
||||
* When an image URL is hosted on a Blossom server that goes down,
|
||||
* apps can retry the same hash on a different server. This minimal
|
||||
* stub simply returns the original URL and a no-op `onError` handler.
|
||||
* Replace with a richer implementation that parses the URL's hash
|
||||
* suffix and rotates through the viewer's BUD-03 "User Server List"
|
||||
* (kind 10063) or an app-configured server list.
|
||||
*/
|
||||
export function useBlossomFallback(url: string): { src: string; onError: () => void } {
|
||||
const [src, setSrc] = useState(url);
|
||||
const onError = useCallback(() => {
|
||||
// Stub: no-op. A real implementation would swap `src` to the next
|
||||
// known Blossom mirror here.
|
||||
setSrc((prev) => prev);
|
||||
}, []);
|
||||
return { src, onError };
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Viewer's own custom emoji collection (NIP-30).
|
||||
*
|
||||
* This minimal stub returns an empty list. To enable the viewer's
|
||||
* custom emojis as a fallback when posts don't carry their own
|
||||
* `emoji` tags, replace this implementation with one that fetches
|
||||
* the user's kind 10030 "Emoji List" event and any kind 30030
|
||||
* "Emoji Set" events it references, then exposes every shortcode
|
||||
* → URL pair here.
|
||||
*/
|
||||
export function useCustomEmojis(): { emojis: Array<{ shortcode: string; url: string }> } {
|
||||
return { emojis: [] };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Returns the internal URL for a user's profile page.
|
||||
*
|
||||
* Defaults to `/<npub1...>`, matching the template's `/:nip19`
|
||||
* route in AppRouter. If a user's metadata has a `nip05` identifier
|
||||
* you want to prefer, swap the return statement accordingly
|
||||
* (e.g. `/@${nip05}` with a corresponding `/:handle` route).
|
||||
*
|
||||
* The `metadata` argument is accepted for parity with richer
|
||||
* implementations that route by NIP-05 handle; the stub ignores it.
|
||||
*/
|
||||
export function useProfileUrl(pubkey: string, _metadata?: NostrMetadata): string {
|
||||
return `/${nip19.npubEncode(pubkey)}`;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* An avatar shape is stored in kind-0 metadata as the `shape` property.
|
||||
* Typically an emoji glyph used as a mask (e.g. "🐱", "⭐").
|
||||
*
|
||||
* This minimal stub exposes just enough surface for `NoteContent` to
|
||||
* read the shape and pass it into `AudioVisualizer`. The stubbed
|
||||
* `AudioVisualizer` ignores it; a richer implementation would use
|
||||
* the shape to generate a CSS mask URL for the avatar.
|
||||
*/
|
||||
export type AvatarShape = string;
|
||||
|
||||
/**
|
||||
* Extract the avatar shape from Nostr metadata. Returns `undefined`
|
||||
* when the metadata is missing or has no `shape` field.
|
||||
*/
|
||||
export function getAvatarShape(
|
||||
metadata: { [key: string]: unknown } | undefined,
|
||||
): AvatarShape | undefined {
|
||||
if (!metadata) return undefined;
|
||||
const shape = metadata.shape;
|
||||
if (typeof shape !== 'string') return undefined;
|
||||
// Light guard: only return short, non-ASCII values (emoji-like)
|
||||
if (shape.length === 0 || shape.length > 20) return undefined;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (!/[^\x00-\x7F]/.test(shape)) return undefined;
|
||||
return shape;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
/** ISO 3166-1 alpha-2 country code to country name and flag emoji mapping. */
|
||||
export const COUNTRIES: Record<string, { name: string; flag: string }> = {
|
||||
AF: { name: 'Afghanistan', flag: '🇦🇫' },
|
||||
AL: { name: 'Albania', flag: '🇦🇱' },
|
||||
DZ: { name: 'Algeria', flag: '🇩🇿' },
|
||||
AD: { name: 'Andorra', flag: '🇦🇩' },
|
||||
AO: { name: 'Angola', flag: '🇦🇴' },
|
||||
AG: { name: 'Antigua and Barbuda', flag: '🇦🇬' },
|
||||
AR: { name: 'Argentina', flag: '🇦🇷' },
|
||||
AM: { name: 'Armenia', flag: '🇦🇲' },
|
||||
AU: { name: 'Australia', flag: '🇦🇺' },
|
||||
AT: { name: 'Austria', flag: '🇦🇹' },
|
||||
AZ: { name: 'Azerbaijan', flag: '🇦🇿' },
|
||||
BS: { name: 'Bahamas', flag: '🇧🇸' },
|
||||
BH: { name: 'Bahrain', flag: '🇧🇭' },
|
||||
BD: { name: 'Bangladesh', flag: '🇧🇩' },
|
||||
BB: { name: 'Barbados', flag: '🇧🇧' },
|
||||
BY: { name: 'Belarus', flag: '🇧🇾' },
|
||||
BE: { name: 'Belgium', flag: '🇧🇪' },
|
||||
BZ: { name: 'Belize', flag: '🇧🇿' },
|
||||
BJ: { name: 'Benin', flag: '🇧🇯' },
|
||||
BT: { name: 'Bhutan', flag: '🇧🇹' },
|
||||
BO: { name: 'Bolivia', flag: '🇧🇴' },
|
||||
BA: { name: 'Bosnia and Herzegovina', flag: '🇧🇦' },
|
||||
BW: { name: 'Botswana', flag: '🇧🇼' },
|
||||
BR: { name: 'Brazil', flag: '🇧🇷' },
|
||||
BN: { name: 'Brunei', flag: '🇧🇳' },
|
||||
BG: { name: 'Bulgaria', flag: '🇧🇬' },
|
||||
BF: { name: 'Burkina Faso', flag: '🇧🇫' },
|
||||
BI: { name: 'Burundi', flag: '🇧🇮' },
|
||||
CV: { name: 'Cabo Verde', flag: '🇨🇻' },
|
||||
KH: { name: 'Cambodia', flag: '🇰🇭' },
|
||||
CM: { name: 'Cameroon', flag: '🇨🇲' },
|
||||
CA: { name: 'Canada', flag: '🇨🇦' },
|
||||
CF: { name: 'Central African Republic', flag: '🇨🇫' },
|
||||
TD: { name: 'Chad', flag: '🇹🇩' },
|
||||
CL: { name: 'Chile', flag: '🇨🇱' },
|
||||
CN: { name: 'China', flag: '🇨🇳' },
|
||||
CO: { name: 'Colombia', flag: '🇨🇴' },
|
||||
KM: { name: 'Comoros', flag: '🇰🇲' },
|
||||
CG: { name: 'Congo', flag: '🇨🇬' },
|
||||
CD: { name: 'Congo (DRC)', flag: '🇨🇩' },
|
||||
CR: { name: 'Costa Rica', flag: '🇨🇷' },
|
||||
CI: { name: "Cote d'Ivoire", flag: '🇨🇮' },
|
||||
HR: { name: 'Croatia', flag: '🇭🇷' },
|
||||
CU: { name: 'Cuba', flag: '🇨🇺' },
|
||||
CY: { name: 'Cyprus', flag: '🇨🇾' },
|
||||
CZ: { name: 'Czechia', flag: '🇨🇿' },
|
||||
DK: { name: 'Denmark', flag: '🇩🇰' },
|
||||
DJ: { name: 'Djibouti', flag: '🇩🇯' },
|
||||
DM: { name: 'Dominica', flag: '🇩🇲' },
|
||||
DO: { name: 'Dominican Republic', flag: '🇩🇴' },
|
||||
EC: { name: 'Ecuador', flag: '🇪🇨' },
|
||||
EG: { name: 'Egypt', flag: '🇪🇬' },
|
||||
SV: { name: 'El Salvador', flag: '🇸🇻' },
|
||||
GQ: { name: 'Equatorial Guinea', flag: '🇬🇶' },
|
||||
ER: { name: 'Eritrea', flag: '🇪🇷' },
|
||||
EE: { name: 'Estonia', flag: '🇪🇪' },
|
||||
SZ: { name: 'Eswatini', flag: '🇸🇿' },
|
||||
ET: { name: 'Ethiopia', flag: '🇪🇹' },
|
||||
FJ: { name: 'Fiji', flag: '🇫🇯' },
|
||||
FI: { name: 'Finland', flag: '🇫🇮' },
|
||||
FR: { name: 'France', flag: '🇫🇷' },
|
||||
GA: { name: 'Gabon', flag: '🇬🇦' },
|
||||
GM: { name: 'Gambia', flag: '🇬🇲' },
|
||||
GE: { name: 'Georgia', flag: '🇬🇪' },
|
||||
DE: { name: 'Germany', flag: '🇩🇪' },
|
||||
GH: { name: 'Ghana', flag: '🇬🇭' },
|
||||
GR: { name: 'Greece', flag: '🇬🇷' },
|
||||
GD: { name: 'Grenada', flag: '🇬🇩' },
|
||||
GT: { name: 'Guatemala', flag: '🇬🇹' },
|
||||
GN: { name: 'Guinea', flag: '🇬🇳' },
|
||||
GW: { name: 'Guinea-Bissau', flag: '🇬🇼' },
|
||||
GY: { name: 'Guyana', flag: '🇬🇾' },
|
||||
HT: { name: 'Haiti', flag: '🇭🇹' },
|
||||
HN: { name: 'Honduras', flag: '🇭🇳' },
|
||||
HU: { name: 'Hungary', flag: '🇭🇺' },
|
||||
IS: { name: 'Iceland', flag: '🇮🇸' },
|
||||
IN: { name: 'India', flag: '🇮🇳' },
|
||||
ID: { name: 'Indonesia', flag: '🇮🇩' },
|
||||
IR: { name: 'Iran', flag: '🇮🇷' },
|
||||
IQ: { name: 'Iraq', flag: '🇮🇶' },
|
||||
IE: { name: 'Ireland', flag: '🇮🇪' },
|
||||
IL: { name: 'Israel', flag: '🇮🇱' },
|
||||
IT: { name: 'Italy', flag: '🇮🇹' },
|
||||
JM: { name: 'Jamaica', flag: '🇯🇲' },
|
||||
JP: { name: 'Japan', flag: '🇯🇵' },
|
||||
JO: { name: 'Jordan', flag: '🇯🇴' },
|
||||
KZ: { name: 'Kazakhstan', flag: '🇰🇿' },
|
||||
KE: { name: 'Kenya', flag: '🇰🇪' },
|
||||
KI: { name: 'Kiribati', flag: '🇰🇮' },
|
||||
KP: { name: 'North Korea', flag: '🇰🇵' },
|
||||
KR: { name: 'South Korea', flag: '🇰🇷' },
|
||||
KW: { name: 'Kuwait', flag: '🇰🇼' },
|
||||
KG: { name: 'Kyrgyzstan', flag: '🇰🇬' },
|
||||
LA: { name: 'Laos', flag: '🇱🇦' },
|
||||
LV: { name: 'Latvia', flag: '🇱🇻' },
|
||||
LB: { name: 'Lebanon', flag: '🇱🇧' },
|
||||
LS: { name: 'Lesotho', flag: '🇱🇸' },
|
||||
LR: { name: 'Liberia', flag: '🇱🇷' },
|
||||
LY: { name: 'Libya', flag: '🇱🇾' },
|
||||
LI: { name: 'Liechtenstein', flag: '🇱🇮' },
|
||||
LT: { name: 'Lithuania', flag: '🇱🇹' },
|
||||
LU: { name: 'Luxembourg', flag: '🇱🇺' },
|
||||
MG: { name: 'Madagascar', flag: '🇲🇬' },
|
||||
MW: { name: 'Malawi', flag: '🇲🇼' },
|
||||
MY: { name: 'Malaysia', flag: '🇲🇾' },
|
||||
MV: { name: 'Maldives', flag: '🇲🇻' },
|
||||
ML: { name: 'Mali', flag: '🇲🇱' },
|
||||
MT: { name: 'Malta', flag: '🇲🇹' },
|
||||
MH: { name: 'Marshall Islands', flag: '🇲🇭' },
|
||||
MR: { name: 'Mauritania', flag: '🇲🇷' },
|
||||
MU: { name: 'Mauritius', flag: '🇲🇺' },
|
||||
MX: { name: 'Mexico', flag: '🇲🇽' },
|
||||
FM: { name: 'Micronesia', flag: '🇫🇲' },
|
||||
MD: { name: 'Moldova', flag: '🇲🇩' },
|
||||
MC: { name: 'Monaco', flag: '🇲🇨' },
|
||||
MN: { name: 'Mongolia', flag: '🇲🇳' },
|
||||
ME: { name: 'Montenegro', flag: '🇲🇪' },
|
||||
MA: { name: 'Morocco', flag: '🇲🇦' },
|
||||
MZ: { name: 'Mozambique', flag: '🇲🇿' },
|
||||
MM: { name: 'Myanmar', flag: '🇲🇲' },
|
||||
NA: { name: 'Namibia', flag: '🇳🇦' },
|
||||
NR: { name: 'Nauru', flag: '🇳🇷' },
|
||||
NP: { name: 'Nepal', flag: '🇳🇵' },
|
||||
NL: { name: 'Netherlands', flag: '🇳🇱' },
|
||||
NZ: { name: 'New Zealand', flag: '🇳🇿' },
|
||||
NI: { name: 'Nicaragua', flag: '🇳🇮' },
|
||||
NE: { name: 'Niger', flag: '🇳🇪' },
|
||||
NG: { name: 'Nigeria', flag: '🇳🇬' },
|
||||
MK: { name: 'North Macedonia', flag: '🇲🇰' },
|
||||
NO: { name: 'Norway', flag: '🇳🇴' },
|
||||
OM: { name: 'Oman', flag: '🇴🇲' },
|
||||
PK: { name: 'Pakistan', flag: '🇵🇰' },
|
||||
PW: { name: 'Palau', flag: '🇵🇼' },
|
||||
PA: { name: 'Panama', flag: '🇵🇦' },
|
||||
PG: { name: 'Papua New Guinea', flag: '🇵🇬' },
|
||||
PY: { name: 'Paraguay', flag: '🇵🇾' },
|
||||
PE: { name: 'Peru', flag: '🇵🇪' },
|
||||
PH: { name: 'Philippines', flag: '🇵🇭' },
|
||||
PL: { name: 'Poland', flag: '🇵🇱' },
|
||||
PT: { name: 'Portugal', flag: '🇵🇹' },
|
||||
QA: { name: 'Qatar', flag: '🇶🇦' },
|
||||
RO: { name: 'Romania', flag: '🇷🇴' },
|
||||
RU: { name: 'Russia', flag: '🇷🇺' },
|
||||
RW: { name: 'Rwanda', flag: '🇷🇼' },
|
||||
KN: { name: 'Saint Kitts and Nevis', flag: '🇰🇳' },
|
||||
LC: { name: 'Saint Lucia', flag: '🇱🇨' },
|
||||
VC: { name: 'Saint Vincent and the Grenadines', flag: '🇻🇨' },
|
||||
WS: { name: 'Samoa', flag: '🇼🇸' },
|
||||
SM: { name: 'San Marino', flag: '🇸🇲' },
|
||||
ST: { name: 'Sao Tome and Principe', flag: '🇸🇹' },
|
||||
SA: { name: 'Saudi Arabia', flag: '🇸🇦' },
|
||||
SN: { name: 'Senegal', flag: '🇸🇳' },
|
||||
RS: { name: 'Serbia', flag: '🇷🇸' },
|
||||
SC: { name: 'Seychelles', flag: '🇸🇨' },
|
||||
SL: { name: 'Sierra Leone', flag: '🇸🇱' },
|
||||
SG: { name: 'Singapore', flag: '🇸🇬' },
|
||||
SK: { name: 'Slovakia', flag: '🇸🇰' },
|
||||
SI: { name: 'Slovenia', flag: '🇸🇮' },
|
||||
SB: { name: 'Solomon Islands', flag: '🇸🇧' },
|
||||
SO: { name: 'Somalia', flag: '🇸🇴' },
|
||||
ZA: { name: 'South Africa', flag: '🇿🇦' },
|
||||
SS: { name: 'South Sudan', flag: '🇸🇸' },
|
||||
ES: { name: 'Spain', flag: '🇪🇸' },
|
||||
LK: { name: 'Sri Lanka', flag: '🇱🇰' },
|
||||
SD: { name: 'Sudan', flag: '🇸🇩' },
|
||||
SR: { name: 'Suriname', flag: '🇸🇷' },
|
||||
SE: { name: 'Sweden', flag: '🇸🇪' },
|
||||
CH: { name: 'Switzerland', flag: '🇨🇭' },
|
||||
SY: { name: 'Syria', flag: '🇸🇾' },
|
||||
TW: { name: 'Taiwan', flag: '🇹🇼' },
|
||||
TJ: { name: 'Tajikistan', flag: '🇹🇯' },
|
||||
TZ: { name: 'Tanzania', flag: '🇹🇿' },
|
||||
TH: { name: 'Thailand', flag: '🇹🇭' },
|
||||
TL: { name: 'Timor-Leste', flag: '🇹🇱' },
|
||||
TG: { name: 'Togo', flag: '🇹🇬' },
|
||||
TO: { name: 'Tonga', flag: '🇹🇴' },
|
||||
TT: { name: 'Trinidad and Tobago', flag: '🇹🇹' },
|
||||
TN: { name: 'Tunisia', flag: '🇹🇳' },
|
||||
TR: { name: 'Turkey', flag: '🇹🇷' },
|
||||
TM: { name: 'Turkmenistan', flag: '🇹🇲' },
|
||||
TV: { name: 'Tuvalu', flag: '🇹🇻' },
|
||||
UG: { name: 'Uganda', flag: '🇺🇬' },
|
||||
UA: { name: 'Ukraine', flag: '🇺🇦' },
|
||||
AE: { name: 'United Arab Emirates', flag: '🇦🇪' },
|
||||
GB: { name: 'United Kingdom', flag: '🇬🇧' },
|
||||
US: { name: 'United States', flag: '🇺🇸' },
|
||||
UY: { name: 'Uruguay', flag: '🇺🇾' },
|
||||
UZ: { name: 'Uzbekistan', flag: '🇺🇿' },
|
||||
VU: { name: 'Vanuatu', flag: '🇻🇺' },
|
||||
VA: { name: 'Vatican City', flag: '🇻🇦' },
|
||||
VE: { name: 'Venezuela', flag: '🇻🇪' },
|
||||
VN: { name: 'Vietnam', flag: '🇻🇳' },
|
||||
YE: { name: 'Yemen', flag: '🇾🇪' },
|
||||
ZM: { name: 'Zambia', flag: '🇿🇲' },
|
||||
ZW: { name: 'Zimbabwe', flag: '🇿🇼' },
|
||||
};
|
||||
|
||||
/** Pre-sorted array of country entries for searching. */
|
||||
const COUNTRY_LIST = Object.entries(COUNTRIES)
|
||||
.map(([code, { name, flag }]) => ({ code, name, flag }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
export type CountryEntry = typeof COUNTRY_LIST[number];
|
||||
|
||||
export interface CountryMatch {
|
||||
country: CountryEntry;
|
||||
exact: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a single country matching the query (case-insensitive).
|
||||
* Matches exact code/name or name prefix (e.g. "angol" -> Angola).
|
||||
* Returns the match with an `exact` flag indicating whether it was a full match.
|
||||
*/
|
||||
export function searchCountry(query: string): CountryMatch | null {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (q.length < 2) return null;
|
||||
|
||||
// Exact code match
|
||||
for (const entry of COUNTRY_LIST) {
|
||||
if (entry.code.toLowerCase() === q) {
|
||||
return { country: entry, exact: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Exact name match
|
||||
for (const entry of COUNTRY_LIST) {
|
||||
if (entry.name.toLowerCase() === q) {
|
||||
return { country: entry, exact: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix match (shortest name = most specific)
|
||||
let best: CountryEntry | null = null;
|
||||
for (const entry of COUNTRY_LIST) {
|
||||
if (entry.name.toLowerCase().startsWith(q)) {
|
||||
if (!best || entry.name.length < best.name.length) {
|
||||
best = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best ? { country: best, exact: false } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map of ISO 3166-1 alpha-2 codes to their Wikipedia article titles,
|
||||
* only for countries whose common name differs from the Wikipedia title.
|
||||
*/
|
||||
const WIKIPEDIA_TITLES: Record<string, string> = {
|
||||
BS: 'The Bahamas',
|
||||
BO: 'Bolivia',
|
||||
CG: 'Republic of the Congo',
|
||||
CD: 'Democratic Republic of the Congo',
|
||||
CI: 'Ivory Coast',
|
||||
CZ: 'Czech Republic',
|
||||
SZ: 'Eswatini',
|
||||
GM: 'The Gambia',
|
||||
GE: 'Georgia (country)',
|
||||
IR: 'Iran',
|
||||
KP: 'North Korea',
|
||||
KR: 'South Korea',
|
||||
LA: 'Laos',
|
||||
FM: 'Federated States of Micronesia',
|
||||
MD: 'Moldova',
|
||||
MM: 'Myanmar',
|
||||
MK: 'North Macedonia',
|
||||
RU: 'Russia',
|
||||
ST: 'São Tomé and Príncipe',
|
||||
SY: 'Syria',
|
||||
TW: 'Taiwan',
|
||||
TZ: 'Tanzania',
|
||||
GB: 'United Kingdom',
|
||||
US: 'United States',
|
||||
VE: 'Venezuela',
|
||||
VN: 'Vietnam',
|
||||
};
|
||||
|
||||
/** Get the Wikipedia article title for a country. */
|
||||
export function getWikipediaTitle(code: string): string | null {
|
||||
const upper = code.toUpperCase();
|
||||
|
||||
if (upper.includes('-')) {
|
||||
// Subdivision — fall back to parent country
|
||||
const countryCode = upper.split('-')[0];
|
||||
const country = COUNTRIES[countryCode];
|
||||
if (!country) return null;
|
||||
return WIKIPEDIA_TITLES[countryCode] ?? country.name;
|
||||
}
|
||||
|
||||
const country = COUNTRIES[upper];
|
||||
if (!country) return null;
|
||||
return WIKIPEDIA_TITLES[upper] ?? country.name;
|
||||
}
|
||||
|
||||
/** Get country info from an ISO 3166 code (country or subdivision). */
|
||||
export function getCountryInfo(code: string): { name: string; flag: string; subdivision?: string } | null {
|
||||
const upper = code.toUpperCase();
|
||||
|
||||
// Handle subdivision codes like "US-CA"
|
||||
if (upper.includes('-')) {
|
||||
const [countryCode] = upper.split('-');
|
||||
const country = COUNTRIES[countryCode];
|
||||
if (!country) return null;
|
||||
return {
|
||||
name: country.name,
|
||||
flag: country.flag,
|
||||
subdivision: upper,
|
||||
};
|
||||
}
|
||||
|
||||
const country = COUNTRIES[upper];
|
||||
if (!country) return null;
|
||||
return { name: country.name, flag: country.flag };
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Checks if a string is a NIP-30 custom emoji shortcode (`:shortcode:` format).
|
||||
*/
|
||||
export function isCustomEmoji(content: string): boolean {
|
||||
return /^:[a-zA-Z0-9_-]+:$/.test(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the custom emoji URL from a NostrEvent's tags for a given shortcode.
|
||||
* The shortcode should include the colons (e.g., `:soapbox:`).
|
||||
*/
|
||||
export function getCustomEmojiUrl(shortcode: string, tags: string[][]): string | undefined {
|
||||
const name = shortcode.slice(1, -1); // Remove surrounding colons
|
||||
const emojiTag = tags.find(([tagName, tagShortcode]) => tagName === 'emoji' && tagShortcode === name);
|
||||
return emojiTag?.[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a map of shortcode -> URL from an event's emoji tags.
|
||||
*/
|
||||
export function buildEmojiMap(tags: string[][]): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const tag of tags) {
|
||||
if (tag[0] === 'emoji' && tag[1] && tag[2]) {
|
||||
map.set(tag[1], tag[2]);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a resolved reaction emoji that can be rendered.
|
||||
* For custom emojis, includes the URL; for unicode, just the content string.
|
||||
*/
|
||||
export interface ResolvedEmoji {
|
||||
/** The display content — unicode emoji string or `:shortcode:` */
|
||||
content: string;
|
||||
/** For custom emojis, the image URL. Undefined for unicode emojis. */
|
||||
url?: string;
|
||||
/** For custom emojis, the shortcode name (without colons). */
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a kind 7 reaction event is valid.
|
||||
* Custom emoji reactions (`:shortcode:` content) are invalid without a matching `emoji` tag.
|
||||
*/
|
||||
export function isValidReaction(event: NostrEvent): boolean {
|
||||
const content = event.content.trim();
|
||||
const emoji = (content === '+' || content === '') ? '+' : content;
|
||||
if (isCustomEmoji(emoji)) {
|
||||
return getCustomEmojiUrl(emoji, event.tags) !== undefined;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a reaction emoji from a kind 7 event into a ResolvedEmoji.
|
||||
* Returns `undefined` for malformed custom emoji reactions (missing emoji tag).
|
||||
*/
|
||||
export function resolveReactionEmoji(event: NostrEvent): ResolvedEmoji | undefined {
|
||||
const content = event.content.trim();
|
||||
const emoji = (content === '+' || content === '') ? '👍' : content === '-' ? '👎' : content;
|
||||
|
||||
if (isCustomEmoji(emoji)) {
|
||||
const url = getCustomEmojiUrl(emoji, event.tags);
|
||||
if (url) {
|
||||
return { content: emoji, url, name: emoji.slice(1, -1) };
|
||||
}
|
||||
// Malformed: custom emoji shortcode without a matching emoji tag
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return { content: emoji };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Get a display name for a user.
|
||||
* Uses metadata.name if available, otherwise generates a deterministic username.
|
||||
* Visual truncation is handled by CSS (`truncate` class) on the containing element
|
||||
* to avoid breaking NIP-30 custom emoji shortcodes.
|
||||
*/
|
||||
export function getDisplayName(
|
||||
metadata: NostrMetadata | undefined,
|
||||
pubkey: string,
|
||||
): string {
|
||||
return metadata?.name || genUserName(pubkey);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/** Parsed imeta entry from NIP-94 tags. */
|
||||
export interface ImetaEntry {
|
||||
url: string;
|
||||
thumbnail?: string;
|
||||
mime?: string;
|
||||
/** Summary text (used as webxdc app name for webxdc attachments). */
|
||||
summary?: string;
|
||||
/** Webxdc session UUID — present when the attachment is a stateful webxdc app. */
|
||||
webxdc?: string;
|
||||
/** Pixel dimensions from NIP-94 `dim` tag, e.g. "1280x720". */
|
||||
dim?: string;
|
||||
/** Blurhash placeholder from NIP-94 `blurhash` tag. */
|
||||
blurhash?: string;
|
||||
}
|
||||
|
||||
/** Parse all imeta tags into a map keyed by URL. Works for any event kind. */
|
||||
export function parseImetaMap(tags: string[][]): Map<string, ImetaEntry> {
|
||||
const map = new Map<string, ImetaEntry>();
|
||||
for (const tag of tags) {
|
||||
if (tag[0] !== 'imeta') continue;
|
||||
const entry: Record<string, string> = {};
|
||||
for (let i = 1; i < tag.length; i++) {
|
||||
const part = tag[i];
|
||||
const spaceIdx = part.indexOf(' ');
|
||||
if (spaceIdx === -1) continue;
|
||||
const key = part.slice(0, spaceIdx);
|
||||
const value = part.slice(spaceIdx + 1);
|
||||
entry[key] = value;
|
||||
}
|
||||
if (entry.url) {
|
||||
map.set(entry.url, {
|
||||
url: entry.url,
|
||||
thumbnail: entry.image,
|
||||
mime: entry.m,
|
||||
summary: entry.summary,
|
||||
webxdc: entry.webxdc,
|
||||
dim: entry.dim,
|
||||
blurhash: entry.blurhash,
|
||||
});
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/** Image extensions rendered inline. */
|
||||
export const IMAGE_EXTS = 'jpg|jpeg|png|gif|webp|svg|avif';
|
||||
|
||||
/** Video extensions rendered as players. */
|
||||
export const VIDEO_EXTS = 'mp4|webm|mov|qt|avi|mkv|flv';
|
||||
|
||||
/** Audio extensions rendered as players. */
|
||||
export const AUDIO_EXTS = 'mp3|wav|ogg|flac|m4a|aac|opus';
|
||||
|
||||
/** All media extensions (image + video + audio + webxdc). */
|
||||
export const ALL_MEDIA_EXTS = `${IMAGE_EXTS}|${VIDEO_EXTS}|${AUDIO_EXTS}|xdc`;
|
||||
|
||||
/** Matches image URLs. */
|
||||
export const IMAGE_URL_REGEX = new RegExp(
|
||||
`https?:\\/\\/[^\\s]+\\.(${IMAGE_EXTS})(\\?[^\\s]*)?`,
|
||||
'i',
|
||||
);
|
||||
|
||||
/** Matches video URLs. */
|
||||
export const VIDEO_URL_REGEX = new RegExp(
|
||||
`https?:\\/\\/[^\\s]+\\.(${VIDEO_EXTS})(\\?[^\\s]*)?`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
/** Matches audio URLs. */
|
||||
export const AUDIO_URL_REGEX = new RegExp(
|
||||
`https?:\\/\\/[^\\s]+\\.(${AUDIO_EXTS})(\\?[^\\s]*)?`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
/** Matches any media URL (video, audio, webxdc) that is rendered as an embed — not a link preview. */
|
||||
export const EMBED_MEDIA_URL_REGEX = new RegExp(
|
||||
`https?:\\/\\/[^\\s]+\\.(${VIDEO_EXTS}|${AUDIO_EXTS}|xdc)(\\?[^\\s]*)?`,
|
||||
'i',
|
||||
);
|
||||
|
||||
/** Matches all NIP-92 media URLs for imeta tag generation (images + video + audio + webxdc). */
|
||||
export const IMETA_MEDIA_URL_REGEX = new RegExp(
|
||||
`https?:\\/\\/[^\\s]+\\.(${ALL_MEDIA_EXTS})(\\?[^\\s]*)?`,
|
||||
'gi',
|
||||
);
|
||||
|
||||
/**
|
||||
* Non-global variant of IMETA_MEDIA_URL_REGEX, safe for `.test()` calls.
|
||||
*
|
||||
* IMPORTANT: Never use the global (`g`) IMETA_MEDIA_URL_REGEX with `.test()` —
|
||||
* the global flag makes `lastIndex` stateful, so repeated `.test()` calls
|
||||
* (e.g. inside `.find()` or `.filter()`) will alternate between matching and
|
||||
* not matching, causing every other URL to be misclassified.
|
||||
*/
|
||||
export const IMETA_MEDIA_URL_TEST_REGEX = new RegExp(
|
||||
IMETA_MEDIA_URL_REGEX.source,
|
||||
'i',
|
||||
);
|
||||
|
||||
/** Infers a MIME type from a file extension string (lowercase). */
|
||||
export function mimeFromExt(ext: string): string {
|
||||
switch (ext) {
|
||||
case 'jpg': case 'jpeg': return 'image/jpeg';
|
||||
case 'png': return 'image/png';
|
||||
case 'gif': return 'image/gif';
|
||||
case 'webp': return 'image/webp';
|
||||
case 'svg': return 'image/svg+xml';
|
||||
case 'avif': return 'image/avif';
|
||||
case 'mp4': return 'video/mp4';
|
||||
case 'webm': return 'video/webm';
|
||||
case 'mov': return 'video/quicktime';
|
||||
case 'qt': return 'video/quicktime';
|
||||
case 'avi': return 'video/x-msvideo';
|
||||
case 'mkv': return 'video/x-matroska';
|
||||
case 'flv': return 'video/x-flv';
|
||||
case 'mp3': return 'audio/mpeg';
|
||||
case 'wav': return 'audio/wav';
|
||||
case 'ogg': return 'audio/ogg';
|
||||
case 'flac': return 'audio/flac';
|
||||
case 'm4a': return 'audio/mp4';
|
||||
case 'aac': return 'audio/aac';
|
||||
case 'opus': return 'audio/opus';
|
||||
case 'xdc': return 'application/x-webxdc';
|
||||
default: return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Extracts all video URLs from a string. */
|
||||
export function extractVideoUrls(content: string): string[] {
|
||||
return content.match(new RegExp(VIDEO_URL_REGEX.source, 'gi')) ?? [];
|
||||
}
|
||||
|
||||
/** Extracts all audio URLs from a string. */
|
||||
export function extractAudioUrls(content: string): string[] {
|
||||
return content.match(new RegExp(AUDIO_URL_REGEX.source, 'gi')) ?? [];
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Validate that a string is a well-formed HTTPS URL.
|
||||
*
|
||||
* Returns the normalised `href` when valid, or `undefined` otherwise.
|
||||
* This **must** be used whenever a URL originates from untrusted Nostr
|
||||
* event data (tags, metadata fields, etc.) and will be placed into an
|
||||
* `href`, `window.open()`, or `openUrl()` call. Without this check a
|
||||
* malicious `javascript:` URI could execute arbitrary code.
|
||||
*/
|
||||
export function sanitizeUrl(raw: string | undefined | null): string | undefined {
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const parsed = new URL(raw);
|
||||
if (parsed.protocol === 'https:') {
|
||||
return parsed.href;
|
||||
}
|
||||
} catch {
|
||||
// not a valid URL
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
Reference in new issue
Block a user