Merge branch 'main' into feat/web-bookmarks-nip-b0

# Conflicts:
#	docs/apps.md
#	src/os/registry.ts
This commit is contained in:
2026-09-06 18:48:51 +02:00
16 changed files with 995 additions and 45 deletions

View File

@@ -89,14 +89,15 @@ export default function ExampleApp({ setTitle }: AppProps) {
}
```
## The eight apps
## The nine apps
| App | `id` | Params | Notes |
|---|---|---|---|
| Feed | `feed` | — | kind 1 timeline, Following/Global, composer (⌘↵ publishes) |
| Profile | `profile` | `pubkey`, `relays?` | kind 0 metadata, the author's notes, follow/unfollow |
| Note | `notes` | `id`, `relays?` | One note and its replies. **Not** a singleton |
| Reader | `articles` | `pubkey?`, `identifier?`, `kind?`, `relays?` | NIP-23 long-form, `react-markdown` |
| Note | `notes` | `id?`, `relays?` | One note and its replies, or a blank local draft when `id` is absent. **Not** a singleton |
| Reader | `articles` | `pubkey?`, `identifier?`, `kind?`, `relays?` | NIP-23 long-form, `react-markdown`, NIP-84 highlights |
| Bookmarks | `bookmarks` | — | NIP-51 kind 10003 list — bookmarked notes and articles |
| Web Bookmarks | `web-bookmarks` | — | NIP-B0 kind 39701 — one addressable event per saved URL |
| Relays | `relays` | — | Connection state, subscription count, measured latency |
| Settings | `settings` | — | Theme, relay list, Blossom servers, account, session |
@@ -110,6 +111,19 @@ the `d` tag is the URL itself (scheme stripped for `https`, see `bookmarkDTag` i
which relays are free to ignore, so the client also drops it from its own query cache
rather than trusting a refetch to reflect it.
### Highlighting selects against the DOM, not the markdown source
`HighlightLayer` (`src/apps/articles/HighlightLayer.tsx`) tracks `window.getSelection()`
against the rendered article, not the raw markdown — the highlighted text saved to a kind
9802 event is whatever that `Selection`'s `.toString()` returns, i.e. the plain-text content
the reader actually saw, not markdown syntax.
### Bookmarks are one whole-list replacement, like follow lists
kind 10003 is a replaceable event: publishing it replaces the entire list. `useToggleBookmark`
(`src/hooks/useBookmarks.ts`) therefore reads the current list back before publishing an
update, the same trap [follow lists](#follow-lists-are-a-whole-list-replacement) have.
### Follow lists are a whole-list replacement
kind 3 replaces the entire contact list. The follow button therefore reads the current

View File

@@ -0,0 +1,142 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Highlighter } from 'lucide-react';
import { AppSectionTitle } from '@/components/os/AppChrome';
import { AuthorLine } from '@/components/nostr/AuthorLine';
import { useCreateHighlight, useHighlights } from '@/hooks/useHighlights';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
interface SelectionState {
text: string;
top: number;
left: number;
}
/**
* Wraps article content with NIP-84 highlighting: selecting text shows a
* floating "Highlight" button (à la Medium/Kindle), and existing highlights
* from the network are listed underneath the article.
*/
export function HighlightLayer({
address,
authorPubkey,
children,
}: {
/** `kind:pubkey:d-identifier` of the article being read. */
address: string;
authorPubkey: string;
children: ReactNode;
}) {
const { user } = useCurrentUser();
const containerRef = useRef<HTMLDivElement>(null);
const [selection, setSelection] = useState<SelectionState | null>(null);
const create = useCreateHighlight();
const { toast } = useToast();
useEffect(() => {
// No point tracking selection at all when highlighting can't happen —
// signed out, or the article has no usable address to attach one to.
// (Stale selection state from before either went missing is harmless:
// the button below also requires `user && address` to render.)
if (!user || !address) return;
function handleSelectionChange() {
const sel = window.getSelection();
const container = containerRef.current;
if (!sel || sel.isCollapsed || sel.rangeCount === 0 || !container) {
setSelection(null);
return;
}
const range = sel.getRangeAt(0);
// commonAncestorContainer, not anchorNode: anchorNode is only where the
// selection *started*, so a selection that starts inside the article
// and is dragged out past its boundary would otherwise still pass.
if (!container.contains(range.commonAncestorContainer)) {
setSelection(null);
return;
}
const text = sel.toString().trim();
if (!text) {
setSelection(null);
return;
}
const rect = range.getBoundingClientRect();
setSelection({ text, top: rect.top, left: rect.left + rect.width / 2 });
}
document.addEventListener('selectionchange', handleSelectionChange);
return () => document.removeEventListener('selectionchange', handleSelectionChange);
}, [user, address]);
const handleHighlight = async () => {
if (!selection || !address) return;
const { text } = selection;
window.getSelection()?.removeAllRanges();
setSelection(null);
try {
await create.mutateAsync({ text, address, authorPubkey });
toast({ title: 'Highlighted' });
} catch (error) {
toast({
title: 'Could not save highlight',
description: error instanceof Error ? error.message : 'No relay accepted it.',
variant: 'destructive',
});
}
};
return (
<>
<div ref={containerRef} className="relative">
{children}
{user && address && selection && (
<button
type="button"
// Selection collapses on mousedown before onClick fires unless
// that default is prevented — the button would otherwise vanish
// the instant it's pressed.
onMouseDown={(event) => event.preventDefault()}
onClick={handleHighlight}
style={{
position: 'fixed',
// Clamped so a selection near the top of the viewport doesn't
// push the button off-screen and out of reach.
top: Math.max(8, selection.top - 40),
left: selection.left,
transform: 'translateX(-50%)',
}}
className="z-50 flex items-center gap-1.5 rounded-full bg-foreground px-3 py-1.5 text-xs font-medium text-background shadow-lg"
>
<Highlighter className="size-3.5" aria-hidden />
Highlight
</button>
)}
</div>
<HighlightsList address={address} />
</>
);
}
function HighlightsList({ address }: { address: string }) {
const highlights = useHighlights(address);
if (!highlights.data || highlights.data.length === 0) return null;
return (
<section className="mt-10 border-t border-border pt-6">
<AppSectionTitle>
{highlights.data.length} {highlights.data.length === 1 ? 'Highlight' : 'Highlights'}
</AppSectionTitle>
<ul className="space-y-4">
{highlights.data.map((event) => (
<li key={event.id} className="border-l-2 border-primary/40 pl-3">
<blockquote className="text-[14px] italic leading-relaxed">{event.content}</blockquote>
<AuthorLine pubkey={event.pubkey} createdAt={event.created_at} size="sm" className="mt-1.5" />
</li>
))}
</ul>
</section>
);
}

View File

@@ -1,7 +1,7 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { ChevronLeft, Link2 } from 'lucide-react';
import { Bookmark, ChevronLeft, Link2, Rss } from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
import {
AppBody,
@@ -13,11 +13,15 @@ import {
EmptyState,
} from '@/components/os/AppChrome';
import { AuthorLine } from '@/components/nostr/AuthorLine';
import { HighlightLayer } from './HighlightLayer';
import { BookmarkButton } from '@/components/nostr/BookmarkButton';
import { Markdown } from './Markdown';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMyBookmarkedArticles } from '@/hooks/useBookmarks';
import {
absoluteTime,
decodeRelayHints,
@@ -32,6 +36,8 @@ import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils';
import type { AppParams, AppProps } from '@/os/types';
type ListScope = 'recent' | 'bookmarked';
const ARTICLE_KIND = 30023;
/** A long-form event is only useful with a body and a `d` identifier (NIP-23). */
@@ -84,6 +90,13 @@ function useArticle(
export default function ArticlesApp({ params, setTitle, setParams }: AppProps) {
const isMobile = useIsMobile();
const { user } = useCurrentUser();
// Signing out mid-session must not strand the reader on a "Bookmarked" tab
// it can no longer see anything in, so the effective scope is derived
// rather than corrected after render — same reasoning as the Feed.
const [requestedScope, setRequestedScope] = useState<ListScope>('recent');
const scope: ListScope = user ? requestedScope : 'recent';
// The selection lives in the window's params rather than local state, so the
// URL, a reload and the switch between the desktop and mobile shells all
@@ -102,7 +115,9 @@ export default function ArticlesApp({ params, setTitle, setParams }: AppProps) {
[setParams],
);
const list = useRecentArticles();
const recent = useRecentArticles();
const bookmarked = useMyBookmarkedArticles();
const list = scope === 'recent' ? recent : bookmarked;
const article = useArticle(
selected?.pubkey,
selected?.identifier,
@@ -116,13 +131,19 @@ export default function ArticlesApp({ params, setTitle, setParams }: AppProps) {
}, [title, setTitle]);
const listPane = (
<ArticleList
query={list}
selected={selected}
onSelect={(event, identifier) =>
select({ pubkey: event.pubkey, identifier, kind: String(event.kind) })
}
/>
<div className="flex h-full min-h-0 flex-col">
<ListScopeTabs scope={requestedScope} disabled={!user} onChange={setRequestedScope} />
<div className="os-scroll min-h-0 flex-1 overflow-y-auto">
<ArticleList
query={list}
scope={scope}
selected={selected}
onSelect={(event, identifier) =>
select({ pubkey: event.pubkey, identifier, kind: String(event.kind) })
}
/>
</div>
</div>
);
const readerPane = !selected ? (
@@ -173,7 +194,19 @@ export default function ArticlesApp({ params, setTitle, setParams }: AppProps) {
<span className="truncate text-[13px] font-medium">
{title ?? 'Long-form articles'}
</span>
{article.data && <CopyArticleLink event={article.data} />}
{article.data && (
<div className="ml-auto flex items-center gap-2">
{tagValue(article.data, 'd') && (
<BookmarkButton
target={{
type: 'a',
value: `${article.data.kind}:${article.data.pubkey}:${tagValue(article.data, 'd')}`,
}}
/>
)}
<CopyArticleLink event={article.data} />
</div>
)}
</AppToolbar>
<AppSplit>
@@ -192,7 +225,7 @@ function CopyArticleLink({ event }: { event: NostrEvent }) {
<Button
variant="ghost"
size="sm"
className="ml-auto h-7 shrink-0 gap-1.5 px-2 text-xs"
className="h-7 shrink-0 gap-1.5 px-2 text-xs"
onClick={async () => {
try {
const naddr = nip19.naddrEncode({
@@ -214,12 +247,74 @@ function CopyArticleLink({ event }: { event: NostrEvent }) {
);
}
function ListScopeTabs({
scope,
disabled,
onChange,
}: {
scope: ListScope;
disabled: boolean;
onChange: (scope: ListScope) => void;
}) {
return (
<div className="flex shrink-0 items-center gap-1 border-b border-border p-2">
<ScopeTab
active={scope === 'recent'}
onClick={() => onChange('recent')}
icon={<Rss className="size-3.5" aria-hidden />}
label="Recent"
/>
<ScopeTab
active={scope === 'bookmarked'}
disabled={disabled}
onClick={() => onChange('bookmarked')}
icon={<Bookmark className="size-3.5" aria-hidden />}
label="Bookmarked"
/>
</div>
);
}
function ScopeTab({
active,
disabled,
onClick,
icon,
label,
}: {
active: boolean;
disabled?: boolean;
onClick: () => void;
icon: React.ReactNode;
label: string;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-pressed={active}
className={cn(
'flex flex-1 items-center justify-center gap-1.5 rounded-md px-2 py-1 text-[12px] font-medium transition-colors',
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
'disabled:cursor-not-allowed disabled:opacity-40',
active ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:bg-muted',
)}
>
{icon}
{label}
</button>
);
}
function ArticleList({
query,
scope,
selected,
onSelect,
}: {
query: ReturnType<typeof useRecentArticles>;
scope: ListScope;
selected: { pubkey: string; identifier: string } | null;
onSelect: (event: NostrEvent, identifier: string) => void;
}) {
@@ -236,14 +331,14 @@ function ArticleList({
if (!query.data || query.data.length === 0) {
return (
<p className="px-3 py-6 text-center text-xs text-muted-foreground">
No articles on your relays.
{scope === 'bookmarked' ? 'You havent bookmarked any articles yet.' : 'No articles on your relays.'}
</p>
);
}
return (
<>
<AppSectionTitle>Recent</AppSectionTitle>
<AppSectionTitle>{scope === 'bookmarked' ? 'Bookmarked' : 'Recent'}</AppSectionTitle>
<ul className="pb-2">
{query.data.map((event) => {
const identifier = tagValue(event, 'd')!;
@@ -319,9 +414,17 @@ function ArticleView({ event }: { event: NostrEvent }) {
)}
</header>
<div className="mt-6 text-[15px]">
<Markdown>{event.content}</Markdown>
</div>
<HighlightLayer
// An empty string (rather than a malformed "kind:pubkey:" address)
// when the article has no `d` tag — HighlightLayer treats a falsy
// address as "highlighting isn't available for this article."
address={tagValue(event, 'd') ? `${event.kind}:${event.pubkey}:${tagValue(event, 'd')}` : ''}
authorPubkey={event.pubkey}
>
<div className="mt-6 text-[15px]">
<Markdown>{event.content}</Markdown>
</div>
</HighlightLayer>
</article>
);
}

View File

@@ -0,0 +1,142 @@
import { useEffect } from 'react';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import { AppBody, AppLayout, AppSectionTitle, AppToolbar, EmptyState } from '@/components/os/AppChrome';
import { LoginRequired } from '@/components/nostr/LoginRequired';
import { NoteCard } from '@/components/nostr/NoteCard';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useAuthor } from '@/hooks/useAuthor';
import { useBookmarkedNoteIds, useMyBookmarkedArticles } from '@/hooks/useBookmarks';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useWindowManager } from '@/os/useWindowManager';
import { displayName, relativeTime, tagValue } from '@/lib/nostrUtils';
import type { AppProps } from '@/os/types';
function useBookmarkedNotes(ids: string[]) {
const { nostr } = useNostr();
return useQuery<NostrEvent[]>({
queryKey: ['nostr', 'bookmarked-notes', ids.join(',')],
enabled: ids.length > 0,
queryFn: async ({ signal }) => {
const events = await nostr.query([{ ids, limit: ids.length }], {
signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]),
});
const order = new Map(ids.map((id, index) => [id, index]));
return [...events].sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));
},
staleTime: 60_000,
});
}
export default function BookmarksApp({ setTitle }: AppProps) {
const { user } = useCurrentUser();
const { openApp } = useWindowManager();
useEffect(() => setTitle('Bookmarks'), [setTitle]);
const noteIds = useBookmarkedNoteIds();
const notes = useBookmarkedNotes(noteIds);
const articles = useMyBookmarkedArticles();
if (!user) {
return <LoginRequired action="see your bookmarks" />;
}
const isLoading = (noteIds.length > 0 && notes.isLoading) || articles.isLoading;
// React Query leaves `data` undefined on a failed query too, so an error
// must be checked before treating "no data" as "no bookmarks" — otherwise
// a relay/network failure reads as an empty list.
const isError = notes.isError || articles.isError;
const isEmpty =
!isLoading && !isError && (notes.data?.length ?? 0) === 0 && (articles.data?.length ?? 0) === 0;
return (
<AppLayout>
<AppToolbar>
<span className="text-[13px] font-medium">Bookmarks</span>
</AppToolbar>
<AppBody>
{isLoading ? (
<div className="space-y-3 p-4">
{Array.from({ length: 4 }).map((_, index) => (
<Skeleton key={index} className="h-16 w-full" />
))}
</div>
) : isError ? (
<EmptyState
title="Couldn't load your bookmarks"
hint="None of your relays responded. Check the Relays app or try again."
action={
<Button
size="sm"
variant="outline"
onClick={() => {
notes.refetch();
articles.refetch();
}}
>
Try again
</Button>
}
/>
) : isEmpty ? (
<EmptyState
title="No bookmarks yet"
hint="Bookmark a note or an article and it will show up here."
/>
) : (
<>
{notes.data && notes.data.length > 0 && (
<>
<AppSectionTitle>Notes</AppSectionTitle>
{notes.data.map((event) => (
<NoteCard key={event.id} event={event} />
))}
</>
)}
{articles.data && articles.data.length > 0 && (
<>
<AppSectionTitle>Articles</AppSectionTitle>
{articles.data.map((event) => (
<ArticleRow
key={event.id}
event={event}
onOpen={() =>
openApp('articles', {
pubkey: event.pubkey,
identifier: tagValue(event, 'd') ?? '',
kind: String(event.kind),
})
}
/>
))}
</>
)}
</>
)}
</AppBody>
</AppLayout>
);
}
function ArticleRow({ event, onOpen }: { event: NostrEvent; onOpen: () => void }) {
const author = useAuthor(event.pubkey);
const title = tagValue(event, 'title') ?? tagValue(event, 'd') ?? 'Untitled';
return (
<button
type="button"
onClick={onOpen}
className="w-full border-b border-border px-4 py-3 text-left transition-colors last:border-b-0 hover:bg-muted/40"
>
<span className="block truncate text-[14px] font-medium">{title}</span>
<span className="mt-0.5 block truncate text-xs text-muted-foreground">
{displayName(event.pubkey, author.data?.metadata)} · {relativeTime(event.created_at)}
</span>
</button>
);
}

View File

@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from 'react';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { Globe, Loader2, Users } from 'lucide-react';
import { FileText, Globe, Loader2, Users } from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
import { AppBody, AppLayout, AppToolbar, EmptyState } from '@/components/os/AppChrome';
import { NoteCard } from '@/components/nostr/NoteCard';
@@ -11,6 +11,8 @@ import { Skeleton } from '@/components/ui/skeleton';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMyFollows } from '@/hooks/useFollows';
import { cn } from '@/lib/utils';
import { useWindowManager } from '@/os/useWindowManager';
import { isReply } from '@/lib/nostrUtils';
import type { AppProps } from '@/os/types';
type Scope = 'following' | 'global';
@@ -20,9 +22,17 @@ const PAGE_SIZE = 50;
/**
* A kind 1 event is only worth rendering if it has something to render. Relays
* happily return blanks and oddities, so the feed validates before it draws.
* Replies (NIP-10 `e` tags) are excluded too: without their parent for
* context they read as indistinguishable, orphaned root posts — open the
* thread from the Note app instead.
*/
function isRenderableNote(event: NostrEvent): boolean {
return event.kind === 1 && typeof event.content === 'string' && event.content.trim().length > 0;
return (
event.kind === 1 &&
typeof event.content === 'string' &&
event.content.trim().length > 0 &&
!isReply(event)
);
}
function useFeed(scope: Scope, authors: string[] | undefined) {
@@ -51,6 +61,7 @@ function useFeed(scope: Scope, authors: string[] | undefined) {
export default function FeedApp({ setTitle }: AppProps) {
const { user } = useCurrentUser();
const { openApp } = useWindowManager();
const { data: follows } = useMyFollows();
const [requestedScope, setScope] = useState<Scope>('following');
@@ -85,6 +96,15 @@ export default function FeedApp({ setTitle }: AppProps) {
/>
<div className="ml-auto flex items-center gap-2">
{query.isFetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" aria-hidden />}
<Button
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 text-xs"
onClick={() => openApp('notes')}
>
<FileText className="size-3.5" aria-hidden />
New note
</Button>
<Button
variant="ghost"
size="sm"

107
src/apps/notes/Draft.tsx Normal file
View File

@@ -0,0 +1,107 @@
import { useState } from 'react';
import { Loader2, Send, Trash2 } from 'lucide-react';
import { AppBody, AppLayout, AppToolbar } from '@/components/os/AppChrome';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
const DRAFT_KEY = 'layer-os:draft-note';
/**
* A blank note kept as a local draft — not published until you say so, and
* not lost between sessions or windows in the meantime. This is the "open a
* new note" entry point (reachable from the Go menu, the command palette,
* and the Feed toolbar) for writing something before deciding it is worth
* publishing.
*/
export function DraftNote({ onPublished }: { onPublished: (id: string) => void }) {
const { user } = useCurrentUser();
const [draft, setDraft] = useLocalStorage(DRAFT_KEY, '');
const publish = useNostrPublish();
const { toast } = useToast();
const [confirmingDiscard, setConfirmingDiscard] = useState(false);
const trimmed = draft.trim();
const handlePublish = async () => {
// Guarded here too, not just via the button's `disabled` — React hasn't
// necessarily re-rendered with publish.isPending yet when a second click
// lands in the same tick, and mutateAsync itself doesn't dedupe calls.
if (!trimmed || publish.isPending) return;
try {
const event = await publish.mutateAsync({ kind: 1, content: trimmed, tags: [] });
setDraft('');
toast({ title: 'Note published' });
onPublished(event.id);
} catch (error) {
toast({
title: 'Could not publish',
description: error instanceof Error ? error.message : 'No relay accepted the note.',
variant: 'destructive',
});
}
};
const handleDiscard = () => {
if (!confirmingDiscard) {
setConfirmingDiscard(true);
return;
}
setDraft('');
setConfirmingDiscard(false);
};
return (
<AppLayout>
<AppToolbar>
<span className="text-[13px] font-medium">New Note</span>
<div className="ml-auto flex items-center gap-2">
{draft && (
<Button
variant="ghost"
size="sm"
className="h-7 gap-1.5 px-2 text-xs text-muted-foreground"
onClick={handleDiscard}
onBlur={() => setConfirmingDiscard(false)}
>
<Trash2 className="size-3.5" aria-hidden />
{confirmingDiscard ? 'Click again to discard' : 'Discard draft'}
</Button>
)}
{user && (
<Button
size="sm"
className="h-7 gap-1.5 px-2.5 text-xs"
onClick={handlePublish}
disabled={!trimmed || publish.isPending}
>
{publish.isPending ? (
<Loader2 className="size-3.5 animate-spin" aria-hidden />
) : (
<Send className="size-3.5" aria-hidden />
)}
Publish
</Button>
)}
</div>
</AppToolbar>
<AppBody className="flex flex-col p-4">
<Textarea
value={draft}
onChange={(event) => setDraft(event.target.value)}
placeholder={
user
? 'Write something… its kept as a local draft until you publish it.'
: 'Write something… its kept as a local draft on this device. Sign in to publish it.'
}
autoFocus
className="min-h-40 flex-1 resize-none border-0 bg-transparent p-0 text-[15px] leading-relaxed shadow-none focus-visible:ring-0"
/>
</AppBody>
</AppLayout>
);
}

View File

@@ -8,6 +8,7 @@ import { AuthorLine } from '@/components/nostr/AuthorLine';
import { NoteContent } from '@/components/nostr/NoteContent';
import { NoteCard } from '@/components/nostr/NoteCard';
import { Composer } from '@/apps/feed/Composer';
import { DraftNote } from './Draft';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -51,7 +52,7 @@ function useReplies(id: string | undefined, relays: string[] | undefined) {
});
}
export default function NotesApp({ params, setTitle }: AppProps) {
export default function NotesApp({ params, setTitle, setParams }: AppProps) {
const { user } = useCurrentUser();
const id = params.id;
const relays = decodeRelayHints(params.relays);
@@ -62,11 +63,11 @@ export default function NotesApp({ params, setTitle }: AppProps) {
const name = note.data ? displayName(note.data.pubkey, author.data?.metadata) : undefined;
useEffect(() => {
setTitle(name ? `Note by ${name}` : 'Note');
}, [name, setTitle]);
setTitle(id ? (name ? `Note by ${name}` : 'Note') : 'New Note');
}, [id, name, setTitle]);
if (!id) {
return <EmptyState title="No note selected" hint="Open a note from the feed to read its thread." />;
return <DraftNote onPublished={(publishedId) => setParams({ ...params, id: publishedId })} />;
}
if (note.isLoading) {

View File

@@ -14,9 +14,14 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMyFollows } from '@/hooks/useFollows';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { decodeRelayHints, displayName, npubOf, sanitizeUrl } from '@/lib/nostrUtils';
import { decodeRelayHints, displayName, isReply, npubOf, sanitizeUrl } from '@/lib/nostrUtils';
import type { AppProps } from '@/os/types';
/**
* Replies are excluded here for the same reason as the Feed: without their
* parent for context, a reply on a profile's timeline reads as an orphaned
* root post rather than what it is.
*/
function useAuthorNotes(pubkey: string | undefined, relays: string[] | undefined) {
const { nostr } = useNostr();
@@ -29,7 +34,7 @@ function useAuthorNotes(pubkey: string | undefined, relays: string[] | undefined
{ signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]), relays },
);
return events
.filter((event) => event.content.trim().length > 0)
.filter((event) => event.content.trim().length > 0 && !isReply(event))
.sort((a, b) => b.created_at - a.created_at);
},
staleTime: 60_000,

View File

@@ -0,0 +1,51 @@
import { Bookmark, BookmarkCheck, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { isBookmarked, useBookmarkedTargets, useToggleBookmark, type BookmarkTarget } from '@/hooks/useBookmarks';
import { cn } from '@/lib/utils';
/** Toggles `target` in and out of the signed-in user's NIP-51 bookmark list. */
export function BookmarkButton({ target, className }: { target: BookmarkTarget; className?: string }) {
const { user } = useCurrentUser();
const targets = useBookmarkedTargets();
const toggle = useToggleBookmark();
const { toast } = useToast();
if (!user) return null;
const bookmarked = isBookmarked(targets, target);
const handleClick = async () => {
try {
await toggle.mutateAsync(target);
} catch (error) {
toast({
title: bookmarked ? 'Could not remove bookmark' : 'Could not bookmark',
description: error instanceof Error ? error.message : 'No relay accepted the update.',
variant: 'destructive',
});
}
};
return (
<Button
type="button"
variant="ghost"
size="sm"
className={cn('h-7 gap-1.5 px-2 text-xs text-muted-foreground', bookmarked && 'text-primary', className)}
onClick={handleClick}
disabled={toggle.isPending}
aria-pressed={bookmarked}
>
{toggle.isPending ? (
<Loader2 className="size-3.5 animate-spin" aria-hidden />
) : bookmarked ? (
<BookmarkCheck className="size-3.5" aria-hidden />
) : (
<Bookmark className="size-3.5" aria-hidden />
)}
{bookmarked ? 'Bookmarked' : 'Bookmark'}
</Button>
);
}

View File

@@ -3,6 +3,7 @@ import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { AuthorLine } from './AuthorLine';
import { NoteContent } from './NoteContent';
import { BookmarkButton } from './BookmarkButton';
import { Button } from '@/components/ui/button';
import { useWindowManager } from '@/os/useWindowManager';
import { useToast } from '@/hooks/useToast';
@@ -69,6 +70,7 @@ export function NoteCard({ event, compact, className }: NoteCardProps) {
<Repeat2 className="size-3.5" aria-hidden />
Copy link
</Button>
<BookmarkButton target={{ type: 'e', value: event.id }} />
</div>
)}
</div>

163
src/hooks/useBookmarks.ts Normal file
View File

@@ -0,0 +1,163 @@
import { useMemo } from 'react';
import { useNostr } from '@nostrify/react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import { useCurrentUser } from './useCurrentUser';
import { useNostrPublish } from './useNostrPublish';
import { tagValue } from '@/lib/nostrUtils';
const ARTICLE_KIND = 30023;
/** NIP-51 "Bookmarks": an uncategorized, global, replaceable list per user. */
export const BOOKMARK_LIST_KIND = 10003;
export interface BookmarkTarget {
/** `e` for a kind-1 note, `a` for an addressable event (e.g. a NIP-23 article). */
type: 'e' | 'a';
/** An event id for `e`, or `kind:pubkey:d-identifier` for `a`. */
value: string;
}
function bookmarkQueryKey(pubkey: string | undefined) {
return ['nostr', 'bookmarks', pubkey ?? ''] as const;
}
async function fetchBookmarkList(
nostr: ReturnType<typeof useNostr>['nostr'],
pubkey: string,
signal?: AbortSignal,
): Promise<NostrEvent | null> {
const [event] = await nostr.query(
[{ kinds: [BOOKMARK_LIST_KIND], authors: [pubkey], limit: 1 }],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(6000)].filter((s): s is AbortSignal => Boolean(s))) },
);
return event ?? null;
}
/** The current user's kind 10003 bookmark list, or null if they don't have one yet. */
export function useBookmarkList() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useQuery<NostrEvent | null>({
queryKey: bookmarkQueryKey(user?.pubkey),
enabled: Boolean(user),
queryFn: ({ signal }) => fetchBookmarkList(nostr, user!.pubkey, signal),
staleTime: 60_000,
});
}
/** The list's public `e`/`a` entries, in the shape a `BookmarkButton` checks against. */
export function useBookmarkedTargets(): BookmarkTarget[] {
const { data } = useBookmarkList();
if (!data) return [];
return data.tags
.filter((tag): tag is [string, string] => (tag[0] === 'e' || tag[0] === 'a') && Boolean(tag[1]))
.map(([type, value]) => ({ type: type as 'e' | 'a', value }));
}
export function isBookmarked(targets: BookmarkTarget[], target: BookmarkTarget): boolean {
return targets.some((t) => t.type === target.type && t.value === target.value);
}
/**
* Adds or removes one target from the bookmark list. Fetches the list fresh
* from relays right before writing — kind 10003 is a whole-list replacement,
* so publishing against a stale cached copy (the query's staleTime is 60s)
* could silently drop entries added from another tab or device in the
* meantime, the same trap NIP-02 follow lists have.
*/
export function useToggleBookmark() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const publish = useNostrPublish();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (target: BookmarkTarget) => {
if (!user) throw new Error('Sign in to bookmark');
const current = await fetchBookmarkList(nostr, user.pubkey);
const currentTags = current?.tags ?? [];
const already = currentTags.some(([name, value]) => name === target.type && value === target.value);
const tags = already
? currentTags.filter(([name, value]) => !(name === target.type && value === target.value))
: [...currentTags, [target.type, target.value]];
return publish.mutateAsync({
kind: BOOKMARK_LIST_KIND,
content: current?.content ?? '',
tags,
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: bookmarkQueryKey(user?.pubkey) });
},
});
}
interface ParsedAddress {
kind: number;
pubkey: string;
identifier: string;
}
/**
* Parses a NIP-01 `kind:pubkey:d-identifier` address tag value, or null if
* malformed — including an empty identifier, which would otherwise produce
* a `#d: ['']` relay query and a bookmark nothing can reliably resolve.
*/
function parseAddress(address: string): ParsedAddress | null {
const [kindPart, pubkey, ...rest] = address.split(':');
const kind = Number(kindPart);
const identifier = rest.join(':');
if (!Number.isInteger(kind) || !pubkey || !identifier) return null;
return { kind, pubkey, identifier };
}
/** The current user's bookmarked note ids (`e` tags), skipping any malformed entries. */
export function useBookmarkedNoteIds(): string[] {
const targets = useBookmarkedTargets();
return useMemo(
() => targets.filter((t) => t.type === 'e').map((t) => t.value),
[targets],
);
}
/**
* The current user's bookmarked NIP-23 articles, fetched and narrowed back
* down to the exact `kind:pubkey:d` triples bookmarked — the relay filter
* can only constrain by kind/author/`d`, not the full address.
*/
export function useMyBookmarkedArticles() {
const { nostr } = useNostr();
const targets = useBookmarkedTargets();
const addresses = useMemo(() => targets.filter((t) => t.type === 'a').map((t) => t.value), [targets]);
const parsed = useMemo(
() =>
addresses
.map(parseAddress)
.filter((a): a is ParsedAddress => a !== null && a.kind === ARTICLE_KIND),
[addresses],
);
const authors = useMemo(() => [...new Set(parsed.map((a) => a.pubkey))], [parsed]);
const dTags = useMemo(() => [...new Set(parsed.map((a) => a.identifier))], [parsed]);
return useQuery<NostrEvent[]>({
queryKey: ['nostr', 'bookmarked-articles', addresses.join(',')],
enabled: parsed.length > 0,
queryFn: async ({ signal }) => {
const events = await nostr.query(
[{ kinds: [ARTICLE_KIND], authors, '#d': dTags, limit: parsed.length * 2 }],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]) },
);
const wanted = new Set(addresses);
return events.filter(
(event) =>
wanted.has(`${event.kind}:${event.pubkey}:${tagValue(event, 'd')}`) &&
event.content.trim().length > 0,
);
},
staleTime: 60_000,
});
}

