138 Commits
Author SHA1 Message Date
Chad Curtis 346cea5f89 hi 2025-07-14 21:58:29 +00:00
Chad Curtis 3d97870b59 init 2025-07-14 21:40:30 +00:00
Alex Gleason 0cda9cb7fc LoginDialog: use a password input
Fixes https://gitlab.com/soapbox-pub/mkstack/-/issues/13
2025-07-03 19:14:11 -05:00
Alex Gleason 49952a10bf Parse AppConfig with a zod schema 2025-07-03 19:04:40 -05:00
Alex Gleason fce2a3da23 Give Dork 1 beer 2025-06-26 17:57:28 -05:00
Alex Gleason 15dbc6df85 AccountSwitcher: modal={false} 2025-06-26 10:35:59 -05:00
Alex Gleason 508fa84466 Default to Primal relay 2025-06-24 20:38:59 -05:00
Alex Gleason b7ff219e6e avatar: object-cover 2025-06-23 22:49:53 -05:00
Alex Gleason b9750b3759 Update "Vibe with MKStack" link 2025-06-21 14:33:00 -05:00
Alex Gleason ad1c8b123c "Efficient Query Design" 2025-06-17 19:39:47 -05:00
Alex Gleason 4e1c43ee13 npm audit fix 2025-06-16 14:11:01 -05:00
Alex Gleason 1e179b4396 Add AbortSignal polyfills 2025-06-15 12:35:47 -05:00
Alex Gleason cd5376ff49 Add missing nostr__ server prefixes 2025-06-15 10:55:39 -05:00
Alex Gleason 561975cded Add @latest to js-dev-mcp 2025-06-14 22:37:43 -05:00
Alex Gleason 7a5fce4933 Use js-dev-mcp from npm 2025-06-14 22:36:58 -05:00
Alex Gleason 8559a004e8 Simplify "Nostr Implementation Guidelines" again 2025-06-13 22:09:06 -05:00
Alex Gleason df40d30f15 Emphasize "Nostr Implementation Guidelines" section 2025-06-13 20:59:25 -05:00
Alex Gleason 062545d061 Use fully qualified tool names in CONTEXT.md 2025-06-13 20:56:15 -05:00
Alex Gleason 9625533ed4 Add t-tag guidance 2025-06-13 19:49:46 -05:00
Alex Gleason db09c45a54 "Testing Your Changes" tweak for Gemini 2025-06-13 18:54:50 -05:00
Alex Gleason ed143157bf Add "Thorough NIP Review" bullet for Gemini Flash 2025-06-13 18:53:28 -05:00
Alex Gleason 9646620a46 Merge branch 'nostr-deploy' into 'main'
Update deploy command in package.json to use nostr-deploy-cli

See merge request soapbox-pub/mkstack!6
2025-06-11 19:23:17 +00:00
sepehr-safari 830c10fe8d Update deploy command in package.json to use nostr-deploy-cli 2025-06-11 22:15:41 +03:00
Alex Gleason 927010c0d0 1 minute timeout 2025-06-09 22:35:34 -05:00
Alex Gleason e70b3640e8 Remove prerendering after all 2025-06-09 22:30:09 -05:00
Alex Gleason 1983126de9 Prerender with Puppeteer 2025-06-09 22:03:22 -05:00
Alex Gleason 87d3cfb2eb Add manifest link to head 2025-06-09 21:19:43 -05:00
Alex Gleason 98aa853716 Teach the robot to use tags instead of json data in content 2025-06-09 15:16:17 -05:00
Alex Gleason 5d4a19eb9c Vibed by -> Vibed with 2025-06-09 09:24:03 -05:00
Alex Gleason 10386c2c38 Avoid any type 2025-06-09 00:24:57 -05:00
Alex Gleason 034b5eab33 Vibed by MKStack 2025-06-08 23:54:04 -05:00
Alex Gleason fddd1d20f3 Run vercel with npx, remove as dev dependency 2025-06-08 09:36:22 -05:00
Alex Gleason aa1088499f Merge branch 'vercel-deploy' into 'main'
Add Vercel as a devDependency and update deploy command to replace Surge with Vercel

See merge request soapbox-pub/mkstack!5
2025-06-08 13:15:56 +00:00
sepehr-safari c07a53e727 Add Vercel as a devDependency and update deploy command to replace Surge with Vercel 2025-06-08 15:50:28 +03:00
Alex Gleason 68202d655e Add InferSeoMetaPlugin 2025-06-07 16:37:03 -05:00
Alex Gleason 641f570329 Only add the client tag if the page is served over https 2025-06-07 16:32:28 -05:00
Alex Gleason c2d5187efb Add information about tags to context 2025-06-07 16:24:11 -05:00
Alex Gleason 9ad31aa674 Add clarifying section about creating new kinds vs using existing kinds 2025-06-07 15:47:56 -05:00
Alex Gleason d1a4e26f79 Add Unhead 2025-06-07 15:19:21 -05:00
Alex Gleason b3bc9d45e0 Tell the robot to use the generate_kind tool 2025-06-07 14:29:29 -05:00
Alex Gleason 1b74dc38fd Switch to Nostrbook MCP from npm 2025-06-07 13:58:00 -05:00
Alex Gleason 7a7d91dbed Add no-inline-script eslint rule 2025-06-07 10:56:52 -05:00
Alex Gleason 2d325f7343 inter -> font-name 2025-06-06 14:28:01 -05:00
Alex Gleason d2854f917c Add event validation step to context 2025-06-05 05:23:23 -05:00
Alex Gleason 28cda6d365 Remove unnecessary text 2025-06-04 18:34:23 -05:00
Alex Gleason da87f2c7b1 RelaySelector should not accept any props 2025-06-04 18:32:45 -05:00
Alex Gleason 61508020ae Tell the robot to manage a NIP.md file 2025-06-04 17:56:30 -05:00
Alex Gleason f146bf58d7 Add a sane default CSP 2025-06-04 13:07:41 -05:00
Alex Gleason cd87b6e430 Publish to preset relays 2025-06-04 11:32:12 -05:00
Alex Gleason 696c5ba963 Bully the robot to use skeletons instead of spinners 2025-06-04 11:00:35 -05:00
Alex Gleason 36e49106a6 Update CONTEXT.md with latest changes 2025-06-04 10:35:07 -05:00
Alex Gleason 048bf4cc69 Refactor AppProvider, AppConfig and presetRelays 2025-06-04 10:20:31 -05:00
Alex Gleason 3ad83cd114 Refactor AppProvider 2025-06-04 10:06:38 -05:00
Alex Gleason c3310ab485 Consolidate ThemeProvider and AppProvider 2025-06-04 09:42:53 -05:00
Alex Gleason bce7af2e76 Remove dark mode text from CONTEXT.md 2025-06-04 09:15:25 -05:00
Alex Gleason f762136f14 Remove Spinner and don't lazy-load components 2025-06-04 09:14:44 -05:00
Alex Gleason 5b90ebe482 Prevent the bot from disabling eslint rules 2025-06-02 22:35:07 -05:00
Alex Gleason c2ff2a990f Reorder relays 2025-06-02 22:13:22 -05:00
Alex Gleason 0481cd024e Tweak the default relay list 2025-06-02 22:08:03 -05:00
Alex Gleason 1617d80ece Use hostname in client tag 2025-06-02 22:05:03 -05:00
Alex Gleason a8163d7a6c Add RelaySelector 2025-06-02 21:46:07 -05:00
Alex Gleason 190f0cd791 Switch back to relay.nostr.band 2025-06-02 18:41:06 -05:00
Alex Gleason aa4110e6b3 CONTEXT.md tweaks 2025-06-02 15:25:16 -05:00
Alex Gleason 94d1688f43 Loosen color scheme phrasing 2025-06-02 11:53:12 -05:00
Alex Gleason 9f12c58dc0 Add Design Customization section to CONTEXT.md 2025-06-02 10:53:54 -05:00
Alex Gleason 0ee653f631 Make light theme the default 2025-06-02 10:14:56 -05:00
Alex Gleason 3672a13ac8 Bully the robot to add a custom font 2025-06-02 10:13:20 -05:00
Alex Gleason ac46749fad Don't write tests so religiously 2025-06-01 21:34:11 -05:00
Alex Gleason 1fc548c7e9 Improve eslint rules for unused vars 2025-06-01 17:28:25 -05:00
Alex Gleason 8bdff8da6d Lazy load page components 2025-06-01 16:26:09 -05:00
Alex Gleason 3a34db8320 Add dark theme support to NotFound.tsx 2025-06-01 16:08:27 -05:00
Alex Gleason 065f3cfe02 Suppress only React Router Future warnings in tests 2025-06-01 15:36:05 -05:00
Alex Gleason ed2d3798ea Silence console output from passed tests 2025-06-01 14:28:02 -05:00
Alex Gleason 03f804ed90 Clarify signer usage 2025-06-01 11:57:37 -05:00
Alex Gleason aa1e2145d0 Fix NoteContent test 2025-06-01 11:12:35 -05:00
Alex Gleason 130300f1c1 Use generated username fallback in other parts of the UI 2025-06-01 11:11:13 -05:00
Alex Gleason 9cb2795496 Add genUserName module 2025-06-01 11:04:22 -05:00
Alex Gleason 34770a3145 LoginArea display and context improvements 2025-06-01 11:00:53 -05:00
Alex Gleason 37bee859b6 Upgrade Vite to 6.x, fixing dependency vulnerability 2025-06-01 09:58:00 -05:00
Alex Gleason 139e6696db Improve LoginArea sizing and space 2025-06-01 09:47:15 -05:00
Alex Gleason 738b512d9c ThemeProvider nitpicks 2025-06-01 09:37:49 -05:00
Alex Gleason 7c5fe75572 Generate a deterministic name from pubkey if no display name is set 2025-06-01 09:28:20 -05:00
Alex Gleason 865ca7039f Improve NoteContent and NoteContent tests 2025-06-01 09:20:00 -05:00
Alex Gleason acbe053c97 Add nip19 routing info to CONTEXT.md 2025-06-01 08:57:58 -05:00
Alex Gleason 830d806933 NoteContent can linkify any kind, add TestApp component and "Testing Your Changes" to CONTEXT.md 2025-06-01 08:39:33 -05:00
Alex Gleason ee42c84171 Scroll to top during navigation changes 2025-06-01 07:32:33 -05:00
Alex Gleason 98f3305aa1 Add FIXME comment to Index.tsx 2025-05-31 00:03:40 +02:00
Alex Gleason 2d326ca5e9 Remove ThemeToggle component 2025-05-31 00:01:08 +02:00
Alex Gleason dbd28373a5 Require additional index.html properties 2025-05-30 23:58:38 +02:00
Alex Gleason ed3080d34e Return errors for FIXME comments 2025-05-30 23:46:15 +02:00
Alex Gleason 79ed87e67c useNostrPublish returns the event 2025-05-30 23:40:57 +02:00
Alex Gleason 9221693edb Remove theme toggle from CONTEXT.md 2025-05-30 23:38:20 +02:00
Alex Gleason 1b8dab92b9 webmanifest eslint 2025-05-30 23:02:12 +02:00
Alex Gleason 95de9fde27 eslint HTML title 2025-05-30 22:58:43 +02:00
Alex Gleason 81f90b9985 Add dark theme support to placeholder index 2025-05-30 22:48:59 +02:00
Alex Gleason 0e8a141490 Add custom eslint rule: no-placeholder-comments 2025-05-30 22:45:59 +02:00
Alex Gleason a6eeb05d6e Add ThemeProvider 2025-05-30 22:38:23 +02:00
Alex Gleason e0d94fae71 Add GitLab CI file 2025-05-30 22:19:04 +02:00
Alex Gleason be2d2d63fa Add PWA _redirects file 2025-05-30 22:18:50 +02:00
Alex Gleason f633f4b423 Use claude sonnet, not opus 2025-05-29 22:11:40 +02:00
Alex Gleason 2c5d38013f Switch to Ditto relay, don't include intentional error in App.tsx lol 2025-05-27 23:48:03 +02:00
Alex Gleason d14652559e Add test suite 2025-05-27 23:10:17 +02:00
Alex Gleason 4254b9eb0b Change phrasing of relay list AI comments 2025-05-27 22:44:48 +02:00
Alex Gleason e099d8b467 Merge branch 'eslint' into 'main'
Add eslint to ci

See merge request soapbox-pub/mkstack!4
2025-05-23 10:40:36 +00:00
Alex Gleason ef7667501b Add eslint to ci 2025-05-23 12:39:21 +02:00
Alex Gleason 7edfde7e9f Upgrade model to claude-sonnet-4 2025-05-22 21:38:26 +02:00
Alex Gleason 69faf49454 Add max width to AccountSwitcher 2025-05-20 03:32:37 -05:00
Alex Gleason aa2468b656 Kind 1 text rendering 2025-05-17 00:37:39 -05:00
Alex Gleason 7ee419bc6d Stop setting wrong relay URLs 2025-05-16 18:30:47 -05:00
Alex Gleason 73e7e818b2 Improve AccountSwitcher without kind 0 2025-05-16 14:09:28 -05:00
Alex Gleason ebc399776d Fix SignupDialog (so it logs the user in immediately after generating the key) 2025-05-16 13:55:12 -05:00
Alex Gleason 56df17b56e CONTEXT: fix Nostr headings depth 2025-05-16 13:47:14 -05:00
Alex Gleason 856d333c30 CONTEXT: encryption and decryption 2025-05-16 13:43:59 -05:00
Alex Gleason b24578f0db CONTEXT: LoginArea should not be wrapped in any conditional logic 2025-05-16 12:30:41 -05:00
Alex Gleason cc3d87192c Add a "client" tag to all published events 2025-05-16 12:28:01 -05:00
Alex Gleason 70eceef6ae Fix ci script type checking 2025-05-14 23:09:39 -05:00
Alex Gleason 601b3ce370 Add file uploads with Blossom 2025-05-14 17:15:00 -05:00
Alex Gleason f77a6a4af3 Add EditProfileForm 2025-05-14 15:56:53 -05:00
Alex Gleason d05a78880a CONTEXT.md: small correction for nip19 identifiers 2025-05-14 12:00:02 -05:00
Alex Gleason 750c165c05 Merge branch 'nip19' into 'main'
Add NIP-19 decoding to context

See merge request soapbox-pub/mkstack!3
2025-05-10 21:55:00 +00:00
Alex Gleason aa91528de8 Add NIP-19 decoding to context 2025-05-10 16:54:06 -05:00
Alex Gleason 95eb9634b5 Upgrade Nostrify 2025-05-10 10:00:02 -05:00
Alex Gleason 69060820f8 Include 404.html in build 2025-05-09 19:23:25 -05:00
Alex Gleason 1a431c9d8a Add useAuthor code snippet to CONTEXT.md 2025-05-09 16:10:33 -05:00
Alex Gleason 246ffb2181 Improve stack image 2025-05-07 11:19:08 -05:00
Alex Gleason db13869675 Improve stack banner 2025-05-07 10:41:39 -05:00
Alex Gleason b8137d0751 Change stack banner image 2025-05-06 18:06:03 -05:00
Alex Gleason 16ca716db2 add stack image 2025-05-05 21:47:02 -05:00
Alex Gleason 70dec2fc9a Add stack.json, mcp.json -> agent.json 2025-05-05 21:15:37 -05:00
Alex Gleason cac4ae6b93 Upgrade @nostrify/react 2025-05-04 18:40:41 -05:00
Alex Gleason a7fcaaf1f3 Add mcp.json 2025-05-03 16:26:06 -05:00
Alex Gleason 3052ce66f1 Merge branch 'fix-mac-issue' into 'main'
Fix mac issue

