mirror of
https://github.com/hoornet/vega.git
synced 2026-04-29 09:10:00 -07:00
Refactor: split overgrown files into focused modules
Split client.ts (1036 lines) into 11 domain modules under lib/nostr/ — core, notes, social, articles, engagement, dms, bookmarks, muting, search, relays, trending. Barrel index.ts re-exports all; zero consumer import changes. Extract ProfileView sub-components (ImageField, Nip05Field, EditProfileForm, ProfileMediaGallery), NoteContent renderers (TextSegments, MediaCards), and NoteCard actions (NoteActions, InlineReplyBox). All component files now ≤270 lines, all lib files ≤300.
This commit is contained in:
96
src/components/feed/InlineReplyBox.tsx
Normal file
96
src/components/feed/InlineReplyBox.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { NDKEvent } from "@nostr-dev-kit/ndk";
|
||||
import { publishReply } from "../../lib/nostr";
|
||||
import { useReplyCount } from "../../hooks/useReplyCount";
|
||||
import { EmojiPicker } from "../shared/EmojiPicker";
|
||||
|
||||
interface InlineReplyBoxProps {
|
||||
event: NDKEvent;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function InlineReplyBox({ event, name }: InlineReplyBoxProps) {
|
||||
const [replyText, setReplyText] = useState("");
|
||||
const [replying, setReplying] = useState(false);
|
||||
const [replyError, setReplyError] = useState<string | null>(null);
|
||||
const [replySent, setReplySent] = useState(false);
|
||||
const [showReplyEmoji, setShowReplyEmoji] = useState(false);
|
||||
const replyRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [, adjustReplyCount] = useReplyCount(event.id);
|
||||
|
||||
const handleReplySubmit = async () => {
|
||||
if (!replyText.trim() || replying) return;
|
||||
setReplying(true);
|
||||
setReplyError(null);
|
||||
try {
|
||||
await publishReply(replyText.trim(), { id: event.id, pubkey: event.pubkey });
|
||||
setReplyText("");
|
||||
setReplySent(true);
|
||||
adjustReplyCount(1);
|
||||
setTimeout(() => { setReplySent(false); }, 1500);
|
||||
} catch (err) {
|
||||
setReplyError(`Failed: ${err}`);
|
||||
} finally {
|
||||
setReplying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReplyKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) handleReplySubmit();
|
||||
if (e.key === "Escape") {
|
||||
// Parent controls visibility — just blur
|
||||
replyRef.current?.blur();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-2 border-l-2 border-border pl-3">
|
||||
<textarea
|
||||
ref={replyRef}
|
||||
value={replyText}
|
||||
onChange={(e) => setReplyText(e.target.value)}
|
||||
onKeyDown={handleReplyKeyDown}
|
||||
placeholder={`Reply to ${name}…`}
|
||||
rows={2}
|
||||
className="w-full bg-transparent text-text text-[12px] placeholder:text-text-dim resize-none focus:outline-none"
|
||||
autoFocus
|
||||
/>
|
||||
{replyError && <p className="text-danger text-[10px] mb-1">{replyError}</p>}
|
||||
<div className="flex items-center justify-end gap-2 mt-1">
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowReplyEmoji((v) => !v)}
|
||||
title="Insert emoji"
|
||||
className="text-text-dim hover:text-text text-[12px] transition-colors"
|
||||
>
|
||||
☺
|
||||
</button>
|
||||
{showReplyEmoji && (
|
||||
<EmojiPicker
|
||||
onSelect={(emoji) => {
|
||||
const ta = replyRef.current;
|
||||
if (ta) {
|
||||
const start = ta.selectionStart ?? replyText.length;
|
||||
const end = ta.selectionEnd ?? replyText.length;
|
||||
setReplyText(replyText.slice(0, start) + emoji + replyText.slice(end));
|
||||
setTimeout(() => { ta.selectionStart = ta.selectionEnd = start + emoji.length; ta.focus(); }, 0);
|
||||
} else {
|
||||
setReplyText((t) => t + emoji);
|
||||
}
|
||||
}}
|
||||
onClose={() => setShowReplyEmoji(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-text-dim text-[10px]">Ctrl+Enter</span>
|
||||
<button
|
||||
onClick={handleReplySubmit}
|
||||
disabled={!replyText.trim() || replying}
|
||||
className="px-2 py-0.5 text-[10px] bg-accent hover:bg-accent-hover text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
{replySent ? "replied ✓" : replying ? "posting…" : "reply"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
116
src/components/feed/MediaCards.tsx
Normal file
116
src/components/feed/MediaCards.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import { ContentSegment } from "../../lib/parsing";
|
||||
|
||||
export function VideoBlock({ sources }: { sources: string[] }) {
|
||||
if (sources.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{sources.map((src, i) => (
|
||||
<video
|
||||
key={i}
|
||||
src={src}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
className="max-w-full max-h-80 rounded-sm bg-bg-raised border border-border"
|
||||
onError={(e) => { (e.target as HTMLVideoElement).style.display = "none"; }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AudioBlock({ sources }: { sources: string[] }) {
|
||||
if (sources.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{sources.map((src, i) => {
|
||||
const filename = src.split("/").pop()?.split("?")[0] ?? src;
|
||||
return (
|
||||
<div key={i} className="rounded-sm bg-bg-raised border border-border p-2">
|
||||
<div className="text-[11px] text-text-muted mb-1 truncate">{filename}</div>
|
||||
<audio controls preload="metadata" className="w-full h-8" src={src} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function YouTubeCard({ seg }: { seg: ContentSegment }) {
|
||||
return (
|
||||
<a
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<img
|
||||
src={`https://img.youtube.com/vi/${seg.mediaId}/hqdefault.jpg`}
|
||||
alt=""
|
||||
className="w-28 h-16 rounded-sm object-cover shrink-0"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">YouTube</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function VimeoCard({ seg }: { seg: ContentSegment }) {
|
||||
return (
|
||||
<a
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-black/40 flex items-center justify-center shrink-0">
|
||||
<svg width="14" height="14" viewBox="0 0 20 20" fill="white"><polygon points="6,3 17,10 6,17" /></svg>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Vimeo</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpotifyCard({ seg }: { seg: ContentSegment }) {
|
||||
return (
|
||||
<a
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-[#1DB954]/20 flex items-center justify-center shrink-0">
|
||||
<span className="text-[#1DB954] text-lg font-bold">S</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Spotify · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function TidalCard({ seg }: { seg: ContentSegment }) {
|
||||
return (
|
||||
<a
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center shrink-0">
|
||||
<span className="text-white text-lg font-bold">T</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Tidal · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
224
src/components/feed/NoteActions.tsx
Normal file
224
src/components/feed/NoteActions.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
import { useState } from "react";
|
||||
import { NDKEvent, nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { useReactionCount } from "../../hooks/useReactionCount";
|
||||
import { useReplyCount } from "../../hooks/useReplyCount";
|
||||
import { useZapCount } from "../../hooks/useZapCount";
|
||||
import { useUserStore } from "../../stores/user";
|
||||
import { useBookmarkStore } from "../../stores/bookmark";
|
||||
import { publishReaction, publishRepost } from "../../lib/nostr";
|
||||
import { ZapModal } from "../zap/ZapModal";
|
||||
import { QuoteModal } from "./QuoteModal";
|
||||
|
||||
const REACTION_EMOJIS = ["❤️", "🤙", "🔥", "😂", "🫡", "👀", "⚡"];
|
||||
|
||||
interface NoteActionsProps {
|
||||
event: NDKEvent;
|
||||
onReplyToggle: () => void;
|
||||
showReply: boolean;
|
||||
}
|
||||
|
||||
export function NoteActions({ event, onReplyToggle, showReply }: NoteActionsProps) {
|
||||
const profile = useProfile(event.pubkey);
|
||||
const name = profile?.displayName || profile?.name || event.pubkey.slice(0, 8) + "…";
|
||||
const avatar = profile?.picture;
|
||||
const { loggedIn } = useUserStore();
|
||||
const { bookmarkedIds, addBookmark, removeBookmark } = useBookmarkStore();
|
||||
const isBookmarked = bookmarkedIds.includes(event.id!);
|
||||
|
||||
const likedKey = "wrystr_liked";
|
||||
const getLiked = () => {
|
||||
try { return new Set<string>(JSON.parse(localStorage.getItem(likedKey) || "[]")); }
|
||||
catch { return new Set<string>(); }
|
||||
};
|
||||
const [liked, setLiked] = useState(() => getLiked().has(event.id));
|
||||
const [liking, setLiking] = useState(false);
|
||||
const [reactionCount, adjustReactionCount] = useReactionCount(event.id);
|
||||
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
|
||||
const [replyCount] = useReplyCount(event.id);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const zapData = useZapCount(event.id);
|
||||
const [showZap, setShowZap] = useState(false);
|
||||
const [showQuote, setShowQuote] = useState(false);
|
||||
const [reposting, setReposting] = useState(false);
|
||||
const [reposted, setReposted] = useState(false);
|
||||
|
||||
const handleReact = async (emoji?: string) => {
|
||||
if (!loggedIn || liked || liking) return;
|
||||
setLiking(true);
|
||||
setShowEmojiPicker(false);
|
||||
try {
|
||||
await publishReaction(event.id, event.pubkey, emoji || "+");
|
||||
const likedSet = getLiked();
|
||||
likedSet.add(event.id);
|
||||
localStorage.setItem(likedKey, JSON.stringify(Array.from(likedSet)));
|
||||
setLiked(true);
|
||||
adjustReactionCount(1);
|
||||
} finally {
|
||||
setLiking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
const nevent = nip19.neventEncode({ id: event.id!, author: event.pubkey });
|
||||
await navigator.clipboard.writeText("nostr:" + nevent);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const handleRepost = async () => {
|
||||
if (reposting || reposted) return;
|
||||
setReposting(true);
|
||||
try {
|
||||
await publishRepost(event);
|
||||
setReposted(true);
|
||||
} finally {
|
||||
setReposting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-4 mt-2">
|
||||
<button
|
||||
onClick={onReplyToggle}
|
||||
className={`text-[11px] transition-colors ${
|
||||
showReply ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
reply{replyCount !== null && replyCount > 0 ? ` ${replyCount}` : ""}
|
||||
</button>
|
||||
<div className="relative flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => handleReact("❤️")}
|
||||
disabled={liked || liking}
|
||||
className={`text-[11px] transition-colors ${
|
||||
liked ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
} disabled:cursor-default`}
|
||||
>
|
||||
{liked ? "♥" : "♡"}{reactionCount !== null && reactionCount > 0 ? ` ${reactionCount}` : liked ? " liked" : " like"}
|
||||
</button>
|
||||
{!liked && !liking && (
|
||||
<button
|
||||
onClick={() => setShowEmojiPicker((v) => !v)}
|
||||
className="text-[10px] text-text-dim hover:text-accent transition-colors opacity-0 group-hover/card:opacity-100"
|
||||
title="React with emoji"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
{showEmojiPicker && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-[9]" onClick={() => setShowEmojiPicker(false)} />
|
||||
<div className="absolute bottom-6 left-0 bg-bg-raised border border-border shadow-lg z-10 flex gap-0.5 px-1.5 py-1">
|
||||
{REACTION_EMOJIS.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
onClick={() => handleReact(emoji)}
|
||||
className="text-[16px] hover:scale-125 transition-transform px-0.5"
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleRepost}
|
||||
disabled={reposting || reposted}
|
||||
className={`text-[11px] transition-colors disabled:cursor-default ${
|
||||
reposted ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
}`}
|
||||
>
|
||||
{reposted ? "reposted ✓" : reposting ? "…" : "repost"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowQuote(true)}
|
||||
className="text-[11px] text-text-dim hover:text-text transition-colors"
|
||||
>
|
||||
quote
|
||||
</button>
|
||||
{(profile?.lud16 || profile?.lud06) && (
|
||||
<button
|
||||
onClick={() => setShowZap(true)}
|
||||
className="text-[11px] text-text-dim hover:text-zap transition-colors"
|
||||
>
|
||||
{zapData && zapData.totalSats > 0
|
||||
? `⚡ ${zapData.totalSats.toLocaleString()} sats`
|
||||
: "⚡ zap"}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => isBookmarked ? removeBookmark(event.id!) : addBookmark(event.id!)}
|
||||
className={`text-[11px] transition-colors ${
|
||||
isBookmarked ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
}`}
|
||||
>
|
||||
{isBookmarked ? "▪ saved" : "▫ save"}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className={`text-[11px] transition-colors ${
|
||||
copied ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
{copied ? "copied ✓" : "share"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showZap && (
|
||||
<ZapModal
|
||||
target={{ type: "note", event, recipientPubkey: event.pubkey }}
|
||||
recipientName={name}
|
||||
onClose={() => setShowZap(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showQuote && (
|
||||
<QuoteModal
|
||||
event={event}
|
||||
authorName={name}
|
||||
authorAvatar={avatar}
|
||||
onClose={() => setShowQuote(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoggedOutStats({ event }: { event: NDKEvent }) {
|
||||
const [reactionCount] = useReactionCount(event.id);
|
||||
const [replyCount] = useReplyCount(event.id);
|
||||
const zapData = useZapCount(event.id);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleShare = async () => {
|
||||
const nevent = nip19.neventEncode({ id: event.id!, author: event.pubkey });
|
||||
await navigator.clipboard.writeText("nostr:" + nevent);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 mt-1.5">
|
||||
{replyCount !== null && replyCount > 0 && (
|
||||
<span className="text-text-dim text-[11px]">↩ {replyCount}</span>
|
||||
)}
|
||||
{reactionCount !== null && reactionCount > 0 && (
|
||||
<span className="text-text-dim text-[11px]">♥ {reactionCount}</span>
|
||||
)}
|
||||
{zapData !== null && zapData.totalSats > 0 && (
|
||||
<span className="text-zap text-[11px]">⚡ {zapData.totalSats.toLocaleString()} sats</span>
|
||||
)}
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className={`text-[11px] transition-colors ${
|
||||
copied ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
{copied ? "copied ✓" : "share"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,20 +2,14 @@ import { useState, useRef, useEffect } from "react";
|
||||
import { NDKEvent } from "@nostr-dev-kit/ndk";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { useNip05Verified } from "../../hooks/useNip05Verified";
|
||||
import { useReactionCount } from "../../hooks/useReactionCount";
|
||||
import { useReplyCount } from "../../hooks/useReplyCount";
|
||||
import { useZapCount } from "../../hooks/useZapCount";
|
||||
import { useUserStore } from "../../stores/user";
|
||||
import { useMuteStore } from "../../stores/mute";
|
||||
import { useBookmarkStore } from "../../stores/bookmark";
|
||||
import { useUIStore } from "../../stores/ui";
|
||||
import { timeAgo, shortenPubkey } from "../../lib/utils";
|
||||
import { nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { publishReaction, publishReply, publishRepost, getNDK, fetchNoteById } from "../../lib/nostr";
|
||||
import { getNDK, fetchNoteById } from "../../lib/nostr";
|
||||
import { NoteContent } from "./NoteContent";
|
||||
import { ZapModal } from "../zap/ZapModal";
|
||||
import { QuoteModal } from "./QuoteModal";
|
||||
import { EmojiPicker } from "../shared/EmojiPicker";
|
||||
import { NoteActions, LoggedOutStats } from "./NoteActions";
|
||||
import { InlineReplyBox } from "./InlineReplyBox";
|
||||
|
||||
interface NoteCardProps {
|
||||
event: NDKEvent;
|
||||
@@ -47,8 +41,6 @@ export function NoteCard({ event, focused }: NoteCardProps) {
|
||||
const { loggedIn, pubkey: ownPubkey, follows, follow, unfollow } = useUserStore();
|
||||
const { mutedPubkeys, mute, unmute } = useMuteStore();
|
||||
const isMuted = mutedPubkeys.includes(event.pubkey);
|
||||
const { bookmarkedIds, addBookmark, removeBookmark } = useBookmarkStore();
|
||||
const isBookmarked = bookmarkedIds.includes(event.id!);
|
||||
const { openProfile, openThread, currentView } = useUIStore();
|
||||
|
||||
const parentEventId = getParentEventId(event);
|
||||
@@ -58,93 +50,9 @@ export function NoteCard({ event, focused }: NoteCardProps) {
|
||||
useEffect(() => {
|
||||
if (focused) cardRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||
}, [focused]);
|
||||
const likedKey = "wrystr_liked";
|
||||
const getLiked = () => {
|
||||
try { return new Set<string>(JSON.parse(localStorage.getItem(likedKey) || "[]")); }
|
||||
catch { return new Set<string>(); }
|
||||
};
|
||||
const [liked, setLiked] = useState(() => getLiked().has(event.id));
|
||||
const [liking, setLiking] = useState(false);
|
||||
const [reactionCount, adjustReactionCount] = useReactionCount(event.id);
|
||||
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
|
||||
const [replyCount, adjustReplyCount] = useReplyCount(event.id);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const zapData = useZapCount(event.id);
|
||||
const [showReply, setShowReply] = useState(false);
|
||||
const [replyText, setReplyText] = useState("");
|
||||
const [replying, setReplying] = useState(false);
|
||||
const [replyError, setReplyError] = useState<string | null>(null);
|
||||
const [replySent, setReplySent] = useState(false);
|
||||
const replyRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [showZap, setShowZap] = useState(false);
|
||||
const [showQuote, setShowQuote] = useState(false);
|
||||
const [showReplyEmoji, setShowReplyEmoji] = useState(false);
|
||||
const [reposting, setReposting] = useState(false);
|
||||
const [reposted, setReposted] = useState(false);
|
||||
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
const REACTION_EMOJIS = ["❤️", "🤙", "🔥", "😂", "🫡", "👀", "⚡"];
|
||||
|
||||
const handleReact = async (emoji?: string) => {
|
||||
if (!loggedIn || liked || liking) return;
|
||||
setLiking(true);
|
||||
setShowEmojiPicker(false);
|
||||
try {
|
||||
await publishReaction(event.id, event.pubkey, emoji || "+");
|
||||
const likedSet = getLiked();
|
||||
likedSet.add(event.id);
|
||||
localStorage.setItem(likedKey, JSON.stringify(Array.from(likedSet)));
|
||||
setLiked(true);
|
||||
adjustReactionCount(1);
|
||||
} finally {
|
||||
setLiking(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReply = () => {
|
||||
setShowReply((v) => !v);
|
||||
if (!showReply) setTimeout(() => replyRef.current?.focus(), 50);
|
||||
};
|
||||
|
||||
const handleReplySubmit = async () => {
|
||||
if (!replyText.trim() || replying) return;
|
||||
setReplying(true);
|
||||
setReplyError(null);
|
||||
try {
|
||||
await publishReply(replyText.trim(), { id: event.id, pubkey: event.pubkey });
|
||||
setReplyText("");
|
||||
setReplySent(true);
|
||||
adjustReplyCount(1);
|
||||
setTimeout(() => { setShowReply(false); setReplySent(false); }, 1500);
|
||||
} catch (err) {
|
||||
setReplyError(`Failed: ${err}`);
|
||||
} finally {
|
||||
setReplying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReplyKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) handleReplySubmit();
|
||||
if (e.key === "Escape") setShowReply(false);
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
const nevent = nip19.neventEncode({ id: event.id!, author: event.pubkey });
|
||||
await navigator.clipboard.writeText("nostr:" + nevent);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const handleRepost = async () => {
|
||||
if (reposting || reposted) return;
|
||||
setReposting(true);
|
||||
try {
|
||||
await publishRepost(event);
|
||||
setReposted(true);
|
||||
} finally {
|
||||
setReposting(false);
|
||||
}
|
||||
};
|
||||
const [showReply, setShowReply] = useState(false);
|
||||
|
||||
return (
|
||||
<article
|
||||
@@ -250,185 +158,18 @@ export function NoteCard({ event, focused }: NoteCardProps) {
|
||||
|
||||
{/* Actions */}
|
||||
{loggedIn && !!getNDK().signer && (
|
||||
<div className="flex items-center gap-4 mt-2">
|
||||
<button
|
||||
onClick={handleReply}
|
||||
className={`text-[11px] transition-colors ${
|
||||
showReply ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
reply{replyCount !== null && replyCount > 0 ? ` ${replyCount}` : ""}
|
||||
</button>
|
||||
<div className="relative flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => handleReact("❤️")}
|
||||
disabled={liked || liking}
|
||||
className={`text-[11px] transition-colors ${
|
||||
liked ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
} disabled:cursor-default`}
|
||||
>
|
||||
{liked ? "♥" : "♡"}{reactionCount !== null && reactionCount > 0 ? ` ${reactionCount}` : liked ? " liked" : " like"}
|
||||
</button>
|
||||
{!liked && !liking && (
|
||||
<button
|
||||
onClick={() => setShowEmojiPicker((v) => !v)}
|
||||
className="text-[10px] text-text-dim hover:text-accent transition-colors opacity-0 group-hover/card:opacity-100"
|
||||
title="React with emoji"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
{showEmojiPicker && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-[9]" onClick={() => setShowEmojiPicker(false)} />
|
||||
<div className="absolute bottom-6 left-0 bg-bg-raised border border-border shadow-lg z-10 flex gap-0.5 px-1.5 py-1">
|
||||
{REACTION_EMOJIS.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
onClick={() => handleReact(emoji)}
|
||||
className="text-[16px] hover:scale-125 transition-transform px-0.5"
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleRepost}
|
||||
disabled={reposting || reposted}
|
||||
className={`text-[11px] transition-colors disabled:cursor-default ${
|
||||
reposted ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
}`}
|
||||
>
|
||||
{reposted ? "reposted ✓" : reposting ? "…" : "repost"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowQuote(true)}
|
||||
className="text-[11px] text-text-dim hover:text-text transition-colors"
|
||||
>
|
||||
quote
|
||||
</button>
|
||||
{(profile?.lud16 || profile?.lud06) && (
|
||||
<button
|
||||
onClick={() => setShowZap(true)}
|
||||
className="text-[11px] text-text-dim hover:text-zap transition-colors"
|
||||
>
|
||||
{zapData && zapData.totalSats > 0
|
||||
? `⚡ ${zapData.totalSats.toLocaleString()} sats`
|
||||
: "⚡ zap"}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => isBookmarked ? removeBookmark(event.id!) : addBookmark(event.id!)}
|
||||
className={`text-[11px] transition-colors ${
|
||||
isBookmarked ? "text-accent" : "text-text-dim hover:text-accent"
|
||||
}`}
|
||||
>
|
||||
{isBookmarked ? "▪ saved" : "▫ save"}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className={`text-[11px] transition-colors ${
|
||||
copied ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
{copied ? "copied ✓" : "share"}
|
||||
</button>
|
||||
</div>
|
||||
<NoteActions
|
||||
event={event}
|
||||
onReplyToggle={() => setShowReply((v) => !v)}
|
||||
showReply={showReply}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Stats visible when logged out */}
|
||||
{!loggedIn && (
|
||||
<div className="flex items-center gap-3 mt-1.5">
|
||||
{replyCount !== null && replyCount > 0 && (
|
||||
<span className="text-text-dim text-[11px]">↩ {replyCount}</span>
|
||||
)}
|
||||
{reactionCount !== null && reactionCount > 0 && (
|
||||
<span className="text-text-dim text-[11px]">♥ {reactionCount}</span>
|
||||
)}
|
||||
{zapData !== null && zapData.totalSats > 0 && (
|
||||
<span className="text-zap text-[11px]">⚡ {zapData.totalSats.toLocaleString()} sats</span>
|
||||
)}
|
||||
<button
|
||||
onClick={handleShare}
|
||||
className={`text-[11px] transition-colors ${
|
||||
copied ? "text-accent" : "text-text-dim hover:text-text"
|
||||
}`}
|
||||
>
|
||||
{copied ? "copied ✓" : "share"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showZap && (
|
||||
<ZapModal
|
||||
target={{ type: "note", event, recipientPubkey: event.pubkey }}
|
||||
recipientName={name}
|
||||
onClose={() => setShowZap(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showQuote && (
|
||||
<QuoteModal
|
||||
event={event}
|
||||
authorName={name}
|
||||
authorAvatar={avatar}
|
||||
onClose={() => setShowQuote(false)}
|
||||
/>
|
||||
)}
|
||||
{!loggedIn && <LoggedOutStats event={event} />}
|
||||
|
||||
{/* Inline reply box */}
|
||||
{showReply && (
|
||||
<div className="mt-2 border-l-2 border-border pl-3">
|
||||
<textarea
|
||||
ref={replyRef}
|
||||
value={replyText}
|
||||
onChange={(e) => setReplyText(e.target.value)}
|
||||
onKeyDown={handleReplyKeyDown}
|
||||
placeholder={`Reply to ${name}…`}
|
||||
rows={2}
|
||||
className="w-full bg-transparent text-text text-[12px] placeholder:text-text-dim resize-none focus:outline-none"
|
||||
/>
|
||||
{replyError && <p className="text-danger text-[10px] mb-1">{replyError}</p>}
|
||||
<div className="flex items-center justify-end gap-2 mt-1">
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowReplyEmoji((v) => !v)}
|
||||
title="Insert emoji"
|
||||
className="text-text-dim hover:text-text text-[12px] transition-colors"
|
||||
>
|
||||
☺
|
||||
</button>
|
||||
{showReplyEmoji && (
|
||||
<EmojiPicker
|
||||
onSelect={(emoji) => {
|
||||
const ta = replyRef.current;
|
||||
if (ta) {
|
||||
const start = ta.selectionStart ?? replyText.length;
|
||||
const end = ta.selectionEnd ?? replyText.length;
|
||||
setReplyText(replyText.slice(0, start) + emoji + replyText.slice(end));
|
||||
setTimeout(() => { ta.selectionStart = ta.selectionEnd = start + emoji.length; ta.focus(); }, 0);
|
||||
} else {
|
||||
setReplyText((t) => t + emoji);
|
||||
}
|
||||
}}
|
||||
onClose={() => setShowReplyEmoji(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-text-dim text-[10px]">Ctrl+Enter</span>
|
||||
<button
|
||||
onClick={handleReplySubmit}
|
||||
disabled={!replyText.trim() || replying}
|
||||
className="px-2 py-0.5 text-[10px] bg-accent hover:bg-accent-hover text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
{replySent ? "replied ✓" : replying ? "posting…" : "reply"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{showReply && <InlineReplyBox event={event} name={name} />}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { ReactNode, useEffect, useState } from "react";
|
||||
import { NDKEvent, nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { NDKEvent } from "@nostr-dev-kit/ndk";
|
||||
import { useUIStore } from "../../stores/ui";
|
||||
import { fetchNoteById } from "../../lib/nostr";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { shortenPubkey } from "../../lib/utils";
|
||||
import { ImageLightbox } from "../shared/ImageLightbox";
|
||||
import { parseContent } from "../../lib/parsing";
|
||||
import { renderTextSegments } from "./TextSegments";
|
||||
import { VideoBlock, AudioBlock, YouTubeCard, VimeoCard, SpotifyCard, TidalCard } from "./MediaCards";
|
||||
|
||||
function ImageGrid({ images, onImageClick }: { images: string[]; onImageClick: (index: number) => void }) {
|
||||
const count = images.length;
|
||||
@@ -107,45 +109,6 @@ function ImageGrid({ images, onImageClick }: { images: string[]; onImageClick: (
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Returns true if we handled the URL internally (njump.me interception).
|
||||
function tryHandleUrlInternally(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.hostname === "njump.me") {
|
||||
const entity = u.pathname.replace(/^\//, "");
|
||||
if (entity) return tryOpenNostrEntity(entity);
|
||||
}
|
||||
} catch { /* not a valid URL */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
// Decodes a NIP-19 bech32 string and navigates internally where possible.
|
||||
// Returns true if handled, false if the caller should fall back to a browser open.
|
||||
function tryOpenNostrEntity(raw: string): boolean {
|
||||
try {
|
||||
const decoded = nip19.decode(raw);
|
||||
const { openProfile, openArticle } = useUIStore.getState();
|
||||
if (decoded.type === "npub") {
|
||||
openProfile(decoded.data as string);
|
||||
return true;
|
||||
}
|
||||
if (decoded.type === "nprofile") {
|
||||
openProfile((decoded.data as { pubkey: string }).pubkey);
|
||||
return true;
|
||||
}
|
||||
if (decoded.type === "naddr") {
|
||||
const { kind } = decoded.data as { kind: number; pubkey: string; identifier: string };
|
||||
if (kind === 30023) {
|
||||
openArticle(raw);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// note / nevent / other naddr kinds — fall through to njump.me
|
||||
} catch { /* invalid entity */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
function QuotePreview({ eventId }: { eventId: string }) {
|
||||
const [event, setEvent] = useState<NDKEvent | null>(null);
|
||||
const { openThread, currentView } = useUIStore();
|
||||
@@ -178,13 +141,6 @@ function QuotePreview({ eventId }: { eventId: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function MentionName({ pubkey, fallback }: { pubkey?: string; fallback: string }) {
|
||||
const profile = useProfile(pubkey ?? "");
|
||||
if (!pubkey) return <>{fallback}</>;
|
||||
const name = profile?.displayName || profile?.name;
|
||||
return <>{name || fallback}</>;
|
||||
}
|
||||
|
||||
interface NoteContentProps {
|
||||
content: string;
|
||||
/** Render only inline text (no media blocks). Used inside the clickable area. */
|
||||
@@ -208,60 +164,11 @@ export function NoteContent({ content, inline, mediaOnly }: NoteContentProps) {
|
||||
|
||||
// --- Inline text + images (safe inside clickable wrapper) ---
|
||||
if (inline) {
|
||||
const inlineElements: ReactNode[] = [];
|
||||
segments.forEach((seg, i) => {
|
||||
switch (seg.type) {
|
||||
case "text":
|
||||
inlineElements.push(<span key={i}>{seg.value}</span>);
|
||||
break;
|
||||
case "link":
|
||||
inlineElements.push(
|
||||
<a
|
||||
key={i}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-accent hover:text-accent-hover underline underline-offset-2 decoration-accent/40"
|
||||
onClick={(e) => {
|
||||
if (tryHandleUrlInternally(seg.value)) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
{seg.display}
|
||||
</a>
|
||||
);
|
||||
break;
|
||||
case "mention":
|
||||
inlineElements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent cursor-pointer hover:text-accent-hover"
|
||||
onClick={(e) => { e.stopPropagation(); tryOpenNostrEntity(seg.value); }}
|
||||
>
|
||||
@<MentionName pubkey={seg.mentionPubkey} fallback={seg.display ?? seg.value.slice(0, 12) + "…"} />
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
case "hashtag":
|
||||
inlineElements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent/80 cursor-pointer hover:text-accent"
|
||||
onClick={(e) => { e.stopPropagation(); openHashtag(seg.value); }}
|
||||
>
|
||||
{seg.display}
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
return (
|
||||
<div>
|
||||
<div className="note-content text-text text-[13px] break-words whitespace-pre-wrap leading-relaxed">
|
||||
{inlineElements}
|
||||
{renderTextSegments(segments, openHashtag, { resolveMentions: true })}
|
||||
</div>
|
||||
{/* Images stay inside the clickable area (they have their own stopPropagation) */}
|
||||
<ImageGrid images={images} onImageClick={setLightboxIndex} />
|
||||
{lightboxIndex !== null && (
|
||||
<ImageLightbox
|
||||
@@ -283,179 +190,22 @@ export function NoteContent({ content, inline, mediaOnly }: NoteContentProps) {
|
||||
|
||||
return (
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
{/* Videos */}
|
||||
{videos.length > 0 && (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{videos.map((src, i) => (
|
||||
<video
|
||||
key={i}
|
||||
src={src}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
className="max-w-full max-h-80 rounded-sm bg-bg-raised border border-border"
|
||||
onError={(e) => { (e.target as HTMLVideoElement).style.display = "none"; }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Audio */}
|
||||
{audios.length > 0 && (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{audios.map((src, i) => {
|
||||
const filename = src.split("/").pop()?.split("?")[0] ?? src;
|
||||
return (
|
||||
<div key={i} className="rounded-sm bg-bg-raised border border-border p-2">
|
||||
<div className="text-[11px] text-text-muted mb-1 truncate">{filename}</div>
|
||||
<audio controls preload="metadata" className="w-full h-8" src={src} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* YouTube — open in browser (WebKitGTK can't play YouTube iframes) */}
|
||||
{youtubes.map((seg, i) => (
|
||||
<a
|
||||
key={`yt-${i}`}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<img
|
||||
src={`https://img.youtube.com/vi/${seg.mediaId}/hqdefault.jpg`}
|
||||
alt=""
|
||||
className="w-28 h-16 rounded-sm object-cover shrink-0"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">YouTube</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Vimeo — open in browser */}
|
||||
{vimeos.map((seg, i) => (
|
||||
<a
|
||||
key={`vim-${i}`}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-black/40 flex items-center justify-center shrink-0">
|
||||
<svg width="14" height="14" viewBox="0 0 20 20" fill="white"><polygon points="6,3 17,10 6,17" /></svg>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Vimeo</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Spotify — open in browser/app */}
|
||||
{spotifys.map((seg, i) => (
|
||||
<a
|
||||
key={`sp-${i}`}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-[#1DB954]/20 flex items-center justify-center shrink-0">
|
||||
<span className="text-[#1DB954] text-lg font-bold">S</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Spotify · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Tidal — open in browser/app */}
|
||||
{tidals.map((seg, i) => (
|
||||
<a
|
||||
key={`td-${i}`}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer"
|
||||
>
|
||||
<div className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center shrink-0">
|
||||
<span className="text-white text-lg font-bold">T</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Tidal · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Quoted notes */}
|
||||
{quoteIds.map((id) => (
|
||||
<QuotePreview key={id} eventId={id} />
|
||||
))}
|
||||
<VideoBlock sources={videos} />
|
||||
<AudioBlock sources={audios} />
|
||||
{youtubes.map((seg, i) => <YouTubeCard key={`yt-${i}`} seg={seg} />)}
|
||||
{vimeos.map((seg, i) => <VimeoCard key={`vim-${i}`} seg={seg} />)}
|
||||
{spotifys.map((seg, i) => <SpotifyCard key={`sp-${i}`} seg={seg} />)}
|
||||
{tidals.map((seg, i) => <TidalCard key={`td-${i}`} seg={seg} />)}
|
||||
{quoteIds.map((id) => <QuotePreview key={id} eventId={id} />)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Default: full render (used in ThreadView, SearchView, etc.) ---
|
||||
const inlineElements: ReactNode[] = [];
|
||||
segments.forEach((seg, i) => {
|
||||
switch (seg.type) {
|
||||
case "text":
|
||||
inlineElements.push(<span key={i}>{seg.value}</span>);
|
||||
break;
|
||||
case "link":
|
||||
inlineElements.push(
|
||||
<a
|
||||
key={i}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-accent hover:text-accent-hover underline underline-offset-2 decoration-accent/40"
|
||||
onClick={(e) => {
|
||||
if (tryHandleUrlInternally(seg.value)) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
{seg.display}
|
||||
</a>
|
||||
);
|
||||
break;
|
||||
case "mention":
|
||||
inlineElements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent cursor-pointer hover:text-accent-hover"
|
||||
onClick={(e) => { e.stopPropagation(); tryOpenNostrEntity(seg.value); }}
|
||||
>
|
||||
@{seg.display}
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
case "hashtag":
|
||||
inlineElements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent/80 cursor-pointer hover:text-accent"
|
||||
onClick={(e) => { e.stopPropagation(); openHashtag(seg.value); }}
|
||||
>
|
||||
{seg.display}
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="note-content text-text text-[13px] break-words whitespace-pre-wrap leading-relaxed">
|
||||
{inlineElements}
|
||||
{renderTextSegments(segments, openHashtag)}
|
||||
</div>
|
||||
|
||||
<ImageGrid images={images} onImageClick={setLightboxIndex} />
|
||||
@@ -469,90 +219,13 @@ export function NoteContent({ content, inline, mediaOnly }: NoteContentProps) {
|
||||
/>
|
||||
)}
|
||||
|
||||
{videos.length > 0 && (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{videos.map((src, i) => (
|
||||
<video
|
||||
key={i}
|
||||
src={src}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
className="max-w-full max-h-80 rounded-sm bg-bg-raised border border-border"
|
||||
onError={(e) => { (e.target as HTMLVideoElement).style.display = "none"; }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{audios.length > 0 && (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
{audios.map((src, i) => {
|
||||
const filename = src.split("/").pop()?.split("?")[0] ?? src;
|
||||
return (
|
||||
<div key={i} className="rounded-sm bg-bg-raised border border-border p-2">
|
||||
<div className="text-[11px] text-text-muted mb-1 truncate">{filename}</div>
|
||||
<audio controls preload="metadata" className="w-full h-8" src={src} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{youtubes.map((seg, i) => (
|
||||
<a key={`yt-${i}`} href={seg.value} target="_blank" rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer">
|
||||
<img src={`https://img.youtube.com/vi/${seg.mediaId}/hqdefault.jpg`} alt=""
|
||||
className="w-28 h-16 rounded-sm object-cover shrink-0" loading="lazy" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">YouTube</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{vimeos.map((seg, i) => (
|
||||
<a key={`vim-${i}`} href={seg.value} target="_blank" rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer">
|
||||
<div className="w-10 h-10 rounded-full bg-black/40 flex items-center justify-center shrink-0">
|
||||
<svg width="14" height="14" viewBox="0 0 20 20" fill="white"><polygon points="6,3 17,10 6,17" /></svg>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Vimeo</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{spotifys.map((seg, i) => (
|
||||
<a key={`sp-${i}`} href={seg.value} target="_blank" rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer">
|
||||
<div className="w-10 h-10 rounded-full bg-[#1DB954]/20 flex items-center justify-center shrink-0">
|
||||
<span className="text-[#1DB954] text-lg font-bold">S</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Spotify · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{tidals.map((seg, i) => (
|
||||
<a key={`td-${i}`} href={seg.value} target="_blank" rel="noopener noreferrer"
|
||||
className="mt-2 flex items-center gap-3 rounded-sm bg-bg-raised border border-border p-3 hover:bg-bg-hover transition-colors cursor-pointer">
|
||||
<div className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center shrink-0">
|
||||
<span className="text-white text-lg font-bold">T</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] text-text-muted">Tidal · {seg.mediaType}</div>
|
||||
<div className="text-[12px] text-accent truncate">{seg.value}</div>
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
|
||||
{quoteIds.map((id) => (
|
||||
<QuotePreview key={id} eventId={id} />
|
||||
))}
|
||||
<VideoBlock sources={videos} />
|
||||
<AudioBlock sources={audios} />
|
||||
{youtubes.map((seg, i) => <YouTubeCard key={`yt-${i}`} seg={seg} />)}
|
||||
{vimeos.map((seg, i) => <VimeoCard key={`vim-${i}`} seg={seg} />)}
|
||||
{spotifys.map((seg, i) => <SpotifyCard key={`sp-${i}`} seg={seg} />)}
|
||||
{tidals.map((seg, i) => <TidalCard key={`td-${i}`} seg={seg} />)}
|
||||
{quoteIds.map((id) => <QuotePreview key={id} eventId={id} />)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
116
src/components/feed/TextSegments.tsx
Normal file
116
src/components/feed/TextSegments.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import { ReactNode } from "react";
|
||||
import { nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { useUIStore } from "../../stores/ui";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { ContentSegment } from "../../lib/parsing";
|
||||
|
||||
// Returns true if we handled the URL internally (njump.me interception).
|
||||
export function tryHandleUrlInternally(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.hostname === "njump.me") {
|
||||
const entity = u.pathname.replace(/^\//, "");
|
||||
if (entity) return tryOpenNostrEntity(entity);
|
||||
}
|
||||
} catch { /* not a valid URL */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
// Decodes a NIP-19 bech32 string and navigates internally where possible.
|
||||
// Returns true if handled, false if the caller should fall back to a browser open.
|
||||
export function tryOpenNostrEntity(raw: string): boolean {
|
||||
try {
|
||||
const decoded = nip19.decode(raw);
|
||||
const { openProfile, openArticle } = useUIStore.getState();
|
||||
if (decoded.type === "npub") {
|
||||
openProfile(decoded.data as string);
|
||||
return true;
|
||||
}
|
||||
if (decoded.type === "nprofile") {
|
||||
openProfile((decoded.data as { pubkey: string }).pubkey);
|
||||
return true;
|
||||
}
|
||||
if (decoded.type === "naddr") {
|
||||
const { kind } = decoded.data as { kind: number; pubkey: string; identifier: string };
|
||||
if (kind === 30023) {
|
||||
openArticle(raw);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// note / nevent / other naddr kinds — fall through to njump.me
|
||||
} catch { /* invalid entity */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
export function MentionName({ pubkey, fallback }: { pubkey?: string; fallback: string }) {
|
||||
const profile = useProfile(pubkey ?? "");
|
||||
if (!pubkey) return <>{fallback}</>;
|
||||
const name = profile?.displayName || profile?.name;
|
||||
return <>{name || fallback}</>;
|
||||
}
|
||||
|
||||
interface RenderTextSegmentsOptions {
|
||||
/** If true, use MentionName component for mentions (inline mode). If false, use seg.display directly. */
|
||||
resolveMentions?: boolean;
|
||||
}
|
||||
|
||||
export function renderTextSegments(
|
||||
segments: ContentSegment[],
|
||||
openHashtag: (tag: string) => void,
|
||||
options: RenderTextSegmentsOptions = {}
|
||||
): ReactNode[] {
|
||||
const { resolveMentions = false } = options;
|
||||
const elements: ReactNode[] = [];
|
||||
|
||||
segments.forEach((seg, i) => {
|
||||
switch (seg.type) {
|
||||
case "text":
|
||||
elements.push(<span key={i}>{seg.value}</span>);
|
||||
break;
|
||||
case "link":
|
||||
elements.push(
|
||||
<a
|
||||
key={i}
|
||||
href={seg.value}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-accent hover:text-accent-hover underline underline-offset-2 decoration-accent/40"
|
||||
onClick={(e) => {
|
||||
if (tryHandleUrlInternally(seg.value)) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
{seg.display}
|
||||
</a>
|
||||
);
|
||||
break;
|
||||
case "mention":
|
||||
elements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent cursor-pointer hover:text-accent-hover"
|
||||
onClick={(e) => { e.stopPropagation(); tryOpenNostrEntity(seg.value); }}
|
||||
>
|
||||
@{resolveMentions
|
||||
? <MentionName pubkey={seg.mentionPubkey} fallback={seg.display ?? seg.value.slice(0, 12) + "…"} />
|
||||
: seg.display}
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
case "hashtag":
|
||||
elements.push(
|
||||
<span
|
||||
key={i}
|
||||
className="text-accent/80 cursor-pointer hover:text-accent"
|
||||
onClick={(e) => { e.stopPropagation(); openHashtag(seg.value); }}
|
||||
>
|
||||
{seg.display}
|
||||
</span>
|
||||
);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return elements;
|
||||
}
|
||||
96
src/components/profile/EditProfileForm.tsx
Normal file
96
src/components/profile/EditProfileForm.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { useState } from "react";
|
||||
import { useUserStore } from "../../stores/user";
|
||||
import { invalidateProfileCache } from "../../hooks/useProfile";
|
||||
import { publishProfile } from "../../lib/nostr";
|
||||
import { ImageField } from "./ImageField";
|
||||
import { Nip05Field } from "./Nip05Field";
|
||||
|
||||
export function EditProfileForm({ pubkey, onSaved }: { pubkey: string; onSaved: () => void }) {
|
||||
const { profile, fetchOwnProfile } = useUserStore();
|
||||
const [name, setName] = useState(profile?.name || "");
|
||||
const [displayName, setDisplayName] = useState(profile?.displayName || "");
|
||||
const [about, setAbout] = useState(profile?.about || "");
|
||||
const [picture, setPicture] = useState(profile?.picture || "");
|
||||
const [banner, setBanner] = useState(profile?.banner || "");
|
||||
const [website, setWebsite] = useState(profile?.website || "");
|
||||
const [nip05, setNip05] = useState(profile?.nip05 || "");
|
||||
const [lud16, setLud16] = useState(profile?.lud16 || "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
invalidateProfileCache(pubkey);
|
||||
await publishProfile({
|
||||
name: name.trim() || undefined,
|
||||
display_name: displayName.trim() || undefined,
|
||||
about: about.trim() || undefined,
|
||||
picture: picture.trim() || undefined,
|
||||
banner: banner.trim() || undefined,
|
||||
website: website.trim() || undefined,
|
||||
nip05: nip05.trim() || undefined,
|
||||
lud16: lud16.trim() || undefined,
|
||||
});
|
||||
await fetchOwnProfile();
|
||||
setSaved(true);
|
||||
setTimeout(onSaved, 1000);
|
||||
} catch (err) {
|
||||
setError(`Failed to save: ${err}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const field = (label: string, value: string, onChange: (v: string) => void, placeholder = "") => (
|
||||
<div>
|
||||
<label className="text-text-dim text-[10px] block mb-1">{label}</label>
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4 border-b border-border">
|
||||
<div className="grid grid-cols-2 gap-3 mb-3">
|
||||
{field("Display name", displayName, setDisplayName, "Square that Circle")}
|
||||
{field("Username", name, setName, "squarethecircle")}
|
||||
<Nip05Field value={nip05} onChange={setNip05} pubkey={pubkey} />
|
||||
{field("Lightning address (lud16)", lud16, setLud16, "you@walletofsatoshi.com")}
|
||||
{field("Website", website, setWebsite, "https://…")}
|
||||
<ImageField label="Profile picture" value={picture} onChange={setPicture} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="text-text-dim text-[10px] block mb-1">Bio</label>
|
||||
<textarea
|
||||
value={about}
|
||||
onChange={(e) => setAbout(e.target.value)}
|
||||
placeholder="Tell people about yourself…"
|
||||
rows={3}
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] resize-none focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<ImageField label="Banner image" value={banner} onChange={setBanner} />
|
||||
</div>
|
||||
{error && <p className="text-danger text-[11px] mb-2">{error}</p>}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving || saved}
|
||||
className="px-4 py-1.5 text-[11px] bg-accent hover:bg-accent-hover text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saved ? "saved ✓" : saving ? "saving…" : "save profile"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
50
src/components/profile/ImageField.tsx
Normal file
50
src/components/profile/ImageField.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { uploadImage } from "../../lib/upload";
|
||||
|
||||
export function ImageField({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
setUploadError(null);
|
||||
try {
|
||||
const url = await uploadImage(file);
|
||||
onChange(url);
|
||||
} catch (err) {
|
||||
setUploadError(String(err));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="text-text-dim text-[10px] block mb-1">{label}</label>
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="https://… or click upload →"
|
||||
className="flex-1 bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="px-2 py-1.5 text-[10px] border border-border text-text-dim hover:text-accent hover:border-accent/40 transition-colors disabled:opacity-40 disabled:cursor-not-allowed shrink-0"
|
||||
title="Upload from your computer"
|
||||
>
|
||||
{uploading ? "uploading…" : "upload"}
|
||||
</button>
|
||||
</div>
|
||||
{uploadError && <p className="text-danger text-[10px] mt-1">{uploadError}</p>}
|
||||
<input ref={fileRef} type="file" accept="image/*" onChange={handleFile} className="hidden" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
src/components/profile/Nip05Field.tsx
Normal file
62
src/components/profile/Nip05Field.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Nip05Status = "idle" | "checking" | "valid" | "mismatch" | "notfound";
|
||||
|
||||
export function Nip05Field({ value, onChange, pubkey }: { value: string; onChange: (v: string) => void; pubkey: string }) {
|
||||
const [status, setStatus] = useState<Nip05Status>("idle");
|
||||
|
||||
useEffect(() => {
|
||||
if (!value.includes("@")) { setStatus("idle"); return; }
|
||||
setStatus("checking");
|
||||
const t = setTimeout(async () => {
|
||||
const [name, domain] = value.trim().split("@");
|
||||
if (!name || !domain) { setStatus("notfound"); return; }
|
||||
try {
|
||||
const resp = await fetch(`https://${domain}/.well-known/nostr.json?name=${encodeURIComponent(name)}`);
|
||||
const data = await resp.json();
|
||||
const resolved = data.names?.[name];
|
||||
if (!resolved) setStatus("notfound");
|
||||
else if (resolved === pubkey) setStatus("valid");
|
||||
else setStatus("mismatch");
|
||||
} catch {
|
||||
setStatus("notfound");
|
||||
}
|
||||
}, 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, pubkey]);
|
||||
|
||||
const badge = {
|
||||
idle: null,
|
||||
checking: <span className="text-text-dim text-[10px]">checking…</span>,
|
||||
valid: <span className="text-success text-[10px]">✓ verified</span>,
|
||||
mismatch: <span className="text-danger text-[10px]">✗ pubkey mismatch</span>,
|
||||
notfound: <span className="text-danger text-[10px]">✗ not found</span>,
|
||||
}[status];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-baseline gap-2 mb-1">
|
||||
<label className="text-text-dim text-[10px]">NIP-05 verified name</label>
|
||||
{badge}
|
||||
</div>
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="you@domain.com"
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
<p className="text-text-dim text-[10px] mt-1">
|
||||
Proves your identity via a domain you control.{" "}
|
||||
<a
|
||||
href="https://nostr.how/en/guides/get-verified"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-accent hover:text-accent-hover transition-colors"
|
||||
>
|
||||
How to get verified ↗
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
130
src/components/profile/ProfileMediaGallery.tsx
Normal file
130
src/components/profile/ProfileMediaGallery.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { useState } from "react";
|
||||
import { NDKEvent } from "@nostr-dev-kit/ndk";
|
||||
import { useUIStore } from "../../stores/ui";
|
||||
import { parseContent } from "../../lib/parsing";
|
||||
import { ImageLightbox } from "../shared/ImageLightbox";
|
||||
|
||||
const MEDIA_SEGMENT_TYPES = new Set(["image", "video", "audio", "youtube", "vimeo"]);
|
||||
|
||||
interface MediaItem {
|
||||
type: "image" | "video" | "audio";
|
||||
url: string;
|
||||
thumbnailId?: string;
|
||||
noteId: string;
|
||||
}
|
||||
|
||||
function extractMediaItems(notes: NDKEvent[]): MediaItem[] {
|
||||
const items: MediaItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const note of notes) {
|
||||
const segments = parseContent(note.content);
|
||||
for (const seg of segments) {
|
||||
if (!MEDIA_SEGMENT_TYPES.has(seg.type)) continue;
|
||||
if (seen.has(seg.value)) continue;
|
||||
seen.add(seg.value);
|
||||
if (seg.type === "image") {
|
||||
items.push({ type: "image", url: seg.value, noteId: note.id! });
|
||||
} else if (seg.type === "video" || seg.type === "youtube" || seg.type === "vimeo") {
|
||||
items.push({ type: "video", url: seg.value, thumbnailId: seg.mediaId, noteId: note.id! });
|
||||
} else if (seg.type === "audio") {
|
||||
items.push({ type: "audio", url: seg.value, noteId: note.id! });
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function ProfileMediaGallery({ notes, loading }: { notes: NDKEvent[]; loading: boolean }) {
|
||||
const { openThread } = useUIStore();
|
||||
const [lightboxIdx, setLightboxIdx] = useState<number | null>(null);
|
||||
|
||||
if (loading) {
|
||||
return <div className="px-4 py-8 text-text-dim text-[12px] text-center">Loading media…</div>;
|
||||
}
|
||||
|
||||
const items = extractMediaItems(notes);
|
||||
const imageUrls = items.filter((i) => i.type === "image").map((i) => i.url);
|
||||
|
||||
if (items.length === 0) {
|
||||
return <div className="px-4 py-8 text-text-dim text-[12px] text-center">No media found.</div>;
|
||||
}
|
||||
|
||||
const openNote = (noteId: string) => {
|
||||
const note = notes.find((n) => n.id === noteId);
|
||||
if (note) openThread(note, "profile");
|
||||
};
|
||||
|
||||
let imageIndex = 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 xl:grid-cols-3 gap-1 p-2">
|
||||
{items.map((item, idx) => {
|
||||
if (item.type === "image") {
|
||||
const currentImageIdx = imageIndex++;
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={() => setLightboxIdx(currentImageIdx)}
|
||||
>
|
||||
<img
|
||||
src={item.url}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (item.type === "video") {
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity relative flex items-center justify-center"
|
||||
onClick={() => openNote(item.noteId)}
|
||||
>
|
||||
{item.thumbnailId ? (
|
||||
<img
|
||||
src={`https://img.youtube.com/vi/${item.thumbnailId}/mqdefault.jpg`}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full bg-bg-raised" />
|
||||
)}
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<span className="w-10 h-10 rounded-full bg-black/60 flex items-center justify-center text-white text-lg">▶</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// audio
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity flex items-center justify-center"
|
||||
onClick={() => openNote(item.noteId)}
|
||||
>
|
||||
<div className="text-center">
|
||||
<span className="text-3xl text-text-dim">♪</span>
|
||||
<p className="text-text-dim text-[10px] mt-1 px-2 truncate">{item.url.split("/").pop()}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{lightboxIdx !== null && (
|
||||
<ImageLightbox
|
||||
images={imageUrls}
|
||||
index={lightboxIdx}
|
||||
onClose={() => setLightboxIdx(null)}
|
||||
onNavigate={(i) => setLightboxIdx(i)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,218 +1,17 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { NDKEvent } from "@nostr-dev-kit/ndk";
|
||||
import { useUIStore } from "../../stores/ui";
|
||||
import { useUserStore } from "../../stores/user";
|
||||
import { useMuteStore } from "../../stores/mute";
|
||||
import { useProfile, invalidateProfileCache } from "../../hooks/useProfile";
|
||||
import { fetchUserNotesNIP65, fetchAuthorArticles, publishProfile, getNDK } from "../../lib/nostr";
|
||||
import { parseContent } from "../../lib/parsing";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import { fetchUserNotesNIP65, fetchAuthorArticles, getNDK } from "../../lib/nostr";
|
||||
import { shortenPubkey } from "../../lib/utils";
|
||||
import { uploadImage } from "../../lib/upload";
|
||||
import { NoteCard } from "../feed/NoteCard";
|
||||
import { ArticleCard } from "../article/ArticleCard";
|
||||
import { ZapModal } from "../zap/ZapModal";
|
||||
import { ImageLightbox } from "../shared/ImageLightbox";
|
||||
|
||||
// ── Profile helper sub-components ────────────────────────────────────────────
|
||||
|
||||
function ImageField({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
setUploadError(null);
|
||||
try {
|
||||
const url = await uploadImage(file);
|
||||
onChange(url);
|
||||
} catch (err) {
|
||||
setUploadError(String(err));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label className="text-text-dim text-[10px] block mb-1">{label}</label>
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="https://… or click upload →"
|
||||
className="flex-1 bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="px-2 py-1.5 text-[10px] border border-border text-text-dim hover:text-accent hover:border-accent/40 transition-colors disabled:opacity-40 disabled:cursor-not-allowed shrink-0"
|
||||
title="Upload from your computer"
|
||||
>
|
||||
{uploading ? "uploading…" : "upload"}
|
||||
</button>
|
||||
</div>
|
||||
{uploadError && <p className="text-danger text-[10px] mt-1">{uploadError}</p>}
|
||||
<input ref={fileRef} type="file" accept="image/*" onChange={handleFile} className="hidden" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Nip05Status = "idle" | "checking" | "valid" | "mismatch" | "notfound";
|
||||
|
||||
function Nip05Field({ value, onChange, pubkey }: { value: string; onChange: (v: string) => void; pubkey: string }) {
|
||||
const [status, setStatus] = useState<Nip05Status>("idle");
|
||||
|
||||
useEffect(() => {
|
||||
if (!value.includes("@")) { setStatus("idle"); return; }
|
||||
setStatus("checking");
|
||||
const t = setTimeout(async () => {
|
||||
const [name, domain] = value.trim().split("@");
|
||||
if (!name || !domain) { setStatus("notfound"); return; }
|
||||
try {
|
||||
const resp = await fetch(`https://${domain}/.well-known/nostr.json?name=${encodeURIComponent(name)}`);
|
||||
const data = await resp.json();
|
||||
const resolved = data.names?.[name];
|
||||
if (!resolved) setStatus("notfound");
|
||||
else if (resolved === pubkey) setStatus("valid");
|
||||
else setStatus("mismatch");
|
||||
} catch {
|
||||
setStatus("notfound");
|
||||
}
|
||||
}, 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, pubkey]);
|
||||
|
||||
const badge = {
|
||||
idle: null,
|
||||
checking: <span className="text-text-dim text-[10px]">checking…</span>,
|
||||
valid: <span className="text-success text-[10px]">✓ verified</span>,
|
||||
mismatch: <span className="text-danger text-[10px]">✗ pubkey mismatch</span>,
|
||||
notfound: <span className="text-danger text-[10px]">✗ not found</span>,
|
||||
}[status];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-baseline gap-2 mb-1">
|
||||
<label className="text-text-dim text-[10px]">NIP-05 verified name</label>
|
||||
{badge}
|
||||
</div>
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="you@domain.com"
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
<p className="text-text-dim text-[10px] mt-1">
|
||||
Proves your identity via a domain you control.{" "}
|
||||
<a
|
||||
href="https://nostr.how/en/guides/get-verified"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-accent hover:text-accent-hover transition-colors"
|
||||
>
|
||||
How to get verified ↗
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EditProfileForm({ pubkey, onSaved }: { pubkey: string; onSaved: () => void }) {
|
||||
const { profile, fetchOwnProfile } = useUserStore();
|
||||
const [name, setName] = useState(profile?.name || "");
|
||||
const [displayName, setDisplayName] = useState(profile?.displayName || "");
|
||||
const [about, setAbout] = useState(profile?.about || "");
|
||||
const [picture, setPicture] = useState(profile?.picture || "");
|
||||
const [banner, setBanner] = useState(profile?.banner || "");
|
||||
const [website, setWebsite] = useState(profile?.website || "");
|
||||
const [nip05, setNip05] = useState(profile?.nip05 || "");
|
||||
const [lud16, setLud16] = useState(profile?.lud16 || "");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
invalidateProfileCache(pubkey);
|
||||
await publishProfile({
|
||||
name: name.trim() || undefined,
|
||||
display_name: displayName.trim() || undefined,
|
||||
about: about.trim() || undefined,
|
||||
picture: picture.trim() || undefined,
|
||||
banner: banner.trim() || undefined,
|
||||
website: website.trim() || undefined,
|
||||
nip05: nip05.trim() || undefined,
|
||||
lud16: lud16.trim() || undefined,
|
||||
});
|
||||
await fetchOwnProfile();
|
||||
setSaved(true);
|
||||
setTimeout(onSaved, 1000);
|
||||
} catch (err) {
|
||||
setError(`Failed to save: ${err}`);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const field = (label: string, value: string, onChange: (v: string) => void, placeholder = "") => (
|
||||
<div>
|
||||
<label className="text-text-dim text-[10px] block mb-1">{label}</label>
|
||||
<input
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4 border-b border-border">
|
||||
<div className="grid grid-cols-2 gap-3 mb-3">
|
||||
{field("Display name", displayName, setDisplayName, "Square that Circle")}
|
||||
{field("Username", name, setName, "squarethecircle")}
|
||||
<Nip05Field value={nip05} onChange={setNip05} pubkey={pubkey} />
|
||||
{field("Lightning address (lud16)", lud16, setLud16, "you@walletofsatoshi.com")}
|
||||
{field("Website", website, setWebsite, "https://…")}
|
||||
<ImageField label="Profile picture" value={picture} onChange={setPicture} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label className="text-text-dim text-[10px] block mb-1">Bio</label>
|
||||
<textarea
|
||||
value={about}
|
||||
onChange={(e) => setAbout(e.target.value)}
|
||||
placeholder="Tell people about yourself…"
|
||||
rows={3}
|
||||
className="w-full bg-bg border border-border px-3 py-1.5 text-text text-[12px] resize-none focus:outline-none focus:border-accent/50"
|
||||
style={{ WebkitUserSelect: "text", userSelect: "text" } as React.CSSProperties}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<ImageField label="Banner image" value={banner} onChange={setBanner} />
|
||||
</div>
|
||||
{error && <p className="text-danger text-[11px] mb-2">{error}</p>}
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving || saved}
|
||||
className="px-4 py-1.5 text-[11px] bg-accent hover:bg-accent-hover text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saved ? "saved ✓" : saving ? "saving…" : "save profile"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { EditProfileForm } from "./EditProfileForm";
|
||||
import { ProfileMediaGallery } from "./ProfileMediaGallery";
|
||||
|
||||
export function ProfileView() {
|
||||
const { selectedPubkey, goBack, openDM } = useUIStore();
|
||||
@@ -467,130 +266,3 @@ export function ProfileView() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Media gallery sub-component ──────────────────────────────────────────────
|
||||
|
||||
const MEDIA_SEGMENT_TYPES = new Set(["image", "video", "audio", "youtube", "vimeo"]);
|
||||
|
||||
interface MediaItem {
|
||||
type: "image" | "video" | "audio";
|
||||
url: string;
|
||||
thumbnailId?: string;
|
||||
noteId: string;
|
||||
}
|
||||
|
||||
function extractMediaItems(notes: NDKEvent[]): MediaItem[] {
|
||||
const items: MediaItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const note of notes) {
|
||||
const segments = parseContent(note.content);
|
||||
for (const seg of segments) {
|
||||
if (!MEDIA_SEGMENT_TYPES.has(seg.type)) continue;
|
||||
if (seen.has(seg.value)) continue;
|
||||
seen.add(seg.value);
|
||||
if (seg.type === "image") {
|
||||
items.push({ type: "image", url: seg.value, noteId: note.id! });
|
||||
} else if (seg.type === "video" || seg.type === "youtube" || seg.type === "vimeo") {
|
||||
items.push({ type: "video", url: seg.value, thumbnailId: seg.mediaId, noteId: note.id! });
|
||||
} else if (seg.type === "audio") {
|
||||
items.push({ type: "audio", url: seg.value, noteId: note.id! });
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function ProfileMediaGallery({ notes, loading }: { notes: NDKEvent[]; loading: boolean }) {
|
||||
const { openThread } = useUIStore();
|
||||
const [lightboxIdx, setLightboxIdx] = useState<number | null>(null);
|
||||
|
||||
if (loading) {
|
||||
return <div className="px-4 py-8 text-text-dim text-[12px] text-center">Loading media…</div>;
|
||||
}
|
||||
|
||||
const items = extractMediaItems(notes);
|
||||
const imageUrls = items.filter((i) => i.type === "image").map((i) => i.url);
|
||||
|
||||
if (items.length === 0) {
|
||||
return <div className="px-4 py-8 text-text-dim text-[12px] text-center">No media found.</div>;
|
||||
}
|
||||
|
||||
const openNote = (noteId: string) => {
|
||||
const note = notes.find((n) => n.id === noteId);
|
||||
if (note) openThread(note, "profile");
|
||||
};
|
||||
|
||||
let imageIndex = 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 xl:grid-cols-3 gap-1 p-2">
|
||||
{items.map((item, idx) => {
|
||||
if (item.type === "image") {
|
||||
const currentImageIdx = imageIndex++;
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={() => setLightboxIdx(currentImageIdx)}
|
||||
>
|
||||
<img
|
||||
src={item.url}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = "none"; }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (item.type === "video") {
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity relative flex items-center justify-center"
|
||||
onClick={() => openNote(item.noteId)}
|
||||
>
|
||||
{item.thumbnailId ? (
|
||||
<img
|
||||
src={`https://img.youtube.com/vi/${item.thumbnailId}/mqdefault.jpg`}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full bg-bg-raised" />
|
||||
)}
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<span className="w-10 h-10 rounded-full bg-black/60 flex items-center justify-center text-white text-lg">▶</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// audio
|
||||
return (
|
||||
<div
|
||||
key={idx}
|
||||
className="aspect-square overflow-hidden bg-bg-raised cursor-pointer hover:opacity-80 transition-opacity flex items-center justify-center"
|
||||
onClick={() => openNote(item.noteId)}
|
||||
>
|
||||
<div className="text-center">
|
||||
<span className="text-3xl text-text-dim">♪</span>
|
||||
<p className="text-text-dim text-[10px] mt-1 px-2 truncate">{item.url.split("/").pop()}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{lightboxIdx !== null && (
|
||||
<ImageLightbox
|
||||
images={imageUrls}
|
||||
index={lightboxIdx}
|
||||
onClose={() => setLightboxIdx(null)}
|
||||
onNavigate={(i) => setLightboxIdx(i)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
106
src/lib/nostr/articles.ts
Normal file
106
src/lib/nostr/articles.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage, nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function publishArticle(opts: {
|
||||
title: string;
|
||||
content: string;
|
||||
summary?: string;
|
||||
image?: string;
|
||||
tags?: string[];
|
||||
}): Promise<{ relayCount: number }> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const slug = opts.title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
.slice(0, 60) + "-" + Date.now();
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 30023;
|
||||
event.content = opts.content;
|
||||
event.tags = [
|
||||
["d", slug],
|
||||
["title", opts.title],
|
||||
["published_at", String(Math.floor(Date.now() / 1000))],
|
||||
];
|
||||
if (opts.summary) event.tags.push(["summary", opts.summary]);
|
||||
if (opts.image) event.tags.push(["image", opts.image]);
|
||||
if (opts.tags) opts.tags.forEach((t) => event.tags.push(["t", t]));
|
||||
|
||||
const relays = await event.publish();
|
||||
return { relayCount: relays.size };
|
||||
}
|
||||
|
||||
export async function fetchArticle(naddr: string): Promise<NDKEvent | null> {
|
||||
const instance = getNDK();
|
||||
try {
|
||||
const decoded = nip19.decode(naddr);
|
||||
if (decoded.type !== "naddr") return null;
|
||||
const { identifier, pubkey, kind } = decoded.data;
|
||||
const filter: NDKFilter = {
|
||||
kinds: [kind as NDKKind],
|
||||
authors: [pubkey],
|
||||
"#d": [identifier],
|
||||
limit: 1,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events)[0] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchAuthorArticles(pubkey: string, limit = 20): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Article], authors: [pubkey], limit };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchArticleFeed(limit = 40, authors?: string[]): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Article], limit };
|
||||
if (authors && authors.length > 0) filter.authors = authors;
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function searchArticles(query: string, limit = 30): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const isHashtag = query.startsWith("#");
|
||||
const filter: NDKFilter & { search?: string } = isHashtag
|
||||
? { kinds: [NDKKind.Article], "#t": [query.slice(1).toLowerCase()], limit }
|
||||
: { kinds: [NDKKind.Article], search: query, limit };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchByAddr(addr: string): Promise<NDKEvent | null> {
|
||||
const instance = getNDK();
|
||||
// addr format: "30023:<pubkey>:<d-tag>"
|
||||
const parts = addr.split(":");
|
||||
if (parts.length < 3) return null;
|
||||
const kind = parseInt(parts[0]);
|
||||
const pubkey = parts[1];
|
||||
const dTag = parts.slice(2).join(":");
|
||||
const filter: NDKFilter = {
|
||||
kinds: [kind as NDKKind],
|
||||
authors: [pubkey],
|
||||
"#d": [dTag],
|
||||
limit: 1,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events)[0] ?? null;
|
||||
}
|
||||
49
src/lib/nostr/bookmarks.ts
Normal file
49
src/lib/nostr/bookmarks.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function fetchBookmarkList(pubkey: string): Promise<string[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [10003 as NDKKind], authors: [pubkey], limit: 1 };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
if (events.size === 0) return [];
|
||||
const event = Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))[0];
|
||||
return event.tags.filter((t) => t[0] === "e" && t[1]).map((t) => t[1]);
|
||||
}
|
||||
|
||||
export async function publishBookmarkList(eventIds: string[]): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) return;
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 10003 as NDKKind;
|
||||
event.content = "";
|
||||
event.tags = eventIds.map((id) => ["e", id]);
|
||||
await event.publish();
|
||||
}
|
||||
|
||||
export async function fetchBookmarkListFull(pubkey: string): Promise<{ eventIds: string[]; articleAddrs: string[] }> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [10003 as NDKKind], authors: [pubkey], limit: 1 };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
if (events.size === 0) return { eventIds: [], articleAddrs: [] };
|
||||
const event = Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))[0];
|
||||
const eventIds = event.tags.filter((t) => t[0] === "e" && t[1]).map((t) => t[1]);
|
||||
const articleAddrs = event.tags.filter((t) => t[0] === "a" && t[1]).map((t) => t[1]);
|
||||
return { eventIds, articleAddrs };
|
||||
}
|
||||
|
||||
export async function publishBookmarkListFull(eventIds: string[], articleAddrs: string[]): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) return;
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 10003 as NDKKind;
|
||||
event.content = "";
|
||||
event.tags = [
|
||||
...eventIds.map((id) => ["e", id]),
|
||||
...articleAddrs.map((addr) => ["a", addr]),
|
||||
];
|
||||
await event.publish();
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
82
src/lib/nostr/core.ts
Normal file
82
src/lib/nostr/core.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import NDK, { NDKRelay } from "@nostr-dev-kit/ndk";
|
||||
|
||||
export const RELAY_STORAGE_KEY = "wrystr_relays";
|
||||
|
||||
export const FALLBACK_RELAYS = [
|
||||
"wss://relay.damus.io",
|
||||
"wss://nos.lol",
|
||||
"wss://relay.snort.social",
|
||||
];
|
||||
|
||||
export function getStoredRelayUrls(): string[] {
|
||||
try {
|
||||
const stored = localStorage.getItem(RELAY_STORAGE_KEY);
|
||||
if (stored) return JSON.parse(stored);
|
||||
} catch { /* ignore */ }
|
||||
return FALLBACK_RELAYS;
|
||||
}
|
||||
|
||||
export function saveRelayUrls(urls: string[]) {
|
||||
localStorage.setItem(RELAY_STORAGE_KEY, JSON.stringify(urls));
|
||||
}
|
||||
|
||||
let ndk: NDK | null = null;
|
||||
|
||||
export function getNDK(): NDK {
|
||||
if (!ndk) {
|
||||
ndk = new NDK({
|
||||
explicitRelayUrls: getStoredRelayUrls(),
|
||||
});
|
||||
}
|
||||
return ndk;
|
||||
}
|
||||
|
||||
export function addRelay(url: string): void {
|
||||
const instance = getNDK();
|
||||
const urls = getStoredRelayUrls();
|
||||
if (!urls.includes(url)) {
|
||||
saveRelayUrls([...urls, url]);
|
||||
}
|
||||
if (!instance.pool?.relays.has(url)) {
|
||||
const relay = new NDKRelay(url, undefined, instance);
|
||||
instance.pool?.addRelay(relay, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function removeRelay(url: string): void {
|
||||
const instance = getNDK();
|
||||
const relay = instance.pool?.relays.get(url);
|
||||
if (relay) {
|
||||
relay.disconnect();
|
||||
instance.pool?.relays.delete(url);
|
||||
}
|
||||
saveRelayUrls(getStoredRelayUrls().filter((u) => u !== url));
|
||||
}
|
||||
|
||||
function waitForConnectedRelay(instance: NDK, timeoutMs = 10000): Promise<void> {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
// Even on timeout, continue — some relays may connect later
|
||||
console.warn("Relay connection timeout, continuing anyway");
|
||||
resolve();
|
||||
}, timeoutMs);
|
||||
|
||||
const check = () => {
|
||||
const relays = Array.from(instance.pool?.relays?.values() ?? []);
|
||||
const hasConnected = relays.some((r) => r.connected);
|
||||
if (hasConnected) {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(check, 300);
|
||||
}
|
||||
};
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
export async function connectToRelays(): Promise<void> {
|
||||
const instance = getNDK();
|
||||
await instance.connect();
|
||||
await waitForConnectedRelay(instance);
|
||||
}
|
||||
119
src/lib/nostr/dms.ts
Normal file
119
src/lib/nostr/dms.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { NDKEvent, NDKKind, NDKSubscriptionCacheUsage, giftWrap, giftUnwrap } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
async function unwrapGiftWraps(events: NDKEvent[]): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) return [];
|
||||
const rumors: NDKEvent[] = [];
|
||||
for (const wrap of events) {
|
||||
try {
|
||||
const rumor = await giftUnwrap(wrap, undefined, instance.signer);
|
||||
if (rumor && rumor.kind === NDKKind.PrivateDirectMessage) {
|
||||
// Preserve wrapper ID for dedup, but use rumor's created_at for ordering
|
||||
rumors.push(rumor);
|
||||
}
|
||||
} catch {
|
||||
// Not for us or corrupted — skip silently
|
||||
}
|
||||
}
|
||||
return rumors;
|
||||
}
|
||||
|
||||
export async function fetchDMConversations(myPubkey: string): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
// Fetch NIP-04 (legacy) and NIP-17 (gift-wrap) in parallel
|
||||
const [nip04Received, nip04Sent, giftWraps] = await Promise.all([
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.EncryptedDirectMessage], "#p": [myPubkey], limit: 500 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.EncryptedDirectMessage], authors: [myPubkey], limit: 500 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.GiftWrap], "#p": [myPubkey], limit: 500 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
]);
|
||||
|
||||
const nip17Rumors = await unwrapGiftWraps(Array.from(giftWraps));
|
||||
|
||||
const seen = new Set<string>();
|
||||
return [...Array.from(nip04Received), ...Array.from(nip04Sent), ...nip17Rumors]
|
||||
.filter((e) => { if (seen.has(e.id!)) return false; seen.add(e.id!); return true; })
|
||||
.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchDMThread(myPubkey: string, theirPubkey: string): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
// Fetch NIP-04 and NIP-17 in parallel
|
||||
const [fromThem, fromMe, giftWraps] = await Promise.all([
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.EncryptedDirectMessage], "#p": [myPubkey], authors: [theirPubkey], limit: 200 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.EncryptedDirectMessage], "#p": [theirPubkey], authors: [myPubkey], limit: 200 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.GiftWrap], "#p": [myPubkey], limit: 200 },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
]);
|
||||
|
||||
// Unwrap NIP-17 and filter to only messages from/to this partner
|
||||
const allRumors = await unwrapGiftWraps(Array.from(giftWraps));
|
||||
const partnerRumors = allRumors.filter((r) => {
|
||||
const pTag = r.tags.find((t) => t[0] === "p")?.[1];
|
||||
return r.pubkey === theirPubkey || pTag === theirPubkey;
|
||||
});
|
||||
|
||||
return [...Array.from(fromThem), ...Array.from(fromMe), ...partnerRumors]
|
||||
.sort((a, b) => (a.created_at ?? 0) - (b.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function sendDM(recipientPubkey: string, content: string): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const myUser = await instance.signer.user();
|
||||
const recipient = instance.getUser({ pubkey: recipientPubkey });
|
||||
|
||||
// Create unsigned rumor (kind 14)
|
||||
const rumor = new NDKEvent(instance);
|
||||
rumor.kind = NDKKind.PrivateDirectMessage;
|
||||
rumor.content = content;
|
||||
rumor.tags = [["p", recipientPubkey]];
|
||||
rumor.pubkey = myUser.pubkey;
|
||||
rumor.created_at = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Gift-wrap to recipient and self (so sent messages appear in our inbox)
|
||||
const [wrappedForRecipient, wrappedForSelf] = await Promise.all([
|
||||
giftWrap(rumor, recipient, instance.signer),
|
||||
giftWrap(rumor, myUser, instance.signer),
|
||||
]);
|
||||
|
||||
await Promise.all([
|
||||
wrappedForRecipient.publish(),
|
||||
wrappedForSelf.publish(),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function decryptDM(event: NDKEvent, myPubkey: string): Promise<string> {
|
||||
// Kind 14 (NIP-17 rumor) — content is already plaintext after unwrapping
|
||||
if (event.kind === NDKKind.PrivateDirectMessage) {
|
||||
return event.content;
|
||||
}
|
||||
|
||||
// Kind 4 (NIP-04 legacy) — decrypt as before
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("No signer");
|
||||
const otherPubkey =
|
||||
event.pubkey === myPubkey
|
||||
? (event.tags.find((t) => t[0] === "p")?.[1] ?? "")
|
||||
: event.pubkey;
|
||||
const otherUser = instance.getUser({ pubkey: otherPubkey });
|
||||
return instance.signer.decrypt(otherUser, event.content, "nip04");
|
||||
}
|
||||
134
src/lib/nostr/engagement.ts
Normal file
134
src/lib/nostr/engagement.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function publishReaction(eventId: string, eventPubkey: string, reaction = "+"): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = NDKKind.Reaction;
|
||||
event.content = reaction;
|
||||
event.tags = [
|
||||
["e", eventId],
|
||||
["p", eventPubkey],
|
||||
];
|
||||
await event.publish();
|
||||
}
|
||||
|
||||
export async function fetchReactionCount(eventId: string): Promise<number> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Reaction],
|
||||
"#e": [eventId],
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return events.size;
|
||||
}
|
||||
|
||||
export async function fetchReplyCount(eventId: string): Promise<number> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
"#e": [eventId],
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return events.size;
|
||||
}
|
||||
|
||||
export async function fetchZapCount(eventId: string): Promise<{ count: number; totalSats: number }> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Zap], "#e": [eventId] };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
let totalSats = 0;
|
||||
for (const event of events) {
|
||||
const desc = event.tags.find((t) => t[0] === "description")?.[1];
|
||||
if (desc) {
|
||||
try {
|
||||
const zapReq = JSON.parse(desc) as { tags?: string[][] };
|
||||
const amountTag = zapReq.tags?.find((t) => t[0] === "amount");
|
||||
if (amountTag?.[1]) totalSats += Math.round(parseInt(amountTag[1]) / 1000);
|
||||
} catch { /* malformed */ }
|
||||
}
|
||||
}
|
||||
return { count: events.size, totalSats };
|
||||
}
|
||||
|
||||
export async function fetchBatchEngagement(eventIds: string[]): Promise<Map<string, { reactions: number; replies: number; zapSats: number }>> {
|
||||
const instance = getNDK();
|
||||
const result = new Map<string, { reactions: number; replies: number; zapSats: number }>();
|
||||
for (const id of eventIds) {
|
||||
result.set(id, { reactions: 0, replies: 0, zapSats: 0 });
|
||||
}
|
||||
|
||||
// Batch in chunks to avoid oversized filters
|
||||
const chunkSize = 50;
|
||||
for (let i = 0; i < eventIds.length; i += chunkSize) {
|
||||
const chunk = eventIds.slice(i, i + chunkSize);
|
||||
|
||||
const [reactions, replies, zaps] = await Promise.all([
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.Reaction], "#e": chunk },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.Text], "#e": chunk },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
instance.fetchEvents(
|
||||
{ kinds: [NDKKind.Zap], "#e": chunk },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
),
|
||||
]);
|
||||
|
||||
for (const event of reactions) {
|
||||
const eTag = event.tags.find((t) => t[0] === "e")?.[1];
|
||||
if (eTag && result.has(eTag)) result.get(eTag)!.reactions++;
|
||||
}
|
||||
|
||||
for (const event of replies) {
|
||||
const eTag = event.tags.find((t) => t[0] === "e")?.[1];
|
||||
if (eTag && result.has(eTag)) result.get(eTag)!.replies++;
|
||||
}
|
||||
|
||||
for (const event of zaps) {
|
||||
const eTag = event.tags.find((t) => t[0] === "e")?.[1];
|
||||
if (eTag && result.has(eTag)) {
|
||||
const desc = event.tags.find((t) => t[0] === "description")?.[1];
|
||||
if (desc) {
|
||||
try {
|
||||
const zapReq = JSON.parse(desc) as { tags?: string[][] };
|
||||
const amountTag = zapReq.tags?.find((t) => t[0] === "amount");
|
||||
if (amountTag?.[1]) result.get(eTag)!.zapSats += Math.round(parseInt(amountTag[1]) / 1000);
|
||||
} catch { /* malformed */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function fetchZapsReceived(pubkey: string, limit = 50): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Zap], "#p": [pubkey], limit };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchZapsSent(pubkey: string, limit = 50): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
// Zap receipts (kind 9735) with uppercase P tag = the sender's pubkey
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Zap], "#P": [pubkey], limit };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
@@ -1,2 +1,13 @@
|
||||
export { getNDK, connectToRelays, fetchGlobalFeed, fetchFollowFeed, fetchReplies, publishNote, publishArticle, publishProfile, publishReaction, publishRepost, publishQuote, publishReply, publishContactList, fetchBatchEngagement, fetchReactionCount, fetchReplyCount, fetchZapCount, fetchNoteById, fetchUserNotes, fetchProfile, fetchArticle, fetchAuthorArticles, fetchArticleFeed, searchArticles, fetchZapsReceived, fetchZapsSent, fetchDMConversations, fetchDMThread, sendDM, decryptDM, fetchBookmarkList, publishBookmarkList, fetchBookmarkListFull, publishBookmarkListFull, fetchByAddr, fetchMuteList, publishMuteList, getStoredRelayUrls, addRelay, removeRelay, searchNotes, searchUsers, fetchUserRelayList, publishRelayList, fetchUserNotesNIP65, fetchFollowSuggestions, fetchMentions, resolveNip05, advancedSearch, fetchRelayRecommendations, fetchTrendingHashtags, fetchTrendingCandidates, fetchHashtagFeed, fetchNewFollowers } from "./client";
|
||||
export type { UserRelayList, AdvancedSearchResults } from "./client";
|
||||
export { getNDK, connectToRelays, getStoredRelayUrls, addRelay, removeRelay } from "./core";
|
||||
export { fetchGlobalFeed, fetchFollowFeed, fetchUserNotes, fetchUserNotesNIP65, fetchNoteById, fetchReplies, publishNote, publishReply, publishRepost, publishQuote, fetchHashtagFeed } from "./notes";
|
||||
export { publishProfile, publishContactList, fetchProfile, fetchFollowSuggestions, fetchMentions, fetchNewFollowers } from "./social";
|
||||
export { publishArticle, fetchArticle, fetchAuthorArticles, fetchArticleFeed, searchArticles, fetchByAddr } from "./articles";
|
||||
export { publishReaction, fetchReactionCount, fetchReplyCount, fetchZapCount, fetchBatchEngagement, fetchZapsReceived, fetchZapsSent } from "./engagement";
|
||||
export { fetchDMConversations, fetchDMThread, sendDM, decryptDM } from "./dms";
|
||||
export { fetchBookmarkList, publishBookmarkList, fetchBookmarkListFull, publishBookmarkListFull } from "./bookmarks";
|
||||
export { fetchMuteList, publishMuteList } from "./muting";
|
||||
export { searchNotes, searchUsers, resolveNip05, advancedSearch } from "./search";
|
||||
export type { AdvancedSearchResults } from "./search";
|
||||
export { fetchUserRelayList, publishRelayList, fetchRelayRecommendations } from "./relays";
|
||||
export type { UserRelayList } from "./relays";
|
||||
export { fetchTrendingCandidates, fetchTrendingHashtags } from "./trending";
|
||||
|
||||
23
src/lib/nostr/muting.ts
Normal file
23
src/lib/nostr/muting.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function fetchMuteList(pubkey: string): Promise<string[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [10000 as NDKKind], authors: [pubkey], limit: 1 };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
if (events.size === 0) return [];
|
||||
const event = Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))[0];
|
||||
return event.tags.filter((t) => t[0] === "p" && t[1]).map((t) => t[1]);
|
||||
}
|
||||
|
||||
export async function publishMuteList(pubkeys: string[]): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) return;
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 10000 as NDKKind;
|
||||
event.content = "";
|
||||
event.tags = pubkeys.map((pk) => ["p", pk]);
|
||||
await event.publish();
|
||||
}
|
||||
154
src/lib/nostr/notes.ts
Normal file
154
src/lib/nostr/notes.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKRelaySet, NDKSubscriptionCacheUsage, nip19 } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK, getStoredRelayUrls } from "./core";
|
||||
import { fetchUserRelayList } from "./relays";
|
||||
|
||||
export async function fetchGlobalFeed(limit: number = 50): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
limit,
|
||||
};
|
||||
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchFollowFeed(pubkeys: string[], limit = 80): Promise<NDKEvent[]> {
|
||||
if (pubkeys.length === 0) return [];
|
||||
const instance = getNDK();
|
||||
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
authors: pubkeys,
|
||||
limit,
|
||||
};
|
||||
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchUserNotes(pubkey: string, limit = 30): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
authors: [pubkey],
|
||||
limit,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchUserNotesNIP65(pubkey: string, limit = 30): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [NDKKind.Text], authors: [pubkey], limit };
|
||||
try {
|
||||
const relayList = await fetchUserRelayList(pubkey);
|
||||
if (relayList.write.length > 0) {
|
||||
const merged = Array.from(new Set([...relayList.write, ...getStoredRelayUrls()]));
|
||||
const relaySet = NDKRelaySet.fromRelayUrls(merged, instance);
|
||||
const events = await instance.fetchEvents(filter, { cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }, relaySet);
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
} catch { /* fallthrough */ }
|
||||
return fetchUserNotes(pubkey, limit);
|
||||
}
|
||||
|
||||
export async function fetchNoteById(eventId: string): Promise<NDKEvent | null> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { ids: [eventId], limit: 1 };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events)[0] ?? null;
|
||||
}
|
||||
|
||||
export async function fetchReplies(eventId: string): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
"#e": [eventId],
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (a.created_at ?? 0) - (b.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function publishNote(content: string): Promise<NDKEvent> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = NDKKind.Text;
|
||||
event.content = content;
|
||||
await event.publish();
|
||||
return event;
|
||||
}
|
||||
|
||||
export async function publishReply(content: string, replyTo: { id: string; pubkey: string }): Promise<NDKEvent> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = NDKKind.Text;
|
||||
event.content = content;
|
||||
event.tags = [
|
||||
["e", replyTo.id, "", "reply"],
|
||||
["p", replyTo.pubkey],
|
||||
];
|
||||
await event.publish();
|
||||
return event;
|
||||
}
|
||||
|
||||
export async function publishRepost(event: NDKEvent): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const repost = new NDKEvent(instance);
|
||||
repost.kind = NDKKind.Repost; // kind 6
|
||||
repost.content = JSON.stringify(event.rawEvent());
|
||||
repost.tags = [
|
||||
["e", event.id!, "", "mention"],
|
||||
["p", event.pubkey],
|
||||
];
|
||||
await repost.publish();
|
||||
}
|
||||
|
||||
export async function publishQuote(content: string, quotedEvent: NDKEvent): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const nevent = nip19.neventEncode({ id: quotedEvent.id!, author: quotedEvent.pubkey });
|
||||
const fullContent = content.trim() + "\n\nnostr:" + nevent;
|
||||
|
||||
const note = new NDKEvent(instance);
|
||||
note.kind = NDKKind.Text;
|
||||
note.content = fullContent;
|
||||
note.tags = [
|
||||
["q", quotedEvent.id!, ""],
|
||||
["p", quotedEvent.pubkey],
|
||||
];
|
||||
await note.publish();
|
||||
}
|
||||
|
||||
export async function fetchHashtagFeed(tag: string, limit = 100): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
"#t": [tag.toLowerCase()],
|
||||
limit,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
64
src/lib/nostr/relays.ts
Normal file
64
src/lib/nostr/relays.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export interface UserRelayList { read: string[]; write: string[]; }
|
||||
|
||||
export async function fetchUserRelayList(pubkey: string): Promise<UserRelayList> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = { kinds: [10002 as NDKKind], authors: [pubkey], limit: 1 };
|
||||
const events = await instance.fetchEvents(filter, { cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY });
|
||||
if (events.size === 0) return { read: [], write: [] };
|
||||
const event = Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))[0];
|
||||
const read: string[] = [], write: string[] = [];
|
||||
for (const tag of event.tags) {
|
||||
if (tag[0] !== "r" || !tag[1]) continue;
|
||||
const marker = tag[2];
|
||||
if (!marker || marker === "read") read.push(tag[1]);
|
||||
if (!marker || marker === "write") write.push(tag[1]);
|
||||
}
|
||||
return { read, write };
|
||||
}
|
||||
|
||||
export async function publishRelayList(relayUrls: string[]): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 10002 as NDKKind;
|
||||
event.content = "";
|
||||
event.tags = relayUrls.map((url) => ["r", url]);
|
||||
await event.publish();
|
||||
}
|
||||
|
||||
export async function fetchRelayRecommendations(
|
||||
follows: string[],
|
||||
ownRelays: string[],
|
||||
sampleSize = 30
|
||||
): Promise<{ url: string; count: number }[]> {
|
||||
if (follows.length === 0) return [];
|
||||
// Sample random follows to avoid hammering relays
|
||||
const shuffled = [...follows].sort(() => Math.random() - 0.5);
|
||||
const sample = shuffled.slice(0, sampleSize);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
sample.map((pk) => fetchUserRelayList(pk))
|
||||
);
|
||||
|
||||
const ownSet = new Set(ownRelays.map((u) => u.replace(/\/$/, "")));
|
||||
const tally = new Map<string, number>();
|
||||
|
||||
for (const result of results) {
|
||||
if (result.status !== "fulfilled") continue;
|
||||
const allUrls = Array.from(new Set([...result.value.read, ...result.value.write]));
|
||||
for (const url of allUrls) {
|
||||
const normalized = url.replace(/\/$/, "");
|
||||
if (ownSet.has(normalized)) continue;
|
||||
tally.set(normalized, (tally.get(normalized) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(tally.entries())
|
||||
.map(([url, count]) => ({ url, count }))
|
||||
.filter((r) => r.count >= 2)
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 8);
|
||||
}
|
||||
159
src/lib/nostr/search.ts
Normal file
159
src/lib/nostr/search.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage, NDKUser } from "@nostr-dev-kit/ndk";
|
||||
import { type ParsedSearch, matchesHasFilter } from "../search";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function searchNotes(query: string, limit = 50): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const isHashtag = query.startsWith("#");
|
||||
const filter: NDKFilter & { search?: string } = isHashtag
|
||||
? { kinds: [NDKKind.Text], "#t": [query.slice(1).toLowerCase()], limit }
|
||||
: { kinds: [NDKKind.Text], search: query, limit };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function searchUsers(query: string, limit = 20): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter & { search?: string } = {
|
||||
kinds: [NDKKind.Metadata],
|
||||
search: query,
|
||||
limit,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events);
|
||||
}
|
||||
|
||||
export async function resolveNip05(identifier: string): Promise<string | null> {
|
||||
const instance = getNDK();
|
||||
try {
|
||||
const user = new NDKUser({ nip05: identifier });
|
||||
user.ndk = instance;
|
||||
await user.fetchProfile();
|
||||
return user.pubkey || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface AdvancedSearchResults {
|
||||
notes: NDKEvent[];
|
||||
articles: NDKEvent[];
|
||||
users: NDKEvent[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an advanced search using a ParsedSearch query.
|
||||
* Resolves NIP-05 identifiers, builds filters, runs queries,
|
||||
* and applies client-side filters (has:image, has:code, etc.).
|
||||
*/
|
||||
export async function advancedSearch(parsed: ParsedSearch, limit = 50): Promise<AdvancedSearchResults> {
|
||||
const instance = getNDK();
|
||||
|
||||
// Handle OR queries — run each sub-query and merge
|
||||
if (parsed.orQueries && parsed.orQueries.length > 0) {
|
||||
const subResults = await Promise.all(parsed.orQueries.map((q) => advancedSearch(q, limit)));
|
||||
const seenNotes = new Set<string>();
|
||||
const seenArticles = new Set<string>();
|
||||
const seenUsers = new Set<string>();
|
||||
const notes: NDKEvent[] = [];
|
||||
const articles: NDKEvent[] = [];
|
||||
const users: NDKEvent[] = [];
|
||||
for (const r of subResults) {
|
||||
for (const e of r.notes) { if (!seenNotes.has(e.id!)) { seenNotes.add(e.id!); notes.push(e); } }
|
||||
for (const e of r.articles) { if (!seenArticles.has(e.id!)) { seenArticles.add(e.id!); articles.push(e); } }
|
||||
for (const e of r.users) { if (!seenUsers.has(e.pubkey)) { seenUsers.add(e.pubkey); users.push(e); } }
|
||||
}
|
||||
return {
|
||||
notes: notes.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)).slice(0, limit),
|
||||
articles: articles.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)).slice(0, limit),
|
||||
users,
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve any NIP-05 or name-based author identifiers
|
||||
const resolvedAuthors = [...parsed.authors];
|
||||
for (const nip05 of parsed.unresolvedNip05) {
|
||||
const resolved = await resolveNip05(nip05.includes("@") || nip05.includes(".") ? nip05 : `_@${nip05}`);
|
||||
if (resolved) {
|
||||
resolvedAuthors.push(resolved);
|
||||
} else {
|
||||
const nameResults = await searchUsers(nip05, 1);
|
||||
if (nameResults.length > 0) {
|
||||
resolvedAuthors.push(nameResults[0].pubkey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which kinds to search
|
||||
const hasKindFilter = parsed.kinds.length > 0;
|
||||
const noteKinds = hasKindFilter
|
||||
? parsed.kinds.filter((k) => k === 1)
|
||||
: [1];
|
||||
const articleKinds = hasKindFilter
|
||||
? parsed.kinds.filter((k) => k === 30023)
|
||||
: [30023];
|
||||
|
||||
const searchText = parsed.searchTerms.join(" ").trim();
|
||||
const hasSearch = searchText.length > 0;
|
||||
const hasHashtags = parsed.hashtags.length > 0;
|
||||
|
||||
const buildFilter = (kinds: number[]): (NDKFilter & { search?: string }) | null => {
|
||||
if (kinds.length === 0 && hasKindFilter) return null;
|
||||
const filter: NDKFilter & { search?: string } = {
|
||||
kinds: kinds.map((k) => k as NDKKind),
|
||||
limit,
|
||||
};
|
||||
if (hasSearch) filter.search = searchText;
|
||||
if (hasHashtags) filter["#t"] = parsed.hashtags;
|
||||
if (resolvedAuthors.length > 0) filter.authors = resolvedAuthors;
|
||||
if (parsed.mentions.length > 0) filter["#p"] = parsed.mentions;
|
||||
if (parsed.since) filter.since = parsed.since;
|
||||
if (parsed.until) filter.until = parsed.until;
|
||||
if (!hasSearch && !hasHashtags && resolvedAuthors.length === 0 && parsed.mentions.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return filter;
|
||||
};
|
||||
|
||||
const opts = { cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY };
|
||||
|
||||
// Wrap fetchEvents with a timeout — NDK can hang forever if no relay supports the filter
|
||||
const fetchWithTimeout = (filter: NDKFilter & { search?: string }, timeoutMs = 8000): Promise<Set<NDKEvent>> => {
|
||||
return Promise.race([
|
||||
instance.fetchEvents(filter, opts),
|
||||
new Promise<Set<NDKEvent>>((resolve) => setTimeout(() => resolve(new Set()), timeoutMs)),
|
||||
]);
|
||||
};
|
||||
|
||||
const noteFilter = noteKinds.length > 0 ? buildFilter(noteKinds) : null;
|
||||
const articleFilter = articleKinds.length > 0 ? buildFilter(articleKinds) : null;
|
||||
const shouldSearchUsers = (!hasKindFilter || parsed.kinds.includes(0)) && hasSearch && !hasHashtags;
|
||||
|
||||
const [noteEvents, articleEvents, userEvents] = await Promise.all([
|
||||
noteFilter ? fetchWithTimeout(noteFilter) : Promise.resolve(new Set<NDKEvent>()),
|
||||
articleFilter ? fetchWithTimeout(articleFilter) : Promise.resolve(new Set<NDKEvent>()),
|
||||
shouldSearchUsers ? fetchWithTimeout({ kinds: [NDKKind.Metadata], search: searchText, limit: 20 } as NDKFilter & { search: string }) : Promise.resolve(new Set<NDKEvent>()),
|
||||
]);
|
||||
|
||||
let notes = Array.from(noteEvents);
|
||||
let articles = Array.from(articleEvents);
|
||||
const users = Array.from(userEvents);
|
||||
|
||||
// Client-side filters: has:image, has:video, has:code, etc.
|
||||
if (parsed.hasFilters.length > 0) {
|
||||
const applyHas = (events: NDKEvent[]) =>
|
||||
events.filter((e) => parsed.hasFilters.every((f) => matchesHasFilter(e.content, f)));
|
||||
notes = applyHas(notes);
|
||||
articles = applyHas(articles);
|
||||
}
|
||||
|
||||
return {
|
||||
notes: notes.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)),
|
||||
articles: articles.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0)),
|
||||
users,
|
||||
};
|
||||
}
|
||||
98
src/lib/nostr/social.ts
Normal file
98
src/lib/nostr/social.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function publishProfile(fields: {
|
||||
name?: string;
|
||||
display_name?: string;
|
||||
about?: string;
|
||||
picture?: string;
|
||||
banner?: string;
|
||||
website?: string;
|
||||
nip05?: string;
|
||||
lud16?: string;
|
||||
}): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 0;
|
||||
event.content = JSON.stringify(fields);
|
||||
await event.publish();
|
||||
}
|
||||
|
||||
export async function publishContactList(pubkeys: string[]): Promise<void> {
|
||||
const instance = getNDK();
|
||||
if (!instance.signer) throw new Error("Not logged in");
|
||||
|
||||
const event = new NDKEvent(instance);
|
||||
event.kind = 3;
|
||||
event.content = "";
|
||||
event.tags = pubkeys.map((pk) => ["p", pk]);
|
||||
await event.publish();
|
||||
}
|
||||
|
||||
export async function fetchProfile(pubkey: string) {
|
||||
const instance = getNDK();
|
||||
const user = instance.getUser({ pubkey });
|
||||
await user.fetchProfile();
|
||||
return user.profile;
|
||||
}
|
||||
|
||||
export async function fetchFollowSuggestions(myFollows: string[]): Promise<{ pubkey: string; mutualCount: number }[]> {
|
||||
if (myFollows.length === 0) return [];
|
||||
const instance = getNDK();
|
||||
// Fetch contact lists (kind 3) from our follows
|
||||
const batchSize = 20;
|
||||
const allContactEvents: NDKEvent[] = [];
|
||||
for (let i = 0; i < myFollows.length; i += batchSize) {
|
||||
const batch = myFollows.slice(i, i + batchSize);
|
||||
const filter: NDKFilter = { kinds: [3 as NDKKind], authors: batch, limit: batch.length };
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
allContactEvents.push(...Array.from(events));
|
||||
}
|
||||
|
||||
// Count how many of our follows follow each pubkey
|
||||
const myFollowSet = new Set(myFollows);
|
||||
const counts = new Map<string, number>();
|
||||
for (const event of allContactEvents) {
|
||||
const pubkeys = event.tags.filter((t) => t[0] === "p" && t[1]).map((t) => t[1]);
|
||||
for (const pk of pubkeys) {
|
||||
if (myFollowSet.has(pk)) continue; // already following
|
||||
counts.set(pk, (counts.get(pk) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove self
|
||||
const myPubkey = (await instance.signer?.user())?.pubkey;
|
||||
if (myPubkey) counts.delete(myPubkey);
|
||||
|
||||
return Array.from(counts.entries())
|
||||
.map(([pubkey, mutualCount]) => ({ pubkey, mutualCount }))
|
||||
.sort((a, b) => b.mutualCount - a.mutualCount)
|
||||
.slice(0, 30);
|
||||
}
|
||||
|
||||
export async function fetchMentions(pubkey: string, since: number, limit = 50): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const events = await instance.fetchEvents(
|
||||
{ kinds: [NDKKind.Text], "#p": [pubkey], since, limit },
|
||||
{ cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY }
|
||||
);
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchNewFollowers(pubkey: string, since: number, limit = 20): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const filter: NDKFilter = {
|
||||
kinds: [3 as NDKKind],
|
||||
"#p": [pubkey],
|
||||
since,
|
||||
limit,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
45
src/lib/nostr/trending.ts
Normal file
45
src/lib/nostr/trending.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { NDKEvent, NDKFilter, NDKKind, NDKSubscriptionCacheUsage } from "@nostr-dev-kit/ndk";
|
||||
import { getNDK } from "./core";
|
||||
|
||||
export async function fetchTrendingCandidates(limit = 200, sinceHours = 24): Promise<NDKEvent[]> {
|
||||
const instance = getNDK();
|
||||
const since = Math.floor(Date.now() / 1000) - sinceHours * 3600;
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text, 30023 as NDKKind],
|
||||
since,
|
||||
limit,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
return Array.from(events).sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));
|
||||
}
|
||||
|
||||
export async function fetchTrendingHashtags(limit = 15): Promise<{ tag: string; count: number }[]> {
|
||||
const instance = getNDK();
|
||||
const since = Math.floor(Date.now() / 1000) - 24 * 60 * 60;
|
||||
const filter: NDKFilter = {
|
||||
kinds: [NDKKind.Text],
|
||||
since,
|
||||
limit: 500,
|
||||
};
|
||||
const events = await instance.fetchEvents(filter, {
|
||||
cacheUsage: NDKSubscriptionCacheUsage.ONLY_RELAY,
|
||||
});
|
||||
|
||||
const counts = new Map<string, number>();
|
||||
for (const event of events) {
|
||||
for (const tag of event.tags) {
|
||||
if (tag[0] !== "t" || !tag[1]) continue;
|
||||
const normalized = tag[1].toLowerCase().trim();
|
||||
if (normalized.length === 0) continue;
|
||||
counts.set(normalized, (counts.get(normalized) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(counts.entries())
|
||||
.filter(([, count]) => count >= 2)
|
||||
.map(([tag, count]) => ({ tag, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, limit);
|
||||
}
|
||||
Reference in New Issue
Block a user