View File

@@ -0,0 +1,61 @@
import { useNostr } from '@nostrify/react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import { useNostrPublish } from './useNostrPublish';
/** NIP-84 "Highlights": a highlighted excerpt of a nostr event or other content. */
export const HIGHLIGHT_KIND = 9802;
function queryKey(address: string) {
return ['nostr', 'highlights', address] as const;
}
/** Highlights tagged to an addressable event, e.g. a NIP-23 article's `kind:pubkey:d`. */
export function useHighlights(address: string | undefined) {
const { nostr } = useNostr();
return useQuery<NostrEvent[]>({
queryKey: queryKey(address ?? ''),
enabled: Boolean(address),
queryFn: async ({ signal }) => {
const events = await nostr.query(
[{ kinds: [HIGHLIGHT_KIND], '#a': [address!], limit: 100 }],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(6000)]) },
);
return events
.filter((event) => event.content.trim().length > 0)
.sort((a, b) => b.created_at - a.created_at);
},
staleTime: 30_000,
});
}
export interface CreateHighlightInput {
/** The highlighted excerpt itself. */
text: string;
/** `kind:pubkey:d-identifier` of the article being highlighted. */
address: string;
/** The article's author, tagged per NIP-84 so the highlight credits them. */
authorPubkey: string;
}
export function useCreateHighlight() {
const publish = useNostrPublish();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ text, address, authorPubkey }: CreateHighlightInput) => {
return publish.mutateAsync({
kind: HIGHLIGHT_KIND,
content: text,
tags: [
['a', address],
['p', authorPubkey, '', 'author'],
],
});
},
onSuccess: (_data, { address }) => {
queryClient.invalidateQueries({ queryKey: queryKey(address) });
},
});
}

