Merge branch 'main' into feat/bookmarks-nip51

This commit is contained in:
2026-09-06 18:44:12 +02:00
8 changed files with 287 additions and 25 deletions

View File

@@ -95,7 +95,7 @@ export default function ExampleApp({ setTitle }: AppProps) {
|---|---|---|---|
| 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 |
| 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` |
| Bookmarks | `bookmarks` | — | NIP-51 kind 10003 list — bookmarked notes and articles |
| Relays | `relays` | — | Connection state, subscription count, measured latency |

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

@@ -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');
}