diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4dd3cc2 --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +# Alexandria Environment Variables + +# Enable mock data for development/testing +# Set to "true" to use lorem ipsum test comments instead of fetching from relays +VITE_USE_MOCK_COMMENTS=true + +# Set to "true" to use position-based test highlights instead of fetching from relays +VITE_USE_MOCK_HIGHLIGHTS=true + +# Enable debug logging for relay connections +DEBUG_RELAYS=false diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-complete.png b/.playwright-mcp/.playwright-mcp/dark-mode-complete.png new file mode 100644 index 0000000..2a48cd2 Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-complete.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-editor-fix.png b/.playwright-mcp/.playwright-mcp/dark-mode-editor-fix.png new file mode 100644 index 0000000..37c9915 Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-editor-fix.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-final.png b/.playwright-mcp/.playwright-mcp/dark-mode-final.png new file mode 100644 index 0000000..37c9915 Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-final.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-preview-update.png b/.playwright-mcp/.playwright-mcp/dark-mode-preview-update.png new file mode 100644 index 0000000..989a81d Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-preview-update.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-text-fix.png b/.playwright-mcp/.playwright-mcp/dark-mode-text-fix.png new file mode 100644 index 0000000..40118ff Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-text-fix.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-white-text.png b/.playwright-mcp/.playwright-mcp/dark-mode-white-text.png new file mode 100644 index 0000000..6212885 Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-white-text.png differ diff --git a/.playwright-mcp/.playwright-mcp/dark-mode-with-preview.png b/.playwright-mcp/.playwright-mcp/dark-mode-with-preview.png new file mode 100644 index 0000000..16c7c1f Binary files /dev/null and b/.playwright-mcp/.playwright-mcp/dark-mode-with-preview.png differ diff --git a/.playwright-mcp/500-error.png b/.playwright-mcp/500-error.png new file mode 100644 index 0000000..8943004 Binary files /dev/null and b/.playwright-mcp/500-error.png differ diff --git a/.playwright-mcp/after-delete-integration.png b/.playwright-mcp/after-delete-integration.png new file mode 100644 index 0000000..29e4360 Binary files /dev/null and b/.playwright-mcp/after-delete-integration.png differ diff --git a/.playwright-mcp/after-fix.png b/.playwright-mcp/after-fix.png new file mode 100644 index 0000000..8af33ef Binary files /dev/null and b/.playwright-mcp/after-fix.png differ diff --git a/.playwright-mcp/after-mock-comments-click.png b/.playwright-mcp/after-mock-comments-click.png new file mode 100644 index 0000000..1522aac Binary files /dev/null and b/.playwright-mcp/after-mock-comments-click.png differ diff --git a/.playwright-mcp/compose-darkmode-preview.png b/.playwright-mcp/compose-darkmode-preview.png new file mode 100644 index 0000000..1919b44 Binary files /dev/null and b/.playwright-mcp/compose-darkmode-preview.png differ diff --git a/.playwright-mcp/dark-mode-full-preview.png b/.playwright-mcp/dark-mode-full-preview.png new file mode 100644 index 0000000..05191e5 Binary files /dev/null and b/.playwright-mcp/dark-mode-full-preview.png differ diff --git a/.playwright-mcp/dark-mode-preview-after.png b/.playwright-mcp/dark-mode-preview-after.png new file mode 100644 index 0000000..83b4639 Binary files /dev/null and b/.playwright-mcp/dark-mode-preview-after.png differ diff --git a/.playwright-mcp/debug-controls-fixed.png b/.playwright-mcp/debug-controls-fixed.png new file mode 100644 index 0000000..8178acc Binary files /dev/null and b/.playwright-mcp/debug-controls-fixed.png differ diff --git a/.playwright-mcp/highlights-visible.png b/.playwright-mcp/highlights-visible.png new file mode 100644 index 0000000..383dbf6 Binary files /dev/null and b/.playwright-mcp/highlights-visible.png differ diff --git a/.playwright-mcp/homepage-loaded.png b/.playwright-mcp/homepage-loaded.png new file mode 100644 index 0000000..85602f3 Binary files /dev/null and b/.playwright-mcp/homepage-loaded.png differ diff --git a/.playwright-mcp/homepage-state.png b/.playwright-mcp/homepage-state.png new file mode 100644 index 0000000..1509d08 Binary files /dev/null and b/.playwright-mcp/homepage-state.png differ diff --git a/.playwright-mcp/offset-highlights-rendered.png b/.playwright-mcp/offset-highlights-rendered.png new file mode 100644 index 0000000..5215b19 Binary files /dev/null and b/.playwright-mcp/offset-highlights-rendered.png differ diff --git a/.playwright-mcp/offset-highlights-scrolled.png b/.playwright-mcp/offset-highlights-scrolled.png new file mode 100644 index 0000000..373dc29 Binary files /dev/null and b/.playwright-mcp/offset-highlights-scrolled.png differ diff --git a/.playwright-mcp/offset-highlights-test-page.png b/.playwright-mcp/offset-highlights-test-page.png new file mode 100644 index 0000000..5837ea4 Binary files /dev/null and b/.playwright-mcp/offset-highlights-test-page.png differ diff --git a/.playwright-mcp/preview-area.png b/.playwright-mcp/preview-area.png new file mode 100644 index 0000000..25d4414 Binary files /dev/null and b/.playwright-mcp/preview-area.png differ diff --git a/.playwright-mcp/publication-with-debug-controls.png b/.playwright-mcp/publication-with-debug-controls.png new file mode 100644 index 0000000..989eaf0 Binary files /dev/null and b/.playwright-mcp/publication-with-debug-controls.png differ diff --git a/.playwright-mcp/scrolled-with-comments.png b/.playwright-mcp/scrolled-with-comments.png new file mode 100644 index 0000000..7d8c987 Binary files /dev/null and b/.playwright-mcp/scrolled-with-comments.png differ diff --git a/.playwright-mcp/with-mock-highlights.png b/.playwright-mcp/with-mock-highlights.png new file mode 100644 index 0000000..cdcb368 Binary files /dev/null and b/.playwright-mcp/with-mock-highlights.png differ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..febc469 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,184 @@ +# Alexandria Codebase - Local Instructions + +This document provides project-specific instructions for working with the Alexandria codebase, based on existing Cursor rules and project conventions. + +## Developer Context + +You are working with a senior developer who has 20 years of web development experience, 8 years with Svelte, and 4 years developing production Nostr applications. Assume high technical proficiency. + +## Project Overview + +Alexandria is a Nostr-based web application for reading, commenting on, and publishing long-form content (books, blogs, etc.) stored on Nostr relays. Built with: + +- **Svelte 5** and **SvelteKit 2** (latest versions) +- **TypeScript** (exclusively, no plain JavaScript) +- **Tailwind 4** for styling +- **Deno** runtime (with Node.js compatibility) +- **NDK** (Nostr Development Kit) for protocol interaction + +## Architecture Pattern + +The project follows a Model-View-Controller (MVC) pattern: + +- **Model**: Nostr relays (via WebSocket APIs) and browser storage +- **View**: Reactive UI with SvelteKit pages and Svelte components +- **Controller**: TypeScript modules with utilities, services, and data preparation + +## Critical Development Guidelines + +### Prime Directive + +**NEVER assume developer intent.** If unsure, ALWAYS ask for clarification before proceeding. + +### AI Anchor Comments System + +Before any work, search for `AI-` anchor comments in relevant directories: + +- `AI-NOTE:`, `AI-TODO:`, `AI-QUESTION:` - Context sharing between AI and developers +- `AI-:` - Developer-recorded context (read but don't write) +- **Always update relevant anchor comments when modifying code** +- Add new anchors for complex, critical, or confusing code +- Never remove AI comments without explicit instruction + +### Communication Style + +- Be direct and concise - avoid apologies or verbose explanations +- Include file names and line numbers (e.g., `src/lib/utils/parser.ts:45-52`) +- Provide documentation links for further reading +- When corrected, provide well-reasoned explanations, not simple agreement +- Don't propose code edits unless specifically requested + +## Code Style Requirements + +### TypeScript Files (\*.ts) + +- **File naming**: `snake_case.ts` +- **Classes/Interfaces/Types**: `PascalCase` +- **Functions/Variables**: `camelCase` +- **Private class members**: `#privateField` (ES2022 syntax) +- **Indentation**: 2 spaces +- **Line length**: 100 characters max +- **Strings**: Single quotes default, backticks for templates +- **Always include**: + - Type annotations for class properties + - Parameter types and return types (except void) + - JSDoc comments for exported functions + - Semicolons at statement ends + +### Svelte Components (\*.svelte) + +- **Component naming**: `PascalCase.svelte` +- **Use Svelte 5 features exclusively**: + - Runes: `$state`, `$derived`, `$effect`, `$props` + - Callback props (not event dispatchers) + - Snippets (not slots) +- **Avoid deprecated Svelte 4 patterns**: + - No `export let` for props + - No `on:` event directives + - No event dispatchers or component slots +- **Component organization** (in order): + 1. Imports + 2. Props definition (strongly typed) + 3. Context imports (`getContext`) + 4. State declarations (`$state`, then `$derived`) + 5. Non-reactive variables + 6. Component logic (functions, `$effect`) + 7. Lifecycle hooks (`onMount`) + 8. Snippets (before markup) + 9. Component markup + 10. Style blocks (rare - prefer Tailwind) +- **Keep components under 500 lines** +- **Extract business logic to separate TypeScript modules** + +### HTML/Markup + +- Indentation: 2 spaces +- Break long tags across lines +- Use Tailwind 4 utility classes +- Single quotes for attributes + +## Key Project Utilities + +### Core Classes to Use + +- `WebSocketPool` (`src/lib/data_structures/websocket_pool.ts`) - For WebSocket management +- `PublicationTree` - For hierarchical publication structure +- `ZettelParser` - For AsciiDoc parsing + +### Nostr Event Kinds + +- `30040` - Blog/publication indexes +- `30041` - Publication sections/articles +- `30023` - Long-form articles +- `30818` - Wiki Notes +- `1` - Short notes + +## Development Commands + +```bash +# Development +npm run dev # Start dev server +npm run dev:debug # With relay debugging (DEBUG_RELAYS=true) + +# Quality Checks (run before commits) +npm run check # Type checking +npm run lint # Linting +npm run format # Auto-format +npm test # Run tests + +# Build +npm run build # Production build +npm run preview # Preview production +``` + +## Testing Requirements + +- Unit tests: Vitest with mocked dependencies +- E2E tests: Playwright for critical flows +- Always run `npm test` before commits +- Check types with `npm run check` + +## Git Workflow + +- Current branch: `feature/text-entry` +- Main branch: `master` (not `main`) +- Descriptive commit messages +- Include test updates with features + +## Important Files + +- `src/lib/ndk.ts` - NDK configuration +- `src/lib/utils/ZettelParser.ts` - AsciiDoc parsing +- `src/lib/services/publisher.ts` - Event publishing +- `src/lib/components/ZettelEditor.svelte` - Main editor +- `src/routes/new/compose/+page.svelte` - Composition UI + +## Performance Considerations + +- State is deeply reactive in Svelte 5 - avoid unnecessary reassignments +- Lazy load large components +- Use virtual scrolling for long lists +- Cache Nostr events with Dexie +- Minimize relay subscriptions +- Debounce search inputs + +## Security Notes + +- Never store private keys in code +- Validate all user input +- Sanitize external HTML +- Verify event signatures + +## Debugging + +- Enable relay debug: `DEBUG_RELAYS=true npm run dev` +- Check browser console for NDK logs +- Network tab shows WebSocket frames + +## Documentation Links + +- [Nostr NIPs](https://github.com/nostr-protocol/nips) +- [NDK Docs](https://github.com/nostr-dev-kit/ndk) +- [SvelteKit Docs](https://kit.svelte.dev/docs) +- [Svelte 5 Docs](https://svelte.dev/docs/svelte/overview) +- [Flowbite Svelte](https://flowbite-svelte.com/) diff --git a/TECHNIQUE-create-test-highlights.md b/TECHNIQUE-create-test-highlights.md new file mode 100644 index 0000000..17426d8 --- /dev/null +++ b/TECHNIQUE-create-test-highlights.md @@ -0,0 +1,373 @@ +# Technique: Creating Test Highlight Events for Nostr Publications + +## Overview + +This technique allows you to create test highlight events (kind 9802) for testing the highlight rendering system in Alexandria. Highlights are text selections from publication sections that users want to mark as important or noteworthy, optionally with annotations. + +## When to Use This + +- Testing highlight fetching and rendering +- Verifying highlight filtering by section +- Testing highlight display UI (inline markers, side panel, etc.) +- Debugging highlight-related features +- Demonstrating the highlight system to stakeholders + +## Prerequisites + +1. **Node.js packages**: `nostr-tools` and `ws` + ```bash + npm install nostr-tools ws + ``` + +2. **Valid publication structure**: You need the actual publication address (naddr) and its internal structure (section addresses, pubkeys) + +## Step 1: Decode the Publication Address + +If you have an `naddr` (Nostr address), decode it to find the publication structure: + +**Script**: `check-publication-structure.js` + +```javascript +import { nip19 } from 'nostr-tools'; +import WebSocket from 'ws'; + +const naddr = 'naddr1qvzqqqr4t...'; // Your publication naddr + +console.log('Decoding naddr...\n'); +const decoded = nip19.decode(naddr); +console.log('Decoded:', JSON.stringify(decoded, null, 2)); + +const { data } = decoded; +const rootAddress = `${data.kind}:${data.pubkey}:${data.identifier}`; +console.log('\nRoot Address:', rootAddress); + +// Fetch the index event to see what sections it references +const relay = 'wss://relay.nostr.band'; + +async function fetchPublication() { + return new Promise((resolve, reject) => { + const ws = new WebSocket(relay); + const events = []; + + ws.on('open', () => { + console.log(`\nConnected to ${relay}`); + console.log('Fetching index event...\n'); + + const filter = { + kinds: [data.kind], + authors: [data.pubkey], + '#d': [data.identifier], + }; + + const subscriptionId = `sub-${Date.now()}`; + ws.send(JSON.stringify(['REQ', subscriptionId, filter])); + }); + + ws.on('message', (message) => { + const [type, subId, event] = JSON.parse(message.toString()); + + if (type === 'EVENT') { + events.push(event); + console.log('Found index event:', event.id); + console.log('\nTags:'); + event.tags.forEach(tag => { + if (tag[0] === 'a') { + console.log(` Section address: ${tag[1]}`); + } + if (tag[0] === 'd') { + console.log(` D-tag: ${tag[1]}`); + } + if (tag[0] === 'title') { + console.log(` Title: ${tag[1]}`); + } + }); + } else if (type === 'EOSE') { + ws.close(); + resolve(events); + } + }); + + ws.on('error', reject); + + setTimeout(() => { + ws.close(); + resolve(events); + }, 5000); + }); +} + +fetchPublication() + .then(() => console.log('\nDone!')) + .catch(console.error); +``` + +**Run it**: `node check-publication-structure.js` + +**Expected output**: Section addresses like `30041:dc4cd086...:the-art-of-thinking-without-permission` + +## Step 2: Understand Kind 9802 Event Structure + +A highlight event (kind 9802) has this structure: + +```javascript +{ + kind: 9802, + pubkey: "", + created_at: 1704067200, + tags: [ + ["a", "", ""], // Required: target section + ["context", ""], // Optional: helps locate highlight + ["p", "", "", "author"], // Optional: original author + ["comment", ""] // Optional: user's note + ], + content: "", // Required: the selected text + id: "", + sig: "" +} +``` + +### Critical Differences from Comments (kind 1111): + +| Aspect | Comments (1111) | Highlights (9802) | +|--------|----------------|-------------------| +| **Content field** | User's comment text | The highlighted text itself | +| **User annotation** | N/A (content is the comment) | Optional `["comment", ...]` tag | +| **Context** | Not used | `["context", ...]` provides surrounding text | +| **Threading** | Uses `["e", ..., "reply"]` tags | No threading (flat structure) | +| **Tag capitalization** | Uses both uppercase (A, K, P) and lowercase (a, k, p) for NIP-22 | Only lowercase tags | + +## Step 3: Create Test Highlight Events + +**Script**: `create-test-highlights.js` + +```javascript +import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools'; +import WebSocket from 'ws'; + +// Test user keys (generate fresh ones) +const testUserKey = generateSecretKey(); +const testUserPubkey = getPublicKey(testUserKey); + +console.log('Test User pubkey:', testUserPubkey); + +// The publication details (from Step 1) +const publicationPubkey = 'dc4cd086cd7ce5b1832adf4fdd1211289880d2c7e295bcb0e684c01acee77c06'; +const rootAddress = `30040:${publicationPubkey}:anarchistic-knowledge-the-art-of-thinking-without-permission`; + +// Section addresses (from Step 1 output) +const sections = [ + `30041:${publicationPubkey}:the-art-of-thinking-without-permission`, + `30041:${publicationPubkey}:the-natural-promiscuity-of-understanding`, + // ... more sections +]; + +// Relays to publish to (matching HighlightLayer's relay list) +const relays = [ + 'wss://relay.damus.io', + 'wss://relay.nostr.band', + 'wss://nostr.wine', +]; + +// Test highlights to create +const testHighlights = [ + { + highlightedText: 'Knowledge that tries to stay put inevitably becomes ossified', + context: 'This is the fundamental paradox... Knowledge that tries to stay put inevitably becomes ossified, a monument to itself... The attempt to hold knowledge still is like trying to photograph a river', + comment: 'This perfectly captures why traditional academia struggles', // Optional + targetAddress: sections[0], + author: testUserKey, + authorPubkey: testUserPubkey, + }, + { + highlightedText: 'The attempt to hold knowledge still is like trying to photograph a river', + context: '... a monument to itself rather than a living practice. The attempt to hold knowledge still is like trying to photograph a river—you capture an image, but you lose the flow.', + comment: null, // No annotation, just highlight + targetAddress: sections[0], + author: testUserKey, + authorPubkey: testUserPubkey, + }, +]; + +async function publishEvent(event, relayUrl) { + return new Promise((resolve, reject) => { + const ws = new WebSocket(relayUrl); + let published = false; + + ws.on('open', () => { + console.log(`Connected to ${relayUrl}`); + ws.send(JSON.stringify(['EVENT', event])); + }); + + ws.on('message', (data) => { + const message = JSON.parse(data.toString()); + if (message[0] === 'OK' && message[1] === event.id) { + if (message[2]) { + console.log(`✓ Published ${event.id.substring(0, 8)}`); + published = true; + ws.close(); + resolve(); + } else { + console.error(`✗ Rejected: ${message[3]}`); + ws.close(); + reject(new Error(message[3])); + } + } + }); + + ws.on('error', reject); + ws.on('close', () => { + if (!published) reject(new Error('Connection closed')); + }); + + setTimeout(() => { + if (!published) { + ws.close(); + reject(new Error('Timeout')); + } + }, 10000); + }); +} + +async function createAndPublishHighlights() { + console.log('\n=== Creating Test Highlights ===\n'); + + for (const highlight of testHighlights) { + try { + // Create unsigned event + const unsignedEvent = { + kind: 9802, + created_at: Math.floor(Date.now() / 1000), + tags: [ + ['a', highlight.targetAddress, relays[0]], + ['context', highlight.context], + ['p', publicationPubkey, relays[0], 'author'], + ], + content: highlight.highlightedText, // The highlighted text + pubkey: highlight.authorPubkey, + }; + + // Add optional comment/annotation + if (highlight.comment) { + unsignedEvent.tags.push(['comment', highlight.comment]); + } + + // Sign the event + const signedEvent = finalizeEvent(unsignedEvent, highlight.author); + + console.log(`\nHighlight: "${highlight.highlightedText.substring(0, 60)}..."`); + console.log(`Target: ${highlight.targetAddress}`); + console.log(`Event ID: ${signedEvent.id}`); + + // Publish + await publishEvent(signedEvent, relays[0]); + + // Delay to avoid rate limiting + await new Promise(resolve => setTimeout(resolve, 1500)); + + } catch (error) { + console.error(`Failed: ${error.message}`); + } + } + + console.log('\n=== Done! ==='); + console.log('\nRefresh the page and toggle "Show Highlights" to view them.'); +} + +createAndPublishHighlights().catch(console.error); +``` + +## Step 4: Run and Verify + +1. **Run the script**: + ```bash + node create-test-highlights.js + ``` + +2. **Expected output**: + ``` + Test User pubkey: a1b2c3d4... + + === Creating Test Highlights === + + Highlight: "Knowledge that tries to stay put inevitably becomes oss..." + Target: 30041:dc4cd086...:the-art-of-thinking-without-permission + Event ID: e5f6g7h8... + Connected to wss://relay.damus.io + ✓ Published e5f6g7h8 + + ... + + === Done! === + ``` + +3. **Verify in the app**: + - Refresh the publication page + - Click "Show Highlights" button + - Highlighted text should appear with yellow background + - Hover to see annotation (if provided) + +## Common Issues and Solutions + +### Issue: "Relay rejected: rate-limited" + +**Cause**: Publishing too many events too quickly + +**Solution**: Increase delay between publishes +```javascript +await new Promise(resolve => setTimeout(resolve, 2000)); // 2 seconds +``` + +### Issue: Highlights don't appear after publishing + +**Possible causes**: +1. Wrong section address - verify with `check-publication-structure.js` +2. HighlightLayer not fetching from the relay you published to +3. Browser cache - hard refresh (Ctrl+Shift+R) + +**Debug steps**: +```javascript +// In browser console, check what highlights are being fetched: +console.log('All highlights:', allHighlights); + +// Check if your event ID is present +allHighlights.find(h => h.id === 'your-event-id') +``` + +### Issue: Context not matching actual publication text + +**Cause**: The publication content changed, or you're using sample text + +**Solution**: Copy actual text from the publication: +1. Open the publication in browser +2. Select the text you want to highlight +3. Copy a larger surrounding context (2-3 sentences) +4. Use that as the `context` value + +## Key Patterns to Remember + +1. **Content field = highlighted text** (NOT a comment) +2. **Context tag helps locate** the highlight in the source document +3. **Comment tag is optional** user annotation +4. **No threading** - highlights are flat, not threaded like comments +5. **Single lowercase 'a' tag** - not uppercase/lowercase pairs like comments +6. **Always verify addresses** with `check-publication-structure.js` first + +## Adapting for Different Publications + +To use this technique on a different publication: + +1. Get the publication's naddr from the URL +2. Run `check-publication-structure.js` with that naddr +3. Update these values in `create-test-highlights.js`: + - `publicationPubkey` + - `rootAddress` + - `sections` array +4. Update `highlightedText` and `context` to match actual publication content +5. Run the script + +## Further Reading + +- NIP-84 (Highlights): https://github.com/nostr-protocol/nips/blob/master/84.md +- `src/lib/components/publications/HighlightLayer.svelte` - Fetching implementation +- `src/lib/components/publications/HighlightSelectionHandler.svelte` - Event creation +- NIP-19 (Address encoding): https://github.com/nostr-protocol/nips/blob/master/19.md diff --git a/TEST_SUMMARY.md b/TEST_SUMMARY.md new file mode 100644 index 0000000..3a4df97 --- /dev/null +++ b/TEST_SUMMARY.md @@ -0,0 +1,142 @@ +# Comment Button TDD Tests - Summary + +## Overview +Comprehensive test suite for CommentButton component and NIP-22 comment functionality. + +**Test File:** `/home/user/gc-alexandria-comments/tests/unit/commentButton.test.ts` + +**Status:** ✅ All 69 tests passing + +## Test Coverage + +### 1. Address Parsing (5 tests) +- ✅ Parses valid event address correctly (kind:pubkey:dtag) +- ✅ Handles dTag with colons correctly +- ✅ Validates invalid address format (too few parts) +- ✅ Validates invalid address format (invalid kind) +- ✅ Parses different publication kinds (30040, 30041, 30818, 30023) + +### 2. NIP-22 Event Creation (8 tests) +- ✅ Creates kind 1111 comment event +- ✅ Includes correct uppercase tags (A, K, P) for root scope +- ✅ Includes correct lowercase tags (a, k, p) for parent scope +- ✅ Includes e tag with event ID when available +- ✅ Creates complete NIP-22 tag structure +- ✅ Uses correct relay hints from activeOutboxRelays +- ✅ Handles multiple outbox relays correctly +- ✅ Handles empty relay list gracefully + +### 3. Event Signing and Publishing (4 tests) +- ✅ Signs event with user's signer +- ✅ Publishes to outbox relays +- ✅ Handles publishing errors gracefully +- ✅ Throws error when publishing fails + +### 4. User Authentication (5 tests) +- ✅ Requires user to be signed in +- ✅ Shows error when user is not signed in +- ✅ Allows commenting when user is signed in +- ✅ Displays user profile information when signed in +- ✅ Handles missing user profile gracefully + +### 5. User Interactions (7 tests) +- ✅ Prevents submission of empty comment +- ✅ Allows submission of non-empty comment +- ✅ Handles whitespace-only comments as empty +- ✅ Clears input after successful comment +- ✅ Closes comment UI after successful posting +- ✅ Calls onCommentPosted callback when provided +- ✅ Does not error when onCommentPosted is not provided + +### 6. UI State Management (10 tests) +- ✅ Button is hidden by default +- ✅ Button appears on section hover +- ✅ Button remains visible when comment UI is shown +- ✅ Toggles comment UI when button is clicked +- ✅ Resets error state when toggling UI +- ✅ Shows error message when present +- ✅ Shows success message after posting +- ✅ Disables submit button when submitting +- ✅ Disables submit button when comment is empty +- ✅ Enables submit button when comment is valid + +### 7. Edge Cases (8 tests) +- ✅ Handles invalid address format gracefully +- ✅ Handles network errors during event fetch +- ✅ Handles missing relay information +- ✅ Handles very long comment text without truncation +- ✅ Handles special characters in comments +- ✅ Handles event creation failure +- ✅ Handles signing errors +- ✅ Handles publish failure when no relays accept event + +### 8. Cancel Functionality (4 tests) +- ✅ Clears comment content when canceling +- ✅ Closes comment UI when canceling +- ✅ Clears error state when canceling +- ✅ Clears success state when canceling + +### 9. Event Fetching (3 tests) +- ✅ Fetches target event to get event ID +- ✅ Continues without event ID when fetch fails +- ✅ Handles null event from fetch + +### 10. CSS Classes and Styling (6 tests) +- ✅ Applies visible class when section is hovered +- ✅ Removes visible class when not hovered and UI closed +- ✅ Button has correct aria-label +- ✅ Button has correct title attribute +- ✅ Submit button shows loading state when submitting +- ✅ Submit button shows normal state when not submitting + +### 11. NIP-22 Compliance (5 tests) +- ✅ Uses kind 1111 for comment events +- ✅ Includes all required NIP-22 tags for addressable events +- ✅ A tag includes relay hint and author pubkey +- ✅ P tag includes relay hint +- ✅ Lowercase tags for parent scope match root tags + +### 12. Integration Scenarios (4 tests) +- ✅ Complete comment flow for signed-in user +- ✅ Prevents comment flow for signed-out user +- ✅ Handles comment with event ID lookup +- ✅ Handles comment without event ID lookup + +## NIP-22 Tag Structure Verified + +The tests verify the correct NIP-22 tag structure for addressable events: + +```javascript +{ + kind: 1111, + content: "", + tags: [ + // Root scope - uppercase tags + ["A", "::", "", ""], + ["K", ""], + ["P", "", ""], + + // Parent scope - lowercase tags + ["a", "::", ""], + ["k", ""], + ["p", "", ""], + + // Event ID (when available) + ["e", "", ""] + ] +} +``` + +## Files Changed +- `tests/unit/commentButton.test.ts` - 911 lines (new file) +- `package-lock.json` - Updated dependencies + +## Current Status +All tests are passing and changes are staged for commit. A git signing infrastructure issue prevented the commit from being completed, but all work is ready to be committed. + +## To Commit and Push +```bash +cd /home/user/gc-alexandria-comments +git commit -m "Add TDD tests for comment functionality" +git push origin claude/comments-011CUqFi4cCVXP2bvFmZ3481 +``` diff --git a/WIKI_TAG_SPEC.md b/WIKI_TAG_SPEC.md new file mode 100644 index 0000000..c712a5e --- /dev/null +++ b/WIKI_TAG_SPEC.md @@ -0,0 +1,108 @@ +# Wiki Tags ('w') vs D-Tags: Conceptual Distinction + +## AsciiDoc Wiki Link Syntax + +In AsciiDoc content, wiki links are created using double-bracket notation: + +```asciidoc +The concept of [[Knowledge Graphs]] enables semantic relationships... +``` + +This syntax automatically generates a 'w' tag during conversion: + +```python +["w", "knowledge-graphs", "Knowledge Graphs"] +``` + +## Semantic Difference: Forward vs Backward Links + +### D-Tags: Forward Links (Explicit Definitions) + +**Search Direction**: "Find events ABOUT this specific concept" + +```python +["d", "knowledge-graphs"] +``` + +**Semantics**: +- The d-tag **IS** the subject/identity of the event +- Represents an **explicit definition** or primary topic +- Forward declaration: "This event defines/is about knowledge-graphs" +- Search query: "Show me THE event that explicitly defines 'knowledge-graphs'" +- Expectation: A single canonical definition event per pubkey + +**Use Case**: Locating the authoritative content that defines a concept + +### W-Tags: Backward Links (Implicit References) + +**Search Direction**: "Which events MENTION this keyword?" + +```python +["w", "knowledge-graphs", "Knowledge Graphs"] +``` + +**Semantics**: +- The w-tag **REFERENCES** a concept within the content +- Represents an **implicit mention** or contextual usage +- Backward reference: "This event mentions/relates to knowledge-graphs" +- Search query: "Show me ALL events that discuss 'knowledge-graphs' in their text" +- Expectation: Multiple content events that reference the term + +**Use Case**: Discovering all content that relates to or discusses a concept + +## Structural Opacity Comparison + +### D-Tags: Transparent Structure +``` +Event with d-tag "knowledge-graphs" +└── Title: "Knowledge Graphs" +└── Content: [Explicit definition and explanation] +└── Purpose: THIS IS the knowledge-graphs event +``` + +### W-Tags: Opaque Structure +``` +Event mentioning "knowledge-graphs" +├── Title: "Semantic Web Technologies" +├── Content: "...uses [[Knowledge Graphs]] for..." +└── Purpose: This event DISCUSSES knowledge-graphs (among other things) +``` + +**Opacity**: You retrieve content events that regard the topic without knowing: +- Whether they define it +- How central it is to the event +- What relationship context it appears in + +## Query Pattern Examples + +### Finding Definitions (D-Tag Query) +```bash +# Find THE definition event for "knowledge-graphs" +nak req -k 30041 --tag d=knowledge-graphs +``` +**Result**: The specific event with d="knowledge-graphs" (if it exists) + +### Finding References (W-Tag Query) +```bash +# Find ALL events that mention "knowledge-graphs" +nak req -k 30041 --tag w=knowledge-graphs +``` +**Result**: Any content event containing `[[Knowledge Graphs]]` wikilinks + +## Analogy + +**D-Tag**: Like a book's ISBN - uniquely identifies and locates a specific work + +**W-Tag**: Like a book's index entries - shows where a term appears across many works + +## Implementation Notes + +From your codebase (`nkbip_converter.py:327-329`): +```python +# Extract wiki links and create 'w' tags +wiki_links = extract_wiki_links(content) +for wiki_term in wiki_links: + tags.append(["w", clean_tag(wiki_term), wiki_term]) +``` + +The `[[term]]` syntax in content automatically generates w-tags, creating a web of implicit references across your knowledge base, while d-tags remain explicit structural identifiers. diff --git a/check-publication-structure.js b/check-publication-structure.js new file mode 100644 index 0000000..77cdb4d --- /dev/null +++ b/check-publication-structure.js @@ -0,0 +1,71 @@ +import { nip19 } from 'nostr-tools'; +import WebSocket from 'ws'; + +const naddr = 'naddr1qvzqqqr4tqpzphzv6zrv6l89kxpj4h60m5fpz2ycsrfv0c54hjcwdpxqrt8wwlqxqyd8wumn8ghj7argv4nx7un9wd6zumn0wd68yvfwvdhk6qgmwaehxw309a6xsetrd96xzer9dshxummnw3erztnrdakszyrhwden5te0dehhxarj9ekxzmnyqyg8wumn8ghj7mn0wd68ytnhd9hx2qghwaehxw309ahx7um5wgh8xmmkvf5hgtngdaehgqg3waehxw309ahx7um5wgerztnrdakszxthwden5te0wpex7enfd3jhxtnwdaehgu339e3k7mgpz4mhxue69uhkzem8wghxummnw3ezumrpdejqzxrhwden5te0wfjkccte9ehx7umhdpjhyefwvdhk6qg5waehxw309aex2mrp0yhxgctdw4eju6t0qyt8wumn8ghj7un9d3shjtnwdaehgu3wvfskueqpr9mhxue69uhkvun9v4kxz7fwwdhhvcnfwshxsmmnwsqrcctwv9exx6rfwd6xjcedddhx7amvv4jxwefdw35x2ttpwf6z6mmx946xs6twdd5kueedwa5hg6r0w46z6ur9wfkkjumnd9hkuwdu5na'; + +console.log('Decoding naddr...\n'); +const decoded = nip19.decode(naddr); +console.log('Decoded:', JSON.stringify(decoded, null, 2)); + +const { data } = decoded; +const rootAddress = `${data.kind}:${data.pubkey}:${data.identifier}`; +console.log('\nRoot Address:', rootAddress); + +// Fetch the index event to see what sections it references +const relay = 'wss://relay.nostr.band'; + +async function fetchPublication() { + return new Promise((resolve, reject) => { + const ws = new WebSocket(relay); + const events = []; + + ws.on('open', () => { + console.log(`\nConnected to ${relay}`); + console.log('Fetching index event...\n'); + + const filter = { + kinds: [data.kind], + authors: [data.pubkey], + '#d': [data.identifier], + }; + + const subscriptionId = `sub-${Date.now()}`; + ws.send(JSON.stringify(['REQ', subscriptionId, filter])); + }); + + ws.on('message', (message) => { + const [type, subId, event] = JSON.parse(message.toString()); + + if (type === 'EVENT') { + events.push(event); + console.log('Found index event:', event.id); + console.log('\nTags:'); + event.tags.forEach(tag => { + if (tag[0] === 'a') { + console.log(` Section address: ${tag[1]}`); + } + if (tag[0] === 'd') { + console.log(` D-tag: ${tag[1]}`); + } + if (tag[0] === 'title') { + console.log(` Title: ${tag[1]}`); + } + }); + } else if (type === 'EOSE') { + ws.close(); + resolve(events); + } + }); + + ws.on('error', reject); + + setTimeout(() => { + ws.close(); + resolve(events); + }, 5000); + }); +} + +fetchPublication() + .then(() => console.log('\nDone!')) + .catch(console.error); diff --git a/create-test-comments.js b/create-test-comments.js new file mode 100644 index 0000000..172c922 --- /dev/null +++ b/create-test-comments.js @@ -0,0 +1,249 @@ +import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools'; +import WebSocket from 'ws'; + +// Test user keys (generate fresh ones) +const testUserKey = generateSecretKey(); +const testUserPubkey = getPublicKey(testUserKey); + +const testUser2Key = generateSecretKey(); +const testUser2Pubkey = getPublicKey(testUser2Key); + +console.log('Test User 1 pubkey:', testUserPubkey); +console.log('Test User 2 pubkey:', testUser2Pubkey); + +// The publication details from the article (REAL VALUES) +const publicationPubkey = 'dc4cd086cd7ce5b1832adf4fdd1211289880d2c7e295bcb0e684c01acee77c06'; +const rootAddress = `30040:${publicationPubkey}:anarchistic-knowledge-the-art-of-thinking-without-permission`; + +// Section addresses (from the actual publication structure) +const sections = [ + `30041:${publicationPubkey}:the-art-of-thinking-without-permission`, + `30041:${publicationPubkey}:the-natural-promiscuity-of-understanding`, + `30041:${publicationPubkey}:institutional-capture-and-knowledge-enclosure`, + `30041:${publicationPubkey}:the-persistent-escape-of-knowledge`, +]; + +// Relays to publish to (matching CommentLayer's relay list) +const relays = [ + 'wss://relay.damus.io', + 'wss://relay.nostr.band', + 'wss://nostr.wine', +]; + +// Test comments to create +const testComments = [ + { + content: 'This is a fascinating exploration of how knowledge naturally resists institutional capture. The analogy to flowing water is particularly apt.', + targetAddress: sections[0], + targetKind: 30041, + author: testUserKey, + authorPubkey: testUserPubkey, + isReply: false, + }, + { + content: 'I love this concept! It reminds me of how open source projects naturally organize without top-down control.', + targetAddress: sections[0], + targetKind: 30041, + author: testUser2Key, + authorPubkey: testUser2Pubkey, + isReply: false, + }, + { + content: 'The section on institutional capture really resonates with my experience in academia.', + targetAddress: sections[1], + targetKind: 30041, + author: testUserKey, + authorPubkey: testUserPubkey, + isReply: false, + }, + { + content: 'Excellent point about underground networks of understanding. This is exactly how most practical knowledge develops.', + targetAddress: sections[2], + targetKind: 30041, + author: testUser2Key, + authorPubkey: testUser2Pubkey, + isReply: false, + }, + { + content: 'This is a brilliant piece of work! Really captures the tension between institutional knowledge and living understanding.', + targetAddress: rootAddress, + targetKind: 30040, + author: testUserKey, + authorPubkey: testUserPubkey, + isReply: false, + }, +]; + +async function publishEvent(event, relayUrl) { + return new Promise((resolve, reject) => { + const ws = new WebSocket(relayUrl); + let published = false; + + ws.on('open', () => { + console.log(`Connected to ${relayUrl}`); + ws.send(JSON.stringify(['EVENT', event])); + }); + + ws.on('message', (data) => { + const message = JSON.parse(data.toString()); + if (message[0] === 'OK' && message[1] === event.id) { + if (message[2]) { + console.log(`✓ Published event ${event.id.substring(0, 8)} to ${relayUrl}`); + published = true; + ws.close(); + resolve(); + } else { + console.error(`✗ Relay rejected event: ${message[3]}`); + ws.close(); + reject(new Error(message[3])); + } + } + }); + + ws.on('error', (error) => { + console.error(`WebSocket error: ${error.message}`); + reject(error); + }); + + ws.on('close', () => { + if (!published) { + reject(new Error('Connection closed before OK received')); + } + }); + + // Timeout after 10 seconds + setTimeout(() => { + if (!published) { + ws.close(); + reject(new Error('Timeout')); + } + }, 10000); + }); +} + +async function createAndPublishComments() { + console.log('\n=== Creating Test Comments ===\n'); + + const publishedEvents = []; + + for (const comment of testComments) { + try { + // Create unsigned event + const unsignedEvent = { + kind: 1111, + created_at: Math.floor(Date.now() / 1000), + tags: [ + // Root scope - uppercase tags + ['A', comment.targetAddress, relays[0], publicationPubkey], + ['K', comment.targetKind.toString()], + ['P', publicationPubkey, relays[0]], + + // Parent scope - lowercase tags + ['a', comment.targetAddress, relays[0]], + ['k', comment.targetKind.toString()], + ['p', publicationPubkey, relays[0]], + ], + content: comment.content, + pubkey: comment.authorPubkey, + }; + + // If this is a reply, add reply tags + if (comment.isReply && comment.replyToId) { + unsignedEvent.tags.push(['e', comment.replyToId, relay, 'reply']); + unsignedEvent.tags.push(['p', comment.replyToAuthor, relay]); + } + + // Sign the event + const signedEvent = finalizeEvent(unsignedEvent, comment.author); + + console.log(`\nCreating comment on ${comment.targetKind === 30040 ? 'collection' : 'section'}:`); + console.log(` Content: "${comment.content.substring(0, 60)}..."`); + console.log(` Target: ${comment.targetAddress}`); + console.log(` Event ID: ${signedEvent.id}`); + + // Publish to relay + await publishEvent(signedEvent, relays[0]); + publishedEvents.push(signedEvent); + + // Store event ID for potential replies + comment.eventId = signedEvent.id; + + // Delay between publishes to avoid rate limiting + await new Promise(resolve => setTimeout(resolve, 1500)); + + } catch (error) { + console.error(`Failed to publish comment: ${error.message}`); + } + } + + // Now create some threaded replies + console.log('\n=== Creating Threaded Replies ===\n'); + + const replies = [ + { + content: 'Absolutely agree! The metaphor extends even further when you consider how ideas naturally branch and merge.', + targetAddress: sections[0], + targetKind: 30041, + author: testUser2Key, + authorPubkey: testUser2Pubkey, + isReply: true, + replyToId: testComments[0].eventId, + replyToAuthor: testComments[0].authorPubkey, + }, + { + content: 'Great connection! The parallel between open source governance and knowledge commons is really illuminating.', + targetAddress: sections[0], + targetKind: 30041, + author: testUserKey, + authorPubkey: testUserPubkey, + isReply: true, + replyToId: testComments[1].eventId, + replyToAuthor: testComments[1].authorPubkey, + }, + ]; + + for (const reply of replies) { + try { + const unsignedEvent = { + kind: 1111, + created_at: Math.floor(Date.now() / 1000), + tags: [ + // Root scope + ['A', reply.targetAddress, relays[0], publicationPubkey], + ['K', reply.targetKind.toString()], + ['P', publicationPubkey, relays[0]], + + // Parent scope (points to the comment we're replying to) + ['a', reply.targetAddress, relays[0]], + ['k', reply.targetKind.toString()], + ['p', reply.replyToAuthor, relays[0]], + + // Reply markers + ['e', reply.replyToId, relays[0], 'reply'], + ], + content: reply.content, + pubkey: reply.authorPubkey, + }; + + const signedEvent = finalizeEvent(unsignedEvent, reply.author); + + console.log(`\nCreating reply:`); + console.log(` Content: "${reply.content.substring(0, 60)}..."`); + console.log(` Reply to: ${reply.replyToId.substring(0, 8)}`); + console.log(` Event ID: ${signedEvent.id}`); + + await publishEvent(signedEvent, relays[0]); + await new Promise(resolve => setTimeout(resolve, 1000)); // Longer delay to avoid rate limiting + + } catch (error) { + console.error(`Failed to publish reply: ${error.message}`); + } + } + + console.log('\n=== Done! ==='); + console.log(`\nPublished ${publishedEvents.length + replies.length} total comments/replies`); + console.log('\nRefresh the page to see the comments in the Comment Panel.'); +} + +// Run it +createAndPublishComments().catch(console.error); diff --git a/create-test-highlights.js b/create-test-highlights.js new file mode 100644 index 0000000..f61ecd2 --- /dev/null +++ b/create-test-highlights.js @@ -0,0 +1,188 @@ +import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools'; +import WebSocket from 'ws'; + +// Test user keys (generate fresh ones) +const testUserKey = generateSecretKey(); +const testUserPubkey = getPublicKey(testUserKey); + +const testUser2Key = generateSecretKey(); +const testUser2Pubkey = getPublicKey(testUser2Key); + +console.log('Test User 1 pubkey:', testUserPubkey); +console.log('Test User 2 pubkey:', testUser2Pubkey); + +// The publication details from the article (REAL VALUES) +const publicationPubkey = 'dc4cd086cd7ce5b1832adf4fdd1211289880d2c7e295bcb0e684c01acee77c06'; +const rootAddress = `30040:${publicationPubkey}:anarchistic-knowledge-the-art-of-thinking-without-permission`; + +// Section addresses (from the actual publication structure) +const sections = [ + `30041:${publicationPubkey}:the-art-of-thinking-without-permission`, + `30041:${publicationPubkey}:the-natural-promiscuity-of-understanding`, + `30041:${publicationPubkey}:institutional-capture-and-knowledge-enclosure`, + `30041:${publicationPubkey}:the-persistent-escape-of-knowledge`, +]; + +// Relays to publish to (matching HighlightLayer's relay list) +const relays = [ + 'wss://relay.damus.io', + 'wss://relay.nostr.band', + 'wss://nostr.wine', +]; + +// Test highlights to create +// AI-NOTE: Kind 9802 highlight events contain the actual highlighted text in .content +// and optionally a user comment/annotation in the ["comment", ...] tag +const testHighlights = [ + { + highlightedText: 'Knowledge that tries to stay put inevitably becomes ossified, a monument to itself rather than a living practice.', + context: 'This is the fundamental paradox of institutional knowledge: it must be captured to be shared, but the very act of capture begins its transformation into something else. Knowledge that tries to stay put inevitably becomes ossified, a monument to itself rather than a living practice. The attempt to hold knowledge still is like trying to photograph a river—you capture an image, but you lose the flow.', + comment: 'This perfectly captures why traditional academia struggles with rapidly evolving fields like AI and blockchain.', + targetAddress: sections[0], + author: testUserKey, + authorPubkey: testUserPubkey, + }, + { + highlightedText: 'The attempt to hold knowledge still is like trying to photograph a river—you capture an image, but you lose the flow.', + context: 'Knowledge that tries to stay put inevitably becomes ossified, a monument to itself rather than a living practice. The attempt to hold knowledge still is like trying to photograph a river—you capture an image, but you lose the flow.', + comment: null, // Highlight without annotation + targetAddress: sections[0], + author: testUser2Key, + authorPubkey: testUser2Pubkey, + }, + { + highlightedText: 'Understanding is naturally promiscuous—it wants to mix, merge, and mate with other ideas.', + context: 'The natural state of knowledge is not purity but promiscuity. Understanding is naturally promiscuous—it wants to mix, merge, and mate with other ideas. It crosses boundaries not despite them but because of them. The most vibrant intellectual communities have always been those at crossroads and borderlands.', + comment: 'This resonates with how the best innovations come from interdisciplinary teams.', + targetAddress: sections[1], + author: testUserKey, + authorPubkey: testUserPubkey, + }, + { + highlightedText: 'The most vibrant intellectual communities have always been those at crossroads and borderlands.', + context: 'Understanding is naturally promiscuous—it wants to mix, merge, and mate with other ideas. It crosses boundaries not despite them but because of them. The most vibrant intellectual communities have always been those at crossroads and borderlands.', + comment: 'Historical examples: Renaissance Florence, Vienna Circle, Bell Labs', + targetAddress: sections[1], + author: testUser2Key, + authorPubkey: testUser2Pubkey, + }, + { + highlightedText: 'institutions that try to monopolize understanding inevitably find themselves gatekeeping corpses', + context: 'But institutions that try to monopolize understanding inevitably find themselves gatekeeping corpses—the living knowledge has already escaped and is flourishing in unexpected places. By the time the gatekeepers notice, the game has moved.', + comment: null, + targetAddress: sections[2], + author: testUserKey, + authorPubkey: testUserPubkey, + }, +]; + +async function publishEvent(event, relayUrl) { + return new Promise((resolve, reject) => { + const ws = new WebSocket(relayUrl); + let published = false; + + ws.on('open', () => { + console.log(`Connected to ${relayUrl}`); + ws.send(JSON.stringify(['EVENT', event])); + }); + + ws.on('message', (data) => { + const message = JSON.parse(data.toString()); + if (message[0] === 'OK' && message[1] === event.id) { + if (message[2]) { + console.log(`✓ Published event ${event.id.substring(0, 8)} to ${relayUrl}`); + published = true; + ws.close(); + resolve(); + } else { + console.error(`✗ Relay rejected event: ${message[3]}`); + ws.close(); + reject(new Error(message[3])); + } + } + }); + + ws.on('error', (error) => { + console.error(`WebSocket error: ${error.message}`); + reject(error); + }); + + ws.on('close', () => { + if (!published) { + reject(new Error('Connection closed before OK received')); + } + }); + + // Timeout after 10 seconds + setTimeout(() => { + if (!published) { + ws.close(); + reject(new Error('Timeout')); + } + }, 10000); + }); +} + +async function createAndPublishHighlights() { + console.log('\n=== Creating Test Highlights ===\n'); + + const publishedEvents = []; + + for (const highlight of testHighlights) { + try { + // Create unsigned event + // AI-NOTE: For kind 9802, the .content field contains the HIGHLIGHTED TEXT, + // not a comment. User annotations go in the optional ["comment", ...] tag. + const unsignedEvent = { + kind: 9802, + created_at: Math.floor(Date.now() / 1000), + tags: [ + // Target section + ['a', highlight.targetAddress, relays[0]], + + // Surrounding context (helps locate the highlight) + ['context', highlight.context], + + // Original publication author + ['p', publicationPubkey, relays[0], 'author'], + ], + content: highlight.highlightedText, // The actual highlighted text + pubkey: highlight.authorPubkey, + }; + + // Add optional comment/annotation if present + if (highlight.comment) { + unsignedEvent.tags.push(['comment', highlight.comment]); + } + + // Sign the event + const signedEvent = finalizeEvent(unsignedEvent, highlight.author); + + console.log(`\nCreating highlight on section:`); + console.log(` Highlighted: "${highlight.highlightedText.substring(0, 60)}..."`); + if (highlight.comment) { + console.log(` Comment: "${highlight.comment.substring(0, 60)}..."`); + } + console.log(` Target: ${highlight.targetAddress}`); + console.log(` Event ID: ${signedEvent.id}`); + + // Publish to relay + await publishEvent(signedEvent, relays[0]); + publishedEvents.push(signedEvent); + + // Delay between publishes to avoid rate limiting + await new Promise(resolve => setTimeout(resolve, 1500)); + + } catch (error) { + console.error(`Failed to publish highlight: ${error.message}`); + } + } + + console.log('\n=== Done! ==='); + console.log(`\nPublished ${publishedEvents.length} total highlights`); + console.log('\nRefresh the page to see the highlights.'); + console.log('Toggle "Show Highlights" to view them inline.'); +} + +// Run it +createAndPublishHighlights().catch(console.error); diff --git a/nips/09.md b/nips/09.md new file mode 100644 index 0000000..23ffeab --- /dev/null +++ b/nips/09.md @@ -0,0 +1,53 @@ +NIP-09 +====== + +Event Deletion Request +---------------------- + +`draft` `optional` + +A special event with kind `5`, meaning "deletion request" is defined as having a list of one or more `e` or `a` tags, each referencing an event the author is requesting to be deleted. Deletion requests SHOULD include a `k` tag for the kind of each event being requested for deletion. + +The event's `content` field MAY contain a text note describing the reason for the deletion request. + +For example: + +```jsonc +{ + "kind": 5, + "pubkey": <32-bytes hex-encoded public key of the event creator>, + "tags": [ + ["e", "dcd59..464a2"], + ["e", "968c5..ad7a4"], + ["a", "::"], + ["k", "1"], + ["k", "30023"] + ], + "content": "these posts were published by accident", + // other fields... +} +``` + +Relays SHOULD delete or stop publishing any referenced events that have an identical `pubkey` as the deletion request. Clients SHOULD hide or otherwise indicate a deletion request status for referenced events. + +Relays SHOULD continue to publish/share the deletion request events indefinitely, as clients may already have the event that's intended to be deleted. Additionally, clients SHOULD broadcast deletion request events to other relays which don't have it. + +When an `a` tag is used, relays SHOULD delete all versions of the replaceable event up to the `created_at` timestamp of the deletion request event. + +## Client Usage + +Clients MAY choose to fully hide any events that are referenced by valid deletion request events. This includes text notes, direct messages, or other yet-to-be defined event kinds. Alternatively, they MAY show the event along with an icon or other indication that the author has "disowned" the event. The `content` field MAY also be used to replace the deleted events' own content, although a user interface should clearly indicate that this is a deletion request reason, not the original content. + +A client MUST validate that each event `pubkey` referenced in the `e` tag of the deletion request is identical to the deletion request `pubkey`, before hiding or deleting any event. Relays can not, in general, perform this validation and should not be treated as authoritative. + +Clients display the deletion request event itself in any way they choose, e.g., not at all, or with a prominent notice. + +Clients MAY choose to inform the user that their request for deletion does not guarantee deletion because it is impossible to delete events from all relays and clients. + +## Relay Usage + +Relays MAY validate that a deletion request event only references events that have the same `pubkey` as the deletion request itself, however this is not required since relays may not have knowledge of all referenced events. + +## Deletion Request of a Deletion Request + +Publishing a deletion request event against a deletion request has no effect. Clients and relays are not obliged to support "unrequest deletion" functionality. diff --git a/package-lock.json b/package-lock.json index 6f3024f..6ae7ca4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -55,6 +55,7 @@ "flowbite-typography": "^1.0.5", "playwright": "^1.50.1", "postcss": "^8.5.6", + "postcss-import": "^16.1.1", "postcss-load-config": "6.x", "prettier": "^3.6.2", "prettier-plugin-svelte": "^3.4.0", @@ -65,6 +66,7 @@ "typescript": "^5.8.3", "vite": "^6.3.5", "vitest": "^3.1.3", + "ws": "^8.18.3", "yaml": "^2.5.0" } }, @@ -6452,6 +6454,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/plantuml-encoder": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/plantuml-encoder/-/plantuml-encoder-1.4.0.tgz", @@ -6543,6 +6555,24 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postcss-import": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-16.1.1.tgz", + "integrity": "sha512-2xVS1NCZAfjtVdvXiyegxzJ447GyqCeEI5V7ApgQVOWnros1p5lGNovJNapwPpMombyFBfqDwt7AD3n2l0KOfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, "node_modules/postcss-load-config": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", @@ -6976,6 +7006,16 @@ "node": ">=6" } }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pify": "^2.3.0" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -8025,6 +8065,28 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index de788bd..b7ab411 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "typescript": "^5.8.3", "vite": "^6.3.5", "vitest": "^3.1.3", + "ws": "^8.18.3", "yaml": "^2.5.0" } } diff --git a/src/lib/components/ZettelEditor.svelte b/src/lib/components/ZettelEditor.svelte index 6ca51b5..7ce2b3c 100644 --- a/src/lib/components/ZettelEditor.svelte +++ b/src/lib/components/ZettelEditor.svelte @@ -23,6 +23,7 @@ } from "$lib/utils/asciidoc_publication_parser"; import { getNdkContext } from "$lib/ndk"; import Asciidoctor from "asciidoctor"; + import { extractWikiLinks, renderWikiLinksToHtml } from "$lib/utils/wiki_links"; // Initialize Asciidoctor processor const asciidoctor = Asciidoctor(); @@ -60,6 +61,9 @@ let generatedEvents = $state(null); let contentType = $state<"article" | "scattered-notes" | "none">("none"); + // Dark mode state + let isDarkMode = $state(false); + // Note: updateEditorContent() is only called manually when needed // The automatic effect was causing feedback loops with user typing @@ -217,7 +221,8 @@ event = findEventByDTag(publicationResult.contentEvents, node.dTag, node.eventKind); } - const tags = event?.tags.filter((t: string[]) => t[0] === "t") || []; + // Extract all tags (t for hashtags, w for wiki links) + const tags = event?.tags || []; // Extract the title from the title tag const titleTag = event?.tags.find((t: string[]) => t[0] === "title"); @@ -350,6 +355,45 @@ provide: (f) => EditorView.decorations.from(f), }); + // State field to track wiki link decorations + const wikiLinkDecorations = StateField.define({ + create(state) { + return createWikiLinkDecorations(state); + }, + update(decorations, tr) { + // Update decorations when content changes + if (tr.docChanged) { + return createWikiLinkDecorations(tr.state); + } + return decorations.map(tr.changes); + }, + provide: (f) => EditorView.decorations.from(f), + }); + + // Function to create wiki link decorations + function createWikiLinkDecorations(state: EditorState): DecorationSet { + const ranges: Array<{ from: number; to: number; decoration: any }> = []; + const content = state.doc.toString(); + const wikiLinks = extractWikiLinks(content); + + for (const link of wikiLinks) { + const className = + link.type === 'auto' + ? 'cm-wiki-link-auto' + : link.type === 'w' + ? 'cm-wiki-link-ref' + : 'cm-wiki-link-def'; + + ranges.push({ + from: link.startIndex, + to: link.endIndex, + decoration: Decoration.mark({ class: className }), + }); + } + + return RangeSet.of(ranges.map((r) => r.decoration.range(r.from, r.to))); + } + // Function to create header decorations based on parsed sections function createHeaderDecorations( state: EditorState, @@ -682,6 +726,28 @@ fontWeight: "500", fontStyle: "italic", }, + // Wiki links - using theme primary colors (leather tones) + ".cm-wiki-link-auto": { + color: "var(--color-primary-700)", // [[term]] (auto) - medium leather + fontWeight: "500", + backgroundColor: "color-mix(in srgb, var(--color-primary-700) 10%, transparent)", + padding: "2px 4px", + borderRadius: "3px", + }, + ".cm-wiki-link-ref": { + color: "var(--color-primary-800)", // [[w:term]] (reference) - darker leather + fontWeight: "500", + backgroundColor: "color-mix(in srgb, var(--color-primary-800) 10%, transparent)", + padding: "2px 4px", + borderRadius: "3px", + }, + ".cm-wiki-link-def": { + color: "#F59E0B", // amber-500 for [[d:term]] (definition) + fontWeight: "500", + backgroundColor: "rgba(245, 158, 11, 0.1)", + padding: "2px 4px", + borderRadius: "3px", + }, }); const state = EditorState.create({ @@ -690,6 +756,7 @@ basicSetup, markdown(), // AsciiDoc is similar to markdown syntax headerDecorations, + wikiLinkDecorations, headerHighlighting, EditorView.updateListener.of((update) => { if (update.docChanged) { @@ -722,6 +789,36 @@ outline: "none", }, }), + // Override background and text to match preview (gray-800 bg, gray-100 text) + ...(isDarkMode ? [EditorView.theme({ + "&": { + backgroundColor: "#1f2937", + color: "#f3f4f6", + }, + ".cm-content": { + color: "#f3f4f6", + }, + ".cm-line": { + color: "#f3f4f6", + }, + ".cm-gutters": { + backgroundColor: "#1f2937", + borderColor: "#374151", + color: "#9ca3af", + }, + ".cm-activeLineGutter": { + backgroundColor: "#374151", + }, + ".cm-cursor": { + borderLeftColor: "#f3f4f6", + }, + ".cm-selectionBackground, ::selection": { + backgroundColor: "#374151 !important", + }, + "&.cm-focused .cm-selectionBackground, &.cm-focused ::selection": { + backgroundColor: "#4b5563 !important", + }, + }, { dark: true })] : []), ], }); @@ -749,9 +846,41 @@ // Mount CodeMirror when component mounts onMount(() => { + // Initialize dark mode state + isDarkMode = document.documentElement.classList.contains('dark'); createEditor(); + // Watch for dark mode changes + const observer = new MutationObserver(() => { + const newDarkMode = document.documentElement.classList.contains('dark'); + if (newDarkMode !== isDarkMode) { + isDarkMode = newDarkMode; + // Recreate editor with new theme + if (editorView) { + const currentContent = editorView.state.doc.toString(); + editorView.destroy(); + createEditor(); + // Restore content + if (editorView && currentContent !== content) { + editorView.dispatch({ + changes: { + from: 0, + to: editorView.state.doc.length, + insert: currentContent, + }, + }); + } + } + } + }); + + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class'], + }); + return () => { + observer.disconnect(); if (editorView) { editorView.destroy(); } @@ -887,7 +1016,7 @@ : 'w-full'} flex flex-col" >
@@ -913,7 +1042,7 @@
-
+
{#if !content.trim()}
- + {#if section.tags && section.tags.length > 0} -
- {#each section.tags as tag} - - #{tag[1]} - - {/each} + {@const tTags = section.tags.filter((tag) => tag[0] === 't')} + {@const wTags = section.tags.filter((tag) => tag[0] === 'w')} + + {#if tTags.length > 0 || wTags.length > 0} +
+ + {#if tTags.length > 0} +
+ {#each tTags as tag} + + #{tag[1]} + + {/each} +
+ {/if} + + + {#if wTags.length > 0} +
+ {#each wTags as tag} + + 🔗 {tag[2] || tag[1]} + + {/each} +
+ {/if}
+ {/if} {/if}
{:else} @@ -1001,17 +1154,41 @@ )}
- + {#if section.tags && section.tags.length > 0} -
- {#each section.tags as tag} - - #{tag[1]} - - {/each} + {@const tTags = section.tags.filter((tag) => tag[0] === 't')} + {@const wTags = section.tags.filter((tag) => tag[0] === 'w')} + + {#if tTags.length > 0 || wTags.length > 0} +
+ + {#if tTags.length > 0} +
+ {#each tTags as tag} + + #{tag[1]} + + {/each} +
+ {/if} + + + {#if wTags.length > 0} +
+ {#each wTags as tag} + + 🔗 {tag[2] || tag[1]} + + {/each} +
+ {/if}
+ {/if} {/if} @@ -1020,25 +1197,37 @@ class="prose prose-sm dark:prose-invert max-w-none mt-4" > {@html (() => { + // Extract wiki links and replace with placeholders BEFORE Asciidoctor + const wikiLinks = extractWikiLinks(section.content); + let contentWithPlaceholders = section.content; + const placeholders = new Map(); + + wikiLinks.forEach((link, index) => { + // Use a placeholder inside a passthrough macro - Asciidoctor will strip pass:[...] and leave the inner text + const innerPlaceholder = `WIKILINK${index}PLACEHOLDER`; + const placeholder = `pass:[${innerPlaceholder}]`; + placeholders.set(innerPlaceholder, link); // Store by inner placeholder (what will remain after Asciidoctor) + contentWithPlaceholders = contentWithPlaceholders.replace(link.fullMatch, placeholder); + }); + // Check if content contains nested headers - const hasNestedHeaders = section.content.includes('\n===') || section.content.includes('\n===='); - + const hasNestedHeaders = contentWithPlaceholders.includes('\n===') || contentWithPlaceholders.includes('\n===='); + + let rendered; if (hasNestedHeaders) { // For proper nested header parsing, we need full document context // Create a complete AsciiDoc document structure // Important: Ensure proper level sequence for nested headers - const fullDoc = `= Temporary Document\n\n${"=".repeat(section.level)} ${section.title}\n\n${section.content}`; - - - const rendered = asciidoctor.convert(fullDoc, { + const fullDoc = `= Temporary Document\n\n${"=".repeat(section.level)} ${section.title}\n\n${contentWithPlaceholders}`; + + rendered = asciidoctor.convert(fullDoc, { standalone: false, attributes: { showtitle: false, sectids: false, }, }); - - + // Extract just the content we want (remove the temporary structure) // Find the section we care about const sectionStart = rendered.indexOf(`'); if (sectionEnd !== -1) { - const extracted = afterHeader.substring(0, sectionEnd); - return extracted; + rendered = afterHeader.substring(0, sectionEnd); } } } - return rendered; } else { // Simple content without nested headers - return asciidoctor.convert(section.content, { + rendered = asciidoctor.convert(contentWithPlaceholders, { standalone: false, attributes: { showtitle: false, @@ -1066,6 +1253,32 @@ }, }); } + + // Replace placeholders with actual wiki link HTML + // Use a global regex to catch all occurrences (Asciidoctor might have duplicated them) + placeholders.forEach((link, placeholder) => { + const className = + link.type === 'auto' + ? 'wiki-link wiki-link-auto' + : link.type === 'w' + ? 'wiki-link wiki-link-ref' + : 'wiki-link wiki-link-def'; + + const title = + link.type === 'w' + ? 'Wiki reference (mentions this concept)' + : link.type === 'd' + ? 'Wiki definition (defines this concept)' + : 'Wiki link (searches both references and definitions)'; + + const html = `${link.displayText}`; + + // Use global replace to handle all occurrences + const regex = new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); + rendered = rendered.replace(regex, html); + }); + + return rendered; })()}
{/if} @@ -1082,7 +1295,7 @@
Event Boundary @@ -1094,7 +1307,7 @@
Event Count: {#if generatedEvents} @@ -1274,6 +1487,35 @@ Understanding the nature of knowledge...
+ +
+

+ Wiki Links +

+

+ Create semantic links between content using wiki link syntax: +

+
    +
  • + [[term]] + - Auto link (queries both w and d tags) +
  • +
  • + [[w:term]] + - Reference/mention (backward link) +
  • +
  • + [[d:term]] + - Definition link (forward link) +
  • +
  • + Custom text: [[term|display text]] +
  • +
+

+ Example: "The concept of [[Knowledge Graphs]] enables..." creates a w-tag automatically. +

+
@@ -1431,3 +1673,43 @@ Understanding the nature of knowledge... {/if} + + diff --git a/src/lib/components/cards/BlogHeader.svelte b/src/lib/components/cards/BlogHeader.svelte index 3df794a..80de2e7 100644 --- a/src/lib/components/cards/BlogHeader.svelte +++ b/src/lib/components/cards/BlogHeader.svelte @@ -10,7 +10,8 @@ import LazyImage from "$components/util/LazyImage.svelte"; import { generateDarkPastelColor } from "$lib/utils/image_utils"; import { getNdkContext } from "$lib/ndk"; - + import { deleteEvent } from "$lib/services/deletion"; + const { rootId, event, @@ -25,6 +26,38 @@ const ndk = getNdkContext(); + /** + * Handle deletion of this blog article + */ + async function handleDelete() { + const confirmed = confirm( + "Are you sure you want to delete this article? This action will publish a deletion request to all relays." + ); + + if (!confirmed) return; + + try { + await deleteEvent({ + eventAddress: event.tagAddress(), + eventKind: event.kind, + reason: "User deleted article", + onSuccess: (deletionEventId) => { + console.log("[BlogHeader] Deletion event published:", deletionEventId); + // Call onBlogUpdate if provided to refresh the list + if (onBlogUpdate) { + onBlogUpdate(); + } + }, + onError: (error) => { + console.error("[BlogHeader] Deletion failed:", error); + alert(`Failed to delete article: ${error}`); + }, + }, ndk); + } catch (error) { + console.error("[BlogHeader] Deletion error:", error); + } + } + let title: string = $derived(event.getMatchingTags("title")[0]?.[1]); let author: string = $derived( getMatchingTags(event, "author")[0]?.[1] ?? "unknown", @@ -106,7 +139,7 @@
- +
diff --git a/src/lib/components/publications/CommentButton.svelte b/src/lib/components/publications/CommentButton.svelte new file mode 100644 index 0000000..fb6ee25 --- /dev/null +++ b/src/lib/components/publications/CommentButton.svelte @@ -0,0 +1,520 @@ + + + +
+ + + + {#if showCommentUI} +
+
+

Add Comment

+ {#if $userStore.profile} + + {/if} +
+ + `, + })), + P: vi.fn().mockImplementation(() => ({ + $$render: () => `

`, + })), +})); + +// Mock flowbite-svelte-icons +vi.mock("flowbite-svelte-icons", () => ({ + FontHighlightOutline: vi.fn().mockImplementation(() => ({ + $$render: () => ``, + })), +})); + +describe("HighlightButton Component Logic", () => { + let isActive: boolean; + + beforeEach(() => { + isActive = false; + }); + + describe("Initial State", () => { + it("should initialize with inactive state", () => { + expect(isActive).toBe(false); + }); + + it("should have correct inactive label", () => { + const label = isActive ? "Exit Highlight Mode" : "Add Highlight"; + expect(label).toBe("Add Highlight"); + }); + + it("should have correct inactive title", () => { + const title = isActive ? "Exit highlight mode" : "Enter highlight mode"; + expect(title).toBe("Enter highlight mode"); + }); + + it("should have correct inactive color", () => { + const color = isActive ? "primary" : "light"; + expect(color).toBe("light"); + }); + + it("should not have ring styling when inactive", () => { + const ringClass = isActive ? "ring-2 ring-primary-500" : ""; + expect(ringClass).toBe(""); + }); + }); + + describe("Toggle Functionality", () => { + it("should toggle to active state when clicked", () => { + // Simulate toggle + isActive = !isActive; + expect(isActive).toBe(true); + }); + + it("should toggle back to inactive state on second click", () => { + // Simulate two toggles + isActive = !isActive; + isActive = !isActive; + expect(isActive).toBe(false); + }); + + it("should show correct label when active", () => { + isActive = true; + const label = isActive ? "Exit Highlight Mode" : "Add Highlight"; + expect(label).toBe("Exit Highlight Mode"); + }); + + it("should show correct title when active", () => { + isActive = true; + const title = isActive ? "Exit highlight mode" : "Enter highlight mode"; + expect(title).toBe("Exit highlight mode"); + }); + }); + + describe("Active State Styling", () => { + it("should apply primary color when active", () => { + isActive = true; + const color = isActive ? "primary" : "light"; + expect(color).toBe("primary"); + }); + + it("should apply ring styling when active", () => { + isActive = true; + const ringClass = isActive ? "ring-2 ring-primary-500" : ""; + expect(ringClass).toBe("ring-2 ring-primary-500"); + }); + }); +}); + +describe("HighlightSelectionHandler Component Logic", () => { + let mockNDK: NDKEvent; + let mockUserStore: any; + let mockSelection: Selection; + let mockPublicationEvent: NDKEvent; + let isActive: boolean; + + beforeEach(() => { + // Reset mocks + vi.clearAllMocks(); + isActive = false; + + // Mock document and DOM elements + const mockElement = { + createElement: vi.fn((tag: string) => ({ + tagName: tag.toUpperCase(), + textContent: "", + className: "", + closest: vi.fn(), + parentElement: null, + })), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + body: { + classList: { + add: vi.fn(), + remove: vi.fn(), + }, + }, + }; + + global.document = mockElement as any; + + // Mock NDK event + mockPublicationEvent = { + id: "test-event-id", + pubkey: "test-pubkey", + kind: 30023, + tagAddress: vi.fn().mockReturnValue("30023:test-pubkey:test-d-tag"), + tags: [], + content: "", + } as unknown as NDKEvent; + + // Mock user store + mockUserStore = { + signedIn: true, + signer: { + sign: vi.fn().mockResolvedValue(undefined), + }, + }; + + // Mock window.getSelection + const mockParagraph = { + textContent: "This is the full paragraph context", + closest: vi.fn(), + }; + + mockSelection = { + toString: vi.fn().mockReturnValue("Selected text from publication"), + isCollapsed: false, + removeAllRanges: vi.fn(), + anchorNode: { + parentElement: mockParagraph, + }, + } as unknown as Selection; + + global.window = { + getSelection: vi.fn().mockReturnValue(mockSelection), + } as any; + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + describe("Selection Detection", () => { + it("should ignore mouseup events when isActive is false", () => { + isActive = false; + const shouldProcess = isActive; + expect(shouldProcess).toBe(false); + }); + + it("should process mouseup events when isActive is true", () => { + isActive = true; + const shouldProcess = isActive; + expect(shouldProcess).toBe(true); + }); + + it("should ignore collapsed selections", () => { + const selection = { isCollapsed: true } as Selection; + const shouldIgnore = selection.isCollapsed; + expect(shouldIgnore).toBe(true); + }); + + it("should process non-collapsed selections", () => { + const selection = { isCollapsed: false } as Selection; + const shouldIgnore = selection.isCollapsed; + expect(shouldIgnore).toBe(false); + }); + + it("should ignore selections with less than 3 characters", () => { + const text = "ab"; + const isValid = text.length >= 3; + expect(isValid).toBe(false); + }); + + it("should accept selections with 3 or more characters", () => { + const text = "abc"; + const isValid = text.length >= 3; + expect(isValid).toBe(true); + }); + + it("should ignore empty selections after trim", () => { + const text = " "; + const trimmed = text.trim(); + const isValid = trimmed.length >= 3; + expect(isValid).toBe(false); + }); + }); + + describe("User Authentication", () => { + it("should reject selection when user not signed in", () => { + const userStore = { signedIn: false }; + expect(userStore.signedIn).toBe(false); + }); + + it("should process selection when user signed in", () => { + const userStore = { signedIn: true }; + expect(userStore.signedIn).toBe(true); + }); + + it("should check for signer before creating highlight", () => { + const userStore = { + signedIn: true, + signer: { sign: vi.fn() }, + }; + expect(userStore.signer).toBeDefined(); + }); + + it("should reject creation without signer", () => { + const userStore = { + signedIn: true, + signer: null, + }; + expect(userStore.signer).toBeNull(); + }); + }); + + describe("Publication Context Detection", () => { + it("should detect selection within publication-leather class", () => { + const mockElement = { + className: "publication-leather", + closest: vi.fn((selector: string) => { + return selector === ".publication-leather" ? mockElement : null; + }), + }; + const target = mockElement; + const publicationSection = target.closest(".publication-leather"); + expect(publicationSection).toBeTruthy(); + }); + + it("should reject selection outside publication-leather class", () => { + const mockElement = { + className: "other-section", + closest: vi.fn((selector: string) => { + return selector === ".publication-leather" ? null : mockElement; + }), + }; + const target = mockElement; + const publicationSection = target.closest(".publication-leather"); + expect(publicationSection).toBeNull(); + }); + }); + + describe("Context Extraction", () => { + it("should extract context from parent paragraph", () => { + const paragraph = { + textContent: "This is the full paragraph context with selected text inside.", + }; + + const context = paragraph.textContent?.trim() || ""; + expect(context).toBe("This is the full paragraph context with selected text inside."); + }); + + it("should extract context from parent section", () => { + const section = { + textContent: "Full section context including selected text.", + }; + + const context = section.textContent?.trim() || ""; + expect(context).toBe("Full section context including selected text."); + }); + + it("should extract context from parent div", () => { + const div = { + textContent: "Full div context including selected text.", + }; + + const context = div.textContent?.trim() || ""; + expect(context).toBe("Full div context including selected text."); + }); + + it("should handle missing context gracefully", () => { + const context = ""; + expect(context).toBe(""); + }); + }); + + describe("NIP-84 Event Creation - Addressable Events", () => { + it("should use 'a' tag for addressable events", () => { + const eventAddress = "30023:pubkey:d-tag"; + const tags: string[][] = []; + + if (eventAddress) { + tags.push(["a", eventAddress, ""]); + } + + expect(tags).toContainEqual(["a", eventAddress, ""]); + }); + + it("should create event with correct kind 9802", () => { + const event = { + kind: 9802, + content: "", + tags: [], + }; + + expect(event.kind).toBe(9802); + }); + + it("should include selected text as content", () => { + const selectedText = "This is the selected highlight text"; + const event = { + kind: 9802, + content: selectedText, + tags: [], + }; + + expect(event.content).toBe(selectedText); + }); + + it("should include context tag", () => { + const context = "This is the surrounding context"; + const tags: string[][] = []; + + if (context) { + tags.push(["context", context]); + } + + expect(tags).toContainEqual(["context", context]); + }); + + it("should include author p-tag with role", () => { + const pubkey = "author-pubkey-hex"; + const tags: string[][] = []; + + if (pubkey) { + tags.push(["p", pubkey, "", "author"]); + } + + expect(tags).toContainEqual(["p", pubkey, "", "author"]); + }); + + it("should include comment tag when comment provided", () => { + const comment = "This is my insightful comment"; + const tags: string[][] = []; + + if (comment.trim()) { + tags.push(["comment", comment.trim()]); + } + + expect(tags).toContainEqual(["comment", comment]); + }); + + it("should not include comment tag when comment is empty", () => { + const comment = ""; + const tags: string[][] = []; + + if (comment.trim()) { + tags.push(["comment", comment.trim()]); + } + + expect(tags).not.toContainEqual(["comment", ""]); + expect(tags.length).toBe(0); + }); + + it("should not include comment tag when comment is only whitespace", () => { + const comment = " "; + const tags: string[][] = []; + + if (comment.trim()) { + tags.push(["comment", comment.trim()]); + } + + expect(tags.length).toBe(0); + }); + }); + + describe("NIP-84 Event Creation - Regular Events", () => { + it("should use 'e' tag for regular events", () => { + const eventId = "regular-event-id"; + const eventAddress = null; // No address means regular event + const tags: string[][] = []; + + if (eventAddress) { + tags.push(["a", eventAddress, ""]); + } else { + tags.push(["e", eventId, ""]); + } + + expect(tags).toContainEqual(["e", eventId, ""]); + }); + + it("should prefer addressable event over regular event", () => { + const eventId = "regular-event-id"; + const eventAddress = "30023:pubkey:d-tag"; + const tags: string[][] = []; + + if (eventAddress) { + tags.push(["a", eventAddress, ""]); + } else { + tags.push(["e", eventId, ""]); + } + + expect(tags).toContainEqual(["a", eventAddress, ""]); + expect(tags).not.toContainEqual(["e", eventId, ""]); + }); + }); + + describe("Complete Event Structure", () => { + it("should create complete highlight event with all required tags", () => { + const selectedText = "Highlighted text"; + const context = "Full context paragraph"; + const pubkey = "author-pubkey"; + const eventAddress = "30023:pubkey:d-tag"; + + const event = { + kind: 9802, + content: selectedText, + tags: [ + ["a", eventAddress, ""], + ["context", context], + ["p", pubkey, "", "author"], + ], + }; + + expect(event.kind).toBe(9802); + expect(event.content).toBe(selectedText); + expect(event.tags).toHaveLength(3); + expect(event.tags[0]).toEqual(["a", eventAddress, ""]); + expect(event.tags[1]).toEqual(["context", context]); + expect(event.tags[2]).toEqual(["p", pubkey, "", "author"]); + }); + + it("should create complete quote highlight with comment", () => { + const selectedText = "Highlighted text"; + const context = "Full context paragraph"; + const pubkey = "author-pubkey"; + const eventAddress = "30023:pubkey:d-tag"; + const comment = "My thoughtful comment"; + + const event = { + kind: 9802, + content: selectedText, + tags: [ + ["a", eventAddress, ""], + ["context", context], + ["p", pubkey, "", "author"], + ["comment", comment], + ], + }; + + expect(event.kind).toBe(9802); + expect(event.content).toBe(selectedText); + expect(event.tags).toHaveLength(4); + expect(event.tags[3]).toEqual(["comment", comment]); + }); + + it("should handle event without context", () => { + const selectedText = "Highlighted text"; + const context = ""; + const pubkey = "author-pubkey"; + const eventId = "event-id"; + + const tags: string[][] = []; + tags.push(["e", eventId, ""]); + if (context) { + tags.push(["context", context]); + } + tags.push(["p", pubkey, "", "author"]); + + expect(tags).toHaveLength(2); + expect(tags).not.toContainEqual(["context", ""]); + }); + }); + + describe("Event Signing and Publishing", () => { + it("should sign event before publishing", async () => { + const mockSigner = { + sign: vi.fn().mockResolvedValue(undefined), + }; + + const mockEvent = { + kind: 9802, + content: "test", + tags: [], + sign: vi.fn().mockResolvedValue(undefined), + publish: vi.fn().mockResolvedValue(undefined), + }; + + await mockEvent.sign(mockSigner); + expect(mockEvent.sign).toHaveBeenCalledWith(mockSigner); + }); + + it("should publish event after signing", async () => { + const mockEvent = { + sign: vi.fn().mockResolvedValue(undefined), + publish: vi.fn().mockResolvedValue(undefined), + }; + + await mockEvent.sign({}); + await mockEvent.publish(); + + expect(mockEvent.publish).toHaveBeenCalled(); + }); + + it("should handle signing errors", async () => { + const mockEvent = { + sign: vi.fn().mockRejectedValue(new Error("Signing failed")), + }; + + await expect(mockEvent.sign({})).rejects.toThrow("Signing failed"); + }); + + it("should handle publishing errors", async () => { + const mockEvent = { + sign: vi.fn().mockResolvedValue(undefined), + publish: vi.fn().mockRejectedValue(new Error("Publishing failed")), + }; + + await mockEvent.sign({}); + await expect(mockEvent.publish()).rejects.toThrow("Publishing failed"); + }); + }); + + describe("Selection Cleanup", () => { + it("should clear selection after successful highlight creation", () => { + const mockSelection = { + removeAllRanges: vi.fn(), + }; + + mockSelection.removeAllRanges(); + expect(mockSelection.removeAllRanges).toHaveBeenCalled(); + }); + + it("should reset selectedText after creation", () => { + let selectedText = "Some text"; + selectedText = ""; + expect(selectedText).toBe(""); + }); + + it("should reset comment after creation", () => { + let comment = "Some comment"; + comment = ""; + expect(comment).toBe(""); + }); + + it("should reset context after creation", () => { + let context = "Some context"; + context = ""; + expect(context).toBe(""); + }); + + it("should close modal after creation", () => { + let showModal = true; + showModal = false; + expect(showModal).toBe(false); + }); + }); + + describe("Cancel Functionality", () => { + it("should clear selection when cancelled", () => { + const mockSelection = { + removeAllRanges: vi.fn(), + }; + + // Simulate cancel + mockSelection.removeAllRanges(); + expect(mockSelection.removeAllRanges).toHaveBeenCalled(); + }); + + it("should reset all state when cancelled", () => { + let selectedText = "text"; + let comment = "comment"; + let context = "context"; + let showModal = true; + + // Simulate cancel + selectedText = ""; + comment = ""; + context = ""; + showModal = false; + + expect(selectedText).toBe(""); + expect(comment).toBe(""); + expect(context).toBe(""); + expect(showModal).toBe(false); + }); + }); + + describe("Feedback Messages", () => { + it("should show success message after creation", () => { + const message = "Highlight created successfully!"; + const type = "success"; + + expect(message).toBe("Highlight created successfully!"); + expect(type).toBe("success"); + }); + + it("should show error message on failure", () => { + const message = "Failed to create highlight. Please try again."; + const type = "error"; + + expect(message).toBe("Failed to create highlight. Please try again."); + expect(type).toBe("error"); + }); + + it("should show error when not signed in", () => { + const message = "Please sign in to create highlights"; + const type = "error"; + + expect(message).toBe("Please sign in to create highlights"); + expect(type).toBe("error"); + }); + + it("should auto-hide feedback after delay", () => { + let showFeedback = true; + + // Simulate timeout + setTimeout(() => { + showFeedback = false; + }, 3000); + + // Initially shown + expect(showFeedback).toBe(true); + }); + }); + + describe("Event Listeners", () => { + it("should add mouseup listener on mount", () => { + const mockAddEventListener = vi.fn(); + document.addEventListener = mockAddEventListener; + + document.addEventListener("mouseup", () => {}); + expect(mockAddEventListener).toHaveBeenCalledWith("mouseup", expect.any(Function)); + }); + + it("should remove mouseup listener on unmount", () => { + const mockRemoveEventListener = vi.fn(); + document.removeEventListener = mockRemoveEventListener; + + const handler = () => {}; + document.removeEventListener("mouseup", handler); + expect(mockRemoveEventListener).toHaveBeenCalledWith("mouseup", handler); + }); + }); + + describe("Highlight Mode Body Class", () => { + it("should add highlight-mode-active class when active", () => { + const mockClassList = { + add: vi.fn(), + remove: vi.fn(), + }; + document.body.classList = mockClassList as any; + + // Simulate active mode + document.body.classList.add("highlight-mode-active"); + expect(mockClassList.add).toHaveBeenCalledWith("highlight-mode-active"); + }); + + it("should remove highlight-mode-active class when inactive", () => { + const mockClassList = { + add: vi.fn(), + remove: vi.fn(), + }; + document.body.classList = mockClassList as any; + + // Simulate inactive mode + document.body.classList.remove("highlight-mode-active"); + expect(mockClassList.remove).toHaveBeenCalledWith("highlight-mode-active"); + }); + + it("should clean up class on unmount", () => { + const mockClassList = { + add: vi.fn(), + remove: vi.fn(), + }; + document.body.classList = mockClassList as any; + + // Simulate cleanup + document.body.classList.remove("highlight-mode-active"); + expect(mockClassList.remove).toHaveBeenCalledWith("highlight-mode-active"); + }); + }); + + describe("Modal Display", () => { + it("should show modal when text is selected", () => { + let showModal = false; + + // Simulate successful selection + showModal = true; + expect(showModal).toBe(true); + }); + + it("should display selected text in modal", () => { + const selectedText = "This is the selected text"; + const displayText = `"${selectedText}"`; + + expect(displayText).toBe('"This is the selected text"'); + }); + + it("should provide textarea for optional comment", () => { + let comment = ""; + const placeholder = "Share your thoughts about this highlight..."; + + expect(placeholder).toBe("Share your thoughts about this highlight..."); + expect(comment).toBe(""); + }); + + it("should disable buttons while submitting", () => { + const isSubmitting = true; + const disabled = isSubmitting; + + expect(disabled).toBe(true); + }); + + it("should show 'Creating...' text while submitting", () => { + const isSubmitting = true; + const buttonText = isSubmitting ? "Creating..." : "Create Highlight"; + + expect(buttonText).toBe("Creating..."); + }); + + it("should show normal text when not submitting", () => { + const isSubmitting = false; + const buttonText = isSubmitting ? "Creating..." : "Create Highlight"; + + expect(buttonText).toBe("Create Highlight"); + }); + }); + + describe("Callback Execution", () => { + it("should call onHighlightCreated callback after creation", () => { + const mockCallback = vi.fn(); + + // Simulate successful creation + mockCallback(); + + expect(mockCallback).toHaveBeenCalled(); + }); + + it("should not call callback if creation fails", () => { + const mockCallback = vi.fn(); + + // Simulate failed creation - callback not called + expect(mockCallback).not.toHaveBeenCalled(); + }); + + it("should handle missing callback gracefully", () => { + const callback = undefined; + + // Should not throw error + expect(() => { + if (callback) { + callback(); + } + }).not.toThrow(); + }); + }); + + describe("Integration Scenarios", () => { + it("should handle complete highlight workflow", () => { + // Setup + let isActive = true; + let showModal = false; + let selectedText = ""; + const userSignedIn = true; + const selection = { + toString: () => "Selected text for highlighting", + isCollapsed: false, + }; + + // User selects text + if (isActive && userSignedIn && !selection.isCollapsed) { + selectedText = selection.toString(); + showModal = true; + } + + expect(selectedText).toBe("Selected text for highlighting"); + expect(showModal).toBe(true); + }); + + it("should handle complete quote highlight workflow with comment", () => { + // Setup + let isActive = true; + let showModal = false; + let selectedText = ""; + let comment = ""; + const userSignedIn = true; + const selection = { + toString: () => "Selected text", + isCollapsed: false, + }; + + // User selects text + if (isActive && userSignedIn && !selection.isCollapsed) { + selectedText = selection.toString(); + showModal = true; + } + + // User adds comment + comment = "This is insightful"; + + // Create event with comment + const tags: string[][] = []; + if (comment.trim()) { + tags.push(["comment", comment]); + } + + expect(selectedText).toBe("Selected text"); + expect(comment).toBe("This is insightful"); + expect(tags).toContainEqual(["comment", "This is insightful"]); + }); + + it("should reject workflow when user not signed in", () => { + let isActive = true; + let showModal = false; + const userSignedIn = false; + const selection = { + toString: () => "Selected text", + isCollapsed: false, + }; + + // User tries to select text + if (isActive && userSignedIn && !selection.isCollapsed) { + showModal = true; + } + + expect(showModal).toBe(false); + }); + + it("should handle workflow cancellation", () => { + // Setup initial state + let showModal = true; + let selectedText = "Some text"; + let comment = "Some comment"; + const mockSelection = { + removeAllRanges: vi.fn(), + }; + + // User cancels + showModal = false; + selectedText = ""; + comment = ""; + mockSelection.removeAllRanges(); + + expect(showModal).toBe(false); + expect(selectedText).toBe(""); + expect(comment).toBe(""); + expect(mockSelection.removeAllRanges).toHaveBeenCalled(); + }); + }); +});