View File

@@ -1,4 +1,19 @@
import { useState, useEffect } from 'react';
import { useCallback, useEffect, useState } from 'react';
/**
* Fired on `window` whenever `useLocalStorage` writes a key, so every
* component sharing that key *within this document* stays in sync — the
* native `storage` event only fires in *other* tabs/documents, never the
* one that made the write. Without this, e.g. two "New Note" draft windows
* open at once would silently diverge: each holds its own React state, both
* write to the same localStorage entry, and neither sees the other's edits.
*/
const LOCAL_STORAGE_EVENT = 'app:local-storage';
interface LocalStorageEventDetail {
key: string;
value: string;
}
/**
* Generic hook for managing localStorage state
@@ -24,17 +39,30 @@ export function useLocalStorage<T>(
}
});
const setValue = (value: T | ((prev: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(state) : value;
setState(valueToStore);
localStorage.setItem(key, serialize(valueToStore));
} catch (error) {
console.warn(`Failed to save ${key} to localStorage:`, error);
}
};
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setState((prev) => {
try {
const valueToStore = value instanceof Function ? value(prev) : value;
const serialized = serialize(valueToStore);
localStorage.setItem(key, serialized);
window.dispatchEvent(
new CustomEvent<LocalStorageEventDetail>(LOCAL_STORAGE_EVENT, {
detail: { key, value: serialized },
}),
);
return valueToStore;
} catch (error) {
console.warn(`Failed to save ${key} to localStorage:`, error);
return prev;
}
});
},
[key, serialize],
);
// Sync with localStorage changes from other tabs
// Sync with localStorage changes from other tabs, and from other
// components sharing this key in this tab (see LOCAL_STORAGE_EVENT above).
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
@@ -45,10 +73,23 @@ export function useLocalStorage<T>(
}
}
};
const handleLocalChange = (e: Event) => {
const detail = (e as CustomEvent<LocalStorageEventDetail>).detail;
if (detail?.key !== key) return;
try {
setState(deserialize(detail.value));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
window.addEventListener(LOCAL_STORAGE_EVENT, handleLocalChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener(LOCAL_STORAGE_EVENT, handleLocalChange);
};
}, [key, deserialize]);
return [state, setValue] as const;
}
}

View File

@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';
import type { NostrEvent } from '@nostrify/nostrify';
import { isReply, rootReference } from './nostrUtils';
function note(tags: string[][]): NostrEvent {
return {
id: 'x',
pubkey: 'y',
created_at: 0,
kind: 1,
tags,
content: 'hello',
sig: '',
};
}
describe('isReply', () => {
it('is false for a root note with no e tag', () => {
expect(isReply(note([]))).toBe(false);
});
it('is true for a note with a marked root e tag', () => {
expect(isReply(note([['e', 'root-id', '', 'root']]))).toBe(true);
});
it('is true for a note using the deprecated positional e tag', () => {
expect(isReply(note([['e', 'parent-id']]))).toBe(true);
});
it('is false for a note that only mentions another event', () => {
expect(isReply(note([['e', 'mentioned-id', '', 'mention']]))).toBe(false);
});
it('is true for a note with a mention alongside a marked reply', () => {
expect(
isReply(
note([
['e', 'root-id', '', 'root'],
['e', 'mentioned-id', '', 'mention'],
]),
),
).toBe(true);
});
});
describe('rootReference', () => {
it('prefers the marked root tag over positional ones', () => {
const event = note([
['e', 'mention-id', '', 'mention'],
['e', 'root-id', '', 'root'],
]);
expect(rootReference(event)).toBe('root-id');
});
it('falls back to the first positional e tag per the deprecated scheme', () => {
const event = note([
['e', 'root-id'],
['e', 'reply-id'],
]);
expect(rootReference(event)).toBe('root-id');
});
it('is undefined for a root note', () => {
expect(rootReference(note([]))).toBeUndefined();
});
it('is undefined for a note that only mentions another event', () => {
expect(rootReference(note([['e', 'mentioned-id', '', 'mention']]))).toBeUndefined();
});
it('ignores a mention when falling back to the positional scheme', () => {
const event = note([
['e', 'mentioned-id', '', 'mention'],
['e', 'root-id'],
]);
expect(rootReference(event)).toBe('root-id');
});
});

View File

@@ -93,15 +93,25 @@ export function tagValues(event: NostrEvent, name: string): string[] {
/**
* The event a reply points at, following NIP-10: prefer an explicit `root`
* marker, fall back to the last positional `e` tag.
* marker, fall back to the first *unmarked* `e` tag (the deprecated scheme
* puts the root id first: `["e", <root-id>], ["e", <reply-id>]`). A `mention`
* or `reply`-only marker is never treated as the root — a mention isn't
* part of the thread, and a lone `reply` marker without `root` is malformed
* per NIP-10 rather than an implicit root.
*/
export function rootReference(event: NostrEvent): string | undefined {
const marked = event.tags.find(([name, , , marker]) => name === 'e' && marker === 'root');
if (marked) return marked[1];
const positional = event.tags.filter(([name]) => name === 'e');
const positional = event.tags.filter(([name, , , marker]) => name === 'e' && !marker);
return positional[0]?.[1];
}
/**
* True for a reply per NIP-10: a marked `root`/`reply` `e` tag, or an
* unmarked one (the deprecated positional scheme). An `e` tag marked
* `mention` alone does not make an event a reply — it cites another event
* without being part of its thread.
*/
export function isReply(event: NostrEvent): boolean {
return event.tags.some(([name]) => name === 'e');
return event.tags.some(([name, , , marker]) => name === 'e' && marker !== 'mention');
}

View File

@@ -1,5 +1,5 @@
import { lazy } from 'react';
import { Activity, BookOpen, FileText, Info, Link2, Rss, Settings, User } from 'lucide-react';
import { Activity, Bookmark, BookOpen, FileText, Info, Link2, Rss, Settings, User } from 'lucide-react';
import type { AppDefinition } from './types';
/**
@@ -49,6 +49,16 @@ export const APPS: AppDefinition[] = [
defaultSize: { width: 780, height: 760 },
minSize: { width: 360, height: 320 },
},
{
id: 'bookmarks',
title: 'Bookmarks',
description: 'Notes and articles you have saved',
icon: Bookmark,
category: 'social',
component: lazy(() => import('@/apps/bookmarks')),
defaultSize: { width: 600, height: 660 },
minSize: { width: 340, height: 300 },
},
{
id: 'web-bookmarks',
title: 'Web Bookmarks',