See merge request soapbox-pub/mkstack!2
2025-05-02 15:43:50 +00:00
danidfra 87a0846bbe Fix mac issue 2025-05-02 12:40:51 -03:00
Alex Gleason e4d081d3da Add npm deploy script 2025-04-26 13:59:26 -05:00
Alex Gleason d623f11653 Add GitHub Pages deploy action 2025-04-25 13:46:43 -05:00
Alex Gleason 2ac30c4f29 Use just relay.nostr.band as the default relay for now 2025-04-25 09:50:32 -05:00
Alex Gleason b8603ff80e Remove unused App.css 2025-04-25 09:43:03 -05:00
Alex Gleason 3cc2fe6d64 Add a placeholder useNostr hook 2025-04-25 09:32:43 -05:00
80 changed files with 8721 additions and 3571 deletions

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
name: Deploy to GitHub Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Install dependencies and build
run: |
npm install
npm run build
cp dist/index.html dist/404.html
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: dist
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+30
View File
@@ -0,0 +1,30 @@
name: Test
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
- name: Clean install dependencies
run: |
rm -rf node_modules package-lock.json
npm install
- name: Run tests
run: npm run test
+3
View File
@@ -20,3 +20,6 @@ dist-ssr
*.njsproj
*.sln
*.sw?
# Vercel
.vercel
+30
View File
@@ -0,0 +1,30 @@
image: node:22
default:
interruptible: true
timeout: 1 minute
stages:
- build
- deploy
build:
stage: build
script:
- npm run build
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
pages:
stage: deploy
script:
- npm run build
- rm -rf public
- mv dist public
artifacts:
paths:
- public
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
+670 -19
View File
@@ -9,17 +9,35 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/hooks/`: Custom hooks including `useNostr` and `useNostrQuery`
- `/src/pages/`: Page components used by React Router
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
@@ -42,7 +60,7 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
@@ -75,10 +93,174 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -115,11 +297,148 @@ function usePosts() {
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project.
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
@@ -163,13 +482,199 @@ function MyComponent() {
<div>
{/* other components ... */}
<LoginArea />
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It handles all the login-related UI and interactions internally, including displaying login dialogs and switching between accounts.
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set identifiers in NIP-19. Their prefixes:
- `npub`: public keys
- `nsec`: private keys
- `note`: note ids
- `nprofile`: a nostr profile
- `nevent`: a nostr event
- `naddr`: a nostr replaceable event coordinate
- `nrelay`: a nostr relay (deprecated)
NIP-19 identifiers include a prefix, the number "1", then a base32-encoded data string.
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Use in URL Paths
For URL routing, use NIP-19 identifiers as path parameters (e.g., `/:nip19`) to create secure, universal links to Nostr events. Decode the identifier and render the appropriate component based on the type:
- Regular events: Use `/nevent1...` paths
- Replaceable/addressable events: Use `/naddr1...` paths
Always use `naddr` identifiers for addressable events instead of just the `d` tag value, as `naddr` contains the author pubkey needed to create secure filters. This prevents security issues where malicious actors could publish events with the same `d` tag to override content.
```ts
// Secure routing with naddr
const decoded = nip19.decode(params.nip19);
if (decoded.type === 'naddr' && decoded.data.kind === 30024) {
// Render ArticlePage component
}
```
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
@@ -178,21 +683,167 @@ The `LoginArea` component displays a "Log in" button when the user is logged out
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to multiple Nostr relays for network redundancy
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Build & Deployment
## Loading States
- Build for production: `npm run build`
- Development build: `npm run build:dev`
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Important for AI Assistants**: Only create tests when the user is experiencing a specific problem or explicitly requests tests. Do not proactively write tests for new features or components unless the user is having issues that require testing to diagnose or resolve.
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you modify code, you should test your changes after you're finished by running:
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
```bash
npm run ci
```
This command will typecheck the code and attempt to build it.
Your task is not considered finished until this test passes without errors.
**Your task is not considered finished until this test passes without errors.**
+116
View File
@@ -0,0 +1,116 @@
# NIP-GNOME: Gnome Speak Translation Protocol
`draft` `optional`
## Abstract
This NIP defines a client-side translation protocol for converting kind 1 (Short Text Note) events into "Gnome Speak" - a whimsical fantasy language that transforms regular text into gnome-themed vocabulary and expressions.
## Motivation
To create an immersive and entertaining experience for users of gnome-themed Nostr clients, where all text content is automatically translated into a consistent fantasy language that maintains readability while adding magical woodland charm.
## Specification
### Translation Scope
- **MUST** translate all kind 1 events (Short Text Notes) into Gnome Speak
- **SHOULD NOT** translate other event kinds to maintain protocol compatibility
- **MUST** preserve original URLs, Nostr references (npub, note, etc.), and hashtags without translation
- **SHOULD** maintain the semantic meaning of the original text
### Translation Rules
#### Vocabulary Substitution
Common words are replaced with gnome-themed equivalents:
- Greetings: `hello` → `greetings, fellow earth-dweller`
- Technology: `computer` → `thinking-box of metal and magic`
- Time: `today` → `this blessed sun-cycle`
- Actions: `go` → `venture forth`
- People: `friend` → `companion of the woodland path`
#### Gnome Expressions
- Exclamations are enhanced with gnome phrases: `!` → `! By my pointy hat!`
- Sentence starters may be added: `In the sacred grove, ...`
- Sentence endings may be appended: `...as the ancients foretold.`
#### Special Formatting
- Bitcoin/crypto terms: `bitcoin` → `✨golden acorns of the digital realm✨`
- Nostr terms: `nostr` → `🍄message-mushroom🍄`
- Greetings: `gm` → `🌅when dew kisses the earth🌅`
### Implementation
#### Client Behavior
Clients implementing this NIP:
1. **MUST** detect kind 1 events
2. **MUST** apply Gnome Speak translation before displaying content
3. **SHOULD** preserve original content for editing/replying
4. **MAY** provide toggle to view original content
5. **SHOULD** indicate when content has been translated
#### Content Preservation
- Original event content **MUST** remain unchanged in storage/transmission
- Translation occurs only at display time
- Replies and quotes **SHOULD** reference original content, not translated
#### Tag Usage
Clients **MAY** add a `t` tag with value `gnome` to indicate gnome-themed content:
```json
{
"kind": 1,
"content": "Hello world!",
"tags": [["t", "gnome"]],
...
}
```
### Example
Original event:
```json
{
"kind": 1,
"content": "Good morning! Having coffee and checking bitcoin prices.",
"tags": [],
...
}
```
Displayed as:
```
"When dew kisses the earth! Partaking of bitter bean brew and witnessing ✨golden acorns of the digital realm✨ values, blessed by the forest spirits."
```
## Rationale
This approach provides:
1. **Immersive Experience**: Creates a consistent fantasy atmosphere
2. **Protocol Compatibility**: No changes to underlying Nostr protocol
3. **Reversibility**: Original content always preserved
4. **Interoperability**: Non-gnome clients display original content normally
## Security Considerations
- Translation is purely cosmetic and doesn't affect event integrity
- Original content validation remains unchanged
- No additional attack vectors introduced
## Implementation Status
This NIP is implemented in Gnome Nostr client as a client-side translation layer.
## References
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
- [NIP-10: Text Notes and Threads](https://github.com/nostr-protocol/nips/blob/master/10.md)
+76 -4
View File
@@ -1,7 +1,79 @@
# mkstack
# 🍄 Gnome Nostr - The Sacred Network of Woodland Folk
> NOTE: This README is from a template and should be replaced with your project description.
A magical Nostr client where all text notes (kind 1 events) are automatically translated into the ancient gnome tongue! Connect with fellow earth-dwellers across the message-mushroom network.
## Created with mkstack
## ✨ Features
mkstack is a starter template for building Nostr web clients in TypeScript, using React, Tailwind, shadcn/ui, Vite, and Nostrify.
- **🍄 Gnome Speak Translation**: All kind 1 events are automatically translated into whimsical gnome language
- **🌲 Forest-Themed UI**: Beautiful gnome-inspired design with earthy colors and woodland aesthetics
- **🔗 Full Nostr Compatibility**: Works with any Nostr relay and preserves all protocol functionality
- **📱 Responsive Design**: Works perfectly on desktop and mobile devices
- **🌙 Dark/Light Mode**: Toggle between day forest and night forest themes
- **⚡ Lightning Fast**: Built with modern React, Vite, and TailwindCSS
## 🎭 Gnome Speak Examples
Regular text is magically transformed:
- `"Hello world!"` → `"Greetings, fellow earth-dweller world! By my pointy hat!"`
- `"Good morning everyone"` → `"🌅When dew kisses the earth🌅 all forest folk"`
- `"I love bitcoin"` → `"I cherish like precious gems ✨golden acorns of the digital realm✨"`
- `"This is about #nostr"` → `"This is a woodland proclamation about #nostr"` (hashtags preserved)
## 🛡️ Protocol Preservation
While the display is transformed into gnome speak, the underlying Nostr protocol remains unchanged:
- ✅ URLs are preserved and linkified
- ✅ Nostr references (npub, note, etc.) work normally
- ✅ Hashtags remain functional for filtering
- ✅ Original content is preserved for replies and quotes
- ✅ Compatible with all other Nostr clients
## 🏗️ Technical Details
- **Framework**: React 18 with TypeScript
- **Styling**: TailwindCSS with custom gnome theme
- **Nostr**: Nostrify for protocol integration
- **Font**: Comfortaa Variable for whimsical feel
- **Build**: Vite for fast development and production builds
## 🌟 Custom NIP
This client implements a custom translation protocol documented in `NIP.md`. The translation:
- Only affects kind 1 events (Short Text Notes)
- Preserves URLs, Nostr references, and hashtags
- Maintains semantic meaning while adding magical charm
- Is purely client-side - no protocol changes required
## 🚀 Getting Started
1. **Clone the repository**
2. **Install dependencies**: `npm install`
3. **Start development**: `npm run dev`
4. **Build for production**: `npm run build`
## 🎨 Customization
The gnome vocabulary can be extended in `src/lib/gnomeSpeak.ts`. Add new word mappings to enhance the magical transformation!
## 🤝 Contributing
Contributions are welcome! Whether you want to:
- Add more gnome vocabulary
- Improve the forest-themed UI
- Fix bugs or add features
- Enhance the translation algorithm
Feel free to open issues and pull requests.
## 📜 License
This project is open source and available under the MIT License.
---
*Vibed with [MKStack](https://soapbox.pub/mkstack) • Blessed by the forest spirits 🍄✨*
**May your mushrooms grow tall and your acorns be golden!** 🌰✨
+16
View File
@@ -0,0 +1,16 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+146
View File
@@ -0,0 +1,146 @@
# Custom ESLint Rules
This directory contains custom ESLint rules for the project.
## no-inline-script
This rule prevents the use of inline script tags in HTML files. Inline scripts can pose security risks and violate Content Security Policy (CSP) directives.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Inline JavaScript code -->
<script>
console.log("This is inline JavaScript");
</script>
<!-- Inline JSON-LD structured data -->
<script type="application/ld+json">
{"@context": "https://schema.org", "@type": "Organization"}
</script>
```
✅ **Good** - These are fine:
```html
<!-- External script files -->
<script src="/js/app.js"></script>
<script type="module" src="/src/main.tsx"></script>
<!-- Empty script tags (no content) -->
<script id="data-container"></script>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-inline-script": "error"
```
### Purpose
This rule helps maintain security best practices by:
- Preventing XSS vulnerabilities from inline scripts
- Enforcing Content Security Policy compliance
- Encouraging separation of concerns (HTML structure vs JavaScript logic)
- Making code easier to maintain and debug
## no-placeholder-comments
This rule detects and flags comments that start with "// In a real" (case-insensitive). These comments typically indicate placeholder implementations that should be replaced with real code.
### Examples
❌ **Bad** - These will trigger the rule:
```javascript
// In a real application, this would connect to a database
const data = [];
// in a real world scenario, this would be different
const config = {};
/* In a real implementation, we would handle errors */
const handleError = () => {};
```
✅ **Good** - These are fine:
```javascript
// This is a regular comment
const data = [];
// TODO: Implement database connection
const config = {};
// Note: In a real application, consider using a database
const handleError = () => {};
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-placeholder-comments": "error"
```
You can change the severity level to:
- `"off"` - Disable the rule
- `"warn"` - Show as warning
- `"error"` - Show as error (current setting)
### Purpose
This rule helps ensure that placeholder comments used during development are replaced with actual implementations before code is committed or deployed to production.
## require-webmanifest
This rule ensures that HTML files include a proper web manifest link tag and that the referenced manifest file exists. Web manifests are essential for Progressive Web Apps (PWAs) and provide metadata about the application.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Missing manifest link entirely -->
<head>
<title>My App</title>
</head>
<!-- Manifest file doesn't exist -->
<head>
<link rel="manifest" href="/nonexistent-manifest.json">
</head>
<!-- Invalid manifest link (missing rel or href) -->
<head>
<link href="/manifest.json">
</head>
```
✅ **Good** - These are fine:
```html
<!-- Proper manifest link with existing file -->
<head>
<link rel="manifest" href="/manifest.json">
</head>
<!-- Alternative valid manifest link -->
<head>
<link rel="manifest" href="/public/site.webmanifest">
</head>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/require-webmanifest": "error"
```
### Purpose
This rule helps ensure:
- PWA compliance by requiring a web manifest
- Proper manifest file structure and accessibility
- Better user experience on mobile devices
- App installation capabilities
- Consistent branding and metadata across platforms
+11
View File
@@ -0,0 +1,11 @@
import noInlineScript from './no-inline-script.js';
import noPlaceholderComments from './no-placeholder-comments.js';
import requireWebmanifest from './require-webmanifest.js';
export default {
rules: {
'no-inline-script': noInlineScript,
'no-placeholder-comments': noPlaceholderComments,
'require-webmanifest': requireWebmanifest,
},
};
+40
View File
@@ -0,0 +1,40 @@
/**
* Rule to prevent inline script tags in HTML files
*/
export default {
meta: {
type: 'problem',
docs: {
description: 'Prevent inline script tags in HTML files',
category: 'Security',
recommended: true,
},
fixable: null,
schema: [],
messages: {
noInlineScript: 'Inline script tags are not allowed. Move script content to external files.',
},
},
create(context) {
return {
// For HTML files, we need to check script tags
'ScriptTag'(node) {
// Check if this is an inline script (has content but no src attribute)
const hasContent = node.value && node.value.value && node.value.value.trim().length > 0;
const hasSrc = node.attributes && node.attributes.some(attr =>
attr.key && attr.key.value === 'src'
);
// If the script has content but no src attribute, it's an inline script
if (hasContent && !hasSrc) {
context.report({
node,
messageId: 'noInlineScript',
});
}
},
};
},
};
+45
View File
@@ -0,0 +1,45 @@
/**
* Custom ESLint rule to detect placeholder comments starting with "// In a real"
* These comments indicate incomplete implementations that should be replaced with real code.
*/
export default {
meta: {
type: "problem",
docs: {
description: "Disallow placeholder comments starting with '// In a real'",
category: "Best Practices",
recommended: true,
},
fixable: null,
schema: [],
messages: {
placeholderComment: "Placeholder comment detected: '{{comment}}'. This should be replaced with a real implementation.",
},
},
create(context) {
const sourceCode = context.getSourceCode();
return {
Program() {
const comments = sourceCode.getAllComments();
comments.forEach((comment) => {
const commentText = comment.value.trim();
// Check if comment starts with "In a real" (case-insensitive)
if (commentText.toLowerCase().startsWith("in a real")) {
context.report({
node: comment,
messageId: "placeholderComment",
data: {
comment: `// ${commentText}`,
},
});
}
});
},
};
},
};
+84
View File
@@ -0,0 +1,84 @@
import fs from 'fs';
import path from 'path';
export default {
meta: {
type: 'problem',
docs: {
description: 'Require web manifest file and proper HTML link tag',
category: 'Best Practices',
},
fixable: null,
schema: [],
messages: {
missingManifestFile: 'Web manifest file not found. Expected {{expectedPath}}',
missingManifestLink: 'Missing web manifest link tag in HTML head',
invalidManifestLink: 'Web manifest link tag has incorrect rel or href attribute',
},
},
create(context) {
const filename = context.getFilename();
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
}
return {
Program(node) {
const sourceCode = context.getSourceCode();
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
const manifestMatch = htmlContent.match(manifestLinkRegex);
if (!manifestMatch) {
context.report({
node,
messageId: 'missingManifestLink',
});
return;
}
// Extract href from the manifest link
const hrefMatch = manifestMatch[0].match(/href=["']([^"']+)["']/i);
if (!hrefMatch) {
context.report({
node,
messageId: 'invalidManifestLink',
});
return;
}
const manifestPath = hrefMatch[1];
// Resolve the manifest file path relative to the project root
const htmlDir = path.dirname(filename);
let resolvedManifestPath;
if (manifestPath.startsWith('/')) {
// Absolute path - check in public directory first, then project root
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
const rootPath = path.resolve(htmlDir, '.' + manifestPath);
resolvedManifestPath = fs.existsSync(publicPath) ? publicPath : rootPath;
} else {
// Relative path
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
}
// Check if the manifest file exists
if (!fs.existsSync(resolvedManifestPath)) {
context.report({
node,
messageId: 'missingManifestFile',
data: {
expectedPath: manifestPath,
},
});
}
},
};
},
};
+47 -1
View File
@@ -3,6 +3,9 @@ import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import htmlEslint from "@html-eslint/eslint-plugin";
import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
@@ -13,9 +16,14 @@ export default tseslint.config(
ecmaVersion: 2020,
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
"custom": customRules,
},
rules: {
...reactHooks.configs.recommended.rules,
@@ -23,7 +31,45 @@ export default tseslint.config(
"warn",
{ allowConstantExport: true },
],
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true,
},
],
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
},
},
{
files: ["**/*.html"],
plugins: {
"@html-eslint": htmlEslint,
"custom": customRules,
},
languageOptions: {
parser: htmlParser,
},
rules: {
"@html-eslint/require-title": "error",
"@html-eslint/require-meta-charset": "error",
"@html-eslint/require-meta-description": "error",
"@html-eslint/require-meta-viewport": "error",
"@html-eslint/require-open-graph-protocol": [
"error",
[
"og:type",
"og:title",
"og:description",
],
],
"custom/no-inline-script": "error",
"custom/require-webmanifest": "error",
},
}
);
+1
View File
@@ -0,0 +1 @@
hi
+8 -2
View File
@@ -3,10 +3,16 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mkstack</title>
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>Gnome Nostr - The Sacred Network of Woodland Folk</title>
<meta name="description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<meta property="og:type" content="website">
<meta property="og:title" content="Gnome Nostr - The Sacred Network of Woodland Folk">
<meta property="og:description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
</html>
+3972 -3154
View File
File diff suppressed because it is too large. Load diff
+17 -9
View File
@@ -5,16 +5,15 @@
"type": "module",
"scripts": {
"dev": "npm i && vite",
"build": "npm i && vite build",
"build:dev": "npm i && vite build --mode development",
"ci": "npm i && tsc --noEmit && vite build",
"lint": "npm i && eslint .",
"preview": "npm i && vite preview"
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@fontsource-variable/comfortaa": "^5.2.6",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.44.0",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.1",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,6 +42,8 @@
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
@@ -51,6 +52,7 @@
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.13.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
@@ -62,11 +64,15 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^3.23.8"
"zod": "^3.25.71"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
@@ -76,10 +82,12 @@
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^5.4.1"
"vite": "^6.3.5",
"vitest": "^3.1.4"
}
}
+1
View File
@@ -0,0 +1 @@
/* /index.html 200
+21
View File
@@ -0,0 +1,21 @@
{
"name": "Gnome Nostr - The Sacred Network of Woodland Folk",
"short_name": "Gnome Nostr",
"description": "A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!",
"start_url": "/",
"display": "standalone",
"background_color": "#f0f5f0",
"theme_color": "#d97706",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
-42
View File
@@ -1,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+8
View File
@@ -0,0 +1,8 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from './App';
test('App', () => {
render(<App />);
})
+41 -19
View File
@@ -1,17 +1,24 @@
import NostrProvider from '@/components/NostrProvider'
// NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter';
// AI: do not modify this relay list
const defaultRelays = [
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://ditto.pub/relay',
];
const head = createHead({
plugins: [
InferSeoMetaPlugin(),
],
});
const queryClient = new QueryClient({
defaultOptions: {
@@ -23,22 +30,37 @@ const queryClient = new QueryClient({
},
});
// NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() {
return (
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider relays={defaultRelays}>
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<Toaster />
<Sonner />
<AppRouter />
</TooltipProvider>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</NostrProvider>
</NostrLoginProvider>
</AppProvider>
</UnheadProvider>
);
}
+2
View File
@@ -1,4 +1,5 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import NotFound from "./pages/NotFound";
@@ -6,6 +7,7 @@ import NotFound from "./pages/NotFound";
export function AppRouter() {
return (
<BrowserRouter>
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+103
View File
@@ -0,0 +1,103 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
/** Application storage key */
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
setConfig(updater);
};
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
useApplyTheme(config.theme);
return (
<AppContext.Provider value={appContextValue}>
{children}
</AppContext.Provider>
);
}
/**
* Hook to apply theme changes to the document root
*/
function useApplyTheme(theme: Theme) {
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
// Handle system theme changes when theme is set to "system"
useEffect(() => {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
+349
View File
@@ -0,0 +1,349 @@
import React, { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile';
export const EditProfileForm: React.FC = () => {
const queryClient = useQueryClient();
const { user, metadata } = useCurrentUser();
const { mutateAsync: publishEvent, isPending } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const { toast } = useToast();
// Initialize the form with default values
const form = useForm<NostrMetadata>({
resolver: zodResolver(n.metadata()),
defaultValues: {
name: '',
about: '',
picture: '',
banner: '',
website: '',
nip05: '',
bot: false,
},
});
// Update form values when user data is loaded
useEffect(() => {
if (metadata) {
form.reset({
name: metadata.name || '',
about: metadata.about || '',
picture: metadata.picture || '',
banner: metadata.banner || '',
website: metadata.website || '',
nip05: metadata.nip05 || '',
bot: metadata.bot || false,
});
}
}, [metadata, form]);
// Handle file uploads for profile picture and banner
const uploadPicture = async (file: File, field: 'picture' | 'banner') => {
try {
// The first tuple in the array contains the URL
const [[_, url]] = await uploadFile(file);
form.setValue(field, url);
toast({
title: 'Success',
description: `${field === 'picture' ? 'Profile picture' : 'Banner'} uploaded successfully`,
});
} catch (error) {
console.error(`Failed to upload ${field}:`, error);
toast({
title: 'Error',
description: `Failed to upload ${field === 'picture' ? 'profile picture' : 'banner'}. Please try again.`,
variant: 'destructive',
});
}
};
const onSubmit = async (values: NostrMetadata) => {
if (!user) {
toast({
title: 'Error',
description: 'You must be logged in to update your profile',
variant: 'destructive',
});
return;
}
try {
// Combine existing metadata with new values
const data = { ...metadata, ...values };
// Clean up empty values
for (const key in data) {
if (data[key] === '') {
delete data[key];
}
}
// Publish the metadata event (kind 0)
await publishEvent({
kind: 0,
content: JSON.stringify(data),
});
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['logins'] });
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
toast({
title: 'Success',
description: 'Your profile has been updated',
});
} catch (error) {
console.error('Failed to update profile:', error);
toast({
title: 'Error',
description: 'Failed to update your profile. Please try again.',
variant: 'destructive',
});
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is your display name that will be displayed to others.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="about"
render={({ field }) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
A short description about yourself.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="picture"
render={({ field }) => (
<ImageUploadField
field={field}
label="Profile Picture"
placeholder="https://example.com/profile.jpg"
description="URL to your profile picture. You can upload an image or provide a URL."
previewType="square"
onUpload={(file) => uploadPicture(file, 'picture')}
/>
)}
/>
<FormField
control={form.control}
name="banner"
render={({ field }) => (
<ImageUploadField
field={field}
label="Banner Image"
placeholder="https://example.com/banner.jpg"
description="URL to a wide banner image for your profile. You can upload an image or provide a URL."
previewType="wide"
onUpload={(file) => uploadPicture(file, 'banner')}
/>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="website"
render={({ field }) => (
<FormItem>
<FormLabel>Website</FormLabel>
<FormControl>
<Input placeholder="https://yourwebsite.com" {...field} />
</FormControl>
<FormDescription>
Your personal website or social media link.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="nip05"
render={({ field }) => (
<FormItem>
<FormLabel>NIP-05 Identifier</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
Your verified Nostr identifier.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="bot"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Bot Account</FormLabel>
<FormDescription>
Mark this account as automated or a bot.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full md:w-auto"
disabled={isPending || isUploading}
>
{(isPending || isUploading) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Save Profile
</Button>
</form>
</Form>
);
};
// Reusable component for image upload fields
interface ImageUploadFieldProps {
field: {
value: string | undefined;
onChange: (value: string) => void;
name: string;
onBlur: () => void;
};
label: string;
placeholder: string;
description: string;
previewType: 'square' | 'wide';
onUpload: (file: File) => void;
}
const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
field,
label,
placeholder,
description,
previewType,
onUpload,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
return (
<FormItem>
<FormLabel>{label}</FormLabel>
<div className="flex flex-col gap-2">
<FormControl>
<Input
placeholder={placeholder}
name={field.name}
value={field.value ?? ''}
onChange={e => field.onChange(e.target.value)}
onBlur={field.onBlur}
/>
</FormControl>
<div className="flex items-center gap-2">
<input
type="file"
ref={fileInputRef}
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
onUpload(file);
}
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-4 w-4 mr-2" />
Upload Image
</Button>
{field.value && (
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
<img
src={field.value}
alt={`${label} preview`}
className="h-full w-full object-cover"
/>
</div>
)}
</div>
</div>
<FormDescription>
{description}
</FormDescription>
<FormMessage />
</FormItem>
);
};
+193
View File
@@ -0,0 +1,193 @@
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Send, Sparkles, Leaf } from 'lucide-react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { translateToGnomeSpeak } from '@/lib/gnomeSpeak';
import { useToast } from '@/hooks/useToast';
export function GnomeComposer() {
const [content, setContent] = useState('');
const [isPreviewMode, setIsPreviewMode] = useState(false);
const { user } = useCurrentUser();
const { mutate: createEvent, isPending } = useNostrPublish();
const { toast } = useToast();
const author = useAuthor(user?.pubkey || '');
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? (user?.pubkey ? genUserName(user.pubkey) : 'Anonymous Gnome');
const profileImage = metadata?.picture;
const handleSubmit = () => {
if (!content.trim()) {
toast({
title: "Empty woodland proclamation!",
description: "Even gnomes need something to say to the forest folk.",
variant: "destructive",
});
return;
}
if (!user) {
toast({
title: "Authentication required",
description: "You must be logged in to share woodland wisdom.",
variant: "destructive",
});
return;
}
createEvent(
{
kind: 1,
content: content.trim(),
tags: [['t', 'gnome']] // Tag all posts as gnome content
},
{
onSuccess: () => {
setContent('');
setIsPreviewMode(false);
toast({
title: "Woodland proclamation sent! 🍄",
description: "Your message has been carried by the forest winds to all the message-mushrooms.",
});
},
onError: (error) => {
toast({
title: "Forest spirits are troubled",
description: `Failed to send your proclamation: ${error.message}`,
variant: "destructive",
});
}
}
);
};
const gnomeTranslatedContent = content ? translateToGnomeSpeak(content) : '';
if (!user) {
return (
<Card className="mb-6 border-2 border-dashed border-muted">
<CardContent className="py-8 text-center">
<div className="space-y-4">
<div className="text-4xl">🍄</div>
<div>
<h3 className="font-semibold mb-2">Join the Forest Council</h3>
<p className="text-muted-foreground">
Log in to share your woodland wisdom with fellow gnomes across the message-mushroom network!
</p>
</div>
</div>
</CardContent>
</Card>
);
}
return (
<Card className="mb-6 border-2 border-primary/20 shadow-lg">
<CardHeader className="pb-3">
<div className="flex items-center space-x-3">
<Avatar className="h-10 w-10 border-2 border-primary/30">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-primary text-primary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<div className="flex items-center space-x-2">
<CardTitle className="text-lg">Share Woodland Wisdom</CardTitle>
<Badge variant="secondary" className="gnome-wiggle">
🍄 Gnome Speak
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Your words will be translated into the ancient gnome tongue
</p>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">Your Message:</label>
<Button
variant="ghost"
size="sm"
onClick={() => setIsPreviewMode(!isPreviewMode)}
className="text-xs"
>
<Sparkles className="h-3 w-3 mr-1" />
{isPreviewMode ? 'Edit' : 'Preview Gnome Speak'}
</Button>
</div>
{!isPreviewMode ? (
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Share your thoughts with the forest folk... (will be translated to gnome speak)"
className="min-h-[100px] resize-none border-2 border-border/50 focus:border-primary/50"
maxLength={280}
/>
) : (
<div className="min-h-[100px] p-3 border-2 border-accent/30 rounded-md bg-accent/5">
<p className="text-sm text-muted-foreground mb-2 font-medium">
🍄 Gnome Speak Translation:
</p>
<div className="text-sm leading-relaxed">
{gnomeTranslatedContent || (
<span className="text-muted-foreground italic">
Your gnome translation will appear here...
</span>
)}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>
{content.length}/280 characters
</span>
{content && (
<span className="text-accent">
✨ Will be auto-translated to gnome speak
</span>
)}
</div>
</div>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2 text-xs text-muted-foreground">
<Leaf className="h-3 w-3" />
<span>Broadcasting to message-mushroom network</span>
</div>
<Button
onClick={handleSubmit}
disabled={!content.trim() || isPending}
className="font-medium"
>
{isPending ? (
<>
<Sparkles className="h-4 w-4 mr-2 animate-spin" />
Sending to Forest...
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
Share Wisdom
</>
)}
</Button>
</div>
</CardContent>
</Card>
);
}
+221
View File
@@ -0,0 +1,221 @@
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Heart, MessageCircle, Repeat2 } from 'lucide-react';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { NoteContent } from '@/components/NoteContent';
import { RelaySelector } from '@/components/RelaySelector';
import type { NostrEvent } from '@nostrify/nostrify';
function GnomePost({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
const about = metadata?.about;
// Format timestamp
const timestamp = new Date(event.created_at * 1000);
const timeAgo = formatTimeAgo(timestamp);
return (
<Card className="mb-4 border-2 border-border/50 hover:border-primary/30 transition-all duration-300 hover:shadow-lg mushroom-glow">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Avatar className="h-12 w-12 border-2 border-primary/20">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-secondary text-secondary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<h3 className="font-semibold text-foreground truncate">
{displayName}
</h3>
<Badge variant="secondary" className="text-xs gnome-wiggle">
🍄 Gnome
</Badge>
</div>
{about && (
<p className="text-sm text-muted-foreground truncate mt-1">
{about}
</p>
)}
<p className="text-xs text-muted-foreground mt-1">
{timeAgo} • via message-mushroom 🍄
</p>
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="mb-4">
<NoteContent event={event} className="text-sm leading-relaxed" />
</div>
{/* Gnome-themed interaction buttons */}
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-primary group">
<Heart className="h-4 w-4 mr-1 group-hover:fill-current transition-all" />
<span className="text-xs">Sprinkle Fairy Dust</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-accent group">
<MessageCircle className="h-4 w-4 mr-1" />
<span className="text-xs">Forest Whisper</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-secondary group">
<Repeat2 className="h-4 w-4 mr-1" />
<span className="text-xs">Spread Seeds</span>
</Button>
</div>
</CardContent>
</Card>
);
}
function GnomePostSkeleton() {
return (
<Card className="mb-4">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Skeleton className="h-12 w-12 rounded-full" />
<div className="flex-1 space-y-2">
<div className="flex items-center space-x-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-20" />
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="h-4 w-3/5" />
</div>
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
</div>
</CardContent>
</Card>
);
}
function formatTimeAgo(date: Date): string {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffInSeconds < 60) {
return 'just now';
} else if (diffInSeconds < 3600) {
const minutes = Math.floor(diffInSeconds / 60);
return `${minutes}m ago`;
} else if (diffInSeconds < 86400) {
const hours = Math.floor(diffInSeconds / 3600);
return `${hours}h ago`;
} else {
const days = Math.floor(diffInSeconds / 86400);
return `${days}d ago`;
}
}
export function GnomeFeed() {
const { nostr } = useNostr();
const { data: posts, isLoading, error } = useQuery({
queryKey: ['gnome-feed'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for kind 1 events (text notes) that will be translated to gnome speak
const events = await nostr.query([
{
kinds: [1],
limit: 50,
}
], { signal });
// Sort by creation time (newest first)
return events.sort((a, b) => b.created_at - a.created_at);
},
refetchInterval: 30000, // Refetch every 30 seconds
});
if (error) {
return (
<div className="col-span-full">
<Card className="border-dashed border-destructive/50">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-4xl">🍄💔</div>
<div>
<h3 className="font-semibold text-destructive mb-2">
The forest spirits are troubled!
</h3>
<p className="text-muted-foreground mb-4">
Unable to connect to the message-mushroom network. The woodland whispers have gone silent.
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isLoading) {
return (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<GnomePostSkeleton key={i} />
))}
</div>
);
}
if (!posts || posts.length === 0) {
return (
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-6xl gnome-wiggle">🍄</div>
<div>
<h3 className="font-semibold mb-2">
The forest is quiet today...
</h3>
<p className="text-muted-foreground mb-4">
No woodland proclamations found. Perhaps the gnomes are all busy tending their gardens? Try another message-mushroom relay to discover more forest folk!
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className="space-y-4">
{posts.map((post) => (
<GnomePost key={post.id} event={post} />
))}
</div>
);
}
+88
View File
@@ -0,0 +1,88 @@
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoginArea } from '@/components/auth/LoginArea';
import { RelaySelector } from '@/components/RelaySelector';
import { useTheme } from '@/hooks/useTheme';
import { Moon, Sun, Leaf, TreePine, Sparkles } from 'lucide-react';
export function GnomeHeader() {
const { theme, setTheme } = useTheme();
return (
<Card className="mb-6 border-2 border-primary/30 bg-gradient-to-r from-primary/5 via-accent/5 to-secondary/5">
<CardContent className="py-6">
<div className="flex flex-col space-y-4">
{/* Main header */}
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="text-3xl gnome-wiggle">🍄</div>
<div>
<h1 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Gnome Nostr
</h1>
<p className="text-sm text-muted-foreground">
The sacred network of woodland folk
</p>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge variant="secondary" className="hidden md:flex items-center space-x-1">
<Sparkles className="h-3 w-3" />
<span>Gnome Speak</span>
</Badge>
<Button
variant="ghost"
size="sm"
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
className="text-muted-foreground hover:text-foreground"
>
{theme === 'light' ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
)}
<span className="hidden sm:inline ml-1">
{theme === 'light' ? 'Night Forest' : 'Day Forest'}
</span>
</Button>
<LoginArea className="max-w-48" />
</div>
</div>
{/* Info and controls bar */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0 pt-3 border-t border-border/30">
<div className="flex items-center space-x-4 text-xs text-muted-foreground">
<div className="flex items-center space-x-1">
<TreePine className="h-3 w-3" />
<span className="hidden sm:inline">Text notes translated to gnome speak</span>
<span className="sm:hidden">Gnome translation active</span>
</div>
</div>
<div className="flex items-center space-x-2">
<Leaf className="h-3 w-3 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Relay:</span>
<RelaySelector className="max-w-48" />
</div>
</div>
{/* Welcome message */}
<div className="bg-accent/10 border border-accent/20 rounded-lg p-4 text-center">
<p className="text-sm text-accent-foreground">
<span className="font-medium">🌟 Welcome to the enchanted forest!</span>
<br />
<span className="text-xs text-muted-foreground mt-1 block">
All text notes are magically translated into the ancient gnome tongue.
Share your woodland wisdom with fellow earth-dwellers!
</span>
</p>
</div>
</div>
</CardContent>
</Card>
);
}
+31 -5
View File
@@ -1,28 +1,54 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import React, { useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
interface NostrProviderProps {
children: React.ReactNode;
relays: string[];
}
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children, relays } = props;
const { children } = props;
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
// Create NPool instance only once
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
pool.current = new NPool({
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map(relays.map((url) => [url, filters]));
return new Map([[relayUrl.current, filters]]);
},
eventRouter(_event: NostrEvent) {
return relays;
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
},
});
}
+138
View File
@@ -0,0 +1,138 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Check out this link: https://example.com',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
// The URL should still be linkified even after gnome translation
const link = screen.getByRole('link', { name: /https:\/\/example/ });
expect(link).toBeInTheDocument();
expect(link.getAttribute('href')).toMatch(/https:\/\/example/);
expect(link).toHaveAttribute('target', '_blank');
});
it('linkifies URLs in kind 1111 events (comments)', () => {
const event: NostrEvent = {
id: 'test-comment-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [
['a', '30040:pubkey:identifier'],
['k', '30040'],
['p', 'pubkey'],
],
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
expect(link).toHaveAttribute('target', '_blank');
});
it('handles text without URLs correctly', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [],
content: 'This is just plain text without any links.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders hashtags as links', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'This is a post about #nostr and #bitcoin development.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
// Hashtags are preserved during gnome translation
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
expect(bitcoinHashtag).toBeInTheDocument();
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
});
it('generates deterministic names for users without metadata and styles them differently', () => {
// Use a valid npub for testing
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
expect(linkText).toEqual("@Swift Falcon");
});
});
+142
View File
@@ -0,0 +1,142 @@
import { useMemo } from 'react';
import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils';
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from '@/lib/gnomeSpeak';
interface NoteContentProps {
event: NostrEvent;
className?: string;
}
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({
event,
className,
}: NoteContentProps) {
// Process the content to render mentions, links, etc.
const content = useMemo(() => {
// Translate to gnome speak if it's a kind 1 event
const originalText = event.content;
const text = shouldTranslateToGnomeSpeak(event.kind)
? translateToGnomeSpeak(originalText)
: originalText;
// Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
const parts: React.ReactNode[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
let keyCounter = 0;
while ((match = regex.exec(text)) !== null) {
const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match;
const index = match.index;
// Add text before this match
if (index > lastIndex) {
parts.push(text.substring(lastIndex, index));
}
if (url) {
// Handle URLs
parts.push(
<a
key={`url-${keyCounter++}`}
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
>
{url}
</a>
);
} else if (nostrPrefix && nostrData) {
// Handle Nostr references
try {
const nostrId = `${nostrPrefix}${nostrData}`;
const decoded = nip19.decode(nostrId);
if (decoded.type === 'npub') {
const pubkey = decoded.data;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
);
}
} catch {
// If decoding fails, just render as text
parts.push(fullMatch);
}
} else if (hashtag) {
// Handle hashtags
const tag = hashtag.slice(1); // Remove the #
parts.push(
<Link
key={`hashtag-${keyCounter++}`}
to={`/t/${tag}`}
className="text-blue-500 hover:underline"
>
{hashtag}
</Link>
);
}
lastIndex = index + fullMatch.length;
}
// Add any remaining text
if (lastIndex < text.length) {
parts.push(text.substring(lastIndex));
}
// If no special content was found, just use the plain text
if (parts.length === 0) {
parts.push(text);
}
return parts;
}, [event]);
return (
<div className={cn("whitespace-pre-wrap break-words", className)}>
{content.length > 0 ? content : event.content}
</div>
);
}
// Helper component to display user mentions
function NostrMention({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
return (
<Link
to={`/${npub}`}
className={cn(
"font-medium hover:underline",
hasRealName
? "text-blue-500"
: "text-gray-500 hover:text-gray-700"
)}
>
@{displayName}
</Link>
);
}
+174
View File
@@ -0,0 +1,174 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
interface RelaySelectorProps {
className?: string;
}
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url: string) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("justify-between", className)}
>
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue && isValidRelayInput(inputValue) ? (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{inputValue ? "Invalid relay URL" : "No relay found."}
</div>
)}
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
.map((option) => (
<CommandItem
key={option.url}
value={option.url}
onSelect={(currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedRelay === option.url ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span className="font-medium">{option.name}</span>
<span className="text-xs text-muted-foreground">{option.url}</span>
</div>
</CommandItem>
))}
{inputValue && isValidRelayInput(inputValue) && (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer border-t"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
+20 -12
View File
@@ -1,8 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React from 'react';
import { ChevronDown, LogOut, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -11,7 +10,9 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { RelaySelector } from '@/components/RelaySelector';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -22,21 +23,28 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
if (!currentUser) return null;
const getDisplayName = (account: Account): string => {
return account.metadata.name ?? genUserName(account.pubkey);
}
return (
<DropdownMenu>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
<AvatarImage src={currentUser.metadata.picture} alt={currentUser.metadata.name} />
<AvatarFallback>{currentUser.metadata.name?.charAt(0)}</AvatarFallback>
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
</Avatar>
<div className='flex-1 text-left hidden md:block'>
<p className='font-medium text-sm'>{currentUser.metadata.name}</p>
<div className='flex-1 text-left hidden md:block truncate'>
<p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
</div>
<ChevronDown className='w-4 h-4 text-muted-foreground' />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => (
<DropdownMenuItem
@@ -45,11 +53,11 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
>
<Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={user.metadata.name} />
<AvatarFallback>{user.metadata.name?.charAt(0)}</AvatarFallback>
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar>
<div className='flex-1'>
<p className='text-sm font-medium'>{user.metadata.name}</p>
<div className='flex-1 truncate'>
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem>
+10 -5
View File
@@ -1,15 +1,20 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState } from 'react';
import { useState } from 'react';
import { User } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
export function LoginArea() {
export interface LoginAreaProps {
className?: string;
}
export function LoginArea({ className }: LoginAreaProps) {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
@@ -20,7 +25,7 @@ export function LoginArea() {
};
return (
<>
<div className={cn("inline-flex items-center justify-center", className)}>
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
@@ -29,7 +34,7 @@ export function LoginArea() {
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span>Log in</span>
<span className='truncate'>Log in</span>
</Button>
)}
@@ -44,6 +49,6 @@ export function LoginArea() {
isOpen={signupDialogOpen}
onClose={() => setSignupDialogOpen(false)}
/>
</>
</div>
);
}
+2 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useEffect, useRef, useState } from 'react';
import React, { useRef, useState } from 'react';
import { Shield, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { Input } from '@/components/ui/input.tsx';
@@ -135,6 +135,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
Enter your nsec
</label>
<Input
type='password'
id='nsec'
value={nsec}
onChange={(e) => setNsec(e.target.value)}
+10 -7
View File
@@ -12,6 +12,7 @@ import {
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { useLoginActions } from '@/hooks/useLoginActions';
import { generateSecretKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
@@ -22,19 +23,19 @@ interface SignupDialogProps {
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
const [isLoading, setIsLoading] = useState(false);
const [nsecKey, setNsecKey] = useState('');
const [nsec, setNsec] = useState('');
const login = useLoginActions();
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
try {
// Generate a new private key
const privateKey = generateSecretKey();
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
const nsec = nip19.nsecEncode(privateKey);
setNsecKey(nsec);
setNsec(nip19.nsecEncode(sk));
setStep('download');
} catch (error) {
console.error('Failed to generate key:', error);
@@ -50,7 +51,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const downloadKey = () => {
// Create a blob with the key text
const blob = new Blob([nsecKey], { type: 'text/plain' });
const blob = new Blob([nsec], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
// Create a temporary link element and trigger download
@@ -71,6 +72,8 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
};
const finishSignup = () => {
login.nsec(nsec);
setStep('done');
onClose();
@@ -118,7 +121,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
{step === 'download' && (
<div className='space-y-6'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
<code className='text-xs break-all'>{nsecKey}</code>
<code className='text-xs break-all'>{nsec}</code>
</div>
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'>
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
import { buttonVariants } from "@/components/ui/button-variants"
const AlertDialog = AlertDialogPrimitive.Root
+1 -1
View File
@@ -24,7 +24,7 @@ const AvatarImage = React.forwardRef<
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
className={cn("aspect-square h-full w-full object-cover", className)}
{...props}
/>
))
+21
View File
@@ -0,0 +1,21 @@
import { cva } from "class-variance-authority"
export const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
+3 -22
View File
@@ -1,27 +1,8 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
import { badgeVariants } from "./badge-variants"
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
@@ -33,4 +14,4 @@ function Badge({ className, variant, ...props }: BadgeProps) {
)
}
export { Badge, badgeVariants }
export { Badge }
+30
View File
@@ -0,0 +1,30 @@
import { cva } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+3 -31
View File
@@ -1,37 +1,9 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
import { buttonVariants } from "./button-variants"
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
@@ -53,4 +25,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
)
Button.displayName = "Button"
export { Button, buttonVariants }
export { Button }
+1 -1
View File
@@ -3,7 +3,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
import { buttonVariants } from "@/components/ui/button-variants";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+1 -1
View File
@@ -21,7 +21,7 @@ const Command = React.forwardRef<
))
Command.displayName = CommandPrimitive.displayName
interface CommandDialogProps extends DialogProps {}
type CommandDialogProps = DialogProps
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
+48
View File
@@ -0,0 +1,48 @@
import * as React from "react"
import {
FieldPath,
FieldValues,
useFormContext,
} from "react-hook-form"
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
export const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
type FormItemContextValue = {
id: string
}
export const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
export const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
+1 -44
View File
@@ -7,25 +7,14 @@ import {
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { FormFieldContext, FormItemContext, useFormField } from "./form-utils"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
@@ -39,37 +28,6 @@ const FormField = <
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
@@ -165,7 +123,6 @@ const FormMessage = React.forwardRef<
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
@@ -0,0 +1,5 @@
import { cva } from "class-variance-authority"
export const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
+1 -6
View File
@@ -1,9 +1,9 @@
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { navigationMenuTriggerStyle } from "./navigation-menu-variants"
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
@@ -40,10 +40,6 @@ NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
@@ -116,7 +112,6 @@ NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
+2 -1
View File
@@ -2,7 +2,8 @@ import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { ButtonProps, buttonVariants } from "@/components/ui/button"
import { ButtonProps } from "@/components/ui/button"
import { buttonVariants } from "@/components/ui/button-variants"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
+52
View File
@@ -0,0 +1,52 @@
import * as React from "react"
import { cva } from "class-variance-authority"
export const SIDEBAR_COOKIE_NAME = "sidebar:state"
export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
export const SIDEBAR_WIDTH = "16rem"
export const SIDEBAR_WIDTH_MOBILE = "18rem"
export const SIDEBAR_WIDTH_ICON = "3rem"
export const SIDEBAR_KEYBOARD_SHORTCUT = "b"
export type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
export const SidebarContext = React.createContext<SidebarContext | null>(null)
export function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
export const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+15 -52
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { VariantProps, cva } from "class-variance-authority"
import { VariantProps } from "class-variance-authority"
import { PanelLeft } from "lucide-react"
import { useIsMobile } from "@/hooks/useIsMobile"
@@ -16,34 +16,18 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
const SIDEBAR_COOKIE_NAME = "sidebar:state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContext | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
import {
SIDEBAR_COOKIE_NAME,
SIDEBAR_COOKIE_MAX_AGE,
SIDEBAR_WIDTH,
SIDEBAR_WIDTH_MOBILE,
SIDEBAR_WIDTH_ICON,
SIDEBAR_KEYBOARD_SHORTCUT,
SidebarContext,
useSidebar,
sidebarMenuButtonVariants,
type SidebarContext as SidebarContextType,
} from "./sidebar-utils"
const SidebarProvider = React.forwardRef<
HTMLDivElement,
@@ -114,7 +98,7 @@ const SidebarProvider = React.forwardRef<
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContext>(
const contextValue = React.useMemo<SidebarContextType>(
() => ({
state,
open,
@@ -509,27 +493,7 @@ const SidebarMenuItem = React.forwardRef<
))
SidebarMenuItem.displayName = "SidebarMenuItem"
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
@@ -757,5 +721,4 @@ export {
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
}
+1 -2
View File
@@ -2,8 +2,7 @@ import * as React from "react"
import { cn } from "@/lib/utils"
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
+1 -1
View File
@@ -3,7 +3,7 @@ import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
import { toggleVariants } from "@/components/ui/toggle-variants"
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
+23
View File
@@ -0,0 +1,23 @@
import { cva } from "class-variance-authority"
export const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+3 -24
View File
@@ -1,30 +1,9 @@
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
import { toggleVariants } from "./toggle-variants"
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
@@ -40,4 +19,4 @@ const Toggle = React.forwardRef<
Toggle.displayName = TogglePrimitive.Root.displayName
export { Toggle, toggleVariants }
export { Toggle }
+21
View File
@@ -0,0 +1,21 @@
import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export interface AppConfig {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
+14
View File
@@ -0,0 +1,14 @@
import { useContext } from "react";
import { AppContext, type AppContextType } from "@/contexts/AppContext";
/**
* Hook to access and update application configuration
* @returns Application context with config and update methods
*/
export function useAppContext(): AppContextType {
const context = useContext(AppContext);
if (context === undefined) {
throw new Error('useAppContext must be used within an AppProvider');
}
return context;
}
+2 -2
View File
@@ -38,11 +38,11 @@ export function useCurrentUser() {
}, [logins, loginToUser]);
const user = users[0] as NUser | undefined;
const data = useAuthor(user?.pubkey);
const author = useAuthor(user?.pubkey);
return {
user,
data,
users,
...author.data,
};
}
+54
View File
@@ -0,0 +1,54 @@
import { useState, useEffect } from 'react';
/**
* Generic hook for managing localStorage state
*/
export function useLocalStorage<T>(
key: string,
defaultValue: T,
serializer?: {
serialize: (value: T) => string;
deserialize: (value: string) => T;
}
) {
const serialize = serializer?.serialize || JSON.stringify;
const deserialize = serializer?.deserialize || JSON.parse;
const [state, setState] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? deserialize(item) : defaultValue;
} catch (error) {
console.warn(`Failed to load ${key} from localStorage:`, error);
return defaultValue;
}
});
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);
}
};
// Sync with localStorage changes from other tabs
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(deserialize(e.newValue));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [key, deserialize]);
return [state, setValue] as const;
}
+6
View File
@@ -0,0 +1,6 @@
// This file exists because LLMs get confused and try to create this file if it doesn't exist.
// The `useNostr` hook should be imported directly from `@nostrify/react`, not from this file.
// This file SHOULD NOT be edited or removed.
export { useNostr } from "@nostrify/react";
+14 -10
View File
@@ -1,29 +1,33 @@
import { useNostr } from "@nostrify/react";
import { useMutation } from "@tanstack/react-query";
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useCurrentUser } from "./useCurrentUser";
interface EventTemplate {
kind: number;
content?: string;
tags?: string[][];
created_at?: number;
}
import type { NostrEvent } from "@nostrify/nostrify";
export function useNostrPublish() {
export function useNostrPublish(): UseMutationResult<NostrEvent> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (t: EventTemplate) => {
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
if (user) {
const tags = t.tags ?? [];
// Add the client tag if it doesn't exist
if (location.protocol === "https:" && !tags.some(([name]) => name === "client")) {
tags.push(["client", location.hostname]);
}
const event = await user.signer.signEvent({
kind: t.kind,
content: t.content ?? "",
tags: t.tags ?? [],
tags,
created_at: t.created_at ?? Math.floor(Date.now() / 1000),
});
await nostr.event(event, { signal: AbortSignal.timeout(5000) });
return event;
} else {
throw new Error("User is not logged in");
}
+20
View File
@@ -0,0 +1,20 @@
import { type Theme } from "@/contexts/AppContext";
import { useAppContext } from "@/hooks/useAppContext";
/**
* Hook to get and set the active theme
* @returns Theme context with theme and setTheme
*/
export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } {
const { config, updateConfig } = useAppContext();
return {
theme: config.theme,
setTheme: (theme: Theme) => {
updateConfig((currentConfig) => ({
...currentConfig,
theme,
}));
}
}
}
+4 -13
View File
@@ -15,13 +15,6 @@ type ToasterToast = ToastProps & {
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
@@ -29,23 +22,21 @@ function genId() {
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
type: "ADD_TOAST";
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
type: "UPDATE_TOAST";
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
type: "DISMISS_TOAST";
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
type: "REMOVE_TOAST";
toastId?: ToasterToast["id"]
}
+26
View File
@@ -0,0 +1,26 @@
import { useMutation } from "@tanstack/react-query";
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import { useCurrentUser } from "./useCurrentUser";
export function useUploadFile() {
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (file: File) => {
if (!user) {
throw new Error('Must be logged in to upload files');
}
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
],
signer: user.signer,
});
const tags = await uploader.upload(file);
return tags;
},
});
}
+116 -62
View File
@@ -4,89 +4,85 @@
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
/* Gnome Forest Theme - Light Mode */
--background: 120 20% 97%; /* Very light sage green */
--foreground: 120 15% 15%; /* Dark forest green */
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--card: 120 25% 95%; /* Light moss green */
--card-foreground: 120 15% 15%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--popover: 120 25% 95%;
--popover-foreground: 120 15% 15%;
--primary: 222.2 47.4% 11.2%;
--primary-foreground: 210 40% 98%;
--primary: 25 85% 55%; /* Warm mushroom orange */
--primary-foreground: 120 25% 95%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--secondary: 120 30% 85%; /* Soft forest green */
--secondary-foreground: 120 15% 15%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--muted: 120 20% 90%; /* Light moss */
--muted-foreground: 120 10% 45%; /* Medium forest green */
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--accent: 45 90% 70%; /* Golden acorn yellow */
--accent-foreground: 120 15% 15%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--destructive: 0 84.2% 60.2%; /* Red mushroom */
--destructive-foreground: 120 25% 95%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--border: 120 25% 85%; /* Soft green border */
--input: 120 25% 90%; /* Light input background */
--ring: 25 85% 55%; /* Mushroom orange focus ring */
--radius: 0.5rem;
--radius: 0.75rem; /* More rounded for organic feel */
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
--sidebar-background: 120 30% 92%;
--sidebar-foreground: 120 15% 20%;
--sidebar-primary: 25 85% 55%;
--sidebar-primary-foreground: 120 25% 95%;
--sidebar-accent: 120 25% 88%;
--sidebar-accent-foreground: 120 15% 15%;
--sidebar-border: 120 25% 80%;
--sidebar-ring: 25 85% 55%;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
/* Gnome Forest Theme - Dark Mode (Night in the Forest) */
--background: 120 25% 8%; /* Deep forest night */
--foreground: 120 20% 85%; /* Light moss green */
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--card: 120 20% 12%; /* Dark forest floor */
--card-foreground: 120 20% 85%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--popover: 120 20% 12%;
--popover-foreground: 120 20% 85%;
--primary: 210 40% 98%;
--primary-foreground: 222.2 47.4% 11.2%;
--primary: 25 85% 65%; /* Bright mushroom orange */
--primary-foreground: 120 20% 12%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--secondary: 120 15% 20%; /* Dark moss */
--secondary-foreground: 120 20% 85%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--muted: 120 15% 18%; /* Dark undergrowth */
--muted-foreground: 120 15% 60%; /* Medium light green */
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--accent: 45 90% 75%; /* Bright golden acorn */
--accent-foreground: 120 20% 12%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--destructive: 0 75% 55%; /* Dark red mushroom */
--destructive-foreground: 120 20% 85%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 212.7 26.8% 83.9%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
--border: 120 20% 20%; /* Dark forest border */
--input: 120 20% 15%; /* Dark input background */
--ring: 25 85% 65%; /* Bright mushroom focus ring */
--sidebar-background: 120 25% 10%;
--sidebar-foreground: 120 20% 80%;
--sidebar-primary: 25 85% 65%;
--sidebar-primary-foreground: 120 20% 12%;
--sidebar-accent: 120 20% 18%;
--sidebar-accent-foreground: 120 20% 85%;
--sidebar-border: 120 20% 20%;
--sidebar-ring: 25 85% 65%;
}
}
@@ -97,5 +93,63 @@
body {
@apply bg-background text-foreground;
background-image:
radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(255, 119, 48, 0.1) 0%, transparent 50%),
radial-gradient(circle at 40% 40%, rgba(120, 200, 120, 0.05) 0%, transparent 50%);
}
}
/* Gnome-specific animations and effects */
@keyframes gnome-wiggle {
0%, 100% { transform: rotate(-1deg); }
50% { transform: rotate(1deg); }
}
@keyframes mushroom-glow {
0%, 100% { box-shadow: 0 0 5px rgba(255, 119, 48, 0.3); }
50% { box-shadow: 0 0 15px rgba(255, 119, 48, 0.5); }
}
@keyframes forest-shimmer {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
.gnome-wiggle {
animation: gnome-wiggle 2s ease-in-out infinite;
}
.mushroom-glow {
animation: mushroom-glow 3s ease-in-out infinite;
}
.forest-shimmer {
background: linear-gradient(
90deg,
transparent,
rgba(120, 200, 120, 0.2),
transparent
);
background-size: 200% 100%;
animation: forest-shimmer 3s ease-in-out infinite;
}
/* Custom scrollbar for gnome theme */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: hsl(var(--muted));
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: hsl(var(--primary));
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: hsl(var(--accent));
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest';
import { genUserName } from './genUserName';
describe('genUserName', () => {
it('generates a deterministic name from a seed', () => {
const seed = 'test-seed-123';
const name1 = genUserName(seed);
const name2 = genUserName(seed);
expect(name1).toEqual('Brave Whale');
expect(name1).toEqual(name2);
});
it('generates different names for different seeds', () => {
const name1 = genUserName('seed1');
const name2 = genUserName('seed2');
const name3 = genUserName('seed3');
// While it's theoretically possible for different seeds to generate the same name,
// it's very unlikely with our word lists
expect(name1).not.toBe(name2);
expect(name2).not.toBe(name3);
expect(name1).not.toBe(name3);
});
it('handles typical Nostr pubkey format', () => {
// Typical hex pubkey (64 characters)
const pubkey = 'e4690a13290739da123aa17d553851dec4cdd0e9d89aa18de3741c446caf8761';
const name = genUserName(pubkey);
expect(name).toEqual('Gentle Hawk');
});
});
+29
View File
@@ -0,0 +1,29 @@
/** Generate a deterministic user display name based on a string seed. */
export function genUserName(seed: string): string {
// Use a simple hash of the pubkey to generate consistent adjective + noun combinations
const adjectives = [
'Swift', 'Bright', 'Calm', 'Bold', 'Wise', 'Kind', 'Quick', 'Brave',
'Cool', 'Sharp', 'Clear', 'Strong', 'Smart', 'Fast', 'Keen', 'Pure',
'Noble', 'Gentle', 'Fierce', 'Steady', 'Clever', 'Proud', 'Silent', 'Wild'
];
const nouns = [
'Fox', 'Eagle', 'Wolf', 'Bear', 'Lion', 'Tiger', 'Hawk', 'Owl',
'Deer', 'Raven', 'Falcon', 'Lynx', 'Otter', 'Whale', 'Shark', 'Dolphin',
'Phoenix', 'Dragon', 'Panther', 'Jaguar', 'Cheetah', 'Leopard', 'Puma', 'Cobra'
];
// Create a simple hash from the pubkey
let hash = 0;
for (let i = 0; i < seed.length; i++) {
const char = seed.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
// Use absolute value to ensure positive index
const adjIndex = Math.abs(hash) % adjectives.length;
const nounIndex = Math.abs(hash >> 8) % nouns.length;
return [adjectives[adjIndex], nouns[nounIndex]].join(' ');
}
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect } from 'vitest';
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from './gnomeSpeak';
describe('gnomeSpeak', () => {
describe('shouldTranslateToGnomeSpeak', () => {
it('returns true for kind 1 events', () => {
expect(shouldTranslateToGnomeSpeak(1)).toBe(true);
});
it('returns false for other event kinds', () => {
expect(shouldTranslateToGnomeSpeak(0)).toBe(false);
expect(shouldTranslateToGnomeSpeak(3)).toBe(false);
expect(shouldTranslateToGnomeSpeak(1111)).toBe(false);
expect(shouldTranslateToGnomeSpeak(30023)).toBe(false);
});
});
describe('translateToGnomeSpeak', () => {
it('translates basic words to gnome speak', () => {
const result = translateToGnomeSpeak('Hello world! This is good.');
expect(result).toContain('Greetings, fellow');
expect(result).toContain('splendid as');
});
it('preserves URLs during translation', () => {
const result = translateToGnomeSpeak('Check out https://example.com for good info');
expect(result).toMatch(/https:\/\/example/);
expect(result).toContain('splendid as');
});
it('preserves nostr references during translation', () => {
const result = translateToGnomeSpeak('Follow nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0 for good content');
expect(result).toContain('nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0');
expect(result).toContain('splendid as');
});
it('preserves hashtags during translation', () => {
const result = translateToGnomeSpeak('This is about #nostr and #bitcoin development');
expect(result).toContain('#nostr');
expect(result).toContain('#bitcoin');
});
it('adds gnome-specific formatting for special terms', () => {
const result = translateToGnomeSpeak('I love bitcoin and gm everyone!');
expect(result).toContain('golden acorns of the digital realm');
expect(result).toContain('🌅when dew kisses the earth🌅');
});
it('handles empty or invalid input', () => {
expect(translateToGnomeSpeak('')).toBe('');
expect(translateToGnomeSpeak(null as unknown as string)).toBe(null);
expect(translateToGnomeSpeak(undefined as unknown as string)).toBe(undefined);
});
it('capitalizes sentences properly', () => {
const result = translateToGnomeSpeak('hello world. this is good.');
expect(result).toMatch(/^[A-Z]/); // Should start with capital letter
expect(result).toMatch(/\. [A-Z]/); // Should capitalize after periods
});
});
});
+923
View File
@@ -0,0 +1,923 @@
/**
* Gnome Speak Translator
* Transforms regular text into whimsical gnome language
*/
// Common gnome words and phrases
const gnomeVocabulary: Record<string, string> = {
// Greetings and expressions
'hello': 'greetings, fellow earth-dweller',
'hi': 'huzzah',
'hey': 'ho there',
'howdy': 'well met, forest-friend',
'welcome': 'blessed be your arrival',
'goodbye': 'may your mushrooms grow tall',
'bye': 'farewell, friend of the forest',
'farewell': 'until the paths cross again',
'thanks': 'blessings of the garden upon you',
'thank you': 'may the roots remember your kindness',
'please': 'if it pleases the woodland spirits',
'sorry': 'forgive this humble gnome',
'excuse me': 'pardon this forest-dweller',
'yes': 'aye, by my pointy hat',
'yeah': 'indeed, forest-friend',
'yep': 'certainly, woodland-companion',
'absolutely': 'as sure as ancient-oaks',
'definitely': 'certain as sunrise',
'certainly': 'without doubt, earth-friend',
'sure': 'as reliable as mountain-stones',
'no': 'nay, not even for all the acorns in the forest',
'nope': 'negative, forest-friend',
'never': 'not in a thousand-seasons',
'maybe': 'perhaps, if the mushrooms align',
'perhaps': 'possibly, when stars-align',
'possibly': 'might be, if spirits-will',
'probably': 'likely as autumn-leaves-falling',
'ok': 'very well, tiny friend',
'okay': 'indeed, little earth-dweller',
'alright': 'acceptable to forest-council',
'fine': 'satisfactory as spring-weather',
'wow': 'by the ancient-spirits',
'whoa': 'sacred mushrooms preserve-us',
'oh': 'woodland-spirits witness',
'oops': 'clumsy as startled-squirrels',
'darn': 'cursed as wilted-flowers',
// Common descriptive words
'good': 'splendid as morning dew',
'great': 'magnificent as ancient oak',
'awesome': 'wondrous as fairy rings',
'amazing': 'astounding as dragon sightings',
'incredible': 'miraculous as talking trees',
'wonderful': 'marvelous as rainbow bridges',
'excellent': 'superb as crystal caves',
'fantastic': 'enchanting as unicorn meadows',
'perfect': 'flawless as crystal dewdrops',
'beautiful': 'lovely as blooming flowers',
'pretty': 'charming as flower petals',
'gorgeous': 'stunning as sunset glades',
'handsome': 'dashing as noble stags',
'nice': 'pleasant as garden breeze',
'sweet': 'endearing as honey-flavored-words',
'cool': 'refreshing as spring water',
'hot': 'blazing as dragon breath',
'warm': 'cozy as hearth embers',
'cold': 'frigid as mountain peaks',
'bad': 'cursed as wilted leaves',
'terrible': 'dreadful as goblin raids',
'horrible': 'ghastly as poisoned wells',
'awful': 'abysmal as barren wastelands',
'ugly': 'unsightly as rotting stumps',
'hideous': 'repulsive as swamp creatures',
'disgusting': 'revolting as rotten-smell-smellers',
'gross': 'sickening as filth-encountering',
'big': 'enormous as giant toadstools',
'large': 'vast as forest clearings',
'huge': 'colossal as mountain trolls',
'massive': 'immense as ancient trees',
'giant': 'titanic as elder dragons',
'small': 'tiny as acorn caps',
'little': 'wee as dewdrops',
'tiny': 'minuscule as fairy footprints',
'miniature': 'pocket-sized as gnome homes',
'fast': 'swift as woodland sprites',
'quick': 'rapid as darting squirrels',
'speedy': 'fleet as racing rabbits',
'slow': 'leisurely as growing moss',
'sluggish': 'plodding as sleepy bears',
'new': 'fresh as spring shoots',
'old': 'ancient as elder trees',
'young': 'youthful as new growth',
'fresh': 'crisp as dawn air',
'stale': 'aged as ancient crumbs',
'clean': 'pure as mountain springs',
'dirty': 'soiled as muddy paths',
'rich': 'wealthy as treasure hoards',
'poor': 'humble as simple folk',
'expensive': 'costly as rare gems',
'cheap': 'affordable as common stones',
'free': 'unbound as forest winds',
'easy': 'simple as breathing air',
'difficult': 'challenging as mountain climbing',
'hard': 'tough as ancient bark',
'soft': 'gentle as rabbit fur',
'strong': 'mighty as bear strength',
'weak': 'frail as spider silk',
'heavy': 'weighty as boulder loads',
'light': 'airy as dandelion fluff',
'dark': 'shadowy as deep cave',
'bright': 'radiant as summer sun',
'loud': 'noisy as thunder crashes',
'quiet': 'silent as falling snow',
'busy': 'active as worker ants',
'lazy': 'idle as sunbathing cats',
'tired': 'weary as day\'s end',
'awake': 'alert as watchful owls',
'alive': 'living with forest vitality',
'dead': 'lifeless as fallen logs',
'healthy': 'robust as oak trees',
'sick': 'ailing like withered plants',
'safe': 'secure as burrow homes',
'dangerous': 'perilous as cliff edges',
'careful': 'cautious as deer at streams',
'careless': 'reckless as storm winds',
'smart': 'clever as cunning foxes',
'stupid': 'mindlessly as senseless acts',
'wise': 'sage as ancient owls',
'foolish': 'unwise as reckless youth',
'funny': 'amusing as playful otters',
'serious': 'grave as solemn ceremonies',
'strange': 'odd as two-headed mushrooms',
'normal': 'ordinary as daily sunrise',
'special': 'unique as snowflake patterns',
'different': 'distinct as individual leaves',
'same': 'identical as twin acorns',
'similar': 'alike as sister streams',
'equal': 'equivalent as balanced scales',
'fair': 'just as forest law',
'unfair': 'unjust as stolen honey',
'true': 'accurate as gnome-wisdom',
'false': 'untrue as winter promises',
'right': 'correct as compass needles',
'wrong': 'mistaken as lost travelers',
'correct': 'proper as forest protocol',
'important': 'significant as ancient laws',
'interesting': 'fascinating as rare discoveries',
'boring': 'dull as watching grass grow',
'fun': 'enjoyable as harvest festivals',
'lucky': 'fortunate as four-leaf clovers',
'unlucky': 'cursed as broken mirrors',
'successful': 'triumphant as victorious warriors',
'popular': 'beloved as festival leaders',
'famous': 'renowned as legendary heroes',
'unknown': 'mysterious as hidden valleys',
// Emotions and feelings
'happy': 'merry as spring festivals',
'joyful': 'gleeful as dancing pixies',
'cheerful': 'bright as sunny meadows',
'excited': 'thrilled as treasure hunters',
'delighted': 'pleased as successful gardeners',
'ecstatic': 'overjoyed as festival winners',
'elated': 'uplifted as soaring-eagles',
'content': 'satisfied as well-fed-bears',
'pleased': 'gratified as successful-gardeners',
'glad': 'happy as singing-birds',
'relieved': 'unburdened as dropped-heavy-packs',
'grateful': 'thankful as rain-blessed-crops',
'proud': 'dignified as royal stags',
'confident': 'assured as mountain peaks',
'brave': 'courageous as warrior bears',
'bold': 'daring as cliff-climbing-goats',
'calm': 'peaceful as still ponds',
'relaxed': 'at-ease as sunbathing-cats',
'peaceful': 'tranquil as morning-meadows',
'sad': 'melancholy as autumn rain',
'unhappy': 'sorrowful as wilting flowers',
'depressed': 'gloomy as storm clouds',
'miserable': 'wretched as lost wanderers',
'heartbroken': 'shattered as fallen-bird-eggs',
'lonely': 'isolated as single-trees',
'hurt': 'wounded as thorn-pricked-paws',
'angry': 'wrathful as disturbed badgers',
'mad': 'furious as territorial bears',
'furious': 'enraged as protective mothers',
'annoyed': 'vexed as pestered squirrels',
'irritated': 'bothered as interrupted naps',
'frustrated': 'blocked like dammed-streams',
'afraid': 'fearful as startled mice',
'scared': 'frightened as hunted-rabbits',
'terrified': 'petrified as stone-statues',
'nervous': 'jittery as caffeine-buzzed-squirrels',
'worried': 'concerned as protective-parents',
'anxious': 'worried as storm-watching-sailors',
'surprised': 'astonished as sudden storms',
'shocked': 'stunned as lightning-struck-trees',
'amazed': 'astounded as miracle-witnesses',
'confused': 'puzzled as riddle-hearers',
'lost': 'directionless as pathless-wanderers',
'curious': 'inquisitive as exploring-kittens',
'interested': 'engaged as story-listeners',
'bored': 'uninterested as sleepy-sloths',
'jealous': 'envious as covetous-dragons',
'envious': 'resentful as have-nots',
'greedy': 'grasping as hoarding-squirrels',
'selfish': 'self-centered as narcissistic-peacocks',
'generous': 'giving as abundant-fruit-trees',
'kind': 'gentle as mother\'s touch',
'mean': 'nasty as stinging-nettles',
'cruel': 'harsh as winter-storms',
'embarrassed': 'ashamed as public-mistake-makers',
'guilty': 'remorseful as wrongdoing-confessors',
'ashamed': 'dishonored as oath-breakers',
// Actions and verbs
'go': 'venture forth',
'come': 'approach the sacred circle',
'see': 'witness with gnome-eyes',
'look': 'gaze upon',
'watch': 'observe like sentinel-owls',
'listen': 'hear the whispers of the wind',
'hear': 'perceive with gnome-ears',
'speak': 'utter in ancient dialect',
'talk': 'speak in the ancient tongue',
'say': 'declare to forest council',
'tell': 'relate tales by firelight',
'ask': 'inquire of the wise ones',
'answer': 'respond with woodland-wisdom',
'think': 'ponder in the mushroom circle',
'know': 'hold wisdom in thy cap',
'learn': 'gather knowledge like berries',
'teach': 'share wisdom of the ancients',
'understand': 'comprehend with woodland wisdom',
'remember': 'recall from memory-moss',
'forget': 'lose to the mists of time',
'believe': 'trust in forest magic',
'hope': 'wish upon evening stars',
'feel': 'sense with gnome-heart',
'love': 'cherish like precious gems',
'like': 'fancy as favorite flowers',
'hate': 'despise like garden pests',
'want': 'desire like moths seek flame',
'need': 'require like flowers need rain',
'have': 'possess like territorial-bears',
'get': 'obtain through forest cunning',
'give': 'bestow gifts of the heart',
'take': 'gather like squirrels in autumn',
'put': 'place with gnomish care',
'make': 'craft with gnomish hands',
'do': 'perform with woodland-skill',
'work': 'toil in the earth',
'play': 'frolic like woodland creatures',
'help': 'lend aid to fellow forest-folk',
'try': 'attempt with gnomish determination',
'use': 'employ with woodland wisdom',
'find': 'discover hidden treasures',
'lose': 'misplace in the deep woods',
'keep': 'guard like dragon\'s treasure',
'save': 'preserve like squirrels save nuts',
'spend': 'use like autumn leaves falling',
'buy': 'trade for with shiny pebbles',
'sell': 'barter in the market grove',
'pay': 'offer tribute to forest spirits',
'win': 'triumph like mighty oak',
'start': 'begin the woodland journey',
'stop': 'halt like deer sensing danger',
'end': 'conclude like sunset',
'finish': 'complete like harvest-gathering',
'begin': 'commence the forest-quest',
'continue': 'proceed along woodland-path',
'change': 'transform like caterpillars',
'move': 'shift like dancing leaves',
'stay': 'remain rooted like ancient trees',
'leave': 'depart on woodland winds',
'return': 'come back to the sacred grove',
'arrive': 'reach journey\'s end',
'travel': 'journey through wild lands',
'visit': 'call upon forest friends',
'meet': 'encounter on woodland paths',
'follow': 'walk the same forest path',
'lead': 'guide like wise elders',
'run': 'scamper through the underbrush',
'walk': 'stroll the forest paths',
'sit': 'perch upon mushroom throne',
'stand': 'rise like proud saplings',
'sleep': 'rest in the embrace of moss',
'wake': 'greet the morning sun',
'eat': 'partake of nature\'s gifts',
'drink': 'sip the sacred waters',
'cook': 'prepare over gnome-fires',
'read': 'decipher the runes of knowledge',
'write': 'inscribe upon bark and stone',
'build': 'construct like industrious beavers',
'break': 'shatter like brittle ice',
'fix': 'mend with gnomish skill',
'open': 'unseal like blooming flowers',
'close': 'shut like evening blossoms',
'turn': 'rotate like seasons changing',
'carry': 'bear like pack mules',
'hold': 'grasp with gnomish grip',
'throw': 'hurl like catapult stones',
'catch': 'capture like spider webs',
'send': 'dispatch like messenger birds',
'bring': 'carry like busy ants',
'show': 'reveal like dawn breaking',
'hide': 'conceal in forest-shadows',
'wait': 'pause like patient stones',
'hurry': 'rush like urgent-messengers',
'choose': 'select like wise owls',
'decide': 'determine by mushroom council',
'plan': 'scheme like clever foxes',
'create': 'birth from gnomish imagination',
'destroy': 'unmake like winter storms',
'grow': 'flourish like spring gardens',
'die': 'return to the eternal soil',
'live': 'dwell in harmony with nature',
'happen': 'occur by woodland chance',
'seem': 'appear like morning mist',
'become': 'transform into',
'remain': 'stay like enduring-stones',
'appear': 'manifest like forest-spirits',
'disappear': 'vanish like morning-mist',
'exist': 'be present in forest-realm',
'matter': 'be important as ancient oaks',
'care': 'tend like garden keeper',
'worry': 'fret like anxious rabbits',
'call': 'summon with woodland voice',
'let': 'allow the forest spirits',
'allow': 'permit by gnomish law',
'join': 'unite like flowing streams',
'share': 'spread like dandelion seeds',
'agree': 'harmonize like bird songs',
'disagree': 'clash like thunder storms',
'fight': 'battle like fierce badgers',
'argue': 'quarrel like territorial squirrels',
'discuss': 'debate in council circles',
'explain': 'clarify like morning light',
'describe': 'paint word-pictures',
'compare': 'measure against ancient standards',
'include': 'embrace within the circle',
'exclude': 'banish from sacred-grove',
'add': 'include like gathering-berries',
'remove': 'extract like pulling-weeds',
'increase': 'grow like expanding-trees',
'decrease': 'shrink like autumn-leaves',
'improve': 'enhance like garden-tending',
'develop': 'cultivate like patient farmers',
'manage': 'oversee like head gardener',
'control': 'command like forest kings',
'organize': 'arrange like busy bees',
'prepare': 'ready like winter-preparations',
'provide': 'supply from nature\'s storehouse',
'offer': 'present like gift-bearing visitors',
'accept': 'receive with grateful heart',
'refuse': 'decline like stubborn-mules',
'reject': 'spurn like bitter-berries',
'receive': 'welcome like spring rain',
'support': 'uphold like sturdy roots',
'oppose': 'resist like stubborn stones',
'protect': 'shield like mother bears',
'attack': 'assault like angry wasps',
'defend': 'guard like loyal hounds',
'escape': 'flee like startled rabbits',
'avoid': 'evade like nimble deer',
'reach': 'extend like growing vines',
'touch': 'contact with gentle-paws',
'push': 'shove like rolling boulders',
'pull': 'draw like flowing streams',
'lift': 'raise like morning mist',
'drop': 'release like autumn leaves',
'pick': 'select like berry gatherers',
'enter': 'cross the sacred threshold',
'exit': 'depart through hidden doors',
'pass': 'traverse like mountain paths',
'cross': 'bridge like fallen-logs',
'climb': 'ascend like squirrel-acrobats',
'jump': 'leap like bounding-deer',
'fall': 'tumble like rolling-acorns',
'swim': 'glide like graceful-fish',
'dance': 'move like wind-blown-leaves',
'sing': 'vocalize like morning-birds',
'laugh': 'chortle like amused-gnomes',
'cry': 'weep like rain-clouds',
'smile': 'grin like happy-sunflowers',
'frown': 'scowl like storm-clouds',
// Technology terms (gnome-ified)
'computer': 'thinking-box of metal and magic',
'laptop': 'portable wisdom-chest',
'phone': 'speaking-crystal',
'smartphone': 'clever communication-gem',
'internet': 'the great web of knowledge',
'website': 'digital mushroom ring',
'email': 'letter-sprite delivery',
'password': 'secret gnome-word',
'app': 'magical tool-sprite',
'software': 'spell-weaving programs',
'program': 'coded spell-sequence',
'code': 'mystical rune-writing',
'bug': 'mischievous code-gremlin',
'update': 'spell-enhancement ritual',
'download': 'summon from the ether',
'upload': 'send to the cloud-spirits',
'file': 'digital scroll-bundle',
'delete': 'banish to the void',
'bitcoin': 'golden acorns of the digital realm',
'crypto': 'mystical coin-magic',
'blockchain': 'the eternal ledger of the earth spirits',
'nostr': 'the sacred network of gnome-kind',
'relay': 'message-mushroom',
'post': 'woodland proclamation',
'message': 'whisper carried by wind',
'chat': 'friendly forest-chatter',
'comment': 'thoughtful tree-response',
'reply': 'echo from the grove',
'mention': 'call by woodland-name',
'tag': 'forest-marker label',
'hashtag': 'topic-gathering symbol',
'follower': 'path-walking companion',
'friend': 'woodland-path companion',
'user': 'forest-path wanderer',
'account': 'woodland-identity record',
'profile': 'forest-dweller description',
'avatar': 'spirit-image representation',
'feed': 'stream of woodland-news',
'trending': 'popular as festival-topics',
'viral': 'spreading like wildfire-news',
// Time and nature
'today': 'this blessed sun-cycle',
'tomorrow': 'the next dawn',
'yesterday': 'the previous twilight',
'now': 'this very forest-moment',
'soon': 'before the next acorn-fall',
'later': 'after the sun-shift',
'early': 'with the first bird-songs',
'late': 'when shadows grow long',
'morning': 'when dew kisses the earth',
'afternoon': 'when sun reaches tree-tops',
'evening': 'when fireflies dance',
'night': 'when the moon watches over',
'day': 'sun-blessed time',
'week': 'seven turnings of the earth',
'month': 'one moon-cycle',
'year': 'full journey round the sun',
'time': 'the eternal forest-flow',
'moment': 'brief woodland-instant',
'hour': 'sun-shadow measurement',
'minute': 'tiny time-fragment',
'second': 'heartbeat-duration',
'season': 'nature\'s changing-mood',
'spring': 'time of awakening-growth',
'summer': 'season of abundant-warmth',
'autumn': 'harvest of golden-leaves',
'winter': 'the great forest-slumber',
'weather': 'sky-spirit\'s current-mood',
'rain': 'sky-tears blessing the earth',
'snow': 'winter\'s white forest-blanket',
'sun': 'the great golden-eye',
'moon': 'night\'s silver-guardian',
'stars': 'celestial navigation-gems',
'sky': 'the endless blue-canopy',
'cloud': 'sky-spirit\'s fluffy-messenger',
'wind': 'breath of the forest-spirits',
'storm': 'sky-spirits\' angry-dance',
'thunder': 'voice of the cloud-giants',
'lightning': 'sky-fire\'s brilliant-flash',
'rainbow': 'bridge between earth and sky',
'nature': 'the great mother-spirit',
'earth': 'our beloved soil-mother',
'world': 'the vast forest-realm',
'ground': 'the solid earth-foundation',
'soil': 'the life-giving dirt-magic',
'rock': 'earth\'s ancient bone-structure',
'stone': 'small piece of mountain-heart',
'mountain': 'earth\'s reaching-toward-sky',
'hill': 'gentle earth-rise',
'valley': 'earth\'s peaceful-embrace',
'forest': 'the sacred tree-gathering',
'tree': 'earth\'s reaching-toward-light',
'branch': 'tree\'s extending-arm',
'leaf': 'tree\'s breathing-surface',
'root': 'tree\'s earth-drinking-finger',
'flower': 'plant\'s colorful-celebration',
'grass': 'earth\'s green-carpet',
'plant': 'earth\'s growing-child',
'garden': 'tended plant-paradise',
'water': 'life-giving crystal liquid',
'river': 'flowing water-pathway',
'lake': 'earth\'s water-mirror',
'ocean': 'vast water-wilderness',
'fire': 'dancing heat-spirit',
'flame': 'fire\'s reaching-tongue',
'smoke': 'fire\'s gray-breath',
'wood': 'tree\'s gift-material',
'animal': 'forest-dwelling-creature',
'bird': 'sky-dancing-singer',
'fish': 'water-dwelling-swimmer',
'dog': 'loyal four-legged-friend',
'cat': 'independent whisker-hunter',
'horse': 'noble four-legged-runner',
'cow': 'gentle milk-giving-beast',
'pig': 'round mud-loving-creature',
'chicken': 'feathered egg-laying-bird',
'bear': 'mighty forest-guardian',
'wolf': 'pack-hunting-howler',
'deer': 'graceful forest-leaper',
'rabbit': 'quick-hopping-nibbler',
'squirrel': 'tree-climbing-nut-gatherer',
'mouse': 'tiny cheese-seeking-creature',
'rat': 'clever tunnel-dwelling-survivor',
'snake': 'slithering ground-crawler',
'spider': 'web-weaving-hunter',
'bee': 'buzzing honey-maker',
'butterfly': 'colorful flower-dancer',
'ant': 'industrious colony-worker',
'fly': 'annoying buzzing-pest',
'mosquito': 'blood-seeking-tiny-vampire',
'frog': 'pond-dwelling-croaker',
'turtle': 'shell-carrying-slow-walker',
'owl': 'wise night-hunting-watcher',
'eagle': 'majestic sky-soaring-hunter',
'dragon': 'legendary fire-breathing-beast',
'unicorn': 'mythical horn-bearing-horse',
'fairy': 'tiny magical-forest-sprite',
'elf': 'pointed-ear-woodland-dweller',
'dwarf': 'bearded mountain-tunnel-digger',
'wizard': 'spell-casting-wise-elder',
'witch': 'potion-brewing-magic-user',
'ghost': 'transparent spirit-being',
'monster': 'frightening creature-of-darkness',
// Food and sustenance
'food': 'earth\'s bounty',
'meal': 'feast of forest-gifts',
'breakfast': 'dawn\'s energy-awakening',
'lunch': 'midday sustenance-break',
'dinner': 'evening\'s nourishment-gathering',
'snack': 'small between-meal-nibble',
'hungry': 'craving earth\'s-nourishment',
'thirsty': 'needing liquid-refreshment',
'full': 'satisfied with belly-bounty',
'coffee': 'bitter bean brew',
'tea': 'leaf-water of wisdom',
'milk': 'cow\'s white-gift',
'juice': 'fruit\'s liquid-essence',
'beer': 'grain\'s fermented-celebration',
'wine': 'grape\'s aged-transformation',
'bread': 'grain-gift of the fields',
'cake': 'sweet celebration-tower',
'cookie': 'small sweet-disk',
'pizza': 'flat bread with toppings-garden',
'meat': 'animal\'s protein-gift',
'vegetable': 'earth\'s colorful-children',
'fruit': 'tree\'s sweet-offering',
'apple': 'red orb of crisp-sweetness',
'banana': 'yellow crescent-fruit',
'orange': 'citrus sun-sphere',
'cheese': 'milk\'s aged-transformation',
'egg': 'bird\'s oval-creation',
'honey': 'bee\'s golden-sweetness',
'sugar': 'cane\'s crystallized-sweetness',
'salt': 'sea\'s mineral-gift',
'spicy': 'fire-tongue-sensation',
'delicious': 'wonderfully tasty-pleasure',
'tasty': 'pleasing to tongue-senses',
'yummy': 'delightfully satisfying-flavor',
// People and relationships
'person': 'wanderer of the mortal realm',
'people': 'fellow earth-dwellers',
'human': 'tall-folk',
'man': 'bearded earth-walker',
'woman': 'graceful forest-daughter',
'child': 'young sprout',
'baby': 'tiny seedling',
'boy': 'male young-sprout',
'girl': 'female young-blossom',
'family': 'clan of the same burrow',
'mother': 'nurturing life-bringer',
'father': 'protecting life-provider',
'parent': 'life-giving-elder',
'son': 'male offspring-sprout',
'daughter': 'female offspring-blossom',
'brother': 'male sibling-companion',
'sister': 'female sibling-friend',
'husband': 'male life-bond-companion',
'wife': 'female life-bond-companion',
'boyfriend': 'courting male-companion',
'girlfriend': 'courting female-companion',
'neighbor': 'nearby-dwelling-friend',
'stranger': 'unknown path-crosser',
'teacher': 'wisdom-sharing-elder',
'student': 'knowledge-seeking-sprout',
'doctor': 'healing-arts-practitioner',
'worker': 'labor-providing-being',
'boss': 'work-directing-leader',
'leader': 'group-guiding-chief',
'team': 'cooperating-group-unit',
'group': 'gathered-together-collection',
'community': 'shared-dwelling-collective',
// Places and locations
'place': 'woodland-location',
'home': 'cozy burrow-dwelling',
'house': 'family nest-structure',
'building': 'tall human-construction',
'room': 'enclosed dwelling-space',
'kitchen': 'food-preparation-chamber',
'bedroom': 'sleeping-rest-sanctuary',
'bathroom': 'cleansing-water-room',
'office': 'work-task-chamber',
'school': 'learning-wisdom-hall',
'hospital': 'healing-treatment-center',
'store': 'goods-trading-establishment',
'restaurant': 'food-serving-hall',
'park': 'public green-space',
'street': 'paved pathway-for-travel',
'road': 'long travel-route',
'city': 'large human-settlement',
'town': 'medium human-gathering',
'village': 'small community-cluster',
'country': 'large territorial-region',
'state': 'governmental-territory-division',
'beach': 'sandy water-meeting-shore',
'island': 'water-surrounded-land',
'desert': 'dry sandy-wasteland',
'farm': 'food-growing-sanctuary',
'field': 'open earth-expanse',
'meadow': 'flower-filled-clearing',
// Objects and things
'thing': 'woodland-object',
'object': 'physical forest-item',
'item': 'individual possession-piece',
'stuff': 'various collected-objects',
'book': 'knowledge-filled-pages',
'paper': 'tree-pulp-writing-surface',
'pen': 'ink-flowing-writing-stick',
'pencil': 'graphite-marking-tool',
'car': 'metal traveling-box',
'bike': 'two-wheeled-pedal-machine',
'train': 'long track-riding-transport',
'plane': 'sky-flying-metal-bird',
'boat': 'water-floating-vessel',
'ship': 'large ocean-crossing-craft',
'chair': 'sitting-support-furniture',
'table': 'flat surface-for-placing',
'bed': 'sleeping-comfort-platform',
'door': 'entrance-barrier-portal',
'window': 'transparent wall-opening',
'wall': 'vertical room-boundary',
'floor': 'horizontal walking-surface',
'roof': 'overhead shelter-covering',
'box': 'storage-container-cube',
'bag': 'flexible carrying-container',
'bottle': 'liquid-holding-vessel',
'cup': 'small drinking-container',
'plate': 'flat food-serving-disk',
'knife': 'sharp cutting-blade',
'fork': 'pronged eating-tool',
'spoon': 'curved scooping-utensil',
'clothes': 'body-covering-garments',
'shirt': 'upper-body-covering',
'pants': 'leg-covering-garment',
'shoes': 'foot-protecting-coverings',
'hat': 'head-covering-accessory',
'ring': 'finger-circling-jewelry',
'key': 'lock-opening-metal-tool',
'money': 'trade-value-tokens',
'coin': 'small metal-currency-disk',
'card': 'flat rectangular-object',
'gift': 'present-offering-surprise',
'toy': 'play-entertainment-object',
'game': 'rule-based-fun-activity',
'ball': 'round bouncing-sphere',
'tool': 'work-assisting-implement',
'machine': 'mechanical working-device',
'camera': 'image-capturing-box',
'picture': 'visual-image-representation',
'photo': 'light-captured-moment',
'mirror': 'reflection-showing-surface',
'lamp': 'artificial light-provider',
'candle': 'wax flame-holder',
'ice': 'frozen solid-water',
'glass': 'transparent brittle-material',
'metal': 'hard shiny-material',
'plastic': 'synthetic flexible-material',
'rubber': 'bouncy stretchy-material',
'fabric': 'woven thread-material',
'leather': 'animal-hide-material',
'string': 'thin flexible-cord',
'rope': 'thick strong-cord',
'chain': 'linked metal-connections',
'wire': 'thin metal-strand',
'nail': 'sharp fastening-spike',
'screw': 'threaded fastening-rod',
'hammer': 'striking-force-tool',
'saw': 'cutting-teeth-tool',
'brush': 'bristled cleaning-tool',
'paint': 'color-coating-liquid',
'soap': 'cleaning-foam-substance',
'towel': 'drying-absorption-cloth',
'blanket': 'warmth-providing-cover',
'pillow': 'head-supporting-cushion',
'clock': 'time-displaying-device',
'calendar': 'date-organizing-chart',
'map': 'location-showing-guide',
'flag': 'symbolic cloth-banner',
'seed': 'plant\'s future-potential',
'stick': 'small wood-piece',
'shell': 'sea-creature\'s protective-home',
'feather': 'bird\'s flight-enabling-plume',
'bone': 'skeleton\'s structural-piece',
'fur': 'animal\'s warm-covering',
'scale': 'fish\'s protective-armor',
'horn': 'animal\'s pointed-growth',
'tail': 'animal\'s rear-appendage',
'wing': 'flight-enabling-appendage',
'claw': 'sharp grasping-nail',
'tooth': 'biting-chewing-bone',
'eye': 'vision-sensing-orb',
'ear': 'sound-detecting-organ',
'nose': 'smell-sensing-protrusion',
'mouth': 'eating-speaking-opening',
'hand': 'grasping-manipulation-appendage',
'finger': 'hand\'s flexible-digit',
'foot': 'walking-support-appendage',
'toe': 'foot\'s small-digit',
'head': 'thinking-sensing-sphere',
'hair': 'head\'s growing-strands',
'face': 'front-expression-surface',
'neck': 'head-connecting-column',
'shoulder': 'arm-connecting-joint',
'arm': 'reaching-grasping-limb',
'leg': 'walking-supporting-limb',
'knee': 'leg-bending-joint',
'chest': 'front-torso-area',
'stomach': 'food-digesting-organ',
'heart': 'blood-pumping-organ',
'brain': 'thinking-control-organ',
'blood': 'life-flowing-red-liquid',
'skin': 'body\'s protective-covering',
'muscle': 'movement-creating-tissue',
'breath': 'life-sustaining-air-flow',
'voice': 'sound-producing-expression',
'word': 'meaning-carrying-sound-unit',
'language': 'communication-sound-system',
'name': 'identity-labeling-word',
'story': 'event-narrative-tale',
'joke': 'humor-creating-tale',
'song': 'melodic-sound-creation',
'music': 'organized-sound-art',
'sound': 'air-vibration-sensation',
'noise': 'unwanted-sound-disturbance',
'silence': 'absence-of-sound',
'color': 'light-wavelength-perception',
'red': 'blood-fire-color',
'blue': 'sky-water-color',
'green': 'grass-leaf-color',
'yellow': 'sun-gold-color',
'purple': 'royal-flower-color',
'pink': 'blossom-blush-color',
'brown': 'earth-wood-color',
'black': 'night-shadow-color',
'white': 'snow-cloud-color',
'gray': 'storm-stone-color',
'silver': 'moon-metal-color',
'gold': 'treasure-sun-color',
};
// Gnome exclamations and interjections
const gnomeExclamations = [
'By my pointy hat!',
'Great toadstools!',
'Mushroom caps!',
'Sacred acorns!',
'Blessed berries!',
'Garden spirits preserve us!',
'Forest magic!',
'Woodland wonders!',
'Gnome\'s beard!',
'Tiny treasures!',
'Earth\'s bounty!',
'Root and branch!',
'Moss and mushrooms!',
'Fern and flower!',
'Bark and berry!',
'Stone and stream!'
];
// Gnome sentence starters
const gnomeSentenceStarters = [
'In the sacred grove, ',
'By the ancient oak, ',
'Beneath the mushroom ring, ',
'Among the forest folk, ',
'In the woodland realm, ',
'By the babbling brook, ',
'Under the starlit sky, ',
'Within the garden walls, ',
'Beside the fairy ring, ',
'Through the morning mist, ',
'As the seasons turn, ',
'When the moon is full, ',
'In the depths of the forest, ',
'Where the wild things grow, ',
'Beyond the garden gate, '
];
// Gnome sentence endings
const gnomeSentenceEndings = [
', as the ancients foretold.',
', blessed by the forest spirits.',
', in harmony with nature.',
', according to gnome wisdom.',
', as written in the bark of the elder tree.',
', by the light of the fireflies.',
', under the watchful eyes of the owls.',
', with the blessing of the earth mother.',
', as sure as mushrooms grow.',
', in the way of our people.',
', following the old traditions.',
', as the seasons decree.',
', by the sacred laws of the woodland.',
', in the manner of the wise ones.',
', as nature intended.'
];
/**
* Translates regular text into gnome speak
*/
export function translateToGnomeSpeak(text: string): string {
if (!text || typeof text !== 'string') {
return text;
}
let gnomeText = text.toLowerCase();
// Preserve URLs
const urlRegex = /(https?:\/\/[^\s]+)/g;
const urlMatches: string[] = [];
gnomeText = gnomeText.replace(urlRegex, (match) => {
urlMatches.push(match);
return `__URL_${urlMatches.length - 1}__`;
});
// Preserve nostr: references
const nostrRegex = /(nostr:(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+))/g;
const nostrMatches: string[] = [];
gnomeText = gnomeText.replace(nostrRegex, (match) => {
nostrMatches.push(match);
return `__NOSTR_${nostrMatches.length - 1}__`;
});
// Preserve hashtags
const hashtagRegex = /(#\w+)/g;
const hashtagMatches: string[] = [];
gnomeText = gnomeText.replace(hashtagRegex, (match) => {
hashtagMatches.push(match);
return `__HASHTAG_${hashtagMatches.length - 1}__`;
});
// Replace words with gnome equivalents
Object.entries(gnomeVocabulary).forEach(([english, gnome]) => {
const escapedEnglish = english.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b${escapedEnglish}\\b`, 'gi');
gnomeText = gnomeText.replace(regex, gnome);
});
// Add gnome exclamations for emphasis
gnomeText = gnomeText.replace(/!/g, () => {
const exclamation = gnomeExclamations[Math.floor(Math.random() * gnomeExclamations.length)];
return `! ${exclamation}`;
});
// Add gnome sentence starters occasionally
const sentences = gnomeText.split(/[.!?]+/).filter(s => s.trim());
const gnomeSentences = sentences.map((sentence, index) => {
const trimmed = sentence.trim();
if (!trimmed) return sentence;
// Add starter to some sentences (not all, to avoid repetition)
if (Math.random() < 0.3 && index > 0) {
const starter = gnomeSentenceStarters[Math.floor(Math.random() * gnomeSentenceStarters.length)];
return starter + trimmed;
}
return trimmed;
});
// Rejoin sentences
gnomeText = gnomeSentences.join('. ');
// Add gnome endings occasionally
if (Math.random() < 0.4) {
const ending = gnomeSentenceEndings[Math.floor(Math.random() * gnomeSentenceEndings.length)];
gnomeText += ending;
}
// Capitalize first letter of sentences
gnomeText = gnomeText.replace(/(^|[.!?]\s+)([a-z])/g, (match, prefix, letter) => {
return prefix + letter.toUpperCase();
});
// Add some gnome-specific formatting
gnomeText = gnomeText.replace(/\b(bitcoin|btc)\b/gi, '✨golden acorns of the digital realm✨');
gnomeText = gnomeText.replace(/\b(gm|good morning)\b/gi, '🌅when dew kisses the earth🌅');
gnomeText = gnomeText.replace(/\b(gn|good night)\b/gi, '🌙when the moon watches over🌙');
// Restore preserved patterns
gnomeText = gnomeText.replace(/__URL_(\d+)__/g, (_, index) => urlMatches[parseInt(index)]);
gnomeText = gnomeText.replace(/__NOSTR_(\d+)__/g, (_, index) => nostrMatches[parseInt(index)]);
gnomeText = gnomeText.replace(/__HASHTAG_(\d+)__/g, (_, index) => hashtagMatches[parseInt(index)]);
return gnomeText;
}
/**
* Checks if text should be translated (only kind 1 events)
*/
export function shouldTranslateToGnomeSpeak(eventKind: number): boolean {
return eventKind === 1;
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Polyfill for AbortSignal.any()
*
* AbortSignal.any() creates an AbortSignal that will be aborted when any of the
* provided signals are aborted. This is useful for combining multiple abort signals.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static
*/
// Check if AbortSignal.any is already available
if (!AbortSignal.any) {
AbortSignal.any = function(signals: AbortSignal[]): AbortSignal {
// If no signals provided, return a signal that never aborts
if (signals.length === 0) {
return new AbortController().signal;
}
// If only one signal, return it directly for efficiency
if (signals.length === 1) {
return signals[0];
}
// Check if any signal is already aborted
for (const signal of signals) {
if (signal.aborted) {
// Create an already-aborted signal with the same reason
const controller = new AbortController();
controller.abort(signal.reason);
return controller.signal;
}
}
// Create a new controller for the combined signal
const controller = new AbortController();
// Function to abort the combined signal
const onAbort = (event: Event) => {
const target = event.target as AbortSignal;
controller.abort(target.reason);
};
// Listen for abort events on all input signals
for (const signal of signals) {
signal.addEventListener('abort', onAbort, { once: true });
}
// Clean up listeners when the combined signal is aborted
controller.signal.addEventListener('abort', () => {
for (const signal of signals) {
signal.removeEventListener('abort', onAbort);
}
}, { once: true });
return controller.signal;
};
}
/**
* Polyfill for AbortSignal.timeout()
*
* AbortSignal.timeout() creates an AbortSignal that will be aborted after a
* specified number of milliseconds.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
*/
// Check if AbortSignal.timeout is already available
if (!AbortSignal.timeout) {
AbortSignal.timeout = function(milliseconds: number): AbortSignal {
const controller = new AbortController();
setTimeout(() => {
controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
}, milliseconds);
return controller.signal;
};
}
+9 -3
View File
@@ -1,6 +1,12 @@
import { createRoot } from 'react-dom/client'
import { createRoot } from 'react-dom/client';
import App from './App.tsx'
import './index.css'
// Import polyfills first
import './lib/polyfills.ts';
import App from './App.tsx';
import './index.css';
// Import gnome-themed font
import '@fontsource-variable/comfortaa';
createRoot(document.getElementById("root")!).render(<App />);
+30 -5
View File
@@ -1,11 +1,36 @@
// Update this page (the content is just a fallback if you fail to update the page)
import { useSeoMeta } from '@unhead/react';
import { GnomeHeader } from '@/components/GnomeHeader';
import { GnomeComposer } from '@/components/GnomeComposer';
import { GnomeFeed } from '@/components/GnomeFeed';
const Index = () => {
useSeoMeta({
title: 'Gnome Nostr - The Sacred Network of Woodland Folk',
description: 'A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!',
});
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">Welcome to Your Blank App</h1>
<p className="text-xl text-gray-600">Start building your amazing project here!</p>
<div className="min-h-screen bg-background">
<div className="container max-w-2xl mx-auto px-4 py-6">
<GnomeHeader />
<GnomeComposer />
<GnomeFeed />
{/* Footer with MKStack attribution */}
<div className="mt-12 pt-6 border-t border-border/30 text-center">
<p className="text-xs text-muted-foreground">
Vibed with{' '}
<a
href="https://soapbox.pub/mkstack"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-accent transition-colors underline"
>
MKStack
</a>
{' '}• Blessed by the forest spirits 🍄✨
</p>
</div>
</div>
</div>
);
+10 -4
View File
@@ -1,9 +1,15 @@
import { useSeoMeta } from "@unhead/react";
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
const NotFound = () => {
const location = useLocation();
useSeoMeta({
title: "404 - Page Not Found",
description: "The page you are looking for could not be found. Return to the home page to continue browsing.",
});
useEffect(() => {
console.error(
"404 Error: User attempted to access non-existent route:",
@@ -12,11 +18,11 @@ const NotFound = () => {
}, [location.pathname]);
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<div className="text-center">
<h1 className="text-4xl font-bold mb-4">404</h1>
<p className="text-xl text-gray-600 mb-4">Oops! Page not found</p>
<a href="/" className="text-blue-500 hover:text-blue-700 underline">
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">404</h1>
<p className="text-xl text-gray-600 dark:text-gray-400 mb-4">Oops! Page not found</p>
<a href="/" className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline">
Return to Home
</a>
</div>
+45
View File
@@ -0,0 +1,45 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createHead, UnheadProvider } from '@unhead/react/client';
import { BrowserRouter } from 'react-router-dom';
import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
interface TestAppProps {
children: React.ReactNode;
}
export function TestApp({ children }: TestAppProps) {
const head = createHead();
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
};
return (
<UnheadProvider head={head}>
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
);
}
export default TestApp;
+40
View File
@@ -0,0 +1,40 @@
import '@testing-library/jest-dom';
import { vi } from 'vitest';
// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock window.scrollTo
Object.defineProperty(window, 'scrollTo', {
writable: true,
value: vi.fn(),
});
// Mock IntersectionObserver
global.IntersectionObserver = vi.fn().mockImplementation((_callback) => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
root: null,
rootMargin: '',
thresholds: [],
}));
// Mock ResizeObserver
global.ResizeObserver = vi.fn().mockImplementation((_callback) => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
}));
+19
View File
@@ -0,0 +1,19 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}
+5 -1
View File
@@ -1,4 +1,5 @@
import type { Config } from "tailwindcss";
import tailwindcssAnimate from "tailwindcss-animate";
export default {
darkMode: ["class"],
@@ -18,6 +19,9 @@ export default {
}
},
extend: {
fontFamily: {
sans: ['Comfortaa Variable', 'Comfortaa', 'system-ui', 'sans-serif'],
},
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
@@ -92,5 +96,5 @@ export default {
}
}
},
plugins: [require("tailwindcss-animate")],
plugins: [tailwindcssAnimate],
} satisfies Config;
+15 -4
View File
@@ -1,17 +1,28 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "node:path";
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vitest/config";
// https://vitejs.dev/config/
export default defineConfig(() => ({
server: {
host: "::",
port: 8080,
},
plugins: [react()],
plugins: [
react(),
],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
onConsoleLog(log) {
return !log.includes("React Router Future Flag Warning");
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
}));
}));